2 * Copyright (c) 1982, 1986, 1988, 1990, 1993
3 * The Regents of the University of California.
4 * Copyright (c) 2004 The FreeBSD Foundation
5 * Copyright (c) 2004-2008 Robert N. M. Watson
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
36 * Comments on the socket life cycle:
38 * soalloc() sets of socket layer state for a socket, called only by
39 * socreate() and sonewconn(). Socket layer private.
41 * sodealloc() tears down socket layer state for a socket, called only by
42 * sofree() and sonewconn(). Socket layer private.
44 * pru_attach() associates protocol layer state with an allocated socket;
45 * called only once, may fail, aborting socket allocation. This is called
46 * from socreate() and sonewconn(). Socket layer private.
48 * pru_detach() disassociates protocol layer state from an attached socket,
49 * and will be called exactly once for sockets in which pru_attach() has
50 * been successfully called. If pru_attach() returned an error,
51 * pru_detach() will not be called. Socket layer private.
53 * pru_abort() and pru_close() notify the protocol layer that the last
54 * consumer of a socket is starting to tear down the socket, and that the
55 * protocol should terminate the connection. Historically, pru_abort() also
56 * detached protocol state from the socket state, but this is no longer the
59 * socreate() creates a socket and attaches protocol state. This is a public
60 * interface that may be used by socket layer consumers to create new
63 * sonewconn() creates a socket and attaches protocol state. This is a
64 * public interface that may be used by protocols to create new sockets when
65 * a new connection is received and will be available for accept() on a
68 * soclose() destroys a socket after possibly waiting for it to disconnect.
69 * This is a public interface that socket consumers should use to close and
70 * release a socket when done with it.
72 * soabort() destroys a socket without waiting for it to disconnect (used
73 * only for incoming connections that are already partially or fully
74 * connected). This is used internally by the socket layer when clearing
75 * listen socket queues (due to overflow or close on the listen socket), but
76 * is also a public interface protocols may use to abort connections in
77 * their incomplete listen queues should they no longer be required. Sockets
78 * placed in completed connection listen queues should not be aborted for
79 * reasons described in the comment above the soclose() implementation. This
80 * is not a general purpose close routine, and except in the specific
81 * circumstances described here, should not be used.
83 * sofree() will free a socket and its protocol state if all references on
84 * the socket have been released, and is the public interface to attempt to
85 * free a socket when a reference is removed. This is a socket layer private
88 * NOTE: In addition to socreate() and soclose(), which provide a single
89 * socket reference to the consumer to be managed as required, there are two
90 * calls to explicitly manage socket references, soref(), and sorele().
91 * Currently, these are generally required only when transitioning a socket
92 * from a listen queue to a file descriptor, in order to prevent garbage
93 * collection of the socket at an untimely moment. For a number of reasons,
94 * these interfaces are not preferred, and should be avoided.
96 * NOTE: With regard to VNETs the general rule is that callers do not set
97 * curvnet. Exceptions to this rule include soabort(), sodisconnect(),
98 * sofree() (and with that sorele(), sotryfree()), as well as sonewconn()
99 * and sorflush(), which are usually called from a pre-set VNET context.
100 * sopoll() currently does not need a VNET context to be set.
103 #include <sys/cdefs.h>
104 __FBSDID("$FreeBSD$");
106 #include "opt_inet.h"
107 #include "opt_inet6.h"
108 #include "opt_compat.h"
110 #include <sys/param.h>
111 #include <sys/systm.h>
112 #include <sys/fcntl.h>
113 #include <sys/limits.h>
114 #include <sys/lock.h>
116 #include <sys/malloc.h>
117 #include <sys/mbuf.h>
118 #include <sys/mutex.h>
119 #include <sys/domain.h>
120 #include <sys/file.h> /* for struct knote */
121 #include <sys/hhook.h>
122 #include <sys/kernel.h>
123 #include <sys/khelp.h>
124 #include <sys/event.h>
125 #include <sys/eventhandler.h>
126 #include <sys/poll.h>
127 #include <sys/proc.h>
128 #include <sys/protosw.h>
129 #include <sys/socket.h>
130 #include <sys/socketvar.h>
131 #include <sys/resourcevar.h>
132 #include <net/route.h>
133 #include <sys/signalvar.h>
134 #include <sys/stat.h>
136 #include <sys/sysctl.h>
137 #include <sys/taskqueue.h>
139 #include <sys/jail.h>
140 #include <sys/syslog.h>
141 #include <netinet/in.h>
143 #include <net/vnet.h>
145 #include <security/mac/mac_framework.h>
149 #ifdef COMPAT_FREEBSD32
150 #include <sys/mount.h>
151 #include <sys/sysent.h>
152 #include <compat/freebsd32/freebsd32.h>
155 static int soreceive_rcvoob(struct socket *so, struct uio *uio,
158 static void filt_sordetach(struct knote *kn);
159 static int filt_soread(struct knote *kn, long hint);
160 static void filt_sowdetach(struct knote *kn);
161 static int filt_sowrite(struct knote *kn, long hint);
162 static int inline hhook_run_socket(struct socket *so, void *hctx, int32_t h_id);
163 static int filt_soempty(struct knote *kn, long hint);
164 fo_kqfilter_t soo_kqfilter;
166 static struct filterops soread_filtops = {
168 .f_detach = filt_sordetach,
169 .f_event = filt_soread,
171 static struct filterops sowrite_filtops = {
173 .f_detach = filt_sowdetach,
174 .f_event = filt_sowrite,
176 static struct filterops soempty_filtops = {
178 .f_detach = filt_sowdetach,
179 .f_event = filt_soempty,
182 so_gen_t so_gencnt; /* generation count for sockets */
184 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
185 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
187 #define VNET_SO_ASSERT(so) \
188 VNET_ASSERT(curvnet != NULL, \
189 ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
191 VNET_DEFINE(struct hhook_head *, socket_hhh[HHOOK_SOCKET_LAST + 1]);
192 #define V_socket_hhh VNET(socket_hhh)
195 * Limit on the number of connections in the listen queue waiting
197 * NB: The original sysctl somaxconn is still available but hidden
198 * to prevent confusion about the actual purpose of this number.
200 static u_int somaxconn = SOMAXCONN;
203 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
209 error = sysctl_handle_int(oidp, &val, 0, req);
210 if (error || !req->newptr )
214 * The purpose of the UINT_MAX / 3 limit, is so that the formula
216 * below, will not overflow.
219 if (val < 1 || val > UINT_MAX / 3)
225 SYSCTL_PROC(_kern_ipc, OID_AUTO, soacceptqueue, CTLTYPE_UINT | CTLFLAG_RW,
226 0, sizeof(int), sysctl_somaxconn, "I",
227 "Maximum listen socket pending connection accept queue size");
228 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn,
229 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_SKIP,
230 0, sizeof(int), sysctl_somaxconn, "I",
231 "Maximum listen socket pending connection accept queue size (compat)");
233 static int numopensockets;
234 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
235 &numopensockets, 0, "Number of open sockets");
238 * accept_mtx locks down per-socket fields relating to accept queues. See
239 * socketvar.h for an annotation of the protected fields of struct socket.
241 struct mtx accept_mtx;
242 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
245 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
248 static struct mtx so_global_mtx;
249 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
252 * General IPC sysctl name space, used by sockets and a variety of other IPC
255 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
258 * Initialize the socket subsystem and set up the socket
261 static uma_zone_t socket_zone;
265 socket_zone_change(void *tag)
268 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
272 socket_hhook_register(int subtype)
275 if (hhook_head_register(HHOOK_TYPE_SOCKET, subtype,
276 &V_socket_hhh[subtype],
277 HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
278 printf("%s: WARNING: unable to register hook\n", __func__);
282 socket_hhook_deregister(int subtype)
285 if (hhook_head_deregister(V_socket_hhh[subtype]) != 0)
286 printf("%s: WARNING: unable to deregister hook\n", __func__);
290 socket_init(void *tag)
293 socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL,
294 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
295 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
296 uma_zone_set_warning(socket_zone, "kern.ipc.maxsockets limit reached");
297 EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL,
298 EVENTHANDLER_PRI_FIRST);
300 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL);
303 socket_vnet_init(const void *unused __unused)
307 /* We expect a contiguous range */
308 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
309 socket_hhook_register(i);
311 VNET_SYSINIT(socket_vnet_init, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
312 socket_vnet_init, NULL);
315 socket_vnet_uninit(const void *unused __unused)
319 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
320 socket_hhook_deregister(i);
322 VNET_SYSUNINIT(socket_vnet_uninit, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
323 socket_vnet_uninit, NULL);
326 * Initialise maxsockets. This SYSINIT must be run after
330 init_maxsockets(void *ignored)
333 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
334 maxsockets = imax(maxsockets, maxfiles);
336 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
339 * Sysctl to get and set the maximum global sockets limit. Notify protocols
340 * of the change so that they can update their dependent limits as required.
343 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
345 int error, newmaxsockets;
347 newmaxsockets = maxsockets;
348 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
349 if (error == 0 && req->newptr) {
350 if (newmaxsockets > maxsockets &&
351 newmaxsockets <= maxfiles) {
352 maxsockets = newmaxsockets;
353 EVENTHANDLER_INVOKE(maxsockets_change);
359 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
360 &maxsockets, 0, sysctl_maxsockets, "IU",
361 "Maximum number of sockets available");
364 * Socket operation routines. These routines are called by the routines in
365 * sys_socket.c or from a system process, and implement the semantics of
366 * socket operations by switching out to the protocol specific routines.
370 * Get a socket structure from our zone, and initialize it. Note that it
371 * would probably be better to allocate socket and PCB at the same time, but
372 * I'm not convinced that all the protocols can be easily modified to do
375 * soalloc() returns a socket with a ref count of 0.
377 static struct socket *
378 soalloc(struct vnet *vnet)
382 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
386 if (mac_socket_init(so, M_NOWAIT) != 0) {
387 uma_zfree(socket_zone, so);
391 if (khelp_init_osd(HELPER_CLASS_SOCKET, &so->osd)) {
392 uma_zfree(socket_zone, so);
396 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
397 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
398 sx_init(&so->so_snd.sb_sx, "so_snd_sx");
399 sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
400 TAILQ_INIT(&so->so_snd.sb_aiojobq);
401 TAILQ_INIT(&so->so_rcv.sb_aiojobq);
402 TASK_INIT(&so->so_snd.sb_aiotask, 0, soaio_snd, so);
403 TASK_INIT(&so->so_rcv.sb_aiotask, 0, soaio_rcv, so);
405 VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
406 __func__, __LINE__, so));
409 /* We shouldn't need the so_global_mtx */
410 if (hhook_run_socket(so, NULL, HHOOK_SOCKET_CREATE)) {
411 /* Do we need more comprehensive error returns? */
412 uma_zfree(socket_zone, so);
415 mtx_lock(&so_global_mtx);
416 so->so_gencnt = ++so_gencnt;
419 vnet->vnet_sockcnt++;
421 mtx_unlock(&so_global_mtx);
427 * Free the storage associated with a socket at the socket layer, tear down
428 * locks, labels, etc. All protocol state is assumed already to have been
429 * torn down (and possibly never set up) by the caller.
432 sodealloc(struct socket *so)
435 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
436 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
438 mtx_lock(&so_global_mtx);
439 so->so_gencnt = ++so_gencnt;
440 --numopensockets; /* Could be below, but faster here. */
442 VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
443 __func__, __LINE__, so));
444 so->so_vnet->vnet_sockcnt--;
446 mtx_unlock(&so_global_mtx);
447 if (so->so_rcv.sb_hiwat)
448 (void)chgsbsize(so->so_cred->cr_uidinfo,
449 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
450 if (so->so_snd.sb_hiwat)
451 (void)chgsbsize(so->so_cred->cr_uidinfo,
452 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
453 /* remove accept filter if one is present. */
454 if (so->so_accf != NULL)
455 do_setopt_accept_filter(so, NULL);
457 mac_socket_destroy(so);
459 hhook_run_socket(so, NULL, HHOOK_SOCKET_CLOSE);
462 khelp_destroy_osd(&so->osd);
463 sx_destroy(&so->so_snd.sb_sx);
464 sx_destroy(&so->so_rcv.sb_sx);
465 SOCKBUF_LOCK_DESTROY(&so->so_snd);
466 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
467 uma_zfree(socket_zone, so);
471 * socreate returns a socket with a ref count of 1. The socket should be
472 * closed with soclose().
475 socreate(int dom, struct socket **aso, int type, int proto,
476 struct ucred *cred, struct thread *td)
483 prp = pffindproto(dom, proto, type);
485 prp = pffindtype(dom, type);
488 /* No support for domain. */
489 if (pffinddomain(dom) == NULL)
490 return (EAFNOSUPPORT);
491 /* No support for socket type. */
492 if (proto == 0 && type != 0)
494 return (EPROTONOSUPPORT);
496 if (prp->pr_usrreqs->pru_attach == NULL ||
497 prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
498 return (EPROTONOSUPPORT);
500 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
501 return (EPROTONOSUPPORT);
503 if (prp->pr_type != type)
505 so = soalloc(CRED_TO_VNET(cred));
509 TAILQ_INIT(&so->so_incomp);
510 TAILQ_INIT(&so->so_comp);
512 so->so_cred = crhold(cred);
513 if ((prp->pr_domain->dom_family == PF_INET) ||
514 (prp->pr_domain->dom_family == PF_INET6) ||
515 (prp->pr_domain->dom_family == PF_ROUTE))
516 so->so_fibnum = td->td_proc->p_fibnum;
521 mac_socket_create(cred, so);
523 knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
524 knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
527 * Auto-sizing of socket buffers is managed by the protocols and
528 * the appropriate flags must be set in the pru_attach function.
530 CURVNET_SET(so->so_vnet);
531 error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
534 KASSERT(so->so_count == 1, ("socreate: so_count %d",
545 static int regression_sonewconn_earlytest = 1;
546 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
547 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
551 * When an attempt at a new connection is noted on a socket which accepts
552 * connections, sonewconn is called. If the connection is possible (subject
553 * to space constraints, etc.) then we allocate a new structure, properly
554 * linked into the data structure of the original socket, and return this.
555 * Connstatus may be 0, or SS_ISCONFIRMING, or SS_ISCONNECTED.
557 * Note: the ref count on the socket is 0 on return.
560 sonewconn(struct socket *head, int connstatus)
562 static struct timeval lastover;
563 static struct timeval overinterval = { 60, 0 };
564 static int overcount;
570 over = (head->so_qlen > 3 * head->so_qlimit / 2);
573 if (regression_sonewconn_earlytest && over) {
579 if (ratecheck(&lastover, &overinterval)) {
580 log(LOG_DEBUG, "%s: pcb %p: Listen queue overflow: "
581 "%i already in queue awaiting acceptance "
582 "(%d occurrences)\n",
583 __func__, head->so_pcb, head->so_qlen, overcount);
590 VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
591 __func__, __LINE__, head));
592 so = soalloc(head->so_vnet);
594 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
595 "limit reached or out of memory\n",
596 __func__, head->so_pcb);
599 if ((head->so_options & SO_ACCEPTFILTER) != 0)
602 so->so_type = head->so_type;
603 so->so_options = head->so_options &~ SO_ACCEPTCONN;
604 so->so_linger = head->so_linger;
605 so->so_state = head->so_state | SS_NOFDREF;
606 so->so_fibnum = head->so_fibnum;
607 so->so_proto = head->so_proto;
608 so->so_cred = crhold(head->so_cred);
610 mac_socket_newconn(head, so);
612 knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
613 knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
614 VNET_SO_ASSERT(head);
615 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
617 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
618 __func__, head->so_pcb);
621 if ((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
623 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
624 __func__, head->so_pcb);
627 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
628 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
629 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
630 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
631 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
632 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
633 so->so_state |= connstatus;
636 * The accept socket may be tearing down but we just
637 * won a race on the ACCEPT_LOCK.
638 * However, if sctp_peeloff() is called on a 1-to-many
639 * style socket, the SO_ACCEPTCONN doesn't need to be set.
641 if (!(head->so_options & SO_ACCEPTCONN) &&
642 ((head->so_proto->pr_protocol != IPPROTO_SCTP) ||
643 (head->so_type != SOCK_SEQPACKET))) {
646 sofree(so); /* NB: returns ACCEPT_UNLOCK'ed. */
650 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
651 so->so_qstate |= SQ_COMP;
655 * Keep removing sockets from the head until there's room for
656 * us to insert on the tail. In pre-locking revisions, this
657 * was a simple if(), but as we could be racing with other
658 * threads and soabort() requires dropping locks, we must
659 * loop waiting for the condition to be true.
661 while (head->so_incqlen > head->so_qlimit) {
663 sp = TAILQ_FIRST(&head->so_incomp);
664 TAILQ_REMOVE(&head->so_incomp, sp, so_list);
666 sp->so_qstate &= ~SQ_INCOMP;
672 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
673 so->so_qstate |= SQ_INCOMP;
679 wakeup_one(&head->so_timeo);
685 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
689 CURVNET_SET(so->so_vnet);
690 error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
696 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
700 CURVNET_SET(so->so_vnet);
701 error = (*so->so_proto->pr_usrreqs->pru_bindat)(fd, so, nam, td);
707 * solisten() transitions a socket from a non-listening state to a listening
708 * state, but can also be used to update the listen queue depth on an
709 * existing listen socket. The protocol will call back into the sockets
710 * layer using solisten_proto_check() and solisten_proto() to check and set
711 * socket-layer listen state. Call backs are used so that the protocol can
712 * acquire both protocol and socket layer locks in whatever order is required
715 * Protocol implementors are advised to hold the socket lock across the
716 * socket-layer test and set to avoid races at the socket layer.
719 solisten(struct socket *so, int backlog, struct thread *td)
723 CURVNET_SET(so->so_vnet);
724 error = (*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td);
730 solisten_proto_check(struct socket *so)
733 SOCK_LOCK_ASSERT(so);
735 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
742 solisten_proto(struct socket *so, int backlog)
745 SOCK_LOCK_ASSERT(so);
747 if (backlog < 0 || backlog > somaxconn)
749 so->so_qlimit = backlog;
750 so->so_options |= SO_ACCEPTCONN;
754 * Evaluate the reference count and named references on a socket; if no
755 * references remain, free it. This should be called whenever a reference is
756 * released, such as in sorele(), but also when named reference flags are
757 * cleared in socket or protocol code.
759 * sofree() will free the socket if:
761 * - There are no outstanding file descriptor references or related consumers
764 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
766 * - The protocol does not have an outstanding strong reference on the socket
769 * - The socket is not in a completed connection queue, so a process has been
770 * notified that it is present. If it is removed, the user process may
771 * block in accept() despite select() saying the socket was ready.
774 sofree(struct socket *so)
776 struct protosw *pr = so->so_proto;
779 ACCEPT_LOCK_ASSERT();
780 SOCK_LOCK_ASSERT(so);
782 if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
783 (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
791 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
792 (so->so_qstate & SQ_INCOMP) != 0,
793 ("sofree: so_head != NULL, but neither SQ_COMP nor "
795 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
796 (so->so_qstate & SQ_INCOMP) == 0,
797 ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
798 TAILQ_REMOVE(&head->so_incomp, so, so_list);
800 so->so_qstate &= ~SQ_INCOMP;
803 KASSERT((so->so_qstate & SQ_COMP) == 0 &&
804 (so->so_qstate & SQ_INCOMP) == 0,
805 ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
806 so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
807 if (so->so_options & SO_ACCEPTCONN) {
808 KASSERT((TAILQ_EMPTY(&so->so_comp)),
809 ("sofree: so_comp populated"));
810 KASSERT((TAILQ_EMPTY(&so->so_incomp)),
811 ("sofree: so_incomp populated"));
817 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
818 (*pr->pr_domain->dom_dispose)(so);
819 if (pr->pr_usrreqs->pru_detach != NULL)
820 (*pr->pr_usrreqs->pru_detach)(so);
823 * From this point on, we assume that no other references to this
824 * socket exist anywhere else in the stack. Therefore, no locks need
825 * to be acquired or held.
827 * We used to do a lot of socket buffer and socket locking here, as
828 * well as invoke sorflush() and perform wakeups. The direct call to
829 * dom_dispose() and sbrelease_internal() are an inlining of what was
830 * necessary from sorflush().
832 * Notice that the socket buffer and kqueue state are torn down
833 * before calling pru_detach. This means that protocols shold not
834 * assume they can perform socket wakeups, etc, in their detach code.
836 sbdestroy(&so->so_snd, so);
837 sbdestroy(&so->so_rcv, so);
838 seldrain(&so->so_snd.sb_sel);
839 seldrain(&so->so_rcv.sb_sel);
840 knlist_destroy(&so->so_rcv.sb_sel.si_note);
841 knlist_destroy(&so->so_snd.sb_sel.si_note);
846 * Close a socket on last file table reference removal. Initiate disconnect
847 * if connected. Free socket when disconnect complete.
849 * This function will sorele() the socket. Note that soclose() may be called
850 * prior to the ref count reaching zero. The actual socket structure will
851 * not be freed until the ref count reaches zero.
854 soclose(struct socket *so)
858 KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
860 CURVNET_SET(so->so_vnet);
861 funsetown(&so->so_sigio);
862 if (so->so_state & SS_ISCONNECTED) {
863 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
864 error = sodisconnect(so);
866 if (error == ENOTCONN)
871 if (so->so_options & SO_LINGER) {
872 if ((so->so_state & SS_ISDISCONNECTING) &&
873 (so->so_state & SS_NBIO))
875 while (so->so_state & SS_ISCONNECTED) {
876 error = tsleep(&so->so_timeo,
877 PSOCK | PCATCH, "soclos",
886 if (so->so_proto->pr_usrreqs->pru_close != NULL)
887 (*so->so_proto->pr_usrreqs->pru_close)(so);
889 if (so->so_options & SO_ACCEPTCONN) {
892 * Prevent new additions to the accept queues due
893 * to ACCEPT_LOCK races while we are draining them.
895 so->so_options &= ~SO_ACCEPTCONN;
896 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
897 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
899 sp->so_qstate &= ~SQ_INCOMP;
905 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
906 TAILQ_REMOVE(&so->so_comp, sp, so_list);
908 sp->so_qstate &= ~SQ_COMP;
914 KASSERT((TAILQ_EMPTY(&so->so_comp)),
915 ("%s: so_comp populated", __func__));
916 KASSERT((TAILQ_EMPTY(&so->so_incomp)),
917 ("%s: so_incomp populated", __func__));
920 KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
921 so->so_state |= SS_NOFDREF;
922 sorele(so); /* NB: Returns with ACCEPT_UNLOCK(). */
928 * soabort() is used to abruptly tear down a connection, such as when a
929 * resource limit is reached (listen queue depth exceeded), or if a listen
930 * socket is closed while there are sockets waiting to be accepted.
932 * This interface is tricky, because it is called on an unreferenced socket,
933 * and must be called only by a thread that has actually removed the socket
934 * from the listen queue it was on, or races with other threads are risked.
936 * This interface will call into the protocol code, so must not be called
937 * with any socket locks held. Protocols do call it while holding their own
938 * recursible protocol mutexes, but this is something that should be subject
939 * to review in the future.
942 soabort(struct socket *so)
946 * In as much as is possible, assert that no references to this
947 * socket are held. This is not quite the same as asserting that the
948 * current thread is responsible for arranging for no references, but
949 * is as close as we can get for now.
951 KASSERT(so->so_count == 0, ("soabort: so_count"));
952 KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
953 KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
954 KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
955 KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
958 if (so->so_proto->pr_usrreqs->pru_abort != NULL)
959 (*so->so_proto->pr_usrreqs->pru_abort)(so);
966 soaccept(struct socket *so, struct sockaddr **nam)
971 KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
972 so->so_state &= ~SS_NOFDREF;
975 CURVNET_SET(so->so_vnet);
976 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
982 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
985 return (soconnectat(AT_FDCWD, so, nam, td));
989 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
993 if (so->so_options & SO_ACCEPTCONN)
996 CURVNET_SET(so->so_vnet);
998 * If protocol is connection-based, can only connect once.
999 * Otherwise, if connected, try to disconnect first. This allows
1000 * user to disconnect by connecting to, e.g., a null address.
1002 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
1003 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
1004 (error = sodisconnect(so)))) {
1008 * Prevent accumulated error from previous connection from
1012 if (fd == AT_FDCWD) {
1013 error = (*so->so_proto->pr_usrreqs->pru_connect)(so,
1016 error = (*so->so_proto->pr_usrreqs->pru_connectat)(fd,
1026 soconnect2(struct socket *so1, struct socket *so2)
1030 CURVNET_SET(so1->so_vnet);
1031 error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
1037 sodisconnect(struct socket *so)
1041 if ((so->so_state & SS_ISCONNECTED) == 0)
1043 if (so->so_state & SS_ISDISCONNECTING)
1046 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
1050 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1053 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1054 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1058 int clen = 0, error, dontroute;
1060 KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
1061 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1062 ("sosend_dgram: !PR_ATOMIC"));
1065 resid = uio->uio_resid;
1067 resid = top->m_pkthdr.len;
1069 * In theory resid should be unsigned. However, space must be
1070 * signed, as it might be less than 0 if we over-committed, and we
1071 * must use a signed comparison of space and resid. On the other
1072 * hand, a negative resid causes us to loop sending 0-length
1073 * segments to the protocol.
1081 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1083 td->td_ru.ru_msgsnd++;
1084 if (control != NULL)
1085 clen = control->m_len;
1087 SOCKBUF_LOCK(&so->so_snd);
1088 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1089 SOCKBUF_UNLOCK(&so->so_snd);
1094 error = so->so_error;
1096 SOCKBUF_UNLOCK(&so->so_snd);
1099 if ((so->so_state & SS_ISCONNECTED) == 0) {
1101 * `sendto' and `sendmsg' is allowed on a connection-based
1102 * socket if it supports implied connect. Return ENOTCONN if
1103 * not connected and no address is supplied.
1105 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1106 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1107 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1108 !(resid == 0 && clen != 0)) {
1109 SOCKBUF_UNLOCK(&so->so_snd);
1113 } else if (addr == NULL) {
1114 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1117 error = EDESTADDRREQ;
1118 SOCKBUF_UNLOCK(&so->so_snd);
1124 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
1125 * problem and need fixing.
1127 space = sbspace(&so->so_snd);
1128 if (flags & MSG_OOB)
1131 SOCKBUF_UNLOCK(&so->so_snd);
1132 if (resid > space) {
1138 if (flags & MSG_EOR)
1139 top->m_flags |= M_EOR;
1142 * Copy the data from userland into a mbuf chain.
1143 * If no data is to be copied in, a single empty mbuf
1146 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1147 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1149 error = EFAULT; /* only possible error */
1152 space -= resid - uio->uio_resid;
1153 resid = uio->uio_resid;
1155 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1157 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1162 so->so_options |= SO_DONTROUTE;
1166 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1167 * of date. We could have received a reset packet in an interrupt or
1168 * maybe we slept while doing page faults in uiomove() etc. We could
1169 * probably recheck again inside the locking protection here, but
1170 * there are probably other places that this also happens. We must
1174 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1175 (flags & MSG_OOB) ? PRUS_OOB :
1177 * If the user set MSG_EOF, the protocol understands this flag and
1178 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1180 ((flags & MSG_EOF) &&
1181 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1184 /* If there is more to send set PRUS_MORETOCOME */
1185 (flags & MSG_MORETOCOME) ||
1186 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1187 top, addr, control, td);
1190 so->so_options &= ~SO_DONTROUTE;
1199 if (control != NULL)
1205 * Send on a socket. If send must go all at once and message is larger than
1206 * send buffering, then hard error. Lock against other senders. If must go
1207 * all at once and not enough room now, then inform user that this would
1208 * block and do nothing. Otherwise, if nonblocking, send as much as
1209 * possible. The data to be sent is described by "uio" if nonzero, otherwise
1210 * by the mbuf chain "top" (which must be null if uio is not). Data provided
1211 * in mbuf chain must be small enough to send all at once.
1213 * Returns nonzero on error, timeout or signal; callers must check for short
1214 * counts if EINTR/ERESTART are returned. Data and control buffers are freed
1218 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1219 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1223 int clen = 0, error, dontroute;
1224 int atomic = sosendallatonce(so) || top;
1227 resid = uio->uio_resid;
1229 resid = top->m_pkthdr.len;
1231 * In theory resid should be unsigned. However, space must be
1232 * signed, as it might be less than 0 if we over-committed, and we
1233 * must use a signed comparison of space and resid. On the other
1234 * hand, a negative resid causes us to loop sending 0-length
1235 * segments to the protocol.
1237 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1238 * type sockets since that's an error.
1240 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1246 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1247 (so->so_proto->pr_flags & PR_ATOMIC);
1249 td->td_ru.ru_msgsnd++;
1250 if (control != NULL)
1251 clen = control->m_len;
1253 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1259 SOCKBUF_LOCK(&so->so_snd);
1260 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1261 SOCKBUF_UNLOCK(&so->so_snd);
1266 error = so->so_error;
1268 SOCKBUF_UNLOCK(&so->so_snd);
1271 if ((so->so_state & SS_ISCONNECTED) == 0) {
1273 * `sendto' and `sendmsg' is allowed on a connection-
1274 * based socket if it supports implied connect.
1275 * Return ENOTCONN if not connected and no address is
1278 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1279 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1280 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1281 !(resid == 0 && clen != 0)) {
1282 SOCKBUF_UNLOCK(&so->so_snd);
1286 } else if (addr == NULL) {
1287 SOCKBUF_UNLOCK(&so->so_snd);
1288 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1291 error = EDESTADDRREQ;
1295 space = sbspace(&so->so_snd);
1296 if (flags & MSG_OOB)
1298 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1299 clen > so->so_snd.sb_hiwat) {
1300 SOCKBUF_UNLOCK(&so->so_snd);
1304 if (space < resid + clen &&
1305 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1306 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1307 SOCKBUF_UNLOCK(&so->so_snd);
1308 error = EWOULDBLOCK;
1311 error = sbwait(&so->so_snd);
1312 SOCKBUF_UNLOCK(&so->so_snd);
1317 SOCKBUF_UNLOCK(&so->so_snd);
1322 if (flags & MSG_EOR)
1323 top->m_flags |= M_EOR;
1326 * Copy the data from userland into a mbuf
1327 * chain. If resid is 0, which can happen
1328 * only if we have control to send, then
1329 * a single empty mbuf is returned. This
1330 * is a workaround to prevent protocol send
1333 top = m_uiotombuf(uio, M_WAITOK, space,
1334 (atomic ? max_hdr : 0),
1335 (atomic ? M_PKTHDR : 0) |
1336 ((flags & MSG_EOR) ? M_EOR : 0));
1338 error = EFAULT; /* only possible error */
1341 space -= resid - uio->uio_resid;
1342 resid = uio->uio_resid;
1346 so->so_options |= SO_DONTROUTE;
1350 * XXX all the SBS_CANTSENDMORE checks previously
1351 * done could be out of date. We could have received
1352 * a reset packet in an interrupt or maybe we slept
1353 * while doing page faults in uiomove() etc. We
1354 * could probably recheck again inside the locking
1355 * protection here, but there are probably other
1356 * places that this also happens. We must rethink
1360 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1361 (flags & MSG_OOB) ? PRUS_OOB :
1363 * If the user set MSG_EOF, the protocol understands
1364 * this flag and nothing left to send then use
1365 * PRU_SEND_EOF instead of PRU_SEND.
1367 ((flags & MSG_EOF) &&
1368 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1371 /* If there is more to send set PRUS_MORETOCOME. */
1372 (flags & MSG_MORETOCOME) ||
1373 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1374 top, addr, control, td);
1377 so->so_options &= ~SO_DONTROUTE;
1385 } while (resid && space > 0);
1389 sbunlock(&so->so_snd);
1393 if (control != NULL)
1399 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1400 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1404 CURVNET_SET(so->so_vnet);
1405 error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1406 control, flags, td);
1412 * The part of soreceive() that implements reading non-inline out-of-band
1413 * data from a socket. For more complete comments, see soreceive(), from
1414 * which this code originated.
1416 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1417 * unable to return an mbuf chain to the caller.
1420 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1422 struct protosw *pr = so->so_proto;
1426 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1429 m = m_get(M_WAITOK, MT_DATA);
1430 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1434 error = uiomove(mtod(m, void *),
1435 (int) min(uio->uio_resid, m->m_len), uio);
1437 } while (uio->uio_resid && error == 0 && m);
1445 * Following replacement or removal of the first mbuf on the first mbuf chain
1446 * of a socket buffer, push necessary state changes back into the socket
1447 * buffer so that other consumers see the values consistently. 'nextrecord'
1448 * is the callers locally stored value of the original value of
1449 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1450 * NOTE: 'nextrecord' may be NULL.
1452 static __inline void
1453 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1456 SOCKBUF_LOCK_ASSERT(sb);
1458 * First, update for the new value of nextrecord. If necessary, make
1459 * it the first record.
1461 if (sb->sb_mb != NULL)
1462 sb->sb_mb->m_nextpkt = nextrecord;
1464 sb->sb_mb = nextrecord;
1467 * Now update any dependent socket buffer fields to reflect the new
1468 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
1469 * addition of a second clause that takes care of the case where
1470 * sb_mb has been updated, but remains the last record.
1472 if (sb->sb_mb == NULL) {
1473 sb->sb_mbtail = NULL;
1474 sb->sb_lastrecord = NULL;
1475 } else if (sb->sb_mb->m_nextpkt == NULL)
1476 sb->sb_lastrecord = sb->sb_mb;
1480 * Implement receive operations on a socket. We depend on the way that
1481 * records are added to the sockbuf by sbappend. In particular, each record
1482 * (mbufs linked through m_next) must begin with an address if the protocol
1483 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1484 * data, and then zero or more mbufs of data. In order to allow parallelism
1485 * between network receive and copying to user space, as well as avoid
1486 * sleeping with a mutex held, we release the socket buffer mutex during the
1487 * user space copy. Although the sockbuf is locked, new data may still be
1488 * appended, and thus we must maintain consistency of the sockbuf during that
1491 * The caller may receive the data as a single mbuf chain by supplying an
1492 * mbuf **mp0 for use in returning the chain. The uio is then used only for
1493 * the count in uio_resid.
1496 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1497 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1499 struct mbuf *m, **mp;
1500 int flags, error, offset;
1502 struct protosw *pr = so->so_proto;
1503 struct mbuf *nextrecord;
1505 ssize_t orig_resid = uio->uio_resid;
1510 if (controlp != NULL)
1513 flags = *flagsp &~ MSG_EOR;
1516 if (flags & MSG_OOB)
1517 return (soreceive_rcvoob(so, uio, flags));
1520 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1521 && uio->uio_resid) {
1523 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1526 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1531 SOCKBUF_LOCK(&so->so_rcv);
1532 m = so->so_rcv.sb_mb;
1534 * If we have less data than requested, block awaiting more (subject
1535 * to any timeout) if:
1536 * 1. the current count is less than the low water mark, or
1537 * 2. MSG_DONTWAIT is not set
1539 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1540 sbavail(&so->so_rcv) < uio->uio_resid) &&
1541 sbavail(&so->so_rcv) < so->so_rcv.sb_lowat &&
1542 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1543 KASSERT(m != NULL || !sbavail(&so->so_rcv),
1544 ("receive: m == %p sbavail == %u",
1545 m, sbavail(&so->so_rcv)));
1549 error = so->so_error;
1550 if ((flags & MSG_PEEK) == 0)
1552 SOCKBUF_UNLOCK(&so->so_rcv);
1555 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1556 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1558 SOCKBUF_UNLOCK(&so->so_rcv);
1563 for (; m != NULL; m = m->m_next)
1564 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1565 m = so->so_rcv.sb_mb;
1568 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1569 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1570 SOCKBUF_UNLOCK(&so->so_rcv);
1574 if (uio->uio_resid == 0) {
1575 SOCKBUF_UNLOCK(&so->so_rcv);
1578 if ((so->so_state & SS_NBIO) ||
1579 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1580 SOCKBUF_UNLOCK(&so->so_rcv);
1581 error = EWOULDBLOCK;
1584 SBLASTRECORDCHK(&so->so_rcv);
1585 SBLASTMBUFCHK(&so->so_rcv);
1586 error = sbwait(&so->so_rcv);
1587 SOCKBUF_UNLOCK(&so->so_rcv);
1594 * From this point onward, we maintain 'nextrecord' as a cache of the
1595 * pointer to the next record in the socket buffer. We must keep the
1596 * various socket buffer pointers and local stack versions of the
1597 * pointers in sync, pushing out modifications before dropping the
1598 * socket buffer mutex, and re-reading them when picking it up.
1600 * Otherwise, we will race with the network stack appending new data
1601 * or records onto the socket buffer by using inconsistent/stale
1602 * versions of the field, possibly resulting in socket buffer
1605 * By holding the high-level sblock(), we prevent simultaneous
1606 * readers from pulling off the front of the socket buffer.
1608 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1610 uio->uio_td->td_ru.ru_msgrcv++;
1611 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1612 SBLASTRECORDCHK(&so->so_rcv);
1613 SBLASTMBUFCHK(&so->so_rcv);
1614 nextrecord = m->m_nextpkt;
1615 if (pr->pr_flags & PR_ADDR) {
1616 KASSERT(m->m_type == MT_SONAME,
1617 ("m->m_type == %d", m->m_type));
1620 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1622 if (flags & MSG_PEEK) {
1625 sbfree(&so->so_rcv, m);
1626 so->so_rcv.sb_mb = m_free(m);
1627 m = so->so_rcv.sb_mb;
1628 sockbuf_pushsync(&so->so_rcv, nextrecord);
1633 * Process one or more MT_CONTROL mbufs present before any data mbufs
1634 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1635 * just copy the data; if !MSG_PEEK, we call into the protocol to
1636 * perform externalization (or freeing if controlp == NULL).
1638 if (m != NULL && m->m_type == MT_CONTROL) {
1639 struct mbuf *cm = NULL, *cmn;
1640 struct mbuf **cme = &cm;
1643 if (flags & MSG_PEEK) {
1644 if (controlp != NULL) {
1645 *controlp = m_copym(m, 0, m->m_len,
1647 controlp = &(*controlp)->m_next;
1651 sbfree(&so->so_rcv, m);
1652 so->so_rcv.sb_mb = m->m_next;
1655 cme = &(*cme)->m_next;
1656 m = so->so_rcv.sb_mb;
1658 } while (m != NULL && m->m_type == MT_CONTROL);
1659 if ((flags & MSG_PEEK) == 0)
1660 sockbuf_pushsync(&so->so_rcv, nextrecord);
1661 while (cm != NULL) {
1664 if (pr->pr_domain->dom_externalize != NULL) {
1665 SOCKBUF_UNLOCK(&so->so_rcv);
1667 error = (*pr->pr_domain->dom_externalize)
1668 (cm, controlp, flags);
1669 SOCKBUF_LOCK(&so->so_rcv);
1670 } else if (controlp != NULL)
1674 if (controlp != NULL) {
1676 while (*controlp != NULL)
1677 controlp = &(*controlp)->m_next;
1682 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1684 nextrecord = so->so_rcv.sb_mb;
1688 if ((flags & MSG_PEEK) == 0) {
1689 KASSERT(m->m_nextpkt == nextrecord,
1690 ("soreceive: post-control, nextrecord !sync"));
1691 if (nextrecord == NULL) {
1692 KASSERT(so->so_rcv.sb_mb == m,
1693 ("soreceive: post-control, sb_mb!=m"));
1694 KASSERT(so->so_rcv.sb_lastrecord == m,
1695 ("soreceive: post-control, lastrecord!=m"));
1699 if (type == MT_OOBDATA)
1702 if ((flags & MSG_PEEK) == 0) {
1703 KASSERT(so->so_rcv.sb_mb == nextrecord,
1704 ("soreceive: sb_mb != nextrecord"));
1705 if (so->so_rcv.sb_mb == NULL) {
1706 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1707 ("soreceive: sb_lastercord != NULL"));
1711 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1712 SBLASTRECORDCHK(&so->so_rcv);
1713 SBLASTMBUFCHK(&so->so_rcv);
1716 * Now continue to read any data mbufs off of the head of the socket
1717 * buffer until the read request is satisfied. Note that 'type' is
1718 * used to store the type of any mbuf reads that have happened so far
1719 * such that soreceive() can stop reading if the type changes, which
1720 * causes soreceive() to return only one of regular data and inline
1721 * out-of-band data in a single socket receive operation.
1725 while (m != NULL && !(m->m_flags & M_NOTAVAIL) && uio->uio_resid > 0
1728 * If the type of mbuf has changed since the last mbuf
1729 * examined ('type'), end the receive operation.
1731 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1732 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
1733 if (type != m->m_type)
1735 } else if (type == MT_OOBDATA)
1738 KASSERT(m->m_type == MT_DATA,
1739 ("m->m_type == %d", m->m_type));
1740 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1741 len = uio->uio_resid;
1742 if (so->so_oobmark && len > so->so_oobmark - offset)
1743 len = so->so_oobmark - offset;
1744 if (len > m->m_len - moff)
1745 len = m->m_len - moff;
1747 * If mp is set, just pass back the mbufs. Otherwise copy
1748 * them out via the uio, then free. Sockbuf must be
1749 * consistent here (points to current mbuf, it points to next
1750 * record) when we drop priority; we must note any additions
1751 * to the sockbuf when we block interrupts again.
1754 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1755 SBLASTRECORDCHK(&so->so_rcv);
1756 SBLASTMBUFCHK(&so->so_rcv);
1757 SOCKBUF_UNLOCK(&so->so_rcv);
1758 error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1759 SOCKBUF_LOCK(&so->so_rcv);
1762 * The MT_SONAME mbuf has already been removed
1763 * from the record, so it is necessary to
1764 * remove the data mbufs, if any, to preserve
1765 * the invariant in the case of PR_ADDR that
1766 * requires MT_SONAME mbufs at the head of
1769 if (pr->pr_flags & PR_ATOMIC &&
1770 ((flags & MSG_PEEK) == 0))
1771 (void)sbdroprecord_locked(&so->so_rcv);
1772 SOCKBUF_UNLOCK(&so->so_rcv);
1776 uio->uio_resid -= len;
1777 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1778 if (len == m->m_len - moff) {
1779 if (m->m_flags & M_EOR)
1781 if (flags & MSG_PEEK) {
1785 nextrecord = m->m_nextpkt;
1786 sbfree(&so->so_rcv, m);
1788 m->m_nextpkt = NULL;
1791 so->so_rcv.sb_mb = m = m->m_next;
1794 so->so_rcv.sb_mb = m_free(m);
1795 m = so->so_rcv.sb_mb;
1797 sockbuf_pushsync(&so->so_rcv, nextrecord);
1798 SBLASTRECORDCHK(&so->so_rcv);
1799 SBLASTMBUFCHK(&so->so_rcv);
1802 if (flags & MSG_PEEK)
1806 if (flags & MSG_DONTWAIT) {
1807 *mp = m_copym(m, 0, len,
1811 * m_copym() couldn't
1813 * Adjust uio_resid back
1815 * down by len bytes,
1816 * which we didn't end
1817 * up "copying" over).
1819 uio->uio_resid += len;
1823 SOCKBUF_UNLOCK(&so->so_rcv);
1824 *mp = m_copym(m, 0, len,
1826 SOCKBUF_LOCK(&so->so_rcv);
1829 sbcut_locked(&so->so_rcv, len);
1832 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1833 if (so->so_oobmark) {
1834 if ((flags & MSG_PEEK) == 0) {
1835 so->so_oobmark -= len;
1836 if (so->so_oobmark == 0) {
1837 so->so_rcv.sb_state |= SBS_RCVATMARK;
1842 if (offset == so->so_oobmark)
1846 if (flags & MSG_EOR)
1849 * If the MSG_WAITALL flag is set (for non-atomic socket), we
1850 * must not quit until "uio->uio_resid == 0" or an error
1851 * termination. If a signal/timeout occurs, return with a
1852 * short count but without error. Keep sockbuf locked
1853 * against other readers.
1855 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1856 !sosendallatonce(so) && nextrecord == NULL) {
1857 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1859 so->so_rcv.sb_state & SBS_CANTRCVMORE)
1862 * Notify the protocol that some data has been
1863 * drained before blocking.
1865 if (pr->pr_flags & PR_WANTRCVD) {
1866 SOCKBUF_UNLOCK(&so->so_rcv);
1868 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1869 SOCKBUF_LOCK(&so->so_rcv);
1871 SBLASTRECORDCHK(&so->so_rcv);
1872 SBLASTMBUFCHK(&so->so_rcv);
1874 * We could receive some data while was notifying
1875 * the protocol. Skip blocking in this case.
1877 if (so->so_rcv.sb_mb == NULL) {
1878 error = sbwait(&so->so_rcv);
1880 SOCKBUF_UNLOCK(&so->so_rcv);
1884 m = so->so_rcv.sb_mb;
1886 nextrecord = m->m_nextpkt;
1890 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1891 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1893 if ((flags & MSG_PEEK) == 0)
1894 (void) sbdroprecord_locked(&so->so_rcv);
1896 if ((flags & MSG_PEEK) == 0) {
1899 * First part is an inline SB_EMPTY_FIXUP(). Second
1900 * part makes sure sb_lastrecord is up-to-date if
1901 * there is still data in the socket buffer.
1903 so->so_rcv.sb_mb = nextrecord;
1904 if (so->so_rcv.sb_mb == NULL) {
1905 so->so_rcv.sb_mbtail = NULL;
1906 so->so_rcv.sb_lastrecord = NULL;
1907 } else if (nextrecord->m_nextpkt == NULL)
1908 so->so_rcv.sb_lastrecord = nextrecord;
1910 SBLASTRECORDCHK(&so->so_rcv);
1911 SBLASTMBUFCHK(&so->so_rcv);
1913 * If soreceive() is being done from the socket callback,
1914 * then don't need to generate ACK to peer to update window,
1915 * since ACK will be generated on return to TCP.
1917 if (!(flags & MSG_SOCALLBCK) &&
1918 (pr->pr_flags & PR_WANTRCVD)) {
1919 SOCKBUF_UNLOCK(&so->so_rcv);
1921 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1922 SOCKBUF_LOCK(&so->so_rcv);
1925 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1926 if (orig_resid == uio->uio_resid && orig_resid &&
1927 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1928 SOCKBUF_UNLOCK(&so->so_rcv);
1931 SOCKBUF_UNLOCK(&so->so_rcv);
1936 sbunlock(&so->so_rcv);
1941 * Optimized version of soreceive() for stream (TCP) sockets.
1942 * XXXAO: (MSG_WAITALL | MSG_PEEK) isn't properly handled.
1945 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
1946 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1948 int len = 0, error = 0, flags, oresid;
1950 struct mbuf *m, *n = NULL;
1952 /* We only do stream sockets. */
1953 if (so->so_type != SOCK_STREAM)
1957 if (controlp != NULL)
1960 flags = *flagsp &~ MSG_EOR;
1963 if (flags & MSG_OOB)
1964 return (soreceive_rcvoob(so, uio, flags));
1970 /* Prevent other readers from entering the socket. */
1971 error = sblock(sb, SBLOCKWAIT(flags));
1976 /* Easy one, no space to copyout anything. */
1977 if (uio->uio_resid == 0) {
1981 oresid = uio->uio_resid;
1983 /* We will never ever get anything unless we are or were connected. */
1984 if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
1990 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1992 /* Abort if socket has reported problems. */
1994 if (sbavail(sb) > 0)
1996 if (oresid > uio->uio_resid)
1998 error = so->so_error;
1999 if (!(flags & MSG_PEEK))
2004 /* Door is closed. Deliver what is left, if any. */
2005 if (sb->sb_state & SBS_CANTRCVMORE) {
2006 if (sbavail(sb) > 0)
2012 /* Socket buffer is empty and we shall not block. */
2013 if (sbavail(sb) == 0 &&
2014 ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2019 /* Socket buffer got some data that we shall deliver now. */
2020 if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
2021 ((so->so_state & SS_NBIO) ||
2022 (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2023 sbavail(sb) >= sb->sb_lowat ||
2024 sbavail(sb) >= uio->uio_resid ||
2025 sbavail(sb) >= sb->sb_hiwat) ) {
2029 /* On MSG_WAITALL we must wait until all data or error arrives. */
2030 if ((flags & MSG_WAITALL) &&
2031 (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
2035 * Wait and block until (more) data comes in.
2036 * NB: Drops the sockbuf lock during wait.
2044 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2045 KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
2046 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2050 uio->uio_td->td_ru.ru_msgrcv++;
2052 /* Fill uio until full or current end of socket buffer is reached. */
2053 len = min(uio->uio_resid, sbavail(sb));
2055 /* Dequeue as many mbufs as possible. */
2056 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2060 m_cat(*mp0, sb->sb_mb);
2062 m != NULL && m->m_len <= len;
2064 KASSERT(!(m->m_flags & M_NOTAVAIL),
2065 ("%s: m %p not available", __func__, m));
2067 uio->uio_resid -= m->m_len;
2073 sb->sb_lastrecord = sb->sb_mb;
2074 if (sb->sb_mb == NULL)
2077 /* Copy the remainder. */
2079 KASSERT(sb->sb_mb != NULL,
2080 ("%s: len > 0 && sb->sb_mb empty", __func__));
2082 m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
2084 len = 0; /* Don't flush data from sockbuf. */
2086 uio->uio_resid -= len;
2097 /* NB: Must unlock socket buffer as uiomove may sleep. */
2099 error = m_mbuftouio(uio, sb->sb_mb, len);
2104 SBLASTRECORDCHK(sb);
2108 * Remove the delivered data from the socket buffer unless we
2109 * were only peeking.
2111 if (!(flags & MSG_PEEK)) {
2113 sbdrop_locked(sb, len);
2115 /* Notify protocol that we drained some data. */
2116 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2117 (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2118 !(flags & MSG_SOCALLBCK))) {
2121 (*so->so_proto->pr_usrreqs->pru_rcvd)(so, flags);
2127 * For MSG_WAITALL we may have to loop again and wait for
2128 * more data to come in.
2130 if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2133 SOCKBUF_LOCK_ASSERT(sb);
2134 SBLASTRECORDCHK(sb);
2142 * Optimized version of soreceive() for simple datagram cases from userspace.
2143 * Unlike in the stream case, we're able to drop a datagram if copyout()
2144 * fails, and because we handle datagrams atomically, we don't need to use a
2145 * sleep lock to prevent I/O interlacing.
2148 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2149 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2151 struct mbuf *m, *m2;
2154 struct protosw *pr = so->so_proto;
2155 struct mbuf *nextrecord;
2159 if (controlp != NULL)
2162 flags = *flagsp &~ MSG_EOR;
2167 * For any complicated cases, fall back to the full
2168 * soreceive_generic().
2170 if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
2171 return (soreceive_generic(so, psa, uio, mp0, controlp,
2175 * Enforce restrictions on use.
2177 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2178 ("soreceive_dgram: wantrcvd"));
2179 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2180 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2181 ("soreceive_dgram: SBS_RCVATMARK"));
2182 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2183 ("soreceive_dgram: P_CONNREQUIRED"));
2186 * Loop blocking while waiting for a datagram.
2188 SOCKBUF_LOCK(&so->so_rcv);
2189 while ((m = so->so_rcv.sb_mb) == NULL) {
2190 KASSERT(sbavail(&so->so_rcv) == 0,
2191 ("soreceive_dgram: sb_mb NULL but sbavail %u",
2192 sbavail(&so->so_rcv)));
2194 error = so->so_error;
2196 SOCKBUF_UNLOCK(&so->so_rcv);
2199 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2200 uio->uio_resid == 0) {
2201 SOCKBUF_UNLOCK(&so->so_rcv);
2204 if ((so->so_state & SS_NBIO) ||
2205 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2206 SOCKBUF_UNLOCK(&so->so_rcv);
2207 return (EWOULDBLOCK);
2209 SBLASTRECORDCHK(&so->so_rcv);
2210 SBLASTMBUFCHK(&so->so_rcv);
2211 error = sbwait(&so->so_rcv);
2213 SOCKBUF_UNLOCK(&so->so_rcv);
2217 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2220 uio->uio_td->td_ru.ru_msgrcv++;
2221 SBLASTRECORDCHK(&so->so_rcv);
2222 SBLASTMBUFCHK(&so->so_rcv);
2223 nextrecord = m->m_nextpkt;
2224 if (nextrecord == NULL) {
2225 KASSERT(so->so_rcv.sb_lastrecord == m,
2226 ("soreceive_dgram: lastrecord != m"));
2229 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2230 ("soreceive_dgram: m_nextpkt != nextrecord"));
2233 * Pull 'm' and its chain off the front of the packet queue.
2235 so->so_rcv.sb_mb = NULL;
2236 sockbuf_pushsync(&so->so_rcv, nextrecord);
2239 * Walk 'm's chain and free that many bytes from the socket buffer.
2241 for (m2 = m; m2 != NULL; m2 = m2->m_next)
2242 sbfree(&so->so_rcv, m2);
2245 * Do a few last checks before we let go of the lock.
2247 SBLASTRECORDCHK(&so->so_rcv);
2248 SBLASTMBUFCHK(&so->so_rcv);
2249 SOCKBUF_UNLOCK(&so->so_rcv);
2251 if (pr->pr_flags & PR_ADDR) {
2252 KASSERT(m->m_type == MT_SONAME,
2253 ("m->m_type == %d", m->m_type));
2255 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2260 /* XXXRW: Can this happen? */
2265 * Packet to copyout() is now in 'm' and it is disconnected from the
2268 * Process one or more MT_CONTROL mbufs present before any data mbufs
2269 * in the first mbuf chain on the socket buffer. We call into the
2270 * protocol to perform externalization (or freeing if controlp ==
2271 * NULL). In some cases there can be only MT_CONTROL mbufs without
2274 if (m->m_type == MT_CONTROL) {
2275 struct mbuf *cm = NULL, *cmn;
2276 struct mbuf **cme = &cm;
2282 cme = &(*cme)->m_next;
2284 } while (m != NULL && m->m_type == MT_CONTROL);
2285 while (cm != NULL) {
2288 if (pr->pr_domain->dom_externalize != NULL) {
2289 error = (*pr->pr_domain->dom_externalize)
2290 (cm, controlp, flags);
2291 } else if (controlp != NULL)
2295 if (controlp != NULL) {
2296 while (*controlp != NULL)
2297 controlp = &(*controlp)->m_next;
2302 KASSERT(m == NULL || m->m_type == MT_DATA,
2303 ("soreceive_dgram: !data"));
2304 while (m != NULL && uio->uio_resid > 0) {
2305 len = uio->uio_resid;
2308 error = uiomove(mtod(m, char *), (int)len, uio);
2313 if (len == m->m_len)
2330 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2331 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2335 CURVNET_SET(so->so_vnet);
2336 error = (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
2343 soshutdown(struct socket *so, int how)
2345 struct protosw *pr = so->so_proto;
2346 int error, soerror_enotconn;
2348 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2351 soerror_enotconn = 0;
2353 (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
2355 * POSIX mandates us to return ENOTCONN when shutdown(2) is
2356 * invoked on a datagram sockets, however historically we would
2357 * actually tear socket down. This is known to be leveraged by
2358 * some applications to unblock process waiting in recvXXX(2)
2359 * by other process that it shares that socket with. Try to meet
2360 * both backward-compatibility and POSIX requirements by forcing
2361 * ENOTCONN but still asking protocol to perform pru_shutdown().
2363 if (so->so_type != SOCK_DGRAM)
2365 soerror_enotconn = 1;
2368 CURVNET_SET(so->so_vnet);
2369 if (pr->pr_usrreqs->pru_flush != NULL)
2370 (*pr->pr_usrreqs->pru_flush)(so, how);
2373 if (how != SHUT_RD) {
2374 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2375 wakeup(&so->so_timeo);
2377 return ((error == 0 && soerror_enotconn) ? ENOTCONN : error);
2379 wakeup(&so->so_timeo);
2382 return (soerror_enotconn ? ENOTCONN : 0);
2386 sorflush(struct socket *so)
2388 struct sockbuf *sb = &so->so_rcv;
2389 struct protosw *pr = so->so_proto;
2395 * In order to avoid calling dom_dispose with the socket buffer mutex
2396 * held, and in order to generally avoid holding the lock for a long
2397 * time, we make a copy of the socket buffer and clear the original
2398 * (except locks, state). The new socket buffer copy won't have
2399 * initialized locks so we can only call routines that won't use or
2400 * assert those locks.
2402 * Dislodge threads currently blocked in receive and wait to acquire
2403 * a lock against other simultaneous readers before clearing the
2404 * socket buffer. Don't let our acquire be interrupted by a signal
2405 * despite any existing socket disposition on interruptable waiting.
2408 (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2411 * Invalidate/clear most of the sockbuf structure, but leave selinfo
2412 * and mutex data unchanged.
2415 bzero(&aso, sizeof(aso));
2416 aso.so_pcb = so->so_pcb;
2417 bcopy(&sb->sb_startzero, &aso.so_rcv.sb_startzero,
2418 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2419 bzero(&sb->sb_startzero,
2420 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2425 * Dispose of special rights and flush the copied socket. Don't call
2426 * any unsafe routines (that rely on locks being initialized) on aso.
2428 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2429 (*pr->pr_domain->dom_dispose)(&aso);
2430 sbrelease_internal(&aso.so_rcv, so);
2434 * Wrapper for Socket established helper hook.
2435 * Parameters: socket, context of the hook point, hook id.
2438 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
2440 struct socket_hhook_data hhook_data = {
2447 CURVNET_SET(so->so_vnet);
2448 HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
2451 /* Ugly but needed, since hhooks return void for now */
2452 return (hhook_data.status);
2456 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2457 * additional variant to handle the case where the option value needs to be
2458 * some kind of integer, but not a specific size. In addition to their use
2459 * here, these functions are also called by the protocol-level pr_ctloutput()
2463 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2468 * If the user gives us more than we wanted, we ignore it, but if we
2469 * don't get the minimum length the caller wants, we return EINVAL.
2470 * On success, sopt->sopt_valsize is set to however much we actually
2473 if ((valsize = sopt->sopt_valsize) < minlen)
2476 sopt->sopt_valsize = valsize = len;
2478 if (sopt->sopt_td != NULL)
2479 return (copyin(sopt->sopt_val, buf, valsize));
2481 bcopy(sopt->sopt_val, buf, valsize);
2486 * Kernel version of setsockopt(2).
2488 * XXX: optlen is size_t, not socklen_t
2491 so_setsockopt(struct socket *so, int level, int optname, void *optval,
2494 struct sockopt sopt;
2496 sopt.sopt_level = level;
2497 sopt.sopt_name = optname;
2498 sopt.sopt_dir = SOPT_SET;
2499 sopt.sopt_val = optval;
2500 sopt.sopt_valsize = optlen;
2501 sopt.sopt_td = NULL;
2502 return (sosetopt(so, &sopt));
2506 sosetopt(struct socket *so, struct sockopt *sopt)
2517 CURVNET_SET(so->so_vnet);
2519 if (sopt->sopt_level != SOL_SOCKET) {
2520 if (so->so_proto->pr_ctloutput != NULL) {
2521 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2525 error = ENOPROTOOPT;
2527 switch (sopt->sopt_name) {
2528 case SO_ACCEPTFILTER:
2529 error = do_setopt_accept_filter(so, sopt);
2535 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2540 so->so_linger = l.l_linger;
2542 so->so_options |= SO_LINGER;
2544 so->so_options &= ~SO_LINGER;
2551 case SO_USELOOPBACK:
2561 error = sooptcopyin(sopt, &optval, sizeof optval,
2567 so->so_options |= sopt->sopt_name;
2569 so->so_options &= ~sopt->sopt_name;
2574 error = sooptcopyin(sopt, &optval, sizeof optval,
2579 if (optval < 0 || optval >= rt_numfibs) {
2583 if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
2584 (so->so_proto->pr_domain->dom_family == PF_INET6) ||
2585 (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
2586 so->so_fibnum = optval;
2591 case SO_USER_COOKIE:
2592 error = sooptcopyin(sopt, &val32, sizeof val32,
2596 so->so_user_cookie = val32;
2603 error = sooptcopyin(sopt, &optval, sizeof optval,
2609 * Values < 1 make no sense for any of these options,
2617 switch (sopt->sopt_name) {
2620 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2621 &so->so_snd : &so->so_rcv, (u_long)optval,
2622 so, curthread) == 0) {
2626 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
2627 &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
2631 * Make sure the low-water is never greater than the
2635 SOCKBUF_LOCK(&so->so_snd);
2636 so->so_snd.sb_lowat =
2637 (optval > so->so_snd.sb_hiwat) ?
2638 so->so_snd.sb_hiwat : optval;
2639 SOCKBUF_UNLOCK(&so->so_snd);
2642 SOCKBUF_LOCK(&so->so_rcv);
2643 so->so_rcv.sb_lowat =
2644 (optval > so->so_rcv.sb_hiwat) ?
2645 so->so_rcv.sb_hiwat : optval;
2646 SOCKBUF_UNLOCK(&so->so_rcv);
2653 #ifdef COMPAT_FREEBSD32
2654 if (SV_CURPROC_FLAG(SV_ILP32)) {
2655 struct timeval32 tv32;
2657 error = sooptcopyin(sopt, &tv32, sizeof tv32,
2659 CP(tv32, tv, tv_sec);
2660 CP(tv32, tv, tv_usec);
2663 error = sooptcopyin(sopt, &tv, sizeof tv,
2667 if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
2668 tv.tv_usec >= 1000000) {
2672 if (tv.tv_sec > INT32_MAX)
2676 switch (sopt->sopt_name) {
2678 so->so_snd.sb_timeo = val;
2681 so->so_rcv.sb_timeo = val;
2688 error = sooptcopyin(sopt, &extmac, sizeof extmac,
2692 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2700 error = sooptcopyin(sopt, &optval, sizeof optval,
2704 if (optval < 0 || optval > SO_TS_CLOCK_MAX) {
2708 so->so_ts_clock = optval;
2711 case SO_MAX_PACING_RATE:
2712 error = sooptcopyin(sopt, &val32, sizeof(val32),
2716 so->so_max_pacing_rate = val32;
2720 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
2721 error = hhook_run_socket(so, sopt,
2724 error = ENOPROTOOPT;
2727 if (error == 0 && so->so_proto->pr_ctloutput != NULL)
2728 (void)(*so->so_proto->pr_ctloutput)(so, sopt);
2736 * Helper routine for getsockopt.
2739 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2747 * Documented get behavior is that we always return a value, possibly
2748 * truncated to fit in the user's buffer. Traditional behavior is
2749 * that we always tell the user precisely how much we copied, rather
2750 * than something useful like the total amount we had available for
2751 * her. Note that this interface is not idempotent; the entire
2752 * answer must be generated ahead of time.
2754 valsize = min(len, sopt->sopt_valsize);
2755 sopt->sopt_valsize = valsize;
2756 if (sopt->sopt_val != NULL) {
2757 if (sopt->sopt_td != NULL)
2758 error = copyout(buf, sopt->sopt_val, valsize);
2760 bcopy(buf, sopt->sopt_val, valsize);
2766 sogetopt(struct socket *so, struct sockopt *sopt)
2775 CURVNET_SET(so->so_vnet);
2777 if (sopt->sopt_level != SOL_SOCKET) {
2778 if (so->so_proto->pr_ctloutput != NULL)
2779 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2781 error = ENOPROTOOPT;
2785 switch (sopt->sopt_name) {
2786 case SO_ACCEPTFILTER:
2787 error = do_getopt_accept_filter(so, sopt);
2792 l.l_onoff = so->so_options & SO_LINGER;
2793 l.l_linger = so->so_linger;
2795 error = sooptcopyout(sopt, &l, sizeof l);
2798 case SO_USELOOPBACK:
2810 optval = so->so_options & sopt->sopt_name;
2812 error = sooptcopyout(sopt, &optval, sizeof optval);
2816 optval = so->so_type;
2820 optval = so->so_proto->pr_protocol;
2825 optval = so->so_error;
2831 optval = so->so_snd.sb_hiwat;
2835 optval = so->so_rcv.sb_hiwat;
2839 optval = so->so_snd.sb_lowat;
2843 optval = so->so_rcv.sb_lowat;
2848 tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
2849 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2850 #ifdef COMPAT_FREEBSD32
2851 if (SV_CURPROC_FLAG(SV_ILP32)) {
2852 struct timeval32 tv32;
2854 CP(tv, tv32, tv_sec);
2855 CP(tv, tv32, tv_usec);
2856 error = sooptcopyout(sopt, &tv32, sizeof tv32);
2859 error = sooptcopyout(sopt, &tv, sizeof tv);
2864 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2868 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2872 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2880 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2884 error = mac_getsockopt_peerlabel(
2885 sopt->sopt_td->td_ucred, so, &extmac);
2888 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2894 case SO_LISTENQLIMIT:
2895 optval = so->so_qlimit;
2899 optval = so->so_qlen;
2902 case SO_LISTENINCQLEN:
2903 optval = so->so_incqlen;
2907 optval = so->so_ts_clock;
2910 case SO_MAX_PACING_RATE:
2911 optval = so->so_max_pacing_rate;
2915 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
2916 error = hhook_run_socket(so, sopt,
2919 error = ENOPROTOOPT;
2931 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2933 struct mbuf *m, *m_prev;
2934 int sopt_size = sopt->sopt_valsize;
2936 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
2939 if (sopt_size > MLEN) {
2940 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
2941 if ((m->m_flags & M_EXT) == 0) {
2945 m->m_len = min(MCLBYTES, sopt_size);
2947 m->m_len = min(MLEN, sopt_size);
2949 sopt_size -= m->m_len;
2954 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
2959 if (sopt_size > MLEN) {
2960 MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
2962 if ((m->m_flags & M_EXT) == 0) {
2967 m->m_len = min(MCLBYTES, sopt_size);
2969 m->m_len = min(MLEN, sopt_size);
2971 sopt_size -= m->m_len;
2979 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2981 struct mbuf *m0 = m;
2983 if (sopt->sopt_val == NULL)
2985 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2986 if (sopt->sopt_td != NULL) {
2989 error = copyin(sopt->sopt_val, mtod(m, char *),
2996 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2997 sopt->sopt_valsize -= m->m_len;
2998 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3001 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
3002 panic("ip6_sooptmcopyin");
3007 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
3009 struct mbuf *m0 = m;
3012 if (sopt->sopt_val == NULL)
3014 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3015 if (sopt->sopt_td != NULL) {
3018 error = copyout(mtod(m, char *), sopt->sopt_val,
3025 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
3026 sopt->sopt_valsize -= m->m_len;
3027 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3028 valsize += m->m_len;
3032 /* enough soopt buffer should be given from user-land */
3036 sopt->sopt_valsize = valsize;
3041 * sohasoutofband(): protocol notifies socket layer of the arrival of new
3042 * out-of-band data, which will then notify socket consumers.
3045 sohasoutofband(struct socket *so)
3048 if (so->so_sigio != NULL)
3049 pgsigio(&so->so_sigio, SIGURG, 0);
3050 selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
3054 sopoll(struct socket *so, int events, struct ucred *active_cred,
3059 * We do not need to set or assert curvnet as long as everyone uses
3062 return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
3067 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3072 SOCKBUF_LOCK(&so->so_snd);
3073 SOCKBUF_LOCK(&so->so_rcv);
3074 if (events & (POLLIN | POLLRDNORM))
3075 if (soreadabledata(so))
3076 revents |= events & (POLLIN | POLLRDNORM);
3078 if (events & (POLLOUT | POLLWRNORM))
3079 if (sowriteable(so))
3080 revents |= events & (POLLOUT | POLLWRNORM);
3082 if (events & (POLLPRI | POLLRDBAND))
3083 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
3084 revents |= events & (POLLPRI | POLLRDBAND);
3086 if ((events & POLLINIGNEOF) == 0) {
3087 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3088 revents |= events & (POLLIN | POLLRDNORM);
3089 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3095 if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
3096 selrecord(td, &so->so_rcv.sb_sel);
3097 so->so_rcv.sb_flags |= SB_SEL;
3100 if (events & (POLLOUT | POLLWRNORM)) {
3101 selrecord(td, &so->so_snd.sb_sel);
3102 so->so_snd.sb_flags |= SB_SEL;
3106 SOCKBUF_UNLOCK(&so->so_rcv);
3107 SOCKBUF_UNLOCK(&so->so_snd);
3112 soo_kqfilter(struct file *fp, struct knote *kn)
3114 struct socket *so = kn->kn_fp->f_data;
3117 switch (kn->kn_filter) {
3119 kn->kn_fop = &soread_filtops;
3123 kn->kn_fop = &sowrite_filtops;
3127 kn->kn_fop = &soempty_filtops;
3135 knlist_add(&sb->sb_sel.si_note, kn, 1);
3136 sb->sb_flags |= SB_KNOTE;
3142 * Some routines that return EOPNOTSUPP for entry points that are not
3143 * supported by a protocol. Fill in as needed.
3146 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
3153 pru_aio_queue_notsupp(struct socket *so, struct kaiocb *job)
3160 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
3167 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3174 pru_bindat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3182 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3189 pru_connectat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3197 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
3204 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
3205 struct ifnet *ifp, struct thread *td)
3212 pru_disconnect_notsupp(struct socket *so)
3219 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
3226 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
3233 pru_rcvd_notsupp(struct socket *so, int flags)
3240 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
3247 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
3248 struct sockaddr *addr, struct mbuf *control, struct thread *td)
3255 pru_ready_notsupp(struct socket *so, struct mbuf *m, int count)
3258 return (EOPNOTSUPP);
3262 * This isn't really a ``null'' operation, but it's the default one and
3263 * doesn't do anything destructive.
3266 pru_sense_null(struct socket *so, struct stat *sb)
3269 sb->st_blksize = so->so_snd.sb_hiwat;
3274 pru_shutdown_notsupp(struct socket *so)
3281 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
3288 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
3289 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
3296 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
3297 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3304 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
3312 filt_sordetach(struct knote *kn)
3314 struct socket *so = kn->kn_fp->f_data;
3316 SOCKBUF_LOCK(&so->so_rcv);
3317 knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
3318 if (knlist_empty(&so->so_rcv.sb_sel.si_note))
3319 so->so_rcv.sb_flags &= ~SB_KNOTE;
3320 SOCKBUF_UNLOCK(&so->so_rcv);
3325 filt_soread(struct knote *kn, long hint)
3329 so = kn->kn_fp->f_data;
3330 if (so->so_options & SO_ACCEPTCONN) {
3331 kn->kn_data = so->so_qlen;
3332 return (!TAILQ_EMPTY(&so->so_comp));
3335 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3337 kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
3338 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3339 kn->kn_flags |= EV_EOF;
3340 kn->kn_fflags = so->so_error;
3342 } else if (so->so_error) /* temporary udp error */
3345 if (kn->kn_sfflags & NOTE_LOWAT) {
3346 if (kn->kn_data >= kn->kn_sdata)
3348 } else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
3351 /* This hook returning non-zero indicates an event, not error */
3352 return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
3356 filt_sowdetach(struct knote *kn)
3358 struct socket *so = kn->kn_fp->f_data;
3360 SOCKBUF_LOCK(&so->so_snd);
3361 knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
3362 if (knlist_empty(&so->so_snd.sb_sel.si_note))
3363 so->so_snd.sb_flags &= ~SB_KNOTE;
3364 SOCKBUF_UNLOCK(&so->so_snd);
3369 filt_sowrite(struct knote *kn, long hint)
3373 so = kn->kn_fp->f_data;
3374 SOCKBUF_LOCK_ASSERT(&so->so_snd);
3375 kn->kn_data = sbspace(&so->so_snd);
3377 hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
3379 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3380 kn->kn_flags |= EV_EOF;
3381 kn->kn_fflags = so->so_error;
3383 } else if (so->so_error) /* temporary udp error */
3385 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3386 (so->so_proto->pr_flags & PR_CONNREQUIRED))
3388 else if (kn->kn_sfflags & NOTE_LOWAT)
3389 return (kn->kn_data >= kn->kn_sdata);
3391 return (kn->kn_data >= so->so_snd.sb_lowat);
3395 filt_soempty(struct knote *kn, long hint)
3399 so = kn->kn_fp->f_data;
3400 SOCKBUF_LOCK_ASSERT(&so->so_snd);
3401 kn->kn_data = sbused(&so->so_snd);
3403 if (kn->kn_data == 0)
3410 socheckuid(struct socket *so, uid_t uid)
3415 if (so->so_cred->cr_uid != uid)
3421 * These functions are used by protocols to notify the socket layer (and its
3422 * consumers) of state changes in the sockets driven by protocol-side events.
3426 * Procedures to manipulate state flags of socket and do appropriate wakeups.
3428 * Normal sequence from the active (originating) side is that
3429 * soisconnecting() is called during processing of connect() call, resulting
3430 * in an eventual call to soisconnected() if/when the connection is
3431 * established. When the connection is torn down soisdisconnecting() is
3432 * called during processing of disconnect() call, and soisdisconnected() is
3433 * called when the connection to the peer is totally severed. The semantics
3434 * of these routines are such that connectionless protocols can call
3435 * soisconnected() and soisdisconnected() only, bypassing the in-progress
3436 * calls when setting up a ``connection'' takes no time.
3438 * From the passive side, a socket is created with two queues of sockets:
3439 * so_incomp for connections in progress and so_comp for connections already
3440 * made and awaiting user acceptance. As a protocol is preparing incoming
3441 * connections, it creates a socket structure queued on so_incomp by calling
3442 * sonewconn(). When the connection is established, soisconnected() is
3443 * called, and transfers the socket structure to so_comp, making it available
3446 * If a socket is closed with sockets on either so_incomp or so_comp, these
3447 * sockets are dropped.
3449 * If higher-level protocols are implemented in the kernel, the wakeups done
3450 * here will sometimes cause software-interrupt process scheduling.
3453 soisconnecting(struct socket *so)
3457 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3458 so->so_state |= SS_ISCONNECTING;
3463 soisconnected(struct socket *so)
3465 struct socket *head;
3471 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3472 so->so_state |= SS_ISCONNECTED;
3474 if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
3475 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3477 TAILQ_REMOVE(&head->so_incomp, so, so_list);
3479 so->so_qstate &= ~SQ_INCOMP;
3480 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
3482 so->so_qstate |= SQ_COMP;
3485 wakeup_one(&head->so_timeo);
3488 soupcall_set(so, SO_RCV,
3489 head->so_accf->so_accept_filter->accf_callback,
3490 head->so_accf->so_accept_filter_arg);
3491 so->so_options &= ~SO_ACCEPTFILTER;
3492 ret = head->so_accf->so_accept_filter->accf_callback(so,
3493 head->so_accf->so_accept_filter_arg, M_NOWAIT);
3494 if (ret == SU_ISCONNECTED)
3495 soupcall_clear(so, SO_RCV);
3497 if (ret == SU_ISCONNECTED)
3504 wakeup(&so->so_timeo);
3510 soisdisconnecting(struct socket *so)
3514 * Note: This code assumes that SOCK_LOCK(so) and
3515 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3517 SOCKBUF_LOCK(&so->so_rcv);
3518 so->so_state &= ~SS_ISCONNECTING;
3519 so->so_state |= SS_ISDISCONNECTING;
3520 socantrcvmore_locked(so);
3521 SOCKBUF_LOCK(&so->so_snd);
3522 socantsendmore_locked(so);
3523 wakeup(&so->so_timeo);
3527 soisdisconnected(struct socket *so)
3531 * Note: This code assumes that SOCK_LOCK(so) and
3532 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3534 SOCKBUF_LOCK(&so->so_rcv);
3535 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3536 so->so_state |= SS_ISDISCONNECTED;
3537 socantrcvmore_locked(so);
3538 SOCKBUF_LOCK(&so->so_snd);
3539 sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
3540 socantsendmore_locked(so);
3541 wakeup(&so->so_timeo);
3545 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3548 sodupsockaddr(const struct sockaddr *sa, int mflags)
3550 struct sockaddr *sa2;
3552 sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3554 bcopy(sa, sa2, sa->sa_len);
3559 * Register per-socket buffer upcalls.
3562 soupcall_set(struct socket *so, int which,
3563 int (*func)(struct socket *, void *, int), void *arg)
3575 panic("soupcall_set: bad which");
3577 SOCKBUF_LOCK_ASSERT(sb);
3579 /* XXX: accf_http actually wants to do this on purpose. */
3580 KASSERT(sb->sb_upcall == NULL, ("soupcall_set: overwriting upcall"));
3582 sb->sb_upcall = func;
3583 sb->sb_upcallarg = arg;
3584 sb->sb_flags |= SB_UPCALL;
3588 soupcall_clear(struct socket *so, int which)
3600 panic("soupcall_clear: bad which");
3602 SOCKBUF_LOCK_ASSERT(sb);
3603 KASSERT(sb->sb_upcall != NULL, ("soupcall_clear: no upcall to clear"));
3604 sb->sb_upcall = NULL;
3605 sb->sb_upcallarg = NULL;
3606 sb->sb_flags &= ~SB_UPCALL;
3610 * Create an external-format (``xsocket'') structure using the information in
3611 * the kernel-format socket structure pointed to by so. This is done to
3612 * reduce the spew of irrelevant information over this interface, to isolate
3613 * user code from changes in the kernel structure, and potentially to provide
3614 * information-hiding if we decide that some of this information should be
3615 * hidden from users.
3618 sotoxsocket(struct socket *so, struct xsocket *xso)
3621 xso->xso_len = sizeof *xso;
3623 xso->so_type = so->so_type;
3624 xso->so_options = so->so_options;
3625 xso->so_linger = so->so_linger;
3626 xso->so_state = so->so_state;
3627 xso->so_pcb = so->so_pcb;
3628 xso->xso_protocol = so->so_proto->pr_protocol;
3629 xso->xso_family = so->so_proto->pr_domain->dom_family;
3630 xso->so_qlen = so->so_qlen;
3631 xso->so_incqlen = so->so_incqlen;
3632 xso->so_qlimit = so->so_qlimit;
3633 xso->so_timeo = so->so_timeo;
3634 xso->so_error = so->so_error;
3635 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
3636 xso->so_oobmark = so->so_oobmark;
3637 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
3638 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
3639 xso->so_uid = so->so_cred->cr_uid;
3644 * Socket accessor functions to provide external consumers with
3645 * a safe interface to socket state
3650 so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *),
3654 TAILQ_FOREACH(so, &so->so_comp, so_list)
3659 so_sockbuf_rcv(struct socket *so)
3662 return (&so->so_rcv);
3666 so_sockbuf_snd(struct socket *so)
3669 return (&so->so_snd);
3673 so_state_get(const struct socket *so)
3676 return (so->so_state);
3680 so_state_set(struct socket *so, int val)
3687 so_options_get(const struct socket *so)
3690 return (so->so_options);
3694 so_options_set(struct socket *so, int val)
3697 so->so_options = val;
3701 so_error_get(const struct socket *so)
3704 return (so->so_error);
3708 so_error_set(struct socket *so, int val)
3715 so_linger_get(const struct socket *so)
3718 return (so->so_linger);
3722 so_linger_set(struct socket *so, int val)
3725 so->so_linger = val;
3729 so_protosw_get(const struct socket *so)
3732 return (so->so_proto);
3736 so_protosw_set(struct socket *so, struct protosw *val)
3743 so_sorwakeup(struct socket *so)
3750 so_sowwakeup(struct socket *so)
3757 so_sorwakeup_locked(struct socket *so)
3760 sorwakeup_locked(so);
3764 so_sowwakeup_locked(struct socket *so)
3767 sowwakeup_locked(so);
3771 so_lock(struct socket *so)
3778 so_unlock(struct socket *so)