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