The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


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

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

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
    3  *      The Regents of the University of California.
    4  * Copyright (c) 2004-2009 Robert N. M. Watson
    5  * All rights reserved.
    6  *
    7  * Redistribution and use in source and binary forms, with or without
    8  * modification, are permitted provided that the following conditions
    9  * are met:
   10  * 1. Redistributions of source code must retain the above copyright
   11  *    notice, this list of conditions and the following disclaimer.
   12  * 2. Redistributions in binary form must reproduce the above copyright
   13  *    notice, this list of conditions and the following disclaimer in the
   14  *    documentation and/or other materials provided with the distribution.
   15  * 4. Neither the name of the University nor the names of its contributors
   16  *    may be used to endorse or promote products derived from this software
   17  *    without specific prior written permission.
   18  *
   19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   29  * SUCH DAMAGE.
   30  *
   31  *      From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
   32  */
   33 
   34 /*
   35  * UNIX Domain (Local) Sockets
   36  *
   37  * This is an implementation of UNIX (local) domain sockets.  Each socket has
   38  * an associated struct unpcb (UNIX protocol control block).  Stream sockets
   39  * may be connected to 0 or 1 other socket.  Datagram sockets may be
   40  * connected to 0, 1, or many other sockets.  Sockets may be created and
   41  * connected in pairs (socketpair(2)), or bound/connected to using the file
   42  * system name space.  For most purposes, only the receive socket buffer is
   43  * used, as sending on one socket delivers directly to the receive socket
   44  * buffer of a second socket.
   45  *
   46  * The implementation is substantially complicated by the fact that
   47  * "ancillary data", such as file descriptors or credentials, may be passed
   48  * across UNIX domain sockets.  The potential for passing UNIX domain sockets
   49  * over other UNIX domain sockets requires the implementation of a simple
   50  * garbage collector to find and tear down cycles of disconnected sockets.
   51  *
   52  * TODO:
   53  *      RDM
   54  *      rethink name space problems
   55  *      need a proper out-of-band
   56  */
   57 
   58 #include <sys/cdefs.h>
   59 __FBSDID("$FreeBSD$");
   60 
   61 #include "opt_ddb.h"
   62 
   63 #include <sys/param.h>
   64 #include <sys/capsicum.h>
   65 #include <sys/domain.h>
   66 #include <sys/fcntl.h>
   67 #include <sys/malloc.h>         /* XXX must be before <sys/file.h> */
   68 #include <sys/eventhandler.h>
   69 #include <sys/file.h>
   70 #include <sys/filedesc.h>
   71 #include <sys/kernel.h>
   72 #include <sys/lock.h>
   73 #include <sys/mbuf.h>
   74 #include <sys/mount.h>
   75 #include <sys/mutex.h>
   76 #include <sys/namei.h>
   77 #include <sys/proc.h>
   78 #include <sys/protosw.h>
   79 #include <sys/queue.h>
   80 #include <sys/resourcevar.h>
   81 #include <sys/rwlock.h>
   82 #include <sys/socket.h>
   83 #include <sys/socketvar.h>
   84 #include <sys/signalvar.h>
   85 #include <sys/stat.h>
   86 #include <sys/sx.h>
   87 #include <sys/sysctl.h>
   88 #include <sys/systm.h>
   89 #include <sys/taskqueue.h>
   90 #include <sys/un.h>
   91 #include <sys/unpcb.h>
   92 #include <sys/vnode.h>
   93 
   94 #include <net/vnet.h>
   95 
   96 #ifdef DDB
   97 #include <ddb/ddb.h>
   98 #endif
   99 
  100 #include <security/mac/mac_framework.h>
  101 
  102 #include <vm/uma.h>
  103 
  104 MALLOC_DECLARE(M_FILECAPS);
  105 
  106 /*
  107  * Locking key:
  108  * (l)  Locked using list lock
  109  * (g)  Locked using linkage lock
  110  */
  111 
  112 static uma_zone_t       unp_zone;
  113 static unp_gen_t        unp_gencnt;     /* (l) */
  114 static u_int            unp_count;      /* (l) Count of local sockets. */
  115 static ino_t            unp_ino;        /* Prototype for fake inode numbers. */
  116 static int              unp_rights;     /* (g) File descriptors in flight. */
  117 static struct unp_head  unp_shead;      /* (l) List of stream sockets. */
  118 static struct unp_head  unp_dhead;      /* (l) List of datagram sockets. */
  119 static struct unp_head  unp_sphead;     /* (l) List of seqpacket sockets. */
  120 
  121 struct unp_defer {
  122         SLIST_ENTRY(unp_defer) ud_link;
  123         struct file *ud_fp;
  124 };
  125 static SLIST_HEAD(, unp_defer) unp_defers;
  126 static int unp_defers_count;
  127 
  128 static const struct sockaddr    sun_noname = { sizeof(sun_noname), AF_LOCAL };
  129 
  130 /*
  131  * Garbage collection of cyclic file descriptor/socket references occurs
  132  * asynchronously in a taskqueue context in order to avoid recursion and
  133  * reentrance in the UNIX domain socket, file descriptor, and socket layer
  134  * code.  See unp_gc() for a full description.
  135  */
  136 static struct timeout_task unp_gc_task;
  137 
  138 /*
  139  * The close of unix domain sockets attached as SCM_RIGHTS is
  140  * postponed to the taskqueue, to avoid arbitrary recursion depth.
  141  * The attached sockets might have another sockets attached.
  142  */
  143 static struct task      unp_defer_task;
  144 
  145 /*
  146  * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
  147  * stream sockets, although the total for sender and receiver is actually
  148  * only PIPSIZ.
  149  *
  150  * Datagram sockets really use the sendspace as the maximum datagram size,
  151  * and don't really want to reserve the sendspace.  Their recvspace should be
  152  * large enough for at least one max-size datagram plus address.
  153  */
  154 #ifndef PIPSIZ
  155 #define PIPSIZ  8192
  156 #endif
  157 static u_long   unpst_sendspace = PIPSIZ;
  158 static u_long   unpst_recvspace = PIPSIZ;
  159 static u_long   unpdg_sendspace = 2*1024;       /* really max datagram size */
  160 static u_long   unpdg_recvspace = 4*1024;
  161 static u_long   unpsp_sendspace = PIPSIZ;       /* really max datagram size */
  162 static u_long   unpsp_recvspace = PIPSIZ;
  163 
  164 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
  165 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0,
  166     "SOCK_STREAM");
  167 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
  168 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, CTLFLAG_RW, 0,
  169     "SOCK_SEQPACKET");
  170 
  171 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
  172            &unpst_sendspace, 0, "Default stream send space.");
  173 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
  174            &unpst_recvspace, 0, "Default stream receive space.");
  175 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
  176            &unpdg_sendspace, 0, "Default datagram send space.");
  177 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
  178            &unpdg_recvspace, 0, "Default datagram receive space.");
  179 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
  180            &unpsp_sendspace, 0, "Default seqpacket send space.");
  181 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
  182            &unpsp_recvspace, 0, "Default seqpacket receive space.");
  183 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
  184     "File descriptors in flight.");
  185 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
  186     &unp_defers_count, 0,
  187     "File descriptors deferred to taskqueue for close.");
  188 
  189 /*
  190  * Locking and synchronization:
  191  *
  192  * Three types of locks exit in the local domain socket implementation: a
  193  * global list mutex, a global linkage rwlock, and per-unpcb mutexes.  Of the
  194  * global locks, the list lock protects the socket count, global generation
  195  * number, and stream/datagram global lists.  The linkage lock protects the
  196  * interconnection of unpcbs, the v_socket and unp_vnode pointers, and can be
  197  * held exclusively over the acquisition of multiple unpcb locks to prevent
  198  * deadlock.
  199  *
  200  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
  201  * allocated in pru_attach() and freed in pru_detach().  The validity of that
  202  * pointer is an invariant, so no lock is required to dereference the so_pcb
  203  * pointer if a valid socket reference is held by the caller.  In practice,
  204  * this is always true during operations performed on a socket.  Each unpcb
  205  * has a back-pointer to its socket, unp_socket, which will be stable under
  206  * the same circumstances.
  207  *
  208  * This pointer may only be safely dereferenced as long as a valid reference
  209  * to the unpcb is held.  Typically, this reference will be from the socket,
  210  * or from another unpcb when the referring unpcb's lock is held (in order
  211  * that the reference not be invalidated during use).  For example, to follow
  212  * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
  213  * as unp_socket remains valid as long as the reference to unp_conn is valid.
  214  *
  215  * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx.  Individual
  216  * atomic reads without the lock may be performed "lockless", but more
  217  * complex reads and read-modify-writes require the mutex to be held.  No
  218  * lock order is defined between unpcb locks -- multiple unpcb locks may be
  219  * acquired at the same time only when holding the linkage rwlock
  220  * exclusively, which prevents deadlocks.
  221  *
  222  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
  223  * protocols, bind() is a non-atomic operation, and connect() requires
  224  * potential sleeping in the protocol, due to potentially waiting on local or
  225  * distributed file systems.  We try to separate "lookup" operations, which
  226  * may sleep, and the IPC operations themselves, which typically can occur
  227  * with relative atomicity as locks can be held over the entire operation.
  228  *
  229  * Another tricky issue is simultaneous multi-threaded or multi-process
  230  * access to a single UNIX domain socket.  These are handled by the flags
  231  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
  232  * binding, both of which involve dropping UNIX domain socket locks in order
  233  * to perform namei() and other file system operations.
  234  */
  235 static struct rwlock    unp_link_rwlock;
  236 static struct mtx       unp_list_lock;
  237 static struct mtx       unp_defers_lock;
  238 
  239 #define UNP_LINK_LOCK_INIT()            rw_init(&unp_link_rwlock,       \
  240                                             "unp_link_rwlock")
  241 
  242 #define UNP_LINK_LOCK_ASSERT()  rw_assert(&unp_link_rwlock,     \
  243                                             RA_LOCKED)
  244 #define UNP_LINK_UNLOCK_ASSERT()        rw_assert(&unp_link_rwlock,     \
  245                                             RA_UNLOCKED)
  246 
  247 #define UNP_LINK_RLOCK()                rw_rlock(&unp_link_rwlock)
  248 #define UNP_LINK_RUNLOCK()              rw_runlock(&unp_link_rwlock)
  249 #define UNP_LINK_WLOCK()                rw_wlock(&unp_link_rwlock)
  250 #define UNP_LINK_WUNLOCK()              rw_wunlock(&unp_link_rwlock)
  251 #define UNP_LINK_WLOCK_ASSERT()         rw_assert(&unp_link_rwlock,     \
  252                                             RA_WLOCKED)
  253 
  254 #define UNP_LIST_LOCK_INIT()            mtx_init(&unp_list_lock,        \
  255                                             "unp_list_lock", NULL, MTX_DEF)
  256 #define UNP_LIST_LOCK()                 mtx_lock(&unp_list_lock)
  257 #define UNP_LIST_UNLOCK()               mtx_unlock(&unp_list_lock)
  258 
  259 #define UNP_DEFERRED_LOCK_INIT()        mtx_init(&unp_defers_lock, \
  260                                             "unp_defer", NULL, MTX_DEF)
  261 #define UNP_DEFERRED_LOCK()             mtx_lock(&unp_defers_lock)
  262 #define UNP_DEFERRED_UNLOCK()           mtx_unlock(&unp_defers_lock)
  263 
  264 #define UNP_PCB_LOCK_INIT(unp)          mtx_init(&(unp)->unp_mtx,       \
  265                                             "unp_mtx", "unp_mtx",       \
  266                                             MTX_DUPOK|MTX_DEF|MTX_RECURSE)
  267 #define UNP_PCB_LOCK_DESTROY(unp)       mtx_destroy(&(unp)->unp_mtx)
  268 #define UNP_PCB_LOCK(unp)               mtx_lock(&(unp)->unp_mtx)
  269 #define UNP_PCB_UNLOCK(unp)             mtx_unlock(&(unp)->unp_mtx)
  270 #define UNP_PCB_LOCK_ASSERT(unp)        mtx_assert(&(unp)->unp_mtx, MA_OWNED)
  271 
  272 static int      uipc_connect2(struct socket *, struct socket *);
  273 static int      uipc_ctloutput(struct socket *, struct sockopt *);
  274 static int      unp_connect(struct socket *, struct sockaddr *,
  275                     struct thread *);
  276 static int      unp_connectat(int, struct socket *, struct sockaddr *,
  277                     struct thread *);
  278 static int      unp_connect2(struct socket *so, struct socket *so2, int);
  279 static void     unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
  280 static void     unp_dispose(struct mbuf *);
  281 static void     unp_shutdown(struct unpcb *);
  282 static void     unp_drop(struct unpcb *, int);
  283 static void     unp_gc(__unused void *, int);
  284 static void     unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
  285 static void     unp_discard(struct file *);
  286 static void     unp_freerights(struct filedescent **, int);
  287 static void     unp_init(void);
  288 static int      unp_internalize(struct mbuf **, struct thread *);
  289 static void     unp_internalize_fp(struct file *);
  290 static int      unp_externalize(struct mbuf *, struct mbuf **, int);
  291 static int      unp_externalize_fp(struct file *);
  292 static struct mbuf      *unp_addsockcred(struct thread *, struct mbuf *);
  293 static void     unp_process_defers(void * __unused, int);
  294 
  295 /*
  296  * Definitions of protocols supported in the LOCAL domain.
  297  */
  298 static struct domain localdomain;
  299 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
  300 static struct pr_usrreqs uipc_usrreqs_seqpacket;
  301 static struct protosw localsw[] = {
  302 {
  303         .pr_type =              SOCK_STREAM,
  304         .pr_domain =            &localdomain,
  305         .pr_flags =             PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
  306         .pr_ctloutput =         &uipc_ctloutput,
  307         .pr_usrreqs =           &uipc_usrreqs_stream
  308 },
  309 {
  310         .pr_type =              SOCK_DGRAM,
  311         .pr_domain =            &localdomain,
  312         .pr_flags =             PR_ATOMIC|PR_ADDR|PR_RIGHTS,
  313         .pr_ctloutput =         &uipc_ctloutput,
  314         .pr_usrreqs =           &uipc_usrreqs_dgram
  315 },
  316 {
  317         .pr_type =              SOCK_SEQPACKET,
  318         .pr_domain =            &localdomain,
  319 
  320         /*
  321          * XXXRW: For now, PR_ADDR because soreceive will bump into them
  322          * due to our use of sbappendaddr.  A new sbappend variants is needed
  323          * that supports both atomic record writes and control data.
  324          */
  325         .pr_flags =             PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
  326                                     PR_RIGHTS,
  327         .pr_ctloutput =         &uipc_ctloutput,
  328         .pr_usrreqs =           &uipc_usrreqs_seqpacket,
  329 },
  330 };
  331 
  332 static struct domain localdomain = {
  333         .dom_family =           AF_LOCAL,
  334         .dom_name =             "local",
  335         .dom_init =             unp_init,
  336         .dom_externalize =      unp_externalize,
  337         .dom_dispose =          unp_dispose,
  338         .dom_protosw =          localsw,
  339         .dom_protoswNPROTOSW =  &localsw[sizeof(localsw)/sizeof(localsw[0])]
  340 };
  341 DOMAIN_SET(local);
  342 
  343 static void
  344 uipc_abort(struct socket *so)
  345 {
  346         struct unpcb *unp, *unp2;
  347 
  348         unp = sotounpcb(so);
  349         KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
  350 
  351         UNP_LINK_WLOCK();
  352         UNP_PCB_LOCK(unp);
  353         unp2 = unp->unp_conn;
  354         if (unp2 != NULL) {
  355                 UNP_PCB_LOCK(unp2);
  356                 unp_drop(unp2, ECONNABORTED);
  357                 UNP_PCB_UNLOCK(unp2);
  358         }
  359         UNP_PCB_UNLOCK(unp);
  360         UNP_LINK_WUNLOCK();
  361 }
  362 
  363 static int
  364 uipc_accept(struct socket *so, struct sockaddr **nam)
  365 {
  366         struct unpcb *unp, *unp2;
  367         const struct sockaddr *sa;
  368 
  369         /*
  370          * Pass back name of connected socket, if it was bound and we are
  371          * still connected (our peer may have closed already!).
  372          */
  373         unp = sotounpcb(so);
  374         KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
  375 
  376         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
  377         UNP_LINK_RLOCK();
  378         unp2 = unp->unp_conn;
  379         if (unp2 != NULL && unp2->unp_addr != NULL) {
  380                 UNP_PCB_LOCK(unp2);
  381                 sa = (struct sockaddr *) unp2->unp_addr;
  382                 bcopy(sa, *nam, sa->sa_len);
  383                 UNP_PCB_UNLOCK(unp2);
  384         } else {
  385                 sa = &sun_noname;
  386                 bcopy(sa, *nam, sa->sa_len);
  387         }
  388         UNP_LINK_RUNLOCK();
  389         return (0);
  390 }
  391 
  392 static int
  393 uipc_attach(struct socket *so, int proto, struct thread *td)
  394 {
  395         u_long sendspace, recvspace;
  396         struct unpcb *unp;
  397         int error;
  398 
  399         KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
  400         if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
  401                 switch (so->so_type) {
  402                 case SOCK_STREAM:
  403                         sendspace = unpst_sendspace;
  404                         recvspace = unpst_recvspace;
  405                         break;
  406 
  407                 case SOCK_DGRAM:
  408                         sendspace = unpdg_sendspace;
  409                         recvspace = unpdg_recvspace;
  410                         break;
  411 
  412                 case SOCK_SEQPACKET:
  413                         sendspace = unpsp_sendspace;
  414                         recvspace = unpsp_recvspace;
  415                         break;
  416 
  417                 default:
  418                         panic("uipc_attach");
  419                 }
  420                 error = soreserve(so, sendspace, recvspace);
  421                 if (error)
  422                         return (error);
  423         }
  424         unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
  425         if (unp == NULL)
  426                 return (ENOBUFS);
  427         LIST_INIT(&unp->unp_refs);
  428         UNP_PCB_LOCK_INIT(unp);
  429         unp->unp_socket = so;
  430         so->so_pcb = unp;
  431         unp->unp_refcount = 1;
  432         if (so->so_head != NULL)
  433                 unp->unp_flags |= UNP_NASCENT;
  434 
  435         UNP_LIST_LOCK();
  436         unp->unp_gencnt = ++unp_gencnt;
  437         unp_count++;
  438         switch (so->so_type) {
  439         case SOCK_STREAM:
  440                 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
  441                 break;
  442 
  443         case SOCK_DGRAM:
  444                 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
  445                 break;
  446 
  447         case SOCK_SEQPACKET:
  448                 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
  449                 break;
  450 
  451         default:
  452                 panic("uipc_attach");
  453         }
  454         UNP_LIST_UNLOCK();
  455 
  456         return (0);
  457 }
  458 
  459 static int
  460 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
  461 {
  462         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
  463         struct vattr vattr;
  464         int error, namelen;
  465         struct nameidata nd;
  466         struct unpcb *unp;
  467         struct vnode *vp;
  468         struct mount *mp;
  469         cap_rights_t rights;
  470         char *buf;
  471 
  472         if (nam->sa_family != AF_UNIX)
  473                 return (EAFNOSUPPORT);
  474 
  475         unp = sotounpcb(so);
  476         KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
  477 
  478         if (soun->sun_len > sizeof(struct sockaddr_un))
  479                 return (EINVAL);
  480         namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
  481         if (namelen <= 0)
  482                 return (EINVAL);
  483 
  484         /*
  485          * We don't allow simultaneous bind() calls on a single UNIX domain
  486          * socket, so flag in-progress operations, and return an error if an
  487          * operation is already in progress.
  488          *
  489          * Historically, we have not allowed a socket to be rebound, so this
  490          * also returns an error.  Not allowing re-binding simplifies the
  491          * implementation and avoids a great many possible failure modes.
  492          */
  493         UNP_PCB_LOCK(unp);
  494         if (unp->unp_vnode != NULL) {
  495                 UNP_PCB_UNLOCK(unp);
  496                 return (EINVAL);
  497         }
  498         if (unp->unp_flags & UNP_BINDING) {
  499                 UNP_PCB_UNLOCK(unp);
  500                 return (EALREADY);
  501         }
  502         unp->unp_flags |= UNP_BINDING;
  503         UNP_PCB_UNLOCK(unp);
  504 
  505         buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
  506         bcopy(soun->sun_path, buf, namelen);
  507         buf[namelen] = 0;
  508 
  509 restart:
  510         NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
  511             UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
  512 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
  513         error = namei(&nd);
  514         if (error)
  515                 goto error;
  516         vp = nd.ni_vp;
  517         if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
  518                 NDFREE(&nd, NDF_ONLY_PNBUF);
  519                 if (nd.ni_dvp == vp)
  520                         vrele(nd.ni_dvp);
  521                 else
  522                         vput(nd.ni_dvp);
  523                 if (vp != NULL) {
  524                         vrele(vp);
  525                         error = EADDRINUSE;
  526                         goto error;
  527                 }
  528                 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
  529                 if (error)
  530                         goto error;
  531                 goto restart;
  532         }
  533         VATTR_NULL(&vattr);
  534         vattr.va_type = VSOCK;
  535         vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
  536 #ifdef MAC
  537         error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
  538             &vattr);
  539 #endif
  540         if (error == 0)
  541                 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
  542         NDFREE(&nd, NDF_ONLY_PNBUF);
  543         vput(nd.ni_dvp);
  544         if (error) {
  545                 vn_finished_write(mp);
  546                 goto error;
  547         }
  548         vp = nd.ni_vp;
  549         ASSERT_VOP_ELOCKED(vp, "uipc_bind");
  550         soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
  551 
  552         UNP_LINK_WLOCK();
  553         UNP_PCB_LOCK(unp);
  554         VOP_UNP_BIND(vp, unp->unp_socket);
  555         unp->unp_vnode = vp;
  556         unp->unp_addr = soun;
  557         unp->unp_flags &= ~UNP_BINDING;
  558         UNP_PCB_UNLOCK(unp);
  559         UNP_LINK_WUNLOCK();
  560         VOP_UNLOCK(vp, 0);
  561         vn_finished_write(mp);
  562         free(buf, M_TEMP);
  563         return (0);
  564 
  565 error:
  566         UNP_PCB_LOCK(unp);
  567         unp->unp_flags &= ~UNP_BINDING;
  568         UNP_PCB_UNLOCK(unp);
  569         free(buf, M_TEMP);
  570         return (error);
  571 }
  572 
  573 static int
  574 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
  575 {
  576 
  577         return (uipc_bindat(AT_FDCWD, so, nam, td));
  578 }
  579 
  580 static int
  581 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
  582 {
  583         int error;
  584 
  585         KASSERT(td == curthread, ("uipc_connect: td != curthread"));
  586         UNP_LINK_WLOCK();
  587         error = unp_connect(so, nam, td);
  588         UNP_LINK_WUNLOCK();
  589         return (error);
  590 }
  591 
  592 static int
  593 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
  594     struct thread *td)
  595 {
  596         int error;
  597 
  598         KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
  599         UNP_LINK_WLOCK();
  600         error = unp_connectat(fd, so, nam, td);
  601         UNP_LINK_WUNLOCK();
  602         return (error);
  603 }
  604 
  605 static void
  606 uipc_close(struct socket *so)
  607 {
  608         struct unpcb *unp, *unp2;
  609 
  610         unp = sotounpcb(so);
  611         KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
  612 
  613         UNP_LINK_WLOCK();
  614         UNP_PCB_LOCK(unp);
  615         unp2 = unp->unp_conn;
  616         if (unp2 != NULL) {
  617                 UNP_PCB_LOCK(unp2);
  618                 unp_disconnect(unp, unp2);
  619                 UNP_PCB_UNLOCK(unp2);
  620         }
  621         UNP_PCB_UNLOCK(unp);
  622         UNP_LINK_WUNLOCK();
  623 }
  624 
  625 static int
  626 uipc_connect2(struct socket *so1, struct socket *so2)
  627 {
  628         struct unpcb *unp, *unp2;
  629         int error;
  630 
  631         UNP_LINK_WLOCK();
  632         unp = so1->so_pcb;
  633         KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
  634         UNP_PCB_LOCK(unp);
  635         unp2 = so2->so_pcb;
  636         KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
  637         UNP_PCB_LOCK(unp2);
  638         error = unp_connect2(so1, so2, PRU_CONNECT2);
  639         UNP_PCB_UNLOCK(unp2);
  640         UNP_PCB_UNLOCK(unp);
  641         UNP_LINK_WUNLOCK();
  642         return (error);
  643 }
  644 
  645 static void
  646 uipc_detach(struct socket *so)
  647 {
  648         struct unpcb *unp, *unp2;
  649         struct sockaddr_un *saved_unp_addr;
  650         struct vnode *vp;
  651         int freeunp, local_unp_rights;
  652 
  653         unp = sotounpcb(so);
  654         KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
  655 
  656         vp = NULL;
  657         local_unp_rights = 0;
  658 
  659         UNP_LIST_LOCK();
  660         LIST_REMOVE(unp, unp_link);
  661         unp->unp_gencnt = ++unp_gencnt;
  662         --unp_count;
  663         UNP_LIST_UNLOCK();
  664 
  665         if ((unp->unp_flags & UNP_NASCENT) != 0) {
  666                 UNP_PCB_LOCK(unp);
  667                 goto teardown;
  668         }
  669         UNP_LINK_WLOCK();
  670         UNP_PCB_LOCK(unp);
  671 
  672         /*
  673          * XXXRW: Should assert vp->v_socket == so.
  674          */
  675         if ((vp = unp->unp_vnode) != NULL) {
  676                 VOP_UNP_DETACH(vp);
  677                 unp->unp_vnode = NULL;
  678         }
  679         unp2 = unp->unp_conn;
  680         if (unp2 != NULL) {
  681                 UNP_PCB_LOCK(unp2);
  682                 unp_disconnect(unp, unp2);
  683                 UNP_PCB_UNLOCK(unp2);
  684         }
  685 
  686         /*
  687          * We hold the linkage lock exclusively, so it's OK to acquire
  688          * multiple pcb locks at a time.
  689          */
  690         while (!LIST_EMPTY(&unp->unp_refs)) {
  691                 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
  692 
  693                 UNP_PCB_LOCK(ref);
  694                 unp_drop(ref, ECONNRESET);
  695                 UNP_PCB_UNLOCK(ref);
  696         }
  697         local_unp_rights = unp_rights;
  698         UNP_LINK_WUNLOCK();
  699 teardown:
  700         unp->unp_socket->so_pcb = NULL;
  701         saved_unp_addr = unp->unp_addr;
  702         unp->unp_addr = NULL;
  703         unp->unp_refcount--;
  704         freeunp = (unp->unp_refcount == 0);
  705         if (saved_unp_addr != NULL)
  706                 free(saved_unp_addr, M_SONAME);
  707         if (freeunp) {
  708                 UNP_PCB_LOCK_DESTROY(unp);
  709                 uma_zfree(unp_zone, unp);
  710         } else
  711                 UNP_PCB_UNLOCK(unp);
  712         if (vp)
  713                 vrele(vp);
  714         if (local_unp_rights)
  715                 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
  716 }
  717 
  718 static int
  719 uipc_disconnect(struct socket *so)
  720 {
  721         struct unpcb *unp, *unp2;
  722 
  723         unp = sotounpcb(so);
  724         KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
  725 
  726         UNP_LINK_WLOCK();
  727         UNP_PCB_LOCK(unp);
  728         unp2 = unp->unp_conn;
  729         if (unp2 != NULL) {
  730                 UNP_PCB_LOCK(unp2);
  731                 unp_disconnect(unp, unp2);
  732                 UNP_PCB_UNLOCK(unp2);
  733         }
  734         UNP_PCB_UNLOCK(unp);
  735         UNP_LINK_WUNLOCK();
  736         return (0);
  737 }
  738 
  739 static int
  740 uipc_listen(struct socket *so, int backlog, struct thread *td)
  741 {
  742         struct unpcb *unp;
  743         int error;
  744 
  745         unp = sotounpcb(so);
  746         KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
  747 
  748         UNP_PCB_LOCK(unp);
  749         if (unp->unp_vnode == NULL) {
  750                 UNP_PCB_UNLOCK(unp);
  751                 return (EINVAL);
  752         }
  753 
  754         SOCK_LOCK(so);
  755         error = solisten_proto_check(so);
  756         if (error == 0) {
  757                 cru2x(td->td_ucred, &unp->unp_peercred);
  758                 unp->unp_flags |= UNP_HAVEPCCACHED;
  759                 solisten_proto(so, backlog);
  760         }
  761         SOCK_UNLOCK(so);
  762         UNP_PCB_UNLOCK(unp);
  763         return (error);
  764 }
  765 
  766 static int
  767 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
  768 {
  769         struct unpcb *unp, *unp2;
  770         const struct sockaddr *sa;
  771 
  772         unp = sotounpcb(so);
  773         KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
  774 
  775         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
  776         UNP_LINK_RLOCK();
  777         /*
  778          * XXX: It seems that this test always fails even when connection is
  779          * established.  So, this else clause is added as workaround to
  780          * return PF_LOCAL sockaddr.
  781          */
  782         unp2 = unp->unp_conn;
  783         if (unp2 != NULL) {
  784                 UNP_PCB_LOCK(unp2);
  785                 if (unp2->unp_addr != NULL)
  786                         sa = (struct sockaddr *) unp2->unp_addr;
  787                 else
  788                         sa = &sun_noname;
  789                 bcopy(sa, *nam, sa->sa_len);
  790                 UNP_PCB_UNLOCK(unp2);
  791         } else {
  792                 sa = &sun_noname;
  793                 bcopy(sa, *nam, sa->sa_len);
  794         }
  795         UNP_LINK_RUNLOCK();
  796         return (0);
  797 }
  798 
  799 static int
  800 uipc_rcvd(struct socket *so, int flags)
  801 {
  802         struct unpcb *unp, *unp2;
  803         struct socket *so2;
  804         u_int mbcnt, sbcc;
  805 
  806         unp = sotounpcb(so);
  807         KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
  808 
  809         if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
  810                 panic("uipc_rcvd socktype %d", so->so_type);
  811 
  812         /*
  813          * Adjust backpressure on sender and wakeup any waiting to write.
  814          *
  815          * The unp lock is acquired to maintain the validity of the unp_conn
  816          * pointer; no lock on unp2 is required as unp2->unp_socket will be
  817          * static as long as we don't permit unp2 to disconnect from unp,
  818          * which is prevented by the lock on unp.  We cache values from
  819          * so_rcv to avoid holding the so_rcv lock over the entire
  820          * transaction on the remote so_snd.
  821          */
  822         SOCKBUF_LOCK(&so->so_rcv);
  823         mbcnt = so->so_rcv.sb_mbcnt;
  824         sbcc = so->so_rcv.sb_cc;
  825         SOCKBUF_UNLOCK(&so->so_rcv);
  826         /*
  827          * There is a benign race condition at this point.  If we're planning to
  828          * clear SB_STOP, but uipc_send is called on the connected socket at
  829          * this instant, it might add data to the sockbuf and set SB_STOP.  Then
  830          * we would erroneously clear SB_STOP below, even though the sockbuf is
  831          * full.  The race is benign because the only ill effect is to allow the
  832          * sockbuf to exceed its size limit, and the size limits are not
  833          * strictly guaranteed anyway.
  834          */
  835         UNP_PCB_LOCK(unp);
  836         unp2 = unp->unp_conn;
  837         if (unp2 == NULL) {
  838                 UNP_PCB_UNLOCK(unp);
  839                 return (0);
  840         }
  841         so2 = unp2->unp_socket;
  842         SOCKBUF_LOCK(&so2->so_snd);
  843         if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
  844                 so2->so_snd.sb_flags &= ~SB_STOP;
  845         sowwakeup_locked(so2);
  846         UNP_PCB_UNLOCK(unp);
  847         return (0);
  848 }
  849 
  850 static int
  851 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
  852     struct mbuf *control, struct thread *td)
  853 {
  854         struct unpcb *unp, *unp2;
  855         struct socket *so2;
  856         u_int mbcnt, sbcc;
  857         int error = 0;
  858 
  859         unp = sotounpcb(so);
  860         KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
  861 
  862         if (flags & PRUS_OOB) {
  863                 error = EOPNOTSUPP;
  864                 goto release;
  865         }
  866         if (control != NULL && (error = unp_internalize(&control, td)))
  867                 goto release;
  868         if ((nam != NULL) || (flags & PRUS_EOF))
  869                 UNP_LINK_WLOCK();
  870         else
  871                 UNP_LINK_RLOCK();
  872         switch (so->so_type) {
  873         case SOCK_DGRAM:
  874         {
  875                 const struct sockaddr *from;
  876 
  877                 unp2 = unp->unp_conn;
  878                 if (nam != NULL) {
  879                         UNP_LINK_WLOCK_ASSERT();
  880                         if (unp2 != NULL) {
  881                                 error = EISCONN;
  882                                 break;
  883                         }
  884                         error = unp_connect(so, nam, td);
  885                         if (error)
  886                                 break;
  887                         unp2 = unp->unp_conn;
  888                 }
  889 
  890                 /*
  891                  * Because connect() and send() are non-atomic in a sendto()
  892                  * with a target address, it's possible that the socket will
  893                  * have disconnected before the send() can run.  In that case
  894                  * return the slightly counter-intuitive but otherwise
  895                  * correct error that the socket is not connected.
  896                  */
  897                 if (unp2 == NULL) {
  898                         error = ENOTCONN;
  899                         break;
  900                 }
  901                 /* Lockless read. */
  902                 if (unp2->unp_flags & UNP_WANTCRED)
  903                         control = unp_addsockcred(td, control);
  904                 UNP_PCB_LOCK(unp);
  905                 if (unp->unp_addr != NULL)
  906                         from = (struct sockaddr *)unp->unp_addr;
  907                 else
  908                         from = &sun_noname;
  909                 so2 = unp2->unp_socket;
  910                 SOCKBUF_LOCK(&so2->so_rcv);
  911                 if (sbappendaddr_locked(&so2->so_rcv, from, m,
  912                     control)) {
  913                         sorwakeup_locked(so2);
  914                         m = NULL;
  915                         control = NULL;
  916                 } else {
  917                         SOCKBUF_UNLOCK(&so2->so_rcv);
  918                         error = ENOBUFS;
  919                 }
  920                 if (nam != NULL) {
  921                         UNP_LINK_WLOCK_ASSERT();
  922                         UNP_PCB_LOCK(unp2);
  923                         unp_disconnect(unp, unp2);
  924                         UNP_PCB_UNLOCK(unp2);
  925                 }
  926                 UNP_PCB_UNLOCK(unp);
  927                 break;
  928         }
  929 
  930         case SOCK_SEQPACKET:
  931         case SOCK_STREAM:
  932                 if ((so->so_state & SS_ISCONNECTED) == 0) {
  933                         if (nam != NULL) {
  934                                 UNP_LINK_WLOCK_ASSERT();
  935                                 error = unp_connect(so, nam, td);
  936                                 if (error)
  937                                         break;  /* XXX */
  938                         } else {
  939                                 error = ENOTCONN;
  940                                 break;
  941                         }
  942                 }
  943 
  944                 /* Lockless read. */
  945                 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
  946                         error = EPIPE;
  947                         break;
  948                 }
  949 
  950                 /*
  951                  * Because connect() and send() are non-atomic in a sendto()
  952                  * with a target address, it's possible that the socket will
  953                  * have disconnected before the send() can run.  In that case
  954                  * return the slightly counter-intuitive but otherwise
  955                  * correct error that the socket is not connected.
  956                  *
  957                  * Locking here must be done carefully: the linkage lock
  958                  * prevents interconnections between unpcbs from changing, so
  959                  * we can traverse from unp to unp2 without acquiring unp's
  960                  * lock.  Socket buffer locks follow unpcb locks, so we can
  961                  * acquire both remote and lock socket buffer locks.
  962                  */
  963                 unp2 = unp->unp_conn;
  964                 if (unp2 == NULL) {
  965                         error = ENOTCONN;
  966                         break;
  967                 }
  968                 so2 = unp2->unp_socket;
  969                 UNP_PCB_LOCK(unp2);
  970                 SOCKBUF_LOCK(&so2->so_rcv);
  971                 if (unp2->unp_flags & UNP_WANTCRED) {
  972                         /*
  973                          * Credentials are passed only once on SOCK_STREAM
  974                          * and SOCK_SEQPACKET.
  975                          */
  976                         unp2->unp_flags &= ~UNP_WANTCRED;
  977                         control = unp_addsockcred(td, control);
  978                 }
  979                 /*
  980                  * Send to paired receive port, and then reduce send buffer
  981                  * hiwater marks to maintain backpressure.  Wake up readers.
  982                  */
  983                 switch (so->so_type) {
  984                 case SOCK_STREAM:
  985                         if (control != NULL) {
  986                                 if (sbappendcontrol_locked(&so2->so_rcv, m,
  987                                     control))
  988                                         control = NULL;
  989                         } else
  990                                 sbappend_locked(&so2->so_rcv, m);
  991                         break;
  992 
  993                 case SOCK_SEQPACKET: {
  994                         const struct sockaddr *from;
  995 
  996                         from = &sun_noname;
  997                         /*
  998                          * Don't check for space available in so2->so_rcv.
  999                          * Unix domain sockets only check for space in the
 1000                          * sending sockbuf, and that check is performed one
 1001                          * level up the stack.
 1002                          */
 1003                         if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
 1004                                 from, m, control))
 1005                                 control = NULL;
 1006                         break;
 1007                         }
 1008                 }
 1009 
 1010                 mbcnt = so2->so_rcv.sb_mbcnt;
 1011                 sbcc = so2->so_rcv.sb_cc;
 1012                 sorwakeup_locked(so2);
 1013 
 1014                 /*
 1015                  * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
 1016                  * it would be possible for uipc_rcvd to be called at this
 1017                  * point, drain the receiving sockbuf, clear SB_STOP, and then
 1018                  * we would set SB_STOP below.  That could lead to an empty
 1019                  * sockbuf having SB_STOP set
 1020                  */
 1021                 SOCKBUF_LOCK(&so->so_snd);
 1022                 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
 1023                         so->so_snd.sb_flags |= SB_STOP;
 1024                 SOCKBUF_UNLOCK(&so->so_snd);
 1025                 UNP_PCB_UNLOCK(unp2);
 1026                 m = NULL;
 1027                 break;
 1028 
 1029         default:
 1030                 panic("uipc_send unknown socktype");
 1031         }
 1032 
 1033         /*
 1034          * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
 1035          */
 1036         if (flags & PRUS_EOF) {
 1037                 UNP_PCB_LOCK(unp);
 1038                 socantsendmore(so);
 1039                 unp_shutdown(unp);
 1040                 UNP_PCB_UNLOCK(unp);
 1041         }
 1042 
 1043         if ((nam != NULL) || (flags & PRUS_EOF))
 1044                 UNP_LINK_WUNLOCK();
 1045         else
 1046                 UNP_LINK_RUNLOCK();
 1047 
 1048         if (control != NULL && error != 0)
 1049                 unp_dispose(control);
 1050 
 1051 release:
 1052         if (control != NULL)
 1053                 m_freem(control);
 1054         if (m != NULL)
 1055                 m_freem(m);
 1056         return (error);
 1057 }
 1058 
 1059 static int
 1060 uipc_sense(struct socket *so, struct stat *sb)
 1061 {
 1062         struct unpcb *unp;
 1063 
 1064         unp = sotounpcb(so);
 1065         KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
 1066 
 1067         sb->st_blksize = so->so_snd.sb_hiwat;
 1068         UNP_PCB_LOCK(unp);
 1069         sb->st_dev = NODEV;
 1070         if (unp->unp_ino == 0)
 1071                 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
 1072         sb->st_ino = unp->unp_ino;
 1073         UNP_PCB_UNLOCK(unp);
 1074         return (0);
 1075 }
 1076 
 1077 static int
 1078 uipc_shutdown(struct socket *so)
 1079 {
 1080         struct unpcb *unp;
 1081 
 1082         unp = sotounpcb(so);
 1083         KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
 1084 
 1085         UNP_LINK_WLOCK();
 1086         UNP_PCB_LOCK(unp);
 1087         socantsendmore(so);
 1088         unp_shutdown(unp);
 1089         UNP_PCB_UNLOCK(unp);
 1090         UNP_LINK_WUNLOCK();
 1091         return (0);
 1092 }
 1093 
 1094 static int
 1095 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
 1096 {
 1097         struct unpcb *unp;
 1098         const struct sockaddr *sa;
 1099 
 1100         unp = sotounpcb(so);
 1101         KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
 1102 
 1103         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
 1104         UNP_PCB_LOCK(unp);
 1105         if (unp->unp_addr != NULL)
 1106                 sa = (struct sockaddr *) unp->unp_addr;
 1107         else
 1108                 sa = &sun_noname;
 1109         bcopy(sa, *nam, sa->sa_len);
 1110         UNP_PCB_UNLOCK(unp);
 1111         return (0);
 1112 }
 1113 
 1114 static struct pr_usrreqs uipc_usrreqs_dgram = {
 1115         .pru_abort =            uipc_abort,
 1116         .pru_accept =           uipc_accept,
 1117         .pru_attach =           uipc_attach,
 1118         .pru_bind =             uipc_bind,
 1119         .pru_bindat =           uipc_bindat,
 1120         .pru_connect =          uipc_connect,
 1121         .pru_connectat =        uipc_connectat,
 1122         .pru_connect2 =         uipc_connect2,
 1123         .pru_detach =           uipc_detach,
 1124         .pru_disconnect =       uipc_disconnect,
 1125         .pru_listen =           uipc_listen,
 1126         .pru_peeraddr =         uipc_peeraddr,
 1127         .pru_rcvd =             uipc_rcvd,
 1128         .pru_send =             uipc_send,
 1129         .pru_sense =            uipc_sense,
 1130         .pru_shutdown =         uipc_shutdown,
 1131         .pru_sockaddr =         uipc_sockaddr,
 1132         .pru_soreceive =        soreceive_dgram,
 1133         .pru_close =            uipc_close,
 1134 };
 1135 
 1136 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
 1137         .pru_abort =            uipc_abort,
 1138         .pru_accept =           uipc_accept,
 1139         .pru_attach =           uipc_attach,
 1140         .pru_bind =             uipc_bind,
 1141         .pru_bindat =           uipc_bindat,
 1142         .pru_connect =          uipc_connect,
 1143         .pru_connectat =        uipc_connectat,
 1144         .pru_connect2 =         uipc_connect2,
 1145         .pru_detach =           uipc_detach,
 1146         .pru_disconnect =       uipc_disconnect,
 1147         .pru_listen =           uipc_listen,
 1148         .pru_peeraddr =         uipc_peeraddr,
 1149         .pru_rcvd =             uipc_rcvd,
 1150         .pru_send =             uipc_send,
 1151         .pru_sense =            uipc_sense,
 1152         .pru_shutdown =         uipc_shutdown,
 1153         .pru_sockaddr =         uipc_sockaddr,
 1154         .pru_soreceive =        soreceive_generic,      /* XXX: or...? */
 1155         .pru_close =            uipc_close,
 1156 };
 1157 
 1158 static struct pr_usrreqs uipc_usrreqs_stream = {
 1159         .pru_abort =            uipc_abort,
 1160         .pru_accept =           uipc_accept,
 1161         .pru_attach =           uipc_attach,
 1162         .pru_bind =             uipc_bind,
 1163         .pru_bindat =           uipc_bindat,
 1164         .pru_connect =          uipc_connect,
 1165         .pru_connectat =        uipc_connectat,
 1166         .pru_connect2 =         uipc_connect2,
 1167         .pru_detach =           uipc_detach,
 1168         .pru_disconnect =       uipc_disconnect,
 1169         .pru_listen =           uipc_listen,
 1170         .pru_peeraddr =         uipc_peeraddr,
 1171         .pru_rcvd =             uipc_rcvd,
 1172         .pru_send =             uipc_send,
 1173         .pru_sense =            uipc_sense,
 1174         .pru_shutdown =         uipc_shutdown,
 1175         .pru_sockaddr =         uipc_sockaddr,
 1176         .pru_soreceive =        soreceive_generic,
 1177         .pru_close =            uipc_close,
 1178 };
 1179 
 1180 static int
 1181 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
 1182 {
 1183         struct unpcb *unp;
 1184         struct xucred xu;
 1185         int error, optval;
 1186 
 1187         if (sopt->sopt_level != 0)
 1188                 return (EINVAL);
 1189 
 1190         unp = sotounpcb(so);
 1191         KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
 1192         error = 0;
 1193         switch (sopt->sopt_dir) {
 1194         case SOPT_GET:
 1195                 switch (sopt->sopt_name) {
 1196                 case LOCAL_PEERCRED:
 1197                         UNP_PCB_LOCK(unp);
 1198                         if (unp->unp_flags & UNP_HAVEPC)
 1199                                 xu = unp->unp_peercred;
 1200                         else {
 1201                                 if (so->so_type == SOCK_STREAM)
 1202                                         error = ENOTCONN;
 1203                                 else
 1204                                         error = EINVAL;
 1205                         }
 1206                         UNP_PCB_UNLOCK(unp);
 1207                         if (error == 0)
 1208                                 error = sooptcopyout(sopt, &xu, sizeof(xu));
 1209                         break;
 1210 
 1211                 case LOCAL_CREDS:
 1212                         /* Unlocked read. */
 1213                         optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
 1214                         error = sooptcopyout(sopt, &optval, sizeof(optval));
 1215                         break;
 1216 
 1217                 case LOCAL_CONNWAIT:
 1218                         /* Unlocked read. */
 1219                         optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
 1220                         error = sooptcopyout(sopt, &optval, sizeof(optval));
 1221                         break;
 1222 
 1223                 default:
 1224                         error = EOPNOTSUPP;
 1225                         break;
 1226                 }
 1227                 break;
 1228 
 1229         case SOPT_SET:
 1230                 switch (sopt->sopt_name) {
 1231                 case LOCAL_CREDS:
 1232                 case LOCAL_CONNWAIT:
 1233                         error = sooptcopyin(sopt, &optval, sizeof(optval),
 1234                                             sizeof(optval));
 1235                         if (error)
 1236                                 break;
 1237 
 1238 #define OPTSET(bit) do {                                                \
 1239         UNP_PCB_LOCK(unp);                                              \
 1240         if (optval)                                                     \
 1241                 unp->unp_flags |= bit;                                  \
 1242         else                                                            \
 1243                 unp->unp_flags &= ~bit;                                 \
 1244         UNP_PCB_UNLOCK(unp);                                            \
 1245 } while (0)
 1246 
 1247                         switch (sopt->sopt_name) {
 1248                         case LOCAL_CREDS:
 1249                                 OPTSET(UNP_WANTCRED);
 1250                                 break;
 1251 
 1252                         case LOCAL_CONNWAIT:
 1253                                 OPTSET(UNP_CONNWAIT);
 1254                                 break;
 1255 
 1256                         default:
 1257                                 break;
 1258                         }
 1259                         break;
 1260 #undef  OPTSET
 1261                 default:
 1262                         error = ENOPROTOOPT;
 1263                         break;
 1264                 }
 1265                 break;
 1266 
 1267         default:
 1268                 error = EOPNOTSUPP;
 1269                 break;
 1270         }
 1271         return (error);
 1272 }
 1273 
 1274 static int
 1275 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
 1276 {
 1277 
 1278         return (unp_connectat(AT_FDCWD, so, nam, td));
 1279 }
 1280 
 1281 static int
 1282 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
 1283     struct thread *td)
 1284 {
 1285         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
 1286         struct vnode *vp;
 1287         struct socket *so2, *so3;
 1288         struct unpcb *unp, *unp2, *unp3;
 1289         struct nameidata nd;
 1290         char buf[SOCK_MAXADDRLEN];
 1291         struct sockaddr *sa;
 1292         cap_rights_t rights;
 1293         int error, len;
 1294 
 1295         if (nam->sa_family != AF_UNIX)
 1296                 return (EAFNOSUPPORT);
 1297 
 1298         UNP_LINK_WLOCK_ASSERT();
 1299 
 1300         unp = sotounpcb(so);
 1301         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
 1302 
 1303         if (nam->sa_len > sizeof(struct sockaddr_un))
 1304                 return (EINVAL);
 1305         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
 1306         if (len <= 0)
 1307                 return (EINVAL);
 1308         bcopy(soun->sun_path, buf, len);
 1309         buf[len] = 0;
 1310 
 1311         UNP_PCB_LOCK(unp);
 1312         if (unp->unp_flags & UNP_CONNECTING) {
 1313                 UNP_PCB_UNLOCK(unp);
 1314                 return (EALREADY);
 1315         }
 1316         UNP_LINK_WUNLOCK();
 1317         unp->unp_flags |= UNP_CONNECTING;
 1318         UNP_PCB_UNLOCK(unp);
 1319 
 1320         sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
 1321         NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
 1322             UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
 1323         error = namei(&nd);
 1324         if (error)
 1325                 vp = NULL;
 1326         else
 1327                 vp = nd.ni_vp;
 1328         ASSERT_VOP_LOCKED(vp, "unp_connect");
 1329         NDFREE(&nd, NDF_ONLY_PNBUF);
 1330         if (error)
 1331                 goto bad;
 1332 
 1333         if (vp->v_type != VSOCK) {
 1334                 error = ENOTSOCK;
 1335                 goto bad;
 1336         }
 1337 #ifdef MAC
 1338         error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
 1339         if (error)
 1340                 goto bad;
 1341 #endif
 1342         error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
 1343         if (error)
 1344                 goto bad;
 1345 
 1346         unp = sotounpcb(so);
 1347         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
 1348 
 1349         /*
 1350          * Lock linkage lock for two reasons: make sure v_socket is stable,
 1351          * and to protect simultaneous locking of multiple pcbs.
 1352          */
 1353         UNP_LINK_WLOCK();
 1354         VOP_UNP_CONNECT(vp, &so2);
 1355         if (so2 == NULL) {
 1356                 error = ECONNREFUSED;
 1357                 goto bad2;
 1358         }
 1359         if (so->so_type != so2->so_type) {
 1360                 error = EPROTOTYPE;
 1361                 goto bad2;
 1362         }
 1363         if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
 1364                 if (so2->so_options & SO_ACCEPTCONN) {
 1365                         CURVNET_SET(so2->so_vnet);
 1366                         so3 = sonewconn(so2, 0);
 1367                         CURVNET_RESTORE();
 1368                 } else
 1369                         so3 = NULL;
 1370                 if (so3 == NULL) {
 1371                         error = ECONNREFUSED;
 1372                         goto bad2;
 1373                 }
 1374                 unp = sotounpcb(so);
 1375                 unp2 = sotounpcb(so2);
 1376                 unp3 = sotounpcb(so3);
 1377                 UNP_PCB_LOCK(unp);
 1378                 UNP_PCB_LOCK(unp2);
 1379                 UNP_PCB_LOCK(unp3);
 1380                 if (unp2->unp_addr != NULL) {
 1381                         bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
 1382                         unp3->unp_addr = (struct sockaddr_un *) sa;
 1383                         sa = NULL;
 1384                 }
 1385 
 1386                 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
 1387                     ("unp_connect: listener without cached peercred"));
 1388                 unp_copy_peercred(td, unp3, unp, unp2);
 1389 
 1390                 UNP_PCB_UNLOCK(unp3);
 1391                 UNP_PCB_UNLOCK(unp2);
 1392                 UNP_PCB_UNLOCK(unp);
 1393 #ifdef MAC
 1394                 mac_socketpeer_set_from_socket(so, so3);
 1395                 mac_socketpeer_set_from_socket(so3, so);
 1396 #endif
 1397 
 1398                 so2 = so3;
 1399         }
 1400         unp = sotounpcb(so);
 1401         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
 1402         unp2 = sotounpcb(so2);
 1403         KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
 1404         UNP_PCB_LOCK(unp);
 1405         UNP_PCB_LOCK(unp2);
 1406         error = unp_connect2(so, so2, PRU_CONNECT);
 1407         UNP_PCB_UNLOCK(unp2);
 1408         UNP_PCB_UNLOCK(unp);
 1409 bad2:
 1410         UNP_LINK_WUNLOCK();
 1411 bad:
 1412         if (vp != NULL)
 1413                 vput(vp);
 1414         free(sa, M_SONAME);
 1415         UNP_LINK_WLOCK();
 1416         UNP_PCB_LOCK(unp);
 1417         unp->unp_flags &= ~UNP_CONNECTING;
 1418         UNP_PCB_UNLOCK(unp);
 1419         return (error);
 1420 }
 1421 
 1422 /*
 1423  * Set socket peer credentials at connection time.
 1424  *
 1425  * The client's PCB credentials are copied from its process structure.  The
 1426  * server's PCB credentials are copied from the socket on which it called
 1427  * listen(2).  uipc_listen cached that process's credentials at the time.
 1428  */
 1429 void
 1430 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
 1431     struct unpcb *server_unp, struct unpcb *listen_unp)
 1432 {
 1433         cru2x(td->td_ucred, &client_unp->unp_peercred);
 1434         client_unp->unp_flags |= UNP_HAVEPC;
 1435 
 1436         memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
 1437             sizeof(server_unp->unp_peercred));
 1438         server_unp->unp_flags |= UNP_HAVEPC;
 1439         if (listen_unp->unp_flags & UNP_WANTCRED)
 1440                 client_unp->unp_flags |= UNP_WANTCRED;
 1441 }
 1442 
 1443 static int
 1444 unp_connect2(struct socket *so, struct socket *so2, int req)
 1445 {
 1446         struct unpcb *unp;
 1447         struct unpcb *unp2;
 1448 
 1449         unp = sotounpcb(so);
 1450         KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
 1451         unp2 = sotounpcb(so2);
 1452         KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
 1453 
 1454         UNP_LINK_WLOCK_ASSERT();
 1455         UNP_PCB_LOCK_ASSERT(unp);
 1456         UNP_PCB_LOCK_ASSERT(unp2);
 1457 
 1458         if (so2->so_type != so->so_type)
 1459                 return (EPROTOTYPE);
 1460         unp2->unp_flags &= ~UNP_NASCENT;
 1461         unp->unp_conn = unp2;
 1462 
 1463         switch (so->so_type) {
 1464         case SOCK_DGRAM:
 1465                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
 1466                 soisconnected(so);
 1467                 break;
 1468 
 1469         case SOCK_STREAM:
 1470         case SOCK_SEQPACKET:
 1471                 unp2->unp_conn = unp;
 1472                 if (req == PRU_CONNECT &&
 1473                     ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
 1474                         soisconnecting(so);
 1475                 else
 1476                         soisconnected(so);
 1477                 soisconnected(so2);
 1478                 break;
 1479 
 1480         default:
 1481                 panic("unp_connect2");
 1482         }
 1483         return (0);
 1484 }
 1485 
 1486 static void
 1487 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
 1488 {
 1489         struct socket *so;
 1490 
 1491         KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
 1492 
 1493         UNP_LINK_WLOCK_ASSERT();
 1494         UNP_PCB_LOCK_ASSERT(unp);
 1495         UNP_PCB_LOCK_ASSERT(unp2);
 1496 
 1497         unp->unp_conn = NULL;
 1498         switch (unp->unp_socket->so_type) {
 1499         case SOCK_DGRAM:
 1500                 LIST_REMOVE(unp, unp_reflink);
 1501                 so = unp->unp_socket;
 1502                 SOCK_LOCK(so);
 1503                 so->so_state &= ~SS_ISCONNECTED;
 1504                 SOCK_UNLOCK(so);
 1505                 break;
 1506 
 1507         case SOCK_STREAM:
 1508         case SOCK_SEQPACKET:
 1509                 soisdisconnected(unp->unp_socket);
 1510                 unp2->unp_conn = NULL;
 1511                 soisdisconnected(unp2->unp_socket);
 1512                 break;
 1513         }
 1514 }
 1515 
 1516 /*
 1517  * unp_pcblist() walks the global list of struct unpcb's to generate a
 1518  * pointer list, bumping the refcount on each unpcb.  It then copies them out
 1519  * sequentially, validating the generation number on each to see if it has
 1520  * been detached.  All of this is necessary because copyout() may sleep on
 1521  * disk I/O.
 1522  */
 1523 static int
 1524 unp_pcblist(SYSCTL_HANDLER_ARGS)
 1525 {
 1526         int error, i, n;
 1527         int freeunp;
 1528         struct unpcb *unp, **unp_list;
 1529         unp_gen_t gencnt;
 1530         struct xunpgen *xug;
 1531         struct unp_head *head;
 1532         struct xunpcb *xu;
 1533 
 1534         switch ((intptr_t)arg1) {
 1535         case SOCK_STREAM:
 1536                 head = &unp_shead;
 1537                 break;
 1538 
 1539         case SOCK_DGRAM:
 1540                 head = &unp_dhead;
 1541                 break;
 1542 
 1543         case SOCK_SEQPACKET:
 1544                 head = &unp_sphead;
 1545                 break;
 1546 
 1547         default:
 1548                 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
 1549         }
 1550 
 1551         /*
 1552          * The process of preparing the PCB list is too time-consuming and
 1553          * resource-intensive to repeat twice on every request.
 1554          */
 1555         if (req->oldptr == NULL) {
 1556                 n = unp_count;
 1557                 req->oldidx = 2 * (sizeof *xug)
 1558                         + (n + n/8) * sizeof(struct xunpcb);
 1559                 return (0);
 1560         }
 1561 
 1562         if (req->newptr != NULL)
 1563                 return (EPERM);
 1564 
 1565         /*
 1566          * OK, now we're committed to doing something.
 1567          */
 1568         xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
 1569         UNP_LIST_LOCK();
 1570         gencnt = unp_gencnt;
 1571         n = unp_count;
 1572         UNP_LIST_UNLOCK();
 1573 
 1574         xug->xug_len = sizeof *xug;
 1575         xug->xug_count = n;
 1576         xug->xug_gen = gencnt;
 1577         xug->xug_sogen = so_gencnt;
 1578         error = SYSCTL_OUT(req, xug, sizeof *xug);
 1579         if (error) {
 1580                 free(xug, M_TEMP);
 1581                 return (error);
 1582         }
 1583 
 1584         unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
 1585 
 1586         UNP_LIST_LOCK();
 1587         for (unp = LIST_FIRST(head), i = 0; unp && i < n;
 1588              unp = LIST_NEXT(unp, unp_link)) {
 1589                 UNP_PCB_LOCK(unp);
 1590                 if (unp->unp_gencnt <= gencnt) {
 1591                         if (cr_cansee(req->td->td_ucred,
 1592                             unp->unp_socket->so_cred)) {
 1593                                 UNP_PCB_UNLOCK(unp);
 1594                                 continue;
 1595                         }
 1596                         unp_list[i++] = unp;
 1597                         unp->unp_refcount++;
 1598                 }
 1599                 UNP_PCB_UNLOCK(unp);
 1600         }
 1601         UNP_LIST_UNLOCK();
 1602         n = i;                  /* In case we lost some during malloc. */
 1603 
 1604         error = 0;
 1605         xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
 1606         for (i = 0; i < n; i++) {
 1607                 unp = unp_list[i];
 1608                 UNP_PCB_LOCK(unp);
 1609                 unp->unp_refcount--;
 1610                 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
 1611                         xu->xu_len = sizeof *xu;
 1612                         xu->xu_unpp = unp;
 1613                         /*
 1614                          * XXX - need more locking here to protect against
 1615                          * connect/disconnect races for SMP.
 1616                          */
 1617                         if (unp->unp_addr != NULL)
 1618                                 bcopy(unp->unp_addr, &xu->xu_addr,
 1619                                       unp->unp_addr->sun_len);
 1620                         if (unp->unp_conn != NULL &&
 1621                             unp->unp_conn->unp_addr != NULL)
 1622                                 bcopy(unp->unp_conn->unp_addr,
 1623                                       &xu->xu_caddr,
 1624                                       unp->unp_conn->unp_addr->sun_len);
 1625                         bcopy(unp, &xu->xu_unp, sizeof *unp);
 1626                         sotoxsocket(unp->unp_socket, &xu->xu_socket);
 1627                         UNP_PCB_UNLOCK(unp);
 1628                         error = SYSCTL_OUT(req, xu, sizeof *xu);
 1629                 } else {
 1630                         freeunp = (unp->unp_refcount == 0);
 1631                         UNP_PCB_UNLOCK(unp);
 1632                         if (freeunp) {
 1633                                 UNP_PCB_LOCK_DESTROY(unp);
 1634                                 uma_zfree(unp_zone, unp);
 1635                         }
 1636                 }
 1637         }
 1638         free(xu, M_TEMP);
 1639         if (!error) {
 1640                 /*
 1641                  * Give the user an updated idea of our state.  If the
 1642                  * generation differs from what we told her before, she knows
 1643                  * that something happened while we were processing this
 1644                  * request, and it might be necessary to retry.
 1645                  */
 1646                 xug->xug_gen = unp_gencnt;
 1647                 xug->xug_sogen = so_gencnt;
 1648                 xug->xug_count = unp_count;
 1649                 error = SYSCTL_OUT(req, xug, sizeof *xug);
 1650         }
 1651         free(unp_list, M_TEMP);
 1652         free(xug, M_TEMP);
 1653         return (error);
 1654 }
 1655 
 1656 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
 1657     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
 1658     "List of active local datagram sockets");
 1659 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
 1660     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
 1661     "List of active local stream sockets");
 1662 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
 1663     CTLTYPE_OPAQUE | CTLFLAG_RD,
 1664     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
 1665     "List of active local seqpacket sockets");
 1666 
 1667 static void
 1668 unp_shutdown(struct unpcb *unp)
 1669 {
 1670         struct unpcb *unp2;
 1671         struct socket *so;
 1672 
 1673         UNP_LINK_WLOCK_ASSERT();
 1674         UNP_PCB_LOCK_ASSERT(unp);
 1675 
 1676         unp2 = unp->unp_conn;
 1677         if ((unp->unp_socket->so_type == SOCK_STREAM ||
 1678             (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
 1679                 so = unp2->unp_socket;
 1680                 if (so != NULL)
 1681                         socantrcvmore(so);
 1682         }
 1683 }
 1684 
 1685 static void
 1686 unp_drop(struct unpcb *unp, int errno)
 1687 {
 1688         struct socket *so = unp->unp_socket;
 1689         struct unpcb *unp2;
 1690 
 1691         UNP_LINK_WLOCK_ASSERT();
 1692         UNP_PCB_LOCK_ASSERT(unp);
 1693 
 1694         so->so_error = errno;
 1695         unp2 = unp->unp_conn;
 1696         if (unp2 == NULL)
 1697                 return;
 1698         UNP_PCB_LOCK(unp2);
 1699         unp_disconnect(unp, unp2);
 1700         UNP_PCB_UNLOCK(unp2);
 1701 }
 1702 
 1703 static void
 1704 unp_freerights(struct filedescent **fdep, int fdcount)
 1705 {
 1706         struct file *fp;
 1707         int i;
 1708 
 1709         KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
 1710 
 1711         for (i = 0; i < fdcount; i++) {
 1712                 fp = fdep[i]->fde_file;
 1713                 filecaps_free(&fdep[i]->fde_caps);
 1714                 unp_discard(fp);
 1715         }
 1716         free(fdep[0], M_FILECAPS);
 1717 }
 1718 
 1719 static int
 1720 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
 1721 {
 1722         struct thread *td = curthread;          /* XXX */
 1723         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
 1724         int i;
 1725         int *fdp;
 1726         struct filedesc *fdesc = td->td_proc->p_fd;
 1727         struct filedescent *fde, **fdep;
 1728         void *data;
 1729         socklen_t clen = control->m_len, datalen;
 1730         int error, newfds;
 1731         u_int newlen;
 1732 
 1733         UNP_LINK_UNLOCK_ASSERT();
 1734 
 1735         error = 0;
 1736         if (controlp != NULL) /* controlp == NULL => free control messages */
 1737                 *controlp = NULL;
 1738         while (cm != NULL) {
 1739                 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
 1740                         error = EINVAL;
 1741                         break;
 1742                 }
 1743                 data = CMSG_DATA(cm);
 1744                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
 1745                 if (cm->cmsg_level == SOL_SOCKET
 1746                     && cm->cmsg_type == SCM_RIGHTS) {
 1747                         newfds = datalen / sizeof(*fdep);
 1748                         if (newfds == 0)
 1749                                 goto next;
 1750                         fdep = data;
 1751 
 1752                         /* If we're not outputting the descriptors free them. */
 1753                         if (error || controlp == NULL) {
 1754                                 unp_freerights(fdep, newfds);
 1755                                 goto next;
 1756                         }
 1757                         FILEDESC_XLOCK(fdesc);
 1758 
 1759                         /*
 1760                          * Now change each pointer to an fd in the global
 1761                          * table to an integer that is the index to the local
 1762                          * fd table entry that we set up to point to the
 1763                          * global one we are transferring.
 1764                          */
 1765                         newlen = newfds * sizeof(int);
 1766                         *controlp = sbcreatecontrol(NULL, newlen,
 1767                             SCM_RIGHTS, SOL_SOCKET);
 1768                         if (*controlp == NULL) {
 1769                                 FILEDESC_XUNLOCK(fdesc);
 1770                                 error = E2BIG;
 1771                                 unp_freerights(fdep, newfds);
 1772                                 goto next;
 1773                         }
 1774 
 1775                         fdp = (int *)
 1776                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
 1777                         if (fdallocn(td, 0, fdp, newfds) != 0) {
 1778                                 FILEDESC_XUNLOCK(td->td_proc->p_fd);
 1779                                 error = EMSGSIZE;
 1780                                 unp_freerights(fdep, newfds);
 1781                                 m_freem(*controlp);
 1782                                 *controlp = NULL;
 1783                                 goto next;
 1784                         }
 1785                         for (i = 0; i < newfds; i++, fdp++) {
 1786                                 fde = &fdesc->fd_ofiles[*fdp];
 1787                                 fde->fde_file = fdep[i]->fde_file;
 1788                                 filecaps_move(&fdep[i]->fde_caps,
 1789                                     &fde->fde_caps);
 1790                                 if ((flags & MSG_CMSG_CLOEXEC) != 0)
 1791                                         fde->fde_flags |= UF_EXCLOSE;
 1792                                 unp_externalize_fp(fde->fde_file);
 1793                         }
 1794                         FILEDESC_XUNLOCK(fdesc);
 1795                         free(fdep[0], M_FILECAPS);
 1796                 } else {
 1797                         /* We can just copy anything else across. */
 1798                         if (error || controlp == NULL)
 1799                                 goto next;
 1800                         *controlp = sbcreatecontrol(NULL, datalen,
 1801                             cm->cmsg_type, cm->cmsg_level);
 1802                         if (*controlp == NULL) {
 1803                                 error = ENOBUFS;
 1804                                 goto next;
 1805                         }
 1806                         bcopy(data,
 1807                             CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
 1808                             datalen);
 1809                 }
 1810                 controlp = &(*controlp)->m_next;
 1811 
 1812 next:
 1813                 if (CMSG_SPACE(datalen) < clen) {
 1814                         clen -= CMSG_SPACE(datalen);
 1815                         cm = (struct cmsghdr *)
 1816                             ((caddr_t)cm + CMSG_SPACE(datalen));
 1817                 } else {
 1818                         clen = 0;
 1819                         cm = NULL;
 1820                 }
 1821         }
 1822 
 1823         m_freem(control);
 1824         return (error);
 1825 }
 1826 
 1827 static void
 1828 unp_zone_change(void *tag)
 1829 {
 1830 
 1831         uma_zone_set_max(unp_zone, maxsockets);
 1832 }
 1833 
 1834 static void
 1835 unp_init(void)
 1836 {
 1837 
 1838 #ifdef VIMAGE
 1839         if (!IS_DEFAULT_VNET(curvnet))
 1840                 return;
 1841 #endif
 1842         unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
 1843             NULL, NULL, UMA_ALIGN_PTR, 0);
 1844         if (unp_zone == NULL)
 1845                 panic("unp_init");
 1846         uma_zone_set_max(unp_zone, maxsockets);
 1847         uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
 1848         EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
 1849             NULL, EVENTHANDLER_PRI_ANY);
 1850         LIST_INIT(&unp_dhead);
 1851         LIST_INIT(&unp_shead);
 1852         LIST_INIT(&unp_sphead);
 1853         SLIST_INIT(&unp_defers);
 1854         TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
 1855         TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
 1856         UNP_LINK_LOCK_INIT();
 1857         UNP_LIST_LOCK_INIT();
 1858         UNP_DEFERRED_LOCK_INIT();
 1859 }
 1860 
 1861 static int
 1862 unp_internalize(struct mbuf **controlp, struct thread *td)
 1863 {
 1864         struct mbuf *control = *controlp;
 1865         struct proc *p = td->td_proc;
 1866         struct filedesc *fdesc = p->p_fd;
 1867         struct bintime *bt;
 1868         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
 1869         struct cmsgcred *cmcred;
 1870         struct filedescent *fde, **fdep, *fdev;
 1871         struct file *fp;
 1872         struct timeval *tv;
 1873         int i, *fdp;
 1874         void *data;
 1875         socklen_t clen = control->m_len, datalen;
 1876         int error, oldfds;
 1877         u_int newlen;
 1878 
 1879         UNP_LINK_UNLOCK_ASSERT();
 1880 
 1881         error = 0;
 1882         *controlp = NULL;
 1883         while (cm != NULL) {
 1884                 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
 1885                     || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
 1886                         error = EINVAL;
 1887                         goto out;
 1888                 }
 1889                 data = CMSG_DATA(cm);
 1890                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
 1891 
 1892                 switch (cm->cmsg_type) {
 1893                 /*
 1894                  * Fill in credential information.
 1895                  */
 1896                 case SCM_CREDS:
 1897                         *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
 1898                             SCM_CREDS, SOL_SOCKET);
 1899                         if (*controlp == NULL) {
 1900                                 error = ENOBUFS;
 1901                                 goto out;
 1902                         }
 1903                         cmcred = (struct cmsgcred *)
 1904                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
 1905                         cmcred->cmcred_pid = p->p_pid;
 1906                         cmcred->cmcred_uid = td->td_ucred->cr_ruid;
 1907                         cmcred->cmcred_gid = td->td_ucred->cr_rgid;
 1908                         cmcred->cmcred_euid = td->td_ucred->cr_uid;
 1909                         cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
 1910                             CMGROUP_MAX);
 1911                         for (i = 0; i < cmcred->cmcred_ngroups; i++)
 1912                                 cmcred->cmcred_groups[i] =
 1913                                     td->td_ucred->cr_groups[i];
 1914                         break;
 1915 
 1916                 case SCM_RIGHTS:
 1917                         oldfds = datalen / sizeof (int);
 1918                         if (oldfds == 0)
 1919                                 break;
 1920                         /*
 1921                          * Check that all the FDs passed in refer to legal
 1922                          * files.  If not, reject the entire operation.
 1923                          */
 1924                         fdp = data;
 1925                         FILEDESC_SLOCK(fdesc);
 1926                         for (i = 0; i < oldfds; i++, fdp++) {
 1927                                 fp = fget_locked(fdesc, *fdp);
 1928                                 if (fp == NULL) {
 1929                                         FILEDESC_SUNLOCK(fdesc);
 1930                                         error = EBADF;
 1931                                         goto out;
 1932                                 }
 1933                                 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
 1934                                         FILEDESC_SUNLOCK(fdesc);
 1935                                         error = EOPNOTSUPP;
 1936                                         goto out;
 1937                                 }
 1938 
 1939                         }
 1940 
 1941                         /*
 1942                          * Now replace the integer FDs with pointers to the
 1943                          * file structure and capability rights.
 1944                          */
 1945                         newlen = oldfds * sizeof(fdep[0]);
 1946                         *controlp = sbcreatecontrol(NULL, newlen,
 1947                             SCM_RIGHTS, SOL_SOCKET);
 1948                         if (*controlp == NULL) {
 1949                                 FILEDESC_SUNLOCK(fdesc);
 1950                                 error = E2BIG;
 1951                                 goto out;
 1952                         }
 1953                         fdp = data;
 1954                         fdep = (struct filedescent **)
 1955                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
 1956                         fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
 1957                             M_WAITOK);
 1958                         for (i = 0; i < oldfds; i++, fdev++, fdp++) {
 1959                                 fde = &fdesc->fd_ofiles[*fdp];
 1960                                 fdep[i] = fdev;
 1961                                 fdep[i]->fde_file = fde->fde_file;
 1962                                 filecaps_copy(&fde->fde_caps,
 1963                                     &fdep[i]->fde_caps);
 1964                                 unp_internalize_fp(fdep[i]->fde_file);
 1965                         }
 1966                         FILEDESC_SUNLOCK(fdesc);
 1967                         break;
 1968 
 1969                 case SCM_TIMESTAMP:
 1970                         *controlp = sbcreatecontrol(NULL, sizeof(*tv),
 1971                             SCM_TIMESTAMP, SOL_SOCKET);
 1972                         if (*controlp == NULL) {
 1973                                 error = ENOBUFS;
 1974                                 goto out;
 1975                         }
 1976                         tv = (struct timeval *)
 1977                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
 1978                         microtime(tv);
 1979                         break;
 1980 
 1981                 case SCM_BINTIME:
 1982                         *controlp = sbcreatecontrol(NULL, sizeof(*bt),
 1983                             SCM_BINTIME, SOL_SOCKET);
 1984                         if (*controlp == NULL) {
 1985                                 error = ENOBUFS;
 1986                                 goto out;
 1987                         }
 1988                         bt = (struct bintime *)
 1989                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
 1990                         bintime(bt);
 1991                         break;
 1992 
 1993                 default:
 1994                         error = EINVAL;
 1995                         goto out;
 1996                 }
 1997 
 1998                 controlp = &(*controlp)->m_next;
 1999                 if (CMSG_SPACE(datalen) < clen) {
 2000                         clen -= CMSG_SPACE(datalen);
 2001                         cm = (struct cmsghdr *)
 2002                             ((caddr_t)cm + CMSG_SPACE(datalen));
 2003                 } else {
 2004                         clen = 0;
 2005                         cm = NULL;
 2006                 }
 2007         }
 2008 
 2009 out:
 2010         m_freem(control);
 2011         return (error);
 2012 }
 2013 
 2014 static struct mbuf *
 2015 unp_addsockcred(struct thread *td, struct mbuf *control)
 2016 {
 2017         struct mbuf *m, *n, *n_prev;
 2018         struct sockcred *sc;
 2019         const struct cmsghdr *cm;
 2020         int ngroups;
 2021         int i;
 2022 
 2023         ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
 2024         m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
 2025         if (m == NULL)
 2026                 return (control);
 2027 
 2028         sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
 2029         sc->sc_uid = td->td_ucred->cr_ruid;
 2030         sc->sc_euid = td->td_ucred->cr_uid;
 2031         sc->sc_gid = td->td_ucred->cr_rgid;
 2032         sc->sc_egid = td->td_ucred->cr_gid;
 2033         sc->sc_ngroups = ngroups;
 2034         for (i = 0; i < sc->sc_ngroups; i++)
 2035                 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
 2036 
 2037         /*
 2038          * Unlink SCM_CREDS control messages (struct cmsgcred), since just
 2039          * created SCM_CREDS control message (struct sockcred) has another
 2040          * format.
 2041          */
 2042         if (control != NULL)
 2043                 for (n = control, n_prev = NULL; n != NULL;) {
 2044                         cm = mtod(n, struct cmsghdr *);
 2045                         if (cm->cmsg_level == SOL_SOCKET &&
 2046                             cm->cmsg_type == SCM_CREDS) {
 2047                                 if (n_prev == NULL)
 2048                                         control = n->m_next;
 2049                                 else
 2050                                         n_prev->m_next = n->m_next;
 2051                                 n = m_free(n);
 2052                         } else {
 2053                                 n_prev = n;
 2054                                 n = n->m_next;
 2055                         }
 2056                 }
 2057 
 2058         /* Prepend it to the head. */
 2059         m->m_next = control;
 2060         return (m);
 2061 }
 2062 
 2063 static struct unpcb *
 2064 fptounp(struct file *fp)
 2065 {
 2066         struct socket *so;
 2067 
 2068         if (fp->f_type != DTYPE_SOCKET)
 2069                 return (NULL);
 2070         if ((so = fp->f_data) == NULL)
 2071                 return (NULL);
 2072         if (so->so_proto->pr_domain != &localdomain)
 2073                 return (NULL);
 2074         return sotounpcb(so);
 2075 }
 2076 
 2077 static void
 2078 unp_discard(struct file *fp)
 2079 {
 2080         struct unp_defer *dr;
 2081 
 2082         if (unp_externalize_fp(fp)) {
 2083                 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
 2084                 dr->ud_fp = fp;
 2085                 UNP_DEFERRED_LOCK();
 2086                 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
 2087                 UNP_DEFERRED_UNLOCK();
 2088                 atomic_add_int(&unp_defers_count, 1);
 2089                 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
 2090         } else
 2091                 (void) closef(fp, (struct thread *)NULL);
 2092 }
 2093 
 2094 static void
 2095 unp_process_defers(void *arg __unused, int pending)
 2096 {
 2097         struct unp_defer *dr;
 2098         SLIST_HEAD(, unp_defer) drl;
 2099         int count;
 2100 
 2101         SLIST_INIT(&drl);
 2102         for (;;) {
 2103                 UNP_DEFERRED_LOCK();
 2104                 if (SLIST_FIRST(&unp_defers) == NULL) {
 2105                         UNP_DEFERRED_UNLOCK();
 2106                         break;
 2107                 }
 2108                 SLIST_SWAP(&unp_defers, &drl, unp_defer);
 2109                 UNP_DEFERRED_UNLOCK();
 2110                 count = 0;
 2111                 while ((dr = SLIST_FIRST(&drl)) != NULL) {
 2112                         SLIST_REMOVE_HEAD(&drl, ud_link);
 2113                         closef(dr->ud_fp, NULL);
 2114                         free(dr, M_TEMP);
 2115                         count++;
 2116                 }
 2117                 atomic_add_int(&unp_defers_count, -count);
 2118         }
 2119 }
 2120 
 2121 static void
 2122 unp_internalize_fp(struct file *fp)
 2123 {
 2124         struct unpcb *unp;
 2125 
 2126         UNP_LINK_WLOCK();
 2127         if ((unp = fptounp(fp)) != NULL) {
 2128                 unp->unp_file = fp;
 2129                 unp->unp_msgcount++;
 2130         }
 2131         fhold(fp);
 2132         unp_rights++;
 2133         UNP_LINK_WUNLOCK();
 2134 }
 2135 
 2136 static int
 2137 unp_externalize_fp(struct file *fp)
 2138 {
 2139         struct unpcb *unp;
 2140         int ret;
 2141 
 2142         UNP_LINK_WLOCK();
 2143         if ((unp = fptounp(fp)) != NULL) {
 2144                 unp->unp_msgcount--;
 2145                 ret = 1;
 2146         } else
 2147                 ret = 0;
 2148         unp_rights--;
 2149         UNP_LINK_WUNLOCK();
 2150         return (ret);
 2151 }
 2152 
 2153 /*
 2154  * unp_defer indicates whether additional work has been defered for a future
 2155  * pass through unp_gc().  It is thread local and does not require explicit
 2156  * synchronization.
 2157  */
 2158 static int      unp_marked;
 2159 static int      unp_unreachable;
 2160 
 2161 static void
 2162 unp_accessable(struct filedescent **fdep, int fdcount)
 2163 {
 2164         struct unpcb *unp;
 2165         struct file *fp;
 2166         int i;
 2167 
 2168         for (i = 0; i < fdcount; i++) {
 2169                 fp = fdep[i]->fde_file;
 2170                 if ((unp = fptounp(fp)) == NULL)
 2171                         continue;
 2172                 if (unp->unp_gcflag & UNPGC_REF)
 2173                         continue;
 2174                 unp->unp_gcflag &= ~UNPGC_DEAD;
 2175                 unp->unp_gcflag |= UNPGC_REF;
 2176                 unp_marked++;
 2177         }
 2178 }
 2179 
 2180 static void
 2181 unp_gc_process(struct unpcb *unp)
 2182 {
 2183         struct socket *soa;
 2184         struct socket *so;
 2185         struct file *fp;
 2186 
 2187         /* Already processed. */
 2188         if (unp->unp_gcflag & UNPGC_SCANNED)
 2189                 return;
 2190         fp = unp->unp_file;
 2191 
 2192         /*
 2193          * Check for a socket potentially in a cycle.  It must be in a
 2194          * queue as indicated by msgcount, and this must equal the file
 2195          * reference count.  Note that when msgcount is 0 the file is NULL.
 2196          */
 2197         if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
 2198             unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
 2199                 unp->unp_gcflag |= UNPGC_DEAD;
 2200                 unp_unreachable++;
 2201                 return;
 2202         }
 2203 
 2204         /*
 2205          * Mark all sockets we reference with RIGHTS.
 2206          */
 2207         so = unp->unp_socket;
 2208         if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
 2209                 SOCKBUF_LOCK(&so->so_rcv);
 2210                 unp_scan(so->so_rcv.sb_mb, unp_accessable);
 2211                 SOCKBUF_UNLOCK(&so->so_rcv);
 2212         }
 2213 
 2214         /*
 2215          * Mark all sockets in our accept queue.
 2216          */
 2217         ACCEPT_LOCK();
 2218         TAILQ_FOREACH(soa, &so->so_comp, so_list) {
 2219                 if ((sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS) != 0)
 2220                         continue;
 2221                 SOCKBUF_LOCK(&soa->so_rcv);
 2222                 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
 2223                 SOCKBUF_UNLOCK(&soa->so_rcv);
 2224         }
 2225         ACCEPT_UNLOCK();
 2226         unp->unp_gcflag |= UNPGC_SCANNED;
 2227 }
 2228 
 2229 static int unp_recycled;
 2230 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, 
 2231     "Number of unreachable sockets claimed by the garbage collector.");
 2232 
 2233 static int unp_taskcount;
 2234 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, 
 2235     "Number of times the garbage collector has run.");
 2236 
 2237 static void
 2238 unp_gc(__unused void *arg, int pending)
 2239 {
 2240         struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
 2241                                     NULL };
 2242         struct unp_head **head;
 2243         struct file *f, **unref;
 2244         struct unpcb *unp;
 2245         int i, total;
 2246 
 2247         unp_taskcount++;
 2248         UNP_LIST_LOCK();
 2249         /*
 2250          * First clear all gc flags from previous runs, apart from
 2251          * UNPGC_IGNORE_RIGHTS.
 2252          */
 2253         for (head = heads; *head != NULL; head++)
 2254                 LIST_FOREACH(unp, *head, unp_link)
 2255                         unp->unp_gcflag =
 2256                             (unp->unp_gcflag & UNPGC_IGNORE_RIGHTS);
 2257 
 2258         /*
 2259          * Scan marking all reachable sockets with UNPGC_REF.  Once a socket
 2260          * is reachable all of the sockets it references are reachable.
 2261          * Stop the scan once we do a complete loop without discovering
 2262          * a new reachable socket.
 2263          */
 2264         do {
 2265                 unp_unreachable = 0;
 2266                 unp_marked = 0;
 2267                 for (head = heads; *head != NULL; head++)
 2268                         LIST_FOREACH(unp, *head, unp_link)
 2269                                 unp_gc_process(unp);
 2270         } while (unp_marked);
 2271         UNP_LIST_UNLOCK();
 2272         if (unp_unreachable == 0)
 2273                 return;
 2274 
 2275         /*
 2276          * Allocate space for a local list of dead unpcbs.
 2277          */
 2278         unref = malloc(unp_unreachable * sizeof(struct file *),
 2279             M_TEMP, M_WAITOK);
 2280 
 2281         /*
 2282          * Iterate looking for sockets which have been specifically marked
 2283          * as as unreachable and store them locally.
 2284          */
 2285         UNP_LINK_RLOCK();
 2286         UNP_LIST_LOCK();
 2287         for (total = 0, head = heads; *head != NULL; head++)
 2288                 LIST_FOREACH(unp, *head, unp_link)
 2289                         if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
 2290                                 f = unp->unp_file;
 2291                                 if (unp->unp_msgcount == 0 || f == NULL ||
 2292                                     f->f_count != unp->unp_msgcount)
 2293                                         continue;
 2294                                 unref[total++] = f;
 2295                                 fhold(f);
 2296                                 KASSERT(total <= unp_unreachable,
 2297                                     ("unp_gc: incorrect unreachable count."));
 2298                         }
 2299         UNP_LIST_UNLOCK();
 2300         UNP_LINK_RUNLOCK();
 2301 
 2302         /*
 2303          * Now flush all sockets, free'ing rights.  This will free the
 2304          * struct files associated with these sockets but leave each socket
 2305          * with one remaining ref.
 2306          */
 2307         for (i = 0; i < total; i++) {
 2308                 struct socket *so;
 2309 
 2310                 so = unref[i]->f_data;
 2311                 CURVNET_SET(so->so_vnet);
 2312                 sorflush(so);
 2313                 CURVNET_RESTORE();
 2314         }
 2315 
 2316         /*
 2317          * And finally release the sockets so they can be reclaimed.
 2318          */
 2319         for (i = 0; i < total; i++)
 2320                 fdrop(unref[i], NULL);
 2321         unp_recycled += total;
 2322         free(unref, M_TEMP);
 2323 }
 2324 
 2325 static void
 2326 unp_dispose(struct mbuf *m)
 2327 {
 2328 
 2329         if (m)
 2330                 unp_scan(m, unp_freerights);
 2331 }
 2332 
 2333 /*
 2334  * Synchronize against unp_gc, which can trip over data as we are freeing it.
 2335  */
 2336 void
 2337 unp_dispose_so(struct socket *so)
 2338 {
 2339         struct unpcb *unp;
 2340 
 2341         unp = sotounpcb(so);
 2342         UNP_LIST_LOCK();
 2343         unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
 2344         UNP_LIST_UNLOCK();
 2345         unp_dispose(so->so_rcv.sb_mb);
 2346 }
 2347 
 2348 static void
 2349 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
 2350 {
 2351         struct mbuf *m;
 2352         struct cmsghdr *cm;
 2353         void *data;
 2354         socklen_t clen, datalen;
 2355 
 2356         while (m0 != NULL) {
 2357                 for (m = m0; m; m = m->m_next) {
 2358                         if (m->m_type != MT_CONTROL)
 2359                                 continue;
 2360 
 2361                         cm = mtod(m, struct cmsghdr *);
 2362                         clen = m->m_len;
 2363 
 2364                         while (cm != NULL) {
 2365                                 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
 2366                                         break;
 2367 
 2368                                 data = CMSG_DATA(cm);
 2369                                 datalen = (caddr_t)cm + cm->cmsg_len
 2370                                     - (caddr_t)data;
 2371 
 2372                                 if (cm->cmsg_level == SOL_SOCKET &&
 2373                                     cm->cmsg_type == SCM_RIGHTS) {
 2374                                         (*op)(data, datalen /
 2375                                             sizeof(struct filedescent *));
 2376                                 }
 2377 
 2378                                 if (CMSG_SPACE(datalen) < clen) {
 2379                                         clen -= CMSG_SPACE(datalen);
 2380                                         cm = (struct cmsghdr *)
 2381                                             ((caddr_t)cm + CMSG_SPACE(datalen));
 2382                                 } else {
 2383                                         clen = 0;
 2384                                         cm = NULL;
 2385                                 }
 2386                         }
 2387                 }
 2388                 m0 = m0->m_nextpkt;
 2389         }
 2390 }
 2391 
 2392 /*
 2393  * A helper function called by VFS before socket-type vnode reclamation.
 2394  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
 2395  * use count.
 2396  */
 2397 void
 2398 vfs_unp_reclaim(struct vnode *vp)
 2399 {
 2400         struct socket *so;
 2401         struct unpcb *unp;
 2402         int active;
 2403 
 2404         ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
 2405         KASSERT(vp->v_type == VSOCK,
 2406             ("vfs_unp_reclaim: vp->v_type != VSOCK"));
 2407 
 2408         active = 0;
 2409         UNP_LINK_WLOCK();
 2410         VOP_UNP_CONNECT(vp, &so);
 2411         if (so == NULL)
 2412                 goto done;
 2413         unp = sotounpcb(so);
 2414         if (unp == NULL)
 2415                 goto done;
 2416         UNP_PCB_LOCK(unp);
 2417         if (unp->unp_vnode == vp) {
 2418                 VOP_UNP_DETACH(vp);
 2419                 unp->unp_vnode = NULL;
 2420                 active = 1;
 2421         }
 2422         UNP_PCB_UNLOCK(unp);
 2423 done:
 2424         UNP_LINK_WUNLOCK();
 2425         if (active)
 2426                 vunref(vp);
 2427 }
 2428 
 2429 #ifdef DDB
 2430 static void
 2431 db_print_indent(int indent)
 2432 {
 2433         int i;
 2434 
 2435         for (i = 0; i < indent; i++)
 2436                 db_printf(" ");
 2437 }
 2438 
 2439 static void
 2440 db_print_unpflags(int unp_flags)
 2441 {
 2442         int comma;
 2443 
 2444         comma = 0;
 2445         if (unp_flags & UNP_HAVEPC) {
 2446                 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
 2447                 comma = 1;
 2448         }
 2449         if (unp_flags & UNP_HAVEPCCACHED) {
 2450                 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
 2451                 comma = 1;
 2452         }
 2453         if (unp_flags & UNP_WANTCRED) {
 2454                 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
 2455                 comma = 1;
 2456         }
 2457         if (unp_flags & UNP_CONNWAIT) {
 2458                 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
 2459                 comma = 1;
 2460         }
 2461         if (unp_flags & UNP_CONNECTING) {
 2462                 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
 2463                 comma = 1;
 2464         }
 2465         if (unp_flags & UNP_BINDING) {
 2466                 db_printf("%sUNP_BINDING", comma ? ", " : "");
 2467                 comma = 1;
 2468         }
 2469 }
 2470 
 2471 static void
 2472 db_print_xucred(int indent, struct xucred *xu)
 2473 {
 2474         int comma, i;
 2475 
 2476         db_print_indent(indent);
 2477         db_printf("cr_version: %u   cr_uid: %u   cr_ngroups: %d\n",
 2478             xu->cr_version, xu->cr_uid, xu->cr_ngroups);
 2479         db_print_indent(indent);
 2480         db_printf("cr_groups: ");
 2481         comma = 0;
 2482         for (i = 0; i < xu->cr_ngroups; i++) {
 2483                 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
 2484                 comma = 1;
 2485         }
 2486         db_printf("\n");
 2487 }
 2488 
 2489 static void
 2490 db_print_unprefs(int indent, struct unp_head *uh)
 2491 {
 2492         struct unpcb *unp;
 2493         int counter;
 2494 
 2495         counter = 0;
 2496         LIST_FOREACH(unp, uh, unp_reflink) {
 2497                 if (counter % 4 == 0)
 2498                         db_print_indent(indent);
 2499                 db_printf("%p  ", unp);
 2500                 if (counter % 4 == 3)
 2501                         db_printf("\n");
 2502                 counter++;
 2503         }
 2504         if (counter != 0 && counter % 4 != 0)
 2505                 db_printf("\n");
 2506 }
 2507 
 2508 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
 2509 {
 2510         struct unpcb *unp;
 2511 
 2512         if (!have_addr) {
 2513                 db_printf("usage: show unpcb <addr>\n");
 2514                 return;
 2515         }
 2516         unp = (struct unpcb *)addr;
 2517 
 2518         db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
 2519             unp->unp_vnode);
 2520 
 2521         db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
 2522             unp->unp_conn);
 2523 
 2524         db_printf("unp_refs:\n");
 2525         db_print_unprefs(2, &unp->unp_refs);
 2526 
 2527         /* XXXRW: Would be nice to print the full address, if any. */
 2528         db_printf("unp_addr: %p\n", unp->unp_addr);
 2529 
 2530         db_printf("unp_gencnt: %llu\n",
 2531             (unsigned long long)unp->unp_gencnt);
 2532 
 2533         db_printf("unp_flags: %x (", unp->unp_flags);
 2534         db_print_unpflags(unp->unp_flags);
 2535         db_printf(")\n");
 2536 
 2537         db_printf("unp_peercred:\n");
 2538         db_print_xucred(2, &unp->unp_peercred);
 2539 
 2540         db_printf("unp_refcount: %u\n", unp->unp_refcount);
 2541 }
 2542 #endif

Cache object: 4d9a316af66d7d5f3b19def2a780f11e


[ 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.