sctp_output.c revision 283697
1/*-
2 * Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
3 * Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
4 * Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * a) Redistributions of source code must retain the above copyright notice,
10 *    this list of conditions and the following disclaimer.
11 *
12 * b) Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in
14 *    the documentation and/or other materials provided with the distribution.
15 *
16 * c) Neither the name of Cisco Systems, Inc. nor the names of its
17 *    contributors may be used to endorse or promote products derived
18 *    from this software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
22 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30 * THE POSSIBILITY OF SUCH DAMAGE.
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: stable/10/sys/netinet/sctp_output.c 283697 2015-05-29 11:01:46Z tuexen $");
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#if defined(INET) || defined(INET6)
54#include <netinet/udp.h>
55#endif
56#include <netinet/udp_var.h>
57#include <machine/in_cksum.h>
58
59
60
61#define SCTP_MAX_GAPS_INARRAY 4
62struct sack_track {
63	uint8_t right_edge;	/* mergable on the right edge */
64	uint8_t left_edge;	/* mergable on the left edge */
65	uint8_t num_entries;
66	uint8_t spare;
67	struct sctp_gap_ack_block gaps[SCTP_MAX_GAPS_INARRAY];
68};
69
70struct sack_track sack_array[256] = {
71	{0, 0, 0, 0,		/* 0x00 */
72		{{0, 0},
73		{0, 0},
74		{0, 0},
75		{0, 0}
76		}
77	},
78	{1, 0, 1, 0,		/* 0x01 */
79		{{0, 0},
80		{0, 0},
81		{0, 0},
82		{0, 0}
83		}
84	},
85	{0, 0, 1, 0,		/* 0x02 */
86		{{1, 1},
87		{0, 0},
88		{0, 0},
89		{0, 0}
90		}
91	},
92	{1, 0, 1, 0,		/* 0x03 */
93		{{0, 1},
94		{0, 0},
95		{0, 0},
96		{0, 0}
97		}
98	},
99	{0, 0, 1, 0,		/* 0x04 */
100		{{2, 2},
101		{0, 0},
102		{0, 0},
103		{0, 0}
104		}
105	},
106	{1, 0, 2, 0,		/* 0x05 */
107		{{0, 0},
108		{2, 2},
109		{0, 0},
110		{0, 0}
111		}
112	},
113	{0, 0, 1, 0,		/* 0x06 */
114		{{1, 2},
115		{0, 0},
116		{0, 0},
117		{0, 0}
118		}
119	},
120	{1, 0, 1, 0,		/* 0x07 */
121		{{0, 2},
122		{0, 0},
123		{0, 0},
124		{0, 0}
125		}
126	},
127	{0, 0, 1, 0,		/* 0x08 */
128		{{3, 3},
129		{0, 0},
130		{0, 0},
131		{0, 0}
132		}
133	},
134	{1, 0, 2, 0,		/* 0x09 */
135		{{0, 0},
136		{3, 3},
137		{0, 0},
138		{0, 0}
139		}
140	},
141	{0, 0, 2, 0,		/* 0x0a */
142		{{1, 1},
143		{3, 3},
144		{0, 0},
145		{0, 0}
146		}
147	},
148	{1, 0, 2, 0,		/* 0x0b */
149		{{0, 1},
150		{3, 3},
151		{0, 0},
152		{0, 0}
153		}
154	},
155	{0, 0, 1, 0,		/* 0x0c */
156		{{2, 3},
157		{0, 0},
158		{0, 0},
159		{0, 0}
160		}
161	},
162	{1, 0, 2, 0,		/* 0x0d */
163		{{0, 0},
164		{2, 3},
165		{0, 0},
166		{0, 0}
167		}
168	},
169	{0, 0, 1, 0,		/* 0x0e */
170		{{1, 3},
171		{0, 0},
172		{0, 0},
173		{0, 0}
174		}
175	},
176	{1, 0, 1, 0,		/* 0x0f */
177		{{0, 3},
178		{0, 0},
179		{0, 0},
180		{0, 0}
181		}
182	},
183	{0, 0, 1, 0,		/* 0x10 */
184		{{4, 4},
185		{0, 0},
186		{0, 0},
187		{0, 0}
188		}
189	},
190	{1, 0, 2, 0,		/* 0x11 */
191		{{0, 0},
192		{4, 4},
193		{0, 0},
194		{0, 0}
195		}
196	},
197	{0, 0, 2, 0,		/* 0x12 */
198		{{1, 1},
199		{4, 4},
200		{0, 0},
201		{0, 0}
202		}
203	},
204	{1, 0, 2, 0,		/* 0x13 */
205		{{0, 1},
206		{4, 4},
207		{0, 0},
208		{0, 0}
209		}
210	},
211	{0, 0, 2, 0,		/* 0x14 */
212		{{2, 2},
213		{4, 4},
214		{0, 0},
215		{0, 0}
216		}
217	},
218	{1, 0, 3, 0,		/* 0x15 */
219		{{0, 0},
220		{2, 2},
221		{4, 4},
222		{0, 0}
223		}
224	},
225	{0, 0, 2, 0,		/* 0x16 */
226		{{1, 2},
227		{4, 4},
228		{0, 0},
229		{0, 0}
230		}
231	},
232	{1, 0, 2, 0,		/* 0x17 */
233		{{0, 2},
234		{4, 4},
235		{0, 0},
236		{0, 0}
237		}
238	},
239	{0, 0, 1, 0,		/* 0x18 */
240		{{3, 4},
241		{0, 0},
242		{0, 0},
243		{0, 0}
244		}
245	},
246	{1, 0, 2, 0,		/* 0x19 */
247		{{0, 0},
248		{3, 4},
249		{0, 0},
250		{0, 0}
251		}
252	},
253	{0, 0, 2, 0,		/* 0x1a */
254		{{1, 1},
255		{3, 4},
256		{0, 0},
257		{0, 0}
258		}
259	},
260	{1, 0, 2, 0,		/* 0x1b */
261		{{0, 1},
262		{3, 4},
263		{0, 0},
264		{0, 0}
265		}
266	},
267	{0, 0, 1, 0,		/* 0x1c */
268		{{2, 4},
269		{0, 0},
270		{0, 0},
271		{0, 0}
272		}
273	},
274	{1, 0, 2, 0,		/* 0x1d */
275		{{0, 0},
276		{2, 4},
277		{0, 0},
278		{0, 0}
279		}
280	},
281	{0, 0, 1, 0,		/* 0x1e */
282		{{1, 4},
283		{0, 0},
284		{0, 0},
285		{0, 0}
286		}
287	},
288	{1, 0, 1, 0,		/* 0x1f */
289		{{0, 4},
290		{0, 0},
291		{0, 0},
292		{0, 0}
293		}
294	},
295	{0, 0, 1, 0,		/* 0x20 */
296		{{5, 5},
297		{0, 0},
298		{0, 0},
299		{0, 0}
300		}
301	},
302	{1, 0, 2, 0,		/* 0x21 */
303		{{0, 0},
304		{5, 5},
305		{0, 0},
306		{0, 0}
307		}
308	},
309	{0, 0, 2, 0,		/* 0x22 */
310		{{1, 1},
311		{5, 5},
312		{0, 0},
313		{0, 0}
314		}
315	},
316	{1, 0, 2, 0,		/* 0x23 */
317		{{0, 1},
318		{5, 5},
319		{0, 0},
320		{0, 0}
321		}
322	},
323	{0, 0, 2, 0,		/* 0x24 */
324		{{2, 2},
325		{5, 5},
326		{0, 0},
327		{0, 0}
328		}
329	},
330	{1, 0, 3, 0,		/* 0x25 */
331		{{0, 0},
332		{2, 2},
333		{5, 5},
334		{0, 0}
335		}
336	},
337	{0, 0, 2, 0,		/* 0x26 */
338		{{1, 2},
339		{5, 5},
340		{0, 0},
341		{0, 0}
342		}
343	},
344	{1, 0, 2, 0,		/* 0x27 */
345		{{0, 2},
346		{5, 5},
347		{0, 0},
348		{0, 0}
349		}
350	},
351	{0, 0, 2, 0,		/* 0x28 */
352		{{3, 3},
353		{5, 5},
354		{0, 0},
355		{0, 0}
356		}
357	},
358	{1, 0, 3, 0,		/* 0x29 */
359		{{0, 0},
360		{3, 3},
361		{5, 5},
362		{0, 0}
363		}
364	},
365	{0, 0, 3, 0,		/* 0x2a */
366		{{1, 1},
367		{3, 3},
368		{5, 5},
369		{0, 0}
370		}
371	},
372	{1, 0, 3, 0,		/* 0x2b */
373		{{0, 1},
374		{3, 3},
375		{5, 5},
376		{0, 0}
377		}
378	},
379	{0, 0, 2, 0,		/* 0x2c */
380		{{2, 3},
381		{5, 5},
382		{0, 0},
383		{0, 0}
384		}
385	},
386	{1, 0, 3, 0,		/* 0x2d */
387		{{0, 0},
388		{2, 3},
389		{5, 5},
390		{0, 0}
391		}
392	},
393	{0, 0, 2, 0,		/* 0x2e */
394		{{1, 3},
395		{5, 5},
396		{0, 0},
397		{0, 0}
398		}
399	},
400	{1, 0, 2, 0,		/* 0x2f */
401		{{0, 3},
402		{5, 5},
403		{0, 0},
404		{0, 0}
405		}
406	},
407	{0, 0, 1, 0,		/* 0x30 */
408		{{4, 5},
409		{0, 0},
410		{0, 0},
411		{0, 0}
412		}
413	},
414	{1, 0, 2, 0,		/* 0x31 */
415		{{0, 0},
416		{4, 5},
417		{0, 0},
418		{0, 0}
419		}
420	},
421	{0, 0, 2, 0,		/* 0x32 */
422		{{1, 1},
423		{4, 5},
424		{0, 0},
425		{0, 0}
426		}
427	},
428	{1, 0, 2, 0,		/* 0x33 */
429		{{0, 1},
430		{4, 5},
431		{0, 0},
432		{0, 0}
433		}
434	},
435	{0, 0, 2, 0,		/* 0x34 */
436		{{2, 2},
437		{4, 5},
438		{0, 0},
439		{0, 0}
440		}
441	},
442	{1, 0, 3, 0,		/* 0x35 */
443		{{0, 0},
444		{2, 2},
445		{4, 5},
446		{0, 0}
447		}
448	},
449	{0, 0, 2, 0,		/* 0x36 */
450		{{1, 2},
451		{4, 5},
452		{0, 0},
453		{0, 0}
454		}
455	},
456	{1, 0, 2, 0,		/* 0x37 */
457		{{0, 2},
458		{4, 5},
459		{0, 0},
460		{0, 0}
461		}
462	},
463	{0, 0, 1, 0,		/* 0x38 */
464		{{3, 5},
465		{0, 0},
466		{0, 0},
467		{0, 0}
468		}
469	},
470	{1, 0, 2, 0,		/* 0x39 */
471		{{0, 0},
472		{3, 5},
473		{0, 0},
474		{0, 0}
475		}
476	},
477	{0, 0, 2, 0,		/* 0x3a */
478		{{1, 1},
479		{3, 5},
480		{0, 0},
481		{0, 0}
482		}
483	},
484	{1, 0, 2, 0,		/* 0x3b */
485		{{0, 1},
486		{3, 5},
487		{0, 0},
488		{0, 0}
489		}
490	},
491	{0, 0, 1, 0,		/* 0x3c */
492		{{2, 5},
493		{0, 0},
494		{0, 0},
495		{0, 0}
496		}
497	},
498	{1, 0, 2, 0,		/* 0x3d */
499		{{0, 0},
500		{2, 5},
501		{0, 0},
502		{0, 0}
503		}
504	},
505	{0, 0, 1, 0,		/* 0x3e */
506		{{1, 5},
507		{0, 0},
508		{0, 0},
509		{0, 0}
510		}
511	},
512	{1, 0, 1, 0,		/* 0x3f */
513		{{0, 5},
514		{0, 0},
515		{0, 0},
516		{0, 0}
517		}
518	},
519	{0, 0, 1, 0,		/* 0x40 */
520		{{6, 6},
521		{0, 0},
522		{0, 0},
523		{0, 0}
524		}
525	},
526	{1, 0, 2, 0,		/* 0x41 */
527		{{0, 0},
528		{6, 6},
529		{0, 0},
530		{0, 0}
531		}
532	},
533	{0, 0, 2, 0,		/* 0x42 */
534		{{1, 1},
535		{6, 6},
536		{0, 0},
537		{0, 0}
538		}
539	},
540	{1, 0, 2, 0,		/* 0x43 */
541		{{0, 1},
542		{6, 6},
543		{0, 0},
544		{0, 0}
545		}
546	},
547	{0, 0, 2, 0,		/* 0x44 */
548		{{2, 2},
549		{6, 6},
550		{0, 0},
551		{0, 0}
552		}
553	},
554	{1, 0, 3, 0,		/* 0x45 */
555		{{0, 0},
556		{2, 2},
557		{6, 6},
558		{0, 0}
559		}
560	},
561	{0, 0, 2, 0,		/* 0x46 */
562		{{1, 2},
563		{6, 6},
564		{0, 0},
565		{0, 0}
566		}
567	},
568	{1, 0, 2, 0,		/* 0x47 */
569		{{0, 2},
570		{6, 6},
571		{0, 0},
572		{0, 0}
573		}
574	},
575	{0, 0, 2, 0,		/* 0x48 */
576		{{3, 3},
577		{6, 6},
578		{0, 0},
579		{0, 0}
580		}
581	},
582	{1, 0, 3, 0,		/* 0x49 */
583		{{0, 0},
584		{3, 3},
585		{6, 6},
586		{0, 0}
587		}
588	},
589	{0, 0, 3, 0,		/* 0x4a */
590		{{1, 1},
591		{3, 3},
592		{6, 6},
593		{0, 0}
594		}
595	},
596	{1, 0, 3, 0,		/* 0x4b */
597		{{0, 1},
598		{3, 3},
599		{6, 6},
600		{0, 0}
601		}
602	},
603	{0, 0, 2, 0,		/* 0x4c */
604		{{2, 3},
605		{6, 6},
606		{0, 0},
607		{0, 0}
608		}
609	},
610	{1, 0, 3, 0,		/* 0x4d */
611		{{0, 0},
612		{2, 3},
613		{6, 6},
614		{0, 0}
615		}
616	},
617	{0, 0, 2, 0,		/* 0x4e */
618		{{1, 3},
619		{6, 6},
620		{0, 0},
621		{0, 0}
622		}
623	},
624	{1, 0, 2, 0,		/* 0x4f */
625		{{0, 3},
626		{6, 6},
627		{0, 0},
628		{0, 0}
629		}
630	},
631	{0, 0, 2, 0,		/* 0x50 */
632		{{4, 4},
633		{6, 6},
634		{0, 0},
635		{0, 0}
636		}
637	},
638	{1, 0, 3, 0,		/* 0x51 */
639		{{0, 0},
640		{4, 4},
641		{6, 6},
642		{0, 0}
643		}
644	},
645	{0, 0, 3, 0,		/* 0x52 */
646		{{1, 1},
647		{4, 4},
648		{6, 6},
649		{0, 0}
650		}
651	},
652	{1, 0, 3, 0,		/* 0x53 */
653		{{0, 1},
654		{4, 4},
655		{6, 6},
656		{0, 0}
657		}
658	},
659	{0, 0, 3, 0,		/* 0x54 */
660		{{2, 2},
661		{4, 4},
662		{6, 6},
663		{0, 0}
664		}
665	},
666	{1, 0, 4, 0,		/* 0x55 */
667		{{0, 0},
668		{2, 2},
669		{4, 4},
670		{6, 6}
671		}
672	},
673	{0, 0, 3, 0,		/* 0x56 */
674		{{1, 2},
675		{4, 4},
676		{6, 6},
677		{0, 0}
678		}
679	},
680	{1, 0, 3, 0,		/* 0x57 */
681		{{0, 2},
682		{4, 4},
683		{6, 6},
684		{0, 0}
685		}
686	},
687	{0, 0, 2, 0,		/* 0x58 */
688		{{3, 4},
689		{6, 6},
690		{0, 0},
691		{0, 0}
692		}
693	},
694	{1, 0, 3, 0,		/* 0x59 */
695		{{0, 0},
696		{3, 4},
697		{6, 6},
698		{0, 0}
699		}
700	},
701	{0, 0, 3, 0,		/* 0x5a */
702		{{1, 1},
703		{3, 4},
704		{6, 6},
705		{0, 0}
706		}
707	},
708	{1, 0, 3, 0,		/* 0x5b */
709		{{0, 1},
710		{3, 4},
711		{6, 6},
712		{0, 0}
713		}
714	},
715	{0, 0, 2, 0,		/* 0x5c */
716		{{2, 4},
717		{6, 6},
718		{0, 0},
719		{0, 0}
720		}
721	},
722	{1, 0, 3, 0,		/* 0x5d */
723		{{0, 0},
724		{2, 4},
725		{6, 6},
726		{0, 0}
727		}
728	},
729	{0, 0, 2, 0,		/* 0x5e */
730		{{1, 4},
731		{6, 6},
732		{0, 0},
733		{0, 0}
734		}
735	},
736	{1, 0, 2, 0,		/* 0x5f */
737		{{0, 4},
738		{6, 6},
739		{0, 0},
740		{0, 0}
741		}
742	},
743	{0, 0, 1, 0,		/* 0x60 */
744		{{5, 6},
745		{0, 0},
746		{0, 0},
747		{0, 0}
748		}
749	},
750	{1, 0, 2, 0,		/* 0x61 */
751		{{0, 0},
752		{5, 6},
753		{0, 0},
754		{0, 0}
755		}
756	},
757	{0, 0, 2, 0,		/* 0x62 */
758		{{1, 1},
759		{5, 6},
760		{0, 0},
761		{0, 0}
762		}
763	},
764	{1, 0, 2, 0,		/* 0x63 */
765		{{0, 1},
766		{5, 6},
767		{0, 0},
768		{0, 0}
769		}
770	},
771	{0, 0, 2, 0,		/* 0x64 */
772		{{2, 2},
773		{5, 6},
774		{0, 0},
775		{0, 0}
776		}
777	},
778	{1, 0, 3, 0,		/* 0x65 */
779		{{0, 0},
780		{2, 2},
781		{5, 6},
782		{0, 0}
783		}
784	},
785	{0, 0, 2, 0,		/* 0x66 */
786		{{1, 2},
787		{5, 6},
788		{0, 0},
789		{0, 0}
790		}
791	},
792	{1, 0, 2, 0,		/* 0x67 */
793		{{0, 2},
794		{5, 6},
795		{0, 0},
796		{0, 0}
797		}
798	},
799	{0, 0, 2, 0,		/* 0x68 */
800		{{3, 3},
801		{5, 6},
802		{0, 0},
803		{0, 0}
804		}
805	},
806	{1, 0, 3, 0,		/* 0x69 */
807		{{0, 0},
808		{3, 3},
809		{5, 6},
810		{0, 0}
811		}
812	},
813	{0, 0, 3, 0,		/* 0x6a */
814		{{1, 1},
815		{3, 3},
816		{5, 6},
817		{0, 0}
818		}
819	},
820	{1, 0, 3, 0,		/* 0x6b */
821		{{0, 1},
822		{3, 3},
823		{5, 6},
824		{0, 0}
825		}
826	},
827	{0, 0, 2, 0,		/* 0x6c */
828		{{2, 3},
829		{5, 6},
830		{0, 0},
831		{0, 0}
832		}
833	},
834	{1, 0, 3, 0,		/* 0x6d */
835		{{0, 0},
836		{2, 3},
837		{5, 6},
838		{0, 0}
839		}
840	},
841	{0, 0, 2, 0,		/* 0x6e */
842		{{1, 3},
843		{5, 6},
844		{0, 0},
845		{0, 0}
846		}
847	},
848	{1, 0, 2, 0,		/* 0x6f */
849		{{0, 3},
850		{5, 6},
851		{0, 0},
852		{0, 0}
853		}
854	},
855	{0, 0, 1, 0,		/* 0x70 */
856		{{4, 6},
857		{0, 0},
858		{0, 0},
859		{0, 0}
860		}
861	},
862	{1, 0, 2, 0,		/* 0x71 */
863		{{0, 0},
864		{4, 6},
865		{0, 0},
866		{0, 0}
867		}
868	},
869	{0, 0, 2, 0,		/* 0x72 */
870		{{1, 1},
871		{4, 6},
872		{0, 0},
873		{0, 0}
874		}
875	},
876	{1, 0, 2, 0,		/* 0x73 */
877		{{0, 1},
878		{4, 6},
879		{0, 0},
880		{0, 0}
881		}
882	},
883	{0, 0, 2, 0,		/* 0x74 */
884		{{2, 2},
885		{4, 6},
886		{0, 0},
887		{0, 0}
888		}
889	},
890	{1, 0, 3, 0,		/* 0x75 */
891		{{0, 0},
892		{2, 2},
893		{4, 6},
894		{0, 0}
895		}
896	},
897	{0, 0, 2, 0,		/* 0x76 */
898		{{1, 2},
899		{4, 6},
900		{0, 0},
901		{0, 0}
902		}
903	},
904	{1, 0, 2, 0,		/* 0x77 */
905		{{0, 2},
906		{4, 6},
907		{0, 0},
908		{0, 0}
909		}
910	},
911	{0, 0, 1, 0,		/* 0x78 */
912		{{3, 6},
913		{0, 0},
914		{0, 0},
915		{0, 0}
916		}
917	},
918	{1, 0, 2, 0,		/* 0x79 */
919		{{0, 0},
920		{3, 6},
921		{0, 0},
922		{0, 0}
923		}
924	},
925	{0, 0, 2, 0,		/* 0x7a */
926		{{1, 1},
927		{3, 6},
928		{0, 0},
929		{0, 0}
930		}
931	},
932	{1, 0, 2, 0,		/* 0x7b */
933		{{0, 1},
934		{3, 6},
935		{0, 0},
936		{0, 0}
937		}
938	},
939	{0, 0, 1, 0,		/* 0x7c */
940		{{2, 6},
941		{0, 0},
942		{0, 0},
943		{0, 0}
944		}
945	},
946	{1, 0, 2, 0,		/* 0x7d */
947		{{0, 0},
948		{2, 6},
949		{0, 0},
950		{0, 0}
951		}
952	},
953	{0, 0, 1, 0,		/* 0x7e */
954		{{1, 6},
955		{0, 0},
956		{0, 0},
957		{0, 0}
958		}
959	},
960	{1, 0, 1, 0,		/* 0x7f */
961		{{0, 6},
962		{0, 0},
963		{0, 0},
964		{0, 0}
965		}
966	},
967	{0, 1, 1, 0,		/* 0x80 */
968		{{7, 7},
969		{0, 0},
970		{0, 0},
971		{0, 0}
972		}
973	},
974	{1, 1, 2, 0,		/* 0x81 */
975		{{0, 0},
976		{7, 7},
977		{0, 0},
978		{0, 0}
979		}
980	},
981	{0, 1, 2, 0,		/* 0x82 */
982		{{1, 1},
983		{7, 7},
984		{0, 0},
985		{0, 0}
986		}
987	},
988	{1, 1, 2, 0,		/* 0x83 */
989		{{0, 1},
990		{7, 7},
991		{0, 0},
992		{0, 0}
993		}
994	},
995	{0, 1, 2, 0,		/* 0x84 */
996		{{2, 2},
997		{7, 7},
998		{0, 0},
999		{0, 0}
1000		}
1001	},
1002	{1, 1, 3, 0,		/* 0x85 */
1003		{{0, 0},
1004		{2, 2},
1005		{7, 7},
1006		{0, 0}
1007		}
1008	},
1009	{0, 1, 2, 0,		/* 0x86 */
1010		{{1, 2},
1011		{7, 7},
1012		{0, 0},
1013		{0, 0}
1014		}
1015	},
1016	{1, 1, 2, 0,		/* 0x87 */
1017		{{0, 2},
1018		{7, 7},
1019		{0, 0},
1020		{0, 0}
1021		}
1022	},
1023	{0, 1, 2, 0,		/* 0x88 */
1024		{{3, 3},
1025		{7, 7},
1026		{0, 0},
1027		{0, 0}
1028		}
1029	},
1030	{1, 1, 3, 0,		/* 0x89 */
1031		{{0, 0},
1032		{3, 3},
1033		{7, 7},
1034		{0, 0}
1035		}
1036	},
1037	{0, 1, 3, 0,		/* 0x8a */
1038		{{1, 1},
1039		{3, 3},
1040		{7, 7},
1041		{0, 0}
1042		}
1043	},
1044	{1, 1, 3, 0,		/* 0x8b */
1045		{{0, 1},
1046		{3, 3},
1047		{7, 7},
1048		{0, 0}
1049		}
1050	},
1051	{0, 1, 2, 0,		/* 0x8c */
1052		{{2, 3},
1053		{7, 7},
1054		{0, 0},
1055		{0, 0}
1056		}
1057	},
1058	{1, 1, 3, 0,		/* 0x8d */
1059		{{0, 0},
1060		{2, 3},
1061		{7, 7},
1062		{0, 0}
1063		}
1064	},
1065	{0, 1, 2, 0,		/* 0x8e */
1066		{{1, 3},
1067		{7, 7},
1068		{0, 0},
1069		{0, 0}
1070		}
1071	},
1072	{1, 1, 2, 0,		/* 0x8f */
1073		{{0, 3},
1074		{7, 7},
1075		{0, 0},
1076		{0, 0}
1077		}
1078	},
1079	{0, 1, 2, 0,		/* 0x90 */
1080		{{4, 4},
1081		{7, 7},
1082		{0, 0},
1083		{0, 0}
1084		}
1085	},
1086	{1, 1, 3, 0,		/* 0x91 */
1087		{{0, 0},
1088		{4, 4},
1089		{7, 7},
1090		{0, 0}
1091		}
1092	},
1093	{0, 1, 3, 0,		/* 0x92 */
1094		{{1, 1},
1095		{4, 4},
1096		{7, 7},
1097		{0, 0}
1098		}
1099	},
1100	{1, 1, 3, 0,		/* 0x93 */
1101		{{0, 1},
1102		{4, 4},
1103		{7, 7},
1104		{0, 0}
1105		}
1106	},
1107	{0, 1, 3, 0,		/* 0x94 */
1108		{{2, 2},
1109		{4, 4},
1110		{7, 7},
1111		{0, 0}
1112		}
1113	},
1114	{1, 1, 4, 0,		/* 0x95 */
1115		{{0, 0},
1116		{2, 2},
1117		{4, 4},
1118		{7, 7}
1119		}
1120	},
1121	{0, 1, 3, 0,		/* 0x96 */
1122		{{1, 2},
1123		{4, 4},
1124		{7, 7},
1125		{0, 0}
1126		}
1127	},
1128	{1, 1, 3, 0,		/* 0x97 */
1129		{{0, 2},
1130		{4, 4},
1131		{7, 7},
1132		{0, 0}
1133		}
1134	},
1135	{0, 1, 2, 0,		/* 0x98 */
1136		{{3, 4},
1137		{7, 7},
1138		{0, 0},
1139		{0, 0}
1140		}
1141	},
1142	{1, 1, 3, 0,		/* 0x99 */
1143		{{0, 0},
1144		{3, 4},
1145		{7, 7},
1146		{0, 0}
1147		}
1148	},
1149	{0, 1, 3, 0,		/* 0x9a */
1150		{{1, 1},
1151		{3, 4},
1152		{7, 7},
1153		{0, 0}
1154		}
1155	},
1156	{1, 1, 3, 0,		/* 0x9b */
1157		{{0, 1},
1158		{3, 4},
1159		{7, 7},
1160		{0, 0}
1161		}
1162	},
1163	{0, 1, 2, 0,		/* 0x9c */
1164		{{2, 4},
1165		{7, 7},
1166		{0, 0},
1167		{0, 0}
1168		}
1169	},
1170	{1, 1, 3, 0,		/* 0x9d */
1171		{{0, 0},
1172		{2, 4},
1173		{7, 7},
1174		{0, 0}
1175		}
1176	},
1177	{0, 1, 2, 0,		/* 0x9e */
1178		{{1, 4},
1179		{7, 7},
1180		{0, 0},
1181		{0, 0}
1182		}
1183	},
1184	{1, 1, 2, 0,		/* 0x9f */
1185		{{0, 4},
1186		{7, 7},
1187		{0, 0},
1188		{0, 0}
1189		}
1190	},
1191	{0, 1, 2, 0,		/* 0xa0 */
1192		{{5, 5},
1193		{7, 7},
1194		{0, 0},
1195		{0, 0}
1196		}
1197	},
1198	{1, 1, 3, 0,		/* 0xa1 */
1199		{{0, 0},
1200		{5, 5},
1201		{7, 7},
1202		{0, 0}
1203		}
1204	},
1205	{0, 1, 3, 0,		/* 0xa2 */
1206		{{1, 1},
1207		{5, 5},
1208		{7, 7},
1209		{0, 0}
1210		}
1211	},
1212	{1, 1, 3, 0,		/* 0xa3 */
1213		{{0, 1},
1214		{5, 5},
1215		{7, 7},
1216		{0, 0}
1217		}
1218	},
1219	{0, 1, 3, 0,		/* 0xa4 */
1220		{{2, 2},
1221		{5, 5},
1222		{7, 7},
1223		{0, 0}
1224		}
1225	},
1226	{1, 1, 4, 0,		/* 0xa5 */
1227		{{0, 0},
1228		{2, 2},
1229		{5, 5},
1230		{7, 7}
1231		}
1232	},
1233	{0, 1, 3, 0,		/* 0xa6 */
1234		{{1, 2},
1235		{5, 5},
1236		{7, 7},
1237		{0, 0}
1238		}
1239	},
1240	{1, 1, 3, 0,		/* 0xa7 */
1241		{{0, 2},
1242		{5, 5},
1243		{7, 7},
1244		{0, 0}
1245		}
1246	},
1247	{0, 1, 3, 0,		/* 0xa8 */
1248		{{3, 3},
1249		{5, 5},
1250		{7, 7},
1251		{0, 0}
1252		}
1253	},
1254	{1, 1, 4, 0,		/* 0xa9 */
1255		{{0, 0},
1256		{3, 3},
1257		{5, 5},
1258		{7, 7}
1259		}
1260	},
1261	{0, 1, 4, 0,		/* 0xaa */
1262		{{1, 1},
1263		{3, 3},
1264		{5, 5},
1265		{7, 7}
1266		}
1267	},
1268	{1, 1, 4, 0,		/* 0xab */
1269		{{0, 1},
1270		{3, 3},
1271		{5, 5},
1272		{7, 7}
1273		}
1274	},
1275	{0, 1, 3, 0,		/* 0xac */
1276		{{2, 3},
1277		{5, 5},
1278		{7, 7},
1279		{0, 0}
1280		}
1281	},
1282	{1, 1, 4, 0,		/* 0xad */
1283		{{0, 0},
1284		{2, 3},
1285		{5, 5},
1286		{7, 7}
1287		}
1288	},
1289	{0, 1, 3, 0,		/* 0xae */
1290		{{1, 3},
1291		{5, 5},
1292		{7, 7},
1293		{0, 0}
1294		}
1295	},
1296	{1, 1, 3, 0,		/* 0xaf */
1297		{{0, 3},
1298		{5, 5},
1299		{7, 7},
1300		{0, 0}
1301		}
1302	},
1303	{0, 1, 2, 0,		/* 0xb0 */
1304		{{4, 5},
1305		{7, 7},
1306		{0, 0},
1307		{0, 0}
1308		}
1309	},
1310	{1, 1, 3, 0,		/* 0xb1 */
1311		{{0, 0},
1312		{4, 5},
1313		{7, 7},
1314		{0, 0}
1315		}
1316	},
1317	{0, 1, 3, 0,		/* 0xb2 */
1318		{{1, 1},
1319		{4, 5},
1320		{7, 7},
1321		{0, 0}
1322		}
1323	},
1324	{1, 1, 3, 0,		/* 0xb3 */
1325		{{0, 1},
1326		{4, 5},
1327		{7, 7},
1328		{0, 0}
1329		}
1330	},
1331	{0, 1, 3, 0,		/* 0xb4 */
1332		{{2, 2},
1333		{4, 5},
1334		{7, 7},
1335		{0, 0}
1336		}
1337	},
1338	{1, 1, 4, 0,		/* 0xb5 */
1339		{{0, 0},
1340		{2, 2},
1341		{4, 5},
1342		{7, 7}
1343		}
1344	},
1345	{0, 1, 3, 0,		/* 0xb6 */
1346		{{1, 2},
1347		{4, 5},
1348		{7, 7},
1349		{0, 0}
1350		}
1351	},
1352	{1, 1, 3, 0,		/* 0xb7 */
1353		{{0, 2},
1354		{4, 5},
1355		{7, 7},
1356		{0, 0}
1357		}
1358	},
1359	{0, 1, 2, 0,		/* 0xb8 */
1360		{{3, 5},
1361		{7, 7},
1362		{0, 0},
1363		{0, 0}
1364		}
1365	},
1366	{1, 1, 3, 0,		/* 0xb9 */
1367		{{0, 0},
1368		{3, 5},
1369		{7, 7},
1370		{0, 0}
1371		}
1372	},
1373	{0, 1, 3, 0,		/* 0xba */
1374		{{1, 1},
1375		{3, 5},
1376		{7, 7},
1377		{0, 0}
1378		}
1379	},
1380	{1, 1, 3, 0,		/* 0xbb */
1381		{{0, 1},
1382		{3, 5},
1383		{7, 7},
1384		{0, 0}
1385		}
1386	},
1387	{0, 1, 2, 0,		/* 0xbc */
1388		{{2, 5},
1389		{7, 7},
1390		{0, 0},
1391		{0, 0}
1392		}
1393	},
1394	{1, 1, 3, 0,		/* 0xbd */
1395		{{0, 0},
1396		{2, 5},
1397		{7, 7},
1398		{0, 0}
1399		}
1400	},
1401	{0, 1, 2, 0,		/* 0xbe */
1402		{{1, 5},
1403		{7, 7},
1404		{0, 0},
1405		{0, 0}
1406		}
1407	},
1408	{1, 1, 2, 0,		/* 0xbf */
1409		{{0, 5},
1410		{7, 7},
1411		{0, 0},
1412		{0, 0}
1413		}
1414	},
1415	{0, 1, 1, 0,		/* 0xc0 */
1416		{{6, 7},
1417		{0, 0},
1418		{0, 0},
1419		{0, 0}
1420		}
1421	},
1422	{1, 1, 2, 0,		/* 0xc1 */
1423		{{0, 0},
1424		{6, 7},
1425		{0, 0},
1426		{0, 0}
1427		}
1428	},
1429	{0, 1, 2, 0,		/* 0xc2 */
1430		{{1, 1},
1431		{6, 7},
1432		{0, 0},
1433		{0, 0}
1434		}
1435	},
1436	{1, 1, 2, 0,		/* 0xc3 */
1437		{{0, 1},
1438		{6, 7},
1439		{0, 0},
1440		{0, 0}
1441		}
1442	},
1443	{0, 1, 2, 0,		/* 0xc4 */
1444		{{2, 2},
1445		{6, 7},
1446		{0, 0},
1447		{0, 0}
1448		}
1449	},
1450	{1, 1, 3, 0,		/* 0xc5 */
1451		{{0, 0},
1452		{2, 2},
1453		{6, 7},
1454		{0, 0}
1455		}
1456	},
1457	{0, 1, 2, 0,		/* 0xc6 */
1458		{{1, 2},
1459		{6, 7},
1460		{0, 0},
1461		{0, 0}
1462		}
1463	},
1464	{1, 1, 2, 0,		/* 0xc7 */
1465		{{0, 2},
1466		{6, 7},
1467		{0, 0},
1468		{0, 0}
1469		}
1470	},
1471	{0, 1, 2, 0,		/* 0xc8 */
1472		{{3, 3},
1473		{6, 7},
1474		{0, 0},
1475		{0, 0}
1476		}
1477	},
1478	{1, 1, 3, 0,		/* 0xc9 */
1479		{{0, 0},
1480		{3, 3},
1481		{6, 7},
1482		{0, 0}
1483		}
1484	},
1485	{0, 1, 3, 0,		/* 0xca */
1486		{{1, 1},
1487		{3, 3},
1488		{6, 7},
1489		{0, 0}
1490		}
1491	},
1492	{1, 1, 3, 0,		/* 0xcb */
1493		{{0, 1},
1494		{3, 3},
1495		{6, 7},
1496		{0, 0}
1497		}
1498	},
1499	{0, 1, 2, 0,		/* 0xcc */
1500		{{2, 3},
1501		{6, 7},
1502		{0, 0},
1503		{0, 0}
1504		}
1505	},
1506	{1, 1, 3, 0,		/* 0xcd */
1507		{{0, 0},
1508		{2, 3},
1509		{6, 7},
1510		{0, 0}
1511		}
1512	},
1513	{0, 1, 2, 0,		/* 0xce */
1514		{{1, 3},
1515		{6, 7},
1516		{0, 0},
1517		{0, 0}
1518		}
1519	},
1520	{1, 1, 2, 0,		/* 0xcf */
1521		{{0, 3},
1522		{6, 7},
1523		{0, 0},
1524		{0, 0}
1525		}
1526	},
1527	{0, 1, 2, 0,		/* 0xd0 */
1528		{{4, 4},
1529		{6, 7},
1530		{0, 0},
1531		{0, 0}
1532		}
1533	},
1534	{1, 1, 3, 0,		/* 0xd1 */
1535		{{0, 0},
1536		{4, 4},
1537		{6, 7},
1538		{0, 0}
1539		}
1540	},
1541	{0, 1, 3, 0,		/* 0xd2 */
1542		{{1, 1},
1543		{4, 4},
1544		{6, 7},
1545		{0, 0}
1546		}
1547	},
1548	{1, 1, 3, 0,		/* 0xd3 */
1549		{{0, 1},
1550		{4, 4},
1551		{6, 7},
1552		{0, 0}
1553		}
1554	},
1555	{0, 1, 3, 0,		/* 0xd4 */
1556		{{2, 2},
1557		{4, 4},
1558		{6, 7},
1559		{0, 0}
1560		}
1561	},
1562	{1, 1, 4, 0,		/* 0xd5 */
1563		{{0, 0},
1564		{2, 2},
1565		{4, 4},
1566		{6, 7}
1567		}
1568	},
1569	{0, 1, 3, 0,		/* 0xd6 */
1570		{{1, 2},
1571		{4, 4},
1572		{6, 7},
1573		{0, 0}
1574		}
1575	},
1576	{1, 1, 3, 0,		/* 0xd7 */
1577		{{0, 2},
1578		{4, 4},
1579		{6, 7},
1580		{0, 0}
1581		}
1582	},
1583	{0, 1, 2, 0,		/* 0xd8 */
1584		{{3, 4},
1585		{6, 7},
1586		{0, 0},
1587		{0, 0}
1588		}
1589	},
1590	{1, 1, 3, 0,		/* 0xd9 */
1591		{{0, 0},
1592		{3, 4},
1593		{6, 7},
1594		{0, 0}
1595		}
1596	},
1597	{0, 1, 3, 0,		/* 0xda */
1598		{{1, 1},
1599		{3, 4},
1600		{6, 7},
1601		{0, 0}
1602		}
1603	},
1604	{1, 1, 3, 0,		/* 0xdb */
1605		{{0, 1},
1606		{3, 4},
1607		{6, 7},
1608		{0, 0}
1609		}
1610	},
1611	{0, 1, 2, 0,		/* 0xdc */
1612		{{2, 4},
1613		{6, 7},
1614		{0, 0},
1615		{0, 0}
1616		}
1617	},
1618	{1, 1, 3, 0,		/* 0xdd */
1619		{{0, 0},
1620		{2, 4},
1621		{6, 7},
1622		{0, 0}
1623		}
1624	},
1625	{0, 1, 2, 0,		/* 0xde */
1626		{{1, 4},
1627		{6, 7},
1628		{0, 0},
1629		{0, 0}
1630		}
1631	},
1632	{1, 1, 2, 0,		/* 0xdf */
1633		{{0, 4},
1634		{6, 7},
1635		{0, 0},
1636		{0, 0}
1637		}
1638	},
1639	{0, 1, 1, 0,		/* 0xe0 */
1640		{{5, 7},
1641		{0, 0},
1642		{0, 0},
1643		{0, 0}
1644		}
1645	},
1646	{1, 1, 2, 0,		/* 0xe1 */
1647		{{0, 0},
1648		{5, 7},
1649		{0, 0},
1650		{0, 0}
1651		}
1652	},
1653	{0, 1, 2, 0,		/* 0xe2 */
1654		{{1, 1},
1655		{5, 7},
1656		{0, 0},
1657		{0, 0}
1658		}
1659	},
1660	{1, 1, 2, 0,		/* 0xe3 */
1661		{{0, 1},
1662		{5, 7},
1663		{0, 0},
1664		{0, 0}
1665		}
1666	},
1667	{0, 1, 2, 0,		/* 0xe4 */
1668		{{2, 2},
1669		{5, 7},
1670		{0, 0},
1671		{0, 0}
1672		}
1673	},
1674	{1, 1, 3, 0,		/* 0xe5 */
1675		{{0, 0},
1676		{2, 2},
1677		{5, 7},
1678		{0, 0}
1679		}
1680	},
1681	{0, 1, 2, 0,		/* 0xe6 */
1682		{{1, 2},
1683		{5, 7},
1684		{0, 0},
1685		{0, 0}
1686		}
1687	},
1688	{1, 1, 2, 0,		/* 0xe7 */
1689		{{0, 2},
1690		{5, 7},
1691		{0, 0},
1692		{0, 0}
1693		}
1694	},
1695	{0, 1, 2, 0,		/* 0xe8 */
1696		{{3, 3},
1697		{5, 7},
1698		{0, 0},
1699		{0, 0}
1700		}
1701	},
1702	{1, 1, 3, 0,		/* 0xe9 */
1703		{{0, 0},
1704		{3, 3},
1705		{5, 7},
1706		{0, 0}
1707		}
1708	},
1709	{0, 1, 3, 0,		/* 0xea */
1710		{{1, 1},
1711		{3, 3},
1712		{5, 7},
1713		{0, 0}
1714		}
1715	},
1716	{1, 1, 3, 0,		/* 0xeb */
1717		{{0, 1},
1718		{3, 3},
1719		{5, 7},
1720		{0, 0}
1721		}
1722	},
1723	{0, 1, 2, 0,		/* 0xec */
1724		{{2, 3},
1725		{5, 7},
1726		{0, 0},
1727		{0, 0}
1728		}
1729	},
1730	{1, 1, 3, 0,		/* 0xed */
1731		{{0, 0},
1732		{2, 3},
1733		{5, 7},
1734		{0, 0}
1735		}
1736	},
1737	{0, 1, 2, 0,		/* 0xee */
1738		{{1, 3},
1739		{5, 7},
1740		{0, 0},
1741		{0, 0}
1742		}
1743	},
1744	{1, 1, 2, 0,		/* 0xef */
1745		{{0, 3},
1746		{5, 7},
1747		{0, 0},
1748		{0, 0}
1749		}
1750	},
1751	{0, 1, 1, 0,		/* 0xf0 */
1752		{{4, 7},
1753		{0, 0},
1754		{0, 0},
1755		{0, 0}
1756		}
1757	},
1758	{1, 1, 2, 0,		/* 0xf1 */
1759		{{0, 0},
1760		{4, 7},
1761		{0, 0},
1762		{0, 0}
1763		}
1764	},
1765	{0, 1, 2, 0,		/* 0xf2 */
1766		{{1, 1},
1767		{4, 7},
1768		{0, 0},
1769		{0, 0}
1770		}
1771	},
1772	{1, 1, 2, 0,		/* 0xf3 */
1773		{{0, 1},
1774		{4, 7},
1775		{0, 0},
1776		{0, 0}
1777		}
1778	},
1779	{0, 1, 2, 0,		/* 0xf4 */
1780		{{2, 2},
1781		{4, 7},
1782		{0, 0},
1783		{0, 0}
1784		}
1785	},
1786	{1, 1, 3, 0,		/* 0xf5 */
1787		{{0, 0},
1788		{2, 2},
1789		{4, 7},
1790		{0, 0}
1791		}
1792	},
1793	{0, 1, 2, 0,		/* 0xf6 */
1794		{{1, 2},
1795		{4, 7},
1796		{0, 0},
1797		{0, 0}
1798		}
1799	},
1800	{1, 1, 2, 0,		/* 0xf7 */
1801		{{0, 2},
1802		{4, 7},
1803		{0, 0},
1804		{0, 0}
1805		}
1806	},
1807	{0, 1, 1, 0,		/* 0xf8 */
1808		{{3, 7},
1809		{0, 0},
1810		{0, 0},
1811		{0, 0}
1812		}
1813	},
1814	{1, 1, 2, 0,		/* 0xf9 */
1815		{{0, 0},
1816		{3, 7},
1817		{0, 0},
1818		{0, 0}
1819		}
1820	},
1821	{0, 1, 2, 0,		/* 0xfa */
1822		{{1, 1},
1823		{3, 7},
1824		{0, 0},
1825		{0, 0}
1826		}
1827	},
1828	{1, 1, 2, 0,		/* 0xfb */
1829		{{0, 1},
1830		{3, 7},
1831		{0, 0},
1832		{0, 0}
1833		}
1834	},
1835	{0, 1, 1, 0,		/* 0xfc */
1836		{{2, 7},
1837		{0, 0},
1838		{0, 0},
1839		{0, 0}
1840		}
1841	},
1842	{1, 1, 2, 0,		/* 0xfd */
1843		{{0, 0},
1844		{2, 7},
1845		{0, 0},
1846		{0, 0}
1847		}
1848	},
1849	{0, 1, 1, 0,		/* 0xfe */
1850		{{1, 7},
1851		{0, 0},
1852		{0, 0},
1853		{0, 0}
1854		}
1855	},
1856	{1, 1, 1, 0,		/* 0xff */
1857		{{0, 7},
1858		{0, 0},
1859		{0, 0},
1860		{0, 0}
1861		}
1862	}
1863};
1864
1865
1866int
1867sctp_is_address_in_scope(struct sctp_ifa *ifa,
1868    struct sctp_scoping *scope,
1869    int do_update)
1870{
1871	if ((scope->loopback_scope == 0) &&
1872	    (ifa->ifn_p) && SCTP_IFN_IS_IFT_LOOP(ifa->ifn_p)) {
1873		/*
1874		 * skip loopback if not in scope *
1875		 */
1876		return (0);
1877	}
1878	switch (ifa->address.sa.sa_family) {
1879#ifdef INET
1880	case AF_INET:
1881		if (scope->ipv4_addr_legal) {
1882			struct sockaddr_in *sin;
1883
1884			sin = &ifa->address.sin;
1885			if (sin->sin_addr.s_addr == 0) {
1886				/* not in scope , unspecified */
1887				return (0);
1888			}
1889			if ((scope->ipv4_local_scope == 0) &&
1890			    (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
1891				/* private address not in scope */
1892				return (0);
1893			}
1894		} else {
1895			return (0);
1896		}
1897		break;
1898#endif
1899#ifdef INET6
1900	case AF_INET6:
1901		if (scope->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 = &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 ((scope->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
1939static struct mbuf *
1940sctp_add_addr_to_mbuf(struct mbuf *m, struct sctp_ifa *ifa, uint16_t * len)
1941{
1942#if defined(INET) || defined(INET6)
1943	struct sctp_paramhdr *parmh;
1944	struct mbuf *mret;
1945	uint16_t plen;
1946
1947#endif
1948
1949	switch (ifa->address.sa.sa_family) {
1950#ifdef INET
1951	case AF_INET:
1952		plen = (uint16_t) sizeof(struct sctp_ipv4addr_param);
1953		break;
1954#endif
1955#ifdef INET6
1956	case AF_INET6:
1957		plen = (uint16_t) sizeof(struct sctp_ipv6addr_param);
1958		break;
1959#endif
1960	default:
1961		return (m);
1962	}
1963#if defined(INET) || defined(INET6)
1964	if (M_TRAILINGSPACE(m) >= plen) {
1965		/* easy side we just drop it on the end */
1966		parmh = (struct sctp_paramhdr *)(SCTP_BUF_AT(m, SCTP_BUF_LEN(m)));
1967		mret = m;
1968	} else {
1969		/* Need more space */
1970		mret = m;
1971		while (SCTP_BUF_NEXT(mret) != NULL) {
1972			mret = SCTP_BUF_NEXT(mret);
1973		}
1974		SCTP_BUF_NEXT(mret) = sctp_get_mbuf_for_msg(plen, 0, M_NOWAIT, 1, MT_DATA);
1975		if (SCTP_BUF_NEXT(mret) == NULL) {
1976			/* We are hosed, can't add more addresses */
1977			return (m);
1978		}
1979		mret = SCTP_BUF_NEXT(mret);
1980		parmh = mtod(mret, struct sctp_paramhdr *);
1981	}
1982	/* now add the parameter */
1983	switch (ifa->address.sa.sa_family) {
1984#ifdef INET
1985	case AF_INET:
1986		{
1987			struct sctp_ipv4addr_param *ipv4p;
1988			struct sockaddr_in *sin;
1989
1990			sin = &ifa->address.sin;
1991			ipv4p = (struct sctp_ipv4addr_param *)parmh;
1992			parmh->param_type = htons(SCTP_IPV4_ADDRESS);
1993			parmh->param_length = htons(plen);
1994			ipv4p->addr = sin->sin_addr.s_addr;
1995			SCTP_BUF_LEN(mret) += plen;
1996			break;
1997		}
1998#endif
1999#ifdef INET6
2000	case AF_INET6:
2001		{
2002			struct sctp_ipv6addr_param *ipv6p;
2003			struct sockaddr_in6 *sin6;
2004
2005			sin6 = &ifa->address.sin6;
2006			ipv6p = (struct sctp_ipv6addr_param *)parmh;
2007			parmh->param_type = htons(SCTP_IPV6_ADDRESS);
2008			parmh->param_length = htons(plen);
2009			memcpy(ipv6p->addr, &sin6->sin6_addr,
2010			    sizeof(ipv6p->addr));
2011			/* clear embedded scope in the address */
2012			in6_clearscope((struct in6_addr *)ipv6p->addr);
2013			SCTP_BUF_LEN(mret) += plen;
2014			break;
2015		}
2016#endif
2017	default:
2018		return (m);
2019	}
2020	if (len != NULL) {
2021		*len += plen;
2022	}
2023	return (mret);
2024#endif
2025}
2026
2027
2028struct mbuf *
2029sctp_add_addresses_to_i_ia(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
2030    struct sctp_scoping *scope,
2031    struct mbuf *m_at, int cnt_inits_to,
2032    uint16_t * padding_len, uint16_t * chunk_len)
2033{
2034	struct sctp_vrf *vrf = NULL;
2035	int cnt, limit_out = 0, total_count;
2036	uint32_t vrf_id;
2037
2038	vrf_id = inp->def_vrf_id;
2039	SCTP_IPI_ADDR_RLOCK();
2040	vrf = sctp_find_vrf(vrf_id);
2041	if (vrf == NULL) {
2042		SCTP_IPI_ADDR_RUNLOCK();
2043		return (m_at);
2044	}
2045	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
2046		struct sctp_ifa *sctp_ifap;
2047		struct sctp_ifn *sctp_ifnp;
2048
2049		cnt = cnt_inits_to;
2050		if (vrf->total_ifa_count > SCTP_COUNT_LIMIT) {
2051			limit_out = 1;
2052			cnt = SCTP_ADDRESS_LIMIT;
2053			goto skip_count;
2054		}
2055		LIST_FOREACH(sctp_ifnp, &vrf->ifnlist, next_ifn) {
2056			if ((scope->loopback_scope == 0) &&
2057			    SCTP_IFN_IS_IFT_LOOP(sctp_ifnp)) {
2058				/*
2059				 * Skip loopback devices if loopback_scope
2060				 * not set
2061				 */
2062				continue;
2063			}
2064			LIST_FOREACH(sctp_ifap, &sctp_ifnp->ifalist, next_ifa) {
2065#ifdef INET
2066				if ((sctp_ifap->address.sa.sa_family == AF_INET) &&
2067				    (prison_check_ip4(inp->ip_inp.inp.inp_cred,
2068				    &sctp_ifap->address.sin.sin_addr) != 0)) {
2069					continue;
2070				}
2071#endif
2072#ifdef INET6
2073				if ((sctp_ifap->address.sa.sa_family == AF_INET6) &&
2074				    (prison_check_ip6(inp->ip_inp.inp.inp_cred,
2075				    &sctp_ifap->address.sin6.sin6_addr) != 0)) {
2076					continue;
2077				}
2078#endif
2079				if (sctp_is_addr_restricted(stcb, sctp_ifap)) {
2080					continue;
2081				}
2082				if (sctp_is_address_in_scope(sctp_ifap, scope, 1) == 0) {
2083					continue;
2084				}
2085				cnt++;
2086				if (cnt > SCTP_ADDRESS_LIMIT) {
2087					break;
2088				}
2089			}
2090			if (cnt > SCTP_ADDRESS_LIMIT) {
2091				break;
2092			}
2093		}
2094skip_count:
2095		if (cnt > 1) {
2096			total_count = 0;
2097			LIST_FOREACH(sctp_ifnp, &vrf->ifnlist, next_ifn) {
2098				cnt = 0;
2099				if ((scope->loopback_scope == 0) &&
2100				    SCTP_IFN_IS_IFT_LOOP(sctp_ifnp)) {
2101					/*
2102					 * Skip loopback devices if
2103					 * loopback_scope not set
2104					 */
2105					continue;
2106				}
2107				LIST_FOREACH(sctp_ifap, &sctp_ifnp->ifalist, next_ifa) {
2108#ifdef INET
2109					if ((sctp_ifap->address.sa.sa_family == AF_INET) &&
2110					    (prison_check_ip4(inp->ip_inp.inp.inp_cred,
2111					    &sctp_ifap->address.sin.sin_addr) != 0)) {
2112						continue;
2113					}
2114#endif
2115#ifdef INET6
2116					if ((sctp_ifap->address.sa.sa_family == AF_INET6) &&
2117					    (prison_check_ip6(inp->ip_inp.inp.inp_cred,
2118					    &sctp_ifap->address.sin6.sin6_addr) != 0)) {
2119						continue;
2120					}
2121#endif
2122					if (sctp_is_addr_restricted(stcb, sctp_ifap)) {
2123						continue;
2124					}
2125					if (sctp_is_address_in_scope(sctp_ifap,
2126					    scope, 0) == 0) {
2127						continue;
2128					}
2129					if ((chunk_len != NULL) &&
2130					    (padding_len != NULL) &&
2131					    (*padding_len > 0)) {
2132						memset(mtod(m_at, caddr_t)+*chunk_len, 0, *padding_len);
2133						SCTP_BUF_LEN(m_at) += *padding_len;
2134						*chunk_len += *padding_len;
2135						*padding_len = 0;
2136					}
2137					m_at = sctp_add_addr_to_mbuf(m_at, sctp_ifap, chunk_len);
2138					if (limit_out) {
2139						cnt++;
2140						total_count++;
2141						if (cnt >= 2) {
2142							/*
2143							 * two from each
2144							 * address
2145							 */
2146							break;
2147						}
2148						if (total_count > SCTP_ADDRESS_LIMIT) {
2149							/* No more addresses */
2150							break;
2151						}
2152					}
2153				}
2154			}
2155		}
2156	} else {
2157		struct sctp_laddr *laddr;
2158
2159		cnt = cnt_inits_to;
2160		/* First, how many ? */
2161		LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2162			if (laddr->ifa == NULL) {
2163				continue;
2164			}
2165			if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED)
2166				/*
2167				 * Address being deleted by the system, dont
2168				 * list.
2169				 */
2170				continue;
2171			if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2172				/*
2173				 * Address being deleted on this ep don't
2174				 * list.
2175				 */
2176				continue;
2177			}
2178			if (sctp_is_address_in_scope(laddr->ifa,
2179			    scope, 1) == 0) {
2180				continue;
2181			}
2182			cnt++;
2183		}
2184		/*
2185		 * To get through a NAT we only list addresses if we have
2186		 * more than one. That way if you just bind a single address
2187		 * we let the source of the init dictate our address.
2188		 */
2189		if (cnt > 1) {
2190			cnt = cnt_inits_to;
2191			LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2192				if (laddr->ifa == NULL) {
2193					continue;
2194				}
2195				if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
2196					continue;
2197				}
2198				if (sctp_is_address_in_scope(laddr->ifa,
2199				    scope, 0) == 0) {
2200					continue;
2201				}
2202				if ((chunk_len != NULL) &&
2203				    (padding_len != NULL) &&
2204				    (*padding_len > 0)) {
2205					memset(mtod(m_at, caddr_t)+*chunk_len, 0, *padding_len);
2206					SCTP_BUF_LEN(m_at) += *padding_len;
2207					*chunk_len += *padding_len;
2208					*padding_len = 0;
2209				}
2210				m_at = sctp_add_addr_to_mbuf(m_at, laddr->ifa, chunk_len);
2211				cnt++;
2212				if (cnt >= SCTP_ADDRESS_LIMIT) {
2213					break;
2214				}
2215			}
2216		}
2217	}
2218	SCTP_IPI_ADDR_RUNLOCK();
2219	return (m_at);
2220}
2221
2222static struct sctp_ifa *
2223sctp_is_ifa_addr_preferred(struct sctp_ifa *ifa,
2224    uint8_t dest_is_loop,
2225    uint8_t dest_is_priv,
2226    sa_family_t fam)
2227{
2228	uint8_t dest_is_global = 0;
2229
2230	/* dest_is_priv is true if destination is a private address */
2231	/* dest_is_loop is true if destination is a loopback addresses */
2232
2233	/**
2234	 * Here we determine if its a preferred address. A preferred address
2235	 * means it is the same scope or higher scope then the destination.
2236	 * L = loopback, P = private, G = global
2237	 * -----------------------------------------
2238	 *    src    |  dest | result
2239	 *  ----------------------------------------
2240	 *     L     |    L  |    yes
2241	 *  -----------------------------------------
2242	 *     P     |    L  |    yes-v4 no-v6
2243	 *  -----------------------------------------
2244	 *     G     |    L  |    yes-v4 no-v6
2245	 *  -----------------------------------------
2246	 *     L     |    P  |    no
2247	 *  -----------------------------------------
2248	 *     P     |    P  |    yes
2249	 *  -----------------------------------------
2250	 *     G     |    P  |    no
2251	 *   -----------------------------------------
2252	 *     L     |    G  |    no
2253	 *   -----------------------------------------
2254	 *     P     |    G  |    no
2255	 *    -----------------------------------------
2256	 *     G     |    G  |    yes
2257	 *    -----------------------------------------
2258	 */
2259
2260	if (ifa->address.sa.sa_family != fam) {
2261		/* forget mis-matched family */
2262		return (NULL);
2263	}
2264	if ((dest_is_priv == 0) && (dest_is_loop == 0)) {
2265		dest_is_global = 1;
2266	}
2267	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Is destination preferred:");
2268	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &ifa->address.sa);
2269	/* Ok the address may be ok */
2270#ifdef INET6
2271	if (fam == AF_INET6) {
2272		/* ok to use deprecated addresses? no lets not! */
2273		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
2274			SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:1\n");
2275			return (NULL);
2276		}
2277		if (ifa->src_is_priv && !ifa->src_is_loop) {
2278			if (dest_is_loop) {
2279				SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:2\n");
2280				return (NULL);
2281			}
2282		}
2283		if (ifa->src_is_glob) {
2284			if (dest_is_loop) {
2285				SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:3\n");
2286				return (NULL);
2287			}
2288		}
2289	}
2290#endif
2291	/*
2292	 * Now that we know what is what, implement or table this could in
2293	 * theory be done slicker (it used to be), but this is
2294	 * straightforward and easier to validate :-)
2295	 */
2296	SCTPDBG(SCTP_DEBUG_OUTPUT3, "src_loop:%d src_priv:%d src_glob:%d\n",
2297	    ifa->src_is_loop, ifa->src_is_priv, ifa->src_is_glob);
2298	SCTPDBG(SCTP_DEBUG_OUTPUT3, "dest_loop:%d dest_priv:%d dest_glob:%d\n",
2299	    dest_is_loop, dest_is_priv, dest_is_global);
2300
2301	if ((ifa->src_is_loop) && (dest_is_priv)) {
2302		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:4\n");
2303		return (NULL);
2304	}
2305	if ((ifa->src_is_glob) && (dest_is_priv)) {
2306		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:5\n");
2307		return (NULL);
2308	}
2309	if ((ifa->src_is_loop) && (dest_is_global)) {
2310		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:6\n");
2311		return (NULL);
2312	}
2313	if ((ifa->src_is_priv) && (dest_is_global)) {
2314		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:7\n");
2315		return (NULL);
2316	}
2317	SCTPDBG(SCTP_DEBUG_OUTPUT3, "YES\n");
2318	/* its a preferred address */
2319	return (ifa);
2320}
2321
2322static struct sctp_ifa *
2323sctp_is_ifa_addr_acceptable(struct sctp_ifa *ifa,
2324    uint8_t dest_is_loop,
2325    uint8_t dest_is_priv,
2326    sa_family_t fam)
2327{
2328	uint8_t dest_is_global = 0;
2329
2330	/**
2331	 * Here we determine if its a acceptable address. A acceptable
2332	 * address means it is the same scope or higher scope but we can
2333	 * allow for NAT which means its ok to have a global dest and a
2334	 * private src.
2335	 *
2336	 * L = loopback, P = private, G = global
2337	 * -----------------------------------------
2338	 *  src    |  dest | result
2339	 * -----------------------------------------
2340	 *   L     |   L   |    yes
2341	 *  -----------------------------------------
2342	 *   P     |   L   |    yes-v4 no-v6
2343	 *  -----------------------------------------
2344	 *   G     |   L   |    yes
2345	 * -----------------------------------------
2346	 *   L     |   P   |    no
2347	 * -----------------------------------------
2348	 *   P     |   P   |    yes
2349	 * -----------------------------------------
2350	 *   G     |   P   |    yes - May not work
2351	 * -----------------------------------------
2352	 *   L     |   G   |    no
2353	 * -----------------------------------------
2354	 *   P     |   G   |    yes - May not work
2355	 * -----------------------------------------
2356	 *   G     |   G   |    yes
2357	 * -----------------------------------------
2358	 */
2359
2360	if (ifa->address.sa.sa_family != fam) {
2361		/* forget non matching family */
2362		SCTPDBG(SCTP_DEBUG_OUTPUT3, "ifa_fam:%d fam:%d\n",
2363		    ifa->address.sa.sa_family, fam);
2364		return (NULL);
2365	}
2366	/* Ok the address may be ok */
2367	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT3, &ifa->address.sa);
2368	SCTPDBG(SCTP_DEBUG_OUTPUT3, "dst_is_loop:%d dest_is_priv:%d\n",
2369	    dest_is_loop, dest_is_priv);
2370	if ((dest_is_loop == 0) && (dest_is_priv == 0)) {
2371		dest_is_global = 1;
2372	}
2373#ifdef INET6
2374	if (fam == AF_INET6) {
2375		/* ok to use deprecated addresses? */
2376		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
2377			return (NULL);
2378		}
2379		if (ifa->src_is_priv) {
2380			/* Special case, linklocal to loop */
2381			if (dest_is_loop)
2382				return (NULL);
2383		}
2384	}
2385#endif
2386	/*
2387	 * Now that we know what is what, implement our table. This could in
2388	 * theory be done slicker (it used to be), but this is
2389	 * straightforward and easier to validate :-)
2390	 */
2391	SCTPDBG(SCTP_DEBUG_OUTPUT3, "ifa->src_is_loop:%d dest_is_priv:%d\n",
2392	    ifa->src_is_loop,
2393	    dest_is_priv);
2394	if ((ifa->src_is_loop == 1) && (dest_is_priv)) {
2395		return (NULL);
2396	}
2397	SCTPDBG(SCTP_DEBUG_OUTPUT3, "ifa->src_is_loop:%d dest_is_glob:%d\n",
2398	    ifa->src_is_loop,
2399	    dest_is_global);
2400	if ((ifa->src_is_loop == 1) && (dest_is_global)) {
2401		return (NULL);
2402	}
2403	SCTPDBG(SCTP_DEBUG_OUTPUT3, "address is acceptable\n");
2404	/* its an acceptable address */
2405	return (ifa);
2406}
2407
2408int
2409sctp_is_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
2410{
2411	struct sctp_laddr *laddr;
2412
2413	if (stcb == NULL) {
2414		/* There are no restrictions, no TCB :-) */
2415		return (0);
2416	}
2417	LIST_FOREACH(laddr, &stcb->asoc.sctp_restricted_addrs, sctp_nxt_addr) {
2418		if (laddr->ifa == NULL) {
2419			SCTPDBG(SCTP_DEBUG_OUTPUT1, "%s: NULL ifa\n",
2420			    __FUNCTION__);
2421			continue;
2422		}
2423		if (laddr->ifa == ifa) {
2424			/* Yes it is on the list */
2425			return (1);
2426		}
2427	}
2428	return (0);
2429}
2430
2431
2432int
2433sctp_is_addr_in_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa)
2434{
2435	struct sctp_laddr *laddr;
2436
2437	if (ifa == NULL)
2438		return (0);
2439	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2440		if (laddr->ifa == NULL) {
2441			SCTPDBG(SCTP_DEBUG_OUTPUT1, "%s: NULL ifa\n",
2442			    __FUNCTION__);
2443			continue;
2444		}
2445		if ((laddr->ifa == ifa) && laddr->action == 0)
2446			/* same pointer */
2447			return (1);
2448	}
2449	return (0);
2450}
2451
2452
2453
2454static struct sctp_ifa *
2455sctp_choose_boundspecific_inp(struct sctp_inpcb *inp,
2456    sctp_route_t * ro,
2457    uint32_t vrf_id,
2458    int non_asoc_addr_ok,
2459    uint8_t dest_is_priv,
2460    uint8_t dest_is_loop,
2461    sa_family_t fam)
2462{
2463	struct sctp_laddr *laddr, *starting_point;
2464	void *ifn;
2465	int resettotop = 0;
2466	struct sctp_ifn *sctp_ifn;
2467	struct sctp_ifa *sctp_ifa, *sifa;
2468	struct sctp_vrf *vrf;
2469	uint32_t ifn_index;
2470
2471	vrf = sctp_find_vrf(vrf_id);
2472	if (vrf == NULL)
2473		return (NULL);
2474
2475	ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2476	ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2477	sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2478	/*
2479	 * first question, is the ifn we will emit on in our list, if so, we
2480	 * want such an address. Note that we first looked for a preferred
2481	 * address.
2482	 */
2483	if (sctp_ifn) {
2484		/* is a preferred one on the interface we route out? */
2485		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2486#ifdef INET
2487			if ((sctp_ifa->address.sa.sa_family == AF_INET) &&
2488			    (prison_check_ip4(inp->ip_inp.inp.inp_cred,
2489			    &sctp_ifa->address.sin.sin_addr) != 0)) {
2490				continue;
2491			}
2492#endif
2493#ifdef INET6
2494			if ((sctp_ifa->address.sa.sa_family == AF_INET6) &&
2495			    (prison_check_ip6(inp->ip_inp.inp.inp_cred,
2496			    &sctp_ifa->address.sin6.sin6_addr) != 0)) {
2497				continue;
2498			}
2499#endif
2500			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2501			    (non_asoc_addr_ok == 0))
2502				continue;
2503			sifa = sctp_is_ifa_addr_preferred(sctp_ifa,
2504			    dest_is_loop,
2505			    dest_is_priv, fam);
2506			if (sifa == NULL)
2507				continue;
2508			if (sctp_is_addr_in_ep(inp, sifa)) {
2509				atomic_add_int(&sifa->refcount, 1);
2510				return (sifa);
2511			}
2512		}
2513	}
2514	/*
2515	 * ok, now we now need to find one on the list of the addresses. We
2516	 * can't get one on the emitting interface so let's find first a
2517	 * preferred one. If not that an acceptable one otherwise... we
2518	 * return NULL.
2519	 */
2520	starting_point = inp->next_addr_touse;
2521once_again:
2522	if (inp->next_addr_touse == NULL) {
2523		inp->next_addr_touse = LIST_FIRST(&inp->sctp_addr_list);
2524		resettotop = 1;
2525	}
2526	for (laddr = inp->next_addr_touse; laddr;
2527	    laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2528		if (laddr->ifa == NULL) {
2529			/* address has been removed */
2530			continue;
2531		}
2532		if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2533			/* address is being deleted */
2534			continue;
2535		}
2536		sifa = sctp_is_ifa_addr_preferred(laddr->ifa, dest_is_loop,
2537		    dest_is_priv, fam);
2538		if (sifa == NULL)
2539			continue;
2540		atomic_add_int(&sifa->refcount, 1);
2541		return (sifa);
2542	}
2543	if (resettotop == 0) {
2544		inp->next_addr_touse = NULL;
2545		goto once_again;
2546	}
2547	inp->next_addr_touse = starting_point;
2548	resettotop = 0;
2549once_again_too:
2550	if (inp->next_addr_touse == NULL) {
2551		inp->next_addr_touse = LIST_FIRST(&inp->sctp_addr_list);
2552		resettotop = 1;
2553	}
2554	/* ok, what about an acceptable address in the inp */
2555	for (laddr = inp->next_addr_touse; laddr;
2556	    laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2557		if (laddr->ifa == NULL) {
2558			/* address has been removed */
2559			continue;
2560		}
2561		if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2562			/* address is being deleted */
2563			continue;
2564		}
2565		sifa = sctp_is_ifa_addr_acceptable(laddr->ifa, dest_is_loop,
2566		    dest_is_priv, fam);
2567		if (sifa == NULL)
2568			continue;
2569		atomic_add_int(&sifa->refcount, 1);
2570		return (sifa);
2571	}
2572	if (resettotop == 0) {
2573		inp->next_addr_touse = NULL;
2574		goto once_again_too;
2575	}
2576	/*
2577	 * no address bound can be a source for the destination we are in
2578	 * trouble
2579	 */
2580	return (NULL);
2581}
2582
2583
2584
2585static struct sctp_ifa *
2586sctp_choose_boundspecific_stcb(struct sctp_inpcb *inp,
2587    struct sctp_tcb *stcb,
2588    sctp_route_t * ro,
2589    uint32_t vrf_id,
2590    uint8_t dest_is_priv,
2591    uint8_t dest_is_loop,
2592    int non_asoc_addr_ok,
2593    sa_family_t fam)
2594{
2595	struct sctp_laddr *laddr, *starting_point;
2596	void *ifn;
2597	struct sctp_ifn *sctp_ifn;
2598	struct sctp_ifa *sctp_ifa, *sifa;
2599	uint8_t start_at_beginning = 0;
2600	struct sctp_vrf *vrf;
2601	uint32_t ifn_index;
2602
2603	/*
2604	 * first question, is the ifn we will emit on in our list, if so, we
2605	 * want that one.
2606	 */
2607	vrf = sctp_find_vrf(vrf_id);
2608	if (vrf == NULL)
2609		return (NULL);
2610
2611	ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2612	ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2613	sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2614
2615	/*
2616	 * first question, is the ifn we will emit on in our list?  If so,
2617	 * we want that one. First we look for a preferred. Second, we go
2618	 * for an acceptable.
2619	 */
2620	if (sctp_ifn) {
2621		/* first try for a preferred address on the ep */
2622		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2623#ifdef INET
2624			if ((sctp_ifa->address.sa.sa_family == AF_INET) &&
2625			    (prison_check_ip4(inp->ip_inp.inp.inp_cred,
2626			    &sctp_ifa->address.sin.sin_addr) != 0)) {
2627				continue;
2628			}
2629#endif
2630#ifdef INET6
2631			if ((sctp_ifa->address.sa.sa_family == AF_INET6) &&
2632			    (prison_check_ip6(inp->ip_inp.inp.inp_cred,
2633			    &sctp_ifa->address.sin6.sin6_addr) != 0)) {
2634				continue;
2635			}
2636#endif
2637			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) && (non_asoc_addr_ok == 0))
2638				continue;
2639			if (sctp_is_addr_in_ep(inp, sctp_ifa)) {
2640				sifa = sctp_is_ifa_addr_preferred(sctp_ifa, dest_is_loop, dest_is_priv, fam);
2641				if (sifa == NULL)
2642					continue;
2643				if (((non_asoc_addr_ok == 0) &&
2644				    (sctp_is_addr_restricted(stcb, sifa))) ||
2645				    (non_asoc_addr_ok &&
2646				    (sctp_is_addr_restricted(stcb, sifa)) &&
2647				    (!sctp_is_addr_pending(stcb, sifa)))) {
2648					/* on the no-no list */
2649					continue;
2650				}
2651				atomic_add_int(&sifa->refcount, 1);
2652				return (sifa);
2653			}
2654		}
2655		/* next try for an acceptable address on the ep */
2656		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2657#ifdef INET
2658			if ((sctp_ifa->address.sa.sa_family == AF_INET) &&
2659			    (prison_check_ip4(inp->ip_inp.inp.inp_cred,
2660			    &sctp_ifa->address.sin.sin_addr) != 0)) {
2661				continue;
2662			}
2663#endif
2664#ifdef INET6
2665			if ((sctp_ifa->address.sa.sa_family == AF_INET6) &&
2666			    (prison_check_ip6(inp->ip_inp.inp.inp_cred,
2667			    &sctp_ifa->address.sin6.sin6_addr) != 0)) {
2668				continue;
2669			}
2670#endif
2671			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) && (non_asoc_addr_ok == 0))
2672				continue;
2673			if (sctp_is_addr_in_ep(inp, sctp_ifa)) {
2674				sifa = sctp_is_ifa_addr_acceptable(sctp_ifa, dest_is_loop, dest_is_priv, fam);
2675				if (sifa == NULL)
2676					continue;
2677				if (((non_asoc_addr_ok == 0) &&
2678				    (sctp_is_addr_restricted(stcb, sifa))) ||
2679				    (non_asoc_addr_ok &&
2680				    (sctp_is_addr_restricted(stcb, sifa)) &&
2681				    (!sctp_is_addr_pending(stcb, sifa)))) {
2682					/* on the no-no list */
2683					continue;
2684				}
2685				atomic_add_int(&sifa->refcount, 1);
2686				return (sifa);
2687			}
2688		}
2689
2690	}
2691	/*
2692	 * if we can't find one like that then we must look at all addresses
2693	 * bound to pick one at first preferable then secondly acceptable.
2694	 */
2695	starting_point = stcb->asoc.last_used_address;
2696sctp_from_the_top:
2697	if (stcb->asoc.last_used_address == NULL) {
2698		start_at_beginning = 1;
2699		stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
2700	}
2701	/* search beginning with the last used address */
2702	for (laddr = stcb->asoc.last_used_address; laddr;
2703	    laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2704		if (laddr->ifa == NULL) {
2705			/* address has been removed */
2706			continue;
2707		}
2708		if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2709			/* address is being deleted */
2710			continue;
2711		}
2712		sifa = sctp_is_ifa_addr_preferred(laddr->ifa, dest_is_loop, dest_is_priv, fam);
2713		if (sifa == NULL)
2714			continue;
2715		if (((non_asoc_addr_ok == 0) &&
2716		    (sctp_is_addr_restricted(stcb, sifa))) ||
2717		    (non_asoc_addr_ok &&
2718		    (sctp_is_addr_restricted(stcb, sifa)) &&
2719		    (!sctp_is_addr_pending(stcb, sifa)))) {
2720			/* on the no-no list */
2721			continue;
2722		}
2723		stcb->asoc.last_used_address = laddr;
2724		atomic_add_int(&sifa->refcount, 1);
2725		return (sifa);
2726	}
2727	if (start_at_beginning == 0) {
2728		stcb->asoc.last_used_address = NULL;
2729		goto sctp_from_the_top;
2730	}
2731	/* now try for any higher scope than the destination */
2732	stcb->asoc.last_used_address = starting_point;
2733	start_at_beginning = 0;
2734sctp_from_the_top2:
2735	if (stcb->asoc.last_used_address == NULL) {
2736		start_at_beginning = 1;
2737		stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
2738	}
2739	/* search beginning with the last used address */
2740	for (laddr = stcb->asoc.last_used_address; laddr;
2741	    laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2742		if (laddr->ifa == NULL) {
2743			/* address has been removed */
2744			continue;
2745		}
2746		if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2747			/* address is being deleted */
2748			continue;
2749		}
2750		sifa = sctp_is_ifa_addr_acceptable(laddr->ifa, dest_is_loop,
2751		    dest_is_priv, fam);
2752		if (sifa == NULL)
2753			continue;
2754		if (((non_asoc_addr_ok == 0) &&
2755		    (sctp_is_addr_restricted(stcb, sifa))) ||
2756		    (non_asoc_addr_ok &&
2757		    (sctp_is_addr_restricted(stcb, sifa)) &&
2758		    (!sctp_is_addr_pending(stcb, sifa)))) {
2759			/* on the no-no list */
2760			continue;
2761		}
2762		stcb->asoc.last_used_address = laddr;
2763		atomic_add_int(&sifa->refcount, 1);
2764		return (sifa);
2765	}
2766	if (start_at_beginning == 0) {
2767		stcb->asoc.last_used_address = NULL;
2768		goto sctp_from_the_top2;
2769	}
2770	return (NULL);
2771}
2772
2773static struct sctp_ifa *
2774sctp_select_nth_preferred_addr_from_ifn_boundall(struct sctp_ifn *ifn,
2775    struct sctp_inpcb *inp,
2776    struct sctp_tcb *stcb,
2777    int non_asoc_addr_ok,
2778    uint8_t dest_is_loop,
2779    uint8_t dest_is_priv,
2780    int addr_wanted,
2781    sa_family_t fam,
2782    sctp_route_t * ro
2783)
2784{
2785	struct sctp_ifa *ifa, *sifa;
2786	int num_eligible_addr = 0;
2787
2788#ifdef INET6
2789	struct sockaddr_in6 sin6, lsa6;
2790
2791	if (fam == AF_INET6) {
2792		memcpy(&sin6, &ro->ro_dst, sizeof(struct sockaddr_in6));
2793		(void)sa6_recoverscope(&sin6);
2794	}
2795#endif				/* INET6 */
2796	LIST_FOREACH(ifa, &ifn->ifalist, next_ifa) {
2797#ifdef INET
2798		if ((ifa->address.sa.sa_family == AF_INET) &&
2799		    (prison_check_ip4(inp->ip_inp.inp.inp_cred,
2800		    &ifa->address.sin.sin_addr) != 0)) {
2801			continue;
2802		}
2803#endif
2804#ifdef INET6
2805		if ((ifa->address.sa.sa_family == AF_INET6) &&
2806		    (prison_check_ip6(inp->ip_inp.inp.inp_cred,
2807		    &ifa->address.sin6.sin6_addr) != 0)) {
2808			continue;
2809		}
2810#endif
2811		if ((ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2812		    (non_asoc_addr_ok == 0))
2813			continue;
2814		sifa = sctp_is_ifa_addr_preferred(ifa, dest_is_loop,
2815		    dest_is_priv, fam);
2816		if (sifa == NULL)
2817			continue;
2818#ifdef INET6
2819		if (fam == AF_INET6 &&
2820		    dest_is_loop &&
2821		    sifa->src_is_loop && sifa->src_is_priv) {
2822			/*
2823			 * don't allow fe80::1 to be a src on loop ::1, we
2824			 * don't list it to the peer so we will get an
2825			 * abort.
2826			 */
2827			continue;
2828		}
2829		if (fam == AF_INET6 &&
2830		    IN6_IS_ADDR_LINKLOCAL(&sifa->address.sin6.sin6_addr) &&
2831		    IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr)) {
2832			/*
2833			 * link-local <-> link-local must belong to the same
2834			 * scope.
2835			 */
2836			memcpy(&lsa6, &sifa->address.sin6, sizeof(struct sockaddr_in6));
2837			(void)sa6_recoverscope(&lsa6);
2838			if (sin6.sin6_scope_id != lsa6.sin6_scope_id) {
2839				continue;
2840			}
2841		}
2842#endif				/* INET6 */
2843
2844		/*
2845		 * Check if the IPv6 address matches to next-hop. In the
2846		 * mobile case, old IPv6 address may be not deleted from the
2847		 * interface. Then, the interface has previous and new
2848		 * addresses.  We should use one corresponding to the
2849		 * next-hop.  (by micchie)
2850		 */
2851#ifdef INET6
2852		if (stcb && fam == AF_INET6 &&
2853		    sctp_is_mobility_feature_on(stcb->sctp_ep, SCTP_MOBILITY_BASE)) {
2854			if (sctp_v6src_match_nexthop(&sifa->address.sin6, ro)
2855			    == 0) {
2856				continue;
2857			}
2858		}
2859#endif
2860#ifdef INET
2861		/* Avoid topologically incorrect IPv4 address */
2862		if (stcb && fam == AF_INET &&
2863		    sctp_is_mobility_feature_on(stcb->sctp_ep, SCTP_MOBILITY_BASE)) {
2864			if (sctp_v4src_match_nexthop(sifa, ro) == 0) {
2865				continue;
2866			}
2867		}
2868#endif
2869		if (stcb) {
2870			if (sctp_is_address_in_scope(ifa, &stcb->asoc.scope, 0) == 0) {
2871				continue;
2872			}
2873			if (((non_asoc_addr_ok == 0) &&
2874			    (sctp_is_addr_restricted(stcb, sifa))) ||
2875			    (non_asoc_addr_ok &&
2876			    (sctp_is_addr_restricted(stcb, sifa)) &&
2877			    (!sctp_is_addr_pending(stcb, sifa)))) {
2878				/*
2879				 * It is restricted for some reason..
2880				 * probably not yet added.
2881				 */
2882				continue;
2883			}
2884		}
2885		if (num_eligible_addr >= addr_wanted) {
2886			return (sifa);
2887		}
2888		num_eligible_addr++;
2889	}
2890	return (NULL);
2891}
2892
2893
2894static int
2895sctp_count_num_preferred_boundall(struct sctp_ifn *ifn,
2896    struct sctp_inpcb *inp,
2897    struct sctp_tcb *stcb,
2898    int non_asoc_addr_ok,
2899    uint8_t dest_is_loop,
2900    uint8_t dest_is_priv,
2901    sa_family_t fam)
2902{
2903	struct sctp_ifa *ifa, *sifa;
2904	int num_eligible_addr = 0;
2905
2906	LIST_FOREACH(ifa, &ifn->ifalist, next_ifa) {
2907#ifdef INET
2908		if ((ifa->address.sa.sa_family == AF_INET) &&
2909		    (prison_check_ip4(inp->ip_inp.inp.inp_cred,
2910		    &ifa->address.sin.sin_addr) != 0)) {
2911			continue;
2912		}
2913#endif
2914#ifdef INET6
2915		if ((ifa->address.sa.sa_family == AF_INET6) &&
2916		    (stcb != NULL) &&
2917		    (prison_check_ip6(inp->ip_inp.inp.inp_cred,
2918		    &ifa->address.sin6.sin6_addr) != 0)) {
2919			continue;
2920		}
2921#endif
2922		if ((ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2923		    (non_asoc_addr_ok == 0)) {
2924			continue;
2925		}
2926		sifa = sctp_is_ifa_addr_preferred(ifa, dest_is_loop,
2927		    dest_is_priv, fam);
2928		if (sifa == NULL) {
2929			continue;
2930		}
2931		if (stcb) {
2932			if (sctp_is_address_in_scope(ifa, &stcb->asoc.scope, 0) == 0) {
2933				continue;
2934			}
2935			if (((non_asoc_addr_ok == 0) &&
2936			    (sctp_is_addr_restricted(stcb, sifa))) ||
2937			    (non_asoc_addr_ok &&
2938			    (sctp_is_addr_restricted(stcb, sifa)) &&
2939			    (!sctp_is_addr_pending(stcb, sifa)))) {
2940				/*
2941				 * It is restricted for some reason..
2942				 * probably not yet added.
2943				 */
2944				continue;
2945			}
2946		}
2947		num_eligible_addr++;
2948	}
2949	return (num_eligible_addr);
2950}
2951
2952static struct sctp_ifa *
2953sctp_choose_boundall(struct sctp_inpcb *inp,
2954    struct sctp_tcb *stcb,
2955    struct sctp_nets *net,
2956    sctp_route_t * ro,
2957    uint32_t vrf_id,
2958    uint8_t dest_is_priv,
2959    uint8_t dest_is_loop,
2960    int non_asoc_addr_ok,
2961    sa_family_t fam)
2962{
2963	int cur_addr_num = 0, num_preferred = 0;
2964	void *ifn;
2965	struct sctp_ifn *sctp_ifn, *looked_at = NULL, *emit_ifn;
2966	struct sctp_ifa *sctp_ifa, *sifa;
2967	uint32_t ifn_index;
2968	struct sctp_vrf *vrf;
2969
2970#ifdef INET
2971	int retried = 0;
2972
2973#endif
2974
2975	/*-
2976	 * For boundall we can use any address in the association.
2977	 * If non_asoc_addr_ok is set we can use any address (at least in
2978	 * theory). So we look for preferred addresses first. If we find one,
2979	 * we use it. Otherwise we next try to get an address on the
2980	 * interface, which we should be able to do (unless non_asoc_addr_ok
2981	 * is false and we are routed out that way). In these cases where we
2982	 * can't use the address of the interface we go through all the
2983	 * ifn's looking for an address we can use and fill that in. Punting
2984	 * means we send back address 0, which will probably cause problems
2985	 * actually since then IP will fill in the address of the route ifn,
2986	 * which means we probably already rejected it.. i.e. here comes an
2987	 * abort :-<.
2988	 */
2989	vrf = sctp_find_vrf(vrf_id);
2990	if (vrf == NULL)
2991		return (NULL);
2992
2993	ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2994	ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2995	SCTPDBG(SCTP_DEBUG_OUTPUT2, "ifn from route:%p ifn_index:%d\n", ifn, ifn_index);
2996	emit_ifn = looked_at = sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2997	if (sctp_ifn == NULL) {
2998		/* ?? We don't have this guy ?? */
2999		SCTPDBG(SCTP_DEBUG_OUTPUT2, "No ifn emit interface?\n");
3000		goto bound_all_plan_b;
3001	}
3002	SCTPDBG(SCTP_DEBUG_OUTPUT2, "ifn_index:%d name:%s is emit interface\n",
3003	    ifn_index, sctp_ifn->ifn_name);
3004
3005	if (net) {
3006		cur_addr_num = net->indx_of_eligible_next_to_use;
3007	}
3008	num_preferred = sctp_count_num_preferred_boundall(sctp_ifn,
3009	    inp, stcb,
3010	    non_asoc_addr_ok,
3011	    dest_is_loop,
3012	    dest_is_priv, fam);
3013	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Found %d preferred source addresses for intf:%s\n",
3014	    num_preferred, sctp_ifn->ifn_name);
3015	if (num_preferred == 0) {
3016		/*
3017		 * no eligible addresses, we must use some other interface
3018		 * address if we can find one.
3019		 */
3020		goto bound_all_plan_b;
3021	}
3022	/*
3023	 * Ok we have num_eligible_addr set with how many we can use, this
3024	 * may vary from call to call due to addresses being deprecated
3025	 * etc..
3026	 */
3027	if (cur_addr_num >= num_preferred) {
3028		cur_addr_num = 0;
3029	}
3030	/*
3031	 * select the nth address from the list (where cur_addr_num is the
3032	 * nth) and 0 is the first one, 1 is the second one etc...
3033	 */
3034	SCTPDBG(SCTP_DEBUG_OUTPUT2, "cur_addr_num:%d\n", cur_addr_num);
3035
3036	sctp_ifa = sctp_select_nth_preferred_addr_from_ifn_boundall(sctp_ifn, inp, stcb, non_asoc_addr_ok, dest_is_loop,
3037	    dest_is_priv, cur_addr_num, fam, ro);
3038
3039	/* if sctp_ifa is NULL something changed??, fall to plan b. */
3040	if (sctp_ifa) {
3041		atomic_add_int(&sctp_ifa->refcount, 1);
3042		if (net) {
3043			/* save off where the next one we will want */
3044			net->indx_of_eligible_next_to_use = cur_addr_num + 1;
3045		}
3046		return (sctp_ifa);
3047	}
3048	/*
3049	 * plan_b: Look at all interfaces and find a preferred address. If
3050	 * no preferred fall through to plan_c.
3051	 */
3052bound_all_plan_b:
3053	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan B\n");
3054	LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
3055		SCTPDBG(SCTP_DEBUG_OUTPUT2, "Examine interface %s\n",
3056		    sctp_ifn->ifn_name);
3057		if (dest_is_loop == 0 && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
3058			/* wrong base scope */
3059			SCTPDBG(SCTP_DEBUG_OUTPUT2, "skip\n");
3060			continue;
3061		}
3062		if ((sctp_ifn == looked_at) && looked_at) {
3063			/* already looked at this guy */
3064			SCTPDBG(SCTP_DEBUG_OUTPUT2, "already seen\n");
3065			continue;
3066		}
3067		num_preferred = sctp_count_num_preferred_boundall(sctp_ifn, inp, stcb, non_asoc_addr_ok,
3068		    dest_is_loop, dest_is_priv, fam);
3069		SCTPDBG(SCTP_DEBUG_OUTPUT2,
3070		    "Found ifn:%p %d preferred source addresses\n",
3071		    ifn, num_preferred);
3072		if (num_preferred == 0) {
3073			/* None on this interface. */
3074			SCTPDBG(SCTP_DEBUG_OUTPUT2, "No prefered -- skipping to next\n");
3075			continue;
3076		}
3077		SCTPDBG(SCTP_DEBUG_OUTPUT2,
3078		    "num preferred:%d on interface:%p cur_addr_num:%d\n",
3079		    num_preferred, (void *)sctp_ifn, cur_addr_num);
3080
3081		/*
3082		 * Ok we have num_eligible_addr set with how many we can
3083		 * use, this may vary from call to call due to addresses
3084		 * being deprecated etc..
3085		 */
3086		if (cur_addr_num >= num_preferred) {
3087			cur_addr_num = 0;
3088		}
3089		sifa = sctp_select_nth_preferred_addr_from_ifn_boundall(sctp_ifn, inp, stcb, non_asoc_addr_ok, dest_is_loop,
3090		    dest_is_priv, cur_addr_num, fam, ro);
3091		if (sifa == NULL)
3092			continue;
3093		if (net) {
3094			net->indx_of_eligible_next_to_use = cur_addr_num + 1;
3095			SCTPDBG(SCTP_DEBUG_OUTPUT2, "we selected %d\n",
3096			    cur_addr_num);
3097			SCTPDBG(SCTP_DEBUG_OUTPUT2, "Source:");
3098			SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &sifa->address.sa);
3099			SCTPDBG(SCTP_DEBUG_OUTPUT2, "Dest:");
3100			SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &net->ro._l_addr.sa);
3101		}
3102		atomic_add_int(&sifa->refcount, 1);
3103		return (sifa);
3104	}
3105#ifdef INET
3106again_with_private_addresses_allowed:
3107#endif
3108	/* plan_c: do we have an acceptable address on the emit interface */
3109	sifa = NULL;
3110	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan C: find acceptable on interface\n");
3111	if (emit_ifn == NULL) {
3112		SCTPDBG(SCTP_DEBUG_OUTPUT2, "Jump to Plan D - no emit_ifn\n");
3113		goto plan_d;
3114	}
3115	LIST_FOREACH(sctp_ifa, &emit_ifn->ifalist, next_ifa) {
3116		SCTPDBG(SCTP_DEBUG_OUTPUT2, "ifa:%p\n", (void *)sctp_ifa);
3117#ifdef INET
3118		if ((sctp_ifa->address.sa.sa_family == AF_INET) &&
3119		    (prison_check_ip4(inp->ip_inp.inp.inp_cred,
3120		    &sctp_ifa->address.sin.sin_addr) != 0)) {
3121			SCTPDBG(SCTP_DEBUG_OUTPUT2, "Jailed\n");
3122			continue;
3123		}
3124#endif
3125#ifdef INET6
3126		if ((sctp_ifa->address.sa.sa_family == AF_INET6) &&
3127		    (prison_check_ip6(inp->ip_inp.inp.inp_cred,
3128		    &sctp_ifa->address.sin6.sin6_addr) != 0)) {
3129			SCTPDBG(SCTP_DEBUG_OUTPUT2, "Jailed\n");
3130			continue;
3131		}
3132#endif
3133		if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
3134		    (non_asoc_addr_ok == 0)) {
3135			SCTPDBG(SCTP_DEBUG_OUTPUT2, "Defer\n");
3136			continue;
3137		}
3138		sifa = sctp_is_ifa_addr_acceptable(sctp_ifa, dest_is_loop,
3139		    dest_is_priv, fam);
3140		if (sifa == NULL) {
3141			SCTPDBG(SCTP_DEBUG_OUTPUT2, "IFA not acceptable\n");
3142			continue;
3143		}
3144		if (stcb) {
3145			if (sctp_is_address_in_scope(sifa, &stcb->asoc.scope, 0) == 0) {
3146				SCTPDBG(SCTP_DEBUG_OUTPUT2, "NOT in scope\n");
3147				sifa = NULL;
3148				continue;
3149			}
3150			if (((non_asoc_addr_ok == 0) &&
3151			    (sctp_is_addr_restricted(stcb, sifa))) ||
3152			    (non_asoc_addr_ok &&
3153			    (sctp_is_addr_restricted(stcb, sifa)) &&
3154			    (!sctp_is_addr_pending(stcb, sifa)))) {
3155				/*
3156				 * It is restricted for some reason..
3157				 * probably not yet added.
3158				 */
3159				SCTPDBG(SCTP_DEBUG_OUTPUT2, "Its resticted\n");
3160				sifa = NULL;
3161				continue;
3162			}
3163		} else {
3164			SCTP_PRINTF("Stcb is null - no print\n");
3165		}
3166		atomic_add_int(&sifa->refcount, 1);
3167		goto out;
3168	}
3169plan_d:
3170	/*
3171	 * plan_d: We are in trouble. No preferred address on the emit
3172	 * interface. And not even a preferred address on all interfaces. Go
3173	 * out and see if we can find an acceptable address somewhere
3174	 * amongst all interfaces.
3175	 */
3176	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan D looked_at is %p\n", (void *)looked_at);
3177	LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
3178		if (dest_is_loop == 0 && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
3179			/* wrong base scope */
3180			continue;
3181		}
3182		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
3183#ifdef INET
3184			if ((sctp_ifa->address.sa.sa_family == AF_INET) &&
3185			    (prison_check_ip4(inp->ip_inp.inp.inp_cred,
3186			    &sctp_ifa->address.sin.sin_addr) != 0)) {
3187				continue;
3188			}
3189#endif
3190#ifdef INET6
3191			if ((sctp_ifa->address.sa.sa_family == AF_INET6) &&
3192			    (prison_check_ip6(inp->ip_inp.inp.inp_cred,
3193			    &sctp_ifa->address.sin6.sin6_addr) != 0)) {
3194				continue;
3195			}
3196#endif
3197			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
3198			    (non_asoc_addr_ok == 0))
3199				continue;
3200			sifa = sctp_is_ifa_addr_acceptable(sctp_ifa,
3201			    dest_is_loop,
3202			    dest_is_priv, fam);
3203			if (sifa == NULL)
3204				continue;
3205			if (stcb) {
3206				if (sctp_is_address_in_scope(sifa, &stcb->asoc.scope, 0) == 0) {
3207					sifa = NULL;
3208					continue;
3209				}
3210				if (((non_asoc_addr_ok == 0) &&
3211				    (sctp_is_addr_restricted(stcb, sifa))) ||
3212				    (non_asoc_addr_ok &&
3213				    (sctp_is_addr_restricted(stcb, sifa)) &&
3214				    (!sctp_is_addr_pending(stcb, sifa)))) {
3215					/*
3216					 * It is restricted for some
3217					 * reason.. probably not yet added.
3218					 */
3219					sifa = NULL;
3220					continue;
3221				}
3222			}
3223			goto out;
3224		}
3225	}
3226#ifdef INET
3227	if ((retried == 0) && (stcb->asoc.scope.ipv4_local_scope == 0)) {
3228		stcb->asoc.scope.ipv4_local_scope = 1;
3229		retried = 1;
3230		goto again_with_private_addresses_allowed;
3231	} else if (retried == 1) {
3232		stcb->asoc.scope.ipv4_local_scope = 0;
3233	}
3234#endif
3235out:
3236#ifdef INET
3237	if (sifa) {
3238		if (retried == 1) {
3239			LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
3240				if (dest_is_loop == 0 && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
3241					/* wrong base scope */
3242					continue;
3243				}
3244				LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
3245					struct sctp_ifa *tmp_sifa;
3246
3247#ifdef INET
3248					if ((sctp_ifa->address.sa.sa_family == AF_INET) &&
3249					    (prison_check_ip4(inp->ip_inp.inp.inp_cred,
3250					    &sctp_ifa->address.sin.sin_addr) != 0)) {
3251						continue;
3252					}
3253#endif
3254#ifdef INET6
3255					if ((sctp_ifa->address.sa.sa_family == AF_INET6) &&
3256					    (prison_check_ip6(inp->ip_inp.inp.inp_cred,
3257					    &sctp_ifa->address.sin6.sin6_addr) != 0)) {
3258						continue;
3259					}
3260#endif
3261					if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
3262					    (non_asoc_addr_ok == 0))
3263						continue;
3264					tmp_sifa = sctp_is_ifa_addr_acceptable(sctp_ifa,
3265					    dest_is_loop,
3266					    dest_is_priv, fam);
3267					if (tmp_sifa == NULL) {
3268						continue;
3269					}
3270					if (tmp_sifa == sifa) {
3271						continue;
3272					}
3273					if (stcb) {
3274						if (sctp_is_address_in_scope(tmp_sifa,
3275						    &stcb->asoc.scope, 0) == 0) {
3276							continue;
3277						}
3278						if (((non_asoc_addr_ok == 0) &&
3279						    (sctp_is_addr_restricted(stcb, tmp_sifa))) ||
3280						    (non_asoc_addr_ok &&
3281						    (sctp_is_addr_restricted(stcb, tmp_sifa)) &&
3282						    (!sctp_is_addr_pending(stcb, tmp_sifa)))) {
3283							/*
3284							 * It is restricted
3285							 * for some reason..
3286							 * probably not yet
3287							 * added.
3288							 */
3289							continue;
3290						}
3291					}
3292					if ((tmp_sifa->address.sin.sin_family == AF_INET) &&
3293					    (IN4_ISPRIVATE_ADDRESS(&(tmp_sifa->address.sin.sin_addr)))) {
3294						sctp_add_local_addr_restricted(stcb, tmp_sifa);
3295					}
3296				}
3297			}
3298		}
3299		atomic_add_int(&sifa->refcount, 1);
3300	}
3301#endif
3302	return (sifa);
3303}
3304
3305
3306
3307/* tcb may be NULL */
3308struct sctp_ifa *
3309sctp_source_address_selection(struct sctp_inpcb *inp,
3310    struct sctp_tcb *stcb,
3311    sctp_route_t * ro,
3312    struct sctp_nets *net,
3313    int non_asoc_addr_ok, uint32_t vrf_id)
3314{
3315	struct sctp_ifa *answer;
3316	uint8_t dest_is_priv, dest_is_loop;
3317	sa_family_t fam;
3318
3319#ifdef INET
3320	struct sockaddr_in *to = (struct sockaddr_in *)&ro->ro_dst;
3321
3322#endif
3323#ifdef INET6
3324	struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&ro->ro_dst;
3325
3326#endif
3327
3328	/**
3329	 * Rules: - Find the route if needed, cache if I can. - Look at
3330	 * interface address in route, Is it in the bound list. If so we
3331	 * have the best source. - If not we must rotate amongst the
3332	 * addresses.
3333	 *
3334	 * Cavets and issues
3335	 *
3336	 * Do we need to pay attention to scope. We can have a private address
3337	 * or a global address we are sourcing or sending to. So if we draw
3338	 * it out
3339	 * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
3340	 * For V4
3341	 * ------------------------------------------
3342	 *      source     *      dest  *  result
3343	 * -----------------------------------------
3344	 * <a>  Private    *    Global  *  NAT
3345	 * -----------------------------------------
3346	 * <b>  Private    *    Private *  No problem
3347	 * -----------------------------------------
3348	 * <c>  Global     *    Private *  Huh, How will this work?
3349	 * -----------------------------------------
3350	 * <d>  Global     *    Global  *  No Problem
3351	 *------------------------------------------
3352	 * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
3353	 * For V6
3354	 *------------------------------------------
3355	 *      source     *      dest  *  result
3356	 * -----------------------------------------
3357	 * <a>  Linklocal  *    Global  *
3358	 * -----------------------------------------
3359	 * <b>  Linklocal  * Linklocal  *  No problem
3360	 * -----------------------------------------
3361	 * <c>  Global     * Linklocal  *  Huh, How will this work?
3362	 * -----------------------------------------
3363	 * <d>  Global     *    Global  *  No Problem
3364	 *------------------------------------------
3365	 * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
3366	 *
3367	 * And then we add to that what happens if there are multiple addresses
3368	 * assigned to an interface. Remember the ifa on a ifn is a linked
3369	 * list of addresses. So one interface can have more than one IP
3370	 * address. What happens if we have both a private and a global
3371	 * address? Do we then use context of destination to sort out which
3372	 * one is best? And what about NAT's sending P->G may get you a NAT
3373	 * translation, or should you select the G thats on the interface in
3374	 * preference.
3375	 *
3376	 * Decisions:
3377	 *
3378	 * - count the number of addresses on the interface.
3379	 * - if it is one, no problem except case <c>.
3380	 *   For <a> we will assume a NAT out there.
3381	 * - if there are more than one, then we need to worry about scope P
3382	 *   or G. We should prefer G -> G and P -> P if possible.
3383	 *   Then as a secondary fall back to mixed types G->P being a last
3384	 *   ditch one.
3385	 * - The above all works for bound all, but bound specific we need to
3386	 *   use the same concept but instead only consider the bound
3387	 *   addresses. If the bound set is NOT assigned to the interface then
3388	 *   we must use rotation amongst the bound addresses..
3389	 */
3390	if (ro->ro_rt == NULL) {
3391		/*
3392		 * Need a route to cache.
3393		 */
3394		SCTP_RTALLOC(ro, vrf_id);
3395	}
3396	if (ro->ro_rt == NULL) {
3397		return (NULL);
3398	}
3399	fam = ro->ro_dst.sa_family;
3400	dest_is_priv = dest_is_loop = 0;
3401	/* Setup our scopes for the destination */
3402	switch (fam) {
3403#ifdef INET
3404	case AF_INET:
3405		/* Scope based on outbound address */
3406		if (IN4_ISLOOPBACK_ADDRESS(&to->sin_addr)) {
3407			dest_is_loop = 1;
3408			if (net != NULL) {
3409				/* mark it as local */
3410				net->addr_is_local = 1;
3411			}
3412		} else if ((IN4_ISPRIVATE_ADDRESS(&to->sin_addr))) {
3413			dest_is_priv = 1;
3414		}
3415		break;
3416#endif
3417#ifdef INET6
3418	case AF_INET6:
3419		/* Scope based on outbound address */
3420		if (IN6_IS_ADDR_LOOPBACK(&to6->sin6_addr) ||
3421		    SCTP_ROUTE_IS_REAL_LOOP(ro)) {
3422			/*
3423			 * If the address is a loopback address, which
3424			 * consists of "::1" OR "fe80::1%lo0", we are
3425			 * loopback scope. But we don't use dest_is_priv
3426			 * (link local addresses).
3427			 */
3428			dest_is_loop = 1;
3429			if (net != NULL) {
3430				/* mark it as local */
3431				net->addr_is_local = 1;
3432			}
3433		} else if (IN6_IS_ADDR_LINKLOCAL(&to6->sin6_addr)) {
3434			dest_is_priv = 1;
3435		}
3436		break;
3437#endif
3438	}
3439	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Select source addr for:");
3440	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)&ro->ro_dst);
3441	SCTP_IPI_ADDR_RLOCK();
3442	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3443		/*
3444		 * Bound all case
3445		 */
3446		answer = sctp_choose_boundall(inp, stcb, net, ro, vrf_id,
3447		    dest_is_priv, dest_is_loop,
3448		    non_asoc_addr_ok, fam);
3449		SCTP_IPI_ADDR_RUNLOCK();
3450		return (answer);
3451	}
3452	/*
3453	 * Subset bound case
3454	 */
3455	if (stcb) {
3456		answer = sctp_choose_boundspecific_stcb(inp, stcb, ro,
3457		    vrf_id, dest_is_priv,
3458		    dest_is_loop,
3459		    non_asoc_addr_ok, fam);
3460	} else {
3461		answer = sctp_choose_boundspecific_inp(inp, ro, vrf_id,
3462		    non_asoc_addr_ok,
3463		    dest_is_priv,
3464		    dest_is_loop, fam);
3465	}
3466	SCTP_IPI_ADDR_RUNLOCK();
3467	return (answer);
3468}
3469
3470static int
3471sctp_find_cmsg(int c_type, void *data, struct mbuf *control, size_t cpsize)
3472{
3473	struct cmsghdr cmh;
3474	int tlen, at, found;
3475	struct sctp_sndinfo sndinfo;
3476	struct sctp_prinfo prinfo;
3477	struct sctp_authinfo authinfo;
3478
3479	tlen = SCTP_BUF_LEN(control);
3480	at = 0;
3481	found = 0;
3482	/*
3483	 * Independent of how many mbufs, find the c_type inside the control
3484	 * structure and copy out the data.
3485	 */
3486	while (at < tlen) {
3487		if ((tlen - at) < (int)CMSG_ALIGN(sizeof(cmh))) {
3488			/* There is not enough room for one more. */
3489			return (found);
3490		}
3491		m_copydata(control, at, sizeof(cmh), (caddr_t)&cmh);
3492		if (cmh.cmsg_len < CMSG_ALIGN(sizeof(cmh))) {
3493			/* We dont't have a complete CMSG header. */
3494			return (found);
3495		}
3496		if (((int)cmh.cmsg_len + at) > tlen) {
3497			/* We don't have the complete CMSG. */
3498			return (found);
3499		}
3500		if ((cmh.cmsg_level == IPPROTO_SCTP) &&
3501		    ((c_type == cmh.cmsg_type) ||
3502		    ((c_type == SCTP_SNDRCV) &&
3503		    ((cmh.cmsg_type == SCTP_SNDINFO) ||
3504		    (cmh.cmsg_type == SCTP_PRINFO) ||
3505		    (cmh.cmsg_type == SCTP_AUTHINFO))))) {
3506			if (c_type == cmh.cmsg_type) {
3507				if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < cpsize) {
3508					return (found);
3509				}
3510				/* It is exactly what we want. Copy it out. */
3511				m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), cpsize, (caddr_t)data);
3512				return (1);
3513			} else {
3514				struct sctp_sndrcvinfo *sndrcvinfo;
3515
3516				sndrcvinfo = (struct sctp_sndrcvinfo *)data;
3517				if (found == 0) {
3518					if (cpsize < sizeof(struct sctp_sndrcvinfo)) {
3519						return (found);
3520					}
3521					memset(sndrcvinfo, 0, sizeof(struct sctp_sndrcvinfo));
3522				}
3523				switch (cmh.cmsg_type) {
3524				case SCTP_SNDINFO:
3525					if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct sctp_sndinfo)) {
3526						return (found);
3527					}
3528					m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct sctp_sndinfo), (caddr_t)&sndinfo);
3529					sndrcvinfo->sinfo_stream = sndinfo.snd_sid;
3530					sndrcvinfo->sinfo_flags = sndinfo.snd_flags;
3531					sndrcvinfo->sinfo_ppid = sndinfo.snd_ppid;
3532					sndrcvinfo->sinfo_context = sndinfo.snd_context;
3533					sndrcvinfo->sinfo_assoc_id = sndinfo.snd_assoc_id;
3534					break;
3535				case SCTP_PRINFO:
3536					if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct sctp_prinfo)) {
3537						return (found);
3538					}
3539					m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct sctp_prinfo), (caddr_t)&prinfo);
3540					if (prinfo.pr_policy != SCTP_PR_SCTP_NONE) {
3541						sndrcvinfo->sinfo_timetolive = prinfo.pr_value;
3542					} else {
3543						sndrcvinfo->sinfo_timetolive = 0;
3544					}
3545					sndrcvinfo->sinfo_flags |= prinfo.pr_policy;
3546					break;
3547				case SCTP_AUTHINFO:
3548					if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct sctp_authinfo)) {
3549						return (found);
3550					}
3551					m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct sctp_authinfo), (caddr_t)&authinfo);
3552					sndrcvinfo->sinfo_keynumber_valid = 1;
3553					sndrcvinfo->sinfo_keynumber = authinfo.auth_keynumber;
3554					break;
3555				default:
3556					return (found);
3557				}
3558				found = 1;
3559			}
3560		}
3561		at += CMSG_ALIGN(cmh.cmsg_len);
3562	}
3563	return (found);
3564}
3565
3566static int
3567sctp_process_cmsgs_for_init(struct sctp_tcb *stcb, struct mbuf *control, int *error)
3568{
3569	struct cmsghdr cmh;
3570	int tlen, at;
3571	struct sctp_initmsg initmsg;
3572
3573#ifdef INET
3574	struct sockaddr_in sin;
3575
3576#endif
3577#ifdef INET6
3578	struct sockaddr_in6 sin6;
3579
3580#endif
3581
3582	tlen = SCTP_BUF_LEN(control);
3583	at = 0;
3584	while (at < tlen) {
3585		if ((tlen - at) < (int)CMSG_ALIGN(sizeof(cmh))) {
3586			/* There is not enough room for one more. */
3587			*error = EINVAL;
3588			return (1);
3589		}
3590		m_copydata(control, at, sizeof(cmh), (caddr_t)&cmh);
3591		if (cmh.cmsg_len < CMSG_ALIGN(sizeof(cmh))) {
3592			/* We dont't have a complete CMSG header. */
3593			*error = EINVAL;
3594			return (1);
3595		}
3596		if (((int)cmh.cmsg_len + at) > tlen) {
3597			/* We don't have the complete CMSG. */
3598			*error = EINVAL;
3599			return (1);
3600		}
3601		if (cmh.cmsg_level == IPPROTO_SCTP) {
3602			switch (cmh.cmsg_type) {
3603			case SCTP_INIT:
3604				if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct sctp_initmsg)) {
3605					*error = EINVAL;
3606					return (1);
3607				}
3608				m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct sctp_initmsg), (caddr_t)&initmsg);
3609				if (initmsg.sinit_max_attempts)
3610					stcb->asoc.max_init_times = initmsg.sinit_max_attempts;
3611				if (initmsg.sinit_num_ostreams)
3612					stcb->asoc.pre_open_streams = initmsg.sinit_num_ostreams;
3613				if (initmsg.sinit_max_instreams)
3614					stcb->asoc.max_inbound_streams = initmsg.sinit_max_instreams;
3615				if (initmsg.sinit_max_init_timeo)
3616					stcb->asoc.initial_init_rto_max = initmsg.sinit_max_init_timeo;
3617				if (stcb->asoc.streamoutcnt < stcb->asoc.pre_open_streams) {
3618					struct sctp_stream_out *tmp_str;
3619					unsigned int i;
3620
3621#if defined(SCTP_DETAILED_STR_STATS)
3622					int j;
3623
3624#endif
3625
3626					/* Default is NOT correct */
3627					SCTPDBG(SCTP_DEBUG_OUTPUT1, "Ok, default:%d pre_open:%d\n",
3628					    stcb->asoc.streamoutcnt, stcb->asoc.pre_open_streams);
3629					SCTP_TCB_UNLOCK(stcb);
3630					SCTP_MALLOC(tmp_str,
3631					    struct sctp_stream_out *,
3632					    (stcb->asoc.pre_open_streams * sizeof(struct sctp_stream_out)),
3633					    SCTP_M_STRMO);
3634					SCTP_TCB_LOCK(stcb);
3635					if (tmp_str != NULL) {
3636						SCTP_FREE(stcb->asoc.strmout, SCTP_M_STRMO);
3637						stcb->asoc.strmout = tmp_str;
3638						stcb->asoc.strm_realoutsize = stcb->asoc.streamoutcnt = stcb->asoc.pre_open_streams;
3639					} else {
3640						stcb->asoc.pre_open_streams = stcb->asoc.streamoutcnt;
3641					}
3642					for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
3643						TAILQ_INIT(&stcb->asoc.strmout[i].outqueue);
3644						stcb->asoc.strmout[i].chunks_on_queues = 0;
3645						stcb->asoc.strmout[i].next_sequence_send = 0;
3646#if defined(SCTP_DETAILED_STR_STATS)
3647						for (j = 0; j < SCTP_PR_SCTP_MAX + 1; j++) {
3648							stcb->asoc.strmout[i].abandoned_sent[j] = 0;
3649							stcb->asoc.strmout[i].abandoned_unsent[j] = 0;
3650						}
3651#else
3652						stcb->asoc.strmout[i].abandoned_sent[0] = 0;
3653						stcb->asoc.strmout[i].abandoned_unsent[0] = 0;
3654#endif
3655						stcb->asoc.strmout[i].stream_no = i;
3656						stcb->asoc.strmout[i].last_msg_incomplete = 0;
3657						stcb->asoc.ss_functions.sctp_ss_init_stream(&stcb->asoc.strmout[i], NULL);
3658					}
3659				}
3660				break;
3661#ifdef INET
3662			case SCTP_DSTADDRV4:
3663				if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct in_addr)) {
3664					*error = EINVAL;
3665					return (1);
3666				}
3667				memset(&sin, 0, sizeof(struct sockaddr_in));
3668				sin.sin_family = AF_INET;
3669				sin.sin_len = sizeof(struct sockaddr_in);
3670				sin.sin_port = stcb->rport;
3671				m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct in_addr), (caddr_t)&sin.sin_addr);
3672				if ((sin.sin_addr.s_addr == INADDR_ANY) ||
3673				    (sin.sin_addr.s_addr == INADDR_BROADCAST) ||
3674				    IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
3675					*error = EINVAL;
3676					return (1);
3677				}
3678				if (sctp_add_remote_addr(stcb, (struct sockaddr *)&sin, NULL,
3679				    SCTP_DONOT_SETSCOPE, SCTP_ADDR_IS_CONFIRMED)) {
3680					*error = ENOBUFS;
3681					return (1);
3682				}
3683				break;
3684#endif
3685#ifdef INET6
3686			case SCTP_DSTADDRV6:
3687				if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct in6_addr)) {
3688					*error = EINVAL;
3689					return (1);
3690				}
3691				memset(&sin6, 0, sizeof(struct sockaddr_in6));
3692				sin6.sin6_family = AF_INET6;
3693				sin6.sin6_len = sizeof(struct sockaddr_in6);
3694				sin6.sin6_port = stcb->rport;
3695				m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct in6_addr), (caddr_t)&sin6.sin6_addr);
3696				if (IN6_IS_ADDR_UNSPECIFIED(&sin6.sin6_addr) ||
3697				    IN6_IS_ADDR_MULTICAST(&sin6.sin6_addr)) {
3698					*error = EINVAL;
3699					return (1);
3700				}
3701#ifdef INET
3702				if (IN6_IS_ADDR_V4MAPPED(&sin6.sin6_addr)) {
3703					in6_sin6_2_sin(&sin, &sin6);
3704					if ((sin.sin_addr.s_addr == INADDR_ANY) ||
3705					    (sin.sin_addr.s_addr == INADDR_BROADCAST) ||
3706					    IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
3707						*error = EINVAL;
3708						return (1);
3709					}
3710					if (sctp_add_remote_addr(stcb, (struct sockaddr *)&sin, NULL,
3711					    SCTP_DONOT_SETSCOPE, SCTP_ADDR_IS_CONFIRMED)) {
3712						*error = ENOBUFS;
3713						return (1);
3714					}
3715				} else
3716#endif
3717					if (sctp_add_remote_addr(stcb, (struct sockaddr *)&sin6, NULL,
3718				    SCTP_DONOT_SETSCOPE, SCTP_ADDR_IS_CONFIRMED)) {
3719					*error = ENOBUFS;
3720					return (1);
3721				}
3722				break;
3723#endif
3724			default:
3725				break;
3726			}
3727		}
3728		at += CMSG_ALIGN(cmh.cmsg_len);
3729	}
3730	return (0);
3731}
3732
3733static struct sctp_tcb *
3734sctp_findassociation_cmsgs(struct sctp_inpcb **inp_p,
3735    uint16_t port,
3736    struct mbuf *control,
3737    struct sctp_nets **net_p,
3738    int *error)
3739{
3740	struct cmsghdr cmh;
3741	int tlen, at;
3742	struct sctp_tcb *stcb;
3743	struct sockaddr *addr;
3744
3745#ifdef INET
3746	struct sockaddr_in sin;
3747
3748#endif
3749#ifdef INET6
3750	struct sockaddr_in6 sin6;
3751
3752#endif
3753
3754	tlen = SCTP_BUF_LEN(control);
3755	at = 0;
3756	while (at < tlen) {
3757		if ((tlen - at) < (int)CMSG_ALIGN(sizeof(cmh))) {
3758			/* There is not enough room for one more. */
3759			*error = EINVAL;
3760			return (NULL);
3761		}
3762		m_copydata(control, at, sizeof(cmh), (caddr_t)&cmh);
3763		if (cmh.cmsg_len < CMSG_ALIGN(sizeof(cmh))) {
3764			/* We dont't have a complete CMSG header. */
3765			*error = EINVAL;
3766			return (NULL);
3767		}
3768		if (((int)cmh.cmsg_len + at) > tlen) {
3769			/* We don't have the complete CMSG. */
3770			*error = EINVAL;
3771			return (NULL);
3772		}
3773		if (cmh.cmsg_level == IPPROTO_SCTP) {
3774			switch (cmh.cmsg_type) {
3775#ifdef INET
3776			case SCTP_DSTADDRV4:
3777				if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct in_addr)) {
3778					*error = EINVAL;
3779					return (NULL);
3780				}
3781				memset(&sin, 0, sizeof(struct sockaddr_in));
3782				sin.sin_family = AF_INET;
3783				sin.sin_len = sizeof(struct sockaddr_in);
3784				sin.sin_port = port;
3785				m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct in_addr), (caddr_t)&sin.sin_addr);
3786				addr = (struct sockaddr *)&sin;
3787				break;
3788#endif
3789#ifdef INET6
3790			case SCTP_DSTADDRV6:
3791				if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct in6_addr)) {
3792					*error = EINVAL;
3793					return (NULL);
3794				}
3795				memset(&sin6, 0, sizeof(struct sockaddr_in6));
3796				sin6.sin6_family = AF_INET6;
3797				sin6.sin6_len = sizeof(struct sockaddr_in6);
3798				sin6.sin6_port = port;
3799				m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct in6_addr), (caddr_t)&sin6.sin6_addr);
3800#ifdef INET
3801				if (IN6_IS_ADDR_V4MAPPED(&sin6.sin6_addr)) {
3802					in6_sin6_2_sin(&sin, &sin6);
3803					addr = (struct sockaddr *)&sin;
3804				} else
3805#endif
3806					addr = (struct sockaddr *)&sin6;
3807				break;
3808#endif
3809			default:
3810				addr = NULL;
3811				break;
3812			}
3813			if (addr) {
3814				stcb = sctp_findassociation_ep_addr(inp_p, addr, net_p, NULL, NULL);
3815				if (stcb != NULL) {
3816					return (stcb);
3817				}
3818			}
3819		}
3820		at += CMSG_ALIGN(cmh.cmsg_len);
3821	}
3822	return (NULL);
3823}
3824
3825static struct mbuf *
3826sctp_add_cookie(struct mbuf *init, int init_offset,
3827    struct mbuf *initack, int initack_offset, struct sctp_state_cookie *stc_in, uint8_t ** signature)
3828{
3829	struct mbuf *copy_init, *copy_initack, *m_at, *sig, *mret;
3830	struct sctp_state_cookie *stc;
3831	struct sctp_paramhdr *ph;
3832	uint8_t *foo;
3833	int sig_offset;
3834	uint16_t cookie_sz;
3835
3836	mret = sctp_get_mbuf_for_msg((sizeof(struct sctp_state_cookie) +
3837	    sizeof(struct sctp_paramhdr)), 0,
3838	    M_NOWAIT, 1, MT_DATA);
3839	if (mret == NULL) {
3840		return (NULL);
3841	}
3842	copy_init = SCTP_M_COPYM(init, init_offset, M_COPYALL, M_NOWAIT);
3843	if (copy_init == NULL) {
3844		sctp_m_freem(mret);
3845		return (NULL);
3846	}
3847#ifdef SCTP_MBUF_LOGGING
3848	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
3849		struct mbuf *mat;
3850
3851		for (mat = copy_init; mat; mat = SCTP_BUF_NEXT(mat)) {
3852			if (SCTP_BUF_IS_EXTENDED(mat)) {
3853				sctp_log_mb(mat, SCTP_MBUF_ICOPY);
3854			}
3855		}
3856	}
3857#endif
3858	copy_initack = SCTP_M_COPYM(initack, initack_offset, M_COPYALL,
3859	    M_NOWAIT);
3860	if (copy_initack == NULL) {
3861		sctp_m_freem(mret);
3862		sctp_m_freem(copy_init);
3863		return (NULL);
3864	}
3865#ifdef SCTP_MBUF_LOGGING
3866	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
3867		struct mbuf *mat;
3868
3869		for (mat = copy_initack; mat; mat = SCTP_BUF_NEXT(mat)) {
3870			if (SCTP_BUF_IS_EXTENDED(mat)) {
3871				sctp_log_mb(mat, SCTP_MBUF_ICOPY);
3872			}
3873		}
3874	}
3875#endif
3876	/* easy side we just drop it on the end */
3877	ph = mtod(mret, struct sctp_paramhdr *);
3878	SCTP_BUF_LEN(mret) = sizeof(struct sctp_state_cookie) +
3879	    sizeof(struct sctp_paramhdr);
3880	stc = (struct sctp_state_cookie *)((caddr_t)ph +
3881	    sizeof(struct sctp_paramhdr));
3882	ph->param_type = htons(SCTP_STATE_COOKIE);
3883	ph->param_length = 0;	/* fill in at the end */
3884	/* Fill in the stc cookie data */
3885	memcpy(stc, stc_in, sizeof(struct sctp_state_cookie));
3886
3887	/* tack the INIT and then the INIT-ACK onto the chain */
3888	cookie_sz = 0;
3889	for (m_at = mret; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3890		cookie_sz += SCTP_BUF_LEN(m_at);
3891		if (SCTP_BUF_NEXT(m_at) == NULL) {
3892			SCTP_BUF_NEXT(m_at) = copy_init;
3893			break;
3894		}
3895	}
3896	for (m_at = copy_init; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3897		cookie_sz += SCTP_BUF_LEN(m_at);
3898		if (SCTP_BUF_NEXT(m_at) == NULL) {
3899			SCTP_BUF_NEXT(m_at) = copy_initack;
3900			break;
3901		}
3902	}
3903	for (m_at = copy_initack; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3904		cookie_sz += SCTP_BUF_LEN(m_at);
3905		if (SCTP_BUF_NEXT(m_at) == NULL) {
3906			break;
3907		}
3908	}
3909	sig = sctp_get_mbuf_for_msg(SCTP_SECRET_SIZE, 0, M_NOWAIT, 1, MT_DATA);
3910	if (sig == NULL) {
3911		/* no space, so free the entire chain */
3912		sctp_m_freem(mret);
3913		return (NULL);
3914	}
3915	SCTP_BUF_LEN(sig) = 0;
3916	SCTP_BUF_NEXT(m_at) = sig;
3917	sig_offset = 0;
3918	foo = (uint8_t *) (mtod(sig, caddr_t)+sig_offset);
3919	memset(foo, 0, SCTP_SIGNATURE_SIZE);
3920	*signature = foo;
3921	SCTP_BUF_LEN(sig) += SCTP_SIGNATURE_SIZE;
3922	cookie_sz += SCTP_SIGNATURE_SIZE;
3923	ph->param_length = htons(cookie_sz);
3924	return (mret);
3925}
3926
3927
3928static uint8_t
3929sctp_get_ect(struct sctp_tcb *stcb)
3930{
3931	if ((stcb != NULL) && (stcb->asoc.ecn_supported == 1)) {
3932		return (SCTP_ECT0_BIT);
3933	} else {
3934		return (0);
3935	}
3936}
3937
3938#if defined(INET) || defined(INET6)
3939static void
3940sctp_handle_no_route(struct sctp_tcb *stcb,
3941    struct sctp_nets *net,
3942    int so_locked)
3943{
3944	SCTPDBG(SCTP_DEBUG_OUTPUT1, "dropped packet - no valid source addr\n");
3945
3946	if (net) {
3947		SCTPDBG(SCTP_DEBUG_OUTPUT1, "Destination was ");
3948		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT1, &net->ro._l_addr.sa);
3949		if (net->dest_state & SCTP_ADDR_CONFIRMED) {
3950			if ((net->dest_state & SCTP_ADDR_REACHABLE) && stcb) {
3951				SCTPDBG(SCTP_DEBUG_OUTPUT1, "no route takes interface %p down\n", (void *)net);
3952				sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_DOWN,
3953				    stcb, 0,
3954				    (void *)net,
3955				    so_locked);
3956				net->dest_state &= ~SCTP_ADDR_REACHABLE;
3957				net->dest_state &= ~SCTP_ADDR_PF;
3958			}
3959		}
3960		if (stcb) {
3961			if (net == stcb->asoc.primary_destination) {
3962				/* need a new primary */
3963				struct sctp_nets *alt;
3964
3965				alt = sctp_find_alternate_net(stcb, net, 0);
3966				if (alt != net) {
3967					if (stcb->asoc.alternate) {
3968						sctp_free_remote_addr(stcb->asoc.alternate);
3969					}
3970					stcb->asoc.alternate = alt;
3971					atomic_add_int(&stcb->asoc.alternate->ref_count, 1);
3972					if (net->ro._s_addr) {
3973						sctp_free_ifa(net->ro._s_addr);
3974						net->ro._s_addr = NULL;
3975					}
3976					net->src_addr_selected = 0;
3977				}
3978			}
3979		}
3980	}
3981}
3982
3983#endif
3984
3985static int
3986sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
3987    struct sctp_tcb *stcb,	/* may be NULL */
3988    struct sctp_nets *net,
3989    struct sockaddr *to,
3990    struct mbuf *m,
3991    uint32_t auth_offset,
3992    struct sctp_auth_chunk *auth,
3993    uint16_t auth_keyid,
3994    int nofragment_flag,
3995    int ecn_ok,
3996    int out_of_asoc_ok,
3997    uint16_t src_port,
3998    uint16_t dest_port,
3999    uint32_t v_tag,
4000    uint16_t port,
4001    union sctp_sockstore *over_addr,
4002    uint8_t mflowtype, uint32_t mflowid,
4003#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
4004    int so_locked SCTP_UNUSED
4005#else
4006    int so_locked
4007#endif
4008)
4009/* nofragment_flag to tell if IP_DF should be set (IPv4 only) */
4010{
4011	/**
4012	 * Given a mbuf chain (via SCTP_BUF_NEXT()) that holds a packet header
4013	 * WITH an SCTPHDR but no IP header, endpoint inp and sa structure:
4014	 * - fill in the HMAC digest of any AUTH chunk in the packet.
4015	 * - calculate and fill in the SCTP checksum.
4016	 * - prepend an IP address header.
4017	 * - if boundall use INADDR_ANY.
4018	 * - if boundspecific do source address selection.
4019	 * - set fragmentation option for ipV4.
4020	 * - On return from IP output, check/adjust mtu size of output
4021	 *   interface and smallest_mtu size as well.
4022	 */
4023	/* Will need ifdefs around this */
4024	struct mbuf *newm;
4025	struct sctphdr *sctphdr;
4026	int packet_length;
4027	int ret;
4028
4029#if defined(INET) || defined(INET6)
4030	uint32_t vrf_id;
4031
4032#endif
4033#if defined(INET) || defined(INET6)
4034	struct mbuf *o_pak;
4035	sctp_route_t *ro = NULL;
4036	struct udphdr *udp = NULL;
4037
4038#endif
4039	uint8_t tos_value;
4040
4041#if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4042	struct socket *so = NULL;
4043
4044#endif
4045
4046	if ((net) && (net->dest_state & SCTP_ADDR_OUT_OF_SCOPE)) {
4047		SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EFAULT);
4048		sctp_m_freem(m);
4049		return (EFAULT);
4050	}
4051#if defined(INET) || defined(INET6)
4052	if (stcb) {
4053		vrf_id = stcb->asoc.vrf_id;
4054	} else {
4055		vrf_id = inp->def_vrf_id;
4056	}
4057#endif
4058	/* fill in the HMAC digest for any AUTH chunk in the packet */
4059	if ((auth != NULL) && (stcb != NULL)) {
4060		sctp_fill_hmac_digest_m(m, auth_offset, auth, stcb, auth_keyid);
4061	}
4062	if (net) {
4063		tos_value = net->dscp;
4064	} else if (stcb) {
4065		tos_value = stcb->asoc.default_dscp;
4066	} else {
4067		tos_value = inp->sctp_ep.default_dscp;
4068	}
4069
4070	switch (to->sa_family) {
4071#ifdef INET
4072	case AF_INET:
4073		{
4074			struct ip *ip = NULL;
4075			sctp_route_t iproute;
4076			int len;
4077
4078			len = sizeof(struct ip) + sizeof(struct sctphdr);
4079			if (port) {
4080				len += sizeof(struct udphdr);
4081			}
4082			newm = sctp_get_mbuf_for_msg(len, 1, M_NOWAIT, 1, MT_DATA);
4083			if (newm == NULL) {
4084				sctp_m_freem(m);
4085				SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
4086				return (ENOMEM);
4087			}
4088			SCTP_ALIGN_TO_END(newm, len);
4089			SCTP_BUF_LEN(newm) = len;
4090			SCTP_BUF_NEXT(newm) = m;
4091			m = newm;
4092			if (net != NULL) {
4093				m->m_pkthdr.flowid = net->flowid;
4094				M_HASHTYPE_SET(m, net->flowtype);
4095			} else {
4096				m->m_pkthdr.flowid = mflowid;
4097				M_HASHTYPE_SET(m, mflowtype);
4098			}
4099			packet_length = sctp_calculate_len(m);
4100			ip = mtod(m, struct ip *);
4101			ip->ip_v = IPVERSION;
4102			ip->ip_hl = (sizeof(struct ip) >> 2);
4103			if (tos_value == 0) {
4104				/*
4105				 * This means especially, that it is not set
4106				 * at the SCTP layer. So use the value from
4107				 * the IP layer.
4108				 */
4109				tos_value = inp->ip_inp.inp.inp_ip_tos;
4110			}
4111			tos_value &= 0xfc;
4112			if (ecn_ok) {
4113				tos_value |= sctp_get_ect(stcb);
4114			}
4115			if ((nofragment_flag) && (port == 0)) {
4116				ip->ip_off = htons(IP_DF);
4117			} else {
4118				ip->ip_off = htons(0);
4119			}
4120			/* FreeBSD has a function for ip_id's */
4121			ip->ip_id = ip_newid();
4122
4123			ip->ip_ttl = inp->ip_inp.inp.inp_ip_ttl;
4124			ip->ip_len = htons(packet_length);
4125			ip->ip_tos = tos_value;
4126			if (port) {
4127				ip->ip_p = IPPROTO_UDP;
4128			} else {
4129				ip->ip_p = IPPROTO_SCTP;
4130			}
4131			ip->ip_sum = 0;
4132			if (net == NULL) {
4133				ro = &iproute;
4134				memset(&iproute, 0, sizeof(iproute));
4135				memcpy(&ro->ro_dst, to, to->sa_len);
4136			} else {
4137				ro = (sctp_route_t *) & net->ro;
4138			}
4139			/* Now the address selection part */
4140			ip->ip_dst.s_addr = ((struct sockaddr_in *)to)->sin_addr.s_addr;
4141
4142			/* call the routine to select the src address */
4143			if (net && out_of_asoc_ok == 0) {
4144				if (net->ro._s_addr && (net->ro._s_addr->localifa_flags & (SCTP_BEING_DELETED | SCTP_ADDR_IFA_UNUSEABLE))) {
4145					sctp_free_ifa(net->ro._s_addr);
4146					net->ro._s_addr = NULL;
4147					net->src_addr_selected = 0;
4148					if (ro->ro_rt) {
4149						RTFREE(ro->ro_rt);
4150						ro->ro_rt = NULL;
4151					}
4152				}
4153				if (net->src_addr_selected == 0) {
4154					/* Cache the source address */
4155					net->ro._s_addr = sctp_source_address_selection(inp, stcb,
4156					    ro, net, 0,
4157					    vrf_id);
4158					net->src_addr_selected = 1;
4159				}
4160				if (net->ro._s_addr == NULL) {
4161					/* No route to host */
4162					net->src_addr_selected = 0;
4163					sctp_handle_no_route(stcb, net, so_locked);
4164					SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4165					sctp_m_freem(m);
4166					return (EHOSTUNREACH);
4167				}
4168				ip->ip_src = net->ro._s_addr->address.sin.sin_addr;
4169			} else {
4170				if (over_addr == NULL) {
4171					struct sctp_ifa *_lsrc;
4172
4173					_lsrc = sctp_source_address_selection(inp, stcb, ro,
4174					    net,
4175					    out_of_asoc_ok,
4176					    vrf_id);
4177					if (_lsrc == NULL) {
4178						sctp_handle_no_route(stcb, net, so_locked);
4179						SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4180						sctp_m_freem(m);
4181						return (EHOSTUNREACH);
4182					}
4183					ip->ip_src = _lsrc->address.sin.sin_addr;
4184					sctp_free_ifa(_lsrc);
4185				} else {
4186					ip->ip_src = over_addr->sin.sin_addr;
4187					SCTP_RTALLOC(ro, vrf_id);
4188				}
4189			}
4190			if (port) {
4191				if (htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port)) == 0) {
4192					sctp_handle_no_route(stcb, net, so_locked);
4193					SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4194					sctp_m_freem(m);
4195					return (EHOSTUNREACH);
4196				}
4197				udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
4198				udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
4199				udp->uh_dport = port;
4200				udp->uh_ulen = htons(packet_length - sizeof(struct ip));
4201				if (V_udp_cksum) {
4202					udp->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, udp->uh_ulen + htons(IPPROTO_UDP));
4203				} else {
4204					udp->uh_sum = 0;
4205				}
4206				sctphdr = (struct sctphdr *)((caddr_t)udp + sizeof(struct udphdr));
4207			} else {
4208				sctphdr = (struct sctphdr *)((caddr_t)ip + sizeof(struct ip));
4209			}
4210
4211			sctphdr->src_port = src_port;
4212			sctphdr->dest_port = dest_port;
4213			sctphdr->v_tag = v_tag;
4214			sctphdr->checksum = 0;
4215
4216			/*
4217			 * If source address selection fails and we find no
4218			 * route then the ip_output should fail as well with
4219			 * a NO_ROUTE_TO_HOST type error. We probably should
4220			 * catch that somewhere and abort the association
4221			 * right away (assuming this is an INIT being sent).
4222			 */
4223			if (ro->ro_rt == NULL) {
4224				/*
4225				 * src addr selection failed to find a route
4226				 * (or valid source addr), so we can't get
4227				 * there from here (yet)!
4228				 */
4229				sctp_handle_no_route(stcb, net, so_locked);
4230				SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4231				sctp_m_freem(m);
4232				return (EHOSTUNREACH);
4233			}
4234			if (ro != &iproute) {
4235				memcpy(&iproute, ro, sizeof(*ro));
4236			}
4237			SCTPDBG(SCTP_DEBUG_OUTPUT3, "Calling ipv4 output routine from low level src addr:%x\n",
4238			    (uint32_t) (ntohl(ip->ip_src.s_addr)));
4239			SCTPDBG(SCTP_DEBUG_OUTPUT3, "Destination is %x\n",
4240			    (uint32_t) (ntohl(ip->ip_dst.s_addr)));
4241			SCTPDBG(SCTP_DEBUG_OUTPUT3, "RTP route is %p through\n",
4242			    (void *)ro->ro_rt);
4243
4244			if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
4245				/* failed to prepend data, give up */
4246				SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
4247				sctp_m_freem(m);
4248				return (ENOMEM);
4249			}
4250			SCTP_ATTACH_CHAIN(o_pak, m, packet_length);
4251			if (port) {
4252#if defined(SCTP_WITH_NO_CSUM)
4253				SCTP_STAT_INCR(sctps_sendnocrc);
4254#else
4255				sctphdr->checksum = sctp_calculate_cksum(m, sizeof(struct ip) + sizeof(struct udphdr));
4256				SCTP_STAT_INCR(sctps_sendswcrc);
4257#endif
4258				if (V_udp_cksum) {
4259					SCTP_ENABLE_UDP_CSUM(o_pak);
4260				}
4261			} else {
4262#if defined(SCTP_WITH_NO_CSUM)
4263				SCTP_STAT_INCR(sctps_sendnocrc);
4264#else
4265				m->m_pkthdr.csum_flags = CSUM_SCTP;
4266				m->m_pkthdr.csum_data = offsetof(struct sctphdr, checksum);
4267				SCTP_STAT_INCR(sctps_sendhwcrc);
4268#endif
4269			}
4270#ifdef SCTP_PACKET_LOGGING
4271			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
4272				sctp_packet_log(o_pak);
4273#endif
4274			/* send it out.  table id is taken from stcb */
4275#if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4276			if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
4277				so = SCTP_INP_SO(inp);
4278				SCTP_SOCKET_UNLOCK(so, 0);
4279			}
4280#endif
4281			SCTP_IP_OUTPUT(ret, o_pak, ro, stcb, vrf_id);
4282#if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4283			if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
4284				atomic_add_int(&stcb->asoc.refcnt, 1);
4285				SCTP_TCB_UNLOCK(stcb);
4286				SCTP_SOCKET_LOCK(so, 0);
4287				SCTP_TCB_LOCK(stcb);
4288				atomic_subtract_int(&stcb->asoc.refcnt, 1);
4289			}
4290#endif
4291			SCTP_STAT_INCR(sctps_sendpackets);
4292			SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
4293			if (ret)
4294				SCTP_STAT_INCR(sctps_senderrors);
4295
4296			SCTPDBG(SCTP_DEBUG_OUTPUT3, "IP output returns %d\n", ret);
4297			if (net == NULL) {
4298				/* free tempy routes */
4299				RO_RTFREE(ro);
4300			} else {
4301				/*
4302				 * PMTU check versus smallest asoc MTU goes
4303				 * here
4304				 */
4305				if ((ro->ro_rt != NULL) &&
4306				    (net->ro._s_addr)) {
4307					uint32_t mtu;
4308
4309					mtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, ro->ro_rt);
4310					if (net->port) {
4311						mtu -= sizeof(struct udphdr);
4312					}
4313					if (mtu && (stcb->asoc.smallest_mtu > mtu)) {
4314						sctp_mtu_size_reset(inp, &stcb->asoc, mtu);
4315						net->mtu = mtu;
4316					}
4317				} else if (ro->ro_rt == NULL) {
4318					/* route was freed */
4319					if (net->ro._s_addr &&
4320					    net->src_addr_selected) {
4321						sctp_free_ifa(net->ro._s_addr);
4322						net->ro._s_addr = NULL;
4323					}
4324					net->src_addr_selected = 0;
4325				}
4326			}
4327			return (ret);
4328		}
4329#endif
4330#ifdef INET6
4331	case AF_INET6:
4332		{
4333			uint32_t flowlabel, flowinfo;
4334			struct ip6_hdr *ip6h;
4335			struct route_in6 ip6route;
4336			struct ifnet *ifp;
4337			struct sockaddr_in6 *sin6, tmp, *lsa6, lsa6_tmp;
4338			int prev_scope = 0;
4339			struct sockaddr_in6 lsa6_storage;
4340			int error;
4341			u_short prev_port = 0;
4342			int len;
4343
4344			if (net) {
4345				flowlabel = net->flowlabel;
4346			} else if (stcb) {
4347				flowlabel = stcb->asoc.default_flowlabel;
4348			} else {
4349				flowlabel = inp->sctp_ep.default_flowlabel;
4350			}
4351			if (flowlabel == 0) {
4352				/*
4353				 * This means especially, that it is not set
4354				 * at the SCTP layer. So use the value from
4355				 * the IP layer.
4356				 */
4357				flowlabel = ntohl(((struct in6pcb *)inp)->in6p_flowinfo);
4358			}
4359			flowlabel &= 0x000fffff;
4360			len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr);
4361			if (port) {
4362				len += sizeof(struct udphdr);
4363			}
4364			newm = sctp_get_mbuf_for_msg(len, 1, M_NOWAIT, 1, MT_DATA);
4365			if (newm == NULL) {
4366				sctp_m_freem(m);
4367				SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
4368				return (ENOMEM);
4369			}
4370			SCTP_ALIGN_TO_END(newm, len);
4371			SCTP_BUF_LEN(newm) = len;
4372			SCTP_BUF_NEXT(newm) = m;
4373			m = newm;
4374			if (net != NULL) {
4375				m->m_pkthdr.flowid = net->flowid;
4376				M_HASHTYPE_SET(m, net->flowtype);
4377			} else {
4378				m->m_pkthdr.flowid = mflowid;
4379				M_HASHTYPE_SET(m, mflowtype);
4380			}
4381			packet_length = sctp_calculate_len(m);
4382
4383			ip6h = mtod(m, struct ip6_hdr *);
4384			/* protect *sin6 from overwrite */
4385			sin6 = (struct sockaddr_in6 *)to;
4386			tmp = *sin6;
4387			sin6 = &tmp;
4388
4389			/* KAME hack: embed scopeid */
4390			if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
4391				SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
4392				return (EINVAL);
4393			}
4394			if (net == NULL) {
4395				memset(&ip6route, 0, sizeof(ip6route));
4396				ro = (sctp_route_t *) & ip6route;
4397				memcpy(&ro->ro_dst, sin6, sin6->sin6_len);
4398			} else {
4399				ro = (sctp_route_t *) & net->ro;
4400			}
4401			/*
4402			 * We assume here that inp_flow is in host byte
4403			 * order within the TCB!
4404			 */
4405			if (tos_value == 0) {
4406				/*
4407				 * This means especially, that it is not set
4408				 * at the SCTP layer. So use the value from
4409				 * the IP layer.
4410				 */
4411				tos_value = (ntohl(((struct in6pcb *)inp)->in6p_flowinfo) >> 20) & 0xff;
4412			}
4413			tos_value &= 0xfc;
4414			if (ecn_ok) {
4415				tos_value |= sctp_get_ect(stcb);
4416			}
4417			flowinfo = 0x06;
4418			flowinfo <<= 8;
4419			flowinfo |= tos_value;
4420			flowinfo <<= 20;
4421			flowinfo |= flowlabel;
4422			ip6h->ip6_flow = htonl(flowinfo);
4423			if (port) {
4424				ip6h->ip6_nxt = IPPROTO_UDP;
4425			} else {
4426				ip6h->ip6_nxt = IPPROTO_SCTP;
4427			}
4428			ip6h->ip6_plen = (packet_length - sizeof(struct ip6_hdr));
4429			ip6h->ip6_dst = sin6->sin6_addr;
4430
4431			/*
4432			 * Add SRC address selection here: we can only reuse
4433			 * to a limited degree the kame src-addr-sel, since
4434			 * we can try their selection but it may not be
4435			 * bound.
4436			 */
4437			bzero(&lsa6_tmp, sizeof(lsa6_tmp));
4438			lsa6_tmp.sin6_family = AF_INET6;
4439			lsa6_tmp.sin6_len = sizeof(lsa6_tmp);
4440			lsa6 = &lsa6_tmp;
4441			if (net && out_of_asoc_ok == 0) {
4442				if (net->ro._s_addr && (net->ro._s_addr->localifa_flags & (SCTP_BEING_DELETED | SCTP_ADDR_IFA_UNUSEABLE))) {
4443					sctp_free_ifa(net->ro._s_addr);
4444					net->ro._s_addr = NULL;
4445					net->src_addr_selected = 0;
4446					if (ro->ro_rt) {
4447						RTFREE(ro->ro_rt);
4448						ro->ro_rt = NULL;
4449					}
4450				}
4451				if (net->src_addr_selected == 0) {
4452					sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
4453					/* KAME hack: embed scopeid */
4454					if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
4455						SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
4456						return (EINVAL);
4457					}
4458					/* Cache the source address */
4459					net->ro._s_addr = sctp_source_address_selection(inp,
4460					    stcb,
4461					    ro,
4462					    net,
4463					    0,
4464					    vrf_id);
4465					(void)sa6_recoverscope(sin6);
4466					net->src_addr_selected = 1;
4467				}
4468				if (net->ro._s_addr == NULL) {
4469					SCTPDBG(SCTP_DEBUG_OUTPUT3, "V6:No route to host\n");
4470					net->src_addr_selected = 0;
4471					sctp_handle_no_route(stcb, net, so_locked);
4472					SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4473					sctp_m_freem(m);
4474					return (EHOSTUNREACH);
4475				}
4476				lsa6->sin6_addr = net->ro._s_addr->address.sin6.sin6_addr;
4477			} else {
4478				sin6 = (struct sockaddr_in6 *)&ro->ro_dst;
4479				/* KAME hack: embed scopeid */
4480				if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
4481					SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
4482					return (EINVAL);
4483				}
4484				if (over_addr == NULL) {
4485					struct sctp_ifa *_lsrc;
4486
4487					_lsrc = sctp_source_address_selection(inp, stcb, ro,
4488					    net,
4489					    out_of_asoc_ok,
4490					    vrf_id);
4491					if (_lsrc == NULL) {
4492						sctp_handle_no_route(stcb, net, so_locked);
4493						SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4494						sctp_m_freem(m);
4495						return (EHOSTUNREACH);
4496					}
4497					lsa6->sin6_addr = _lsrc->address.sin6.sin6_addr;
4498					sctp_free_ifa(_lsrc);
4499				} else {
4500					lsa6->sin6_addr = over_addr->sin6.sin6_addr;
4501					SCTP_RTALLOC(ro, vrf_id);
4502				}
4503				(void)sa6_recoverscope(sin6);
4504			}
4505			lsa6->sin6_port = inp->sctp_lport;
4506
4507			if (ro->ro_rt == NULL) {
4508				/*
4509				 * src addr selection failed to find a route
4510				 * (or valid source addr), so we can't get
4511				 * there from here!
4512				 */
4513				sctp_handle_no_route(stcb, net, so_locked);
4514				SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4515				sctp_m_freem(m);
4516				return (EHOSTUNREACH);
4517			}
4518			/*
4519			 * XXX: sa6 may not have a valid sin6_scope_id in
4520			 * the non-SCOPEDROUTING case.
4521			 */
4522			bzero(&lsa6_storage, sizeof(lsa6_storage));
4523			lsa6_storage.sin6_family = AF_INET6;
4524			lsa6_storage.sin6_len = sizeof(lsa6_storage);
4525			lsa6_storage.sin6_addr = lsa6->sin6_addr;
4526			if ((error = sa6_recoverscope(&lsa6_storage)) != 0) {
4527				SCTPDBG(SCTP_DEBUG_OUTPUT3, "recover scope fails error %d\n", error);
4528				sctp_m_freem(m);
4529				return (error);
4530			}
4531			/* XXX */
4532			lsa6_storage.sin6_addr = lsa6->sin6_addr;
4533			lsa6_storage.sin6_port = inp->sctp_lport;
4534			lsa6 = &lsa6_storage;
4535			ip6h->ip6_src = lsa6->sin6_addr;
4536
4537			if (port) {
4538				if (htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port)) == 0) {
4539					sctp_handle_no_route(stcb, net, so_locked);
4540					SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4541					sctp_m_freem(m);
4542					return (EHOSTUNREACH);
4543				}
4544				udp = (struct udphdr *)((caddr_t)ip6h + sizeof(struct ip6_hdr));
4545				udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
4546				udp->uh_dport = port;
4547				udp->uh_ulen = htons(packet_length - sizeof(struct ip6_hdr));
4548				udp->uh_sum = 0;
4549				sctphdr = (struct sctphdr *)((caddr_t)udp + sizeof(struct udphdr));
4550			} else {
4551				sctphdr = (struct sctphdr *)((caddr_t)ip6h + sizeof(struct ip6_hdr));
4552			}
4553
4554			sctphdr->src_port = src_port;
4555			sctphdr->dest_port = dest_port;
4556			sctphdr->v_tag = v_tag;
4557			sctphdr->checksum = 0;
4558
4559			/*
4560			 * We set the hop limit now since there is a good
4561			 * chance that our ro pointer is now filled
4562			 */
4563			ip6h->ip6_hlim = SCTP_GET_HLIM(inp, ro);
4564			ifp = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
4565
4566#ifdef SCTP_DEBUG
4567			/* Copy to be sure something bad is not happening */
4568			sin6->sin6_addr = ip6h->ip6_dst;
4569			lsa6->sin6_addr = ip6h->ip6_src;
4570#endif
4571
4572			SCTPDBG(SCTP_DEBUG_OUTPUT3, "Calling ipv6 output routine from low level\n");
4573			SCTPDBG(SCTP_DEBUG_OUTPUT3, "src: ");
4574			SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT3, (struct sockaddr *)lsa6);
4575			SCTPDBG(SCTP_DEBUG_OUTPUT3, "dst: ");
4576			SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT3, (struct sockaddr *)sin6);
4577			if (net) {
4578				sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
4579				/*
4580				 * preserve the port and scope for link
4581				 * local send
4582				 */
4583				prev_scope = sin6->sin6_scope_id;
4584				prev_port = sin6->sin6_port;
4585			}
4586			if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
4587				/* failed to prepend data, give up */
4588				sctp_m_freem(m);
4589				SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
4590				return (ENOMEM);
4591			}
4592			SCTP_ATTACH_CHAIN(o_pak, m, packet_length);
4593			if (port) {
4594#if defined(SCTP_WITH_NO_CSUM)
4595				SCTP_STAT_INCR(sctps_sendnocrc);
4596#else
4597				sctphdr->checksum = sctp_calculate_cksum(m, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
4598				SCTP_STAT_INCR(sctps_sendswcrc);
4599#endif
4600				if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), packet_length - sizeof(struct ip6_hdr))) == 0) {
4601					udp->uh_sum = 0xffff;
4602				}
4603			} else {
4604#if defined(SCTP_WITH_NO_CSUM)
4605				SCTP_STAT_INCR(sctps_sendnocrc);
4606#else
4607				m->m_pkthdr.csum_flags = CSUM_SCTP_IPV6;
4608				m->m_pkthdr.csum_data = offsetof(struct sctphdr, checksum);
4609				SCTP_STAT_INCR(sctps_sendhwcrc);
4610#endif
4611			}
4612			/* send it out. table id is taken from stcb */
4613#if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4614			if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
4615				so = SCTP_INP_SO(inp);
4616				SCTP_SOCKET_UNLOCK(so, 0);
4617			}
4618#endif
4619#ifdef SCTP_PACKET_LOGGING
4620			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
4621				sctp_packet_log(o_pak);
4622#endif
4623			SCTP_IP6_OUTPUT(ret, o_pak, (struct route_in6 *)ro, &ifp, stcb, vrf_id);
4624#if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4625			if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
4626				atomic_add_int(&stcb->asoc.refcnt, 1);
4627				SCTP_TCB_UNLOCK(stcb);
4628				SCTP_SOCKET_LOCK(so, 0);
4629				SCTP_TCB_LOCK(stcb);
4630				atomic_subtract_int(&stcb->asoc.refcnt, 1);
4631			}
4632#endif
4633			if (net) {
4634				/* for link local this must be done */
4635				sin6->sin6_scope_id = prev_scope;
4636				sin6->sin6_port = prev_port;
4637			}
4638			SCTPDBG(SCTP_DEBUG_OUTPUT3, "return from send is %d\n", ret);
4639			SCTP_STAT_INCR(sctps_sendpackets);
4640			SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
4641			if (ret) {
4642				SCTP_STAT_INCR(sctps_senderrors);
4643			}
4644			if (net == NULL) {
4645				/* Now if we had a temp route free it */
4646				RO_RTFREE(ro);
4647			} else {
4648				/*
4649				 * PMTU check versus smallest asoc MTU goes
4650				 * here
4651				 */
4652				if (ro->ro_rt == NULL) {
4653					/* Route was freed */
4654					if (net->ro._s_addr &&
4655					    net->src_addr_selected) {
4656						sctp_free_ifa(net->ro._s_addr);
4657						net->ro._s_addr = NULL;
4658					}
4659					net->src_addr_selected = 0;
4660				}
4661				if ((ro->ro_rt != NULL) &&
4662				    (net->ro._s_addr)) {
4663					uint32_t mtu;
4664
4665					mtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, ro->ro_rt);
4666					if (mtu &&
4667					    (stcb->asoc.smallest_mtu > mtu)) {
4668						sctp_mtu_size_reset(inp, &stcb->asoc, mtu);
4669						net->mtu = mtu;
4670						if (net->port) {
4671							net->mtu -= sizeof(struct udphdr);
4672						}
4673					}
4674				} else if (ifp) {
4675					if (ND_IFINFO(ifp)->linkmtu &&
4676					    (stcb->asoc.smallest_mtu > ND_IFINFO(ifp)->linkmtu)) {
4677						sctp_mtu_size_reset(inp,
4678						    &stcb->asoc,
4679						    ND_IFINFO(ifp)->linkmtu);
4680					}
4681				}
4682			}
4683			return (ret);
4684		}
4685#endif
4686	default:
4687		SCTPDBG(SCTP_DEBUG_OUTPUT1, "Unknown protocol (TSNH) type %d\n",
4688		    ((struct sockaddr *)to)->sa_family);
4689		sctp_m_freem(m);
4690		SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EFAULT);
4691		return (EFAULT);
4692	}
4693}
4694
4695
4696void
4697sctp_send_initiate(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int so_locked
4698#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
4699    SCTP_UNUSED
4700#endif
4701)
4702{
4703	struct mbuf *m, *m_last;
4704	struct sctp_nets *net;
4705	struct sctp_init_chunk *init;
4706	struct sctp_supported_addr_param *sup_addr;
4707	struct sctp_adaptation_layer_indication *ali;
4708	struct sctp_supported_chunk_types_param *pr_supported;
4709	struct sctp_paramhdr *ph;
4710	int cnt_inits_to = 0;
4711	int ret;
4712	uint16_t num_ext, chunk_len, padding_len, parameter_len;
4713
4714	/* INIT's always go to the primary (and usually ONLY address) */
4715	net = stcb->asoc.primary_destination;
4716	if (net == NULL) {
4717		net = TAILQ_FIRST(&stcb->asoc.nets);
4718		if (net == NULL) {
4719			/* TSNH */
4720			return;
4721		}
4722		/* we confirm any address we send an INIT to */
4723		net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
4724		(void)sctp_set_primary_addr(stcb, NULL, net);
4725	} else {
4726		/* we confirm any address we send an INIT to */
4727		net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
4728	}
4729	SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT\n");
4730#ifdef INET6
4731	if (net->ro._l_addr.sa.sa_family == AF_INET6) {
4732		/*
4733		 * special hook, if we are sending to link local it will not
4734		 * show up in our private address count.
4735		 */
4736		if (IN6_IS_ADDR_LINKLOCAL(&net->ro._l_addr.sin6.sin6_addr))
4737			cnt_inits_to = 1;
4738	}
4739#endif
4740	if (SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
4741		/* This case should not happen */
4742		SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT - failed timer?\n");
4743		return;
4744	}
4745	/* start the INIT timer */
4746	sctp_timer_start(SCTP_TIMER_TYPE_INIT, inp, stcb, net);
4747
4748	m = sctp_get_mbuf_for_msg(MCLBYTES, 1, M_NOWAIT, 1, MT_DATA);
4749	if (m == NULL) {
4750		/* No memory, INIT timer will re-attempt. */
4751		SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT - mbuf?\n");
4752		return;
4753	}
4754	chunk_len = (uint16_t) sizeof(struct sctp_init_chunk);
4755	padding_len = 0;
4756	/* Now lets put the chunk header in place */
4757	init = mtod(m, struct sctp_init_chunk *);
4758	/* now the chunk header */
4759	init->ch.chunk_type = SCTP_INITIATION;
4760	init->ch.chunk_flags = 0;
4761	/* fill in later from mbuf we build */
4762	init->ch.chunk_length = 0;
4763	/* place in my tag */
4764	init->init.initiate_tag = htonl(stcb->asoc.my_vtag);
4765	/* set up some of the credits. */
4766	init->init.a_rwnd = htonl(max(inp->sctp_socket ? SCTP_SB_LIMIT_RCV(inp->sctp_socket) : 0,
4767	    SCTP_MINIMAL_RWND));
4768	init->init.num_outbound_streams = htons(stcb->asoc.pre_open_streams);
4769	init->init.num_inbound_streams = htons(stcb->asoc.max_inbound_streams);
4770	init->init.initial_tsn = htonl(stcb->asoc.init_seq_number);
4771
4772	/* Adaptation layer indication parameter */
4773	if (inp->sctp_ep.adaptation_layer_indicator_provided) {
4774		parameter_len = (uint16_t) sizeof(struct sctp_adaptation_layer_indication);
4775		ali = (struct sctp_adaptation_layer_indication *)(mtod(m, caddr_t)+chunk_len);
4776		ali->ph.param_type = htons(SCTP_ULP_ADAPTATION);
4777		ali->ph.param_length = htons(parameter_len);
4778		ali->indication = htonl(inp->sctp_ep.adaptation_layer_indicator);
4779		chunk_len += parameter_len;
4780	}
4781	/* ECN parameter */
4782	if (stcb->asoc.ecn_supported == 1) {
4783		parameter_len = (uint16_t) sizeof(struct sctp_paramhdr);
4784		ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+chunk_len);
4785		ph->param_type = htons(SCTP_ECN_CAPABLE);
4786		ph->param_length = htons(parameter_len);
4787		chunk_len += parameter_len;
4788	}
4789	/* PR-SCTP supported parameter */
4790	if (stcb->asoc.prsctp_supported == 1) {
4791		parameter_len = (uint16_t) sizeof(struct sctp_paramhdr);
4792		ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+chunk_len);
4793		ph->param_type = htons(SCTP_PRSCTP_SUPPORTED);
4794		ph->param_length = htons(parameter_len);
4795		chunk_len += parameter_len;
4796	}
4797	/* Add NAT friendly parameter. */
4798	if (SCTP_BASE_SYSCTL(sctp_inits_include_nat_friendly)) {
4799		parameter_len = (uint16_t) sizeof(struct sctp_paramhdr);
4800		ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+chunk_len);
4801		ph->param_type = htons(SCTP_HAS_NAT_SUPPORT);
4802		ph->param_length = htons(parameter_len);
4803		chunk_len += parameter_len;
4804	}
4805	/* And now tell the peer which extensions we support */
4806	num_ext = 0;
4807	pr_supported = (struct sctp_supported_chunk_types_param *)(mtod(m, caddr_t)+chunk_len);
4808	if (stcb->asoc.prsctp_supported == 1) {
4809		pr_supported->chunk_types[num_ext++] = SCTP_FORWARD_CUM_TSN;
4810	}
4811	if (stcb->asoc.auth_supported == 1) {
4812		pr_supported->chunk_types[num_ext++] = SCTP_AUTHENTICATION;
4813	}
4814	if (stcb->asoc.asconf_supported == 1) {
4815		pr_supported->chunk_types[num_ext++] = SCTP_ASCONF;
4816		pr_supported->chunk_types[num_ext++] = SCTP_ASCONF_ACK;
4817	}
4818	if (stcb->asoc.reconfig_supported == 1) {
4819		pr_supported->chunk_types[num_ext++] = SCTP_STREAM_RESET;
4820	}
4821	if (stcb->asoc.nrsack_supported == 1) {
4822		pr_supported->chunk_types[num_ext++] = SCTP_NR_SELECTIVE_ACK;
4823	}
4824	if (stcb->asoc.pktdrop_supported == 1) {
4825		pr_supported->chunk_types[num_ext++] = SCTP_PACKET_DROPPED;
4826	}
4827	if (num_ext > 0) {
4828		parameter_len = (uint16_t) sizeof(struct sctp_supported_chunk_types_param) + num_ext;
4829		pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
4830		pr_supported->ph.param_length = htons(parameter_len);
4831		padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
4832		chunk_len += parameter_len;
4833	}
4834	/* add authentication parameters */
4835	if (stcb->asoc.auth_supported) {
4836		/* attach RANDOM parameter, if available */
4837		if (stcb->asoc.authinfo.random != NULL) {
4838			struct sctp_auth_random *randp;
4839
4840			if (padding_len > 0) {
4841				memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4842				chunk_len += padding_len;
4843				padding_len = 0;
4844			}
4845			randp = (struct sctp_auth_random *)(mtod(m, caddr_t)+chunk_len);
4846			parameter_len = (uint16_t) sizeof(struct sctp_auth_random) + stcb->asoc.authinfo.random_len;
4847			/* random key already contains the header */
4848			memcpy(randp, stcb->asoc.authinfo.random->key, parameter_len);
4849			padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
4850			chunk_len += parameter_len;
4851		}
4852		/* add HMAC_ALGO parameter */
4853		if (stcb->asoc.local_hmacs != NULL) {
4854			struct sctp_auth_hmac_algo *hmacs;
4855
4856			if (padding_len > 0) {
4857				memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4858				chunk_len += padding_len;
4859				padding_len = 0;
4860			}
4861			hmacs = (struct sctp_auth_hmac_algo *)(mtod(m, caddr_t)+chunk_len);
4862			parameter_len = (uint16_t) (sizeof(struct sctp_auth_hmac_algo) +
4863			    stcb->asoc.local_hmacs->num_algo * sizeof(uint16_t));
4864			hmacs->ph.param_type = htons(SCTP_HMAC_LIST);
4865			hmacs->ph.param_length = htons(parameter_len);
4866			sctp_serialize_hmaclist(stcb->asoc.local_hmacs, (uint8_t *) hmacs->hmac_ids);
4867			padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
4868			chunk_len += parameter_len;
4869		}
4870		/* add CHUNKS parameter */
4871		if (stcb->asoc.local_auth_chunks != NULL) {
4872			struct sctp_auth_chunk_list *chunks;
4873
4874			if (padding_len > 0) {
4875				memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4876				chunk_len += padding_len;
4877				padding_len = 0;
4878			}
4879			chunks = (struct sctp_auth_chunk_list *)(mtod(m, caddr_t)+chunk_len);
4880			parameter_len = (uint16_t) (sizeof(struct sctp_auth_chunk_list) +
4881			    sctp_auth_get_chklist_size(stcb->asoc.local_auth_chunks));
4882			chunks->ph.param_type = htons(SCTP_CHUNK_LIST);
4883			chunks->ph.param_length = htons(parameter_len);
4884			sctp_serialize_auth_chunks(stcb->asoc.local_auth_chunks, chunks->chunk_types);
4885			padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
4886			chunk_len += parameter_len;
4887		}
4888	}
4889	/* now any cookie time extensions */
4890	if (stcb->asoc.cookie_preserve_req) {
4891		struct sctp_cookie_perserve_param *cookie_preserve;
4892
4893		if (padding_len > 0) {
4894			memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4895			chunk_len += padding_len;
4896			padding_len = 0;
4897		}
4898		parameter_len = (uint16_t) sizeof(struct sctp_cookie_perserve_param);
4899		cookie_preserve = (struct sctp_cookie_perserve_param *)(mtod(m, caddr_t)+chunk_len);
4900		cookie_preserve->ph.param_type = htons(SCTP_COOKIE_PRESERVE);
4901		cookie_preserve->ph.param_length = htons(parameter_len);
4902		cookie_preserve->time = htonl(stcb->asoc.cookie_preserve_req);
4903		stcb->asoc.cookie_preserve_req = 0;
4904		chunk_len += parameter_len;
4905	}
4906	if (stcb->asoc.scope.ipv4_addr_legal || stcb->asoc.scope.ipv6_addr_legal) {
4907		uint8_t i;
4908
4909		if (padding_len > 0) {
4910			memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4911			chunk_len += padding_len;
4912			padding_len = 0;
4913		}
4914		parameter_len = (uint16_t) sizeof(struct sctp_paramhdr);
4915		if (stcb->asoc.scope.ipv4_addr_legal) {
4916			parameter_len += (uint16_t) sizeof(uint16_t);
4917		}
4918		if (stcb->asoc.scope.ipv6_addr_legal) {
4919			parameter_len += (uint16_t) sizeof(uint16_t);
4920		}
4921		sup_addr = (struct sctp_supported_addr_param *)(mtod(m, caddr_t)+chunk_len);
4922		sup_addr->ph.param_type = htons(SCTP_SUPPORTED_ADDRTYPE);
4923		sup_addr->ph.param_length = htons(parameter_len);
4924		i = 0;
4925		if (stcb->asoc.scope.ipv4_addr_legal) {
4926			sup_addr->addr_type[i++] = htons(SCTP_IPV4_ADDRESS);
4927		}
4928		if (stcb->asoc.scope.ipv6_addr_legal) {
4929			sup_addr->addr_type[i++] = htons(SCTP_IPV6_ADDRESS);
4930		}
4931		padding_len = 4 - 2 * i;
4932		chunk_len += parameter_len;
4933	}
4934	SCTP_BUF_LEN(m) = chunk_len;
4935	/* now the addresses */
4936	/*
4937	 * To optimize this we could put the scoping stuff into a structure
4938	 * and remove the individual uint8's from the assoc structure. Then
4939	 * we could just sifa in the address within the stcb. But for now
4940	 * this is a quick hack to get the address stuff teased apart.
4941	 */
4942	m_last = sctp_add_addresses_to_i_ia(inp, stcb, &stcb->asoc.scope,
4943	    m, cnt_inits_to,
4944	    &padding_len, &chunk_len);
4945
4946	init->ch.chunk_length = htons(chunk_len);
4947	if (padding_len > 0) {
4948		if (sctp_add_pad_tombuf(m_last, padding_len) == NULL) {
4949			sctp_m_freem(m);
4950			return;
4951		}
4952	}
4953	SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT - calls lowlevel_output\n");
4954	ret = sctp_lowlevel_chunk_output(inp, stcb, net,
4955	    (struct sockaddr *)&net->ro._l_addr,
4956	    m, 0, NULL, 0, 0, 0, 0,
4957	    inp->sctp_lport, stcb->rport, htonl(0),
4958	    net->port, NULL,
4959	    0, 0,
4960	    so_locked);
4961	SCTPDBG(SCTP_DEBUG_OUTPUT4, "lowlevel_output - %d\n", ret);
4962	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
4963	(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
4964}
4965
4966struct mbuf *
4967sctp_arethere_unrecognized_parameters(struct mbuf *in_initpkt,
4968    int param_offset, int *abort_processing, struct sctp_chunkhdr *cp, int *nat_friendly)
4969{
4970	/*
4971	 * Given a mbuf containing an INIT or INIT-ACK with the param_offset
4972	 * being equal to the beginning of the params i.e. (iphlen +
4973	 * sizeof(struct sctp_init_msg) parse through the parameters to the
4974	 * end of the mbuf verifying that all parameters are known.
4975	 *
4976	 * For unknown parameters build and return a mbuf with
4977	 * UNRECOGNIZED_PARAMETER errors. If the flags indicate to stop
4978	 * processing this chunk stop, and set *abort_processing to 1.
4979	 *
4980	 * By having param_offset be pre-set to where parameters begin it is
4981	 * hoped that this routine may be reused in the future by new
4982	 * features.
4983	 */
4984	struct sctp_paramhdr *phdr, params;
4985
4986	struct mbuf *mat, *op_err;
4987	char tempbuf[SCTP_PARAM_BUFFER_SIZE];
4988	int at, limit, pad_needed;
4989	uint16_t ptype, plen, padded_size;
4990	int err_at;
4991
4992	*abort_processing = 0;
4993	mat = in_initpkt;
4994	err_at = 0;
4995	limit = ntohs(cp->chunk_length) - sizeof(struct sctp_init_chunk);
4996	at = param_offset;
4997	op_err = NULL;
4998	SCTPDBG(SCTP_DEBUG_OUTPUT1, "Check for unrecognized param's\n");
4999	phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
5000	while ((phdr != NULL) && ((size_t)limit >= sizeof(struct sctp_paramhdr))) {
5001		ptype = ntohs(phdr->param_type);
5002		plen = ntohs(phdr->param_length);
5003		if ((plen > limit) || (plen < sizeof(struct sctp_paramhdr))) {
5004			/* wacked parameter */
5005			SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error %d\n", plen);
5006			goto invalid_size;
5007		}
5008		limit -= SCTP_SIZE32(plen);
5009		/*-
5010		 * All parameters for all chunks that we know/understand are
5011		 * listed here. We process them other places and make
5012		 * appropriate stop actions per the upper bits. However this
5013		 * is the generic routine processor's can call to get back
5014		 * an operr.. to either incorporate (init-ack) or send.
5015		 */
5016		padded_size = SCTP_SIZE32(plen);
5017		switch (ptype) {
5018			/* Param's with variable size */
5019		case SCTP_HEARTBEAT_INFO:
5020		case SCTP_STATE_COOKIE:
5021		case SCTP_UNRECOG_PARAM:
5022		case SCTP_ERROR_CAUSE_IND:
5023			/* ok skip fwd */
5024			at += padded_size;
5025			break;
5026			/* Param's with variable size within a range */
5027		case SCTP_CHUNK_LIST:
5028		case SCTP_SUPPORTED_CHUNK_EXT:
5029			if (padded_size > (sizeof(struct sctp_supported_chunk_types_param) + (sizeof(uint8_t) * SCTP_MAX_SUPPORTED_EXT))) {
5030				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error chklist %d\n", plen);
5031				goto invalid_size;
5032			}
5033			at += padded_size;
5034			break;
5035		case SCTP_SUPPORTED_ADDRTYPE:
5036			if (padded_size > SCTP_MAX_ADDR_PARAMS_SIZE) {
5037				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error supaddrtype %d\n", plen);
5038				goto invalid_size;
5039			}
5040			at += padded_size;
5041			break;
5042		case SCTP_RANDOM:
5043			if (padded_size > (sizeof(struct sctp_auth_random) + SCTP_RANDOM_MAX_SIZE)) {
5044				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error random %d\n", plen);
5045				goto invalid_size;
5046			}
5047			at += padded_size;
5048			break;
5049		case SCTP_SET_PRIM_ADDR:
5050		case SCTP_DEL_IP_ADDRESS:
5051		case SCTP_ADD_IP_ADDRESS:
5052			if ((padded_size != sizeof(struct sctp_asconf_addrv4_param)) &&
5053			    (padded_size != sizeof(struct sctp_asconf_addr_param))) {
5054				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error setprim %d\n", plen);
5055				goto invalid_size;
5056			}
5057			at += padded_size;
5058			break;
5059			/* Param's with a fixed size */
5060		case SCTP_IPV4_ADDRESS:
5061			if (padded_size != sizeof(struct sctp_ipv4addr_param)) {
5062				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ipv4 addr %d\n", plen);
5063				goto invalid_size;
5064			}
5065			at += padded_size;
5066			break;
5067		case SCTP_IPV6_ADDRESS:
5068			if (padded_size != sizeof(struct sctp_ipv6addr_param)) {
5069				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ipv6 addr %d\n", plen);
5070				goto invalid_size;
5071			}
5072			at += padded_size;
5073			break;
5074		case SCTP_COOKIE_PRESERVE:
5075			if (padded_size != sizeof(struct sctp_cookie_perserve_param)) {
5076				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error cookie-preserve %d\n", plen);
5077				goto invalid_size;
5078			}
5079			at += padded_size;
5080			break;
5081		case SCTP_HAS_NAT_SUPPORT:
5082			*nat_friendly = 1;
5083			/* fall through */
5084		case SCTP_PRSCTP_SUPPORTED:
5085			if (padded_size != sizeof(struct sctp_paramhdr)) {
5086				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error prsctp/nat support %d\n", plen);
5087				goto invalid_size;
5088			}
5089			at += padded_size;
5090			break;
5091		case SCTP_ECN_CAPABLE:
5092			if (padded_size != sizeof(struct sctp_paramhdr)) {
5093				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ecn %d\n", plen);
5094				goto invalid_size;
5095			}
5096			at += padded_size;
5097			break;
5098		case SCTP_ULP_ADAPTATION:
5099			if (padded_size != sizeof(struct sctp_adaptation_layer_indication)) {
5100				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error adapatation %d\n", plen);
5101				goto invalid_size;
5102			}
5103			at += padded_size;
5104			break;
5105		case SCTP_SUCCESS_REPORT:
5106			if (padded_size != sizeof(struct sctp_asconf_paramhdr)) {
5107				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error success %d\n", plen);
5108				goto invalid_size;
5109			}
5110			at += padded_size;
5111			break;
5112		case SCTP_HOSTNAME_ADDRESS:
5113			{
5114				/* We can NOT handle HOST NAME addresses!! */
5115				int l_len;
5116
5117				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Can't handle hostname addresses.. abort processing\n");
5118				*abort_processing = 1;
5119				if (op_err == NULL) {
5120					/* Ok need to try to get a mbuf */
5121#ifdef INET6
5122					l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5123#else
5124					l_len = sizeof(struct ip) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5125#endif
5126					l_len += plen;
5127					l_len += sizeof(struct sctp_paramhdr);
5128					op_err = sctp_get_mbuf_for_msg(l_len, 0, M_NOWAIT, 1, MT_DATA);
5129					if (op_err) {
5130						SCTP_BUF_LEN(op_err) = 0;
5131						/*
5132						 * pre-reserve space for ip
5133						 * and sctp header  and
5134						 * chunk hdr
5135						 */
5136#ifdef INET6
5137						SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
5138#else
5139						SCTP_BUF_RESV_UF(op_err, sizeof(struct ip));
5140#endif
5141						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
5142						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
5143					}
5144				}
5145				if (op_err) {
5146					/* If we have space */
5147					struct sctp_paramhdr s;
5148
5149					if (err_at % 4) {
5150						uint32_t cpthis = 0;
5151
5152						pad_needed = 4 - (err_at % 4);
5153						m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
5154						err_at += pad_needed;
5155					}
5156					s.param_type = htons(SCTP_CAUSE_UNRESOLVABLE_ADDR);
5157					s.param_length = htons(sizeof(s) + plen);
5158					m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
5159					err_at += sizeof(s);
5160					phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, min(sizeof(tempbuf), plen));
5161					if (phdr == NULL) {
5162						sctp_m_freem(op_err);
5163						/*
5164						 * we are out of memory but
5165						 * we still need to have a
5166						 * look at what to do (the
5167						 * system is in trouble
5168						 * though).
5169						 */
5170						return (NULL);
5171					}
5172					m_copyback(op_err, err_at, plen, (caddr_t)phdr);
5173				}
5174				return (op_err);
5175				break;
5176			}
5177		default:
5178			/*
5179			 * we do not recognize the parameter figure out what
5180			 * we do.
5181			 */
5182			SCTPDBG(SCTP_DEBUG_OUTPUT1, "Hit default param %x\n", ptype);
5183			if ((ptype & 0x4000) == 0x4000) {
5184				/* Report bit is set?? */
5185				SCTPDBG(SCTP_DEBUG_OUTPUT1, "report op err\n");
5186				if (op_err == NULL) {
5187					int l_len;
5188
5189					/* Ok need to try to get an mbuf */
5190#ifdef INET6
5191					l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5192#else
5193					l_len = sizeof(struct ip) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5194#endif
5195					l_len += plen;
5196					l_len += sizeof(struct sctp_paramhdr);
5197					op_err = sctp_get_mbuf_for_msg(l_len, 0, M_NOWAIT, 1, MT_DATA);
5198					if (op_err) {
5199						SCTP_BUF_LEN(op_err) = 0;
5200#ifdef INET6
5201						SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
5202#else
5203						SCTP_BUF_RESV_UF(op_err, sizeof(struct ip));
5204#endif
5205						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
5206						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
5207					}
5208				}
5209				if (op_err) {
5210					/* If we have space */
5211					struct sctp_paramhdr s;
5212
5213					if (err_at % 4) {
5214						uint32_t cpthis = 0;
5215
5216						pad_needed = 4 - (err_at % 4);
5217						m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
5218						err_at += pad_needed;
5219					}
5220					s.param_type = htons(SCTP_UNRECOG_PARAM);
5221					s.param_length = htons(sizeof(s) + plen);
5222					m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
5223					err_at += sizeof(s);
5224					if (plen > sizeof(tempbuf)) {
5225						plen = sizeof(tempbuf);
5226					}
5227					phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, min(sizeof(tempbuf), plen));
5228					if (phdr == NULL) {
5229						sctp_m_freem(op_err);
5230						/*
5231						 * we are out of memory but
5232						 * we still need to have a
5233						 * look at what to do (the
5234						 * system is in trouble
5235						 * though).
5236						 */
5237						op_err = NULL;
5238						goto more_processing;
5239					}
5240					m_copyback(op_err, err_at, plen, (caddr_t)phdr);
5241					err_at += plen;
5242				}
5243			}
5244	more_processing:
5245			if ((ptype & 0x8000) == 0x0000) {
5246				SCTPDBG(SCTP_DEBUG_OUTPUT1, "stop proc\n");
5247				return (op_err);
5248			} else {
5249				/* skip this chunk and continue processing */
5250				SCTPDBG(SCTP_DEBUG_OUTPUT1, "move on\n");
5251				at += SCTP_SIZE32(plen);
5252			}
5253			break;
5254
5255		}
5256		phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
5257	}
5258	return (op_err);
5259invalid_size:
5260	SCTPDBG(SCTP_DEBUG_OUTPUT1, "abort flag set\n");
5261	*abort_processing = 1;
5262	if ((op_err == NULL) && phdr) {
5263		int l_len;
5264
5265#ifdef INET6
5266		l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5267#else
5268		l_len = sizeof(struct ip) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5269#endif
5270		l_len += (2 * sizeof(struct sctp_paramhdr));
5271		op_err = sctp_get_mbuf_for_msg(l_len, 0, M_NOWAIT, 1, MT_DATA);
5272		if (op_err) {
5273			SCTP_BUF_LEN(op_err) = 0;
5274#ifdef INET6
5275			SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
5276#else
5277			SCTP_BUF_RESV_UF(op_err, sizeof(struct ip));
5278#endif
5279			SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
5280			SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
5281		}
5282	}
5283	if ((op_err) && phdr) {
5284		struct sctp_paramhdr s;
5285
5286		if (err_at % 4) {
5287			uint32_t cpthis = 0;
5288
5289			pad_needed = 4 - (err_at % 4);
5290			m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
5291			err_at += pad_needed;
5292		}
5293		s.param_type = htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
5294		s.param_length = htons(sizeof(s) + sizeof(struct sctp_paramhdr));
5295		m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
5296		err_at += sizeof(s);
5297		/* Only copy back the p-hdr that caused the issue */
5298		m_copyback(op_err, err_at, sizeof(struct sctp_paramhdr), (caddr_t)phdr);
5299	}
5300	return (op_err);
5301}
5302
5303static int
5304sctp_are_there_new_addresses(struct sctp_association *asoc,
5305    struct mbuf *in_initpkt, int offset, struct sockaddr *src)
5306{
5307	/*
5308	 * Given a INIT packet, look through the packet to verify that there
5309	 * are NO new addresses. As we go through the parameters add reports
5310	 * of any un-understood parameters that require an error.  Also we
5311	 * must return (1) to drop the packet if we see a un-understood
5312	 * parameter that tells us to drop the chunk.
5313	 */
5314	struct sockaddr *sa_touse;
5315	struct sockaddr *sa;
5316	struct sctp_paramhdr *phdr, params;
5317	uint16_t ptype, plen;
5318	uint8_t fnd;
5319	struct sctp_nets *net;
5320
5321#ifdef INET
5322	struct sockaddr_in sin4, *sa4;
5323
5324#endif
5325#ifdef INET6
5326	struct sockaddr_in6 sin6, *sa6;
5327
5328#endif
5329
5330#ifdef INET
5331	memset(&sin4, 0, sizeof(sin4));
5332	sin4.sin_family = AF_INET;
5333	sin4.sin_len = sizeof(sin4);
5334#endif
5335#ifdef INET6
5336	memset(&sin6, 0, sizeof(sin6));
5337	sin6.sin6_family = AF_INET6;
5338	sin6.sin6_len = sizeof(sin6);
5339#endif
5340	/* First what about the src address of the pkt ? */
5341	fnd = 0;
5342	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
5343		sa = (struct sockaddr *)&net->ro._l_addr;
5344		if (sa->sa_family == src->sa_family) {
5345#ifdef INET
5346			if (sa->sa_family == AF_INET) {
5347				struct sockaddr_in *src4;
5348
5349				sa4 = (struct sockaddr_in *)sa;
5350				src4 = (struct sockaddr_in *)src;
5351				if (sa4->sin_addr.s_addr == src4->sin_addr.s_addr) {
5352					fnd = 1;
5353					break;
5354				}
5355			}
5356#endif
5357#ifdef INET6
5358			if (sa->sa_family == AF_INET6) {
5359				struct sockaddr_in6 *src6;
5360
5361				sa6 = (struct sockaddr_in6 *)sa;
5362				src6 = (struct sockaddr_in6 *)src;
5363				if (SCTP6_ARE_ADDR_EQUAL(sa6, src6)) {
5364					fnd = 1;
5365					break;
5366				}
5367			}
5368#endif
5369		}
5370	}
5371	if (fnd == 0) {
5372		/* New address added! no need to look futher. */
5373		return (1);
5374	}
5375	/* Ok so far lets munge through the rest of the packet */
5376	offset += sizeof(struct sctp_init_chunk);
5377	phdr = sctp_get_next_param(in_initpkt, offset, &params, sizeof(params));
5378	while (phdr) {
5379		sa_touse = NULL;
5380		ptype = ntohs(phdr->param_type);
5381		plen = ntohs(phdr->param_length);
5382		switch (ptype) {
5383#ifdef INET
5384		case SCTP_IPV4_ADDRESS:
5385			{
5386				struct sctp_ipv4addr_param *p4, p4_buf;
5387
5388				phdr = sctp_get_next_param(in_initpkt, offset,
5389				    (struct sctp_paramhdr *)&p4_buf, sizeof(p4_buf));
5390				if (plen != sizeof(struct sctp_ipv4addr_param) ||
5391				    phdr == NULL) {
5392					return (1);
5393				}
5394				p4 = (struct sctp_ipv4addr_param *)phdr;
5395				sin4.sin_addr.s_addr = p4->addr;
5396				sa_touse = (struct sockaddr *)&sin4;
5397				break;
5398			}
5399#endif
5400#ifdef INET6
5401		case SCTP_IPV6_ADDRESS:
5402			{
5403				struct sctp_ipv6addr_param *p6, p6_buf;
5404
5405				phdr = sctp_get_next_param(in_initpkt, offset,
5406				    (struct sctp_paramhdr *)&p6_buf, sizeof(p6_buf));
5407				if (plen != sizeof(struct sctp_ipv6addr_param) ||
5408				    phdr == NULL) {
5409					return (1);
5410				}
5411				p6 = (struct sctp_ipv6addr_param *)phdr;
5412				memcpy((caddr_t)&sin6.sin6_addr, p6->addr,
5413				    sizeof(p6->addr));
5414				sa_touse = (struct sockaddr *)&sin6;
5415				break;
5416			}
5417#endif
5418		default:
5419			sa_touse = NULL;
5420			break;
5421		}
5422		if (sa_touse) {
5423			/* ok, sa_touse points to one to check */
5424			fnd = 0;
5425			TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
5426				sa = (struct sockaddr *)&net->ro._l_addr;
5427				if (sa->sa_family != sa_touse->sa_family) {
5428					continue;
5429				}
5430#ifdef INET
5431				if (sa->sa_family == AF_INET) {
5432					sa4 = (struct sockaddr_in *)sa;
5433					if (sa4->sin_addr.s_addr ==
5434					    sin4.sin_addr.s_addr) {
5435						fnd = 1;
5436						break;
5437					}
5438				}
5439#endif
5440#ifdef INET6
5441				if (sa->sa_family == AF_INET6) {
5442					sa6 = (struct sockaddr_in6 *)sa;
5443					if (SCTP6_ARE_ADDR_EQUAL(
5444					    sa6, &sin6)) {
5445						fnd = 1;
5446						break;
5447					}
5448				}
5449#endif
5450			}
5451			if (!fnd) {
5452				/* New addr added! no need to look further */
5453				return (1);
5454			}
5455		}
5456		offset += SCTP_SIZE32(plen);
5457		phdr = sctp_get_next_param(in_initpkt, offset, &params, sizeof(params));
5458	}
5459	return (0);
5460}
5461
5462/*
5463 * Given a MBUF chain that was sent into us containing an INIT. Build a
5464 * INIT-ACK with COOKIE and send back. We assume that the in_initpkt has done
5465 * a pullup to include IPv6/4header, SCTP header and initial part of INIT
5466 * message (i.e. the struct sctp_init_msg).
5467 */
5468void
5469sctp_send_initiate_ack(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
5470    struct mbuf *init_pkt, int iphlen, int offset,
5471    struct sockaddr *src, struct sockaddr *dst,
5472    struct sctphdr *sh, struct sctp_init_chunk *init_chk,
5473    uint8_t mflowtype, uint32_t mflowid,
5474    uint32_t vrf_id, uint16_t port, int hold_inp_lock)
5475{
5476	struct sctp_association *asoc;
5477	struct mbuf *m, *m_tmp, *m_last, *m_cookie, *op_err;
5478	struct sctp_init_ack_chunk *initack;
5479	struct sctp_adaptation_layer_indication *ali;
5480	struct sctp_supported_chunk_types_param *pr_supported;
5481	struct sctp_paramhdr *ph;
5482	union sctp_sockstore *over_addr;
5483	struct sctp_scoping scp;
5484
5485#ifdef INET
5486	struct sockaddr_in *dst4 = (struct sockaddr_in *)dst;
5487	struct sockaddr_in *src4 = (struct sockaddr_in *)src;
5488	struct sockaddr_in *sin;
5489
5490#endif
5491#ifdef INET6
5492	struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)dst;
5493	struct sockaddr_in6 *src6 = (struct sockaddr_in6 *)src;
5494	struct sockaddr_in6 *sin6;
5495
5496#endif
5497	struct sockaddr *to;
5498	struct sctp_state_cookie stc;
5499	struct sctp_nets *net = NULL;
5500	uint8_t *signature = NULL;
5501	int cnt_inits_to = 0;
5502	uint16_t his_limit, i_want;
5503	int abort_flag;
5504	int nat_friendly = 0;
5505	struct socket *so;
5506	uint16_t num_ext, chunk_len, padding_len, parameter_len;
5507
5508	if (stcb) {
5509		asoc = &stcb->asoc;
5510	} else {
5511		asoc = NULL;
5512	}
5513	if ((asoc != NULL) &&
5514	    (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
5515	    (sctp_are_there_new_addresses(asoc, init_pkt, offset, src))) {
5516		/* new addresses, out of here in non-cookie-wait states */
5517		/*
5518		 * Send a ABORT, we don't add the new address error clause
5519		 * though we even set the T bit and copy in the 0 tag.. this
5520		 * looks no different than if no listener was present.
5521		 */
5522		op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code),
5523		    "Address added");
5524		sctp_send_abort(init_pkt, iphlen, src, dst, sh, 0, op_err,
5525		    mflowtype, mflowid,
5526		    vrf_id, port);
5527		return;
5528	}
5529	abort_flag = 0;
5530	op_err = sctp_arethere_unrecognized_parameters(init_pkt,
5531	    (offset + sizeof(struct sctp_init_chunk)),
5532	    &abort_flag, (struct sctp_chunkhdr *)init_chk, &nat_friendly);
5533	if (abort_flag) {
5534do_a_abort:
5535		if (op_err == NULL) {
5536			char msg[SCTP_DIAG_INFO_LEN];
5537
5538			snprintf(msg, sizeof(msg), "%s:%d at %s\n", __FILE__, __LINE__, __FUNCTION__);
5539			op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code),
5540			    msg);
5541		}
5542		sctp_send_abort(init_pkt, iphlen, src, dst, sh,
5543		    init_chk->init.initiate_tag, op_err,
5544		    mflowtype, mflowid,
5545		    vrf_id, port);
5546		return;
5547	}
5548	m = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_NOWAIT, 1, MT_DATA);
5549	if (m == NULL) {
5550		/* No memory, INIT timer will re-attempt. */
5551		if (op_err)
5552			sctp_m_freem(op_err);
5553		return;
5554	}
5555	chunk_len = (uint16_t) sizeof(struct sctp_init_ack_chunk);
5556	padding_len = 0;
5557
5558	/*
5559	 * We might not overwrite the identification[] completely and on
5560	 * some platforms time_entered will contain some padding. Therefore
5561	 * zero out the cookie to avoid putting uninitialized memory on the
5562	 * wire.
5563	 */
5564	memset(&stc, 0, sizeof(struct sctp_state_cookie));
5565
5566	/* the time I built cookie */
5567	(void)SCTP_GETTIME_TIMEVAL(&stc.time_entered);
5568
5569	/* populate any tie tags */
5570	if (asoc != NULL) {
5571		/* unlock before tag selections */
5572		stc.tie_tag_my_vtag = asoc->my_vtag_nonce;
5573		stc.tie_tag_peer_vtag = asoc->peer_vtag_nonce;
5574		stc.cookie_life = asoc->cookie_life;
5575		net = asoc->primary_destination;
5576	} else {
5577		stc.tie_tag_my_vtag = 0;
5578		stc.tie_tag_peer_vtag = 0;
5579		/* life I will award this cookie */
5580		stc.cookie_life = inp->sctp_ep.def_cookie_life;
5581	}
5582
5583	/* copy in the ports for later check */
5584	stc.myport = sh->dest_port;
5585	stc.peerport = sh->src_port;
5586
5587	/*
5588	 * If we wanted to honor cookie life extentions, we would add to
5589	 * stc.cookie_life. For now we should NOT honor any extension
5590	 */
5591	stc.site_scope = stc.local_scope = stc.loopback_scope = 0;
5592	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
5593		stc.ipv6_addr_legal = 1;
5594		if (SCTP_IPV6_V6ONLY(inp)) {
5595			stc.ipv4_addr_legal = 0;
5596		} else {
5597			stc.ipv4_addr_legal = 1;
5598		}
5599	} else {
5600		stc.ipv6_addr_legal = 0;
5601		stc.ipv4_addr_legal = 1;
5602	}
5603#ifdef SCTP_DONT_DO_PRIVADDR_SCOPE
5604	stc.ipv4_scope = 1;
5605#else
5606	stc.ipv4_scope = 0;
5607#endif
5608	if (net == NULL) {
5609		to = src;
5610		switch (dst->sa_family) {
5611#ifdef INET
5612		case AF_INET:
5613			{
5614				/* lookup address */
5615				stc.address[0] = src4->sin_addr.s_addr;
5616				stc.address[1] = 0;
5617				stc.address[2] = 0;
5618				stc.address[3] = 0;
5619				stc.addr_type = SCTP_IPV4_ADDRESS;
5620				/* local from address */
5621				stc.laddress[0] = dst4->sin_addr.s_addr;
5622				stc.laddress[1] = 0;
5623				stc.laddress[2] = 0;
5624				stc.laddress[3] = 0;
5625				stc.laddr_type = SCTP_IPV4_ADDRESS;
5626				/* scope_id is only for v6 */
5627				stc.scope_id = 0;
5628#ifndef SCTP_DONT_DO_PRIVADDR_SCOPE
5629				if (IN4_ISPRIVATE_ADDRESS(&src4->sin_addr)) {
5630					stc.ipv4_scope = 1;
5631				}
5632#else
5633				stc.ipv4_scope = 1;
5634#endif				/* SCTP_DONT_DO_PRIVADDR_SCOPE */
5635				/* Must use the address in this case */
5636				if (sctp_is_address_on_local_host(src, vrf_id)) {
5637					stc.loopback_scope = 1;
5638					stc.ipv4_scope = 1;
5639					stc.site_scope = 1;
5640					stc.local_scope = 0;
5641				}
5642				break;
5643			}
5644#endif
5645#ifdef INET6
5646		case AF_INET6:
5647			{
5648				stc.addr_type = SCTP_IPV6_ADDRESS;
5649				memcpy(&stc.address, &src6->sin6_addr, sizeof(struct in6_addr));
5650				stc.scope_id = in6_getscope(&src6->sin6_addr);
5651				if (sctp_is_address_on_local_host(src, vrf_id)) {
5652					stc.loopback_scope = 1;
5653					stc.local_scope = 0;
5654					stc.site_scope = 1;
5655					stc.ipv4_scope = 1;
5656				} else if (IN6_IS_ADDR_LINKLOCAL(&src6->sin6_addr)) {
5657					/*
5658					 * If the new destination is a
5659					 * LINK_LOCAL we must have common
5660					 * both site and local scope. Don't
5661					 * set local scope though since we
5662					 * must depend on the source to be
5663					 * added implicitly. We cannot
5664					 * assure just because we share one
5665					 * link that all links are common.
5666					 */
5667					stc.local_scope = 0;
5668					stc.site_scope = 1;
5669					stc.ipv4_scope = 1;
5670					/*
5671					 * we start counting for the private
5672					 * address stuff at 1. since the
5673					 * link local we source from won't
5674					 * show up in our scoped count.
5675					 */
5676					cnt_inits_to = 1;
5677					/*
5678					 * pull out the scope_id from
5679					 * incoming pkt
5680					 */
5681				} else if (IN6_IS_ADDR_SITELOCAL(&src6->sin6_addr)) {
5682					/*
5683					 * If the new destination is
5684					 * SITE_LOCAL then we must have site
5685					 * scope in common.
5686					 */
5687					stc.site_scope = 1;
5688				}
5689				memcpy(&stc.laddress, &dst6->sin6_addr, sizeof(struct in6_addr));
5690				stc.laddr_type = SCTP_IPV6_ADDRESS;
5691				break;
5692			}
5693#endif
5694		default:
5695			/* TSNH */
5696			goto do_a_abort;
5697			break;
5698		}
5699	} else {
5700		/* set the scope per the existing tcb */
5701
5702#ifdef INET6
5703		struct sctp_nets *lnet;
5704
5705#endif
5706
5707		stc.loopback_scope = asoc->scope.loopback_scope;
5708		stc.ipv4_scope = asoc->scope.ipv4_local_scope;
5709		stc.site_scope = asoc->scope.site_scope;
5710		stc.local_scope = asoc->scope.local_scope;
5711#ifdef INET6
5712		/* Why do we not consider IPv4 LL addresses? */
5713		TAILQ_FOREACH(lnet, &asoc->nets, sctp_next) {
5714			if (lnet->ro._l_addr.sin6.sin6_family == AF_INET6) {
5715				if (IN6_IS_ADDR_LINKLOCAL(&lnet->ro._l_addr.sin6.sin6_addr)) {
5716					/*
5717					 * if we have a LL address, start
5718					 * counting at 1.
5719					 */
5720					cnt_inits_to = 1;
5721				}
5722			}
5723		}
5724#endif
5725		/* use the net pointer */
5726		to = (struct sockaddr *)&net->ro._l_addr;
5727		switch (to->sa_family) {
5728#ifdef INET
5729		case AF_INET:
5730			sin = (struct sockaddr_in *)to;
5731			stc.address[0] = sin->sin_addr.s_addr;
5732			stc.address[1] = 0;
5733			stc.address[2] = 0;
5734			stc.address[3] = 0;
5735			stc.addr_type = SCTP_IPV4_ADDRESS;
5736			if (net->src_addr_selected == 0) {
5737				/*
5738				 * strange case here, the INIT should have
5739				 * did the selection.
5740				 */
5741				net->ro._s_addr = sctp_source_address_selection(inp,
5742				    stcb, (sctp_route_t *) & net->ro,
5743				    net, 0, vrf_id);
5744				if (net->ro._s_addr == NULL)
5745					return;
5746
5747				net->src_addr_selected = 1;
5748
5749			}
5750			stc.laddress[0] = net->ro._s_addr->address.sin.sin_addr.s_addr;
5751			stc.laddress[1] = 0;
5752			stc.laddress[2] = 0;
5753			stc.laddress[3] = 0;
5754			stc.laddr_type = SCTP_IPV4_ADDRESS;
5755			/* scope_id is only for v6 */
5756			stc.scope_id = 0;
5757			break;
5758#endif
5759#ifdef INET6
5760		case AF_INET6:
5761			sin6 = (struct sockaddr_in6 *)to;
5762			memcpy(&stc.address, &sin6->sin6_addr,
5763			    sizeof(struct in6_addr));
5764			stc.addr_type = SCTP_IPV6_ADDRESS;
5765			stc.scope_id = sin6->sin6_scope_id;
5766			if (net->src_addr_selected == 0) {
5767				/*
5768				 * strange case here, the INIT should have
5769				 * done the selection.
5770				 */
5771				net->ro._s_addr = sctp_source_address_selection(inp,
5772				    stcb, (sctp_route_t *) & net->ro,
5773				    net, 0, vrf_id);
5774				if (net->ro._s_addr == NULL)
5775					return;
5776
5777				net->src_addr_selected = 1;
5778			}
5779			memcpy(&stc.laddress, &net->ro._s_addr->address.sin6.sin6_addr,
5780			    sizeof(struct in6_addr));
5781			stc.laddr_type = SCTP_IPV6_ADDRESS;
5782			break;
5783#endif
5784		}
5785	}
5786	/* Now lets put the SCTP header in place */
5787	initack = mtod(m, struct sctp_init_ack_chunk *);
5788	/* Save it off for quick ref */
5789	stc.peers_vtag = init_chk->init.initiate_tag;
5790	/* who are we */
5791	memcpy(stc.identification, SCTP_VERSION_STRING,
5792	    min(strlen(SCTP_VERSION_STRING), sizeof(stc.identification)));
5793	memset(stc.reserved, 0, SCTP_RESERVE_SPACE);
5794	/* now the chunk header */
5795	initack->ch.chunk_type = SCTP_INITIATION_ACK;
5796	initack->ch.chunk_flags = 0;
5797	/* fill in later from mbuf we build */
5798	initack->ch.chunk_length = 0;
5799	/* place in my tag */
5800	if ((asoc != NULL) &&
5801	    ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
5802	    (SCTP_GET_STATE(asoc) == SCTP_STATE_INUSE) ||
5803	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED))) {
5804		/* re-use the v-tags and init-seq here */
5805		initack->init.initiate_tag = htonl(asoc->my_vtag);
5806		initack->init.initial_tsn = htonl(asoc->init_seq_number);
5807	} else {
5808		uint32_t vtag, itsn;
5809
5810		if (hold_inp_lock) {
5811			SCTP_INP_INCR_REF(inp);
5812			SCTP_INP_RUNLOCK(inp);
5813		}
5814		if (asoc) {
5815			atomic_add_int(&asoc->refcnt, 1);
5816			SCTP_TCB_UNLOCK(stcb);
5817	new_tag:
5818			vtag = sctp_select_a_tag(inp, inp->sctp_lport, sh->src_port, 1);
5819			if ((asoc->peer_supports_nat) && (vtag == asoc->my_vtag)) {
5820				/*
5821				 * Got a duplicate vtag on some guy behind a
5822				 * nat make sure we don't use it.
5823				 */
5824				goto new_tag;
5825			}
5826			initack->init.initiate_tag = htonl(vtag);
5827			/* get a TSN to use too */
5828			itsn = sctp_select_initial_TSN(&inp->sctp_ep);
5829			initack->init.initial_tsn = htonl(itsn);
5830			SCTP_TCB_LOCK(stcb);
5831			atomic_add_int(&asoc->refcnt, -1);
5832		} else {
5833			vtag = sctp_select_a_tag(inp, inp->sctp_lport, sh->src_port, 1);
5834			initack->init.initiate_tag = htonl(vtag);
5835			/* get a TSN to use too */
5836			initack->init.initial_tsn = htonl(sctp_select_initial_TSN(&inp->sctp_ep));
5837		}
5838		if (hold_inp_lock) {
5839			SCTP_INP_RLOCK(inp);
5840			SCTP_INP_DECR_REF(inp);
5841		}
5842	}
5843	/* save away my tag to */
5844	stc.my_vtag = initack->init.initiate_tag;
5845
5846	/* set up some of the credits. */
5847	so = inp->sctp_socket;
5848	if (so == NULL) {
5849		/* memory problem */
5850		sctp_m_freem(m);
5851		return;
5852	} else {
5853		initack->init.a_rwnd = htonl(max(SCTP_SB_LIMIT_RCV(so), SCTP_MINIMAL_RWND));
5854	}
5855	/* set what I want */
5856	his_limit = ntohs(init_chk->init.num_inbound_streams);
5857	/* choose what I want */
5858	if (asoc != NULL) {
5859		if (asoc->streamoutcnt > inp->sctp_ep.pre_open_stream_count) {
5860			i_want = asoc->streamoutcnt;
5861		} else {
5862			i_want = inp->sctp_ep.pre_open_stream_count;
5863		}
5864	} else {
5865		i_want = inp->sctp_ep.pre_open_stream_count;
5866	}
5867	if (his_limit < i_want) {
5868		/* I Want more :< */
5869		initack->init.num_outbound_streams = init_chk->init.num_inbound_streams;
5870	} else {
5871		/* I can have what I want :> */
5872		initack->init.num_outbound_streams = htons(i_want);
5873	}
5874	/* tell him his limit. */
5875	initack->init.num_inbound_streams =
5876	    htons(inp->sctp_ep.max_open_streams_intome);
5877
5878	/* adaptation layer indication parameter */
5879	if (inp->sctp_ep.adaptation_layer_indicator_provided) {
5880		parameter_len = (uint16_t) sizeof(struct sctp_adaptation_layer_indication);
5881		ali = (struct sctp_adaptation_layer_indication *)(mtod(m, caddr_t)+chunk_len);
5882		ali->ph.param_type = htons(SCTP_ULP_ADAPTATION);
5883		ali->ph.param_length = htons(parameter_len);
5884		ali->indication = htonl(inp->sctp_ep.adaptation_layer_indicator);
5885		chunk_len += parameter_len;
5886	}
5887	/* ECN parameter */
5888	if (((asoc != NULL) && (asoc->ecn_supported == 1)) ||
5889	    ((asoc == NULL) && (inp->ecn_supported == 1))) {
5890		parameter_len = (uint16_t) sizeof(struct sctp_paramhdr);
5891		ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+chunk_len);
5892		ph->param_type = htons(SCTP_ECN_CAPABLE);
5893		ph->param_length = htons(parameter_len);
5894		chunk_len += parameter_len;
5895	}
5896	/* PR-SCTP supported parameter */
5897	if (((asoc != NULL) && (asoc->prsctp_supported == 1)) ||
5898	    ((asoc == NULL) && (inp->prsctp_supported == 1))) {
5899		parameter_len = (uint16_t) sizeof(struct sctp_paramhdr);
5900		ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+chunk_len);
5901		ph->param_type = htons(SCTP_PRSCTP_SUPPORTED);
5902		ph->param_length = htons(parameter_len);
5903		chunk_len += parameter_len;
5904	}
5905	/* Add NAT friendly parameter */
5906	if (nat_friendly) {
5907		parameter_len = (uint16_t) sizeof(struct sctp_paramhdr);
5908		ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+chunk_len);
5909		ph->param_type = htons(SCTP_HAS_NAT_SUPPORT);
5910		ph->param_length = htons(parameter_len);
5911		chunk_len += parameter_len;
5912	}
5913	/* And now tell the peer which extensions we support */
5914	num_ext = 0;
5915	pr_supported = (struct sctp_supported_chunk_types_param *)(mtod(m, caddr_t)+chunk_len);
5916	if (((asoc != NULL) && (asoc->prsctp_supported == 1)) ||
5917	    ((asoc == NULL) && (inp->prsctp_supported == 1))) {
5918		pr_supported->chunk_types[num_ext++] = SCTP_FORWARD_CUM_TSN;
5919	}
5920	if (((asoc != NULL) && (asoc->auth_supported == 1)) ||
5921	    ((asoc == NULL) && (inp->auth_supported == 1))) {
5922		pr_supported->chunk_types[num_ext++] = SCTP_AUTHENTICATION;
5923	}
5924	if (((asoc != NULL) && (asoc->asconf_supported == 1)) ||
5925	    ((asoc == NULL) && (inp->asconf_supported == 1))) {
5926		pr_supported->chunk_types[num_ext++] = SCTP_ASCONF;
5927		pr_supported->chunk_types[num_ext++] = SCTP_ASCONF_ACK;
5928	}
5929	if (((asoc != NULL) && (asoc->reconfig_supported == 1)) ||
5930	    ((asoc == NULL) && (inp->reconfig_supported == 1))) {
5931		pr_supported->chunk_types[num_ext++] = SCTP_STREAM_RESET;
5932	}
5933	if (((asoc != NULL) && (asoc->nrsack_supported == 1)) ||
5934	    ((asoc == NULL) && (inp->nrsack_supported == 1))) {
5935		pr_supported->chunk_types[num_ext++] = SCTP_NR_SELECTIVE_ACK;
5936	}
5937	if (((asoc != NULL) && (asoc->pktdrop_supported == 1)) ||
5938	    ((asoc == NULL) && (inp->pktdrop_supported == 1))) {
5939		pr_supported->chunk_types[num_ext++] = SCTP_PACKET_DROPPED;
5940	}
5941	if (num_ext > 0) {
5942		parameter_len = (uint16_t) sizeof(struct sctp_supported_chunk_types_param) + num_ext;
5943		pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
5944		pr_supported->ph.param_length = htons(parameter_len);
5945		padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
5946		chunk_len += parameter_len;
5947	}
5948	/* add authentication parameters */
5949	if (((asoc != NULL) && (asoc->auth_supported == 1)) ||
5950	    ((asoc == NULL) && (inp->auth_supported == 1))) {
5951		struct sctp_auth_random *randp;
5952		struct sctp_auth_hmac_algo *hmacs;
5953		struct sctp_auth_chunk_list *chunks;
5954
5955		if (padding_len > 0) {
5956			memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
5957			chunk_len += padding_len;
5958			padding_len = 0;
5959		}
5960		/* generate and add RANDOM parameter */
5961		randp = (struct sctp_auth_random *)(mtod(m, caddr_t)+chunk_len);
5962		parameter_len = (uint16_t) sizeof(struct sctp_auth_random) +
5963		    SCTP_AUTH_RANDOM_SIZE_DEFAULT;
5964		randp->ph.param_type = htons(SCTP_RANDOM);
5965		randp->ph.param_length = htons(parameter_len);
5966		SCTP_READ_RANDOM(randp->random_data, SCTP_AUTH_RANDOM_SIZE_DEFAULT);
5967		padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
5968		chunk_len += parameter_len;
5969
5970		if (padding_len > 0) {
5971			memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
5972			chunk_len += padding_len;
5973			padding_len = 0;
5974		}
5975		/* add HMAC_ALGO parameter */
5976		hmacs = (struct sctp_auth_hmac_algo *)(mtod(m, caddr_t)+chunk_len);
5977		parameter_len = (uint16_t) sizeof(struct sctp_auth_hmac_algo) +
5978		    sctp_serialize_hmaclist(inp->sctp_ep.local_hmacs,
5979		    (uint8_t *) hmacs->hmac_ids);
5980		hmacs->ph.param_type = htons(SCTP_HMAC_LIST);
5981		hmacs->ph.param_length = htons(parameter_len);
5982		padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
5983		chunk_len += parameter_len;
5984
5985		if (padding_len > 0) {
5986			memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
5987			chunk_len += padding_len;
5988			padding_len = 0;
5989		}
5990		/* add CHUNKS parameter */
5991		chunks = (struct sctp_auth_chunk_list *)(mtod(m, caddr_t)+chunk_len);
5992		parameter_len = (uint16_t) sizeof(struct sctp_auth_chunk_list) +
5993		    sctp_serialize_auth_chunks(inp->sctp_ep.local_auth_chunks,
5994		    chunks->chunk_types);
5995		chunks->ph.param_type = htons(SCTP_CHUNK_LIST);
5996		chunks->ph.param_length = htons(parameter_len);
5997		padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
5998		chunk_len += parameter_len;
5999	}
6000	SCTP_BUF_LEN(m) = chunk_len;
6001	m_last = m;
6002	/* now the addresses */
6003	/*
6004	 * To optimize this we could put the scoping stuff into a structure
6005	 * and remove the individual uint8's from the stc structure. Then we
6006	 * could just sifa in the address within the stc.. but for now this
6007	 * is a quick hack to get the address stuff teased apart.
6008	 */
6009	scp.ipv4_addr_legal = stc.ipv4_addr_legal;
6010	scp.ipv6_addr_legal = stc.ipv6_addr_legal;
6011	scp.loopback_scope = stc.loopback_scope;
6012	scp.ipv4_local_scope = stc.ipv4_scope;
6013	scp.local_scope = stc.local_scope;
6014	scp.site_scope = stc.site_scope;
6015	m_last = sctp_add_addresses_to_i_ia(inp, stcb, &scp, m_last,
6016	    cnt_inits_to,
6017	    &padding_len, &chunk_len);
6018	/* padding_len can only be positive, if no addresses have been added */
6019	if (padding_len > 0) {
6020		memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
6021		chunk_len += padding_len;
6022		SCTP_BUF_LEN(m) += padding_len;
6023		padding_len = 0;
6024	}
6025	/* tack on the operational error if present */
6026	if (op_err) {
6027		parameter_len = 0;
6028		for (m_tmp = op_err; m_tmp != NULL; m_tmp = SCTP_BUF_NEXT(m_tmp)) {
6029			parameter_len += SCTP_BUF_LEN(m_tmp);
6030		}
6031		padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
6032		SCTP_BUF_NEXT(m_last) = op_err;
6033		while (SCTP_BUF_NEXT(m_last) != NULL) {
6034			m_last = SCTP_BUF_NEXT(m_last);
6035		}
6036		chunk_len += parameter_len;
6037	}
6038	if (padding_len > 0) {
6039		m_last = sctp_add_pad_tombuf(m_last, padding_len);
6040		if (m_last == NULL) {
6041			/* Houston we have a problem, no space */
6042			sctp_m_freem(m);
6043			return;
6044		}
6045		chunk_len += padding_len;
6046		padding_len = 0;
6047	}
6048	/* Now we must build a cookie */
6049	m_cookie = sctp_add_cookie(init_pkt, offset, m, 0, &stc, &signature);
6050	if (m_cookie == NULL) {
6051		/* memory problem */
6052		sctp_m_freem(m);
6053		return;
6054	}
6055	/* Now append the cookie to the end and update the space/size */
6056	SCTP_BUF_NEXT(m_last) = m_cookie;
6057	parameter_len = 0;
6058	for (m_tmp = m_cookie; m_tmp != NULL; m_tmp = SCTP_BUF_NEXT(m_tmp)) {
6059		parameter_len += SCTP_BUF_LEN(m_tmp);
6060		if (SCTP_BUF_NEXT(m_tmp) == NULL) {
6061			m_last = m_tmp;
6062		}
6063	}
6064	padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
6065	chunk_len += parameter_len;
6066
6067	/*
6068	 * Place in the size, but we don't include the last pad (if any) in
6069	 * the INIT-ACK.
6070	 */
6071	initack->ch.chunk_length = htons(chunk_len);
6072
6073	/*
6074	 * Time to sign the cookie, we don't sign over the cookie signature
6075	 * though thus we set trailer.
6076	 */
6077	(void)sctp_hmac_m(SCTP_HMAC,
6078	    (uint8_t *) inp->sctp_ep.secret_key[(int)(inp->sctp_ep.current_secret_number)],
6079	    SCTP_SECRET_SIZE, m_cookie, sizeof(struct sctp_paramhdr),
6080	    (uint8_t *) signature, SCTP_SIGNATURE_SIZE);
6081	/*
6082	 * We sifa 0 here to NOT set IP_DF if its IPv4, we ignore the return
6083	 * here since the timer will drive a retranmission.
6084	 */
6085	if (padding_len > 0) {
6086		if (sctp_add_pad_tombuf(m_last, padding_len) == NULL) {
6087			sctp_m_freem(m);
6088			return;
6089		}
6090	}
6091	if (stc.loopback_scope) {
6092		over_addr = (union sctp_sockstore *)dst;
6093	} else {
6094		over_addr = NULL;
6095	}
6096
6097	(void)sctp_lowlevel_chunk_output(inp, NULL, NULL, to, m, 0, NULL, 0, 0,
6098	    0, 0,
6099	    inp->sctp_lport, sh->src_port, init_chk->init.initiate_tag,
6100	    port, over_addr,
6101	    mflowtype, mflowid,
6102	    SCTP_SO_NOT_LOCKED);
6103	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
6104}
6105
6106
6107static void
6108sctp_prune_prsctp(struct sctp_tcb *stcb,
6109    struct sctp_association *asoc,
6110    struct sctp_sndrcvinfo *srcv,
6111    int dataout)
6112{
6113	int freed_spc = 0;
6114	struct sctp_tmit_chunk *chk, *nchk;
6115
6116	SCTP_TCB_LOCK_ASSERT(stcb);
6117	if ((asoc->prsctp_supported) &&
6118	    (asoc->sent_queue_cnt_removeable > 0)) {
6119		TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
6120			/*
6121			 * Look for chunks marked with the PR_SCTP flag AND
6122			 * the buffer space flag. If the one being sent is
6123			 * equal or greater priority then purge the old one
6124			 * and free some space.
6125			 */
6126			if (PR_SCTP_BUF_ENABLED(chk->flags)) {
6127				/*
6128				 * This one is PR-SCTP AND buffer space
6129				 * limited type
6130				 */
6131				if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
6132					/*
6133					 * Lower numbers equates to higher
6134					 * priority so if the one we are
6135					 * looking at has a larger or equal
6136					 * priority we want to drop the data
6137					 * and NOT retransmit it.
6138					 */
6139					if (chk->data) {
6140						/*
6141						 * We release the book_size
6142						 * if the mbuf is here
6143						 */
6144						int ret_spc;
6145						uint8_t sent;
6146
6147						if (chk->sent > SCTP_DATAGRAM_UNSENT)
6148							sent = 1;
6149						else
6150							sent = 0;
6151						ret_spc = sctp_release_pr_sctp_chunk(stcb, chk,
6152						    sent,
6153						    SCTP_SO_LOCKED);
6154						freed_spc += ret_spc;
6155						if (freed_spc >= dataout) {
6156							return;
6157						}
6158					}	/* if chunk was present */
6159				}	/* if of sufficent priority */
6160			}	/* if chunk has enabled */
6161		}		/* tailqforeach */
6162
6163		TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
6164			/* Here we must move to the sent queue and mark */
6165			if (PR_SCTP_BUF_ENABLED(chk->flags)) {
6166				if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
6167					if (chk->data) {
6168						/*
6169						 * We release the book_size
6170						 * if the mbuf is here
6171						 */
6172						int ret_spc;
6173
6174						ret_spc = sctp_release_pr_sctp_chunk(stcb, chk,
6175						    0, SCTP_SO_LOCKED);
6176
6177						freed_spc += ret_spc;
6178						if (freed_spc >= dataout) {
6179							return;
6180						}
6181					}	/* end if chk->data */
6182				}	/* end if right class */
6183			}	/* end if chk pr-sctp */
6184		}		/* tailqforeachsafe (chk) */
6185	}			/* if enabled in asoc */
6186}
6187
6188int
6189sctp_get_frag_point(struct sctp_tcb *stcb,
6190    struct sctp_association *asoc)
6191{
6192	int siz, ovh;
6193
6194	/*
6195	 * For endpoints that have both v6 and v4 addresses we must reserve
6196	 * room for the ipv6 header, for those that are only dealing with V4
6197	 * we use a larger frag point.
6198	 */
6199	if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
6200		ovh = SCTP_MED_OVERHEAD;
6201	} else {
6202		ovh = SCTP_MED_V4_OVERHEAD;
6203	}
6204
6205	if (stcb->asoc.sctp_frag_point > asoc->smallest_mtu)
6206		siz = asoc->smallest_mtu - ovh;
6207	else
6208		siz = (stcb->asoc.sctp_frag_point - ovh);
6209	/*
6210	 * if (siz > (MCLBYTES-sizeof(struct sctp_data_chunk))) {
6211	 */
6212	/* A data chunk MUST fit in a cluster */
6213	/* siz = (MCLBYTES - sizeof(struct sctp_data_chunk)); */
6214	/* } */
6215
6216	/* adjust for an AUTH chunk if DATA requires auth */
6217	if (sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks))
6218		siz -= sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
6219
6220	if (siz % 4) {
6221		/* make it an even word boundary please */
6222		siz -= (siz % 4);
6223	}
6224	return (siz);
6225}
6226
6227static void
6228sctp_set_prsctp_policy(struct sctp_stream_queue_pending *sp)
6229{
6230	/*
6231	 * We assume that the user wants PR_SCTP_TTL if the user provides a
6232	 * positive lifetime but does not specify any PR_SCTP policy.
6233	 */
6234	if (PR_SCTP_ENABLED(sp->sinfo_flags)) {
6235		sp->act_flags |= PR_SCTP_POLICY(sp->sinfo_flags);
6236	} else if (sp->timetolive > 0) {
6237		sp->sinfo_flags |= SCTP_PR_SCTP_TTL;
6238		sp->act_flags |= PR_SCTP_POLICY(sp->sinfo_flags);
6239	} else {
6240		return;
6241	}
6242	switch (PR_SCTP_POLICY(sp->sinfo_flags)) {
6243	case CHUNK_FLAGS_PR_SCTP_BUF:
6244		/*
6245		 * Time to live is a priority stored in tv_sec when doing
6246		 * the buffer drop thing.
6247		 */
6248		sp->ts.tv_sec = sp->timetolive;
6249		sp->ts.tv_usec = 0;
6250		break;
6251	case CHUNK_FLAGS_PR_SCTP_TTL:
6252		{
6253			struct timeval tv;
6254
6255			(void)SCTP_GETTIME_TIMEVAL(&sp->ts);
6256			tv.tv_sec = sp->timetolive / 1000;
6257			tv.tv_usec = (sp->timetolive * 1000) % 1000000;
6258			/*
6259			 * TODO sctp_constants.h needs alternative time
6260			 * macros when _KERNEL is undefined.
6261			 */
6262			timevaladd(&sp->ts, &tv);
6263		}
6264		break;
6265	case CHUNK_FLAGS_PR_SCTP_RTX:
6266		/*
6267		 * Time to live is a the number or retransmissions stored in
6268		 * tv_sec.
6269		 */
6270		sp->ts.tv_sec = sp->timetolive;
6271		sp->ts.tv_usec = 0;
6272		break;
6273	default:
6274		SCTPDBG(SCTP_DEBUG_USRREQ1,
6275		    "Unknown PR_SCTP policy %u.\n",
6276		    PR_SCTP_POLICY(sp->sinfo_flags));
6277		break;
6278	}
6279}
6280
6281static int
6282sctp_msg_append(struct sctp_tcb *stcb,
6283    struct sctp_nets *net,
6284    struct mbuf *m,
6285    struct sctp_sndrcvinfo *srcv, int hold_stcb_lock)
6286{
6287	int error = 0;
6288	struct mbuf *at;
6289	struct sctp_stream_queue_pending *sp = NULL;
6290	struct sctp_stream_out *strm;
6291
6292	/*
6293	 * Given an mbuf chain, put it into the association send queue and
6294	 * place it on the wheel
6295	 */
6296	if (srcv->sinfo_stream >= stcb->asoc.streamoutcnt) {
6297		/* Invalid stream number */
6298		SCTP_LTRACE_ERR_RET_PKT(m, NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
6299		error = EINVAL;
6300		goto out_now;
6301	}
6302	if ((stcb->asoc.stream_locked) &&
6303	    (stcb->asoc.stream_locked_on != srcv->sinfo_stream)) {
6304		SCTP_LTRACE_ERR_RET_PKT(m, NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
6305		error = EINVAL;
6306		goto out_now;
6307	}
6308	strm = &stcb->asoc.strmout[srcv->sinfo_stream];
6309	/* Now can we send this? */
6310	if ((SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
6311	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
6312	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
6313	    (stcb->asoc.state & SCTP_STATE_SHUTDOWN_PENDING)) {
6314		/* got data while shutting down */
6315		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
6316		error = ECONNRESET;
6317		goto out_now;
6318	}
6319	sctp_alloc_a_strmoq(stcb, sp);
6320	if (sp == NULL) {
6321		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
6322		error = ENOMEM;
6323		goto out_now;
6324	}
6325	sp->sinfo_flags = srcv->sinfo_flags;
6326	sp->timetolive = srcv->sinfo_timetolive;
6327	sp->ppid = srcv->sinfo_ppid;
6328	sp->context = srcv->sinfo_context;
6329	if (sp->sinfo_flags & SCTP_ADDR_OVER) {
6330		sp->net = net;
6331		atomic_add_int(&sp->net->ref_count, 1);
6332	} else {
6333		sp->net = NULL;
6334	}
6335	(void)SCTP_GETTIME_TIMEVAL(&sp->ts);
6336	sp->stream = srcv->sinfo_stream;
6337	sp->msg_is_complete = 1;
6338	sp->sender_all_done = 1;
6339	sp->some_taken = 0;
6340	sp->data = m;
6341	sp->tail_mbuf = NULL;
6342	sctp_set_prsctp_policy(sp);
6343	/*
6344	 * We could in theory (for sendall) sifa the length in, but we would
6345	 * still have to hunt through the chain since we need to setup the
6346	 * tail_mbuf
6347	 */
6348	sp->length = 0;
6349	for (at = m; at; at = SCTP_BUF_NEXT(at)) {
6350		if (SCTP_BUF_NEXT(at) == NULL)
6351			sp->tail_mbuf = at;
6352		sp->length += SCTP_BUF_LEN(at);
6353	}
6354	if (srcv->sinfo_keynumber_valid) {
6355		sp->auth_keyid = srcv->sinfo_keynumber;
6356	} else {
6357		sp->auth_keyid = stcb->asoc.authinfo.active_keyid;
6358	}
6359	if (sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks)) {
6360		sctp_auth_key_acquire(stcb, sp->auth_keyid);
6361		sp->holds_key_ref = 1;
6362	}
6363	if (hold_stcb_lock == 0) {
6364		SCTP_TCB_SEND_LOCK(stcb);
6365	}
6366	sctp_snd_sb_alloc(stcb, sp->length);
6367	atomic_add_int(&stcb->asoc.stream_queue_cnt, 1);
6368	TAILQ_INSERT_TAIL(&strm->outqueue, sp, next);
6369	stcb->asoc.ss_functions.sctp_ss_add_to_stream(stcb, &stcb->asoc, strm, sp, 1);
6370	m = NULL;
6371	if (hold_stcb_lock == 0) {
6372		SCTP_TCB_SEND_UNLOCK(stcb);
6373	}
6374out_now:
6375	if (m) {
6376		sctp_m_freem(m);
6377	}
6378	return (error);
6379}
6380
6381
6382static struct mbuf *
6383sctp_copy_mbufchain(struct mbuf *clonechain,
6384    struct mbuf *outchain,
6385    struct mbuf **endofchain,
6386    int can_take_mbuf,
6387    int sizeofcpy,
6388    uint8_t copy_by_ref)
6389{
6390	struct mbuf *m;
6391	struct mbuf *appendchain;
6392	caddr_t cp;
6393	int len;
6394
6395	if (endofchain == NULL) {
6396		/* error */
6397error_out:
6398		if (outchain)
6399			sctp_m_freem(outchain);
6400		return (NULL);
6401	}
6402	if (can_take_mbuf) {
6403		appendchain = clonechain;
6404	} else {
6405		if (!copy_by_ref &&
6406		    (sizeofcpy <= (int)((((SCTP_BASE_SYSCTL(sctp_mbuf_threshold_count) - 1) * MLEN) + MHLEN)))
6407		    ) {
6408			/* Its not in a cluster */
6409			if (*endofchain == NULL) {
6410				/* lets get a mbuf cluster */
6411				if (outchain == NULL) {
6412					/* This is the general case */
6413			new_mbuf:
6414					outchain = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_NOWAIT, 1, MT_HEADER);
6415					if (outchain == NULL) {
6416						goto error_out;
6417					}
6418					SCTP_BUF_LEN(outchain) = 0;
6419					*endofchain = outchain;
6420					/* get the prepend space */
6421					SCTP_BUF_RESV_UF(outchain, (SCTP_FIRST_MBUF_RESV + 4));
6422				} else {
6423					/*
6424					 * We really should not get a NULL
6425					 * in endofchain
6426					 */
6427					/* find end */
6428					m = outchain;
6429					while (m) {
6430						if (SCTP_BUF_NEXT(m) == NULL) {
6431							*endofchain = m;
6432							break;
6433						}
6434						m = SCTP_BUF_NEXT(m);
6435					}
6436					/* sanity */
6437					if (*endofchain == NULL) {
6438						/*
6439						 * huh, TSNH XXX maybe we
6440						 * should panic
6441						 */
6442						sctp_m_freem(outchain);
6443						goto new_mbuf;
6444					}
6445				}
6446				/* get the new end of length */
6447				len = M_TRAILINGSPACE(*endofchain);
6448			} else {
6449				/* how much is left at the end? */
6450				len = M_TRAILINGSPACE(*endofchain);
6451			}
6452			/* Find the end of the data, for appending */
6453			cp = (mtod((*endofchain), caddr_t)+SCTP_BUF_LEN((*endofchain)));
6454
6455			/* Now lets copy it out */
6456			if (len >= sizeofcpy) {
6457				/* It all fits, copy it in */
6458				m_copydata(clonechain, 0, sizeofcpy, cp);
6459				SCTP_BUF_LEN((*endofchain)) += sizeofcpy;
6460			} else {
6461				/* fill up the end of the chain */
6462				if (len > 0) {
6463					m_copydata(clonechain, 0, len, cp);
6464					SCTP_BUF_LEN((*endofchain)) += len;
6465					/* now we need another one */
6466					sizeofcpy -= len;
6467				}
6468				m = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_NOWAIT, 1, MT_HEADER);
6469				if (m == NULL) {
6470					/* We failed */
6471					goto error_out;
6472				}
6473				SCTP_BUF_NEXT((*endofchain)) = m;
6474				*endofchain = m;
6475				cp = mtod((*endofchain), caddr_t);
6476				m_copydata(clonechain, len, sizeofcpy, cp);
6477				SCTP_BUF_LEN((*endofchain)) += sizeofcpy;
6478			}
6479			return (outchain);
6480		} else {
6481			/* copy the old fashion way */
6482			appendchain = SCTP_M_COPYM(clonechain, 0, M_COPYALL, M_NOWAIT);
6483#ifdef SCTP_MBUF_LOGGING
6484			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
6485				struct mbuf *mat;
6486
6487				for (mat = appendchain; mat; mat = SCTP_BUF_NEXT(mat)) {
6488					if (SCTP_BUF_IS_EXTENDED(mat)) {
6489						sctp_log_mb(mat, SCTP_MBUF_ICOPY);
6490					}
6491				}
6492			}
6493#endif
6494		}
6495	}
6496	if (appendchain == NULL) {
6497		/* error */
6498		if (outchain)
6499			sctp_m_freem(outchain);
6500		return (NULL);
6501	}
6502	if (outchain) {
6503		/* tack on to the end */
6504		if (*endofchain != NULL) {
6505			SCTP_BUF_NEXT(((*endofchain))) = appendchain;
6506		} else {
6507			m = outchain;
6508			while (m) {
6509				if (SCTP_BUF_NEXT(m) == NULL) {
6510					SCTP_BUF_NEXT(m) = appendchain;
6511					break;
6512				}
6513				m = SCTP_BUF_NEXT(m);
6514			}
6515		}
6516		/*
6517		 * save off the end and update the end-chain postion
6518		 */
6519		m = appendchain;
6520		while (m) {
6521			if (SCTP_BUF_NEXT(m) == NULL) {
6522				*endofchain = m;
6523				break;
6524			}
6525			m = SCTP_BUF_NEXT(m);
6526		}
6527		return (outchain);
6528	} else {
6529		/* save off the end and update the end-chain postion */
6530		m = appendchain;
6531		while (m) {
6532			if (SCTP_BUF_NEXT(m) == NULL) {
6533				*endofchain = m;
6534				break;
6535			}
6536			m = SCTP_BUF_NEXT(m);
6537		}
6538		return (appendchain);
6539	}
6540}
6541
6542static int
6543sctp_med_chunk_output(struct sctp_inpcb *inp,
6544    struct sctp_tcb *stcb,
6545    struct sctp_association *asoc,
6546    int *num_out,
6547    int *reason_code,
6548    int control_only, int from_where,
6549    struct timeval *now, int *now_filled, int frag_point, int so_locked
6550#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
6551    SCTP_UNUSED
6552#endif
6553);
6554
6555static void
6556sctp_sendall_iterator(struct sctp_inpcb *inp, struct sctp_tcb *stcb, void *ptr,
6557    uint32_t val SCTP_UNUSED)
6558{
6559	struct sctp_copy_all *ca;
6560	struct mbuf *m;
6561	int ret = 0;
6562	int added_control = 0;
6563	int un_sent, do_chunk_output = 1;
6564	struct sctp_association *asoc;
6565	struct sctp_nets *net;
6566
6567	ca = (struct sctp_copy_all *)ptr;
6568	if (ca->m == NULL) {
6569		return;
6570	}
6571	if (ca->inp != inp) {
6572		/* TSNH */
6573		return;
6574	}
6575	if (ca->sndlen > 0) {
6576		m = SCTP_M_COPYM(ca->m, 0, M_COPYALL, M_NOWAIT);
6577		if (m == NULL) {
6578			/* can't copy so we are done */
6579			ca->cnt_failed++;
6580			return;
6581		}
6582#ifdef SCTP_MBUF_LOGGING
6583		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
6584			struct mbuf *mat;
6585
6586			for (mat = m; mat; mat = SCTP_BUF_NEXT(mat)) {
6587				if (SCTP_BUF_IS_EXTENDED(mat)) {
6588					sctp_log_mb(mat, SCTP_MBUF_ICOPY);
6589				}
6590			}
6591		}
6592#endif
6593	} else {
6594		m = NULL;
6595	}
6596	SCTP_TCB_LOCK_ASSERT(stcb);
6597	if (stcb->asoc.alternate) {
6598		net = stcb->asoc.alternate;
6599	} else {
6600		net = stcb->asoc.primary_destination;
6601	}
6602	if (ca->sndrcv.sinfo_flags & SCTP_ABORT) {
6603		/* Abort this assoc with m as the user defined reason */
6604		if (m != NULL) {
6605			SCTP_BUF_PREPEND(m, sizeof(struct sctp_paramhdr), M_NOWAIT);
6606		} else {
6607			m = sctp_get_mbuf_for_msg(sizeof(struct sctp_paramhdr),
6608			    0, M_NOWAIT, 1, MT_DATA);
6609			SCTP_BUF_LEN(m) = sizeof(struct sctp_paramhdr);
6610		}
6611		if (m != NULL) {
6612			struct sctp_paramhdr *ph;
6613
6614			ph = mtod(m, struct sctp_paramhdr *);
6615			ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
6616			ph->param_length = htons(sizeof(struct sctp_paramhdr) + ca->sndlen);
6617		}
6618		/*
6619		 * We add one here to keep the assoc from dis-appearing on
6620		 * us.
6621		 */
6622		atomic_add_int(&stcb->asoc.refcnt, 1);
6623		sctp_abort_an_association(inp, stcb, m, SCTP_SO_NOT_LOCKED);
6624		/*
6625		 * sctp_abort_an_association calls sctp_free_asoc() free
6626		 * association will NOT free it since we incremented the
6627		 * refcnt .. we do this to prevent it being freed and things
6628		 * getting tricky since we could end up (from free_asoc)
6629		 * calling inpcb_free which would get a recursive lock call
6630		 * to the iterator lock.. But as a consequence of that the
6631		 * stcb will return to us un-locked.. since free_asoc
6632		 * returns with either no TCB or the TCB unlocked, we must
6633		 * relock.. to unlock in the iterator timer :-0
6634		 */
6635		SCTP_TCB_LOCK(stcb);
6636		atomic_add_int(&stcb->asoc.refcnt, -1);
6637		goto no_chunk_output;
6638	} else {
6639		if (m) {
6640			ret = sctp_msg_append(stcb, net, m,
6641			    &ca->sndrcv, 1);
6642		}
6643		asoc = &stcb->asoc;
6644		if (ca->sndrcv.sinfo_flags & SCTP_EOF) {
6645			/* shutdown this assoc */
6646			int cnt;
6647
6648			cnt = sctp_is_there_unsent_data(stcb, SCTP_SO_NOT_LOCKED);
6649
6650			if (TAILQ_EMPTY(&asoc->send_queue) &&
6651			    TAILQ_EMPTY(&asoc->sent_queue) &&
6652			    (cnt == 0)) {
6653				if (asoc->locked_on_sending) {
6654					goto abort_anyway;
6655				}
6656				/*
6657				 * there is nothing queued to send, so I'm
6658				 * done...
6659				 */
6660				if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
6661				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
6662				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
6663					/*
6664					 * only send SHUTDOWN the first time
6665					 * through
6666					 */
6667					if (SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) {
6668						SCTP_STAT_DECR_GAUGE32(sctps_currestab);
6669					}
6670					SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_SENT);
6671					SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING);
6672					sctp_stop_timers_for_shutdown(stcb);
6673					sctp_send_shutdown(stcb, net);
6674					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
6675					    net);
6676					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
6677					    asoc->primary_destination);
6678					added_control = 1;
6679					do_chunk_output = 0;
6680				}
6681			} else {
6682				/*
6683				 * we still got (or just got) data to send,
6684				 * so set SHUTDOWN_PENDING
6685				 */
6686				/*
6687				 * XXX sockets draft says that SCTP_EOF
6688				 * should be sent with no data.  currently,
6689				 * we will allow user data to be sent first
6690				 * and move to SHUTDOWN-PENDING
6691				 */
6692				if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
6693				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
6694				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
6695					if (asoc->locked_on_sending) {
6696						/*
6697						 * Locked to send out the
6698						 * data
6699						 */
6700						struct sctp_stream_queue_pending *sp;
6701
6702						sp = TAILQ_LAST(&asoc->locked_on_sending->outqueue, sctp_streamhead);
6703						if (sp) {
6704							if ((sp->length == 0) && (sp->msg_is_complete == 0))
6705								asoc->state |= SCTP_STATE_PARTIAL_MSG_LEFT;
6706						}
6707					}
6708					asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
6709					if (TAILQ_EMPTY(&asoc->send_queue) &&
6710					    TAILQ_EMPTY(&asoc->sent_queue) &&
6711					    (asoc->state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
6712				abort_anyway:
6713						atomic_add_int(&stcb->asoc.refcnt, 1);
6714						sctp_abort_an_association(stcb->sctp_ep, stcb,
6715						    NULL, SCTP_SO_NOT_LOCKED);
6716						atomic_add_int(&stcb->asoc.refcnt, -1);
6717						goto no_chunk_output;
6718					}
6719					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
6720					    asoc->primary_destination);
6721				}
6722			}
6723
6724		}
6725	}
6726	un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
6727	    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
6728
6729	if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
6730	    (stcb->asoc.total_flight > 0) &&
6731	    (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))) {
6732		do_chunk_output = 0;
6733	}
6734	if (do_chunk_output)
6735		sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_NOT_LOCKED);
6736	else if (added_control) {
6737		int num_out, reason, now_filled = 0;
6738		struct timeval now;
6739		int frag_point;
6740
6741		frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
6742		(void)sctp_med_chunk_output(inp, stcb, &stcb->asoc, &num_out,
6743		    &reason, 1, 1, &now, &now_filled, frag_point, SCTP_SO_NOT_LOCKED);
6744	}
6745no_chunk_output:
6746	if (ret) {
6747		ca->cnt_failed++;
6748	} else {
6749		ca->cnt_sent++;
6750	}
6751}
6752
6753static void
6754sctp_sendall_completes(void *ptr, uint32_t val SCTP_UNUSED)
6755{
6756	struct sctp_copy_all *ca;
6757
6758	ca = (struct sctp_copy_all *)ptr;
6759	/*
6760	 * Do a notify here? Kacheong suggests that the notify be done at
6761	 * the send time.. so you would push up a notification if any send
6762	 * failed. Don't know if this is feasable since the only failures we
6763	 * have is "memory" related and if you cannot get an mbuf to send
6764	 * the data you surely can't get an mbuf to send up to notify the
6765	 * user you can't send the data :->
6766	 */
6767
6768	/* now free everything */
6769	sctp_m_freem(ca->m);
6770	SCTP_FREE(ca, SCTP_M_COPYAL);
6771}
6772
6773static struct mbuf *
6774sctp_copy_out_all(struct uio *uio, int len)
6775{
6776	struct mbuf *ret, *at;
6777	int left, willcpy, cancpy, error;
6778
6779	ret = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_WAITOK, 1, MT_DATA);
6780	if (ret == NULL) {
6781		/* TSNH */
6782		return (NULL);
6783	}
6784	left = len;
6785	SCTP_BUF_LEN(ret) = 0;
6786	/* save space for the data chunk header */
6787	cancpy = M_TRAILINGSPACE(ret);
6788	willcpy = min(cancpy, left);
6789	at = ret;
6790	while (left > 0) {
6791		/* Align data to the end */
6792		error = uiomove(mtod(at, caddr_t), willcpy, uio);
6793		if (error) {
6794	err_out_now:
6795			sctp_m_freem(at);
6796			return (NULL);
6797		}
6798		SCTP_BUF_LEN(at) = willcpy;
6799		SCTP_BUF_NEXT_PKT(at) = SCTP_BUF_NEXT(at) = 0;
6800		left -= willcpy;
6801		if (left > 0) {
6802			SCTP_BUF_NEXT(at) = sctp_get_mbuf_for_msg(left, 0, M_WAITOK, 1, MT_DATA);
6803			if (SCTP_BUF_NEXT(at) == NULL) {
6804				goto err_out_now;
6805			}
6806			at = SCTP_BUF_NEXT(at);
6807			SCTP_BUF_LEN(at) = 0;
6808			cancpy = M_TRAILINGSPACE(at);
6809			willcpy = min(cancpy, left);
6810		}
6811	}
6812	return (ret);
6813}
6814
6815static int
6816sctp_sendall(struct sctp_inpcb *inp, struct uio *uio, struct mbuf *m,
6817    struct sctp_sndrcvinfo *srcv)
6818{
6819	int ret;
6820	struct sctp_copy_all *ca;
6821
6822	SCTP_MALLOC(ca, struct sctp_copy_all *, sizeof(struct sctp_copy_all),
6823	    SCTP_M_COPYAL);
6824	if (ca == NULL) {
6825		sctp_m_freem(m);
6826		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
6827		return (ENOMEM);
6828	}
6829	memset(ca, 0, sizeof(struct sctp_copy_all));
6830
6831	ca->inp = inp;
6832	if (srcv) {
6833		memcpy(&ca->sndrcv, srcv, sizeof(struct sctp_nonpad_sndrcvinfo));
6834	}
6835	/*
6836	 * take off the sendall flag, it would be bad if we failed to do
6837	 * this :-0
6838	 */
6839	ca->sndrcv.sinfo_flags &= ~SCTP_SENDALL;
6840	/* get length and mbuf chain */
6841	if (uio) {
6842		ca->sndlen = uio->uio_resid;
6843		ca->m = sctp_copy_out_all(uio, ca->sndlen);
6844		if (ca->m == NULL) {
6845			SCTP_FREE(ca, SCTP_M_COPYAL);
6846			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
6847			return (ENOMEM);
6848		}
6849	} else {
6850		/* Gather the length of the send */
6851		struct mbuf *mat;
6852
6853		ca->sndlen = 0;
6854		for (mat = m; mat; mat = SCTP_BUF_NEXT(mat)) {
6855			ca->sndlen += SCTP_BUF_LEN(mat);
6856		}
6857	}
6858	ret = sctp_initiate_iterator(NULL, sctp_sendall_iterator, NULL,
6859	    SCTP_PCB_ANY_FLAGS, SCTP_PCB_ANY_FEATURES,
6860	    SCTP_ASOC_ANY_STATE,
6861	    (void *)ca, 0,
6862	    sctp_sendall_completes, inp, 1);
6863	if (ret) {
6864		SCTP_PRINTF("Failed to initiate iterator for sendall\n");
6865		SCTP_FREE(ca, SCTP_M_COPYAL);
6866		SCTP_LTRACE_ERR_RET_PKT(m, inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EFAULT);
6867		return (EFAULT);
6868	}
6869	return (0);
6870}
6871
6872
6873void
6874sctp_toss_old_cookies(struct sctp_tcb *stcb, struct sctp_association *asoc)
6875{
6876	struct sctp_tmit_chunk *chk, *nchk;
6877
6878	TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
6879		if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
6880			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
6881			if (chk->data) {
6882				sctp_m_freem(chk->data);
6883				chk->data = NULL;
6884			}
6885			asoc->ctrl_queue_cnt--;
6886			sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
6887		}
6888	}
6889}
6890
6891void
6892sctp_toss_old_asconf(struct sctp_tcb *stcb)
6893{
6894	struct sctp_association *asoc;
6895	struct sctp_tmit_chunk *chk, *nchk;
6896	struct sctp_asconf_chunk *acp;
6897
6898	asoc = &stcb->asoc;
6899	TAILQ_FOREACH_SAFE(chk, &asoc->asconf_send_queue, sctp_next, nchk) {
6900		/* find SCTP_ASCONF chunk in queue */
6901		if (chk->rec.chunk_id.id == SCTP_ASCONF) {
6902			if (chk->data) {
6903				acp = mtod(chk->data, struct sctp_asconf_chunk *);
6904				if (SCTP_TSN_GT(ntohl(acp->serial_number), asoc->asconf_seq_out_acked)) {
6905					/* Not Acked yet */
6906					break;
6907				}
6908			}
6909			TAILQ_REMOVE(&asoc->asconf_send_queue, chk, sctp_next);
6910			if (chk->data) {
6911				sctp_m_freem(chk->data);
6912				chk->data = NULL;
6913			}
6914			asoc->ctrl_queue_cnt--;
6915			sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
6916		}
6917	}
6918}
6919
6920
6921static void
6922sctp_clean_up_datalist(struct sctp_tcb *stcb,
6923    struct sctp_association *asoc,
6924    struct sctp_tmit_chunk **data_list,
6925    int bundle_at,
6926    struct sctp_nets *net)
6927{
6928	int i;
6929	struct sctp_tmit_chunk *tp1;
6930
6931	for (i = 0; i < bundle_at; i++) {
6932		/* off of the send queue */
6933		TAILQ_REMOVE(&asoc->send_queue, data_list[i], sctp_next);
6934		asoc->send_queue_cnt--;
6935		if (i > 0) {
6936			/*
6937			 * Any chunk NOT 0 you zap the time chunk 0 gets
6938			 * zapped or set based on if a RTO measurment is
6939			 * needed.
6940			 */
6941			data_list[i]->do_rtt = 0;
6942		}
6943		/* record time */
6944		data_list[i]->sent_rcv_time = net->last_sent_time;
6945		data_list[i]->rec.data.cwnd_at_send = net->cwnd;
6946		data_list[i]->rec.data.fast_retran_tsn = data_list[i]->rec.data.TSN_seq;
6947		if (data_list[i]->whoTo == NULL) {
6948			data_list[i]->whoTo = net;
6949			atomic_add_int(&net->ref_count, 1);
6950		}
6951		/* on to the sent queue */
6952		tp1 = TAILQ_LAST(&asoc->sent_queue, sctpchunk_listhead);
6953		if ((tp1) && SCTP_TSN_GT(tp1->rec.data.TSN_seq, data_list[i]->rec.data.TSN_seq)) {
6954			struct sctp_tmit_chunk *tpp;
6955
6956			/* need to move back */
6957	back_up_more:
6958			tpp = TAILQ_PREV(tp1, sctpchunk_listhead, sctp_next);
6959			if (tpp == NULL) {
6960				TAILQ_INSERT_BEFORE(tp1, data_list[i], sctp_next);
6961				goto all_done;
6962			}
6963			tp1 = tpp;
6964			if (SCTP_TSN_GT(tp1->rec.data.TSN_seq, data_list[i]->rec.data.TSN_seq)) {
6965				goto back_up_more;
6966			}
6967			TAILQ_INSERT_AFTER(&asoc->sent_queue, tp1, data_list[i], sctp_next);
6968		} else {
6969			TAILQ_INSERT_TAIL(&asoc->sent_queue,
6970			    data_list[i],
6971			    sctp_next);
6972		}
6973all_done:
6974		/* This does not lower until the cum-ack passes it */
6975		asoc->sent_queue_cnt++;
6976		if ((asoc->peers_rwnd <= 0) &&
6977		    (asoc->total_flight == 0) &&
6978		    (bundle_at == 1)) {
6979			/* Mark the chunk as being a window probe */
6980			SCTP_STAT_INCR(sctps_windowprobed);
6981		}
6982#ifdef SCTP_AUDITING_ENABLED
6983		sctp_audit_log(0xC2, 3);
6984#endif
6985		data_list[i]->sent = SCTP_DATAGRAM_SENT;
6986		data_list[i]->snd_count = 1;
6987		data_list[i]->rec.data.chunk_was_revoked = 0;
6988		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_FLIGHT_LOGGING_ENABLE) {
6989			sctp_misc_ints(SCTP_FLIGHT_LOG_UP,
6990			    data_list[i]->whoTo->flight_size,
6991			    data_list[i]->book_size,
6992			    (uintptr_t) data_list[i]->whoTo,
6993			    data_list[i]->rec.data.TSN_seq);
6994		}
6995		sctp_flight_size_increase(data_list[i]);
6996		sctp_total_flight_increase(stcb, data_list[i]);
6997		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_RWND_ENABLE) {
6998			sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
6999			    asoc->peers_rwnd, data_list[i]->send_size, SCTP_BASE_SYSCTL(sctp_peer_chunk_oh));
7000		}
7001		asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
7002		    (uint32_t) (data_list[i]->send_size + SCTP_BASE_SYSCTL(sctp_peer_chunk_oh)));
7003		if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
7004			/* SWS sender side engages */
7005			asoc->peers_rwnd = 0;
7006		}
7007	}
7008	if (asoc->cc_functions.sctp_cwnd_update_packet_transmitted) {
7009		(*asoc->cc_functions.sctp_cwnd_update_packet_transmitted) (stcb, net);
7010	}
7011}
7012
7013static void
7014sctp_clean_up_ctl(struct sctp_tcb *stcb, struct sctp_association *asoc, int so_locked
7015#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
7016    SCTP_UNUSED
7017#endif
7018)
7019{
7020	struct sctp_tmit_chunk *chk, *nchk;
7021
7022	TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
7023		if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
7024		    (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK) ||	/* EY */
7025		    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) ||
7026		    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_ACK) ||
7027		    (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) ||
7028		    (chk->rec.chunk_id.id == SCTP_SHUTDOWN) ||
7029		    (chk->rec.chunk_id.id == SCTP_SHUTDOWN_ACK) ||
7030		    (chk->rec.chunk_id.id == SCTP_OPERATION_ERROR) ||
7031		    (chk->rec.chunk_id.id == SCTP_PACKET_DROPPED) ||
7032		    (chk->rec.chunk_id.id == SCTP_COOKIE_ACK) ||
7033		    (chk->rec.chunk_id.id == SCTP_ECN_CWR) ||
7034		    (chk->rec.chunk_id.id == SCTP_ASCONF_ACK)) {
7035			/* Stray chunks must be cleaned up */
7036	clean_up_anyway:
7037			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
7038			if (chk->data) {
7039				sctp_m_freem(chk->data);
7040				chk->data = NULL;
7041			}
7042			asoc->ctrl_queue_cnt--;
7043			if (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN)
7044				asoc->fwd_tsn_cnt--;
7045			sctp_free_a_chunk(stcb, chk, so_locked);
7046		} else if (chk->rec.chunk_id.id == SCTP_STREAM_RESET) {
7047			/* special handling, we must look into the param */
7048			if (chk != asoc->str_reset) {
7049				goto clean_up_anyway;
7050			}
7051		}
7052	}
7053}
7054
7055
7056static int
7057sctp_can_we_split_this(struct sctp_tcb *stcb,
7058    uint32_t length,
7059    uint32_t goal_mtu, uint32_t frag_point, int eeor_on)
7060{
7061	/*
7062	 * Make a decision on if I should split a msg into multiple parts.
7063	 * This is only asked of incomplete messages.
7064	 */
7065	if (eeor_on) {
7066		/*
7067		 * If we are doing EEOR we need to always send it if its the
7068		 * entire thing, since it might be all the guy is putting in
7069		 * the hopper.
7070		 */
7071		if (goal_mtu >= length) {
7072			/*-
7073			 * If we have data outstanding,
7074			 * we get another chance when the sack
7075			 * arrives to transmit - wait for more data
7076			 */
7077			if (stcb->asoc.total_flight == 0) {
7078				/*
7079				 * If nothing is in flight, we zero the
7080				 * packet counter.
7081				 */
7082				return (length);
7083			}
7084			return (0);
7085
7086		} else {
7087			/* You can fill the rest */
7088			return (goal_mtu);
7089		}
7090	}
7091	/*-
7092	 * For those strange folk that make the send buffer
7093	 * smaller than our fragmentation point, we can't
7094	 * get a full msg in so we have to allow splitting.
7095	 */
7096	if (SCTP_SB_LIMIT_SND(stcb->sctp_socket) < frag_point) {
7097		return (length);
7098	}
7099	if ((length <= goal_mtu) ||
7100	    ((length - goal_mtu) < SCTP_BASE_SYSCTL(sctp_min_residual))) {
7101		/* Sub-optimial residual don't split in non-eeor mode. */
7102		return (0);
7103	}
7104	/*
7105	 * If we reach here length is larger than the goal_mtu. Do we wish
7106	 * to split it for the sake of packet putting together?
7107	 */
7108	if (goal_mtu >= min(SCTP_BASE_SYSCTL(sctp_min_split_point), frag_point)) {
7109		/* Its ok to split it */
7110		return (min(goal_mtu, frag_point));
7111	}
7112	/* Nope, can't split */
7113	return (0);
7114
7115}
7116
7117static uint32_t
7118sctp_move_to_outqueue(struct sctp_tcb *stcb,
7119    struct sctp_stream_out *strq,
7120    uint32_t goal_mtu,
7121    uint32_t frag_point,
7122    int *locked,
7123    int *giveup,
7124    int eeor_mode,
7125    int *bail,
7126    int so_locked
7127#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
7128    SCTP_UNUSED
7129#endif
7130)
7131{
7132	/* Move from the stream to the send_queue keeping track of the total */
7133	struct sctp_association *asoc;
7134	struct sctp_stream_queue_pending *sp;
7135	struct sctp_tmit_chunk *chk;
7136	struct sctp_data_chunk *dchkh;
7137	uint32_t to_move, length;
7138	uint8_t rcv_flags = 0;
7139	uint8_t some_taken;
7140	uint8_t send_lock_up = 0;
7141
7142	SCTP_TCB_LOCK_ASSERT(stcb);
7143	asoc = &stcb->asoc;
7144one_more_time:
7145	/* sa_ignore FREED_MEMORY */
7146	sp = TAILQ_FIRST(&strq->outqueue);
7147	if (sp == NULL) {
7148		*locked = 0;
7149		if (send_lock_up == 0) {
7150			SCTP_TCB_SEND_LOCK(stcb);
7151			send_lock_up = 1;
7152		}
7153		sp = TAILQ_FIRST(&strq->outqueue);
7154		if (sp) {
7155			goto one_more_time;
7156		}
7157		if (strq->last_msg_incomplete) {
7158			SCTP_PRINTF("Huh? Stream:%d lm_in_c=%d but queue is NULL\n",
7159			    strq->stream_no,
7160			    strq->last_msg_incomplete);
7161			strq->last_msg_incomplete = 0;
7162		}
7163		to_move = 0;
7164		if (send_lock_up) {
7165			SCTP_TCB_SEND_UNLOCK(stcb);
7166			send_lock_up = 0;
7167		}
7168		goto out_of;
7169	}
7170	if ((sp->msg_is_complete) && (sp->length == 0)) {
7171		if (sp->sender_all_done) {
7172			/*
7173			 * We are doing differed cleanup. Last time through
7174			 * when we took all the data the sender_all_done was
7175			 * not set.
7176			 */
7177			if ((sp->put_last_out == 0) && (sp->discard_rest == 0)) {
7178				SCTP_PRINTF("Gak, put out entire msg with NO end!-1\n");
7179				SCTP_PRINTF("sender_done:%d len:%d msg_comp:%d put_last_out:%d send_lock:%d\n",
7180				    sp->sender_all_done,
7181				    sp->length,
7182				    sp->msg_is_complete,
7183				    sp->put_last_out,
7184				    send_lock_up);
7185			}
7186			if ((TAILQ_NEXT(sp, next) == NULL) && (send_lock_up == 0)) {
7187				SCTP_TCB_SEND_LOCK(stcb);
7188				send_lock_up = 1;
7189			}
7190			atomic_subtract_int(&asoc->stream_queue_cnt, 1);
7191			TAILQ_REMOVE(&strq->outqueue, sp, next);
7192			stcb->asoc.ss_functions.sctp_ss_remove_from_stream(stcb, asoc, strq, sp, send_lock_up);
7193			if (sp->net) {
7194				sctp_free_remote_addr(sp->net);
7195				sp->net = NULL;
7196			}
7197			if (sp->data) {
7198				sctp_m_freem(sp->data);
7199				sp->data = NULL;
7200			}
7201			sctp_free_a_strmoq(stcb, sp, so_locked);
7202			/* we can't be locked to it */
7203			*locked = 0;
7204			stcb->asoc.locked_on_sending = NULL;
7205			if (send_lock_up) {
7206				SCTP_TCB_SEND_UNLOCK(stcb);
7207				send_lock_up = 0;
7208			}
7209			/* back to get the next msg */
7210			goto one_more_time;
7211		} else {
7212			/*
7213			 * sender just finished this but still holds a
7214			 * reference
7215			 */
7216			*locked = 1;
7217			*giveup = 1;
7218			to_move = 0;
7219			goto out_of;
7220		}
7221	} else {
7222		/* is there some to get */
7223		if (sp->length == 0) {
7224			/* no */
7225			*locked = 1;
7226			*giveup = 1;
7227			to_move = 0;
7228			goto out_of;
7229		} else if (sp->discard_rest) {
7230			if (send_lock_up == 0) {
7231				SCTP_TCB_SEND_LOCK(stcb);
7232				send_lock_up = 1;
7233			}
7234			/* Whack down the size */
7235			atomic_subtract_int(&stcb->asoc.total_output_queue_size, sp->length);
7236			if ((stcb->sctp_socket != NULL) && \
7237			    ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
7238			    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL))) {
7239				atomic_subtract_int(&stcb->sctp_socket->so_snd.sb_cc, sp->length);
7240			}
7241			if (sp->data) {
7242				sctp_m_freem(sp->data);
7243				sp->data = NULL;
7244				sp->tail_mbuf = NULL;
7245			}
7246			sp->length = 0;
7247			sp->some_taken = 1;
7248			*locked = 1;
7249			*giveup = 1;
7250			to_move = 0;
7251			goto out_of;
7252		}
7253	}
7254	some_taken = sp->some_taken;
7255	if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
7256		sp->msg_is_complete = 1;
7257	}
7258re_look:
7259	length = sp->length;
7260	if (sp->msg_is_complete) {
7261		/* The message is complete */
7262		to_move = min(length, frag_point);
7263		if (to_move == length) {
7264			/* All of it fits in the MTU */
7265			if (sp->some_taken) {
7266				rcv_flags |= SCTP_DATA_LAST_FRAG;
7267				sp->put_last_out = 1;
7268			} else {
7269				rcv_flags |= SCTP_DATA_NOT_FRAG;
7270				sp->put_last_out = 1;
7271			}
7272		} else {
7273			/* Not all of it fits, we fragment */
7274			if (sp->some_taken == 0) {
7275				rcv_flags |= SCTP_DATA_FIRST_FRAG;
7276			}
7277			sp->some_taken = 1;
7278		}
7279	} else {
7280		to_move = sctp_can_we_split_this(stcb, length, goal_mtu, frag_point, eeor_mode);
7281		if (to_move) {
7282			/*-
7283			 * We use a snapshot of length in case it
7284			 * is expanding during the compare.
7285			 */
7286			uint32_t llen;
7287
7288			llen = length;
7289			if (to_move >= llen) {
7290				to_move = llen;
7291				if (send_lock_up == 0) {
7292					/*-
7293					 * We are taking all of an incomplete msg
7294					 * thus we need a send lock.
7295					 */
7296					SCTP_TCB_SEND_LOCK(stcb);
7297					send_lock_up = 1;
7298					if (sp->msg_is_complete) {
7299						/*
7300						 * the sender finished the
7301						 * msg
7302						 */
7303						goto re_look;
7304					}
7305				}
7306			}
7307			if (sp->some_taken == 0) {
7308				rcv_flags |= SCTP_DATA_FIRST_FRAG;
7309				sp->some_taken = 1;
7310			}
7311		} else {
7312			/* Nothing to take. */
7313			if (sp->some_taken) {
7314				*locked = 1;
7315			}
7316			*giveup = 1;
7317			to_move = 0;
7318			goto out_of;
7319		}
7320	}
7321
7322	/* If we reach here, we can copy out a chunk */
7323	sctp_alloc_a_chunk(stcb, chk);
7324	if (chk == NULL) {
7325		/* No chunk memory */
7326		*giveup = 1;
7327		to_move = 0;
7328		goto out_of;
7329	}
7330	/*
7331	 * Setup for unordered if needed by looking at the user sent info
7332	 * flags.
7333	 */
7334	if (sp->sinfo_flags & SCTP_UNORDERED) {
7335		rcv_flags |= SCTP_DATA_UNORDERED;
7336	}
7337	if ((SCTP_BASE_SYSCTL(sctp_enable_sack_immediately) && ((sp->sinfo_flags & SCTP_EOF) == SCTP_EOF)) ||
7338	    ((sp->sinfo_flags & SCTP_SACK_IMMEDIATELY) == SCTP_SACK_IMMEDIATELY)) {
7339		rcv_flags |= SCTP_DATA_SACK_IMMEDIATELY;
7340	}
7341	/* clear out the chunk before setting up */
7342	memset(chk, 0, sizeof(*chk));
7343	chk->rec.data.rcv_flags = rcv_flags;
7344
7345	if (to_move >= length) {
7346		/* we think we can steal the whole thing */
7347		if ((sp->sender_all_done == 0) && (send_lock_up == 0)) {
7348			SCTP_TCB_SEND_LOCK(stcb);
7349			send_lock_up = 1;
7350		}
7351		if (to_move < sp->length) {
7352			/* bail, it changed */
7353			goto dont_do_it;
7354		}
7355		chk->data = sp->data;
7356		chk->last_mbuf = sp->tail_mbuf;
7357		/* register the stealing */
7358		sp->data = sp->tail_mbuf = NULL;
7359	} else {
7360		struct mbuf *m;
7361
7362dont_do_it:
7363		chk->data = SCTP_M_COPYM(sp->data, 0, to_move, M_NOWAIT);
7364		chk->last_mbuf = NULL;
7365		if (chk->data == NULL) {
7366			sp->some_taken = some_taken;
7367			sctp_free_a_chunk(stcb, chk, so_locked);
7368			*bail = 1;
7369			to_move = 0;
7370			goto out_of;
7371		}
7372#ifdef SCTP_MBUF_LOGGING
7373		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
7374			struct mbuf *mat;
7375
7376			for (mat = chk->data; mat; mat = SCTP_BUF_NEXT(mat)) {
7377				if (SCTP_BUF_IS_EXTENDED(mat)) {
7378					sctp_log_mb(mat, SCTP_MBUF_ICOPY);
7379				}
7380			}
7381		}
7382#endif
7383		/* Pull off the data */
7384		m_adj(sp->data, to_move);
7385		/* Now lets work our way down and compact it */
7386		m = sp->data;
7387		while (m && (SCTP_BUF_LEN(m) == 0)) {
7388			sp->data = SCTP_BUF_NEXT(m);
7389			SCTP_BUF_NEXT(m) = NULL;
7390			if (sp->tail_mbuf == m) {
7391				/*-
7392				 * Freeing tail? TSNH since
7393				 * we supposedly were taking less
7394				 * than the sp->length.
7395				 */
7396#ifdef INVARIANTS
7397				panic("Huh, freing tail? - TSNH");
7398#else
7399				SCTP_PRINTF("Huh, freeing tail? - TSNH\n");
7400				sp->tail_mbuf = sp->data = NULL;
7401				sp->length = 0;
7402#endif
7403
7404			}
7405			sctp_m_free(m);
7406			m = sp->data;
7407		}
7408	}
7409	if (SCTP_BUF_IS_EXTENDED(chk->data)) {
7410		chk->copy_by_ref = 1;
7411	} else {
7412		chk->copy_by_ref = 0;
7413	}
7414	/*
7415	 * get last_mbuf and counts of mb useage This is ugly but hopefully
7416	 * its only one mbuf.
7417	 */
7418	if (chk->last_mbuf == NULL) {
7419		chk->last_mbuf = chk->data;
7420		while (SCTP_BUF_NEXT(chk->last_mbuf) != NULL) {
7421			chk->last_mbuf = SCTP_BUF_NEXT(chk->last_mbuf);
7422		}
7423	}
7424	if (to_move > length) {
7425		/*- This should not happen either
7426		 * since we always lower to_move to the size
7427		 * of sp->length if its larger.
7428		 */
7429#ifdef INVARIANTS
7430		panic("Huh, how can to_move be larger?");
7431#else
7432		SCTP_PRINTF("Huh, how can to_move be larger?\n");
7433		sp->length = 0;
7434#endif
7435	} else {
7436		atomic_subtract_int(&sp->length, to_move);
7437	}
7438	if (M_LEADINGSPACE(chk->data) < (int)sizeof(struct sctp_data_chunk)) {
7439		/* Not enough room for a chunk header, get some */
7440		struct mbuf *m;
7441
7442		m = sctp_get_mbuf_for_msg(1, 0, M_NOWAIT, 0, MT_DATA);
7443		if (m == NULL) {
7444			/*
7445			 * we're in trouble here. _PREPEND below will free
7446			 * all the data if there is no leading space, so we
7447			 * must put the data back and restore.
7448			 */
7449			if (send_lock_up == 0) {
7450				SCTP_TCB_SEND_LOCK(stcb);
7451				send_lock_up = 1;
7452			}
7453			if (chk->data == NULL) {
7454				/* unsteal the data */
7455				sp->data = chk->data;
7456				sp->tail_mbuf = chk->last_mbuf;
7457			} else {
7458				struct mbuf *m_tmp;
7459
7460				/* reassemble the data */
7461				m_tmp = sp->data;
7462				sp->data = chk->data;
7463				SCTP_BUF_NEXT(chk->last_mbuf) = m_tmp;
7464			}
7465			sp->some_taken = some_taken;
7466			atomic_add_int(&sp->length, to_move);
7467			chk->data = NULL;
7468			*bail = 1;
7469			sctp_free_a_chunk(stcb, chk, so_locked);
7470			to_move = 0;
7471			goto out_of;
7472		} else {
7473			SCTP_BUF_LEN(m) = 0;
7474			SCTP_BUF_NEXT(m) = chk->data;
7475			chk->data = m;
7476			M_ALIGN(chk->data, 4);
7477		}
7478	}
7479	SCTP_BUF_PREPEND(chk->data, sizeof(struct sctp_data_chunk), M_NOWAIT);
7480	if (chk->data == NULL) {
7481		/* HELP, TSNH since we assured it would not above? */
7482#ifdef INVARIANTS
7483		panic("prepend failes HELP?");
7484#else
7485		SCTP_PRINTF("prepend fails HELP?\n");
7486		sctp_free_a_chunk(stcb, chk, so_locked);
7487#endif
7488		*bail = 1;
7489		to_move = 0;
7490		goto out_of;
7491	}
7492	sctp_snd_sb_alloc(stcb, sizeof(struct sctp_data_chunk));
7493	chk->book_size = chk->send_size = (to_move + sizeof(struct sctp_data_chunk));
7494	chk->book_size_scale = 0;
7495	chk->sent = SCTP_DATAGRAM_UNSENT;
7496
7497	chk->flags = 0;
7498	chk->asoc = &stcb->asoc;
7499	chk->pad_inplace = 0;
7500	chk->no_fr_allowed = 0;
7501	chk->rec.data.stream_seq = strq->next_sequence_send;
7502	if ((rcv_flags & SCTP_DATA_LAST_FRAG) &&
7503	    !(rcv_flags & SCTP_DATA_UNORDERED)) {
7504		strq->next_sequence_send++;
7505	}
7506	chk->rec.data.stream_number = sp->stream;
7507	chk->rec.data.payloadtype = sp->ppid;
7508	chk->rec.data.context = sp->context;
7509	chk->rec.data.doing_fast_retransmit = 0;
7510
7511	chk->rec.data.timetodrop = sp->ts;
7512	chk->flags = sp->act_flags;
7513
7514	if (sp->net) {
7515		chk->whoTo = sp->net;
7516		atomic_add_int(&chk->whoTo->ref_count, 1);
7517	} else
7518		chk->whoTo = NULL;
7519
7520	if (sp->holds_key_ref) {
7521		chk->auth_keyid = sp->auth_keyid;
7522		sctp_auth_key_acquire(stcb, chk->auth_keyid);
7523		chk->holds_key_ref = 1;
7524	}
7525	chk->rec.data.TSN_seq = atomic_fetchadd_int(&asoc->sending_seq, 1);
7526	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_AT_SEND_2_OUTQ) {
7527		sctp_misc_ints(SCTP_STRMOUT_LOG_SEND,
7528		    (uintptr_t) stcb, sp->length,
7529		    (uint32_t) ((chk->rec.data.stream_number << 16) | chk->rec.data.stream_seq),
7530		    chk->rec.data.TSN_seq);
7531	}
7532	dchkh = mtod(chk->data, struct sctp_data_chunk *);
7533	/*
7534	 * Put the rest of the things in place now. Size was done earlier in
7535	 * previous loop prior to padding.
7536	 */
7537
7538#ifdef SCTP_ASOCLOG_OF_TSNS
7539	SCTP_TCB_LOCK_ASSERT(stcb);
7540	if (asoc->tsn_out_at >= SCTP_TSN_LOG_SIZE) {
7541		asoc->tsn_out_at = 0;
7542		asoc->tsn_out_wrapped = 1;
7543	}
7544	asoc->out_tsnlog[asoc->tsn_out_at].tsn = chk->rec.data.TSN_seq;
7545	asoc->out_tsnlog[asoc->tsn_out_at].strm = chk->rec.data.stream_number;
7546	asoc->out_tsnlog[asoc->tsn_out_at].seq = chk->rec.data.stream_seq;
7547	asoc->out_tsnlog[asoc->tsn_out_at].sz = chk->send_size;
7548	asoc->out_tsnlog[asoc->tsn_out_at].flgs = chk->rec.data.rcv_flags;
7549	asoc->out_tsnlog[asoc->tsn_out_at].stcb = (void *)stcb;
7550	asoc->out_tsnlog[asoc->tsn_out_at].in_pos = asoc->tsn_out_at;
7551	asoc->out_tsnlog[asoc->tsn_out_at].in_out = 2;
7552	asoc->tsn_out_at++;
7553#endif
7554
7555	dchkh->ch.chunk_type = SCTP_DATA;
7556	dchkh->ch.chunk_flags = chk->rec.data.rcv_flags;
7557	dchkh->dp.tsn = htonl(chk->rec.data.TSN_seq);
7558	dchkh->dp.stream_id = htons(strq->stream_no);
7559	dchkh->dp.stream_sequence = htons(chk->rec.data.stream_seq);
7560	dchkh->dp.protocol_id = chk->rec.data.payloadtype;
7561	dchkh->ch.chunk_length = htons(chk->send_size);
7562	/* Now advance the chk->send_size by the actual pad needed. */
7563	if (chk->send_size < SCTP_SIZE32(chk->book_size)) {
7564		/* need a pad */
7565		struct mbuf *lm;
7566		int pads;
7567
7568		pads = SCTP_SIZE32(chk->book_size) - chk->send_size;
7569		lm = sctp_pad_lastmbuf(chk->data, pads, chk->last_mbuf);
7570		if (lm != NULL) {
7571			chk->last_mbuf = lm;
7572			chk->pad_inplace = 1;
7573		}
7574		chk->send_size += pads;
7575	}
7576	if (PR_SCTP_ENABLED(chk->flags)) {
7577		asoc->pr_sctp_cnt++;
7578	}
7579	if (sp->msg_is_complete && (sp->length == 0) && (sp->sender_all_done)) {
7580		/* All done pull and kill the message */
7581		atomic_subtract_int(&asoc->stream_queue_cnt, 1);
7582		if (sp->put_last_out == 0) {
7583			SCTP_PRINTF("Gak, put out entire msg with NO end!-2\n");
7584			SCTP_PRINTF("sender_done:%d len:%d msg_comp:%d put_last_out:%d send_lock:%d\n",
7585			    sp->sender_all_done,
7586			    sp->length,
7587			    sp->msg_is_complete,
7588			    sp->put_last_out,
7589			    send_lock_up);
7590		}
7591		if ((send_lock_up == 0) && (TAILQ_NEXT(sp, next) == NULL)) {
7592			SCTP_TCB_SEND_LOCK(stcb);
7593			send_lock_up = 1;
7594		}
7595		TAILQ_REMOVE(&strq->outqueue, sp, next);
7596		stcb->asoc.ss_functions.sctp_ss_remove_from_stream(stcb, asoc, strq, sp, send_lock_up);
7597		if (sp->net) {
7598			sctp_free_remote_addr(sp->net);
7599			sp->net = NULL;
7600		}
7601		if (sp->data) {
7602			sctp_m_freem(sp->data);
7603			sp->data = NULL;
7604		}
7605		sctp_free_a_strmoq(stcb, sp, so_locked);
7606
7607		/* we can't be locked to it */
7608		*locked = 0;
7609		stcb->asoc.locked_on_sending = NULL;
7610	} else {
7611		/* more to go, we are locked */
7612		*locked = 1;
7613	}
7614	asoc->chunks_on_out_queue++;
7615	strq->chunks_on_queues++;
7616	TAILQ_INSERT_TAIL(&asoc->send_queue, chk, sctp_next);
7617	asoc->send_queue_cnt++;
7618out_of:
7619	if (send_lock_up) {
7620		SCTP_TCB_SEND_UNLOCK(stcb);
7621	}
7622	return (to_move);
7623}
7624
7625
7626static void
7627sctp_fill_outqueue(struct sctp_tcb *stcb,
7628    struct sctp_nets *net, int frag_point, int eeor_mode, int *quit_now, int so_locked
7629#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
7630    SCTP_UNUSED
7631#endif
7632)
7633{
7634	struct sctp_association *asoc;
7635	struct sctp_stream_out *strq;
7636	int goal_mtu, moved_how_much, total_moved = 0, bail = 0;
7637	int locked, giveup;
7638
7639	SCTP_TCB_LOCK_ASSERT(stcb);
7640	asoc = &stcb->asoc;
7641	switch (net->ro._l_addr.sa.sa_family) {
7642#ifdef INET
7643	case AF_INET:
7644		goal_mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
7645		break;
7646#endif
7647#ifdef INET6
7648	case AF_INET6:
7649		goal_mtu = net->mtu - SCTP_MIN_OVERHEAD;
7650		break;
7651#endif
7652	default:
7653		/* TSNH */
7654		goal_mtu = net->mtu;
7655		break;
7656	}
7657	/* Need an allowance for the data chunk header too */
7658	goal_mtu -= sizeof(struct sctp_data_chunk);
7659
7660	/* must make even word boundary */
7661	goal_mtu &= 0xfffffffc;
7662	if (asoc->locked_on_sending) {
7663		/* We are stuck on one stream until the message completes. */
7664		strq = asoc->locked_on_sending;
7665		locked = 1;
7666	} else {
7667		strq = stcb->asoc.ss_functions.sctp_ss_select_stream(stcb, net, asoc);
7668		locked = 0;
7669	}
7670	while ((goal_mtu > 0) && strq) {
7671		giveup = 0;
7672		bail = 0;
7673		moved_how_much = sctp_move_to_outqueue(stcb, strq, goal_mtu, frag_point, &locked,
7674		    &giveup, eeor_mode, &bail, so_locked);
7675		if (moved_how_much)
7676			stcb->asoc.ss_functions.sctp_ss_scheduled(stcb, net, asoc, strq, moved_how_much);
7677
7678		if (locked) {
7679			asoc->locked_on_sending = strq;
7680			if ((moved_how_much == 0) || (giveup) || bail)
7681				/* no more to move for now */
7682				break;
7683		} else {
7684			asoc->locked_on_sending = NULL;
7685			if ((giveup) || bail) {
7686				break;
7687			}
7688			strq = stcb->asoc.ss_functions.sctp_ss_select_stream(stcb, net, asoc);
7689			if (strq == NULL) {
7690				break;
7691			}
7692		}
7693		total_moved += moved_how_much;
7694		goal_mtu -= (moved_how_much + sizeof(struct sctp_data_chunk));
7695		goal_mtu &= 0xfffffffc;
7696	}
7697	if (bail)
7698		*quit_now = 1;
7699
7700	stcb->asoc.ss_functions.sctp_ss_packet_done(stcb, net, asoc);
7701
7702	if (total_moved == 0) {
7703		if ((stcb->asoc.sctp_cmt_on_off == 0) &&
7704		    (net == stcb->asoc.primary_destination)) {
7705			/* ran dry for primary network net */
7706			SCTP_STAT_INCR(sctps_primary_randry);
7707		} else if (stcb->asoc.sctp_cmt_on_off > 0) {
7708			/* ran dry with CMT on */
7709			SCTP_STAT_INCR(sctps_cmt_randry);
7710		}
7711	}
7712}
7713
7714void
7715sctp_fix_ecn_echo(struct sctp_association *asoc)
7716{
7717	struct sctp_tmit_chunk *chk;
7718
7719	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7720		if (chk->rec.chunk_id.id == SCTP_ECN_ECHO) {
7721			chk->sent = SCTP_DATAGRAM_UNSENT;
7722		}
7723	}
7724}
7725
7726void
7727sctp_move_chunks_from_net(struct sctp_tcb *stcb, struct sctp_nets *net)
7728{
7729	struct sctp_association *asoc;
7730	struct sctp_tmit_chunk *chk;
7731	struct sctp_stream_queue_pending *sp;
7732	unsigned int i;
7733
7734	if (net == NULL) {
7735		return;
7736	}
7737	asoc = &stcb->asoc;
7738	for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
7739		TAILQ_FOREACH(sp, &stcb->asoc.strmout[i].outqueue, next) {
7740			if (sp->net == net) {
7741				sctp_free_remote_addr(sp->net);
7742				sp->net = NULL;
7743			}
7744		}
7745	}
7746	TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
7747		if (chk->whoTo == net) {
7748			sctp_free_remote_addr(chk->whoTo);
7749			chk->whoTo = NULL;
7750		}
7751	}
7752}
7753
7754int
7755sctp_med_chunk_output(struct sctp_inpcb *inp,
7756    struct sctp_tcb *stcb,
7757    struct sctp_association *asoc,
7758    int *num_out,
7759    int *reason_code,
7760    int control_only, int from_where,
7761    struct timeval *now, int *now_filled, int frag_point, int so_locked
7762#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
7763    SCTP_UNUSED
7764#endif
7765)
7766{
7767	/**
7768	 * Ok this is the generic chunk service queue. we must do the
7769	 * following: - Service the stream queue that is next, moving any
7770	 * message (note I must get a complete message i.e. FIRST/MIDDLE and
7771	 * LAST to the out queue in one pass) and assigning TSN's - Check to
7772	 * see if the cwnd/rwnd allows any output, if so we go ahead and
7773	 * fomulate and send the low level chunks. Making sure to combine
7774	 * any control in the control chunk queue also.
7775	 */
7776	struct sctp_nets *net, *start_at, *sack_goes_to = NULL, *old_start_at = NULL;
7777	struct mbuf *outchain, *endoutchain;
7778	struct sctp_tmit_chunk *chk, *nchk;
7779
7780	/* temp arrays for unlinking */
7781	struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
7782	int no_fragmentflg, error;
7783	unsigned int max_rwnd_per_dest, max_send_per_dest;
7784	int one_chunk, hbflag, skip_data_for_this_net;
7785	int asconf, cookie, no_out_cnt;
7786	int bundle_at, ctl_cnt, no_data_chunks, eeor_mode;
7787	unsigned int mtu, r_mtu, omtu, mx_mtu, to_out;
7788	int tsns_sent = 0;
7789	uint32_t auth_offset = 0;
7790	struct sctp_auth_chunk *auth = NULL;
7791	uint16_t auth_keyid;
7792	int override_ok = 1;
7793	int skip_fill_up = 0;
7794	int data_auth_reqd = 0;
7795
7796	/*
7797	 * JRS 5/14/07 - Add flag for whether a heartbeat is sent to the
7798	 * destination.
7799	 */
7800	int quit_now = 0;
7801
7802	*num_out = 0;
7803	*reason_code = 0;
7804	auth_keyid = stcb->asoc.authinfo.active_keyid;
7805	if ((asoc->state & SCTP_STATE_SHUTDOWN_PENDING) ||
7806	    (asoc->state & SCTP_STATE_SHUTDOWN_RECEIVED) ||
7807	    (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR))) {
7808		eeor_mode = 1;
7809	} else {
7810		eeor_mode = 0;
7811	}
7812	ctl_cnt = no_out_cnt = asconf = cookie = 0;
7813	/*
7814	 * First lets prime the pump. For each destination, if there is room
7815	 * in the flight size, attempt to pull an MTU's worth out of the
7816	 * stream queues into the general send_queue
7817	 */
7818#ifdef SCTP_AUDITING_ENABLED
7819	sctp_audit_log(0xC2, 2);
7820#endif
7821	SCTP_TCB_LOCK_ASSERT(stcb);
7822	hbflag = 0;
7823	if ((control_only) || (asoc->stream_reset_outstanding))
7824		no_data_chunks = 1;
7825	else
7826		no_data_chunks = 0;
7827
7828	/* Nothing to possible to send? */
7829	if ((TAILQ_EMPTY(&asoc->control_send_queue) ||
7830	    (asoc->ctrl_queue_cnt == stcb->asoc.ecn_echo_cnt_onq)) &&
7831	    TAILQ_EMPTY(&asoc->asconf_send_queue) &&
7832	    TAILQ_EMPTY(&asoc->send_queue) &&
7833	    stcb->asoc.ss_functions.sctp_ss_is_empty(stcb, asoc)) {
7834nothing_to_send:
7835		*reason_code = 9;
7836		return (0);
7837	}
7838	if (asoc->peers_rwnd == 0) {
7839		/* No room in peers rwnd */
7840		*reason_code = 1;
7841		if (asoc->total_flight > 0) {
7842			/* we are allowed one chunk in flight */
7843			no_data_chunks = 1;
7844		}
7845	}
7846	if (stcb->asoc.ecn_echo_cnt_onq) {
7847		/* Record where a sack goes, if any */
7848		if (no_data_chunks &&
7849		    (asoc->ctrl_queue_cnt == stcb->asoc.ecn_echo_cnt_onq)) {
7850			/* Nothing but ECNe to send - we don't do that */
7851			goto nothing_to_send;
7852		}
7853		TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7854			if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
7855			    (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK)) {
7856				sack_goes_to = chk->whoTo;
7857				break;
7858			}
7859		}
7860	}
7861	max_rwnd_per_dest = ((asoc->peers_rwnd + asoc->total_flight) / asoc->numnets);
7862	if (stcb->sctp_socket)
7863		max_send_per_dest = SCTP_SB_LIMIT_SND(stcb->sctp_socket) / asoc->numnets;
7864	else
7865		max_send_per_dest = 0;
7866	if (no_data_chunks == 0) {
7867		/* How many non-directed chunks are there? */
7868		TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
7869			if (chk->whoTo == NULL) {
7870				/*
7871				 * We already have non-directed chunks on
7872				 * the queue, no need to do a fill-up.
7873				 */
7874				skip_fill_up = 1;
7875				break;
7876			}
7877		}
7878
7879	}
7880	if ((no_data_chunks == 0) &&
7881	    (skip_fill_up == 0) &&
7882	    (!stcb->asoc.ss_functions.sctp_ss_is_empty(stcb, asoc))) {
7883		TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
7884			/*
7885			 * This for loop we are in takes in each net, if
7886			 * its's got space in cwnd and has data sent to it
7887			 * (when CMT is off) then it calls
7888			 * sctp_fill_outqueue for the net. This gets data on
7889			 * the send queue for that network.
7890			 *
7891			 * In sctp_fill_outqueue TSN's are assigned and data is
7892			 * copied out of the stream buffers. Note mostly
7893			 * copy by reference (we hope).
7894			 */
7895			net->window_probe = 0;
7896			if ((net != stcb->asoc.alternate) &&
7897			    ((net->dest_state & SCTP_ADDR_PF) ||
7898			    (!(net->dest_state & SCTP_ADDR_REACHABLE)) ||
7899			    (net->dest_state & SCTP_ADDR_UNCONFIRMED))) {
7900				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
7901					sctp_log_cwnd(stcb, net, 1,
7902					    SCTP_CWND_LOG_FILL_OUTQ_CALLED);
7903				}
7904				continue;
7905			}
7906			if ((stcb->asoc.cc_functions.sctp_cwnd_new_transmission_begins) &&
7907			    (net->flight_size == 0)) {
7908				(*stcb->asoc.cc_functions.sctp_cwnd_new_transmission_begins) (stcb, net);
7909			}
7910			if (net->flight_size >= net->cwnd) {
7911				/* skip this network, no room - can't fill */
7912				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
7913					sctp_log_cwnd(stcb, net, 3,
7914					    SCTP_CWND_LOG_FILL_OUTQ_CALLED);
7915				}
7916				continue;
7917			}
7918			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
7919				sctp_log_cwnd(stcb, net, 4, SCTP_CWND_LOG_FILL_OUTQ_CALLED);
7920			}
7921			sctp_fill_outqueue(stcb, net, frag_point, eeor_mode, &quit_now, so_locked);
7922			if (quit_now) {
7923				/* memory alloc failure */
7924				no_data_chunks = 1;
7925				break;
7926			}
7927		}
7928	}
7929	/* now service each destination and send out what we can for it */
7930	/* Nothing to send? */
7931	if (TAILQ_EMPTY(&asoc->control_send_queue) &&
7932	    TAILQ_EMPTY(&asoc->asconf_send_queue) &&
7933	    TAILQ_EMPTY(&asoc->send_queue)) {
7934		*reason_code = 8;
7935		return (0);
7936	}
7937	if (asoc->sctp_cmt_on_off > 0) {
7938		/* get the last start point */
7939		start_at = asoc->last_net_cmt_send_started;
7940		if (start_at == NULL) {
7941			/* null so to beginning */
7942			start_at = TAILQ_FIRST(&asoc->nets);
7943		} else {
7944			start_at = TAILQ_NEXT(asoc->last_net_cmt_send_started, sctp_next);
7945			if (start_at == NULL) {
7946				start_at = TAILQ_FIRST(&asoc->nets);
7947			}
7948		}
7949		asoc->last_net_cmt_send_started = start_at;
7950	} else {
7951		start_at = TAILQ_FIRST(&asoc->nets);
7952	}
7953	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7954		if (chk->whoTo == NULL) {
7955			if (asoc->alternate) {
7956				chk->whoTo = asoc->alternate;
7957			} else {
7958				chk->whoTo = asoc->primary_destination;
7959			}
7960			atomic_add_int(&chk->whoTo->ref_count, 1);
7961		}
7962	}
7963	old_start_at = NULL;
7964again_one_more_time:
7965	for (net = start_at; net != NULL; net = TAILQ_NEXT(net, sctp_next)) {
7966		/* how much can we send? */
7967		/* SCTPDBG("Examine for sending net:%x\n", (uint32_t)net); */
7968		if (old_start_at && (old_start_at == net)) {
7969			/* through list ocmpletely. */
7970			break;
7971		}
7972		tsns_sent = 0xa;
7973		if (TAILQ_EMPTY(&asoc->control_send_queue) &&
7974		    TAILQ_EMPTY(&asoc->asconf_send_queue) &&
7975		    (net->flight_size >= net->cwnd)) {
7976			/*
7977			 * Nothing on control or asconf and flight is full,
7978			 * we can skip even in the CMT case.
7979			 */
7980			continue;
7981		}
7982		bundle_at = 0;
7983		endoutchain = outchain = NULL;
7984		no_fragmentflg = 1;
7985		one_chunk = 0;
7986		if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
7987			skip_data_for_this_net = 1;
7988		} else {
7989			skip_data_for_this_net = 0;
7990		}
7991		if ((net->ro.ro_rt) && (net->ro.ro_rt->rt_ifp)) {
7992			/*
7993			 * if we have a route and an ifp check to see if we
7994			 * have room to send to this guy
7995			 */
7996			struct ifnet *ifp;
7997
7998			ifp = net->ro.ro_rt->rt_ifp;
7999			if ((ifp->if_snd.ifq_len + 2) >= ifp->if_snd.ifq_maxlen) {
8000				SCTP_STAT_INCR(sctps_ifnomemqueued);
8001				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
8002					sctp_log_maxburst(stcb, net, ifp->if_snd.ifq_len, ifp->if_snd.ifq_maxlen, SCTP_MAX_IFP_APPLIED);
8003				}
8004				continue;
8005			}
8006		}
8007		switch (((struct sockaddr *)&net->ro._l_addr)->sa_family) {
8008#ifdef INET
8009		case AF_INET:
8010			mtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
8011			break;
8012#endif
8013#ifdef INET6
8014		case AF_INET6:
8015			mtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
8016			break;
8017#endif
8018		default:
8019			/* TSNH */
8020			mtu = net->mtu;
8021			break;
8022		}
8023		mx_mtu = mtu;
8024		to_out = 0;
8025		if (mtu > asoc->peers_rwnd) {
8026			if (asoc->total_flight > 0) {
8027				/* We have a packet in flight somewhere */
8028				r_mtu = asoc->peers_rwnd;
8029			} else {
8030				/* We are always allowed to send one MTU out */
8031				one_chunk = 1;
8032				r_mtu = mtu;
8033			}
8034		} else {
8035			r_mtu = mtu;
8036		}
8037		/************************/
8038		/* ASCONF transmission */
8039		/************************/
8040		/* Now first lets go through the asconf queue */
8041		TAILQ_FOREACH_SAFE(chk, &asoc->asconf_send_queue, sctp_next, nchk) {
8042			if (chk->rec.chunk_id.id != SCTP_ASCONF) {
8043				continue;
8044			}
8045			if (chk->whoTo == NULL) {
8046				if (asoc->alternate == NULL) {
8047					if (asoc->primary_destination != net) {
8048						break;
8049					}
8050				} else {
8051					if (asoc->alternate != net) {
8052						break;
8053					}
8054				}
8055			} else {
8056				if (chk->whoTo != net) {
8057					break;
8058				}
8059			}
8060			if (chk->data == NULL) {
8061				break;
8062			}
8063			if (chk->sent != SCTP_DATAGRAM_UNSENT &&
8064			    chk->sent != SCTP_DATAGRAM_RESEND) {
8065				break;
8066			}
8067			/*
8068			 * if no AUTH is yet included and this chunk
8069			 * requires it, make sure to account for it.  We
8070			 * don't apply the size until the AUTH chunk is
8071			 * actually added below in case there is no room for
8072			 * this chunk. NOTE: we overload the use of "omtu"
8073			 * here
8074			 */
8075			if ((auth == NULL) &&
8076			    sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
8077			    stcb->asoc.peer_auth_chunks)) {
8078				omtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
8079			} else
8080				omtu = 0;
8081			/* Here we do NOT factor the r_mtu */
8082			if ((chk->send_size < (int)(mtu - omtu)) ||
8083			    (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
8084				/*
8085				 * We probably should glom the mbuf chain
8086				 * from the chk->data for control but the
8087				 * problem is it becomes yet one more level
8088				 * of tracking to do if for some reason
8089				 * output fails. Then I have got to
8090				 * reconstruct the merged control chain.. el
8091				 * yucko.. for now we take the easy way and
8092				 * do the copy
8093				 */
8094				/*
8095				 * Add an AUTH chunk, if chunk requires it
8096				 * save the offset into the chain for AUTH
8097				 */
8098				if ((auth == NULL) &&
8099				    (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
8100				    stcb->asoc.peer_auth_chunks))) {
8101					outchain = sctp_add_auth_chunk(outchain,
8102					    &endoutchain,
8103					    &auth,
8104					    &auth_offset,
8105					    stcb,
8106					    chk->rec.chunk_id.id);
8107					SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8108				}
8109				outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain,
8110				    (int)chk->rec.chunk_id.can_take_data,
8111				    chk->send_size, chk->copy_by_ref);
8112				if (outchain == NULL) {
8113					*reason_code = 8;
8114					SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
8115					return (ENOMEM);
8116				}
8117				SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8118				/* update our MTU size */
8119				if (mtu > (chk->send_size + omtu))
8120					mtu -= (chk->send_size + omtu);
8121				else
8122					mtu = 0;
8123				to_out += (chk->send_size + omtu);
8124				/* Do clear IP_DF ? */
8125				if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
8126					no_fragmentflg = 0;
8127				}
8128				if (chk->rec.chunk_id.can_take_data)
8129					chk->data = NULL;
8130				/*
8131				 * set hb flag since we can use these for
8132				 * RTO
8133				 */
8134				hbflag = 1;
8135				asconf = 1;
8136				/*
8137				 * should sysctl this: don't bundle data
8138				 * with ASCONF since it requires AUTH
8139				 */
8140				no_data_chunks = 1;
8141				chk->sent = SCTP_DATAGRAM_SENT;
8142				if (chk->whoTo == NULL) {
8143					chk->whoTo = net;
8144					atomic_add_int(&net->ref_count, 1);
8145				}
8146				chk->snd_count++;
8147				if (mtu == 0) {
8148					/*
8149					 * Ok we are out of room but we can
8150					 * output without effecting the
8151					 * flight size since this little guy
8152					 * is a control only packet.
8153					 */
8154					sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
8155					/*
8156					 * do NOT clear the asconf flag as
8157					 * it is used to do appropriate
8158					 * source address selection.
8159					 */
8160					if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
8161					    (struct sockaddr *)&net->ro._l_addr,
8162					    outchain, auth_offset, auth,
8163					    stcb->asoc.authinfo.active_keyid,
8164					    no_fragmentflg, 0, asconf,
8165					    inp->sctp_lport, stcb->rport,
8166					    htonl(stcb->asoc.peer_vtag),
8167					    net->port, NULL,
8168					    0, 0,
8169					    so_locked))) {
8170						if (error == ENOBUFS) {
8171							asoc->ifp_had_enobuf = 1;
8172							SCTP_STAT_INCR(sctps_lowlevelerr);
8173						}
8174						if (from_where == 0) {
8175							SCTP_STAT_INCR(sctps_lowlevelerrusr);
8176						}
8177						if (*now_filled == 0) {
8178							(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8179							*now_filled = 1;
8180							*now = net->last_sent_time;
8181						} else {
8182							net->last_sent_time = *now;
8183						}
8184						hbflag = 0;
8185						/* error, could not output */
8186						if (error == EHOSTUNREACH) {
8187							/*
8188							 * Destination went
8189							 * unreachable
8190							 * during this send
8191							 */
8192							sctp_move_chunks_from_net(stcb, net);
8193						}
8194						*reason_code = 7;
8195						continue;
8196					} else
8197						asoc->ifp_had_enobuf = 0;
8198					if (*now_filled == 0) {
8199						(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8200						*now_filled = 1;
8201						*now = net->last_sent_time;
8202					} else {
8203						net->last_sent_time = *now;
8204					}
8205					hbflag = 0;
8206					/*
8207					 * increase the number we sent, if a
8208					 * cookie is sent we don't tell them
8209					 * any was sent out.
8210					 */
8211					outchain = endoutchain = NULL;
8212					auth = NULL;
8213					auth_offset = 0;
8214					if (!no_out_cnt)
8215						*num_out += ctl_cnt;
8216					/* recalc a clean slate and setup */
8217					switch (net->ro._l_addr.sa.sa_family) {
8218#ifdef INET
8219					case AF_INET:
8220						mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
8221						break;
8222#endif
8223#ifdef INET6
8224					case AF_INET6:
8225						mtu = net->mtu - SCTP_MIN_OVERHEAD;
8226						break;
8227#endif
8228					default:
8229						/* TSNH */
8230						mtu = net->mtu;
8231						break;
8232					}
8233					to_out = 0;
8234					no_fragmentflg = 1;
8235				}
8236			}
8237		}
8238		/************************/
8239		/* Control transmission */
8240		/************************/
8241		/* Now first lets go through the control queue */
8242		TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
8243			if ((sack_goes_to) &&
8244			    (chk->rec.chunk_id.id == SCTP_ECN_ECHO) &&
8245			    (chk->whoTo != sack_goes_to)) {
8246				/*
8247				 * if we have a sack in queue, and we are
8248				 * looking at an ecn echo that is NOT queued
8249				 * to where the sack is going..
8250				 */
8251				if (chk->whoTo == net) {
8252					/*
8253					 * Don't transmit it to where its
8254					 * going (current net)
8255					 */
8256					continue;
8257				} else if (sack_goes_to == net) {
8258					/*
8259					 * But do transmit it to this
8260					 * address
8261					 */
8262					goto skip_net_check;
8263				}
8264			}
8265			if (chk->whoTo == NULL) {
8266				if (asoc->alternate == NULL) {
8267					if (asoc->primary_destination != net) {
8268						continue;
8269					}
8270				} else {
8271					if (asoc->alternate != net) {
8272						continue;
8273					}
8274				}
8275			} else {
8276				if (chk->whoTo != net) {
8277					continue;
8278				}
8279			}
8280	skip_net_check:
8281			if (chk->data == NULL) {
8282				continue;
8283			}
8284			if (chk->sent != SCTP_DATAGRAM_UNSENT) {
8285				/*
8286				 * It must be unsent. Cookies and ASCONF's
8287				 * hang around but there timers will force
8288				 * when marked for resend.
8289				 */
8290				continue;
8291			}
8292			/*
8293			 * if no AUTH is yet included and this chunk
8294			 * requires it, make sure to account for it.  We
8295			 * don't apply the size until the AUTH chunk is
8296			 * actually added below in case there is no room for
8297			 * this chunk. NOTE: we overload the use of "omtu"
8298			 * here
8299			 */
8300			if ((auth == NULL) &&
8301			    sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
8302			    stcb->asoc.peer_auth_chunks)) {
8303				omtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
8304			} else
8305				omtu = 0;
8306			/* Here we do NOT factor the r_mtu */
8307			if ((chk->send_size <= (int)(mtu - omtu)) ||
8308			    (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
8309				/*
8310				 * We probably should glom the mbuf chain
8311				 * from the chk->data for control but the
8312				 * problem is it becomes yet one more level
8313				 * of tracking to do if for some reason
8314				 * output fails. Then I have got to
8315				 * reconstruct the merged control chain.. el
8316				 * yucko.. for now we take the easy way and
8317				 * do the copy
8318				 */
8319				/*
8320				 * Add an AUTH chunk, if chunk requires it
8321				 * save the offset into the chain for AUTH
8322				 */
8323				if ((auth == NULL) &&
8324				    (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
8325				    stcb->asoc.peer_auth_chunks))) {
8326					outchain = sctp_add_auth_chunk(outchain,
8327					    &endoutchain,
8328					    &auth,
8329					    &auth_offset,
8330					    stcb,
8331					    chk->rec.chunk_id.id);
8332					SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8333				}
8334				outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain,
8335				    (int)chk->rec.chunk_id.can_take_data,
8336				    chk->send_size, chk->copy_by_ref);
8337				if (outchain == NULL) {
8338					*reason_code = 8;
8339					SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
8340					return (ENOMEM);
8341				}
8342				SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8343				/* update our MTU size */
8344				if (mtu > (chk->send_size + omtu))
8345					mtu -= (chk->send_size + omtu);
8346				else
8347					mtu = 0;
8348				to_out += (chk->send_size + omtu);
8349				/* Do clear IP_DF ? */
8350				if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
8351					no_fragmentflg = 0;
8352				}
8353				if (chk->rec.chunk_id.can_take_data)
8354					chk->data = NULL;
8355				/* Mark things to be removed, if needed */
8356				if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
8357				    (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK) ||	/* EY */
8358				    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) ||
8359				    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_ACK) ||
8360				    (chk->rec.chunk_id.id == SCTP_SHUTDOWN) ||
8361				    (chk->rec.chunk_id.id == SCTP_SHUTDOWN_ACK) ||
8362				    (chk->rec.chunk_id.id == SCTP_OPERATION_ERROR) ||
8363				    (chk->rec.chunk_id.id == SCTP_COOKIE_ACK) ||
8364				    (chk->rec.chunk_id.id == SCTP_ECN_CWR) ||
8365				    (chk->rec.chunk_id.id == SCTP_PACKET_DROPPED) ||
8366				    (chk->rec.chunk_id.id == SCTP_ASCONF_ACK)) {
8367					if (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) {
8368						hbflag = 1;
8369					}
8370					/* remove these chunks at the end */
8371					if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
8372					    (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK)) {
8373						/* turn off the timer */
8374						if (SCTP_OS_TIMER_PENDING(&stcb->asoc.dack_timer.timer)) {
8375							sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
8376							    inp, stcb, net, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_1);
8377						}
8378					}
8379					ctl_cnt++;
8380				} else {
8381					/*
8382					 * Other chunks, since they have
8383					 * timers running (i.e. COOKIE) we
8384					 * just "trust" that it gets sent or
8385					 * retransmitted.
8386					 */
8387					ctl_cnt++;
8388					if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
8389						cookie = 1;
8390						no_out_cnt = 1;
8391					} else if (chk->rec.chunk_id.id == SCTP_ECN_ECHO) {
8392						/*
8393						 * Increment ecne send count
8394						 * here this means we may be
8395						 * over-zealous in our
8396						 * counting if the send
8397						 * fails, but its the best
8398						 * place to do it (we used
8399						 * to do it in the queue of
8400						 * the chunk, but that did
8401						 * not tell how many times
8402						 * it was sent.
8403						 */
8404						SCTP_STAT_INCR(sctps_sendecne);
8405					}
8406					chk->sent = SCTP_DATAGRAM_SENT;
8407					if (chk->whoTo == NULL) {
8408						chk->whoTo = net;
8409						atomic_add_int(&net->ref_count, 1);
8410					}
8411					chk->snd_count++;
8412				}
8413				if (mtu == 0) {
8414					/*
8415					 * Ok we are out of room but we can
8416					 * output without effecting the
8417					 * flight size since this little guy
8418					 * is a control only packet.
8419					 */
8420					if (asconf) {
8421						sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
8422						/*
8423						 * do NOT clear the asconf
8424						 * flag as it is used to do
8425						 * appropriate source
8426						 * address selection.
8427						 */
8428					}
8429					if (cookie) {
8430						sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
8431						cookie = 0;
8432					}
8433					if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
8434					    (struct sockaddr *)&net->ro._l_addr,
8435					    outchain,
8436					    auth_offset, auth,
8437					    stcb->asoc.authinfo.active_keyid,
8438					    no_fragmentflg, 0, asconf,
8439					    inp->sctp_lport, stcb->rport,
8440					    htonl(stcb->asoc.peer_vtag),
8441					    net->port, NULL,
8442					    0, 0,
8443					    so_locked))) {
8444						if (error == ENOBUFS) {
8445							asoc->ifp_had_enobuf = 1;
8446							SCTP_STAT_INCR(sctps_lowlevelerr);
8447						}
8448						if (from_where == 0) {
8449							SCTP_STAT_INCR(sctps_lowlevelerrusr);
8450						}
8451						/* error, could not output */
8452						if (hbflag) {
8453							if (*now_filled == 0) {
8454								(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8455								*now_filled = 1;
8456								*now = net->last_sent_time;
8457							} else {
8458								net->last_sent_time = *now;
8459							}
8460							hbflag = 0;
8461						}
8462						if (error == EHOSTUNREACH) {
8463							/*
8464							 * Destination went
8465							 * unreachable
8466							 * during this send
8467							 */
8468							sctp_move_chunks_from_net(stcb, net);
8469						}
8470						*reason_code = 7;
8471						continue;
8472					} else
8473						asoc->ifp_had_enobuf = 0;
8474					/* Only HB or ASCONF advances time */
8475					if (hbflag) {
8476						if (*now_filled == 0) {
8477							(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8478							*now_filled = 1;
8479							*now = net->last_sent_time;
8480						} else {
8481							net->last_sent_time = *now;
8482						}
8483						hbflag = 0;
8484					}
8485					/*
8486					 * increase the number we sent, if a
8487					 * cookie is sent we don't tell them
8488					 * any was sent out.
8489					 */
8490					outchain = endoutchain = NULL;
8491					auth = NULL;
8492					auth_offset = 0;
8493					if (!no_out_cnt)
8494						*num_out += ctl_cnt;
8495					/* recalc a clean slate and setup */
8496					switch (net->ro._l_addr.sa.sa_family) {
8497#ifdef INET
8498					case AF_INET:
8499						mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
8500						break;
8501#endif
8502#ifdef INET6
8503					case AF_INET6:
8504						mtu = net->mtu - SCTP_MIN_OVERHEAD;
8505						break;
8506#endif
8507					default:
8508						/* TSNH */
8509						mtu = net->mtu;
8510						break;
8511					}
8512					to_out = 0;
8513					no_fragmentflg = 1;
8514				}
8515			}
8516		}
8517		/* JRI: if dest is in PF state, do not send data to it */
8518		if ((asoc->sctp_cmt_on_off > 0) &&
8519		    (net != stcb->asoc.alternate) &&
8520		    (net->dest_state & SCTP_ADDR_PF)) {
8521			goto no_data_fill;
8522		}
8523		if (net->flight_size >= net->cwnd) {
8524			goto no_data_fill;
8525		}
8526		if ((asoc->sctp_cmt_on_off > 0) &&
8527		    (SCTP_BASE_SYSCTL(sctp_buffer_splitting) & SCTP_RECV_BUFFER_SPLITTING) &&
8528		    (net->flight_size > max_rwnd_per_dest)) {
8529			goto no_data_fill;
8530		}
8531		/*
8532		 * We need a specific accounting for the usage of the send
8533		 * buffer. We also need to check the number of messages per
8534		 * net. For now, this is better than nothing and it disabled
8535		 * by default...
8536		 */
8537		if ((asoc->sctp_cmt_on_off > 0) &&
8538		    (SCTP_BASE_SYSCTL(sctp_buffer_splitting) & SCTP_SEND_BUFFER_SPLITTING) &&
8539		    (max_send_per_dest > 0) &&
8540		    (net->flight_size > max_send_per_dest)) {
8541			goto no_data_fill;
8542		}
8543		/*********************/
8544		/* Data transmission */
8545		/*********************/
8546		/*
8547		 * if AUTH for DATA is required and no AUTH has been added
8548		 * yet, account for this in the mtu now... if no data can be
8549		 * bundled, this adjustment won't matter anyways since the
8550		 * packet will be going out...
8551		 */
8552		data_auth_reqd = sctp_auth_is_required_chunk(SCTP_DATA,
8553		    stcb->asoc.peer_auth_chunks);
8554		if (data_auth_reqd && (auth == NULL)) {
8555			mtu -= sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
8556		}
8557		/* now lets add any data within the MTU constraints */
8558		switch (((struct sockaddr *)&net->ro._l_addr)->sa_family) {
8559#ifdef INET
8560		case AF_INET:
8561			if (net->mtu > (sizeof(struct ip) + sizeof(struct sctphdr)))
8562				omtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
8563			else
8564				omtu = 0;
8565			break;
8566#endif
8567#ifdef INET6
8568		case AF_INET6:
8569			if (net->mtu > (sizeof(struct ip6_hdr) + sizeof(struct sctphdr)))
8570				omtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
8571			else
8572				omtu = 0;
8573			break;
8574#endif
8575		default:
8576			/* TSNH */
8577			omtu = 0;
8578			break;
8579		}
8580		if ((((asoc->state & SCTP_STATE_OPEN) == SCTP_STATE_OPEN) &&
8581		    (skip_data_for_this_net == 0)) ||
8582		    (cookie)) {
8583			TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
8584				if (no_data_chunks) {
8585					/* let only control go out */
8586					*reason_code = 1;
8587					break;
8588				}
8589				if (net->flight_size >= net->cwnd) {
8590					/* skip this net, no room for data */
8591					*reason_code = 2;
8592					break;
8593				}
8594				if ((chk->whoTo != NULL) &&
8595				    (chk->whoTo != net)) {
8596					/* Don't send the chunk on this net */
8597					continue;
8598				}
8599				if (asoc->sctp_cmt_on_off == 0) {
8600					if ((asoc->alternate) &&
8601					    (asoc->alternate != net) &&
8602					    (chk->whoTo == NULL)) {
8603						continue;
8604					} else if ((net != asoc->primary_destination) &&
8605						    (asoc->alternate == NULL) &&
8606					    (chk->whoTo == NULL)) {
8607						continue;
8608					}
8609				}
8610				if ((chk->send_size > omtu) && ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) == 0)) {
8611					/*-
8612					 * strange, we have a chunk that is
8613					 * to big for its destination and
8614					 * yet no fragment ok flag.
8615					 * Something went wrong when the
8616					 * PMTU changed...we did not mark
8617					 * this chunk for some reason?? I
8618					 * will fix it here by letting IP
8619					 * fragment it for now and printing
8620					 * a warning. This really should not
8621					 * happen ...
8622					 */
8623					SCTP_PRINTF("Warning chunk of %d bytes > mtu:%d and yet PMTU disc missed\n",
8624					    chk->send_size, mtu);
8625					chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;
8626				}
8627				if (SCTP_BASE_SYSCTL(sctp_enable_sack_immediately) &&
8628				    ((asoc->state & SCTP_STATE_SHUTDOWN_PENDING) == SCTP_STATE_SHUTDOWN_PENDING)) {
8629					struct sctp_data_chunk *dchkh;
8630
8631					dchkh = mtod(chk->data, struct sctp_data_chunk *);
8632					dchkh->ch.chunk_flags |= SCTP_DATA_SACK_IMMEDIATELY;
8633				}
8634				if (((chk->send_size <= mtu) && (chk->send_size <= r_mtu)) ||
8635				    ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) && (chk->send_size <= asoc->peers_rwnd))) {
8636					/* ok we will add this one */
8637
8638					/*
8639					 * Add an AUTH chunk, if chunk
8640					 * requires it, save the offset into
8641					 * the chain for AUTH
8642					 */
8643					if (data_auth_reqd) {
8644						if (auth == NULL) {
8645							outchain = sctp_add_auth_chunk(outchain,
8646							    &endoutchain,
8647							    &auth,
8648							    &auth_offset,
8649							    stcb,
8650							    SCTP_DATA);
8651							auth_keyid = chk->auth_keyid;
8652							override_ok = 0;
8653							SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8654						} else if (override_ok) {
8655							/*
8656							 * use this data's
8657							 * keyid
8658							 */
8659							auth_keyid = chk->auth_keyid;
8660							override_ok = 0;
8661						} else if (auth_keyid != chk->auth_keyid) {
8662							/*
8663							 * different keyid,
8664							 * so done bundling
8665							 */
8666							break;
8667						}
8668					}
8669					outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain, 0,
8670					    chk->send_size, chk->copy_by_ref);
8671					if (outchain == NULL) {
8672						SCTPDBG(SCTP_DEBUG_OUTPUT3, "No memory?\n");
8673						if (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
8674							sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
8675						}
8676						*reason_code = 3;
8677						SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
8678						return (ENOMEM);
8679					}
8680					/* upate our MTU size */
8681					/* Do clear IP_DF ? */
8682					if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
8683						no_fragmentflg = 0;
8684					}
8685					/* unsigned subtraction of mtu */
8686					if (mtu > chk->send_size)
8687						mtu -= chk->send_size;
8688					else
8689						mtu = 0;
8690					/* unsigned subtraction of r_mtu */
8691					if (r_mtu > chk->send_size)
8692						r_mtu -= chk->send_size;
8693					else
8694						r_mtu = 0;
8695
8696					to_out += chk->send_size;
8697					if ((to_out > mx_mtu) && no_fragmentflg) {
8698#ifdef INVARIANTS
8699						panic("Exceeding mtu of %d out size is %d", mx_mtu, to_out);
8700#else
8701						SCTP_PRINTF("Exceeding mtu of %d out size is %d\n",
8702						    mx_mtu, to_out);
8703#endif
8704					}
8705					chk->window_probe = 0;
8706					data_list[bundle_at++] = chk;
8707					if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
8708						break;
8709					}
8710					if (chk->sent == SCTP_DATAGRAM_UNSENT) {
8711						if ((chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED) == 0) {
8712							SCTP_STAT_INCR_COUNTER64(sctps_outorderchunks);
8713						} else {
8714							SCTP_STAT_INCR_COUNTER64(sctps_outunorderchunks);
8715						}
8716						if (((chk->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) == SCTP_DATA_LAST_FRAG) &&
8717						    ((chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) == 0))
8718							/*
8719							 * Count number of
8720							 * user msg's that
8721							 * were fragmented
8722							 * we do this by
8723							 * counting when we
8724							 * see a LAST
8725							 * fragment only.
8726							 */
8727							SCTP_STAT_INCR_COUNTER64(sctps_fragusrmsgs);
8728					}
8729					if ((mtu == 0) || (r_mtu == 0) || (one_chunk)) {
8730						if ((one_chunk) && (stcb->asoc.total_flight == 0)) {
8731							data_list[0]->window_probe = 1;
8732							net->window_probe = 1;
8733						}
8734						break;
8735					}
8736				} else {
8737					/*
8738					 * Must be sent in order of the
8739					 * TSN's (on a network)
8740					 */
8741					break;
8742				}
8743			}	/* for (chunk gather loop for this net) */
8744		}		/* if asoc.state OPEN */
8745no_data_fill:
8746		/* Is there something to send for this destination? */
8747		if (outchain) {
8748			/* We may need to start a control timer or two */
8749			if (asconf) {
8750				sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp,
8751				    stcb, net);
8752				/*
8753				 * do NOT clear the asconf flag as it is
8754				 * used to do appropriate source address
8755				 * selection.
8756				 */
8757			}
8758			if (cookie) {
8759				sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
8760				cookie = 0;
8761			}
8762			/* must start a send timer if data is being sent */
8763			if (bundle_at && (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer))) {
8764				/*
8765				 * no timer running on this destination
8766				 * restart it.
8767				 */
8768				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
8769			}
8770			/* Now send it, if there is anything to send :> */
8771			if ((error = sctp_lowlevel_chunk_output(inp,
8772			    stcb,
8773			    net,
8774			    (struct sockaddr *)&net->ro._l_addr,
8775			    outchain,
8776			    auth_offset,
8777			    auth,
8778			    auth_keyid,
8779			    no_fragmentflg,
8780			    bundle_at,
8781			    asconf,
8782			    inp->sctp_lport, stcb->rport,
8783			    htonl(stcb->asoc.peer_vtag),
8784			    net->port, NULL,
8785			    0, 0,
8786			    so_locked))) {
8787				/* error, we could not output */
8788				if (error == ENOBUFS) {
8789					SCTP_STAT_INCR(sctps_lowlevelerr);
8790					asoc->ifp_had_enobuf = 1;
8791				}
8792				if (from_where == 0) {
8793					SCTP_STAT_INCR(sctps_lowlevelerrusr);
8794				}
8795				SCTPDBG(SCTP_DEBUG_OUTPUT3, "Gak send error %d\n", error);
8796				if (hbflag) {
8797					if (*now_filled == 0) {
8798						(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8799						*now_filled = 1;
8800						*now = net->last_sent_time;
8801					} else {
8802						net->last_sent_time = *now;
8803					}
8804					hbflag = 0;
8805				}
8806				if (error == EHOSTUNREACH) {
8807					/*
8808					 * Destination went unreachable
8809					 * during this send
8810					 */
8811					sctp_move_chunks_from_net(stcb, net);
8812				}
8813				*reason_code = 6;
8814				/*-
8815				 * I add this line to be paranoid. As far as
8816				 * I can tell the continue, takes us back to
8817				 * the top of the for, but just to make sure
8818				 * I will reset these again here.
8819				 */
8820				ctl_cnt = bundle_at = 0;
8821				continue;	/* This takes us back to the
8822						 * for() for the nets. */
8823			} else {
8824				asoc->ifp_had_enobuf = 0;
8825			}
8826			endoutchain = NULL;
8827			auth = NULL;
8828			auth_offset = 0;
8829			if (bundle_at || hbflag) {
8830				/* For data/asconf and hb set time */
8831				if (*now_filled == 0) {
8832					(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8833					*now_filled = 1;
8834					*now = net->last_sent_time;
8835				} else {
8836					net->last_sent_time = *now;
8837				}
8838			}
8839			if (!no_out_cnt) {
8840				*num_out += (ctl_cnt + bundle_at);
8841			}
8842			if (bundle_at) {
8843				/* setup for a RTO measurement */
8844				tsns_sent = data_list[0]->rec.data.TSN_seq;
8845				/* fill time if not already filled */
8846				if (*now_filled == 0) {
8847					(void)SCTP_GETTIME_TIMEVAL(&asoc->time_last_sent);
8848					*now_filled = 1;
8849					*now = asoc->time_last_sent;
8850				} else {
8851					asoc->time_last_sent = *now;
8852				}
8853				if (net->rto_needed) {
8854					data_list[0]->do_rtt = 1;
8855					net->rto_needed = 0;
8856				}
8857				SCTP_STAT_INCR_BY(sctps_senddata, bundle_at);
8858				sctp_clean_up_datalist(stcb, asoc, data_list, bundle_at, net);
8859			}
8860			if (one_chunk) {
8861				break;
8862			}
8863		}
8864		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
8865			sctp_log_cwnd(stcb, net, tsns_sent, SCTP_CWND_LOG_FROM_SEND);
8866		}
8867	}
8868	if (old_start_at == NULL) {
8869		old_start_at = start_at;
8870		start_at = TAILQ_FIRST(&asoc->nets);
8871		if (old_start_at)
8872			goto again_one_more_time;
8873	}
8874	/*
8875	 * At the end there should be no NON timed chunks hanging on this
8876	 * queue.
8877	 */
8878	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
8879		sctp_log_cwnd(stcb, net, *num_out, SCTP_CWND_LOG_FROM_SEND);
8880	}
8881	if ((*num_out == 0) && (*reason_code == 0)) {
8882		*reason_code = 4;
8883	} else {
8884		*reason_code = 5;
8885	}
8886	sctp_clean_up_ctl(stcb, asoc, so_locked);
8887	return (0);
8888}
8889
8890void
8891sctp_queue_op_err(struct sctp_tcb *stcb, struct mbuf *op_err)
8892{
8893	/*-
8894	 * Prepend a OPERATIONAL_ERROR chunk header and put on the end of
8895	 * the control chunk queue.
8896	 */
8897	struct sctp_chunkhdr *hdr;
8898	struct sctp_tmit_chunk *chk;
8899	struct mbuf *mat;
8900
8901	SCTP_TCB_LOCK_ASSERT(stcb);
8902	sctp_alloc_a_chunk(stcb, chk);
8903	if (chk == NULL) {
8904		/* no memory */
8905		sctp_m_freem(op_err);
8906		return;
8907	}
8908	chk->copy_by_ref = 0;
8909	SCTP_BUF_PREPEND(op_err, sizeof(struct sctp_chunkhdr), M_NOWAIT);
8910	if (op_err == NULL) {
8911		sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
8912		return;
8913	}
8914	chk->send_size = 0;
8915	for (mat = op_err; mat != NULL; mat = SCTP_BUF_NEXT(mat)) {
8916		chk->send_size += SCTP_BUF_LEN(mat);
8917	}
8918	chk->sent = SCTP_DATAGRAM_UNSENT;
8919	chk->snd_count = 0;
8920	chk->asoc = &stcb->asoc;
8921	chk->data = op_err;
8922	chk->whoTo = NULL;
8923	hdr = mtod(op_err, struct sctp_chunkhdr *);
8924	hdr->chunk_type = SCTP_OPERATION_ERROR;
8925	hdr->chunk_flags = 0;
8926	hdr->chunk_length = htons(chk->send_size);
8927	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue,
8928	    chk,
8929	    sctp_next);
8930	chk->asoc->ctrl_queue_cnt++;
8931}
8932
8933int
8934sctp_send_cookie_echo(struct mbuf *m,
8935    int offset,
8936    struct sctp_tcb *stcb,
8937    struct sctp_nets *net)
8938{
8939	/*-
8940	 * pull out the cookie and put it at the front of the control chunk
8941	 * queue.
8942	 */
8943	int at;
8944	struct mbuf *cookie;
8945	struct sctp_paramhdr parm, *phdr;
8946	struct sctp_chunkhdr *hdr;
8947	struct sctp_tmit_chunk *chk;
8948	uint16_t ptype, plen;
8949
8950	/* First find the cookie in the param area */
8951	cookie = NULL;
8952	at = offset + sizeof(struct sctp_init_chunk);
8953
8954	SCTP_TCB_LOCK_ASSERT(stcb);
8955	do {
8956		phdr = sctp_get_next_param(m, at, &parm, sizeof(parm));
8957		if (phdr == NULL) {
8958			return (-3);
8959		}
8960		ptype = ntohs(phdr->param_type);
8961		plen = ntohs(phdr->param_length);
8962		if (ptype == SCTP_STATE_COOKIE) {
8963			int pad;
8964
8965			/* found the cookie */
8966			if ((pad = (plen % 4))) {
8967				plen += 4 - pad;
8968			}
8969			cookie = SCTP_M_COPYM(m, at, plen, M_NOWAIT);
8970			if (cookie == NULL) {
8971				/* No memory */
8972				return (-2);
8973			}
8974#ifdef SCTP_MBUF_LOGGING
8975			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
8976				struct mbuf *mat;
8977
8978				for (mat = cookie; mat; mat = SCTP_BUF_NEXT(mat)) {
8979					if (SCTP_BUF_IS_EXTENDED(mat)) {
8980						sctp_log_mb(mat, SCTP_MBUF_ICOPY);
8981					}
8982				}
8983			}
8984#endif
8985			break;
8986		}
8987		at += SCTP_SIZE32(plen);
8988	} while (phdr);
8989	if (cookie == NULL) {
8990		/* Did not find the cookie */
8991		return (-3);
8992	}
8993	/* ok, we got the cookie lets change it into a cookie echo chunk */
8994
8995	/* first the change from param to cookie */
8996	hdr = mtod(cookie, struct sctp_chunkhdr *);
8997	hdr->chunk_type = SCTP_COOKIE_ECHO;
8998	hdr->chunk_flags = 0;
8999	/* get the chunk stuff now and place it in the FRONT of the queue */
9000	sctp_alloc_a_chunk(stcb, chk);
9001	if (chk == NULL) {
9002		/* no memory */
9003		sctp_m_freem(cookie);
9004		return (-5);
9005	}
9006	chk->copy_by_ref = 0;
9007	chk->rec.chunk_id.id = SCTP_COOKIE_ECHO;
9008	chk->rec.chunk_id.can_take_data = 0;
9009	chk->flags = CHUNK_FLAGS_FRAGMENT_OK;
9010	chk->send_size = plen;
9011	chk->sent = SCTP_DATAGRAM_UNSENT;
9012	chk->snd_count = 0;
9013	chk->asoc = &stcb->asoc;
9014	chk->data = cookie;
9015	chk->whoTo = net;
9016	atomic_add_int(&chk->whoTo->ref_count, 1);
9017	TAILQ_INSERT_HEAD(&chk->asoc->control_send_queue, chk, sctp_next);
9018	chk->asoc->ctrl_queue_cnt++;
9019	return (0);
9020}
9021
9022void
9023sctp_send_heartbeat_ack(struct sctp_tcb *stcb,
9024    struct mbuf *m,
9025    int offset,
9026    int chk_length,
9027    struct sctp_nets *net)
9028{
9029	/*
9030	 * take a HB request and make it into a HB ack and send it.
9031	 */
9032	struct mbuf *outchain;
9033	struct sctp_chunkhdr *chdr;
9034	struct sctp_tmit_chunk *chk;
9035
9036
9037	if (net == NULL)
9038		/* must have a net pointer */
9039		return;
9040
9041	outchain = SCTP_M_COPYM(m, offset, chk_length, M_NOWAIT);
9042	if (outchain == NULL) {
9043		/* gak out of memory */
9044		return;
9045	}
9046#ifdef SCTP_MBUF_LOGGING
9047	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
9048		struct mbuf *mat;
9049
9050		for (mat = outchain; mat; mat = SCTP_BUF_NEXT(mat)) {
9051			if (SCTP_BUF_IS_EXTENDED(mat)) {
9052				sctp_log_mb(mat, SCTP_MBUF_ICOPY);
9053			}
9054		}
9055	}
9056#endif
9057	chdr = mtod(outchain, struct sctp_chunkhdr *);
9058	chdr->chunk_type = SCTP_HEARTBEAT_ACK;
9059	chdr->chunk_flags = 0;
9060	if (chk_length % 4) {
9061		/* need pad */
9062		uint32_t cpthis = 0;
9063		int padlen;
9064
9065		padlen = 4 - (chk_length % 4);
9066		m_copyback(outchain, chk_length, padlen, (caddr_t)&cpthis);
9067	}
9068	sctp_alloc_a_chunk(stcb, chk);
9069	if (chk == NULL) {
9070		/* no memory */
9071		sctp_m_freem(outchain);
9072		return;
9073	}
9074	chk->copy_by_ref = 0;
9075	chk->rec.chunk_id.id = SCTP_HEARTBEAT_ACK;
9076	chk->rec.chunk_id.can_take_data = 1;
9077	chk->flags = 0;
9078	chk->send_size = chk_length;
9079	chk->sent = SCTP_DATAGRAM_UNSENT;
9080	chk->snd_count = 0;
9081	chk->asoc = &stcb->asoc;
9082	chk->data = outchain;
9083	chk->whoTo = net;
9084	atomic_add_int(&chk->whoTo->ref_count, 1);
9085	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
9086	chk->asoc->ctrl_queue_cnt++;
9087}
9088
9089void
9090sctp_send_cookie_ack(struct sctp_tcb *stcb)
9091{
9092	/* formulate and queue a cookie-ack back to sender */
9093	struct mbuf *cookie_ack;
9094	struct sctp_chunkhdr *hdr;
9095	struct sctp_tmit_chunk *chk;
9096
9097	SCTP_TCB_LOCK_ASSERT(stcb);
9098
9099	cookie_ack = sctp_get_mbuf_for_msg(sizeof(struct sctp_chunkhdr), 0, M_NOWAIT, 1, MT_HEADER);
9100	if (cookie_ack == NULL) {
9101		/* no mbuf's */
9102		return;
9103	}
9104	SCTP_BUF_RESV_UF(cookie_ack, SCTP_MIN_OVERHEAD);
9105	sctp_alloc_a_chunk(stcb, chk);
9106	if (chk == NULL) {
9107		/* no memory */
9108		sctp_m_freem(cookie_ack);
9109		return;
9110	}
9111	chk->copy_by_ref = 0;
9112	chk->rec.chunk_id.id = SCTP_COOKIE_ACK;
9113	chk->rec.chunk_id.can_take_data = 1;
9114	chk->flags = 0;
9115	chk->send_size = sizeof(struct sctp_chunkhdr);
9116	chk->sent = SCTP_DATAGRAM_UNSENT;
9117	chk->snd_count = 0;
9118	chk->asoc = &stcb->asoc;
9119	chk->data = cookie_ack;
9120	if (chk->asoc->last_control_chunk_from != NULL) {
9121		chk->whoTo = chk->asoc->last_control_chunk_from;
9122		atomic_add_int(&chk->whoTo->ref_count, 1);
9123	} else {
9124		chk->whoTo = NULL;
9125	}
9126	hdr = mtod(cookie_ack, struct sctp_chunkhdr *);
9127	hdr->chunk_type = SCTP_COOKIE_ACK;
9128	hdr->chunk_flags = 0;
9129	hdr->chunk_length = htons(chk->send_size);
9130	SCTP_BUF_LEN(cookie_ack) = chk->send_size;
9131	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
9132	chk->asoc->ctrl_queue_cnt++;
9133	return;
9134}
9135
9136
9137void
9138sctp_send_shutdown_ack(struct sctp_tcb *stcb, struct sctp_nets *net)
9139{
9140	/* formulate and queue a SHUTDOWN-ACK back to the sender */
9141	struct mbuf *m_shutdown_ack;
9142	struct sctp_shutdown_ack_chunk *ack_cp;
9143	struct sctp_tmit_chunk *chk;
9144
9145	m_shutdown_ack = sctp_get_mbuf_for_msg(sizeof(struct sctp_shutdown_ack_chunk), 0, M_NOWAIT, 1, MT_HEADER);
9146	if (m_shutdown_ack == NULL) {
9147		/* no mbuf's */
9148		return;
9149	}
9150	SCTP_BUF_RESV_UF(m_shutdown_ack, SCTP_MIN_OVERHEAD);
9151	sctp_alloc_a_chunk(stcb, chk);
9152	if (chk == NULL) {
9153		/* no memory */
9154		sctp_m_freem(m_shutdown_ack);
9155		return;
9156	}
9157	chk->copy_by_ref = 0;
9158	chk->rec.chunk_id.id = SCTP_SHUTDOWN_ACK;
9159	chk->rec.chunk_id.can_take_data = 1;
9160	chk->flags = 0;
9161	chk->send_size = sizeof(struct sctp_chunkhdr);
9162	chk->sent = SCTP_DATAGRAM_UNSENT;
9163	chk->snd_count = 0;
9164	chk->flags = 0;
9165	chk->asoc = &stcb->asoc;
9166	chk->data = m_shutdown_ack;
9167	chk->whoTo = net;
9168	if (chk->whoTo) {
9169		atomic_add_int(&chk->whoTo->ref_count, 1);
9170	}
9171	ack_cp = mtod(m_shutdown_ack, struct sctp_shutdown_ack_chunk *);
9172	ack_cp->ch.chunk_type = SCTP_SHUTDOWN_ACK;
9173	ack_cp->ch.chunk_flags = 0;
9174	ack_cp->ch.chunk_length = htons(chk->send_size);
9175	SCTP_BUF_LEN(m_shutdown_ack) = chk->send_size;
9176	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
9177	chk->asoc->ctrl_queue_cnt++;
9178	return;
9179}
9180
9181void
9182sctp_send_shutdown(struct sctp_tcb *stcb, struct sctp_nets *net)
9183{
9184	/* formulate and queue a SHUTDOWN to the sender */
9185	struct mbuf *m_shutdown;
9186	struct sctp_shutdown_chunk *shutdown_cp;
9187	struct sctp_tmit_chunk *chk;
9188
9189	m_shutdown = sctp_get_mbuf_for_msg(sizeof(struct sctp_shutdown_chunk), 0, M_NOWAIT, 1, MT_HEADER);
9190	if (m_shutdown == NULL) {
9191		/* no mbuf's */
9192		return;
9193	}
9194	SCTP_BUF_RESV_UF(m_shutdown, SCTP_MIN_OVERHEAD);
9195	sctp_alloc_a_chunk(stcb, chk);
9196	if (chk == NULL) {
9197		/* no memory */
9198		sctp_m_freem(m_shutdown);
9199		return;
9200	}
9201	chk->copy_by_ref = 0;
9202	chk->rec.chunk_id.id = SCTP_SHUTDOWN;
9203	chk->rec.chunk_id.can_take_data = 1;
9204	chk->flags = 0;
9205	chk->send_size = sizeof(struct sctp_shutdown_chunk);
9206	chk->sent = SCTP_DATAGRAM_UNSENT;
9207	chk->snd_count = 0;
9208	chk->flags = 0;
9209	chk->asoc = &stcb->asoc;
9210	chk->data = m_shutdown;
9211	chk->whoTo = net;
9212	if (chk->whoTo) {
9213		atomic_add_int(&chk->whoTo->ref_count, 1);
9214	}
9215	shutdown_cp = mtod(m_shutdown, struct sctp_shutdown_chunk *);
9216	shutdown_cp->ch.chunk_type = SCTP_SHUTDOWN;
9217	shutdown_cp->ch.chunk_flags = 0;
9218	shutdown_cp->ch.chunk_length = htons(chk->send_size);
9219	shutdown_cp->cumulative_tsn_ack = htonl(stcb->asoc.cumulative_tsn);
9220	SCTP_BUF_LEN(m_shutdown) = chk->send_size;
9221	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
9222	chk->asoc->ctrl_queue_cnt++;
9223	return;
9224}
9225
9226void
9227sctp_send_asconf(struct sctp_tcb *stcb, struct sctp_nets *net, int addr_locked)
9228{
9229	/*
9230	 * formulate and queue an ASCONF to the peer. ASCONF parameters
9231	 * should be queued on the assoc queue.
9232	 */
9233	struct sctp_tmit_chunk *chk;
9234	struct mbuf *m_asconf;
9235	int len;
9236
9237	SCTP_TCB_LOCK_ASSERT(stcb);
9238
9239	if ((!TAILQ_EMPTY(&stcb->asoc.asconf_send_queue)) &&
9240	    (!sctp_is_feature_on(stcb->sctp_ep, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS))) {
9241		/* can't send a new one if there is one in flight already */
9242		return;
9243	}
9244	/* compose an ASCONF chunk, maximum length is PMTU */
9245	m_asconf = sctp_compose_asconf(stcb, &len, addr_locked);
9246	if (m_asconf == NULL) {
9247		return;
9248	}
9249	sctp_alloc_a_chunk(stcb, chk);
9250	if (chk == NULL) {
9251		/* no memory */
9252		sctp_m_freem(m_asconf);
9253		return;
9254	}
9255	chk->copy_by_ref = 0;
9256	chk->rec.chunk_id.id = SCTP_ASCONF;
9257	chk->rec.chunk_id.can_take_data = 0;
9258	chk->flags = CHUNK_FLAGS_FRAGMENT_OK;
9259	chk->data = m_asconf;
9260	chk->send_size = len;
9261	chk->sent = SCTP_DATAGRAM_UNSENT;
9262	chk->snd_count = 0;
9263	chk->asoc = &stcb->asoc;
9264	chk->whoTo = net;
9265	if (chk->whoTo) {
9266		atomic_add_int(&chk->whoTo->ref_count, 1);
9267	}
9268	TAILQ_INSERT_TAIL(&chk->asoc->asconf_send_queue, chk, sctp_next);
9269	chk->asoc->ctrl_queue_cnt++;
9270	return;
9271}
9272
9273void
9274sctp_send_asconf_ack(struct sctp_tcb *stcb)
9275{
9276	/*
9277	 * formulate and queue a asconf-ack back to sender. the asconf-ack
9278	 * must be stored in the tcb.
9279	 */
9280	struct sctp_tmit_chunk *chk;
9281	struct sctp_asconf_ack *ack, *latest_ack;
9282	struct mbuf *m_ack;
9283	struct sctp_nets *net = NULL;
9284
9285	SCTP_TCB_LOCK_ASSERT(stcb);
9286	/* Get the latest ASCONF-ACK */
9287	latest_ack = TAILQ_LAST(&stcb->asoc.asconf_ack_sent, sctp_asconf_ackhead);
9288	if (latest_ack == NULL) {
9289		return;
9290	}
9291	if (latest_ack->last_sent_to != NULL &&
9292	    latest_ack->last_sent_to == stcb->asoc.last_control_chunk_from) {
9293		/* we're doing a retransmission */
9294		net = sctp_find_alternate_net(stcb, stcb->asoc.last_control_chunk_from, 0);
9295		if (net == NULL) {
9296			/* no alternate */
9297			if (stcb->asoc.last_control_chunk_from == NULL) {
9298				if (stcb->asoc.alternate) {
9299					net = stcb->asoc.alternate;
9300				} else {
9301					net = stcb->asoc.primary_destination;
9302				}
9303			} else {
9304				net = stcb->asoc.last_control_chunk_from;
9305			}
9306		}
9307	} else {
9308		/* normal case */
9309		if (stcb->asoc.last_control_chunk_from == NULL) {
9310			if (stcb->asoc.alternate) {
9311				net = stcb->asoc.alternate;
9312			} else {
9313				net = stcb->asoc.primary_destination;
9314			}
9315		} else {
9316			net = stcb->asoc.last_control_chunk_from;
9317		}
9318	}
9319	latest_ack->last_sent_to = net;
9320
9321	TAILQ_FOREACH(ack, &stcb->asoc.asconf_ack_sent, next) {
9322		if (ack->data == NULL) {
9323			continue;
9324		}
9325		/* copy the asconf_ack */
9326		m_ack = SCTP_M_COPYM(ack->data, 0, M_COPYALL, M_NOWAIT);
9327		if (m_ack == NULL) {
9328			/* couldn't copy it */
9329			return;
9330		}
9331#ifdef SCTP_MBUF_LOGGING
9332		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
9333			struct mbuf *mat;
9334
9335			for (mat = m_ack; mat; mat = SCTP_BUF_NEXT(mat)) {
9336				if (SCTP_BUF_IS_EXTENDED(mat)) {
9337					sctp_log_mb(mat, SCTP_MBUF_ICOPY);
9338				}
9339			}
9340		}
9341#endif
9342
9343		sctp_alloc_a_chunk(stcb, chk);
9344		if (chk == NULL) {
9345			/* no memory */
9346			if (m_ack)
9347				sctp_m_freem(m_ack);
9348			return;
9349		}
9350		chk->copy_by_ref = 0;
9351		chk->rec.chunk_id.id = SCTP_ASCONF_ACK;
9352		chk->rec.chunk_id.can_take_data = 1;
9353		chk->flags = CHUNK_FLAGS_FRAGMENT_OK;
9354		chk->whoTo = net;
9355		if (chk->whoTo) {
9356			atomic_add_int(&chk->whoTo->ref_count, 1);
9357		}
9358		chk->data = m_ack;
9359		chk->send_size = 0;
9360		/* Get size */
9361		chk->send_size = ack->len;
9362		chk->sent = SCTP_DATAGRAM_UNSENT;
9363		chk->snd_count = 0;
9364		chk->asoc = &stcb->asoc;
9365
9366		TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
9367		chk->asoc->ctrl_queue_cnt++;
9368	}
9369	return;
9370}
9371
9372
9373static int
9374sctp_chunk_retransmission(struct sctp_inpcb *inp,
9375    struct sctp_tcb *stcb,
9376    struct sctp_association *asoc,
9377    int *cnt_out, struct timeval *now, int *now_filled, int *fr_done, int so_locked
9378#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
9379    SCTP_UNUSED
9380#endif
9381)
9382{
9383	/*-
9384	 * send out one MTU of retransmission. If fast_retransmit is
9385	 * happening we ignore the cwnd. Otherwise we obey the cwnd and
9386	 * rwnd. For a Cookie or Asconf in the control chunk queue we
9387	 * retransmit them by themselves.
9388	 *
9389	 * For data chunks we will pick out the lowest TSN's in the sent_queue
9390	 * marked for resend and bundle them all together (up to a MTU of
9391	 * destination). The address to send to should have been
9392	 * selected/changed where the retransmission was marked (i.e. in FR
9393	 * or t3-timeout routines).
9394	 */
9395	struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
9396	struct sctp_tmit_chunk *chk, *fwd;
9397	struct mbuf *m, *endofchain;
9398	struct sctp_nets *net = NULL;
9399	uint32_t tsns_sent = 0;
9400	int no_fragmentflg, bundle_at, cnt_thru;
9401	unsigned int mtu;
9402	int error, i, one_chunk, fwd_tsn, ctl_cnt, tmr_started;
9403	struct sctp_auth_chunk *auth = NULL;
9404	uint32_t auth_offset = 0;
9405	uint16_t auth_keyid;
9406	int override_ok = 1;
9407	int data_auth_reqd = 0;
9408	uint32_t dmtu = 0;
9409
9410	SCTP_TCB_LOCK_ASSERT(stcb);
9411	tmr_started = ctl_cnt = bundle_at = error = 0;
9412	no_fragmentflg = 1;
9413	fwd_tsn = 0;
9414	*cnt_out = 0;
9415	fwd = NULL;
9416	endofchain = m = NULL;
9417	auth_keyid = stcb->asoc.authinfo.active_keyid;
9418#ifdef SCTP_AUDITING_ENABLED
9419	sctp_audit_log(0xC3, 1);
9420#endif
9421	if ((TAILQ_EMPTY(&asoc->sent_queue)) &&
9422	    (TAILQ_EMPTY(&asoc->control_send_queue))) {
9423		SCTPDBG(SCTP_DEBUG_OUTPUT1, "SCTP hits empty queue with cnt set to %d?\n",
9424		    asoc->sent_queue_retran_cnt);
9425		asoc->sent_queue_cnt = 0;
9426		asoc->sent_queue_cnt_removeable = 0;
9427		/* send back 0/0 so we enter normal transmission */
9428		*cnt_out = 0;
9429		return (0);
9430	}
9431	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
9432		if ((chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) ||
9433		    (chk->rec.chunk_id.id == SCTP_STREAM_RESET) ||
9434		    (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN)) {
9435			if (chk->sent != SCTP_DATAGRAM_RESEND) {
9436				continue;
9437			}
9438			if (chk->rec.chunk_id.id == SCTP_STREAM_RESET) {
9439				if (chk != asoc->str_reset) {
9440					/*
9441					 * not eligible for retran if its
9442					 * not ours
9443					 */
9444					continue;
9445				}
9446			}
9447			ctl_cnt++;
9448			if (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) {
9449				fwd_tsn = 1;
9450			}
9451			/*
9452			 * Add an AUTH chunk, if chunk requires it save the
9453			 * offset into the chain for AUTH
9454			 */
9455			if ((auth == NULL) &&
9456			    (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
9457			    stcb->asoc.peer_auth_chunks))) {
9458				m = sctp_add_auth_chunk(m, &endofchain,
9459				    &auth, &auth_offset,
9460				    stcb,
9461				    chk->rec.chunk_id.id);
9462				SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9463			}
9464			m = sctp_copy_mbufchain(chk->data, m, &endofchain, 0, chk->send_size, chk->copy_by_ref);
9465			break;
9466		}
9467	}
9468	one_chunk = 0;
9469	cnt_thru = 0;
9470	/* do we have control chunks to retransmit? */
9471	if (m != NULL) {
9472		/* Start a timer no matter if we suceed or fail */
9473		if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
9474			sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, chk->whoTo);
9475		} else if (chk->rec.chunk_id.id == SCTP_ASCONF)
9476			sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, chk->whoTo);
9477		chk->snd_count++;	/* update our count */
9478		if ((error = sctp_lowlevel_chunk_output(inp, stcb, chk->whoTo,
9479		    (struct sockaddr *)&chk->whoTo->ro._l_addr, m,
9480		    auth_offset, auth, stcb->asoc.authinfo.active_keyid,
9481		    no_fragmentflg, 0, 0,
9482		    inp->sctp_lport, stcb->rport, htonl(stcb->asoc.peer_vtag),
9483		    chk->whoTo->port, NULL,
9484		    0, 0,
9485		    so_locked))) {
9486			SCTP_STAT_INCR(sctps_lowlevelerr);
9487			return (error);
9488		}
9489		endofchain = NULL;
9490		auth = NULL;
9491		auth_offset = 0;
9492		/*
9493		 * We don't want to mark the net->sent time here since this
9494		 * we use this for HB and retrans cannot measure RTT
9495		 */
9496		/* (void)SCTP_GETTIME_TIMEVAL(&chk->whoTo->last_sent_time); */
9497		*cnt_out += 1;
9498		chk->sent = SCTP_DATAGRAM_SENT;
9499		sctp_ucount_decr(stcb->asoc.sent_queue_retran_cnt);
9500		if (fwd_tsn == 0) {
9501			return (0);
9502		} else {
9503			/* Clean up the fwd-tsn list */
9504			sctp_clean_up_ctl(stcb, asoc, so_locked);
9505			return (0);
9506		}
9507	}
9508	/*
9509	 * Ok, it is just data retransmission we need to do or that and a
9510	 * fwd-tsn with it all.
9511	 */
9512	if (TAILQ_EMPTY(&asoc->sent_queue)) {
9513		return (SCTP_RETRAN_DONE);
9514	}
9515	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED) ||
9516	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT)) {
9517		/* not yet open, resend the cookie and that is it */
9518		return (1);
9519	}
9520#ifdef SCTP_AUDITING_ENABLED
9521	sctp_auditing(20, inp, stcb, NULL);
9522#endif
9523	data_auth_reqd = sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks);
9524	TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
9525		if (chk->sent != SCTP_DATAGRAM_RESEND) {
9526			/* No, not sent to this net or not ready for rtx */
9527			continue;
9528		}
9529		if (chk->data == NULL) {
9530			SCTP_PRINTF("TSN:%x chk->snd_count:%d chk->sent:%d can't retran - no data\n",
9531			    chk->rec.data.TSN_seq, chk->snd_count, chk->sent);
9532			continue;
9533		}
9534		if ((SCTP_BASE_SYSCTL(sctp_max_retran_chunk)) &&
9535		    (chk->snd_count >= SCTP_BASE_SYSCTL(sctp_max_retran_chunk))) {
9536			/* Gak, we have exceeded max unlucky retran, abort! */
9537			SCTP_PRINTF("Gak, chk->snd_count:%d >= max:%d - send abort\n",
9538			    chk->snd_count,
9539			    SCTP_BASE_SYSCTL(sctp_max_retran_chunk));
9540			atomic_add_int(&stcb->asoc.refcnt, 1);
9541			sctp_abort_an_association(stcb->sctp_ep, stcb, NULL, so_locked);
9542			SCTP_TCB_LOCK(stcb);
9543			atomic_subtract_int(&stcb->asoc.refcnt, 1);
9544			return (SCTP_RETRAN_EXIT);
9545		}
9546		/* pick up the net */
9547		net = chk->whoTo;
9548		switch (net->ro._l_addr.sa.sa_family) {
9549#ifdef INET
9550		case AF_INET:
9551			mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
9552			break;
9553#endif
9554#ifdef INET6
9555		case AF_INET6:
9556			mtu = net->mtu - SCTP_MIN_OVERHEAD;
9557			break;
9558#endif
9559		default:
9560			/* TSNH */
9561			mtu = net->mtu;
9562			break;
9563		}
9564
9565		if ((asoc->peers_rwnd < mtu) && (asoc->total_flight > 0)) {
9566			/* No room in peers rwnd */
9567			uint32_t tsn;
9568
9569			tsn = asoc->last_acked_seq + 1;
9570			if (tsn == chk->rec.data.TSN_seq) {
9571				/*
9572				 * we make a special exception for this
9573				 * case. The peer has no rwnd but is missing
9574				 * the lowest chunk.. which is probably what
9575				 * is holding up the rwnd.
9576				 */
9577				goto one_chunk_around;
9578			}
9579			return (1);
9580		}
9581one_chunk_around:
9582		if (asoc->peers_rwnd < mtu) {
9583			one_chunk = 1;
9584			if ((asoc->peers_rwnd == 0) &&
9585			    (asoc->total_flight == 0)) {
9586				chk->window_probe = 1;
9587				chk->whoTo->window_probe = 1;
9588			}
9589		}
9590#ifdef SCTP_AUDITING_ENABLED
9591		sctp_audit_log(0xC3, 2);
9592#endif
9593		bundle_at = 0;
9594		m = NULL;
9595		net->fast_retran_ip = 0;
9596		if (chk->rec.data.doing_fast_retransmit == 0) {
9597			/*
9598			 * if no FR in progress skip destination that have
9599			 * flight_size > cwnd.
9600			 */
9601			if (net->flight_size >= net->cwnd) {
9602				continue;
9603			}
9604		} else {
9605			/*
9606			 * Mark the destination net to have FR recovery
9607			 * limits put on it.
9608			 */
9609			*fr_done = 1;
9610			net->fast_retran_ip = 1;
9611		}
9612
9613		/*
9614		 * if no AUTH is yet included and this chunk requires it,
9615		 * make sure to account for it.  We don't apply the size
9616		 * until the AUTH chunk is actually added below in case
9617		 * there is no room for this chunk.
9618		 */
9619		if (data_auth_reqd && (auth == NULL)) {
9620			dmtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
9621		} else
9622			dmtu = 0;
9623
9624		if ((chk->send_size <= (mtu - dmtu)) ||
9625		    (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
9626			/* ok we will add this one */
9627			if (data_auth_reqd) {
9628				if (auth == NULL) {
9629					m = sctp_add_auth_chunk(m,
9630					    &endofchain,
9631					    &auth,
9632					    &auth_offset,
9633					    stcb,
9634					    SCTP_DATA);
9635					auth_keyid = chk->auth_keyid;
9636					override_ok = 0;
9637					SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9638				} else if (override_ok) {
9639					auth_keyid = chk->auth_keyid;
9640					override_ok = 0;
9641				} else if (chk->auth_keyid != auth_keyid) {
9642					/* different keyid, so done bundling */
9643					break;
9644				}
9645			}
9646			m = sctp_copy_mbufchain(chk->data, m, &endofchain, 0, chk->send_size, chk->copy_by_ref);
9647			if (m == NULL) {
9648				SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
9649				return (ENOMEM);
9650			}
9651			/* Do clear IP_DF ? */
9652			if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
9653				no_fragmentflg = 0;
9654			}
9655			/* upate our MTU size */
9656			if (mtu > (chk->send_size + dmtu))
9657				mtu -= (chk->send_size + dmtu);
9658			else
9659				mtu = 0;
9660			data_list[bundle_at++] = chk;
9661			if (one_chunk && (asoc->total_flight <= 0)) {
9662				SCTP_STAT_INCR(sctps_windowprobed);
9663			}
9664		}
9665		if (one_chunk == 0) {
9666			/*
9667			 * now are there anymore forward from chk to pick
9668			 * up?
9669			 */
9670			for (fwd = TAILQ_NEXT(chk, sctp_next); fwd != NULL; fwd = TAILQ_NEXT(fwd, sctp_next)) {
9671				if (fwd->sent != SCTP_DATAGRAM_RESEND) {
9672					/* Nope, not for retran */
9673					continue;
9674				}
9675				if (fwd->whoTo != net) {
9676					/* Nope, not the net in question */
9677					continue;
9678				}
9679				if (data_auth_reqd && (auth == NULL)) {
9680					dmtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
9681				} else
9682					dmtu = 0;
9683				if (fwd->send_size <= (mtu - dmtu)) {
9684					if (data_auth_reqd) {
9685						if (auth == NULL) {
9686							m = sctp_add_auth_chunk(m,
9687							    &endofchain,
9688							    &auth,
9689							    &auth_offset,
9690							    stcb,
9691							    SCTP_DATA);
9692							auth_keyid = fwd->auth_keyid;
9693							override_ok = 0;
9694							SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9695						} else if (override_ok) {
9696							auth_keyid = fwd->auth_keyid;
9697							override_ok = 0;
9698						} else if (fwd->auth_keyid != auth_keyid) {
9699							/*
9700							 * different keyid,
9701							 * so done bundling
9702							 */
9703							break;
9704						}
9705					}
9706					m = sctp_copy_mbufchain(fwd->data, m, &endofchain, 0, fwd->send_size, fwd->copy_by_ref);
9707					if (m == NULL) {
9708						SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
9709						return (ENOMEM);
9710					}
9711					/* Do clear IP_DF ? */
9712					if (fwd->flags & CHUNK_FLAGS_FRAGMENT_OK) {
9713						no_fragmentflg = 0;
9714					}
9715					/* upate our MTU size */
9716					if (mtu > (fwd->send_size + dmtu))
9717						mtu -= (fwd->send_size + dmtu);
9718					else
9719						mtu = 0;
9720					data_list[bundle_at++] = fwd;
9721					if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
9722						break;
9723					}
9724				} else {
9725					/* can't fit so we are done */
9726					break;
9727				}
9728			}
9729		}
9730		/* Is there something to send for this destination? */
9731		if (m) {
9732			/*
9733			 * No matter if we fail/or suceed we should start a
9734			 * timer. A failure is like a lost IP packet :-)
9735			 */
9736			if (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
9737				/*
9738				 * no timer running on this destination
9739				 * restart it.
9740				 */
9741				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
9742				tmr_started = 1;
9743			}
9744			/* Now lets send it, if there is anything to send :> */
9745			if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
9746			    (struct sockaddr *)&net->ro._l_addr, m,
9747			    auth_offset, auth, auth_keyid,
9748			    no_fragmentflg, 0, 0,
9749			    inp->sctp_lport, stcb->rport, htonl(stcb->asoc.peer_vtag),
9750			    net->port, NULL,
9751			    0, 0,
9752			    so_locked))) {
9753				/* error, we could not output */
9754				SCTP_STAT_INCR(sctps_lowlevelerr);
9755				return (error);
9756			}
9757			endofchain = NULL;
9758			auth = NULL;
9759			auth_offset = 0;
9760			/* For HB's */
9761			/*
9762			 * We don't want to mark the net->sent time here
9763			 * since this we use this for HB and retrans cannot
9764			 * measure RTT
9765			 */
9766			/* (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time); */
9767
9768			/* For auto-close */
9769			cnt_thru++;
9770			if (*now_filled == 0) {
9771				(void)SCTP_GETTIME_TIMEVAL(&asoc->time_last_sent);
9772				*now = asoc->time_last_sent;
9773				*now_filled = 1;
9774			} else {
9775				asoc->time_last_sent = *now;
9776			}
9777			*cnt_out += bundle_at;
9778#ifdef SCTP_AUDITING_ENABLED
9779			sctp_audit_log(0xC4, bundle_at);
9780#endif
9781			if (bundle_at) {
9782				tsns_sent = data_list[0]->rec.data.TSN_seq;
9783			}
9784			for (i = 0; i < bundle_at; i++) {
9785				SCTP_STAT_INCR(sctps_sendretransdata);
9786				data_list[i]->sent = SCTP_DATAGRAM_SENT;
9787				/*
9788				 * When we have a revoked data, and we
9789				 * retransmit it, then we clear the revoked
9790				 * flag since this flag dictates if we
9791				 * subtracted from the fs
9792				 */
9793				if (data_list[i]->rec.data.chunk_was_revoked) {
9794					/* Deflate the cwnd */
9795					data_list[i]->whoTo->cwnd -= data_list[i]->book_size;
9796					data_list[i]->rec.data.chunk_was_revoked = 0;
9797				}
9798				data_list[i]->snd_count++;
9799				sctp_ucount_decr(asoc->sent_queue_retran_cnt);
9800				/* record the time */
9801				data_list[i]->sent_rcv_time = asoc->time_last_sent;
9802				if (data_list[i]->book_size_scale) {
9803					/*
9804					 * need to double the book size on
9805					 * this one
9806					 */
9807					data_list[i]->book_size_scale = 0;
9808					/*
9809					 * Since we double the booksize, we
9810					 * must also double the output queue
9811					 * size, since this get shrunk when
9812					 * we free by this amount.
9813					 */
9814					atomic_add_int(&((asoc)->total_output_queue_size), data_list[i]->book_size);
9815					data_list[i]->book_size *= 2;
9816
9817
9818				} else {
9819					if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_RWND_ENABLE) {
9820						sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
9821						    asoc->peers_rwnd, data_list[i]->send_size, SCTP_BASE_SYSCTL(sctp_peer_chunk_oh));
9822					}
9823					asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
9824					    (uint32_t) (data_list[i]->send_size +
9825					    SCTP_BASE_SYSCTL(sctp_peer_chunk_oh)));
9826				}
9827				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_FLIGHT_LOGGING_ENABLE) {
9828					sctp_misc_ints(SCTP_FLIGHT_LOG_UP_RSND,
9829					    data_list[i]->whoTo->flight_size,
9830					    data_list[i]->book_size,
9831					    (uintptr_t) data_list[i]->whoTo,
9832					    data_list[i]->rec.data.TSN_seq);
9833				}
9834				sctp_flight_size_increase(data_list[i]);
9835				sctp_total_flight_increase(stcb, data_list[i]);
9836				if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
9837					/* SWS sender side engages */
9838					asoc->peers_rwnd = 0;
9839				}
9840				if ((i == 0) &&
9841				    (data_list[i]->rec.data.doing_fast_retransmit)) {
9842					SCTP_STAT_INCR(sctps_sendfastretrans);
9843					if ((data_list[i] == TAILQ_FIRST(&asoc->sent_queue)) &&
9844					    (tmr_started == 0)) {
9845						/*-
9846						 * ok we just fast-retrans'd
9847						 * the lowest TSN, i.e the
9848						 * first on the list. In
9849						 * this case we want to give
9850						 * some more time to get a
9851						 * SACK back without a
9852						 * t3-expiring.
9853						 */
9854						sctp_timer_stop(SCTP_TIMER_TYPE_SEND, inp, stcb, net,
9855						    SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_4);
9856						sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
9857					}
9858				}
9859			}
9860			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
9861				sctp_log_cwnd(stcb, net, tsns_sent, SCTP_CWND_LOG_FROM_RESEND);
9862			}
9863#ifdef SCTP_AUDITING_ENABLED
9864			sctp_auditing(21, inp, stcb, NULL);
9865#endif
9866		} else {
9867			/* None will fit */
9868			return (1);
9869		}
9870		if (asoc->sent_queue_retran_cnt <= 0) {
9871			/* all done we have no more to retran */
9872			asoc->sent_queue_retran_cnt = 0;
9873			break;
9874		}
9875		if (one_chunk) {
9876			/* No more room in rwnd */
9877			return (1);
9878		}
9879		/* stop the for loop here. we sent out a packet */
9880		break;
9881	}
9882	return (0);
9883}
9884
9885static void
9886sctp_timer_validation(struct sctp_inpcb *inp,
9887    struct sctp_tcb *stcb,
9888    struct sctp_association *asoc)
9889{
9890	struct sctp_nets *net;
9891
9892	/* Validate that a timer is running somewhere */
9893	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
9894		if (SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
9895			/* Here is a timer */
9896			return;
9897		}
9898	}
9899	SCTP_TCB_LOCK_ASSERT(stcb);
9900	/* Gak, we did not have a timer somewhere */
9901	SCTPDBG(SCTP_DEBUG_OUTPUT3, "Deadlock avoided starting timer on a dest at retran\n");
9902	if (asoc->alternate) {
9903		sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, asoc->alternate);
9904	} else {
9905		sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, asoc->primary_destination);
9906	}
9907	return;
9908}
9909
9910void
9911sctp_chunk_output(struct sctp_inpcb *inp,
9912    struct sctp_tcb *stcb,
9913    int from_where,
9914    int so_locked
9915#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
9916    SCTP_UNUSED
9917#endif
9918)
9919{
9920	/*-
9921	 * Ok this is the generic chunk service queue. we must do the
9922	 * following:
9923	 * - See if there are retransmits pending, if so we must
9924	 *   do these first.
9925	 * - Service the stream queue that is next, moving any
9926	 *   message (note I must get a complete message i.e.
9927	 *   FIRST/MIDDLE and LAST to the out queue in one pass) and assigning
9928	 *   TSN's
9929	 * - Check to see if the cwnd/rwnd allows any output, if so we
9930	 *   go ahead and fomulate and send the low level chunks. Making sure
9931	 *   to combine any control in the control chunk queue also.
9932	 */
9933	struct sctp_association *asoc;
9934	struct sctp_nets *net;
9935	int error = 0, num_out, tot_out = 0, ret = 0, reason_code;
9936	unsigned int burst_cnt = 0;
9937	struct timeval now;
9938	int now_filled = 0;
9939	int nagle_on;
9940	int frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
9941	int un_sent = 0;
9942	int fr_done;
9943	unsigned int tot_frs = 0;
9944
9945	asoc = &stcb->asoc;
9946	/* The Nagle algorithm is only applied when handling a send call. */
9947	if (from_where == SCTP_OUTPUT_FROM_USR_SEND) {
9948		if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NODELAY)) {
9949			nagle_on = 0;
9950		} else {
9951			nagle_on = 1;
9952		}
9953	} else {
9954		nagle_on = 0;
9955	}
9956	SCTP_TCB_LOCK_ASSERT(stcb);
9957
9958	un_sent = (stcb->asoc.total_output_queue_size - stcb->asoc.total_flight);
9959
9960	if ((un_sent <= 0) &&
9961	    (TAILQ_EMPTY(&asoc->control_send_queue)) &&
9962	    (TAILQ_EMPTY(&asoc->asconf_send_queue)) &&
9963	    (asoc->sent_queue_retran_cnt == 0)) {
9964		/* Nothing to do unless there is something to be sent left */
9965		return;
9966	}
9967	/*
9968	 * Do we have something to send, data or control AND a sack timer
9969	 * running, if so piggy-back the sack.
9970	 */
9971	if (SCTP_OS_TIMER_PENDING(&stcb->asoc.dack_timer.timer)) {
9972		sctp_send_sack(stcb, so_locked);
9973		(void)SCTP_OS_TIMER_STOP(&stcb->asoc.dack_timer.timer);
9974	}
9975	while (asoc->sent_queue_retran_cnt) {
9976		/*-
9977		 * Ok, it is retransmission time only, we send out only ONE
9978		 * packet with a single call off to the retran code.
9979		 */
9980		if (from_where == SCTP_OUTPUT_FROM_COOKIE_ACK) {
9981			/*-
9982			 * Special hook for handling cookiess discarded
9983			 * by peer that carried data. Send cookie-ack only
9984			 * and then the next call with get the retran's.
9985			 */
9986			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1,
9987			    from_where,
9988			    &now, &now_filled, frag_point, so_locked);
9989			return;
9990		} else if (from_where != SCTP_OUTPUT_FROM_HB_TMR) {
9991			/* if its not from a HB then do it */
9992			fr_done = 0;
9993			ret = sctp_chunk_retransmission(inp, stcb, asoc, &num_out, &now, &now_filled, &fr_done, so_locked);
9994			if (fr_done) {
9995				tot_frs++;
9996			}
9997		} else {
9998			/*
9999			 * its from any other place, we don't allow retran
10000			 * output (only control)
10001			 */
10002			ret = 1;
10003		}
10004		if (ret > 0) {
10005			/* Can't send anymore */
10006			/*-
10007			 * now lets push out control by calling med-level
10008			 * output once. this assures that we WILL send HB's
10009			 * if queued too.
10010			 */
10011			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1,
10012			    from_where,
10013			    &now, &now_filled, frag_point, so_locked);
10014#ifdef SCTP_AUDITING_ENABLED
10015			sctp_auditing(8, inp, stcb, NULL);
10016#endif
10017			sctp_timer_validation(inp, stcb, asoc);
10018			return;
10019		}
10020		if (ret < 0) {
10021			/*-
10022			 * The count was off.. retran is not happening so do
10023			 * the normal retransmission.
10024			 */
10025#ifdef SCTP_AUDITING_ENABLED
10026			sctp_auditing(9, inp, stcb, NULL);
10027#endif
10028			if (ret == SCTP_RETRAN_EXIT) {
10029				return;
10030			}
10031			break;
10032		}
10033		if (from_where == SCTP_OUTPUT_FROM_T3) {
10034			/* Only one transmission allowed out of a timeout */
10035#ifdef SCTP_AUDITING_ENABLED
10036			sctp_auditing(10, inp, stcb, NULL);
10037#endif
10038			/* Push out any control */
10039			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1, from_where,
10040			    &now, &now_filled, frag_point, so_locked);
10041			return;
10042		}
10043		if ((asoc->fr_max_burst > 0) && (tot_frs >= asoc->fr_max_burst)) {
10044			/* Hit FR burst limit */
10045			return;
10046		}
10047		if ((num_out == 0) && (ret == 0)) {
10048			/* No more retrans to send */
10049			break;
10050		}
10051	}
10052#ifdef SCTP_AUDITING_ENABLED
10053	sctp_auditing(12, inp, stcb, NULL);
10054#endif
10055	/* Check for bad destinations, if they exist move chunks around. */
10056	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
10057		if (!(net->dest_state & SCTP_ADDR_REACHABLE)) {
10058			/*-
10059			 * if possible move things off of this address we
10060			 * still may send below due to the dormant state but
10061			 * we try to find an alternate address to send to
10062			 * and if we have one we move all queued data on the
10063			 * out wheel to this alternate address.
10064			 */
10065			if (net->ref_count > 1)
10066				sctp_move_chunks_from_net(stcb, net);
10067		} else {
10068			/*-
10069			 * if ((asoc->sat_network) || (net->addr_is_local))
10070			 * { burst_limit = asoc->max_burst *
10071			 * SCTP_SAT_NETWORK_BURST_INCR; }
10072			 */
10073			if (asoc->max_burst > 0) {
10074				if (SCTP_BASE_SYSCTL(sctp_use_cwnd_based_maxburst)) {
10075					if ((net->flight_size + (asoc->max_burst * net->mtu)) < net->cwnd) {
10076						/*
10077						 * JRS - Use the congestion
10078						 * control given in the
10079						 * congestion control module
10080						 */
10081						asoc->cc_functions.sctp_cwnd_update_after_output(stcb, net, asoc->max_burst);
10082						if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
10083							sctp_log_maxburst(stcb, net, 0, asoc->max_burst, SCTP_MAX_BURST_APPLIED);
10084						}
10085						SCTP_STAT_INCR(sctps_maxburstqueued);
10086					}
10087					net->fast_retran_ip = 0;
10088				} else {
10089					if (net->flight_size == 0) {
10090						/*
10091						 * Should be decaying the
10092						 * cwnd here
10093						 */
10094						;
10095					}
10096				}
10097			}
10098		}
10099
10100	}
10101	burst_cnt = 0;
10102	do {
10103		error = sctp_med_chunk_output(inp, stcb, asoc, &num_out,
10104		    &reason_code, 0, from_where,
10105		    &now, &now_filled, frag_point, so_locked);
10106		if (error) {
10107			SCTPDBG(SCTP_DEBUG_OUTPUT1, "Error %d was returned from med-c-op\n", error);
10108			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
10109				sctp_log_maxburst(stcb, asoc->primary_destination, error, burst_cnt, SCTP_MAX_BURST_ERROR_STOP);
10110			}
10111			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
10112				sctp_log_cwnd(stcb, NULL, error, SCTP_SEND_NOW_COMPLETES);
10113				sctp_log_cwnd(stcb, NULL, 0xdeadbeef, SCTP_SEND_NOW_COMPLETES);
10114			}
10115			break;
10116		}
10117		SCTPDBG(SCTP_DEBUG_OUTPUT3, "m-c-o put out %d\n", num_out);
10118
10119		tot_out += num_out;
10120		burst_cnt++;
10121		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
10122			sctp_log_cwnd(stcb, NULL, num_out, SCTP_SEND_NOW_COMPLETES);
10123			if (num_out == 0) {
10124				sctp_log_cwnd(stcb, NULL, reason_code, SCTP_SEND_NOW_COMPLETES);
10125			}
10126		}
10127		if (nagle_on) {
10128			/*
10129			 * When the Nagle algorithm is used, look at how
10130			 * much is unsent, then if its smaller than an MTU
10131			 * and we have data in flight we stop, except if we
10132			 * are handling a fragmented user message.
10133			 */
10134			un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
10135			    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
10136			if ((un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD)) &&
10137			    (stcb->asoc.total_flight > 0) &&
10138			    ((stcb->asoc.locked_on_sending == NULL) ||
10139			    sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR))) {
10140				break;
10141			}
10142		}
10143		if (TAILQ_EMPTY(&asoc->control_send_queue) &&
10144		    TAILQ_EMPTY(&asoc->send_queue) &&
10145		    stcb->asoc.ss_functions.sctp_ss_is_empty(stcb, asoc)) {
10146			/* Nothing left to send */
10147			break;
10148		}
10149		if ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) <= 0) {
10150			/* Nothing left to send */
10151			break;
10152		}
10153	} while (num_out &&
10154	    ((asoc->max_burst == 0) ||
10155	    SCTP_BASE_SYSCTL(sctp_use_cwnd_based_maxburst) ||
10156	    (burst_cnt < asoc->max_burst)));
10157
10158	if (SCTP_BASE_SYSCTL(sctp_use_cwnd_based_maxburst) == 0) {
10159		if ((asoc->max_burst > 0) && (burst_cnt >= asoc->max_burst)) {
10160			SCTP_STAT_INCR(sctps_maxburstqueued);
10161			asoc->burst_limit_applied = 1;
10162			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
10163				sctp_log_maxburst(stcb, asoc->primary_destination, 0, burst_cnt, SCTP_MAX_BURST_APPLIED);
10164			}
10165		} else {
10166			asoc->burst_limit_applied = 0;
10167		}
10168	}
10169	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
10170		sctp_log_cwnd(stcb, NULL, tot_out, SCTP_SEND_NOW_COMPLETES);
10171	}
10172	SCTPDBG(SCTP_DEBUG_OUTPUT1, "Ok, we have put out %d chunks\n",
10173	    tot_out);
10174
10175	/*-
10176	 * Now we need to clean up the control chunk chain if a ECNE is on
10177	 * it. It must be marked as UNSENT again so next call will continue
10178	 * to send it until such time that we get a CWR, to remove it.
10179	 */
10180	if (stcb->asoc.ecn_echo_cnt_onq)
10181		sctp_fix_ecn_echo(asoc);
10182	return;
10183}
10184
10185
10186int
10187sctp_output(
10188    struct sctp_inpcb *inp,
10189    struct mbuf *m,
10190    struct sockaddr *addr,
10191    struct mbuf *control,
10192    struct thread *p,
10193    int flags)
10194{
10195	if (inp == NULL) {
10196		SCTP_LTRACE_ERR_RET_PKT(m, inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
10197		return (EINVAL);
10198	}
10199	if (inp->sctp_socket == NULL) {
10200		SCTP_LTRACE_ERR_RET_PKT(m, inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
10201		return (EINVAL);
10202	}
10203	return (sctp_sosend(inp->sctp_socket,
10204	    addr,
10205	    (struct uio *)NULL,
10206	    m,
10207	    control,
10208	    flags, p
10209	    ));
10210}
10211
10212void
10213send_forward_tsn(struct sctp_tcb *stcb,
10214    struct sctp_association *asoc)
10215{
10216	struct sctp_tmit_chunk *chk;
10217	struct sctp_forward_tsn_chunk *fwdtsn;
10218	uint32_t advance_peer_ack_point;
10219
10220	SCTP_TCB_LOCK_ASSERT(stcb);
10221	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
10222		if (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) {
10223			/* mark it to unsent */
10224			chk->sent = SCTP_DATAGRAM_UNSENT;
10225			chk->snd_count = 0;
10226			/* Do we correct its output location? */
10227			if (chk->whoTo) {
10228				sctp_free_remote_addr(chk->whoTo);
10229				chk->whoTo = NULL;
10230			}
10231			goto sctp_fill_in_rest;
10232		}
10233	}
10234	/* Ok if we reach here we must build one */
10235	sctp_alloc_a_chunk(stcb, chk);
10236	if (chk == NULL) {
10237		return;
10238	}
10239	asoc->fwd_tsn_cnt++;
10240	chk->copy_by_ref = 0;
10241	chk->rec.chunk_id.id = SCTP_FORWARD_CUM_TSN;
10242	chk->rec.chunk_id.can_take_data = 0;
10243	chk->flags = 0;
10244	chk->asoc = asoc;
10245	chk->whoTo = NULL;
10246	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_NOWAIT, 1, MT_DATA);
10247	if (chk->data == NULL) {
10248		sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
10249		return;
10250	}
10251	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
10252	chk->sent = SCTP_DATAGRAM_UNSENT;
10253	chk->snd_count = 0;
10254	TAILQ_INSERT_TAIL(&asoc->control_send_queue, chk, sctp_next);
10255	asoc->ctrl_queue_cnt++;
10256sctp_fill_in_rest:
10257	/*-
10258	 * Here we go through and fill out the part that deals with
10259	 * stream/seq of the ones we skip.
10260	 */
10261	SCTP_BUF_LEN(chk->data) = 0;
10262	{
10263		struct sctp_tmit_chunk *at, *tp1, *last;
10264		struct sctp_strseq *strseq;
10265		unsigned int cnt_of_space, i, ovh;
10266		unsigned int space_needed;
10267		unsigned int cnt_of_skipped = 0;
10268
10269		TAILQ_FOREACH(at, &asoc->sent_queue, sctp_next) {
10270			if ((at->sent != SCTP_FORWARD_TSN_SKIP) &&
10271			    (at->sent != SCTP_DATAGRAM_NR_ACKED)) {
10272				/* no more to look at */
10273				break;
10274			}
10275			if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
10276				/* We don't report these */
10277				continue;
10278			}
10279			cnt_of_skipped++;
10280		}
10281		space_needed = (sizeof(struct sctp_forward_tsn_chunk) +
10282		    (cnt_of_skipped * sizeof(struct sctp_strseq)));
10283
10284		cnt_of_space = M_TRAILINGSPACE(chk->data);
10285
10286		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
10287			ovh = SCTP_MIN_OVERHEAD;
10288		} else {
10289			ovh = SCTP_MIN_V4_OVERHEAD;
10290		}
10291		if (cnt_of_space > (asoc->smallest_mtu - ovh)) {
10292			/* trim to a mtu size */
10293			cnt_of_space = asoc->smallest_mtu - ovh;
10294		}
10295		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
10296			sctp_misc_ints(SCTP_FWD_TSN_CHECK,
10297			    0xff, 0, cnt_of_skipped,
10298			    asoc->advanced_peer_ack_point);
10299
10300		}
10301		advance_peer_ack_point = asoc->advanced_peer_ack_point;
10302		if (cnt_of_space < space_needed) {
10303			/*-
10304			 * ok we must trim down the chunk by lowering the
10305			 * advance peer ack point.
10306			 */
10307			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
10308				sctp_misc_ints(SCTP_FWD_TSN_CHECK,
10309				    0xff, 0xff, cnt_of_space,
10310				    space_needed);
10311			}
10312			cnt_of_skipped = cnt_of_space - sizeof(struct sctp_forward_tsn_chunk);
10313			cnt_of_skipped /= sizeof(struct sctp_strseq);
10314			/*-
10315			 * Go through and find the TSN that will be the one
10316			 * we report.
10317			 */
10318			at = TAILQ_FIRST(&asoc->sent_queue);
10319			if (at != NULL) {
10320				for (i = 0; i < cnt_of_skipped; i++) {
10321					tp1 = TAILQ_NEXT(at, sctp_next);
10322					if (tp1 == NULL) {
10323						break;
10324					}
10325					at = tp1;
10326				}
10327			}
10328			if (at && SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
10329				sctp_misc_ints(SCTP_FWD_TSN_CHECK,
10330				    0xff, cnt_of_skipped, at->rec.data.TSN_seq,
10331				    asoc->advanced_peer_ack_point);
10332			}
10333			last = at;
10334			/*-
10335			 * last now points to last one I can report, update
10336			 * peer ack point
10337			 */
10338			if (last)
10339				advance_peer_ack_point = last->rec.data.TSN_seq;
10340			space_needed = sizeof(struct sctp_forward_tsn_chunk) +
10341			    cnt_of_skipped * sizeof(struct sctp_strseq);
10342		}
10343		chk->send_size = space_needed;
10344		/* Setup the chunk */
10345		fwdtsn = mtod(chk->data, struct sctp_forward_tsn_chunk *);
10346		fwdtsn->ch.chunk_length = htons(chk->send_size);
10347		fwdtsn->ch.chunk_flags = 0;
10348		fwdtsn->ch.chunk_type = SCTP_FORWARD_CUM_TSN;
10349		fwdtsn->new_cumulative_tsn = htonl(advance_peer_ack_point);
10350		SCTP_BUF_LEN(chk->data) = chk->send_size;
10351		fwdtsn++;
10352		/*-
10353		 * Move pointer to after the fwdtsn and transfer to the
10354		 * strseq pointer.
10355		 */
10356		strseq = (struct sctp_strseq *)fwdtsn;
10357		/*-
10358		 * Now populate the strseq list. This is done blindly
10359		 * without pulling out duplicate stream info. This is
10360		 * inefficent but won't harm the process since the peer will
10361		 * look at these in sequence and will thus release anything.
10362		 * It could mean we exceed the PMTU and chop off some that
10363		 * we could have included.. but this is unlikely (aka 1432/4
10364		 * would mean 300+ stream seq's would have to be reported in
10365		 * one FWD-TSN. With a bit of work we can later FIX this to
10366		 * optimize and pull out duplcates.. but it does add more
10367		 * overhead. So for now... not!
10368		 */
10369		at = TAILQ_FIRST(&asoc->sent_queue);
10370		for (i = 0; i < cnt_of_skipped; i++) {
10371			tp1 = TAILQ_NEXT(at, sctp_next);
10372			if (tp1 == NULL)
10373				break;
10374			if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
10375				/* We don't report these */
10376				i--;
10377				at = tp1;
10378				continue;
10379			}
10380			if (at->rec.data.TSN_seq == advance_peer_ack_point) {
10381				at->rec.data.fwd_tsn_cnt = 0;
10382			}
10383			strseq->stream = ntohs(at->rec.data.stream_number);
10384			strseq->sequence = ntohs(at->rec.data.stream_seq);
10385			strseq++;
10386			at = tp1;
10387		}
10388	}
10389	return;
10390}
10391
10392void
10393sctp_send_sack(struct sctp_tcb *stcb, int so_locked
10394#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
10395    SCTP_UNUSED
10396#endif
10397)
10398{
10399	/*-
10400	 * Queue up a SACK or NR-SACK in the control queue.
10401	 * We must first check to see if a SACK or NR-SACK is
10402	 * somehow on the control queue.
10403	 * If so, we will take and and remove the old one.
10404	 */
10405	struct sctp_association *asoc;
10406	struct sctp_tmit_chunk *chk, *a_chk;
10407	struct sctp_sack_chunk *sack;
10408	struct sctp_nr_sack_chunk *nr_sack;
10409	struct sctp_gap_ack_block *gap_descriptor;
10410	struct sack_track *selector;
10411	int mergeable = 0;
10412	int offset;
10413	caddr_t limit;
10414	uint32_t *dup;
10415	int limit_reached = 0;
10416	unsigned int i, siz, j;
10417	unsigned int num_gap_blocks = 0, num_nr_gap_blocks = 0, space;
10418	int num_dups = 0;
10419	int space_req;
10420	uint32_t highest_tsn;
10421	uint8_t flags;
10422	uint8_t type;
10423	uint8_t tsn_map;
10424
10425	if (stcb->asoc.nrsack_supported == 1) {
10426		type = SCTP_NR_SELECTIVE_ACK;
10427	} else {
10428		type = SCTP_SELECTIVE_ACK;
10429	}
10430	a_chk = NULL;
10431	asoc = &stcb->asoc;
10432	SCTP_TCB_LOCK_ASSERT(stcb);
10433	if (asoc->last_data_chunk_from == NULL) {
10434		/* Hmm we never received anything */
10435		return;
10436	}
10437	sctp_slide_mapping_arrays(stcb);
10438	sctp_set_rwnd(stcb, asoc);
10439	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
10440		if (chk->rec.chunk_id.id == type) {
10441			/* Hmm, found a sack already on queue, remove it */
10442			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
10443			asoc->ctrl_queue_cnt--;
10444			a_chk = chk;
10445			if (a_chk->data) {
10446				sctp_m_freem(a_chk->data);
10447				a_chk->data = NULL;
10448			}
10449			if (a_chk->whoTo) {
10450				sctp_free_remote_addr(a_chk->whoTo);
10451				a_chk->whoTo = NULL;
10452			}
10453			break;
10454		}
10455	}
10456	if (a_chk == NULL) {
10457		sctp_alloc_a_chunk(stcb, a_chk);
10458		if (a_chk == NULL) {
10459			/* No memory so we drop the idea, and set a timer */
10460			if (stcb->asoc.delayed_ack) {
10461				sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
10462				    stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_5);
10463				sctp_timer_start(SCTP_TIMER_TYPE_RECV,
10464				    stcb->sctp_ep, stcb, NULL);
10465			} else {
10466				stcb->asoc.send_sack = 1;
10467			}
10468			return;
10469		}
10470		a_chk->copy_by_ref = 0;
10471		a_chk->rec.chunk_id.id = type;
10472		a_chk->rec.chunk_id.can_take_data = 1;
10473	}
10474	/* Clear our pkt counts */
10475	asoc->data_pkts_seen = 0;
10476
10477	a_chk->flags = 0;
10478	a_chk->asoc = asoc;
10479	a_chk->snd_count = 0;
10480	a_chk->send_size = 0;	/* fill in later */
10481	a_chk->sent = SCTP_DATAGRAM_UNSENT;
10482	a_chk->whoTo = NULL;
10483
10484	if ((asoc->numduptsns) ||
10485	    (!(asoc->last_data_chunk_from->dest_state & SCTP_ADDR_REACHABLE))) {
10486		/*-
10487		 * Ok, we have some duplicates or the destination for the
10488		 * sack is unreachable, lets see if we can select an
10489		 * alternate than asoc->last_data_chunk_from
10490		 */
10491		if ((asoc->last_data_chunk_from->dest_state & SCTP_ADDR_REACHABLE) &&
10492		    (asoc->used_alt_onsack > asoc->numnets)) {
10493			/* We used an alt last time, don't this time */
10494			a_chk->whoTo = NULL;
10495		} else {
10496			asoc->used_alt_onsack++;
10497			a_chk->whoTo = sctp_find_alternate_net(stcb, asoc->last_data_chunk_from, 0);
10498		}
10499		if (a_chk->whoTo == NULL) {
10500			/* Nope, no alternate */
10501			a_chk->whoTo = asoc->last_data_chunk_from;
10502			asoc->used_alt_onsack = 0;
10503		}
10504	} else {
10505		/*
10506		 * No duplicates so we use the last place we received data
10507		 * from.
10508		 */
10509		asoc->used_alt_onsack = 0;
10510		a_chk->whoTo = asoc->last_data_chunk_from;
10511	}
10512	if (a_chk->whoTo) {
10513		atomic_add_int(&a_chk->whoTo->ref_count, 1);
10514	}
10515	if (SCTP_TSN_GT(asoc->highest_tsn_inside_map, asoc->highest_tsn_inside_nr_map)) {
10516		highest_tsn = asoc->highest_tsn_inside_map;
10517	} else {
10518		highest_tsn = asoc->highest_tsn_inside_nr_map;
10519	}
10520	if (highest_tsn == asoc->cumulative_tsn) {
10521		/* no gaps */
10522		if (type == SCTP_SELECTIVE_ACK) {
10523			space_req = sizeof(struct sctp_sack_chunk);
10524		} else {
10525			space_req = sizeof(struct sctp_nr_sack_chunk);
10526		}
10527	} else {
10528		/* gaps get a cluster */
10529		space_req = MCLBYTES;
10530	}
10531	/* Ok now lets formulate a MBUF with our sack */
10532	a_chk->data = sctp_get_mbuf_for_msg(space_req, 0, M_NOWAIT, 1, MT_DATA);
10533	if ((a_chk->data == NULL) ||
10534	    (a_chk->whoTo == NULL)) {
10535		/* rats, no mbuf memory */
10536		if (a_chk->data) {
10537			/* was a problem with the destination */
10538			sctp_m_freem(a_chk->data);
10539			a_chk->data = NULL;
10540		}
10541		sctp_free_a_chunk(stcb, a_chk, so_locked);
10542		/* sa_ignore NO_NULL_CHK */
10543		if (stcb->asoc.delayed_ack) {
10544			sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
10545			    stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_6);
10546			sctp_timer_start(SCTP_TIMER_TYPE_RECV,
10547			    stcb->sctp_ep, stcb, NULL);
10548		} else {
10549			stcb->asoc.send_sack = 1;
10550		}
10551		return;
10552	}
10553	/* ok, lets go through and fill it in */
10554	SCTP_BUF_RESV_UF(a_chk->data, SCTP_MIN_OVERHEAD);
10555	space = M_TRAILINGSPACE(a_chk->data);
10556	if (space > (a_chk->whoTo->mtu - SCTP_MIN_OVERHEAD)) {
10557		space = (a_chk->whoTo->mtu - SCTP_MIN_OVERHEAD);
10558	}
10559	limit = mtod(a_chk->data, caddr_t);
10560	limit += space;
10561
10562	flags = 0;
10563
10564	if ((asoc->sctp_cmt_on_off > 0) &&
10565	    SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
10566		/*-
10567		 * CMT DAC algorithm: If 2 (i.e., 0x10) packets have been
10568		 * received, then set high bit to 1, else 0. Reset
10569		 * pkts_rcvd.
10570		 */
10571		flags |= (asoc->cmt_dac_pkts_rcvd << 6);
10572		asoc->cmt_dac_pkts_rcvd = 0;
10573	}
10574#ifdef SCTP_ASOCLOG_OF_TSNS
10575	stcb->asoc.cumack_logsnt[stcb->asoc.cumack_log_atsnt] = asoc->cumulative_tsn;
10576	stcb->asoc.cumack_log_atsnt++;
10577	if (stcb->asoc.cumack_log_atsnt >= SCTP_TSN_LOG_SIZE) {
10578		stcb->asoc.cumack_log_atsnt = 0;
10579	}
10580#endif
10581	/* reset the readers interpretation */
10582	stcb->freed_by_sorcv_sincelast = 0;
10583
10584	if (type == SCTP_SELECTIVE_ACK) {
10585		sack = mtod(a_chk->data, struct sctp_sack_chunk *);
10586		nr_sack = NULL;
10587		gap_descriptor = (struct sctp_gap_ack_block *)((caddr_t)sack + sizeof(struct sctp_sack_chunk));
10588		if (highest_tsn > asoc->mapping_array_base_tsn) {
10589			siz = (((highest_tsn - asoc->mapping_array_base_tsn) + 1) + 7) / 8;
10590		} else {
10591			siz = (((MAX_TSN - highest_tsn) + 1) + highest_tsn + 7) / 8;
10592		}
10593	} else {
10594		sack = NULL;
10595		nr_sack = mtod(a_chk->data, struct sctp_nr_sack_chunk *);
10596		gap_descriptor = (struct sctp_gap_ack_block *)((caddr_t)nr_sack + sizeof(struct sctp_nr_sack_chunk));
10597		if (asoc->highest_tsn_inside_map > asoc->mapping_array_base_tsn) {
10598			siz = (((asoc->highest_tsn_inside_map - asoc->mapping_array_base_tsn) + 1) + 7) / 8;
10599		} else {
10600			siz = (((MAX_TSN - asoc->mapping_array_base_tsn) + 1) + asoc->highest_tsn_inside_map + 7) / 8;
10601		}
10602	}
10603
10604	if (SCTP_TSN_GT(asoc->mapping_array_base_tsn, asoc->cumulative_tsn)) {
10605		offset = 1;
10606	} else {
10607		offset = asoc->mapping_array_base_tsn - asoc->cumulative_tsn;
10608	}
10609	if (((type == SCTP_SELECTIVE_ACK) &&
10610	    SCTP_TSN_GT(highest_tsn, asoc->cumulative_tsn)) ||
10611	    ((type == SCTP_NR_SELECTIVE_ACK) &&
10612	    SCTP_TSN_GT(asoc->highest_tsn_inside_map, asoc->cumulative_tsn))) {
10613		/* we have a gap .. maybe */
10614		for (i = 0; i < siz; i++) {
10615			tsn_map = asoc->mapping_array[i];
10616			if (type == SCTP_SELECTIVE_ACK) {
10617				tsn_map |= asoc->nr_mapping_array[i];
10618			}
10619			if (i == 0) {
10620				/*
10621				 * Clear all bits corresponding to TSNs
10622				 * smaller or equal to the cumulative TSN.
10623				 */
10624				tsn_map &= (~0 << (1 - offset));
10625			}
10626			selector = &sack_array[tsn_map];
10627			if (mergeable && selector->right_edge) {
10628				/*
10629				 * Backup, left and right edges were ok to
10630				 * merge.
10631				 */
10632				num_gap_blocks--;
10633				gap_descriptor--;
10634			}
10635			if (selector->num_entries == 0)
10636				mergeable = 0;
10637			else {
10638				for (j = 0; j < selector->num_entries; j++) {
10639					if (mergeable && selector->right_edge) {
10640						/*
10641						 * do a merge by NOT setting
10642						 * the left side
10643						 */
10644						mergeable = 0;
10645					} else {
10646						/*
10647						 * no merge, set the left
10648						 * side
10649						 */
10650						mergeable = 0;
10651						gap_descriptor->start = htons((selector->gaps[j].start + offset));
10652					}
10653					gap_descriptor->end = htons((selector->gaps[j].end + offset));
10654					num_gap_blocks++;
10655					gap_descriptor++;
10656					if (((caddr_t)gap_descriptor + sizeof(struct sctp_gap_ack_block)) > limit) {
10657						/* no more room */
10658						limit_reached = 1;
10659						break;
10660					}
10661				}
10662				if (selector->left_edge) {
10663					mergeable = 1;
10664				}
10665			}
10666			if (limit_reached) {
10667				/* Reached the limit stop */
10668				break;
10669			}
10670			offset += 8;
10671		}
10672	}
10673	if ((type == SCTP_NR_SELECTIVE_ACK) &&
10674	    (limit_reached == 0)) {
10675
10676		mergeable = 0;
10677
10678		if (asoc->highest_tsn_inside_nr_map > asoc->mapping_array_base_tsn) {
10679			siz = (((asoc->highest_tsn_inside_nr_map - asoc->mapping_array_base_tsn) + 1) + 7) / 8;
10680		} else {
10681			siz = (((MAX_TSN - asoc->mapping_array_base_tsn) + 1) + asoc->highest_tsn_inside_nr_map + 7) / 8;
10682		}
10683
10684		if (SCTP_TSN_GT(asoc->mapping_array_base_tsn, asoc->cumulative_tsn)) {
10685			offset = 1;
10686		} else {
10687			offset = asoc->mapping_array_base_tsn - asoc->cumulative_tsn;
10688		}
10689		if (SCTP_TSN_GT(asoc->highest_tsn_inside_nr_map, asoc->cumulative_tsn)) {
10690			/* we have a gap .. maybe */
10691			for (i = 0; i < siz; i++) {
10692				tsn_map = asoc->nr_mapping_array[i];
10693				if (i == 0) {
10694					/*
10695					 * Clear all bits corresponding to
10696					 * TSNs smaller or equal to the
10697					 * cumulative TSN.
10698					 */
10699					tsn_map &= (~0 << (1 - offset));
10700				}
10701				selector = &sack_array[tsn_map];
10702				if (mergeable && selector->right_edge) {
10703					/*
10704					 * Backup, left and right edges were
10705					 * ok to merge.
10706					 */
10707					num_nr_gap_blocks--;
10708					gap_descriptor--;
10709				}
10710				if (selector->num_entries == 0)
10711					mergeable = 0;
10712				else {
10713					for (j = 0; j < selector->num_entries; j++) {
10714						if (mergeable && selector->right_edge) {
10715							/*
10716							 * do a merge by NOT
10717							 * setting the left
10718							 * side
10719							 */
10720							mergeable = 0;
10721						} else {
10722							/*
10723							 * no merge, set the
10724							 * left side
10725							 */
10726							mergeable = 0;
10727							gap_descriptor->start = htons((selector->gaps[j].start + offset));
10728						}
10729						gap_descriptor->end = htons((selector->gaps[j].end + offset));
10730						num_nr_gap_blocks++;
10731						gap_descriptor++;
10732						if (((caddr_t)gap_descriptor + sizeof(struct sctp_gap_ack_block)) > limit) {
10733							/* no more room */
10734							limit_reached = 1;
10735							break;
10736						}
10737					}
10738					if (selector->left_edge) {
10739						mergeable = 1;
10740					}
10741				}
10742				if (limit_reached) {
10743					/* Reached the limit stop */
10744					break;
10745				}
10746				offset += 8;
10747			}
10748		}
10749	}
10750	/* now we must add any dups we are going to report. */
10751	if ((limit_reached == 0) && (asoc->numduptsns)) {
10752		dup = (uint32_t *) gap_descriptor;
10753		for (i = 0; i < asoc->numduptsns; i++) {
10754			*dup = htonl(asoc->dup_tsns[i]);
10755			dup++;
10756			num_dups++;
10757			if (((caddr_t)dup + sizeof(uint32_t)) > limit) {
10758				/* no more room */
10759				break;
10760			}
10761		}
10762		asoc->numduptsns = 0;
10763	}
10764	/*
10765	 * now that the chunk is prepared queue it to the control chunk
10766	 * queue.
10767	 */
10768	if (type == SCTP_SELECTIVE_ACK) {
10769		a_chk->send_size = sizeof(struct sctp_sack_chunk) +
10770		    (num_gap_blocks + num_nr_gap_blocks) * sizeof(struct sctp_gap_ack_block) +
10771		    num_dups * sizeof(int32_t);
10772		SCTP_BUF_LEN(a_chk->data) = a_chk->send_size;
10773		sack->sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
10774		sack->sack.a_rwnd = htonl(asoc->my_rwnd);
10775		sack->sack.num_gap_ack_blks = htons(num_gap_blocks);
10776		sack->sack.num_dup_tsns = htons(num_dups);
10777		sack->ch.chunk_type = type;
10778		sack->ch.chunk_flags = flags;
10779		sack->ch.chunk_length = htons(a_chk->send_size);
10780	} else {
10781		a_chk->send_size = sizeof(struct sctp_nr_sack_chunk) +
10782		    (num_gap_blocks + num_nr_gap_blocks) * sizeof(struct sctp_gap_ack_block) +
10783		    num_dups * sizeof(int32_t);
10784		SCTP_BUF_LEN(a_chk->data) = a_chk->send_size;
10785		nr_sack->nr_sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
10786		nr_sack->nr_sack.a_rwnd = htonl(asoc->my_rwnd);
10787		nr_sack->nr_sack.num_gap_ack_blks = htons(num_gap_blocks);
10788		nr_sack->nr_sack.num_nr_gap_ack_blks = htons(num_nr_gap_blocks);
10789		nr_sack->nr_sack.num_dup_tsns = htons(num_dups);
10790		nr_sack->nr_sack.reserved = 0;
10791		nr_sack->ch.chunk_type = type;
10792		nr_sack->ch.chunk_flags = flags;
10793		nr_sack->ch.chunk_length = htons(a_chk->send_size);
10794	}
10795	TAILQ_INSERT_TAIL(&asoc->control_send_queue, a_chk, sctp_next);
10796	asoc->my_last_reported_rwnd = asoc->my_rwnd;
10797	asoc->ctrl_queue_cnt++;
10798	asoc->send_sack = 0;
10799	SCTP_STAT_INCR(sctps_sendsacks);
10800	return;
10801}
10802
10803void
10804sctp_send_abort_tcb(struct sctp_tcb *stcb, struct mbuf *operr, int so_locked
10805#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
10806    SCTP_UNUSED
10807#endif
10808)
10809{
10810	struct mbuf *m_abort, *m, *m_last;
10811	struct mbuf *m_out, *m_end = NULL;
10812	struct sctp_abort_chunk *abort;
10813	struct sctp_auth_chunk *auth = NULL;
10814	struct sctp_nets *net;
10815	uint32_t vtag;
10816	uint32_t auth_offset = 0;
10817	uint16_t cause_len, chunk_len, padding_len;
10818
10819	SCTP_TCB_LOCK_ASSERT(stcb);
10820	/*-
10821	 * Add an AUTH chunk, if chunk requires it and save the offset into
10822	 * the chain for AUTH
10823	 */
10824	if (sctp_auth_is_required_chunk(SCTP_ABORT_ASSOCIATION,
10825	    stcb->asoc.peer_auth_chunks)) {
10826		m_out = sctp_add_auth_chunk(NULL, &m_end, &auth, &auth_offset,
10827		    stcb, SCTP_ABORT_ASSOCIATION);
10828		SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
10829	} else {
10830		m_out = NULL;
10831	}
10832	m_abort = sctp_get_mbuf_for_msg(sizeof(struct sctp_abort_chunk), 0, M_NOWAIT, 1, MT_HEADER);
10833	if (m_abort == NULL) {
10834		if (m_out) {
10835			sctp_m_freem(m_out);
10836		}
10837		if (operr) {
10838			sctp_m_freem(operr);
10839		}
10840		return;
10841	}
10842	/* link in any error */
10843	SCTP_BUF_NEXT(m_abort) = operr;
10844	cause_len = 0;
10845	m_last = NULL;
10846	for (m = operr; m; m = SCTP_BUF_NEXT(m)) {
10847		cause_len += (uint16_t) SCTP_BUF_LEN(m);
10848		if (SCTP_BUF_NEXT(m) == NULL) {
10849			m_last = m;
10850		}
10851	}
10852	SCTP_BUF_LEN(m_abort) = sizeof(struct sctp_abort_chunk);
10853	chunk_len = (uint16_t) sizeof(struct sctp_abort_chunk) + cause_len;
10854	padding_len = SCTP_SIZE32(chunk_len) - chunk_len;
10855	if (m_out == NULL) {
10856		/* NO Auth chunk prepended, so reserve space in front */
10857		SCTP_BUF_RESV_UF(m_abort, SCTP_MIN_OVERHEAD);
10858		m_out = m_abort;
10859	} else {
10860		/* Put AUTH chunk at the front of the chain */
10861		SCTP_BUF_NEXT(m_end) = m_abort;
10862	}
10863	if (stcb->asoc.alternate) {
10864		net = stcb->asoc.alternate;
10865	} else {
10866		net = stcb->asoc.primary_destination;
10867	}
10868	/* Fill in the ABORT chunk header. */
10869	abort = mtod(m_abort, struct sctp_abort_chunk *);
10870	abort->ch.chunk_type = SCTP_ABORT_ASSOCIATION;
10871	if (stcb->asoc.peer_vtag == 0) {
10872		/* This happens iff the assoc is in COOKIE-WAIT state. */
10873		vtag = stcb->asoc.my_vtag;
10874		abort->ch.chunk_flags = SCTP_HAD_NO_TCB;
10875	} else {
10876		vtag = stcb->asoc.peer_vtag;
10877		abort->ch.chunk_flags = 0;
10878	}
10879	abort->ch.chunk_length = htons(chunk_len);
10880	/* Add padding, if necessary. */
10881	if (padding_len > 0) {
10882		if ((m_last == NULL) ||
10883		    (sctp_add_pad_tombuf(m_last, padding_len) == NULL)) {
10884			sctp_m_freem(m_out);
10885			return;
10886		}
10887	}
10888	(void)sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb, net,
10889	    (struct sockaddr *)&net->ro._l_addr,
10890	    m_out, auth_offset, auth, stcb->asoc.authinfo.active_keyid, 1, 0, 0,
10891	    stcb->sctp_ep->sctp_lport, stcb->rport, htonl(vtag),
10892	    stcb->asoc.primary_destination->port, NULL,
10893	    0, 0,
10894	    so_locked);
10895	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
10896}
10897
10898void
10899sctp_send_shutdown_complete(struct sctp_tcb *stcb,
10900    struct sctp_nets *net,
10901    int reflect_vtag)
10902{
10903	/* formulate and SEND a SHUTDOWN-COMPLETE */
10904	struct mbuf *m_shutdown_comp;
10905	struct sctp_shutdown_complete_chunk *shutdown_complete;
10906	uint32_t vtag;
10907	uint8_t flags;
10908
10909	m_shutdown_comp = sctp_get_mbuf_for_msg(sizeof(struct sctp_chunkhdr), 0, M_NOWAIT, 1, MT_HEADER);
10910	if (m_shutdown_comp == NULL) {
10911		/* no mbuf's */
10912		return;
10913	}
10914	if (reflect_vtag) {
10915		flags = SCTP_HAD_NO_TCB;
10916		vtag = stcb->asoc.my_vtag;
10917	} else {
10918		flags = 0;
10919		vtag = stcb->asoc.peer_vtag;
10920	}
10921	shutdown_complete = mtod(m_shutdown_comp, struct sctp_shutdown_complete_chunk *);
10922	shutdown_complete->ch.chunk_type = SCTP_SHUTDOWN_COMPLETE;
10923	shutdown_complete->ch.chunk_flags = flags;
10924	shutdown_complete->ch.chunk_length = htons(sizeof(struct sctp_shutdown_complete_chunk));
10925	SCTP_BUF_LEN(m_shutdown_comp) = sizeof(struct sctp_shutdown_complete_chunk);
10926	(void)sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb, net,
10927	    (struct sockaddr *)&net->ro._l_addr,
10928	    m_shutdown_comp, 0, NULL, 0, 1, 0, 0,
10929	    stcb->sctp_ep->sctp_lport, stcb->rport,
10930	    htonl(vtag),
10931	    net->port, NULL,
10932	    0, 0,
10933	    SCTP_SO_NOT_LOCKED);
10934	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
10935	return;
10936}
10937
10938static void
10939sctp_send_resp_msg(struct sockaddr *src, struct sockaddr *dst,
10940    struct sctphdr *sh, uint32_t vtag,
10941    uint8_t type, struct mbuf *cause,
10942    uint8_t mflowtype, uint32_t mflowid,
10943    uint32_t vrf_id, uint16_t port)
10944{
10945	struct mbuf *o_pak;
10946	struct mbuf *mout;
10947	struct sctphdr *shout;
10948	struct sctp_chunkhdr *ch;
10949
10950#if defined(INET) || defined(INET6)
10951	struct udphdr *udp;
10952	int ret;
10953
10954#endif
10955	int len, cause_len, padding_len;
10956
10957#ifdef INET
10958	struct sockaddr_in *src_sin, *dst_sin;
10959	struct ip *ip;
10960
10961#endif
10962#ifdef INET6
10963	struct sockaddr_in6 *src_sin6, *dst_sin6;
10964	struct ip6_hdr *ip6;
10965
10966#endif
10967
10968	/* Compute the length of the cause and add final padding. */
10969	cause_len = 0;
10970	if (cause != NULL) {
10971		struct mbuf *m_at, *m_last = NULL;
10972
10973		for (m_at = cause; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
10974			if (SCTP_BUF_NEXT(m_at) == NULL)
10975				m_last = m_at;
10976			cause_len += SCTP_BUF_LEN(m_at);
10977		}
10978		padding_len = cause_len % 4;
10979		if (padding_len != 0) {
10980			padding_len = 4 - padding_len;
10981		}
10982		if (padding_len != 0) {
10983			if (sctp_add_pad_tombuf(m_last, padding_len) == NULL) {
10984				sctp_m_freem(cause);
10985				return;
10986			}
10987		}
10988	} else {
10989		padding_len = 0;
10990	}
10991	/* Get an mbuf for the header. */
10992	len = sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
10993	switch (dst->sa_family) {
10994#ifdef INET
10995	case AF_INET:
10996		len += sizeof(struct ip);
10997		break;
10998#endif
10999#ifdef INET6
11000	case AF_INET6:
11001		len += sizeof(struct ip6_hdr);
11002		break;
11003#endif
11004	default:
11005		break;
11006	}
11007#if defined(INET) || defined(INET6)
11008	if (port) {
11009		len += sizeof(struct udphdr);
11010	}
11011#endif
11012	mout = sctp_get_mbuf_for_msg(len + max_linkhdr, 1, M_NOWAIT, 1, MT_DATA);
11013	if (mout == NULL) {
11014		if (cause) {
11015			sctp_m_freem(cause);
11016		}
11017		return;
11018	}
11019	SCTP_BUF_RESV_UF(mout, max_linkhdr);
11020	SCTP_BUF_LEN(mout) = len;
11021	SCTP_BUF_NEXT(mout) = cause;
11022	mout->m_pkthdr.flowid = mflowid;
11023	M_HASHTYPE_SET(mout, mflowtype);
11024#ifdef INET
11025	ip = NULL;
11026#endif
11027#ifdef INET6
11028	ip6 = NULL;
11029#endif
11030	switch (dst->sa_family) {
11031#ifdef INET
11032	case AF_INET:
11033		src_sin = (struct sockaddr_in *)src;
11034		dst_sin = (struct sockaddr_in *)dst;
11035		ip = mtod(mout, struct ip *);
11036		ip->ip_v = IPVERSION;
11037		ip->ip_hl = (sizeof(struct ip) >> 2);
11038		ip->ip_tos = 0;
11039		ip->ip_id = ip_newid();
11040		ip->ip_off = 0;
11041		ip->ip_ttl = MODULE_GLOBAL(ip_defttl);
11042		if (port) {
11043			ip->ip_p = IPPROTO_UDP;
11044		} else {
11045			ip->ip_p = IPPROTO_SCTP;
11046		}
11047		ip->ip_src.s_addr = dst_sin->sin_addr.s_addr;
11048		ip->ip_dst.s_addr = src_sin->sin_addr.s_addr;
11049		ip->ip_sum = 0;
11050		len = sizeof(struct ip);
11051		shout = (struct sctphdr *)((caddr_t)ip + len);
11052		break;
11053#endif
11054#ifdef INET6
11055	case AF_INET6:
11056		src_sin6 = (struct sockaddr_in6 *)src;
11057		dst_sin6 = (struct sockaddr_in6 *)dst;
11058		ip6 = mtod(mout, struct ip6_hdr *);
11059		ip6->ip6_flow = htonl(0x60000000);
11060		if (V_ip6_auto_flowlabel) {
11061			ip6->ip6_flow |= (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
11062		}
11063		ip6->ip6_hlim = MODULE_GLOBAL(ip6_defhlim);
11064		if (port) {
11065			ip6->ip6_nxt = IPPROTO_UDP;
11066		} else {
11067			ip6->ip6_nxt = IPPROTO_SCTP;
11068		}
11069		ip6->ip6_src = dst_sin6->sin6_addr;
11070		ip6->ip6_dst = src_sin6->sin6_addr;
11071		len = sizeof(struct ip6_hdr);
11072		shout = (struct sctphdr *)((caddr_t)ip6 + len);
11073		break;
11074#endif
11075	default:
11076		len = 0;
11077		shout = mtod(mout, struct sctphdr *);
11078		break;
11079	}
11080#if defined(INET) || defined(INET6)
11081	if (port) {
11082		if (htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port)) == 0) {
11083			sctp_m_freem(mout);
11084			return;
11085		}
11086		udp = (struct udphdr *)shout;
11087		udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
11088		udp->uh_dport = port;
11089		udp->uh_sum = 0;
11090		udp->uh_ulen = htons(sizeof(struct udphdr) +
11091		    sizeof(struct sctphdr) +
11092		    sizeof(struct sctp_chunkhdr) +
11093		    cause_len + padding_len);
11094		len += sizeof(struct udphdr);
11095		shout = (struct sctphdr *)((caddr_t)shout + sizeof(struct udphdr));
11096	} else {
11097		udp = NULL;
11098	}
11099#endif
11100	shout->src_port = sh->dest_port;
11101	shout->dest_port = sh->src_port;
11102	shout->checksum = 0;
11103	if (vtag) {
11104		shout->v_tag = htonl(vtag);
11105	} else {
11106		shout->v_tag = sh->v_tag;
11107	}
11108	len += sizeof(struct sctphdr);
11109	ch = (struct sctp_chunkhdr *)((caddr_t)shout + sizeof(struct sctphdr));
11110	ch->chunk_type = type;
11111	if (vtag) {
11112		ch->chunk_flags = 0;
11113	} else {
11114		ch->chunk_flags = SCTP_HAD_NO_TCB;
11115	}
11116	ch->chunk_length = htons(sizeof(struct sctp_chunkhdr) + cause_len);
11117	len += sizeof(struct sctp_chunkhdr);
11118	len += cause_len + padding_len;
11119
11120	if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
11121		sctp_m_freem(mout);
11122		return;
11123	}
11124	SCTP_ATTACH_CHAIN(o_pak, mout, len);
11125	switch (dst->sa_family) {
11126#ifdef INET
11127	case AF_INET:
11128		if (port) {
11129			if (V_udp_cksum) {
11130				udp->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, udp->uh_ulen + htons(IPPROTO_UDP));
11131			} else {
11132				udp->uh_sum = 0;
11133			}
11134		}
11135		ip->ip_len = htons(len);
11136		if (port) {
11137#if defined(SCTP_WITH_NO_CSUM)
11138			SCTP_STAT_INCR(sctps_sendnocrc);
11139#else
11140			shout->checksum = sctp_calculate_cksum(mout, sizeof(struct ip) + sizeof(struct udphdr));
11141			SCTP_STAT_INCR(sctps_sendswcrc);
11142#endif
11143			if (V_udp_cksum) {
11144				SCTP_ENABLE_UDP_CSUM(o_pak);
11145			}
11146		} else {
11147#if defined(SCTP_WITH_NO_CSUM)
11148			SCTP_STAT_INCR(sctps_sendnocrc);
11149#else
11150			mout->m_pkthdr.csum_flags = CSUM_SCTP;
11151			mout->m_pkthdr.csum_data = offsetof(struct sctphdr, checksum);
11152			SCTP_STAT_INCR(sctps_sendhwcrc);
11153#endif
11154		}
11155#ifdef SCTP_PACKET_LOGGING
11156		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING) {
11157			sctp_packet_log(o_pak);
11158		}
11159#endif
11160		SCTP_IP_OUTPUT(ret, o_pak, NULL, NULL, vrf_id);
11161		break;
11162#endif
11163#ifdef INET6
11164	case AF_INET6:
11165		ip6->ip6_plen = len - sizeof(struct ip6_hdr);
11166		if (port) {
11167#if defined(SCTP_WITH_NO_CSUM)
11168			SCTP_STAT_INCR(sctps_sendnocrc);
11169#else
11170			shout->checksum = sctp_calculate_cksum(mout, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
11171			SCTP_STAT_INCR(sctps_sendswcrc);
11172#endif
11173			if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), len - sizeof(struct ip6_hdr))) == 0) {
11174				udp->uh_sum = 0xffff;
11175			}
11176		} else {
11177#if defined(SCTP_WITH_NO_CSUM)
11178			SCTP_STAT_INCR(sctps_sendnocrc);
11179#else
11180			mout->m_pkthdr.csum_flags = CSUM_SCTP_IPV6;
11181			mout->m_pkthdr.csum_data = offsetof(struct sctphdr, checksum);
11182			SCTP_STAT_INCR(sctps_sendhwcrc);
11183#endif
11184		}
11185#ifdef SCTP_PACKET_LOGGING
11186		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING) {
11187			sctp_packet_log(o_pak);
11188		}
11189#endif
11190		SCTP_IP6_OUTPUT(ret, o_pak, NULL, NULL, NULL, vrf_id);
11191		break;
11192#endif
11193	default:
11194		SCTPDBG(SCTP_DEBUG_OUTPUT1, "Unknown protocol (TSNH) type %d\n",
11195		    dst->sa_family);
11196		sctp_m_freem(mout);
11197		SCTP_LTRACE_ERR_RET_PKT(mout, NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EFAULT);
11198		return;
11199	}
11200	SCTP_STAT_INCR(sctps_sendpackets);
11201	SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
11202	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
11203	return;
11204}
11205
11206void
11207sctp_send_shutdown_complete2(struct sockaddr *src, struct sockaddr *dst,
11208    struct sctphdr *sh,
11209    uint8_t mflowtype, uint32_t mflowid,
11210    uint32_t vrf_id, uint16_t port)
11211{
11212	sctp_send_resp_msg(src, dst, sh, 0, SCTP_SHUTDOWN_COMPLETE, NULL,
11213	    mflowtype, mflowid,
11214	    vrf_id, port);
11215}
11216
11217void
11218sctp_send_hb(struct sctp_tcb *stcb, struct sctp_nets *net, int so_locked
11219#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
11220    SCTP_UNUSED
11221#endif
11222)
11223{
11224	struct sctp_tmit_chunk *chk;
11225	struct sctp_heartbeat_chunk *hb;
11226	struct timeval now;
11227
11228	SCTP_TCB_LOCK_ASSERT(stcb);
11229	if (net == NULL) {
11230		return;
11231	}
11232	(void)SCTP_GETTIME_TIMEVAL(&now);
11233	switch (net->ro._l_addr.sa.sa_family) {
11234#ifdef INET
11235	case AF_INET:
11236		break;
11237#endif
11238#ifdef INET6
11239	case AF_INET6:
11240		break;
11241#endif
11242	default:
11243		return;
11244	}
11245	sctp_alloc_a_chunk(stcb, chk);
11246	if (chk == NULL) {
11247		SCTPDBG(SCTP_DEBUG_OUTPUT4, "Gak, can't get a chunk for hb\n");
11248		return;
11249	}
11250	chk->copy_by_ref = 0;
11251	chk->rec.chunk_id.id = SCTP_HEARTBEAT_REQUEST;
11252	chk->rec.chunk_id.can_take_data = 1;
11253	chk->flags = 0;
11254	chk->asoc = &stcb->asoc;
11255	chk->send_size = sizeof(struct sctp_heartbeat_chunk);
11256
11257	chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_NOWAIT, 1, MT_HEADER);
11258	if (chk->data == NULL) {
11259		sctp_free_a_chunk(stcb, chk, so_locked);
11260		return;
11261	}
11262	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11263	SCTP_BUF_LEN(chk->data) = chk->send_size;
11264	chk->sent = SCTP_DATAGRAM_UNSENT;
11265	chk->snd_count = 0;
11266	chk->whoTo = net;
11267	atomic_add_int(&chk->whoTo->ref_count, 1);
11268	/* Now we have a mbuf that we can fill in with the details */
11269	hb = mtod(chk->data, struct sctp_heartbeat_chunk *);
11270	memset(hb, 0, sizeof(struct sctp_heartbeat_chunk));
11271	/* fill out chunk header */
11272	hb->ch.chunk_type = SCTP_HEARTBEAT_REQUEST;
11273	hb->ch.chunk_flags = 0;
11274	hb->ch.chunk_length = htons(chk->send_size);
11275	/* Fill out hb parameter */
11276	hb->heartbeat.hb_info.ph.param_type = htons(SCTP_HEARTBEAT_INFO);
11277	hb->heartbeat.hb_info.ph.param_length = htons(sizeof(struct sctp_heartbeat_info_param));
11278	hb->heartbeat.hb_info.time_value_1 = now.tv_sec;
11279	hb->heartbeat.hb_info.time_value_2 = now.tv_usec;
11280	/* Did our user request this one, put it in */
11281	hb->heartbeat.hb_info.addr_family = (uint8_t) net->ro._l_addr.sa.sa_family;
11282	hb->heartbeat.hb_info.addr_len = net->ro._l_addr.sa.sa_len;
11283	if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
11284		/*
11285		 * we only take from the entropy pool if the address is not
11286		 * confirmed.
11287		 */
11288		net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
11289		net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
11290	} else {
11291		net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = 0;
11292		net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = 0;
11293	}
11294	switch (net->ro._l_addr.sa.sa_family) {
11295#ifdef INET
11296	case AF_INET:
11297		memcpy(hb->heartbeat.hb_info.address,
11298		    &net->ro._l_addr.sin.sin_addr,
11299		    sizeof(net->ro._l_addr.sin.sin_addr));
11300		break;
11301#endif
11302#ifdef INET6
11303	case AF_INET6:
11304		memcpy(hb->heartbeat.hb_info.address,
11305		    &net->ro._l_addr.sin6.sin6_addr,
11306		    sizeof(net->ro._l_addr.sin6.sin6_addr));
11307		break;
11308#endif
11309	default:
11310		return;
11311		break;
11312	}
11313	net->hb_responded = 0;
11314	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
11315	stcb->asoc.ctrl_queue_cnt++;
11316	SCTP_STAT_INCR(sctps_sendheartbeat);
11317	return;
11318}
11319
11320void
11321sctp_send_ecn_echo(struct sctp_tcb *stcb, struct sctp_nets *net,
11322    uint32_t high_tsn)
11323{
11324	struct sctp_association *asoc;
11325	struct sctp_ecne_chunk *ecne;
11326	struct sctp_tmit_chunk *chk;
11327
11328	if (net == NULL) {
11329		return;
11330	}
11331	asoc = &stcb->asoc;
11332	SCTP_TCB_LOCK_ASSERT(stcb);
11333	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
11334		if ((chk->rec.chunk_id.id == SCTP_ECN_ECHO) && (net == chk->whoTo)) {
11335			/* found a previous ECN_ECHO update it if needed */
11336			uint32_t cnt, ctsn;
11337
11338			ecne = mtod(chk->data, struct sctp_ecne_chunk *);
11339			ctsn = ntohl(ecne->tsn);
11340			if (SCTP_TSN_GT(high_tsn, ctsn)) {
11341				ecne->tsn = htonl(high_tsn);
11342				SCTP_STAT_INCR(sctps_queue_upd_ecne);
11343			}
11344			cnt = ntohl(ecne->num_pkts_since_cwr);
11345			cnt++;
11346			ecne->num_pkts_since_cwr = htonl(cnt);
11347			return;
11348		}
11349	}
11350	/* nope could not find one to update so we must build one */
11351	sctp_alloc_a_chunk(stcb, chk);
11352	if (chk == NULL) {
11353		return;
11354	}
11355	SCTP_STAT_INCR(sctps_queue_upd_ecne);
11356	chk->copy_by_ref = 0;
11357	chk->rec.chunk_id.id = SCTP_ECN_ECHO;
11358	chk->rec.chunk_id.can_take_data = 0;
11359	chk->flags = 0;
11360	chk->asoc = &stcb->asoc;
11361	chk->send_size = sizeof(struct sctp_ecne_chunk);
11362	chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_NOWAIT, 1, MT_HEADER);
11363	if (chk->data == NULL) {
11364		sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
11365		return;
11366	}
11367	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11368	SCTP_BUF_LEN(chk->data) = chk->send_size;
11369	chk->sent = SCTP_DATAGRAM_UNSENT;
11370	chk->snd_count = 0;
11371	chk->whoTo = net;
11372	atomic_add_int(&chk->whoTo->ref_count, 1);
11373
11374	stcb->asoc.ecn_echo_cnt_onq++;
11375	ecne = mtod(chk->data, struct sctp_ecne_chunk *);
11376	ecne->ch.chunk_type = SCTP_ECN_ECHO;
11377	ecne->ch.chunk_flags = 0;
11378	ecne->ch.chunk_length = htons(sizeof(struct sctp_ecne_chunk));
11379	ecne->tsn = htonl(high_tsn);
11380	ecne->num_pkts_since_cwr = htonl(1);
11381	TAILQ_INSERT_HEAD(&stcb->asoc.control_send_queue, chk, sctp_next);
11382	asoc->ctrl_queue_cnt++;
11383}
11384
11385void
11386sctp_send_packet_dropped(struct sctp_tcb *stcb, struct sctp_nets *net,
11387    struct mbuf *m, int len, int iphlen, int bad_crc)
11388{
11389	struct sctp_association *asoc;
11390	struct sctp_pktdrop_chunk *drp;
11391	struct sctp_tmit_chunk *chk;
11392	uint8_t *datap;
11393	int was_trunc = 0;
11394	int fullsz = 0;
11395	long spc;
11396	int offset;
11397	struct sctp_chunkhdr *ch, chunk_buf;
11398	unsigned int chk_length;
11399
11400	if (!stcb) {
11401		return;
11402	}
11403	asoc = &stcb->asoc;
11404	SCTP_TCB_LOCK_ASSERT(stcb);
11405	if (asoc->pktdrop_supported == 0) {
11406		/*-
11407		 * peer must declare support before I send one.
11408		 */
11409		return;
11410	}
11411	if (stcb->sctp_socket == NULL) {
11412		return;
11413	}
11414	sctp_alloc_a_chunk(stcb, chk);
11415	if (chk == NULL) {
11416		return;
11417	}
11418	chk->copy_by_ref = 0;
11419	chk->rec.chunk_id.id = SCTP_PACKET_DROPPED;
11420	chk->rec.chunk_id.can_take_data = 1;
11421	chk->flags = 0;
11422	len -= iphlen;
11423	chk->send_size = len;
11424	/* Validate that we do not have an ABORT in here. */
11425	offset = iphlen + sizeof(struct sctphdr);
11426	ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, offset,
11427	    sizeof(*ch), (uint8_t *) & chunk_buf);
11428	while (ch != NULL) {
11429		chk_length = ntohs(ch->chunk_length);
11430		if (chk_length < sizeof(*ch)) {
11431			/* break to abort land */
11432			break;
11433		}
11434		switch (ch->chunk_type) {
11435		case SCTP_PACKET_DROPPED:
11436		case SCTP_ABORT_ASSOCIATION:
11437		case SCTP_INITIATION_ACK:
11438			/**
11439			 * We don't respond with an PKT-DROP to an ABORT
11440			 * or PKT-DROP. We also do not respond to an
11441			 * INIT-ACK, because we can't know if the initiation
11442			 * tag is correct or not.
11443			 */
11444			sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
11445			return;
11446		default:
11447			break;
11448		}
11449		offset += SCTP_SIZE32(chk_length);
11450		ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, offset,
11451		    sizeof(*ch), (uint8_t *) & chunk_buf);
11452	}
11453
11454	if ((len + SCTP_MAX_OVERHEAD + sizeof(struct sctp_pktdrop_chunk)) >
11455	    min(stcb->asoc.smallest_mtu, MCLBYTES)) {
11456		/*
11457		 * only send 1 mtu worth, trim off the excess on the end.
11458		 */
11459		fullsz = len;
11460		len = min(stcb->asoc.smallest_mtu, MCLBYTES) - SCTP_MAX_OVERHEAD;
11461		was_trunc = 1;
11462	}
11463	chk->asoc = &stcb->asoc;
11464	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_NOWAIT, 1, MT_DATA);
11465	if (chk->data == NULL) {
11466jump_out:
11467		sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
11468		return;
11469	}
11470	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11471	drp = mtod(chk->data, struct sctp_pktdrop_chunk *);
11472	if (drp == NULL) {
11473		sctp_m_freem(chk->data);
11474		chk->data = NULL;
11475		goto jump_out;
11476	}
11477	chk->book_size = SCTP_SIZE32((chk->send_size + sizeof(struct sctp_pktdrop_chunk) +
11478	    sizeof(struct sctphdr) + SCTP_MED_OVERHEAD));
11479	chk->book_size_scale = 0;
11480	if (was_trunc) {
11481		drp->ch.chunk_flags = SCTP_PACKET_TRUNCATED;
11482		drp->trunc_len = htons(fullsz);
11483		/*
11484		 * Len is already adjusted to size minus overhead above take
11485		 * out the pkt_drop chunk itself from it.
11486		 */
11487		chk->send_size = len - sizeof(struct sctp_pktdrop_chunk);
11488		len = chk->send_size;
11489	} else {
11490		/* no truncation needed */
11491		drp->ch.chunk_flags = 0;
11492		drp->trunc_len = htons(0);
11493	}
11494	if (bad_crc) {
11495		drp->ch.chunk_flags |= SCTP_BADCRC;
11496	}
11497	chk->send_size += sizeof(struct sctp_pktdrop_chunk);
11498	SCTP_BUF_LEN(chk->data) = chk->send_size;
11499	chk->sent = SCTP_DATAGRAM_UNSENT;
11500	chk->snd_count = 0;
11501	if (net) {
11502		/* we should hit here */
11503		chk->whoTo = net;
11504		atomic_add_int(&chk->whoTo->ref_count, 1);
11505	} else {
11506		chk->whoTo = NULL;
11507	}
11508	drp->ch.chunk_type = SCTP_PACKET_DROPPED;
11509	drp->ch.chunk_length = htons(chk->send_size);
11510	spc = SCTP_SB_LIMIT_RCV(stcb->sctp_socket);
11511	if (spc < 0) {
11512		spc = 0;
11513	}
11514	drp->bottle_bw = htonl(spc);
11515	if (asoc->my_rwnd) {
11516		drp->current_onq = htonl(asoc->size_on_reasm_queue +
11517		    asoc->size_on_all_streams +
11518		    asoc->my_rwnd_control_len +
11519		    stcb->sctp_socket->so_rcv.sb_cc);
11520	} else {
11521		/*-
11522		 * If my rwnd is 0, possibly from mbuf depletion as well as
11523		 * space used, tell the peer there is NO space aka onq == bw
11524		 */
11525		drp->current_onq = htonl(spc);
11526	}
11527	drp->reserved = 0;
11528	datap = drp->data;
11529	m_copydata(m, iphlen, len, (caddr_t)datap);
11530	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
11531	asoc->ctrl_queue_cnt++;
11532}
11533
11534void
11535sctp_send_cwr(struct sctp_tcb *stcb, struct sctp_nets *net, uint32_t high_tsn, uint8_t override)
11536{
11537	struct sctp_association *asoc;
11538	struct sctp_cwr_chunk *cwr;
11539	struct sctp_tmit_chunk *chk;
11540
11541	SCTP_TCB_LOCK_ASSERT(stcb);
11542	if (net == NULL) {
11543		return;
11544	}
11545	asoc = &stcb->asoc;
11546	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
11547		if ((chk->rec.chunk_id.id == SCTP_ECN_CWR) && (net == chk->whoTo)) {
11548			/*
11549			 * found a previous CWR queued to same destination
11550			 * update it if needed
11551			 */
11552			uint32_t ctsn;
11553
11554			cwr = mtod(chk->data, struct sctp_cwr_chunk *);
11555			ctsn = ntohl(cwr->tsn);
11556			if (SCTP_TSN_GT(high_tsn, ctsn)) {
11557				cwr->tsn = htonl(high_tsn);
11558			}
11559			if (override & SCTP_CWR_REDUCE_OVERRIDE) {
11560				/* Make sure override is carried */
11561				cwr->ch.chunk_flags |= SCTP_CWR_REDUCE_OVERRIDE;
11562			}
11563			return;
11564		}
11565	}
11566	sctp_alloc_a_chunk(stcb, chk);
11567	if (chk == NULL) {
11568		return;
11569	}
11570	chk->copy_by_ref = 0;
11571	chk->rec.chunk_id.id = SCTP_ECN_CWR;
11572	chk->rec.chunk_id.can_take_data = 1;
11573	chk->flags = 0;
11574	chk->asoc = &stcb->asoc;
11575	chk->send_size = sizeof(struct sctp_cwr_chunk);
11576	chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_NOWAIT, 1, MT_HEADER);
11577	if (chk->data == NULL) {
11578		sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
11579		return;
11580	}
11581	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11582	SCTP_BUF_LEN(chk->data) = chk->send_size;
11583	chk->sent = SCTP_DATAGRAM_UNSENT;
11584	chk->snd_count = 0;
11585	chk->whoTo = net;
11586	atomic_add_int(&chk->whoTo->ref_count, 1);
11587	cwr = mtod(chk->data, struct sctp_cwr_chunk *);
11588	cwr->ch.chunk_type = SCTP_ECN_CWR;
11589	cwr->ch.chunk_flags = override;
11590	cwr->ch.chunk_length = htons(sizeof(struct sctp_cwr_chunk));
11591	cwr->tsn = htonl(high_tsn);
11592	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
11593	asoc->ctrl_queue_cnt++;
11594}
11595
11596void
11597sctp_add_stream_reset_out(struct sctp_tmit_chunk *chk,
11598    int number_entries, uint16_t * list,
11599    uint32_t seq, uint32_t resp_seq, uint32_t last_sent)
11600{
11601	uint16_t len, old_len, i;
11602	struct sctp_stream_reset_out_request *req_out;
11603	struct sctp_chunkhdr *ch;
11604
11605	ch = mtod(chk->data, struct sctp_chunkhdr *);
11606	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11607
11608	/* get to new offset for the param. */
11609	req_out = (struct sctp_stream_reset_out_request *)((caddr_t)ch + len);
11610	/* now how long will this param be? */
11611	len = (sizeof(struct sctp_stream_reset_out_request) + (sizeof(uint16_t) * number_entries));
11612	req_out->ph.param_type = htons(SCTP_STR_RESET_OUT_REQUEST);
11613	req_out->ph.param_length = htons(len);
11614	req_out->request_seq = htonl(seq);
11615	req_out->response_seq = htonl(resp_seq);
11616	req_out->send_reset_at_tsn = htonl(last_sent);
11617	if (number_entries) {
11618		for (i = 0; i < number_entries; i++) {
11619			req_out->list_of_streams[i] = htons(list[i]);
11620		}
11621	}
11622	if (SCTP_SIZE32(len) > len) {
11623		/*-
11624		 * Need to worry about the pad we may end up adding to the
11625		 * end. This is easy since the struct is either aligned to 4
11626		 * bytes or 2 bytes off.
11627		 */
11628		req_out->list_of_streams[number_entries] = 0;
11629	}
11630	/* now fix the chunk length */
11631	ch->chunk_length = htons(len + old_len);
11632	chk->book_size = len + old_len;
11633	chk->book_size_scale = 0;
11634	chk->send_size = SCTP_SIZE32(chk->book_size);
11635	SCTP_BUF_LEN(chk->data) = chk->send_size;
11636	return;
11637}
11638
11639static void
11640sctp_add_stream_reset_in(struct sctp_tmit_chunk *chk,
11641    int number_entries, uint16_t * list,
11642    uint32_t seq)
11643{
11644	uint16_t len, old_len, i;
11645	struct sctp_stream_reset_in_request *req_in;
11646	struct sctp_chunkhdr *ch;
11647
11648	ch = mtod(chk->data, struct sctp_chunkhdr *);
11649	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11650
11651	/* get to new offset for the param. */
11652	req_in = (struct sctp_stream_reset_in_request *)((caddr_t)ch + len);
11653	/* now how long will this param be? */
11654	len = (sizeof(struct sctp_stream_reset_in_request) + (sizeof(uint16_t) * number_entries));
11655	req_in->ph.param_type = htons(SCTP_STR_RESET_IN_REQUEST);
11656	req_in->ph.param_length = htons(len);
11657	req_in->request_seq = htonl(seq);
11658	if (number_entries) {
11659		for (i = 0; i < number_entries; i++) {
11660			req_in->list_of_streams[i] = htons(list[i]);
11661		}
11662	}
11663	if (SCTP_SIZE32(len) > len) {
11664		/*-
11665		 * Need to worry about the pad we may end up adding to the
11666		 * end. This is easy since the struct is either aligned to 4
11667		 * bytes or 2 bytes off.
11668		 */
11669		req_in->list_of_streams[number_entries] = 0;
11670	}
11671	/* now fix the chunk length */
11672	ch->chunk_length = htons(len + old_len);
11673	chk->book_size = len + old_len;
11674	chk->book_size_scale = 0;
11675	chk->send_size = SCTP_SIZE32(chk->book_size);
11676	SCTP_BUF_LEN(chk->data) = chk->send_size;
11677	return;
11678}
11679
11680static void
11681sctp_add_stream_reset_tsn(struct sctp_tmit_chunk *chk,
11682    uint32_t seq)
11683{
11684	uint16_t len, old_len;
11685	struct sctp_stream_reset_tsn_request *req_tsn;
11686	struct sctp_chunkhdr *ch;
11687
11688	ch = mtod(chk->data, struct sctp_chunkhdr *);
11689	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11690
11691	/* get to new offset for the param. */
11692	req_tsn = (struct sctp_stream_reset_tsn_request *)((caddr_t)ch + len);
11693	/* now how long will this param be? */
11694	len = sizeof(struct sctp_stream_reset_tsn_request);
11695	req_tsn->ph.param_type = htons(SCTP_STR_RESET_TSN_REQUEST);
11696	req_tsn->ph.param_length = htons(len);
11697	req_tsn->request_seq = htonl(seq);
11698
11699	/* now fix the chunk length */
11700	ch->chunk_length = htons(len + old_len);
11701	chk->send_size = len + old_len;
11702	chk->book_size = SCTP_SIZE32(chk->send_size);
11703	chk->book_size_scale = 0;
11704	SCTP_BUF_LEN(chk->data) = SCTP_SIZE32(chk->send_size);
11705	return;
11706}
11707
11708void
11709sctp_add_stream_reset_result(struct sctp_tmit_chunk *chk,
11710    uint32_t resp_seq, uint32_t result)
11711{
11712	uint16_t len, old_len;
11713	struct sctp_stream_reset_response *resp;
11714	struct sctp_chunkhdr *ch;
11715
11716	ch = mtod(chk->data, struct sctp_chunkhdr *);
11717	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11718
11719	/* get to new offset for the param. */
11720	resp = (struct sctp_stream_reset_response *)((caddr_t)ch + len);
11721	/* now how long will this param be? */
11722	len = sizeof(struct sctp_stream_reset_response);
11723	resp->ph.param_type = htons(SCTP_STR_RESET_RESPONSE);
11724	resp->ph.param_length = htons(len);
11725	resp->response_seq = htonl(resp_seq);
11726	resp->result = ntohl(result);
11727
11728	/* now fix the chunk length */
11729	ch->chunk_length = htons(len + old_len);
11730	chk->book_size = len + old_len;
11731	chk->book_size_scale = 0;
11732	chk->send_size = SCTP_SIZE32(chk->book_size);
11733	SCTP_BUF_LEN(chk->data) = chk->send_size;
11734	return;
11735}
11736
11737void
11738sctp_add_stream_reset_result_tsn(struct sctp_tmit_chunk *chk,
11739    uint32_t resp_seq, uint32_t result,
11740    uint32_t send_una, uint32_t recv_next)
11741{
11742	uint16_t len, old_len;
11743	struct sctp_stream_reset_response_tsn *resp;
11744	struct sctp_chunkhdr *ch;
11745
11746	ch = mtod(chk->data, struct sctp_chunkhdr *);
11747	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11748
11749	/* get to new offset for the param. */
11750	resp = (struct sctp_stream_reset_response_tsn *)((caddr_t)ch + len);
11751	/* now how long will this param be? */
11752	len = sizeof(struct sctp_stream_reset_response_tsn);
11753	resp->ph.param_type = htons(SCTP_STR_RESET_RESPONSE);
11754	resp->ph.param_length = htons(len);
11755	resp->response_seq = htonl(resp_seq);
11756	resp->result = htonl(result);
11757	resp->senders_next_tsn = htonl(send_una);
11758	resp->receivers_next_tsn = htonl(recv_next);
11759
11760	/* now fix the chunk length */
11761	ch->chunk_length = htons(len + old_len);
11762	chk->book_size = len + old_len;
11763	chk->send_size = SCTP_SIZE32(chk->book_size);
11764	chk->book_size_scale = 0;
11765	SCTP_BUF_LEN(chk->data) = chk->send_size;
11766	return;
11767}
11768
11769static void
11770sctp_add_an_out_stream(struct sctp_tmit_chunk *chk,
11771    uint32_t seq,
11772    uint16_t adding)
11773{
11774	uint16_t len, old_len;
11775	struct sctp_chunkhdr *ch;
11776	struct sctp_stream_reset_add_strm *addstr;
11777
11778	ch = mtod(chk->data, struct sctp_chunkhdr *);
11779	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11780
11781	/* get to new offset for the param. */
11782	addstr = (struct sctp_stream_reset_add_strm *)((caddr_t)ch + len);
11783	/* now how long will this param be? */
11784	len = sizeof(struct sctp_stream_reset_add_strm);
11785
11786	/* Fill it out. */
11787	addstr->ph.param_type = htons(SCTP_STR_RESET_ADD_OUT_STREAMS);
11788	addstr->ph.param_length = htons(len);
11789	addstr->request_seq = htonl(seq);
11790	addstr->number_of_streams = htons(adding);
11791	addstr->reserved = 0;
11792
11793	/* now fix the chunk length */
11794	ch->chunk_length = htons(len + old_len);
11795	chk->send_size = len + old_len;
11796	chk->book_size = SCTP_SIZE32(chk->send_size);
11797	chk->book_size_scale = 0;
11798	SCTP_BUF_LEN(chk->data) = SCTP_SIZE32(chk->send_size);
11799	return;
11800}
11801
11802static void
11803sctp_add_an_in_stream(struct sctp_tmit_chunk *chk,
11804    uint32_t seq,
11805    uint16_t adding)
11806{
11807	uint16_t len, old_len;
11808	struct sctp_chunkhdr *ch;
11809	struct sctp_stream_reset_add_strm *addstr;
11810
11811	ch = mtod(chk->data, struct sctp_chunkhdr *);
11812	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11813
11814	/* get to new offset for the param. */
11815	addstr = (struct sctp_stream_reset_add_strm *)((caddr_t)ch + len);
11816	/* now how long will this param be? */
11817	len = sizeof(struct sctp_stream_reset_add_strm);
11818	/* Fill it out. */
11819	addstr->ph.param_type = htons(SCTP_STR_RESET_ADD_IN_STREAMS);
11820	addstr->ph.param_length = htons(len);
11821	addstr->request_seq = htonl(seq);
11822	addstr->number_of_streams = htons(adding);
11823	addstr->reserved = 0;
11824
11825	/* now fix the chunk length */
11826	ch->chunk_length = htons(len + old_len);
11827	chk->send_size = len + old_len;
11828	chk->book_size = SCTP_SIZE32(chk->send_size);
11829	chk->book_size_scale = 0;
11830	SCTP_BUF_LEN(chk->data) = SCTP_SIZE32(chk->send_size);
11831	return;
11832}
11833
11834int
11835sctp_send_str_reset_req(struct sctp_tcb *stcb,
11836    uint16_t number_entries, uint16_t * list,
11837    uint8_t send_out_req,
11838    uint8_t send_in_req,
11839    uint8_t send_tsn_req,
11840    uint8_t add_stream,
11841    uint16_t adding_o,
11842    uint16_t adding_i, uint8_t peer_asked)
11843{
11844
11845	struct sctp_association *asoc;
11846	struct sctp_tmit_chunk *chk;
11847	struct sctp_chunkhdr *ch;
11848	uint32_t seq;
11849
11850	asoc = &stcb->asoc;
11851	if (asoc->stream_reset_outstanding) {
11852		/*-
11853		 * Already one pending, must get ACK back to clear the flag.
11854		 */
11855		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EBUSY);
11856		return (EBUSY);
11857	}
11858	if ((send_out_req == 0) && (send_in_req == 0) && (send_tsn_req == 0) &&
11859	    (add_stream == 0)) {
11860		/* nothing to do */
11861		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
11862		return (EINVAL);
11863	}
11864	if (send_tsn_req && (send_out_req || send_in_req)) {
11865		/* error, can't do that */
11866		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
11867		return (EINVAL);
11868	}
11869	if (number_entries > (MCLBYTES -
11870	    SCTP_MIN_OVERHEAD -
11871	    sizeof(struct sctp_chunkhdr) -
11872	    sizeof(struct sctp_stream_reset_out_request)) /
11873	    sizeof(uint16_t)) {
11874		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
11875		return (ENOMEM);
11876	}
11877	sctp_alloc_a_chunk(stcb, chk);
11878	if (chk == NULL) {
11879		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
11880		return (ENOMEM);
11881	}
11882	chk->copy_by_ref = 0;
11883	chk->rec.chunk_id.id = SCTP_STREAM_RESET;
11884	chk->rec.chunk_id.can_take_data = 0;
11885	chk->flags = 0;
11886	chk->asoc = &stcb->asoc;
11887	chk->book_size = sizeof(struct sctp_chunkhdr);
11888	chk->send_size = SCTP_SIZE32(chk->book_size);
11889	chk->book_size_scale = 0;
11890
11891	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_NOWAIT, 1, MT_DATA);
11892	if (chk->data == NULL) {
11893		sctp_free_a_chunk(stcb, chk, SCTP_SO_LOCKED);
11894		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
11895		return (ENOMEM);
11896	}
11897	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11898
11899	/* setup chunk parameters */
11900	chk->sent = SCTP_DATAGRAM_UNSENT;
11901	chk->snd_count = 0;
11902	if (stcb->asoc.alternate) {
11903		chk->whoTo = stcb->asoc.alternate;
11904	} else {
11905		chk->whoTo = stcb->asoc.primary_destination;
11906	}
11907	atomic_add_int(&chk->whoTo->ref_count, 1);
11908	ch = mtod(chk->data, struct sctp_chunkhdr *);
11909	ch->chunk_type = SCTP_STREAM_RESET;
11910	ch->chunk_flags = 0;
11911	ch->chunk_length = htons(chk->book_size);
11912	SCTP_BUF_LEN(chk->data) = chk->send_size;
11913
11914	seq = stcb->asoc.str_reset_seq_out;
11915	if (send_out_req) {
11916		sctp_add_stream_reset_out(chk, number_entries, list,
11917		    seq, (stcb->asoc.str_reset_seq_in - 1), (stcb->asoc.sending_seq - 1));
11918		asoc->stream_reset_out_is_outstanding = 1;
11919		seq++;
11920		asoc->stream_reset_outstanding++;
11921	}
11922	if ((add_stream & 1) &&
11923	    ((stcb->asoc.strm_realoutsize - stcb->asoc.streamoutcnt) < adding_o)) {
11924		/* Need to allocate more */
11925		struct sctp_stream_out *oldstream;
11926		struct sctp_stream_queue_pending *sp, *nsp;
11927		int i;
11928
11929#if defined(SCTP_DETAILED_STR_STATS)
11930		int j;
11931
11932#endif
11933
11934		oldstream = stcb->asoc.strmout;
11935		/* get some more */
11936		SCTP_MALLOC(stcb->asoc.strmout, struct sctp_stream_out *,
11937		    ((stcb->asoc.streamoutcnt + adding_o) * sizeof(struct sctp_stream_out)),
11938		    SCTP_M_STRMO);
11939		if (stcb->asoc.strmout == NULL) {
11940			uint8_t x;
11941
11942			stcb->asoc.strmout = oldstream;
11943			/* Turn off the bit */
11944			x = add_stream & 0xfe;
11945			add_stream = x;
11946			goto skip_stuff;
11947		}
11948		/*
11949		 * Ok now we proceed with copying the old out stuff and
11950		 * initializing the new stuff.
11951		 */
11952		SCTP_TCB_SEND_LOCK(stcb);
11953		stcb->asoc.ss_functions.sctp_ss_clear(stcb, &stcb->asoc, 0, 1);
11954		for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
11955			TAILQ_INIT(&stcb->asoc.strmout[i].outqueue);
11956			stcb->asoc.strmout[i].chunks_on_queues = oldstream[i].chunks_on_queues;
11957			stcb->asoc.strmout[i].next_sequence_send = oldstream[i].next_sequence_send;
11958			stcb->asoc.strmout[i].last_msg_incomplete = oldstream[i].last_msg_incomplete;
11959			stcb->asoc.strmout[i].stream_no = i;
11960			stcb->asoc.ss_functions.sctp_ss_init_stream(&stcb->asoc.strmout[i], &oldstream[i]);
11961			/* now anything on those queues? */
11962			TAILQ_FOREACH_SAFE(sp, &oldstream[i].outqueue, next, nsp) {
11963				TAILQ_REMOVE(&oldstream[i].outqueue, sp, next);
11964				TAILQ_INSERT_TAIL(&stcb->asoc.strmout[i].outqueue, sp, next);
11965			}
11966			/* Now move assoc pointers too */
11967			if (stcb->asoc.last_out_stream == &oldstream[i]) {
11968				stcb->asoc.last_out_stream = &stcb->asoc.strmout[i];
11969			}
11970			if (stcb->asoc.locked_on_sending == &oldstream[i]) {
11971				stcb->asoc.locked_on_sending = &stcb->asoc.strmout[i];
11972			}
11973		}
11974		/* now the new streams */
11975		stcb->asoc.ss_functions.sctp_ss_init(stcb, &stcb->asoc, 1);
11976		for (i = stcb->asoc.streamoutcnt; i < (stcb->asoc.streamoutcnt + adding_o); i++) {
11977			TAILQ_INIT(&stcb->asoc.strmout[i].outqueue);
11978			stcb->asoc.strmout[i].chunks_on_queues = 0;
11979#if defined(SCTP_DETAILED_STR_STATS)
11980			for (j = 0; j < SCTP_PR_SCTP_MAX + 1; j++) {
11981				stcb->asoc.strmout[i].abandoned_sent[j] = 0;
11982				stcb->asoc.strmout[i].abandoned_unsent[j] = 0;
11983			}
11984#else
11985			stcb->asoc.strmout[i].abandoned_sent[0] = 0;
11986			stcb->asoc.strmout[i].abandoned_unsent[0] = 0;
11987#endif
11988			stcb->asoc.strmout[i].next_sequence_send = 0x0;
11989			stcb->asoc.strmout[i].stream_no = i;
11990			stcb->asoc.strmout[i].last_msg_incomplete = 0;
11991			stcb->asoc.ss_functions.sctp_ss_init_stream(&stcb->asoc.strmout[i], NULL);
11992		}
11993		stcb->asoc.strm_realoutsize = stcb->asoc.streamoutcnt + adding_o;
11994		SCTP_FREE(oldstream, SCTP_M_STRMO);
11995		SCTP_TCB_SEND_UNLOCK(stcb);
11996	}
11997skip_stuff:
11998	if ((add_stream & 1) && (adding_o > 0)) {
11999		asoc->strm_pending_add_size = adding_o;
12000		asoc->peer_req_out = peer_asked;
12001		sctp_add_an_out_stream(chk, seq, adding_o);
12002		seq++;
12003		asoc->stream_reset_outstanding++;
12004	}
12005	if ((add_stream & 2) && (adding_i > 0)) {
12006		sctp_add_an_in_stream(chk, seq, adding_i);
12007		seq++;
12008		asoc->stream_reset_outstanding++;
12009	}
12010	if (send_in_req) {
12011		sctp_add_stream_reset_in(chk, number_entries, list, seq);
12012		seq++;
12013		asoc->stream_reset_outstanding++;
12014	}
12015	if (send_tsn_req) {
12016		sctp_add_stream_reset_tsn(chk, seq);
12017		asoc->stream_reset_outstanding++;
12018	}
12019	asoc->str_reset = chk;
12020	/* insert the chunk for sending */
12021	TAILQ_INSERT_TAIL(&asoc->control_send_queue,
12022	    chk,
12023	    sctp_next);
12024	asoc->ctrl_queue_cnt++;
12025	sctp_timer_start(SCTP_TIMER_TYPE_STRRESET, stcb->sctp_ep, stcb, chk->whoTo);
12026	return (0);
12027}
12028
12029void
12030sctp_send_abort(struct mbuf *m, int iphlen, struct sockaddr *src, struct sockaddr *dst,
12031    struct sctphdr *sh, uint32_t vtag, struct mbuf *cause,
12032    uint8_t mflowtype, uint32_t mflowid,
12033    uint32_t vrf_id, uint16_t port)
12034{
12035	/* Don't respond to an ABORT with an ABORT. */
12036	if (sctp_is_there_an_abort_here(m, iphlen, &vtag)) {
12037		if (cause)
12038			sctp_m_freem(cause);
12039		return;
12040	}
12041	sctp_send_resp_msg(src, dst, sh, vtag, SCTP_ABORT_ASSOCIATION, cause,
12042	    mflowtype, mflowid,
12043	    vrf_id, port);
12044	return;
12045}
12046
12047void
12048sctp_send_operr_to(struct sockaddr *src, struct sockaddr *dst,
12049    struct sctphdr *sh, uint32_t vtag, struct mbuf *cause,
12050    uint8_t mflowtype, uint32_t mflowid,
12051    uint32_t vrf_id, uint16_t port)
12052{
12053	sctp_send_resp_msg(src, dst, sh, vtag, SCTP_OPERATION_ERROR, cause,
12054	    mflowtype, mflowid,
12055	    vrf_id, port);
12056	return;
12057}
12058
12059static struct mbuf *
12060sctp_copy_resume(struct uio *uio,
12061    int max_send_len,
12062    int user_marks_eor,
12063    int *error,
12064    uint32_t * sndout,
12065    struct mbuf **new_tail)
12066{
12067	struct mbuf *m;
12068
12069	m = m_uiotombuf(uio, M_WAITOK, max_send_len, 0,
12070	    (M_PKTHDR | (user_marks_eor ? M_EOR : 0)));
12071	if (m == NULL) {
12072		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOBUFS);
12073		*error = ENOBUFS;
12074	} else {
12075		*sndout = m_length(m, NULL);
12076		*new_tail = m_last(m);
12077	}
12078	return (m);
12079}
12080
12081static int
12082sctp_copy_one(struct sctp_stream_queue_pending *sp,
12083    struct uio *uio,
12084    int resv_upfront)
12085{
12086	int left;
12087
12088	left = sp->length;
12089	sp->data = m_uiotombuf(uio, M_WAITOK, sp->length,
12090	    resv_upfront, 0);
12091	if (sp->data == NULL) {
12092		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOBUFS);
12093		return (ENOBUFS);
12094	}
12095	sp->tail_mbuf = m_last(sp->data);
12096	return (0);
12097}
12098
12099
12100
12101static struct sctp_stream_queue_pending *
12102sctp_copy_it_in(struct sctp_tcb *stcb,
12103    struct sctp_association *asoc,
12104    struct sctp_sndrcvinfo *srcv,
12105    struct uio *uio,
12106    struct sctp_nets *net,
12107    int max_send_len,
12108    int user_marks_eor,
12109    int *error)
12110{
12111	/*-
12112	 * This routine must be very careful in its work. Protocol
12113	 * processing is up and running so care must be taken to spl...()
12114	 * when you need to do something that may effect the stcb/asoc. The
12115	 * sb is locked however. When data is copied the protocol processing
12116	 * should be enabled since this is a slower operation...
12117	 */
12118	struct sctp_stream_queue_pending *sp = NULL;
12119	int resv_in_first;
12120
12121	*error = 0;
12122	/* Now can we send this? */
12123	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
12124	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
12125	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
12126	    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
12127		/* got data while shutting down */
12128		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12129		*error = ECONNRESET;
12130		goto out_now;
12131	}
12132	sctp_alloc_a_strmoq(stcb, sp);
12133	if (sp == NULL) {
12134		SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
12135		*error = ENOMEM;
12136		goto out_now;
12137	}
12138	sp->act_flags = 0;
12139	sp->sender_all_done = 0;
12140	sp->sinfo_flags = srcv->sinfo_flags;
12141	sp->timetolive = srcv->sinfo_timetolive;
12142	sp->ppid = srcv->sinfo_ppid;
12143	sp->context = srcv->sinfo_context;
12144	(void)SCTP_GETTIME_TIMEVAL(&sp->ts);
12145
12146	sp->stream = srcv->sinfo_stream;
12147	sp->length = min(uio->uio_resid, max_send_len);
12148	if ((sp->length == (uint32_t) uio->uio_resid) &&
12149	    ((user_marks_eor == 0) ||
12150	    (srcv->sinfo_flags & SCTP_EOF) ||
12151	    (user_marks_eor && (srcv->sinfo_flags & SCTP_EOR)))) {
12152		sp->msg_is_complete = 1;
12153	} else {
12154		sp->msg_is_complete = 0;
12155	}
12156	sp->sender_all_done = 0;
12157	sp->some_taken = 0;
12158	sp->put_last_out = 0;
12159	resv_in_first = sizeof(struct sctp_data_chunk);
12160	sp->data = sp->tail_mbuf = NULL;
12161	if (sp->length == 0) {
12162		*error = 0;
12163		goto skip_copy;
12164	}
12165	if (srcv->sinfo_keynumber_valid) {
12166		sp->auth_keyid = srcv->sinfo_keynumber;
12167	} else {
12168		sp->auth_keyid = stcb->asoc.authinfo.active_keyid;
12169	}
12170	if (sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks)) {
12171		sctp_auth_key_acquire(stcb, sp->auth_keyid);
12172		sp->holds_key_ref = 1;
12173	}
12174	*error = sctp_copy_one(sp, uio, resv_in_first);
12175skip_copy:
12176	if (*error) {
12177		sctp_free_a_strmoq(stcb, sp, SCTP_SO_LOCKED);
12178		sp = NULL;
12179	} else {
12180		if (sp->sinfo_flags & SCTP_ADDR_OVER) {
12181			sp->net = net;
12182			atomic_add_int(&sp->net->ref_count, 1);
12183		} else {
12184			sp->net = NULL;
12185		}
12186		sctp_set_prsctp_policy(sp);
12187	}
12188out_now:
12189	return (sp);
12190}
12191
12192
12193int
12194sctp_sosend(struct socket *so,
12195    struct sockaddr *addr,
12196    struct uio *uio,
12197    struct mbuf *top,
12198    struct mbuf *control,
12199    int flags,
12200    struct thread *p
12201)
12202{
12203	int error, use_sndinfo = 0;
12204	struct sctp_sndrcvinfo sndrcvninfo;
12205	struct sockaddr *addr_to_use;
12206
12207#if defined(INET) && defined(INET6)
12208	struct sockaddr_in sin;
12209
12210#endif
12211
12212	if (control) {
12213		/* process cmsg snd/rcv info (maybe a assoc-id) */
12214		if (sctp_find_cmsg(SCTP_SNDRCV, (void *)&sndrcvninfo, control,
12215		    sizeof(sndrcvninfo))) {
12216			/* got one */
12217			use_sndinfo = 1;
12218		}
12219	}
12220	addr_to_use = addr;
12221#if defined(INET) && defined(INET6)
12222	if ((addr) && (addr->sa_family == AF_INET6)) {
12223		struct sockaddr_in6 *sin6;
12224
12225		sin6 = (struct sockaddr_in6 *)addr;
12226		if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
12227			in6_sin6_2_sin(&sin, sin6);
12228			addr_to_use = (struct sockaddr *)&sin;
12229		}
12230	}
12231#endif
12232	error = sctp_lower_sosend(so, addr_to_use, uio, top,
12233	    control,
12234	    flags,
12235	    use_sndinfo ? &sndrcvninfo : NULL
12236	    ,p
12237	    );
12238	return (error);
12239}
12240
12241
12242int
12243sctp_lower_sosend(struct socket *so,
12244    struct sockaddr *addr,
12245    struct uio *uio,
12246    struct mbuf *i_pak,
12247    struct mbuf *control,
12248    int flags,
12249    struct sctp_sndrcvinfo *srcv
12250    ,
12251    struct thread *p
12252)
12253{
12254	unsigned int sndlen = 0, max_len;
12255	int error, len;
12256	struct mbuf *top = NULL;
12257	int queue_only = 0, queue_only_for_init = 0;
12258	int free_cnt_applied = 0;
12259	int un_sent;
12260	int now_filled = 0;
12261	unsigned int inqueue_bytes = 0;
12262	struct sctp_block_entry be;
12263	struct sctp_inpcb *inp;
12264	struct sctp_tcb *stcb = NULL;
12265	struct timeval now;
12266	struct sctp_nets *net;
12267	struct sctp_association *asoc;
12268	struct sctp_inpcb *t_inp;
12269	int user_marks_eor;
12270	int create_lock_applied = 0;
12271	int nagle_applies = 0;
12272	int some_on_control = 0;
12273	int got_all_of_the_send = 0;
12274	int hold_tcblock = 0;
12275	int non_blocking = 0;
12276	uint32_t local_add_more, local_soresv = 0;
12277	uint16_t port;
12278	uint16_t sinfo_flags;
12279	sctp_assoc_t sinfo_assoc_id;
12280
12281	error = 0;
12282	net = NULL;
12283	stcb = NULL;
12284	asoc = NULL;
12285
12286	t_inp = inp = (struct sctp_inpcb *)so->so_pcb;
12287	if (inp == NULL) {
12288		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12289		error = EINVAL;
12290		if (i_pak) {
12291			SCTP_RELEASE_PKT(i_pak);
12292		}
12293		return (error);
12294	}
12295	if ((uio == NULL) && (i_pak == NULL)) {
12296		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12297		return (EINVAL);
12298	}
12299	user_marks_eor = sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR);
12300	atomic_add_int(&inp->total_sends, 1);
12301	if (uio) {
12302		if (uio->uio_resid < 0) {
12303			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12304			return (EINVAL);
12305		}
12306		sndlen = uio->uio_resid;
12307	} else {
12308		top = SCTP_HEADER_TO_CHAIN(i_pak);
12309		sndlen = SCTP_HEADER_LEN(i_pak);
12310	}
12311	SCTPDBG(SCTP_DEBUG_OUTPUT1, "Send called addr:%p send length %d\n",
12312	    (void *)addr,
12313	    sndlen);
12314	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
12315	    (inp->sctp_socket->so_qlimit)) {
12316		/* The listener can NOT send */
12317		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOTCONN);
12318		error = ENOTCONN;
12319		goto out_unlocked;
12320	}
12321	/**
12322	 * Pre-screen address, if one is given the sin-len
12323	 * must be set correctly!
12324	 */
12325	if (addr) {
12326		union sctp_sockstore *raddr = (union sctp_sockstore *)addr;
12327
12328		switch (raddr->sa.sa_family) {
12329#ifdef INET
12330		case AF_INET:
12331			if (raddr->sin.sin_len != sizeof(struct sockaddr_in)) {
12332				SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12333				error = EINVAL;
12334				goto out_unlocked;
12335			}
12336			port = raddr->sin.sin_port;
12337			break;
12338#endif
12339#ifdef INET6
12340		case AF_INET6:
12341			if (raddr->sin6.sin6_len != sizeof(struct sockaddr_in6)) {
12342				SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12343				error = EINVAL;
12344				goto out_unlocked;
12345			}
12346			port = raddr->sin6.sin6_port;
12347			break;
12348#endif
12349		default:
12350			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EAFNOSUPPORT);
12351			error = EAFNOSUPPORT;
12352			goto out_unlocked;
12353		}
12354	} else
12355		port = 0;
12356
12357	if (srcv) {
12358		sinfo_flags = srcv->sinfo_flags;
12359		sinfo_assoc_id = srcv->sinfo_assoc_id;
12360		if (INVALID_SINFO_FLAG(sinfo_flags) ||
12361		    PR_SCTP_INVALID_POLICY(sinfo_flags)) {
12362			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12363			error = EINVAL;
12364			goto out_unlocked;
12365		}
12366		if (srcv->sinfo_flags)
12367			SCTP_STAT_INCR(sctps_sends_with_flags);
12368	} else {
12369		sinfo_flags = inp->def_send.sinfo_flags;
12370		sinfo_assoc_id = inp->def_send.sinfo_assoc_id;
12371	}
12372	if (sinfo_flags & SCTP_SENDALL) {
12373		/* its a sendall */
12374		error = sctp_sendall(inp, uio, top, srcv);
12375		top = NULL;
12376		goto out_unlocked;
12377	}
12378	if ((sinfo_flags & SCTP_ADDR_OVER) && (addr == NULL)) {
12379		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12380		error = EINVAL;
12381		goto out_unlocked;
12382	}
12383	/* now we must find the assoc */
12384	if ((inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) ||
12385	    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
12386		SCTP_INP_RLOCK(inp);
12387		stcb = LIST_FIRST(&inp->sctp_asoc_list);
12388		if (stcb) {
12389			SCTP_TCB_LOCK(stcb);
12390			hold_tcblock = 1;
12391		}
12392		SCTP_INP_RUNLOCK(inp);
12393	} else if (sinfo_assoc_id) {
12394		stcb = sctp_findassociation_ep_asocid(inp, sinfo_assoc_id, 0);
12395	} else if (addr) {
12396		/*-
12397		 * Since we did not use findep we must
12398		 * increment it, and if we don't find a tcb
12399		 * decrement it.
12400		 */
12401		SCTP_INP_WLOCK(inp);
12402		SCTP_INP_INCR_REF(inp);
12403		SCTP_INP_WUNLOCK(inp);
12404		stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
12405		if (stcb == NULL) {
12406			SCTP_INP_WLOCK(inp);
12407			SCTP_INP_DECR_REF(inp);
12408			SCTP_INP_WUNLOCK(inp);
12409		} else {
12410			hold_tcblock = 1;
12411		}
12412	}
12413	if ((stcb == NULL) && (addr)) {
12414		/* Possible implicit send? */
12415		SCTP_ASOC_CREATE_LOCK(inp);
12416		create_lock_applied = 1;
12417		if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
12418		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
12419			/* Should I really unlock ? */
12420			SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12421			error = EINVAL;
12422			goto out_unlocked;
12423
12424		}
12425		if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) &&
12426		    (addr->sa_family == AF_INET6)) {
12427			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12428			error = EINVAL;
12429			goto out_unlocked;
12430		}
12431		SCTP_INP_WLOCK(inp);
12432		SCTP_INP_INCR_REF(inp);
12433		SCTP_INP_WUNLOCK(inp);
12434		/* With the lock applied look again */
12435		stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
12436		if ((stcb == NULL) && (control != NULL) && (port > 0)) {
12437			stcb = sctp_findassociation_cmsgs(&t_inp, port, control, &net, &error);
12438		}
12439		if (stcb == NULL) {
12440			SCTP_INP_WLOCK(inp);
12441			SCTP_INP_DECR_REF(inp);
12442			SCTP_INP_WUNLOCK(inp);
12443		} else {
12444			hold_tcblock = 1;
12445		}
12446		if (error) {
12447			goto out_unlocked;
12448		}
12449		if (t_inp != inp) {
12450			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOTCONN);
12451			error = ENOTCONN;
12452			goto out_unlocked;
12453		}
12454	}
12455	if (stcb == NULL) {
12456		if (addr == NULL) {
12457			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOENT);
12458			error = ENOENT;
12459			goto out_unlocked;
12460		} else {
12461			/* We must go ahead and start the INIT process */
12462			uint32_t vrf_id;
12463
12464			if ((sinfo_flags & SCTP_ABORT) ||
12465			    ((sinfo_flags & SCTP_EOF) && (sndlen == 0))) {
12466				/*-
12467				 * User asks to abort a non-existant assoc,
12468				 * or EOF a non-existant assoc with no data
12469				 */
12470				SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOENT);
12471				error = ENOENT;
12472				goto out_unlocked;
12473			}
12474			/* get an asoc/stcb struct */
12475			vrf_id = inp->def_vrf_id;
12476#ifdef INVARIANTS
12477			if (create_lock_applied == 0) {
12478				panic("Error, should hold create lock and I don't?");
12479			}
12480#endif
12481			stcb = sctp_aloc_assoc(inp, addr, &error, 0, vrf_id,
12482			    p
12483			    );
12484			if (stcb == NULL) {
12485				/* Error is setup for us in the call */
12486				goto out_unlocked;
12487			}
12488			if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) {
12489				stcb->sctp_ep->sctp_flags |= SCTP_PCB_FLAGS_CONNECTED;
12490				/*
12491				 * Set the connected flag so we can queue
12492				 * data
12493				 */
12494				soisconnecting(so);
12495			}
12496			hold_tcblock = 1;
12497			if (create_lock_applied) {
12498				SCTP_ASOC_CREATE_UNLOCK(inp);
12499				create_lock_applied = 0;
12500			} else {
12501				SCTP_PRINTF("Huh-3? create lock should have been on??\n");
12502			}
12503			/*
12504			 * Turn on queue only flag to prevent data from
12505			 * being sent
12506			 */
12507			queue_only = 1;
12508			asoc = &stcb->asoc;
12509			SCTP_SET_STATE(asoc, SCTP_STATE_COOKIE_WAIT);
12510			(void)SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
12511
12512			/* initialize authentication params for the assoc */
12513			sctp_initialize_auth_params(inp, stcb);
12514
12515			if (control) {
12516				if (sctp_process_cmsgs_for_init(stcb, control, &error)) {
12517					sctp_free_assoc(inp, stcb, SCTP_PCBFREE_FORCE, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_7);
12518					hold_tcblock = 0;
12519					stcb = NULL;
12520					goto out_unlocked;
12521				}
12522			}
12523			/* out with the INIT */
12524			queue_only_for_init = 1;
12525			/*-
12526			 * we may want to dig in after this call and adjust the MTU
12527			 * value. It defaulted to 1500 (constant) but the ro
12528			 * structure may now have an update and thus we may need to
12529			 * change it BEFORE we append the message.
12530			 */
12531		}
12532	} else
12533		asoc = &stcb->asoc;
12534	if (srcv == NULL)
12535		srcv = (struct sctp_sndrcvinfo *)&asoc->def_send;
12536	if (srcv->sinfo_flags & SCTP_ADDR_OVER) {
12537		if (addr)
12538			net = sctp_findnet(stcb, addr);
12539		else
12540			net = NULL;
12541		if ((net == NULL) ||
12542		    ((port != 0) && (port != stcb->rport))) {
12543			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12544			error = EINVAL;
12545			goto out_unlocked;
12546		}
12547	} else {
12548		if (stcb->asoc.alternate) {
12549			net = stcb->asoc.alternate;
12550		} else {
12551			net = stcb->asoc.primary_destination;
12552		}
12553	}
12554	atomic_add_int(&stcb->total_sends, 1);
12555	/* Keep the stcb from being freed under our feet */
12556	atomic_add_int(&asoc->refcnt, 1);
12557	free_cnt_applied = 1;
12558
12559	if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NO_FRAGMENT)) {
12560		if (sndlen > asoc->smallest_mtu) {
12561			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EMSGSIZE);
12562			error = EMSGSIZE;
12563			goto out_unlocked;
12564		}
12565	}
12566	if (SCTP_SO_IS_NBIO(so)
12567	    || (flags & MSG_NBIO)
12568	    ) {
12569		non_blocking = 1;
12570	}
12571	/* would we block? */
12572	if (non_blocking) {
12573		if (hold_tcblock == 0) {
12574			SCTP_TCB_LOCK(stcb);
12575			hold_tcblock = 1;
12576		}
12577		inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12578		if ((SCTP_SB_LIMIT_SND(so) < (sndlen + inqueue_bytes + stcb->asoc.sb_send_resv)) ||
12579		    (stcb->asoc.chunks_on_out_queue >= SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue))) {
12580			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EWOULDBLOCK);
12581			if (sndlen > SCTP_SB_LIMIT_SND(so))
12582				error = EMSGSIZE;
12583			else
12584				error = EWOULDBLOCK;
12585			goto out_unlocked;
12586		}
12587		stcb->asoc.sb_send_resv += sndlen;
12588		SCTP_TCB_UNLOCK(stcb);
12589		hold_tcblock = 0;
12590	} else {
12591		atomic_add_int(&stcb->asoc.sb_send_resv, sndlen);
12592	}
12593	local_soresv = sndlen;
12594	if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
12595		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12596		error = ECONNRESET;
12597		goto out_unlocked;
12598	}
12599	if (create_lock_applied) {
12600		SCTP_ASOC_CREATE_UNLOCK(inp);
12601		create_lock_applied = 0;
12602	}
12603	if (asoc->stream_reset_outstanding) {
12604		/*
12605		 * Can't queue any data while stream reset is underway.
12606		 */
12607		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EAGAIN);
12608		error = EAGAIN;
12609		goto out_unlocked;
12610	}
12611	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
12612	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
12613		queue_only = 1;
12614	}
12615	/* we are now done with all control */
12616	if (control) {
12617		sctp_m_freem(control);
12618		control = NULL;
12619	}
12620	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
12621	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
12622	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
12623	    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
12624		if (srcv->sinfo_flags & SCTP_ABORT) {
12625			;
12626		} else {
12627			SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12628			error = ECONNRESET;
12629			goto out_unlocked;
12630		}
12631	}
12632	/* Ok, we will attempt a msgsnd :> */
12633	if (p) {
12634		p->td_ru.ru_msgsnd++;
12635	}
12636	/* Are we aborting? */
12637	if (srcv->sinfo_flags & SCTP_ABORT) {
12638		struct mbuf *mm;
12639		int tot_demand, tot_out = 0, max_out;
12640
12641		SCTP_STAT_INCR(sctps_sends_with_abort);
12642		if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
12643		    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
12644			/* It has to be up before we abort */
12645			/* how big is the user initiated abort? */
12646			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12647			error = EINVAL;
12648			goto out;
12649		}
12650		if (hold_tcblock) {
12651			SCTP_TCB_UNLOCK(stcb);
12652			hold_tcblock = 0;
12653		}
12654		if (top) {
12655			struct mbuf *cntm = NULL;
12656
12657			mm = sctp_get_mbuf_for_msg(sizeof(struct sctp_paramhdr), 0, M_WAITOK, 1, MT_DATA);
12658			if (sndlen != 0) {
12659				for (cntm = top; cntm; cntm = SCTP_BUF_NEXT(cntm)) {
12660					tot_out += SCTP_BUF_LEN(cntm);
12661				}
12662			}
12663		} else {
12664			/* Must fit in a MTU */
12665			tot_out = sndlen;
12666			tot_demand = (tot_out + sizeof(struct sctp_paramhdr));
12667			if (tot_demand > SCTP_DEFAULT_ADD_MORE) {
12668				/* To big */
12669				SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EMSGSIZE);
12670				error = EMSGSIZE;
12671				goto out;
12672			}
12673			mm = sctp_get_mbuf_for_msg(tot_demand, 0, M_WAITOK, 1, MT_DATA);
12674		}
12675		if (mm == NULL) {
12676			SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
12677			error = ENOMEM;
12678			goto out;
12679		}
12680		max_out = asoc->smallest_mtu - sizeof(struct sctp_paramhdr);
12681		max_out -= sizeof(struct sctp_abort_msg);
12682		if (tot_out > max_out) {
12683			tot_out = max_out;
12684		}
12685		if (mm) {
12686			struct sctp_paramhdr *ph;
12687
12688			/* now move forward the data pointer */
12689			ph = mtod(mm, struct sctp_paramhdr *);
12690			ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
12691			ph->param_length = htons(sizeof(struct sctp_paramhdr) + tot_out);
12692			ph++;
12693			SCTP_BUF_LEN(mm) = tot_out + sizeof(struct sctp_paramhdr);
12694			if (top == NULL) {
12695				error = uiomove((caddr_t)ph, (int)tot_out, uio);
12696				if (error) {
12697					/*-
12698					 * Here if we can't get his data we
12699					 * still abort we just don't get to
12700					 * send the users note :-0
12701					 */
12702					sctp_m_freem(mm);
12703					mm = NULL;
12704				}
12705			} else {
12706				if (sndlen != 0) {
12707					SCTP_BUF_NEXT(mm) = top;
12708				}
12709			}
12710		}
12711		if (hold_tcblock == 0) {
12712			SCTP_TCB_LOCK(stcb);
12713		}
12714		atomic_add_int(&stcb->asoc.refcnt, -1);
12715		free_cnt_applied = 0;
12716		/* release this lock, otherwise we hang on ourselves */
12717		sctp_abort_an_association(stcb->sctp_ep, stcb, mm, SCTP_SO_LOCKED);
12718		/* now relock the stcb so everything is sane */
12719		hold_tcblock = 0;
12720		stcb = NULL;
12721		/*
12722		 * In this case top is already chained to mm avoid double
12723		 * free, since we free it below if top != NULL and driver
12724		 * would free it after sending the packet out
12725		 */
12726		if (sndlen != 0) {
12727			top = NULL;
12728		}
12729		goto out_unlocked;
12730	}
12731	/* Calculate the maximum we can send */
12732	inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12733	if (SCTP_SB_LIMIT_SND(so) > inqueue_bytes) {
12734		if (non_blocking) {
12735			/* we already checked for non-blocking above. */
12736			max_len = sndlen;
12737		} else {
12738			max_len = SCTP_SB_LIMIT_SND(so) - inqueue_bytes;
12739		}
12740	} else {
12741		max_len = 0;
12742	}
12743	if (hold_tcblock) {
12744		SCTP_TCB_UNLOCK(stcb);
12745		hold_tcblock = 0;
12746	}
12747	/* Is the stream no. valid? */
12748	if (srcv->sinfo_stream >= asoc->streamoutcnt) {
12749		/* Invalid stream number */
12750		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12751		error = EINVAL;
12752		goto out_unlocked;
12753	}
12754	if (asoc->strmout == NULL) {
12755		/* huh? software error */
12756		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EFAULT);
12757		error = EFAULT;
12758		goto out_unlocked;
12759	}
12760	/* Unless E_EOR mode is on, we must make a send FIT in one call. */
12761	if ((user_marks_eor == 0) &&
12762	    (sndlen > SCTP_SB_LIMIT_SND(stcb->sctp_socket))) {
12763		/* It will NEVER fit */
12764		SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EMSGSIZE);
12765		error = EMSGSIZE;
12766		goto out_unlocked;
12767	}
12768	if ((uio == NULL) && user_marks_eor) {
12769		/*-
12770		 * We do not support eeor mode for
12771		 * sending with mbuf chains (like sendfile).
12772		 */
12773		SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12774		error = EINVAL;
12775		goto out_unlocked;
12776	}
12777	if (user_marks_eor) {
12778		local_add_more = min(SCTP_SB_LIMIT_SND(so), SCTP_BASE_SYSCTL(sctp_add_more_threshold));
12779	} else {
12780		/*-
12781		 * For non-eeor the whole message must fit in
12782		 * the socket send buffer.
12783		 */
12784		local_add_more = sndlen;
12785	}
12786	len = 0;
12787	if (non_blocking) {
12788		goto skip_preblock;
12789	}
12790	if (((max_len <= local_add_more) &&
12791	    (SCTP_SB_LIMIT_SND(so) >= local_add_more)) ||
12792	    (max_len == 0) ||
12793	    ((stcb->asoc.chunks_on_out_queue + stcb->asoc.stream_queue_cnt) >= SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue))) {
12794		/* No room right now ! */
12795		SOCKBUF_LOCK(&so->so_snd);
12796		inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12797		while ((SCTP_SB_LIMIT_SND(so) < (inqueue_bytes + local_add_more)) ||
12798		    ((stcb->asoc.stream_queue_cnt + stcb->asoc.chunks_on_out_queue) >= SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue))) {
12799			SCTPDBG(SCTP_DEBUG_OUTPUT1, "pre_block limit:%u <(inq:%d + %d) || (%d+%d > %d)\n",
12800			    (unsigned int)SCTP_SB_LIMIT_SND(so),
12801			    inqueue_bytes,
12802			    local_add_more,
12803			    stcb->asoc.stream_queue_cnt,
12804			    stcb->asoc.chunks_on_out_queue,
12805			    SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue));
12806			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
12807				sctp_log_block(SCTP_BLOCK_LOG_INTO_BLKA, asoc, sndlen);
12808			}
12809			be.error = 0;
12810			stcb->block_entry = &be;
12811			error = sbwait(&so->so_snd);
12812			stcb->block_entry = NULL;
12813			if (error || so->so_error || be.error) {
12814				if (error == 0) {
12815					if (so->so_error)
12816						error = so->so_error;
12817					if (be.error) {
12818						error = be.error;
12819					}
12820				}
12821				SOCKBUF_UNLOCK(&so->so_snd);
12822				goto out_unlocked;
12823			}
12824			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
12825				sctp_log_block(SCTP_BLOCK_LOG_OUTOF_BLK,
12826				    asoc, stcb->asoc.total_output_queue_size);
12827			}
12828			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
12829				goto out_unlocked;
12830			}
12831			inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12832		}
12833		if (SCTP_SB_LIMIT_SND(so) > inqueue_bytes) {
12834			max_len = SCTP_SB_LIMIT_SND(so) - inqueue_bytes;
12835		} else {
12836			max_len = 0;
12837		}
12838		SOCKBUF_UNLOCK(&so->so_snd);
12839	}
12840skip_preblock:
12841	if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
12842		goto out_unlocked;
12843	}
12844	/*
12845	 * sndlen covers for mbuf case uio_resid covers for the non-mbuf
12846	 * case NOTE: uio will be null when top/mbuf is passed
12847	 */
12848	if (sndlen == 0) {
12849		if (srcv->sinfo_flags & SCTP_EOF) {
12850			got_all_of_the_send = 1;
12851			goto dataless_eof;
12852		} else {
12853			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12854			error = EINVAL;
12855			goto out;
12856		}
12857	}
12858	if (top == NULL) {
12859		struct sctp_stream_queue_pending *sp;
12860		struct sctp_stream_out *strm;
12861		uint32_t sndout;
12862
12863		SCTP_TCB_SEND_LOCK(stcb);
12864		if ((asoc->stream_locked) &&
12865		    (asoc->stream_locked_on != srcv->sinfo_stream)) {
12866			SCTP_TCB_SEND_UNLOCK(stcb);
12867			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12868			error = EINVAL;
12869			goto out;
12870		}
12871		SCTP_TCB_SEND_UNLOCK(stcb);
12872
12873		strm = &stcb->asoc.strmout[srcv->sinfo_stream];
12874		if (strm->last_msg_incomplete == 0) {
12875	do_a_copy_in:
12876			sp = sctp_copy_it_in(stcb, asoc, srcv, uio, net, max_len, user_marks_eor, &error);
12877			if ((sp == NULL) || (error)) {
12878				goto out;
12879			}
12880			SCTP_TCB_SEND_LOCK(stcb);
12881			if (sp->msg_is_complete) {
12882				strm->last_msg_incomplete = 0;
12883				asoc->stream_locked = 0;
12884			} else {
12885				/*
12886				 * Just got locked to this guy in case of an
12887				 * interrupt.
12888				 */
12889				strm->last_msg_incomplete = 1;
12890				asoc->stream_locked = 1;
12891				asoc->stream_locked_on = srcv->sinfo_stream;
12892				sp->sender_all_done = 0;
12893			}
12894			sctp_snd_sb_alloc(stcb, sp->length);
12895			atomic_add_int(&asoc->stream_queue_cnt, 1);
12896			if (srcv->sinfo_flags & SCTP_UNORDERED) {
12897				SCTP_STAT_INCR(sctps_sends_with_unord);
12898			}
12899			TAILQ_INSERT_TAIL(&strm->outqueue, sp, next);
12900			stcb->asoc.ss_functions.sctp_ss_add_to_stream(stcb, asoc, strm, sp, 1);
12901			SCTP_TCB_SEND_UNLOCK(stcb);
12902		} else {
12903			SCTP_TCB_SEND_LOCK(stcb);
12904			sp = TAILQ_LAST(&strm->outqueue, sctp_streamhead);
12905			SCTP_TCB_SEND_UNLOCK(stcb);
12906			if (sp == NULL) {
12907				/* ???? Huh ??? last msg is gone */
12908#ifdef INVARIANTS
12909				panic("Warning: Last msg marked incomplete, yet nothing left?");
12910#else
12911				SCTP_PRINTF("Warning: Last msg marked incomplete, yet nothing left?\n");
12912				strm->last_msg_incomplete = 0;
12913#endif
12914				goto do_a_copy_in;
12915
12916			}
12917		}
12918		while (uio->uio_resid > 0) {
12919			/* How much room do we have? */
12920			struct mbuf *new_tail, *mm;
12921
12922			if (SCTP_SB_LIMIT_SND(so) > stcb->asoc.total_output_queue_size)
12923				max_len = SCTP_SB_LIMIT_SND(so) - stcb->asoc.total_output_queue_size;
12924			else
12925				max_len = 0;
12926
12927			if ((max_len > SCTP_BASE_SYSCTL(sctp_add_more_threshold)) ||
12928			    (max_len && (SCTP_SB_LIMIT_SND(so) < SCTP_BASE_SYSCTL(sctp_add_more_threshold))) ||
12929			    (uio->uio_resid && (uio->uio_resid <= (int)max_len))) {
12930				sndout = 0;
12931				new_tail = NULL;
12932				if (hold_tcblock) {
12933					SCTP_TCB_UNLOCK(stcb);
12934					hold_tcblock = 0;
12935				}
12936				mm = sctp_copy_resume(uio, max_len, user_marks_eor, &error, &sndout, &new_tail);
12937				if ((mm == NULL) || error) {
12938					if (mm) {
12939						sctp_m_freem(mm);
12940					}
12941					goto out;
12942				}
12943				/* Update the mbuf and count */
12944				SCTP_TCB_SEND_LOCK(stcb);
12945				if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
12946					/*
12947					 * we need to get out. Peer probably
12948					 * aborted.
12949					 */
12950					sctp_m_freem(mm);
12951					if (stcb->asoc.state & SCTP_PCB_FLAGS_WAS_ABORTED) {
12952						SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12953						error = ECONNRESET;
12954					}
12955					SCTP_TCB_SEND_UNLOCK(stcb);
12956					goto out;
12957				}
12958				if (sp->tail_mbuf) {
12959					/* tack it to the end */
12960					SCTP_BUF_NEXT(sp->tail_mbuf) = mm;
12961					sp->tail_mbuf = new_tail;
12962				} else {
12963					/* A stolen mbuf */
12964					sp->data = mm;
12965					sp->tail_mbuf = new_tail;
12966				}
12967				sctp_snd_sb_alloc(stcb, sndout);
12968				atomic_add_int(&sp->length, sndout);
12969				len += sndout;
12970
12971				/* Did we reach EOR? */
12972				if ((uio->uio_resid == 0) &&
12973				    ((user_marks_eor == 0) ||
12974				    (srcv->sinfo_flags & SCTP_EOF) ||
12975				    (user_marks_eor && (srcv->sinfo_flags & SCTP_EOR)))) {
12976					sp->msg_is_complete = 1;
12977				} else {
12978					sp->msg_is_complete = 0;
12979				}
12980				SCTP_TCB_SEND_UNLOCK(stcb);
12981			}
12982			if (uio->uio_resid == 0) {
12983				/* got it all? */
12984				continue;
12985			}
12986			/* PR-SCTP? */
12987			if ((asoc->prsctp_supported) && (asoc->sent_queue_cnt_removeable > 0)) {
12988				/*
12989				 * This is ugly but we must assure locking
12990				 * order
12991				 */
12992				if (hold_tcblock == 0) {
12993					SCTP_TCB_LOCK(stcb);
12994					hold_tcblock = 1;
12995				}
12996				sctp_prune_prsctp(stcb, asoc, srcv, sndlen);
12997				inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12998				if (SCTP_SB_LIMIT_SND(so) > stcb->asoc.total_output_queue_size)
12999					max_len = SCTP_SB_LIMIT_SND(so) - inqueue_bytes;
13000				else
13001					max_len = 0;
13002				if (max_len > 0) {
13003					continue;
13004				}
13005				SCTP_TCB_UNLOCK(stcb);
13006				hold_tcblock = 0;
13007			}
13008			/* wait for space now */
13009			if (non_blocking) {
13010				/* Non-blocking io in place out */
13011				goto skip_out_eof;
13012			}
13013			/* What about the INIT, send it maybe */
13014			if (queue_only_for_init) {
13015				if (hold_tcblock == 0) {
13016					SCTP_TCB_LOCK(stcb);
13017					hold_tcblock = 1;
13018				}
13019				if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
13020					/* a collision took us forward? */
13021					queue_only = 0;
13022				} else {
13023					sctp_send_initiate(inp, stcb, SCTP_SO_LOCKED);
13024					SCTP_SET_STATE(asoc, SCTP_STATE_COOKIE_WAIT);
13025					queue_only = 1;
13026				}
13027			}
13028			if ((net->flight_size > net->cwnd) &&
13029			    (asoc->sctp_cmt_on_off == 0)) {
13030				SCTP_STAT_INCR(sctps_send_cwnd_avoid);
13031				queue_only = 1;
13032			} else if (asoc->ifp_had_enobuf) {
13033				SCTP_STAT_INCR(sctps_ifnomemqueued);
13034				if (net->flight_size > (2 * net->mtu)) {
13035					queue_only = 1;
13036				}
13037				asoc->ifp_had_enobuf = 0;
13038			}
13039			un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
13040			    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
13041			if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
13042			    (stcb->asoc.total_flight > 0) &&
13043			    (stcb->asoc.stream_queue_cnt < SCTP_MAX_DATA_BUNDLING) &&
13044			    (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))) {
13045
13046				/*-
13047				 * Ok, Nagle is set on and we have data outstanding.
13048				 * Don't send anything and let SACKs drive out the
13049				 * data unless wen have a "full" segment to send.
13050				 */
13051				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
13052					sctp_log_nagle_event(stcb, SCTP_NAGLE_APPLIED);
13053				}
13054				SCTP_STAT_INCR(sctps_naglequeued);
13055				nagle_applies = 1;
13056			} else {
13057				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
13058					if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY))
13059						sctp_log_nagle_event(stcb, SCTP_NAGLE_SKIPPED);
13060				}
13061				SCTP_STAT_INCR(sctps_naglesent);
13062				nagle_applies = 0;
13063			}
13064			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13065
13066				sctp_misc_ints(SCTP_CWNDLOG_PRESEND, queue_only_for_init, queue_only,
13067				    nagle_applies, un_sent);
13068				sctp_misc_ints(SCTP_CWNDLOG_PRESEND, stcb->asoc.total_output_queue_size,
13069				    stcb->asoc.total_flight,
13070				    stcb->asoc.chunks_on_out_queue, stcb->asoc.total_flight_count);
13071			}
13072			if (queue_only_for_init)
13073				queue_only_for_init = 0;
13074			if ((queue_only == 0) && (nagle_applies == 0)) {
13075				/*-
13076				 * need to start chunk output
13077				 * before blocking.. note that if
13078				 * a lock is already applied, then
13079				 * the input via the net is happening
13080				 * and I don't need to start output :-D
13081				 */
13082				if (hold_tcblock == 0) {
13083					if (SCTP_TCB_TRYLOCK(stcb)) {
13084						hold_tcblock = 1;
13085						sctp_chunk_output(inp,
13086						    stcb,
13087						    SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13088					}
13089				} else {
13090					sctp_chunk_output(inp,
13091					    stcb,
13092					    SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13093				}
13094				if (hold_tcblock == 1) {
13095					SCTP_TCB_UNLOCK(stcb);
13096					hold_tcblock = 0;
13097				}
13098			}
13099			SOCKBUF_LOCK(&so->so_snd);
13100			/*-
13101			 * This is a bit strange, but I think it will
13102			 * work. The total_output_queue_size is locked and
13103			 * protected by the TCB_LOCK, which we just released.
13104			 * There is a race that can occur between releasing it
13105			 * above, and me getting the socket lock, where sacks
13106			 * come in but we have not put the SB_WAIT on the
13107			 * so_snd buffer to get the wakeup. After the LOCK
13108			 * is applied the sack_processing will also need to
13109			 * LOCK the so->so_snd to do the actual sowwakeup(). So
13110			 * once we have the socket buffer lock if we recheck the
13111			 * size we KNOW we will get to sleep safely with the
13112			 * wakeup flag in place.
13113			 */
13114			if (SCTP_SB_LIMIT_SND(so) <= (stcb->asoc.total_output_queue_size +
13115			    min(SCTP_BASE_SYSCTL(sctp_add_more_threshold), SCTP_SB_LIMIT_SND(so)))) {
13116				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13117					sctp_log_block(SCTP_BLOCK_LOG_INTO_BLK,
13118					    asoc, uio->uio_resid);
13119				}
13120				be.error = 0;
13121				stcb->block_entry = &be;
13122				error = sbwait(&so->so_snd);
13123				stcb->block_entry = NULL;
13124
13125				if (error || so->so_error || be.error) {
13126					if (error == 0) {
13127						if (so->so_error)
13128							error = so->so_error;
13129						if (be.error) {
13130							error = be.error;
13131						}
13132					}
13133					SOCKBUF_UNLOCK(&so->so_snd);
13134					goto out_unlocked;
13135				}
13136				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13137					sctp_log_block(SCTP_BLOCK_LOG_OUTOF_BLK,
13138					    asoc, stcb->asoc.total_output_queue_size);
13139				}
13140			}
13141			SOCKBUF_UNLOCK(&so->so_snd);
13142			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
13143				goto out_unlocked;
13144			}
13145		}
13146		SCTP_TCB_SEND_LOCK(stcb);
13147		if (sp) {
13148			if (sp->msg_is_complete == 0) {
13149				strm->last_msg_incomplete = 1;
13150				asoc->stream_locked = 1;
13151				asoc->stream_locked_on = srcv->sinfo_stream;
13152			} else {
13153				sp->sender_all_done = 1;
13154				strm->last_msg_incomplete = 0;
13155				asoc->stream_locked = 0;
13156			}
13157		} else {
13158			SCTP_PRINTF("Huh no sp TSNH?\n");
13159			strm->last_msg_incomplete = 0;
13160			asoc->stream_locked = 0;
13161		}
13162		SCTP_TCB_SEND_UNLOCK(stcb);
13163		if (uio->uio_resid == 0) {
13164			got_all_of_the_send = 1;
13165		}
13166	} else {
13167		/* We send in a 0, since we do NOT have any locks */
13168		error = sctp_msg_append(stcb, net, top, srcv, 0);
13169		top = NULL;
13170		if (srcv->sinfo_flags & SCTP_EOF) {
13171			/*
13172			 * This should only happen for Panda for the mbuf
13173			 * send case, which does NOT yet support EEOR mode.
13174			 * Thus, we can just set this flag to do the proper
13175			 * EOF handling.
13176			 */
13177			got_all_of_the_send = 1;
13178		}
13179	}
13180	if (error) {
13181		goto out;
13182	}
13183dataless_eof:
13184	/* EOF thing ? */
13185	if ((srcv->sinfo_flags & SCTP_EOF) &&
13186	    (got_all_of_the_send == 1)) {
13187		int cnt;
13188
13189		SCTP_STAT_INCR(sctps_sends_with_eof);
13190		error = 0;
13191		if (hold_tcblock == 0) {
13192			SCTP_TCB_LOCK(stcb);
13193			hold_tcblock = 1;
13194		}
13195		cnt = sctp_is_there_unsent_data(stcb, SCTP_SO_LOCKED);
13196		if (TAILQ_EMPTY(&asoc->send_queue) &&
13197		    TAILQ_EMPTY(&asoc->sent_queue) &&
13198		    (cnt == 0)) {
13199			if (asoc->locked_on_sending) {
13200				goto abort_anyway;
13201			}
13202			/* there is nothing queued to send, so I'm done... */
13203			if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
13204			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
13205			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
13206				struct sctp_nets *netp;
13207
13208				/* only send SHUTDOWN the first time through */
13209				if (SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) {
13210					SCTP_STAT_DECR_GAUGE32(sctps_currestab);
13211				}
13212				SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_SENT);
13213				SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING);
13214				sctp_stop_timers_for_shutdown(stcb);
13215				if (stcb->asoc.alternate) {
13216					netp = stcb->asoc.alternate;
13217				} else {
13218					netp = stcb->asoc.primary_destination;
13219				}
13220				sctp_send_shutdown(stcb, netp);
13221				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
13222				    netp);
13223				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
13224				    asoc->primary_destination);
13225			}
13226		} else {
13227			/*-
13228			 * we still got (or just got) data to send, so set
13229			 * SHUTDOWN_PENDING
13230			 */
13231			/*-
13232			 * XXX sockets draft says that SCTP_EOF should be
13233			 * sent with no data.  currently, we will allow user
13234			 * data to be sent first and move to
13235			 * SHUTDOWN-PENDING
13236			 */
13237			if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
13238			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
13239			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
13240				if (hold_tcblock == 0) {
13241					SCTP_TCB_LOCK(stcb);
13242					hold_tcblock = 1;
13243				}
13244				if (asoc->locked_on_sending) {
13245					/* Locked to send out the data */
13246					struct sctp_stream_queue_pending *sp;
13247
13248					sp = TAILQ_LAST(&asoc->locked_on_sending->outqueue, sctp_streamhead);
13249					if (sp) {
13250						if ((sp->length == 0) && (sp->msg_is_complete == 0))
13251							asoc->state |= SCTP_STATE_PARTIAL_MSG_LEFT;
13252					}
13253				}
13254				asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
13255				if (TAILQ_EMPTY(&asoc->send_queue) &&
13256				    TAILQ_EMPTY(&asoc->sent_queue) &&
13257				    (asoc->state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
13258			abort_anyway:
13259					if (free_cnt_applied) {
13260						atomic_add_int(&stcb->asoc.refcnt, -1);
13261						free_cnt_applied = 0;
13262					}
13263					sctp_abort_an_association(stcb->sctp_ep, stcb,
13264					    NULL, SCTP_SO_LOCKED);
13265					/*
13266					 * now relock the stcb so everything
13267					 * is sane
13268					 */
13269					hold_tcblock = 0;
13270					stcb = NULL;
13271					goto out;
13272				}
13273				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
13274				    asoc->primary_destination);
13275				sctp_feature_off(inp, SCTP_PCB_FLAGS_NODELAY);
13276			}
13277		}
13278	}
13279skip_out_eof:
13280	if (!TAILQ_EMPTY(&stcb->asoc.control_send_queue)) {
13281		some_on_control = 1;
13282	}
13283	if (queue_only_for_init) {
13284		if (hold_tcblock == 0) {
13285			SCTP_TCB_LOCK(stcb);
13286			hold_tcblock = 1;
13287		}
13288		if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
13289			/* a collision took us forward? */
13290			queue_only = 0;
13291		} else {
13292			sctp_send_initiate(inp, stcb, SCTP_SO_LOCKED);
13293			SCTP_SET_STATE(&stcb->asoc, SCTP_STATE_COOKIE_WAIT);
13294			queue_only = 1;
13295		}
13296	}
13297	if ((net->flight_size > net->cwnd) &&
13298	    (stcb->asoc.sctp_cmt_on_off == 0)) {
13299		SCTP_STAT_INCR(sctps_send_cwnd_avoid);
13300		queue_only = 1;
13301	} else if (asoc->ifp_had_enobuf) {
13302		SCTP_STAT_INCR(sctps_ifnomemqueued);
13303		if (net->flight_size > (2 * net->mtu)) {
13304			queue_only = 1;
13305		}
13306		asoc->ifp_had_enobuf = 0;
13307	}
13308	un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
13309	    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
13310	if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
13311	    (stcb->asoc.total_flight > 0) &&
13312	    (stcb->asoc.stream_queue_cnt < SCTP_MAX_DATA_BUNDLING) &&
13313	    (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))) {
13314		/*-
13315		 * Ok, Nagle is set on and we have data outstanding.
13316		 * Don't send anything and let SACKs drive out the
13317		 * data unless wen have a "full" segment to send.
13318		 */
13319		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
13320			sctp_log_nagle_event(stcb, SCTP_NAGLE_APPLIED);
13321		}
13322		SCTP_STAT_INCR(sctps_naglequeued);
13323		nagle_applies = 1;
13324	} else {
13325		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
13326			if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY))
13327				sctp_log_nagle_event(stcb, SCTP_NAGLE_SKIPPED);
13328		}
13329		SCTP_STAT_INCR(sctps_naglesent);
13330		nagle_applies = 0;
13331	}
13332	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13333		sctp_misc_ints(SCTP_CWNDLOG_PRESEND, queue_only_for_init, queue_only,
13334		    nagle_applies, un_sent);
13335		sctp_misc_ints(SCTP_CWNDLOG_PRESEND, stcb->asoc.total_output_queue_size,
13336		    stcb->asoc.total_flight,
13337		    stcb->asoc.chunks_on_out_queue, stcb->asoc.total_flight_count);
13338	}
13339	if ((queue_only == 0) && (nagle_applies == 0) && (stcb->asoc.peers_rwnd && un_sent)) {
13340		/* we can attempt to send too. */
13341		if (hold_tcblock == 0) {
13342			/*
13343			 * If there is activity recv'ing sacks no need to
13344			 * send
13345			 */
13346			if (SCTP_TCB_TRYLOCK(stcb)) {
13347				sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13348				hold_tcblock = 1;
13349			}
13350		} else {
13351			sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13352		}
13353	} else if ((queue_only == 0) &&
13354		    (stcb->asoc.peers_rwnd == 0) &&
13355	    (stcb->asoc.total_flight == 0)) {
13356		/* We get to have a probe outstanding */
13357		if (hold_tcblock == 0) {
13358			hold_tcblock = 1;
13359			SCTP_TCB_LOCK(stcb);
13360		}
13361		sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13362	} else if (some_on_control) {
13363		int num_out, reason, frag_point;
13364
13365		/* Here we do control only */
13366		if (hold_tcblock == 0) {
13367			hold_tcblock = 1;
13368			SCTP_TCB_LOCK(stcb);
13369		}
13370		frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
13371		(void)sctp_med_chunk_output(inp, stcb, &stcb->asoc, &num_out,
13372		    &reason, 1, 1, &now, &now_filled, frag_point, SCTP_SO_LOCKED);
13373	}
13374	SCTPDBG(SCTP_DEBUG_OUTPUT1, "USR Send complete qo:%d prw:%d unsent:%d tf:%d cooq:%d toqs:%d err:%d\n",
13375	    queue_only, stcb->asoc.peers_rwnd, un_sent,
13376	    stcb->asoc.total_flight, stcb->asoc.chunks_on_out_queue,
13377	    stcb->asoc.total_output_queue_size, error);
13378
13379out:
13380out_unlocked:
13381
13382	if (local_soresv && stcb) {
13383		atomic_subtract_int(&stcb->asoc.sb_send_resv, sndlen);
13384	}
13385	if (create_lock_applied) {
13386		SCTP_ASOC_CREATE_UNLOCK(inp);
13387	}
13388	if ((stcb) && hold_tcblock) {
13389		SCTP_TCB_UNLOCK(stcb);
13390	}
13391	if (stcb && free_cnt_applied) {
13392		atomic_add_int(&stcb->asoc.refcnt, -1);
13393	}
13394#ifdef INVARIANTS
13395	if (stcb) {
13396		if (mtx_owned(&stcb->tcb_mtx)) {
13397			panic("Leaving with tcb mtx owned?");
13398		}
13399		if (mtx_owned(&stcb->tcb_send_mtx)) {
13400			panic("Leaving with tcb send mtx owned?");
13401		}
13402	}
13403#endif
13404#ifdef INVARIANTS
13405	if (inp) {
13406		sctp_validate_no_locks(inp);
13407	} else {
13408		SCTP_PRINTF("Warning - inp is NULL so cant validate locks\n");
13409	}
13410#endif
13411	if (top) {
13412		sctp_m_freem(top);
13413	}
13414	if (control) {
13415		sctp_m_freem(control);
13416	}
13417	return (error);
13418}
13419
13420
13421/*
13422 * generate an AUTHentication chunk, if required
13423 */
13424struct mbuf *
13425sctp_add_auth_chunk(struct mbuf *m, struct mbuf **m_end,
13426    struct sctp_auth_chunk **auth_ret, uint32_t * offset,
13427    struct sctp_tcb *stcb, uint8_t chunk)
13428{
13429	struct mbuf *m_auth;
13430	struct sctp_auth_chunk *auth;
13431	int chunk_len;
13432	struct mbuf *cn;
13433
13434	if ((m_end == NULL) || (auth_ret == NULL) || (offset == NULL) ||
13435	    (stcb == NULL))
13436		return (m);
13437
13438	if (stcb->asoc.auth_supported == 0) {
13439		return (m);
13440	}
13441	/* does the requested chunk require auth? */
13442	if (!sctp_auth_is_required_chunk(chunk, stcb->asoc.peer_auth_chunks)) {
13443		return (m);
13444	}
13445	m_auth = sctp_get_mbuf_for_msg(sizeof(*auth), 0, M_NOWAIT, 1, MT_HEADER);
13446	if (m_auth == NULL) {
13447		/* no mbuf's */
13448		return (m);
13449	}
13450	/* reserve some space if this will be the first mbuf */
13451	if (m == NULL)
13452		SCTP_BUF_RESV_UF(m_auth, SCTP_MIN_OVERHEAD);
13453	/* fill in the AUTH chunk details */
13454	auth = mtod(m_auth, struct sctp_auth_chunk *);
13455	bzero(auth, sizeof(*auth));
13456	auth->ch.chunk_type = SCTP_AUTHENTICATION;
13457	auth->ch.chunk_flags = 0;
13458	chunk_len = sizeof(*auth) +
13459	    sctp_get_hmac_digest_len(stcb->asoc.peer_hmac_id);
13460	auth->ch.chunk_length = htons(chunk_len);
13461	auth->hmac_id = htons(stcb->asoc.peer_hmac_id);
13462	/* key id and hmac digest will be computed and filled in upon send */
13463
13464	/* save the offset where the auth was inserted into the chain */
13465	*offset = 0;
13466	for (cn = m; cn; cn = SCTP_BUF_NEXT(cn)) {
13467		*offset += SCTP_BUF_LEN(cn);
13468	}
13469
13470	/* update length and return pointer to the auth chunk */
13471	SCTP_BUF_LEN(m_auth) = chunk_len;
13472	m = sctp_copy_mbufchain(m_auth, m, m_end, 1, chunk_len, 0);
13473	if (auth_ret != NULL)
13474		*auth_ret = auth;
13475
13476	return (m);
13477}
13478
13479#ifdef INET6
13480int
13481sctp_v6src_match_nexthop(struct sockaddr_in6 *src6, sctp_route_t * ro)
13482{
13483	struct nd_prefix *pfx = NULL;
13484	struct nd_pfxrouter *pfxrtr = NULL;
13485	struct sockaddr_in6 gw6;
13486
13487	if (ro == NULL || ro->ro_rt == NULL || src6->sin6_family != AF_INET6)
13488		return (0);
13489
13490	/* get prefix entry of address */
13491	LIST_FOREACH(pfx, &MODULE_GLOBAL(nd_prefix), ndpr_entry) {
13492		if (pfx->ndpr_stateflags & NDPRF_DETACHED)
13493			continue;
13494		if (IN6_ARE_MASKED_ADDR_EQUAL(&pfx->ndpr_prefix.sin6_addr,
13495		    &src6->sin6_addr, &pfx->ndpr_mask))
13496			break;
13497	}
13498	/* no prefix entry in the prefix list */
13499	if (pfx == NULL) {
13500		SCTPDBG(SCTP_DEBUG_OUTPUT2, "No prefix entry for ");
13501		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)src6);
13502		return (0);
13503	}
13504	SCTPDBG(SCTP_DEBUG_OUTPUT2, "v6src_match_nexthop(), Prefix entry is ");
13505	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)src6);
13506
13507	/* search installed gateway from prefix entry */
13508	LIST_FOREACH(pfxrtr, &pfx->ndpr_advrtrs, pfr_entry) {
13509		memset(&gw6, 0, sizeof(struct sockaddr_in6));
13510		gw6.sin6_family = AF_INET6;
13511		gw6.sin6_len = sizeof(struct sockaddr_in6);
13512		memcpy(&gw6.sin6_addr, &pfxrtr->router->rtaddr,
13513		    sizeof(struct in6_addr));
13514		SCTPDBG(SCTP_DEBUG_OUTPUT2, "prefix router is ");
13515		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)&gw6);
13516		SCTPDBG(SCTP_DEBUG_OUTPUT2, "installed router is ");
13517		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, ro->ro_rt->rt_gateway);
13518		if (sctp_cmpaddr((struct sockaddr *)&gw6,
13519		    ro->ro_rt->rt_gateway)) {
13520			SCTPDBG(SCTP_DEBUG_OUTPUT2, "pfxrouter is installed\n");
13521			return (1);
13522		}
13523	}
13524	SCTPDBG(SCTP_DEBUG_OUTPUT2, "pfxrouter is not installed\n");
13525	return (0);
13526}
13527
13528#endif
13529
13530int
13531sctp_v4src_match_nexthop(struct sctp_ifa *sifa, sctp_route_t * ro)
13532{
13533#ifdef INET
13534	struct sockaddr_in *sin, *mask;
13535	struct ifaddr *ifa;
13536	struct in_addr srcnetaddr, gwnetaddr;
13537
13538	if (ro == NULL || ro->ro_rt == NULL ||
13539	    sifa->address.sa.sa_family != AF_INET) {
13540		return (0);
13541	}
13542	ifa = (struct ifaddr *)sifa->ifa;
13543	mask = (struct sockaddr_in *)(ifa->ifa_netmask);
13544	sin = &sifa->address.sin;
13545	srcnetaddr.s_addr = (sin->sin_addr.s_addr & mask->sin_addr.s_addr);
13546	SCTPDBG(SCTP_DEBUG_OUTPUT1, "match_nexthop4: src address is ");
13547	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &sifa->address.sa);
13548	SCTPDBG(SCTP_DEBUG_OUTPUT1, "network address is %x\n", srcnetaddr.s_addr);
13549
13550	sin = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
13551	gwnetaddr.s_addr = (sin->sin_addr.s_addr & mask->sin_addr.s_addr);
13552	SCTPDBG(SCTP_DEBUG_OUTPUT1, "match_nexthop4: nexthop is ");
13553	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, ro->ro_rt->rt_gateway);
13554	SCTPDBG(SCTP_DEBUG_OUTPUT1, "network address is %x\n", gwnetaddr.s_addr);
13555	if (srcnetaddr.s_addr == gwnetaddr.s_addr) {
13556		return (1);
13557	}
13558#endif
13559	return (0);
13560}
13561