]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/sctputil.c
Fix SCTP socket use-after-free.
[FreeBSD/FreeBSD.git] / sys / netinet / sctputil.c
1 /*-
2  * Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
3  * Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
4  * Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * a) Redistributions of source code must retain the above copyright notice,
10  *    this list of conditions and the following disclaimer.
11  *
12  * b) Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the distribution.
15  *
16  * c) Neither the name of Cisco Systems, Inc. nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
22  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30  * THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #include <netinet/sctp_os.h>
37 #include <netinet/sctp_pcb.h>
38 #include <netinet/sctputil.h>
39 #include <netinet/sctp_var.h>
40 #include <netinet/sctp_sysctl.h>
41 #ifdef INET6
42 #include <netinet6/sctp6_var.h>
43 #endif
44 #include <netinet/sctp_header.h>
45 #include <netinet/sctp_output.h>
46 #include <netinet/sctp_uio.h>
47 #include <netinet/sctp_timer.h>
48 #include <netinet/sctp_indata.h>
49 #include <netinet/sctp_auth.h>
50 #include <netinet/sctp_asconf.h>
51 #include <netinet/sctp_bsd_addr.h>
52 #if defined(INET6) || defined(INET)
53 #include <netinet/tcp_var.h>
54 #endif
55 #include <netinet/udp.h>
56 #include <netinet/udp_var.h>
57 #include <sys/proc.h>
58 #ifdef INET6
59 #include <netinet/icmp6.h>
60 #endif
61
62
63 #ifndef KTR_SCTP
64 #define KTR_SCTP KTR_SUBSYS
65 #endif
66
67 extern const struct sctp_cc_functions sctp_cc_functions[];
68 extern const struct sctp_ss_functions sctp_ss_functions[];
69
70 void
71 sctp_sblog(struct sockbuf *sb, struct sctp_tcb *stcb, int from, int incr)
72 {
73 #if defined(SCTP_LOCAL_TRACE_BUF)
74         struct sctp_cwnd_log sctp_clog;
75
76         sctp_clog.x.sb.stcb = stcb;
77         sctp_clog.x.sb.so_sbcc = sb->sb_cc;
78         if (stcb)
79                 sctp_clog.x.sb.stcb_sbcc = stcb->asoc.sb_cc;
80         else
81                 sctp_clog.x.sb.stcb_sbcc = 0;
82         sctp_clog.x.sb.incr = incr;
83         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
84             SCTP_LOG_EVENT_SB,
85             from,
86             sctp_clog.x.misc.log1,
87             sctp_clog.x.misc.log2,
88             sctp_clog.x.misc.log3,
89             sctp_clog.x.misc.log4);
90 #endif
91 }
92
93 void
94 sctp_log_closing(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int16_t loc)
95 {
96 #if defined(SCTP_LOCAL_TRACE_BUF)
97         struct sctp_cwnd_log sctp_clog;
98
99         sctp_clog.x.close.inp = (void *)inp;
100         sctp_clog.x.close.sctp_flags = inp->sctp_flags;
101         if (stcb) {
102                 sctp_clog.x.close.stcb = (void *)stcb;
103                 sctp_clog.x.close.state = (uint16_t)stcb->asoc.state;
104         } else {
105                 sctp_clog.x.close.stcb = 0;
106                 sctp_clog.x.close.state = 0;
107         }
108         sctp_clog.x.close.loc = loc;
109         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
110             SCTP_LOG_EVENT_CLOSE,
111             0,
112             sctp_clog.x.misc.log1,
113             sctp_clog.x.misc.log2,
114             sctp_clog.x.misc.log3,
115             sctp_clog.x.misc.log4);
116 #endif
117 }
118
119 void
120 rto_logging(struct sctp_nets *net, int from)
121 {
122 #if defined(SCTP_LOCAL_TRACE_BUF)
123         struct sctp_cwnd_log sctp_clog;
124
125         memset(&sctp_clog, 0, sizeof(sctp_clog));
126         sctp_clog.x.rto.net = (void *)net;
127         sctp_clog.x.rto.rtt = net->rtt / 1000;
128         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
129             SCTP_LOG_EVENT_RTT,
130             from,
131             sctp_clog.x.misc.log1,
132             sctp_clog.x.misc.log2,
133             sctp_clog.x.misc.log3,
134             sctp_clog.x.misc.log4);
135 #endif
136 }
137
138 void
139 sctp_log_strm_del_alt(struct sctp_tcb *stcb, uint32_t tsn, uint16_t sseq, uint16_t stream, int from)
140 {
141 #if defined(SCTP_LOCAL_TRACE_BUF)
142         struct sctp_cwnd_log sctp_clog;
143
144         sctp_clog.x.strlog.stcb = stcb;
145         sctp_clog.x.strlog.n_tsn = tsn;
146         sctp_clog.x.strlog.n_sseq = sseq;
147         sctp_clog.x.strlog.e_tsn = 0;
148         sctp_clog.x.strlog.e_sseq = 0;
149         sctp_clog.x.strlog.strm = stream;
150         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
151             SCTP_LOG_EVENT_STRM,
152             from,
153             sctp_clog.x.misc.log1,
154             sctp_clog.x.misc.log2,
155             sctp_clog.x.misc.log3,
156             sctp_clog.x.misc.log4);
157 #endif
158 }
159
160 void
161 sctp_log_nagle_event(struct sctp_tcb *stcb, int action)
162 {
163 #if defined(SCTP_LOCAL_TRACE_BUF)
164         struct sctp_cwnd_log sctp_clog;
165
166         sctp_clog.x.nagle.stcb = (void *)stcb;
167         sctp_clog.x.nagle.total_flight = stcb->asoc.total_flight;
168         sctp_clog.x.nagle.total_in_queue = stcb->asoc.total_output_queue_size;
169         sctp_clog.x.nagle.count_in_queue = stcb->asoc.chunks_on_out_queue;
170         sctp_clog.x.nagle.count_in_flight = stcb->asoc.total_flight_count;
171         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
172             SCTP_LOG_EVENT_NAGLE,
173             action,
174             sctp_clog.x.misc.log1,
175             sctp_clog.x.misc.log2,
176             sctp_clog.x.misc.log3,
177             sctp_clog.x.misc.log4);
178 #endif
179 }
180
181 void
182 sctp_log_sack(uint32_t old_cumack, uint32_t cumack, uint32_t tsn, uint16_t gaps, uint16_t dups, int from)
183 {
184 #if defined(SCTP_LOCAL_TRACE_BUF)
185         struct sctp_cwnd_log sctp_clog;
186
187         sctp_clog.x.sack.cumack = cumack;
188         sctp_clog.x.sack.oldcumack = old_cumack;
189         sctp_clog.x.sack.tsn = tsn;
190         sctp_clog.x.sack.numGaps = gaps;
191         sctp_clog.x.sack.numDups = dups;
192         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
193             SCTP_LOG_EVENT_SACK,
194             from,
195             sctp_clog.x.misc.log1,
196             sctp_clog.x.misc.log2,
197             sctp_clog.x.misc.log3,
198             sctp_clog.x.misc.log4);
199 #endif
200 }
201
202 void
203 sctp_log_map(uint32_t map, uint32_t cum, uint32_t high, int from)
204 {
205 #if defined(SCTP_LOCAL_TRACE_BUF)
206         struct sctp_cwnd_log sctp_clog;
207
208         memset(&sctp_clog, 0, sizeof(sctp_clog));
209         sctp_clog.x.map.base = map;
210         sctp_clog.x.map.cum = cum;
211         sctp_clog.x.map.high = high;
212         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
213             SCTP_LOG_EVENT_MAP,
214             from,
215             sctp_clog.x.misc.log1,
216             sctp_clog.x.misc.log2,
217             sctp_clog.x.misc.log3,
218             sctp_clog.x.misc.log4);
219 #endif
220 }
221
222 void
223 sctp_log_fr(uint32_t biggest_tsn, uint32_t biggest_new_tsn, uint32_t tsn, int from)
224 {
225 #if defined(SCTP_LOCAL_TRACE_BUF)
226         struct sctp_cwnd_log sctp_clog;
227
228         memset(&sctp_clog, 0, sizeof(sctp_clog));
229         sctp_clog.x.fr.largest_tsn = biggest_tsn;
230         sctp_clog.x.fr.largest_new_tsn = biggest_new_tsn;
231         sctp_clog.x.fr.tsn = tsn;
232         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
233             SCTP_LOG_EVENT_FR,
234             from,
235             sctp_clog.x.misc.log1,
236             sctp_clog.x.misc.log2,
237             sctp_clog.x.misc.log3,
238             sctp_clog.x.misc.log4);
239 #endif
240 }
241
242 #ifdef SCTP_MBUF_LOGGING
243 void
244 sctp_log_mb(struct mbuf *m, int from)
245 {
246 #if defined(SCTP_LOCAL_TRACE_BUF)
247         struct sctp_cwnd_log sctp_clog;
248
249         sctp_clog.x.mb.mp = m;
250         sctp_clog.x.mb.mbuf_flags = (uint8_t)(SCTP_BUF_GET_FLAGS(m));
251         sctp_clog.x.mb.size = (uint16_t)(SCTP_BUF_LEN(m));
252         sctp_clog.x.mb.data = SCTP_BUF_AT(m, 0);
253         if (SCTP_BUF_IS_EXTENDED(m)) {
254                 sctp_clog.x.mb.ext = SCTP_BUF_EXTEND_BASE(m);
255                 sctp_clog.x.mb.refcnt = (uint8_t)(SCTP_BUF_EXTEND_REFCNT(m));
256         } else {
257                 sctp_clog.x.mb.ext = 0;
258                 sctp_clog.x.mb.refcnt = 0;
259         }
260         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
261             SCTP_LOG_EVENT_MBUF,
262             from,
263             sctp_clog.x.misc.log1,
264             sctp_clog.x.misc.log2,
265             sctp_clog.x.misc.log3,
266             sctp_clog.x.misc.log4);
267 #endif
268 }
269
270 void
271 sctp_log_mbc(struct mbuf *m, int from)
272 {
273         struct mbuf *mat;
274
275         for (mat = m; mat; mat = SCTP_BUF_NEXT(mat)) {
276                 sctp_log_mb(mat, from);
277         }
278 }
279 #endif
280
281 void
282 sctp_log_strm_del(struct sctp_queued_to_read *control, struct sctp_queued_to_read *poschk, int from)
283 {
284 #if defined(SCTP_LOCAL_TRACE_BUF)
285         struct sctp_cwnd_log sctp_clog;
286
287         if (control == NULL) {
288                 SCTP_PRINTF("Gak log of NULL?\n");
289                 return;
290         }
291         sctp_clog.x.strlog.stcb = control->stcb;
292         sctp_clog.x.strlog.n_tsn = control->sinfo_tsn;
293         sctp_clog.x.strlog.n_sseq = (uint16_t)control->mid;
294         sctp_clog.x.strlog.strm = control->sinfo_stream;
295         if (poschk != NULL) {
296                 sctp_clog.x.strlog.e_tsn = poschk->sinfo_tsn;
297                 sctp_clog.x.strlog.e_sseq = (uint16_t)poschk->mid;
298         } else {
299                 sctp_clog.x.strlog.e_tsn = 0;
300                 sctp_clog.x.strlog.e_sseq = 0;
301         }
302         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
303             SCTP_LOG_EVENT_STRM,
304             from,
305             sctp_clog.x.misc.log1,
306             sctp_clog.x.misc.log2,
307             sctp_clog.x.misc.log3,
308             sctp_clog.x.misc.log4);
309 #endif
310 }
311
312 void
313 sctp_log_cwnd(struct sctp_tcb *stcb, struct sctp_nets *net, int augment, uint8_t from)
314 {
315 #if defined(SCTP_LOCAL_TRACE_BUF)
316         struct sctp_cwnd_log sctp_clog;
317
318         sctp_clog.x.cwnd.net = net;
319         if (stcb->asoc.send_queue_cnt > 255)
320                 sctp_clog.x.cwnd.cnt_in_send = 255;
321         else
322                 sctp_clog.x.cwnd.cnt_in_send = stcb->asoc.send_queue_cnt;
323         if (stcb->asoc.stream_queue_cnt > 255)
324                 sctp_clog.x.cwnd.cnt_in_str = 255;
325         else
326                 sctp_clog.x.cwnd.cnt_in_str = stcb->asoc.stream_queue_cnt;
327
328         if (net) {
329                 sctp_clog.x.cwnd.cwnd_new_value = net->cwnd;
330                 sctp_clog.x.cwnd.inflight = net->flight_size;
331                 sctp_clog.x.cwnd.pseudo_cumack = net->pseudo_cumack;
332                 sctp_clog.x.cwnd.meets_pseudo_cumack = net->new_pseudo_cumack;
333                 sctp_clog.x.cwnd.need_new_pseudo_cumack = net->find_pseudo_cumack;
334         }
335         if (SCTP_CWNDLOG_PRESEND == from) {
336                 sctp_clog.x.cwnd.meets_pseudo_cumack = stcb->asoc.peers_rwnd;
337         }
338         sctp_clog.x.cwnd.cwnd_augment = augment;
339         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
340             SCTP_LOG_EVENT_CWND,
341             from,
342             sctp_clog.x.misc.log1,
343             sctp_clog.x.misc.log2,
344             sctp_clog.x.misc.log3,
345             sctp_clog.x.misc.log4);
346 #endif
347 }
348
349 void
350 sctp_log_lock(struct sctp_inpcb *inp, struct sctp_tcb *stcb, uint8_t from)
351 {
352 #if defined(SCTP_LOCAL_TRACE_BUF)
353         struct sctp_cwnd_log sctp_clog;
354
355         memset(&sctp_clog, 0, sizeof(sctp_clog));
356         if (inp) {
357                 sctp_clog.x.lock.sock = (void *)inp->sctp_socket;
358
359         } else {
360                 sctp_clog.x.lock.sock = (void *)NULL;
361         }
362         sctp_clog.x.lock.inp = (void *)inp;
363         if (stcb) {
364                 sctp_clog.x.lock.tcb_lock = mtx_owned(&stcb->tcb_mtx);
365         } else {
366                 sctp_clog.x.lock.tcb_lock = SCTP_LOCK_UNKNOWN;
367         }
368         if (inp) {
369                 sctp_clog.x.lock.inp_lock = mtx_owned(&inp->inp_mtx);
370                 sctp_clog.x.lock.create_lock = mtx_owned(&inp->inp_create_mtx);
371         } else {
372                 sctp_clog.x.lock.inp_lock = SCTP_LOCK_UNKNOWN;
373                 sctp_clog.x.lock.create_lock = SCTP_LOCK_UNKNOWN;
374         }
375         sctp_clog.x.lock.info_lock = rw_wowned(&SCTP_BASE_INFO(ipi_ep_mtx));
376         if (inp && (inp->sctp_socket)) {
377                 sctp_clog.x.lock.sock_lock = mtx_owned(&(inp->sctp_socket->so_rcv.sb_mtx));
378                 sctp_clog.x.lock.sockrcvbuf_lock = mtx_owned(&(inp->sctp_socket->so_rcv.sb_mtx));
379                 sctp_clog.x.lock.socksndbuf_lock = mtx_owned(&(inp->sctp_socket->so_snd.sb_mtx));
380         } else {
381                 sctp_clog.x.lock.sock_lock = SCTP_LOCK_UNKNOWN;
382                 sctp_clog.x.lock.sockrcvbuf_lock = SCTP_LOCK_UNKNOWN;
383                 sctp_clog.x.lock.socksndbuf_lock = SCTP_LOCK_UNKNOWN;
384         }
385         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
386             SCTP_LOG_LOCK_EVENT,
387             from,
388             sctp_clog.x.misc.log1,
389             sctp_clog.x.misc.log2,
390             sctp_clog.x.misc.log3,
391             sctp_clog.x.misc.log4);
392 #endif
393 }
394
395 void
396 sctp_log_maxburst(struct sctp_tcb *stcb, struct sctp_nets *net, int error, int burst, uint8_t from)
397 {
398 #if defined(SCTP_LOCAL_TRACE_BUF)
399         struct sctp_cwnd_log sctp_clog;
400
401         memset(&sctp_clog, 0, sizeof(sctp_clog));
402         sctp_clog.x.cwnd.net = net;
403         sctp_clog.x.cwnd.cwnd_new_value = error;
404         sctp_clog.x.cwnd.inflight = net->flight_size;
405         sctp_clog.x.cwnd.cwnd_augment = burst;
406         if (stcb->asoc.send_queue_cnt > 255)
407                 sctp_clog.x.cwnd.cnt_in_send = 255;
408         else
409                 sctp_clog.x.cwnd.cnt_in_send = stcb->asoc.send_queue_cnt;
410         if (stcb->asoc.stream_queue_cnt > 255)
411                 sctp_clog.x.cwnd.cnt_in_str = 255;
412         else
413                 sctp_clog.x.cwnd.cnt_in_str = stcb->asoc.stream_queue_cnt;
414         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
415             SCTP_LOG_EVENT_MAXBURST,
416             from,
417             sctp_clog.x.misc.log1,
418             sctp_clog.x.misc.log2,
419             sctp_clog.x.misc.log3,
420             sctp_clog.x.misc.log4);
421 #endif
422 }
423
424 void
425 sctp_log_rwnd(uint8_t from, uint32_t peers_rwnd, uint32_t snd_size, uint32_t overhead)
426 {
427 #if defined(SCTP_LOCAL_TRACE_BUF)
428         struct sctp_cwnd_log sctp_clog;
429
430         sctp_clog.x.rwnd.rwnd = peers_rwnd;
431         sctp_clog.x.rwnd.send_size = snd_size;
432         sctp_clog.x.rwnd.overhead = overhead;
433         sctp_clog.x.rwnd.new_rwnd = 0;
434         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
435             SCTP_LOG_EVENT_RWND,
436             from,
437             sctp_clog.x.misc.log1,
438             sctp_clog.x.misc.log2,
439             sctp_clog.x.misc.log3,
440             sctp_clog.x.misc.log4);
441 #endif
442 }
443
444 void
445 sctp_log_rwnd_set(uint8_t from, uint32_t peers_rwnd, uint32_t flight_size, uint32_t overhead, uint32_t a_rwndval)
446 {
447 #if defined(SCTP_LOCAL_TRACE_BUF)
448         struct sctp_cwnd_log sctp_clog;
449
450         sctp_clog.x.rwnd.rwnd = peers_rwnd;
451         sctp_clog.x.rwnd.send_size = flight_size;
452         sctp_clog.x.rwnd.overhead = overhead;
453         sctp_clog.x.rwnd.new_rwnd = a_rwndval;
454         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
455             SCTP_LOG_EVENT_RWND,
456             from,
457             sctp_clog.x.misc.log1,
458             sctp_clog.x.misc.log2,
459             sctp_clog.x.misc.log3,
460             sctp_clog.x.misc.log4);
461 #endif
462 }
463
464 #ifdef SCTP_MBCNT_LOGGING
465 static void
466 sctp_log_mbcnt(uint8_t from, uint32_t total_oq, uint32_t book, uint32_t total_mbcnt_q, uint32_t mbcnt)
467 {
468 #if defined(SCTP_LOCAL_TRACE_BUF)
469         struct sctp_cwnd_log sctp_clog;
470
471         sctp_clog.x.mbcnt.total_queue_size = total_oq;
472         sctp_clog.x.mbcnt.size_change = book;
473         sctp_clog.x.mbcnt.total_queue_mb_size = total_mbcnt_q;
474         sctp_clog.x.mbcnt.mbcnt_change = mbcnt;
475         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
476             SCTP_LOG_EVENT_MBCNT,
477             from,
478             sctp_clog.x.misc.log1,
479             sctp_clog.x.misc.log2,
480             sctp_clog.x.misc.log3,
481             sctp_clog.x.misc.log4);
482 #endif
483 }
484 #endif
485
486 void
487 sctp_misc_ints(uint8_t from, uint32_t a, uint32_t b, uint32_t c, uint32_t d)
488 {
489 #if defined(SCTP_LOCAL_TRACE_BUF)
490         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
491             SCTP_LOG_MISC_EVENT,
492             from,
493             a, b, c, d);
494 #endif
495 }
496
497 void
498 sctp_wakeup_log(struct sctp_tcb *stcb, uint32_t wake_cnt, int from)
499 {
500 #if defined(SCTP_LOCAL_TRACE_BUF)
501         struct sctp_cwnd_log sctp_clog;
502
503         sctp_clog.x.wake.stcb = (void *)stcb;
504         sctp_clog.x.wake.wake_cnt = wake_cnt;
505         sctp_clog.x.wake.flight = stcb->asoc.total_flight_count;
506         sctp_clog.x.wake.send_q = stcb->asoc.send_queue_cnt;
507         sctp_clog.x.wake.sent_q = stcb->asoc.sent_queue_cnt;
508
509         if (stcb->asoc.stream_queue_cnt < 0xff)
510                 sctp_clog.x.wake.stream_qcnt = (uint8_t)stcb->asoc.stream_queue_cnt;
511         else
512                 sctp_clog.x.wake.stream_qcnt = 0xff;
513
514         if (stcb->asoc.chunks_on_out_queue < 0xff)
515                 sctp_clog.x.wake.chunks_on_oque = (uint8_t)stcb->asoc.chunks_on_out_queue;
516         else
517                 sctp_clog.x.wake.chunks_on_oque = 0xff;
518
519         sctp_clog.x.wake.sctpflags = 0;
520         /* set in the defered mode stuff */
521         if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_DONT_WAKE)
522                 sctp_clog.x.wake.sctpflags |= 1;
523         if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_WAKEOUTPUT)
524                 sctp_clog.x.wake.sctpflags |= 2;
525         if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_WAKEINPUT)
526                 sctp_clog.x.wake.sctpflags |= 4;
527         /* what about the sb */
528         if (stcb->sctp_socket) {
529                 struct socket *so = stcb->sctp_socket;
530
531                 sctp_clog.x.wake.sbflags = (uint8_t)((so->so_snd.sb_flags & 0x00ff));
532         } else {
533                 sctp_clog.x.wake.sbflags = 0xff;
534         }
535         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
536             SCTP_LOG_EVENT_WAKE,
537             from,
538             sctp_clog.x.misc.log1,
539             sctp_clog.x.misc.log2,
540             sctp_clog.x.misc.log3,
541             sctp_clog.x.misc.log4);
542 #endif
543 }
544
545 void
546 sctp_log_block(uint8_t from, struct sctp_association *asoc, ssize_t sendlen)
547 {
548 #if defined(SCTP_LOCAL_TRACE_BUF)
549         struct sctp_cwnd_log sctp_clog;
550
551         sctp_clog.x.blk.onsb = asoc->total_output_queue_size;
552         sctp_clog.x.blk.send_sent_qcnt = (uint16_t)(asoc->send_queue_cnt + asoc->sent_queue_cnt);
553         sctp_clog.x.blk.peer_rwnd = asoc->peers_rwnd;
554         sctp_clog.x.blk.stream_qcnt = (uint16_t)asoc->stream_queue_cnt;
555         sctp_clog.x.blk.chunks_on_oque = (uint16_t)asoc->chunks_on_out_queue;
556         sctp_clog.x.blk.flight_size = (uint16_t)(asoc->total_flight / 1024);
557         sctp_clog.x.blk.sndlen = (uint32_t)sendlen;
558         SCTP_CTR6(KTR_SCTP, "SCTP:%d[%d]:%x-%x-%x-%x",
559             SCTP_LOG_EVENT_BLOCK,
560             from,
561             sctp_clog.x.misc.log1,
562             sctp_clog.x.misc.log2,
563             sctp_clog.x.misc.log3,
564             sctp_clog.x.misc.log4);
565 #endif
566 }
567
568 int
569 sctp_fill_stat_log(void *optval SCTP_UNUSED, size_t *optsize SCTP_UNUSED)
570 {
571         /* May need to fix this if ktrdump does not work */
572         return (0);
573 }
574
575 #ifdef SCTP_AUDITING_ENABLED
576 uint8_t sctp_audit_data[SCTP_AUDIT_SIZE][2];
577 static int sctp_audit_indx = 0;
578
579 static
580 void
581 sctp_print_audit_report(void)
582 {
583         int i;
584         int cnt;
585
586         cnt = 0;
587         for (i = sctp_audit_indx; i < SCTP_AUDIT_SIZE; i++) {
588                 if ((sctp_audit_data[i][0] == 0xe0) &&
589                     (sctp_audit_data[i][1] == 0x01)) {
590                         cnt = 0;
591                         SCTP_PRINTF("\n");
592                 } else if (sctp_audit_data[i][0] == 0xf0) {
593                         cnt = 0;
594                         SCTP_PRINTF("\n");
595                 } else if ((sctp_audit_data[i][0] == 0xc0) &&
596                     (sctp_audit_data[i][1] == 0x01)) {
597                         SCTP_PRINTF("\n");
598                         cnt = 0;
599                 }
600                 SCTP_PRINTF("%2.2x%2.2x ", (uint32_t)sctp_audit_data[i][0],
601                     (uint32_t)sctp_audit_data[i][1]);
602                 cnt++;
603                 if ((cnt % 14) == 0)
604                         SCTP_PRINTF("\n");
605         }
606         for (i = 0; i < sctp_audit_indx; i++) {
607                 if ((sctp_audit_data[i][0] == 0xe0) &&
608                     (sctp_audit_data[i][1] == 0x01)) {
609                         cnt = 0;
610                         SCTP_PRINTF("\n");
611                 } else if (sctp_audit_data[i][0] == 0xf0) {
612                         cnt = 0;
613                         SCTP_PRINTF("\n");
614                 } else if ((sctp_audit_data[i][0] == 0xc0) &&
615                     (sctp_audit_data[i][1] == 0x01)) {
616                         SCTP_PRINTF("\n");
617                         cnt = 0;
618                 }
619                 SCTP_PRINTF("%2.2x%2.2x ", (uint32_t)sctp_audit_data[i][0],
620                     (uint32_t)sctp_audit_data[i][1]);
621                 cnt++;
622                 if ((cnt % 14) == 0)
623                         SCTP_PRINTF("\n");
624         }
625         SCTP_PRINTF("\n");
626 }
627
628 void
629 sctp_auditing(int from, struct sctp_inpcb *inp, struct sctp_tcb *stcb,
630     struct sctp_nets *net)
631 {
632         int resend_cnt, tot_out, rep, tot_book_cnt;
633         struct sctp_nets *lnet;
634         struct sctp_tmit_chunk *chk;
635
636         sctp_audit_data[sctp_audit_indx][0] = 0xAA;
637         sctp_audit_data[sctp_audit_indx][1] = 0x000000ff & from;
638         sctp_audit_indx++;
639         if (sctp_audit_indx >= SCTP_AUDIT_SIZE) {
640                 sctp_audit_indx = 0;
641         }
642         if (inp == NULL) {
643                 sctp_audit_data[sctp_audit_indx][0] = 0xAF;
644                 sctp_audit_data[sctp_audit_indx][1] = 0x01;
645                 sctp_audit_indx++;
646                 if (sctp_audit_indx >= SCTP_AUDIT_SIZE) {
647                         sctp_audit_indx = 0;
648                 }
649                 return;
650         }
651         if (stcb == NULL) {
652                 sctp_audit_data[sctp_audit_indx][0] = 0xAF;
653                 sctp_audit_data[sctp_audit_indx][1] = 0x02;
654                 sctp_audit_indx++;
655                 if (sctp_audit_indx >= SCTP_AUDIT_SIZE) {
656                         sctp_audit_indx = 0;
657                 }
658                 return;
659         }
660         sctp_audit_data[sctp_audit_indx][0] = 0xA1;
661         sctp_audit_data[sctp_audit_indx][1] =
662             (0x000000ff & stcb->asoc.sent_queue_retran_cnt);
663         sctp_audit_indx++;
664         if (sctp_audit_indx >= SCTP_AUDIT_SIZE) {
665                 sctp_audit_indx = 0;
666         }
667         rep = 0;
668         tot_book_cnt = 0;
669         resend_cnt = tot_out = 0;
670         TAILQ_FOREACH(chk, &stcb->asoc.sent_queue, sctp_next) {
671                 if (chk->sent == SCTP_DATAGRAM_RESEND) {
672                         resend_cnt++;
673                 } else if (chk->sent < SCTP_DATAGRAM_RESEND) {
674                         tot_out += chk->book_size;
675                         tot_book_cnt++;
676                 }
677         }
678         if (resend_cnt != stcb->asoc.sent_queue_retran_cnt) {
679                 sctp_audit_data[sctp_audit_indx][0] = 0xAF;
680                 sctp_audit_data[sctp_audit_indx][1] = 0xA1;
681                 sctp_audit_indx++;
682                 if (sctp_audit_indx >= SCTP_AUDIT_SIZE) {
683                         sctp_audit_indx = 0;
684                 }
685                 SCTP_PRINTF("resend_cnt:%d asoc-tot:%d\n",
686                     resend_cnt, stcb->asoc.sent_queue_retran_cnt);
687                 rep = 1;
688                 stcb->asoc.sent_queue_retran_cnt = resend_cnt;
689                 sctp_audit_data[sctp_audit_indx][0] = 0xA2;
690                 sctp_audit_data[sctp_audit_indx][1] =
691                     (0x000000ff & stcb->asoc.sent_queue_retran_cnt);
692                 sctp_audit_indx++;
693                 if (sctp_audit_indx >= SCTP_AUDIT_SIZE) {
694                         sctp_audit_indx = 0;
695                 }
696         }
697         if (tot_out != stcb->asoc.total_flight) {
698                 sctp_audit_data[sctp_audit_indx][0] = 0xAF;
699                 sctp_audit_data[sctp_audit_indx][1] = 0xA2;
700                 sctp_audit_indx++;
701                 if (sctp_audit_indx >= SCTP_AUDIT_SIZE) {
702                         sctp_audit_indx = 0;
703                 }
704                 rep = 1;
705                 SCTP_PRINTF("tot_flt:%d asoc_tot:%d\n", tot_out,
706                     (int)stcb->asoc.total_flight);
707                 stcb->asoc.total_flight = tot_out;
708         }
709         if (tot_book_cnt != stcb->asoc.total_flight_count) {
710                 sctp_audit_data[sctp_audit_indx][0] = 0xAF;
711                 sctp_audit_data[sctp_audit_indx][1] = 0xA5;
712                 sctp_audit_indx++;
713                 if (sctp_audit_indx >= SCTP_AUDIT_SIZE) {
714                         sctp_audit_indx = 0;
715                 }
716                 rep = 1;
717                 SCTP_PRINTF("tot_flt_book:%d\n", tot_book_cnt);
718
719                 stcb->asoc.total_flight_count = tot_book_cnt;
720         }
721         tot_out = 0;
722         TAILQ_FOREACH(lnet, &stcb->asoc.nets, sctp_next) {
723                 tot_out += lnet->flight_size;
724         }
725         if (tot_out != stcb->asoc.total_flight) {
726                 sctp_audit_data[sctp_audit_indx][0] = 0xAF;
727                 sctp_audit_data[sctp_audit_indx][1] = 0xA3;
728                 sctp_audit_indx++;
729                 if (sctp_audit_indx >= SCTP_AUDIT_SIZE) {
730                         sctp_audit_indx = 0;
731                 }
732                 rep = 1;
733                 SCTP_PRINTF("real flight:%d net total was %d\n",
734                     stcb->asoc.total_flight, tot_out);
735                 /* now corrective action */
736                 TAILQ_FOREACH(lnet, &stcb->asoc.nets, sctp_next) {
737
738                         tot_out = 0;
739                         TAILQ_FOREACH(chk, &stcb->asoc.sent_queue, sctp_next) {
740                                 if ((chk->whoTo == lnet) &&
741                                     (chk->sent < SCTP_DATAGRAM_RESEND)) {
742                                         tot_out += chk->book_size;
743                                 }
744                         }
745                         if (lnet->flight_size != tot_out) {
746                                 SCTP_PRINTF("net:%p flight was %d corrected to %d\n",
747                                     (void *)lnet, lnet->flight_size,
748                                     tot_out);
749                                 lnet->flight_size = tot_out;
750                         }
751                 }
752         }
753         if (rep) {
754                 sctp_print_audit_report();
755         }
756 }
757
758 void
759 sctp_audit_log(uint8_t ev, uint8_t fd)
760 {
761
762         sctp_audit_data[sctp_audit_indx][0] = ev;
763         sctp_audit_data[sctp_audit_indx][1] = fd;
764         sctp_audit_indx++;
765         if (sctp_audit_indx >= SCTP_AUDIT_SIZE) {
766                 sctp_audit_indx = 0;
767         }
768 }
769
770 #endif
771
772 /*
773  * sctp_stop_timers_for_shutdown() should be called
774  * when entering the SHUTDOWN_SENT or SHUTDOWN_ACK_SENT
775  * state to make sure that all timers are stopped.
776  */
777 void
778 sctp_stop_timers_for_shutdown(struct sctp_tcb *stcb)
779 {
780         struct sctp_association *asoc;
781         struct sctp_nets *net;
782
783         asoc = &stcb->asoc;
784
785         (void)SCTP_OS_TIMER_STOP(&asoc->dack_timer.timer);
786         (void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
787         (void)SCTP_OS_TIMER_STOP(&asoc->asconf_timer.timer);
788         (void)SCTP_OS_TIMER_STOP(&asoc->autoclose_timer.timer);
789         (void)SCTP_OS_TIMER_STOP(&asoc->delayed_event_timer.timer);
790         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
791                 (void)SCTP_OS_TIMER_STOP(&net->pmtu_timer.timer);
792                 (void)SCTP_OS_TIMER_STOP(&net->hb_timer.timer);
793         }
794 }
795
796 /*
797  * A list of sizes based on typical mtu's, used only if next hop size not
798  * returned. These values MUST be multiples of 4 and MUST be ordered.
799  */
800 static uint32_t sctp_mtu_sizes[] = {
801         68,
802         296,
803         508,
804         512,
805         544,
806         576,
807         1004,
808         1492,
809         1500,
810         1536,
811         2000,
812         2048,
813         4352,
814         4464,
815         8166,
816         17912,
817         32000,
818         65532
819 };
820
821 /*
822  * Return the largest MTU in sctp_mtu_sizes smaller than val.
823  * If val is smaller than the minimum, just return the largest
824  * multiple of 4 smaller or equal to val.
825  * Ensure that the result is a multiple of 4.
826  */
827 uint32_t
828 sctp_get_prev_mtu(uint32_t val)
829 {
830         uint32_t i;
831
832         val &= 0xfffffffc;
833         if (val <= sctp_mtu_sizes[0]) {
834                 return (val);
835         }
836         for (i = 1; i < (sizeof(sctp_mtu_sizes) / sizeof(uint32_t)); i++) {
837                 if (val <= sctp_mtu_sizes[i]) {
838                         break;
839                 }
840         }
841         KASSERT((sctp_mtu_sizes[i - 1] & 0x00000003) == 0,
842             ("sctp_mtu_sizes[%u] not a multiple of 4", i - 1));
843         return (sctp_mtu_sizes[i - 1]);
844 }
845
846 /*
847  * Return the smallest MTU in sctp_mtu_sizes larger than val.
848  * If val is larger than the maximum, just return the largest multiple of 4 smaller
849  * or equal to val.
850  * Ensure that the result is a multiple of 4.
851  */
852 uint32_t
853 sctp_get_next_mtu(uint32_t val)
854 {
855         /* select another MTU that is just bigger than this one */
856         uint32_t i;
857
858         val &= 0xfffffffc;
859         for (i = 0; i < (sizeof(sctp_mtu_sizes) / sizeof(uint32_t)); i++) {
860                 if (val < sctp_mtu_sizes[i]) {
861                         KASSERT((sctp_mtu_sizes[i] & 0x00000003) == 0,
862                             ("sctp_mtu_sizes[%u] not a multiple of 4", i));
863                         return (sctp_mtu_sizes[i]);
864                 }
865         }
866         return (val);
867 }
868
869 void
870 sctp_fill_random_store(struct sctp_pcb *m)
871 {
872         /*
873          * Here we use the MD5/SHA-1 to hash with our good randomNumbers and
874          * our counter. The result becomes our good random numbers and we
875          * then setup to give these out. Note that we do no locking to
876          * protect this. This is ok, since if competing folks call this we
877          * will get more gobbled gook in the random store which is what we
878          * want. There is a danger that two guys will use the same random
879          * numbers, but thats ok too since that is random as well :->
880          */
881         m->store_at = 0;
882         (void)sctp_hmac(SCTP_HMAC, (uint8_t *)m->random_numbers,
883             sizeof(m->random_numbers), (uint8_t *)&m->random_counter,
884             sizeof(m->random_counter), (uint8_t *)m->random_store);
885         m->random_counter++;
886 }
887
888 uint32_t
889 sctp_select_initial_TSN(struct sctp_pcb *inp)
890 {
891         /*
892          * A true implementation should use random selection process to get
893          * the initial stream sequence number, using RFC1750 as a good
894          * guideline
895          */
896         uint32_t x, *xp;
897         uint8_t *p;
898         int store_at, new_store;
899
900         if (inp->initial_sequence_debug != 0) {
901                 uint32_t ret;
902
903                 ret = inp->initial_sequence_debug;
904                 inp->initial_sequence_debug++;
905                 return (ret);
906         }
907 retry:
908         store_at = inp->store_at;
909         new_store = store_at + sizeof(uint32_t);
910         if (new_store >= (SCTP_SIGNATURE_SIZE - 3)) {
911                 new_store = 0;
912         }
913         if (!atomic_cmpset_int(&inp->store_at, store_at, new_store)) {
914                 goto retry;
915         }
916         if (new_store == 0) {
917                 /* Refill the random store */
918                 sctp_fill_random_store(inp);
919         }
920         p = &inp->random_store[store_at];
921         xp = (uint32_t *)p;
922         x = *xp;
923         return (x);
924 }
925
926 uint32_t
927 sctp_select_a_tag(struct sctp_inpcb *inp, uint16_t lport, uint16_t rport, int check)
928 {
929         uint32_t x;
930         struct timeval now;
931
932         if (check) {
933                 (void)SCTP_GETTIME_TIMEVAL(&now);
934         }
935         for (;;) {
936                 x = sctp_select_initial_TSN(&inp->sctp_ep);
937                 if (x == 0) {
938                         /* we never use 0 */
939                         continue;
940                 }
941                 if (!check || sctp_is_vtag_good(x, lport, rport, &now)) {
942                         break;
943                 }
944         }
945         return (x);
946 }
947
948 int32_t
949 sctp_map_assoc_state(int kernel_state)
950 {
951         int32_t user_state;
952
953         if (kernel_state & SCTP_STATE_WAS_ABORTED) {
954                 user_state = SCTP_CLOSED;
955         } else if (kernel_state & SCTP_STATE_SHUTDOWN_PENDING) {
956                 user_state = SCTP_SHUTDOWN_PENDING;
957         } else {
958                 switch (kernel_state & SCTP_STATE_MASK) {
959                 case SCTP_STATE_EMPTY:
960                         user_state = SCTP_CLOSED;
961                         break;
962                 case SCTP_STATE_INUSE:
963                         user_state = SCTP_CLOSED;
964                         break;
965                 case SCTP_STATE_COOKIE_WAIT:
966                         user_state = SCTP_COOKIE_WAIT;
967                         break;
968                 case SCTP_STATE_COOKIE_ECHOED:
969                         user_state = SCTP_COOKIE_ECHOED;
970                         break;
971                 case SCTP_STATE_OPEN:
972                         user_state = SCTP_ESTABLISHED;
973                         break;
974                 case SCTP_STATE_SHUTDOWN_SENT:
975                         user_state = SCTP_SHUTDOWN_SENT;
976                         break;
977                 case SCTP_STATE_SHUTDOWN_RECEIVED:
978                         user_state = SCTP_SHUTDOWN_RECEIVED;
979                         break;
980                 case SCTP_STATE_SHUTDOWN_ACK_SENT:
981                         user_state = SCTP_SHUTDOWN_ACK_SENT;
982                         break;
983                 default:
984                         user_state = SCTP_CLOSED;
985                         break;
986                 }
987         }
988         return (user_state);
989 }
990
991 int
992 sctp_init_asoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
993     uint32_t override_tag, uint32_t vrf_id, uint16_t o_strms)
994 {
995         struct sctp_association *asoc;
996
997         /*
998          * Anything set to zero is taken care of by the allocation routine's
999          * bzero
1000          */
1001
1002         /*
1003          * Up front select what scoping to apply on addresses I tell my peer
1004          * Not sure what to do with these right now, we will need to come up
1005          * with a way to set them. We may need to pass them through from the
1006          * caller in the sctp_aloc_assoc() function.
1007          */
1008         int i;
1009 #if defined(SCTP_DETAILED_STR_STATS)
1010         int j;
1011 #endif
1012
1013         asoc = &stcb->asoc;
1014         /* init all variables to a known value. */
1015         SCTP_SET_STATE(stcb, SCTP_STATE_INUSE);
1016         asoc->max_burst = inp->sctp_ep.max_burst;
1017         asoc->fr_max_burst = inp->sctp_ep.fr_max_burst;
1018         asoc->heart_beat_delay = TICKS_TO_MSEC(inp->sctp_ep.sctp_timeoutticks[SCTP_TIMER_HEARTBEAT]);
1019         asoc->cookie_life = inp->sctp_ep.def_cookie_life;
1020         asoc->sctp_cmt_on_off = inp->sctp_cmt_on_off;
1021         asoc->ecn_supported = inp->ecn_supported;
1022         asoc->prsctp_supported = inp->prsctp_supported;
1023         asoc->idata_supported = inp->idata_supported;
1024         asoc->auth_supported = inp->auth_supported;
1025         asoc->asconf_supported = inp->asconf_supported;
1026         asoc->reconfig_supported = inp->reconfig_supported;
1027         asoc->nrsack_supported = inp->nrsack_supported;
1028         asoc->pktdrop_supported = inp->pktdrop_supported;
1029         asoc->idata_supported = inp->idata_supported;
1030         asoc->sctp_cmt_pf = (uint8_t)0;
1031         asoc->sctp_frag_point = inp->sctp_frag_point;
1032         asoc->sctp_features = inp->sctp_features;
1033         asoc->default_dscp = inp->sctp_ep.default_dscp;
1034         asoc->max_cwnd = inp->max_cwnd;
1035 #ifdef INET6
1036         if (inp->sctp_ep.default_flowlabel) {
1037                 asoc->default_flowlabel = inp->sctp_ep.default_flowlabel;
1038         } else {
1039                 if (inp->ip_inp.inp.inp_flags & IN6P_AUTOFLOWLABEL) {
1040                         asoc->default_flowlabel = sctp_select_initial_TSN(&inp->sctp_ep);
1041                         asoc->default_flowlabel &= 0x000fffff;
1042                         asoc->default_flowlabel |= 0x80000000;
1043                 } else {
1044                         asoc->default_flowlabel = 0;
1045                 }
1046         }
1047 #endif
1048         asoc->sb_send_resv = 0;
1049         if (override_tag) {
1050                 asoc->my_vtag = override_tag;
1051         } else {
1052                 asoc->my_vtag = sctp_select_a_tag(inp, stcb->sctp_ep->sctp_lport, stcb->rport, 1);
1053         }
1054         /* Get the nonce tags */
1055         asoc->my_vtag_nonce = sctp_select_a_tag(inp, stcb->sctp_ep->sctp_lport, stcb->rport, 0);
1056         asoc->peer_vtag_nonce = sctp_select_a_tag(inp, stcb->sctp_ep->sctp_lport, stcb->rport, 0);
1057         asoc->vrf_id = vrf_id;
1058
1059 #ifdef SCTP_ASOCLOG_OF_TSNS
1060         asoc->tsn_in_at = 0;
1061         asoc->tsn_out_at = 0;
1062         asoc->tsn_in_wrapped = 0;
1063         asoc->tsn_out_wrapped = 0;
1064         asoc->cumack_log_at = 0;
1065         asoc->cumack_log_atsnt = 0;
1066 #endif
1067 #ifdef SCTP_FS_SPEC_LOG
1068         asoc->fs_index = 0;
1069 #endif
1070         asoc->refcnt = 0;
1071         asoc->assoc_up_sent = 0;
1072         asoc->asconf_seq_out = asoc->str_reset_seq_out = asoc->init_seq_number = asoc->sending_seq =
1073             sctp_select_initial_TSN(&inp->sctp_ep);
1074         asoc->asconf_seq_out_acked = asoc->asconf_seq_out - 1;
1075         /* we are optimisitic here */
1076         asoc->peer_supports_nat = 0;
1077         asoc->sent_queue_retran_cnt = 0;
1078
1079         /* for CMT */
1080         asoc->last_net_cmt_send_started = NULL;
1081
1082         /* This will need to be adjusted */
1083         asoc->last_acked_seq = asoc->init_seq_number - 1;
1084         asoc->advanced_peer_ack_point = asoc->last_acked_seq;
1085         asoc->asconf_seq_in = asoc->last_acked_seq;
1086
1087         /* here we are different, we hold the next one we expect */
1088         asoc->str_reset_seq_in = asoc->last_acked_seq + 1;
1089
1090         asoc->initial_init_rto_max = inp->sctp_ep.initial_init_rto_max;
1091         asoc->initial_rto = inp->sctp_ep.initial_rto;
1092
1093         asoc->default_mtu = inp->sctp_ep.default_mtu;
1094         asoc->max_init_times = inp->sctp_ep.max_init_times;
1095         asoc->max_send_times = inp->sctp_ep.max_send_times;
1096         asoc->def_net_failure = inp->sctp_ep.def_net_failure;
1097         asoc->def_net_pf_threshold = inp->sctp_ep.def_net_pf_threshold;
1098         asoc->free_chunk_cnt = 0;
1099
1100         asoc->iam_blocking = 0;
1101         asoc->context = inp->sctp_context;
1102         asoc->local_strreset_support = inp->local_strreset_support;
1103         asoc->def_send = inp->def_send;
1104         asoc->delayed_ack = TICKS_TO_MSEC(inp->sctp_ep.sctp_timeoutticks[SCTP_TIMER_RECV]);
1105         asoc->sack_freq = inp->sctp_ep.sctp_sack_freq;
1106         asoc->pr_sctp_cnt = 0;
1107         asoc->total_output_queue_size = 0;
1108
1109         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
1110                 asoc->scope.ipv6_addr_legal = 1;
1111                 if (SCTP_IPV6_V6ONLY(inp) == 0) {
1112                         asoc->scope.ipv4_addr_legal = 1;
1113                 } else {
1114                         asoc->scope.ipv4_addr_legal = 0;
1115                 }
1116         } else {
1117                 asoc->scope.ipv6_addr_legal = 0;
1118                 asoc->scope.ipv4_addr_legal = 1;
1119         }
1120
1121         asoc->my_rwnd = max(SCTP_SB_LIMIT_RCV(inp->sctp_socket), SCTP_MINIMAL_RWND);
1122         asoc->peers_rwnd = SCTP_SB_LIMIT_RCV(inp->sctp_socket);
1123
1124         asoc->smallest_mtu = inp->sctp_frag_point;
1125         asoc->minrto = inp->sctp_ep.sctp_minrto;
1126         asoc->maxrto = inp->sctp_ep.sctp_maxrto;
1127
1128         asoc->stream_locked_on = 0;
1129         asoc->ecn_echo_cnt_onq = 0;
1130         asoc->stream_locked = 0;
1131
1132         asoc->send_sack = 1;
1133
1134         LIST_INIT(&asoc->sctp_restricted_addrs);
1135
1136         TAILQ_INIT(&asoc->nets);
1137         TAILQ_INIT(&asoc->pending_reply_queue);
1138         TAILQ_INIT(&asoc->asconf_ack_sent);
1139         /* Setup to fill the hb random cache at first HB */
1140         asoc->hb_random_idx = 4;
1141
1142         asoc->sctp_autoclose_ticks = inp->sctp_ep.auto_close_time;
1143
1144         stcb->asoc.congestion_control_module = inp->sctp_ep.sctp_default_cc_module;
1145         stcb->asoc.cc_functions = sctp_cc_functions[inp->sctp_ep.sctp_default_cc_module];
1146
1147         stcb->asoc.stream_scheduling_module = inp->sctp_ep.sctp_default_ss_module;
1148         stcb->asoc.ss_functions = sctp_ss_functions[inp->sctp_ep.sctp_default_ss_module];
1149
1150         /*
1151          * Now the stream parameters, here we allocate space for all streams
1152          * that we request by default.
1153          */
1154         asoc->strm_realoutsize = asoc->streamoutcnt = asoc->pre_open_streams =
1155             o_strms;
1156         SCTP_MALLOC(asoc->strmout, struct sctp_stream_out *,
1157             asoc->streamoutcnt * sizeof(struct sctp_stream_out),
1158             SCTP_M_STRMO);
1159         if (asoc->strmout == NULL) {
1160                 /* big trouble no memory */
1161                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, ENOMEM);
1162                 return (ENOMEM);
1163         }
1164         for (i = 0; i < asoc->streamoutcnt; i++) {
1165                 /*
1166                  * inbound side must be set to 0xffff, also NOTE when we get
1167                  * the INIT-ACK back (for INIT sender) we MUST reduce the
1168                  * count (streamoutcnt) but first check if we sent to any of
1169                  * the upper streams that were dropped (if some were). Those
1170                  * that were dropped must be notified to the upper layer as
1171                  * failed to send.
1172                  */
1173                 asoc->strmout[i].next_mid_ordered = 0;
1174                 asoc->strmout[i].next_mid_unordered = 0;
1175                 TAILQ_INIT(&asoc->strmout[i].outqueue);
1176                 asoc->strmout[i].chunks_on_queues = 0;
1177 #if defined(SCTP_DETAILED_STR_STATS)
1178                 for (j = 0; j < SCTP_PR_SCTP_MAX + 1; j++) {
1179                         asoc->strmout[i].abandoned_sent[j] = 0;
1180                         asoc->strmout[i].abandoned_unsent[j] = 0;
1181                 }
1182 #else
1183                 asoc->strmout[i].abandoned_sent[0] = 0;
1184                 asoc->strmout[i].abandoned_unsent[0] = 0;
1185 #endif
1186                 asoc->strmout[i].sid = i;
1187                 asoc->strmout[i].last_msg_incomplete = 0;
1188                 asoc->strmout[i].state = SCTP_STREAM_OPENING;
1189                 asoc->ss_functions.sctp_ss_init_stream(stcb, &asoc->strmout[i], NULL);
1190         }
1191         asoc->ss_functions.sctp_ss_init(stcb, asoc, 0);
1192
1193         /* Now the mapping array */
1194         asoc->mapping_array_size = SCTP_INITIAL_MAPPING_ARRAY;
1195         SCTP_MALLOC(asoc->mapping_array, uint8_t *, asoc->mapping_array_size,
1196             SCTP_M_MAP);
1197         if (asoc->mapping_array == NULL) {
1198                 SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
1199                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, ENOMEM);
1200                 return (ENOMEM);
1201         }
1202         memset(asoc->mapping_array, 0, asoc->mapping_array_size);
1203         SCTP_MALLOC(asoc->nr_mapping_array, uint8_t *, asoc->mapping_array_size,
1204             SCTP_M_MAP);
1205         if (asoc->nr_mapping_array == NULL) {
1206                 SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
1207                 SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
1208                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, ENOMEM);
1209                 return (ENOMEM);
1210         }
1211         memset(asoc->nr_mapping_array, 0, asoc->mapping_array_size);
1212
1213         /* Now the init of the other outqueues */
1214         TAILQ_INIT(&asoc->free_chunks);
1215         TAILQ_INIT(&asoc->control_send_queue);
1216         TAILQ_INIT(&asoc->asconf_send_queue);
1217         TAILQ_INIT(&asoc->send_queue);
1218         TAILQ_INIT(&asoc->sent_queue);
1219         TAILQ_INIT(&asoc->resetHead);
1220         asoc->max_inbound_streams = inp->sctp_ep.max_open_streams_intome;
1221         TAILQ_INIT(&asoc->asconf_queue);
1222         /* authentication fields */
1223         asoc->authinfo.random = NULL;
1224         asoc->authinfo.active_keyid = 0;
1225         asoc->authinfo.assoc_key = NULL;
1226         asoc->authinfo.assoc_keyid = 0;
1227         asoc->authinfo.recv_key = NULL;
1228         asoc->authinfo.recv_keyid = 0;
1229         LIST_INIT(&asoc->shared_keys);
1230         asoc->marked_retrans = 0;
1231         asoc->port = inp->sctp_ep.port;
1232         asoc->timoinit = 0;
1233         asoc->timodata = 0;
1234         asoc->timosack = 0;
1235         asoc->timoshutdown = 0;
1236         asoc->timoheartbeat = 0;
1237         asoc->timocookie = 0;
1238         asoc->timoshutdownack = 0;
1239         (void)SCTP_GETTIME_TIMEVAL(&asoc->start_time);
1240         asoc->discontinuity_time = asoc->start_time;
1241         for (i = 0; i < SCTP_PR_SCTP_MAX + 1; i++) {
1242                 asoc->abandoned_unsent[i] = 0;
1243                 asoc->abandoned_sent[i] = 0;
1244         }
1245         /*
1246          * sa_ignore MEMLEAK {memory is put in the assoc mapping array and
1247          * freed later when the association is freed.
1248          */
1249         return (0);
1250 }
1251
1252 void
1253 sctp_print_mapping_array(struct sctp_association *asoc)
1254 {
1255         unsigned int i, limit;
1256
1257         SCTP_PRINTF("Mapping array size: %d, baseTSN: %8.8x, cumAck: %8.8x, highestTSN: (%8.8x, %8.8x).\n",
1258             asoc->mapping_array_size,
1259             asoc->mapping_array_base_tsn,
1260             asoc->cumulative_tsn,
1261             asoc->highest_tsn_inside_map,
1262             asoc->highest_tsn_inside_nr_map);
1263         for (limit = asoc->mapping_array_size; limit > 1; limit--) {
1264                 if (asoc->mapping_array[limit - 1] != 0) {
1265                         break;
1266                 }
1267         }
1268         SCTP_PRINTF("Renegable mapping array (last %d entries are zero):\n", asoc->mapping_array_size - limit);
1269         for (i = 0; i < limit; i++) {
1270                 SCTP_PRINTF("%2.2x%c", asoc->mapping_array[i], ((i + 1) % 16) ? ' ' : '\n');
1271         }
1272         if (limit % 16)
1273                 SCTP_PRINTF("\n");
1274         for (limit = asoc->mapping_array_size; limit > 1; limit--) {
1275                 if (asoc->nr_mapping_array[limit - 1]) {
1276                         break;
1277                 }
1278         }
1279         SCTP_PRINTF("Non renegable mapping array (last %d entries are zero):\n", asoc->mapping_array_size - limit);
1280         for (i = 0; i < limit; i++) {
1281                 SCTP_PRINTF("%2.2x%c", asoc->nr_mapping_array[i], ((i + 1) % 16) ? ' ' : '\n');
1282         }
1283         if (limit % 16)
1284                 SCTP_PRINTF("\n");
1285 }
1286
1287 int
1288 sctp_expand_mapping_array(struct sctp_association *asoc, uint32_t needed)
1289 {
1290         /* mapping array needs to grow */
1291         uint8_t *new_array1, *new_array2;
1292         uint32_t new_size;
1293
1294         new_size = asoc->mapping_array_size + ((needed + 7) / 8 + SCTP_MAPPING_ARRAY_INCR);
1295         SCTP_MALLOC(new_array1, uint8_t *, new_size, SCTP_M_MAP);
1296         SCTP_MALLOC(new_array2, uint8_t *, new_size, SCTP_M_MAP);
1297         if ((new_array1 == NULL) || (new_array2 == NULL)) {
1298                 /* can't get more, forget it */
1299                 SCTP_PRINTF("No memory for expansion of SCTP mapping array %d\n", new_size);
1300                 if (new_array1) {
1301                         SCTP_FREE(new_array1, SCTP_M_MAP);
1302                 }
1303                 if (new_array2) {
1304                         SCTP_FREE(new_array2, SCTP_M_MAP);
1305                 }
1306                 return (-1);
1307         }
1308         memset(new_array1, 0, new_size);
1309         memset(new_array2, 0, new_size);
1310         memcpy(new_array1, asoc->mapping_array, asoc->mapping_array_size);
1311         memcpy(new_array2, asoc->nr_mapping_array, asoc->mapping_array_size);
1312         SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
1313         SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
1314         asoc->mapping_array = new_array1;
1315         asoc->nr_mapping_array = new_array2;
1316         asoc->mapping_array_size = new_size;
1317         return (0);
1318 }
1319
1320
1321 static void
1322 sctp_iterator_work(struct sctp_iterator *it)
1323 {
1324         int iteration_count = 0;
1325         int inp_skip = 0;
1326         int first_in = 1;
1327         struct sctp_inpcb *tinp;
1328
1329         SCTP_INP_INFO_RLOCK();
1330         SCTP_ITERATOR_LOCK();
1331         sctp_it_ctl.cur_it = it;
1332         if (it->inp) {
1333                 SCTP_INP_RLOCK(it->inp);
1334                 SCTP_INP_DECR_REF(it->inp);
1335         }
1336         if (it->inp == NULL) {
1337                 /* iterator is complete */
1338 done_with_iterator:
1339                 sctp_it_ctl.cur_it = NULL;
1340                 SCTP_ITERATOR_UNLOCK();
1341                 SCTP_INP_INFO_RUNLOCK();
1342                 if (it->function_atend != NULL) {
1343                         (*it->function_atend) (it->pointer, it->val);
1344                 }
1345                 SCTP_FREE(it, SCTP_M_ITER);
1346                 return;
1347         }
1348 select_a_new_ep:
1349         if (first_in) {
1350                 first_in = 0;
1351         } else {
1352                 SCTP_INP_RLOCK(it->inp);
1353         }
1354         while (((it->pcb_flags) &&
1355             ((it->inp->sctp_flags & it->pcb_flags) != it->pcb_flags)) ||
1356             ((it->pcb_features) &&
1357             ((it->inp->sctp_features & it->pcb_features) != it->pcb_features))) {
1358                 /* endpoint flags or features don't match, so keep looking */
1359                 if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
1360                         SCTP_INP_RUNLOCK(it->inp);
1361                         goto done_with_iterator;
1362                 }
1363                 tinp = it->inp;
1364                 it->inp = LIST_NEXT(it->inp, sctp_list);
1365                 SCTP_INP_RUNLOCK(tinp);
1366                 if (it->inp == NULL) {
1367                         goto done_with_iterator;
1368                 }
1369                 SCTP_INP_RLOCK(it->inp);
1370         }
1371         /* now go through each assoc which is in the desired state */
1372         if (it->done_current_ep == 0) {
1373                 if (it->function_inp != NULL)
1374                         inp_skip = (*it->function_inp) (it->inp, it->pointer, it->val);
1375                 it->done_current_ep = 1;
1376         }
1377         if (it->stcb == NULL) {
1378                 /* run the per instance function */
1379                 it->stcb = LIST_FIRST(&it->inp->sctp_asoc_list);
1380         }
1381         if ((inp_skip) || it->stcb == NULL) {
1382                 if (it->function_inp_end != NULL) {
1383                         inp_skip = (*it->function_inp_end) (it->inp,
1384                             it->pointer,
1385                             it->val);
1386                 }
1387                 SCTP_INP_RUNLOCK(it->inp);
1388                 goto no_stcb;
1389         }
1390         while (it->stcb) {
1391                 SCTP_TCB_LOCK(it->stcb);
1392                 if (it->asoc_state && ((it->stcb->asoc.state & it->asoc_state) != it->asoc_state)) {
1393                         /* not in the right state... keep looking */
1394                         SCTP_TCB_UNLOCK(it->stcb);
1395                         goto next_assoc;
1396                 }
1397                 /* see if we have limited out the iterator loop */
1398                 iteration_count++;
1399                 if (iteration_count > SCTP_ITERATOR_MAX_AT_ONCE) {
1400                         /* Pause to let others grab the lock */
1401                         atomic_add_int(&it->stcb->asoc.refcnt, 1);
1402                         SCTP_TCB_UNLOCK(it->stcb);
1403                         SCTP_INP_INCR_REF(it->inp);
1404                         SCTP_INP_RUNLOCK(it->inp);
1405                         SCTP_ITERATOR_UNLOCK();
1406                         SCTP_INP_INFO_RUNLOCK();
1407                         SCTP_INP_INFO_RLOCK();
1408                         SCTP_ITERATOR_LOCK();
1409                         if (sctp_it_ctl.iterator_flags) {
1410                                 /* We won't be staying here */
1411                                 SCTP_INP_DECR_REF(it->inp);
1412                                 atomic_add_int(&it->stcb->asoc.refcnt, -1);
1413                                 if (sctp_it_ctl.iterator_flags &
1414                                     SCTP_ITERATOR_STOP_CUR_IT) {
1415                                         sctp_it_ctl.iterator_flags &= ~SCTP_ITERATOR_STOP_CUR_IT;
1416                                         goto done_with_iterator;
1417                                 }
1418                                 if (sctp_it_ctl.iterator_flags &
1419                                     SCTP_ITERATOR_STOP_CUR_INP) {
1420                                         sctp_it_ctl.iterator_flags &= ~SCTP_ITERATOR_STOP_CUR_INP;
1421                                         goto no_stcb;
1422                                 }
1423                                 /* If we reach here huh? */
1424                                 SCTP_PRINTF("Unknown it ctl flag %x\n",
1425                                     sctp_it_ctl.iterator_flags);
1426                                 sctp_it_ctl.iterator_flags = 0;
1427                         }
1428                         SCTP_INP_RLOCK(it->inp);
1429                         SCTP_INP_DECR_REF(it->inp);
1430                         SCTP_TCB_LOCK(it->stcb);
1431                         atomic_add_int(&it->stcb->asoc.refcnt, -1);
1432                         iteration_count = 0;
1433                 }
1434
1435                 /* run function on this one */
1436                 (*it->function_assoc) (it->inp, it->stcb, it->pointer, it->val);
1437
1438                 /*
1439                  * we lie here, it really needs to have its own type but
1440                  * first I must verify that this won't effect things :-0
1441                  */
1442                 if (it->no_chunk_output == 0)
1443                         sctp_chunk_output(it->inp, it->stcb, SCTP_OUTPUT_FROM_T3, SCTP_SO_NOT_LOCKED);
1444
1445                 SCTP_TCB_UNLOCK(it->stcb);
1446 next_assoc:
1447                 it->stcb = LIST_NEXT(it->stcb, sctp_tcblist);
1448                 if (it->stcb == NULL) {
1449                         /* Run last function */
1450                         if (it->function_inp_end != NULL) {
1451                                 inp_skip = (*it->function_inp_end) (it->inp,
1452                                     it->pointer,
1453                                     it->val);
1454                         }
1455                 }
1456         }
1457         SCTP_INP_RUNLOCK(it->inp);
1458 no_stcb:
1459         /* done with all assocs on this endpoint, move on to next endpoint */
1460         it->done_current_ep = 0;
1461         if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
1462                 it->inp = NULL;
1463         } else {
1464                 it->inp = LIST_NEXT(it->inp, sctp_list);
1465         }
1466         if (it->inp == NULL) {
1467                 goto done_with_iterator;
1468         }
1469         goto select_a_new_ep;
1470 }
1471
1472 void
1473 sctp_iterator_worker(void)
1474 {
1475         struct sctp_iterator *it, *nit;
1476
1477         /* This function is called with the WQ lock in place */
1478
1479         sctp_it_ctl.iterator_running = 1;
1480         TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
1481                 /* now lets work on this one */
1482                 TAILQ_REMOVE(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
1483                 SCTP_IPI_ITERATOR_WQ_UNLOCK();
1484                 CURVNET_SET(it->vn);
1485                 sctp_iterator_work(it);
1486                 CURVNET_RESTORE();
1487                 SCTP_IPI_ITERATOR_WQ_LOCK();
1488                 /* sa_ignore FREED_MEMORY */
1489         }
1490         sctp_it_ctl.iterator_running = 0;
1491         return;
1492 }
1493
1494
1495 static void
1496 sctp_handle_addr_wq(void)
1497 {
1498         /* deal with the ADDR wq from the rtsock calls */
1499         struct sctp_laddr *wi, *nwi;
1500         struct sctp_asconf_iterator *asc;
1501
1502         SCTP_MALLOC(asc, struct sctp_asconf_iterator *,
1503             sizeof(struct sctp_asconf_iterator), SCTP_M_ASC_IT);
1504         if (asc == NULL) {
1505                 /* Try later, no memory */
1506                 sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
1507                     (struct sctp_inpcb *)NULL,
1508                     (struct sctp_tcb *)NULL,
1509                     (struct sctp_nets *)NULL);
1510                 return;
1511         }
1512         LIST_INIT(&asc->list_of_work);
1513         asc->cnt = 0;
1514
1515         LIST_FOREACH_SAFE(wi, &SCTP_BASE_INFO(addr_wq), sctp_nxt_addr, nwi) {
1516                 LIST_REMOVE(wi, sctp_nxt_addr);
1517                 LIST_INSERT_HEAD(&asc->list_of_work, wi, sctp_nxt_addr);
1518                 asc->cnt++;
1519         }
1520
1521         if (asc->cnt == 0) {
1522                 SCTP_FREE(asc, SCTP_M_ASC_IT);
1523         } else {
1524                 int ret;
1525
1526                 ret = sctp_initiate_iterator(sctp_asconf_iterator_ep,
1527                     sctp_asconf_iterator_stcb,
1528                     NULL,       /* No ep end for boundall */
1529                     SCTP_PCB_FLAGS_BOUNDALL,
1530                     SCTP_PCB_ANY_FEATURES,
1531                     SCTP_ASOC_ANY_STATE,
1532                     (void *)asc, 0,
1533                     sctp_asconf_iterator_end, NULL, 0);
1534                 if (ret) {
1535                         SCTP_PRINTF("Failed to initiate iterator for handle_addr_wq\n");
1536                         /*
1537                          * Freeing if we are stopping or put back on the
1538                          * addr_wq.
1539                          */
1540                         if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) {
1541                                 sctp_asconf_iterator_end(asc, 0);
1542                         } else {
1543                                 LIST_FOREACH(wi, &asc->list_of_work, sctp_nxt_addr) {
1544                                         LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
1545                                 }
1546                                 SCTP_FREE(asc, SCTP_M_ASC_IT);
1547                         }
1548                 }
1549         }
1550 }
1551
1552 void
1553 sctp_timeout_handler(void *t)
1554 {
1555         struct sctp_inpcb *inp;
1556         struct sctp_tcb *stcb;
1557         struct sctp_nets *net;
1558         struct sctp_timer *tmr;
1559         struct mbuf *op_err;
1560 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1561         struct socket *so;
1562 #endif
1563         int did_output;
1564         int type;
1565
1566         tmr = (struct sctp_timer *)t;
1567         inp = (struct sctp_inpcb *)tmr->ep;
1568         stcb = (struct sctp_tcb *)tmr->tcb;
1569         net = (struct sctp_nets *)tmr->net;
1570         CURVNET_SET((struct vnet *)tmr->vnet);
1571         did_output = 1;
1572
1573 #ifdef SCTP_AUDITING_ENABLED
1574         sctp_audit_log(0xF0, (uint8_t)tmr->type);
1575         sctp_auditing(3, inp, stcb, net);
1576 #endif
1577
1578         /* sanity checks... */
1579         if (tmr->self != (void *)tmr) {
1580                 /*
1581                  * SCTP_PRINTF("Stale SCTP timer fired (%p), ignoring...\n",
1582                  * (void *)tmr);
1583                  */
1584                 CURVNET_RESTORE();
1585                 return;
1586         }
1587         tmr->stopped_from = 0xa001;
1588         if (!SCTP_IS_TIMER_TYPE_VALID(tmr->type)) {
1589                 /*
1590                  * SCTP_PRINTF("SCTP timer fired with invalid type: 0x%x\n",
1591                  * tmr->type);
1592                  */
1593                 CURVNET_RESTORE();
1594                 return;
1595         }
1596         tmr->stopped_from = 0xa002;
1597         if ((tmr->type != SCTP_TIMER_TYPE_ADDR_WQ) && (inp == NULL)) {
1598                 CURVNET_RESTORE();
1599                 return;
1600         }
1601         /* if this is an iterator timeout, get the struct and clear inp */
1602         tmr->stopped_from = 0xa003;
1603         if (inp) {
1604                 SCTP_INP_INCR_REF(inp);
1605                 if ((inp->sctp_socket == NULL) &&
1606                     ((tmr->type != SCTP_TIMER_TYPE_INPKILL) &&
1607                     (tmr->type != SCTP_TIMER_TYPE_INIT) &&
1608                     (tmr->type != SCTP_TIMER_TYPE_SEND) &&
1609                     (tmr->type != SCTP_TIMER_TYPE_RECV) &&
1610                     (tmr->type != SCTP_TIMER_TYPE_HEARTBEAT) &&
1611                     (tmr->type != SCTP_TIMER_TYPE_SHUTDOWN) &&
1612                     (tmr->type != SCTP_TIMER_TYPE_SHUTDOWNACK) &&
1613                     (tmr->type != SCTP_TIMER_TYPE_SHUTDOWNGUARD) &&
1614                     (tmr->type != SCTP_TIMER_TYPE_ASOCKILL))) {
1615                         SCTP_INP_DECR_REF(inp);
1616                         CURVNET_RESTORE();
1617                         return;
1618                 }
1619         }
1620         tmr->stopped_from = 0xa004;
1621         if (stcb) {
1622                 atomic_add_int(&stcb->asoc.refcnt, 1);
1623                 if (stcb->asoc.state == 0) {
1624                         atomic_add_int(&stcb->asoc.refcnt, -1);
1625                         if (inp) {
1626                                 SCTP_INP_DECR_REF(inp);
1627                         }
1628                         CURVNET_RESTORE();
1629                         return;
1630                 }
1631         }
1632         type = tmr->type;
1633         tmr->stopped_from = 0xa005;
1634         SCTPDBG(SCTP_DEBUG_TIMER1, "Timer type %d goes off\n", type);
1635         if (!SCTP_OS_TIMER_ACTIVE(&tmr->timer)) {
1636                 if (inp) {
1637                         SCTP_INP_DECR_REF(inp);
1638                 }
1639                 if (stcb) {
1640                         atomic_add_int(&stcb->asoc.refcnt, -1);
1641                 }
1642                 CURVNET_RESTORE();
1643                 return;
1644         }
1645         tmr->stopped_from = 0xa006;
1646
1647         if (stcb) {
1648                 SCTP_TCB_LOCK(stcb);
1649                 atomic_add_int(&stcb->asoc.refcnt, -1);
1650                 if ((type != SCTP_TIMER_TYPE_ASOCKILL) &&
1651                     ((stcb->asoc.state == 0) ||
1652                     (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED))) {
1653                         SCTP_TCB_UNLOCK(stcb);
1654                         if (inp) {
1655                                 SCTP_INP_DECR_REF(inp);
1656                         }
1657                         CURVNET_RESTORE();
1658                         return;
1659                 }
1660         } else if (inp != NULL) {
1661                 if (type != SCTP_TIMER_TYPE_INPKILL) {
1662                         SCTP_INP_WLOCK(inp);
1663                 }
1664         } else {
1665                 SCTP_WQ_ADDR_LOCK();
1666         }
1667         /* record in stopped what t-o occurred */
1668         tmr->stopped_from = type;
1669
1670         /* mark as being serviced now */
1671         if (SCTP_OS_TIMER_PENDING(&tmr->timer)) {
1672                 /*
1673                  * Callout has been rescheduled.
1674                  */
1675                 goto get_out;
1676         }
1677         if (!SCTP_OS_TIMER_ACTIVE(&tmr->timer)) {
1678                 /*
1679                  * Not active, so no action.
1680                  */
1681                 goto get_out;
1682         }
1683         SCTP_OS_TIMER_DEACTIVATE(&tmr->timer);
1684
1685         /* call the handler for the appropriate timer type */
1686         switch (type) {
1687         case SCTP_TIMER_TYPE_ADDR_WQ:
1688                 sctp_handle_addr_wq();
1689                 break;
1690         case SCTP_TIMER_TYPE_SEND:
1691                 if ((stcb == NULL) || (inp == NULL)) {
1692                         break;
1693                 }
1694                 SCTP_STAT_INCR(sctps_timodata);
1695                 stcb->asoc.timodata++;
1696                 stcb->asoc.num_send_timers_up--;
1697                 if (stcb->asoc.num_send_timers_up < 0) {
1698                         stcb->asoc.num_send_timers_up = 0;
1699                 }
1700                 SCTP_TCB_LOCK_ASSERT(stcb);
1701                 if (sctp_t3rxt_timer(inp, stcb, net)) {
1702                         /* no need to unlock on tcb its gone */
1703
1704                         goto out_decr;
1705                 }
1706                 SCTP_TCB_LOCK_ASSERT(stcb);
1707 #ifdef SCTP_AUDITING_ENABLED
1708                 sctp_auditing(4, inp, stcb, net);
1709 #endif
1710                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_T3, SCTP_SO_NOT_LOCKED);
1711                 if ((stcb->asoc.num_send_timers_up == 0) &&
1712                     (stcb->asoc.sent_queue_cnt > 0)) {
1713                         struct sctp_tmit_chunk *chk;
1714
1715                         /*
1716                          * safeguard. If there on some on the sent queue
1717                          * somewhere but no timers running something is
1718                          * wrong... so we start a timer on the first chunk
1719                          * on the send queue on whatever net it is sent to.
1720                          */
1721                         chk = TAILQ_FIRST(&stcb->asoc.sent_queue);
1722                         sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb,
1723                             chk->whoTo);
1724                 }
1725                 break;
1726         case SCTP_TIMER_TYPE_INIT:
1727                 if ((stcb == NULL) || (inp == NULL)) {
1728                         break;
1729                 }
1730                 SCTP_STAT_INCR(sctps_timoinit);
1731                 stcb->asoc.timoinit++;
1732                 if (sctp_t1init_timer(inp, stcb, net)) {
1733                         /* no need to unlock on tcb its gone */
1734                         goto out_decr;
1735                 }
1736                 /* We do output but not here */
1737                 did_output = 0;
1738                 break;
1739         case SCTP_TIMER_TYPE_RECV:
1740                 if ((stcb == NULL) || (inp == NULL)) {
1741                         break;
1742                 }
1743                 SCTP_STAT_INCR(sctps_timosack);
1744                 stcb->asoc.timosack++;
1745                 sctp_send_sack(stcb, SCTP_SO_NOT_LOCKED);
1746 #ifdef SCTP_AUDITING_ENABLED
1747                 sctp_auditing(4, inp, stcb, net);
1748 #endif
1749                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_SACK_TMR, SCTP_SO_NOT_LOCKED);
1750                 break;
1751         case SCTP_TIMER_TYPE_SHUTDOWN:
1752                 if ((stcb == NULL) || (inp == NULL)) {
1753                         break;
1754                 }
1755                 if (sctp_shutdown_timer(inp, stcb, net)) {
1756                         /* no need to unlock on tcb its gone */
1757                         goto out_decr;
1758                 }
1759                 SCTP_STAT_INCR(sctps_timoshutdown);
1760                 stcb->asoc.timoshutdown++;
1761 #ifdef SCTP_AUDITING_ENABLED
1762                 sctp_auditing(4, inp, stcb, net);
1763 #endif
1764                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_SHUT_TMR, SCTP_SO_NOT_LOCKED);
1765                 break;
1766         case SCTP_TIMER_TYPE_HEARTBEAT:
1767                 if ((stcb == NULL) || (inp == NULL) || (net == NULL)) {
1768                         break;
1769                 }
1770                 SCTP_STAT_INCR(sctps_timoheartbeat);
1771                 stcb->asoc.timoheartbeat++;
1772                 if (sctp_heartbeat_timer(inp, stcb, net)) {
1773                         /* no need to unlock on tcb its gone */
1774                         goto out_decr;
1775                 }
1776 #ifdef SCTP_AUDITING_ENABLED
1777                 sctp_auditing(4, inp, stcb, net);
1778 #endif
1779                 if (!(net->dest_state & SCTP_ADDR_NOHB)) {
1780                         sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT, inp, stcb, net);
1781                         sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_HB_TMR, SCTP_SO_NOT_LOCKED);
1782                 }
1783                 break;
1784         case SCTP_TIMER_TYPE_COOKIE:
1785                 if ((stcb == NULL) || (inp == NULL)) {
1786                         break;
1787                 }
1788
1789                 if (sctp_cookie_timer(inp, stcb, net)) {
1790                         /* no need to unlock on tcb its gone */
1791                         goto out_decr;
1792                 }
1793                 SCTP_STAT_INCR(sctps_timocookie);
1794                 stcb->asoc.timocookie++;
1795 #ifdef SCTP_AUDITING_ENABLED
1796                 sctp_auditing(4, inp, stcb, net);
1797 #endif
1798                 /*
1799                  * We consider T3 and Cookie timer pretty much the same with
1800                  * respect to where from in chunk_output.
1801                  */
1802                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_T3, SCTP_SO_NOT_LOCKED);
1803                 break;
1804         case SCTP_TIMER_TYPE_NEWCOOKIE:
1805                 {
1806                         struct timeval tv;
1807                         int i, secret;
1808
1809                         if (inp == NULL) {
1810                                 break;
1811                         }
1812                         SCTP_STAT_INCR(sctps_timosecret);
1813                         (void)SCTP_GETTIME_TIMEVAL(&tv);
1814                         inp->sctp_ep.time_of_secret_change = tv.tv_sec;
1815                         inp->sctp_ep.last_secret_number =
1816                             inp->sctp_ep.current_secret_number;
1817                         inp->sctp_ep.current_secret_number++;
1818                         if (inp->sctp_ep.current_secret_number >=
1819                             SCTP_HOW_MANY_SECRETS) {
1820                                 inp->sctp_ep.current_secret_number = 0;
1821                         }
1822                         secret = (int)inp->sctp_ep.current_secret_number;
1823                         for (i = 0; i < SCTP_NUMBER_OF_SECRETS; i++) {
1824                                 inp->sctp_ep.secret_key[secret][i] =
1825                                     sctp_select_initial_TSN(&inp->sctp_ep);
1826                         }
1827                         sctp_timer_start(SCTP_TIMER_TYPE_NEWCOOKIE, inp, stcb, net);
1828                 }
1829                 did_output = 0;
1830                 break;
1831         case SCTP_TIMER_TYPE_PATHMTURAISE:
1832                 if ((stcb == NULL) || (inp == NULL)) {
1833                         break;
1834                 }
1835                 SCTP_STAT_INCR(sctps_timopathmtu);
1836                 sctp_pathmtu_timer(inp, stcb, net);
1837                 did_output = 0;
1838                 break;
1839         case SCTP_TIMER_TYPE_SHUTDOWNACK:
1840                 if ((stcb == NULL) || (inp == NULL)) {
1841                         break;
1842                 }
1843                 if (sctp_shutdownack_timer(inp, stcb, net)) {
1844                         /* no need to unlock on tcb its gone */
1845                         goto out_decr;
1846                 }
1847                 SCTP_STAT_INCR(sctps_timoshutdownack);
1848                 stcb->asoc.timoshutdownack++;
1849 #ifdef SCTP_AUDITING_ENABLED
1850                 sctp_auditing(4, inp, stcb, net);
1851 #endif
1852                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_SHUT_ACK_TMR, SCTP_SO_NOT_LOCKED);
1853                 break;
1854         case SCTP_TIMER_TYPE_SHUTDOWNGUARD:
1855                 if ((stcb == NULL) || (inp == NULL)) {
1856                         break;
1857                 }
1858                 SCTP_STAT_INCR(sctps_timoshutdownguard);
1859                 op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code),
1860                     "Shutdown guard timer expired");
1861                 sctp_abort_an_association(inp, stcb, op_err, SCTP_SO_NOT_LOCKED);
1862                 /* no need to unlock on tcb its gone */
1863                 goto out_decr;
1864
1865         case SCTP_TIMER_TYPE_STRRESET:
1866                 if ((stcb == NULL) || (inp == NULL)) {
1867                         break;
1868                 }
1869                 if (sctp_strreset_timer(inp, stcb, net)) {
1870                         /* no need to unlock on tcb its gone */
1871                         goto out_decr;
1872                 }
1873                 SCTP_STAT_INCR(sctps_timostrmrst);
1874                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_STRRST_TMR, SCTP_SO_NOT_LOCKED);
1875                 break;
1876         case SCTP_TIMER_TYPE_ASCONF:
1877                 if ((stcb == NULL) || (inp == NULL)) {
1878                         break;
1879                 }
1880                 if (sctp_asconf_timer(inp, stcb, net)) {
1881                         /* no need to unlock on tcb its gone */
1882                         goto out_decr;
1883                 }
1884                 SCTP_STAT_INCR(sctps_timoasconf);
1885 #ifdef SCTP_AUDITING_ENABLED
1886                 sctp_auditing(4, inp, stcb, net);
1887 #endif
1888                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_ASCONF_TMR, SCTP_SO_NOT_LOCKED);
1889                 break;
1890         case SCTP_TIMER_TYPE_PRIM_DELETED:
1891                 if ((stcb == NULL) || (inp == NULL)) {
1892                         break;
1893                 }
1894                 sctp_delete_prim_timer(inp, stcb, net);
1895                 SCTP_STAT_INCR(sctps_timodelprim);
1896                 break;
1897
1898         case SCTP_TIMER_TYPE_AUTOCLOSE:
1899                 if ((stcb == NULL) || (inp == NULL)) {
1900                         break;
1901                 }
1902                 SCTP_STAT_INCR(sctps_timoautoclose);
1903                 sctp_autoclose_timer(inp, stcb, net);
1904                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_AUTOCLOSE_TMR, SCTP_SO_NOT_LOCKED);
1905                 did_output = 0;
1906                 break;
1907         case SCTP_TIMER_TYPE_ASOCKILL:
1908                 if ((stcb == NULL) || (inp == NULL)) {
1909                         break;
1910                 }
1911                 SCTP_STAT_INCR(sctps_timoassockill);
1912                 /* Can we free it yet? */
1913                 SCTP_INP_DECR_REF(inp);
1914                 sctp_timer_stop(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL,
1915                     SCTP_FROM_SCTPUTIL + SCTP_LOC_1);
1916 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1917                 so = SCTP_INP_SO(inp);
1918                 atomic_add_int(&stcb->asoc.refcnt, 1);
1919                 SCTP_TCB_UNLOCK(stcb);
1920                 SCTP_SOCKET_LOCK(so, 1);
1921                 SCTP_TCB_LOCK(stcb);
1922                 atomic_subtract_int(&stcb->asoc.refcnt, 1);
1923 #endif
1924                 (void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC,
1925                     SCTP_FROM_SCTPUTIL + SCTP_LOC_2);
1926 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1927                 SCTP_SOCKET_UNLOCK(so, 1);
1928 #endif
1929                 /*
1930                  * free asoc, always unlocks (or destroy's) so prevent
1931                  * duplicate unlock or unlock of a free mtx :-0
1932                  */
1933                 stcb = NULL;
1934                 goto out_no_decr;
1935         case SCTP_TIMER_TYPE_INPKILL:
1936                 SCTP_STAT_INCR(sctps_timoinpkill);
1937                 if (inp == NULL) {
1938                         break;
1939                 }
1940                 /*
1941                  * special case, take away our increment since WE are the
1942                  * killer
1943                  */
1944                 SCTP_INP_DECR_REF(inp);
1945                 sctp_timer_stop(SCTP_TIMER_TYPE_INPKILL, inp, NULL, NULL,
1946                     SCTP_FROM_SCTPUTIL + SCTP_LOC_3);
1947                 sctp_inpcb_free(inp, SCTP_FREE_SHOULD_USE_ABORT,
1948                     SCTP_CALLED_FROM_INPKILL_TIMER);
1949                 inp = NULL;
1950                 goto out_no_decr;
1951         default:
1952                 SCTPDBG(SCTP_DEBUG_TIMER1, "sctp_timeout_handler:unknown timer %d\n",
1953                     type);
1954                 break;
1955         }
1956 #ifdef SCTP_AUDITING_ENABLED
1957         sctp_audit_log(0xF1, (uint8_t)type);
1958         if (inp)
1959                 sctp_auditing(5, inp, stcb, net);
1960 #endif
1961         if ((did_output) && stcb) {
1962                 /*
1963                  * Now we need to clean up the control chunk chain if an
1964                  * ECNE is on it. It must be marked as UNSENT again so next
1965                  * call will continue to send it until such time that we get
1966                  * a CWR, to remove it. It is, however, less likely that we
1967                  * will find a ecn echo on the chain though.
1968                  */
1969                 sctp_fix_ecn_echo(&stcb->asoc);
1970         }
1971 get_out:
1972         if (stcb) {
1973                 SCTP_TCB_UNLOCK(stcb);
1974         } else if (inp != NULL) {
1975                 SCTP_INP_WUNLOCK(inp);
1976         } else {
1977                 SCTP_WQ_ADDR_UNLOCK();
1978         }
1979
1980 out_decr:
1981         if (inp) {
1982                 SCTP_INP_DECR_REF(inp);
1983         }
1984
1985 out_no_decr:
1986         SCTPDBG(SCTP_DEBUG_TIMER1, "Timer now complete (type = %d)\n", type);
1987         CURVNET_RESTORE();
1988 }
1989
1990 void
1991 sctp_timer_start(int t_type, struct sctp_inpcb *inp, struct sctp_tcb *stcb,
1992     struct sctp_nets *net)
1993 {
1994         uint32_t to_ticks;
1995         struct sctp_timer *tmr;
1996
1997         if ((t_type != SCTP_TIMER_TYPE_ADDR_WQ) && (inp == NULL))
1998                 return;
1999
2000         tmr = NULL;
2001         if (stcb) {
2002                 SCTP_TCB_LOCK_ASSERT(stcb);
2003         }
2004         switch (t_type) {
2005         case SCTP_TIMER_TYPE_ADDR_WQ:
2006                 /* Only 1 tick away :-) */
2007                 tmr = &SCTP_BASE_INFO(addr_wq_timer);
2008                 to_ticks = SCTP_ADDRESS_TICK_DELAY;
2009                 break;
2010         case SCTP_TIMER_TYPE_SEND:
2011                 /* Here we use the RTO timer */
2012                 {
2013                         int rto_val;
2014
2015                         if ((stcb == NULL) || (net == NULL)) {
2016                                 return;
2017                         }
2018                         tmr = &net->rxt_timer;
2019                         if (net->RTO == 0) {
2020                                 rto_val = stcb->asoc.initial_rto;
2021                         } else {
2022                                 rto_val = net->RTO;
2023                         }
2024                         to_ticks = MSEC_TO_TICKS(rto_val);
2025                 }
2026                 break;
2027         case SCTP_TIMER_TYPE_INIT:
2028                 /*
2029                  * Here we use the INIT timer default usually about 1
2030                  * minute.
2031                  */
2032                 if ((stcb == NULL) || (net == NULL)) {
2033                         return;
2034                 }
2035                 tmr = &net->rxt_timer;
2036                 if (net->RTO == 0) {
2037                         to_ticks = MSEC_TO_TICKS(stcb->asoc.initial_rto);
2038                 } else {
2039                         to_ticks = MSEC_TO_TICKS(net->RTO);
2040                 }
2041                 break;
2042         case SCTP_TIMER_TYPE_RECV:
2043                 /*
2044                  * Here we use the Delayed-Ack timer value from the inp
2045                  * ususually about 200ms.
2046                  */
2047                 if (stcb == NULL) {
2048                         return;
2049                 }
2050                 tmr = &stcb->asoc.dack_timer;
2051                 to_ticks = MSEC_TO_TICKS(stcb->asoc.delayed_ack);
2052                 break;
2053         case SCTP_TIMER_TYPE_SHUTDOWN:
2054                 /* Here we use the RTO of the destination. */
2055                 if ((stcb == NULL) || (net == NULL)) {
2056                         return;
2057                 }
2058                 if (net->RTO == 0) {
2059                         to_ticks = MSEC_TO_TICKS(stcb->asoc.initial_rto);
2060                 } else {
2061                         to_ticks = MSEC_TO_TICKS(net->RTO);
2062                 }
2063                 tmr = &net->rxt_timer;
2064                 break;
2065         case SCTP_TIMER_TYPE_HEARTBEAT:
2066                 /*
2067                  * the net is used here so that we can add in the RTO. Even
2068                  * though we use a different timer. We also add the HB timer
2069                  * PLUS a random jitter.
2070                  */
2071                 if ((stcb == NULL) || (net == NULL)) {
2072                         return;
2073                 } else {
2074                         uint32_t rndval;
2075                         uint32_t jitter;
2076
2077                         if ((net->dest_state & SCTP_ADDR_NOHB) &&
2078                             !(net->dest_state & SCTP_ADDR_UNCONFIRMED)) {
2079                                 return;
2080                         }
2081                         if (net->RTO == 0) {
2082                                 to_ticks = stcb->asoc.initial_rto;
2083                         } else {
2084                                 to_ticks = net->RTO;
2085                         }
2086                         rndval = sctp_select_initial_TSN(&inp->sctp_ep);
2087                         jitter = rndval % to_ticks;
2088                         if (jitter >= (to_ticks >> 1)) {
2089                                 to_ticks = to_ticks + (jitter - (to_ticks >> 1));
2090                         } else {
2091                                 to_ticks = to_ticks - jitter;
2092                         }
2093                         if (!(net->dest_state & SCTP_ADDR_UNCONFIRMED) &&
2094                             !(net->dest_state & SCTP_ADDR_PF)) {
2095                                 to_ticks += net->heart_beat_delay;
2096                         }
2097                         /*
2098                          * Now we must convert the to_ticks that are now in
2099                          * ms to ticks.
2100                          */
2101                         to_ticks = MSEC_TO_TICKS(to_ticks);
2102                         tmr = &net->hb_timer;
2103                 }
2104                 break;
2105         case SCTP_TIMER_TYPE_COOKIE:
2106                 /*
2107                  * Here we can use the RTO timer from the network since one
2108                  * RTT was compelete. If a retran happened then we will be
2109                  * using the RTO initial value.
2110                  */
2111                 if ((stcb == NULL) || (net == NULL)) {
2112                         return;
2113                 }
2114                 if (net->RTO == 0) {
2115                         to_ticks = MSEC_TO_TICKS(stcb->asoc.initial_rto);
2116                 } else {
2117                         to_ticks = MSEC_TO_TICKS(net->RTO);
2118                 }
2119                 tmr = &net->rxt_timer;
2120                 break;
2121         case SCTP_TIMER_TYPE_NEWCOOKIE:
2122                 /*
2123                  * nothing needed but the endpoint here ususually about 60
2124                  * minutes.
2125                  */
2126                 tmr = &inp->sctp_ep.signature_change;
2127                 to_ticks = inp->sctp_ep.sctp_timeoutticks[SCTP_TIMER_SIGNATURE];
2128                 break;
2129         case SCTP_TIMER_TYPE_ASOCKILL:
2130                 if (stcb == NULL) {
2131                         return;
2132                 }
2133                 tmr = &stcb->asoc.strreset_timer;
2134                 to_ticks = MSEC_TO_TICKS(SCTP_ASOC_KILL_TIMEOUT);
2135                 break;
2136         case SCTP_TIMER_TYPE_INPKILL:
2137                 /*
2138                  * The inp is setup to die. We re-use the signature_chage
2139                  * timer since that has stopped and we are in the GONE
2140                  * state.
2141                  */
2142                 tmr = &inp->sctp_ep.signature_change;
2143                 to_ticks = MSEC_TO_TICKS(SCTP_INP_KILL_TIMEOUT);
2144                 break;
2145         case SCTP_TIMER_TYPE_PATHMTURAISE:
2146                 /*
2147                  * Here we use the value found in the EP for PMTU ususually
2148                  * about 10 minutes.
2149                  */
2150                 if ((stcb == NULL) || (net == NULL)) {
2151                         return;
2152                 }
2153                 if (net->dest_state & SCTP_ADDR_NO_PMTUD) {
2154                         return;
2155                 }
2156                 to_ticks = inp->sctp_ep.sctp_timeoutticks[SCTP_TIMER_PMTU];
2157                 tmr = &net->pmtu_timer;
2158                 break;
2159         case SCTP_TIMER_TYPE_SHUTDOWNACK:
2160                 /* Here we use the RTO of the destination */
2161                 if ((stcb == NULL) || (net == NULL)) {
2162                         return;
2163                 }
2164                 if (net->RTO == 0) {
2165                         to_ticks = MSEC_TO_TICKS(stcb->asoc.initial_rto);
2166                 } else {
2167                         to_ticks = MSEC_TO_TICKS(net->RTO);
2168                 }
2169                 tmr = &net->rxt_timer;
2170                 break;
2171         case SCTP_TIMER_TYPE_SHUTDOWNGUARD:
2172                 /*
2173                  * Here we use the endpoints shutdown guard timer usually
2174                  * about 3 minutes.
2175                  */
2176                 if (stcb == NULL) {
2177                         return;
2178                 }
2179                 if (inp->sctp_ep.sctp_timeoutticks[SCTP_TIMER_MAXSHUTDOWN] == 0) {
2180                         to_ticks = 5 * MSEC_TO_TICKS(stcb->asoc.maxrto);
2181                 } else {
2182                         to_ticks = inp->sctp_ep.sctp_timeoutticks[SCTP_TIMER_MAXSHUTDOWN];
2183                 }
2184                 tmr = &stcb->asoc.shut_guard_timer;
2185                 break;
2186         case SCTP_TIMER_TYPE_STRRESET:
2187                 /*
2188                  * Here the timer comes from the stcb but its value is from
2189                  * the net's RTO.
2190                  */
2191                 if ((stcb == NULL) || (net == NULL)) {
2192                         return;
2193                 }
2194                 if (net->RTO == 0) {
2195                         to_ticks = MSEC_TO_TICKS(stcb->asoc.initial_rto);
2196                 } else {
2197                         to_ticks = MSEC_TO_TICKS(net->RTO);
2198                 }
2199                 tmr = &stcb->asoc.strreset_timer;
2200                 break;
2201         case SCTP_TIMER_TYPE_ASCONF:
2202                 /*
2203                  * Here the timer comes from the stcb but its value is from
2204                  * the net's RTO.
2205                  */
2206                 if ((stcb == NULL) || (net == NULL)) {
2207                         return;
2208                 }
2209                 if (net->RTO == 0) {
2210                         to_ticks = MSEC_TO_TICKS(stcb->asoc.initial_rto);
2211                 } else {
2212                         to_ticks = MSEC_TO_TICKS(net->RTO);
2213                 }
2214                 tmr = &stcb->asoc.asconf_timer;
2215                 break;
2216         case SCTP_TIMER_TYPE_PRIM_DELETED:
2217                 if ((stcb == NULL) || (net != NULL)) {
2218                         return;
2219                 }
2220                 to_ticks = MSEC_TO_TICKS(stcb->asoc.initial_rto);
2221                 tmr = &stcb->asoc.delete_prim_timer;
2222                 break;
2223         case SCTP_TIMER_TYPE_AUTOCLOSE:
2224                 if (stcb == NULL) {
2225                         return;
2226                 }
2227                 if (stcb->asoc.sctp_autoclose_ticks == 0) {
2228                         /*
2229                          * Really an error since stcb is NOT set to
2230                          * autoclose
2231                          */
2232                         return;
2233                 }
2234                 to_ticks = stcb->asoc.sctp_autoclose_ticks;
2235                 tmr = &stcb->asoc.autoclose_timer;
2236                 break;
2237         default:
2238                 SCTPDBG(SCTP_DEBUG_TIMER1, "%s: Unknown timer type %d\n",
2239                     __func__, t_type);
2240                 return;
2241                 break;
2242         }
2243         if ((to_ticks <= 0) || (tmr == NULL)) {
2244                 SCTPDBG(SCTP_DEBUG_TIMER1, "%s: %d:software error to_ticks:%d tmr:%p not set ??\n",
2245                     __func__, t_type, to_ticks, (void *)tmr);
2246                 return;
2247         }
2248         if (SCTP_OS_TIMER_PENDING(&tmr->timer)) {
2249                 /*
2250                  * we do NOT allow you to have it already running. if it is
2251                  * we leave the current one up unchanged
2252                  */
2253                 return;
2254         }
2255         /* At this point we can proceed */
2256         if (t_type == SCTP_TIMER_TYPE_SEND) {
2257                 stcb->asoc.num_send_timers_up++;
2258         }
2259         tmr->stopped_from = 0;
2260         tmr->type = t_type;
2261         tmr->ep = (void *)inp;
2262         tmr->tcb = (void *)stcb;
2263         tmr->net = (void *)net;
2264         tmr->self = (void *)tmr;
2265         tmr->vnet = (void *)curvnet;
2266         tmr->ticks = sctp_get_tick_count();
2267         (void)SCTP_OS_TIMER_START(&tmr->timer, to_ticks, sctp_timeout_handler, tmr);
2268         return;
2269 }
2270
2271 void
2272 sctp_timer_stop(int t_type, struct sctp_inpcb *inp, struct sctp_tcb *stcb,
2273     struct sctp_nets *net, uint32_t from)
2274 {
2275         struct sctp_timer *tmr;
2276
2277         if ((t_type != SCTP_TIMER_TYPE_ADDR_WQ) &&
2278             (inp == NULL))
2279                 return;
2280
2281         tmr = NULL;
2282         if (stcb) {
2283                 SCTP_TCB_LOCK_ASSERT(stcb);
2284         }
2285         switch (t_type) {
2286         case SCTP_TIMER_TYPE_ADDR_WQ:
2287                 tmr = &SCTP_BASE_INFO(addr_wq_timer);
2288                 break;
2289         case SCTP_TIMER_TYPE_SEND:
2290                 if ((stcb == NULL) || (net == NULL)) {
2291                         return;
2292                 }
2293                 tmr = &net->rxt_timer;
2294                 break;
2295         case SCTP_TIMER_TYPE_INIT:
2296                 if ((stcb == NULL) || (net == NULL)) {
2297                         return;
2298                 }
2299                 tmr = &net->rxt_timer;
2300                 break;
2301         case SCTP_TIMER_TYPE_RECV:
2302                 if (stcb == NULL) {
2303                         return;
2304                 }
2305                 tmr = &stcb->asoc.dack_timer;
2306                 break;
2307         case SCTP_TIMER_TYPE_SHUTDOWN:
2308                 if ((stcb == NULL) || (net == NULL)) {
2309                         return;
2310                 }
2311                 tmr = &net->rxt_timer;
2312                 break;
2313         case SCTP_TIMER_TYPE_HEARTBEAT:
2314                 if ((stcb == NULL) || (net == NULL)) {
2315                         return;
2316                 }
2317                 tmr = &net->hb_timer;
2318                 break;
2319         case SCTP_TIMER_TYPE_COOKIE:
2320                 if ((stcb == NULL) || (net == NULL)) {
2321                         return;
2322                 }
2323                 tmr = &net->rxt_timer;
2324                 break;
2325         case SCTP_TIMER_TYPE_NEWCOOKIE:
2326                 /* nothing needed but the endpoint here */
2327                 tmr = &inp->sctp_ep.signature_change;
2328                 /*
2329                  * We re-use the newcookie timer for the INP kill timer. We
2330                  * must assure that we do not kill it by accident.
2331                  */
2332                 break;
2333         case SCTP_TIMER_TYPE_ASOCKILL:
2334                 /*
2335                  * Stop the asoc kill timer.
2336                  */
2337                 if (stcb == NULL) {
2338                         return;
2339                 }
2340                 tmr = &stcb->asoc.strreset_timer;
2341                 break;
2342
2343         case SCTP_TIMER_TYPE_INPKILL:
2344                 /*
2345                  * The inp is setup to die. We re-use the signature_chage
2346                  * timer since that has stopped and we are in the GONE
2347                  * state.
2348                  */
2349                 tmr = &inp->sctp_ep.signature_change;
2350                 break;
2351         case SCTP_TIMER_TYPE_PATHMTURAISE:
2352                 if ((stcb == NULL) || (net == NULL)) {
2353                         return;
2354                 }
2355                 tmr = &net->pmtu_timer;
2356                 break;
2357         case SCTP_TIMER_TYPE_SHUTDOWNACK:
2358                 if ((stcb == NULL) || (net == NULL)) {
2359                         return;
2360                 }
2361                 tmr = &net->rxt_timer;
2362                 break;
2363         case SCTP_TIMER_TYPE_SHUTDOWNGUARD:
2364                 if (stcb == NULL) {
2365                         return;
2366                 }
2367                 tmr = &stcb->asoc.shut_guard_timer;
2368                 break;
2369         case SCTP_TIMER_TYPE_STRRESET:
2370                 if (stcb == NULL) {
2371                         return;
2372                 }
2373                 tmr = &stcb->asoc.strreset_timer;
2374                 break;
2375         case SCTP_TIMER_TYPE_ASCONF:
2376                 if (stcb == NULL) {
2377                         return;
2378                 }
2379                 tmr = &stcb->asoc.asconf_timer;
2380                 break;
2381         case SCTP_TIMER_TYPE_PRIM_DELETED:
2382                 if (stcb == NULL) {
2383                         return;
2384                 }
2385                 tmr = &stcb->asoc.delete_prim_timer;
2386                 break;
2387         case SCTP_TIMER_TYPE_AUTOCLOSE:
2388                 if (stcb == NULL) {
2389                         return;
2390                 }
2391                 tmr = &stcb->asoc.autoclose_timer;
2392                 break;
2393         default:
2394                 SCTPDBG(SCTP_DEBUG_TIMER1, "%s: Unknown timer type %d\n",
2395                     __func__, t_type);
2396                 break;
2397         }
2398         if (tmr == NULL) {
2399                 return;
2400         }
2401         if ((tmr->type != t_type) && tmr->type) {
2402                 /*
2403                  * Ok we have a timer that is under joint use. Cookie timer
2404                  * per chance with the SEND timer. We therefore are NOT
2405                  * running the timer that the caller wants stopped.  So just
2406                  * return.
2407                  */
2408                 return;
2409         }
2410         if ((t_type == SCTP_TIMER_TYPE_SEND) && (stcb != NULL)) {
2411                 stcb->asoc.num_send_timers_up--;
2412                 if (stcb->asoc.num_send_timers_up < 0) {
2413                         stcb->asoc.num_send_timers_up = 0;
2414                 }
2415         }
2416         tmr->self = NULL;
2417         tmr->stopped_from = from;
2418         (void)SCTP_OS_TIMER_STOP(&tmr->timer);
2419         return;
2420 }
2421
2422 uint32_t
2423 sctp_calculate_len(struct mbuf *m)
2424 {
2425         uint32_t tlen = 0;
2426         struct mbuf *at;
2427
2428         at = m;
2429         while (at) {
2430                 tlen += SCTP_BUF_LEN(at);
2431                 at = SCTP_BUF_NEXT(at);
2432         }
2433         return (tlen);
2434 }
2435
2436 void
2437 sctp_mtu_size_reset(struct sctp_inpcb *inp,
2438     struct sctp_association *asoc, uint32_t mtu)
2439 {
2440         /*
2441          * Reset the P-MTU size on this association, this involves changing
2442          * the asoc MTU, going through ANY chunk+overhead larger than mtu to
2443          * allow the DF flag to be cleared.
2444          */
2445         struct sctp_tmit_chunk *chk;
2446         unsigned int eff_mtu, ovh;
2447
2448         asoc->smallest_mtu = mtu;
2449         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
2450                 ovh = SCTP_MIN_OVERHEAD;
2451         } else {
2452                 ovh = SCTP_MIN_V4_OVERHEAD;
2453         }
2454         eff_mtu = mtu - ovh;
2455         TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
2456                 if (chk->send_size > eff_mtu) {
2457                         chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;
2458                 }
2459         }
2460         TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
2461                 if (chk->send_size > eff_mtu) {
2462                         chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;
2463                 }
2464         }
2465 }
2466
2467
2468 /*
2469  * given an association and starting time of the current RTT period return
2470  * RTO in number of msecs net should point to the current network
2471  */
2472
2473 uint32_t
2474 sctp_calculate_rto(struct sctp_tcb *stcb,
2475     struct sctp_association *asoc,
2476     struct sctp_nets *net,
2477     struct timeval *old,
2478     int rtt_from_sack)
2479 {
2480         /*-
2481          * given an association and the starting time of the current RTT
2482          * period (in value1/value2) return RTO in number of msecs.
2483          */
2484         int32_t rtt;            /* RTT in ms */
2485         uint32_t new_rto;
2486         int first_measure = 0;
2487         struct timeval now;
2488
2489         /************************/
2490         /* 1. calculate new RTT */
2491         /************************/
2492         /* get the current time */
2493         if (stcb->asoc.use_precise_time) {
2494                 (void)SCTP_GETPTIME_TIMEVAL(&now);
2495         } else {
2496                 (void)SCTP_GETTIME_TIMEVAL(&now);
2497         }
2498         timevalsub(&now, old);
2499         /* store the current RTT in us */
2500         net->rtt = (uint64_t)1000000 * (uint64_t)now.tv_sec +
2501             (uint64_t)now.tv_usec;
2502         /* compute rtt in ms */
2503         rtt = (int32_t)(net->rtt / 1000);
2504         if ((asoc->cc_functions.sctp_rtt_calculated) && (rtt_from_sack == SCTP_RTT_FROM_DATA)) {
2505                 /*
2506                  * Tell the CC module that a new update has just occurred
2507                  * from a sack
2508                  */
2509                 (*asoc->cc_functions.sctp_rtt_calculated) (stcb, net, &now);
2510         }
2511         /*
2512          * Do we need to determine the lan? We do this only on sacks i.e.
2513          * RTT being determined from data not non-data (HB/INIT->INITACK).
2514          */
2515         if ((rtt_from_sack == SCTP_RTT_FROM_DATA) &&
2516             (net->lan_type == SCTP_LAN_UNKNOWN)) {
2517                 if (net->rtt > SCTP_LOCAL_LAN_RTT) {
2518                         net->lan_type = SCTP_LAN_INTERNET;
2519                 } else {
2520                         net->lan_type = SCTP_LAN_LOCAL;
2521                 }
2522         }
2523
2524         /***************************/
2525         /* 2. update RTTVAR & SRTT */
2526         /***************************/
2527         /*-
2528          * Compute the scaled average lastsa and the
2529          * scaled variance lastsv as described in van Jacobson
2530          * Paper "Congestion Avoidance and Control", Annex A.
2531          *
2532          * (net->lastsa >> SCTP_RTT_SHIFT) is the srtt
2533          * (net->lastsa >> SCTP_RTT_VAR_SHIFT) is the rttvar
2534          */
2535         if (net->RTO_measured) {
2536                 rtt -= (net->lastsa >> SCTP_RTT_SHIFT);
2537                 net->lastsa += rtt;
2538                 if (rtt < 0) {
2539                         rtt = -rtt;
2540                 }
2541                 rtt -= (net->lastsv >> SCTP_RTT_VAR_SHIFT);
2542                 net->lastsv += rtt;
2543                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_RTTVAR_LOGGING_ENABLE) {
2544                         rto_logging(net, SCTP_LOG_RTTVAR);
2545                 }
2546         } else {
2547                 /* First RTO measurment */
2548                 net->RTO_measured = 1;
2549                 first_measure = 1;
2550                 net->lastsa = rtt << SCTP_RTT_SHIFT;
2551                 net->lastsv = (rtt / 2) << SCTP_RTT_VAR_SHIFT;
2552                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_RTTVAR_LOGGING_ENABLE) {
2553                         rto_logging(net, SCTP_LOG_INITIAL_RTT);
2554                 }
2555         }
2556         if (net->lastsv == 0) {
2557                 net->lastsv = SCTP_CLOCK_GRANULARITY;
2558         }
2559         new_rto = (net->lastsa >> SCTP_RTT_SHIFT) + net->lastsv;
2560         if ((new_rto > SCTP_SAT_NETWORK_MIN) &&
2561             (stcb->asoc.sat_network_lockout == 0)) {
2562                 stcb->asoc.sat_network = 1;
2563         } else if ((!first_measure) && stcb->asoc.sat_network) {
2564                 stcb->asoc.sat_network = 0;
2565                 stcb->asoc.sat_network_lockout = 1;
2566         }
2567         /* bound it, per C6/C7 in Section 5.3.1 */
2568         if (new_rto < stcb->asoc.minrto) {
2569                 new_rto = stcb->asoc.minrto;
2570         }
2571         if (new_rto > stcb->asoc.maxrto) {
2572                 new_rto = stcb->asoc.maxrto;
2573         }
2574         /* we are now returning the RTO */
2575         return (new_rto);
2576 }
2577
2578 /*
2579  * return a pointer to a contiguous piece of data from the given mbuf chain
2580  * starting at 'off' for 'len' bytes.  If the desired piece spans more than
2581  * one mbuf, a copy is made at 'ptr'. caller must ensure that the buffer size
2582  * is >= 'len' returns NULL if there there isn't 'len' bytes in the chain.
2583  */
2584 caddr_t
2585 sctp_m_getptr(struct mbuf *m, int off, int len, uint8_t *in_ptr)
2586 {
2587         uint32_t count;
2588         uint8_t *ptr;
2589
2590         ptr = in_ptr;
2591         if ((off < 0) || (len <= 0))
2592                 return (NULL);
2593
2594         /* find the desired start location */
2595         while ((m != NULL) && (off > 0)) {
2596                 if (off < SCTP_BUF_LEN(m))
2597                         break;
2598                 off -= SCTP_BUF_LEN(m);
2599                 m = SCTP_BUF_NEXT(m);
2600         }
2601         if (m == NULL)
2602                 return (NULL);
2603
2604         /* is the current mbuf large enough (eg. contiguous)? */
2605         if ((SCTP_BUF_LEN(m) - off) >= len) {
2606                 return (mtod(m, caddr_t)+off);
2607         } else {
2608                 /* else, it spans more than one mbuf, so save a temp copy... */
2609                 while ((m != NULL) && (len > 0)) {
2610                         count = min(SCTP_BUF_LEN(m) - off, len);
2611                         memcpy(ptr, mtod(m, caddr_t)+off, count);
2612                         len -= count;
2613                         ptr += count;
2614                         off = 0;
2615                         m = SCTP_BUF_NEXT(m);
2616                 }
2617                 if ((m == NULL) && (len > 0))
2618                         return (NULL);
2619                 else
2620                         return ((caddr_t)in_ptr);
2621         }
2622 }
2623
2624
2625
2626 struct sctp_paramhdr *
2627 sctp_get_next_param(struct mbuf *m,
2628     int offset,
2629     struct sctp_paramhdr *pull,
2630     int pull_limit)
2631 {
2632         /* This just provides a typed signature to Peter's Pull routine */
2633         return ((struct sctp_paramhdr *)sctp_m_getptr(m, offset, pull_limit,
2634             (uint8_t *)pull));
2635 }
2636
2637
2638 struct mbuf *
2639 sctp_add_pad_tombuf(struct mbuf *m, int padlen)
2640 {
2641         struct mbuf *m_last;
2642         caddr_t dp;
2643
2644         if (padlen > 3) {
2645                 return (NULL);
2646         }
2647         if (padlen <= M_TRAILINGSPACE(m)) {
2648                 /*
2649                  * The easy way. We hope the majority of the time we hit
2650                  * here :)
2651                  */
2652                 m_last = m;
2653         } else {
2654                 /* Hard way we must grow the mbuf chain */
2655                 m_last = sctp_get_mbuf_for_msg(padlen, 0, M_NOWAIT, 1, MT_DATA);
2656                 if (m_last == NULL) {
2657                         return (NULL);
2658                 }
2659                 SCTP_BUF_LEN(m_last) = 0;
2660                 SCTP_BUF_NEXT(m_last) = NULL;
2661                 SCTP_BUF_NEXT(m) = m_last;
2662         }
2663         dp = mtod(m_last, caddr_t)+SCTP_BUF_LEN(m_last);
2664         SCTP_BUF_LEN(m_last) += padlen;
2665         memset(dp, 0, padlen);
2666         return (m_last);
2667 }
2668
2669 struct mbuf *
2670 sctp_pad_lastmbuf(struct mbuf *m, int padval, struct mbuf *last_mbuf)
2671 {
2672         /* find the last mbuf in chain and pad it */
2673         struct mbuf *m_at;
2674
2675         if (last_mbuf != NULL) {
2676                 return (sctp_add_pad_tombuf(last_mbuf, padval));
2677         } else {
2678                 for (m_at = m; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
2679                         if (SCTP_BUF_NEXT(m_at) == NULL) {
2680                                 return (sctp_add_pad_tombuf(m_at, padval));
2681                         }
2682                 }
2683         }
2684         return (NULL);
2685 }
2686
2687 static void
2688 sctp_notify_assoc_change(uint16_t state, struct sctp_tcb *stcb,
2689     uint16_t error, struct sctp_abort_chunk *abort, uint8_t from_peer, int so_locked
2690 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
2691     SCTP_UNUSED
2692 #endif
2693 )
2694 {
2695         struct mbuf *m_notify;
2696         struct sctp_assoc_change *sac;
2697         struct sctp_queued_to_read *control;
2698         unsigned int notif_len;
2699         uint16_t abort_len;
2700         unsigned int i;
2701 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2702         struct socket *so;
2703 #endif
2704
2705         if (stcb == NULL) {
2706                 return;
2707         }
2708         if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVASSOCEVNT)) {
2709                 notif_len = (unsigned int)sizeof(struct sctp_assoc_change);
2710                 if (abort != NULL) {
2711                         abort_len = ntohs(abort->ch.chunk_length);
2712                         /*
2713                          * Only SCTP_CHUNK_BUFFER_SIZE are guaranteed to be
2714                          * contiguous.
2715                          */
2716                         if (abort_len > SCTP_CHUNK_BUFFER_SIZE) {
2717                                 abort_len = SCTP_CHUNK_BUFFER_SIZE;
2718                         }
2719                 } else {
2720                         abort_len = 0;
2721                 }
2722                 if ((state == SCTP_COMM_UP) || (state == SCTP_RESTART)) {
2723                         notif_len += SCTP_ASSOC_SUPPORTS_MAX;
2724                 } else if ((state == SCTP_COMM_LOST) || (state == SCTP_CANT_STR_ASSOC)) {
2725                         notif_len += abort_len;
2726                 }
2727                 m_notify = sctp_get_mbuf_for_msg(notif_len, 0, M_NOWAIT, 1, MT_DATA);
2728                 if (m_notify == NULL) {
2729                         /* Retry with smaller value. */
2730                         notif_len = (unsigned int)sizeof(struct sctp_assoc_change);
2731                         m_notify = sctp_get_mbuf_for_msg(notif_len, 0, M_NOWAIT, 1, MT_DATA);
2732                         if (m_notify == NULL) {
2733                                 goto set_error;
2734                         }
2735                 }
2736                 SCTP_BUF_NEXT(m_notify) = NULL;
2737                 sac = mtod(m_notify, struct sctp_assoc_change *);
2738                 memset(sac, 0, notif_len);
2739                 sac->sac_type = SCTP_ASSOC_CHANGE;
2740                 sac->sac_flags = 0;
2741                 sac->sac_length = sizeof(struct sctp_assoc_change);
2742                 sac->sac_state = state;
2743                 sac->sac_error = error;
2744                 /* XXX verify these stream counts */
2745                 sac->sac_outbound_streams = stcb->asoc.streamoutcnt;
2746                 sac->sac_inbound_streams = stcb->asoc.streamincnt;
2747                 sac->sac_assoc_id = sctp_get_associd(stcb);
2748                 if (notif_len > sizeof(struct sctp_assoc_change)) {
2749                         if ((state == SCTP_COMM_UP) || (state == SCTP_RESTART)) {
2750                                 i = 0;
2751                                 if (stcb->asoc.prsctp_supported == 1) {
2752                                         sac->sac_info[i++] = SCTP_ASSOC_SUPPORTS_PR;
2753                                 }
2754                                 if (stcb->asoc.auth_supported == 1) {
2755                                         sac->sac_info[i++] = SCTP_ASSOC_SUPPORTS_AUTH;
2756                                 }
2757                                 if (stcb->asoc.asconf_supported == 1) {
2758                                         sac->sac_info[i++] = SCTP_ASSOC_SUPPORTS_ASCONF;
2759                                 }
2760                                 if (stcb->asoc.idata_supported == 1) {
2761                                         sac->sac_info[i++] = SCTP_ASSOC_SUPPORTS_INTERLEAVING;
2762                                 }
2763                                 sac->sac_info[i++] = SCTP_ASSOC_SUPPORTS_MULTIBUF;
2764                                 if (stcb->asoc.reconfig_supported == 1) {
2765                                         sac->sac_info[i++] = SCTP_ASSOC_SUPPORTS_RE_CONFIG;
2766                                 }
2767                                 sac->sac_length += i;
2768                         } else if ((state == SCTP_COMM_LOST) || (state == SCTP_CANT_STR_ASSOC)) {
2769                                 memcpy(sac->sac_info, abort, abort_len);
2770                                 sac->sac_length += abort_len;
2771                         }
2772                 }
2773                 SCTP_BUF_LEN(m_notify) = sac->sac_length;
2774                 control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
2775                     0, 0, stcb->asoc.context, 0, 0, 0,
2776                     m_notify);
2777                 if (control != NULL) {
2778                         control->length = SCTP_BUF_LEN(m_notify);
2779                         control->spec_flags = M_NOTIFICATION;
2780                         /* not that we need this */
2781                         control->tail_mbuf = m_notify;
2782                         sctp_add_to_readq(stcb->sctp_ep, stcb,
2783                             control,
2784                             &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD,
2785                             so_locked);
2786                 } else {
2787                         sctp_m_freem(m_notify);
2788                 }
2789         }
2790         /*
2791          * For 1-to-1 style sockets, we send up and error when an ABORT
2792          * comes in.
2793          */
2794 set_error:
2795         if (((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
2796             (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) &&
2797             ((state == SCTP_COMM_LOST) || (state == SCTP_CANT_STR_ASSOC))) {
2798                 SOCK_LOCK(stcb->sctp_socket);
2799                 if (from_peer) {
2800                         if (SCTP_GET_STATE(stcb) == SCTP_STATE_COOKIE_WAIT) {
2801                                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, ECONNREFUSED);
2802                                 stcb->sctp_socket->so_error = ECONNREFUSED;
2803                         } else {
2804                                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, ECONNRESET);
2805                                 stcb->sctp_socket->so_error = ECONNRESET;
2806                         }
2807                 } else {
2808                         if ((SCTP_GET_STATE(stcb) == SCTP_STATE_COOKIE_WAIT) ||
2809                             (SCTP_GET_STATE(stcb) == SCTP_STATE_COOKIE_ECHOED)) {
2810                                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, ETIMEDOUT);
2811                                 stcb->sctp_socket->so_error = ETIMEDOUT;
2812                         } else {
2813                                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, ECONNABORTED);
2814                                 stcb->sctp_socket->so_error = ECONNABORTED;
2815                         }
2816                 }
2817         }
2818         /* Wake ANY sleepers */
2819 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2820         so = SCTP_INP_SO(stcb->sctp_ep);
2821         if (!so_locked) {
2822                 atomic_add_int(&stcb->asoc.refcnt, 1);
2823                 SCTP_TCB_UNLOCK(stcb);
2824                 SCTP_SOCKET_LOCK(so, 1);
2825                 SCTP_TCB_LOCK(stcb);
2826                 atomic_subtract_int(&stcb->asoc.refcnt, 1);
2827                 if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
2828                         SCTP_SOCKET_UNLOCK(so, 1);
2829                         return;
2830                 }
2831         }
2832 #endif
2833         if (((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
2834             (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) &&
2835             ((state == SCTP_COMM_LOST) || (state == SCTP_CANT_STR_ASSOC))) {
2836                 socantrcvmore_locked(stcb->sctp_socket);
2837         }
2838         sorwakeup(stcb->sctp_socket);
2839         sowwakeup(stcb->sctp_socket);
2840 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2841         if (!so_locked) {
2842                 SCTP_SOCKET_UNLOCK(so, 1);
2843         }
2844 #endif
2845 }
2846
2847 static void
2848 sctp_notify_peer_addr_change(struct sctp_tcb *stcb, uint32_t state,
2849     struct sockaddr *sa, uint32_t error, int so_locked
2850 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
2851     SCTP_UNUSED
2852 #endif
2853 )
2854 {
2855         struct mbuf *m_notify;
2856         struct sctp_paddr_change *spc;
2857         struct sctp_queued_to_read *control;
2858
2859         if ((stcb == NULL) ||
2860             sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVPADDREVNT)) {
2861                 /* event not enabled */
2862                 return;
2863         }
2864         m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_paddr_change), 0, M_NOWAIT, 1, MT_DATA);
2865         if (m_notify == NULL)
2866                 return;
2867         SCTP_BUF_LEN(m_notify) = 0;
2868         spc = mtod(m_notify, struct sctp_paddr_change *);
2869         memset(spc, 0, sizeof(struct sctp_paddr_change));
2870         spc->spc_type = SCTP_PEER_ADDR_CHANGE;
2871         spc->spc_flags = 0;
2872         spc->spc_length = sizeof(struct sctp_paddr_change);
2873         switch (sa->sa_family) {
2874 #ifdef INET
2875         case AF_INET:
2876 #ifdef INET6
2877                 if (sctp_is_feature_on(stcb->sctp_ep, SCTP_PCB_FLAGS_NEEDS_MAPPED_V4)) {
2878                         in6_sin_2_v4mapsin6((struct sockaddr_in *)sa,
2879                             (struct sockaddr_in6 *)&spc->spc_aaddr);
2880                 } else {
2881                         memcpy(&spc->spc_aaddr, sa, sizeof(struct sockaddr_in));
2882                 }
2883 #else
2884                 memcpy(&spc->spc_aaddr, sa, sizeof(struct sockaddr_in));
2885 #endif
2886                 break;
2887 #endif
2888 #ifdef INET6
2889         case AF_INET6:
2890                 {
2891                         struct sockaddr_in6 *sin6;
2892
2893                         memcpy(&spc->spc_aaddr, sa, sizeof(struct sockaddr_in6));
2894
2895                         sin6 = (struct sockaddr_in6 *)&spc->spc_aaddr;
2896                         if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr)) {
2897                                 if (sin6->sin6_scope_id == 0) {
2898                                         /* recover scope_id for user */
2899                                         (void)sa6_recoverscope(sin6);
2900                                 } else {
2901                                         /* clear embedded scope_id for user */
2902                                         in6_clearscope(&sin6->sin6_addr);
2903                                 }
2904                         }
2905                         break;
2906                 }
2907 #endif
2908         default:
2909                 /* TSNH */
2910                 break;
2911         }
2912         spc->spc_state = state;
2913         spc->spc_error = error;
2914         spc->spc_assoc_id = sctp_get_associd(stcb);
2915
2916         SCTP_BUF_LEN(m_notify) = sizeof(struct sctp_paddr_change);
2917         SCTP_BUF_NEXT(m_notify) = NULL;
2918
2919         /* append to socket */
2920         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
2921             0, 0, stcb->asoc.context, 0, 0, 0,
2922             m_notify);
2923         if (control == NULL) {
2924                 /* no memory */
2925                 sctp_m_freem(m_notify);
2926                 return;
2927         }
2928         control->length = SCTP_BUF_LEN(m_notify);
2929         control->spec_flags = M_NOTIFICATION;
2930         /* not that we need this */
2931         control->tail_mbuf = m_notify;
2932         sctp_add_to_readq(stcb->sctp_ep, stcb,
2933             control,
2934             &stcb->sctp_socket->so_rcv, 1,
2935             SCTP_READ_LOCK_NOT_HELD,
2936             so_locked);
2937 }
2938
2939
2940 static void
2941 sctp_notify_send_failed(struct sctp_tcb *stcb, uint8_t sent, uint32_t error,
2942     struct sctp_tmit_chunk *chk, int so_locked
2943 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
2944     SCTP_UNUSED
2945 #endif
2946 )
2947 {
2948         struct mbuf *m_notify;
2949         struct sctp_send_failed *ssf;
2950         struct sctp_send_failed_event *ssfe;
2951         struct sctp_queued_to_read *control;
2952         struct sctp_chunkhdr *chkhdr;
2953         int notifhdr_len, chk_len, chkhdr_len, padding_len, payload_len;
2954
2955         if ((stcb == NULL) ||
2956             (sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVSENDFAILEVNT) &&
2957             sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVNSENDFAILEVNT))) {
2958                 /* event not enabled */
2959                 return;
2960         }
2961
2962         if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVNSENDFAILEVNT)) {
2963                 notifhdr_len = sizeof(struct sctp_send_failed_event);
2964         } else {
2965                 notifhdr_len = sizeof(struct sctp_send_failed);
2966         }
2967         m_notify = sctp_get_mbuf_for_msg(notifhdr_len, 0, M_NOWAIT, 1, MT_DATA);
2968         if (m_notify == NULL)
2969                 /* no space left */
2970                 return;
2971         SCTP_BUF_LEN(m_notify) = notifhdr_len;
2972         if (stcb->asoc.idata_supported) {
2973                 chkhdr_len = sizeof(struct sctp_idata_chunk);
2974         } else {
2975                 chkhdr_len = sizeof(struct sctp_data_chunk);
2976         }
2977         /* Use some defaults in case we can't access the chunk header */
2978         if (chk->send_size >= chkhdr_len) {
2979                 payload_len = chk->send_size - chkhdr_len;
2980         } else {
2981                 payload_len = 0;
2982         }
2983         padding_len = 0;
2984         if (chk->data != NULL) {
2985                 chkhdr = mtod(chk->data, struct sctp_chunkhdr *);
2986                 if (chkhdr != NULL) {
2987                         chk_len = ntohs(chkhdr->chunk_length);
2988                         if ((chk_len >= chkhdr_len) &&
2989                             (chk->send_size >= chk_len) &&
2990                             (chk->send_size - chk_len < 4)) {
2991                                 padding_len = chk->send_size - chk_len;
2992                                 payload_len = chk->send_size - chkhdr_len - padding_len;
2993                         }
2994                 }
2995         }
2996         if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVNSENDFAILEVNT)) {
2997                 ssfe = mtod(m_notify, struct sctp_send_failed_event *);
2998                 memset(ssfe, 0, notifhdr_len);
2999                 ssfe->ssfe_type = SCTP_SEND_FAILED_EVENT;
3000                 if (sent) {
3001                         ssfe->ssfe_flags = SCTP_DATA_SENT;
3002                 } else {
3003                         ssfe->ssfe_flags = SCTP_DATA_UNSENT;
3004                 }
3005                 ssfe->ssfe_length = (uint32_t)(notifhdr_len + payload_len);
3006                 ssfe->ssfe_error = error;
3007                 /* not exactly what the user sent in, but should be close :) */
3008                 ssfe->ssfe_info.snd_sid = chk->rec.data.sid;
3009                 ssfe->ssfe_info.snd_flags = chk->rec.data.rcv_flags;
3010                 ssfe->ssfe_info.snd_ppid = chk->rec.data.ppid;
3011                 ssfe->ssfe_info.snd_context = chk->rec.data.context;
3012                 ssfe->ssfe_info.snd_assoc_id = sctp_get_associd(stcb);
3013                 ssfe->ssfe_assoc_id = sctp_get_associd(stcb);
3014         } else {
3015                 ssf = mtod(m_notify, struct sctp_send_failed *);
3016                 memset(ssf, 0, notifhdr_len);
3017                 ssf->ssf_type = SCTP_SEND_FAILED;
3018                 if (sent) {
3019                         ssf->ssf_flags = SCTP_DATA_SENT;
3020                 } else {
3021                         ssf->ssf_flags = SCTP_DATA_UNSENT;
3022                 }
3023                 ssf->ssf_length = (uint32_t)(notifhdr_len + payload_len);
3024                 ssf->ssf_error = error;
3025                 /* not exactly what the user sent in, but should be close :) */
3026                 ssf->ssf_info.sinfo_stream = chk->rec.data.sid;
3027                 ssf->ssf_info.sinfo_ssn = (uint16_t)chk->rec.data.mid;
3028                 ssf->ssf_info.sinfo_flags = chk->rec.data.rcv_flags;
3029                 ssf->ssf_info.sinfo_ppid = chk->rec.data.ppid;
3030                 ssf->ssf_info.sinfo_context = chk->rec.data.context;
3031                 ssf->ssf_info.sinfo_assoc_id = sctp_get_associd(stcb);
3032                 ssf->ssf_assoc_id = sctp_get_associd(stcb);
3033         }
3034         if (chk->data != NULL) {
3035                 /* Trim off the sctp chunk header (it should be there) */
3036                 if (chk->send_size == chkhdr_len + payload_len + padding_len) {
3037                         m_adj(chk->data, chkhdr_len);
3038                         m_adj(chk->data, -padding_len);
3039                         sctp_mbuf_crush(chk->data);
3040                         chk->send_size -= (chkhdr_len + padding_len);
3041                 }
3042         }
3043         SCTP_BUF_NEXT(m_notify) = chk->data;
3044         /* Steal off the mbuf */
3045         chk->data = NULL;
3046         /*
3047          * For this case, we check the actual socket buffer, since the assoc
3048          * is going away we don't want to overfill the socket buffer for a
3049          * non-reader
3050          */
3051         if (sctp_sbspace_failedmsgs(&stcb->sctp_socket->so_rcv) < SCTP_BUF_LEN(m_notify)) {
3052                 sctp_m_freem(m_notify);
3053                 return;
3054         }
3055         /* append to socket */
3056         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
3057             0, 0, stcb->asoc.context, 0, 0, 0,
3058             m_notify);
3059         if (control == NULL) {
3060                 /* no memory */
3061                 sctp_m_freem(m_notify);
3062                 return;
3063         }
3064         control->length = SCTP_BUF_LEN(m_notify);
3065         control->spec_flags = M_NOTIFICATION;
3066         /* not that we need this */
3067         control->tail_mbuf = m_notify;
3068         sctp_add_to_readq(stcb->sctp_ep, stcb,
3069             control,
3070             &stcb->sctp_socket->so_rcv, 1,
3071             SCTP_READ_LOCK_NOT_HELD,
3072             so_locked);
3073 }
3074
3075
3076 static void
3077 sctp_notify_send_failed2(struct sctp_tcb *stcb, uint32_t error,
3078     struct sctp_stream_queue_pending *sp, int so_locked
3079 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
3080     SCTP_UNUSED
3081 #endif
3082 )
3083 {
3084         struct mbuf *m_notify;
3085         struct sctp_send_failed *ssf;
3086         struct sctp_send_failed_event *ssfe;
3087         struct sctp_queued_to_read *control;
3088         int notifhdr_len;
3089
3090         if ((stcb == NULL) ||
3091             (sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVSENDFAILEVNT) &&
3092             sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVNSENDFAILEVNT))) {
3093                 /* event not enabled */
3094                 return;
3095         }
3096         if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVNSENDFAILEVNT)) {
3097                 notifhdr_len = sizeof(struct sctp_send_failed_event);
3098         } else {
3099                 notifhdr_len = sizeof(struct sctp_send_failed);
3100         }
3101         m_notify = sctp_get_mbuf_for_msg(notifhdr_len, 0, M_NOWAIT, 1, MT_DATA);
3102         if (m_notify == NULL) {
3103                 /* no space left */
3104                 return;
3105         }
3106         SCTP_BUF_LEN(m_notify) = notifhdr_len;
3107         if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVNSENDFAILEVNT)) {
3108                 ssfe = mtod(m_notify, struct sctp_send_failed_event *);
3109                 memset(ssfe, 0, notifhdr_len);
3110                 ssfe->ssfe_type = SCTP_SEND_FAILED_EVENT;
3111                 ssfe->ssfe_flags = SCTP_DATA_UNSENT;
3112                 ssfe->ssfe_length = (uint32_t)(notifhdr_len + sp->length);
3113                 ssfe->ssfe_error = error;
3114                 /* not exactly what the user sent in, but should be close :) */
3115                 ssfe->ssfe_info.snd_sid = sp->sid;
3116                 if (sp->some_taken) {
3117                         ssfe->ssfe_info.snd_flags = SCTP_DATA_LAST_FRAG;
3118                 } else {
3119                         ssfe->ssfe_info.snd_flags = SCTP_DATA_NOT_FRAG;
3120                 }
3121                 ssfe->ssfe_info.snd_ppid = sp->ppid;
3122                 ssfe->ssfe_info.snd_context = sp->context;
3123                 ssfe->ssfe_info.snd_assoc_id = sctp_get_associd(stcb);
3124                 ssfe->ssfe_assoc_id = sctp_get_associd(stcb);
3125         } else {
3126                 ssf = mtod(m_notify, struct sctp_send_failed *);
3127                 memset(ssf, 0, notifhdr_len);
3128                 ssf->ssf_type = SCTP_SEND_FAILED;
3129                 ssf->ssf_flags = SCTP_DATA_UNSENT;
3130                 ssf->ssf_length = (uint32_t)(notifhdr_len + sp->length);
3131                 ssf->ssf_error = error;
3132                 /* not exactly what the user sent in, but should be close :) */
3133                 ssf->ssf_info.sinfo_stream = sp->sid;
3134                 ssf->ssf_info.sinfo_ssn = 0;
3135                 if (sp->some_taken) {
3136                         ssf->ssf_info.sinfo_flags = SCTP_DATA_LAST_FRAG;
3137                 } else {
3138                         ssf->ssf_info.sinfo_flags = SCTP_DATA_NOT_FRAG;
3139                 }
3140                 ssf->ssf_info.sinfo_ppid = sp->ppid;
3141                 ssf->ssf_info.sinfo_context = sp->context;
3142                 ssf->ssf_info.sinfo_assoc_id = sctp_get_associd(stcb);
3143                 ssf->ssf_assoc_id = sctp_get_associd(stcb);
3144         }
3145         SCTP_BUF_NEXT(m_notify) = sp->data;
3146
3147         /* Steal off the mbuf */
3148         sp->data = NULL;
3149         /*
3150          * For this case, we check the actual socket buffer, since the assoc
3151          * is going away we don't want to overfill the socket buffer for a
3152          * non-reader
3153          */
3154         if (sctp_sbspace_failedmsgs(&stcb->sctp_socket->so_rcv) < SCTP_BUF_LEN(m_notify)) {
3155                 sctp_m_freem(m_notify);
3156                 return;
3157         }
3158         /* append to socket */
3159         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
3160             0, 0, stcb->asoc.context, 0, 0, 0,
3161             m_notify);
3162         if (control == NULL) {
3163                 /* no memory */
3164                 sctp_m_freem(m_notify);
3165                 return;
3166         }
3167         control->length = SCTP_BUF_LEN(m_notify);
3168         control->spec_flags = M_NOTIFICATION;
3169         /* not that we need this */
3170         control->tail_mbuf = m_notify;
3171         sctp_add_to_readq(stcb->sctp_ep, stcb,
3172             control,
3173             &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, so_locked);
3174 }
3175
3176
3177
3178 static void
3179 sctp_notify_adaptation_layer(struct sctp_tcb *stcb)
3180 {
3181         struct mbuf *m_notify;
3182         struct sctp_adaptation_event *sai;
3183         struct sctp_queued_to_read *control;
3184
3185         if ((stcb == NULL) ||
3186             sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_ADAPTATIONEVNT)) {
3187                 /* event not enabled */
3188                 return;
3189         }
3190
3191         m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_adaption_event), 0, M_NOWAIT, 1, MT_DATA);
3192         if (m_notify == NULL)
3193                 /* no space left */
3194                 return;
3195         SCTP_BUF_LEN(m_notify) = 0;
3196         sai = mtod(m_notify, struct sctp_adaptation_event *);
3197         memset(sai, 0, sizeof(struct sctp_adaptation_event));
3198         sai->sai_type = SCTP_ADAPTATION_INDICATION;
3199         sai->sai_flags = 0;
3200         sai->sai_length = sizeof(struct sctp_adaptation_event);
3201         sai->sai_adaptation_ind = stcb->asoc.peers_adaptation;
3202         sai->sai_assoc_id = sctp_get_associd(stcb);
3203
3204         SCTP_BUF_LEN(m_notify) = sizeof(struct sctp_adaptation_event);
3205         SCTP_BUF_NEXT(m_notify) = NULL;
3206
3207         /* append to socket */
3208         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
3209             0, 0, stcb->asoc.context, 0, 0, 0,
3210             m_notify);
3211         if (control == NULL) {
3212                 /* no memory */
3213                 sctp_m_freem(m_notify);
3214                 return;
3215         }
3216         control->length = SCTP_BUF_LEN(m_notify);
3217         control->spec_flags = M_NOTIFICATION;
3218         /* not that we need this */
3219         control->tail_mbuf = m_notify;
3220         sctp_add_to_readq(stcb->sctp_ep, stcb,
3221             control,
3222             &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, SCTP_SO_NOT_LOCKED);
3223 }
3224
3225 /* This always must be called with the read-queue LOCKED in the INP */
3226 static void
3227 sctp_notify_partial_delivery_indication(struct sctp_tcb *stcb, uint32_t error,
3228     uint32_t val, int so_locked
3229 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
3230     SCTP_UNUSED
3231 #endif
3232 )
3233 {
3234         struct mbuf *m_notify;
3235         struct sctp_pdapi_event *pdapi;
3236         struct sctp_queued_to_read *control;
3237         struct sockbuf *sb;
3238
3239         if ((stcb == NULL) ||
3240             sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_PDAPIEVNT)) {
3241                 /* event not enabled */
3242                 return;
3243         }
3244         if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_CANT_READ) {
3245                 return;
3246         }
3247
3248         m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_pdapi_event), 0, M_NOWAIT, 1, MT_DATA);
3249         if (m_notify == NULL)
3250                 /* no space left */
3251                 return;
3252         SCTP_BUF_LEN(m_notify) = 0;
3253         pdapi = mtod(m_notify, struct sctp_pdapi_event *);
3254         memset(pdapi, 0, sizeof(struct sctp_pdapi_event));
3255         pdapi->pdapi_type = SCTP_PARTIAL_DELIVERY_EVENT;
3256         pdapi->pdapi_flags = 0;
3257         pdapi->pdapi_length = sizeof(struct sctp_pdapi_event);
3258         pdapi->pdapi_indication = error;
3259         pdapi->pdapi_stream = (val >> 16);
3260         pdapi->pdapi_seq = (val & 0x0000ffff);
3261         pdapi->pdapi_assoc_id = sctp_get_associd(stcb);
3262
3263         SCTP_BUF_LEN(m_notify) = sizeof(struct sctp_pdapi_event);
3264         SCTP_BUF_NEXT(m_notify) = NULL;
3265         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
3266             0, 0, stcb->asoc.context, 0, 0, 0,
3267             m_notify);
3268         if (control == NULL) {
3269                 /* no memory */
3270                 sctp_m_freem(m_notify);
3271                 return;
3272         }
3273         control->length = SCTP_BUF_LEN(m_notify);
3274         control->spec_flags = M_NOTIFICATION;
3275         /* not that we need this */
3276         control->tail_mbuf = m_notify;
3277         sb = &stcb->sctp_socket->so_rcv;
3278         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
3279                 sctp_sblog(sb, control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBALLOC, SCTP_BUF_LEN(m_notify));
3280         }
3281         sctp_sballoc(stcb, sb, m_notify);
3282         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
3283                 sctp_sblog(sb, control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBRESULT, 0);
3284         }
3285         control->end_added = 1;
3286         if (stcb->asoc.control_pdapi)
3287                 TAILQ_INSERT_AFTER(&stcb->sctp_ep->read_queue, stcb->asoc.control_pdapi, control, next);
3288         else {
3289                 /* we really should not see this case */
3290                 TAILQ_INSERT_TAIL(&stcb->sctp_ep->read_queue, control, next);
3291         }
3292         if (stcb->sctp_ep && stcb->sctp_socket) {
3293                 /* This should always be the case */
3294 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3295                 struct socket *so;
3296
3297                 so = SCTP_INP_SO(stcb->sctp_ep);
3298                 if (!so_locked) {
3299                         atomic_add_int(&stcb->asoc.refcnt, 1);
3300                         SCTP_TCB_UNLOCK(stcb);
3301                         SCTP_SOCKET_LOCK(so, 1);
3302                         SCTP_TCB_LOCK(stcb);
3303                         atomic_subtract_int(&stcb->asoc.refcnt, 1);
3304                         if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
3305                                 SCTP_SOCKET_UNLOCK(so, 1);
3306                                 return;
3307                         }
3308                 }
3309 #endif
3310                 sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
3311 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3312                 if (!so_locked) {
3313                         SCTP_SOCKET_UNLOCK(so, 1);
3314                 }
3315 #endif
3316         }
3317 }
3318
3319 static void
3320 sctp_notify_shutdown_event(struct sctp_tcb *stcb)
3321 {
3322         struct mbuf *m_notify;
3323         struct sctp_shutdown_event *sse;
3324         struct sctp_queued_to_read *control;
3325
3326         /*
3327          * For TCP model AND UDP connected sockets we will send an error up
3328          * when an SHUTDOWN completes
3329          */
3330         if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
3331             (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
3332                 /* mark socket closed for read/write and wakeup! */
3333 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3334                 struct socket *so;
3335
3336                 so = SCTP_INP_SO(stcb->sctp_ep);
3337                 atomic_add_int(&stcb->asoc.refcnt, 1);
3338                 SCTP_TCB_UNLOCK(stcb);
3339                 SCTP_SOCKET_LOCK(so, 1);
3340                 SCTP_TCB_LOCK(stcb);
3341                 atomic_subtract_int(&stcb->asoc.refcnt, 1);
3342                 if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
3343                         SCTP_SOCKET_UNLOCK(so, 1);
3344                         return;
3345                 }
3346 #endif
3347                 socantsendmore(stcb->sctp_socket);
3348 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3349                 SCTP_SOCKET_UNLOCK(so, 1);
3350 #endif
3351         }
3352         if (sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVSHUTDOWNEVNT)) {
3353                 /* event not enabled */
3354                 return;
3355         }
3356
3357         m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_shutdown_event), 0, M_NOWAIT, 1, MT_DATA);
3358         if (m_notify == NULL)
3359                 /* no space left */
3360                 return;
3361         sse = mtod(m_notify, struct sctp_shutdown_event *);
3362         memset(sse, 0, sizeof(struct sctp_shutdown_event));
3363         sse->sse_type = SCTP_SHUTDOWN_EVENT;
3364         sse->sse_flags = 0;
3365         sse->sse_length = sizeof(struct sctp_shutdown_event);
3366         sse->sse_assoc_id = sctp_get_associd(stcb);
3367
3368         SCTP_BUF_LEN(m_notify) = sizeof(struct sctp_shutdown_event);
3369         SCTP_BUF_NEXT(m_notify) = NULL;
3370
3371         /* append to socket */
3372         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
3373             0, 0, stcb->asoc.context, 0, 0, 0,
3374             m_notify);
3375         if (control == NULL) {
3376                 /* no memory */
3377                 sctp_m_freem(m_notify);
3378                 return;
3379         }
3380         control->length = SCTP_BUF_LEN(m_notify);
3381         control->spec_flags = M_NOTIFICATION;
3382         /* not that we need this */
3383         control->tail_mbuf = m_notify;
3384         sctp_add_to_readq(stcb->sctp_ep, stcb,
3385             control,
3386             &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, SCTP_SO_NOT_LOCKED);
3387 }
3388
3389 static void
3390 sctp_notify_sender_dry_event(struct sctp_tcb *stcb,
3391     int so_locked
3392 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
3393     SCTP_UNUSED
3394 #endif
3395 )
3396 {
3397         struct mbuf *m_notify;
3398         struct sctp_sender_dry_event *event;
3399         struct sctp_queued_to_read *control;
3400
3401         if ((stcb == NULL) ||
3402             sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DRYEVNT)) {
3403                 /* event not enabled */
3404                 return;
3405         }
3406
3407         m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_sender_dry_event), 0, M_NOWAIT, 1, MT_DATA);
3408         if (m_notify == NULL) {
3409                 /* no space left */
3410                 return;
3411         }
3412         SCTP_BUF_LEN(m_notify) = 0;
3413         event = mtod(m_notify, struct sctp_sender_dry_event *);
3414         memset(event, 0, sizeof(struct sctp_sender_dry_event));
3415         event->sender_dry_type = SCTP_SENDER_DRY_EVENT;
3416         event->sender_dry_flags = 0;
3417         event->sender_dry_length = sizeof(struct sctp_sender_dry_event);
3418         event->sender_dry_assoc_id = sctp_get_associd(stcb);
3419
3420         SCTP_BUF_LEN(m_notify) = sizeof(struct sctp_sender_dry_event);
3421         SCTP_BUF_NEXT(m_notify) = NULL;
3422
3423         /* append to socket */
3424         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
3425             0, 0, stcb->asoc.context, 0, 0, 0,
3426             m_notify);
3427         if (control == NULL) {
3428                 /* no memory */
3429                 sctp_m_freem(m_notify);
3430                 return;
3431         }
3432         control->length = SCTP_BUF_LEN(m_notify);
3433         control->spec_flags = M_NOTIFICATION;
3434         /* not that we need this */
3435         control->tail_mbuf = m_notify;
3436         sctp_add_to_readq(stcb->sctp_ep, stcb, control,
3437             &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, so_locked);
3438 }
3439
3440
3441 void
3442 sctp_notify_stream_reset_add(struct sctp_tcb *stcb, uint16_t numberin, uint16_t numberout, int flag)
3443 {
3444         struct mbuf *m_notify;
3445         struct sctp_queued_to_read *control;
3446         struct sctp_stream_change_event *stradd;
3447
3448         if ((stcb == NULL) ||
3449             (sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_STREAM_CHANGEEVNT))) {
3450                 /* event not enabled */
3451                 return;
3452         }
3453         if ((stcb->asoc.peer_req_out) && flag) {
3454                 /* Peer made the request, don't tell the local user */
3455                 stcb->asoc.peer_req_out = 0;
3456                 return;
3457         }
3458         stcb->asoc.peer_req_out = 0;
3459         m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_stream_change_event), 0, M_NOWAIT, 1, MT_DATA);
3460         if (m_notify == NULL)
3461                 /* no space left */
3462                 return;
3463         SCTP_BUF_LEN(m_notify) = 0;
3464         stradd = mtod(m_notify, struct sctp_stream_change_event *);
3465         memset(stradd, 0, sizeof(struct sctp_stream_change_event));
3466         stradd->strchange_type = SCTP_STREAM_CHANGE_EVENT;
3467         stradd->strchange_flags = flag;
3468         stradd->strchange_length = sizeof(struct sctp_stream_change_event);
3469         stradd->strchange_assoc_id = sctp_get_associd(stcb);
3470         stradd->strchange_instrms = numberin;
3471         stradd->strchange_outstrms = numberout;
3472         SCTP_BUF_LEN(m_notify) = sizeof(struct sctp_stream_change_event);
3473         SCTP_BUF_NEXT(m_notify) = NULL;
3474         if (sctp_sbspace(&stcb->asoc, &stcb->sctp_socket->so_rcv) < SCTP_BUF_LEN(m_notify)) {
3475                 /* no space */
3476                 sctp_m_freem(m_notify);
3477                 return;
3478         }
3479         /* append to socket */
3480         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
3481             0, 0, stcb->asoc.context, 0, 0, 0,
3482             m_notify);
3483         if (control == NULL) {
3484                 /* no memory */
3485                 sctp_m_freem(m_notify);
3486                 return;
3487         }
3488         control->length = SCTP_BUF_LEN(m_notify);
3489         control->spec_flags = M_NOTIFICATION;
3490         /* not that we need this */
3491         control->tail_mbuf = m_notify;
3492         sctp_add_to_readq(stcb->sctp_ep, stcb,
3493             control,
3494             &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, SCTP_SO_NOT_LOCKED);
3495 }
3496
3497 void
3498 sctp_notify_stream_reset_tsn(struct sctp_tcb *stcb, uint32_t sending_tsn, uint32_t recv_tsn, int flag)
3499 {
3500         struct mbuf *m_notify;
3501         struct sctp_queued_to_read *control;
3502         struct sctp_assoc_reset_event *strasoc;
3503
3504         if ((stcb == NULL) ||
3505             (sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_ASSOC_RESETEVNT))) {
3506                 /* event not enabled */
3507                 return;
3508         }
3509         m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_assoc_reset_event), 0, M_NOWAIT, 1, MT_DATA);
3510         if (m_notify == NULL)
3511                 /* no space left */
3512                 return;
3513         SCTP_BUF_LEN(m_notify) = 0;
3514         strasoc = mtod(m_notify, struct sctp_assoc_reset_event *);
3515         memset(strasoc, 0, sizeof(struct sctp_assoc_reset_event));
3516         strasoc->assocreset_type = SCTP_ASSOC_RESET_EVENT;
3517         strasoc->assocreset_flags = flag;
3518         strasoc->assocreset_length = sizeof(struct sctp_assoc_reset_event);
3519         strasoc->assocreset_assoc_id = sctp_get_associd(stcb);
3520         strasoc->assocreset_local_tsn = sending_tsn;
3521         strasoc->assocreset_remote_tsn = recv_tsn;
3522         SCTP_BUF_LEN(m_notify) = sizeof(struct sctp_assoc_reset_event);
3523         SCTP_BUF_NEXT(m_notify) = NULL;
3524         if (sctp_sbspace(&stcb->asoc, &stcb->sctp_socket->so_rcv) < SCTP_BUF_LEN(m_notify)) {
3525                 /* no space */
3526                 sctp_m_freem(m_notify);
3527                 return;
3528         }
3529         /* append to socket */
3530         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
3531             0, 0, stcb->asoc.context, 0, 0, 0,
3532             m_notify);
3533         if (control == NULL) {
3534                 /* no memory */
3535                 sctp_m_freem(m_notify);
3536                 return;
3537         }
3538         control->length = SCTP_BUF_LEN(m_notify);
3539         control->spec_flags = M_NOTIFICATION;
3540         /* not that we need this */
3541         control->tail_mbuf = m_notify;
3542         sctp_add_to_readq(stcb->sctp_ep, stcb,
3543             control,
3544             &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, SCTP_SO_NOT_LOCKED);
3545 }
3546
3547
3548
3549 static void
3550 sctp_notify_stream_reset(struct sctp_tcb *stcb,
3551     int number_entries, uint16_t *list, int flag)
3552 {
3553         struct mbuf *m_notify;
3554         struct sctp_queued_to_read *control;
3555         struct sctp_stream_reset_event *strreset;
3556         int len;
3557
3558         if ((stcb == NULL) ||
3559             (sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_STREAM_RESETEVNT))) {
3560                 /* event not enabled */
3561                 return;
3562         }
3563
3564         m_notify = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_NOWAIT, 1, MT_DATA);
3565         if (m_notify == NULL)
3566                 /* no space left */
3567                 return;
3568         SCTP_BUF_LEN(m_notify) = 0;
3569         len = sizeof(struct sctp_stream_reset_event) + (number_entries * sizeof(uint16_t));
3570         if (len > M_TRAILINGSPACE(m_notify)) {
3571                 /* never enough room */
3572                 sctp_m_freem(m_notify);
3573                 return;
3574         }
3575         strreset = mtod(m_notify, struct sctp_stream_reset_event *);
3576         memset(strreset, 0, len);
3577         strreset->strreset_type = SCTP_STREAM_RESET_EVENT;
3578         strreset->strreset_flags = flag;
3579         strreset->strreset_length = len;
3580         strreset->strreset_assoc_id = sctp_get_associd(stcb);
3581         if (number_entries) {
3582                 int i;
3583
3584                 for (i = 0; i < number_entries; i++) {
3585                         strreset->strreset_stream_list[i] = ntohs(list[i]);
3586                 }
3587         }
3588         SCTP_BUF_LEN(m_notify) = len;
3589         SCTP_BUF_NEXT(m_notify) = NULL;
3590         if (sctp_sbspace(&stcb->asoc, &stcb->sctp_socket->so_rcv) < SCTP_BUF_LEN(m_notify)) {
3591                 /* no space */
3592                 sctp_m_freem(m_notify);
3593                 return;
3594         }
3595         /* append to socket */
3596         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
3597             0, 0, stcb->asoc.context, 0, 0, 0,
3598             m_notify);
3599         if (control == NULL) {
3600                 /* no memory */
3601                 sctp_m_freem(m_notify);
3602                 return;
3603         }
3604         control->length = SCTP_BUF_LEN(m_notify);
3605         control->spec_flags = M_NOTIFICATION;
3606         /* not that we need this */
3607         control->tail_mbuf = m_notify;
3608         sctp_add_to_readq(stcb->sctp_ep, stcb,
3609             control,
3610             &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, SCTP_SO_NOT_LOCKED);
3611 }
3612
3613
3614 static void
3615 sctp_notify_remote_error(struct sctp_tcb *stcb, uint16_t error, struct sctp_error_chunk *chunk)
3616 {
3617         struct mbuf *m_notify;
3618         struct sctp_remote_error *sre;
3619         struct sctp_queued_to_read *control;
3620         unsigned int notif_len;
3621         uint16_t chunk_len;
3622
3623         if ((stcb == NULL) ||
3624             sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_RECVPEERERR)) {
3625                 return;
3626         }
3627         if (chunk != NULL) {
3628                 chunk_len = ntohs(chunk->ch.chunk_length);
3629                 /*
3630                  * Only SCTP_CHUNK_BUFFER_SIZE are guaranteed to be
3631                  * contiguous.
3632                  */
3633                 if (chunk_len > SCTP_CHUNK_BUFFER_SIZE) {
3634                         chunk_len = SCTP_CHUNK_BUFFER_SIZE;
3635                 }
3636         } else {
3637                 chunk_len = 0;
3638         }
3639         notif_len = (unsigned int)(sizeof(struct sctp_remote_error) + chunk_len);
3640         m_notify = sctp_get_mbuf_for_msg(notif_len, 0, M_NOWAIT, 1, MT_DATA);
3641         if (m_notify == NULL) {
3642                 /* Retry with smaller value. */
3643                 notif_len = (unsigned int)sizeof(struct sctp_remote_error);
3644                 m_notify = sctp_get_mbuf_for_msg(notif_len, 0, M_NOWAIT, 1, MT_DATA);
3645                 if (m_notify == NULL) {
3646                         return;
3647                 }
3648         }
3649         SCTP_BUF_NEXT(m_notify) = NULL;
3650         sre = mtod(m_notify, struct sctp_remote_error *);
3651         memset(sre, 0, notif_len);
3652         sre->sre_type = SCTP_REMOTE_ERROR;
3653         sre->sre_flags = 0;
3654         sre->sre_length = sizeof(struct sctp_remote_error);
3655         sre->sre_error = error;
3656         sre->sre_assoc_id = sctp_get_associd(stcb);
3657         if (notif_len > sizeof(struct sctp_remote_error)) {
3658                 memcpy(sre->sre_data, chunk, chunk_len);
3659                 sre->sre_length += chunk_len;
3660         }
3661         SCTP_BUF_LEN(m_notify) = sre->sre_length;
3662         control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
3663             0, 0, stcb->asoc.context, 0, 0, 0,
3664             m_notify);
3665         if (control != NULL) {
3666                 control->length = SCTP_BUF_LEN(m_notify);
3667                 control->spec_flags = M_NOTIFICATION;
3668                 /* not that we need this */
3669                 control->tail_mbuf = m_notify;
3670                 sctp_add_to_readq(stcb->sctp_ep, stcb,
3671                     control,
3672                     &stcb->sctp_socket->so_rcv, 1,
3673                     SCTP_READ_LOCK_NOT_HELD, SCTP_SO_NOT_LOCKED);
3674         } else {
3675                 sctp_m_freem(m_notify);
3676         }
3677 }
3678
3679
3680 void
3681 sctp_ulp_notify(uint32_t notification, struct sctp_tcb *stcb,
3682     uint32_t error, void *data, int so_locked
3683 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
3684     SCTP_UNUSED
3685 #endif
3686 )
3687 {
3688         if ((stcb == NULL) ||
3689             (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
3690             (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
3691             (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET)) {
3692                 /* If the socket is gone we are out of here */
3693                 return;
3694         }
3695         if (stcb->sctp_socket->so_rcv.sb_state & SBS_CANTRCVMORE) {
3696                 return;
3697         }
3698         if ((SCTP_GET_STATE(stcb) == SCTP_STATE_COOKIE_WAIT) ||
3699             (SCTP_GET_STATE(stcb) ==  SCTP_STATE_COOKIE_ECHOED)) {
3700                 if ((notification == SCTP_NOTIFY_INTERFACE_DOWN) ||
3701                     (notification == SCTP_NOTIFY_INTERFACE_UP) ||
3702                     (notification == SCTP_NOTIFY_INTERFACE_CONFIRMED)) {
3703                         /* Don't report these in front states */
3704                         return;
3705                 }
3706         }
3707         switch (notification) {
3708         case SCTP_NOTIFY_ASSOC_UP:
3709                 if (stcb->asoc.assoc_up_sent == 0) {
3710                         sctp_notify_assoc_change(SCTP_COMM_UP, stcb, error, NULL, 0, so_locked);
3711                         stcb->asoc.assoc_up_sent = 1;
3712                 }
3713                 if (stcb->asoc.adaptation_needed && (stcb->asoc.adaptation_sent == 0)) {
3714                         sctp_notify_adaptation_layer(stcb);
3715                 }
3716                 if (stcb->asoc.auth_supported == 0) {
3717                         sctp_ulp_notify(SCTP_NOTIFY_NO_PEER_AUTH, stcb, 0,
3718                             NULL, so_locked);
3719                 }
3720                 break;
3721         case SCTP_NOTIFY_ASSOC_DOWN:
3722                 sctp_notify_assoc_change(SCTP_SHUTDOWN_COMP, stcb, error, NULL, 0, so_locked);
3723                 break;
3724         case SCTP_NOTIFY_INTERFACE_DOWN:
3725                 {
3726                         struct sctp_nets *net;
3727
3728                         net = (struct sctp_nets *)data;
3729                         sctp_notify_peer_addr_change(stcb, SCTP_ADDR_UNREACHABLE,
3730                             (struct sockaddr *)&net->ro._l_addr, error, so_locked);
3731                         break;
3732                 }
3733         case SCTP_NOTIFY_INTERFACE_UP:
3734                 {
3735                         struct sctp_nets *net;
3736
3737                         net = (struct sctp_nets *)data;
3738                         sctp_notify_peer_addr_change(stcb, SCTP_ADDR_AVAILABLE,
3739                             (struct sockaddr *)&net->ro._l_addr, error, so_locked);
3740                         break;
3741                 }
3742         case SCTP_NOTIFY_INTERFACE_CONFIRMED:
3743                 {
3744                         struct sctp_nets *net;
3745
3746                         net = (struct sctp_nets *)data;
3747                         sctp_notify_peer_addr_change(stcb, SCTP_ADDR_CONFIRMED,
3748                             (struct sockaddr *)&net->ro._l_addr, error, so_locked);
3749                         break;
3750                 }
3751         case SCTP_NOTIFY_SPECIAL_SP_FAIL:
3752                 sctp_notify_send_failed2(stcb, error,
3753                     (struct sctp_stream_queue_pending *)data, so_locked);
3754                 break;
3755         case SCTP_NOTIFY_SENT_DG_FAIL:
3756                 sctp_notify_send_failed(stcb, 1, error,
3757                     (struct sctp_tmit_chunk *)data, so_locked);
3758                 break;
3759         case SCTP_NOTIFY_UNSENT_DG_FAIL:
3760                 sctp_notify_send_failed(stcb, 0, error,
3761                     (struct sctp_tmit_chunk *)data, so_locked);
3762                 break;
3763         case SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION:
3764                 {
3765                         uint32_t val;
3766
3767                         val = *((uint32_t *)data);
3768
3769                         sctp_notify_partial_delivery_indication(stcb, error, val, so_locked);
3770                         break;
3771                 }
3772         case SCTP_NOTIFY_ASSOC_LOC_ABORTED:
3773                 if ((SCTP_GET_STATE(stcb) == SCTP_STATE_COOKIE_WAIT) ||
3774                     (SCTP_GET_STATE(stcb) == SCTP_STATE_COOKIE_ECHOED)) {
3775                         sctp_notify_assoc_change(SCTP_CANT_STR_ASSOC, stcb, error, data, 0, so_locked);
3776                 } else {
3777                         sctp_notify_assoc_change(SCTP_COMM_LOST, stcb, error, data, 0, so_locked);
3778                 }
3779                 break;
3780         case SCTP_NOTIFY_ASSOC_REM_ABORTED:
3781                 if ((SCTP_GET_STATE(stcb) == SCTP_STATE_COOKIE_WAIT) ||
3782                     (SCTP_GET_STATE(stcb) == SCTP_STATE_COOKIE_ECHOED)) {
3783                         sctp_notify_assoc_change(SCTP_CANT_STR_ASSOC, stcb, error, data, 1, so_locked);
3784                 } else {
3785                         sctp_notify_assoc_change(SCTP_COMM_LOST, stcb, error, data, 1, so_locked);
3786                 }
3787                 break;
3788         case SCTP_NOTIFY_ASSOC_RESTART:
3789                 sctp_notify_assoc_change(SCTP_RESTART, stcb, error, NULL, 0, so_locked);
3790                 if (stcb->asoc.auth_supported == 0) {
3791                         sctp_ulp_notify(SCTP_NOTIFY_NO_PEER_AUTH, stcb, 0,
3792                             NULL, so_locked);
3793                 }
3794                 break;
3795         case SCTP_NOTIFY_STR_RESET_SEND:
3796                 sctp_notify_stream_reset(stcb, error, ((uint16_t *)data), SCTP_STREAM_RESET_OUTGOING_SSN);
3797                 break;
3798         case SCTP_NOTIFY_STR_RESET_RECV:
3799                 sctp_notify_stream_reset(stcb, error, ((uint16_t *)data), SCTP_STREAM_RESET_INCOMING);
3800                 break;
3801         case SCTP_NOTIFY_STR_RESET_FAILED_OUT:
3802                 sctp_notify_stream_reset(stcb, error, ((uint16_t *)data),
3803                     (SCTP_STREAM_RESET_OUTGOING_SSN | SCTP_STREAM_RESET_FAILED));
3804                 break;
3805         case SCTP_NOTIFY_STR_RESET_DENIED_OUT:
3806                 sctp_notify_stream_reset(stcb, error, ((uint16_t *)data),
3807                     (SCTP_STREAM_RESET_OUTGOING_SSN | SCTP_STREAM_RESET_DENIED));
3808                 break;
3809         case SCTP_NOTIFY_STR_RESET_FAILED_IN:
3810                 sctp_notify_stream_reset(stcb, error, ((uint16_t *)data),
3811                     (SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_FAILED));
3812                 break;
3813         case SCTP_NOTIFY_STR_RESET_DENIED_IN:
3814                 sctp_notify_stream_reset(stcb, error, ((uint16_t *)data),
3815                     (SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_DENIED));
3816                 break;
3817         case SCTP_NOTIFY_ASCONF_ADD_IP:
3818                 sctp_notify_peer_addr_change(stcb, SCTP_ADDR_ADDED, data,
3819                     error, so_locked);
3820                 break;
3821         case SCTP_NOTIFY_ASCONF_DELETE_IP:
3822                 sctp_notify_peer_addr_change(stcb, SCTP_ADDR_REMOVED, data,
3823                     error, so_locked);
3824                 break;
3825         case SCTP_NOTIFY_ASCONF_SET_PRIMARY:
3826                 sctp_notify_peer_addr_change(stcb, SCTP_ADDR_MADE_PRIM, data,
3827                     error, so_locked);
3828                 break;
3829         case SCTP_NOTIFY_PEER_SHUTDOWN:
3830                 sctp_notify_shutdown_event(stcb);
3831                 break;
3832         case SCTP_NOTIFY_AUTH_NEW_KEY:
3833                 sctp_notify_authentication(stcb, SCTP_AUTH_NEW_KEY, error,
3834                     (uint16_t)(uintptr_t)data,
3835                     so_locked);
3836                 break;
3837         case SCTP_NOTIFY_AUTH_FREE_KEY:
3838                 sctp_notify_authentication(stcb, SCTP_AUTH_FREE_KEY, error,
3839                     (uint16_t)(uintptr_t)data,
3840                     so_locked);
3841                 break;
3842         case SCTP_NOTIFY_NO_PEER_AUTH:
3843                 sctp_notify_authentication(stcb, SCTP_AUTH_NO_AUTH, error,
3844                     (uint16_t)(uintptr_t)data,
3845                     so_locked);
3846                 break;
3847         case SCTP_NOTIFY_SENDER_DRY:
3848                 sctp_notify_sender_dry_event(stcb, so_locked);
3849                 break;
3850         case SCTP_NOTIFY_REMOTE_ERROR:
3851                 sctp_notify_remote_error(stcb, error, data);
3852                 break;
3853         default:
3854                 SCTPDBG(SCTP_DEBUG_UTIL1, "%s: unknown notification %xh (%u)\n",
3855                     __func__, notification, notification);
3856                 break;
3857         }                       /* end switch */
3858 }
3859
3860 void
3861 sctp_report_all_outbound(struct sctp_tcb *stcb, uint16_t error, int so_locked
3862 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
3863     SCTP_UNUSED
3864 #endif
3865 )
3866 {
3867         struct sctp_association *asoc;
3868         struct sctp_stream_out *outs;
3869         struct sctp_tmit_chunk *chk, *nchk;
3870         struct sctp_stream_queue_pending *sp, *nsp;
3871         int i;
3872
3873         if (stcb == NULL) {
3874                 return;
3875         }
3876         asoc = &stcb->asoc;
3877         if (asoc->state & SCTP_STATE_ABOUT_TO_BE_FREED) {
3878                 /* already being freed */
3879                 return;
3880         }
3881         if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
3882             (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
3883             (asoc->state & SCTP_STATE_CLOSED_SOCKET)) {
3884                 return;
3885         }
3886         /* now through all the gunk freeing chunks */
3887         /* sent queue SHOULD be empty */
3888         TAILQ_FOREACH_SAFE(chk, &asoc->sent_queue, sctp_next, nchk) {
3889                 TAILQ_REMOVE(&asoc->sent_queue, chk, sctp_next);
3890                 asoc->sent_queue_cnt--;
3891                 if (chk->sent != SCTP_DATAGRAM_NR_ACKED) {
3892                         if (asoc->strmout[chk->rec.data.sid].chunks_on_queues > 0) {
3893                                 asoc->strmout[chk->rec.data.sid].chunks_on_queues--;
3894 #ifdef INVARIANTS
3895                         } else {
3896                                 panic("No chunks on the queues for sid %u.", chk->rec.data.sid);
3897 #endif
3898                         }
3899                 }
3900                 if (chk->data != NULL) {
3901                         sctp_free_bufspace(stcb, asoc, chk, 1);
3902                         sctp_ulp_notify(SCTP_NOTIFY_SENT_DG_FAIL, stcb,
3903                             error, chk, so_locked);
3904                         if (chk->data) {
3905                                 sctp_m_freem(chk->data);
3906                                 chk->data = NULL;
3907                         }
3908                 }
3909                 sctp_free_a_chunk(stcb, chk, so_locked);
3910                 /* sa_ignore FREED_MEMORY */
3911         }
3912         /* pending send queue SHOULD be empty */
3913         TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
3914                 TAILQ_REMOVE(&asoc->send_queue, chk, sctp_next);
3915                 asoc->send_queue_cnt--;
3916                 if (asoc->strmout[chk->rec.data.sid].chunks_on_queues > 0) {
3917                         asoc->strmout[chk->rec.data.sid].chunks_on_queues--;
3918 #ifdef INVARIANTS
3919                 } else {
3920                         panic("No chunks on the queues for sid %u.", chk->rec.data.sid);
3921 #endif
3922                 }
3923                 if (chk->data != NULL) {
3924                         sctp_free_bufspace(stcb, asoc, chk, 1);
3925                         sctp_ulp_notify(SCTP_NOTIFY_UNSENT_DG_FAIL, stcb,
3926                             error, chk, so_locked);
3927                         if (chk->data) {
3928                                 sctp_m_freem(chk->data);
3929                                 chk->data = NULL;
3930                         }
3931                 }
3932                 sctp_free_a_chunk(stcb, chk, so_locked);
3933                 /* sa_ignore FREED_MEMORY */
3934         }
3935         for (i = 0; i < asoc->streamoutcnt; i++) {
3936                 /* For each stream */
3937                 outs = &asoc->strmout[i];
3938                 /* clean up any sends there */
3939                 TAILQ_FOREACH_SAFE(sp, &outs->outqueue, next, nsp) {
3940                         atomic_subtract_int(&asoc->stream_queue_cnt, 1);
3941                         TAILQ_REMOVE(&outs->outqueue, sp, next);
3942                         stcb->asoc.ss_functions.sctp_ss_remove_from_stream(stcb, asoc, outs, sp, 1);
3943                         sctp_free_spbufspace(stcb, asoc, sp);
3944                         if (sp->data) {
3945                                 sctp_ulp_notify(SCTP_NOTIFY_SPECIAL_SP_FAIL, stcb,
3946                                     error, (void *)sp, so_locked);
3947                                 if (sp->data) {
3948                                         sctp_m_freem(sp->data);
3949                                         sp->data = NULL;
3950                                         sp->tail_mbuf = NULL;
3951                                         sp->length = 0;
3952                                 }
3953                         }
3954                         if (sp->net) {
3955                                 sctp_free_remote_addr(sp->net);
3956                                 sp->net = NULL;
3957                         }
3958                         /* Free the chunk */
3959                         sctp_free_a_strmoq(stcb, sp, so_locked);
3960                         /* sa_ignore FREED_MEMORY */
3961                 }
3962         }
3963 }
3964
3965 void
3966 sctp_abort_notification(struct sctp_tcb *stcb, uint8_t from_peer, uint16_t error,
3967     struct sctp_abort_chunk *abort, int so_locked
3968 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
3969     SCTP_UNUSED
3970 #endif
3971 )
3972 {
3973         if (stcb == NULL) {
3974                 return;
3975         }
3976         if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) ||
3977             ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
3978             (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_CONNECTED))) {
3979                 stcb->sctp_ep->sctp_flags |= SCTP_PCB_FLAGS_WAS_ABORTED;
3980         }
3981         if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
3982             (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
3983             (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET)) {
3984                 return;
3985         }
3986         SCTP_TCB_SEND_LOCK(stcb);
3987         SCTP_ADD_SUBSTATE(stcb, SCTP_STATE_WAS_ABORTED);
3988         /* Tell them we lost the asoc */
3989         sctp_report_all_outbound(stcb, error, so_locked);
3990         SCTP_TCB_SEND_UNLOCK(stcb);
3991         if (from_peer) {
3992                 sctp_ulp_notify(SCTP_NOTIFY_ASSOC_REM_ABORTED, stcb, error, abort, so_locked);
3993         } else {
3994                 sctp_ulp_notify(SCTP_NOTIFY_ASSOC_LOC_ABORTED, stcb, error, abort, so_locked);
3995         }
3996 }
3997
3998 void
3999 sctp_abort_association(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
4000     struct mbuf *m, int iphlen,
4001     struct sockaddr *src, struct sockaddr *dst,
4002     struct sctphdr *sh, struct mbuf *op_err,
4003     uint8_t mflowtype, uint32_t mflowid,
4004     uint32_t vrf_id, uint16_t port)
4005 {
4006         uint32_t vtag;
4007 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4008         struct socket *so;
4009 #endif
4010
4011         vtag = 0;
4012         if (stcb != NULL) {
4013                 vtag = stcb->asoc.peer_vtag;
4014                 vrf_id = stcb->asoc.vrf_id;
4015         }
4016         sctp_send_abort(m, iphlen, src, dst, sh, vtag, op_err,
4017             mflowtype, mflowid, inp->fibnum,
4018             vrf_id, port);
4019         if (stcb != NULL) {
4020                 /* We have a TCB to abort, send notification too */
4021                 sctp_abort_notification(stcb, 0, 0, NULL, SCTP_SO_NOT_LOCKED);
4022                 /* Ok, now lets free it */
4023 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4024                 so = SCTP_INP_SO(inp);
4025                 atomic_add_int(&stcb->asoc.refcnt, 1);
4026                 SCTP_TCB_UNLOCK(stcb);
4027                 SCTP_SOCKET_LOCK(so, 1);
4028                 SCTP_TCB_LOCK(stcb);
4029                 atomic_subtract_int(&stcb->asoc.refcnt, 1);
4030 #endif
4031                 SCTP_STAT_INCR_COUNTER32(sctps_aborted);
4032                 if ((SCTP_GET_STATE(stcb) == SCTP_STATE_OPEN) ||
4033                     (SCTP_GET_STATE(stcb) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
4034                         SCTP_STAT_DECR_GAUGE32(sctps_currestab);
4035                 }
4036                 (void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC,
4037                     SCTP_FROM_SCTPUTIL + SCTP_LOC_4);
4038 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4039                 SCTP_SOCKET_UNLOCK(so, 1);
4040 #endif
4041         }
4042 }
4043 #ifdef SCTP_ASOCLOG_OF_TSNS
4044 void
4045 sctp_print_out_track_log(struct sctp_tcb *stcb)
4046 {
4047 #ifdef NOSIY_PRINTS
4048         int i;
4049
4050         SCTP_PRINTF("Last ep reason:%x\n", stcb->sctp_ep->last_abort_code);
4051         SCTP_PRINTF("IN bound TSN log-aaa\n");
4052         if ((stcb->asoc.tsn_in_at == 0) && (stcb->asoc.tsn_in_wrapped == 0)) {
4053                 SCTP_PRINTF("None rcvd\n");
4054                 goto none_in;
4055         }
4056         if (stcb->asoc.tsn_in_wrapped) {
4057                 for (i = stcb->asoc.tsn_in_at; i < SCTP_TSN_LOG_SIZE; i++) {
4058                         SCTP_PRINTF("TSN:%x strm:%d seq:%d flags:%x sz:%d\n",
4059                             stcb->asoc.in_tsnlog[i].tsn,
4060                             stcb->asoc.in_tsnlog[i].strm,
4061                             stcb->asoc.in_tsnlog[i].seq,
4062                             stcb->asoc.in_tsnlog[i].flgs,
4063                             stcb->asoc.in_tsnlog[i].sz);
4064                 }
4065         }
4066         if (stcb->asoc.tsn_in_at) {
4067                 for (i = 0; i < stcb->asoc.tsn_in_at; i++) {
4068                         SCTP_PRINTF("TSN:%x strm:%d seq:%d flags:%x sz:%d\n",
4069                             stcb->asoc.in_tsnlog[i].tsn,
4070                             stcb->asoc.in_tsnlog[i].strm,
4071                             stcb->asoc.in_tsnlog[i].seq,
4072                             stcb->asoc.in_tsnlog[i].flgs,
4073                             stcb->asoc.in_tsnlog[i].sz);
4074                 }
4075         }
4076 none_in:
4077         SCTP_PRINTF("OUT bound TSN log-aaa\n");
4078         if ((stcb->asoc.tsn_out_at == 0) &&
4079             (stcb->asoc.tsn_out_wrapped == 0)) {
4080                 SCTP_PRINTF("None sent\n");
4081         }
4082         if (stcb->asoc.tsn_out_wrapped) {
4083                 for (i = stcb->asoc.tsn_out_at; i < SCTP_TSN_LOG_SIZE; i++) {
4084                         SCTP_PRINTF("TSN:%x strm:%d seq:%d flags:%x sz:%d\n",
4085                             stcb->asoc.out_tsnlog[i].tsn,
4086                             stcb->asoc.out_tsnlog[i].strm,
4087                             stcb->asoc.out_tsnlog[i].seq,
4088                             stcb->asoc.out_tsnlog[i].flgs,
4089                             stcb->asoc.out_tsnlog[i].sz);
4090                 }
4091         }
4092         if (stcb->asoc.tsn_out_at) {
4093                 for (i = 0; i < stcb->asoc.tsn_out_at; i++) {
4094                         SCTP_PRINTF("TSN:%x strm:%d seq:%d flags:%x sz:%d\n",
4095                             stcb->asoc.out_tsnlog[i].tsn,
4096                             stcb->asoc.out_tsnlog[i].strm,
4097                             stcb->asoc.out_tsnlog[i].seq,
4098                             stcb->asoc.out_tsnlog[i].flgs,
4099                             stcb->asoc.out_tsnlog[i].sz);
4100                 }
4101         }
4102 #endif
4103 }
4104 #endif
4105
4106 void
4107 sctp_abort_an_association(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
4108     struct mbuf *op_err,
4109     int so_locked
4110 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
4111     SCTP_UNUSED
4112 #endif
4113 )
4114 {
4115 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4116         struct socket *so;
4117 #endif
4118
4119 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4120         so = SCTP_INP_SO(inp);
4121 #endif
4122         if (stcb == NULL) {
4123                 /* Got to have a TCB */
4124                 if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
4125                         if (LIST_EMPTY(&inp->sctp_asoc_list)) {
4126                                 sctp_inpcb_free(inp, SCTP_FREE_SHOULD_USE_ABORT,
4127                                     SCTP_CALLED_DIRECTLY_NOCMPSET);
4128                         }
4129                 }
4130                 return;
4131         }
4132         /* notify the peer */
4133         sctp_send_abort_tcb(stcb, op_err, so_locked);
4134         SCTP_STAT_INCR_COUNTER32(sctps_aborted);
4135         if ((SCTP_GET_STATE(stcb) == SCTP_STATE_OPEN) ||
4136             (SCTP_GET_STATE(stcb) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
4137                 SCTP_STAT_DECR_GAUGE32(sctps_currestab);
4138         }
4139         /* notify the ulp */
4140         if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) == 0) {
4141                 sctp_abort_notification(stcb, 0, 0, NULL, so_locked);
4142         }
4143         /* now free the asoc */
4144 #ifdef SCTP_ASOCLOG_OF_TSNS
4145         sctp_print_out_track_log(stcb);
4146 #endif
4147 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4148         if (!so_locked) {
4149                 atomic_add_int(&stcb->asoc.refcnt, 1);
4150                 SCTP_TCB_UNLOCK(stcb);
4151                 SCTP_SOCKET_LOCK(so, 1);
4152                 SCTP_TCB_LOCK(stcb);
4153                 atomic_subtract_int(&stcb->asoc.refcnt, 1);
4154         }
4155 #endif
4156         (void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC,
4157             SCTP_FROM_SCTPUTIL + SCTP_LOC_5);
4158 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4159         if (!so_locked) {
4160                 SCTP_SOCKET_UNLOCK(so, 1);
4161         }
4162 #endif
4163 }
4164
4165 void
4166 sctp_handle_ootb(struct mbuf *m, int iphlen, int offset,
4167     struct sockaddr *src, struct sockaddr *dst,
4168     struct sctphdr *sh, struct sctp_inpcb *inp,
4169     struct mbuf *cause,
4170     uint8_t mflowtype, uint32_t mflowid, uint16_t fibnum,
4171     uint32_t vrf_id, uint16_t port)
4172 {
4173         struct sctp_chunkhdr *ch, chunk_buf;
4174         unsigned int chk_length;
4175         int contains_init_chunk;
4176
4177         SCTP_STAT_INCR_COUNTER32(sctps_outoftheblue);
4178         /* Generate a TO address for future reference */
4179         if (inp && (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
4180                 if (LIST_EMPTY(&inp->sctp_asoc_list)) {
4181                         sctp_inpcb_free(inp, SCTP_FREE_SHOULD_USE_ABORT,
4182                             SCTP_CALLED_DIRECTLY_NOCMPSET);
4183                 }
4184         }
4185         contains_init_chunk = 0;
4186         ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, offset,
4187             sizeof(*ch), (uint8_t *)&chunk_buf);
4188         while (ch != NULL) {
4189                 chk_length = ntohs(ch->chunk_length);
4190                 if (chk_length < sizeof(*ch)) {
4191                         /* break to abort land */
4192                         break;
4193                 }
4194                 switch (ch->chunk_type) {
4195                 case SCTP_INIT:
4196                         contains_init_chunk = 1;
4197                         break;
4198                 case SCTP_PACKET_DROPPED:
4199                         /* we don't respond to pkt-dropped */
4200                         return;
4201                 case SCTP_ABORT_ASSOCIATION:
4202                         /* we don't respond with an ABORT to an ABORT */
4203                         return;
4204                 case SCTP_SHUTDOWN_COMPLETE:
4205                         /*
4206                          * we ignore it since we are not waiting for it and
4207                          * peer is gone
4208                          */
4209                         return;
4210                 case SCTP_SHUTDOWN_ACK:
4211                         sctp_send_shutdown_complete2(src, dst, sh,
4212                             mflowtype, mflowid, fibnum,
4213                             vrf_id, port);
4214                         return;
4215                 default:
4216                         break;
4217                 }
4218                 offset += SCTP_SIZE32(chk_length);
4219                 ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, offset,
4220                     sizeof(*ch), (uint8_t *)&chunk_buf);
4221         }
4222         if ((SCTP_BASE_SYSCTL(sctp_blackhole) == 0) ||
4223             ((SCTP_BASE_SYSCTL(sctp_blackhole) == 1) &&
4224             (contains_init_chunk == 0))) {
4225                 sctp_send_abort(m, iphlen, src, dst, sh, 0, cause,
4226                     mflowtype, mflowid, fibnum,
4227                     vrf_id, port);
4228         }
4229 }
4230
4231 /*
4232  * check the inbound datagram to make sure there is not an abort inside it,
4233  * if there is return 1, else return 0.
4234  */
4235 int
4236 sctp_is_there_an_abort_here(struct mbuf *m, int iphlen, uint32_t *vtagfill)
4237 {
4238         struct sctp_chunkhdr *ch;
4239         struct sctp_init_chunk *init_chk, chunk_buf;
4240         int offset;
4241         unsigned int chk_length;
4242
4243         offset = iphlen + sizeof(struct sctphdr);
4244         ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, offset, sizeof(*ch),
4245             (uint8_t *)&chunk_buf);
4246         while (ch != NULL) {
4247                 chk_length = ntohs(ch->chunk_length);
4248                 if (chk_length < sizeof(*ch)) {
4249                         /* packet is probably corrupt */
4250                         break;
4251                 }
4252                 /* we seem to be ok, is it an abort? */
4253                 if (ch->chunk_type == SCTP_ABORT_ASSOCIATION) {
4254                         /* yep, tell them */
4255                         return (1);
4256                 }
4257                 if (ch->chunk_type == SCTP_INITIATION) {
4258                         /* need to update the Vtag */
4259                         init_chk = (struct sctp_init_chunk *)sctp_m_getptr(m,
4260                             offset, sizeof(*init_chk), (uint8_t *)&chunk_buf);
4261                         if (init_chk != NULL) {
4262                                 *vtagfill = ntohl(init_chk->init.initiate_tag);
4263                         }
4264                 }
4265                 /* Nope, move to the next chunk */
4266                 offset += SCTP_SIZE32(chk_length);
4267                 ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, offset,
4268                     sizeof(*ch), (uint8_t *)&chunk_buf);
4269         }
4270         return (0);
4271 }
4272
4273 /*
4274  * currently (2/02), ifa_addr embeds scope_id's and don't have sin6_scope_id
4275  * set (i.e. it's 0) so, create this function to compare link local scopes
4276  */
4277 #ifdef INET6
4278 uint32_t
4279 sctp_is_same_scope(struct sockaddr_in6 *addr1, struct sockaddr_in6 *addr2)
4280 {
4281         struct sockaddr_in6 a, b;
4282
4283         /* save copies */
4284         a = *addr1;
4285         b = *addr2;
4286
4287         if (a.sin6_scope_id == 0)
4288                 if (sa6_recoverscope(&a)) {
4289                         /* can't get scope, so can't match */
4290                         return (0);
4291                 }
4292         if (b.sin6_scope_id == 0)
4293                 if (sa6_recoverscope(&b)) {
4294                         /* can't get scope, so can't match */
4295                         return (0);
4296                 }
4297         if (a.sin6_scope_id != b.sin6_scope_id)
4298                 return (0);
4299
4300         return (1);
4301 }
4302
4303 /*
4304  * returns a sockaddr_in6 with embedded scope recovered and removed
4305  */
4306 struct sockaddr_in6 *
4307 sctp_recover_scope(struct sockaddr_in6 *addr, struct sockaddr_in6 *store)
4308 {
4309         /* check and strip embedded scope junk */
4310         if (addr->sin6_family == AF_INET6) {
4311                 if (IN6_IS_SCOPE_LINKLOCAL(&addr->sin6_addr)) {
4312                         if (addr->sin6_scope_id == 0) {
4313                                 *store = *addr;
4314                                 if (!sa6_recoverscope(store)) {
4315                                         /* use the recovered scope */
4316                                         addr = store;
4317                                 }
4318                         } else {
4319                                 /* else, return the original "to" addr */
4320                                 in6_clearscope(&addr->sin6_addr);
4321                         }
4322                 }
4323         }
4324         return (addr);
4325 }
4326 #endif
4327
4328 /*
4329  * are the two addresses the same?  currently a "scopeless" check returns: 1
4330  * if same, 0 if not
4331  */
4332 int
4333 sctp_cmpaddr(struct sockaddr *sa1, struct sockaddr *sa2)
4334 {
4335
4336         /* must be valid */
4337         if (sa1 == NULL || sa2 == NULL)
4338                 return (0);
4339
4340         /* must be the same family */
4341         if (sa1->sa_family != sa2->sa_family)
4342                 return (0);
4343
4344         switch (sa1->sa_family) {
4345 #ifdef INET6
4346         case AF_INET6:
4347                 {
4348                         /* IPv6 addresses */
4349                         struct sockaddr_in6 *sin6_1, *sin6_2;
4350
4351                         sin6_1 = (struct sockaddr_in6 *)sa1;
4352                         sin6_2 = (struct sockaddr_in6 *)sa2;
4353                         return (SCTP6_ARE_ADDR_EQUAL(sin6_1,
4354                             sin6_2));
4355                 }
4356 #endif
4357 #ifdef INET
4358         case AF_INET:
4359                 {
4360                         /* IPv4 addresses */
4361                         struct sockaddr_in *sin_1, *sin_2;
4362
4363                         sin_1 = (struct sockaddr_in *)sa1;
4364                         sin_2 = (struct sockaddr_in *)sa2;
4365                         return (sin_1->sin_addr.s_addr == sin_2->sin_addr.s_addr);
4366                 }
4367 #endif
4368         default:
4369                 /* we don't do these... */
4370                 return (0);
4371         }
4372 }
4373
4374 void
4375 sctp_print_address(struct sockaddr *sa)
4376 {
4377 #ifdef INET6
4378         char ip6buf[INET6_ADDRSTRLEN];
4379 #endif
4380
4381         switch (sa->sa_family) {
4382 #ifdef INET6
4383         case AF_INET6:
4384                 {
4385                         struct sockaddr_in6 *sin6;
4386
4387                         sin6 = (struct sockaddr_in6 *)sa;
4388                         SCTP_PRINTF("IPv6 address: %s:port:%d scope:%u\n",
4389                             ip6_sprintf(ip6buf, &sin6->sin6_addr),
4390                             ntohs(sin6->sin6_port),
4391                             sin6->sin6_scope_id);
4392                         break;
4393                 }
4394 #endif
4395 #ifdef INET
4396         case AF_INET:
4397                 {
4398                         struct sockaddr_in *sin;
4399                         unsigned char *p;
4400
4401                         sin = (struct sockaddr_in *)sa;
4402                         p = (unsigned char *)&sin->sin_addr;
4403                         SCTP_PRINTF("IPv4 address: %u.%u.%u.%u:%d\n",
4404                             p[0], p[1], p[2], p[3], ntohs(sin->sin_port));
4405                         break;
4406                 }
4407 #endif
4408         default:
4409                 SCTP_PRINTF("?\n");
4410                 break;
4411         }
4412 }
4413
4414 void
4415 sctp_pull_off_control_to_new_inp(struct sctp_inpcb *old_inp,
4416     struct sctp_inpcb *new_inp,
4417     struct sctp_tcb *stcb,
4418     int waitflags)
4419 {
4420         /*
4421          * go through our old INP and pull off any control structures that
4422          * belong to stcb and move then to the new inp.
4423          */
4424         struct socket *old_so, *new_so;
4425         struct sctp_queued_to_read *control, *nctl;
4426         struct sctp_readhead tmp_queue;
4427         struct mbuf *m;
4428         int error = 0;
4429
4430         old_so = old_inp->sctp_socket;
4431         new_so = new_inp->sctp_socket;
4432         TAILQ_INIT(&tmp_queue);
4433         error = sblock(&old_so->so_rcv, waitflags);
4434         if (error) {
4435                 /*
4436                  * Gak, can't get sblock, we have a problem. data will be
4437                  * left stranded.. and we don't dare look at it since the
4438                  * other thread may be reading something. Oh well, its a
4439                  * screwed up app that does a peeloff OR a accept while
4440                  * reading from the main socket... actually its only the
4441                  * peeloff() case, since I think read will fail on a
4442                  * listening socket..
4443                  */
4444                 return;
4445         }
4446         /* lock the socket buffers */
4447         SCTP_INP_READ_LOCK(old_inp);
4448         TAILQ_FOREACH_SAFE(control, &old_inp->read_queue, next, nctl) {
4449                 /* Pull off all for out target stcb */
4450                 if (control->stcb == stcb) {
4451                         /* remove it we want it */
4452                         TAILQ_REMOVE(&old_inp->read_queue, control, next);
4453                         TAILQ_INSERT_TAIL(&tmp_queue, control, next);
4454                         m = control->data;
4455                         while (m) {
4456                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
4457                                         sctp_sblog(&old_so->so_rcv, control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBFREE, SCTP_BUF_LEN(m));
4458                                 }
4459                                 sctp_sbfree(control, stcb, &old_so->so_rcv, m);
4460                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
4461                                         sctp_sblog(&old_so->so_rcv, control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBRESULT, 0);
4462                                 }
4463                                 m = SCTP_BUF_NEXT(m);
4464                         }
4465                 }
4466         }
4467         SCTP_INP_READ_UNLOCK(old_inp);
4468         /* Remove the sb-lock on the old socket */
4469
4470         sbunlock(&old_so->so_rcv);
4471         /* Now we move them over to the new socket buffer */
4472         SCTP_INP_READ_LOCK(new_inp);
4473         TAILQ_FOREACH_SAFE(control, &tmp_queue, next, nctl) {
4474                 TAILQ_INSERT_TAIL(&new_inp->read_queue, control, next);
4475                 m = control->data;
4476                 while (m) {
4477                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
4478                                 sctp_sblog(&new_so->so_rcv, control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBALLOC, SCTP_BUF_LEN(m));
4479                         }
4480                         sctp_sballoc(stcb, &new_so->so_rcv, m);
4481                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
4482                                 sctp_sblog(&new_so->so_rcv, control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBRESULT, 0);
4483                         }
4484                         m = SCTP_BUF_NEXT(m);
4485                 }
4486         }
4487         SCTP_INP_READ_UNLOCK(new_inp);
4488 }
4489
4490 void
4491 sctp_wakeup_the_read_socket(struct sctp_inpcb *inp,
4492     struct sctp_tcb *stcb,
4493     int so_locked
4494 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
4495     SCTP_UNUSED
4496 #endif
4497 )
4498 {
4499         if ((inp != NULL) && (inp->sctp_socket != NULL)) {
4500 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4501                 struct socket *so;
4502
4503                 so = SCTP_INP_SO(inp);
4504                 if (!so_locked) {
4505                         if (stcb) {
4506                                 atomic_add_int(&stcb->asoc.refcnt, 1);
4507                                 SCTP_TCB_UNLOCK(stcb);
4508                         }
4509                         SCTP_SOCKET_LOCK(so, 1);
4510                         if (stcb) {
4511                                 SCTP_TCB_LOCK(stcb);
4512                                 atomic_subtract_int(&stcb->asoc.refcnt, 1);
4513                         }
4514                         if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
4515                                 SCTP_SOCKET_UNLOCK(so, 1);
4516                                 return;
4517                         }
4518                 }
4519 #endif
4520                 sctp_sorwakeup(inp, inp->sctp_socket);
4521 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4522                 if (!so_locked) {
4523                         SCTP_SOCKET_UNLOCK(so, 1);
4524                 }
4525 #endif
4526         }
4527 }
4528
4529 void
4530 sctp_add_to_readq(struct sctp_inpcb *inp,
4531     struct sctp_tcb *stcb,
4532     struct sctp_queued_to_read *control,
4533     struct sockbuf *sb,
4534     int end,
4535     int inp_read_lock_held,
4536     int so_locked
4537 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
4538     SCTP_UNUSED
4539 #endif
4540 )
4541 {
4542         /*
4543          * Here we must place the control on the end of the socket read
4544          * queue AND increment sb_cc so that select will work properly on
4545          * read.
4546          */
4547         struct mbuf *m, *prev = NULL;
4548
4549         if (inp == NULL) {
4550                 /* Gak, TSNH!! */
4551 #ifdef INVARIANTS
4552                 panic("Gak, inp NULL on add_to_readq");
4553 #endif
4554                 return;
4555         }
4556         if (inp_read_lock_held == 0)
4557                 SCTP_INP_READ_LOCK(inp);
4558         if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_CANT_READ) {
4559                 sctp_free_remote_addr(control->whoFrom);
4560                 if (control->data) {
4561                         sctp_m_freem(control->data);
4562                         control->data = NULL;
4563                 }
4564                 sctp_free_a_readq(stcb, control);
4565                 if (inp_read_lock_held == 0)
4566                         SCTP_INP_READ_UNLOCK(inp);
4567                 return;
4568         }
4569         if (!(control->spec_flags & M_NOTIFICATION)) {
4570                 atomic_add_int(&inp->total_recvs, 1);
4571                 if (!control->do_not_ref_stcb) {
4572                         atomic_add_int(&stcb->total_recvs, 1);
4573                 }
4574         }
4575         m = control->data;
4576         control->held_length = 0;
4577         control->length = 0;
4578         while (m) {
4579                 if (SCTP_BUF_LEN(m) == 0) {
4580                         /* Skip mbufs with NO length */
4581                         if (prev == NULL) {
4582                                 /* First one */
4583                                 control->data = sctp_m_free(m);
4584                                 m = control->data;
4585                         } else {
4586                                 SCTP_BUF_NEXT(prev) = sctp_m_free(m);
4587                                 m = SCTP_BUF_NEXT(prev);
4588                         }
4589                         if (m == NULL) {
4590                                 control->tail_mbuf = prev;
4591                         }
4592                         continue;
4593                 }
4594                 prev = m;
4595                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
4596                         sctp_sblog(sb, control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBALLOC, SCTP_BUF_LEN(m));
4597                 }
4598                 sctp_sballoc(stcb, sb, m);
4599                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
4600                         sctp_sblog(sb, control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBRESULT, 0);
4601                 }
4602                 atomic_add_int(&control->length, SCTP_BUF_LEN(m));
4603                 m = SCTP_BUF_NEXT(m);
4604         }
4605         if (prev != NULL) {
4606                 control->tail_mbuf = prev;
4607         } else {
4608                 /* Everything got collapsed out?? */
4609                 sctp_free_remote_addr(control->whoFrom);
4610                 sctp_free_a_readq(stcb, control);
4611                 if (inp_read_lock_held == 0)
4612                         SCTP_INP_READ_UNLOCK(inp);
4613                 return;
4614         }
4615         if (end) {
4616                 control->end_added = 1;
4617         }
4618         TAILQ_INSERT_TAIL(&inp->read_queue, control, next);
4619         control->on_read_q = 1;
4620         if (inp_read_lock_held == 0)
4621                 SCTP_INP_READ_UNLOCK(inp);
4622         if (inp && inp->sctp_socket) {
4623                 sctp_wakeup_the_read_socket(inp, stcb, so_locked);
4624         }
4625 }
4626
4627 /*************HOLD THIS COMMENT FOR PATCH FILE OF
4628  *************ALTERNATE ROUTING CODE
4629  */
4630
4631 /*************HOLD THIS COMMENT FOR END OF PATCH FILE OF
4632  *************ALTERNATE ROUTING CODE
4633  */
4634
4635 struct mbuf *
4636 sctp_generate_cause(uint16_t code, char *info)
4637 {
4638         struct mbuf *m;
4639         struct sctp_gen_error_cause *cause;
4640         size_t info_len;
4641         uint16_t len;
4642
4643         if ((code == 0) || (info == NULL)) {
4644                 return (NULL);
4645         }
4646         info_len = strlen(info);
4647         if (info_len > (SCTP_MAX_CAUSE_LENGTH - sizeof(struct sctp_paramhdr))) {
4648                 return (NULL);
4649         }
4650         len = (uint16_t)(sizeof(struct sctp_paramhdr) + info_len);
4651         m = sctp_get_mbuf_for_msg(len, 0, M_NOWAIT, 1, MT_DATA);
4652         if (m != NULL) {
4653                 SCTP_BUF_LEN(m) = len;
4654                 cause = mtod(m, struct sctp_gen_error_cause *);
4655                 cause->code = htons(code);
4656                 cause->length = htons(len);
4657                 memcpy(cause->info, info, info_len);
4658         }
4659         return (m);
4660 }
4661
4662 struct mbuf *
4663 sctp_generate_no_user_data_cause(uint32_t tsn)
4664 {
4665         struct mbuf *m;
4666         struct sctp_error_no_user_data *no_user_data_cause;
4667         uint16_t len;
4668
4669         len = (uint16_t)sizeof(struct sctp_error_no_user_data);
4670         m = sctp_get_mbuf_for_msg(len, 0, M_NOWAIT, 1, MT_DATA);
4671         if (m != NULL) {
4672                 SCTP_BUF_LEN(m) = len;
4673                 no_user_data_cause = mtod(m, struct sctp_error_no_user_data *);
4674                 no_user_data_cause->cause.code = htons(SCTP_CAUSE_NO_USER_DATA);
4675                 no_user_data_cause->cause.length = htons(len);
4676                 no_user_data_cause->tsn = htonl(tsn);
4677         }
4678         return (m);
4679 }
4680
4681 #ifdef SCTP_MBCNT_LOGGING
4682 void
4683 sctp_free_bufspace(struct sctp_tcb *stcb, struct sctp_association *asoc,
4684     struct sctp_tmit_chunk *tp1, int chk_cnt)
4685 {
4686         if (tp1->data == NULL) {
4687                 return;
4688         }
4689         asoc->chunks_on_out_queue -= chk_cnt;
4690         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBCNT_LOGGING_ENABLE) {
4691                 sctp_log_mbcnt(SCTP_LOG_MBCNT_DECREASE,
4692                     asoc->total_output_queue_size,
4693                     tp1->book_size,
4694                     0,
4695                     tp1->mbcnt);
4696         }
4697         if (asoc->total_output_queue_size >= tp1->book_size) {
4698                 atomic_add_int(&asoc->total_output_queue_size, -tp1->book_size);
4699         } else {
4700                 asoc->total_output_queue_size = 0;
4701         }
4702
4703         if (stcb->sctp_socket && (((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) ||
4704             ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)))) {
4705                 if (stcb->sctp_socket->so_snd.sb_cc >= tp1->book_size) {
4706                         stcb->sctp_socket->so_snd.sb_cc -= tp1->book_size;
4707                 } else {
4708                         stcb->sctp_socket->so_snd.sb_cc = 0;
4709
4710                 }
4711         }
4712 }
4713
4714 #endif
4715
4716 int
4717 sctp_release_pr_sctp_chunk(struct sctp_tcb *stcb, struct sctp_tmit_chunk *tp1,
4718     uint8_t sent, int so_locked
4719 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
4720     SCTP_UNUSED
4721 #endif
4722 )
4723 {
4724         struct sctp_stream_out *strq;
4725         struct sctp_tmit_chunk *chk = NULL, *tp2;
4726         struct sctp_stream_queue_pending *sp;
4727         uint32_t mid;
4728         uint16_t sid;
4729         uint8_t foundeom = 0;
4730         int ret_sz = 0;
4731         int notdone;
4732         int do_wakeup_routine = 0;
4733
4734         sid = tp1->rec.data.sid;
4735         mid = tp1->rec.data.mid;
4736         if (sent || !(tp1->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG)) {
4737                 stcb->asoc.abandoned_sent[0]++;
4738                 stcb->asoc.abandoned_sent[PR_SCTP_POLICY(tp1->flags)]++;
4739                 stcb->asoc.strmout[sid].abandoned_sent[0]++;
4740 #if defined(SCTP_DETAILED_STR_STATS)
4741                 stcb->asoc.strmout[stream].abandoned_sent[PR_SCTP_POLICY(tp1->flags)]++;
4742 #endif
4743         } else {
4744                 stcb->asoc.abandoned_unsent[0]++;
4745                 stcb->asoc.abandoned_unsent[PR_SCTP_POLICY(tp1->flags)]++;
4746                 stcb->asoc.strmout[sid].abandoned_unsent[0]++;
4747 #if defined(SCTP_DETAILED_STR_STATS)
4748                 stcb->asoc.strmout[stream].abandoned_unsent[PR_SCTP_POLICY(tp1->flags)]++;
4749 #endif
4750         }
4751         do {
4752                 ret_sz += tp1->book_size;
4753                 if (tp1->data != NULL) {
4754                         if (tp1->sent < SCTP_DATAGRAM_RESEND) {
4755                                 sctp_flight_size_decrease(tp1);
4756                                 sctp_total_flight_decrease(stcb, tp1);
4757                         }
4758                         sctp_free_bufspace(stcb, &stcb->asoc, tp1, 1);
4759                         stcb->asoc.peers_rwnd += tp1->send_size;
4760                         stcb->asoc.peers_rwnd += SCTP_BASE_SYSCTL(sctp_peer_chunk_oh);
4761                         if (sent) {
4762                                 sctp_ulp_notify(SCTP_NOTIFY_SENT_DG_FAIL, stcb, 0, tp1, so_locked);
4763                         } else {
4764                                 sctp_ulp_notify(SCTP_NOTIFY_UNSENT_DG_FAIL, stcb, 0, tp1, so_locked);
4765                         }
4766                         if (tp1->data) {
4767                                 sctp_m_freem(tp1->data);
4768                                 tp1->data = NULL;
4769                         }
4770                         do_wakeup_routine = 1;
4771                         if (PR_SCTP_BUF_ENABLED(tp1->flags)) {
4772                                 stcb->asoc.sent_queue_cnt_removeable--;
4773                         }
4774                 }
4775                 tp1->sent = SCTP_FORWARD_TSN_SKIP;
4776                 if ((tp1->rec.data.rcv_flags & SCTP_DATA_NOT_FRAG) ==
4777                     SCTP_DATA_NOT_FRAG) {
4778                         /* not frag'ed we ae done   */
4779                         notdone = 0;
4780                         foundeom = 1;
4781                 } else if (tp1->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) {
4782                         /* end of frag, we are done */
4783                         notdone = 0;
4784                         foundeom = 1;
4785                 } else {
4786                         /*
4787                          * Its a begin or middle piece, we must mark all of
4788                          * it
4789                          */
4790                         notdone = 1;
4791                         tp1 = TAILQ_NEXT(tp1, sctp_next);
4792                 }
4793         } while (tp1 && notdone);
4794         if (foundeom == 0) {
4795                 /*
4796                  * The multi-part message was scattered across the send and
4797                  * sent queue.
4798                  */
4799                 TAILQ_FOREACH_SAFE(tp1, &stcb->asoc.send_queue, sctp_next, tp2) {
4800                         if ((tp1->rec.data.sid != sid) ||
4801                             (!SCTP_MID_EQ(stcb->asoc.idata_supported, tp1->rec.data.mid, mid))) {
4802                                 break;
4803                         }
4804                         /*
4805                          * save to chk in case we have some on stream out
4806                          * queue. If so and we have an un-transmitted one we
4807                          * don't have to fudge the TSN.
4808                          */
4809                         chk = tp1;
4810                         ret_sz += tp1->book_size;
4811                         sctp_free_bufspace(stcb, &stcb->asoc, tp1, 1);
4812                         if (sent) {
4813                                 sctp_ulp_notify(SCTP_NOTIFY_SENT_DG_FAIL, stcb, 0, tp1, so_locked);
4814                         } else {
4815                                 sctp_ulp_notify(SCTP_NOTIFY_UNSENT_DG_FAIL, stcb, 0, tp1, so_locked);
4816                         }
4817                         if (tp1->data) {
4818                                 sctp_m_freem(tp1->data);
4819                                 tp1->data = NULL;
4820                         }
4821                         /* No flight involved here book the size to 0 */
4822                         tp1->book_size = 0;
4823                         if (tp1->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) {
4824                                 foundeom = 1;
4825                         }
4826                         do_wakeup_routine = 1;
4827                         tp1->sent = SCTP_FORWARD_TSN_SKIP;
4828                         TAILQ_REMOVE(&stcb->asoc.send_queue, tp1, sctp_next);
4829                         /*
4830                          * on to the sent queue so we can wait for it to be
4831                          * passed by.
4832                          */
4833                         TAILQ_INSERT_TAIL(&stcb->asoc.sent_queue, tp1,
4834                             sctp_next);
4835                         stcb->asoc.send_queue_cnt--;
4836                         stcb->asoc.sent_queue_cnt++;
4837                 }
4838         }
4839         if (foundeom == 0) {
4840                 /*
4841                  * Still no eom found. That means there is stuff left on the
4842                  * stream out queue.. yuck.
4843                  */
4844                 SCTP_TCB_SEND_LOCK(stcb);
4845                 strq = &stcb->asoc.strmout[sid];
4846                 sp = TAILQ_FIRST(&strq->outqueue);
4847                 if (sp != NULL) {
4848                         sp->discard_rest = 1;
4849                         /*
4850                          * We may need to put a chunk on the queue that
4851                          * holds the TSN that would have been sent with the
4852                          * LAST bit.
4853                          */
4854                         if (chk == NULL) {
4855                                 /* Yep, we have to */
4856                                 sctp_alloc_a_chunk(stcb, chk);
4857                                 if (chk == NULL) {
4858                                         /*
4859                                          * we are hosed. All we can do is
4860                                          * nothing.. which will cause an
4861                                          * abort if the peer is paying
4862                                          * attention.
4863                                          */
4864                                         goto oh_well;
4865                                 }
4866                                 memset(chk, 0, sizeof(*chk));
4867                                 chk->rec.data.rcv_flags = 0;
4868                                 chk->sent = SCTP_FORWARD_TSN_SKIP;
4869                                 chk->asoc = &stcb->asoc;
4870                                 if (stcb->asoc.idata_supported == 0) {
4871                                         if (sp->sinfo_flags & SCTP_UNORDERED) {
4872                                                 chk->rec.data.mid = 0;
4873                                         } else {
4874                                                 chk->rec.data.mid = strq->next_mid_ordered;
4875                                         }
4876                                 } else {
4877                                         if (sp->sinfo_flags & SCTP_UNORDERED) {
4878                                                 chk->rec.data.mid = strq->next_mid_unordered;
4879                                         } else {
4880                                                 chk->rec.data.mid = strq->next_mid_ordered;
4881                                         }
4882                                 }
4883                                 chk->rec.data.sid = sp->sid;
4884                                 chk->rec.data.ppid = sp->ppid;
4885                                 chk->rec.data.context = sp->context;
4886                                 chk->flags = sp->act_flags;
4887                                 chk->whoTo = NULL;
4888                                 chk->rec.data.tsn = atomic_fetchadd_int(&stcb->asoc.sending_seq, 1);
4889                                 strq->chunks_on_queues++;
4890                                 TAILQ_INSERT_TAIL(&stcb->asoc.sent_queue, chk, sctp_next);
4891                                 stcb->asoc.sent_queue_cnt++;
4892                                 stcb->asoc.pr_sctp_cnt++;
4893                         }
4894                         chk->rec.data.rcv_flags |= SCTP_DATA_LAST_FRAG;
4895                         if (sp->sinfo_flags & SCTP_UNORDERED) {
4896                                 chk->rec.data.rcv_flags |= SCTP_DATA_UNORDERED;
4897                         }
4898                         if (stcb->asoc.idata_supported == 0) {
4899                                 if ((sp->sinfo_flags & SCTP_UNORDERED) == 0) {
4900                                         strq->next_mid_ordered++;
4901                                 }
4902                         } else {
4903                                 if (sp->sinfo_flags & SCTP_UNORDERED) {
4904                                         strq->next_mid_unordered++;
4905                                 } else {
4906                                         strq->next_mid_ordered++;
4907                                 }
4908                         }
4909         oh_well:
4910                         if (sp->data) {
4911                                 /*
4912                                  * Pull any data to free up the SB and allow
4913                                  * sender to "add more" while we will throw
4914                                  * away :-)
4915                                  */
4916                                 sctp_free_spbufspace(stcb, &stcb->asoc, sp);
4917                                 ret_sz += sp->length;
4918                                 do_wakeup_routine = 1;
4919                                 sp->some_taken = 1;
4920                                 sctp_m_freem(sp->data);
4921                                 sp->data = NULL;
4922                                 sp->tail_mbuf = NULL;
4923                                 sp->length = 0;
4924                         }
4925                 }
4926                 SCTP_TCB_SEND_UNLOCK(stcb);
4927         }
4928         if (do_wakeup_routine) {
4929 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4930                 struct socket *so;
4931
4932                 so = SCTP_INP_SO(stcb->sctp_ep);
4933                 if (!so_locked) {
4934                         atomic_add_int(&stcb->asoc.refcnt, 1);
4935                         SCTP_TCB_UNLOCK(stcb);
4936                         SCTP_SOCKET_LOCK(so, 1);
4937                         SCTP_TCB_LOCK(stcb);
4938                         atomic_subtract_int(&stcb->asoc.refcnt, 1);
4939                         if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
4940                                 /* assoc was freed while we were unlocked */
4941                                 SCTP_SOCKET_UNLOCK(so, 1);
4942                                 return (ret_sz);
4943                         }
4944                 }
4945 #endif
4946                 sctp_sowwakeup(stcb->sctp_ep, stcb->sctp_socket);
4947 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4948                 if (!so_locked) {
4949                         SCTP_SOCKET_UNLOCK(so, 1);
4950                 }
4951 #endif
4952         }
4953         return (ret_sz);
4954 }
4955
4956 /*
4957  * checks to see if the given address, sa, is one that is currently known by
4958  * the kernel note: can't distinguish the same address on multiple interfaces
4959  * and doesn't handle multiple addresses with different zone/scope id's note:
4960  * ifa_ifwithaddr() compares the entire sockaddr struct
4961  */
4962 struct sctp_ifa *
4963 sctp_find_ifa_in_ep(struct sctp_inpcb *inp, struct sockaddr *addr,
4964     int holds_lock)
4965 {
4966         struct sctp_laddr *laddr;
4967
4968         if (holds_lock == 0) {
4969                 SCTP_INP_RLOCK(inp);
4970         }
4971
4972         LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
4973                 if (laddr->ifa == NULL)
4974                         continue;
4975                 if (addr->sa_family != laddr->ifa->address.sa.sa_family)
4976                         continue;
4977 #ifdef INET
4978                 if (addr->sa_family == AF_INET) {
4979                         if (((struct sockaddr_in *)addr)->sin_addr.s_addr ==
4980                             laddr->ifa->address.sin.sin_addr.s_addr) {
4981                                 /* found him. */
4982                                 if (holds_lock == 0) {
4983                                         SCTP_INP_RUNLOCK(inp);
4984                                 }
4985                                 return (laddr->ifa);
4986                                 break;
4987                         }
4988                 }
4989 #endif
4990 #ifdef INET6
4991                 if (addr->sa_family == AF_INET6) {
4992                         if (SCTP6_ARE_ADDR_EQUAL((struct sockaddr_in6 *)addr,
4993                             &laddr->ifa->address.sin6)) {
4994                                 /* found him. */
4995                                 if (holds_lock == 0) {
4996                                         SCTP_INP_RUNLOCK(inp);
4997                                 }
4998                                 return (laddr->ifa);
4999                                 break;
5000                         }
5001                 }
5002 #endif
5003         }
5004         if (holds_lock == 0) {
5005                 SCTP_INP_RUNLOCK(inp);
5006         }
5007         return (NULL);
5008 }
5009
5010 uint32_t
5011 sctp_get_ifa_hash_val(struct sockaddr *addr)
5012 {
5013         switch (addr->sa_family) {
5014 #ifdef INET
5015         case AF_INET:
5016                 {
5017                         struct sockaddr_in *sin;
5018
5019                         sin = (struct sockaddr_in *)addr;
5020                         return (sin->sin_addr.s_addr ^ (sin->sin_addr.s_addr >> 16));
5021                 }
5022 #endif
5023 #ifdef INET6
5024         case AF_INET6:
5025                 {
5026                         struct sockaddr_in6 *sin6;
5027                         uint32_t hash_of_addr;
5028
5029                         sin6 = (struct sockaddr_in6 *)addr;
5030                         hash_of_addr = (sin6->sin6_addr.s6_addr32[0] +
5031                             sin6->sin6_addr.s6_addr32[1] +
5032                             sin6->sin6_addr.s6_addr32[2] +
5033                             sin6->sin6_addr.s6_addr32[3]);
5034                         hash_of_addr = (hash_of_addr ^ (hash_of_addr >> 16));
5035                         return (hash_of_addr);
5036                 }
5037 #endif
5038         default:
5039                 break;
5040         }
5041         return (0);
5042 }
5043
5044 struct sctp_ifa *
5045 sctp_find_ifa_by_addr(struct sockaddr *addr, uint32_t vrf_id, int holds_lock)
5046 {
5047         struct sctp_ifa *sctp_ifap;
5048         struct sctp_vrf *vrf;
5049         struct sctp_ifalist *hash_head;
5050         uint32_t hash_of_addr;
5051
5052         if (holds_lock == 0)
5053                 SCTP_IPI_ADDR_RLOCK();
5054
5055         vrf = sctp_find_vrf(vrf_id);
5056         if (vrf == NULL) {
5057                 if (holds_lock == 0)
5058                         SCTP_IPI_ADDR_RUNLOCK();
5059                 return (NULL);
5060         }
5061
5062         hash_of_addr = sctp_get_ifa_hash_val(addr);
5063
5064         hash_head = &vrf->vrf_addr_hash[(hash_of_addr & vrf->vrf_addr_hashmark)];
5065         if (hash_head == NULL) {
5066                 SCTP_PRINTF("hash_of_addr:%x mask:%x table:%x - ",
5067                     hash_of_addr, (uint32_t)vrf->vrf_addr_hashmark,
5068                     (uint32_t)(hash_of_addr & vrf->vrf_addr_hashmark));
5069                 sctp_print_address(addr);
5070                 SCTP_PRINTF("No such bucket for address\n");
5071                 if (holds_lock == 0)
5072                         SCTP_IPI_ADDR_RUNLOCK();
5073
5074                 return (NULL);
5075         }
5076         LIST_FOREACH(sctp_ifap, hash_head, next_bucket) {
5077                 if (addr->sa_family != sctp_ifap->address.sa.sa_family)
5078                         continue;
5079 #ifdef INET
5080                 if (addr->sa_family == AF_INET) {
5081                         if (((struct sockaddr_in *)addr)->sin_addr.s_addr ==
5082                             sctp_ifap->address.sin.sin_addr.s_addr) {
5083                                 /* found him. */
5084                                 if (holds_lock == 0)
5085                                         SCTP_IPI_ADDR_RUNLOCK();
5086                                 return (sctp_ifap);
5087                                 break;
5088                         }
5089                 }
5090 #endif
5091 #ifdef INET6
5092                 if (addr->sa_family == AF_INET6) {
5093                         if (SCTP6_ARE_ADDR_EQUAL((struct sockaddr_in6 *)addr,
5094                             &sctp_ifap->address.sin6)) {
5095                                 /* found him. */
5096                                 if (holds_lock == 0)
5097                                         SCTP_IPI_ADDR_RUNLOCK();
5098                                 return (sctp_ifap);
5099                                 break;
5100                         }
5101                 }
5102 #endif
5103         }
5104         if (holds_lock == 0)
5105                 SCTP_IPI_ADDR_RUNLOCK();
5106         return (NULL);
5107 }
5108
5109 static void
5110 sctp_user_rcvd(struct sctp_tcb *stcb, uint32_t *freed_so_far, int hold_rlock,
5111     uint32_t rwnd_req)
5112 {
5113         /* User pulled some data, do we need a rwnd update? */
5114         int r_unlocked = 0;
5115         uint32_t dif, rwnd;
5116         struct socket *so = NULL;
5117
5118         if (stcb == NULL)
5119                 return;
5120
5121         atomic_add_int(&stcb->asoc.refcnt, 1);
5122
5123         if ((SCTP_GET_STATE(stcb) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
5124             (stcb->asoc.state & (SCTP_STATE_ABOUT_TO_BE_FREED | SCTP_STATE_SHUTDOWN_RECEIVED))) {
5125                 /* Pre-check If we are freeing no update */
5126                 goto no_lock;
5127         }
5128         SCTP_INP_INCR_REF(stcb->sctp_ep);
5129         if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
5130             (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
5131                 goto out;
5132         }
5133         so = stcb->sctp_socket;
5134         if (so == NULL) {
5135                 goto out;
5136         }
5137         atomic_add_int(&stcb->freed_by_sorcv_sincelast, *freed_so_far);
5138         /* Have you have freed enough to look */
5139         *freed_so_far = 0;
5140         /* Yep, its worth a look and the lock overhead */
5141
5142         /* Figure out what the rwnd would be */
5143         rwnd = sctp_calc_rwnd(stcb, &stcb->asoc);
5144         if (rwnd >= stcb->asoc.my_last_reported_rwnd) {
5145                 dif = rwnd - stcb->asoc.my_last_reported_rwnd;
5146         } else {
5147                 dif = 0;
5148         }
5149         if (dif >= rwnd_req) {
5150                 if (hold_rlock) {
5151                         SCTP_INP_READ_UNLOCK(stcb->sctp_ep);
5152                         r_unlocked = 1;
5153                 }
5154                 if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
5155                         /*
5156                          * One last check before we allow the guy possibly
5157                          * to get in. There is a race, where the guy has not
5158                          * reached the gate. In that case
5159                          */
5160                         goto out;
5161                 }
5162                 SCTP_TCB_LOCK(stcb);
5163                 if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
5164                         /* No reports here */
5165                         SCTP_TCB_UNLOCK(stcb);
5166                         goto out;
5167                 }
5168                 SCTP_STAT_INCR(sctps_wu_sacks_sent);
5169                 sctp_send_sack(stcb, SCTP_SO_LOCKED);
5170
5171                 sctp_chunk_output(stcb->sctp_ep, stcb,
5172                     SCTP_OUTPUT_FROM_USR_RCVD, SCTP_SO_LOCKED);
5173                 /* make sure no timer is running */
5174                 sctp_timer_stop(SCTP_TIMER_TYPE_RECV, stcb->sctp_ep, stcb, NULL,
5175                     SCTP_FROM_SCTPUTIL + SCTP_LOC_6);
5176                 SCTP_TCB_UNLOCK(stcb);
5177         } else {
5178                 /* Update how much we have pending */
5179                 stcb->freed_by_sorcv_sincelast = dif;
5180         }
5181 out:
5182         if (so && r_unlocked && hold_rlock) {
5183                 SCTP_INP_READ_LOCK(stcb->sctp_ep);
5184         }
5185
5186         SCTP_INP_DECR_REF(stcb->sctp_ep);
5187 no_lock:
5188         atomic_add_int(&stcb->asoc.refcnt, -1);
5189         return;
5190 }
5191
5192 int
5193 sctp_sorecvmsg(struct socket *so,
5194     struct uio *uio,
5195     struct mbuf **mp,
5196     struct sockaddr *from,
5197     int fromlen,
5198     int *msg_flags,
5199     struct sctp_sndrcvinfo *sinfo,
5200     int filling_sinfo)
5201 {
5202         /*
5203          * MSG flags we will look at MSG_DONTWAIT - non-blocking IO.
5204          * MSG_PEEK - Look don't touch :-D (only valid with OUT mbuf copy
5205          * mp=NULL thus uio is the copy method to userland) MSG_WAITALL - ??
5206          * On the way out we may send out any combination of:
5207          * MSG_NOTIFICATION MSG_EOR
5208          *
5209          */
5210         struct sctp_inpcb *inp = NULL;
5211         ssize_t my_len = 0;
5212         ssize_t cp_len = 0;
5213         int error = 0;
5214         struct sctp_queued_to_read *control = NULL, *ctl = NULL, *nxt = NULL;
5215         struct mbuf *m = NULL;
5216         struct sctp_tcb *stcb = NULL;
5217         int wakeup_read_socket = 0;
5218         int freecnt_applied = 0;
5219         int out_flags = 0, in_flags = 0;
5220         int block_allowed = 1;
5221         uint32_t freed_so_far = 0;
5222         ssize_t copied_so_far = 0;
5223         int in_eeor_mode = 0;
5224         int no_rcv_needed = 0;
5225         uint32_t rwnd_req = 0;
5226         int hold_sblock = 0;
5227         int hold_rlock = 0;
5228         ssize_t slen = 0;
5229         uint32_t held_length = 0;
5230         int sockbuf_lock = 0;
5231
5232         if (uio == NULL) {
5233                 SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
5234                 return (EINVAL);
5235         }
5236
5237         if (msg_flags) {
5238                 in_flags = *msg_flags;
5239                 if (in_flags & MSG_PEEK)
5240                         SCTP_STAT_INCR(sctps_read_peeks);
5241         } else {
5242                 in_flags = 0;
5243         }
5244         slen = uio->uio_resid;
5245
5246         /* Pull in and set up our int flags */
5247         if (in_flags & MSG_OOB) {
5248                 /* Out of band's NOT supported */
5249                 return (EOPNOTSUPP);
5250         }
5251         if ((in_flags & MSG_PEEK) && (mp != NULL)) {
5252                 SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
5253                 return (EINVAL);
5254         }
5255         if ((in_flags & (MSG_DONTWAIT
5256             | MSG_NBIO
5257             )) ||
5258             SCTP_SO_IS_NBIO(so)) {
5259                 block_allowed = 0;
5260         }
5261         /* setup the endpoint */
5262         inp = (struct sctp_inpcb *)so->so_pcb;
5263         if (inp == NULL) {
5264                 SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTPUTIL, EFAULT);
5265                 return (EFAULT);
5266         }
5267         rwnd_req = (SCTP_SB_LIMIT_RCV(so) >> SCTP_RWND_HIWAT_SHIFT);
5268         /* Must be at least a MTU's worth */
5269         if (rwnd_req < SCTP_MIN_RWND)
5270                 rwnd_req = SCTP_MIN_RWND;
5271         in_eeor_mode = sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR);
5272         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_RECV_RWND_LOGGING_ENABLE) {
5273                 sctp_misc_ints(SCTP_SORECV_ENTER,
5274                     rwnd_req, in_eeor_mode, so->so_rcv.sb_cc, (uint32_t)uio->uio_resid);
5275         }
5276         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_RECV_RWND_LOGGING_ENABLE) {
5277                 sctp_misc_ints(SCTP_SORECV_ENTERPL,
5278                     rwnd_req, block_allowed, so->so_rcv.sb_cc, (uint32_t)uio->uio_resid);
5279         }
5280
5281
5282         error = sblock(&so->so_rcv, (block_allowed ? SBL_WAIT : 0));
5283         if (error) {
5284                 goto release_unlocked;
5285         }
5286         sockbuf_lock = 1;
5287 restart:
5288
5289
5290 restart_nosblocks:
5291         if (hold_sblock == 0) {
5292                 SOCKBUF_LOCK(&so->so_rcv);
5293                 hold_sblock = 1;
5294         }
5295         if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
5296             (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
5297                 goto out;
5298         }
5299         if ((so->so_rcv.sb_state & SBS_CANTRCVMORE) && (so->so_rcv.sb_cc == 0)) {
5300                 if (so->so_error) {
5301                         error = so->so_error;
5302                         if ((in_flags & MSG_PEEK) == 0)
5303                                 so->so_error = 0;
5304                         goto out;
5305                 } else {
5306                         if (so->so_rcv.sb_cc == 0) {
5307                                 /* indicate EOF */
5308                                 error = 0;
5309                                 goto out;
5310                         }
5311                 }
5312         }
5313         if (so->so_rcv.sb_cc <= held_length) {
5314                 if (so->so_error) {
5315                         error = so->so_error;
5316                         if ((in_flags & MSG_PEEK) == 0) {
5317                                 so->so_error = 0;
5318                         }
5319                         goto out;
5320                 }
5321                 if ((so->so_rcv.sb_cc == 0) &&
5322                     ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
5323                     (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL))) {
5324                         if ((inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) == 0) {
5325                                 /*
5326                                  * For active open side clear flags for
5327                                  * re-use passive open is blocked by
5328                                  * connect.
5329                                  */
5330                                 if (inp->sctp_flags & SCTP_PCB_FLAGS_WAS_ABORTED) {
5331                                         /*
5332                                          * You were aborted, passive side
5333                                          * always hits here
5334                                          */
5335                                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, ECONNRESET);
5336                                         error = ECONNRESET;
5337                                 }
5338                                 so->so_state &= ~(SS_ISCONNECTING |
5339                                     SS_ISDISCONNECTING |
5340                                     SS_ISCONFIRMING |
5341                                     SS_ISCONNECTED);
5342                                 if (error == 0) {
5343                                         if ((inp->sctp_flags & SCTP_PCB_FLAGS_WAS_CONNECTED) == 0) {
5344                                                 SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, ENOTCONN);
5345                                                 error = ENOTCONN;
5346                                         }
5347                                 }
5348                                 goto out;
5349                         }
5350                 }
5351                 if (block_allowed) {
5352                         error = sbwait(&so->so_rcv);
5353                         if (error) {
5354                                 goto out;
5355                         }
5356                         held_length = 0;
5357                         goto restart_nosblocks;
5358                 } else {
5359                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EWOULDBLOCK);
5360                         error = EWOULDBLOCK;
5361                         goto out;
5362                 }
5363         }
5364         if (hold_sblock == 1) {
5365                 SOCKBUF_UNLOCK(&so->so_rcv);
5366                 hold_sblock = 0;
5367         }
5368         /* we possibly have data we can read */
5369         /* sa_ignore FREED_MEMORY */
5370         control = TAILQ_FIRST(&inp->read_queue);
5371         if (control == NULL) {
5372                 /*
5373                  * This could be happening since the appender did the
5374                  * increment but as not yet did the tailq insert onto the
5375                  * read_queue
5376                  */
5377                 if (hold_rlock == 0) {
5378                         SCTP_INP_READ_LOCK(inp);
5379                 }
5380                 control = TAILQ_FIRST(&inp->read_queue);
5381                 if ((control == NULL) && (so->so_rcv.sb_cc != 0)) {
5382 #ifdef INVARIANTS
5383                         panic("Huh, its non zero and nothing on control?");
5384 #endif
5385                         so->so_rcv.sb_cc = 0;
5386                 }
5387                 SCTP_INP_READ_UNLOCK(inp);
5388                 hold_rlock = 0;
5389                 goto restart;
5390         }
5391
5392         if ((control->length == 0) &&
5393             (control->do_not_ref_stcb)) {
5394                 /*
5395                  * Clean up code for freeing assoc that left behind a
5396                  * pdapi.. maybe a peer in EEOR that just closed after
5397                  * sending and never indicated a EOR.
5398                  */
5399                 if (hold_rlock == 0) {
5400                         hold_rlock = 1;
5401                         SCTP_INP_READ_LOCK(inp);
5402                 }
5403                 control->held_length = 0;
5404                 if (control->data) {
5405                         /* Hmm there is data here .. fix */
5406                         struct mbuf *m_tmp;
5407                         int cnt = 0;
5408
5409                         m_tmp = control->data;
5410                         while (m_tmp) {
5411                                 cnt += SCTP_BUF_LEN(m_tmp);
5412                                 if (SCTP_BUF_NEXT(m_tmp) == NULL) {
5413                                         control->tail_mbuf = m_tmp;
5414                                         control->end_added = 1;
5415                                 }
5416                                 m_tmp = SCTP_BUF_NEXT(m_tmp);
5417                         }
5418                         control->length = cnt;
5419                 } else {
5420                         /* remove it */
5421                         TAILQ_REMOVE(&inp->read_queue, control, next);
5422                         /* Add back any hiddend data */
5423                         sctp_free_remote_addr(control->whoFrom);
5424                         sctp_free_a_readq(stcb, control);
5425                 }
5426                 if (hold_rlock) {
5427                         hold_rlock = 0;
5428                         SCTP_INP_READ_UNLOCK(inp);
5429                 }
5430                 goto restart;
5431         }
5432         if ((control->length == 0) &&
5433             (control->end_added == 1)) {
5434                 /*
5435                  * Do we also need to check for (control->pdapi_aborted ==
5436                  * 1)?
5437                  */
5438                 if (hold_rlock == 0) {
5439                         hold_rlock = 1;
5440                         SCTP_INP_READ_LOCK(inp);
5441                 }
5442                 TAILQ_REMOVE(&inp->read_queue, control, next);
5443                 if (control->data) {
5444 #ifdef INVARIANTS
5445                         panic("control->data not null but control->length == 0");
5446 #else
5447                         SCTP_PRINTF("Strange, data left in the control buffer. Cleaning up.\n");
5448                         sctp_m_freem(control->data);
5449                         control->data = NULL;
5450 #endif
5451                 }
5452                 if (control->aux_data) {
5453                         sctp_m_free(control->aux_data);
5454                         control->aux_data = NULL;
5455                 }
5456 #ifdef INVARIANTS
5457                 if (control->on_strm_q) {
5458                         panic("About to free ctl:%p so:%p and its in %d",
5459                             control, so, control->on_strm_q);
5460                 }
5461 #endif
5462                 sctp_free_remote_addr(control->whoFrom);
5463                 sctp_free_a_readq(stcb, control);
5464                 if (hold_rlock) {
5465                         hold_rlock = 0;
5466                         SCTP_INP_READ_UNLOCK(inp);
5467                 }
5468                 goto restart;
5469         }
5470         if (control->length == 0) {
5471                 if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE)) &&
5472                     (filling_sinfo)) {
5473                         /* find a more suitable one then this */
5474                         ctl = TAILQ_NEXT(control, next);
5475                         while (ctl) {
5476                                 if ((ctl->stcb != control->stcb) && (ctl->length) &&
5477                                     (ctl->some_taken ||
5478                                     (ctl->spec_flags & M_NOTIFICATION) ||
5479                                     ((ctl->do_not_ref_stcb == 0) &&
5480                                     (ctl->stcb->asoc.strmin[ctl->sinfo_stream].delivery_started == 0)))
5481                                     ) {
5482                                         /*-
5483                                          * If we have a different TCB next, and there is data
5484                                          * present. If we have already taken some (pdapi), OR we can
5485                                          * ref the tcb and no delivery as started on this stream, we
5486                                          * take it. Note we allow a notification on a different
5487                                          * assoc to be delivered..
5488                                          */
5489                                         control = ctl;
5490                                         goto found_one;
5491                                 } else if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS)) &&
5492                                             (ctl->length) &&
5493                                             ((ctl->some_taken) ||
5494                                             ((ctl->do_not_ref_stcb == 0) &&
5495                                             ((ctl->spec_flags & M_NOTIFICATION) == 0) &&
5496                                     (ctl->stcb->asoc.strmin[ctl->sinfo_stream].delivery_started == 0)))) {
5497                                         /*-
5498                                          * If we have the same tcb, and there is data present, and we
5499                                          * have the strm interleave feature present. Then if we have
5500                                          * taken some (pdapi) or we can refer to tht tcb AND we have
5501                                          * not started a delivery for this stream, we can take it.
5502                                          * Note we do NOT allow a notificaiton on the same assoc to
5503                                          * be delivered.
5504                                          */
5505                                         control = ctl;
5506                                         goto found_one;
5507                                 }
5508                                 ctl = TAILQ_NEXT(ctl, next);
5509                         }
5510                 }
5511                 /*
5512                  * if we reach here, not suitable replacement is available
5513                  * <or> fragment interleave is NOT on. So stuff the sb_cc
5514                  * into the our held count, and its time to sleep again.
5515                  */
5516                 held_length = so->so_rcv.sb_cc;
5517                 control->held_length = so->so_rcv.sb_cc;
5518                 goto restart;
5519         }
5520         /* Clear the held length since there is something to read */
5521         control->held_length = 0;
5522 found_one:
5523         /*
5524          * If we reach here, control has a some data for us to read off.
5525          * Note that stcb COULD be NULL.
5526          */
5527         if (hold_rlock == 0) {
5528                 hold_rlock = 1;
5529                 SCTP_INP_READ_LOCK(inp);
5530         }
5531         control->some_taken++;
5532         stcb = control->stcb;
5533         if (stcb) {
5534                 if ((control->do_not_ref_stcb == 0) &&
5535                     (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED)) {
5536                         if (freecnt_applied == 0)
5537                                 stcb = NULL;
5538                 } else if (control->do_not_ref_stcb == 0) {
5539                         /* you can't free it on me please */
5540                         /*
5541                          * The lock on the socket buffer protects us so the
5542                          * free code will stop. But since we used the
5543                          * socketbuf lock and the sender uses the tcb_lock
5544                          * to increment, we need to use the atomic add to
5545                          * the refcnt
5546                          */
5547                         if (freecnt_applied) {
5548 #ifdef INVARIANTS
5549                                 panic("refcnt already incremented");
5550 #else
5551                                 SCTP_PRINTF("refcnt already incremented?\n");
5552 #endif
5553                         } else {
5554                                 atomic_add_int(&stcb->asoc.refcnt, 1);
5555                                 freecnt_applied = 1;
5556                         }
5557                         /*
5558                          * Setup to remember how much we have not yet told
5559                          * the peer our rwnd has opened up. Note we grab the
5560                          * value from the tcb from last time. Note too that
5561                          * sack sending clears this when a sack is sent,
5562                          * which is fine. Once we hit the rwnd_req, we then
5563                          * will go to the sctp_user_rcvd() that will not
5564                          * lock until it KNOWs it MUST send a WUP-SACK.
5565                          */
5566                         freed_so_far = (uint32_t)stcb->freed_by_sorcv_sincelast;
5567                         stcb->freed_by_sorcv_sincelast = 0;
5568                 }
5569         }
5570         if (stcb &&
5571             ((control->spec_flags & M_NOTIFICATION) == 0) &&
5572             control->do_not_ref_stcb == 0) {
5573                 stcb->asoc.strmin[control->sinfo_stream].delivery_started = 1;
5574         }
5575
5576         /* First lets get off the sinfo and sockaddr info */
5577         if ((sinfo != NULL) && (filling_sinfo != 0)) {
5578                 sinfo->sinfo_stream = control->sinfo_stream;
5579                 sinfo->sinfo_ssn = (uint16_t)control->mid;
5580                 sinfo->sinfo_flags = control->sinfo_flags;
5581                 sinfo->sinfo_ppid = control->sinfo_ppid;
5582                 sinfo->sinfo_context = control->sinfo_context;
5583                 sinfo->sinfo_timetolive = control->sinfo_timetolive;
5584                 sinfo->sinfo_tsn = control->sinfo_tsn;
5585                 sinfo->sinfo_cumtsn = control->sinfo_cumtsn;
5586                 sinfo->sinfo_assoc_id = control->sinfo_assoc_id;
5587                 nxt = TAILQ_NEXT(control, next);
5588                 if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXT_RCVINFO) ||
5589                     sctp_is_feature_on(inp, SCTP_PCB_FLAGS_RECVNXTINFO)) {
5590                         struct sctp_extrcvinfo *s_extra;
5591
5592                         s_extra = (struct sctp_extrcvinfo *)sinfo;
5593                         if ((nxt) &&
5594                             (nxt->length)) {
5595                                 s_extra->serinfo_next_flags = SCTP_NEXT_MSG_AVAIL;
5596                                 if (nxt->sinfo_flags & SCTP_UNORDERED) {
5597                                         s_extra->serinfo_next_flags |= SCTP_NEXT_MSG_IS_UNORDERED;
5598                                 }
5599                                 if (nxt->spec_flags & M_NOTIFICATION) {
5600                                         s_extra->serinfo_next_flags |= SCTP_NEXT_MSG_IS_NOTIFICATION;
5601                                 }
5602                                 s_extra->serinfo_next_aid = nxt->sinfo_assoc_id;
5603                                 s_extra->serinfo_next_length = nxt->length;
5604                                 s_extra->serinfo_next_ppid = nxt->sinfo_ppid;
5605                                 s_extra->serinfo_next_stream = nxt->sinfo_stream;
5606                                 if (nxt->tail_mbuf != NULL) {
5607                                         if (nxt->end_added) {
5608                                                 s_extra->serinfo_next_flags |= SCTP_NEXT_MSG_ISCOMPLETE;
5609                                         }
5610                                 }
5611                         } else {
5612                                 /*
5613                                  * we explicitly 0 this, since the memcpy
5614                                  * got some other things beyond the older
5615                                  * sinfo_ that is on the control's structure
5616                                  * :-D
5617                                  */
5618                                 nxt = NULL;
5619                                 s_extra->serinfo_next_flags = SCTP_NO_NEXT_MSG;
5620                                 s_extra->serinfo_next_aid = 0;
5621                                 s_extra->serinfo_next_length = 0;
5622                                 s_extra->serinfo_next_ppid = 0;
5623                                 s_extra->serinfo_next_stream = 0;
5624                         }
5625                 }
5626                 /*
5627                  * update off the real current cum-ack, if we have an stcb.
5628                  */
5629                 if ((control->do_not_ref_stcb == 0) && stcb)
5630                         sinfo->sinfo_cumtsn = stcb->asoc.cumulative_tsn;
5631                 /*
5632                  * mask off the high bits, we keep the actual chunk bits in
5633                  * there.
5634                  */
5635                 sinfo->sinfo_flags &= 0x00ff;
5636                 if ((control->sinfo_flags >> 8) & SCTP_DATA_UNORDERED) {
5637                         sinfo->sinfo_flags |= SCTP_UNORDERED;
5638                 }
5639         }
5640 #ifdef SCTP_ASOCLOG_OF_TSNS
5641         {
5642                 int index, newindex;
5643                 struct sctp_pcbtsn_rlog *entry;
5644
5645                 do {
5646                         index = inp->readlog_index;
5647                         newindex = index + 1;
5648                         if (newindex >= SCTP_READ_LOG_SIZE) {
5649                                 newindex = 0;
5650                         }
5651                 } while (atomic_cmpset_int(&inp->readlog_index, index, newindex) == 0);
5652                 entry = &inp->readlog[index];
5653                 entry->vtag = control->sinfo_assoc_id;
5654                 entry->strm = control->sinfo_stream;
5655                 entry->seq = (uint16_t)control->mid;
5656                 entry->sz = control->length;
5657                 entry->flgs = control->sinfo_flags;
5658         }
5659 #endif
5660         if ((fromlen > 0) && (from != NULL)) {
5661                 union sctp_sockstore store;
5662                 size_t len;
5663
5664                 switch (control->whoFrom->ro._l_addr.sa.sa_family) {
5665 #ifdef INET6
5666                 case AF_INET6:
5667                         len = sizeof(struct sockaddr_in6);
5668                         store.sin6 = control->whoFrom->ro._l_addr.sin6;
5669                         store.sin6.sin6_port = control->port_from;
5670                         break;
5671 #endif
5672 #ifdef INET
5673                 case AF_INET:
5674 #ifdef INET6
5675                         if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NEEDS_MAPPED_V4)) {
5676                                 len = sizeof(struct sockaddr_in6);
5677                                 in6_sin_2_v4mapsin6(&control->whoFrom->ro._l_addr.sin,
5678                                     &store.sin6);
5679                                 store.sin6.sin6_port = control->port_from;
5680                         } else {
5681                                 len = sizeof(struct sockaddr_in);
5682                                 store.sin = control->whoFrom->ro._l_addr.sin;
5683                                 store.sin.sin_port = control->port_from;
5684                         }
5685 #else
5686                         len = sizeof(struct sockaddr_in);
5687                         store.sin = control->whoFrom->ro._l_addr.sin;
5688                         store.sin.sin_port = control->port_from;
5689 #endif
5690                         break;
5691 #endif
5692                 default:
5693                         len = 0;
5694                         break;
5695                 }
5696                 memcpy(from, &store, min((size_t)fromlen, len));
5697 #ifdef INET6
5698                 {
5699                         struct sockaddr_in6 lsa6, *from6;
5700
5701                         from6 = (struct sockaddr_in6 *)from;
5702                         sctp_recover_scope_mac(from6, (&lsa6));
5703                 }
5704 #endif
5705         }
5706         if (hold_rlock) {
5707                 SCTP_INP_READ_UNLOCK(inp);
5708                 hold_rlock = 0;
5709         }
5710         if (hold_sblock) {
5711                 SOCKBUF_UNLOCK(&so->so_rcv);
5712                 hold_sblock = 0;
5713         }
5714         /* now copy out what data we can */
5715         if (mp == NULL) {
5716                 /* copy out each mbuf in the chain up to length */
5717 get_more_data:
5718                 m = control->data;
5719                 while (m) {
5720                         /* Move out all we can */
5721                         cp_len = uio->uio_resid;
5722                         my_len = SCTP_BUF_LEN(m);
5723                         if (cp_len > my_len) {
5724                                 /* not enough in this buf */
5725                                 cp_len = my_len;
5726                         }
5727                         if (hold_rlock) {
5728                                 SCTP_INP_READ_UNLOCK(inp);
5729                                 hold_rlock = 0;
5730                         }
5731                         if (cp_len > 0)
5732                                 error = uiomove(mtod(m, char *), (int)cp_len, uio);
5733                         /* re-read */
5734                         if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
5735                                 goto release;
5736                         }
5737
5738                         if ((control->do_not_ref_stcb == 0) && stcb &&
5739                             stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
5740                                 no_rcv_needed = 1;
5741                         }
5742                         if (error) {
5743                                 /* error we are out of here */
5744                                 goto release;
5745                         }
5746                         SCTP_INP_READ_LOCK(inp);
5747                         hold_rlock = 1;
5748                         if (cp_len == SCTP_BUF_LEN(m)) {
5749                                 if ((SCTP_BUF_NEXT(m) == NULL) &&
5750                                     (control->end_added)) {
5751                                         out_flags |= MSG_EOR;
5752                                         if ((control->do_not_ref_stcb == 0) &&
5753                                             (control->stcb != NULL) &&
5754                                             ((control->spec_flags & M_NOTIFICATION) == 0))
5755                                                 control->stcb->asoc.strmin[control->sinfo_stream].delivery_started = 0;
5756                                 }
5757                                 if (control->spec_flags & M_NOTIFICATION) {
5758                                         out_flags |= MSG_NOTIFICATION;
5759                                 }
5760                                 /* we ate up the mbuf */
5761                                 if (in_flags & MSG_PEEK) {
5762                                         /* just looking */
5763                                         m = SCTP_BUF_NEXT(m);
5764                                         copied_so_far += cp_len;
5765                                 } else {
5766                                         /* dispose of the mbuf */
5767                                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
5768                                                 sctp_sblog(&so->so_rcv,
5769                                                     control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBFREE, SCTP_BUF_LEN(m));
5770                                         }
5771                                         sctp_sbfree(control, stcb, &so->so_rcv, m);
5772                                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
5773                                                 sctp_sblog(&so->so_rcv,
5774                                                     control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBRESULT, 0);
5775                                         }
5776                                         copied_so_far += cp_len;
5777                                         freed_so_far += (uint32_t)cp_len;
5778                                         freed_so_far += MSIZE;
5779                                         atomic_subtract_int(&control->length, cp_len);
5780                                         control->data = sctp_m_free(m);
5781                                         m = control->data;
5782                                         /*
5783                                          * been through it all, must hold sb
5784                                          * lock ok to null tail
5785                                          */
5786                                         if (control->data == NULL) {
5787 #ifdef INVARIANTS
5788                                                 if ((control->end_added == 0) ||
5789                                                     (TAILQ_NEXT(control, next) == NULL)) {
5790                                                         /*
5791                                                          * If the end is not
5792                                                          * added, OR the
5793                                                          * next is NOT null
5794                                                          * we MUST have the
5795                                                          * lock.
5796                                                          */
5797                                                         if (mtx_owned(&inp->inp_rdata_mtx) == 0) {
5798                                                                 panic("Hmm we don't own the lock?");
5799                                                         }
5800                                                 }
5801 #endif
5802                                                 control->tail_mbuf = NULL;
5803 #ifdef INVARIANTS
5804                                                 if ((control->end_added) && ((out_flags & MSG_EOR) == 0)) {
5805                                                         panic("end_added, nothing left and no MSG_EOR");
5806                                                 }
5807 #endif
5808                                         }
5809                                 }
5810                         } else {
5811                                 /* Do we need to trim the mbuf? */
5812                                 if (control->spec_flags & M_NOTIFICATION) {
5813                                         out_flags |= MSG_NOTIFICATION;
5814                                 }
5815                                 if ((in_flags & MSG_PEEK) == 0) {
5816                                         SCTP_BUF_RESV_UF(m, cp_len);
5817                                         SCTP_BUF_LEN(m) -= (int)cp_len;
5818                                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
5819                                                 sctp_sblog(&so->so_rcv, control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBFREE, (int)cp_len);
5820                                         }
5821                                         atomic_subtract_int(&so->so_rcv.sb_cc, cp_len);
5822                                         if ((control->do_not_ref_stcb == 0) &&
5823                                             stcb) {
5824                                                 atomic_subtract_int(&stcb->asoc.sb_cc, cp_len);
5825                                         }
5826                                         copied_so_far += cp_len;
5827                                         freed_so_far += (uint32_t)cp_len;
5828                                         freed_so_far += MSIZE;
5829                                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
5830                                                 sctp_sblog(&so->so_rcv, control->do_not_ref_stcb ? NULL : stcb,
5831                                                     SCTP_LOG_SBRESULT, 0);
5832                                         }
5833                                         atomic_subtract_int(&control->length, cp_len);
5834                                 } else {
5835                                         copied_so_far += cp_len;
5836                                 }
5837                         }
5838                         if ((out_flags & MSG_EOR) || (uio->uio_resid == 0)) {
5839                                 break;
5840                         }
5841                         if (((stcb) && (in_flags & MSG_PEEK) == 0) &&
5842                             (control->do_not_ref_stcb == 0) &&
5843                             (freed_so_far >= rwnd_req)) {
5844                                 sctp_user_rcvd(stcb, &freed_so_far, hold_rlock, rwnd_req);
5845                         }
5846                 }               /* end while(m) */
5847                 /*
5848                  * At this point we have looked at it all and we either have
5849                  * a MSG_EOR/or read all the user wants... <OR>
5850                  * control->length == 0.
5851                  */
5852                 if ((out_flags & MSG_EOR) && ((in_flags & MSG_PEEK) == 0)) {
5853                         /* we are done with this control */
5854                         if (control->length == 0) {
5855                                 if (control->data) {
5856 #ifdef INVARIANTS
5857                                         panic("control->data not null at read eor?");
5858 #else
5859                                         SCTP_PRINTF("Strange, data left in the control buffer .. invarients would panic?\n");
5860                                         sctp_m_freem(control->data);
5861                                         control->data = NULL;
5862 #endif
5863                                 }
5864                 done_with_control:
5865                                 if (hold_rlock == 0) {
5866                                         SCTP_INP_READ_LOCK(inp);
5867                                         hold_rlock = 1;
5868                                 }
5869                                 TAILQ_REMOVE(&inp->read_queue, control, next);
5870                                 /* Add back any hiddend data */
5871                                 if (control->held_length) {
5872                                         held_length = 0;
5873                                         control->held_length = 0;
5874                                         wakeup_read_socket = 1;
5875                                 }
5876                                 if (control->aux_data) {
5877                                         sctp_m_free(control->aux_data);
5878                                         control->aux_data = NULL;
5879                                 }
5880                                 no_rcv_needed = control->do_not_ref_stcb;
5881                                 sctp_free_remote_addr(control->whoFrom);
5882                                 control->data = NULL;
5883 #ifdef INVARIANTS
5884                                 if (control->on_strm_q) {
5885                                         panic("About to free ctl:%p so:%p and its in %d",
5886                                             control, so, control->on_strm_q);
5887                                 }
5888 #endif
5889                                 sctp_free_a_readq(stcb, control);
5890                                 control = NULL;
5891                                 if ((freed_so_far >= rwnd_req) &&
5892                                     (no_rcv_needed == 0))
5893                                         sctp_user_rcvd(stcb, &freed_so_far, hold_rlock, rwnd_req);
5894
5895                         } else {
5896                                 /*
5897                                  * The user did not read all of this
5898                                  * message, turn off the returned MSG_EOR
5899                                  * since we are leaving more behind on the
5900                                  * control to read.
5901                                  */
5902 #ifdef INVARIANTS
5903                                 if (control->end_added &&
5904                                     (control->data == NULL) &&
5905                                     (control->tail_mbuf == NULL)) {
5906                                         panic("Gak, control->length is corrupt?");
5907                                 }
5908 #endif
5909                                 no_rcv_needed = control->do_not_ref_stcb;
5910                                 out_flags &= ~MSG_EOR;
5911                         }
5912                 }
5913                 if (out_flags & MSG_EOR) {
5914                         goto release;
5915                 }
5916                 if ((uio->uio_resid == 0) ||
5917                     ((in_eeor_mode) &&
5918                     (copied_so_far >= (uint32_t)max(so->so_rcv.sb_lowat, 1)))) {
5919                         goto release;
5920                 }
5921                 /*
5922                  * If I hit here the receiver wants more and this message is
5923                  * NOT done (pd-api). So two questions. Can we block? if not
5924                  * we are done. Did the user NOT set MSG_WAITALL?
5925                  */
5926                 if (block_allowed == 0) {
5927                         goto release;
5928                 }
5929                 /*
5930                  * We need to wait for more data a few things: - We don't
5931                  * sbunlock() so we don't get someone else reading. - We
5932                  * must be sure to account for the case where what is added
5933                  * is NOT to our control when we wakeup.
5934                  */
5935
5936                 /*
5937                  * Do we need to tell the transport a rwnd update might be
5938                  * needed before we go to sleep?
5939                  */
5940                 if (((stcb) && (in_flags & MSG_PEEK) == 0) &&
5941                     ((freed_so_far >= rwnd_req) &&
5942                     (control->do_not_ref_stcb == 0) &&
5943                     (no_rcv_needed == 0))) {
5944                         sctp_user_rcvd(stcb, &freed_so_far, hold_rlock, rwnd_req);
5945                 }
5946 wait_some_more:
5947                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
5948                         goto release;
5949                 }
5950
5951                 if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)
5952                         goto release;
5953
5954                 if (hold_rlock == 1) {
5955                         SCTP_INP_READ_UNLOCK(inp);
5956                         hold_rlock = 0;
5957                 }
5958                 if (hold_sblock == 0) {
5959                         SOCKBUF_LOCK(&so->so_rcv);
5960                         hold_sblock = 1;
5961                 }
5962                 if ((copied_so_far) && (control->length == 0) &&
5963                     (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE))) {
5964                         goto release;
5965                 }
5966                 if (so->so_rcv.sb_cc <= control->held_length) {
5967                         error = sbwait(&so->so_rcv);
5968                         if (error) {
5969                                 goto release;
5970                         }
5971                         control->held_length = 0;
5972                 }
5973                 if (hold_sblock) {
5974                         SOCKBUF_UNLOCK(&so->so_rcv);
5975                         hold_sblock = 0;
5976                 }
5977                 if (control->length == 0) {
5978                         /* still nothing here */
5979                         if (control->end_added == 1) {
5980                                 /* he aborted, or is done i.e.did a shutdown */
5981                                 out_flags |= MSG_EOR;
5982                                 if (control->pdapi_aborted) {
5983                                         if ((control->do_not_ref_stcb == 0) && ((control->spec_flags & M_NOTIFICATION) == 0))
5984                                                 control->stcb->asoc.strmin[control->sinfo_stream].delivery_started = 0;
5985
5986                                         out_flags |= MSG_TRUNC;
5987                                 } else {
5988                                         if ((control->do_not_ref_stcb == 0) && ((control->spec_flags & M_NOTIFICATION) == 0))
5989                                                 control->stcb->asoc.strmin[control->sinfo_stream].delivery_started = 0;
5990                                 }
5991                                 goto done_with_control;
5992                         }
5993                         if (so->so_rcv.sb_cc > held_length) {
5994                                 control->held_length = so->so_rcv.sb_cc;
5995                                 held_length = 0;
5996                         }
5997                         goto wait_some_more;
5998                 } else if (control->data == NULL) {
5999                         /*
6000                          * we must re-sync since data is probably being
6001                          * added
6002                          */
6003                         SCTP_INP_READ_LOCK(inp);
6004                         if ((control->length > 0) && (control->data == NULL)) {
6005                                 /*
6006                                  * big trouble.. we have the lock and its
6007                                  * corrupt?
6008                                  */
6009 #ifdef INVARIANTS
6010                                 panic("Impossible data==NULL length !=0");
6011 #endif
6012                                 out_flags |= MSG_EOR;
6013                                 out_flags |= MSG_TRUNC;
6014                                 control->length = 0;
6015                                 SCTP_INP_READ_UNLOCK(inp);
6016                                 goto done_with_control;
6017                         }
6018                         SCTP_INP_READ_UNLOCK(inp);
6019                         /* We will fall around to get more data */
6020                 }
6021                 goto get_more_data;
6022         } else {
6023                 /*-
6024                  * Give caller back the mbuf chain,
6025                  * store in uio_resid the length
6026                  */
6027                 wakeup_read_socket = 0;
6028                 if ((control->end_added == 0) ||
6029                     (TAILQ_NEXT(control, next) == NULL)) {
6030                         /* Need to get rlock */
6031                         if (hold_rlock == 0) {
6032                                 SCTP_INP_READ_LOCK(inp);
6033                                 hold_rlock = 1;
6034                         }
6035                 }
6036                 if (control->end_added) {
6037                         out_flags |= MSG_EOR;
6038                         if ((control->do_not_ref_stcb == 0) &&
6039                             (control->stcb != NULL) &&
6040                             ((control->spec_flags & M_NOTIFICATION) == 0))
6041                                 control->stcb->asoc.strmin[control->sinfo_stream].delivery_started = 0;
6042                 }
6043                 if (control->spec_flags & M_NOTIFICATION) {
6044                         out_flags |= MSG_NOTIFICATION;
6045                 }
6046                 uio->uio_resid = control->length;
6047                 *mp = control->data;
6048                 m = control->data;
6049                 while (m) {
6050                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
6051                                 sctp_sblog(&so->so_rcv,
6052                                     control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBFREE, SCTP_BUF_LEN(m));
6053                         }
6054                         sctp_sbfree(control, stcb, &so->so_rcv, m);
6055                         freed_so_far += (uint32_t)SCTP_BUF_LEN(m);
6056                         freed_so_far += MSIZE;
6057                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_SB_LOGGING_ENABLE) {
6058                                 sctp_sblog(&so->so_rcv,
6059                                     control->do_not_ref_stcb ? NULL : stcb, SCTP_LOG_SBRESULT, 0);
6060                         }
6061                         m = SCTP_BUF_NEXT(m);
6062                 }
6063                 control->data = control->tail_mbuf = NULL;
6064                 control->length = 0;
6065                 if (out_flags & MSG_EOR) {
6066                         /* Done with this control */
6067                         goto done_with_control;
6068                 }
6069         }
6070 release:
6071         if (hold_rlock == 1) {
6072                 SCTP_INP_READ_UNLOCK(inp);
6073                 hold_rlock = 0;
6074         }
6075         if (hold_sblock == 1) {
6076                 SOCKBUF_UNLOCK(&so->so_rcv);
6077                 hold_sblock = 0;
6078         }
6079
6080         sbunlock(&so->so_rcv);
6081         sockbuf_lock = 0;
6082
6083 release_unlocked:
6084         if (hold_sblock) {
6085                 SOCKBUF_UNLOCK(&so->so_rcv);
6086                 hold_sblock = 0;
6087         }
6088         if ((stcb) && (in_flags & MSG_PEEK) == 0) {
6089                 if ((freed_so_far >= rwnd_req) &&
6090                     (control && (control->do_not_ref_stcb == 0)) &&
6091                     (no_rcv_needed == 0))
6092                         sctp_user_rcvd(stcb, &freed_so_far, hold_rlock, rwnd_req);
6093         }
6094 out:
6095         if (msg_flags) {
6096                 *msg_flags = out_flags;
6097         }
6098         if (((out_flags & MSG_EOR) == 0) &&
6099             ((in_flags & MSG_PEEK) == 0) &&
6100             (sinfo) &&
6101             (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXT_RCVINFO) ||
6102             sctp_is_feature_on(inp, SCTP_PCB_FLAGS_RECVNXTINFO))) {
6103                 struct sctp_extrcvinfo *s_extra;
6104
6105                 s_extra = (struct sctp_extrcvinfo *)sinfo;
6106                 s_extra->serinfo_next_flags = SCTP_NO_NEXT_MSG;
6107         }
6108         if (hold_rlock == 1) {
6109                 SCTP_INP_READ_UNLOCK(inp);
6110         }
6111         if (hold_sblock) {
6112                 SOCKBUF_UNLOCK(&so->so_rcv);
6113         }
6114         if (sockbuf_lock) {
6115                 sbunlock(&so->so_rcv);
6116         }
6117
6118         if (freecnt_applied) {
6119                 /*
6120                  * The lock on the socket buffer protects us so the free
6121                  * code will stop. But since we used the socketbuf lock and
6122                  * the sender uses the tcb_lock to increment, we need to use
6123                  * the atomic add to the refcnt.
6124                  */
6125                 if (stcb == NULL) {
6126 #ifdef INVARIANTS
6127                         panic("stcb for refcnt has gone NULL?");
6128                         goto stage_left;
6129 #else
6130                         goto stage_left;
6131 #endif
6132                 }
6133                 /* Save the value back for next time */
6134                 stcb->freed_by_sorcv_sincelast = freed_so_far;
6135                 atomic_add_int(&stcb->asoc.refcnt, -1);
6136         }
6137         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_RECV_RWND_LOGGING_ENABLE) {
6138                 if (stcb) {
6139                         sctp_misc_ints(SCTP_SORECV_DONE,
6140                             freed_so_far,
6141                             (uint32_t)((uio) ? (slen - uio->uio_resid) : slen),
6142                             stcb->asoc.my_rwnd,
6143                             so->so_rcv.sb_cc);
6144                 } else {
6145                         sctp_misc_ints(SCTP_SORECV_DONE,
6146                             freed_so_far,
6147                             (uint32_t)((uio) ? (slen - uio->uio_resid) : slen),
6148                             0,
6149                             so->so_rcv.sb_cc);
6150                 }
6151         }
6152 stage_left:
6153         if (wakeup_read_socket) {
6154                 sctp_sorwakeup(inp, so);
6155         }
6156         return (error);
6157 }
6158
6159
6160 #ifdef SCTP_MBUF_LOGGING
6161 struct mbuf *
6162 sctp_m_free(struct mbuf *m)
6163 {
6164         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
6165                 sctp_log_mb(m, SCTP_MBUF_IFREE);
6166         }
6167         return (m_free(m));
6168 }
6169
6170 void
6171 sctp_m_freem(struct mbuf *mb)
6172 {
6173         while (mb != NULL)
6174                 mb = sctp_m_free(mb);
6175 }
6176
6177 #endif
6178
6179 int
6180 sctp_dynamic_set_primary(struct sockaddr *sa, uint32_t vrf_id)
6181 {
6182         /*
6183          * Given a local address. For all associations that holds the
6184          * address, request a peer-set-primary.
6185          */
6186         struct sctp_ifa *ifa;
6187         struct sctp_laddr *wi;
6188
6189         ifa = sctp_find_ifa_by_addr(sa, vrf_id, 0);
6190         if (ifa == NULL) {
6191                 SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTPUTIL, EADDRNOTAVAIL);
6192                 return (EADDRNOTAVAIL);
6193         }
6194         /*
6195          * Now that we have the ifa we must awaken the iterator with this
6196          * message.
6197          */
6198         wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
6199         if (wi == NULL) {
6200                 SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTPUTIL, ENOMEM);
6201                 return (ENOMEM);
6202         }
6203         /* Now incr the count and int wi structure */
6204         SCTP_INCR_LADDR_COUNT();
6205         memset(wi, 0, sizeof(*wi));
6206         (void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
6207         wi->ifa = ifa;
6208         wi->action = SCTP_SET_PRIM_ADDR;
6209         atomic_add_int(&ifa->refcount, 1);
6210
6211         /* Now add it to the work queue */
6212         SCTP_WQ_ADDR_LOCK();
6213         /*
6214          * Should this really be a tailq? As it is we will process the
6215          * newest first :-0
6216          */
6217         LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
6218         sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
6219             (struct sctp_inpcb *)NULL,
6220             (struct sctp_tcb *)NULL,
6221             (struct sctp_nets *)NULL);
6222         SCTP_WQ_ADDR_UNLOCK();
6223         return (0);
6224 }
6225
6226
6227 int
6228 sctp_soreceive(struct socket *so,
6229     struct sockaddr **psa,
6230     struct uio *uio,
6231     struct mbuf **mp0,
6232     struct mbuf **controlp,
6233     int *flagsp)
6234 {
6235         int error, fromlen;
6236         uint8_t sockbuf[256];
6237         struct sockaddr *from;
6238         struct sctp_extrcvinfo sinfo;
6239         int filling_sinfo = 1;
6240         int flags;
6241         struct sctp_inpcb *inp;
6242
6243         inp = (struct sctp_inpcb *)so->so_pcb;
6244         /* pickup the assoc we are reading from */
6245         if (inp == NULL) {
6246                 SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6247                 return (EINVAL);
6248         }
6249         if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_RECVDATAIOEVNT) &&
6250             sctp_is_feature_off(inp, SCTP_PCB_FLAGS_RECVRCVINFO) &&
6251             sctp_is_feature_off(inp, SCTP_PCB_FLAGS_RECVNXTINFO)) ||
6252             (controlp == NULL)) {
6253                 /* user does not want the sndrcv ctl */
6254                 filling_sinfo = 0;
6255         }
6256         if (psa) {
6257                 from = (struct sockaddr *)sockbuf;
6258                 fromlen = sizeof(sockbuf);
6259                 from->sa_len = 0;
6260         } else {
6261                 from = NULL;
6262                 fromlen = 0;
6263         }
6264
6265         if (filling_sinfo) {
6266                 memset(&sinfo, 0, sizeof(struct sctp_extrcvinfo));
6267         }
6268         if (flagsp != NULL) {
6269                 flags = *flagsp;
6270         } else {
6271                 flags = 0;
6272         }
6273         error = sctp_sorecvmsg(so, uio, mp0, from, fromlen, &flags,
6274             (struct sctp_sndrcvinfo *)&sinfo, filling_sinfo);
6275         if (flagsp != NULL) {
6276                 *flagsp = flags;
6277         }
6278         if (controlp != NULL) {
6279                 /* copy back the sinfo in a CMSG format */
6280                 if (filling_sinfo && ((flags & MSG_NOTIFICATION) == 0)) {
6281                         *controlp = sctp_build_ctl_nchunk(inp,
6282                             (struct sctp_sndrcvinfo *)&sinfo);
6283                 } else {
6284                         *controlp = NULL;
6285                 }
6286         }
6287         if (psa) {
6288                 /* copy back the address info */
6289                 if (from && from->sa_len) {
6290                         *psa = sodupsockaddr(from, M_NOWAIT);
6291                 } else {
6292                         *psa = NULL;
6293                 }
6294         }
6295         return (error);
6296 }
6297
6298
6299
6300
6301
6302 int
6303 sctp_connectx_helper_add(struct sctp_tcb *stcb, struct sockaddr *addr,
6304     int totaddr, int *error)
6305 {
6306         int added = 0;
6307         int i;
6308         struct sctp_inpcb *inp;
6309         struct sockaddr *sa;
6310         size_t incr = 0;
6311 #ifdef INET
6312         struct sockaddr_in *sin;
6313 #endif
6314 #ifdef INET6
6315         struct sockaddr_in6 *sin6;
6316 #endif
6317
6318         sa = addr;
6319         inp = stcb->sctp_ep;
6320         *error = 0;
6321         for (i = 0; i < totaddr; i++) {
6322                 switch (sa->sa_family) {
6323 #ifdef INET
6324                 case AF_INET:
6325                         incr = sizeof(struct sockaddr_in);
6326                         sin = (struct sockaddr_in *)sa;
6327                         if ((sin->sin_addr.s_addr == INADDR_ANY) ||
6328                             (sin->sin_addr.s_addr == INADDR_BROADCAST) ||
6329                             IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
6330                                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6331                                 (void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC,
6332                                     SCTP_FROM_SCTPUTIL + SCTP_LOC_7);
6333                                 *error = EINVAL;
6334                                 goto out_now;
6335                         }
6336                         if (sctp_add_remote_addr(stcb, sa, NULL, stcb->asoc.port,
6337                             SCTP_DONOT_SETSCOPE,
6338                             SCTP_ADDR_IS_CONFIRMED)) {
6339                                 /* assoc gone no un-lock */
6340                                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, ENOBUFS);
6341                                 (void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC,
6342                                     SCTP_FROM_SCTPUTIL + SCTP_LOC_8);
6343                                 *error = ENOBUFS;
6344                                 goto out_now;
6345                         }
6346                         added++;
6347                         break;
6348 #endif
6349 #ifdef INET6
6350                 case AF_INET6:
6351                         incr = sizeof(struct sockaddr_in6);
6352                         sin6 = (struct sockaddr_in6 *)sa;
6353                         if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
6354                             IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
6355                                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6356                                 (void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC,
6357                                     SCTP_FROM_SCTPUTIL + SCTP_LOC_9);
6358                                 *error = EINVAL;
6359                                 goto out_now;
6360                         }
6361                         if (sctp_add_remote_addr(stcb, sa, NULL, stcb->asoc.port,
6362                             SCTP_DONOT_SETSCOPE,
6363                             SCTP_ADDR_IS_CONFIRMED)) {
6364                                 /* assoc gone no un-lock */
6365                                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTPUTIL, ENOBUFS);
6366                                 (void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC,
6367                                     SCTP_FROM_SCTPUTIL + SCTP_LOC_10);
6368                                 *error = ENOBUFS;
6369                                 goto out_now;
6370                         }
6371                         added++;
6372                         break;
6373 #endif
6374                 default:
6375                         break;
6376                 }
6377                 sa = (struct sockaddr *)((caddr_t)sa + incr);
6378         }
6379 out_now:
6380         return (added);
6381 }
6382
6383 int
6384 sctp_connectx_helper_find(struct sctp_inpcb *inp, struct sockaddr *addr,
6385     unsigned int totaddr,
6386     unsigned int *num_v4, unsigned int *num_v6,
6387     unsigned int limit)
6388 {
6389         struct sockaddr *sa;
6390         struct sctp_tcb *stcb;
6391         unsigned int incr, at, i;
6392
6393         at = 0;
6394         sa = addr;
6395         *num_v6 = *num_v4 = 0;
6396         /* account and validate addresses */
6397         if (totaddr == 0) {
6398                 return (EINVAL);
6399         }
6400         for (i = 0; i < totaddr; i++) {
6401                 if (at + sizeof(struct sockaddr) > limit) {
6402                         return (EINVAL);
6403                 }
6404                 switch (sa->sa_family) {
6405 #ifdef INET
6406                 case AF_INET:
6407                         incr = (unsigned int)sizeof(struct sockaddr_in);
6408                         if (sa->sa_len != incr) {
6409                                 return (EINVAL);
6410                         }
6411                         (*num_v4) += 1;
6412                         break;
6413 #endif
6414 #ifdef INET6
6415                 case AF_INET6:
6416                         {
6417                                 struct sockaddr_in6 *sin6;
6418
6419                                 sin6 = (struct sockaddr_in6 *)sa;
6420                                 if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6421                                         /* Must be non-mapped for connectx */
6422                                         return (EINVAL);
6423                                 }
6424                                 incr = (unsigned int)sizeof(struct sockaddr_in6);
6425                                 if (sa->sa_len != incr) {
6426                                         return (EINVAL);
6427                                 }
6428                                 (*num_v6) += 1;
6429                                 break;
6430                         }
6431 #endif
6432                 default:
6433                         return (EINVAL);
6434                 }
6435                 if ((at + incr) > limit) {
6436                         return (EINVAL);
6437                 }
6438                 SCTP_INP_INCR_REF(inp);
6439                 stcb = sctp_findassociation_ep_addr(&inp, sa, NULL, NULL, NULL);
6440                 if (stcb != NULL) {
6441                         SCTP_TCB_UNLOCK(stcb);
6442                         return (EALREADY);
6443                 } else {
6444                         SCTP_INP_DECR_REF(inp);
6445                 }
6446                 at += incr;
6447                 sa = (struct sockaddr *)((caddr_t)sa + incr);
6448         }
6449         return (0);
6450 }
6451
6452 /*
6453  * sctp_bindx(ADD) for one address.
6454  * assumes all arguments are valid/checked by caller.
6455  */
6456 void
6457 sctp_bindx_add_address(struct socket *so, struct sctp_inpcb *inp,
6458     struct sockaddr *sa, sctp_assoc_t assoc_id,
6459     uint32_t vrf_id, int *error, void *p)
6460 {
6461         struct sockaddr *addr_touse;
6462 #if defined(INET) && defined(INET6)
6463         struct sockaddr_in sin;
6464 #endif
6465
6466         /* see if we're bound all already! */
6467         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
6468                 SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6469                 *error = EINVAL;
6470                 return;
6471         }
6472         addr_touse = sa;
6473 #ifdef INET6
6474         if (sa->sa_family == AF_INET6) {
6475 #ifdef INET
6476                 struct sockaddr_in6 *sin6;
6477
6478 #endif
6479                 if (sa->sa_len != sizeof(struct sockaddr_in6)) {
6480                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6481                         *error = EINVAL;
6482                         return;
6483                 }
6484                 if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) {
6485                         /* can only bind v6 on PF_INET6 sockets */
6486                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6487                         *error = EINVAL;
6488                         return;
6489                 }
6490 #ifdef INET
6491                 sin6 = (struct sockaddr_in6 *)addr_touse;
6492                 if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6493                         if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
6494                             SCTP_IPV6_V6ONLY(inp)) {
6495                                 /* can't bind v4-mapped on PF_INET sockets */
6496                                 SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6497                                 *error = EINVAL;
6498                                 return;
6499                         }
6500                         in6_sin6_2_sin(&sin, sin6);
6501                         addr_touse = (struct sockaddr *)&sin;
6502                 }
6503 #endif
6504         }
6505 #endif
6506 #ifdef INET
6507         if (sa->sa_family == AF_INET) {
6508                 if (sa->sa_len != sizeof(struct sockaddr_in)) {
6509                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6510                         *error = EINVAL;
6511                         return;
6512                 }
6513                 if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
6514                     SCTP_IPV6_V6ONLY(inp)) {
6515                         /* can't bind v4 on PF_INET sockets */
6516                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6517                         *error = EINVAL;
6518                         return;
6519                 }
6520         }
6521 #endif
6522         if (inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) {
6523                 if (p == NULL) {
6524                         /* Can't get proc for Net/Open BSD */
6525                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6526                         *error = EINVAL;
6527                         return;
6528                 }
6529                 *error = sctp_inpcb_bind(so, addr_touse, NULL, p);
6530                 return;
6531         }
6532         /*
6533          * No locks required here since bind and mgmt_ep_sa all do their own
6534          * locking. If we do something for the FIX: below we may need to
6535          * lock in that case.
6536          */
6537         if (assoc_id == 0) {
6538                 /* add the address */
6539                 struct sctp_inpcb *lep;
6540                 struct sockaddr_in *lsin = (struct sockaddr_in *)addr_touse;
6541
6542                 /* validate the incoming port */
6543                 if ((lsin->sin_port != 0) &&
6544                     (lsin->sin_port != inp->sctp_lport)) {
6545                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6546                         *error = EINVAL;
6547                         return;
6548                 } else {
6549                         /* user specified 0 port, set it to existing port */
6550                         lsin->sin_port = inp->sctp_lport;
6551                 }
6552
6553                 lep = sctp_pcb_findep(addr_touse, 1, 0, vrf_id);
6554                 if (lep != NULL) {
6555                         /*
6556                          * We must decrement the refcount since we have the
6557                          * ep already and are binding. No remove going on
6558                          * here.
6559                          */
6560                         SCTP_INP_DECR_REF(lep);
6561                 }
6562                 if (lep == inp) {
6563                         /* already bound to it.. ok */
6564                         return;
6565                 } else if (lep == NULL) {
6566                         ((struct sockaddr_in *)addr_touse)->sin_port = 0;
6567                         *error = sctp_addr_mgmt_ep_sa(inp, addr_touse,
6568                             SCTP_ADD_IP_ADDRESS,
6569                             vrf_id, NULL);
6570                 } else {
6571                         *error = EADDRINUSE;
6572                 }
6573                 if (*error)
6574                         return;
6575         } else {
6576                 /*
6577                  * FIX: decide whether we allow assoc based bindx
6578                  */
6579         }
6580 }
6581
6582 /*
6583  * sctp_bindx(DELETE) for one address.
6584  * assumes all arguments are valid/checked by caller.
6585  */
6586 void
6587 sctp_bindx_delete_address(struct sctp_inpcb *inp,
6588     struct sockaddr *sa, sctp_assoc_t assoc_id,
6589     uint32_t vrf_id, int *error)
6590 {
6591         struct sockaddr *addr_touse;
6592 #if defined(INET) && defined(INET6)
6593         struct sockaddr_in sin;
6594 #endif
6595
6596         /* see if we're bound all already! */
6597         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
6598                 SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6599                 *error = EINVAL;
6600                 return;
6601         }
6602         addr_touse = sa;
6603 #ifdef INET6
6604         if (sa->sa_family == AF_INET6) {
6605 #ifdef INET
6606                 struct sockaddr_in6 *sin6;
6607 #endif
6608
6609                 if (sa->sa_len != sizeof(struct sockaddr_in6)) {
6610                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6611                         *error = EINVAL;
6612                         return;
6613                 }
6614                 if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) {
6615                         /* can only bind v6 on PF_INET6 sockets */
6616                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6617                         *error = EINVAL;
6618                         return;
6619                 }
6620 #ifdef INET
6621                 sin6 = (struct sockaddr_in6 *)addr_touse;
6622                 if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6623                         if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
6624                             SCTP_IPV6_V6ONLY(inp)) {
6625                                 /* can't bind mapped-v4 on PF_INET sockets */
6626                                 SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6627                                 *error = EINVAL;
6628                                 return;
6629                         }
6630                         in6_sin6_2_sin(&sin, sin6);
6631                         addr_touse = (struct sockaddr *)&sin;
6632                 }
6633 #endif
6634         }
6635 #endif
6636 #ifdef INET
6637         if (sa->sa_family == AF_INET) {
6638                 if (sa->sa_len != sizeof(struct sockaddr_in)) {
6639                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6640                         *error = EINVAL;
6641                         return;
6642                 }
6643                 if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
6644                     SCTP_IPV6_V6ONLY(inp)) {
6645                         /* can't bind v4 on PF_INET sockets */
6646                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTPUTIL, EINVAL);
6647                         *error = EINVAL;
6648                         return;
6649                 }
6650         }
6651 #endif
6652         /*
6653          * No lock required mgmt_ep_sa does its own locking. If the FIX:
6654          * below is ever changed we may need to lock before calling
6655          * association level binding.
6656          */
6657         if (assoc_id == 0) {
6658                 /* delete the address */
6659                 *error = sctp_addr_mgmt_ep_sa(inp, addr_touse,
6660                     SCTP_DEL_IP_ADDRESS,
6661                     vrf_id, NULL);
6662         } else {
6663                 /*
6664                  * FIX: decide whether we allow assoc based bindx
6665                  */
6666         }
6667 }
6668
6669 /*
6670  * returns the valid local address count for an assoc, taking into account
6671  * all scoping rules
6672  */
6673 int
6674 sctp_local_addr_count(struct sctp_tcb *stcb)
6675 {
6676         int loopback_scope;
6677 #if defined(INET)
6678         int ipv4_local_scope, ipv4_addr_legal;
6679 #endif
6680 #if defined (INET6)
6681         int local_scope, site_scope, ipv6_addr_legal;
6682 #endif
6683         struct sctp_vrf *vrf;
6684         struct sctp_ifn *sctp_ifn;
6685         struct sctp_ifa *sctp_ifa;
6686         int count = 0;
6687
6688         /* Turn on all the appropriate scopes */
6689         loopback_scope = stcb->asoc.scope.loopback_scope;
6690 #if defined(INET)
6691         ipv4_local_scope = stcb->asoc.scope.ipv4_local_scope;
6692         ipv4_addr_legal = stcb->asoc.scope.ipv4_addr_legal;
6693 #endif
6694 #if defined(INET6)
6695         local_scope = stcb->asoc.scope.local_scope;
6696         site_scope = stcb->asoc.scope.site_scope;
6697         ipv6_addr_legal = stcb->asoc.scope.ipv6_addr_legal;
6698 #endif
6699         SCTP_IPI_ADDR_RLOCK();
6700         vrf = sctp_find_vrf(stcb->asoc.vrf_id);
6701         if (vrf == NULL) {
6702                 /* no vrf, no addresses */
6703                 SCTP_IPI_ADDR_RUNLOCK();
6704                 return (0);
6705         }
6706
6707         if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
6708                 /*
6709                  * bound all case: go through all ifns on the vrf
6710                  */
6711                 LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
6712                         if ((loopback_scope == 0) &&
6713                             SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
6714                                 continue;
6715                         }
6716                         LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
6717                                 if (sctp_is_addr_restricted(stcb, sctp_ifa))
6718                                         continue;
6719                                 switch (sctp_ifa->address.sa.sa_family) {
6720 #ifdef INET
6721                                 case AF_INET:
6722                                         if (ipv4_addr_legal) {
6723                                                 struct sockaddr_in *sin;
6724
6725                                                 sin = &sctp_ifa->address.sin;
6726                                                 if (sin->sin_addr.s_addr == 0) {
6727                                                         /*
6728                                                          * skip unspecified
6729                                                          * addrs
6730                                                          */
6731                                                         continue;
6732                                                 }
6733                                                 if (prison_check_ip4(stcb->sctp_ep->ip_inp.inp.inp_cred,
6734                                                     &sin->sin_addr) != 0) {
6735                                                         continue;
6736                                                 }
6737                                                 if ((ipv4_local_scope == 0) &&
6738                                                     (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
6739                                                         continue;
6740                                                 }
6741                                                 /* count this one */
6742                                                 count++;
6743                                         } else {
6744                                                 continue;
6745                                         }
6746                                         break;
6747 #endif
6748 #ifdef INET6
6749                                 case AF_INET6:
6750                                         if (ipv6_addr_legal) {
6751                                                 struct sockaddr_in6 *sin6;
6752
6753                                                 sin6 = &sctp_ifa->address.sin6;
6754                                                 if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
6755                                                         continue;
6756                                                 }
6757                                                 if (prison_check_ip6(stcb->sctp_ep->ip_inp.inp.inp_cred,
6758                                                     &sin6->sin6_addr) != 0) {
6759                                                         continue;
6760                                                 }
6761                                                 if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
6762                                                         if (local_scope == 0)
6763                                                                 continue;
6764                                                         if (sin6->sin6_scope_id == 0) {
6765                                                                 if (sa6_recoverscope(sin6) != 0)
6766                                                                         /*
6767                                                                          *
6768                                                                          * bad
6769                                                                          * link
6770                                                                          *
6771                                                                          * local
6772                                                                          *
6773                                                                          * address
6774                                                                          */
6775                                                                         continue;
6776                                                         }
6777                                                 }
6778                                                 if ((site_scope == 0) &&
6779                                                     (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
6780                                                         continue;
6781                                                 }
6782                                                 /* count this one */
6783                                                 count++;
6784                                         }
6785                                         break;
6786 #endif
6787                                 default:
6788                                         /* TSNH */
6789                                         break;
6790                                 }
6791                         }
6792                 }
6793         } else {
6794                 /*
6795                  * subset bound case
6796                  */
6797                 struct sctp_laddr *laddr;
6798
6799                 LIST_FOREACH(laddr, &stcb->sctp_ep->sctp_addr_list,
6800                     sctp_nxt_addr) {
6801                         if (sctp_is_addr_restricted(stcb, laddr->ifa)) {
6802                                 continue;
6803                         }
6804                         /* count this one */
6805                         count++;
6806                 }
6807         }
6808         SCTP_IPI_ADDR_RUNLOCK();
6809         return (count);
6810 }
6811
6812 #if defined(SCTP_LOCAL_TRACE_BUF)
6813
6814 void
6815 sctp_log_trace(uint32_t subsys, const char *str SCTP_UNUSED, uint32_t a, uint32_t b, uint32_t c, uint32_t d, uint32_t e, uint32_t f)
6816 {
6817         uint32_t saveindex, newindex;
6818
6819         do {
6820                 saveindex = SCTP_BASE_SYSCTL(sctp_log).index;
6821                 if (saveindex >= SCTP_MAX_LOGGING_SIZE) {
6822                         newindex = 1;
6823                 } else {
6824                         newindex = saveindex + 1;
6825                 }
6826         } while (atomic_cmpset_int(&SCTP_BASE_SYSCTL(sctp_log).index, saveindex, newindex) == 0);
6827         if (saveindex >= SCTP_MAX_LOGGING_SIZE) {
6828                 saveindex = 0;
6829         }
6830         SCTP_BASE_SYSCTL(sctp_log).entry[saveindex].timestamp = SCTP_GET_CYCLECOUNT;
6831         SCTP_BASE_SYSCTL(sctp_log).entry[saveindex].subsys = subsys;
6832         SCTP_BASE_SYSCTL(sctp_log).entry[saveindex].params[0] = a;
6833         SCTP_BASE_SYSCTL(sctp_log).entry[saveindex].params[1] = b;
6834         SCTP_BASE_SYSCTL(sctp_log).entry[saveindex].params[2] = c;
6835         SCTP_BASE_SYSCTL(sctp_log).entry[saveindex].params[3] = d;
6836         SCTP_BASE_SYSCTL(sctp_log).entry[saveindex].params[4] = e;
6837         SCTP_BASE_SYSCTL(sctp_log).entry[saveindex].params[5] = f;
6838 }
6839
6840 #endif
6841 static void
6842 sctp_recv_udp_tunneled_packet(struct mbuf *m, int off, struct inpcb *inp,
6843     const struct sockaddr *sa SCTP_UNUSED, void *ctx SCTP_UNUSED)
6844 {
6845         struct ip *iph;
6846 #ifdef INET6
6847         struct ip6_hdr *ip6;
6848 #endif
6849         struct mbuf *sp, *last;
6850         struct udphdr *uhdr;
6851         uint16_t port;
6852
6853         if ((m->m_flags & M_PKTHDR) == 0) {
6854                 /* Can't handle one that is not a pkt hdr */
6855                 goto out;
6856         }
6857         /* Pull the src port */
6858         iph = mtod(m, struct ip *);
6859         uhdr = (struct udphdr *)((caddr_t)iph + off);
6860         port = uhdr->uh_sport;
6861         /*
6862          * Split out the mbuf chain. Leave the IP header in m, place the
6863          * rest in the sp.
6864          */
6865         sp = m_split(m, off, M_NOWAIT);
6866         if (sp == NULL) {
6867                 /* Gak, drop packet, we can't do a split */
6868                 goto out;
6869         }
6870         if (sp->m_pkthdr.len < sizeof(struct udphdr) + sizeof(struct sctphdr)) {
6871                 /* Gak, packet can't have an SCTP header in it - too small */
6872                 m_freem(sp);
6873                 goto out;
6874         }
6875         /* Now pull up the UDP header and SCTP header together */
6876         sp = m_pullup(sp, sizeof(struct udphdr) + sizeof(struct sctphdr));
6877         if (sp == NULL) {
6878                 /* Gak pullup failed */
6879                 goto out;
6880         }
6881         /* Trim out the UDP header */
6882         m_adj(sp, sizeof(struct udphdr));
6883
6884         /* Now reconstruct the mbuf chain */
6885         for (last = m; last->m_next; last = last->m_next);
6886         last->m_next = sp;
6887         m->m_pkthdr.len += sp->m_pkthdr.len;
6888         /*
6889          * The CSUM_DATA_VALID flags indicates that the HW checked the UDP
6890          * checksum and it was valid. Since CSUM_DATA_VALID ==
6891          * CSUM_SCTP_VALID this would imply that the HW also verified the
6892          * SCTP checksum. Therefore, clear the bit.
6893          */
6894         SCTPDBG(SCTP_DEBUG_CRCOFFLOAD,
6895             "sctp_recv_udp_tunneled_packet(): Packet of length %d received on %s with csum_flags 0x%b.\n",
6896             m->m_pkthdr.len,
6897             if_name(m->m_pkthdr.rcvif),
6898             (int)m->m_pkthdr.csum_flags, CSUM_BITS);
6899         m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
6900         iph = mtod(m, struct ip *);
6901         switch (iph->ip_v) {
6902 #ifdef INET
6903         case IPVERSION:
6904                 iph->ip_len = htons(ntohs(iph->ip_len) - sizeof(struct udphdr));
6905                 sctp_input_with_port(m, off, port);
6906                 break;
6907 #endif
6908 #ifdef INET6
6909         case IPV6_VERSION >> 4:
6910                 ip6 = mtod(m, struct ip6_hdr *);
6911                 ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) - sizeof(struct udphdr));
6912                 sctp6_input_with_port(&m, &off, port);
6913                 break;
6914 #endif
6915         default:
6916                 goto out;
6917                 break;
6918         }
6919         return;
6920 out:
6921         m_freem(m);
6922 }
6923
6924 #ifdef INET
6925 static void
6926 sctp_recv_icmp_tunneled_packet(int cmd, struct sockaddr *sa, void *vip, void *ctx SCTP_UNUSED)
6927 {
6928         struct ip *outer_ip, *inner_ip;
6929         struct sctphdr *sh;
6930         struct icmp *icmp;
6931         struct udphdr *udp;
6932         struct sctp_inpcb *inp;
6933         struct sctp_tcb *stcb;
6934         struct sctp_nets *net;
6935         struct sctp_init_chunk *ch;
6936         struct sockaddr_in src, dst;
6937         uint8_t type, code;
6938
6939         inner_ip = (struct ip *)vip;
6940         icmp = (struct icmp *)((caddr_t)inner_ip -
6941             (sizeof(struct icmp) - sizeof(struct ip)));
6942         outer_ip = (struct ip *)((caddr_t)icmp - sizeof(struct ip));
6943         if (ntohs(outer_ip->ip_len) <
6944             sizeof(struct ip) + 8 + (inner_ip->ip_hl << 2) + sizeof(struct udphdr) + 8) {
6945                 return;
6946         }
6947         udp = (struct udphdr *)((caddr_t)inner_ip + (inner_ip->ip_hl << 2));
6948         sh = (struct sctphdr *)(udp + 1);
6949         memset(&src, 0, sizeof(struct sockaddr_in));
6950         src.sin_family = AF_INET;
6951         src.sin_len = sizeof(struct sockaddr_in);
6952         src.sin_port = sh->src_port;
6953         src.sin_addr = inner_ip->ip_src;
6954         memset(&dst, 0, sizeof(struct sockaddr_in));
6955         dst.sin_family = AF_INET;
6956         dst.sin_len = sizeof(struct sockaddr_in);
6957         dst.sin_port = sh->dest_port;
6958         dst.sin_addr = inner_ip->ip_dst;
6959         /*
6960          * 'dst' holds the dest of the packet that failed to be sent. 'src'
6961          * holds our local endpoint address. Thus we reverse the dst and the
6962          * src in the lookup.
6963          */
6964         inp = NULL;
6965         net = NULL;
6966         stcb = sctp_findassociation_addr_sa((struct sockaddr *)&dst,
6967             (struct sockaddr *)&src,
6968             &inp, &net, 1,
6969             SCTP_DEFAULT_VRFID);
6970         if ((stcb != NULL) &&
6971             (net != NULL) &&
6972             (inp != NULL)) {
6973                 /* Check the UDP port numbers */
6974                 if ((udp->uh_dport != net->port) ||
6975                     (udp->uh_sport != htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port)))) {
6976                         SCTP_TCB_UNLOCK(stcb);
6977                         return;
6978                 }
6979                 /* Check the verification tag */
6980                 if (ntohl(sh->v_tag) != 0) {
6981                         /*
6982                          * This must be the verification tag used for
6983                          * sending out packets. We don't consider packets
6984                          * reflecting the verification tag.
6985                          */
6986                         if (ntohl(sh->v_tag) != stcb->asoc.peer_vtag) {
6987                                 SCTP_TCB_UNLOCK(stcb);
6988                                 return;
6989                         }
6990                 } else {
6991                         if (ntohs(outer_ip->ip_len) >=
6992                             sizeof(struct ip) +
6993                             8 + (inner_ip->ip_hl << 2) + 8 + 20) {
6994                                 /*
6995                                  * In this case we can check if we got an
6996                                  * INIT chunk and if the initiate tag
6997                                  * matches.
6998                                  */
6999                                 ch = (struct sctp_init_chunk *)(sh + 1);
7000                                 if ((ch->ch.chunk_type != SCTP_INITIATION) ||
7001                                     (ntohl(ch->init.initiate_tag) != stcb->asoc.my_vtag)) {
7002                                         SCTP_TCB_UNLOCK(stcb);
7003                                         return;
7004                                 }
7005                         } else {
7006                                 SCTP_TCB_UNLOCK(stcb);
7007                                 return;
7008                         }
7009                 }
7010                 type = icmp->icmp_type;
7011                 code = icmp->icmp_code;
7012                 if ((type == ICMP_UNREACH) &&
7013                     (code == ICMP_UNREACH_PORT)) {
7014                         code = ICMP_UNREACH_PROTOCOL;
7015                 }
7016                 sctp_notify(inp, stcb, net, type, code,
7017                     ntohs(inner_ip->ip_len),
7018                     (uint32_t)ntohs(icmp->icmp_nextmtu));
7019         } else {
7020                 if ((stcb == NULL) && (inp != NULL)) {
7021                         /* reduce ref-count */
7022                         SCTP_INP_WLOCK(inp);
7023                         SCTP_INP_DECR_REF(inp);
7024                         SCTP_INP_WUNLOCK(inp);
7025                 }
7026                 if (stcb) {
7027                         SCTP_TCB_UNLOCK(stcb);
7028                 }
7029         }
7030         return;
7031 }
7032 #endif
7033
7034 #ifdef INET6
7035 static void
7036 sctp_recv_icmp6_tunneled_packet(int cmd, struct sockaddr *sa, void *d, void *ctx SCTP_UNUSED)
7037 {
7038         struct ip6ctlparam *ip6cp;
7039         struct sctp_inpcb *inp;
7040         struct sctp_tcb *stcb;
7041         struct sctp_nets *net;
7042         struct sctphdr sh;
7043         struct udphdr udp;
7044         struct sockaddr_in6 src, dst;
7045         uint8_t type, code;
7046
7047         ip6cp = (struct ip6ctlparam *)d;
7048         /*
7049          * XXX: We assume that when IPV6 is non NULL, M and OFF are valid.
7050          */
7051         if (ip6cp->ip6c_m == NULL) {
7052                 return;
7053         }
7054         /*
7055          * Check if we can safely examine the ports and the verification tag
7056          * of the SCTP common header.
7057          */
7058         if (ip6cp->ip6c_m->m_pkthdr.len <
7059             ip6cp->ip6c_off + sizeof(struct udphdr) + offsetof(struct sctphdr, checksum)) {
7060                 return;
7061         }
7062         /* Copy out the UDP header. */
7063         memset(&udp, 0, sizeof(struct udphdr));
7064         m_copydata(ip6cp->ip6c_m,
7065             ip6cp->ip6c_off,
7066             sizeof(struct udphdr),
7067             (caddr_t)&udp);
7068         /* Copy out the port numbers and the verification tag. */
7069         memset(&sh, 0, sizeof(struct sctphdr));
7070         m_copydata(ip6cp->ip6c_m,
7071             ip6cp->ip6c_off + sizeof(struct udphdr),
7072             sizeof(uint16_t) + sizeof(uint16_t) + sizeof(uint32_t),
7073             (caddr_t)&sh);
7074         memset(&src, 0, sizeof(struct sockaddr_in6));
7075         src.sin6_family = AF_INET6;
7076         src.sin6_len = sizeof(struct sockaddr_in6);
7077         src.sin6_port = sh.src_port;
7078         src.sin6_addr = ip6cp->ip6c_ip6->ip6_src;
7079         if (in6_setscope(&src.sin6_addr, ip6cp->ip6c_m->m_pkthdr.rcvif, NULL) != 0) {
7080                 return;
7081         }
7082         memset(&dst, 0, sizeof(struct sockaddr_in6));
7083         dst.sin6_family = AF_INET6;
7084         dst.sin6_len = sizeof(struct sockaddr_in6);
7085         dst.sin6_port = sh.dest_port;
7086         dst.sin6_addr = ip6cp->ip6c_ip6->ip6_dst;
7087         if (in6_setscope(&dst.sin6_addr, ip6cp->ip6c_m->m_pkthdr.rcvif, NULL) != 0) {
7088                 return;
7089         }
7090         inp = NULL;
7091         net = NULL;
7092         stcb = sctp_findassociation_addr_sa((struct sockaddr *)&dst,
7093             (struct sockaddr *)&src,
7094             &inp, &net, 1, SCTP_DEFAULT_VRFID);
7095         if ((stcb != NULL) &&
7096             (net != NULL) &&
7097             (inp != NULL)) {
7098                 /* Check the UDP port numbers */
7099                 if ((udp.uh_dport != net->port) ||
7100                     (udp.uh_sport != htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port)))) {
7101                         SCTP_TCB_UNLOCK(stcb);
7102                         return;
7103                 }
7104                 /* Check the verification tag */
7105                 if (ntohl(sh.v_tag) != 0) {
7106                         /*
7107                          * This must be the verification tag used for
7108                          * sending out packets. We don't consider packets
7109                          * reflecting the verification tag.
7110                          */
7111                         if (ntohl(sh.v_tag) != stcb->asoc.peer_vtag) {
7112                                 SCTP_TCB_UNLOCK(stcb);
7113                                 return;
7114                         }
7115                 } else {
7116                         if (ip6cp->ip6c_m->m_pkthdr.len >=
7117                             ip6cp->ip6c_off + sizeof(struct udphdr) +
7118                             sizeof(struct sctphdr) +
7119                             sizeof(struct sctp_chunkhdr) +
7120                             offsetof(struct sctp_init, a_rwnd)) {
7121                                 /*
7122                                  * In this case we can check if we got an
7123                                  * INIT chunk and if the initiate tag
7124                                  * matches.
7125                                  */
7126                                 uint32_t initiate_tag;
7127                                 uint8_t chunk_type;
7128
7129                                 m_copydata(ip6cp->ip6c_m,
7130                                     ip6cp->ip6c_off +
7131                                     sizeof(struct udphdr) +
7132                                     sizeof(struct sctphdr),
7133                                     sizeof(uint8_t),
7134                                     (caddr_t)&chunk_type);
7135                                 m_copydata(ip6cp->ip6c_m,
7136                                     ip6cp->ip6c_off +
7137                                     sizeof(struct udphdr) +
7138                                     sizeof(struct sctphdr) +
7139                                     sizeof(struct sctp_chunkhdr),
7140                                     sizeof(uint32_t),
7141                                     (caddr_t)&initiate_tag);
7142                                 if ((chunk_type != SCTP_INITIATION) ||
7143                                     (ntohl(initiate_tag) != stcb->asoc.my_vtag)) {
7144                                         SCTP_TCB_UNLOCK(stcb);
7145                                         return;
7146                                 }
7147                         } else {
7148                                 SCTP_TCB_UNLOCK(stcb);
7149                                 return;
7150                         }
7151                 }
7152                 type = ip6cp->ip6c_icmp6->icmp6_type;
7153                 code = ip6cp->ip6c_icmp6->icmp6_code;
7154                 if ((type == ICMP6_DST_UNREACH) &&
7155                     (code == ICMP6_DST_UNREACH_NOPORT)) {
7156                         type = ICMP6_PARAM_PROB;
7157                         code = ICMP6_PARAMPROB_NEXTHEADER;
7158                 }
7159                 sctp6_notify(inp, stcb, net, type, code,
7160                     ntohl(ip6cp->ip6c_icmp6->icmp6_mtu));
7161         } else {
7162                 if ((stcb == NULL) && (inp != NULL)) {
7163                         /* reduce inp's ref-count */
7164                         SCTP_INP_WLOCK(inp);
7165                         SCTP_INP_DECR_REF(inp);
7166                         SCTP_INP_WUNLOCK(inp);
7167                 }
7168                 if (stcb) {
7169                         SCTP_TCB_UNLOCK(stcb);
7170                 }
7171         }
7172 }
7173 #endif
7174
7175 void
7176 sctp_over_udp_stop(void)
7177 {
7178         /*
7179          * This function assumes sysctl caller holds sctp_sysctl_info_lock()
7180          * for writting!
7181          */
7182 #ifdef INET
7183         if (SCTP_BASE_INFO(udp4_tun_socket) != NULL) {
7184                 soclose(SCTP_BASE_INFO(udp4_tun_socket));
7185                 SCTP_BASE_INFO(udp4_tun_socket) = NULL;
7186         }
7187 #endif
7188 #ifdef INET6
7189         if (SCTP_BASE_INFO(udp6_tun_socket) != NULL) {
7190                 soclose(SCTP_BASE_INFO(udp6_tun_socket));
7191                 SCTP_BASE_INFO(udp6_tun_socket) = NULL;
7192         }
7193 #endif
7194 }
7195
7196 int
7197 sctp_over_udp_start(void)
7198 {
7199         uint16_t port;
7200         int ret;
7201 #ifdef INET
7202         struct sockaddr_in sin;
7203 #endif
7204 #ifdef INET6
7205         struct sockaddr_in6 sin6;
7206 #endif
7207         /*
7208          * This function assumes sysctl caller holds sctp_sysctl_info_lock()
7209          * for writting!
7210          */
7211         port = SCTP_BASE_SYSCTL(sctp_udp_tunneling_port);
7212         if (ntohs(port) == 0) {
7213                 /* Must have a port set */
7214                 return (EINVAL);
7215         }
7216 #ifdef INET
7217         if (SCTP_BASE_INFO(udp4_tun_socket) != NULL) {
7218                 /* Already running -- must stop first */
7219                 return (EALREADY);
7220         }
7221 #endif
7222 #ifdef INET6
7223         if (SCTP_BASE_INFO(udp6_tun_socket) != NULL) {
7224                 /* Already running -- must stop first */
7225                 return (EALREADY);
7226         }
7227 #endif
7228 #ifdef INET
7229         if ((ret = socreate(PF_INET, &SCTP_BASE_INFO(udp4_tun_socket),
7230             SOCK_DGRAM, IPPROTO_UDP,
7231             curthread->td_ucred, curthread))) {
7232                 sctp_over_udp_stop();
7233                 return (ret);
7234         }
7235         /* Call the special UDP hook. */
7236         if ((ret = udp_set_kernel_tunneling(SCTP_BASE_INFO(udp4_tun_socket),
7237             sctp_recv_udp_tunneled_packet,
7238             sctp_recv_icmp_tunneled_packet,
7239             NULL))) {
7240                 sctp_over_udp_stop();
7241                 return (ret);
7242         }
7243         /* Ok, we have a socket, bind it to the port. */
7244         memset(&sin, 0, sizeof(struct sockaddr_in));
7245         sin.sin_len = sizeof(struct sockaddr_in);
7246         sin.sin_family = AF_INET;
7247         sin.sin_port = htons(port);
7248         if ((ret = sobind(SCTP_BASE_INFO(udp4_tun_socket),
7249             (struct sockaddr *)&sin, curthread))) {
7250                 sctp_over_udp_stop();
7251                 return (ret);
7252         }
7253 #endif
7254 #ifdef INET6
7255         if ((ret = socreate(PF_INET6, &SCTP_BASE_INFO(udp6_tun_socket),
7256             SOCK_DGRAM, IPPROTO_UDP,
7257             curthread->td_ucred, curthread))) {
7258                 sctp_over_udp_stop();
7259                 return (ret);
7260         }
7261         /* Call the special UDP hook. */
7262         if ((ret = udp_set_kernel_tunneling(SCTP_BASE_INFO(udp6_tun_socket),
7263             sctp_recv_udp_tunneled_packet,
7264             sctp_recv_icmp6_tunneled_packet,
7265             NULL))) {
7266                 sctp_over_udp_stop();
7267                 return (ret);
7268         }
7269         /* Ok, we have a socket, bind it to the port. */
7270         memset(&sin6, 0, sizeof(struct sockaddr_in6));
7271         sin6.sin6_len = sizeof(struct sockaddr_in6);
7272         sin6.sin6_family = AF_INET6;
7273         sin6.sin6_port = htons(port);
7274         if ((ret = sobind(SCTP_BASE_INFO(udp6_tun_socket),
7275             (struct sockaddr *)&sin6, curthread))) {
7276                 sctp_over_udp_stop();
7277                 return (ret);
7278         }
7279 #endif
7280         return (0);
7281 }
7282
7283 #if defined(INET6) || defined(INET)
7284
7285 /*
7286  * sctp_min_mtu ()returns the minimum of all non-zero arguments.
7287  * If all arguments are zero, zero is returned.
7288  */
7289 uint32_t
7290 sctp_min_mtu(uint32_t mtu1, uint32_t mtu2, uint32_t mtu3)
7291 {
7292         if (mtu1 > 0) {
7293                 if (mtu2 > 0) {
7294                         if (mtu3 > 0) {
7295                                 return (min(mtu1, min(mtu2, mtu3)));
7296                         } else {
7297                                 return (min(mtu1, mtu2));
7298                         }
7299                 } else {
7300                         if (mtu3 > 0) {
7301                                 return (min(mtu1, mtu3));
7302                         } else {
7303                                 return (mtu1);
7304                         }
7305                 }
7306         } else {
7307                 if (mtu2 > 0) {
7308                         if (mtu3 > 0) {
7309                                 return (min(mtu2, mtu3));
7310                         } else {
7311                                 return (mtu2);
7312                         }
7313                 } else {
7314                         return (mtu3);
7315                 }
7316         }
7317 }
7318
7319 void
7320 sctp_hc_set_mtu(union sctp_sockstore *addr, uint16_t fibnum, uint32_t mtu)
7321 {
7322         struct in_conninfo inc;
7323
7324         memset(&inc, 0, sizeof(struct in_conninfo));
7325         inc.inc_fibnum = fibnum;
7326         switch (addr->sa.sa_family) {
7327 #ifdef INET
7328         case AF_INET:
7329                 inc.inc_faddr = addr->sin.sin_addr;
7330                 break;
7331 #endif
7332 #ifdef INET6
7333         case AF_INET6:
7334                 inc.inc_flags |= INC_ISIPV6;
7335                 inc.inc6_faddr = addr->sin6.sin6_addr;
7336                 break;
7337 #endif
7338         default:
7339                 return;
7340         }
7341         tcp_hc_updatemtu(&inc, (u_long)mtu);
7342 }
7343
7344 uint32_t
7345 sctp_hc_get_mtu(union sctp_sockstore *addr, uint16_t fibnum)
7346 {
7347         struct in_conninfo inc;
7348
7349         memset(&inc, 0, sizeof(struct in_conninfo));
7350         inc.inc_fibnum = fibnum;
7351         switch (addr->sa.sa_family) {
7352 #ifdef INET
7353         case AF_INET:
7354                 inc.inc_faddr = addr->sin.sin_addr;
7355                 break;
7356 #endif
7357 #ifdef INET6
7358         case AF_INET6:
7359                 inc.inc_flags |= INC_ISIPV6;
7360                 inc.inc6_faddr = addr->sin6.sin6_addr;
7361                 break;
7362 #endif
7363         default:
7364                 return (0);
7365         }
7366         return ((uint32_t)tcp_hc_getmtu(&inc));
7367 }
7368 #endif