]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/uipc_socket2.c
xnu-3789.21.4.tar.gz
[apple/xnu.git] / bsd / kern / uipc_socket2.c
1 /*
2 * Copyright (c) 1998-2015 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*
30 * Copyright (c) 1982, 1986, 1988, 1990, 1993
31 * The Regents of the University of California. All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. All advertising materials mentioning features or use of this software
42 * must display the following acknowledgement:
43 * This product includes software developed by the University of
44 * California, Berkeley and its contributors.
45 * 4. Neither the name of the University nor the names of its contributors
46 * may be used to endorse or promote products derived from this software
47 * without specific prior written permission.
48 *
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59 * SUCH DAMAGE.
60 *
61 * @(#)uipc_socket2.c 8.1 (Berkeley) 6/10/93
62 */
63 /*
64 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
65 * support for mandatory and extensible security protections. This notice
66 * is included in support of clause 2.2 (b) of the Apple Public License,
67 * Version 2.0.
68 */
69
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/domain.h>
73 #include <sys/kernel.h>
74 #include <sys/proc_internal.h>
75 #include <sys/kauth.h>
76 #include <sys/malloc.h>
77 #include <sys/mbuf.h>
78 #include <sys/mcache.h>
79 #include <sys/protosw.h>
80 #include <sys/stat.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/signalvar.h>
84 #include <sys/sysctl.h>
85 #include <sys/syslog.h>
86 #include <sys/ev.h>
87 #include <kern/locks.h>
88 #include <net/route.h>
89 #include <net/content_filter.h>
90 #include <netinet/in.h>
91 #include <netinet/in_pcb.h>
92 #include <sys/kdebug.h>
93 #include <libkern/OSAtomic.h>
94
95 #if CONFIG_MACF
96 #include <security/mac_framework.h>
97 #endif
98
99 #include <mach/vm_param.h>
100
101 #if MPTCP
102 #include <netinet/mptcp_var.h>
103 #endif
104
105 #define DBG_FNC_SBDROP NETDBG_CODE(DBG_NETSOCK, 4)
106 #define DBG_FNC_SBAPPEND NETDBG_CODE(DBG_NETSOCK, 5)
107
108 extern char *proc_best_name(proc_t p);
109
110 SYSCTL_DECL(_kern_ipc);
111
112 __private_extern__ u_int32_t net_io_policy_throttle_best_effort = 0;
113 SYSCTL_INT(_kern_ipc, OID_AUTO, throttle_best_effort,
114 CTLFLAG_RW | CTLFLAG_LOCKED, &net_io_policy_throttle_best_effort, 0, "");
115
116 static inline void sbcompress(struct sockbuf *, struct mbuf *, struct mbuf *);
117 static struct socket *sonewconn_internal(struct socket *, int);
118 static int sbappendaddr_internal(struct sockbuf *, struct sockaddr *,
119 struct mbuf *, struct mbuf *);
120 static int sbappendcontrol_internal(struct sockbuf *, struct mbuf *,
121 struct mbuf *);
122 static void soevent_ifdenied(struct socket *);
123
124 /*
125 * Primitive routines for operating on sockets and socket buffers
126 */
127 static int soqlimitcompat = 1;
128 static int soqlencomp = 0;
129
130 /*
131 * Based on the number of mbuf clusters configured, high_sb_max and sb_max can
132 * get scaled up or down to suit that memory configuration. high_sb_max is a
133 * higher limit on sb_max that is checked when sb_max gets set through sysctl.
134 */
135
136 u_int32_t sb_max = SB_MAX; /* XXX should be static */
137 u_int32_t high_sb_max = SB_MAX;
138
139 static u_int32_t sb_efficiency = 8; /* parameter for sbreserve() */
140 int32_t total_sbmb_cnt __attribute__((aligned(8))) = 0;
141 int32_t total_sbmb_cnt_floor __attribute__((aligned(8))) = 0;
142 int32_t total_sbmb_cnt_peak __attribute__((aligned(8))) = 0;
143 int64_t sbmb_limreached __attribute__((aligned(8))) = 0;
144
145 /* Control whether to throttle sockets eligible to be throttled */
146 __private_extern__ u_int32_t net_io_policy_throttled = 0;
147 static int sysctl_io_policy_throttled SYSCTL_HANDLER_ARGS;
148
149 u_int32_t net_io_policy_log = 0; /* log socket policy changes */
150 #if CONFIG_PROC_UUID_POLICY
151 u_int32_t net_io_policy_uuid = 1; /* enable UUID socket policy */
152 #endif /* CONFIG_PROC_UUID_POLICY */
153
154 /*
155 * Procedures to manipulate state flags of socket
156 * and do appropriate wakeups. Normal sequence from the
157 * active (originating) side is that soisconnecting() is
158 * called during processing of connect() call,
159 * resulting in an eventual call to soisconnected() if/when the
160 * connection is established. When the connection is torn down
161 * soisdisconnecting() is called during processing of disconnect() call,
162 * and soisdisconnected() is called when the connection to the peer
163 * is totally severed. The semantics of these routines are such that
164 * connectionless protocols can call soisconnected() and soisdisconnected()
165 * only, bypassing the in-progress calls when setting up a ``connection''
166 * takes no time.
167 *
168 * From the passive side, a socket is created with
169 * two queues of sockets: so_incomp for connections in progress
170 * and so_comp for connections already made and awaiting user acceptance.
171 * As a protocol is preparing incoming connections, it creates a socket
172 * structure queued on so_incomp by calling sonewconn(). When the connection
173 * is established, soisconnected() is called, and transfers the
174 * socket structure to so_comp, making it available to accept().
175 *
176 * If a socket is closed with sockets on either
177 * so_incomp or so_comp, these sockets are dropped.
178 *
179 * If higher level protocols are implemented in
180 * the kernel, the wakeups done here will sometimes
181 * cause software-interrupt process scheduling.
182 */
183 void
184 soisconnecting(struct socket *so)
185 {
186
187 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
188 so->so_state |= SS_ISCONNECTING;
189
190 sflt_notify(so, sock_evt_connecting, NULL);
191 }
192
193 void
194 soisconnected(struct socket *so)
195 {
196 struct socket *head = so->so_head;
197
198 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
199 so->so_state |= SS_ISCONNECTED;
200
201 soreserve_preconnect(so, 0);
202
203 sflt_notify(so, sock_evt_connected, NULL);
204
205 if (head && (so->so_state & SS_INCOMP)) {
206 so->so_state &= ~SS_INCOMP;
207 so->so_state |= SS_COMP;
208 if (head->so_proto->pr_getlock != NULL) {
209 socket_unlock(so, 0);
210 socket_lock(head, 1);
211 }
212 postevent(head, 0, EV_RCONN);
213 TAILQ_REMOVE(&head->so_incomp, so, so_list);
214 head->so_incqlen--;
215 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
216 sorwakeup(head);
217 wakeup_one((caddr_t)&head->so_timeo);
218 if (head->so_proto->pr_getlock != NULL) {
219 socket_unlock(head, 1);
220 socket_lock(so, 0);
221 }
222 } else {
223 postevent(so, 0, EV_WCONN);
224 wakeup((caddr_t)&so->so_timeo);
225 sorwakeup(so);
226 sowwakeup(so);
227 soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_CONNECTED |
228 SO_FILT_HINT_CONNINFO_UPDATED);
229 }
230 }
231
232 boolean_t
233 socanwrite(struct socket *so)
234 {
235 return ((so->so_state & SS_ISCONNECTED) ||
236 !(so->so_proto->pr_flags & PR_CONNREQUIRED) ||
237 (so->so_flags1 & SOF1_PRECONNECT_DATA));
238
239 }
240
241 void
242 soisdisconnecting(struct socket *so)
243 {
244 so->so_state &= ~SS_ISCONNECTING;
245 so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
246 soevent(so, SO_FILT_HINT_LOCKED);
247 sflt_notify(so, sock_evt_disconnecting, NULL);
248 wakeup((caddr_t)&so->so_timeo);
249 sowwakeup(so);
250 sorwakeup(so);
251 }
252
253 void
254 soisdisconnected(struct socket *so)
255 {
256 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
257 so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
258 soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_DISCONNECTED |
259 SO_FILT_HINT_CONNINFO_UPDATED);
260 sflt_notify(so, sock_evt_disconnected, NULL);
261 wakeup((caddr_t)&so->so_timeo);
262 sowwakeup(so);
263 sorwakeup(so);
264
265 #if CONTENT_FILTER
266 /* Notify content filters as soon as we cannot send/receive data */
267 cfil_sock_notify_shutdown(so, SHUT_RDWR);
268 #endif /* CONTENT_FILTER */
269 }
270
271 /*
272 * This function will issue a wakeup like soisdisconnected but it will not
273 * notify the socket filters. This will avoid unlocking the socket
274 * in the midst of closing it.
275 */
276 void
277 sodisconnectwakeup(struct socket *so)
278 {
279 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
280 so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
281 soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_DISCONNECTED |
282 SO_FILT_HINT_CONNINFO_UPDATED);
283 wakeup((caddr_t)&so->so_timeo);
284 sowwakeup(so);
285 sorwakeup(so);
286
287 #if CONTENT_FILTER
288 /* Notify content filters as soon as we cannot send/receive data */
289 cfil_sock_notify_shutdown(so, SHUT_RDWR);
290 #endif /* CONTENT_FILTER */
291 }
292
293 /*
294 * When an attempt at a new connection is noted on a socket
295 * which accepts connections, sonewconn is called. If the
296 * connection is possible (subject to space constraints, etc.)
297 * then we allocate a new structure, propoerly linked into the
298 * data structure of the original socket, and return this.
299 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
300 */
301 static struct socket *
302 sonewconn_internal(struct socket *head, int connstatus)
303 {
304 int so_qlen, error = 0;
305 struct socket *so;
306 lck_mtx_t *mutex_held;
307
308 if (head->so_proto->pr_getlock != NULL)
309 mutex_held = (*head->so_proto->pr_getlock)(head, 0);
310 else
311 mutex_held = head->so_proto->pr_domain->dom_mtx;
312 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
313
314 if (!soqlencomp) {
315 /*
316 * This is the default case; so_qlen represents the
317 * sum of both incomplete and completed queues.
318 */
319 so_qlen = head->so_qlen;
320 } else {
321 /*
322 * When kern.ipc.soqlencomp is set to 1, so_qlen
323 * represents only the completed queue. Since we
324 * cannot let the incomplete queue goes unbounded
325 * (in case of SYN flood), we cap the incomplete
326 * queue length to at most somaxconn, and use that
327 * as so_qlen so that we fail immediately below.
328 */
329 so_qlen = head->so_qlen - head->so_incqlen;
330 if (head->so_incqlen > somaxconn)
331 so_qlen = somaxconn;
332 }
333
334 if (so_qlen >=
335 (soqlimitcompat ? head->so_qlimit : (3 * head->so_qlimit / 2)))
336 return ((struct socket *)0);
337 so = soalloc(1, SOCK_DOM(head), head->so_type);
338 if (so == NULL)
339 return ((struct socket *)0);
340 /* check if head was closed during the soalloc */
341 if (head->so_proto == NULL) {
342 sodealloc(so);
343 return ((struct socket *)0);
344 }
345
346 so->so_type = head->so_type;
347 so->so_options = head->so_options &~ SO_ACCEPTCONN;
348 so->so_linger = head->so_linger;
349 so->so_state = head->so_state | SS_NOFDREF;
350 so->so_proto = head->so_proto;
351 so->so_timeo = head->so_timeo;
352 so->so_pgid = head->so_pgid;
353 kauth_cred_ref(head->so_cred);
354 so->so_cred = head->so_cred;
355 so->last_pid = head->last_pid;
356 so->last_upid = head->last_upid;
357 memcpy(so->last_uuid, head->last_uuid, sizeof (so->last_uuid));
358 if (head->so_flags & SOF_DELEGATED) {
359 so->e_pid = head->e_pid;
360 so->e_upid = head->e_upid;
361 memcpy(so->e_uuid, head->e_uuid, sizeof (so->e_uuid));
362 }
363 /* inherit socket options stored in so_flags */
364 so->so_flags = head->so_flags &
365 (SOF_NOSIGPIPE | SOF_NOADDRAVAIL | SOF_REUSESHAREUID |
366 SOF_NOTIFYCONFLICT | SOF_BINDRANDOMPORT | SOF_NPX_SETOPTSHUT |
367 SOF_NODEFUNCT | SOF_PRIVILEGED_TRAFFIC_CLASS| SOF_NOTSENT_LOWAT |
368 SOF_USELRO | SOF_DELEGATED);
369 so->so_usecount = 1;
370 so->next_lock_lr = 0;
371 so->next_unlock_lr = 0;
372
373 so->so_rcv.sb_flags |= SB_RECV; /* XXX */
374 so->so_rcv.sb_so = so->so_snd.sb_so = so;
375 TAILQ_INIT(&so->so_evlist);
376
377 #if CONFIG_MACF_SOCKET
378 mac_socket_label_associate_accept(head, so);
379 #endif
380
381 /* inherit traffic management properties of listener */
382 so->so_flags1 |=
383 head->so_flags1 & (SOF1_TRAFFIC_MGT_SO_BACKGROUND);
384 so->so_background_thread = head->so_background_thread;
385 so->so_traffic_class = head->so_traffic_class;
386
387 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
388 sodealloc(so);
389 return ((struct socket *)0);
390 }
391 so->so_rcv.sb_flags |= (head->so_rcv.sb_flags & SB_USRSIZE);
392 so->so_snd.sb_flags |= (head->so_snd.sb_flags & SB_USRSIZE);
393
394 /*
395 * Must be done with head unlocked to avoid deadlock
396 * for protocol with per socket mutexes.
397 */
398 if (head->so_proto->pr_unlock)
399 socket_unlock(head, 0);
400 if (((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL) != 0) ||
401 error) {
402 sodealloc(so);
403 if (head->so_proto->pr_unlock)
404 socket_lock(head, 0);
405 return ((struct socket *)0);
406 }
407 if (head->so_proto->pr_unlock) {
408 socket_lock(head, 0);
409 /*
410 * Radar 7385998 Recheck that the head is still accepting
411 * to avoid race condition when head is getting closed.
412 */
413 if ((head->so_options & SO_ACCEPTCONN) == 0) {
414 so->so_state &= ~SS_NOFDREF;
415 soclose(so);
416 return ((struct socket *)0);
417 }
418 }
419
420 atomic_add_32(&so->so_proto->pr_domain->dom_refs, 1);
421
422 /* Insert in head appropriate lists */
423 so->so_head = head;
424
425 /*
426 * Since this socket is going to be inserted into the incomp
427 * queue, it can be picked up by another thread in
428 * tcp_dropdropablreq to get dropped before it is setup..
429 * To prevent this race, set in-progress flag which can be
430 * cleared later
431 */
432 so->so_flags |= SOF_INCOMP_INPROGRESS;
433
434 if (connstatus) {
435 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
436 so->so_state |= SS_COMP;
437 } else {
438 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
439 so->so_state |= SS_INCOMP;
440 head->so_incqlen++;
441 }
442 head->so_qlen++;
443
444 /* Attach socket filters for this protocol */
445 sflt_initsock(so);
446
447 if (connstatus) {
448 so->so_state |= connstatus;
449 sorwakeup(head);
450 wakeup((caddr_t)&head->so_timeo);
451 }
452 return (so);
453 }
454
455
456 struct socket *
457 sonewconn(struct socket *head, int connstatus, const struct sockaddr *from)
458 {
459 int error = sflt_connectin(head, from);
460 if (error) {
461 return (NULL);
462 }
463
464 return (sonewconn_internal(head, connstatus));
465 }
466
467 /*
468 * Socantsendmore indicates that no more data will be sent on the
469 * socket; it would normally be applied to a socket when the user
470 * informs the system that no more data is to be sent, by the protocol
471 * code (in case PRU_SHUTDOWN). Socantrcvmore indicates that no more data
472 * will be received, and will normally be applied to the socket by a
473 * protocol when it detects that the peer will send no more data.
474 * Data queued for reading in the socket may yet be read.
475 */
476
477 void
478 socantsendmore(struct socket *so)
479 {
480 so->so_state |= SS_CANTSENDMORE;
481 soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_CANTSENDMORE);
482 sflt_notify(so, sock_evt_cantsendmore, NULL);
483 sowwakeup(so);
484 }
485
486 void
487 socantrcvmore(struct socket *so)
488 {
489 so->so_state |= SS_CANTRCVMORE;
490 soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_CANTRCVMORE);
491 sflt_notify(so, sock_evt_cantrecvmore, NULL);
492 sorwakeup(so);
493 }
494
495 /*
496 * Wait for data to arrive at/drain from a socket buffer.
497 */
498 int
499 sbwait(struct sockbuf *sb)
500 {
501 boolean_t nointr = (sb->sb_flags & SB_NOINTR);
502 void *lr_saved = __builtin_return_address(0);
503 struct socket *so = sb->sb_so;
504 lck_mtx_t *mutex_held;
505 struct timespec ts;
506 int error = 0;
507
508 if (so == NULL) {
509 panic("%s: null so, sb=%p sb_flags=0x%x lr=%p\n",
510 __func__, sb, sb->sb_flags, lr_saved);
511 /* NOTREACHED */
512 } else if (so->so_usecount < 1) {
513 panic("%s: sb=%p sb_flags=0x%x sb_so=%p usecount=%d lr=%p "
514 "lrh= %s\n", __func__, sb, sb->sb_flags, so,
515 so->so_usecount, lr_saved, solockhistory_nr(so));
516 /* NOTREACHED */
517 }
518
519 if ((so->so_state & SS_DRAINING) || (so->so_flags & SOF_DEFUNCT)) {
520 error = EBADF;
521 if (so->so_flags & SOF_DEFUNCT) {
522 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] "
523 "(%d)\n", __func__, proc_selfpid(),
524 proc_best_name(current_proc()),
525 (uint64_t)VM_KERNEL_ADDRPERM(so),
526 SOCK_DOM(so), SOCK_TYPE(so), error);
527 }
528 return (error);
529 }
530
531 if (so->so_proto->pr_getlock != NULL)
532 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
533 else
534 mutex_held = so->so_proto->pr_domain->dom_mtx;
535
536 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
537
538 ts.tv_sec = sb->sb_timeo.tv_sec;
539 ts.tv_nsec = sb->sb_timeo.tv_usec * 1000;
540
541 sb->sb_waiters++;
542 VERIFY(sb->sb_waiters != 0);
543
544 error = msleep((caddr_t)&sb->sb_cc, mutex_held,
545 nointr ? PSOCK : PSOCK | PCATCH,
546 nointr ? "sbwait_nointr" : "sbwait", &ts);
547
548 VERIFY(sb->sb_waiters != 0);
549 sb->sb_waiters--;
550
551 if (so->so_usecount < 1) {
552 panic("%s: 2 sb=%p sb_flags=0x%x sb_so=%p usecount=%d lr=%p "
553 "lrh= %s\n", __func__, sb, sb->sb_flags, so,
554 so->so_usecount, lr_saved, solockhistory_nr(so));
555 /* NOTREACHED */
556 }
557
558 if ((so->so_state & SS_DRAINING) || (so->so_flags & SOF_DEFUNCT)) {
559 error = EBADF;
560 if (so->so_flags & SOF_DEFUNCT) {
561 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] "
562 "(%d)\n", __func__, proc_selfpid(),
563 proc_best_name(current_proc()),
564 (uint64_t)VM_KERNEL_ADDRPERM(so),
565 SOCK_DOM(so), SOCK_TYPE(so), error);
566 }
567 }
568
569 return (error);
570 }
571
572 void
573 sbwakeup(struct sockbuf *sb)
574 {
575 if (sb->sb_waiters > 0)
576 wakeup((caddr_t)&sb->sb_cc);
577 }
578
579 /*
580 * Wakeup processes waiting on a socket buffer.
581 * Do asynchronous notification via SIGIO
582 * if the socket has the SS_ASYNC flag set.
583 */
584 void
585 sowakeup(struct socket *so, struct sockbuf *sb)
586 {
587 if (so->so_flags & SOF_DEFUNCT) {
588 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] si 0x%x, "
589 "fl 0x%x [%s]\n", __func__, proc_selfpid(),
590 proc_best_name(current_proc()),
591 (uint64_t)VM_KERNEL_ADDRPERM(so), SOCK_DOM(so),
592 SOCK_TYPE(so), (uint32_t)sb->sb_sel.si_flags, sb->sb_flags,
593 (sb->sb_flags & SB_RECV) ? "rcv" : "snd");
594 }
595
596 sb->sb_flags &= ~SB_SEL;
597 selwakeup(&sb->sb_sel);
598 sbwakeup(sb);
599 if (so->so_state & SS_ASYNC) {
600 if (so->so_pgid < 0)
601 gsignal(-so->so_pgid, SIGIO);
602 else if (so->so_pgid > 0)
603 proc_signal(so->so_pgid, SIGIO);
604 }
605 if (sb->sb_flags & SB_KNOTE) {
606 KNOTE(&sb->sb_sel.si_note, SO_FILT_HINT_LOCKED);
607 }
608 if (sb->sb_flags & SB_UPCALL) {
609 void (*sb_upcall)(struct socket *, void *, int);
610 caddr_t sb_upcallarg;
611
612 sb_upcall = sb->sb_upcall;
613 sb_upcallarg = sb->sb_upcallarg;
614 /* Let close know that we're about to do an upcall */
615 so->so_upcallusecount++;
616
617 socket_unlock(so, 0);
618 (*sb_upcall)(so, sb_upcallarg, M_DONTWAIT);
619 socket_lock(so, 0);
620
621 so->so_upcallusecount--;
622 /* Tell close that it's safe to proceed */
623 if ((so->so_flags & SOF_CLOSEWAIT) &&
624 so->so_upcallusecount == 0)
625 wakeup((caddr_t)&so->so_upcallusecount);
626 }
627 #if CONTENT_FILTER
628 /*
629 * Trap disconnection events for content filters
630 */
631 if ((so->so_flags & SOF_CONTENT_FILTER) != 0) {
632 if ((sb->sb_flags & SB_RECV)) {
633 if (so->so_state & (SS_CANTRCVMORE))
634 cfil_sock_notify_shutdown(so, SHUT_RD);
635 } else {
636 if (so->so_state & (SS_CANTSENDMORE))
637 cfil_sock_notify_shutdown(so, SHUT_WR);
638 }
639 }
640 #endif /* CONTENT_FILTER */
641 }
642
643 /*
644 * Socket buffer (struct sockbuf) utility routines.
645 *
646 * Each socket contains two socket buffers: one for sending data and
647 * one for receiving data. Each buffer contains a queue of mbufs,
648 * information about the number of mbufs and amount of data in the
649 * queue, and other fields allowing select() statements and notification
650 * on data availability to be implemented.
651 *
652 * Data stored in a socket buffer is maintained as a list of records.
653 * Each record is a list of mbufs chained together with the m_next
654 * field. Records are chained together with the m_nextpkt field. The upper
655 * level routine soreceive() expects the following conventions to be
656 * observed when placing information in the receive buffer:
657 *
658 * 1. If the protocol requires each message be preceded by the sender's
659 * name, then a record containing that name must be present before
660 * any associated data (mbuf's must be of type MT_SONAME).
661 * 2. If the protocol supports the exchange of ``access rights'' (really
662 * just additional data associated with the message), and there are
663 * ``rights'' to be received, then a record containing this data
664 * should be present (mbuf's must be of type MT_RIGHTS).
665 * 3. If a name or rights record exists, then it must be followed by
666 * a data record, perhaps of zero length.
667 *
668 * Before using a new socket structure it is first necessary to reserve
669 * buffer space to the socket, by calling sbreserve(). This should commit
670 * some of the available buffer space in the system buffer pool for the
671 * socket (currently, it does nothing but enforce limits). The space
672 * should be released by calling sbrelease() when the socket is destroyed.
673 */
674
675 /*
676 * Returns: 0 Success
677 * ENOBUFS
678 */
679 int
680 soreserve(struct socket *so, u_int32_t sndcc, u_int32_t rcvcc)
681 {
682
683 if (sbreserve(&so->so_snd, sndcc) == 0)
684 goto bad;
685 else
686 so->so_snd.sb_idealsize = sndcc;
687
688 if (sbreserve(&so->so_rcv, rcvcc) == 0)
689 goto bad2;
690 else
691 so->so_rcv.sb_idealsize = rcvcc;
692
693 if (so->so_rcv.sb_lowat == 0)
694 so->so_rcv.sb_lowat = 1;
695 if (so->so_snd.sb_lowat == 0)
696 so->so_snd.sb_lowat = MCLBYTES;
697 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
698 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
699 return (0);
700 bad2:
701 so->so_snd.sb_flags &= ~SB_SEL;
702 selthreadclear(&so->so_snd.sb_sel);
703 sbrelease(&so->so_snd);
704 bad:
705 return (ENOBUFS);
706 }
707
708 void
709 soreserve_preconnect(struct socket *so, unsigned int pre_cc)
710 {
711 /* As of now, same bytes for both preconnect read and write */
712 so->so_snd.sb_preconn_hiwat = pre_cc;
713 so->so_rcv.sb_preconn_hiwat = pre_cc;
714 }
715
716 /*
717 * Allot mbufs to a sockbuf.
718 * Attempt to scale mbmax so that mbcnt doesn't become limiting
719 * if buffering efficiency is near the normal case.
720 */
721 int
722 sbreserve(struct sockbuf *sb, u_int32_t cc)
723 {
724 if ((u_quad_t)cc > (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES))
725 return (0);
726 sb->sb_hiwat = cc;
727 sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
728 if (sb->sb_lowat > sb->sb_hiwat)
729 sb->sb_lowat = sb->sb_hiwat;
730 return (1);
731 }
732
733 /*
734 * Free mbufs held by a socket, and reserved mbuf space.
735 */
736 /* WARNING needs to do selthreadclear() before calling this */
737 void
738 sbrelease(struct sockbuf *sb)
739 {
740 sbflush(sb);
741 sb->sb_hiwat = 0;
742 sb->sb_mbmax = 0;
743 }
744
745 /*
746 * Routines to add and remove
747 * data from an mbuf queue.
748 *
749 * The routines sbappend() or sbappendrecord() are normally called to
750 * append new mbufs to a socket buffer, after checking that adequate
751 * space is available, comparing the function sbspace() with the amount
752 * of data to be added. sbappendrecord() differs from sbappend() in
753 * that data supplied is treated as the beginning of a new record.
754 * To place a sender's address, optional access rights, and data in a
755 * socket receive buffer, sbappendaddr() should be used. To place
756 * access rights and data in a socket receive buffer, sbappendrights()
757 * should be used. In either case, the new data begins a new record.
758 * Note that unlike sbappend() and sbappendrecord(), these routines check
759 * for the caller that there will be enough space to store the data.
760 * Each fails if there is not enough space, or if it cannot find mbufs
761 * to store additional information in.
762 *
763 * Reliable protocols may use the socket send buffer to hold data
764 * awaiting acknowledgement. Data is normally copied from a socket
765 * send buffer in a protocol with m_copy for output to a peer,
766 * and then removing the data from the socket buffer with sbdrop()
767 * or sbdroprecord() when the data is acknowledged by the peer.
768 */
769
770 /*
771 * Append mbuf chain m to the last record in the
772 * socket buffer sb. The additional space associated
773 * the mbuf chain is recorded in sb. Empty mbufs are
774 * discarded and mbufs are compacted where possible.
775 */
776 int
777 sbappend(struct sockbuf *sb, struct mbuf *m)
778 {
779 struct socket *so = sb->sb_so;
780
781 if (m == NULL || (sb->sb_flags & SB_DROP)) {
782 if (m != NULL)
783 m_freem(m);
784 return (0);
785 }
786
787 SBLASTRECORDCHK(sb, "sbappend 1");
788
789 if (sb->sb_lastrecord != NULL && (sb->sb_mbtail->m_flags & M_EOR))
790 return (sbappendrecord(sb, m));
791
792 if (sb->sb_flags & SB_RECV && !(m && m->m_flags & M_SKIPCFIL)) {
793 int error = sflt_data_in(so, NULL, &m, NULL, 0);
794 SBLASTRECORDCHK(sb, "sbappend 2");
795
796 #if CONTENT_FILTER
797 if (error == 0)
798 error = cfil_sock_data_in(so, NULL, m, NULL, 0);
799 #endif /* CONTENT_FILTER */
800
801 if (error != 0) {
802 if (error != EJUSTRETURN)
803 m_freem(m);
804 return (0);
805 }
806 } else if (m) {
807 m->m_flags &= ~M_SKIPCFIL;
808 }
809
810 /* If this is the first record, it's also the last record */
811 if (sb->sb_lastrecord == NULL)
812 sb->sb_lastrecord = m;
813
814 sbcompress(sb, m, sb->sb_mbtail);
815 SBLASTRECORDCHK(sb, "sbappend 3");
816 return (1);
817 }
818
819 /*
820 * Similar to sbappend, except that this is optimized for stream sockets.
821 */
822 int
823 sbappendstream(struct sockbuf *sb, struct mbuf *m)
824 {
825 struct socket *so = sb->sb_so;
826
827 if (m == NULL || (sb->sb_flags & SB_DROP)) {
828 if (m != NULL)
829 m_freem(m);
830 return (0);
831 }
832
833 if (m->m_nextpkt != NULL || (sb->sb_mb != sb->sb_lastrecord)) {
834 panic("sbappendstream: nexpkt %p || mb %p != lastrecord %p\n",
835 m->m_nextpkt, sb->sb_mb, sb->sb_lastrecord);
836 /* NOTREACHED */
837 }
838
839 SBLASTMBUFCHK(sb, __func__);
840
841 if (sb->sb_flags & SB_RECV && !(m && m->m_flags & M_SKIPCFIL)) {
842 int error = sflt_data_in(so, NULL, &m, NULL, 0);
843 SBLASTRECORDCHK(sb, "sbappendstream 1");
844
845 #if CONTENT_FILTER
846 if (error == 0)
847 error = cfil_sock_data_in(so, NULL, m, NULL, 0);
848 #endif /* CONTENT_FILTER */
849
850 if (error != 0) {
851 if (error != EJUSTRETURN)
852 m_freem(m);
853 return (0);
854 }
855 } else if (m) {
856 m->m_flags &= ~M_SKIPCFIL;
857 }
858
859 sbcompress(sb, m, sb->sb_mbtail);
860 sb->sb_lastrecord = sb->sb_mb;
861 SBLASTRECORDCHK(sb, "sbappendstream 2");
862 return (1);
863 }
864
865 #ifdef SOCKBUF_DEBUG
866 void
867 sbcheck(struct sockbuf *sb)
868 {
869 struct mbuf *m;
870 struct mbuf *n = 0;
871 u_int32_t len = 0, mbcnt = 0;
872 lck_mtx_t *mutex_held;
873
874 if (sb->sb_so->so_proto->pr_getlock != NULL)
875 mutex_held = (*sb->sb_so->so_proto->pr_getlock)(sb->sb_so, 0);
876 else
877 mutex_held = sb->sb_so->so_proto->pr_domain->dom_mtx;
878
879 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
880
881 if (sbchecking == 0)
882 return;
883
884 for (m = sb->sb_mb; m; m = n) {
885 n = m->m_nextpkt;
886 for (; m; m = m->m_next) {
887 len += m->m_len;
888 mbcnt += MSIZE;
889 /* XXX pretty sure this is bogus */
890 if (m->m_flags & M_EXT)
891 mbcnt += m->m_ext.ext_size;
892 }
893 }
894 if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
895 panic("cc %ld != %ld || mbcnt %ld != %ld\n", len, sb->sb_cc,
896 mbcnt, sb->sb_mbcnt);
897 }
898 }
899 #endif
900
901 void
902 sblastrecordchk(struct sockbuf *sb, const char *where)
903 {
904 struct mbuf *m = sb->sb_mb;
905
906 while (m && m->m_nextpkt)
907 m = m->m_nextpkt;
908
909 if (m != sb->sb_lastrecord) {
910 printf("sblastrecordchk: mb 0x%llx lastrecord 0x%llx "
911 "last 0x%llx\n",
912 (uint64_t)VM_KERNEL_ADDRPERM(sb->sb_mb),
913 (uint64_t)VM_KERNEL_ADDRPERM(sb->sb_lastrecord),
914 (uint64_t)VM_KERNEL_ADDRPERM(m));
915 printf("packet chain:\n");
916 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
917 printf("\t0x%llx\n", (uint64_t)VM_KERNEL_ADDRPERM(m));
918 panic("sblastrecordchk from %s", where);
919 }
920 }
921
922 void
923 sblastmbufchk(struct sockbuf *sb, const char *where)
924 {
925 struct mbuf *m = sb->sb_mb;
926 struct mbuf *n;
927
928 while (m && m->m_nextpkt)
929 m = m->m_nextpkt;
930
931 while (m && m->m_next)
932 m = m->m_next;
933
934 if (m != sb->sb_mbtail) {
935 printf("sblastmbufchk: mb 0x%llx mbtail 0x%llx last 0x%llx\n",
936 (uint64_t)VM_KERNEL_ADDRPERM(sb->sb_mb),
937 (uint64_t)VM_KERNEL_ADDRPERM(sb->sb_mbtail),
938 (uint64_t)VM_KERNEL_ADDRPERM(m));
939 printf("packet tree:\n");
940 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
941 printf("\t");
942 for (n = m; n != NULL; n = n->m_next)
943 printf("0x%llx ",
944 (uint64_t)VM_KERNEL_ADDRPERM(n));
945 printf("\n");
946 }
947 panic("sblastmbufchk from %s", where);
948 }
949 }
950
951 /*
952 * Similar to sbappend, except the mbuf chain begins a new record.
953 */
954 int
955 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
956 {
957 struct mbuf *m;
958 int space = 0;
959
960 if (m0 == NULL || (sb->sb_flags & SB_DROP)) {
961 if (m0 != NULL)
962 m_freem(m0);
963 return (0);
964 }
965
966 for (m = m0; m != NULL; m = m->m_next)
967 space += m->m_len;
968
969 if (space > sbspace(sb) && !(sb->sb_flags & SB_UNIX)) {
970 m_freem(m0);
971 return (0);
972 }
973
974 if (sb->sb_flags & SB_RECV && !(m0 && m0->m_flags & M_SKIPCFIL)) {
975 int error = sflt_data_in(sb->sb_so, NULL, &m0, NULL,
976 sock_data_filt_flag_record);
977
978 #if CONTENT_FILTER
979 if (error == 0)
980 error = cfil_sock_data_in(sb->sb_so, NULL, m0, NULL, 0);
981 #endif /* CONTENT_FILTER */
982
983 if (error != 0) {
984 SBLASTRECORDCHK(sb, "sbappendrecord 1");
985 if (error != EJUSTRETURN)
986 m_freem(m0);
987 return (0);
988 }
989 } else if (m0) {
990 m0->m_flags &= ~M_SKIPCFIL;
991 }
992
993 /*
994 * Note this permits zero length records.
995 */
996 sballoc(sb, m0);
997 SBLASTRECORDCHK(sb, "sbappendrecord 2");
998 if (sb->sb_lastrecord != NULL) {
999 sb->sb_lastrecord->m_nextpkt = m0;
1000 } else {
1001 sb->sb_mb = m0;
1002 }
1003 sb->sb_lastrecord = m0;
1004 sb->sb_mbtail = m0;
1005
1006 m = m0->m_next;
1007 m0->m_next = 0;
1008 if (m && (m0->m_flags & M_EOR)) {
1009 m0->m_flags &= ~M_EOR;
1010 m->m_flags |= M_EOR;
1011 }
1012 sbcompress(sb, m, m0);
1013 SBLASTRECORDCHK(sb, "sbappendrecord 3");
1014 return (1);
1015 }
1016
1017 /*
1018 * As above except that OOB data
1019 * is inserted at the beginning of the sockbuf,
1020 * but after any other OOB data.
1021 */
1022 int
1023 sbinsertoob(struct sockbuf *sb, struct mbuf *m0)
1024 {
1025 struct mbuf *m;
1026 struct mbuf **mp;
1027
1028 if (m0 == 0)
1029 return (0);
1030
1031 SBLASTRECORDCHK(sb, "sbinsertoob 1");
1032
1033 if ((sb->sb_flags & SB_RECV && !(m0->m_flags & M_SKIPCFIL)) != 0) {
1034 int error = sflt_data_in(sb->sb_so, NULL, &m0, NULL,
1035 sock_data_filt_flag_oob);
1036
1037 SBLASTRECORDCHK(sb, "sbinsertoob 2");
1038
1039 #if CONTENT_FILTER
1040 if (error == 0)
1041 error = cfil_sock_data_in(sb->sb_so, NULL, m0, NULL, 0);
1042 #endif /* CONTENT_FILTER */
1043
1044 if (error) {
1045 if (error != EJUSTRETURN) {
1046 m_freem(m0);
1047 }
1048 return (0);
1049 }
1050 } else if (m0) {
1051 m0->m_flags &= ~M_SKIPCFIL;
1052 }
1053
1054 for (mp = &sb->sb_mb; *mp; mp = &((*mp)->m_nextpkt)) {
1055 m = *mp;
1056 again:
1057 switch (m->m_type) {
1058
1059 case MT_OOBDATA:
1060 continue; /* WANT next train */
1061
1062 case MT_CONTROL:
1063 m = m->m_next;
1064 if (m)
1065 goto again; /* inspect THIS train further */
1066 }
1067 break;
1068 }
1069 /*
1070 * Put the first mbuf on the queue.
1071 * Note this permits zero length records.
1072 */
1073 sballoc(sb, m0);
1074 m0->m_nextpkt = *mp;
1075 if (*mp == NULL) {
1076 /* m0 is actually the new tail */
1077 sb->sb_lastrecord = m0;
1078 }
1079 *mp = m0;
1080 m = m0->m_next;
1081 m0->m_next = 0;
1082 if (m && (m0->m_flags & M_EOR)) {
1083 m0->m_flags &= ~M_EOR;
1084 m->m_flags |= M_EOR;
1085 }
1086 sbcompress(sb, m, m0);
1087 SBLASTRECORDCHK(sb, "sbinsertoob 3");
1088 return (1);
1089 }
1090
1091 /*
1092 * Append address and data, and optionally, control (ancillary) data
1093 * to the receive queue of a socket. If present,
1094 * m0 must include a packet header with total length.
1095 * Returns 0 if no space in sockbuf or insufficient mbufs.
1096 *
1097 * Returns: 0 No space/out of mbufs
1098 * 1 Success
1099 */
1100 static int
1101 sbappendaddr_internal(struct sockbuf *sb, struct sockaddr *asa,
1102 struct mbuf *m0, struct mbuf *control)
1103 {
1104 struct mbuf *m, *n, *nlast;
1105 int space = asa->sa_len;
1106
1107 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1108 panic("sbappendaddr");
1109
1110 if (m0)
1111 space += m0->m_pkthdr.len;
1112 for (n = control; n; n = n->m_next) {
1113 space += n->m_len;
1114 if (n->m_next == 0) /* keep pointer to last control buf */
1115 break;
1116 }
1117 if (space > sbspace(sb))
1118 return (0);
1119 if (asa->sa_len > MLEN)
1120 return (0);
1121 MGET(m, M_DONTWAIT, MT_SONAME);
1122 if (m == 0)
1123 return (0);
1124 m->m_len = asa->sa_len;
1125 bcopy((caddr_t)asa, mtod(m, caddr_t), asa->sa_len);
1126 if (n)
1127 n->m_next = m0; /* concatenate data to control */
1128 else
1129 control = m0;
1130 m->m_next = control;
1131
1132 SBLASTRECORDCHK(sb, "sbappendadddr 1");
1133
1134 for (n = m; n->m_next != NULL; n = n->m_next)
1135 sballoc(sb, n);
1136 sballoc(sb, n);
1137 nlast = n;
1138
1139 if (sb->sb_lastrecord != NULL) {
1140 sb->sb_lastrecord->m_nextpkt = m;
1141 } else {
1142 sb->sb_mb = m;
1143 }
1144 sb->sb_lastrecord = m;
1145 sb->sb_mbtail = nlast;
1146
1147 SBLASTMBUFCHK(sb, __func__);
1148 SBLASTRECORDCHK(sb, "sbappendadddr 2");
1149
1150 postevent(0, sb, EV_RWBYTES);
1151 return (1);
1152 }
1153
1154 /*
1155 * Returns: 0 Error: No space/out of mbufs/etc.
1156 * 1 Success
1157 *
1158 * Imputed: (*error_out) errno for error
1159 * ENOBUFS
1160 * sflt_data_in:??? [whatever a filter author chooses]
1161 */
1162 int
1163 sbappendaddr(struct sockbuf *sb, struct sockaddr *asa, struct mbuf *m0,
1164 struct mbuf *control, int *error_out)
1165 {
1166 int result = 0;
1167 boolean_t sb_unix = (sb->sb_flags & SB_UNIX);
1168
1169 if (error_out)
1170 *error_out = 0;
1171
1172 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1173 panic("sbappendaddrorfree");
1174
1175 if (sb->sb_flags & SB_DROP) {
1176 if (m0 != NULL)
1177 m_freem(m0);
1178 if (control != NULL && !sb_unix)
1179 m_freem(control);
1180 if (error_out != NULL)
1181 *error_out = EINVAL;
1182 return (0);
1183 }
1184
1185 /* Call socket data in filters */
1186 if (sb->sb_flags & SB_RECV && !(m0 && m0->m_flags & M_SKIPCFIL)) {
1187 int error;
1188 error = sflt_data_in(sb->sb_so, asa, &m0, &control, 0);
1189 SBLASTRECORDCHK(sb, __func__);
1190
1191 #if CONTENT_FILTER
1192 if (error == 0)
1193 error = cfil_sock_data_in(sb->sb_so, asa, m0, control,
1194 0);
1195 #endif /* CONTENT_FILTER */
1196
1197 if (error) {
1198 if (error != EJUSTRETURN) {
1199 if (m0)
1200 m_freem(m0);
1201 if (control != NULL && !sb_unix)
1202 m_freem(control);
1203 if (error_out)
1204 *error_out = error;
1205 }
1206 return (0);
1207 }
1208 } else if (m0) {
1209 m0->m_flags &= ~M_SKIPCFIL;
1210 }
1211
1212 result = sbappendaddr_internal(sb, asa, m0, control);
1213 if (result == 0) {
1214 if (m0)
1215 m_freem(m0);
1216 if (control != NULL && !sb_unix)
1217 m_freem(control);
1218 if (error_out)
1219 *error_out = ENOBUFS;
1220 }
1221
1222 return (result);
1223 }
1224
1225 static int
1226 sbappendcontrol_internal(struct sockbuf *sb, struct mbuf *m0,
1227 struct mbuf *control)
1228 {
1229 struct mbuf *m, *mlast, *n;
1230 int space = 0;
1231
1232 if (control == 0)
1233 panic("sbappendcontrol");
1234
1235 for (m = control; ; m = m->m_next) {
1236 space += m->m_len;
1237 if (m->m_next == 0)
1238 break;
1239 }
1240 n = m; /* save pointer to last control buffer */
1241 for (m = m0; m; m = m->m_next)
1242 space += m->m_len;
1243 if (space > sbspace(sb) && !(sb->sb_flags & SB_UNIX))
1244 return (0);
1245 n->m_next = m0; /* concatenate data to control */
1246 SBLASTRECORDCHK(sb, "sbappendcontrol 1");
1247
1248 for (m = control; m->m_next != NULL; m = m->m_next)
1249 sballoc(sb, m);
1250 sballoc(sb, m);
1251 mlast = m;
1252
1253 if (sb->sb_lastrecord != NULL) {
1254 sb->sb_lastrecord->m_nextpkt = control;
1255 } else {
1256 sb->sb_mb = control;
1257 }
1258 sb->sb_lastrecord = control;
1259 sb->sb_mbtail = mlast;
1260
1261 SBLASTMBUFCHK(sb, __func__);
1262 SBLASTRECORDCHK(sb, "sbappendcontrol 2");
1263
1264 postevent(0, sb, EV_RWBYTES);
1265 return (1);
1266 }
1267
1268 int
1269 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1270 int *error_out)
1271 {
1272 int result = 0;
1273 boolean_t sb_unix = (sb->sb_flags & SB_UNIX);
1274
1275 if (error_out)
1276 *error_out = 0;
1277
1278 if (sb->sb_flags & SB_DROP) {
1279 if (m0 != NULL)
1280 m_freem(m0);
1281 if (control != NULL && !sb_unix)
1282 m_freem(control);
1283 if (error_out != NULL)
1284 *error_out = EINVAL;
1285 return (0);
1286 }
1287
1288 if (sb->sb_flags & SB_RECV && !(m0 && m0->m_flags & M_SKIPCFIL)) {
1289 int error;
1290
1291 error = sflt_data_in(sb->sb_so, NULL, &m0, &control, 0);
1292 SBLASTRECORDCHK(sb, __func__);
1293
1294 #if CONTENT_FILTER
1295 if (error == 0)
1296 error = cfil_sock_data_in(sb->sb_so, NULL, m0, control,
1297 0);
1298 #endif /* CONTENT_FILTER */
1299
1300 if (error) {
1301 if (error != EJUSTRETURN) {
1302 if (m0)
1303 m_freem(m0);
1304 if (control != NULL && !sb_unix)
1305 m_freem(control);
1306 if (error_out)
1307 *error_out = error;
1308 }
1309 return (0);
1310 }
1311 } else if (m0) {
1312 m0->m_flags &= ~M_SKIPCFIL;
1313 }
1314
1315 result = sbappendcontrol_internal(sb, m0, control);
1316 if (result == 0) {
1317 if (m0)
1318 m_freem(m0);
1319 if (control != NULL && !sb_unix)
1320 m_freem(control);
1321 if (error_out)
1322 *error_out = ENOBUFS;
1323 }
1324
1325 return (result);
1326 }
1327
1328 /*
1329 * Append a contiguous TCP data blob with TCP sequence number as control data
1330 * as a new msg to the receive socket buffer.
1331 */
1332 int
1333 sbappendmsgstream_rcv(struct sockbuf *sb, struct mbuf *m, uint32_t seqnum,
1334 int unordered)
1335 {
1336 struct mbuf *m_eor = NULL;
1337 u_int32_t data_len = 0;
1338 int ret = 0;
1339 struct socket *so = sb->sb_so;
1340
1341 VERIFY((m->m_flags & M_PKTHDR) && m_pktlen(m) > 0);
1342 VERIFY(so->so_msg_state != NULL);
1343 VERIFY(sb->sb_flags & SB_RECV);
1344
1345 /* Keep the TCP sequence number in the mbuf pkthdr */
1346 m->m_pkthdr.msg_seq = seqnum;
1347
1348 /* find last mbuf and set M_EOR */
1349 for (m_eor = m; ; m_eor = m_eor->m_next) {
1350 /*
1351 * If the msg is unordered, we need to account for
1352 * these bytes in receive socket buffer size. Otherwise,
1353 * the receive window advertised will shrink because
1354 * of the additional unordered bytes added to the
1355 * receive buffer.
1356 */
1357 if (unordered) {
1358 m_eor->m_flags |= M_UNORDERED_DATA;
1359 data_len += m_eor->m_len;
1360 so->so_msg_state->msg_uno_bytes += m_eor->m_len;
1361 } else {
1362 m_eor->m_flags &= ~M_UNORDERED_DATA;
1363 }
1364 if (m_eor->m_next == NULL)
1365 break;
1366 }
1367
1368 /* set EOR flag at end of byte blob */
1369 m_eor->m_flags |= M_EOR;
1370
1371 /* expand the receive socket buffer to allow unordered data */
1372 if (unordered && !sbreserve(sb, sb->sb_hiwat + data_len)) {
1373 /*
1374 * Could not allocate memory for unordered data, it
1375 * means this packet will have to be delivered in order
1376 */
1377 printf("%s: could not reserve space for unordered data\n",
1378 __func__);
1379 }
1380
1381 if (!unordered && (sb->sb_mbtail != NULL) &&
1382 !(sb->sb_mbtail->m_flags & M_UNORDERED_DATA)) {
1383 sb->sb_mbtail->m_flags &= ~M_EOR;
1384 sbcompress(sb, m, sb->sb_mbtail);
1385 ret = 1;
1386 } else {
1387 ret = sbappendrecord(sb, m);
1388 }
1389 VERIFY(sb->sb_mbtail->m_flags & M_EOR);
1390 return (ret);
1391 }
1392
1393 /*
1394 * TCP streams have message based out of order delivery support, or have
1395 * Multipath TCP support, or are regular TCP sockets
1396 */
1397 int
1398 sbappendstream_rcvdemux(struct socket *so, struct mbuf *m, uint32_t seqnum,
1399 int unordered)
1400 {
1401 int ret = 0;
1402
1403 if ((m != NULL) && (m_pktlen(m) <= 0)) {
1404 m_freem(m);
1405 return (ret);
1406 }
1407
1408 if (so->so_flags & SOF_ENABLE_MSGS) {
1409 ret = sbappendmsgstream_rcv(&so->so_rcv, m, seqnum, unordered);
1410 }
1411 #if MPTCP
1412 else if (so->so_flags & SOF_MPTCP_TRUE) {
1413 ret = sbappendmptcpstream_rcv(&so->so_rcv, m);
1414 }
1415 #endif /* MPTCP */
1416 else {
1417 ret = sbappendstream(&so->so_rcv, m);
1418 }
1419 return (ret);
1420 }
1421
1422 #if MPTCP
1423 int
1424 sbappendmptcpstream_rcv(struct sockbuf *sb, struct mbuf *m)
1425 {
1426 struct socket *so = sb->sb_so;
1427
1428 VERIFY(m == NULL || (m->m_flags & M_PKTHDR));
1429 /* SB_NOCOMPRESS must be set prevent loss of M_PKTHDR data */
1430 VERIFY((sb->sb_flags & (SB_RECV|SB_NOCOMPRESS)) ==
1431 (SB_RECV|SB_NOCOMPRESS));
1432
1433 if (m == NULL || m_pktlen(m) == 0 || (sb->sb_flags & SB_DROP) ||
1434 (so->so_state & SS_CANTRCVMORE)) {
1435 if (m != NULL)
1436 m_freem(m);
1437 return (0);
1438 }
1439 /* the socket is not closed, so SOF_MP_SUBFLOW must be set */
1440 VERIFY(so->so_flags & SOF_MP_SUBFLOW);
1441
1442 if (m->m_nextpkt != NULL || (sb->sb_mb != sb->sb_lastrecord)) {
1443 panic("%s: nexpkt %p || mb %p != lastrecord %p\n", __func__,
1444 m->m_nextpkt, sb->sb_mb, sb->sb_lastrecord);
1445 /* NOTREACHED */
1446 }
1447
1448 SBLASTMBUFCHK(sb, __func__);
1449
1450 if (mptcp_adj_rmap(so, m) != 0)
1451 return (0);
1452
1453 /* No filter support (SB_RECV) on mptcp subflow sockets */
1454
1455 sbcompress(sb, m, sb->sb_mbtail);
1456 sb->sb_lastrecord = sb->sb_mb;
1457 SBLASTRECORDCHK(sb, __func__);
1458 return (1);
1459 }
1460 #endif /* MPTCP */
1461
1462 /*
1463 * Append message to send socket buffer based on priority.
1464 */
1465 int
1466 sbappendmsg_snd(struct sockbuf *sb, struct mbuf *m)
1467 {
1468 struct socket *so = sb->sb_so;
1469 struct msg_priq *priq;
1470 int set_eor = 0;
1471
1472 VERIFY(so->so_msg_state != NULL);
1473
1474 if (m->m_nextpkt != NULL || (sb->sb_mb != sb->sb_lastrecord))
1475 panic("sbappendstream: nexpkt %p || mb %p != lastrecord %p\n",
1476 m->m_nextpkt, sb->sb_mb, sb->sb_lastrecord);
1477
1478 SBLASTMBUFCHK(sb, __func__);
1479
1480 if (m == NULL || (sb->sb_flags & SB_DROP) || so->so_msg_state == NULL) {
1481 if (m != NULL)
1482 m_freem(m);
1483 return (0);
1484 }
1485
1486 priq = &so->so_msg_state->msg_priq[m->m_pkthdr.msg_pri];
1487
1488 /* note if we need to propogate M_EOR to the last mbuf */
1489 if (m->m_flags & M_EOR) {
1490 set_eor = 1;
1491
1492 /* Reset M_EOR from the first mbuf */
1493 m->m_flags &= ~(M_EOR);
1494 }
1495
1496 if (priq->msgq_head == NULL) {
1497 VERIFY(priq->msgq_tail == NULL && priq->msgq_lastmsg == NULL);
1498 priq->msgq_head = priq->msgq_lastmsg = m;
1499 } else {
1500 VERIFY(priq->msgq_tail->m_next == NULL);
1501
1502 /* Check if the last message has M_EOR flag set */
1503 if (priq->msgq_tail->m_flags & M_EOR) {
1504 /* Insert as a new message */
1505 priq->msgq_lastmsg->m_nextpkt = m;
1506
1507 /* move the lastmsg pointer */
1508 priq->msgq_lastmsg = m;
1509 } else {
1510 /* Append to the existing message */
1511 priq->msgq_tail->m_next = m;
1512 }
1513 }
1514
1515 /* Update accounting and the queue tail pointer */
1516
1517 while (m->m_next != NULL) {
1518 sballoc(sb, m);
1519 priq->msgq_bytes += m->m_len;
1520 m = m->m_next;
1521 }
1522 sballoc(sb, m);
1523 priq->msgq_bytes += m->m_len;
1524
1525 if (set_eor) {
1526 m->m_flags |= M_EOR;
1527
1528 /*
1529 * Since the user space can not write a new msg
1530 * without completing the previous one, we can
1531 * reset this flag to start sending again.
1532 */
1533 priq->msgq_flags &= ~(MSGQ_MSG_NOTDONE);
1534 }
1535
1536 priq->msgq_tail = m;
1537
1538 SBLASTRECORDCHK(sb, "sbappendstream 2");
1539 postevent(0, sb, EV_RWBYTES);
1540 return (1);
1541 }
1542
1543 /*
1544 * Pull data from priority queues to the serial snd queue
1545 * right before sending.
1546 */
1547 void
1548 sbpull_unordered_data(struct socket *so, int32_t off, int32_t len)
1549 {
1550 int32_t topull, i;
1551 struct msg_priq *priq = NULL;
1552
1553 VERIFY(so->so_msg_state != NULL);
1554
1555 topull = (off + len) - so->so_msg_state->msg_serial_bytes;
1556
1557 i = MSG_PRI_MAX;
1558 while (i >= MSG_PRI_MIN && topull > 0) {
1559 struct mbuf *m = NULL, *mqhead = NULL, *mend = NULL;
1560 priq = &so->so_msg_state->msg_priq[i];
1561 if ((priq->msgq_flags & MSGQ_MSG_NOTDONE) &&
1562 priq->msgq_head == NULL) {
1563 /*
1564 * We were in the middle of sending
1565 * a message and we have not seen the
1566 * end of it.
1567 */
1568 VERIFY(priq->msgq_lastmsg == NULL &&
1569 priq->msgq_tail == NULL);
1570 return;
1571 }
1572 if (priq->msgq_head != NULL) {
1573 int32_t bytes = 0, topull_tmp = topull;
1574 /*
1575 * We found a msg while scanning the priority
1576 * queue from high to low priority.
1577 */
1578 m = priq->msgq_head;
1579 mqhead = m;
1580 mend = m;
1581
1582 /*
1583 * Move bytes from the priority queue to the
1584 * serial queue. Compute the number of bytes
1585 * being added.
1586 */
1587 while (mqhead->m_next != NULL && topull_tmp > 0) {
1588 bytes += mqhead->m_len;
1589 topull_tmp -= mqhead->m_len;
1590 mend = mqhead;
1591 mqhead = mqhead->m_next;
1592 }
1593
1594 if (mqhead->m_next == NULL) {
1595 /*
1596 * If we have only one more mbuf left,
1597 * move the last mbuf of this message to
1598 * serial queue and set the head of the
1599 * queue to be the next message.
1600 */
1601 bytes += mqhead->m_len;
1602 mend = mqhead;
1603 mqhead = m->m_nextpkt;
1604 if (!(mend->m_flags & M_EOR)) {
1605 /*
1606 * We have not seen the end of
1607 * this message, so we can not
1608 * pull anymore.
1609 */
1610 priq->msgq_flags |= MSGQ_MSG_NOTDONE;
1611 } else {
1612 /* Reset M_EOR */
1613 mend->m_flags &= ~(M_EOR);
1614 }
1615 } else {
1616 /* propogate the next msg pointer */
1617 mqhead->m_nextpkt = m->m_nextpkt;
1618 }
1619 priq->msgq_head = mqhead;
1620
1621 /*
1622 * if the lastmsg pointer points to
1623 * the mbuf that is being dequeued, update
1624 * it to point to the new head.
1625 */
1626 if (priq->msgq_lastmsg == m)
1627 priq->msgq_lastmsg = priq->msgq_head;
1628
1629 m->m_nextpkt = NULL;
1630 mend->m_next = NULL;
1631
1632 if (priq->msgq_head == NULL) {
1633 /* Moved all messages, update tail */
1634 priq->msgq_tail = NULL;
1635 VERIFY(priq->msgq_lastmsg == NULL);
1636 }
1637
1638 /* Move it to serial sb_mb queue */
1639 if (so->so_snd.sb_mb == NULL) {
1640 so->so_snd.sb_mb = m;
1641 } else {
1642 so->so_snd.sb_mbtail->m_next = m;
1643 }
1644
1645 priq->msgq_bytes -= bytes;
1646 VERIFY(priq->msgq_bytes >= 0);
1647 sbwakeup(&so->so_snd);
1648
1649 so->so_msg_state->msg_serial_bytes += bytes;
1650 so->so_snd.sb_mbtail = mend;
1651 so->so_snd.sb_lastrecord = so->so_snd.sb_mb;
1652
1653 topull =
1654 (off + len) - so->so_msg_state->msg_serial_bytes;
1655
1656 if (priq->msgq_flags & MSGQ_MSG_NOTDONE)
1657 break;
1658 } else {
1659 --i;
1660 }
1661 }
1662 sblastrecordchk(&so->so_snd, "sbpull_unordered_data");
1663 sblastmbufchk(&so->so_snd, "sbpull_unordered_data");
1664 }
1665
1666 /*
1667 * Compress mbuf chain m into the socket
1668 * buffer sb following mbuf n. If n
1669 * is null, the buffer is presumed empty.
1670 */
1671 static inline void
1672 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1673 {
1674 int eor = 0, compress = (!(sb->sb_flags & SB_NOCOMPRESS));
1675 struct mbuf *o;
1676
1677 if (m == NULL) {
1678 /* There is nothing to compress; just update the tail */
1679 for (; n->m_next != NULL; n = n->m_next)
1680 ;
1681 sb->sb_mbtail = n;
1682 goto done;
1683 }
1684
1685 while (m != NULL) {
1686 eor |= m->m_flags & M_EOR;
1687 if (compress && m->m_len == 0 && (eor == 0 ||
1688 (((o = m->m_next) || (o = n)) && o->m_type == m->m_type))) {
1689 if (sb->sb_lastrecord == m)
1690 sb->sb_lastrecord = m->m_next;
1691 m = m_free(m);
1692 continue;
1693 }
1694 if (compress && n != NULL && (n->m_flags & M_EOR) == 0 &&
1695 #ifndef __APPLE__
1696 M_WRITABLE(n) &&
1697 #endif
1698 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1699 m->m_len <= M_TRAILINGSPACE(n) &&
1700 n->m_type == m->m_type) {
1701 bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
1702 (unsigned)m->m_len);
1703 n->m_len += m->m_len;
1704 sb->sb_cc += m->m_len;
1705 if (m->m_type != MT_DATA && m->m_type != MT_HEADER &&
1706 m->m_type != MT_OOBDATA) {
1707 /* XXX: Probably don't need */
1708 sb->sb_ctl += m->m_len;
1709 }
1710
1711 /* update send byte count */
1712 if (sb->sb_flags & SB_SNDBYTE_CNT) {
1713 inp_incr_sndbytes_total(sb->sb_so,
1714 m->m_len);
1715 inp_incr_sndbytes_unsent(sb->sb_so,
1716 m->m_len);
1717 }
1718 m = m_free(m);
1719 continue;
1720 }
1721 if (n != NULL)
1722 n->m_next = m;
1723 else
1724 sb->sb_mb = m;
1725 sb->sb_mbtail = m;
1726 sballoc(sb, m);
1727 n = m;
1728 m->m_flags &= ~M_EOR;
1729 m = m->m_next;
1730 n->m_next = NULL;
1731 }
1732 if (eor != 0) {
1733 if (n != NULL)
1734 n->m_flags |= eor;
1735 else
1736 printf("semi-panic: sbcompress\n");
1737 }
1738 done:
1739 SBLASTMBUFCHK(sb, __func__);
1740 postevent(0, sb, EV_RWBYTES);
1741 }
1742
1743 void
1744 sb_empty_assert(struct sockbuf *sb, const char *where)
1745 {
1746 if (!(sb->sb_cc == 0 && sb->sb_mb == NULL && sb->sb_mbcnt == 0 &&
1747 sb->sb_mbtail == NULL && sb->sb_lastrecord == NULL)) {
1748 panic("%s: sb %p so %p cc %d mbcnt %d mb %p mbtail %p "
1749 "lastrecord %p\n", where, sb, sb->sb_so, sb->sb_cc,
1750 sb->sb_mbcnt, sb->sb_mb, sb->sb_mbtail,
1751 sb->sb_lastrecord);
1752 /* NOTREACHED */
1753 }
1754 }
1755
1756 static void
1757 sbflush_priq(struct msg_priq *priq)
1758 {
1759 struct mbuf *m;
1760 m = priq->msgq_head;
1761 if (m != NULL)
1762 m_freem_list(m);
1763 priq->msgq_head = priq->msgq_tail = priq->msgq_lastmsg = NULL;
1764 priq->msgq_bytes = priq->msgq_flags = 0;
1765 }
1766
1767 /*
1768 * Free all mbufs in a sockbuf.
1769 * Check that all resources are reclaimed.
1770 */
1771 void
1772 sbflush(struct sockbuf *sb)
1773 {
1774 void *lr_saved = __builtin_return_address(0);
1775 struct socket *so = sb->sb_so;
1776 u_int32_t i;
1777
1778 /* so_usecount may be 0 if we get here from sofreelastref() */
1779 if (so == NULL) {
1780 panic("%s: null so, sb=%p sb_flags=0x%x lr=%p\n",
1781 __func__, sb, sb->sb_flags, lr_saved);
1782 /* NOTREACHED */
1783 } else if (so->so_usecount < 0) {
1784 panic("%s: sb=%p sb_flags=0x%x sb_so=%p usecount=%d lr=%p "
1785 "lrh= %s\n", __func__, sb, sb->sb_flags, so,
1786 so->so_usecount, lr_saved, solockhistory_nr(so));
1787 /* NOTREACHED */
1788 }
1789
1790 /*
1791 * Obtain lock on the socket buffer (SB_LOCK). This is required
1792 * to prevent the socket buffer from being unexpectedly altered
1793 * while it is used by another thread in socket send/receive.
1794 *
1795 * sblock() must not fail here, hence the assertion.
1796 */
1797 (void) sblock(sb, SBL_WAIT | SBL_NOINTR | SBL_IGNDEFUNCT);
1798 VERIFY(sb->sb_flags & SB_LOCK);
1799
1800 while (sb->sb_mbcnt > 0) {
1801 /*
1802 * Don't call sbdrop(sb, 0) if the leading mbuf is non-empty:
1803 * we would loop forever. Panic instead.
1804 */
1805 if (!sb->sb_cc && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1806 break;
1807 sbdrop(sb, (int)sb->sb_cc);
1808 }
1809
1810 if (!(sb->sb_flags & SB_RECV) && (so->so_flags & SOF_ENABLE_MSGS)) {
1811 VERIFY(so->so_msg_state != NULL);
1812 for (i = MSG_PRI_MIN; i <= MSG_PRI_MAX; ++i) {
1813 sbflush_priq(&so->so_msg_state->msg_priq[i]);
1814 }
1815 so->so_msg_state->msg_serial_bytes = 0;
1816 so->so_msg_state->msg_uno_bytes = 0;
1817 }
1818
1819 sb_empty_assert(sb, __func__);
1820 postevent(0, sb, EV_RWBYTES);
1821
1822 sbunlock(sb, TRUE); /* keep socket locked */
1823 }
1824
1825 /*
1826 * Drop data from (the front of) a sockbuf.
1827 * use m_freem_list to free the mbuf structures
1828 * under a single lock... this is done by pruning
1829 * the top of the tree from the body by keeping track
1830 * of where we get to in the tree and then zeroing the
1831 * two pertinent pointers m_nextpkt and m_next
1832 * the socket buffer is then updated to point at the new
1833 * top of the tree and the pruned area is released via
1834 * m_freem_list.
1835 */
1836 void
1837 sbdrop(struct sockbuf *sb, int len)
1838 {
1839 struct mbuf *m, *free_list, *ml;
1840 struct mbuf *next, *last;
1841
1842 next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1843 #if MPTCP
1844 if ((m != NULL) && (len > 0) &&
1845 (!(sb->sb_flags & SB_RECV)) &&
1846 ((sb->sb_so->so_flags & SOF_MP_SUBFLOW) ||
1847 ((SOCK_CHECK_DOM(sb->sb_so, PF_MULTIPATH)) &&
1848 (SOCK_CHECK_PROTO(sb->sb_so, IPPROTO_TCP)))) &&
1849 (!(sb->sb_so->so_flags1 & SOF1_POST_FALLBACK_SYNC))) {
1850 mptcp_preproc_sbdrop(sb->sb_so, m, (unsigned int)len);
1851 }
1852 #endif /* MPTCP */
1853 KERNEL_DEBUG((DBG_FNC_SBDROP | DBG_FUNC_START), sb, len, 0, 0, 0);
1854
1855 free_list = last = m;
1856 ml = (struct mbuf *)0;
1857
1858 while (len > 0) {
1859 if (m == NULL) {
1860 if (next == NULL) {
1861 /*
1862 * temporarily replacing this panic with printf
1863 * because it occurs occasionally when closing
1864 * a socket when there is no harm in ignoring
1865 * it. This problem will be investigated
1866 * further.
1867 */
1868 /* panic("sbdrop"); */
1869 printf("sbdrop - count not zero\n");
1870 len = 0;
1871 /*
1872 * zero the counts. if we have no mbufs,
1873 * we have no data (PR-2986815)
1874 */
1875 sb->sb_cc = 0;
1876 sb->sb_mbcnt = 0;
1877 if (!(sb->sb_flags & SB_RECV) &&
1878 (sb->sb_so->so_flags & SOF_ENABLE_MSGS)) {
1879 sb->sb_so->so_msg_state->
1880 msg_serial_bytes = 0;
1881 }
1882 break;
1883 }
1884 m = last = next;
1885 next = m->m_nextpkt;
1886 continue;
1887 }
1888 if (m->m_len > len) {
1889 m->m_len -= len;
1890 m->m_data += len;
1891 sb->sb_cc -= len;
1892 /* update the send byte count */
1893 if (sb->sb_flags & SB_SNDBYTE_CNT)
1894 inp_decr_sndbytes_total(sb->sb_so, len);
1895 if (m->m_type != MT_DATA && m->m_type != MT_HEADER &&
1896 m->m_type != MT_OOBDATA)
1897 sb->sb_ctl -= len;
1898 break;
1899 }
1900 len -= m->m_len;
1901 sbfree(sb, m);
1902
1903 ml = m;
1904 m = m->m_next;
1905 }
1906 while (m && m->m_len == 0) {
1907 sbfree(sb, m);
1908
1909 ml = m;
1910 m = m->m_next;
1911 }
1912 if (ml) {
1913 ml->m_next = (struct mbuf *)0;
1914 last->m_nextpkt = (struct mbuf *)0;
1915 m_freem_list(free_list);
1916 }
1917 if (m) {
1918 sb->sb_mb = m;
1919 m->m_nextpkt = next;
1920 } else {
1921 sb->sb_mb = next;
1922 }
1923
1924 /*
1925 * First part is an inline SB_EMPTY_FIXUP(). Second part
1926 * makes sure sb_lastrecord is up-to-date if we dropped
1927 * part of the last record.
1928 */
1929 m = sb->sb_mb;
1930 if (m == NULL) {
1931 sb->sb_mbtail = NULL;
1932 sb->sb_lastrecord = NULL;
1933 } else if (m->m_nextpkt == NULL) {
1934 sb->sb_lastrecord = m;
1935 }
1936
1937 #if CONTENT_FILTER
1938 cfil_sock_buf_update(sb);
1939 #endif /* CONTENT_FILTER */
1940
1941 postevent(0, sb, EV_RWBYTES);
1942
1943 KERNEL_DEBUG((DBG_FNC_SBDROP | DBG_FUNC_END), sb, 0, 0, 0, 0);
1944 }
1945
1946 /*
1947 * Drop a record off the front of a sockbuf
1948 * and move the next record to the front.
1949 */
1950 void
1951 sbdroprecord(struct sockbuf *sb)
1952 {
1953 struct mbuf *m, *mn;
1954
1955 m = sb->sb_mb;
1956 if (m) {
1957 sb->sb_mb = m->m_nextpkt;
1958 do {
1959 sbfree(sb, m);
1960 MFREE(m, mn);
1961 m = mn;
1962 } while (m);
1963 }
1964 SB_EMPTY_FIXUP(sb);
1965 postevent(0, sb, EV_RWBYTES);
1966 }
1967
1968 /*
1969 * Create a "control" mbuf containing the specified data
1970 * with the specified type for presentation on a socket buffer.
1971 */
1972 struct mbuf *
1973 sbcreatecontrol(caddr_t p, int size, int type, int level)
1974 {
1975 struct cmsghdr *cp;
1976 struct mbuf *m;
1977
1978 if (CMSG_SPACE((u_int)size) > MLEN)
1979 return ((struct mbuf *)NULL);
1980 if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
1981 return ((struct mbuf *)NULL);
1982 cp = mtod(m, struct cmsghdr *);
1983 VERIFY(IS_P2ALIGNED(cp, sizeof (u_int32_t)));
1984 /* XXX check size? */
1985 (void) memcpy(CMSG_DATA(cp), p, size);
1986 m->m_len = CMSG_SPACE(size);
1987 cp->cmsg_len = CMSG_LEN(size);
1988 cp->cmsg_level = level;
1989 cp->cmsg_type = type;
1990 return (m);
1991 }
1992
1993 struct mbuf **
1994 sbcreatecontrol_mbuf(caddr_t p, int size, int type, int level, struct mbuf **mp)
1995 {
1996 struct mbuf *m;
1997 struct cmsghdr *cp;
1998
1999 if (*mp == NULL) {
2000 *mp = sbcreatecontrol(p, size, type, level);
2001 return (mp);
2002 }
2003
2004 if (CMSG_SPACE((u_int)size) + (*mp)->m_len > MLEN) {
2005 mp = &(*mp)->m_next;
2006 *mp = sbcreatecontrol(p, size, type, level);
2007 return (mp);
2008 }
2009
2010 m = *mp;
2011
2012 cp = (struct cmsghdr *)(void *)(mtod(m, char *) + m->m_len);
2013 /* CMSG_SPACE ensures 32-bit alignment */
2014 VERIFY(IS_P2ALIGNED(cp, sizeof (u_int32_t)));
2015 m->m_len += CMSG_SPACE(size);
2016
2017 /* XXX check size? */
2018 (void) memcpy(CMSG_DATA(cp), p, size);
2019 cp->cmsg_len = CMSG_LEN(size);
2020 cp->cmsg_level = level;
2021 cp->cmsg_type = type;
2022
2023 return (mp);
2024 }
2025
2026
2027 /*
2028 * Some routines that return EOPNOTSUPP for entry points that are not
2029 * supported by a protocol. Fill in as needed.
2030 */
2031 int
2032 pru_abort_notsupp(struct socket *so)
2033 {
2034 #pragma unused(so)
2035 return (EOPNOTSUPP);
2036 }
2037
2038 int
2039 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
2040 {
2041 #pragma unused(so, nam)
2042 return (EOPNOTSUPP);
2043 }
2044
2045 int
2046 pru_attach_notsupp(struct socket *so, int proto, struct proc *p)
2047 {
2048 #pragma unused(so, proto, p)
2049 return (EOPNOTSUPP);
2050 }
2051
2052 int
2053 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct proc *p)
2054 {
2055 #pragma unused(so, nam, p)
2056 return (EOPNOTSUPP);
2057 }
2058
2059 int
2060 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct proc *p)
2061 {
2062 #pragma unused(so, nam, p)
2063 return (EOPNOTSUPP);
2064 }
2065
2066 int
2067 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
2068 {
2069 #pragma unused(so1, so2)
2070 return (EOPNOTSUPP);
2071 }
2072
2073 int
2074 pru_connectx_notsupp(struct socket *so, struct sockaddr_list **src_sl,
2075 struct sockaddr_list **dst_sl, struct proc *p, uint32_t ifscope,
2076 sae_associd_t aid, sae_connid_t *pcid, uint32_t flags, void *arg,
2077 uint32_t arglen, struct uio *uio, user_ssize_t *bytes_written)
2078 {
2079 #pragma unused(so, src_sl, dst_sl, p, ifscope, aid, pcid, flags, arg, arglen, uio, bytes_written)
2080 return (EOPNOTSUPP);
2081 }
2082
2083 int
2084 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
2085 struct ifnet *ifp, struct proc *p)
2086 {
2087 #pragma unused(so, cmd, data, ifp, p)
2088 return (EOPNOTSUPP);
2089 }
2090
2091 int
2092 pru_detach_notsupp(struct socket *so)
2093 {
2094 #pragma unused(so)
2095 return (EOPNOTSUPP);
2096 }
2097
2098 int
2099 pru_disconnect_notsupp(struct socket *so)
2100 {
2101 #pragma unused(so)
2102 return (EOPNOTSUPP);
2103 }
2104
2105 int
2106 pru_disconnectx_notsupp(struct socket *so, sae_associd_t aid, sae_connid_t cid)
2107 {
2108 #pragma unused(so, aid, cid)
2109 return (EOPNOTSUPP);
2110 }
2111
2112 int
2113 pru_listen_notsupp(struct socket *so, struct proc *p)
2114 {
2115 #pragma unused(so, p)
2116 return (EOPNOTSUPP);
2117 }
2118
2119 int
2120 pru_peeloff_notsupp(struct socket *so, sae_associd_t aid, struct socket **psop)
2121 {
2122 #pragma unused(so, aid, psop)
2123 return (EOPNOTSUPP);
2124 }
2125
2126 int
2127 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
2128 {
2129 #pragma unused(so, nam)
2130 return (EOPNOTSUPP);
2131 }
2132
2133 int
2134 pru_rcvd_notsupp(struct socket *so, int flags)
2135 {
2136 #pragma unused(so, flags)
2137 return (EOPNOTSUPP);
2138 }
2139
2140 int
2141 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
2142 {
2143 #pragma unused(so, m, flags)
2144 return (EOPNOTSUPP);
2145 }
2146
2147 int
2148 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
2149 struct sockaddr *addr, struct mbuf *control, struct proc *p)
2150 {
2151 #pragma unused(so, flags, m, addr, control, p)
2152 return (EOPNOTSUPP);
2153 }
2154
2155 int
2156 pru_send_list_notsupp(struct socket *so, int flags, struct mbuf *m,
2157 struct sockaddr *addr, struct mbuf *control, struct proc *p)
2158 {
2159 #pragma unused(so, flags, m, addr, control, p)
2160 return (EOPNOTSUPP);
2161 }
2162
2163 /*
2164 * This isn't really a ``null'' operation, but it's the default one
2165 * and doesn't do anything destructive.
2166 */
2167 int
2168 pru_sense_null(struct socket *so, void *ub, int isstat64)
2169 {
2170 if (isstat64 != 0) {
2171 struct stat64 *sb64;
2172
2173 sb64 = (struct stat64 *)ub;
2174 sb64->st_blksize = so->so_snd.sb_hiwat;
2175 } else {
2176 struct stat *sb;
2177
2178 sb = (struct stat *)ub;
2179 sb->st_blksize = so->so_snd.sb_hiwat;
2180 }
2181
2182 return (0);
2183 }
2184
2185
2186 int
2187 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
2188 struct mbuf *top, struct mbuf *control, int flags)
2189 {
2190 #pragma unused(so, addr, uio, top, control, flags)
2191 return (EOPNOTSUPP);
2192 }
2193
2194 int
2195 pru_sosend_list_notsupp(struct socket *so, struct uio **uio,
2196 u_int uiocnt, int flags)
2197 {
2198 #pragma unused(so, uio, uiocnt, flags)
2199 return (EOPNOTSUPP);
2200 }
2201
2202 int
2203 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
2204 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2205 {
2206 #pragma unused(so, paddr, uio, mp0, controlp, flagsp)
2207 return (EOPNOTSUPP);
2208 }
2209
2210 int
2211 pru_soreceive_list_notsupp(struct socket *so,
2212 struct recv_msg_elem *recv_msg_array, u_int uiocnt, int *flagsp)
2213 {
2214 #pragma unused(so, recv_msg_array, uiocnt, flagsp)
2215 return (EOPNOTSUPP);
2216 }
2217
2218 int
2219 pru_shutdown_notsupp(struct socket *so)
2220 {
2221 #pragma unused(so)
2222 return (EOPNOTSUPP);
2223 }
2224
2225 int
2226 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
2227 {
2228 #pragma unused(so, nam)
2229 return (EOPNOTSUPP);
2230 }
2231
2232 int
2233 pru_sopoll_notsupp(struct socket *so, int events, kauth_cred_t cred, void *wql)
2234 {
2235 #pragma unused(so, events, cred, wql)
2236 return (EOPNOTSUPP);
2237 }
2238
2239 int
2240 pru_socheckopt_null(struct socket *so, struct sockopt *sopt)
2241 {
2242 #pragma unused(so, sopt)
2243 /*
2244 * Allow all options for set/get by default.
2245 */
2246 return (0);
2247 }
2248
2249 static int
2250 pru_preconnect_null(struct socket *so)
2251 {
2252 #pragma unused(so)
2253 return (0);
2254 }
2255
2256 void
2257 pru_sanitize(struct pr_usrreqs *pru)
2258 {
2259 #define DEFAULT(foo, bar) if ((foo) == NULL) (foo) = (bar)
2260 DEFAULT(pru->pru_abort, pru_abort_notsupp);
2261 DEFAULT(pru->pru_accept, pru_accept_notsupp);
2262 DEFAULT(pru->pru_attach, pru_attach_notsupp);
2263 DEFAULT(pru->pru_bind, pru_bind_notsupp);
2264 DEFAULT(pru->pru_connect, pru_connect_notsupp);
2265 DEFAULT(pru->pru_connect2, pru_connect2_notsupp);
2266 DEFAULT(pru->pru_connectx, pru_connectx_notsupp);
2267 DEFAULT(pru->pru_control, pru_control_notsupp);
2268 DEFAULT(pru->pru_detach, pru_detach_notsupp);
2269 DEFAULT(pru->pru_disconnect, pru_disconnect_notsupp);
2270 DEFAULT(pru->pru_disconnectx, pru_disconnectx_notsupp);
2271 DEFAULT(pru->pru_listen, pru_listen_notsupp);
2272 DEFAULT(pru->pru_peeloff, pru_peeloff_notsupp);
2273 DEFAULT(pru->pru_peeraddr, pru_peeraddr_notsupp);
2274 DEFAULT(pru->pru_rcvd, pru_rcvd_notsupp);
2275 DEFAULT(pru->pru_rcvoob, pru_rcvoob_notsupp);
2276 DEFAULT(pru->pru_send, pru_send_notsupp);
2277 DEFAULT(pru->pru_send_list, pru_send_list_notsupp);
2278 DEFAULT(pru->pru_sense, pru_sense_null);
2279 DEFAULT(pru->pru_shutdown, pru_shutdown_notsupp);
2280 DEFAULT(pru->pru_sockaddr, pru_sockaddr_notsupp);
2281 DEFAULT(pru->pru_sopoll, pru_sopoll_notsupp);
2282 DEFAULT(pru->pru_soreceive, pru_soreceive_notsupp);
2283 DEFAULT(pru->pru_soreceive_list, pru_soreceive_list_notsupp);
2284 DEFAULT(pru->pru_sosend, pru_sosend_notsupp);
2285 DEFAULT(pru->pru_sosend_list, pru_sosend_list_notsupp);
2286 DEFAULT(pru->pru_socheckopt, pru_socheckopt_null);
2287 DEFAULT(pru->pru_preconnect, pru_preconnect_null);
2288 #undef DEFAULT
2289 }
2290
2291 /*
2292 * The following are macros on BSD and functions on Darwin
2293 */
2294
2295 /*
2296 * Do we need to notify the other side when I/O is possible?
2297 */
2298
2299 int
2300 sb_notify(struct sockbuf *sb)
2301 {
2302 return (sb->sb_waiters > 0 ||
2303 (sb->sb_flags & (SB_SEL|SB_ASYNC|SB_UPCALL|SB_KNOTE)));
2304 }
2305
2306 /*
2307 * How much space is there in a socket buffer (so->so_snd or so->so_rcv)?
2308 * This is problematical if the fields are unsigned, as the space might
2309 * still be negative (cc > hiwat or mbcnt > mbmax). Should detect
2310 * overflow and return 0.
2311 */
2312 int
2313 sbspace(struct sockbuf *sb)
2314 {
2315 int pending = 0;
2316 int space = imin((int)(sb->sb_hiwat - sb->sb_cc),
2317 (int)(sb->sb_mbmax - sb->sb_mbcnt));
2318
2319 if (sb->sb_preconn_hiwat != 0)
2320 space = imin((int)(sb->sb_preconn_hiwat - sb->sb_cc), space);
2321
2322 if (space < 0)
2323 space = 0;
2324
2325 /* Compensate for data being processed by content filters */
2326 #if CONTENT_FILTER
2327 pending = cfil_sock_data_space(sb);
2328 #endif /* CONTENT_FILTER */
2329 if (pending > space)
2330 space = 0;
2331 else
2332 space -= pending;
2333
2334 return (space);
2335 }
2336
2337 /*
2338 * If this socket has priority queues, check if there is enough
2339 * space in the priority queue for this msg.
2340 */
2341 int
2342 msgq_sbspace(struct socket *so, struct mbuf *control)
2343 {
2344 int space = 0, error;
2345 u_int32_t msgpri;
2346 VERIFY(so->so_type == SOCK_STREAM &&
2347 SOCK_PROTO(so) == IPPROTO_TCP);
2348 if (control != NULL) {
2349 error = tcp_get_msg_priority(control, &msgpri);
2350 if (error)
2351 return (0);
2352 } else {
2353 msgpri = MSG_PRI_0;
2354 }
2355 space = (so->so_snd.sb_idealsize / MSG_PRI_COUNT) -
2356 so->so_msg_state->msg_priq[msgpri].msgq_bytes;
2357 if (space < 0)
2358 space = 0;
2359 return (space);
2360 }
2361
2362 /* do we have to send all at once on a socket? */
2363 int
2364 sosendallatonce(struct socket *so)
2365 {
2366 return (so->so_proto->pr_flags & PR_ATOMIC);
2367 }
2368
2369 /* can we read something from so? */
2370 int
2371 soreadable(struct socket *so)
2372 {
2373 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
2374 ((so->so_state & SS_CANTRCVMORE)
2375 #if CONTENT_FILTER
2376 && cfil_sock_data_pending(&so->so_rcv) == 0
2377 #endif /* CONTENT_FILTER */
2378 ) ||
2379 so->so_comp.tqh_first || so->so_error);
2380 }
2381
2382 /* can we write something to so? */
2383
2384 int
2385 sowriteable(struct socket *so)
2386 {
2387 if ((so->so_state & SS_CANTSENDMORE) ||
2388 so->so_error > 0)
2389 return (1);
2390 if (so_wait_for_if_feedback(so) || !socanwrite(so))
2391 return (0);
2392 if (so->so_flags1 & SOF1_PRECONNECT_DATA)
2393 return(1);
2394
2395 if (sbspace(&(so)->so_snd) >= (so)->so_snd.sb_lowat) {
2396 if (so->so_flags & SOF_NOTSENT_LOWAT) {
2397 if ((SOCK_DOM(so) == PF_INET6 ||
2398 SOCK_DOM(so) == PF_INET) &&
2399 so->so_type == SOCK_STREAM) {
2400 return (tcp_notsent_lowat_check(so));
2401 }
2402 #if MPTCP
2403 else if ((SOCK_DOM(so) == PF_MULTIPATH) &&
2404 (SOCK_PROTO(so) == IPPROTO_TCP)) {
2405 return (mptcp_notsent_lowat_check(so));
2406 }
2407 #endif
2408 else {
2409 return (1);
2410 }
2411 } else {
2412 return (1);
2413 }
2414 }
2415 return (0);
2416 }
2417
2418 /* adjust counters in sb reflecting allocation of m */
2419
2420 void
2421 sballoc(struct sockbuf *sb, struct mbuf *m)
2422 {
2423 u_int32_t cnt = 1;
2424 sb->sb_cc += m->m_len;
2425 if (m->m_type != MT_DATA && m->m_type != MT_HEADER &&
2426 m->m_type != MT_OOBDATA)
2427 sb->sb_ctl += m->m_len;
2428 sb->sb_mbcnt += MSIZE;
2429
2430 if (m->m_flags & M_EXT) {
2431 sb->sb_mbcnt += m->m_ext.ext_size;
2432 cnt += (m->m_ext.ext_size >> MSIZESHIFT);
2433 }
2434 OSAddAtomic(cnt, &total_sbmb_cnt);
2435 VERIFY(total_sbmb_cnt > 0);
2436 if (total_sbmb_cnt > total_sbmb_cnt_peak)
2437 total_sbmb_cnt_peak = total_sbmb_cnt;
2438
2439 /*
2440 * If data is being added to the send socket buffer,
2441 * update the send byte count
2442 */
2443 if (sb->sb_flags & SB_SNDBYTE_CNT) {
2444 inp_incr_sndbytes_total(sb->sb_so, m->m_len);
2445 inp_incr_sndbytes_unsent(sb->sb_so, m->m_len);
2446 }
2447 }
2448
2449 /* adjust counters in sb reflecting freeing of m */
2450 void
2451 sbfree(struct sockbuf *sb, struct mbuf *m)
2452 {
2453 int cnt = -1;
2454
2455 sb->sb_cc -= m->m_len;
2456 if (m->m_type != MT_DATA && m->m_type != MT_HEADER &&
2457 m->m_type != MT_OOBDATA)
2458 sb->sb_ctl -= m->m_len;
2459 sb->sb_mbcnt -= MSIZE;
2460 if (m->m_flags & M_EXT) {
2461 sb->sb_mbcnt -= m->m_ext.ext_size;
2462 cnt -= (m->m_ext.ext_size >> MSIZESHIFT);
2463 }
2464 OSAddAtomic(cnt, &total_sbmb_cnt);
2465 VERIFY(total_sbmb_cnt >= 0);
2466 if (total_sbmb_cnt < total_sbmb_cnt_floor)
2467 total_sbmb_cnt_floor = total_sbmb_cnt;
2468
2469 /*
2470 * If data is being removed from the send socket buffer,
2471 * update the send byte count
2472 */
2473 if (sb->sb_flags & SB_SNDBYTE_CNT)
2474 inp_decr_sndbytes_total(sb->sb_so, m->m_len);
2475 }
2476
2477 /*
2478 * Set lock on sockbuf sb; sleep if lock is already held.
2479 * Unless SB_NOINTR is set on sockbuf, sleep is interruptible.
2480 * Returns error without lock if sleep is interrupted.
2481 */
2482 int
2483 sblock(struct sockbuf *sb, uint32_t flags)
2484 {
2485 boolean_t nointr = ((sb->sb_flags & SB_NOINTR) || (flags & SBL_NOINTR));
2486 void *lr_saved = __builtin_return_address(0);
2487 struct socket *so = sb->sb_so;
2488 void * wchan;
2489 int error = 0;
2490 thread_t tp = current_thread();
2491
2492 VERIFY((flags & SBL_VALID) == flags);
2493
2494 /* so_usecount may be 0 if we get here from sofreelastref() */
2495 if (so == NULL) {
2496 panic("%s: null so, sb=%p sb_flags=0x%x lr=%p\n",
2497 __func__, sb, sb->sb_flags, lr_saved);
2498 /* NOTREACHED */
2499 } else if (so->so_usecount < 0) {
2500 panic("%s: sb=%p sb_flags=0x%x sb_so=%p usecount=%d lr=%p "
2501 "lrh= %s\n", __func__, sb, sb->sb_flags, so,
2502 so->so_usecount, lr_saved, solockhistory_nr(so));
2503 /* NOTREACHED */
2504 }
2505
2506 /*
2507 * The content filter thread must hold the sockbuf lock
2508 */
2509 if ((so->so_flags & SOF_CONTENT_FILTER) && sb->sb_cfil_thread == tp) {
2510 /*
2511 * Don't panic if we are defunct because SB_LOCK has
2512 * been cleared by sodefunct()
2513 */
2514 if (!(so->so_flags & SOF_DEFUNCT) && !(sb->sb_flags & SB_LOCK))
2515 panic("%s: SB_LOCK not held for %p\n",
2516 __func__, sb);
2517
2518 /* Keep the sockbuf locked */
2519 return (0);
2520 }
2521
2522 if ((sb->sb_flags & SB_LOCK) && !(flags & SBL_WAIT))
2523 return (EWOULDBLOCK);
2524 /*
2525 * We may get here from sorflush(), in which case "sb" may not
2526 * point to the real socket buffer. Use the actual socket buffer
2527 * address from the socket instead.
2528 */
2529 wchan = (sb->sb_flags & SB_RECV) ?
2530 &so->so_rcv.sb_flags : &so->so_snd.sb_flags;
2531
2532 /*
2533 * A content filter thread has exclusive access to the sockbuf
2534 * until it clears the
2535 */
2536 while ((sb->sb_flags & SB_LOCK) ||
2537 ((so->so_flags & SOF_CONTENT_FILTER) &&
2538 sb->sb_cfil_thread != NULL)) {
2539 lck_mtx_t *mutex_held;
2540
2541 /*
2542 * XXX: This code should be moved up above outside of this loop;
2543 * however, we may get here as part of sofreelastref(), and
2544 * at that time pr_getlock() may no longer be able to return
2545 * us the lock. This will be fixed in future.
2546 */
2547 if (so->so_proto->pr_getlock != NULL)
2548 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
2549 else
2550 mutex_held = so->so_proto->pr_domain->dom_mtx;
2551
2552 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
2553
2554 sb->sb_wantlock++;
2555 VERIFY(sb->sb_wantlock != 0);
2556
2557 error = msleep(wchan, mutex_held,
2558 nointr ? PSOCK : PSOCK | PCATCH,
2559 nointr ? "sb_lock_nointr" : "sb_lock", NULL);
2560
2561 VERIFY(sb->sb_wantlock != 0);
2562 sb->sb_wantlock--;
2563
2564 if (error == 0 && (so->so_flags & SOF_DEFUNCT) &&
2565 !(flags & SBL_IGNDEFUNCT)) {
2566 error = EBADF;
2567 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] "
2568 "(%d)\n", __func__, proc_selfpid(),
2569 proc_best_name(current_proc()),
2570 (uint64_t)VM_KERNEL_ADDRPERM(so),
2571 SOCK_DOM(so), SOCK_TYPE(so), error);
2572 }
2573
2574 if (error != 0)
2575 return (error);
2576 }
2577 sb->sb_flags |= SB_LOCK;
2578 return (0);
2579 }
2580
2581 /*
2582 * Release lock on sockbuf sb
2583 */
2584 void
2585 sbunlock(struct sockbuf *sb, boolean_t keeplocked)
2586 {
2587 void *lr_saved = __builtin_return_address(0);
2588 struct socket *so = sb->sb_so;
2589 thread_t tp = current_thread();
2590
2591 /* so_usecount may be 0 if we get here from sofreelastref() */
2592 if (so == NULL) {
2593 panic("%s: null so, sb=%p sb_flags=0x%x lr=%p\n",
2594 __func__, sb, sb->sb_flags, lr_saved);
2595 /* NOTREACHED */
2596 } else if (so->so_usecount < 0) {
2597 panic("%s: sb=%p sb_flags=0x%x sb_so=%p usecount=%d lr=%p "
2598 "lrh= %s\n", __func__, sb, sb->sb_flags, so,
2599 so->so_usecount, lr_saved, solockhistory_nr(so));
2600 /* NOTREACHED */
2601 }
2602
2603 /*
2604 * The content filter thread must hold the sockbuf lock
2605 */
2606 if ((so->so_flags & SOF_CONTENT_FILTER) && sb->sb_cfil_thread == tp) {
2607 /*
2608 * Don't panic if we are defunct because SB_LOCK has
2609 * been cleared by sodefunct()
2610 */
2611 if (!(so->so_flags & SOF_DEFUNCT) &&
2612 !(sb->sb_flags & SB_LOCK) &&
2613 !(so->so_state & SS_DEFUNCT) &&
2614 !(so->so_flags1 & SOF1_DEFUNCTINPROG)) {
2615 panic("%s: SB_LOCK not held for %p\n",
2616 __func__, sb);
2617 }
2618 /* Keep the sockbuf locked and proceed */
2619 } else {
2620 VERIFY((sb->sb_flags & SB_LOCK) ||
2621 (so->so_state & SS_DEFUNCT) ||
2622 (so->so_flags1 & SOF1_DEFUNCTINPROG));
2623
2624 sb->sb_flags &= ~SB_LOCK;
2625
2626 if (sb->sb_wantlock > 0) {
2627 /*
2628 * We may get here from sorflush(), in which case "sb"
2629 * may not point to the real socket buffer. Use the
2630 * actual socket buffer address from the socket instead.
2631 */
2632 wakeup((sb->sb_flags & SB_RECV) ? &so->so_rcv.sb_flags :
2633 &so->so_snd.sb_flags);
2634 }
2635 }
2636
2637 if (!keeplocked) { /* unlock on exit */
2638 lck_mtx_t *mutex_held;
2639
2640 if (so->so_proto->pr_getlock != NULL)
2641 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
2642 else
2643 mutex_held = so->so_proto->pr_domain->dom_mtx;
2644
2645 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
2646
2647 VERIFY(so->so_usecount != 0);
2648 so->so_usecount--;
2649 so->unlock_lr[so->next_unlock_lr] = lr_saved;
2650 so->next_unlock_lr = (so->next_unlock_lr + 1) % SO_LCKDBG_MAX;
2651 lck_mtx_unlock(mutex_held);
2652 }
2653 }
2654
2655 void
2656 sorwakeup(struct socket *so)
2657 {
2658 if (sb_notify(&so->so_rcv))
2659 sowakeup(so, &so->so_rcv);
2660 }
2661
2662 void
2663 sowwakeup(struct socket *so)
2664 {
2665 if (sb_notify(&so->so_snd))
2666 sowakeup(so, &so->so_snd);
2667 }
2668
2669 void
2670 soevent(struct socket *so, long hint)
2671 {
2672 if (so->so_flags & SOF_KNOTE)
2673 KNOTE(&so->so_klist, hint);
2674
2675 soevupcall(so, hint);
2676
2677 /*
2678 * Don't post an event if this a subflow socket or
2679 * the app has opted out of using cellular interface
2680 */
2681 if ((hint & SO_FILT_HINT_IFDENIED) &&
2682 !(so->so_flags & SOF_MP_SUBFLOW) &&
2683 !(so->so_restrictions & SO_RESTRICT_DENY_CELLULAR) &&
2684 !(so->so_restrictions & SO_RESTRICT_DENY_EXPENSIVE))
2685 soevent_ifdenied(so);
2686 }
2687
2688 void
2689 soevupcall(struct socket *so, u_int32_t hint)
2690 {
2691 if (so->so_event != NULL) {
2692 caddr_t so_eventarg = so->so_eventarg;
2693 int locked = hint & SO_FILT_HINT_LOCKED;
2694
2695 hint &= so->so_eventmask;
2696 if (hint != 0) {
2697 if (locked)
2698 socket_unlock(so, 0);
2699
2700 so->so_event(so, so_eventarg, hint);
2701
2702 if (locked)
2703 socket_lock(so, 0);
2704 }
2705 }
2706 }
2707
2708 static void
2709 soevent_ifdenied(struct socket *so)
2710 {
2711 struct kev_netpolicy_ifdenied ev_ifdenied;
2712
2713 bzero(&ev_ifdenied, sizeof (ev_ifdenied));
2714 /*
2715 * The event consumer is interested about the effective {upid,pid,uuid}
2716 * info which can be different than the those related to the process
2717 * that recently performed a system call on the socket, i.e. when the
2718 * socket is delegated.
2719 */
2720 if (so->so_flags & SOF_DELEGATED) {
2721 ev_ifdenied.ev_data.eupid = so->e_upid;
2722 ev_ifdenied.ev_data.epid = so->e_pid;
2723 uuid_copy(ev_ifdenied.ev_data.euuid, so->e_uuid);
2724 } else {
2725 ev_ifdenied.ev_data.eupid = so->last_upid;
2726 ev_ifdenied.ev_data.epid = so->last_pid;
2727 uuid_copy(ev_ifdenied.ev_data.euuid, so->last_uuid);
2728 }
2729
2730 if (++so->so_ifdenied_notifies > 1) {
2731 /*
2732 * Allow for at most one kernel event to be generated per
2733 * socket; so_ifdenied_notifies is reset upon changes in
2734 * the UUID policy. See comments in inp_update_policy.
2735 */
2736 if (net_io_policy_log) {
2737 uuid_string_t buf;
2738
2739 uuid_unparse(ev_ifdenied.ev_data.euuid, buf);
2740 log(LOG_DEBUG, "%s[%d]: so 0x%llx [%d,%d] epid %d "
2741 "euuid %s%s has %d redundant events supressed\n",
2742 __func__, so->last_pid,
2743 (uint64_t)VM_KERNEL_ADDRPERM(so), SOCK_DOM(so),
2744 SOCK_TYPE(so), ev_ifdenied.ev_data.epid, buf,
2745 ((so->so_flags & SOF_DELEGATED) ?
2746 " [delegated]" : ""), so->so_ifdenied_notifies);
2747 }
2748 } else {
2749 if (net_io_policy_log) {
2750 uuid_string_t buf;
2751
2752 uuid_unparse(ev_ifdenied.ev_data.euuid, buf);
2753 log(LOG_DEBUG, "%s[%d]: so 0x%llx [%d,%d] epid %d "
2754 "euuid %s%s event posted\n", __func__,
2755 so->last_pid, (uint64_t)VM_KERNEL_ADDRPERM(so),
2756 SOCK_DOM(so), SOCK_TYPE(so),
2757 ev_ifdenied.ev_data.epid, buf,
2758 ((so->so_flags & SOF_DELEGATED) ?
2759 " [delegated]" : ""));
2760 }
2761 netpolicy_post_msg(KEV_NETPOLICY_IFDENIED, &ev_ifdenied.ev_data,
2762 sizeof (ev_ifdenied));
2763 }
2764 }
2765
2766 /*
2767 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
2768 */
2769 struct sockaddr *
2770 dup_sockaddr(struct sockaddr *sa, int canwait)
2771 {
2772 struct sockaddr *sa2;
2773
2774 MALLOC(sa2, struct sockaddr *, sa->sa_len, M_SONAME,
2775 canwait ? M_WAITOK : M_NOWAIT);
2776 if (sa2)
2777 bcopy(sa, sa2, sa->sa_len);
2778 return (sa2);
2779 }
2780
2781 /*
2782 * Create an external-format (``xsocket'') structure using the information
2783 * in the kernel-format socket structure pointed to by so. This is done
2784 * to reduce the spew of irrelevant information over this interface,
2785 * to isolate user code from changes in the kernel structure, and
2786 * potentially to provide information-hiding if we decide that
2787 * some of this information should be hidden from users.
2788 */
2789 void
2790 sotoxsocket(struct socket *so, struct xsocket *xso)
2791 {
2792 xso->xso_len = sizeof (*xso);
2793 xso->xso_so = (_XSOCKET_PTR(struct socket *))VM_KERNEL_ADDRPERM(so);
2794 xso->so_type = so->so_type;
2795 xso->so_options = (short)(so->so_options & 0xffff);
2796 xso->so_linger = so->so_linger;
2797 xso->so_state = so->so_state;
2798 xso->so_pcb = (_XSOCKET_PTR(caddr_t))VM_KERNEL_ADDRPERM(so->so_pcb);
2799 if (so->so_proto) {
2800 xso->xso_protocol = SOCK_PROTO(so);
2801 xso->xso_family = SOCK_DOM(so);
2802 } else {
2803 xso->xso_protocol = xso->xso_family = 0;
2804 }
2805 xso->so_qlen = so->so_qlen;
2806 xso->so_incqlen = so->so_incqlen;
2807 xso->so_qlimit = so->so_qlimit;
2808 xso->so_timeo = so->so_timeo;
2809 xso->so_error = so->so_error;
2810 xso->so_pgid = so->so_pgid;
2811 xso->so_oobmark = so->so_oobmark;
2812 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
2813 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
2814 xso->so_uid = kauth_cred_getuid(so->so_cred);
2815 }
2816
2817
2818
2819 void
2820 sotoxsocket64(struct socket *so, struct xsocket64 *xso)
2821 {
2822 xso->xso_len = sizeof (*xso);
2823 xso->xso_so = (u_int64_t)VM_KERNEL_ADDRPERM(so);
2824 xso->so_type = so->so_type;
2825 xso->so_options = (short)(so->so_options & 0xffff);
2826 xso->so_linger = so->so_linger;
2827 xso->so_state = so->so_state;
2828 xso->so_pcb = (u_int64_t)VM_KERNEL_ADDRPERM(so->so_pcb);
2829 if (so->so_proto) {
2830 xso->xso_protocol = SOCK_PROTO(so);
2831 xso->xso_family = SOCK_DOM(so);
2832 } else {
2833 xso->xso_protocol = xso->xso_family = 0;
2834 }
2835 xso->so_qlen = so->so_qlen;
2836 xso->so_incqlen = so->so_incqlen;
2837 xso->so_qlimit = so->so_qlimit;
2838 xso->so_timeo = so->so_timeo;
2839 xso->so_error = so->so_error;
2840 xso->so_pgid = so->so_pgid;
2841 xso->so_oobmark = so->so_oobmark;
2842 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
2843 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
2844 xso->so_uid = kauth_cred_getuid(so->so_cred);
2845 }
2846
2847
2848 /*
2849 * This does the same for sockbufs. Note that the xsockbuf structure,
2850 * since it is always embedded in a socket, does not include a self
2851 * pointer nor a length. We make this entry point public in case
2852 * some other mechanism needs it.
2853 */
2854 void
2855 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
2856 {
2857 xsb->sb_cc = sb->sb_cc;
2858 xsb->sb_hiwat = sb->sb_hiwat;
2859 xsb->sb_mbcnt = sb->sb_mbcnt;
2860 xsb->sb_mbmax = sb->sb_mbmax;
2861 xsb->sb_lowat = sb->sb_lowat;
2862 xsb->sb_flags = sb->sb_flags;
2863 xsb->sb_timeo = (short)
2864 (sb->sb_timeo.tv_sec * hz) + sb->sb_timeo.tv_usec / tick;
2865 if (xsb->sb_timeo == 0 && sb->sb_timeo.tv_usec != 0)
2866 xsb->sb_timeo = 1;
2867 }
2868
2869 /*
2870 * Based on the policy set by an all knowing decison maker, throttle sockets
2871 * that either have been marked as belonging to "background" process.
2872 */
2873 inline int
2874 soisthrottled(struct socket *so)
2875 {
2876 /*
2877 * On non-embedded, we rely on implicit throttling by the
2878 * application, as we're missing the system wide "decision maker"
2879 */
2880 return (
2881 (so->so_flags1 & SOF1_TRAFFIC_MGT_SO_BACKGROUND));
2882 }
2883
2884 inline int
2885 soisprivilegedtraffic(struct socket *so)
2886 {
2887 return ((so->so_flags & SOF_PRIVILEGED_TRAFFIC_CLASS) ? 1 : 0);
2888 }
2889
2890 inline int
2891 soissrcbackground(struct socket *so)
2892 {
2893 return ((so->so_flags1 & SOF1_TRAFFIC_MGT_SO_BACKGROUND) ||
2894 IS_SO_TC_BACKGROUND(so->so_traffic_class));
2895 }
2896
2897 inline int
2898 soissrcrealtime(struct socket *so)
2899 {
2900 return (so->so_traffic_class >= SO_TC_AV &&
2901 so->so_traffic_class <= SO_TC_VO);
2902 }
2903
2904 inline int
2905 soissrcbesteffort(struct socket *so)
2906 {
2907 return (so->so_traffic_class == SO_TC_BE ||
2908 so->so_traffic_class == SO_TC_RD ||
2909 so->so_traffic_class == SO_TC_OAM);
2910 }
2911
2912 void
2913 sonullevent(struct socket *so, void *arg, uint32_t hint)
2914 {
2915 #pragma unused(so, arg, hint)
2916 }
2917
2918 /*
2919 * Here is the definition of some of the basic objects in the kern.ipc
2920 * branch of the MIB.
2921 */
2922 SYSCTL_NODE(_kern, KERN_IPC, ipc,
2923 CTLFLAG_RW|CTLFLAG_LOCKED|CTLFLAG_ANYBODY, 0, "IPC");
2924
2925 /* Check that the maximum socket buffer size is within a range */
2926
2927 static int
2928 sysctl_sb_max SYSCTL_HANDLER_ARGS
2929 {
2930 #pragma unused(oidp, arg1, arg2)
2931 u_int32_t new_value;
2932 int changed = 0;
2933 int error = sysctl_io_number(req, sb_max, sizeof (u_int32_t),
2934 &new_value, &changed);
2935 if (!error && changed) {
2936 if (new_value > LOW_SB_MAX && new_value <= high_sb_max) {
2937 sb_max = new_value;
2938 } else {
2939 error = ERANGE;
2940 }
2941 }
2942 return (error);
2943 }
2944
2945 static int
2946 sysctl_io_policy_throttled SYSCTL_HANDLER_ARGS
2947 {
2948 #pragma unused(arg1, arg2)
2949 int i, err;
2950
2951 i = net_io_policy_throttled;
2952
2953 err = sysctl_handle_int(oidp, &i, 0, req);
2954 if (err != 0 || req->newptr == USER_ADDR_NULL)
2955 return (err);
2956
2957 if (i != net_io_policy_throttled)
2958 SOTHROTTLELOG("throttle: network IO policy throttling is "
2959 "now %s\n", i ? "ON" : "OFF");
2960
2961 net_io_policy_throttled = i;
2962
2963 return (err);
2964 }
2965
2966 SYSCTL_PROC(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf,
2967 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
2968 &sb_max, 0, &sysctl_sb_max, "IU", "Maximum socket buffer size");
2969
2970 SYSCTL_INT(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor,
2971 CTLFLAG_RW | CTLFLAG_LOCKED, &sb_efficiency, 0, "");
2972
2973 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters,
2974 CTLFLAG_RD | CTLFLAG_LOCKED, &nmbclusters, 0, "");
2975
2976 SYSCTL_INT(_kern_ipc, OID_AUTO, njcl,
2977 CTLFLAG_RD | CTLFLAG_LOCKED, &njcl, 0, "");
2978
2979 SYSCTL_INT(_kern_ipc, OID_AUTO, njclbytes,
2980 CTLFLAG_RD | CTLFLAG_LOCKED, &njclbytes, 0, "");
2981
2982 SYSCTL_INT(_kern_ipc, KIPC_SOQLIMITCOMPAT, soqlimitcompat,
2983 CTLFLAG_RW | CTLFLAG_LOCKED, &soqlimitcompat, 1,
2984 "Enable socket queue limit compatibility");
2985
2986 SYSCTL_INT(_kern_ipc, OID_AUTO, soqlencomp, CTLFLAG_RW | CTLFLAG_LOCKED,
2987 &soqlencomp, 0, "Listen backlog represents only complete queue");
2988
2989 SYSCTL_INT(_kern_ipc, OID_AUTO, sbmb_cnt, CTLFLAG_RD | CTLFLAG_LOCKED,
2990 &total_sbmb_cnt, 0, "");
2991 SYSCTL_INT(_kern_ipc, OID_AUTO, sbmb_cnt_peak, CTLFLAG_RD | CTLFLAG_LOCKED,
2992 &total_sbmb_cnt_peak, 0, "");
2993 SYSCTL_INT(_kern_ipc, OID_AUTO, sbmb_cnt_floor, CTLFLAG_RD | CTLFLAG_LOCKED,
2994 &total_sbmb_cnt_floor, 0, "");
2995 SYSCTL_QUAD(_kern_ipc, OID_AUTO, sbmb_limreached, CTLFLAG_RD | CTLFLAG_LOCKED,
2996 &sbmb_limreached, "");
2997
2998
2999 SYSCTL_NODE(_kern_ipc, OID_AUTO, io_policy, CTLFLAG_RW, 0, "network IO policy");
3000
3001 SYSCTL_PROC(_kern_ipc_io_policy, OID_AUTO, throttled,
3002 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &net_io_policy_throttled, 0,
3003 sysctl_io_policy_throttled, "I", "");
3004
3005 SYSCTL_INT(_kern_ipc_io_policy, OID_AUTO, log, CTLFLAG_RW | CTLFLAG_LOCKED,
3006 &net_io_policy_log, 0, "");
3007
3008 #if CONFIG_PROC_UUID_POLICY
3009 SYSCTL_INT(_kern_ipc_io_policy, OID_AUTO, uuid, CTLFLAG_RW | CTLFLAG_LOCKED,
3010 &net_io_policy_uuid, 0, "");
3011 #endif /* CONFIG_PROC_UUID_POLICY */