]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/uipc_socket2.c
a6b2af000456afd60dc3d12b380c2138dbd7b813
[apple/xnu.git] / bsd / kern / uipc_socket2.c
1 /*
2 * Copyright (c) 1998-2010 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 * $FreeBSD: src/sys/kern/uipc_socket2.c,v 1.55.2.9 2001/07/26 18:53:02 peter Exp $
63 */
64 /*
65 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
66 * support for mandatory and extensible security protections. This notice
67 * is included in support of clause 2.2 (b) of the Apple Public License,
68 * Version 2.0.
69 */
70
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/domain.h>
74 #include <sys/kernel.h>
75 #include <sys/proc_internal.h>
76 #include <sys/kauth.h>
77 #include <sys/malloc.h>
78 #include <sys/mbuf.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/ev.h>
86 #include <kern/locks.h>
87 #include <net/route.h>
88 #include <netinet/in.h>
89 #include <netinet/in_pcb.h>
90 #include <sys/kdebug.h>
91 #include <libkern/OSAtomic.h>
92
93 #if CONFIG_MACF
94 #include <security/mac_framework.h>
95 #endif
96
97 /* TODO: this should be in a header file somewhere */
98 extern void postevent(struct socket *, struct sockbuf *, int);
99
100 #define DBG_FNC_SBDROP NETDBG_CODE(DBG_NETSOCK, 4)
101 #define DBG_FNC_SBAPPEND NETDBG_CODE(DBG_NETSOCK, 5)
102
103 static inline void sbcompress(struct sockbuf *, struct mbuf *, struct mbuf *);
104 static struct socket *sonewconn_internal(struct socket *, int);
105 static int sbappendaddr_internal(struct sockbuf *, struct sockaddr *,
106 struct mbuf *, struct mbuf *);
107 static int sbappendcontrol_internal(struct sockbuf *, struct mbuf *,
108 struct mbuf *);
109
110 /*
111 * Primitive routines for operating on sockets and socket buffers
112 */
113 static int soqlimitcompat = 1;
114 static int soqlencomp = 0;
115
116 /* Based on the number of mbuf clusters configured, high_sb_max and sb_max can get
117 * scaled up or down to suit that memory configuration. high_sb_max is a higher
118 * limit on sb_max that is checked when sb_max gets set through sysctl.
119 */
120
121 u_int32_t sb_max = SB_MAX; /* XXX should be static */
122 u_int32_t high_sb_max = SB_MAX;
123
124 static u_int32_t sb_efficiency = 8; /* parameter for sbreserve() */
125 __private_extern__ unsigned int total_mb_cnt = 0;
126 __private_extern__ unsigned int total_cl_cnt = 0;
127 __private_extern__ int sbspace_factor = 8;
128
129 /*
130 * Procedures to manipulate state flags of socket
131 * and do appropriate wakeups. Normal sequence from the
132 * active (originating) side is that soisconnecting() is
133 * called during processing of connect() call,
134 * resulting in an eventual call to soisconnected() if/when the
135 * connection is established. When the connection is torn down
136 * soisdisconnecting() is called during processing of disconnect() call,
137 * and soisdisconnected() is called when the connection to the peer
138 * is totally severed. The semantics of these routines are such that
139 * connectionless protocols can call soisconnected() and soisdisconnected()
140 * only, bypassing the in-progress calls when setting up a ``connection''
141 * takes no time.
142 *
143 * From the passive side, a socket is created with
144 * two queues of sockets: so_incomp for connections in progress
145 * and so_comp for connections already made and awaiting user acceptance.
146 * As a protocol is preparing incoming connections, it creates a socket
147 * structure queued on so_incomp by calling sonewconn(). When the connection
148 * is established, soisconnected() is called, and transfers the
149 * socket structure to so_comp, making it available to accept().
150 *
151 * If a socket is closed with sockets on either
152 * so_incomp or so_comp, these sockets are dropped.
153 *
154 * If higher level protocols are implemented in
155 * the kernel, the wakeups done here will sometimes
156 * cause software-interrupt process scheduling.
157 */
158 void
159 soisconnecting(struct socket *so)
160 {
161
162 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
163 so->so_state |= SS_ISCONNECTING;
164
165 sflt_notify(so, sock_evt_connecting, NULL);
166 }
167
168 void
169 soisconnected(struct socket *so)
170 {
171 struct socket *head = so->so_head;
172
173 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
174 so->so_state |= SS_ISCONNECTED;
175
176 sflt_notify(so, sock_evt_connected, NULL);
177
178 if (head && (so->so_state & SS_INCOMP)) {
179 so->so_state &= ~SS_INCOMP;
180 so->so_state |= SS_COMP;
181 if (head->so_proto->pr_getlock != NULL) {
182 socket_unlock(so, 0);
183 socket_lock(head, 1);
184 }
185 postevent(head, 0, EV_RCONN);
186 TAILQ_REMOVE(&head->so_incomp, so, so_list);
187 head->so_incqlen--;
188 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
189 sorwakeup(head);
190 wakeup_one((caddr_t)&head->so_timeo);
191 if (head->so_proto->pr_getlock != NULL) {
192 socket_unlock(head, 1);
193 socket_lock(so, 0);
194 }
195 } else {
196 postevent(so, 0, EV_WCONN);
197 wakeup((caddr_t)&so->so_timeo);
198 sorwakeup(so);
199 sowwakeup(so);
200 }
201 }
202
203 void
204 soisdisconnecting(struct socket *so)
205 {
206 so->so_state &= ~SS_ISCONNECTING;
207 so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
208 sflt_notify(so, sock_evt_disconnecting, NULL);
209 wakeup((caddr_t)&so->so_timeo);
210 sowwakeup(so);
211 sorwakeup(so);
212 }
213
214 void
215 soisdisconnected(struct socket *so)
216 {
217 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
218 so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
219 sflt_notify(so, sock_evt_disconnected, NULL);
220 wakeup((caddr_t)&so->so_timeo);
221 sowwakeup(so);
222 sorwakeup(so);
223 }
224
225 /*
226 * When an attempt at a new connection is noted on a socket
227 * which accepts connections, sonewconn is called. If the
228 * connection is possible (subject to space constraints, etc.)
229 * then we allocate a new structure, propoerly linked into the
230 * data structure of the original socket, and return this.
231 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
232 */
233 static struct socket *
234 sonewconn_internal(struct socket *head, int connstatus)
235 {
236 int so_qlen, error = 0;
237 struct socket *so;
238 lck_mtx_t *mutex_held;
239
240 if (head->so_proto->pr_getlock != NULL)
241 mutex_held = (*head->so_proto->pr_getlock)(head, 0);
242 else
243 mutex_held = head->so_proto->pr_domain->dom_mtx;
244 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
245
246 if (!soqlencomp) {
247 /*
248 * This is the default case; so_qlen represents the
249 * sum of both incomplete and completed queues.
250 */
251 so_qlen = head->so_qlen;
252 } else {
253 /*
254 * When kern.ipc.soqlencomp is set to 1, so_qlen
255 * represents only the completed queue. Since we
256 * cannot let the incomplete queue goes unbounded
257 * (in case of SYN flood), we cap the incomplete
258 * queue length to at most somaxconn, and use that
259 * as so_qlen so that we fail immediately below.
260 */
261 so_qlen = head->so_qlen - head->so_incqlen;
262 if (head->so_incqlen > somaxconn)
263 so_qlen = somaxconn;
264 }
265
266 if (so_qlen >=
267 (soqlimitcompat ? head->so_qlimit : (3 * head->so_qlimit / 2)))
268 return ((struct socket *)0);
269 so = soalloc(1, head->so_proto->pr_domain->dom_family,
270 head->so_type);
271 if (so == NULL)
272 return ((struct socket *)0);
273 /* check if head was closed during the soalloc */
274 if (head->so_proto == NULL) {
275 sodealloc(so);
276 return ((struct socket *)0);
277 }
278
279 so->so_head = head;
280 so->so_type = head->so_type;
281 so->so_options = head->so_options &~ SO_ACCEPTCONN;
282 so->so_linger = head->so_linger;
283 so->so_state = head->so_state | SS_NOFDREF;
284 so->so_proto = head->so_proto;
285 so->so_timeo = head->so_timeo;
286 so->so_pgid = head->so_pgid;
287 so->so_uid = head->so_uid;
288 /* inherit socket options stored in so_flags */
289 so->so_flags = head->so_flags & (SOF_NOSIGPIPE |
290 SOF_NOADDRAVAIL |
291 SOF_REUSESHAREUID |
292 SOF_NOTIFYCONFLICT |
293 SOF_BINDRANDOMPORT |
294 SOF_NPX_SETOPTSHUT);
295 so->so_usecount = 1;
296 so->next_lock_lr = 0;
297 so->next_unlock_lr = 0;
298
299 #ifdef __APPLE__
300 so->so_rcv.sb_flags |= SB_RECV; /* XXX */
301 so->so_rcv.sb_so = so->so_snd.sb_so = so;
302 TAILQ_INIT(&so->so_evlist);
303 #endif
304
305 #if CONFIG_MACF_SOCKET
306 mac_socket_label_associate_accept(head, so);
307 #endif
308
309 /* inherit traffic management properties of listener */
310 so->so_traffic_mgt_flags = head->so_traffic_mgt_flags &
311 (TRAFFIC_MGT_SO_BACKGROUND | TRAFFIC_MGT_SO_BG_REGULATE);
312 so->so_background_thread = head->so_background_thread;
313 #if PKT_PRIORITY
314 so->so_traffic_class = head->so_traffic_class;
315 #endif /* PKT_PRIORITY */
316
317 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
318 sflt_termsock(so);
319 sodealloc(so);
320 return ((struct socket *)0);
321 }
322
323 /*
324 * Must be done with head unlocked to avoid deadlock
325 * for protocol with per socket mutexes.
326 */
327 if (head->so_proto->pr_unlock)
328 socket_unlock(head, 0);
329 if (((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL) != 0) ||
330 error) {
331 sflt_termsock(so);
332 sodealloc(so);
333 if (head->so_proto->pr_unlock)
334 socket_lock(head, 0);
335 return ((struct socket *)0);
336 }
337 if (head->so_proto->pr_unlock)
338 socket_lock(head, 0);
339 #ifdef __APPLE__
340 so->so_proto->pr_domain->dom_refs++;
341 #endif
342
343 if (connstatus) {
344 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
345 so->so_state |= SS_COMP;
346 } else {
347 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
348 so->so_state |= SS_INCOMP;
349 head->so_incqlen++;
350 }
351 head->so_qlen++;
352
353 #ifdef __APPLE__
354 /* Attach socket filters for this protocol */
355 sflt_initsock(so);
356 #endif
357
358 if (connstatus) {
359 so->so_state |= connstatus;
360 sorwakeup(head);
361 wakeup((caddr_t)&head->so_timeo);
362 }
363 return (so);
364 }
365
366
367 struct socket *
368 sonewconn(struct socket *head, int connstatus, const struct sockaddr *from)
369 {
370 int error = 0;
371 struct socket_filter_entry *filter;
372 int filtered = 0;
373
374 for (filter = head->so_filt; filter && (error == 0);
375 filter = filter->sfe_next_onsocket) {
376 if (filter->sfe_filter->sf_filter.sf_connect_in) {
377 if (filtered == 0) {
378 filtered = 1;
379 sflt_use(head);
380 socket_unlock(head, 0);
381 }
382 error = filter->sfe_filter->sf_filter.
383 sf_connect_in(filter->sfe_cookie, head, from);
384 }
385 }
386 if (filtered != 0) {
387 socket_lock(head, 0);
388 sflt_unuse(head);
389 }
390
391 if (error) {
392 return (NULL);
393 }
394
395 return (sonewconn_internal(head, connstatus));
396 }
397
398 /*
399 * Socantsendmore indicates that no more data will be sent on the
400 * socket; it would normally be applied to a socket when the user
401 * informs the system that no more data is to be sent, by the protocol
402 * code (in case PRU_SHUTDOWN). Socantrcvmore indicates that no more data
403 * will be received, and will normally be applied to the socket by a
404 * protocol when it detects that the peer will send no more data.
405 * Data queued for reading in the socket may yet be read.
406 */
407
408 void
409 socantsendmore(struct socket *so)
410 {
411 so->so_state |= SS_CANTSENDMORE;
412 sflt_notify(so, sock_evt_cantsendmore, NULL);
413 sowwakeup(so);
414 }
415
416 void
417 socantrcvmore(struct socket *so)
418 {
419 so->so_state |= SS_CANTRCVMORE;
420 sflt_notify(so, sock_evt_cantrecvmore, NULL);
421 sorwakeup(so);
422 }
423
424 /*
425 * Wait for data to arrive at/drain from a socket buffer.
426 *
427 * Returns: 0 Success
428 * EBADF
429 * msleep:EINTR
430 */
431 int
432 sbwait(struct sockbuf *sb)
433 {
434 int error = 0;
435 uintptr_t lr_saved;
436 struct socket *so = sb->sb_so;
437 lck_mtx_t *mutex_held;
438 struct timespec ts;
439
440 lr_saved = (uintptr_t) __builtin_return_address(0);
441
442 if (so->so_proto->pr_getlock != NULL)
443 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
444 else
445 mutex_held = so->so_proto->pr_domain->dom_mtx;
446
447 sb->sb_flags |= SB_WAIT;
448
449 if (so->so_usecount < 1)
450 panic("sbwait: so=%p refcount=%d\n", so, so->so_usecount);
451 ts.tv_sec = sb->sb_timeo.tv_sec;
452 ts.tv_nsec = sb->sb_timeo.tv_usec * 1000;
453 error = msleep((caddr_t)&sb->sb_cc, mutex_held,
454 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait", &ts);
455
456 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
457
458 if (so->so_usecount < 1)
459 panic("sbwait: so=%p refcount=%d\n", so, so->so_usecount);
460
461 if ((so->so_state & SS_DRAINING)) {
462 error = EBADF;
463 }
464
465 return (error);
466 }
467
468 /*
469 * Lock a sockbuf already known to be locked;
470 * return any error returned from sleep (EINTR).
471 *
472 * Returns: 0 Success
473 * EINTR
474 */
475 int
476 sb_lock(struct sockbuf *sb)
477 {
478 struct socket *so = sb->sb_so;
479 lck_mtx_t *mutex_held;
480 int error = 0;
481
482 if (so == NULL)
483 panic("sb_lock: null so back pointer sb=%p\n", sb);
484
485 while (sb->sb_flags & SB_LOCK) {
486 sb->sb_flags |= SB_WANT;
487 if (so->so_proto->pr_getlock != NULL)
488 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
489 else
490 mutex_held = so->so_proto->pr_domain->dom_mtx;
491 if (so->so_usecount < 1)
492 panic("sb_lock: so=%p refcount=%d\n", so,
493 so->so_usecount);
494
495 error = msleep((caddr_t)&sb->sb_flags, mutex_held,
496 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH,
497 "sb_lock", 0);
498 if (so->so_usecount < 1)
499 panic("sb_lock: 2 so=%p refcount=%d\n", so,
500 so->so_usecount);
501 if (error)
502 return (error);
503 }
504 sb->sb_flags |= SB_LOCK;
505 return (0);
506 }
507
508 /*
509 * Wakeup processes waiting on a socket buffer.
510 * Do asynchronous notification via SIGIO
511 * if the socket has the SS_ASYNC flag set.
512 */
513 void
514 sowakeup(struct socket *so, struct sockbuf *sb)
515 {
516 sb->sb_flags &= ~SB_SEL;
517 selwakeup(&sb->sb_sel);
518 if (sb->sb_flags & SB_WAIT) {
519 sb->sb_flags &= ~SB_WAIT;
520 wakeup((caddr_t)&sb->sb_cc);
521 }
522 if (so->so_state & SS_ASYNC) {
523 if (so->so_pgid < 0)
524 gsignal(-so->so_pgid, SIGIO);
525 else if (so->so_pgid > 0)
526 proc_signal(so->so_pgid, SIGIO);
527 }
528 if (sb->sb_flags & SB_KNOTE) {
529 KNOTE(&sb->sb_sel.si_note, SO_FILT_HINT_LOCKED);
530 }
531 if (sb->sb_flags & SB_UPCALL) {
532 void (*so_upcall)(struct socket *, caddr_t, int);
533 caddr_t so_upcallarg;
534
535 so_upcall = so->so_upcall;
536 so_upcallarg = so->so_upcallarg;
537 /* Let close know that we're about to do an upcall */
538 so->so_flags |= SOF_UPCALLINUSE;
539
540 socket_unlock(so, 0);
541 (*so_upcall)(so, so_upcallarg, M_DONTWAIT);
542 socket_lock(so, 0);
543
544 so->so_flags &= ~SOF_UPCALLINUSE;
545 /* Tell close that it's safe to proceed */
546 if (so->so_flags & SOF_CLOSEWAIT)
547 wakeup((caddr_t)&so->so_upcall);
548 }
549 }
550
551 /*
552 * Socket buffer (struct sockbuf) utility routines.
553 *
554 * Each socket contains two socket buffers: one for sending data and
555 * one for receiving data. Each buffer contains a queue of mbufs,
556 * information about the number of mbufs and amount of data in the
557 * queue, and other fields allowing select() statements and notification
558 * on data availability to be implemented.
559 *
560 * Data stored in a socket buffer is maintained as a list of records.
561 * Each record is a list of mbufs chained together with the m_next
562 * field. Records are chained together with the m_nextpkt field. The upper
563 * level routine soreceive() expects the following conventions to be
564 * observed when placing information in the receive buffer:
565 *
566 * 1. If the protocol requires each message be preceded by the sender's
567 * name, then a record containing that name must be present before
568 * any associated data (mbuf's must be of type MT_SONAME).
569 * 2. If the protocol supports the exchange of ``access rights'' (really
570 * just additional data associated with the message), and there are
571 * ``rights'' to be received, then a record containing this data
572 * should be present (mbuf's must be of type MT_RIGHTS).
573 * 3. If a name or rights record exists, then it must be followed by
574 * a data record, perhaps of zero length.
575 *
576 * Before using a new socket structure it is first necessary to reserve
577 * buffer space to the socket, by calling sbreserve(). This should commit
578 * some of the available buffer space in the system buffer pool for the
579 * socket (currently, it does nothing but enforce limits). The space
580 * should be released by calling sbrelease() when the socket is destroyed.
581 */
582
583 /*
584 * Returns: 0 Success
585 * ENOBUFS
586 */
587 int
588 soreserve(struct socket *so, u_int32_t sndcc, u_int32_t rcvcc)
589 {
590
591 if (sbreserve(&so->so_snd, sndcc) == 0)
592 goto bad;
593 if (sbreserve(&so->so_rcv, rcvcc) == 0)
594 goto bad2;
595 if (so->so_rcv.sb_lowat == 0)
596 so->so_rcv.sb_lowat = 1;
597 if (so->so_snd.sb_lowat == 0)
598 so->so_snd.sb_lowat = MCLBYTES;
599 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
600 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
601 return (0);
602 bad2:
603 #ifdef __APPLE__
604 selthreadclear(&so->so_snd.sb_sel);
605 #endif
606 sbrelease(&so->so_snd);
607 bad:
608 return (ENOBUFS);
609 }
610
611 /*
612 * Allot mbufs to a sockbuf.
613 * Attempt to scale mbmax so that mbcnt doesn't become limiting
614 * if buffering efficiency is near the normal case.
615 */
616 int
617 sbreserve(struct sockbuf *sb, u_int32_t cc)
618 {
619 if ((u_quad_t)cc > (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES))
620 return (0);
621 sb->sb_hiwat = cc;
622 sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
623 if (sb->sb_lowat > sb->sb_hiwat)
624 sb->sb_lowat = sb->sb_hiwat;
625 return (1);
626 }
627
628 /*
629 * Free mbufs held by a socket, and reserved mbuf space.
630 */
631 /* WARNING needs to do selthreadclear() before calling this */
632 void
633 sbrelease(struct sockbuf *sb)
634 {
635 sbflush(sb);
636 sb->sb_hiwat = 0;
637 sb->sb_mbmax = 0;
638 }
639
640 /*
641 * Routines to add and remove
642 * data from an mbuf queue.
643 *
644 * The routines sbappend() or sbappendrecord() are normally called to
645 * append new mbufs to a socket buffer, after checking that adequate
646 * space is available, comparing the function sbspace() with the amount
647 * of data to be added. sbappendrecord() differs from sbappend() in
648 * that data supplied is treated as the beginning of a new record.
649 * To place a sender's address, optional access rights, and data in a
650 * socket receive buffer, sbappendaddr() should be used. To place
651 * access rights and data in a socket receive buffer, sbappendrights()
652 * should be used. In either case, the new data begins a new record.
653 * Note that unlike sbappend() and sbappendrecord(), these routines check
654 * for the caller that there will be enough space to store the data.
655 * Each fails if there is not enough space, or if it cannot find mbufs
656 * to store additional information in.
657 *
658 * Reliable protocols may use the socket send buffer to hold data
659 * awaiting acknowledgement. Data is normally copied from a socket
660 * send buffer in a protocol with m_copy for output to a peer,
661 * and then removing the data from the socket buffer with sbdrop()
662 * or sbdroprecord() when the data is acknowledged by the peer.
663 */
664
665 /*
666 * Append mbuf chain m to the last record in the
667 * socket buffer sb. The additional space associated
668 * the mbuf chain is recorded in sb. Empty mbufs are
669 * discarded and mbufs are compacted where possible.
670 */
671 int
672 sbappend(struct sockbuf *sb, struct mbuf *m)
673 {
674 struct socket *so = sb->sb_so;
675
676 if (m == NULL || (sb->sb_flags & SB_DROP)) {
677 if (m != NULL)
678 m_freem(m);
679 return (0);
680 }
681
682 SBLASTRECORDCHK(sb, "sbappend 1");
683
684 if (sb->sb_lastrecord != NULL && (sb->sb_mbtail->m_flags & M_EOR))
685 return (sbappendrecord(sb, m));
686
687 if (sb->sb_flags & SB_RECV) {
688 int error = sflt_data_in(so, NULL, &m, NULL, 0, NULL);
689 SBLASTRECORDCHK(sb, "sbappend 2");
690 if (error != 0) {
691 if (error != EJUSTRETURN)
692 m_freem(m);
693 return (0);
694 }
695 }
696
697 /* If this is the first record, it's also the last record */
698 if (sb->sb_lastrecord == NULL)
699 sb->sb_lastrecord = m;
700
701 sbcompress(sb, m, sb->sb_mbtail);
702 SBLASTRECORDCHK(sb, "sbappend 3");
703 return (1);
704 }
705
706 /*
707 * Similar to sbappend, except that this is optimized for stream sockets.
708 */
709 int
710 sbappendstream(struct sockbuf *sb, struct mbuf *m)
711 {
712 struct socket *so = sb->sb_so;
713
714 if (m->m_nextpkt != NULL || (sb->sb_mb != sb->sb_lastrecord))
715 panic("sbappendstream: nexpkt %p || mb %p != lastrecord %p\n",
716 m->m_nextpkt, sb->sb_mb, sb->sb_lastrecord);
717
718 SBLASTMBUFCHK(sb, __func__);
719
720 if (m == NULL || (sb->sb_flags & SB_DROP)) {
721 if (m != NULL)
722 m_freem(m);
723 return (0);
724 }
725
726 if (sb->sb_flags & SB_RECV) {
727 int error = sflt_data_in(so, NULL, &m, NULL, 0, NULL);
728 SBLASTRECORDCHK(sb, "sbappendstream 1");
729 if (error != 0) {
730 if (error != EJUSTRETURN)
731 m_freem(m);
732 return (0);
733 }
734 }
735
736 sbcompress(sb, m, sb->sb_mbtail);
737 sb->sb_lastrecord = sb->sb_mb;
738 SBLASTRECORDCHK(sb, "sbappendstream 2");
739 return (1);
740 }
741
742 #ifdef SOCKBUF_DEBUG
743 void
744 sbcheck(struct sockbuf *sb)
745 {
746 struct mbuf *m;
747 struct mbuf *n = 0;
748 u_int32_t len = 0, mbcnt = 0;
749 lck_mtx_t *mutex_held;
750
751 if (sb->sb_so->so_proto->pr_getlock != NULL)
752 mutex_held = (*sb->sb_so->so_proto->pr_getlock)(sb->sb_so, 0);
753 else
754 mutex_held = sb->sb_so->so_proto->pr_domain->dom_mtx;
755
756 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
757
758 if (sbchecking == 0)
759 return;
760
761 for (m = sb->sb_mb; m; m = n) {
762 n = m->m_nextpkt;
763 for (; m; m = m->m_next) {
764 len += m->m_len;
765 mbcnt += MSIZE;
766 /* XXX pretty sure this is bogus */
767 if (m->m_flags & M_EXT)
768 mbcnt += m->m_ext.ext_size;
769 }
770 }
771 if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
772 panic("cc %ld != %ld || mbcnt %ld != %ld\n", len, sb->sb_cc,
773 mbcnt, sb->sb_mbcnt);
774 }
775 }
776 #endif
777
778 void
779 sblastrecordchk(struct sockbuf *sb, const char *where)
780 {
781 struct mbuf *m = sb->sb_mb;
782
783 while (m && m->m_nextpkt)
784 m = m->m_nextpkt;
785
786 if (m != sb->sb_lastrecord) {
787 printf("sblastrecordchk: mb %p lastrecord %p last %p\n",
788 sb->sb_mb, sb->sb_lastrecord, m);
789 printf("packet chain:\n");
790 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
791 printf("\t%p\n", m);
792 panic("sblastrecordchk from %s", where);
793 }
794 }
795
796 void
797 sblastmbufchk(struct sockbuf *sb, const char *where)
798 {
799 struct mbuf *m = sb->sb_mb;
800 struct mbuf *n;
801
802 while (m && m->m_nextpkt)
803 m = m->m_nextpkt;
804
805 while (m && m->m_next)
806 m = m->m_next;
807
808 if (m != sb->sb_mbtail) {
809 printf("sblastmbufchk: mb %p mbtail %p last %p\n",
810 sb->sb_mb, sb->sb_mbtail, m);
811 printf("packet tree:\n");
812 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
813 printf("\t");
814 for (n = m; n != NULL; n = n->m_next)
815 printf("%p ", n);
816 printf("\n");
817 }
818 panic("sblastmbufchk from %s", where);
819 }
820 }
821
822 /*
823 * Similar to sbappend, except the mbuf chain begins a new record.
824 */
825 int
826 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
827 {
828 struct mbuf *m;
829 int space = 0;
830
831 if (m0 == NULL || (sb->sb_flags & SB_DROP)) {
832 if (m0 != NULL)
833 m_freem(m0);
834 return (0);
835 }
836
837 for (m = m0; m != NULL; m = m->m_next)
838 space += m->m_len;
839
840 if (space > sbspace(sb) && !(sb->sb_flags & SB_UNIX)) {
841 m_freem(m0);
842 return (0);
843 }
844
845 if (sb->sb_flags & SB_RECV) {
846 int error = sflt_data_in(sb->sb_so, NULL, &m0, NULL,
847 sock_data_filt_flag_record, NULL);
848 if (error != 0) {
849 SBLASTRECORDCHK(sb, "sbappendrecord 1");
850 if (error != EJUSTRETURN)
851 m_freem(m0);
852 return (0);
853 }
854 }
855
856 /*
857 * Note this permits zero length records.
858 */
859 sballoc(sb, m0);
860 SBLASTRECORDCHK(sb, "sbappendrecord 2");
861 if (sb->sb_lastrecord != NULL) {
862 sb->sb_lastrecord->m_nextpkt = m0;
863 } else {
864 sb->sb_mb = m0;
865 }
866 sb->sb_lastrecord = m0;
867 sb->sb_mbtail = m0;
868
869 m = m0->m_next;
870 m0->m_next = 0;
871 if (m && (m0->m_flags & M_EOR)) {
872 m0->m_flags &= ~M_EOR;
873 m->m_flags |= M_EOR;
874 }
875 sbcompress(sb, m, m0);
876 SBLASTRECORDCHK(sb, "sbappendrecord 3");
877 return (1);
878 }
879
880 /*
881 * As above except that OOB data
882 * is inserted at the beginning of the sockbuf,
883 * but after any other OOB data.
884 */
885 int
886 sbinsertoob(struct sockbuf *sb, struct mbuf *m0)
887 {
888 struct mbuf *m;
889 struct mbuf **mp;
890
891 if (m0 == 0)
892 return (0);
893
894 SBLASTRECORDCHK(sb, "sbinsertoob 1");
895
896 if ((sb->sb_flags & SB_RECV) != 0) {
897 int error = sflt_data_in(sb->sb_so, NULL, &m0, NULL,
898 sock_data_filt_flag_oob, NULL);
899
900 SBLASTRECORDCHK(sb, "sbinsertoob 2");
901 if (error) {
902 if (error != EJUSTRETURN) {
903 m_freem(m0);
904 }
905 return (0);
906 }
907 }
908
909 for (mp = &sb->sb_mb; *mp; mp = &((*mp)->m_nextpkt)) {
910 m = *mp;
911 again:
912 switch (m->m_type) {
913
914 case MT_OOBDATA:
915 continue; /* WANT next train */
916
917 case MT_CONTROL:
918 m = m->m_next;
919 if (m)
920 goto again; /* inspect THIS train further */
921 }
922 break;
923 }
924 /*
925 * Put the first mbuf on the queue.
926 * Note this permits zero length records.
927 */
928 sballoc(sb, m0);
929 m0->m_nextpkt = *mp;
930 if (*mp == NULL) {
931 /* m0 is actually the new tail */
932 sb->sb_lastrecord = m0;
933 }
934 *mp = m0;
935 m = m0->m_next;
936 m0->m_next = 0;
937 if (m && (m0->m_flags & M_EOR)) {
938 m0->m_flags &= ~M_EOR;
939 m->m_flags |= M_EOR;
940 }
941 sbcompress(sb, m, m0);
942 SBLASTRECORDCHK(sb, "sbinsertoob 3");
943 return (1);
944 }
945
946 /*
947 * Append address and data, and optionally, control (ancillary) data
948 * to the receive queue of a socket. If present,
949 * m0 must include a packet header with total length.
950 * Returns 0 if no space in sockbuf or insufficient mbufs.
951 *
952 * Returns: 0 No space/out of mbufs
953 * 1 Success
954 */
955 static int
956 sbappendaddr_internal(struct sockbuf *sb, struct sockaddr *asa,
957 struct mbuf *m0, struct mbuf *control)
958 {
959 struct mbuf *m, *n, *nlast;
960 int space = asa->sa_len;
961
962 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
963 panic("sbappendaddr");
964
965 if (m0)
966 space += m0->m_pkthdr.len;
967 for (n = control; n; n = n->m_next) {
968 space += n->m_len;
969 if (n->m_next == 0) /* keep pointer to last control buf */
970 break;
971 }
972 if (space > sbspace(sb))
973 return (0);
974 if (asa->sa_len > MLEN)
975 return (0);
976 MGET(m, M_DONTWAIT, MT_SONAME);
977 if (m == 0)
978 return (0);
979 m->m_len = asa->sa_len;
980 bcopy((caddr_t)asa, mtod(m, caddr_t), asa->sa_len);
981 if (n)
982 n->m_next = m0; /* concatenate data to control */
983 else
984 control = m0;
985 m->m_next = control;
986
987 SBLASTRECORDCHK(sb, "sbappendadddr 1");
988
989 for (n = m; n->m_next != NULL; n = n->m_next)
990 sballoc(sb, n);
991 sballoc(sb, n);
992 nlast = n;
993
994 if (sb->sb_lastrecord != NULL) {
995 sb->sb_lastrecord->m_nextpkt = m;
996 } else {
997 sb->sb_mb = m;
998 }
999 sb->sb_lastrecord = m;
1000 sb->sb_mbtail = nlast;
1001
1002 SBLASTMBUFCHK(sb, __func__);
1003 SBLASTRECORDCHK(sb, "sbappendadddr 2");
1004
1005 postevent(0, sb, EV_RWBYTES);
1006 return (1);
1007 }
1008
1009 /*
1010 * Returns: 0 Error: No space/out of mbufs/etc.
1011 * 1 Success
1012 *
1013 * Imputed: (*error_out) errno for error
1014 * ENOBUFS
1015 * sflt_data_in:??? [whatever a filter author chooses]
1016 */
1017 int
1018 sbappendaddr(struct sockbuf *sb, struct sockaddr *asa, struct mbuf *m0,
1019 struct mbuf *control, int *error_out)
1020 {
1021 int result = 0;
1022 boolean_t sb_unix = (sb->sb_flags & SB_UNIX);
1023
1024 if (error_out)
1025 *error_out = 0;
1026
1027 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1028 panic("sbappendaddrorfree");
1029
1030 if (sb->sb_flags & SB_DROP) {
1031 if (m0 != NULL)
1032 m_freem(m0);
1033 if (control != NULL && !sb_unix)
1034 m_freem(control);
1035 if (error_out != NULL)
1036 *error_out = EINVAL;
1037 return (0);
1038 }
1039
1040 /* Call socket data in filters */
1041 if ((sb->sb_flags & SB_RECV) != 0) {
1042 int error;
1043 error = sflt_data_in(sb->sb_so, asa, &m0, &control, 0, NULL);
1044 SBLASTRECORDCHK(sb, __func__);
1045 if (error) {
1046 if (error != EJUSTRETURN) {
1047 if (m0)
1048 m_freem(m0);
1049 if (control != NULL && !sb_unix)
1050 m_freem(control);
1051 if (error_out)
1052 *error_out = error;
1053 }
1054 return (0);
1055 }
1056 }
1057
1058 result = sbappendaddr_internal(sb, asa, m0, control);
1059 if (result == 0) {
1060 if (m0)
1061 m_freem(m0);
1062 if (control != NULL && !sb_unix)
1063 m_freem(control);
1064 if (error_out)
1065 *error_out = ENOBUFS;
1066 }
1067
1068 return (result);
1069 }
1070
1071 static int
1072 sbappendcontrol_internal(struct sockbuf *sb, struct mbuf *m0,
1073 struct mbuf *control)
1074 {
1075 struct mbuf *m, *mlast, *n;
1076 int space = 0;
1077
1078 if (control == 0)
1079 panic("sbappendcontrol");
1080
1081 for (m = control; ; m = m->m_next) {
1082 space += m->m_len;
1083 if (m->m_next == 0)
1084 break;
1085 }
1086 n = m; /* save pointer to last control buffer */
1087 for (m = m0; m; m = m->m_next)
1088 space += m->m_len;
1089 if (space > sbspace(sb) && !(sb->sb_flags & SB_UNIX))
1090 return (0);
1091 n->m_next = m0; /* concatenate data to control */
1092
1093 SBLASTRECORDCHK(sb, "sbappendcontrol 1");
1094
1095 for (m = control; m->m_next != NULL; m = m->m_next)
1096 sballoc(sb, m);
1097 sballoc(sb, m);
1098 mlast = m;
1099
1100 if (sb->sb_lastrecord != NULL) {
1101 sb->sb_lastrecord->m_nextpkt = control;
1102 } else {
1103 sb->sb_mb = control;
1104 }
1105 sb->sb_lastrecord = control;
1106 sb->sb_mbtail = mlast;
1107
1108 SBLASTMBUFCHK(sb, __func__);
1109 SBLASTRECORDCHK(sb, "sbappendcontrol 2");
1110
1111 postevent(0, sb, EV_RWBYTES);
1112 return (1);
1113 }
1114
1115 int
1116 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1117 int *error_out)
1118 {
1119 int result = 0;
1120 boolean_t sb_unix = (sb->sb_flags & SB_UNIX);
1121
1122 if (error_out)
1123 *error_out = 0;
1124
1125 if (sb->sb_flags & SB_DROP) {
1126 if (m0 != NULL)
1127 m_freem(m0);
1128 if (control != NULL && !sb_unix)
1129 m_freem(control);
1130 if (error_out != NULL)
1131 *error_out = EINVAL;
1132 return (0);
1133 }
1134
1135 if (sb->sb_flags & SB_RECV) {
1136 int error;
1137
1138 error = sflt_data_in(sb->sb_so, NULL, &m0, &control, 0, NULL);
1139 SBLASTRECORDCHK(sb, __func__);
1140 if (error) {
1141 if (error != EJUSTRETURN) {
1142 if (m0)
1143 m_freem(m0);
1144 if (control != NULL && !sb_unix)
1145 m_freem(control);
1146 if (error_out)
1147 *error_out = error;
1148 }
1149 return (0);
1150 }
1151 }
1152
1153 result = sbappendcontrol_internal(sb, m0, control);
1154 if (result == 0) {
1155 if (m0)
1156 m_freem(m0);
1157 if (control != NULL && !sb_unix)
1158 m_freem(control);
1159 if (error_out)
1160 *error_out = ENOBUFS;
1161 }
1162
1163 return (result);
1164 }
1165
1166 /*
1167 * Compress mbuf chain m into the socket
1168 * buffer sb following mbuf n. If n
1169 * is null, the buffer is presumed empty.
1170 */
1171 static inline void
1172 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1173 {
1174 int eor = 0;
1175 struct mbuf *o;
1176
1177 if (m == NULL) {
1178 /* There is nothing to compress; just update the tail */
1179 for (; n->m_next != NULL; n = n->m_next)
1180 ;
1181 sb->sb_mbtail = n;
1182 goto done;
1183 }
1184
1185 while (m) {
1186 eor |= m->m_flags & M_EOR;
1187 if (m->m_len == 0 && (eor == 0 ||
1188 (((o = m->m_next) || (o = n)) && o->m_type == m->m_type))) {
1189 if (sb->sb_lastrecord == m)
1190 sb->sb_lastrecord = m->m_next;
1191 m = m_free(m);
1192 continue;
1193 }
1194 if (n && (n->m_flags & M_EOR) == 0 &&
1195 #ifndef __APPLE__
1196 M_WRITABLE(n) &&
1197 #endif
1198 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1199 m->m_len <= M_TRAILINGSPACE(n) &&
1200 n->m_type == m->m_type) {
1201 bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
1202 (unsigned)m->m_len);
1203 n->m_len += m->m_len;
1204 sb->sb_cc += m->m_len;
1205 if (m->m_type != MT_DATA && m->m_type != MT_HEADER &&
1206 m->m_type != MT_OOBDATA)
1207 /* XXX: Probably don't need.*/
1208 sb->sb_ctl += m->m_len;
1209 m = m_free(m);
1210 continue;
1211 }
1212 if (n)
1213 n->m_next = m;
1214 else
1215 sb->sb_mb = m;
1216 sb->sb_mbtail = m;
1217 sballoc(sb, m);
1218 n = m;
1219 m->m_flags &= ~M_EOR;
1220 m = m->m_next;
1221 n->m_next = 0;
1222 }
1223 if (eor) {
1224 if (n)
1225 n->m_flags |= eor;
1226 else
1227 printf("semi-panic: sbcompress\n");
1228 }
1229 done:
1230 SBLASTMBUFCHK(sb, __func__);
1231 postevent(0, sb, EV_RWBYTES);
1232 }
1233
1234 void
1235 sb_empty_assert(struct sockbuf *sb, const char *where)
1236 {
1237 if (!(sb->sb_cc == 0 && sb->sb_mb == NULL && sb->sb_mbcnt == 0 &&
1238 sb->sb_mbtail == NULL && sb->sb_lastrecord == NULL)) {
1239 panic("%s: sb %p so %p cc %d mbcnt %d mb %p mbtail %p "
1240 "lastrecord %p\n", where, sb, sb->sb_so, sb->sb_cc,
1241 sb->sb_mbcnt, sb->sb_mb, sb->sb_mbtail, sb->sb_lastrecord);
1242 /* NOTREACHED */
1243 }
1244 }
1245
1246 /*
1247 * Free all mbufs in a sockbuf.
1248 * Check that all resources are reclaimed.
1249 */
1250 void
1251 sbflush(struct sockbuf *sb)
1252 {
1253 if (sb->sb_so == NULL)
1254 panic("sbflush sb->sb_so already null sb=%p\n", sb);
1255 (void) sblock(sb, M_WAIT);
1256 while (sb->sb_mbcnt) {
1257 /*
1258 * Don't call sbdrop(sb, 0) if the leading mbuf is non-empty:
1259 * we would loop forever. Panic instead.
1260 */
1261 if (!sb->sb_cc && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1262 break;
1263 sbdrop(sb, (int)sb->sb_cc);
1264 }
1265 sb_empty_assert(sb, __func__);
1266 postevent(0, sb, EV_RWBYTES);
1267 sbunlock(sb, 1); /* keep socket locked */
1268
1269 }
1270
1271 /*
1272 * Drop data from (the front of) a sockbuf.
1273 * use m_freem_list to free the mbuf structures
1274 * under a single lock... this is done by pruning
1275 * the top of the tree from the body by keeping track
1276 * of where we get to in the tree and then zeroing the
1277 * two pertinent pointers m_nextpkt and m_next
1278 * the socket buffer is then updated to point at the new
1279 * top of the tree and the pruned area is released via
1280 * m_freem_list.
1281 */
1282 void
1283 sbdrop(struct sockbuf *sb, int len)
1284 {
1285 struct mbuf *m, *free_list, *ml;
1286 struct mbuf *next, *last;
1287
1288 KERNEL_DEBUG((DBG_FNC_SBDROP | DBG_FUNC_START), sb, len, 0, 0, 0);
1289
1290 next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1291 free_list = last = m;
1292 ml = (struct mbuf *)0;
1293
1294 while (len > 0) {
1295 if (m == 0) {
1296 if (next == 0) {
1297 /*
1298 * temporarily replacing this panic with printf
1299 * because it occurs occasionally when closing
1300 * a socket when there is no harm in ignoring
1301 * it. This problem will be investigated
1302 * further.
1303 */
1304 /* panic("sbdrop"); */
1305 printf("sbdrop - count not zero\n");
1306 len = 0;
1307 /*
1308 * zero the counts. if we have no mbufs,
1309 * we have no data (PR-2986815)
1310 */
1311 sb->sb_cc = 0;
1312 sb->sb_mbcnt = 0;
1313 break;
1314 }
1315 m = last = next;
1316 next = m->m_nextpkt;
1317 continue;
1318 }
1319 if (m->m_len > len) {
1320 m->m_len -= len;
1321 m->m_data += len;
1322 sb->sb_cc -= len;
1323 if (m->m_type != MT_DATA && m->m_type != MT_HEADER &&
1324 m->m_type != MT_OOBDATA)
1325 sb->sb_ctl -= len;
1326 break;
1327 }
1328 len -= m->m_len;
1329 sbfree(sb, m);
1330
1331 ml = m;
1332 m = m->m_next;
1333 }
1334 while (m && m->m_len == 0) {
1335 sbfree(sb, m);
1336
1337 ml = m;
1338 m = m->m_next;
1339 }
1340 if (ml) {
1341 ml->m_next = (struct mbuf *)0;
1342 last->m_nextpkt = (struct mbuf *)0;
1343 m_freem_list(free_list);
1344 }
1345 if (m) {
1346 sb->sb_mb = m;
1347 m->m_nextpkt = next;
1348 } else {
1349 sb->sb_mb = next;
1350 }
1351
1352 /*
1353 * First part is an inline SB_EMPTY_FIXUP(). Second part
1354 * makes sure sb_lastrecord is up-to-date if we dropped
1355 * part of the last record.
1356 */
1357 m = sb->sb_mb;
1358 if (m == NULL) {
1359 sb->sb_mbtail = NULL;
1360 sb->sb_lastrecord = NULL;
1361 } else if (m->m_nextpkt == NULL) {
1362 sb->sb_lastrecord = m;
1363 }
1364
1365 postevent(0, sb, EV_RWBYTES);
1366
1367 KERNEL_DEBUG((DBG_FNC_SBDROP | DBG_FUNC_END), sb, 0, 0, 0, 0);
1368 }
1369
1370 /*
1371 * Drop a record off the front of a sockbuf
1372 * and move the next record to the front.
1373 */
1374 void
1375 sbdroprecord(struct sockbuf *sb)
1376 {
1377 struct mbuf *m, *mn;
1378
1379 m = sb->sb_mb;
1380 if (m) {
1381 sb->sb_mb = m->m_nextpkt;
1382 do {
1383 sbfree(sb, m);
1384 MFREE(m, mn);
1385 m = mn;
1386 } while (m);
1387 }
1388 SB_EMPTY_FIXUP(sb);
1389 postevent(0, sb, EV_RWBYTES);
1390 }
1391
1392 /*
1393 * Create a "control" mbuf containing the specified data
1394 * with the specified type for presentation on a socket buffer.
1395 */
1396 struct mbuf *
1397 sbcreatecontrol(caddr_t p, int size, int type, int level)
1398 {
1399 struct cmsghdr *cp;
1400 struct mbuf *m;
1401
1402 if (CMSG_SPACE((u_int)size) > MLEN)
1403 return ((struct mbuf *)NULL);
1404 if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
1405 return ((struct mbuf *)NULL);
1406 cp = mtod(m, struct cmsghdr *);
1407 /* XXX check size? */
1408 (void) memcpy(CMSG_DATA(cp), p, size);
1409 m->m_len = CMSG_SPACE(size);
1410 cp->cmsg_len = CMSG_LEN(size);
1411 cp->cmsg_level = level;
1412 cp->cmsg_type = type;
1413 return (m);
1414 }
1415
1416 /*
1417 * Some routines that return EOPNOTSUPP for entry points that are not
1418 * supported by a protocol. Fill in as needed.
1419 */
1420 int
1421 pru_abort_notsupp(__unused struct socket *so)
1422 {
1423 return (EOPNOTSUPP);
1424 }
1425
1426 int
1427 pru_accept_notsupp(__unused struct socket *so, __unused struct sockaddr **nam)
1428 {
1429 return (EOPNOTSUPP);
1430 }
1431
1432 int
1433 pru_attach_notsupp(__unused struct socket *so, __unused int proto,
1434 __unused struct proc *p)
1435 {
1436 return (EOPNOTSUPP);
1437 }
1438
1439 int
1440 pru_bind_notsupp(__unused struct socket *so, __unused struct sockaddr *nam,
1441 __unused struct proc *p)
1442 {
1443 return (EOPNOTSUPP);
1444 }
1445
1446 int
1447 pru_connect_notsupp(__unused struct socket *so, __unused struct sockaddr *nam,
1448 __unused struct proc *p)
1449 {
1450 return (EOPNOTSUPP);
1451 }
1452
1453 int
1454 pru_connect2_notsupp(__unused struct socket *so1, __unused struct socket *so2)
1455 {
1456 return (EOPNOTSUPP);
1457 }
1458
1459 int
1460 pru_control_notsupp(__unused struct socket *so, __unused u_long cmd,
1461 __unused caddr_t data, __unused struct ifnet *ifp, __unused struct proc *p)
1462 {
1463 return (EOPNOTSUPP);
1464 }
1465
1466 int
1467 pru_detach_notsupp(__unused struct socket *so)
1468 {
1469 return (EOPNOTSUPP);
1470 }
1471
1472 int
1473 pru_disconnect_notsupp(__unused struct socket *so)
1474 {
1475 return (EOPNOTSUPP);
1476 }
1477
1478 int
1479 pru_listen_notsupp(__unused struct socket *so, __unused struct proc *p)
1480 {
1481 return (EOPNOTSUPP);
1482 }
1483
1484 int
1485 pru_peeraddr_notsupp(__unused struct socket *so, __unused struct sockaddr **nam)
1486 {
1487 return (EOPNOTSUPP);
1488 }
1489
1490 int
1491 pru_rcvd_notsupp(__unused struct socket *so, __unused int flags)
1492 {
1493 return (EOPNOTSUPP);
1494 }
1495
1496 int
1497 pru_rcvoob_notsupp(__unused struct socket *so, __unused struct mbuf *m,
1498 __unused int flags)
1499 {
1500 return (EOPNOTSUPP);
1501 }
1502
1503 int
1504 pru_send_notsupp(__unused struct socket *so, __unused int flags,
1505 __unused struct mbuf *m, __unused struct sockaddr *addr,
1506 __unused struct mbuf *control, __unused struct proc *p)
1507
1508 {
1509 return (EOPNOTSUPP);
1510 }
1511
1512
1513 /*
1514 * This isn't really a ``null'' operation, but it's the default one
1515 * and doesn't do anything destructive.
1516 */
1517 int
1518 pru_sense_null(struct socket *so, void *ub, int isstat64)
1519 {
1520 if (isstat64 != 0) {
1521 struct stat64 *sb64;
1522
1523 sb64 = (struct stat64 *)ub;
1524 sb64->st_blksize = so->so_snd.sb_hiwat;
1525 } else {
1526 struct stat *sb;
1527
1528 sb = (struct stat *)ub;
1529 sb->st_blksize = so->so_snd.sb_hiwat;
1530 }
1531
1532 return (0);
1533 }
1534
1535
1536 int
1537 pru_sosend_notsupp(__unused struct socket *so, __unused struct sockaddr *addr,
1538 __unused struct uio *uio, __unused struct mbuf *top,
1539 __unused struct mbuf *control, __unused int flags)
1540
1541 {
1542 return (EOPNOTSUPP);
1543 }
1544
1545 int
1546 pru_soreceive_notsupp(__unused struct socket *so,
1547 __unused struct sockaddr **paddr,
1548 __unused struct uio *uio, __unused struct mbuf **mp0,
1549 __unused struct mbuf **controlp, __unused int *flagsp)
1550 {
1551 return (EOPNOTSUPP);
1552 }
1553
1554 int
1555 pru_shutdown_notsupp(__unused struct socket *so)
1556 {
1557 return (EOPNOTSUPP);
1558 }
1559
1560 int
1561 pru_sockaddr_notsupp(__unused struct socket *so, __unused struct sockaddr **nam)
1562 {
1563 return (EOPNOTSUPP);
1564 }
1565
1566 int
1567 pru_sopoll_notsupp(__unused struct socket *so, __unused int events,
1568 __unused kauth_cred_t cred, __unused void *wql)
1569 {
1570 return (EOPNOTSUPP);
1571 }
1572
1573
1574 #ifdef __APPLE__
1575 /*
1576 * The following are macros on BSD and functions on Darwin
1577 */
1578
1579 /*
1580 * Do we need to notify the other side when I/O is possible?
1581 */
1582
1583 int
1584 sb_notify(struct sockbuf *sb)
1585 {
1586 return ((sb->sb_flags &
1587 (SB_WAIT|SB_SEL|SB_ASYNC|SB_UPCALL|SB_KNOTE)) != 0);
1588 }
1589
1590 /*
1591 * How much space is there in a socket buffer (so->so_snd or so->so_rcv)?
1592 * This is problematical if the fields are unsigned, as the space might
1593 * still be negative (cc > hiwat or mbcnt > mbmax). Should detect
1594 * overflow and return 0.
1595 */
1596 int
1597 sbspace(struct sockbuf *sb)
1598 {
1599 int space =
1600 imin((int)(sb->sb_hiwat - sb->sb_cc),
1601 (int)(sb->sb_mbmax - sb->sb_mbcnt));
1602 if (space < 0)
1603 space = 0;
1604
1605 return space;
1606 }
1607
1608 /* do we have to send all at once on a socket? */
1609 int
1610 sosendallatonce(struct socket *so)
1611 {
1612 return (so->so_proto->pr_flags & PR_ATOMIC);
1613 }
1614
1615 /* can we read something from so? */
1616 int
1617 soreadable(struct socket *so)
1618 {
1619 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
1620 (so->so_state & SS_CANTRCVMORE) ||
1621 so->so_comp.tqh_first || so->so_error);
1622 }
1623
1624 /* can we write something to so? */
1625
1626 int
1627 sowriteable(struct socket *so)
1628 {
1629 return ((sbspace(&(so)->so_snd) >= (so)->so_snd.sb_lowat &&
1630 ((so->so_state&SS_ISCONNECTED) ||
1631 (so->so_proto->pr_flags&PR_CONNREQUIRED) == 0)) ||
1632 (so->so_state & SS_CANTSENDMORE) ||
1633 so->so_error);
1634 }
1635
1636 /* adjust counters in sb reflecting allocation of m */
1637
1638 void
1639 sballoc(struct sockbuf *sb, struct mbuf *m)
1640 {
1641 int cnt = 1;
1642 sb->sb_cc += m->m_len;
1643 if (m->m_type != MT_DATA && m->m_type != MT_HEADER &&
1644 m->m_type != MT_OOBDATA)
1645 sb->sb_ctl += m->m_len;
1646 sb->sb_mbcnt += MSIZE;
1647
1648 if (m->m_flags & M_EXT) {
1649 sb->sb_mbcnt += m->m_ext.ext_size;
1650 cnt += m->m_ext.ext_size / MSIZE ;
1651 }
1652 OSAddAtomic(cnt, &total_mb_cnt);
1653 }
1654
1655 /* adjust counters in sb reflecting freeing of m */
1656 void
1657 sbfree(struct sockbuf *sb, struct mbuf *m)
1658 {
1659 int cnt = -1;
1660 sb->sb_cc -= m->m_len;
1661 if (m->m_type != MT_DATA && m->m_type != MT_HEADER &&
1662 m->m_type != MT_OOBDATA)
1663 sb->sb_ctl -= m->m_len;
1664 sb->sb_mbcnt -= MSIZE;
1665 if (m->m_flags & M_EXT) {
1666 sb->sb_mbcnt -= m->m_ext.ext_size;
1667 cnt -= m->m_ext.ext_size / MSIZE ;
1668 }
1669 OSAddAtomic(cnt, &total_mb_cnt);
1670 }
1671
1672 /*
1673 * Set lock on sockbuf sb; sleep if lock is already held.
1674 * Unless SB_NOINTR is set on sockbuf, sleep is interruptible.
1675 * Returns error without lock if sleep is interrupted.
1676 *
1677 * Returns: 0 Success
1678 * EWOULDBLOCK
1679 * sb_lock:EINTR
1680 */
1681 int
1682 sblock(struct sockbuf *sb, int wf)
1683 {
1684 int error = 0;
1685
1686 if (sb->sb_flags & SB_LOCK)
1687 error = (wf == M_WAIT) ? sb_lock(sb) : EWOULDBLOCK;
1688 else
1689 sb->sb_flags |= SB_LOCK;
1690
1691 return (error);
1692 }
1693
1694 /* release lock on sockbuf sb */
1695 void
1696 sbunlock(struct sockbuf *sb, int keeplocked)
1697 {
1698 struct socket *so = sb->sb_so;
1699 void *lr_saved;
1700 lck_mtx_t *mutex_held;
1701
1702 lr_saved = __builtin_return_address(0);
1703
1704 sb->sb_flags &= ~SB_LOCK;
1705
1706 if (sb->sb_flags & SB_WANT) {
1707 sb->sb_flags &= ~SB_WANT;
1708 if (so->so_usecount < 0) {
1709 panic("sbunlock: b4 wakeup so=%p ref=%d lr=%p "
1710 "sb_flags=%x lrh= %s\n", sb->sb_so, so->so_usecount,
1711 lr_saved, sb->sb_flags, solockhistory_nr(so));
1712 /* NOTREACHED */
1713 }
1714 wakeup((caddr_t)&(sb)->sb_flags);
1715 }
1716 if (keeplocked == 0) { /* unlock on exit */
1717 if (so->so_proto->pr_getlock != NULL)
1718 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
1719 else
1720 mutex_held = so->so_proto->pr_domain->dom_mtx;
1721
1722 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
1723
1724 so->so_usecount--;
1725 if (so->so_usecount < 0)
1726 panic("sbunlock: unlock on exit so=%p ref=%d lr=%p "
1727 "sb_flags=%x lrh= %s\n", so, so->so_usecount, lr_saved,
1728 sb->sb_flags, solockhistory_nr(so));
1729 so->unlock_lr[so->next_unlock_lr] = lr_saved;
1730 so->next_unlock_lr = (so->next_unlock_lr+1) % SO_LCKDBG_MAX;
1731 lck_mtx_unlock(mutex_held);
1732 }
1733 }
1734
1735 void
1736 sorwakeup(struct socket *so)
1737 {
1738 if (sb_notify(&so->so_rcv))
1739 sowakeup(so, &so->so_rcv);
1740 }
1741
1742 void
1743 sowwakeup(struct socket *so)
1744 {
1745 if (sb_notify(&so->so_snd))
1746 sowakeup(so, &so->so_snd);
1747 }
1748 #endif /* __APPLE__ */
1749
1750 /*
1751 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
1752 */
1753 struct sockaddr *
1754 dup_sockaddr(struct sockaddr *sa, int canwait)
1755 {
1756 struct sockaddr *sa2;
1757
1758 MALLOC(sa2, struct sockaddr *, sa->sa_len, M_SONAME,
1759 canwait ? M_WAITOK : M_NOWAIT);
1760 if (sa2)
1761 bcopy(sa, sa2, sa->sa_len);
1762 return (sa2);
1763 }
1764
1765 /*
1766 * Create an external-format (``xsocket'') structure using the information
1767 * in the kernel-format socket structure pointed to by so. This is done
1768 * to reduce the spew of irrelevant information over this interface,
1769 * to isolate user code from changes in the kernel structure, and
1770 * potentially to provide information-hiding if we decide that
1771 * some of this information should be hidden from users.
1772 */
1773 void
1774 sotoxsocket(struct socket *so, struct xsocket *xso)
1775 {
1776 xso->xso_len = sizeof (*xso);
1777 xso->xso_so = (_XSOCKET_PTR(struct socket *))(uintptr_t)so;
1778 xso->so_type = so->so_type;
1779 xso->so_options = so->so_options;
1780 xso->so_linger = so->so_linger;
1781 xso->so_state = so->so_state;
1782 xso->so_pcb = (_XSOCKET_PTR(caddr_t))(uintptr_t)so->so_pcb;
1783 if (so->so_proto) {
1784 xso->xso_protocol = so->so_proto->pr_protocol;
1785 xso->xso_family = so->so_proto->pr_domain->dom_family;
1786 } else {
1787 xso->xso_protocol = xso->xso_family = 0;
1788 }
1789 xso->so_qlen = so->so_qlen;
1790 xso->so_incqlen = so->so_incqlen;
1791 xso->so_qlimit = so->so_qlimit;
1792 xso->so_timeo = so->so_timeo;
1793 xso->so_error = so->so_error;
1794 xso->so_pgid = so->so_pgid;
1795 xso->so_oobmark = so->so_oobmark;
1796 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
1797 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
1798 xso->so_uid = so->so_uid;
1799 }
1800
1801
1802 #if !CONFIG_EMBEDDED
1803
1804 void
1805 sotoxsocket64(struct socket *so, struct xsocket64 *xso)
1806 {
1807 xso->xso_len = sizeof (*xso);
1808 xso->xso_so = (u_int64_t)(uintptr_t)so;
1809 xso->so_type = so->so_type;
1810 xso->so_options = so->so_options;
1811 xso->so_linger = so->so_linger;
1812 xso->so_state = so->so_state;
1813 xso->so_pcb = (u_int64_t)(uintptr_t)so->so_pcb;
1814 if (so->so_proto) {
1815 xso->xso_protocol = so->so_proto->pr_protocol;
1816 xso->xso_family = so->so_proto->pr_domain->dom_family;
1817 } else {
1818 xso->xso_protocol = xso->xso_family = 0;
1819 }
1820 xso->so_qlen = so->so_qlen;
1821 xso->so_incqlen = so->so_incqlen;
1822 xso->so_qlimit = so->so_qlimit;
1823 xso->so_timeo = so->so_timeo;
1824 xso->so_error = so->so_error;
1825 xso->so_pgid = so->so_pgid;
1826 xso->so_oobmark = so->so_oobmark;
1827 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
1828 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
1829 xso->so_uid = so->so_uid;
1830 }
1831
1832 #endif /* !CONFIG_EMBEDDED */
1833
1834 /*
1835 * This does the same for sockbufs. Note that the xsockbuf structure,
1836 * since it is always embedded in a socket, does not include a self
1837 * pointer nor a length. We make this entry point public in case
1838 * some other mechanism needs it.
1839 */
1840 void
1841 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1842 {
1843 xsb->sb_cc = sb->sb_cc;
1844 xsb->sb_hiwat = sb->sb_hiwat;
1845 xsb->sb_mbcnt = sb->sb_mbcnt;
1846 xsb->sb_mbmax = sb->sb_mbmax;
1847 xsb->sb_lowat = sb->sb_lowat;
1848 xsb->sb_flags = sb->sb_flags;
1849 xsb->sb_timeo = (short)
1850 (sb->sb_timeo.tv_sec * hz) + sb->sb_timeo.tv_usec / tick;
1851 if (xsb->sb_timeo == 0 && sb->sb_timeo.tv_usec != 0)
1852 xsb->sb_timeo = 1;
1853 }
1854
1855 int
1856 soisbackground(struct socket *so)
1857 {
1858 return (so->so_traffic_mgt_flags & TRAFFIC_MGT_SO_BACKGROUND);
1859 }
1860
1861 #if PKT_PRIORITY
1862 #define _MIN_NXT_CMSGHDR_PTR(cmsg) \
1863 ((char *)(cmsg) + \
1864 __DARWIN_ALIGN32((__uint32_t)(cmsg)->cmsg_len) + \
1865 __DARWIN_ALIGN32(sizeof(struct cmsghdr)))
1866
1867 #define M_FIRST_CMSGHDR(m) \
1868 ((char *)(m) != (char *)0L && (size_t)(m)->m_len >= sizeof(struct cmsghdr) && \
1869 (socklen_t)(m)->m_len >= __DARWIN_ALIGN32(((struct cmsghdr *)(m)->m_data)->cmsg_len) ?\
1870 (struct cmsghdr *)(m)->m_data : \
1871 (struct cmsghdr *)0L)
1872
1873 #define M_NXT_CMSGHDR(m, cmsg) \
1874 ((char *)(cmsg) == (char *)0L ? M_FIRST_CMSGHDR(m) : \
1875 _MIN_NXT_CMSGHDR_PTR(cmsg) > ((char *)(m)->m_data) + (m)->m_len || \
1876 _MIN_NXT_CMSGHDR_PTR(cmsg) < (char *)(m)->m_data ? \
1877 (struct cmsghdr *)0L /* NULL */ : \
1878 (struct cmsghdr *)((unsigned char *)(cmsg) + \
1879 __DARWIN_ALIGN32((__uint32_t)(cmsg)->cmsg_len)))
1880 #endif /* PKT_PRIORITY */
1881
1882 __private_extern__ int
1883 mbuf_traffic_class_from_control(struct mbuf *control)
1884 {
1885 #if !PKT_PRIORITY
1886 #pragma unused(control)
1887 return MBUF_TC_NONE;
1888 #else /* PKT_PRIORITY */
1889 struct cmsghdr *cm;
1890
1891 for (cm = M_FIRST_CMSGHDR(control); cm; cm = M_NXT_CMSGHDR(control, cm)) {
1892 int tc;
1893
1894 if (cm->cmsg_len < sizeof(struct cmsghdr))
1895 break;
1896
1897 if (cm->cmsg_level != SOL_SOCKET || cm->cmsg_type != SO_TRAFFIC_CLASS)
1898 continue;
1899 if (cm->cmsg_len != CMSG_LEN(sizeof(int)))
1900 continue;
1901
1902 tc = *(int *)CMSG_DATA(cm);
1903
1904 switch (tc) {
1905 case SO_TC_BE:
1906 return MBUF_TC_BE;
1907 case SO_TC_BK:
1908 return MBUF_TC_BK;
1909 case SO_TC_VI:
1910 return MBUF_TC_VI;
1911 case SO_TC_VO:
1912 return MBUF_TC_VO;
1913 default:
1914 break;
1915 }
1916 }
1917
1918 return MBUF_TC_NONE;
1919 #endif /* PKT_PRIORITY */
1920 }
1921
1922 /*
1923 * Here is the definition of some of the basic objects in the kern.ipc
1924 * branch of the MIB.
1925 */
1926 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW|CTLFLAG_LOCKED, 0, "IPC");
1927
1928 /* Check that the maximum socket buffer size is within a range */
1929
1930 static int
1931 sysctl_sb_max(__unused struct sysctl_oid *oidp, __unused void *arg1,
1932 __unused int arg2, struct sysctl_req *req)
1933 {
1934 u_int32_t new_value;
1935 int changed = 0;
1936 int error = sysctl_io_number(req, sb_max, sizeof(u_int32_t), &new_value,
1937 &changed);
1938 if (!error && changed) {
1939 if (new_value > LOW_SB_MAX &&
1940 new_value <= high_sb_max ) {
1941 sb_max = new_value;
1942 } else {
1943 error = ERANGE;
1944 }
1945 }
1946 return error;
1947 }
1948
1949 SYSCTL_PROC(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf, CTLTYPE_INT | CTLFLAG_RW,
1950 &sb_max, 0, &sysctl_sb_max, "IU", "Maximum socket buffer size");
1951
1952 SYSCTL_INT(_kern_ipc, OID_AUTO, maxsockets, CTLFLAG_RD,
1953 &maxsockets, 0, "Maximum number of sockets avaliable");
1954 SYSCTL_INT(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1955 &sb_efficiency, 0, "");
1956 SYSCTL_INT(_kern_ipc, OID_AUTO, sbspace_factor, CTLFLAG_RW,
1957 &sbspace_factor, 0, "Ratio of mbuf/cluster use for socket layers");
1958 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters, CTLFLAG_RD,
1959 &nmbclusters, 0, "");
1960 SYSCTL_INT(_kern_ipc, OID_AUTO, njcl, CTLFLAG_RD, &njcl, 0, "");
1961 SYSCTL_INT(_kern_ipc, OID_AUTO, njclbytes, CTLFLAG_RD, &njclbytes, 0, "");
1962 SYSCTL_INT(_kern_ipc, KIPC_SOQLIMITCOMPAT, soqlimitcompat, CTLFLAG_RW,
1963 &soqlimitcompat, 1, "Enable socket queue limit compatibility");
1964 SYSCTL_INT(_kern_ipc, OID_AUTO, soqlencomp, CTLFLAG_RW,
1965 &soqlencomp, 0, "Listen backlog represents only complete queue");