[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/uipc_socket.c

Version: -  FREEBSD  -  FREEBSD8  -  FREEBSD7  -  FREEBSD72  -  FREEBSD71  -  FREEBSD70  -  FREEBSD6  -  FREEBSD64  -  FREEBSD63  -  FREEBSD62  -  FREEBSD61  -  FREEBSD60  -  FREEBSD5  -  FREEBSD55  -  FREEBSD54  -  FREEBSD53  -  FREEBSD52  -  FREEBSD51  -  FREEBSD50  -  FREEBSD4  -  FREEBSD3  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  OPENSOLARIS  -  minix-3-1-1  -  FREEBSD-LIBC  -  FREEBSD7-LIBC  -  FREEBSD6-LIBC  -  GLIBC27 
SearchContext: -  none  -  excerpts  -  bigexcerpts 

    1 /*-
    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
    6  * All rights reserved.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following conditions
   10  * are met:
   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  * 4. 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.
   19  *
   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
   30  * SUCH DAMAGE.
   31  *
   32  *      @(#)uipc_socket.c       8.3 (Berkeley) 4/15/94
   33  */
   34 
   35 /*
   36  * Comments on the socket life cycle:
   37  *
   38  * soalloc() sets of socket layer state for a socket, called only by
   39  * socreate() and sonewconn().  Socket layer private.
   40  *
   41  * sodealloc() tears down socket layer state for a socket, called only by
   42  * sofree() and sonewconn().  Socket layer private.
   43  *
   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.
   47  *
   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.
   52  *
   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
   57  * case.
   58  *
   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
   61  * sockets.
   62  *
   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
   66  * listen socket.
   67  *
   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.
   71  *
   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.
   82  *
   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
   86  * interface.
   87  *
   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.
   95  */
   96 
   97 #include <sys/cdefs.h>
   98 __FBSDID("$FreeBSD$");
   99 
  100 #include "opt_inet.h"
  101 #include "opt_inet6.h"
  102 #include "opt_mac.h"
  103 #include "opt_zero.h"
  104 #include "opt_compat.h"
  105 
  106 #include <sys/param.h>
  107 #include <sys/systm.h>
  108 #include <sys/fcntl.h>
  109 #include <sys/limits.h>
  110 #include <sys/lock.h>
  111 #include <sys/mac.h>
  112 #include <sys/malloc.h>
  113 #include <sys/mbuf.h>
  114 #include <sys/mutex.h>
  115 #include <sys/domain.h>
  116 #include <sys/file.h>                   /* for struct knote */
  117 #include <sys/kernel.h>
  118 #include <sys/event.h>
  119 #include <sys/eventhandler.h>
  120 #include <sys/poll.h>
  121 #include <sys/proc.h>
  122 #include <sys/protosw.h>
  123 #include <sys/socket.h>
  124 #include <sys/socketvar.h>
  125 #include <sys/resourcevar.h>
  126 #include <net/route.h>
  127 #include <sys/signalvar.h>
  128 #include <sys/stat.h>
  129 #include <sys/sx.h>
  130 #include <sys/sysctl.h>
  131 #include <sys/uio.h>
  132 #include <sys/jail.h>
  133 
  134 #include <security/mac/mac_framework.h>
  135 
  136 #include <vm/uma.h>
  137 
  138 #ifdef COMPAT_IA32
  139 #include <sys/mount.h>
  140 #include <compat/freebsd32/freebsd32.h>
  141 
  142 extern struct sysentvec ia32_freebsd_sysvec;
  143 #endif
  144 
  145 static int      soreceive_rcvoob(struct socket *so, struct uio *uio,
  146                     int flags);
  147 
  148 static void     filt_sordetach(struct knote *kn);
  149 static int      filt_soread(struct knote *kn, long hint);
  150 static void     filt_sowdetach(struct knote *kn);
  151 static int      filt_sowrite(struct knote *kn, long hint);
  152 static int      filt_solisten(struct knote *kn, long hint);
  153 
  154 static struct filterops solisten_filtops =
  155         { 1, NULL, filt_sordetach, filt_solisten };
  156 static struct filterops soread_filtops =
  157         { 1, NULL, filt_sordetach, filt_soread };
  158 static struct filterops sowrite_filtops =
  159         { 1, NULL, filt_sowdetach, filt_sowrite };
  160 
  161 uma_zone_t socket_zone;
  162 so_gen_t        so_gencnt;      /* generation count for sockets */
  163 
  164 int     maxsockets;
  165 
  166 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
  167 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
  168 
  169 static int somaxconn = SOMAXCONN;
  170 static int sysctl_somaxconn(SYSCTL_HANDLER_ARGS);
  171 /* XXX: we dont have SYSCTL_USHORT */
  172 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
  173     0, sizeof(int), sysctl_somaxconn, "I", "Maximum pending socket connection "
  174     "queue size");
  175 static int numopensockets;
  176 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
  177     &numopensockets, 0, "Number of open sockets");
  178 #ifdef ZERO_COPY_SOCKETS
  179 /* These aren't static because they're used in other files. */
  180 int so_zero_copy_send = 1;
  181 int so_zero_copy_receive = 1;
  182 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
  183     "Zero copy controls");
  184 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
  185     &so_zero_copy_receive, 0, "Enable zero copy receive");
  186 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
  187     &so_zero_copy_send, 0, "Enable zero copy send");
  188 #endif /* ZERO_COPY_SOCKETS */
  189 
  190 /*
  191  * accept_mtx locks down per-socket fields relating to accept queues.  See
  192  * socketvar.h for an annotation of the protected fields of struct socket.
  193  */
  194 struct mtx accept_mtx;
  195 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
  196 
  197 /*
  198  * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
  199  * so_gencnt field.
  200  */
  201 static struct mtx so_global_mtx;
  202 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
  203 
  204 /*
  205  * General IPC sysctl name space, used by sockets and a variety of other IPC
  206  * types.
  207  */
  208 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
  209 
  210 /*
  211  * Sysctl to get and set the maximum global sockets limit.  Notify protocols
  212  * of the change so that they can update their dependent limits as required.
  213  */
  214 static int
  215 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
  216 {
  217         int error, newmaxsockets;
  218 
  219         newmaxsockets = maxsockets;
  220         error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
  221         if (error == 0 && req->newptr) {
  222                 if (newmaxsockets > maxsockets) {
  223                         maxsockets = newmaxsockets;
  224                         if (maxsockets > ((maxfiles / 4) * 3)) {
  225                                 maxfiles = (maxsockets * 5) / 4;
  226                                 maxfilesperproc = (maxfiles * 9) / 10;
  227                         }
  228                         EVENTHANDLER_INVOKE(maxsockets_change);
  229                 } else
  230                         error = EINVAL;
  231         }
  232         return (error);
  233 }
  234 
  235 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
  236     &maxsockets, 0, sysctl_maxsockets, "IU",
  237     "Maximum number of sockets avaliable");
  238 
  239 /*
  240  * Initialise maxsockets.  This SYSINIT must be run after
  241  * tunable_mbinit().
  242  */
  243 static void
  244 init_maxsockets(void *ignored)
  245 {
  246 
  247         TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
  248         maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
  249 }
  250 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
  251 
  252 /*
  253  * Socket operation routines.  These routines are called by the routines in
  254  * sys_socket.c or from a system process, and implement the semantics of
  255  * socket operations by switching out to the protocol specific routines.
  256  */
  257 
  258 /*
  259  * Get a socket structure from our zone, and initialize it.  Note that it
  260  * would probably be better to allocate socket and PCB at the same time, but
  261  * I'm not convinced that all the protocols can be easily modified to do
  262  * this.
  263  *
  264  * soalloc() returns a socket with a ref count of 0.
  265  */
  266 static struct socket *
  267 soalloc(void)
  268 {
  269         struct socket *so;
  270 
  271         so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
  272         if (so == NULL)
  273                 return (NULL);
  274 #ifdef MAC
  275         if (mac_init_socket(so, M_NOWAIT) != 0) {
  276                 uma_zfree(socket_zone, so);
  277                 return (NULL);
  278         }
  279 #endif
  280         SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
  281         SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
  282         sx_init(&so->so_snd.sb_sx, "so_snd_sx");
  283         sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
  284         TAILQ_INIT(&so->so_aiojobq);
  285         mtx_lock(&so_global_mtx);
  286         so->so_gencnt = ++so_gencnt;
  287         ++numopensockets;
  288         mtx_unlock(&so_global_mtx);
  289         return (so);
  290 }
  291 
  292 /*
  293  * Free the storage associated with a socket at the socket layer, tear down
  294  * locks, labels, etc.  All protocol state is assumed already to have been
  295  * torn down (and possibly never set up) by the caller.
  296  */
  297 static void
  298 sodealloc(struct socket *so)
  299 {
  300 
  301         KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
  302         KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
  303 
  304         mtx_lock(&so_global_mtx);
  305         so->so_gencnt = ++so_gencnt;
  306         --numopensockets;       /* Could be below, but faster here. */
  307         mtx_unlock(&so_global_mtx);
  308         if (so->so_rcv.sb_hiwat)
  309                 (void)chgsbsize(so->so_cred->cr_uidinfo,
  310                     &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
  311         if (so->so_snd.sb_hiwat)
  312                 (void)chgsbsize(so->so_cred->cr_uidinfo,
  313                     &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
  314 #ifdef INET
  315         /* remove acccept filter if one is present. */
  316         if (so->so_accf != NULL)
  317                 do_setopt_accept_filter(so, NULL);
  318 #endif
  319 #ifdef MAC
  320         mac_destroy_socket(so);
  321 #endif
  322         crfree(so->so_cred);
  323         sx_destroy(&so->so_snd.sb_sx);
  324         sx_destroy(&so->so_rcv.sb_sx);
  325         SOCKBUF_LOCK_DESTROY(&so->so_snd);
  326         SOCKBUF_LOCK_DESTROY(&so->so_rcv);
  327         uma_zfree(socket_zone, so);
  328 }
  329 
  330 /*
  331  * socreate returns a socket with a ref count of 1.  The socket should be
  332  * closed with soclose().
  333  */
  334 int
  335 socreate(int dom, struct socket **aso, int type, int proto,
  336     struct ucred *cred, struct thread *td)
  337 {
  338         struct protosw *prp;
  339         struct socket *so;
  340         int error;
  341 
  342         if (proto)
  343                 prp = pffindproto(dom, proto, type);
  344         else
  345                 prp = pffindtype(dom, type);
  346 
  347         if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
  348             prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
  349                 return (EPROTONOSUPPORT);
  350 
  351         if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
  352                 return (EPROTONOSUPPORT);
  353 
  354         if (prp->pr_type != type)
  355                 return (EPROTOTYPE);
  356         so = soalloc();
  357         if (so == NULL)
  358                 return (ENOBUFS);
  359 
  360         TAILQ_INIT(&so->so_incomp);
  361         TAILQ_INIT(&so->so_comp);
  362         so->so_type = type;
  363         so->so_cred = crhold(cred);
  364         if ((prp->pr_domain->dom_family == PF_INET) ||
  365             (prp->pr_domain->dom_family == PF_ROUTE))
  366                 so->so_fibnum = td->td_proc->p_fibnum;
  367         else
  368                 so->so_fibnum = 0;
  369         so->so_proto = prp;
  370 #ifdef MAC
  371         mac_create_socket(cred, so);
  372 #endif
  373         knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
  374             NULL, NULL, NULL);
  375         knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
  376             NULL, NULL, NULL);
  377         so->so_count = 1;
  378         /*
  379          * Auto-sizing of socket buffers is managed by the protocols and
  380          * the appropriate flags must be set in the pru_attach function.
  381          */
  382         error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
  383         if (error) {
  384                 KASSERT(so->so_count == 1, ("socreate: so_count %d",
  385                     so->so_count));
  386                 so->so_count = 0;
  387                 sodealloc(so);
  388                 return (error);
  389         }
  390         *aso = so;
  391         return (0);
  392 }
  393 
  394 #ifdef REGRESSION
  395 static int regression_sonewconn_earlytest = 1;
  396 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
  397     &regression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
  398 #endif
  399 
  400 /*
  401  * When an attempt at a new connection is noted on a socket which accepts
  402  * connections, sonewconn is called.  If the connection is possible (subject
  403  * to space constraints, etc.) then we allocate a new structure, propoerly
  404  * linked into the data structure of the original socket, and return this.
  405  * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
  406  *
  407  * Note: the ref count on the socket is 0 on return.
  408  */
  409 struct socket *
  410 sonewconn(struct socket *head, int connstatus)
  411 {
  412         struct socket *so;
  413         int over;
  414 
  415         ACCEPT_LOCK();
  416         over = (head->so_qlen > 3 * head->so_qlimit / 2);
  417         ACCEPT_UNLOCK();
  418 #ifdef REGRESSION
  419         if (regression_sonewconn_earlytest && over)
  420 #else
  421         if (over)
  422 #endif
  423                 return (NULL);
  424         so = soalloc();
  425         if (so == NULL)
  426                 return (NULL);
  427         if ((head->so_options & SO_ACCEPTFILTER) != 0)
  428                 connstatus = 0;
  429         so->so_head = head;
  430         so->so_type = head->so_type;
  431         so->so_options = head->so_options &~ SO_ACCEPTCONN;
  432         so->so_linger = head->so_linger;
  433         so->so_state = head->so_state | SS_NOFDREF;
  434         so->so_fibnum = head->so_fibnum;
  435         so->so_proto = head->so_proto;
  436         so->so_cred = crhold(head->so_cred);
  437 #ifdef MAC
  438         SOCK_LOCK(head);
  439         mac_create_socket_from_socket(head, so);
  440         SOCK_UNLOCK(head);
  441 #endif
  442         knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
  443             NULL, NULL, NULL);
  444         knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
  445             NULL, NULL, NULL);
  446         if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
  447             (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
  448                 sodealloc(so);
  449                 return (NULL);
  450         }
  451         so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
  452         so->so_snd.sb_lowat = head->so_snd.sb_lowat;
  453         so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
  454         so->so_snd.sb_timeo = head->so_snd.sb_timeo;
  455         so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
  456         so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
  457         so->so_state |= connstatus;
  458         ACCEPT_LOCK();
  459         if (connstatus) {
  460                 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
  461                 so->so_qstate |= SQ_COMP;
  462                 head->so_qlen++;
  463         } else {
  464                 /*
  465                  * Keep removing sockets from the head until there's room for
  466                  * us to insert on the tail.  In pre-locking revisions, this
  467                  * was a simple if(), but as we could be racing with other
  468                  * threads and soabort() requires dropping locks, we must
  469                  * loop waiting for the condition to be true.
  470                  */
  471                 while (head->so_incqlen > head->so_qlimit) {
  472                         struct socket *sp;
  473                         sp = TAILQ_FIRST(&head->so_incomp);
  474                         TAILQ_REMOVE(&head->so_incomp, sp, so_list);
  475                         head->so_incqlen--;
  476                         sp->so_qstate &= ~SQ_INCOMP;
  477                         sp->so_head = NULL;
  478                         ACCEPT_UNLOCK();
  479                         soabort(sp);
  480                         ACCEPT_LOCK();
  481                 }
  482                 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
  483                 so->so_qstate |= SQ_INCOMP;
  484                 head->so_incqlen++;
  485         }
  486         ACCEPT_UNLOCK();
  487         if (connstatus) {
  488                 sorwakeup(head);
  489                 wakeup_one(&head->so_timeo);
  490         }
  491         return (so);
  492 }
  493 
  494 int
  495 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
  496 {
  497 
  498         return ((*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td));
  499 }
  500 
  501 /*
  502  * solisten() transitions a socket from a non-listening state to a listening
  503  * state, but can also be used to update the listen queue depth on an
  504  * existing listen socket.  The protocol will call back into the sockets
  505  * layer using solisten_proto_check() and solisten_proto() to check and set
  506  * socket-layer listen state.  Call backs are used so that the protocol can
  507  * acquire both protocol and socket layer locks in whatever order is required
  508  * by the protocol.
  509  *
  510  * Protocol implementors are advised to hold the socket lock across the
  511  * socket-layer test and set to avoid races at the socket layer.
  512  */
  513 int
  514 solisten(struct socket *so, int backlog, struct thread *td)
  515 {
  516 
  517         return ((*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td));
  518 }
  519 
  520 int
  521 solisten_proto_check(struct socket *so)
  522 {
  523 
  524         SOCK_LOCK_ASSERT(so);
  525 
  526         if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
  527             SS_ISDISCONNECTING))
  528                 return (EINVAL);
  529         return (0);
  530 }
  531 
  532 void
  533 solisten_proto(struct socket *so, int backlog)
  534 {
  535 
  536         SOCK_LOCK_ASSERT(so);
  537 
  538         if (backlog < 0 || backlog > somaxconn)
  539                 backlog = somaxconn;
  540         so->so_qlimit = backlog;
  541         so->so_options |= SO_ACCEPTCONN;
  542 }
  543 
  544 /*
  545  * Attempt to free a socket.  This should really be sotryfree().
  546  *
  547  * sofree() will succeed if:
  548  *
  549  * - There are no outstanding file descriptor references or related consumers
  550  *   (so_count == 0).
  551  *
  552  * - The socket has been closed by user space, if ever open (SS_NOFDREF).
  553  *
  554  * - The protocol does not have an outstanding strong reference on the socket
  555  *   (SS_PROTOREF).
  556  *
  557  * - The socket is not in a completed connection queue, so a process has been
  558  *   notified that it is present.  If it is removed, the user process may
  559  *   block in accept() despite select() saying the socket was ready.
  560  *
  561  * Otherwise, it will quietly abort so that a future call to sofree(), when
  562  * conditions are right, can succeed.
  563  */
  564 void
  565 sofree(struct socket *so)
  566 {
  567         struct protosw *pr = so->so_proto;
  568         struct socket *head;
  569 
  570         ACCEPT_LOCK_ASSERT();
  571         SOCK_LOCK_ASSERT(so);
  572 
  573         if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
  574             (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
  575                 SOCK_UNLOCK(so);
  576                 ACCEPT_UNLOCK();
  577                 return;
  578         }
  579 
  580         head = so->so_head;
  581         if (head != NULL) {
  582                 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
  583                     (so->so_qstate & SQ_INCOMP) != 0,
  584                     ("sofree: so_head != NULL, but neither SQ_COMP nor "
  585                     "SQ_INCOMP"));
  586                 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
  587                     (so->so_qstate & SQ_INCOMP) == 0,
  588                     ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
  589                 TAILQ_REMOVE(&head->so_incomp, so, so_list);
  590                 head->so_incqlen--;
  591                 so->so_qstate &= ~SQ_INCOMP;
  592                 so->so_head = NULL;
  593         }
  594         KASSERT((so->so_qstate & SQ_COMP) == 0 &&
  595             (so->so_qstate & SQ_INCOMP) == 0,
  596             ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
  597             so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
  598         if (so->so_options & SO_ACCEPTCONN) {
  599                 KASSERT((TAILQ_EMPTY(&so->so_comp)), ("sofree: so_comp populated"));
  600                 KASSERT((TAILQ_EMPTY(&so->so_incomp)), ("sofree: so_comp populated"));
  601         }
  602         SOCK_UNLOCK(so);
  603         ACCEPT_UNLOCK();
  604 
  605         if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
  606                 (*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
  607         if (pr->pr_usrreqs->pru_detach != NULL)
  608                 (*pr->pr_usrreqs->pru_detach)(so);
  609 
  610         /*
  611          * From this point on, we assume that no other references to this
  612          * socket exist anywhere else in the stack.  Therefore, no locks need
  613          * to be acquired or held.
  614          *
  615          * We used to do a lot of socket buffer and socket locking here, as
  616          * well as invoke sorflush() and perform wakeups.  The direct call to
  617          * dom_dispose() and sbrelease_internal() are an inlining of what was
  618          * necessary from sorflush().
  619          *
  620          * Notice that the socket buffer and kqueue state are torn down
  621          * before calling pru_detach.  This means that protocols shold not
  622          * assume they can perform socket wakeups, etc, in their detach code.
  623          */
  624         sbdestroy(&so->so_snd, so);
  625         sbdestroy(&so->so_rcv, so);
  626         knlist_destroy(&so->so_rcv.sb_sel.si_note);
  627         knlist_destroy(&so->so_snd.sb_sel.si_note);
  628         sodealloc(so);
  629 }
  630 
  631 /*
  632  * Close a socket on last file table reference removal.  Initiate disconnect
  633  * if connected.  Free socket when disconnect complete.
  634  *
  635  * This function will sorele() the socket.  Note that soclose() may be called
  636  * prior to the ref count reaching zero.  The actual socket structure will
  637  * not be freed until the ref count reaches zero.
  638  */
  639 int
  640 soclose(struct socket *so)
  641 {
  642         int error = 0;
  643 
  644         KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
  645 
  646         funsetown(&so->so_sigio);
  647         if (so->so_state & SS_ISCONNECTED) {
  648                 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
  649                         error = sodisconnect(so);
  650                         if (error)
  651                                 goto drop;
  652                 }
  653                 if (so->so_options & SO_LINGER) {
  654                         if ((so->so_state & SS_ISDISCONNECTING) &&
  655                             (so->so_state & SS_NBIO))
  656                                 goto drop;
  657                         while (so->so_state & SS_ISCONNECTED) {
  658                                 error = tsleep(&so->so_timeo,
  659                                     PSOCK | PCATCH, "soclos", so->so_linger * hz);
  660                                 if (error)
  661                                         break;
  662                         }
  663                 }
  664         }
  665 
  666 drop:
  667         if (so->so_proto->pr_usrreqs->pru_close != NULL)
  668                 (*so->so_proto->pr_usrreqs->pru_close)(so);
  669         if (so->so_options & SO_ACCEPTCONN) {
  670                 struct socket *sp;
  671                 ACCEPT_LOCK();
  672                 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
  673                         TAILQ_REMOVE(&so->so_incomp, sp, so_list);
  674                         so->so_incqlen--;
  675                         sp->so_qstate &= ~SQ_INCOMP;
  676                         sp->so_head = NULL;
  677                         ACCEPT_UNLOCK();
  678                         soabort(sp);
  679                         ACCEPT_LOCK();
  680                 }
  681                 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
  682                         TAILQ_REMOVE(&so->so_comp, sp, so_list);
  683                         so->so_qlen--;
  684                         sp->so_qstate &= ~SQ_COMP;
  685                         sp->so_head = NULL;
  686                         ACCEPT_UNLOCK();
  687                         soabort(sp);
  688                         ACCEPT_LOCK();
  689                 }
  690                 ACCEPT_UNLOCK();
  691         }
  692         ACCEPT_LOCK();
  693         SOCK_LOCK(so);
  694         KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
  695         so->so_state |= SS_NOFDREF;
  696         sorele(so);
  697         return (error);
  698 }
  699 
  700 /*
  701  * soabort() is used to abruptly tear down a connection, such as when a
  702  * resource limit is reached (listen queue depth exceeded), or if a listen
  703  * socket is closed while there are sockets waiting to be accepted.
  704  *
  705  * This interface is tricky, because it is called on an unreferenced socket,
  706  * and must be called only by a thread that has actually removed the socket
  707  * from the listen queue it was on, or races with other threads are risked.
  708  *
  709  * This interface will call into the protocol code, so must not be called
  710  * with any socket locks held.  Protocols do call it while holding their own
  711  * recursible protocol mutexes, but this is something that should be subject
  712  * to review in the future.
  713  */
  714 void
  715 soabort(struct socket *so)
  716 {
  717 
  718         /*
  719          * In as much as is possible, assert that no references to this
  720          * socket are held.  This is not quite the same as asserting that the
  721          * current thread is responsible for arranging for no references, but
  722          * is as close as we can get for now.
  723          */
  724         KASSERT(so->so_count == 0, ("soabort: so_count"));
  725         KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
  726         KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
  727         KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
  728         KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
  729 
  730         if (so->so_proto->pr_usrreqs->pru_abort != NULL)
  731                 (*so->so_proto->pr_usrreqs->pru_abort)(so);
  732         ACCEPT_LOCK();
  733         SOCK_LOCK(so);
  734         sofree(so);
  735 }
  736 
  737 int
  738 soaccept(struct socket *so, struct sockaddr **nam)
  739 {
  740         int error;
  741 
  742         SOCK_LOCK(so);
  743         KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
  744         so->so_state &= ~SS_NOFDREF;
  745         SOCK_UNLOCK(so);
  746         error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
  747         return (error);
  748 }
  749 
  750 int
  751 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
  752 {
  753         int error;
  754 
  755         if (so->so_options & SO_ACCEPTCONN)
  756                 return (EOPNOTSUPP);
  757         /*
  758          * If protocol is connection-based, can only connect once.
  759          * Otherwise, if connected, try to disconnect first.  This allows
  760          * user to disconnect by connecting to, e.g., a null address.
  761          */
  762         if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
  763             ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
  764             (error = sodisconnect(so)))) {
  765                 error = EISCONN;
  766         } else {
  767                 /*
  768                  * Prevent accumulated error from previous connection from
  769                  * biting us.
  770                  */
  771                 so->so_error = 0;
  772                 error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
  773         }
  774 
  775         return (error);
  776 }
  777 
  778 int
  779 soconnect2(struct socket *so1, struct socket *so2)
  780 {
  781 
  782         return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
  783 }
  784 
  785 int
  786 sodisconnect(struct socket *so)
  787 {
  788         int error;
  789 
  790         if ((so->so_state & SS_ISCONNECTED) == 0)
  791                 return (ENOTCONN);
  792         if (so->so_state & SS_ISDISCONNECTING)
  793                 return (EALREADY);
  794         error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
  795         return (error);
  796 }
  797 
  798 #ifdef ZERO_COPY_SOCKETS
  799 struct so_zerocopy_stats{
  800         int size_ok;
  801         int align_ok;
  802         int found_ifp;
  803 };
  804 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
  805 #include <netinet/in.h>
  806 #include <net/route.h>
  807 #include <netinet/in_pcb.h>
  808 #include <vm/vm.h>
  809 #include <vm/vm_page.h>
  810 #include <vm/vm_object.h>
  811 
  812 /*
  813  * sosend_copyin() is only used if zero copy sockets are enabled.  Otherwise
  814  * sosend_dgram() and sosend_generic() use m_uiotombuf().
  815  * 
  816  * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
  817  * all of the data referenced by the uio.  If desired, it uses zero-copy.
  818  * *space will be updated to reflect data copied in.
  819  *
  820  * NB: If atomic I/O is requested, the caller must already have checked that
  821  * space can hold resid bytes.
  822  *
  823  * NB: In the event of an error, the caller may need to free the partial
  824  * chain pointed to by *mpp.  The contents of both *uio and *space may be
  825  * modified even in the case of an error.
  826  */
  827 static int
  828 sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
  829     int flags)
  830 {
  831         struct mbuf *m, **mp, *top;
  832         long len, resid;
  833         int error;
  834 #ifdef ZERO_COPY_SOCKETS
  835         int cow_send;
  836 #endif
  837 
  838         *retmp = top = NULL;
  839         mp = &top;
  840         len = 0;
  841         resid = uio->uio_resid;
  842         error = 0;
  843         do {
  844 #ifdef ZERO_COPY_SOCKETS
  845                 cow_send = 0;
  846 #endif /* ZERO_COPY_SOCKETS */
  847                 if (resid >= MINCLSIZE) {
  848 #ifdef ZERO_COPY_SOCKETS
  849                         if (top == NULL) {
  850                                 m = m_gethdr(M_WAITOK, MT_DATA);
  851                                 m->m_pkthdr.len = 0;
  852                                 m->m_pkthdr.rcvif = NULL;
  853                         } else
  854                                 m = m_get(M_WAITOK, MT_DATA);
  855                         if (so_zero_copy_send &&
  856                             resid>=PAGE_SIZE &&
  857                             *space>=PAGE_SIZE &&
  858                             uio->uio_iov->iov_len>=PAGE_SIZE) {
  859                                 so_zerocp_stats.size_ok++;
  860                                 so_zerocp_stats.align_ok++;
  861                                 cow_send = socow_setup(m, uio);
  862                                 len = cow_send;
  863                         }
  864                         if (!cow_send) {
  865                                 m_clget(m, M_WAITOK);
  866                                 len = min(min(MCLBYTES, resid), *space);
  867                         }
  868 #else /* ZERO_COPY_SOCKETS */
  869                         if (top == NULL) {
  870                                 m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
  871                                 m->m_pkthdr.len = 0;
  872                                 m->m_pkthdr.rcvif = NULL;
  873                         } else
  874                                 m = m_getcl(M_TRYWAIT, MT_DATA, 0);
  875                         len = min(min(MCLBYTES, resid), *space);
  876 #endif /* ZERO_COPY_SOCKETS */
  877                 } else {
  878                         if (top == NULL) {
  879                                 m = m_gethdr(M_TRYWAIT, MT_DATA);
  880                                 m->m_pkthdr.len = 0;
  881                                 m->m_pkthdr.rcvif = NULL;
  882 
  883                                 len = min(min(MHLEN, resid), *space);
  884                                 /*
  885                                  * For datagram protocols, leave room
  886                                  * for protocol headers in first mbuf.
  887                                  */
  888                                 if (atomic && m && len < MHLEN)
  889                                         MH_ALIGN(m, len);
  890                         } else {
  891                                 m = m_get(M_TRYWAIT, MT_DATA);
  892                                 len = min(min(MLEN, resid), *space);
  893                         }
  894                 }
  895                 if (m == NULL) {
  896                         error = ENOBUFS;
  897                         goto out;
  898                 }
  899 
  900                 *space -= len;
  901 #ifdef ZERO_COPY_SOCKETS
  902                 if (cow_send)
  903                         error = 0;
  904                 else
  905 #endif /* ZERO_COPY_SOCKETS */
  906                 error = uiomove(mtod(m, void *), (int)len, uio);
  907                 resid = uio->uio_resid;
  908                 m->m_len = len;
  909                 *mp = m;
  910                 top->m_pkthdr.len += len;
  911                 if (error)
  912                         goto out;
  913                 mp = &m->m_next;
  914                 if (resid <= 0) {
  915                         if (flags & MSG_EOR)
  916                                 top->m_flags |= M_EOR;
  917                         break;
  918                 }
  919         } while (*space > 0 && atomic);
  920 out:
  921         *retmp = top;
  922         return (error);
  923 }
  924 #endif /*ZERO_COPY_SOCKETS*/
  925 
  926 #define SBLOCKWAIT(f)   (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
  927 
  928 int
  929 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
  930     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
  931 {
  932         long space, resid;
  933         int clen = 0, error, dontroute;
  934 #ifdef ZERO_COPY_SOCKETS
  935         int atomic = sosendallatonce(so) || top;
  936 #endif
  937 
  938         KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
  939         KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
  940             ("sodgram_send: !PR_ATOMIC"));
  941 
  942         if (uio != NULL)
  943                 resid = uio->uio_resid;
  944         else
  945                 resid = top->m_pkthdr.len;
  946         /*
  947          * In theory resid should be unsigned.  However, space must be
  948          * signed, as it might be less than 0 if we over-committed, and we
  949          * must use a signed comparison of space and resid.  On the other
  950          * hand, a negative resid causes us to loop sending 0-length
  951          * segments to the protocol.
  952          *
  953          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
  954          * type sockets since that's an error.
  955          */
  956         if (resid < 0) {
  957                 error = EINVAL;
  958                 goto out;
  959         }
  960 
  961         dontroute =
  962             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
  963         if (td != NULL)
  964                 td->td_ru.ru_msgsnd++;
  965         if (control != NULL)
  966                 clen = control->m_len;
  967 
  968         SOCKBUF_LOCK(&so->so_snd);
  969         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
  970                 SOCKBUF_UNLOCK(&so->so_snd);
  971                 error = EPIPE;
  972                 goto out;
  973         }
  974         if (so->so_error) {
  975                 error = so->so_error;
  976                 so->so_error = 0;
  977                 SOCKBUF_UNLOCK(&so->so_snd);
  978                 goto out;
  979         }
  980         if ((so->so_state & SS_ISCONNECTED) == 0) {
  981                 /*
  982                  * `sendto' and `sendmsg' is allowed on a connection-based
  983                  * socket if it supports implied connect.  Return ENOTCONN if
  984                  * not connected and no address is supplied.
  985                  */
  986                 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
  987                     (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
  988                         if ((so->so_state & SS_ISCONFIRMING) == 0 &&
  989                             !(resid == 0 && clen != 0)) {
  990                                 SOCKBUF_UNLOCK(&so->so_snd);
  991                                 error = ENOTCONN;
  992                                 goto out;
  993                         }
  994                 } else if (addr == NULL) {
  995                         if (so->so_proto->pr_flags & PR_CONNREQUIRED)
  996                                 error = ENOTCONN;
  997                         else
  998                                 error = EDESTADDRREQ;
  999                         SOCKBUF_UNLOCK(&so->so_snd);
 1000                         goto out;
 1001                 }
 1002         }
 1003 
 1004         /*
 1005          * Do we need MSG_OOB support in SOCK_DGRAM?  Signs here may be a
 1006          * problem and need fixing.
 1007          */
 1008         space = sbspace(&so->so_snd);
 1009         if (flags & MSG_OOB)
 1010                 space += 1024;
 1011         space -= clen;
 1012         SOCKBUF_UNLOCK(&so->so_snd);
 1013         if (resid > space) {
 1014                 error = EMSGSIZE;
 1015                 goto out;
 1016         }
 1017         if (uio == NULL) {
 1018                 resid = 0;
 1019                 if (flags & MSG_EOR)
 1020                         top->m_flags |= M_EOR;
 1021         } else {
 1022 #ifdef ZERO_COPY_SOCKETS
 1023                 error = sosend_copyin(uio, &top, atomic, &space, flags);
 1024                 if (error)
 1025                         goto out;
 1026 #else
 1027                 /*
 1028                  * Copy the data from userland into a mbuf chain.
 1029                  * If no data is to be copied in, a single empty mbuf
 1030                  * is returned.
 1031                  */
 1032                 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
 1033                     (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
 1034                 if (top == NULL) {
 1035                         error = EFAULT; /* only possible error */
 1036                         goto out;
 1037                 }
 1038                 space -= resid - uio->uio_resid;
 1039 #endif
 1040                 resid = uio->uio_resid;
 1041         }
 1042         KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
 1043         /*
 1044          * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
 1045          * than with.
 1046          */
 1047         if (dontroute) {
 1048                 SOCK_LOCK(so);
 1049                 so->so_options |= SO_DONTROUTE;
 1050                 SOCK_UNLOCK(so);
 1051         }
 1052         /*
 1053          * XXX all the SBS_CANTSENDMORE checks previously done could be out
 1054          * of date.  We could have recieved a reset packet in an interrupt or
 1055          * maybe we slept while doing page faults in uiomove() etc.  We could
 1056          * probably recheck again inside the locking protection here, but
 1057          * there are probably other places that this also happens.  We must
 1058          * rethink this.
 1059          */
 1060         error = (*so->so_proto->pr_usrreqs->pru_send)(so,
 1061             (flags & MSG_OOB) ? PRUS_OOB :
 1062         /*
 1063          * If the user set MSG_EOF, the protocol understands this flag and
 1064          * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
 1065          */
 1066             ((flags & MSG_EOF) &&
 1067              (so->so_proto->pr_flags & PR_IMPLOPCL) &&
 1068              (resid <= 0)) ?
 1069                 PRUS_EOF :
 1070                 /* If there is more to send set PRUS_MORETOCOME */
 1071                 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
 1072                 top, addr, control, td);
 1073         if (dontroute) {
 1074                 SOCK_LOCK(so);
 1075                 so->so_options &= ~SO_DONTROUTE;
 1076                 SOCK_UNLOCK(so);
 1077         }
 1078         clen = 0;
 1079         control = NULL;
 1080         top = NULL;
 1081 out:
 1082         if (top != NULL)
 1083                 m_freem(top);
 1084         if (control != NULL)
 1085                 m_freem(control);
 1086         return (error);
 1087 }
 1088 
 1089 /*
 1090  * Send on a socket.  If send must go all at once and message is larger than
 1091  * send buffering, then hard error.  Lock against other senders.  If must go
 1092  * all at once and not enough room now, then inform user that this would
 1093  * block and do nothing.  Otherwise, if nonblocking, send as much as
 1094  * possible.  The data to be sent is described by "uio" if nonzero, otherwise
 1095  * by the mbuf chain "top" (which must be null if uio is not).  Data provided
 1096  * in mbuf chain must be small enough to send all at once.
 1097  *
 1098  * Returns nonzero on error, timeout or signal; callers must check for short
 1099  * counts if EINTR/ERESTART are returned.  Data and control buffers are freed
 1100  * on return.
 1101  */
 1102 int
 1103 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
 1104     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
 1105 {
 1106         long space, resid;
 1107         int clen = 0, error, dontroute;
 1108         int atomic = sosendallatonce(so) || top;
 1109 
 1110         if (uio != NULL)
 1111                 resid = uio->uio_resid;
 1112         else
 1113                 resid = top->m_pkthdr.len;
 1114         /*
 1115          * In theory resid should be unsigned.  However, space must be
 1116          * signed, as it might be less than 0 if we over-committed, and we
 1117          * must use a signed comparison of space and resid.  On the other
 1118          * hand, a negative resid causes us to loop sending 0-length
 1119          * segments to the protocol.
 1120          *
 1121          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
 1122          * type sockets since that's an error.
 1123          */
 1124         if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
 1125                 error = EINVAL;
 1126                 goto out;
 1127         }
 1128 
 1129         dontroute =
 1130             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
 1131             (so->so_proto->pr_flags & PR_ATOMIC);
 1132         if (td != NULL)
 1133                 td->td_ru.ru_msgsnd++;
 1134         if (control != NULL)
 1135                 clen = control->m_len;
 1136 
 1137         error = sblock(&so->so_snd, SBLOCKWAIT(flags));
 1138         if (error)
 1139                 goto out;
 1140 
 1141 restart:
 1142         do {
 1143                 SOCKBUF_LOCK(&so->so_snd);
 1144                 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
 1145                         SOCKBUF_UNLOCK(&so->so_snd);
 1146                         error = EPIPE;
 1147                         goto release;
 1148                 }
 1149                 if (so->so_error) {
 1150                         error = so->so_error;
 1151                         so->so_error = 0;
 1152                         SOCKBUF_UNLOCK(&so->so_snd);
 1153                         goto release;
 1154                 }
 1155                 if ((so->so_state & SS_ISCONNECTED) == 0) {
 1156                         /*
 1157                          * `sendto' and `sendmsg' is allowed on a connection-
 1158                          * based socket if it supports implied connect.
 1159                          * Return ENOTCONN if not connected and no address is
 1160                          * supplied.
 1161                          */
 1162                         if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
 1163                             (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
 1164                                 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
 1165                                     !(resid == 0 && clen != 0)) {
 1166                                         SOCKBUF_UNLOCK(&so->so_snd);
 1167                                         error = ENOTCONN;
 1168                                         goto release;
 1169                                 }
 1170                         } else if (addr == NULL) {
 1171                                 SOCKBUF_UNLOCK(&so->so_snd);
 1172                                 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
 1173                                         error = ENOTCONN;
 1174                                 else
 1175                                         error = EDESTADDRREQ;
 1176                                 goto release;
 1177                         }
 1178                 }
 1179                 space = sbspace(&so->so_snd);
 1180                 if (flags & MSG_OOB)
 1181                         space += 1024;
 1182                 if ((atomic && resid > so->so_snd.sb_hiwat) ||
 1183                     clen > so->so_snd.sb_hiwat) {
 1184                         SOCKBUF_UNLOCK(&so->so_snd);
 1185                         error = EMSGSIZE;
 1186                         goto release;
 1187                 }
 1188                 if (space < resid + clen &&
 1189                     (atomic || space < so->so_snd.sb_lowat || space < clen)) {
 1190                         if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
 1191                                 SOCKBUF_UNLOCK(&so->so_snd);
 1192                                 error = EWOULDBLOCK;
 1193                                 goto release;
 1194                         }
 1195                         error = sbwait(&so->so_snd);
 1196                         SOCKBUF_UNLOCK(&so->so_snd);
 1197                         if (error)
 1198                                 goto release;
 1199                         goto restart;
 1200                 }
 1201                 SOCKBUF_UNLOCK(&so->so_snd);
 1202                 space -= clen;
 1203                 do {
 1204                         if (uio == NULL) {
 1205                                 resid = 0;
 1206                                 if (flags & MSG_EOR)
 1207                                         top->m_flags |= M_EOR;
 1208                         } else {
 1209 #ifdef ZERO_COPY_SOCKETS
 1210                                 error = sosend_copyin(uio, &top, atomic,
 1211                                     &space, flags);
 1212                                 if (error != 0)
 1213                                         goto release;
 1214 #else
 1215                                 /*
 1216                                  * Copy the data from userland into a mbuf
 1217                                  * chain.  If no data is to be copied in,
 1218                                  * a single empty mbuf is returned.
 1219                                  */
 1220                                 top = m_uiotombuf(uio, M_WAITOK, space,
 1221                                     (atomic ? max_hdr : 0),
 1222                                     (atomic ? M_PKTHDR : 0) |
 1223                                     ((flags & MSG_EOR) ? M_EOR : 0));
 1224                                 if (top == NULL) {
 1225                                         error = EFAULT; /* only possible error */
 1226                                         goto release;
 1227                                 }
 1228                                 space -= resid - uio->uio_resid;
 1229 #endif
 1230                                 resid = uio->uio_resid;
 1231                         }
 1232                         if (dontroute) {
 1233                                 SOCK_LOCK(so);
 1234                                 so->so_options |= SO_DONTROUTE;
 1235                                 SOCK_UNLOCK(so);
 1236                         }
 1237                         /*
 1238                          * XXX all the SBS_CANTSENDMORE checks previously
 1239                          * done could be out of date.  We could have recieved
 1240                          * a reset packet in an interrupt or maybe we slept
 1241                          * while doing page faults in uiomove() etc.  We
 1242                          * could probably recheck again inside the locking
 1243                          * protection here, but there are probably other
 1244                          * places that this also happens.  We must rethink
 1245                          * this.
 1246                          */
 1247                         error = (*so->so_proto->pr_usrreqs->pru_send)(so,
 1248                             (flags & MSG_OOB) ? PRUS_OOB :
 1249                         /*
 1250                          * If the user set MSG_EOF, the protocol understands
 1251                          * this flag and nothing left to send then use
 1252                          * PRU_SEND_EOF instead of PRU_SEND.
 1253                          */
 1254                             ((flags & MSG_EOF) &&
 1255                              (so->so_proto->pr_flags & PR_IMPLOPCL) &&
 1256                              (resid <= 0)) ?
 1257                                 PRUS_EOF :
 1258                         /* If there is more to send set PRUS_MORETOCOME. */
 1259                             (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
 1260                             top, addr, control, td);
 1261                         if (dontroute) {
 1262                                 SOCK_LOCK(so);
 1263                                 so->so_options &= ~SO_DONTROUTE;
 1264                                 SOCK_UNLOCK(so);
 1265                         }
 1266                         clen = 0;
 1267                         control = NULL;
 1268                         top = NULL;
 1269                         if (error)
 1270                                 goto release;
 1271                 } while (resid && space > 0);
 1272         } while (resid);
 1273 
 1274 release:
 1275         sbunlock(&so->so_snd);
 1276 out:
 1277         if (top != NULL)
 1278                 m_freem(top);
 1279         if (control != NULL)
 1280                 m_freem(control);
 1281         return (error);
 1282 }
 1283 
 1284 int
 1285 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
 1286     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
 1287 {
 1288 
 1289         return (so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
 1290             control, flags, td));
 1291 }
 1292 
 1293 /*
 1294  * The part of soreceive() that implements reading non-inline out-of-band
 1295  * data from a socket.  For more complete comments, see soreceive(), from
 1296  * which this code originated.
 1297  *
 1298  * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
 1299  * unable to return an mbuf chain to the caller.
 1300  */
 1301 static int
 1302 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
 1303 {
 1304         struct protosw *pr = so->so_proto;
 1305         struct mbuf *m;
 1306         int error;
 1307 
 1308         KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
 1309 
 1310         m = m_get(M_TRYWAIT, MT_DATA);
 1311         if (m == NULL)
 1312                 return (ENOBUFS);
 1313         error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
 1314         if (error)
 1315                 goto bad;
 1316         do {
 1317 #ifdef ZERO_COPY_SOCKETS
 1318                 if (so_zero_copy_receive) {
 1319                         int disposable;
 1320 
 1321                         if ((m->m_flags & M_EXT)
 1322                          && (m->m_ext.ext_type == EXT_DISPOSABLE))
 1323                                 disposable = 1;
 1324                         else
 1325                                 disposable = 0;
 1326 
 1327                         error = uiomoveco(mtod(m, void *),
 1328                                           min(uio->uio_resid, m->m_len),
 1329                                           uio, disposable);
 1330                 } else
 1331 #endif /* ZERO_COPY_SOCKETS */
 1332                 error = uiomove(mtod(m, void *),
 1333                     (int) min(uio->uio_resid, m->m_len), uio);
 1334                 m = m_free(m);
 1335         } while (uio->uio_resid && error == 0 && m);
 1336 bad:
 1337         if (m != NULL)
 1338                 m_freem(m);
 1339         return (error);
 1340 }
 1341 
 1342 /*
 1343  * Following replacement or removal of the first mbuf on the first mbuf chain
 1344  * of a socket buffer, push necessary state changes back into the socket
 1345  * buffer so that other consumers see the values consistently.  'nextrecord'
 1346  * is the callers locally stored value of the original value of
 1347  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
 1348  * NOTE: 'nextrecord' may be NULL.
 1349  */
 1350 static __inline void
 1351 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
 1352 {
 1353 
 1354         SOCKBUF_LOCK_ASSERT(sb);
 1355         /*
 1356          * First, update for the new value of nextrecord.  If necessary, make
 1357          * it the first record.
 1358          */
 1359         if (sb->sb_mb != NULL)
 1360                 sb->sb_mb->m_nextpkt = nextrecord;
 1361         else
 1362                 sb->sb_mb = nextrecord;
 1363 
 1364         /*
 1365          * Now update any dependent socket buffer fields to reflect the new
 1366          * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
 1367          * addition of a second clause that takes care of the case where
 1368          * sb_mb has been updated, but remains the last record.
 1369          */
 1370         if (sb->sb_mb == NULL) {
 1371                 sb->sb_mbtail = NULL;
 1372                 sb->sb_lastrecord = NULL;
 1373         } else if (sb->sb_mb->m_nextpkt == NULL)
 1374                 sb->sb_lastrecord = sb->sb_mb;
 1375 }
 1376 
 1377 
 1378 /*
 1379  * Implement receive operations on a socket.  We depend on the way that
 1380  * records are added to the sockbuf by sbappend.  In particular, each record
 1381  * (mbufs linked through m_next) must begin with an address if the protocol
 1382  * so specifies, followed by an optional mbuf or mbufs containing ancillary
 1383  * data, and then zero or more mbufs of data.  In order to allow parallelism
 1384  * between network receive and copying to user space, as well as avoid
 1385  * sleeping with a mutex held, we release the socket buffer mutex during the
 1386  * user space copy.  Although the sockbuf is locked, new data may still be
 1387  * appended, and thus we must maintain consistency of the sockbuf during that
 1388  * time.
 1389  *
 1390  * The caller may receive the data as a single mbuf chain by supplying an
 1391  * mbuf **mp0 for use in returning the chain.  The uio is then used only for
 1392  * the count in uio_resid.
 1393  */
 1394 int
 1395 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
 1396     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
 1397 {
 1398         struct mbuf *m, **mp;
 1399         int flags, len, error, offset;
 1400         struct protosw *pr = so->so_proto;
 1401         struct mbuf *nextrecord;
 1402         int moff, type = 0;
 1403         int orig_resid = uio->uio_resid;
 1404 
 1405         mp = mp0;
 1406         if (psa != NULL)
 1407                 *psa = NULL;
 1408         if (controlp != NULL)
 1409                 *controlp = NULL;
 1410         if (flagsp != NULL)
 1411                 flags = *flagsp &~ MSG_EOR;
 1412         else
 1413                 flags = 0;
 1414         if (flags & MSG_OOB)
 1415                 return (soreceive_rcvoob(so, uio, flags));
 1416         if (mp != NULL)
 1417                 *mp = NULL;
 1418         if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
 1419             && uio->uio_resid)
 1420                 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
 1421 
 1422         error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
 1423         if (error)
 1424                 return (error);
 1425 
 1426 restart:
 1427         SOCKBUF_LOCK(&so->so_rcv);
 1428         m = so->so_rcv.sb_mb;
 1429         /*
 1430          * If we have less data than requested, block awaiting more (subject
 1431          * to any timeout) if:
 1432          *   1. the current count is less than the low water mark, or
 1433          *   2. MSG_WAITALL is set, and it is possible to do the entire
 1434          *      receive operation at once if we block (resid <= hiwat).
 1435          *   3. MSG_DONTWAIT is not set
 1436          * If MSG_WAITALL is set but resid is larger than the receive buffer,
 1437          * we have to do the receive in sections, and thus risk returning a
 1438          * short count if a timeout or signal occurs after we start.
 1439          */
 1440         if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
 1441             so->so_rcv.sb_cc < uio->uio_resid) &&
 1442             (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
 1443             ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
 1444             m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
 1445                 KASSERT(m != NULL || !so->so_rcv.sb_cc,
 1446                     ("receive: m == %p so->so_rcv.sb_cc == %u",
 1447                     m, so->so_rcv.sb_cc));
 1448                 if (so->so_error) {
 1449                         if (m != NULL)
 1450                                 goto dontblock;
 1451                         error = so->so_error;
 1452                         if ((flags & MSG_PEEK) == 0)
 1453                                 so->so_error = 0;
 1454                         SOCKBUF_UNLOCK(&so->so_rcv);
 1455                         goto release;
 1456                 }
 1457                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1458                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
 1459                         if (m == NULL) {
 1460                                 SOCKBUF_UNLOCK(&so->so_rcv);
 1461                                 goto release;
 1462                         } else
 1463                                 goto dontblock;
 1464                 }
 1465                 for (; m != NULL; m = m->m_next)
 1466                         if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
 1467                                 m = so->so_rcv.sb_mb;
 1468                                 goto dontblock;
 1469                         }
 1470                 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
 1471                     (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
 1472                         SOCKBUF_UNLOCK(&so->so_rcv);
 1473                         error = ENOTCONN;
 1474                         goto release;
 1475                 }
 1476                 if (uio->uio_resid == 0) {
 1477                         SOCKBUF_UNLOCK(&so->so_rcv);
 1478                         goto release;
 1479                 }
 1480                 if ((so->so_state & SS_NBIO) ||
 1481                     (flags & (MSG_DONTWAIT|MSG_NBIO))) {
 1482                         SOCKBUF_UNLOCK(&so->so_rcv);
 1483                         error = EWOULDBLOCK;
 1484                         goto release;
 1485                 }
 1486                 SBLASTRECORDCHK(&so->so_rcv);
 1487                 SBLASTMBUFCHK(&so->so_rcv);
 1488                 error = sbwait(&so->so_rcv);
 1489                 SOCKBUF_UNLOCK(&so->so_rcv);
 1490                 if (error)
 1491                         goto release;
 1492                 goto restart;
 1493         }
 1494 dontblock:
 1495         /*
 1496          * From this point onward, we maintain 'nextrecord' as a cache of the
 1497          * pointer to the next record in the socket buffer.  We must keep the
 1498          * various socket buffer pointers and local stack versions of the
 1499          * pointers in sync, pushing out modifications before dropping the
 1500          * socket buffer mutex, and re-reading them when picking it up.
 1501          *
 1502          * Otherwise, we will race with the network stack appending new data
 1503          * or records onto the socket buffer by using inconsistent/stale
 1504          * versions of the field, possibly resulting in socket buffer
 1505          * corruption.
 1506          *
 1507          * By holding the high-level sblock(), we prevent simultaneous
 1508          * readers from pulling off the front of the socket buffer.
 1509          */
 1510         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1511         if (uio->uio_td)
 1512                 uio->uio_td->td_ru.ru_msgrcv++;
 1513         KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
 1514         SBLASTRECORDCHK(&so->so_rcv);
 1515         SBLASTMBUFCHK(&so->so_rcv);
 1516         nextrecord = m->m_nextpkt;
 1517         if (pr->pr_flags & PR_ADDR) {
 1518                 KASSERT(m->m_type == MT_SONAME,
 1519                     ("m->m_type == %d", m->m_type));
 1520                 orig_resid = 0;
 1521                 if (psa != NULL)
 1522                         *psa = sodupsockaddr(mtod(m, struct sockaddr *),
 1523                             M_NOWAIT);
 1524                 if (flags & MSG_PEEK) {
 1525                         m = m->m_next;
 1526                 } else {
 1527                         sbfree(&so->so_rcv, m);
 1528                         so->so_rcv.sb_mb = m_free(m);
 1529                         m = so->so_rcv.sb_mb;
 1530                         sockbuf_pushsync(&so->so_rcv, nextrecord);
 1531                 }
 1532         }
 1533 
 1534         /*
 1535          * Process one or more MT_CONTROL mbufs present before any data mbufs
 1536          * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
 1537          * just copy the data; if !MSG_PEEK, we call into the protocol to
 1538          * perform externalization (or freeing if controlp == NULL).
 1539          */
 1540         if (m != NULL && m->m_type == MT_CONTROL) {
 1541                 struct mbuf *cm = NULL, *cmn;
 1542                 struct mbuf **cme = &cm;
 1543 
 1544                 do {
 1545                         if (flags & MSG_PEEK) {
 1546                                 if (controlp != NULL) {
 1547                                         *controlp = m_copy(m, 0, m->m_len);
 1548                                         controlp = &(*controlp)->m_next;
 1549                                 }
 1550                                 m = m->m_next;
 1551                         } else {
 1552                                 sbfree(&so->so_rcv, m);
 1553                                 so->so_rcv.sb_mb = m->m_next;
 1554                                 m->m_next = NULL;
 1555                                 *cme = m;
 1556                                 cme = &(*cme)->m_next;
 1557                                 m = so->so_rcv.sb_mb;
 1558                         }
 1559                 } while (m != NULL && m->m_type == MT_CONTROL);
 1560                 if ((flags & MSG_PEEK) == 0)
 1561                         sockbuf_pushsync(&so->so_rcv, nextrecord);
 1562                 while (cm != NULL) {
 1563                         cmn = cm->m_next;
 1564                         cm->m_next = NULL;
 1565                         if (pr->pr_domain->dom_externalize != NULL) {
 1566                                 SOCKBUF_UNLOCK(&so->so_rcv);
 1567                                 error = (*pr->pr_domain->dom_externalize)
 1568                                     (cm, controlp);
 1569                                 SOCKBUF_LOCK(&so->so_rcv);
 1570                         } else if (controlp != NULL)
 1571                                 *controlp = cm;
 1572                         else
 1573                                 m_freem(cm);
 1574                         if (controlp != NULL) {
 1575                                 orig_resid = 0;
 1576                                 while (*controlp != NULL)
 1577                                         controlp = &(*controlp)->m_next;
 1578                         }
 1579                         cm = cmn;
 1580                 }
 1581                 if (m != NULL)
 1582                         nextrecord = so->so_rcv.sb_mb->m_nextpkt;
 1583                 else
 1584                         nextrecord = so->so_rcv.sb_mb;
 1585                 orig_resid = 0;
 1586         }
 1587         if (m != NULL) {
 1588                 if ((flags & MSG_PEEK) == 0) {
 1589                         KASSERT(m->m_nextpkt == nextrecord,
 1590                             ("soreceive: post-control, nextrecord !sync"));
 1591                         if (nextrecord == NULL) {
 1592                                 KASSERT(so->so_rcv.sb_mb == m,
 1593                                     ("soreceive: post-control, sb_mb!=m"));
 1594                                 KASSERT(so->so_rcv.sb_lastrecord == m,
 1595                                     ("soreceive: post-control, lastrecord!=m"));
 1596                         }
 1597                 }
 1598                 type = m->m_type;
 1599                 if (type == MT_OOBDATA)
 1600                         flags |= MSG_OOB;
 1601         } else {
 1602                 if ((flags & MSG_PEEK) == 0) {
 1603                         KASSERT(so->so_rcv.sb_mb == nextrecord,
 1604                             ("soreceive: sb_mb != nextrecord"));
 1605                         if (so->so_rcv.sb_mb == NULL) {
 1606                                 KASSERT(so->so_rcv.sb_lastrecord == NULL,
 1607                                     ("soreceive: sb_lastercord != NULL"));
 1608                         }
 1609                 }
 1610         }
 1611         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1612         SBLASTRECORDCHK(&so->so_rcv);
 1613         SBLASTMBUFCHK(&so->so_rcv);
 1614 
 1615         /*
 1616          * Now continue to read any data mbufs off of the head of the socket
 1617          * buffer until the read request is satisfied.  Note that 'type' is
 1618          * used to store the type of any mbuf reads that have happened so far
 1619          * such that soreceive() can stop reading if the type changes, which
 1620          * causes soreceive() to return only one of regular data and inline
 1621          * out-of-band data in a single socket receive operation.
 1622          */
 1623         moff = 0;
 1624         offset = 0;
 1625         while (m != NULL && uio->uio_resid > 0 && error == 0) {
 1626                 /*
 1627                  * If the type of mbuf has changed since the last mbuf
 1628                  * examined ('type'), end the receive operation.
 1629                  */
 1630                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1631                 if (m->m_type == MT_OOBDATA) {
 1632                         if (type != MT_OOBDATA)
 1633                                 break;
 1634                 } else if (type == MT_OOBDATA)
 1635                         break;
 1636                 else
 1637                     KASSERT(m->m_type == MT_DATA,
 1638                         ("m->m_type == %d", m->m_type));
 1639                 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
 1640                 len = uio->uio_resid;
 1641                 if (so->so_oobmark && len > so->so_oobmark - offset)
 1642                         len = so->so_oobmark - offset;
 1643                 if (len > m->m_len - moff)
 1644                         len = m->m_len - moff;
 1645                 /*
 1646                  * If mp is set, just pass back the mbufs.  Otherwise copy
 1647                  * them out via the uio, then free.  Sockbuf must be
 1648                  * consistent here (points to current mbuf, it points to next
 1649                  * record) when we drop priority; we must note any additions
 1650                  * to the sockbuf when we block interrupts again.
 1651                  */
 1652                 if (mp == NULL) {
 1653                         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1654                         SBLASTRECORDCHK(&so->so_rcv);
 1655                         SBLASTMBUFCHK(&so->so_rcv);
 1656                         SOCKBUF_UNLOCK(&so->so_rcv);
 1657 #ifdef ZERO_COPY_SOCKETS
 1658                         if (so_zero_copy_receive) {
 1659                                 int disposable;
 1660 
 1661                                 if ((m->m_flags & M_EXT)
 1662                                  && (m->m_ext.ext_type == EXT_DISPOSABLE))
 1663                                         disposable = 1;
 1664                                 else
 1665                                         disposable = 0;
 1666 
 1667                                 error = uiomoveco(mtod(m, char *) + moff,
 1668                                                   (int)len, uio,
 1669                                                   disposable);
 1670                         } else
 1671 #endif /* ZERO_COPY_SOCKETS */
 1672                         error = uiomove(mtod(m, char *) + moff, (int)len, uio);
 1673                         SOCKBUF_LOCK(&so->so_rcv);
 1674                         if (error) {
 1675                                 /*
 1676                                  * The MT_SONAME mbuf has already been removed
 1677                                  * from the record, so it is necessary to
 1678                                  * remove the data mbufs, if any, to preserve
 1679                                  * the invariant in the case of PR_ADDR that
 1680                                  * requires MT_SONAME mbufs at the head of
 1681                                  * each record.
 1682                                  */
 1683                                 if (m && pr->pr_flags & PR_ATOMIC &&
 1684                                     ((flags & MSG_PEEK) == 0))
 1685                                         (void)sbdroprecord_locked(&so->so_rcv);
 1686                                 SOCKBUF_UNLOCK(&so->so_rcv);
 1687                                 goto release;
 1688                         }
 1689                 } else
 1690                         uio->uio_resid -= len;
 1691                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1692                 if (len == m->m_len - moff) {
 1693                         if (m->m_flags & M_EOR)
 1694                                 flags |= MSG_EOR;
 1695                         if (flags & MSG_PEEK) {
 1696                                 m = m->m_next;
 1697                                 moff = 0;
 1698                         } else {
 1699                                 nextrecord = m->m_nextpkt;
 1700                                 sbfree(&so->so_rcv, m);
 1701                                 if (mp != NULL) {
 1702                                         *mp = m;
 1703                                         mp = &m->m_next;
 1704                                         so->so_rcv.sb_mb = m = m->m_next;
 1705                                         *mp = NULL;
 1706                                 } else {
 1707                                         so->so_rcv.sb_mb = m_free(m);
 1708                                         m = so->so_rcv.sb_mb;
 1709                                 }
 1710                                 sockbuf_pushsync(&so->so_rcv, nextrecord);
 1711                                 SBLASTRECORDCHK(&so->so_rcv);
 1712                                 SBLASTMBUFCHK(&so->so_rcv);
 1713                         }
 1714                 } else {
 1715                         if (flags & MSG_PEEK)
 1716                                 moff += len;
 1717                         else {
 1718                                 if (mp != NULL) {
 1719                                         int copy_flag;
 1720 
 1721                                         if (flags & MSG_DONTWAIT)
 1722                                                 copy_flag = M_DONTWAIT;
 1723                                         else
 1724                                                 copy_flag = M_TRYWAIT;
 1725                                         if (copy_flag == M_TRYWAIT)
 1726                                                 SOCKBUF_UNLOCK(&so->so_rcv);
 1727                                         *mp = m_copym(m, 0, len, copy_flag);
 1728                                         if (copy_flag == M_TRYWAIT)
 1729                                                 SOCKBUF_LOCK(&so->so_rcv);
 1730                                         if (*mp == NULL) {
 1731                                                 /*
 1732                                                  * m_copym() couldn't
 1733                                                  * allocate an mbuf.  Adjust
 1734                                                  * uio_resid back (it was
 1735                                                  * adjusted down by len
 1736                                                  * bytes, which we didn't end
 1737                                                  * up "copying" over).
 1738                                                  */
 1739                                                 uio->uio_resid += len;
 1740                                                 break;
 1741                                         }
 1742                                 }
 1743                                 m->m_data += len;
 1744                                 m->m_len -= len;
 1745                                 so->so_rcv.sb_cc -= len;
 1746                         }
 1747                 }
 1748                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1749                 if (so->so_oobmark) {
 1750                         if ((flags & MSG_PEEK) == 0) {
 1751                                 so->so_oobmark -= len;
 1752                                 if (so->so_oobmark == 0) {
 1753                                         so->so_rcv.sb_state |= SBS_RCVATMARK;
 1754                                         break;
 1755                                 }
 1756                         } else {
 1757                                 offset += len;
 1758                                 if (offset == so->so_oobmark)
 1759                                         break;
 1760                         }
 1761                 }
 1762                 if (flags & MSG_EOR)
 1763                         break;
 1764                 /*
 1765                  * If the MSG_WAITALL flag is set (for non-atomic socket), we
 1766                  * must not quit until "uio->uio_resid == 0" or an error
 1767                  * termination.  If a signal/timeout occurs, return with a
 1768                  * short count but without error.  Keep sockbuf locked
 1769                  * against other readers.
 1770                  */
 1771                 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
 1772                     !sosendallatonce(so) && nextrecord == NULL) {
 1773                         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1774                         if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
 1775                                 break;
 1776                         /*
 1777                          * Notify the protocol that some data has been
 1778                          * drained before blocking.
 1779                          */
 1780                         if (pr->pr_flags & PR_WANTRCVD) {
 1781                                 SOCKBUF_UNLOCK(&so->so_rcv);
 1782                                 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
 1783                                 SOCKBUF_LOCK(&so->so_rcv);
 1784                         }
 1785                         SBLASTRECORDCHK(&so->so_rcv);
 1786                         SBLASTMBUFCHK(&so->so_rcv);
 1787                         error = sbwait(&so->so_rcv);
 1788                         if (error) {
 1789                                 SOCKBUF_UNLOCK(&so->so_rcv);
 1790                                 goto release;
 1791                         }
 1792                         m = so->so_rcv.sb_mb;
 1793                         if (m != NULL)
 1794                                 nextrecord = m->m_nextpkt;
 1795                 }
 1796         }
 1797 
 1798         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1799         if (m != NULL && pr->pr_flags & PR_ATOMIC) {
 1800                 flags |= MSG_TRUNC;
 1801                 if ((flags & MSG_PEEK) == 0)
 1802                         (void) sbdroprecord_locked(&so->so_rcv);
 1803         }
 1804         if ((flags & MSG_PEEK) == 0) {
 1805                 if (m == NULL) {
 1806                         /*
 1807                          * First part is an inline SB_EMPTY_FIXUP().  Second
 1808                          * part makes sure sb_lastrecord is up-to-date if
 1809                          * there is still data in the socket buffer.
 1810                          */
 1811                         so->so_rcv.sb_mb = nextrecord;
 1812                         if (so->so_rcv.sb_mb == NULL) {
 1813                                 so->so_rcv.sb_mbtail = NULL;
 1814                                 so->so_rcv.sb_lastrecord = NULL;
 1815                         } else if (nextrecord->m_nextpkt == NULL)
 1816                                 so->so_rcv.sb_lastrecord = nextrecord;
 1817                 }
 1818                 SBLASTRECORDCHK(&so->so_rcv);
 1819                 SBLASTMBUFCHK(&so->so_rcv);
 1820                 /*
 1821                  * If soreceive() is being done from the socket callback,
 1822                  * then don't need to generate ACK to peer to update window,
 1823                  * since ACK will be generated on return to TCP.
 1824                  */
 1825                 if (!(flags & MSG_SOCALLBCK) &&
 1826                     (pr->pr_flags & PR_WANTRCVD)) {
 1827                         SOCKBUF_UNLOCK(&so->so_rcv);
 1828                         (*pr->pr_usrreqs->pru_rcvd)(so, flags);
 1829                         SOCKBUF_LOCK(&so->so_rcv);
 1830                 }
 1831         }
 1832         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1833         if (orig_resid == uio->uio_resid && orig_resid &&
 1834             (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
 1835                 SOCKBUF_UNLOCK(&so->so_rcv);
 1836                 goto restart;
 1837         }
 1838         SOCKBUF_UNLOCK(&so->so_rcv);
 1839 
 1840         if (flagsp != NULL)
 1841                 *flagsp |= flags;
 1842 release:
 1843         sbunlock(&so->so_rcv);
 1844         return (error);
 1845 }
 1846 
 1847 /*
 1848  * Optimized version of soreceive() for simple datagram cases from userspace.
 1849  * Unlike in the stream case, we're able to drop a datagram if copyout()
 1850  * fails, and because we handle datagrams atomically, we don't need to use a
 1851  * sleep lock to prevent I/O interlacing.
 1852  */
 1853 int
 1854 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
 1855     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
 1856 {
 1857         struct mbuf *m, *m2;
 1858         int flags, len, error;
 1859         struct protosw *pr = so->so_proto;
 1860         struct mbuf *nextrecord;
 1861 
 1862         if (psa != NULL)
 1863                 *psa = NULL;
 1864         if (controlp != NULL)
 1865                 *controlp = NULL;
 1866         if (flagsp != NULL)
 1867                 flags = *flagsp &~ MSG_EOR;
 1868         else
 1869                 flags = 0;
 1870 
 1871         /*
 1872          * For any complicated cases, fall back to the full
 1873          * soreceive_generic().
 1874          */
 1875         if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
 1876                 return (soreceive_generic(so, psa, uio, mp0, controlp,
 1877                     flagsp));
 1878 
 1879         /*
 1880          * Enforce restrictions on use.
 1881          */
 1882         KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
 1883             ("soreceive_dgram: wantrcvd"));
 1884         KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
 1885         KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
 1886             ("soreceive_dgram: SBS_RCVATMARK"));
 1887         KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
 1888             ("soreceive_dgram: P_CONNREQUIRED"));
 1889 
 1890         /*
 1891          * Loop blocking while waiting for a datagram.
 1892          */
 1893         SOCKBUF_LOCK(&so->so_rcv);
 1894         while ((m = so->so_rcv.sb_mb) == NULL) {
 1895                 KASSERT(so->so_rcv.sb_cc == 0,
 1896                     ("soreceive_dgram: sb_mb NULL but sb_cc %u",
 1897                     so->so_rcv.sb_cc));
 1898                 if (so->so_error) {
 1899                         error = so->so_error;
 1900                         so->so_error = 0;
 1901                         SOCKBUF_UNLOCK(&so->so_rcv);
 1902                         return (error);
 1903                 }
 1904                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
 1905                     uio->uio_resid == 0) {
 1906                         SOCKBUF_UNLOCK(&so->so_rcv);
 1907                         return (0);
 1908                 }
 1909                 if ((so->so_state & SS_NBIO) ||
 1910                     (flags & (MSG_DONTWAIT|MSG_NBIO))) {
 1911                         SOCKBUF_UNLOCK(&so->so_rcv);
 1912                         return (EWOULDBLOCK);
 1913                 }
 1914                 SBLASTRECORDCHK(&so->so_rcv);
 1915                 SBLASTMBUFCHK(&so->so_rcv);
 1916                 error = sbwait(&so->so_rcv);
 1917                 if (error) {
 1918                         SOCKBUF_UNLOCK(&so->so_rcv);
 1919                         return (error);
 1920                 }
 1921         }
 1922         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 1923 
 1924         if (uio->uio_td)
 1925                 uio->uio_td->td_ru.ru_msgrcv++;
 1926         SBLASTRECORDCHK(&so->so_rcv);
 1927         SBLASTMBUFCHK(&so->so_rcv);
 1928         nextrecord = m->m_nextpkt;
 1929         if (nextrecord == NULL) {
 1930                 KASSERT(so->so_rcv.sb_lastrecord == m,
 1931                     ("soreceive_dgram: lastrecord != m"));
 1932         }
 1933 
 1934         KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
 1935             ("soreceive_dgram: m_nextpkt != nextrecord"));
 1936 
 1937         /*
 1938          * Pull 'm' and its chain off the front of the packet queue.
 1939          */
 1940         so->so_rcv.sb_mb = NULL;
 1941         sockbuf_pushsync(&so->so_rcv, nextrecord);
 1942 
 1943         /*
 1944          * Walk 'm's chain and free that many bytes from the socket buffer.
 1945          */
 1946         for (m2 = m; m2 != NULL; m2 = m2->m_next)
 1947                 sbfree(&so->so_rcv, m2);
 1948 
 1949         /*
 1950          * Do a few last checks before we let go of the lock.
 1951          */
 1952         SBLASTRECORDCHK(&so->so_rcv);
 1953         SBLASTMBUFCHK(&so->so_rcv);
 1954         SOCKBUF_UNLOCK(&so->so_rcv);
 1955 
 1956         if (pr->pr_flags & PR_ADDR) {
 1957                 KASSERT(m->m_type == MT_SONAME,
 1958                     ("m->m_type == %d", m->m_type));
 1959                 if (psa != NULL)
 1960                         *psa = sodupsockaddr(mtod(m, struct sockaddr *),
 1961                             M_NOWAIT);
 1962                 m = m_free(m);
 1963         }
 1964         if (m == NULL) {
 1965                 /* XXXRW: Can this happen? */
 1966                 return (0);
 1967         }
 1968 
 1969         /*
 1970          * Packet to copyout() is now in 'm' and it is disconnected from the
 1971          * queue.
 1972          *
 1973          * Process one or more MT_CONTROL mbufs present before any data mbufs
 1974          * in the first mbuf chain on the socket buffer.  We call into the
 1975          * protocol to perform externalization (or freeing if controlp ==
 1976          * NULL).
 1977          */
 1978         if (m->m_type == MT_CONTROL) {
 1979                 struct mbuf *cm = NULL, *cmn;
 1980                 struct mbuf **cme = &cm;
 1981 
 1982                 do {
 1983                         m2 = m->m_next;
 1984                         m->m_next = NULL;
 1985                         *cme = m;
 1986                         cme = &(*cme)->m_next;
 1987                         m = m2;
 1988                 } while (m != NULL && m->m_type == MT_CONTROL);
 1989                 while (cm != NULL) {
 1990                         cmn = cm->m_next;
 1991                         cm->m_next = NULL;
 1992                         if (pr->pr_domain->dom_externalize != NULL) {
 1993                                 error = (*pr->pr_domain->dom_externalize)
 1994                                     (cm, controlp);
 1995                         } else if (controlp != NULL)
 1996                                 *controlp = cm;
 1997                         else
 1998                                 m_freem(cm);
 1999                         if (controlp != NULL) {
 2000                                 while (*controlp != NULL)
 2001                                         controlp = &(*controlp)->m_next;
 2002                         }
 2003                         cm = cmn;
 2004                 }
 2005         }
 2006         KASSERT(m->m_type == MT_DATA, ("soreceive_dgram: !data"));
 2007 
 2008         while (m != NULL && uio->uio_resid > 0) {
 2009                 len = uio->uio_resid;
 2010                 if (len > m->m_len)
 2011                         len = m->m_len;
 2012                 error = uiomove(mtod(m, char *), (int)len, uio);
 2013                 if (error) {
 2014                         m_freem(m);
 2015                         return (error);
 2016                 }
 2017                 m = m_free(m);
 2018         }
 2019         if (m != NULL)
 2020                 flags |= MSG_TRUNC;
 2021         m_freem(m);
 2022         if (flagsp != NULL)
 2023                 *flagsp |= flags;
 2024         return (0);
 2025 }
 2026 
 2027 int
 2028 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
 2029     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
 2030 {
 2031 
 2032         return (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
 2033             controlp, flagsp));
 2034 }
 2035 
 2036 int
 2037 soshutdown(struct socket *so, int how)
 2038 {
 2039         struct protosw *pr = so->so_proto;
 2040 
 2041         if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
 2042                 return (EINVAL);
 2043         if (pr->pr_usrreqs->pru_flush != NULL) {
 2044                 (*pr->pr_usrreqs->pru_flush)(so, how);
 2045         }
 2046         if (how != SHUT_WR)
 2047                 sorflush(so);
 2048         if (how != SHUT_RD)
 2049                 return ((*pr->pr_usrreqs->pru_shutdown)(so));
 2050         return (0);
 2051 }
 2052 
 2053 void
 2054 sorflush(struct socket *so)
 2055 {
 2056         struct sockbuf *sb = &so->so_rcv;
 2057         struct protosw *pr = so->so_proto;
 2058         struct sockbuf asb;
 2059 
 2060         /*
 2061          * In order to avoid calling dom_dispose with the socket buffer mutex
 2062          * held, and in order to generally avoid holding the lock for a long
 2063          * time, we make a copy of the socket buffer and clear the original
 2064          * (except locks, state).  The new socket buffer copy won't have
 2065          * initialized locks so we can only call routines that won't use or
 2066          * assert those locks.
 2067          *
 2068          * Dislodge threads currently blocked in receive and wait to acquire
 2069          * a lock against other simultaneous readers before clearing the
 2070          * socket buffer.  Don't let our acquire be interrupted by a signal
 2071          * despite any existing socket disposition on interruptable waiting.
 2072          */
 2073         socantrcvmore(so);
 2074         (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
 2075 
 2076         /*
 2077          * Invalidate/clear most of the sockbuf structure, but leave selinfo
 2078          * and mutex data unchanged.
 2079          */
 2080         SOCKBUF_LOCK(sb);
 2081         bzero(&asb, offsetof(struct sockbuf, sb_startzero));
 2082         bcopy(&sb->sb_startzero, &asb.sb_startzero,
 2083             sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
 2084         bzero(&sb->sb_startzero,
 2085             sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
 2086         SOCKBUF_UNLOCK(sb);
 2087         sbunlock(sb);
 2088 
 2089         /*
 2090          * Dispose of special rights and flush the socket buffer.  Don't call
 2091          * any unsafe routines (that rely on locks being initialized) on asb.
 2092          */
 2093         if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
 2094                 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
 2095         sbrelease_internal(&asb, so);
 2096 }
 2097 
 2098 /*
 2099  * Perhaps this routine, and sooptcopyout(), below, ought to come in an
 2100  * additional variant to handle the case where the option value needs to be
 2101  * some kind of integer, but not a specific size.  In addition to their use
 2102  * here, these functions are also called by the protocol-level pr_ctloutput()
 2103  * routines.
 2104  */
 2105 int
 2106 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
 2107 {
 2108         size_t  valsize;
 2109 
 2110         /*
 2111          * If the user gives us more than we wanted, we ignore it, but if we
 2112          * don't get the minimum length the caller wants, we return EINVAL.
 2113          * On success, sopt->sopt_valsize is set to however much we actually
 2114          * retrieved.
 2115          */
 2116         if ((valsize = sopt->sopt_valsize) < minlen)
 2117                 return EINVAL;
 2118         if (valsize > len)
 2119                 sopt->sopt_valsize = valsize = len;
 2120 
 2121         if (sopt->sopt_td != NULL)
 2122                 return (copyin(sopt->sopt_val, buf, valsize));
 2123 
 2124         bcopy(sopt->sopt_val, buf, valsize);
 2125         return (0);
 2126 }
 2127 
 2128 /*
 2129  * Kernel version of setsockopt(2).
 2130  *
 2131  * XXX: optlen is size_t, not socklen_t
 2132  */
 2133 int
 2134 so_setsockopt(struct socket *so, int level, int optname, void *optval,
 2135     size_t optlen)
 2136 {
 2137         struct sockopt sopt;
 2138 
 2139         sopt.sopt_level = level;
 2140         sopt.sopt_name = optname;
 2141         sopt.sopt_dir = SOPT_SET;
 2142         sopt.sopt_val = optval;
 2143         sopt.sopt_valsize = optlen;
 2144         sopt.sopt_td = NULL;
 2145         return (sosetopt(so, &sopt));
 2146 }
 2147 
 2148 int
 2149 sosetopt(struct socket *so, struct sockopt *sopt)
 2150 {
 2151         int     error, optval;
 2152         struct  linger l;
 2153         struct  timeval tv;
 2154         u_long  val;
 2155 #ifdef MAC
 2156         struct mac extmac;
 2157 #endif
 2158 
 2159         error = 0;
 2160         if (sopt->sopt_level != SOL_SOCKET) {
 2161                 if (so->so_proto && so->so_proto->pr_ctloutput)
 2162                         return ((*so->so_proto->pr_ctloutput)
 2163                                   (so, sopt));
 2164                 error = ENOPROTOOPT;
 2165         } else {
 2166                 switch (sopt->sopt_name) {
 2167 #ifdef INET
 2168                 case SO_ACCEPTFILTER:
 2169                         error = do_setopt_accept_filter(so, sopt);
 2170                         if (error)
 2171                                 goto bad;
 2172                         break;
 2173 #endif
 2174                 case SO_LINGER:
 2175                         error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
 2176                         if (error)
 2177                                 goto bad;
 2178 
 2179                         SOCK_LOCK(so);
 2180                         so->so_linger = l.l_linger;
 2181                         if (l.l_onoff)
 2182                                 so->so_options |= SO_LINGER;
 2183                         else
 2184                                 so->so_options &= ~SO_LINGER;
 2185                         SOCK_UNLOCK(so);
 2186                         break;
 2187 
 2188                 case SO_DEBUG:
 2189                 case SO_KEEPALIVE:
 2190                 case SO_DONTROUTE:
 2191                 case SO_USELOOPBACK:
 2192                 case SO_BROADCAST:
 2193                 case SO_REUSEADDR:
 2194                 case SO_REUSEPORT:
 2195                 case SO_OOBINLINE:
 2196                 case SO_TIMESTAMP:
 2197                 case SO_BINTIME:
 2198                 case SO_NOSIGPIPE:
 2199                         error = sooptcopyin(sopt, &optval, sizeof optval,
 2200                                             sizeof optval);
 2201                         if (error)
 2202                                 goto bad;
 2203                         SOCK_LOCK(so);
 2204                         if (optval)
 2205                                 so->so_options |= sopt->sopt_name;
 2206                         else
 2207                                 so->so_options &= ~sopt->sopt_name;
 2208                         SOCK_UNLOCK(so);
 2209                         break;
 2210 
 2211                 case SO_SETFIB:
 2212                         error = sooptcopyin(sopt, &optval, sizeof optval,
 2213                                             sizeof optval);
 2214                         if (optval < 1 || optval > rt_numfibs) {
 2215                                 error = EINVAL;
 2216                                 goto bad;
 2217                         }
 2218                         if ((so->so_proto->pr_domain->dom_family == PF_INET) ||
 2219                             (so->so_proto->pr_domain->dom_family == PF_ROUTE)) {
 2220                                 so->so_fibnum = optval;
 2221                                 /* Note: ignore error */
 2222                                 if (so->so_proto && so->so_proto->pr_ctloutput)
 2223                                         (*so->so_proto->pr_ctloutput)(so, sopt);
 2224                         } else {
 2225                                 so->so_fibnum = 0;
 2226                         }
 2227                         break;
 2228                 case SO_SNDBUF:
 2229                 case SO_RCVBUF:
 2230                 case SO_SNDLOWAT:
 2231                 case SO_RCVLOWAT:
 2232                         error = sooptcopyin(sopt, &optval, sizeof optval,
 2233                                             sizeof optval);
 2234                         if (error)
 2235                                 goto bad;
 2236 
 2237                         /*
 2238                          * Values < 1 make no sense for any of these options,
 2239                          * so disallow them.
 2240                          */
 2241                         if (optval < 1) {
 2242                                 error = EINVAL;
 2243                                 goto bad;
 2244                         }
 2245 
 2246                         switch (sopt->sopt_name) {
 2247                         case SO_SNDBUF:
 2248                         case SO_RCVBUF:
 2249                                 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
 2250                                     &so->so_snd : &so->so_rcv, (u_long)optval,
 2251                                     so, curthread) == 0) {
 2252                                         error = ENOBUFS;
 2253                                         goto bad;
 2254                                 }
 2255                                 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
 2256                                     &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
 2257                                 break;
 2258 
 2259                         /*
 2260                          * Make sure the low-water is never greater than the
 2261                          * high-water.
 2262                          */
 2263                         case SO_SNDLOWAT:
 2264                                 SOCKBUF_LOCK(&so->so_snd);
 2265                                 so->so_snd.sb_lowat =
 2266                                     (optval > so->so_snd.sb_hiwat) ?
 2267                                     so->so_snd.sb_hiwat : optval;
 2268                                 SOCKBUF_UNLOCK(&so->so_snd);
 2269                                 break;
 2270                         case SO_RCVLOWAT:
 2271                                 SOCKBUF_LOCK(&so->so_rcv);
 2272                                 so->so_rcv.sb_lowat =
 2273                                     (optval > so->so_rcv.sb_hiwat) ?
 2274                                     so->so_rcv.sb_hiwat : optval;
 2275                                 SOCKBUF_UNLOCK(&so->so_rcv);
 2276                                 break;
 2277                         }
 2278                         break;
 2279 
 2280                 case SO_SNDTIMEO:
 2281                 case SO_RCVTIMEO:
 2282 #ifdef COMPAT_IA32
 2283                         if (curthread->td_proc->p_sysent == &ia32_freebsd_sysvec) {
 2284                                 struct timeval32 tv32;
 2285 
 2286                                 error = sooptcopyin(sopt, &tv32, sizeof tv32,
 2287                                     sizeof tv32);
 2288                                 CP(tv32, tv, tv_sec);
 2289                                 CP(tv32, tv, tv_usec);
 2290                         } else
 2291 #endif
 2292                                 error = sooptcopyin(sopt, &tv, sizeof tv,
 2293                                     sizeof tv);
 2294                         if (error)
 2295                                 goto bad;
 2296 
 2297                         /* assert(hz > 0); */
 2298                         if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
 2299                             tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
 2300                                 error = EDOM;
 2301                                 goto bad;
 2302                         }
 2303                         /* assert(tick > 0); */
 2304                         /* assert(ULONG_MAX - INT_MAX >= 1000000); */
 2305                         val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
 2306                         if (val > INT_MAX) {
 2307                                 error = EDOM;
 2308                                 goto bad;
 2309                         }
 2310                         if (val == 0 && tv.tv_usec != 0)
 2311                                 val = 1;
 2312 
 2313                         switch (sopt->sopt_name) {
 2314                         case SO_SNDTIMEO:
 2315                                 so->so_snd.sb_timeo = val;
 2316                                 break;
 2317                         case SO_RCVTIMEO:
 2318                                 so->so_rcv.sb_timeo = val;
 2319                                 break;
 2320                         }
 2321                         break;
 2322 
 2323                 case SO_LABEL:
 2324 #ifdef MAC
 2325                         error = sooptcopyin(sopt, &extmac, sizeof extmac,
 2326                             sizeof extmac);
 2327                         if (error)
 2328                                 goto bad;
 2329                         error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
 2330                             so, &extmac);
 2331 #else
 2332                         error = EOPNOTSUPP;
 2333 #endif
 2334                         break;
 2335 
 2336                 default:
 2337                         error = ENOPROTOOPT;
 2338                         break;
 2339                 }
 2340                 if (error == 0 && so->so_proto != NULL &&
 2341                     so->so_proto->pr_ctloutput != NULL) {
 2342                         (void) ((*so->so_proto->pr_ctloutput)
 2343                                   (so, sopt));
 2344                 }
 2345         }
 2346 bad:
 2347         return (error);
 2348 }
 2349 
 2350 /*
 2351  * Helper routine for getsockopt.
 2352  */
 2353 int
 2354 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
 2355 {
 2356         int     error;
 2357         size_t  valsize;
 2358 
 2359         error = 0;
 2360 
 2361         /*
 2362          * Documented get behavior is that we always return a value, possibly
 2363          * truncated to fit in the user's buffer.  Traditional behavior is
 2364          * that we always tell the user precisely how much we copied, rather
 2365          * than something useful like the total amount we had available for
 2366          * her.  Note that this interface is not idempotent; the entire
 2367          * answer must generated ahead of time.
 2368          */
 2369         valsize = min(len, sopt->sopt_valsize);
 2370         sopt->sopt_valsize = valsize;
 2371         if (sopt->sopt_val != NULL) {
 2372                 if (sopt->sopt_td != NULL)
 2373                         error = copyout(buf, sopt->sopt_val, valsize);
 2374                 else
 2375                         bcopy(buf, sopt->sopt_val, valsize);
 2376         }
 2377         return (error);
 2378 }
 2379 
 2380 int
 2381 sogetopt(struct socket *so, struct sockopt *sopt)
 2382 {
 2383         int     error, optval;
 2384         struct  linger l;
 2385         struct  timeval tv;
 2386 #ifdef MAC
 2387         struct mac extmac;
 2388 #endif
 2389 
 2390         error = 0;
 2391         if (sopt->sopt_level != SOL_SOCKET) {
 2392                 if (so->so_proto && so->so_proto->pr_ctloutput) {
 2393                         return ((*so->so_proto->pr_ctloutput)
 2394                                   (so, sopt));
 2395                 } else
 2396                         return (ENOPROTOOPT);
 2397         } else {
 2398                 switch (sopt->sopt_name) {
 2399 #ifdef INET
 2400                 case SO_ACCEPTFILTER:
 2401                         error = do_getopt_accept_filter(so, sopt);
 2402                         break;
 2403 #endif
 2404                 case SO_LINGER:
 2405                         SOCK_LOCK(so);
 2406                         l.l_onoff = so->so_options & SO_LINGER;
 2407                         l.l_linger = so->so_linger;
 2408                         SOCK_UNLOCK(so);
 2409                         error = sooptcopyout(sopt, &l, sizeof l);
 2410                         break;
 2411 
 2412                 case SO_USELOOPBACK:
 2413                 case SO_DONTROUTE:
 2414                 case SO_DEBUG:
 2415                 case SO_KEEPALIVE:
 2416                 case SO_REUSEADDR:
 2417                 case SO_REUSEPORT:
 2418                 case SO_BROADCAST:
 2419                 case SO_OOBINLINE:
 2420                 case SO_ACCEPTCONN:
 2421                 case SO_TIMESTAMP:
 2422                 case SO_BINTIME:
 2423                 case SO_NOSIGPIPE:
 2424                         optval = so->so_options & sopt->sopt_name;
 2425 integer:
 2426                         error = sooptcopyout(sopt, &optval, sizeof optval);
 2427                         break;
 2428 
 2429                 case SO_TYPE:
 2430                         optval = so->so_type;
 2431                         goto integer;
 2432 
 2433                 case SO_ERROR:
 2434                         SOCK_LOCK(so);
 2435                         optval = so->so_error;
 2436                         so->so_error = 0;
 2437                         SOCK_UNLOCK(so);
 2438                         goto integer;
 2439 
 2440                 case SO_SNDBUF:
 2441                         optval = so->so_snd.sb_hiwat;
 2442                         goto integer;
 2443 
 2444                 case SO_RCVBUF:
 2445                         optval = so->so_rcv.sb_hiwat;
 2446                         goto integer;
 2447 
 2448                 case SO_SNDLOWAT:
 2449                         optval = so->so_snd.sb_lowat;
 2450                         goto integer;
 2451 
 2452                 case SO_RCVLOWAT:
 2453                         optval = so->so_rcv.sb_lowat;
 2454                         goto integer;
 2455 
 2456                 case SO_SNDTIMEO:
 2457                 case SO_RCVTIMEO:
 2458                         optval = (sopt->sopt_name == SO_SNDTIMEO ?
 2459                                   so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
 2460 
 2461                         tv.tv_sec = optval / hz;
 2462                         tv.tv_usec = (optval % hz) * tick;
 2463 #ifdef COMPAT_IA32
 2464                         if (curthread->td_proc->p_sysent == &ia32_freebsd_sysvec) {
 2465                                 struct timeval32 tv32;
 2466 
 2467                                 CP(tv, tv32, tv_sec);
 2468                                 CP(tv, tv32, tv_usec);
 2469                                 error = sooptcopyout(sopt, &tv32, sizeof tv32);
 2470                         } else
 2471 #endif
 2472                                 error = sooptcopyout(sopt, &tv, sizeof tv);
 2473                         break;
 2474 
 2475                 case SO_LABEL:
 2476 #ifdef MAC
 2477                         error = sooptcopyin(sopt, &extmac, sizeof(extmac),
 2478                             sizeof(extmac));
 2479                         if (error)
 2480                                 return (error);
 2481                         error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
 2482                             so, &extmac);
 2483                         if (error)
 2484                                 return (error);
 2485                         error = sooptcopyout(sopt, &extmac, sizeof extmac);
 2486 #else
 2487                         error = EOPNOTSUPP;
 2488 #endif
 2489                         break;
 2490 
 2491                 case SO_PEERLABEL:
 2492 #ifdef MAC
 2493                         error = sooptcopyin(sopt, &extmac, sizeof(extmac),
 2494                             sizeof(extmac));
 2495                         if (error)
 2496                                 return (error);
 2497                         error = mac_getsockopt_peerlabel(
 2498                             sopt->sopt_td->td_ucred, so, &extmac);
 2499                         if (error)
 2500                                 return (error);
 2501                         error = sooptcopyout(sopt, &extmac, sizeof extmac);
 2502 #else
 2503                         error = EOPNOTSUPP;
 2504 #endif
 2505                         break;
 2506 
 2507                 case SO_LISTENQLIMIT:
 2508                         optval = so->so_qlimit;
 2509                         goto integer;
 2510 
 2511                 case SO_LISTENQLEN:
 2512                         optval = so->so_qlen;
 2513                         goto integer;
 2514 
 2515                 case SO_LISTENINCQLEN:
 2516                         optval = so->so_incqlen;
 2517                         goto integer;
 2518 
 2519                 default:
 2520                         error = ENOPROTOOPT;
 2521                         break;
 2522                 }
 2523                 return (error);
 2524         }
 2525 }
 2526 
 2527 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
 2528 int
 2529 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
 2530 {
 2531         struct mbuf *m, *m_prev;
 2532         int sopt_size = sopt->sopt_valsize;
 2533 
 2534         MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
 2535         if (m == NULL)
 2536                 return ENOBUFS;
 2537         if (sopt_size > MLEN) {
 2538                 MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
 2539                 if ((m->m_flags & M_EXT) == 0) {
 2540                         m_free(m);
 2541                         return ENOBUFS;
 2542                 }
 2543                 m->m_len = min(MCLBYTES, sopt_size);
 2544         } else {
 2545                 m->m_len = min(MLEN, sopt_size);
 2546         }
 2547         sopt_size -= m->m_len;
 2548         *mp = m;
 2549         m_prev = m;
 2550 
 2551         while (sopt_size) {
 2552                 MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
 2553                 if (m == NULL) {
 2554                         m_freem(*mp);
 2555                         return ENOBUFS;
 2556                 }
 2557                 if (sopt_size > MLEN) {
 2558                         MCLGET(m, sopt->sopt_td != NULL ? M_TRYWAIT :
 2559                             M_DONTWAIT);
 2560                         if ((m->m_flags & M_EXT) == 0) {
 2561                                 m_freem(m);
 2562                                 m_freem(*mp);
 2563                                 return ENOBUFS;
 2564                         }
 2565                         m->m_len = min(MCLBYTES, sopt_size);
 2566                 } else {
 2567                         m->m_len = min(MLEN, sopt_size);
 2568                 }
 2569                 sopt_size -= m->m_len;
 2570                 m_prev->m_next = m;
 2571                 m_prev = m;
 2572         }
 2573         return (0);
 2574 }
 2575 
 2576 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
 2577 int
 2578 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
 2579 {
 2580         struct mbuf *m0 = m;
 2581 
 2582         if (sopt->sopt_val == NULL)
 2583                 return (0);
 2584         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
 2585                 if (sopt->sopt_td != NULL) {
 2586                         int error;
 2587 
 2588                         error = copyin(sopt->sopt_val, mtod(m, char *),
 2589                                        m->m_len);
 2590                         if (error != 0) {
 2591                                 m_freem(m0);
 2592                                 return(error);
 2593                         }
 2594                 } else
 2595                         bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
 2596                 sopt->sopt_valsize -= m->m_len;
 2597                 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
 2598                 m = m->m_next;
 2599         }
 2600         if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
 2601                 panic("ip6_sooptmcopyin");
 2602         return (0);
 2603 }
 2604 
 2605 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
 2606 int
 2607 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
 2608 {
 2609         struct mbuf *m0 = m;
 2610         size_t valsize = 0;
 2611 
 2612         if (sopt->sopt_val == NULL)
 2613                 return (0);
 2614         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
 2615                 if (sopt->sopt_td != NULL) {
 2616                         int error;
 2617 
 2618                         error = copyout(mtod(m, char *), sopt->sopt_val,
 2619                                        m->m_len);
 2620                         if (error != 0) {
 2621                                 m_freem(m0);
 2622                                 return(error);
 2623                         }
 2624                 } else
 2625                         bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
 2626                sopt->sopt_valsize -= m->m_len;
 2627                sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
 2628                valsize += m->m_len;
 2629                m = m->m_next;
 2630         }
 2631         if (m != NULL) {
 2632                 /* enough soopt buffer should be given from user-land */
 2633                 m_freem(m0);
 2634                 return(EINVAL);
 2635         }
 2636         sopt->sopt_valsize = valsize;
 2637         return (0);
 2638 }
 2639 
 2640 /*
 2641  * sohasoutofband(): protocol notifies socket layer of the arrival of new
 2642  * out-of-band data, which will then notify socket consumers.
 2643  */
 2644 void
 2645 sohasoutofband(struct socket *so)
 2646 {
 2647 
 2648         if (so->so_sigio != NULL)
 2649                 pgsigio(&so->so_sigio, SIGURG, 0);
 2650         selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
 2651 }
 2652 
 2653 int
 2654 sopoll(struct socket *so, int events, struct ucred *active_cred,
 2655     struct thread *td)
 2656 {
 2657 
 2658         return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
 2659             td));
 2660 }
 2661 
 2662 int
 2663 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
 2664     struct thread *td)
 2665 {
 2666         int revents = 0;
 2667 
 2668         SOCKBUF_LOCK(&so->so_snd);
 2669         SOCKBUF_LOCK(&so->so_rcv);
 2670         if (events & (POLLIN | POLLRDNORM))
 2671                 if (soreadable(so))
 2672                         revents |= events & (POLLIN | POLLRDNORM);
 2673 
 2674         if (events & POLLINIGNEOF)
 2675                 if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
 2676                     !TAILQ_EMPTY(&so->so_comp) || so->so_error)
 2677                         revents |= POLLINIGNEOF;
 2678 
 2679         if (events & (POLLOUT | POLLWRNORM))
 2680                 if (sowriteable(so))
 2681                         revents |= events & (POLLOUT | POLLWRNORM);
 2682 
 2683         if (events & (POLLPRI | POLLRDBAND))
 2684                 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
 2685                         revents |= events & (POLLPRI | POLLRDBAND);
 2686 
 2687         if (revents == 0) {
 2688                 if (events &
 2689                     (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
 2690                      POLLRDBAND)) {
 2691                         selrecord(td, &so->so_rcv.sb_sel);
 2692                         so->so_rcv.sb_flags |= SB_SEL;
 2693                 }
 2694 
 2695                 if (events & (POLLOUT | POLLWRNORM)) {
 2696                         selrecord(td, &so->so_snd.sb_sel);
 2697                         so->so_snd.sb_flags |= SB_SEL;
 2698                 }
 2699         }
 2700 
 2701         SOCKBUF_UNLOCK(&so->so_rcv);
 2702         SOCKBUF_UNLOCK(&so->so_snd);
 2703         return (revents);
 2704 }
 2705 
 2706 int
 2707 soo_kqfilter(struct file *fp, struct knote *kn)
 2708 {
 2709         struct socket *so = kn->kn_fp->f_data;
 2710         struct sockbuf *sb;
 2711 
 2712         switch (kn->kn_filter) {
 2713         case EVFILT_READ:
 2714                 if (so->so_options & SO_ACCEPTCONN)
 2715                         kn->kn_fop = &solisten_filtops;
 2716                 else
 2717                         kn->kn_fop = &soread_filtops;
 2718                 sb = &so->so_rcv;
 2719                 break;
 2720         case EVFILT_WRITE:
 2721                 kn->kn_fop = &sowrite_filtops;
 2722                 sb = &so->so_snd;
 2723                 break;
 2724         default:
 2725                 return (EINVAL);
 2726         }
 2727 
 2728         SOCKBUF_LOCK(sb);
 2729         knlist_add(&sb->sb_sel.si_note, kn, 1);
 2730         sb->sb_flags |= SB_KNOTE;
 2731         SOCKBUF_UNLOCK(sb);
 2732         return (0);
 2733 }
 2734 
 2735 /*
 2736  * Some routines that return EOPNOTSUPP for entry points that are not
 2737  * supported by a protocol.  Fill in as needed.
 2738  */
 2739 int
 2740 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
 2741 {
 2742 
 2743         return EOPNOTSUPP;
 2744 }
 2745 
 2746 int
 2747 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
 2748 {
 2749 
 2750         return EOPNOTSUPP;
 2751 }
 2752 
 2753 int
 2754 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
 2755 {
 2756 
 2757         return EOPNOTSUPP;
 2758 }
 2759 
 2760 int
 2761 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
 2762 {
 2763 
 2764         return EOPNOTSUPP;
 2765 }
 2766 
 2767 int
 2768 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
 2769 {
 2770 
 2771         return EOPNOTSUPP;
 2772 }
 2773 
 2774 int
 2775 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
 2776     struct ifnet *ifp, struct thread *td)
 2777 {
 2778 
 2779         return EOPNOTSUPP;
 2780 }
 2781 
 2782 int
 2783 pru_disconnect_notsupp(struct socket *so)
 2784 {
 2785 
 2786         return EOPNOTSUPP;
 2787 }
 2788 
 2789 int
 2790 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
 2791 {
 2792 
 2793         return EOPNOTSUPP;
 2794 }
 2795 
 2796 int
 2797 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
 2798 {
 2799 
 2800         return EOPNOTSUPP;
 2801 }
 2802 
 2803 int
 2804 pru_rcvd_notsupp(struct socket *so, int flags)
 2805 {
 2806 
 2807         return EOPNOTSUPP;
 2808 }
 2809 
 2810 int
 2811 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
 2812 {
 2813 
 2814         return EOPNOTSUPP;
 2815 }
 2816 
 2817 int
 2818 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
 2819     struct sockaddr *addr, struct mbuf *control, struct thread *td)
 2820 {
 2821 
 2822         return EOPNOTSUPP;
 2823 }
 2824 
 2825 /*
 2826  * This isn't really a ``null'' operation, but it's the default one and
 2827  * doesn't do anything destructive.
 2828  */
 2829 int
 2830 pru_sense_null(struct socket *so, struct stat *sb)
 2831 {
 2832 
 2833         sb->st_blksize = so->so_snd.sb_hiwat;
 2834         return 0;
 2835 }
 2836 
 2837 int
 2838 pru_shutdown_notsupp(struct socket *so)
 2839 {
 2840 
 2841         return EOPNOTSUPP;
 2842 }
 2843 
 2844 int
 2845 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
 2846 {
 2847 
 2848         return EOPNOTSUPP;
 2849 }
 2850 
 2851 int
 2852 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
 2853     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
 2854 {
 2855 
 2856         return EOPNOTSUPP;
 2857 }
 2858 
 2859 int
 2860 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
 2861     struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
 2862 {
 2863 
 2864         return EOPNOTSUPP;
 2865 }
 2866 
 2867 int
 2868 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
 2869     struct thread *td)
 2870 {
 2871 
 2872         return EOPNOTSUPP;
 2873 }
 2874 
 2875 static void
 2876 filt_sordetach(struct knote *kn)
 2877 {
 2878         struct socket *so = kn->kn_fp->f_data;
 2879 
 2880         SOCKBUF_LOCK(&so->so_rcv);
 2881         knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
 2882         if (knlist_empty(&so->so_rcv.sb_sel.si_note))
 2883                 so->so_rcv.sb_flags &= ~SB_KNOTE;
 2884         SOCKBUF_UNLOCK(&so->so_rcv);
 2885 }
 2886 
 2887 /*ARGSUSED*/
 2888 static int
 2889 filt_soread(struct knote *kn, long hint)
 2890 {
 2891         struct socket *so;
 2892 
 2893         so = kn->kn_fp->f_data;
 2894         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
 2895 
 2896         kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
 2897         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
 2898                 kn->kn_flags |= EV_EOF;
 2899                 kn->kn_fflags = so->so_error;
 2900                 return (1);
 2901         } else if (so->so_error)        /* temporary udp error */
 2902                 return (1);
 2903         else if (kn->kn_sfflags & NOTE_LOWAT)
 2904                 return (kn->kn_data >= kn->kn_sdata);
 2905         else
 2906                 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
 2907 }
 2908 
 2909 static void
 2910 filt_sowdetach(struct knote *kn)
 2911 {
 2912         struct socket *so = kn->kn_fp->f_data;
 2913 
 2914         SOCKBUF_LOCK(&so->so_snd);
 2915         knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
 2916         if (knlist_empty(&so->so_snd.sb_sel.si_note))
 2917                 so->so_snd.sb_flags &= ~SB_KNOTE;
 2918         SOCKBUF_UNLOCK(&so->so_snd);
 2919 }
 2920 
 2921 /*ARGSUSED*/
 2922 static int
 2923 filt_sowrite(struct knote *kn, long hint)
 2924 {
 2925         struct socket *so;
 2926 
 2927         so = kn->kn_fp->f_data;
 2928         SOCKBUF_LOCK_ASSERT(&so->so_snd);
 2929         kn->kn_data = sbspace(&so->so_snd);
 2930         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
 2931                 kn->kn_flags |= EV_EOF;
 2932                 kn->kn_fflags = so->so_error;
 2933                 return (1);
 2934         } else if (so->so_error)        /* temporary udp error */
 2935                 return (1);
 2936         else if (((so->so_state & SS_ISCONNECTED) == 0) &&
 2937             (so->so_proto->pr_flags & PR_CONNREQUIRED))
 2938                 return (0);
 2939         else if (kn->kn_sfflags & NOTE_LOWAT)
 2940                 return (kn->kn_data >= kn->kn_sdata);
 2941         else
 2942                 return (kn->kn_data >= so->so_snd.sb_lowat);
 2943 }
 2944 
 2945 /*ARGSUSED*/
 2946 static int
 2947 filt_solisten(struct knote *kn, long hint)
 2948 {
 2949         struct socket *so = kn->kn_fp->f_data;
 2950 
 2951         kn->kn_data = so->so_qlen;
 2952         return (! TAILQ_EMPTY(&so->so_comp));
 2953 }
 2954 
 2955 int
 2956 socheckuid(struct socket *so, uid_t uid)
 2957 {
 2958 
 2959         if (so == NULL)
 2960                 return (EPERM);
 2961         if (so->so_cred->cr_uid != uid)
 2962                 return (EPERM);
 2963         return (0);
 2964 }
 2965 
 2966 static int
 2967 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
 2968 {
 2969         int error;
 2970         int val;
 2971 
 2972         val = somaxconn;
 2973         error = sysctl_handle_int(oidp, &val, 0, req);
 2974         if (error || !req->newptr )
 2975                 return (error);
 2976 
 2977         if (val < 1 || val > USHRT_MAX)
 2978                 return (EINVAL);
 2979 
 2980         somaxconn = val;
 2981         return (0);
 2982 }
 2983 
 2984 /*
 2985  * These functions are used by protocols to notify the socket layer (and its
 2986  * consumers) of state changes in the sockets driven by protocol-side events.
 2987  */
 2988 
 2989 /*
 2990  * Procedures to manipulate state flags of socket and do appropriate wakeups.
 2991  *
 2992  * Normal sequence from the active (originating) side is that
 2993  * soisconnecting() is called during processing of connect() call, resulting
 2994  * in an eventual call to soisconnected() if/when the connection is
 2995  * established.  When the connection is torn down soisdisconnecting() is
 2996  * called during processing of disconnect() call, and soisdisconnected() is
 2997  * called when the connection to the peer is totally severed.  The semantics
 2998  * of these routines are such that connectionless protocols can call
 2999  * soisconnected() and soisdisconnected() only, bypassing the in-progress
 3000  * calls when setting up a ``connection'' takes no time.
 3001  *
 3002  * From the passive side, a socket is created with two queues of sockets:
 3003  * so_incomp for connections in progress and so_comp for connections already
 3004  * made and awaiting user acceptance.  As a protocol is preparing incoming
 3005  * connections, it creates a socket structure queued on so_incomp by calling
 3006  * sonewconn().  When the connection is established, soisconnected() is
 3007  * called, and transfers the socket structure to so_comp, making it available
 3008  * to accept().
 3009  *
 3010  * If a socket is closed with sockets on either so_incomp or so_comp, these
 3011  * sockets are dropped.
 3012  *
 3013  * If higher-level protocols are implemented in the kernel, the wakeups done
 3014  * here will sometimes cause software-interrupt process scheduling.
 3015  */
 3016 void
 3017 soisconnecting(struct socket *so)
 3018 {
 3019 
 3020         SOCK_LOCK(so);
 3021         so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
 3022         so->so_state |= SS_ISCONNECTING;
 3023         SOCK_UNLOCK(so);
 3024 }
 3025 
 3026 void
 3027 soisconnected(struct socket *so)
 3028 {
 3029         struct socket *head;
 3030 
 3031         ACCEPT_LOCK();
 3032         SOCK_LOCK(so);
 3033         so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
 3034         so->so_state |= SS_ISCONNECTED;
 3035         head = so->so_head;
 3036         if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
 3037                 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
 3038                         SOCK_UNLOCK(so);
 3039                         TAILQ_REMOVE(&head->so_incomp, so, so_list);
 3040                         head->so_incqlen--;
 3041                         so->so_qstate &= ~SQ_INCOMP;
 3042                         TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
 3043                         head->so_qlen++;
 3044                         so->so_qstate |= SQ_COMP;
 3045                         ACCEPT_UNLOCK();
 3046                         sorwakeup(head);
 3047                         wakeup_one(&head->so_timeo);
 3048                 } else {
 3049                         ACCEPT_UNLOCK();
 3050                         so->so_upcall =
 3051                             head->so_accf->so_accept_filter->accf_callback;
 3052                         so->so_upcallarg = head->so_accf->so_accept_filter_arg;
 3053                         so->so_rcv.sb_flags |= SB_UPCALL;
 3054                         so->so_options &= ~SO_ACCEPTFILTER;
 3055                         SOCK_UNLOCK(so);
 3056                         so->so_upcall(so, so->so_upcallarg, M_DONTWAIT);
 3057                 }
 3058                 return;
 3059         }
 3060         SOCK_UNLOCK(so);
 3061         ACCEPT_UNLOCK();
 3062         wakeup(&so->so_timeo);
 3063         sorwakeup(so);
 3064         sowwakeup(so);
 3065 }
 3066 
 3067 void
 3068 soisdisconnecting(struct socket *so)
 3069 {
 3070 
 3071         /*
 3072          * Note: This code assumes that SOCK_LOCK(so) and
 3073          * SOCKBUF_LOCK(&so->so_rcv) are the same.
 3074          */
 3075         SOCKBUF_LOCK(&so->so_rcv);
 3076         so->so_state &= ~SS_ISCONNECTING;
 3077         so->so_state |= SS_ISDISCONNECTING;
 3078         so->so_rcv.sb_state |= SBS_CANTRCVMORE;
 3079         sorwakeup_locked(so);
 3080         SOCKBUF_LOCK(&so->so_snd);
 3081         so->so_snd.sb_state |= SBS_CANTSENDMORE;
 3082         sowwakeup_locked(so);
 3083         wakeup(&so->so_timeo);
 3084 }
 3085 
 3086 void
 3087 soisdisconnected(struct socket *so)
 3088 {
 3089 
 3090         /*
 3091          * Note: This code assumes that SOCK_LOCK(so) and
 3092          * SOCKBUF_LOCK(&so->so_rcv) are the same.
 3093          */
 3094         SOCKBUF_LOCK(&so->so_rcv);
 3095         so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
 3096         so->so_state |= SS_ISDISCONNECTED;
 3097         so->so_rcv.sb_state |= SBS_CANTRCVMORE;
 3098         sorwakeup_locked(so);
 3099         SOCKBUF_LOCK(&so->so_snd);
 3100         so->so_snd.sb_state |= SBS_CANTSENDMORE;
 3101         sbdrop_locked(&so->so_snd, so->so_snd.sb_cc);
 3102         sowwakeup_locked(so);
 3103         wakeup(&so->so_timeo);
 3104 }
 3105 
 3106 /*
 3107  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
 3108  */
 3109 struct sockaddr *
 3110 sodupsockaddr(const struct sockaddr *sa, int mflags)
 3111 {
 3112         struct sockaddr *sa2;
 3113 
 3114         sa2 = malloc(sa->sa_len, M_SONAME, mflags);
 3115         if (sa2)
 3116                 bcopy(sa, sa2, sa->sa_len);
 3117         return sa2;
 3118 }
 3119 
 3120 /*
 3121  * Create an external-format (``xsocket'') structure using the information in
 3122  * the kernel-format socket structure pointed to by so.  This is done to
 3123  * reduce the spew of irrelevant information over this interface, to isolate
 3124  * user code from changes in the kernel structure, and potentially to provide
 3125  * information-hiding if we decide that some of this information should be
 3126  * hidden from users.
 3127  */
 3128 void
 3129 sotoxsocket(struct socket *so, struct xsocket *xso)
 3130 {
 3131 
 3132         xso->xso_len = sizeof *xso;
 3133         xso->xso_so = so;
 3134         xso->so_type = so->so_type;
 3135         xso->so_options = so->so_options;
 3136         xso->so_linger = so->so_linger;
 3137         xso->so_state = so->so_state;
 3138         xso->so_pcb = so->so_pcb;
 3139         xso->xso_protocol = so->so_proto->pr_protocol;
 3140         xso->xso_family = so->so_proto->pr_domain->dom_family;
 3141         xso->so_qlen = so->so_qlen;
 3142         xso->so_incqlen = so->so_incqlen;
 3143         xso->so_qlimit = so->so_qlimit;
 3144         xso->so_timeo = so->so_timeo;
 3145         xso->so_error = so->so_error;
 3146         xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
 3147         xso->so_oobmark = so->so_oobmark;
 3148         sbtoxsockbuf(&so->so_snd, &xso->so_snd);
 3149         sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
 3150         xso->so_uid = so->so_cred->cr_uid;
 3151 }
 3152 
 3153 
 3154 /*
 3155  * Socket accessor functions to provide external consumers with
 3156  * a safe interface to socket state
 3157  *
 3158  */
 3159 
 3160 void
 3161 so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *), void *arg)
 3162 {
 3163         
 3164         TAILQ_FOREACH(so, &so->so_comp, so_list)
 3165                 func(so, arg);
 3166 }
 3167 
 3168 struct sockbuf *
 3169 so_sockbuf_rcv(struct socket *so)
 3170 {
 3171 
 3172         return (&so->so_rcv);
 3173 }
 3174 
 3175 struct sockbuf *
 3176 so_sockbuf_snd(struct socket *so)
 3177 {
 3178 
 3179         return (&so->so_snd);
 3180 }
 3181 
 3182 int
 3183 so_state_get(const struct socket *so)
 3184 {
 3185 
 3186         return (so->so_state);
 3187 }
 3188 
 3189 void
 3190 so_state_set(struct socket *so, int val)
 3191 {
 3192 
 3193         so->so_state = val;
 3194 }
 3195 
 3196 int
 3197 so_options_get(const struct socket *so)
 3198 {
 3199 
 3200         return (so->so_options);
 3201 }
 3202 
 3203 void
 3204 so_options_set(struct socket *so, int val)
 3205 {
 3206 
 3207         so->so_options = val;
 3208 }
 3209 
 3210 int
 3211 so_error_get(const struct socket *so)
 3212 {
 3213 
 3214         return (so->so_error);
 3215 }
 3216 
 3217 void
 3218 so_error_set(struct socket *so, int val)
 3219 {
 3220 
 3221         so->so_error = val;
 3222 }
 3223 
 3224 int
 3225 so_linger_get(const struct socket *so)
 3226 {
 3227 
 3228         return (so->so_linger);
 3229 }
 3230 
 3231 void
 3232 so_linger_set(struct socket *so, int val)
 3233 {
 3234 
 3235         so->so_linger = val;
 3236 }
 3237 
 3238 struct protosw *
 3239 so_protosw_get(const struct socket *so)
 3240 {
 3241 
 3242         return (so->so_proto);
 3243 }
 3244 
 3245 void
 3246 so_protosw_set(struct socket *so, struct protosw *val)
 3247 {
 3248 
 3249         so->so_proto = val;
 3250 }
 3251 
 3252 void
 3253 so_sorwakeup(struct socket *so)
 3254 {
 3255 
 3256         sorwakeup(so);
 3257 }
 3258 
 3259 void
 3260 so_sowwakeup(struct socket *so)
 3261 {
 3262 
 3263         sowwakeup(so);
 3264 }
 3265 
 3266 void
 3267 so_sorwakeup_locked(struct socket *so)
 3268 {
 3269 
 3270         sorwakeup_locked(so);
 3271 }
 3272 
 3273 void
 3274 so_sowwakeup_locked(struct socket *so)
 3275 {
 3276 
 3277         sowwakeup_locked(so);
 3278 }
 3279 
 3280 void
 3281 so_lock(struct socket *so)
 3282 {
 3283         SOCK_LOCK(so);
 3284 }
 3285 
 3286 void
 3287 so_unlock(struct socket *so)
 3288 {
 3289         SOCK_UNLOCK(so);
 3290 }

Cache object: b3513973a9256269de7f14fe527ae1fe


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.