xref: /freebsd/sys/kern/uipc_usrreq.c (revision a50b1900a02f1e279cc5822d06af90e704bc32db)
19454b2d8SWarner Losh /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
4df8bae1dSRodney W. Grimes  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5f344fb0bSWarner Losh  *	The Regents of the University of California. All Rights Reserved.
6f344fb0bSWarner Losh  * Copyright (c) 2004-2009 Robert N. M. Watson All Rights Reserved.
7c0874c34SMatt Macy  * Copyright (c) 2018 Matthew Macy
8df8bae1dSRodney W. Grimes  *
9df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
10df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
11df8bae1dSRodney W. Grimes  * are met:
12df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
13df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
14df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
15df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
16df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
1769a28758SEd Maste  * 3. Neither the name of the University nor the names of its contributors
18df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
19df8bae1dSRodney W. Grimes  *    without specific prior written permission.
20df8bae1dSRodney W. Grimes  *
21df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
32df8bae1dSRodney W. Grimes  *
33748e0b0aSGarrett Wollman  *	From: @(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
34df8bae1dSRodney W. Grimes  */
35df8bae1dSRodney W. Grimes 
36f23929fbSRobert Watson /*
37f23929fbSRobert Watson  * UNIX Domain (Local) Sockets
38f23929fbSRobert Watson  *
39f23929fbSRobert Watson  * This is an implementation of UNIX (local) domain sockets.  Each socket has
40f23929fbSRobert Watson  * an associated struct unpcb (UNIX protocol control block).  Stream sockets
41f23929fbSRobert Watson  * may be connected to 0 or 1 other socket.  Datagram sockets may be
42f23929fbSRobert Watson  * connected to 0, 1, or many other sockets.  Sockets may be created and
43f23929fbSRobert Watson  * connected in pairs (socketpair(2)), or bound/connected to using the file
44f23929fbSRobert Watson  * system name space.  For most purposes, only the receive socket buffer is
45f23929fbSRobert Watson  * used, as sending on one socket delivers directly to the receive socket
465b950deaSRobert Watson  * buffer of a second socket.
475b950deaSRobert Watson  *
485b950deaSRobert Watson  * The implementation is substantially complicated by the fact that
495b950deaSRobert Watson  * "ancillary data", such as file descriptors or credentials, may be passed
505b950deaSRobert Watson  * across UNIX domain sockets.  The potential for passing UNIX domain sockets
515b950deaSRobert Watson  * over other UNIX domain sockets requires the implementation of a simple
525b950deaSRobert Watson  * garbage collector to find and tear down cycles of disconnected sockets.
53aea52f1bSRobert Watson  *
54aea52f1bSRobert Watson  * TODO:
5584d61770SRobert Watson  *	RDM
56aea52f1bSRobert Watson  *	rethink name space problems
57aea52f1bSRobert Watson  *	need a proper out-of-band
58f23929fbSRobert Watson  */
59f23929fbSRobert Watson 
60677b542eSDavid E. O'Brien #include <sys/cdefs.h>
61677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
62677b542eSDavid E. O'Brien 
6303c96c31SRobert Watson #include "opt_ddb.h"
64335654d7SRobert Watson 
65df8bae1dSRodney W. Grimes #include <sys/param.h>
664a144410SRobert Watson #include <sys/capsicum.h>
67fb919e4dSMark Murray #include <sys/domain.h>
68960ed29cSSeigo Tanimura #include <sys/fcntl.h>
69d826c479SBruce Evans #include <sys/malloc.h>		/* XXX must be before <sys/file.h> */
704f590175SPaul Saab #include <sys/eventhandler.h>
71639acc13SGarrett Wollman #include <sys/file.h>
72960ed29cSSeigo Tanimura #include <sys/filedesc.h>
73960ed29cSSeigo Tanimura #include <sys/kernel.h>
74960ed29cSSeigo Tanimura #include <sys/lock.h>
75639acc13SGarrett Wollman #include <sys/mbuf.h>
76033eb86eSJeff Roberson #include <sys/mount.h>
77960ed29cSSeigo Tanimura #include <sys/mutex.h>
78639acc13SGarrett Wollman #include <sys/namei.h>
79639acc13SGarrett Wollman #include <sys/proc.h>
80df8bae1dSRodney W. Grimes #include <sys/protosw.h>
810cb64678SKonstantin Belousov #include <sys/queue.h>
82960ed29cSSeigo Tanimura #include <sys/resourcevar.h>
83e7c33e29SRobert Watson #include <sys/rwlock.h>
84df8bae1dSRodney W. Grimes #include <sys/socket.h>
85df8bae1dSRodney W. Grimes #include <sys/socketvar.h>
86960ed29cSSeigo Tanimura #include <sys/signalvar.h>
87df8bae1dSRodney W. Grimes #include <sys/stat.h>
88960ed29cSSeigo Tanimura #include <sys/sx.h>
89639acc13SGarrett Wollman #include <sys/sysctl.h>
90960ed29cSSeigo Tanimura #include <sys/systm.h>
91a0ec558aSRobert Watson #include <sys/taskqueue.h>
92639acc13SGarrett Wollman #include <sys/un.h>
9398271db4SGarrett Wollman #include <sys/unpcb.h>
94639acc13SGarrett Wollman #include <sys/vnode.h>
95530c0060SRobert Watson 
96530c0060SRobert Watson #include <net/vnet.h>
97df8bae1dSRodney W. Grimes 
9803c96c31SRobert Watson #ifdef DDB
9903c96c31SRobert Watson #include <ddb/ddb.h>
10003c96c31SRobert Watson #endif
10103c96c31SRobert Watson 
102aed55708SRobert Watson #include <security/mac/mac_framework.h>
103aed55708SRobert Watson 
1049e9d298aSJeff Roberson #include <vm/uma.h>
10598271db4SGarrett Wollman 
1068cb539f1SPawel Jakub Dawidek MALLOC_DECLARE(M_FILECAPS);
1078cb539f1SPawel Jakub Dawidek 
1083dab55bcSRobert Watson /*
1093dab55bcSRobert Watson  * Locking key:
1103dab55bcSRobert Watson  * (l)	Locked using list lock
1113dab55bcSRobert Watson  * (g)	Locked using linkage lock
1123dab55bcSRobert Watson  */
1133dab55bcSRobert Watson 
1149e9d298aSJeff Roberson static uma_zone_t	unp_zone;
1153dab55bcSRobert Watson static unp_gen_t	unp_gencnt;	/* (l) */
1163dab55bcSRobert Watson static u_int		unp_count;	/* (l) Count of local sockets. */
117aea52f1bSRobert Watson static ino_t		unp_ino;	/* Prototype for fake inode numbers. */
1183dab55bcSRobert Watson static int		unp_rights;	/* (g) File descriptors in flight. */
1193dab55bcSRobert Watson static struct unp_head	unp_shead;	/* (l) List of stream sockets. */
1203dab55bcSRobert Watson static struct unp_head	unp_dhead;	/* (l) List of datagram sockets. */
12184d61770SRobert Watson static struct unp_head	unp_sphead;	/* (l) List of seqpacket sockets. */
12298271db4SGarrett Wollman 
1230cb64678SKonstantin Belousov struct unp_defer {
1240cb64678SKonstantin Belousov 	SLIST_ENTRY(unp_defer) ud_link;
1250cb64678SKonstantin Belousov 	struct file *ud_fp;
1260cb64678SKonstantin Belousov };
1270cb64678SKonstantin Belousov static SLIST_HEAD(, unp_defer) unp_defers;
1280cb64678SKonstantin Belousov static int unp_defers_count;
1290cb64678SKonstantin Belousov 
130aea52f1bSRobert Watson static const struct sockaddr	sun_noname = { sizeof(sun_noname), AF_LOCAL };
13198271db4SGarrett Wollman 
132df8bae1dSRodney W. Grimes /*
133aea52f1bSRobert Watson  * Garbage collection of cyclic file descriptor/socket references occurs
134aea52f1bSRobert Watson  * asynchronously in a taskqueue context in order to avoid recursion and
135aea52f1bSRobert Watson  * reentrance in the UNIX domain socket, file descriptor, and socket layer
136aea52f1bSRobert Watson  * code.  See unp_gc() for a full description.
137df8bae1dSRodney W. Grimes  */
138daee0f0bSKonstantin Belousov static struct timeout_task unp_gc_task;
139f708ef1bSPoul-Henning Kamp 
140ce5f32deSRobert Watson /*
1410cb64678SKonstantin Belousov  * The close of unix domain sockets attached as SCM_RIGHTS is
1420cb64678SKonstantin Belousov  * postponed to the taskqueue, to avoid arbitrary recursion depth.
1430cb64678SKonstantin Belousov  * The attached sockets might have another sockets attached.
1440cb64678SKonstantin Belousov  */
1450cb64678SKonstantin Belousov static struct task	unp_defer_task;
1460cb64678SKonstantin Belousov 
1470cb64678SKonstantin Belousov /*
1487e711c3aSRobert Watson  * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
1497e711c3aSRobert Watson  * stream sockets, although the total for sender and receiver is actually
1507e711c3aSRobert Watson  * only PIPSIZ.
1517e711c3aSRobert Watson  *
1527e711c3aSRobert Watson  * Datagram sockets really use the sendspace as the maximum datagram size,
1537e711c3aSRobert Watson  * and don't really want to reserve the sendspace.  Their recvspace should be
1547e711c3aSRobert Watson  * large enough for at least one max-size datagram plus address.
1557e711c3aSRobert Watson  */
1567e711c3aSRobert Watson #ifndef PIPSIZ
1577e711c3aSRobert Watson #define	PIPSIZ	8192
1587e711c3aSRobert Watson #endif
1597e711c3aSRobert Watson static u_long	unpst_sendspace = PIPSIZ;
1607e711c3aSRobert Watson static u_long	unpst_recvspace = PIPSIZ;
1617e711c3aSRobert Watson static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
1627e711c3aSRobert Watson static u_long	unpdg_recvspace = 4*1024;
16384d61770SRobert Watson static u_long	unpsp_sendspace = PIPSIZ;	/* really max datagram size */
16484d61770SRobert Watson static u_long	unpsp_recvspace = PIPSIZ;
1657e711c3aSRobert Watson 
1667029da5cSPawel Biernacki static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1677029da5cSPawel Biernacki     "Local domain");
1687029da5cSPawel Biernacki static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
1697029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1706472ac3dSEd Schouten     "SOCK_STREAM");
1717029da5cSPawel Biernacki static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
1727029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1737029da5cSPawel Biernacki     "SOCK_DGRAM");
1747029da5cSPawel Biernacki static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
1757029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
17684d61770SRobert Watson     "SOCK_SEQPACKET");
177e4445a03SRobert Watson 
1787e711c3aSRobert Watson SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
179be6b1304STom Rhodes 	   &unpst_sendspace, 0, "Default stream send space.");
1807e711c3aSRobert Watson SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
181be6b1304STom Rhodes 	   &unpst_recvspace, 0, "Default stream receive space.");
1827e711c3aSRobert Watson SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
183be6b1304STom Rhodes 	   &unpdg_sendspace, 0, "Default datagram send space.");
1847e711c3aSRobert Watson SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
185be6b1304STom Rhodes 	   &unpdg_recvspace, 0, "Default datagram receive space.");
18684d61770SRobert Watson SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
18784d61770SRobert Watson 	   &unpsp_sendspace, 0, "Default seqpacket send space.");
18884d61770SRobert Watson SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
18984d61770SRobert Watson 	   &unpsp_recvspace, 0, "Default seqpacket receive space.");
190be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
191be6b1304STom Rhodes     "File descriptors in flight.");
1920cb64678SKonstantin Belousov SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
1930cb64678SKonstantin Belousov     &unp_defers_count, 0,
1940cb64678SKonstantin Belousov     "File descriptors deferred to taskqueue for close.");
1957e711c3aSRobert Watson 
196175389cfSEdward Tomasz Napierala /*
197e7c33e29SRobert Watson  * Locking and synchronization:
198ce5f32deSRobert Watson  *
19975a67bf3SMatt Macy  * Three types of locks exist in the local domain socket implementation: a
20075a67bf3SMatt Macy  * a global linkage rwlock, the mtxpool lock, and per-unpcb mutexes.
20175a67bf3SMatt Macy  * The linkage lock protects the socket count, global generation number,
20275a67bf3SMatt Macy  * and stream/datagram global lists.
20375a67bf3SMatt Macy  *
20475a67bf3SMatt Macy  * The mtxpool lock protects the vnode from being modified while referenced.
20575a67bf3SMatt Macy  * Lock ordering requires that it be acquired before any unpcb locks.
20675a67bf3SMatt Macy  *
20775a67bf3SMatt Macy  * The unpcb lock (unp_mtx) protects all fields in the unpcb. Of particular
20875a67bf3SMatt Macy  * note is that this includes the unp_conn field. So long as the unpcb lock
20975a67bf3SMatt Macy  * is held the reference to the unpcb pointed to by unp_conn is valid. If we
21075a67bf3SMatt Macy  * require that the unpcb pointed to by unp_conn remain live in cases where
21175a67bf3SMatt Macy  * we need to drop the unp_mtx as when we need to acquire the lock for a
21275a67bf3SMatt Macy  * second unpcb the caller must first acquire an additional reference on the
21375a67bf3SMatt Macy  * second unpcb and then revalidate any state (typically check that unp_conn
21475a67bf3SMatt Macy  * is non-NULL) upon requiring the initial unpcb lock. The lock ordering
21575a67bf3SMatt Macy  * between unpcbs is the conventional ascending address order. Two helper
21675a67bf3SMatt Macy  * routines exist for this:
21775a67bf3SMatt Macy  *
21875a67bf3SMatt Macy  *   - unp_pcb_lock2(unp, unp2) - which just acquires the two locks in the
21975a67bf3SMatt Macy  *     safe ordering.
22075a67bf3SMatt Macy  *
22175a67bf3SMatt Macy  *   - unp_pcb_owned_lock2(unp, unp2, freed) - the lock for unp is held
22275a67bf3SMatt Macy  *     when called. If unp is unlocked and unp2 is subsequently freed
22375a67bf3SMatt Macy  *     freed will be set to 1.
22475a67bf3SMatt Macy  *
22575a67bf3SMatt Macy  * The helper routines for references are:
22675a67bf3SMatt Macy  *
22775a67bf3SMatt Macy  *   - unp_pcb_hold(unp): Can be called any time we currently hold a valid
22875a67bf3SMatt Macy  *     reference to unp.
22975a67bf3SMatt Macy  *
23075a67bf3SMatt Macy  *    - unp_pcb_rele(unp): The caller must hold the unp lock. If we are
23175a67bf3SMatt Macy  *      releasing the last reference, detach must have been called thus
23275a67bf3SMatt Macy  *      unp->unp_socket be NULL.
233ce5f32deSRobert Watson  *
234e7c33e29SRobert Watson  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
235e7c33e29SRobert Watson  * allocated in pru_attach() and freed in pru_detach().  The validity of that
236e7c33e29SRobert Watson  * pointer is an invariant, so no lock is required to dereference the so_pcb
237e7c33e29SRobert Watson  * pointer if a valid socket reference is held by the caller.  In practice,
238e7c33e29SRobert Watson  * this is always true during operations performed on a socket.  Each unpcb
239e7c33e29SRobert Watson  * has a back-pointer to its socket, unp_socket, which will be stable under
240e7c33e29SRobert Watson  * the same circumstances.
241e7c33e29SRobert Watson  *
242e7c33e29SRobert Watson  * This pointer may only be safely dereferenced as long as a valid reference
243e7c33e29SRobert Watson  * to the unpcb is held.  Typically, this reference will be from the socket,
244e7c33e29SRobert Watson  * or from another unpcb when the referring unpcb's lock is held (in order
245e7c33e29SRobert Watson  * that the reference not be invalidated during use).  For example, to follow
24675a67bf3SMatt Macy  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
24775a67bf3SMatt Macy  * that detach is not run clearing unp_socket.
248e7c33e29SRobert Watson  *
249e7c33e29SRobert Watson  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
250e7c33e29SRobert Watson  * protocols, bind() is a non-atomic operation, and connect() requires
251e7c33e29SRobert Watson  * potential sleeping in the protocol, due to potentially waiting on local or
252e7c33e29SRobert Watson  * distributed file systems.  We try to separate "lookup" operations, which
253e7c33e29SRobert Watson  * may sleep, and the IPC operations themselves, which typically can occur
254e7c33e29SRobert Watson  * with relative atomicity as locks can be held over the entire operation.
255e7c33e29SRobert Watson  *
256e7c33e29SRobert Watson  * Another tricky issue is simultaneous multi-threaded or multi-process
257e7c33e29SRobert Watson  * access to a single UNIX domain socket.  These are handled by the flags
258e7c33e29SRobert Watson  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
259e7c33e29SRobert Watson  * binding, both of which involve dropping UNIX domain socket locks in order
260e7c33e29SRobert Watson  * to perform namei() and other file system operations.
261ce5f32deSRobert Watson  */
2623dab55bcSRobert Watson static struct rwlock	unp_link_rwlock;
2630cb64678SKonstantin Belousov static struct mtx	unp_defers_lock;
264e7c33e29SRobert Watson 
2653dab55bcSRobert Watson #define	UNP_LINK_LOCK_INIT()		rw_init(&unp_link_rwlock,	\
2663dab55bcSRobert Watson 					    "unp_link_rwlock")
267e7c33e29SRobert Watson 
2683dab55bcSRobert Watson #define	UNP_LINK_LOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
269e7c33e29SRobert Watson 					    RA_LOCKED)
2703dab55bcSRobert Watson #define	UNP_LINK_UNLOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
271e7c33e29SRobert Watson 					    RA_UNLOCKED)
272e7c33e29SRobert Watson 
2733dab55bcSRobert Watson #define	UNP_LINK_RLOCK()		rw_rlock(&unp_link_rwlock)
2743dab55bcSRobert Watson #define	UNP_LINK_RUNLOCK()		rw_runlock(&unp_link_rwlock)
2753dab55bcSRobert Watson #define	UNP_LINK_WLOCK()		rw_wlock(&unp_link_rwlock)
2763dab55bcSRobert Watson #define	UNP_LINK_WUNLOCK()		rw_wunlock(&unp_link_rwlock)
2773dab55bcSRobert Watson #define	UNP_LINK_WLOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
278e7c33e29SRobert Watson 					    RA_WLOCKED)
279779f106aSGleb Smirnoff #define	UNP_LINK_WOWNED()		rw_wowned(&unp_link_rwlock)
280e7c33e29SRobert Watson 
2810cb64678SKonstantin Belousov #define	UNP_DEFERRED_LOCK_INIT()	mtx_init(&unp_defers_lock, \
2820cb64678SKonstantin Belousov 					    "unp_defer", NULL, MTX_DEF)
2830cb64678SKonstantin Belousov #define	UNP_DEFERRED_LOCK()		mtx_lock(&unp_defers_lock)
2840cb64678SKonstantin Belousov #define	UNP_DEFERRED_UNLOCK()		mtx_unlock(&unp_defers_lock)
2850cb64678SKonstantin Belousov 
28675a67bf3SMatt Macy #define UNP_REF_LIST_LOCK()		UNP_DEFERRED_LOCK();
28775a67bf3SMatt Macy #define UNP_REF_LIST_UNLOCK()		UNP_DEFERRED_UNLOCK();
28875a67bf3SMatt Macy 
289e7c33e29SRobert Watson #define UNP_PCB_LOCK_INIT(unp)		mtx_init(&(unp)->unp_mtx,	\
290d9525340SMatt Macy 					    "unp", "unp",	\
29175a67bf3SMatt Macy 					    MTX_DUPOK|MTX_DEF)
292e7c33e29SRobert Watson #define	UNP_PCB_LOCK_DESTROY(unp)	mtx_destroy(&(unp)->unp_mtx)
293e7c33e29SRobert Watson #define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
29475a67bf3SMatt Macy #define	UNP_PCB_TRYLOCK(unp)		mtx_trylock(&(unp)->unp_mtx)
295e7c33e29SRobert Watson #define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
29675a67bf3SMatt Macy #define	UNP_PCB_OWNED(unp)		mtx_owned(&(unp)->unp_mtx)
297e7c33e29SRobert Watson #define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
29875a67bf3SMatt Macy #define	UNP_PCB_UNLOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
2990d9ce3a1SRobert Watson 
3002c899584SRobert Watson static int	uipc_connect2(struct socket *, struct socket *);
3010b36cd25SRobert Watson static int	uipc_ctloutput(struct socket *, struct sockopt *);
302aea52f1bSRobert Watson static int	unp_connect(struct socket *, struct sockaddr *,
303aea52f1bSRobert Watson 		    struct thread *);
3047493f24eSPawel Jakub Dawidek static int	unp_connectat(int, struct socket *, struct sockaddr *,
3057493f24eSPawel Jakub Dawidek 		    struct thread *);
3066a2989fdSMatthew N. Dodd static int	unp_connect2(struct socket *so, struct socket *so2, int);
307e7c33e29SRobert Watson static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
30899ab95dbSMark Johnston static void	unp_dispose(struct socket *so);
30999ab95dbSMark Johnston static void	unp_dispose_mbuf(struct mbuf *);
3104d77a549SAlfred Perlstein static void	unp_shutdown(struct unpcb *);
311afc055d9SEd Schouten static void	unp_drop(struct unpcb *);
312a0ec558aSRobert Watson static void	unp_gc(__unused void *, int);
313be26ba7cSPawel Jakub Dawidek static void	unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
3144d77a549SAlfred Perlstein static void	unp_discard(struct file *);
3158cb539f1SPawel Jakub Dawidek static void	unp_freerights(struct filedescent **, int);
3160b36cd25SRobert Watson static void	unp_init(void);
3174d77a549SAlfred Perlstein static int	unp_internalize(struct mbuf **, struct thread *);
318397c19d1SJeff Roberson static void	unp_internalize_fp(struct file *);
319c2e3c52eSJilles Tjoelker static int	unp_externalize(struct mbuf *, struct mbuf **, int);
3200cb64678SKonstantin Belousov static int	unp_externalize_fp(struct file *);
3215b950deaSRobert Watson static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *);
3220cb64678SKonstantin Belousov static void	unp_process_defers(void * __unused, int);
323f708ef1bSPoul-Henning Kamp 
32475a67bf3SMatt Macy static void
32575a67bf3SMatt Macy unp_pcb_hold(struct unpcb *unp)
32675a67bf3SMatt Macy {
32775a67bf3SMatt Macy 	MPASS(unp->unp_refcount);
32875a67bf3SMatt Macy 	refcount_acquire(&unp->unp_refcount);
32975a67bf3SMatt Macy }
33075a67bf3SMatt Macy 
33175a67bf3SMatt Macy static int
33275a67bf3SMatt Macy unp_pcb_rele(struct unpcb *unp)
33375a67bf3SMatt Macy {
33475a67bf3SMatt Macy 	int freed;
33575a67bf3SMatt Macy 
33675a67bf3SMatt Macy 	UNP_PCB_LOCK_ASSERT(unp);
33775a67bf3SMatt Macy 	MPASS(unp->unp_refcount);
33875a67bf3SMatt Macy 	if ((freed = refcount_release(&unp->unp_refcount))) {
33975a67bf3SMatt Macy 		/* we got here with having detached? */
34075a67bf3SMatt Macy 		MPASS(unp->unp_socket == NULL);
34175a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
34275a67bf3SMatt Macy 		UNP_PCB_LOCK_DESTROY(unp);
34375a67bf3SMatt Macy 		uma_zfree(unp_zone, unp);
34475a67bf3SMatt Macy 	}
34575a67bf3SMatt Macy 	return (freed);
34675a67bf3SMatt Macy }
34775a67bf3SMatt Macy 
34875a67bf3SMatt Macy static void
34975a67bf3SMatt Macy unp_pcb_lock2(struct unpcb *unp, struct unpcb *unp2)
35075a67bf3SMatt Macy {
35116529dacSMatt Macy 	MPASS(unp != unp2);
35275a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
35375a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp2);
35475a67bf3SMatt Macy 	if ((uintptr_t)unp2 > (uintptr_t)unp) {
35575a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
35675a67bf3SMatt Macy 		UNP_PCB_LOCK(unp2);
35775a67bf3SMatt Macy 	} else {
35875a67bf3SMatt Macy 		UNP_PCB_LOCK(unp2);
35975a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
36075a67bf3SMatt Macy 	}
36175a67bf3SMatt Macy }
36275a67bf3SMatt Macy 
36375a67bf3SMatt Macy static __noinline void
364e62ca80bSMark Johnston unp_pcb_owned_lock2_slowpath(struct unpcb *unp, struct unpcb **unp2p,
365e62ca80bSMark Johnston     int *freed)
36675a67bf3SMatt Macy {
36775a67bf3SMatt Macy 	struct unpcb *unp2;
36875a67bf3SMatt Macy 
36975a67bf3SMatt Macy 	unp2 = *unp2p;
370e62ca80bSMark Johnston 	unp_pcb_hold(unp2);
371e62ca80bSMark Johnston 	UNP_PCB_UNLOCK(unp);
372e62ca80bSMark Johnston 	UNP_PCB_LOCK(unp2);
373e62ca80bSMark Johnston 	UNP_PCB_LOCK(unp);
374e62ca80bSMark Johnston 	*freed = unp_pcb_rele(unp2);
37575a67bf3SMatt Macy 	if (*freed)
37675a67bf3SMatt Macy 		*unp2p = NULL;
37775a67bf3SMatt Macy }
37875a67bf3SMatt Macy 
37975a67bf3SMatt Macy #define unp_pcb_owned_lock2(unp, unp2, freed) do {			\
38075a67bf3SMatt Macy 	freed = 0;							\
381e62ca80bSMark Johnston 	UNP_PCB_LOCK_ASSERT(unp);					\
382e62ca80bSMark Johnston 	UNP_PCB_UNLOCK_ASSERT(unp2);					\
383e62ca80bSMark Johnston 	MPASS((unp) != (unp2));						\
384e62ca80bSMark Johnston 	if (__predict_true(UNP_PCB_TRYLOCK(unp2)))			\
38575a67bf3SMatt Macy 		break;							\
38675a67bf3SMatt Macy 	else if ((uintptr_t)(unp2) > (uintptr_t)(unp))			\
387e62ca80bSMark Johnston 		UNP_PCB_LOCK(unp2);					\
388e62ca80bSMark Johnston 	else								\
38975a67bf3SMatt Macy 		unp_pcb_owned_lock2_slowpath((unp), &(unp2), &freed);	\
39075a67bf3SMatt Macy } while (0)
39175a67bf3SMatt Macy 
392e4445a03SRobert Watson /*
393e4445a03SRobert Watson  * Definitions of protocols supported in the LOCAL domain.
394e4445a03SRobert Watson  */
395e4445a03SRobert Watson static struct domain localdomain;
396fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
39784d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket;
398e4445a03SRobert Watson static struct protosw localsw[] = {
399e4445a03SRobert Watson {
400e4445a03SRobert Watson 	.pr_type =		SOCK_STREAM,
401e4445a03SRobert Watson 	.pr_domain =		&localdomain,
402e4445a03SRobert Watson 	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
403e4445a03SRobert Watson 	.pr_ctloutput =		&uipc_ctloutput,
404fa9402f2SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_stream
405e4445a03SRobert Watson },
406e4445a03SRobert Watson {
407e4445a03SRobert Watson 	.pr_type =		SOCK_DGRAM,
408e4445a03SRobert Watson 	.pr_domain =		&localdomain,
409e4445a03SRobert Watson 	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS,
410aaf63435SGleb Smirnoff 	.pr_ctloutput =		&uipc_ctloutput,
411fa9402f2SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_dgram
412e4445a03SRobert Watson },
41384d61770SRobert Watson {
41484d61770SRobert Watson 	.pr_type =		SOCK_SEQPACKET,
41584d61770SRobert Watson 	.pr_domain =		&localdomain,
41684d61770SRobert Watson 
41784d61770SRobert Watson 	/*
41884d61770SRobert Watson 	 * XXXRW: For now, PR_ADDR because soreceive will bump into them
41984d61770SRobert Watson 	 * due to our use of sbappendaddr.  A new sbappend variants is needed
42084d61770SRobert Watson 	 * that supports both atomic record writes and control data.
42184d61770SRobert Watson 	 */
42284d61770SRobert Watson 	.pr_flags =		PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
42384d61770SRobert Watson 				    PR_RIGHTS,
424e0643280SGleb Smirnoff 	.pr_ctloutput =		&uipc_ctloutput,
42584d61770SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_seqpacket,
42684d61770SRobert Watson },
427e4445a03SRobert Watson };
428e4445a03SRobert Watson 
429e4445a03SRobert Watson static struct domain localdomain = {
430e4445a03SRobert Watson 	.dom_family =		AF_LOCAL,
431e4445a03SRobert Watson 	.dom_name =		"local",
432e4445a03SRobert Watson 	.dom_init =		unp_init,
433e4445a03SRobert Watson 	.dom_externalize =	unp_externalize,
43499ab95dbSMark Johnston 	.dom_dispose =		unp_dispose,
435e4445a03SRobert Watson 	.dom_protosw =		localsw,
43602abd400SPedro F. Giffuni 	.dom_protoswNPROTOSW =	&localsw[nitems(localsw)]
437e4445a03SRobert Watson };
438e4445a03SRobert Watson DOMAIN_SET(local);
439e4445a03SRobert Watson 
440ac45e92fSRobert Watson static void
441a29f300eSGarrett Wollman uipc_abort(struct socket *so)
442df8bae1dSRodney W. Grimes {
443e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
444df8bae1dSRodney W. Grimes 
44540f2ac28SRobert Watson 	unp = sotounpcb(so);
4464d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
44775a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
448e7c33e29SRobert Watson 
449e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
450e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
451e7c33e29SRobert Watson 	if (unp2 != NULL) {
45275a67bf3SMatt Macy 		unp_pcb_hold(unp2);
453e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
45475a67bf3SMatt Macy 		unp_drop(unp2);
45575a67bf3SMatt Macy 	} else
45675a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
457df8bae1dSRodney W. Grimes }
458df8bae1dSRodney W. Grimes 
459a29f300eSGarrett Wollman static int
46057bf258eSGarrett Wollman uipc_accept(struct socket *so, struct sockaddr **nam)
461a29f300eSGarrett Wollman {
462e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
4630d9ce3a1SRobert Watson 	const struct sockaddr *sa;
464df8bae1dSRodney W. Grimes 
465df8bae1dSRodney W. Grimes 	/*
4661c381b19SRobert Watson 	 * Pass back name of connected socket, if it was bound and we are
4671c381b19SRobert Watson 	 * still connected (our peer may have closed already!).
468df8bae1dSRodney W. Grimes 	 */
4694d4b555eSRobert Watson 	unp = sotounpcb(so);
4704d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
471e7c33e29SRobert Watson 
4720d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
4733dab55bcSRobert Watson 	UNP_LINK_RLOCK();
474e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
475e7c33e29SRobert Watson 	if (unp2 != NULL && unp2->unp_addr != NULL) {
476e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp2);
477e7c33e29SRobert Watson 		sa = (struct sockaddr *) unp2->unp_addr;
478e7c33e29SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
479e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
480e7c33e29SRobert Watson 	} else {
4810d9ce3a1SRobert Watson 		sa = &sun_noname;
4820d9ce3a1SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
483e7c33e29SRobert Watson 	}
4843dab55bcSRobert Watson 	UNP_LINK_RUNLOCK();
485e5aeaa0cSDag-Erling Smørgrav 	return (0);
486a29f300eSGarrett Wollman }
487df8bae1dSRodney W. Grimes 
488a29f300eSGarrett Wollman static int
489b40ce416SJulian Elischer uipc_attach(struct socket *so, int proto, struct thread *td)
490a29f300eSGarrett Wollman {
491e7c33e29SRobert Watson 	u_long sendspace, recvspace;
4926d32873cSRobert Watson 	struct unpcb *unp;
4933dab55bcSRobert Watson 	int error;
494779f106aSGleb Smirnoff 	bool locked;
495df8bae1dSRodney W. Grimes 
4966d32873cSRobert Watson 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
4976d32873cSRobert Watson 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
4986d32873cSRobert Watson 		switch (so->so_type) {
4996d32873cSRobert Watson 		case SOCK_STREAM:
500e7c33e29SRobert Watson 			sendspace = unpst_sendspace;
501e7c33e29SRobert Watson 			recvspace = unpst_recvspace;
5026d32873cSRobert Watson 			break;
5036d32873cSRobert Watson 
5046d32873cSRobert Watson 		case SOCK_DGRAM:
505e7c33e29SRobert Watson 			sendspace = unpdg_sendspace;
506e7c33e29SRobert Watson 			recvspace = unpdg_recvspace;
5076d32873cSRobert Watson 			break;
5086d32873cSRobert Watson 
50984d61770SRobert Watson 		case SOCK_SEQPACKET:
51084d61770SRobert Watson 			sendspace = unpsp_sendspace;
51184d61770SRobert Watson 			recvspace = unpsp_recvspace;
51284d61770SRobert Watson 			break;
51384d61770SRobert Watson 
5146d32873cSRobert Watson 		default:
515e7c33e29SRobert Watson 			panic("uipc_attach");
5166d32873cSRobert Watson 		}
517e7c33e29SRobert Watson 		error = soreserve(so, sendspace, recvspace);
5186d32873cSRobert Watson 		if (error)
5196d32873cSRobert Watson 			return (error);
5206d32873cSRobert Watson 	}
52146a1d9bfSRobert Watson 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
5226d32873cSRobert Watson 	if (unp == NULL)
5236d32873cSRobert Watson 		return (ENOBUFS);
5246d32873cSRobert Watson 	LIST_INIT(&unp->unp_refs);
525e7c33e29SRobert Watson 	UNP_PCB_LOCK_INIT(unp);
5266d32873cSRobert Watson 	unp->unp_socket = so;
5276d32873cSRobert Watson 	so->so_pcb = unp;
5289ae328fcSJohn Baldwin 	unp->unp_refcount = 1;
529e7c33e29SRobert Watson 
530779f106aSGleb Smirnoff 	if ((locked = UNP_LINK_WOWNED()) == false)
531779f106aSGleb Smirnoff 		UNP_LINK_WLOCK();
532779f106aSGleb Smirnoff 
5336d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
534f218ac50SMateusz Guzik 	unp->unp_ino = ++unp_ino;
5356d32873cSRobert Watson 	unp_count++;
53684d61770SRobert Watson 	switch (so->so_type) {
53784d61770SRobert Watson 	case SOCK_STREAM:
53884d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
53984d61770SRobert Watson 		break;
54084d61770SRobert Watson 
54184d61770SRobert Watson 	case SOCK_DGRAM:
54284d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
54384d61770SRobert Watson 		break;
54484d61770SRobert Watson 
54584d61770SRobert Watson 	case SOCK_SEQPACKET:
54684d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
54784d61770SRobert Watson 		break;
54884d61770SRobert Watson 
54984d61770SRobert Watson 	default:
55084d61770SRobert Watson 		panic("uipc_attach");
55184d61770SRobert Watson 	}
552779f106aSGleb Smirnoff 
553779f106aSGleb Smirnoff 	if (locked == false)
554779f106aSGleb Smirnoff 		UNP_LINK_WUNLOCK();
5556d32873cSRobert Watson 
5566d32873cSRobert Watson 	return (0);
557a29f300eSGarrett Wollman }
558a29f300eSGarrett Wollman 
559a29f300eSGarrett Wollman static int
5607493f24eSPawel Jakub Dawidek uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
561a29f300eSGarrett Wollman {
562dd47f5caSRobert Watson 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
563dd47f5caSRobert Watson 	struct vattr vattr;
5645050aa86SKonstantin Belousov 	int error, namelen;
565dd47f5caSRobert Watson 	struct nameidata nd;
56640f2ac28SRobert Watson 	struct unpcb *unp;
567dd47f5caSRobert Watson 	struct vnode *vp;
568dd47f5caSRobert Watson 	struct mount *mp;
5697008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
570dd47f5caSRobert Watson 	char *buf;
571a29f300eSGarrett Wollman 
572cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
573cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
574cb7df69bSKevin Lo 
57540f2ac28SRobert Watson 	unp = sotounpcb(so);
5764d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
5774f1f0ef5SRobert Watson 
578a06534c3SBjoern A. Zeeb 	if (soun->sun_len > sizeof(struct sockaddr_un))
579a06534c3SBjoern A. Zeeb 		return (EINVAL);
5804f1f0ef5SRobert Watson 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
5814f1f0ef5SRobert Watson 	if (namelen <= 0)
5824f1f0ef5SRobert Watson 		return (EINVAL);
583dd47f5caSRobert Watson 
584dd47f5caSRobert Watson 	/*
5854f1f0ef5SRobert Watson 	 * We don't allow simultaneous bind() calls on a single UNIX domain
5864f1f0ef5SRobert Watson 	 * socket, so flag in-progress operations, and return an error if an
5874f1f0ef5SRobert Watson 	 * operation is already in progress.
5884f1f0ef5SRobert Watson 	 *
5894f1f0ef5SRobert Watson 	 * Historically, we have not allowed a socket to be rebound, so this
590d7924b70SRobert Watson 	 * also returns an error.  Not allowing re-binding simplifies the
591d7924b70SRobert Watson 	 * implementation and avoids a great many possible failure modes.
592dd47f5caSRobert Watson 	 */
593e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
594dd47f5caSRobert Watson 	if (unp->unp_vnode != NULL) {
595e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
596dd47f5caSRobert Watson 		return (EINVAL);
597dd47f5caSRobert Watson 	}
5984f1f0ef5SRobert Watson 	if (unp->unp_flags & UNP_BINDING) {
599e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
6004f1f0ef5SRobert Watson 		return (EALREADY);
601dd47f5caSRobert Watson 	}
6024f1f0ef5SRobert Watson 	unp->unp_flags |= UNP_BINDING;
603e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
604dd47f5caSRobert Watson 
605dd47f5caSRobert Watson 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
6067928893dSEd Maste 	bcopy(soun->sun_path, buf, namelen);
6077928893dSEd Maste 	buf[namelen] = 0;
608dd47f5caSRobert Watson 
609dd47f5caSRobert Watson restart:
6106c21f6edSKonstantin Belousov 	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
6117008be5bSPawel Jakub Dawidek 	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
612dd47f5caSRobert Watson /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
613dd47f5caSRobert Watson 	error = namei(&nd);
614dd47f5caSRobert Watson 	if (error)
6154f1f0ef5SRobert Watson 		goto error;
616dd47f5caSRobert Watson 	vp = nd.ni_vp;
617dd47f5caSRobert Watson 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
618dd47f5caSRobert Watson 		NDFREE(&nd, NDF_ONLY_PNBUF);
619dd47f5caSRobert Watson 		if (nd.ni_dvp == vp)
620dd47f5caSRobert Watson 			vrele(nd.ni_dvp);
621dd47f5caSRobert Watson 		else
622dd47f5caSRobert Watson 			vput(nd.ni_dvp);
623dd47f5caSRobert Watson 		if (vp != NULL) {
624dd47f5caSRobert Watson 			vrele(vp);
625dd47f5caSRobert Watson 			error = EADDRINUSE;
6264f1f0ef5SRobert Watson 			goto error;
627dd47f5caSRobert Watson 		}
628dd47f5caSRobert Watson 		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
629dd47f5caSRobert Watson 		if (error)
6304f1f0ef5SRobert Watson 			goto error;
631dd47f5caSRobert Watson 		goto restart;
632dd47f5caSRobert Watson 	}
633dd47f5caSRobert Watson 	VATTR_NULL(&vattr);
634dd47f5caSRobert Watson 	vattr.va_type = VSOCK;
635dd47f5caSRobert Watson 	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
636dd47f5caSRobert Watson #ifdef MAC
63730d239bcSRobert Watson 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
638dd47f5caSRobert Watson 	    &vattr);
639dd47f5caSRobert Watson #endif
640885868cdSRobert Watson 	if (error == 0)
641dd47f5caSRobert Watson 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
642dd47f5caSRobert Watson 	NDFREE(&nd, NDF_ONLY_PNBUF);
643dd47f5caSRobert Watson 	vput(nd.ni_dvp);
644dd47f5caSRobert Watson 	if (error) {
645dd47f5caSRobert Watson 		vn_finished_write(mp);
6464f1f0ef5SRobert Watson 		goto error;
647dd47f5caSRobert Watson 	}
648dd47f5caSRobert Watson 	vp = nd.ni_vp;
64957fd3d55SPawel Jakub Dawidek 	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
650dd47f5caSRobert Watson 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
651e7c33e29SRobert Watson 
652e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6530c3c207fSGleb Smirnoff 	VOP_UNP_BIND(vp, unp);
654dd47f5caSRobert Watson 	unp->unp_vnode = vp;
655dd47f5caSRobert Watson 	unp->unp_addr = soun;
6564f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
657e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
658b249ce48SMateusz Guzik 	VOP_UNLOCK(vp);
659dd47f5caSRobert Watson 	vn_finished_write(mp);
6604f1f0ef5SRobert Watson 	free(buf, M_TEMP);
6614f1f0ef5SRobert Watson 	return (0);
662e7c33e29SRobert Watson 
6634f1f0ef5SRobert Watson error:
664e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6654f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
666e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
667dd47f5caSRobert Watson 	free(buf, M_TEMP);
66840f2ac28SRobert Watson 	return (error);
669a29f300eSGarrett Wollman }
670a29f300eSGarrett Wollman 
671a29f300eSGarrett Wollman static int
6727493f24eSPawel Jakub Dawidek uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
6737493f24eSPawel Jakub Dawidek {
6747493f24eSPawel Jakub Dawidek 
6757493f24eSPawel Jakub Dawidek 	return (uipc_bindat(AT_FDCWD, so, nam, td));
6767493f24eSPawel Jakub Dawidek }
6777493f24eSPawel Jakub Dawidek 
6787493f24eSPawel Jakub Dawidek static int
679b40ce416SJulian Elischer uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
680a29f300eSGarrett Wollman {
6810d9ce3a1SRobert Watson 	int error;
682a29f300eSGarrett Wollman 
683fd179ee9SRobert Watson 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
684fd179ee9SRobert Watson 	error = unp_connect(so, nam, td);
6850d9ce3a1SRobert Watson 	return (error);
686a29f300eSGarrett Wollman }
687a29f300eSGarrett Wollman 
6887493f24eSPawel Jakub Dawidek static int
6897493f24eSPawel Jakub Dawidek uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
6907493f24eSPawel Jakub Dawidek     struct thread *td)
6917493f24eSPawel Jakub Dawidek {
6927493f24eSPawel Jakub Dawidek 	int error;
6937493f24eSPawel Jakub Dawidek 
6947493f24eSPawel Jakub Dawidek 	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
6957493f24eSPawel Jakub Dawidek 	error = unp_connectat(fd, so, nam, td);
6967493f24eSPawel Jakub Dawidek 	return (error);
6977493f24eSPawel Jakub Dawidek }
6987493f24eSPawel Jakub Dawidek 
699a152f8a3SRobert Watson static void
700a152f8a3SRobert Watson uipc_close(struct socket *so)
701a152f8a3SRobert Watson {
702e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
703779f106aSGleb Smirnoff 	struct vnode *vp = NULL;
70475a67bf3SMatt Macy 	struct mtx *vplock;
70575a67bf3SMatt Macy 	int freed;
706a152f8a3SRobert Watson 	unp = sotounpcb(so);
707a152f8a3SRobert Watson 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
708e7c33e29SRobert Watson 
70975a67bf3SMatt Macy 	vplock = NULL;
71075a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
71175a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
71275a67bf3SMatt Macy 		mtx_lock(vplock);
713e7c33e29SRobert Watson 	}
71475a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
71575a67bf3SMatt Macy 	if (vp && unp->unp_vnode == NULL) {
71675a67bf3SMatt Macy 		mtx_unlock(vplock);
71775a67bf3SMatt Macy 		vp = NULL;
71875a67bf3SMatt Macy 	}
71975a67bf3SMatt Macy 	if (vp != NULL) {
720779f106aSGleb Smirnoff 		VOP_UNP_DETACH(vp);
721779f106aSGleb Smirnoff 		unp->unp_vnode = NULL;
722779f106aSGleb Smirnoff 	}
72375a67bf3SMatt Macy 	unp2 = unp->unp_conn;
72475a67bf3SMatt Macy 	unp_pcb_hold(unp);
725acf9fd05SMatt Macy 	if (__predict_false(unp == unp2)) {
726acf9fd05SMatt Macy 		unp_disconnect(unp, unp2);
727acf9fd05SMatt Macy 	} else if (unp2 != NULL) {
72875a67bf3SMatt Macy 		unp_pcb_hold(unp2);
72975a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp, unp2, freed);
73075a67bf3SMatt Macy 		unp_disconnect(unp, unp2);
73175a67bf3SMatt Macy 		if (unp_pcb_rele(unp2) == 0)
73275a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp2);
73375a67bf3SMatt Macy 	}
73475a67bf3SMatt Macy 	if (unp_pcb_rele(unp) == 0)
735e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
73675a67bf3SMatt Macy 	if (vp) {
73775a67bf3SMatt Macy 		mtx_unlock(vplock);
738779f106aSGleb Smirnoff 		vrele(vp);
739a152f8a3SRobert Watson 	}
74075a67bf3SMatt Macy }
741a152f8a3SRobert Watson 
7422c899584SRobert Watson static int
743a29f300eSGarrett Wollman uipc_connect2(struct socket *so1, struct socket *so2)
744a29f300eSGarrett Wollman {
745e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
7460d9ce3a1SRobert Watson 	int error;
747a29f300eSGarrett Wollman 
748e7c33e29SRobert Watson 	unp = so1->so_pcb;
7494d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
750e7c33e29SRobert Watson 	unp2 = so2->so_pcb;
751e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
752acf9fd05SMatt Macy 	if (unp != unp2)
75375a67bf3SMatt Macy 		unp_pcb_lock2(unp, unp2);
754acf9fd05SMatt Macy 	else
755acf9fd05SMatt Macy 		UNP_PCB_LOCK(unp);
7566a2989fdSMatthew N. Dodd 	error = unp_connect2(so1, so2, PRU_CONNECT2);
757acf9fd05SMatt Macy 	if (unp != unp2)
758e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
759e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
7600d9ce3a1SRobert Watson 	return (error);
761a29f300eSGarrett Wollman }
762a29f300eSGarrett Wollman 
763bc725eafSRobert Watson static void
764a29f300eSGarrett Wollman uipc_detach(struct socket *so)
765a29f300eSGarrett Wollman {
766e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
76775a67bf3SMatt Macy 	struct mtx *vplock;
7686d32873cSRobert Watson 	struct vnode *vp;
7699ae328fcSJohn Baldwin 	int freeunp, local_unp_rights;
770a29f300eSGarrett Wollman 
77140f2ac28SRobert Watson 	unp = sotounpcb(so);
7724d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
773e7c33e29SRobert Watson 
774434ac8b6SMark Johnston 	vp = NULL;
775c0874c34SMatt Macy 	vplock = NULL;
776434ac8b6SMark Johnston 	local_unp_rights = 0;
777434ac8b6SMark Johnston 
778*a50b1900SMark Johnston 	SOCK_LOCK(so);
779*a50b1900SMark Johnston 	if (!SOLISTENING(so)) {
780*a50b1900SMark Johnston 		/*
781*a50b1900SMark Johnston 		 * Once the socket is removed from the global lists,
782*a50b1900SMark Johnston 		 * uipc_ready() will not be able to locate its socket buffer, so
783*a50b1900SMark Johnston 		 * clear the buffer now.  At this point internalized rights have
784*a50b1900SMark Johnston 		 * already been disposed of.
785*a50b1900SMark Johnston 		 */
786*a50b1900SMark Johnston 		sbrelease(&so->so_rcv, so);
787*a50b1900SMark Johnston 	}
788*a50b1900SMark Johnston 	SOCK_UNLOCK(so);
789*a50b1900SMark Johnston 
790779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
7916d32873cSRobert Watson 	LIST_REMOVE(unp, unp_link);
792a9aa06f7SJason A. Harmening 	if (unp->unp_gcflag & UNPGC_DEAD)
793a9aa06f7SJason A. Harmening 		LIST_REMOVE(unp, unp_dead);
7946d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
7956d32873cSRobert Watson 	--unp_count;
79675a67bf3SMatt Macy 	UNP_LINK_WUNLOCK();
797434ac8b6SMark Johnston 
79875a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
79975a67bf3SMatt Macy  restart:
80075a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
80175a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
80275a67bf3SMatt Macy 		mtx_lock(vplock);
80375a67bf3SMatt Macy 	}
80475a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
805db38b699SMark Johnston 	if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
806c0874c34SMatt Macy 		if (vplock)
80775a67bf3SMatt Macy 			mtx_unlock(vplock);
80875a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
80975a67bf3SMatt Macy 		goto restart;
81075a67bf3SMatt Macy 	}
8116d32873cSRobert Watson 	if ((vp = unp->unp_vnode) != NULL) {
812c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
8136d32873cSRobert Watson 		unp->unp_vnode = NULL;
8146d32873cSRobert Watson 	}
815acf9fd05SMatt Macy 	if (__predict_false(unp == unp->unp_conn)) {
816acf9fd05SMatt Macy 		unp_disconnect(unp, unp);
817acf9fd05SMatt Macy 		unp2 = NULL;
818db38b699SMark Johnston 	} else {
819acf9fd05SMatt Macy 		if ((unp2 = unp->unp_conn) != NULL) {
820acf9fd05SMatt Macy 			unp_pcb_owned_lock2(unp, unp2, freeunp);
821acf9fd05SMatt Macy 			if (freeunp)
822acf9fd05SMatt Macy 				unp2 = NULL;
823acf9fd05SMatt Macy 		}
82475a67bf3SMatt Macy 		unp_pcb_hold(unp);
825e7c33e29SRobert Watson 		if (unp2 != NULL) {
82675a67bf3SMatt Macy 			unp_pcb_hold(unp2);
827e7c33e29SRobert Watson 			unp_disconnect(unp, unp2);
82875a67bf3SMatt Macy 			if (unp_pcb_rele(unp2) == 0)
829e7c33e29SRobert Watson 				UNP_PCB_UNLOCK(unp2);
830e7c33e29SRobert Watson 		}
831db38b699SMark Johnston 	}
83275a67bf3SMatt Macy 	UNP_PCB_UNLOCK(unp);
83375a67bf3SMatt Macy 	UNP_REF_LIST_LOCK();
8346d32873cSRobert Watson 	while (!LIST_EMPTY(&unp->unp_refs)) {
8356d32873cSRobert Watson 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
836e7c33e29SRobert Watson 
83775a67bf3SMatt Macy 		unp_pcb_hold(ref);
83875a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
83975a67bf3SMatt Macy 
84075a67bf3SMatt Macy 		MPASS(ref != unp);
84175a67bf3SMatt Macy 		UNP_PCB_UNLOCK_ASSERT(ref);
842afc055d9SEd Schouten 		unp_drop(ref);
84375a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
8446d32873cSRobert Watson 	}
84575a67bf3SMatt Macy 
84675a67bf3SMatt Macy 	UNP_REF_LIST_UNLOCK();
84775a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
84875a67bf3SMatt Macy 	freeunp = unp_pcb_rele(unp);
84975a67bf3SMatt Macy 	MPASS(freeunp == 0);
850397c19d1SJeff Roberson 	local_unp_rights = unp_rights;
8516d32873cSRobert Watson 	unp->unp_socket->so_pcb = NULL;
85275a67bf3SMatt Macy 	unp->unp_socket = NULL;
853db38b699SMark Johnston 	free(unp->unp_addr, M_SONAME);
854db38b699SMark Johnston 	unp->unp_addr = NULL;
855db38b699SMark Johnston 	if (!unp_pcb_rele(unp))
8566e2faa24SRobert Watson 		UNP_PCB_UNLOCK(unp);
85775a67bf3SMatt Macy 	if (vp) {
85875a67bf3SMatt Macy 		mtx_unlock(vplock);
8596d32873cSRobert Watson 		vrele(vp);
86075a67bf3SMatt Macy 	}
8616d32873cSRobert Watson 	if (local_unp_rights)
862daee0f0bSKonstantin Belousov 		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
863a29f300eSGarrett Wollman }
864a29f300eSGarrett Wollman 
865a29f300eSGarrett Wollman static int
866a29f300eSGarrett Wollman uipc_disconnect(struct socket *so)
867a29f300eSGarrett Wollman {
868e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
86975a67bf3SMatt Macy 	int freed;
870a29f300eSGarrett Wollman 
87140f2ac28SRobert Watson 	unp = sotounpcb(so);
8724d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
873e7c33e29SRobert Watson 
874e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
87575a67bf3SMatt Macy 	if ((unp2 = unp->unp_conn) == NULL) {
876e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
87775a67bf3SMatt Macy 		return (0);
87875a67bf3SMatt Macy 	}
879fcabd541SMatt Macy 	if (__predict_true(unp != unp2)) {
88075a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp, unp2, freed);
88175a67bf3SMatt Macy 		if (__predict_false(freed)) {
88275a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
88375a67bf3SMatt Macy 			return (0);
88475a67bf3SMatt Macy 		}
88575a67bf3SMatt Macy 		unp_pcb_hold(unp2);
886fcabd541SMatt Macy 	}
88775a67bf3SMatt Macy 	unp_pcb_hold(unp);
88875a67bf3SMatt Macy 	unp_disconnect(unp, unp2);
88975a67bf3SMatt Macy 	if (unp_pcb_rele(unp) == 0)
89075a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
891fcabd541SMatt Macy 	if ((unp != unp2) && unp_pcb_rele(unp2) == 0)
89275a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp2);
893e5aeaa0cSDag-Erling Smørgrav 	return (0);
894a29f300eSGarrett Wollman }
895a29f300eSGarrett Wollman 
896a29f300eSGarrett Wollman static int
897d374e81eSRobert Watson uipc_listen(struct socket *so, int backlog, struct thread *td)
898a29f300eSGarrett Wollman {
89940f2ac28SRobert Watson 	struct unpcb *unp;
9000d9ce3a1SRobert Watson 	int error;
901a29f300eSGarrett Wollman 
902beb4b312SGleb Smirnoff 	if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
903beb4b312SGleb Smirnoff 		return (EOPNOTSUPP);
904beb4b312SGleb Smirnoff 
90540f2ac28SRobert Watson 	unp = sotounpcb(so);
9064d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
907e7c33e29SRobert Watson 
908e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
9094d4b555eSRobert Watson 	if (unp->unp_vnode == NULL) {
91047a84387SEd Schouten 		/* Already connected or not bound to an address. */
91147a84387SEd Schouten 		error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
912e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
91347a84387SEd Schouten 		return (error);
91440f2ac28SRobert Watson 	}
915e7c33e29SRobert Watson 
916e7c33e29SRobert Watson 	SOCK_LOCK(so);
917e7c33e29SRobert Watson 	error = solisten_proto_check(so);
918e7c33e29SRobert Watson 	if (error == 0) {
919c5afec6eSDmitry Chagin 		cru2xt(td, &unp->unp_peercred);
920e7c33e29SRobert Watson 		solisten_proto(so, backlog);
921e7c33e29SRobert Watson 	}
922e7c33e29SRobert Watson 	SOCK_UNLOCK(so);
923e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
9240d9ce3a1SRobert Watson 	return (error);
925a29f300eSGarrett Wollman }
926a29f300eSGarrett Wollman 
927a29f300eSGarrett Wollman static int
92857bf258eSGarrett Wollman uipc_peeraddr(struct socket *so, struct sockaddr **nam)
929a29f300eSGarrett Wollman {
930e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
9310d9ce3a1SRobert Watson 	const struct sockaddr *sa;
932a29f300eSGarrett Wollman 
9334d4b555eSRobert Watson 	unp = sotounpcb(so);
9344d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
935e7c33e29SRobert Watson 
9360d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
937afd9f91cSJohn Baldwin 	UNP_LINK_RLOCK();
938bdc5f6a3SHajimu UMEMOTO 	/*
939e7c33e29SRobert Watson 	 * XXX: It seems that this test always fails even when connection is
940e7c33e29SRobert Watson 	 * established.  So, this else clause is added as workaround to
941e7c33e29SRobert Watson 	 * return PF_LOCAL sockaddr.
942bdc5f6a3SHajimu UMEMOTO 	 */
943e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
944e7c33e29SRobert Watson 	if (unp2 != NULL) {
945e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp2);
946e7c33e29SRobert Watson 		if (unp2->unp_addr != NULL)
947afd9f91cSJohn Baldwin 			sa = (struct sockaddr *) unp2->unp_addr;
948e7c33e29SRobert Watson 		else
9490d9ce3a1SRobert Watson 			sa = &sun_noname;
9500d9ce3a1SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
951e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
952e7c33e29SRobert Watson 	} else {
953e7c33e29SRobert Watson 		sa = &sun_noname;
954e7c33e29SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
955e7c33e29SRobert Watson 	}
956afd9f91cSJohn Baldwin 	UNP_LINK_RUNLOCK();
957e5aeaa0cSDag-Erling Smørgrav 	return (0);
958a29f300eSGarrett Wollman }
959a29f300eSGarrett Wollman 
960a29f300eSGarrett Wollman static int
961a29f300eSGarrett Wollman uipc_rcvd(struct socket *so, int flags)
962a29f300eSGarrett Wollman {
963e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
964a29f300eSGarrett Wollman 	struct socket *so2;
965337cc6b6SRobert Watson 	u_int mbcnt, sbcc;
966a29f300eSGarrett Wollman 
96740f2ac28SRobert Watson 	unp = sotounpcb(so);
9682b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
9692b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
9702b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
971e7c33e29SRobert Watson 
972df8bae1dSRodney W. Grimes 	/*
973e7c33e29SRobert Watson 	 * Adjust backpressure on sender and wakeup any waiting to write.
974e7c33e29SRobert Watson 	 *
975d7924b70SRobert Watson 	 * The unp lock is acquired to maintain the validity of the unp_conn
976d7924b70SRobert Watson 	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
977d7924b70SRobert Watson 	 * static as long as we don't permit unp2 to disconnect from unp,
978d7924b70SRobert Watson 	 * which is prevented by the lock on unp.  We cache values from
979d7924b70SRobert Watson 	 * so_rcv to avoid holding the so_rcv lock over the entire
980d7924b70SRobert Watson 	 * transaction on the remote so_snd.
981df8bae1dSRodney W. Grimes 	 */
982337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so->so_rcv);
983337cc6b6SRobert Watson 	mbcnt = so->so_rcv.sb_mbcnt;
9842b21d0e8SGleb Smirnoff 	sbcc = sbavail(&so->so_rcv);
985337cc6b6SRobert Watson 	SOCKBUF_UNLOCK(&so->so_rcv);
986c2090e73SAlan Somers 	/*
987c2090e73SAlan Somers 	 * There is a benign race condition at this point.  If we're planning to
988c2090e73SAlan Somers 	 * clear SB_STOP, but uipc_send is called on the connected socket at
989c2090e73SAlan Somers 	 * this instant, it might add data to the sockbuf and set SB_STOP.  Then
990c2090e73SAlan Somers 	 * we would erroneously clear SB_STOP below, even though the sockbuf is
991c2090e73SAlan Somers 	 * full.  The race is benign because the only ill effect is to allow the
992c2090e73SAlan Somers 	 * sockbuf to exceed its size limit, and the size limits are not
993c2090e73SAlan Somers 	 * strictly guaranteed anyway.
994c2090e73SAlan Somers 	 */
995e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
996e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
997e7c33e29SRobert Watson 	if (unp2 == NULL) {
998e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
999e7c33e29SRobert Watson 		return (0);
1000337cc6b6SRobert Watson 	}
1001e7c33e29SRobert Watson 	so2 = unp2->unp_socket;
1002337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so2->so_snd);
1003c2090e73SAlan Somers 	if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
1004c2090e73SAlan Somers 		so2->so_snd.sb_flags &= ~SB_STOP;
10051e4d7da7SRobert Watson 	sowwakeup_locked(so2);
1006e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1007e5aeaa0cSDag-Erling Smørgrav 	return (0);
1008a29f300eSGarrett Wollman }
1009df8bae1dSRodney W. Grimes 
1010a29f300eSGarrett Wollman static int
101175a67bf3SMatt Macy connect_internal(struct socket *so, struct sockaddr *nam, struct thread *td)
101275a67bf3SMatt Macy {
101375a67bf3SMatt Macy 	int error;
101475a67bf3SMatt Macy 	struct unpcb *unp;
101575a67bf3SMatt Macy 
101675a67bf3SMatt Macy 	unp = so->so_pcb;
101775a67bf3SMatt Macy 	if (unp->unp_conn != NULL)
101875a67bf3SMatt Macy 		return (EISCONN);
101975a67bf3SMatt Macy 	error = unp_connect(so, nam, td);
102075a67bf3SMatt Macy 	if (error)
102175a67bf3SMatt Macy 		return (error);
102275a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
102375a67bf3SMatt Macy 	if (unp->unp_conn == NULL) {
102475a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
102575a67bf3SMatt Macy 		if (error == 0)
102675a67bf3SMatt Macy 			error = ENOTCONN;
102775a67bf3SMatt Macy 	}
102875a67bf3SMatt Macy 	return (error);
102975a67bf3SMatt Macy }
103075a67bf3SMatt Macy 
103175a67bf3SMatt Macy static int
103257bf258eSGarrett Wollman uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1033b40ce416SJulian Elischer     struct mbuf *control, struct thread *td)
1034a29f300eSGarrett Wollman {
1035f3f49bbbSRobert Watson 	struct unpcb *unp, *unp2;
1036a29f300eSGarrett Wollman 	struct socket *so2;
1037c2090e73SAlan Somers 	u_int mbcnt, sbcc;
103875a67bf3SMatt Macy 	int freed, error;
1039a29f300eSGarrett Wollman 
104040f2ac28SRobert Watson 	unp = sotounpcb(so);
10412b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
10422b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
10432b21d0e8SGleb Smirnoff 	    so->so_type == SOCK_SEQPACKET,
10442b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
1045e7c33e29SRobert Watson 
104675a67bf3SMatt Macy 	freed = error = 0;
1047a29f300eSGarrett Wollman 	if (flags & PRUS_OOB) {
1048a29f300eSGarrett Wollman 		error = EOPNOTSUPP;
1049a29f300eSGarrett Wollman 		goto release;
1050a29f300eSGarrett Wollman 	}
1051fc3fcacfSRobert Watson 	if (control != NULL && (error = unp_internalize(&control, td)))
1052a29f300eSGarrett Wollman 		goto release;
105375a67bf3SMatt Macy 
105475a67bf3SMatt Macy 	unp2 = NULL;
1055a29f300eSGarrett Wollman 	switch (so->so_type) {
1056a29f300eSGarrett Wollman 	case SOCK_DGRAM:
1057a29f300eSGarrett Wollman 	{
1058e7dd9a10SRobert Watson 		const struct sockaddr *from;
1059df8bae1dSRodney W. Grimes 
1060fc3fcacfSRobert Watson 		if (nam != NULL) {
106175a67bf3SMatt Macy 			/*
106275a67bf3SMatt Macy 			 * We return with UNP_PCB_LOCK_HELD so we know that
106375a67bf3SMatt Macy 			 * the reference is live if the pointer is valid.
106475a67bf3SMatt Macy 			 */
106575a67bf3SMatt Macy 			if ((error = connect_internal(so, nam, td)))
1066df8bae1dSRodney W. Grimes 				break;
106775a67bf3SMatt Macy 			MPASS(unp->unp_conn != NULL);
1068e7c33e29SRobert Watson 			unp2 = unp->unp_conn;
106975a67bf3SMatt Macy 		} else  {
107075a67bf3SMatt Macy 			UNP_PCB_LOCK(unp);
107160a5ef26SRobert Watson 
1072b5ff0914SRobert Watson 			/*
1073b5ff0914SRobert Watson 			 * Because connect() and send() are non-atomic in a sendto()
1074b5ff0914SRobert Watson 			 * with a target address, it's possible that the socket will
1075b5ff0914SRobert Watson 			 * have disconnected before the send() can run.  In that case
1076b5ff0914SRobert Watson 			 * return the slightly counter-intuitive but otherwise
1077b5ff0914SRobert Watson 			 * correct error that the socket is not connected.
1078b5ff0914SRobert Watson 			 */
107975a67bf3SMatt Macy 			if ((unp2 = unp->unp_conn)  == NULL) {
108075a67bf3SMatt Macy 				UNP_PCB_UNLOCK(unp);
1081b5ff0914SRobert Watson 				error = ENOTCONN;
1082b5ff0914SRobert Watson 				break;
1083b5ff0914SRobert Watson 			}
108475a67bf3SMatt Macy 		}
1085c684c14cSMatt Macy 		if (__predict_false(unp == unp2)) {
1086c684c14cSMatt Macy 			if (unp->unp_socket == NULL) {
1087c684c14cSMatt Macy 				error = ENOTCONN;
1088c684c14cSMatt Macy 				break;
1089c684c14cSMatt Macy 			}
1090c684c14cSMatt Macy 			goto connect_self;
1091c684c14cSMatt Macy 		}
109275a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp, unp2, freed);
109375a67bf3SMatt Macy 		if (__predict_false(freed)) {
109475a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
109575a67bf3SMatt Macy 			error = ENOTCONN;
109675a67bf3SMatt Macy 			break;
109775a67bf3SMatt Macy 		}
109875a67bf3SMatt Macy 		/*
109975a67bf3SMatt Macy 		 * The socket referencing unp2 may have been closed
110075a67bf3SMatt Macy 		 * or unp may have been disconnected if the unp lock
110175a67bf3SMatt Macy 		 * was dropped to acquire unp2.
110275a67bf3SMatt Macy 		 */
110375a67bf3SMatt Macy 		if (__predict_false(unp->unp_conn == NULL) ||
110475a67bf3SMatt Macy 			unp2->unp_socket == NULL) {
110575a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
110675a67bf3SMatt Macy 			if (unp_pcb_rele(unp2) == 0)
110775a67bf3SMatt Macy 				UNP_PCB_UNLOCK(unp2);
110875a67bf3SMatt Macy 			error = ENOTCONN;
110975a67bf3SMatt Macy 			break;
111075a67bf3SMatt Macy 		}
1111c684c14cSMatt Macy 	connect_self:
1112ede6e136SRobert Watson 		if (unp2->unp_flags & UNP_WANTCRED)
1113ede6e136SRobert Watson 			control = unp_addsockcred(td, control);
1114fc3fcacfSRobert Watson 		if (unp->unp_addr != NULL)
111557bf258eSGarrett Wollman 			from = (struct sockaddr *)unp->unp_addr;
1116df8bae1dSRodney W. Grimes 		else
1117df8bae1dSRodney W. Grimes 			from = &sun_noname;
1118ede6e136SRobert Watson 		so2 = unp2->unp_socket;
1119a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
11206dde7ecbSPeter Wemm 		if (sbappendaddr_locked(&so2->so_rcv, from, m,
11218de34a88SAlan Somers 		    control)) {
11221e4d7da7SRobert Watson 			sorwakeup_locked(so2);
1123fc3fcacfSRobert Watson 			m = NULL;
1124fc3fcacfSRobert Watson 			control = NULL;
1125e5aeaa0cSDag-Erling Smørgrav 		} else {
1126a34b7046SRobert Watson 			SOCKBUF_UNLOCK(&so2->so_rcv);
1127df8bae1dSRodney W. Grimes 			error = ENOBUFS;
1128e5aeaa0cSDag-Erling Smørgrav 		}
112975a67bf3SMatt Macy 		if (nam != NULL)
1130e7c33e29SRobert Watson 			unp_disconnect(unp, unp2);
1131c684c14cSMatt Macy 		if (__predict_true(unp != unp2))
1132e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp2);
1133ede6e136SRobert Watson 		UNP_PCB_UNLOCK(unp);
1134df8bae1dSRodney W. Grimes 		break;
1135df8bae1dSRodney W. Grimes 	}
1136df8bae1dSRodney W. Grimes 
113784d61770SRobert Watson 	case SOCK_SEQPACKET:
1138df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
1139402cc72dSDavid Greenman 		if ((so->so_state & SS_ISCONNECTED) == 0) {
1140fc3fcacfSRobert Watson 			if (nam != NULL) {
114175a67bf3SMatt Macy 				if ((error = connect_internal(so, nam, td)))
114275a67bf3SMatt Macy 					break;
1143402cc72dSDavid Greenman 			} else  {
1144402cc72dSDavid Greenman 				error = ENOTCONN;
1145402cc72dSDavid Greenman 				break;
1146402cc72dSDavid Greenman 			}
114775a67bf3SMatt Macy 		} else if ((unp2 = unp->unp_conn) == NULL) {
114875a67bf3SMatt Macy 			error = ENOTCONN;
114975a67bf3SMatt Macy 			break;
115075a67bf3SMatt Macy 		} else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1151df8bae1dSRodney W. Grimes 			error = EPIPE;
1152df8bae1dSRodney W. Grimes 			break;
115375a67bf3SMatt Macy 		} else {
115475a67bf3SMatt Macy 			UNP_PCB_LOCK(unp);
115575a67bf3SMatt Macy 			if ((unp2 = unp->unp_conn) == NULL) {
115675a67bf3SMatt Macy 				UNP_PCB_UNLOCK(unp);
1157b5ff0914SRobert Watson 				error = ENOTCONN;
1158b5ff0914SRobert Watson 				break;
1159b5ff0914SRobert Watson 			}
116075a67bf3SMatt Macy 		}
116175a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp, unp2, freed);
116275a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
116375a67bf3SMatt Macy 		if (__predict_false(freed)) {
116475a67bf3SMatt Macy 			error = ENOTCONN;
116575a67bf3SMatt Macy 			break;
116675a67bf3SMatt Macy 		}
116775a67bf3SMatt Macy 		if ((so2 = unp2->unp_socket) == NULL) {
116875a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp2);
116975a67bf3SMatt Macy 			error = ENOTCONN;
117075a67bf3SMatt Macy 			break;
117175a67bf3SMatt Macy 		}
1172a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
1173f3f49bbbSRobert Watson 		if (unp2->unp_flags & UNP_WANTCRED) {
11746a2989fdSMatthew N. Dodd 			/*
1175716963cbSGleb Smirnoff 			 * Credentials are passed only once on SOCK_STREAM
1176716963cbSGleb Smirnoff 			 * and SOCK_SEQPACKET.
11776a2989fdSMatthew N. Dodd 			 */
1178f3f49bbbSRobert Watson 			unp2->unp_flags &= ~UNP_WANTCRED;
11796a2989fdSMatthew N. Dodd 			control = unp_addsockcred(td, control);
11806a2989fdSMatthew N. Dodd 		}
11815b0480f2SMark Johnston 
1182df8bae1dSRodney W. Grimes 		/*
11835b0480f2SMark Johnston 		 * Send to paired receive port and wake up readers.  Don't
11845b0480f2SMark Johnston 		 * check for space available in the receive buffer if we're
11855b0480f2SMark Johnston 		 * attaching ancillary data; Unix domain sockets only check
11865b0480f2SMark Johnston 		 * for space in the sending sockbuf, and that check is
11875b0480f2SMark Johnston 		 * performed one level up the stack.  At that level we cannot
11885b0480f2SMark Johnston 		 * precisely account for the amount of buffer space used
11895b0480f2SMark Johnston 		 * (e.g., because control messages are not yet internalized).
1190df8bae1dSRodney W. Grimes 		 */
119184d61770SRobert Watson 		switch (so->so_type) {
119284d61770SRobert Watson 		case SOCK_STREAM:
1193fc3fcacfSRobert Watson 			if (control != NULL) {
11945b0480f2SMark Johnston 				sbappendcontrol_locked(&so2->so_rcv, m,
11955b0480f2SMark Johnston 				    control);
1196fc3fcacfSRobert Watson 				control = NULL;
1197e7c33e29SRobert Watson 			} else
1198829fae90SGleb Smirnoff 				sbappend_locked(&so2->so_rcv, m, flags);
119984d61770SRobert Watson 			break;
120084d61770SRobert Watson 
120184d61770SRobert Watson 		case SOCK_SEQPACKET: {
120284d61770SRobert Watson 			const struct sockaddr *from;
120384d61770SRobert Watson 
120484d61770SRobert Watson 			from = &sun_noname;
12058de34a88SAlan Somers 			if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
12068de34a88SAlan Somers 			    from, m, control))
120784d61770SRobert Watson 				control = NULL;
120884d61770SRobert Watson 			break;
120984d61770SRobert Watson 			}
121084d61770SRobert Watson 		}
121184d61770SRobert Watson 
1212c2090e73SAlan Somers 		mbcnt = so2->so_rcv.sb_mbcnt;
12132b21d0e8SGleb Smirnoff 		sbcc = sbavail(&so2->so_rcv);
12142b21d0e8SGleb Smirnoff 		if (sbcc)
1215337cc6b6SRobert Watson 			sorwakeup_locked(so2);
12162b21d0e8SGleb Smirnoff 		else
12172b21d0e8SGleb Smirnoff 			SOCKBUF_UNLOCK(&so2->so_rcv);
1218337cc6b6SRobert Watson 
1219c2090e73SAlan Somers 		/*
1220c2090e73SAlan Somers 		 * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1221c2090e73SAlan Somers 		 * it would be possible for uipc_rcvd to be called at this
1222c2090e73SAlan Somers 		 * point, drain the receiving sockbuf, clear SB_STOP, and then
1223c2090e73SAlan Somers 		 * we would set SB_STOP below.  That could lead to an empty
1224c2090e73SAlan Somers 		 * sockbuf having SB_STOP set
1225c2090e73SAlan Somers 		 */
1226337cc6b6SRobert Watson 		SOCKBUF_LOCK(&so->so_snd);
1227c2090e73SAlan Somers 		if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1228c2090e73SAlan Somers 			so->so_snd.sb_flags |= SB_STOP;
12297abe2ac2SAlan Cox 		SOCKBUF_UNLOCK(&so->so_snd);
1230e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1231fc3fcacfSRobert Watson 		m = NULL;
1232df8bae1dSRodney W. Grimes 		break;
1233df8bae1dSRodney W. Grimes 	}
1234a29f300eSGarrett Wollman 
12356b8fda4dSGarrett Wollman 	/*
123660a5ef26SRobert Watson 	 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
12376b8fda4dSGarrett Wollman 	 */
1238a29f300eSGarrett Wollman 	if (flags & PRUS_EOF) {
1239ede6e136SRobert Watson 		UNP_PCB_LOCK(unp);
12406b8fda4dSGarrett Wollman 		socantsendmore(so);
12416b8fda4dSGarrett Wollman 		unp_shutdown(unp);
1242e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
1243ede6e136SRobert Watson 	}
1244fc3fcacfSRobert Watson 	if (control != NULL && error != 0)
124599ab95dbSMark Johnston 		unp_dispose_mbuf(control);
1246bd508d39SDon Lewis 
1247a29f300eSGarrett Wollman release:
1248fc3fcacfSRobert Watson 	if (control != NULL)
1249a29f300eSGarrett Wollman 		m_freem(control);
1250100db364SGleb Smirnoff 	/*
1251100db364SGleb Smirnoff 	 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1252100db364SGleb Smirnoff 	 * for freeing memory.
1253100db364SGleb Smirnoff 	 */
1254100db364SGleb Smirnoff 	if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1255a29f300eSGarrett Wollman 		m_freem(m);
1256e5aeaa0cSDag-Erling Smørgrav 	return (error);
1257a29f300eSGarrett Wollman }
1258df8bae1dSRodney W. Grimes 
1259*a50b1900SMark Johnston static bool
1260*a50b1900SMark Johnston uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1261*a50b1900SMark Johnston {
1262*a50b1900SMark Johnston 	struct mbuf *mb, *n;
1263*a50b1900SMark Johnston 	struct sockbuf *sb;
1264*a50b1900SMark Johnston 
1265*a50b1900SMark Johnston 	SOCK_LOCK(so);
1266*a50b1900SMark Johnston 	if (SOLISTENING(so)) {
1267*a50b1900SMark Johnston 		SOCK_UNLOCK(so);
1268*a50b1900SMark Johnston 		return (false);
1269*a50b1900SMark Johnston 	}
1270*a50b1900SMark Johnston 	mb = NULL;
1271*a50b1900SMark Johnston 	sb = &so->so_rcv;
1272*a50b1900SMark Johnston 	SOCKBUF_LOCK(sb);
1273*a50b1900SMark Johnston 	if (sb->sb_fnrdy != NULL) {
1274*a50b1900SMark Johnston 		for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1275*a50b1900SMark Johnston 			if (mb == m) {
1276*a50b1900SMark Johnston 				*errorp = sbready(sb, m, count);
1277*a50b1900SMark Johnston 				break;
1278*a50b1900SMark Johnston 			}
1279*a50b1900SMark Johnston 			mb = mb->m_next;
1280*a50b1900SMark Johnston 			if (mb == NULL) {
1281*a50b1900SMark Johnston 				mb = n;
1282*a50b1900SMark Johnston 				n = mb->m_nextpkt;
1283*a50b1900SMark Johnston 			}
1284*a50b1900SMark Johnston 		}
1285*a50b1900SMark Johnston 	}
1286*a50b1900SMark Johnston 	SOCKBUF_UNLOCK(sb);
1287*a50b1900SMark Johnston 	SOCK_UNLOCK(so);
1288*a50b1900SMark Johnston 	return (mb != NULL);
1289*a50b1900SMark Johnston }
1290*a50b1900SMark Johnston 
1291a29f300eSGarrett Wollman static int
1292c80ea19bSGleb Smirnoff uipc_ready(struct socket *so, struct mbuf *m, int count)
1293c80ea19bSGleb Smirnoff {
1294c80ea19bSGleb Smirnoff 	struct unpcb *unp, *unp2;
1295c80ea19bSGleb Smirnoff 	struct socket *so2;
1296*a50b1900SMark Johnston 	int error, i;
1297c80ea19bSGleb Smirnoff 
1298c80ea19bSGleb Smirnoff 	unp = sotounpcb(so);
1299c80ea19bSGleb Smirnoff 
1300*a50b1900SMark Johnston 	KASSERT(so->so_type == SOCK_STREAM,
1301*a50b1900SMark Johnston 	    ("%s: unexpected socket type for %p", __func__, so));
1302*a50b1900SMark Johnston 
1303a62b4665SMatt Macy 	UNP_PCB_LOCK(unp);
1304100db364SGleb Smirnoff 	if ((unp2 = unp->unp_conn) == NULL) {
1305a62b4665SMatt Macy 		UNP_PCB_UNLOCK(unp);
1306*a50b1900SMark Johnston 		goto search;
1307100db364SGleb Smirnoff 	}
1308a62b4665SMatt Macy 	if (unp != unp2) {
1309a62b4665SMatt Macy 		if (UNP_PCB_TRYLOCK(unp2) == 0) {
1310a62b4665SMatt Macy 			unp_pcb_hold(unp2);
1311a62b4665SMatt Macy 			UNP_PCB_UNLOCK(unp);
1312c80ea19bSGleb Smirnoff 			UNP_PCB_LOCK(unp2);
1313a62b4665SMatt Macy 			if (unp_pcb_rele(unp2))
1314*a50b1900SMark Johnston 				goto search;
1315a62b4665SMatt Macy 		} else
1316a62b4665SMatt Macy 			UNP_PCB_UNLOCK(unp);
1317a62b4665SMatt Macy 	}
1318c80ea19bSGleb Smirnoff 	so2 = unp2->unp_socket;
1319c80ea19bSGleb Smirnoff 	SOCKBUF_LOCK(&so2->so_rcv);
1320c80ea19bSGleb Smirnoff 	if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1321c80ea19bSGleb Smirnoff 		sorwakeup_locked(so2);
1322c80ea19bSGleb Smirnoff 	else
1323c80ea19bSGleb Smirnoff 		SOCKBUF_UNLOCK(&so2->so_rcv);
1324c80ea19bSGleb Smirnoff 	UNP_PCB_UNLOCK(unp2);
1325c80ea19bSGleb Smirnoff 	return (error);
1326*a50b1900SMark Johnston 
1327*a50b1900SMark Johnston search:
1328*a50b1900SMark Johnston 	/*
1329*a50b1900SMark Johnston 	 * The receiving socket has been disconnected, but may still be valid.
1330*a50b1900SMark Johnston 	 * In this case, the now-ready mbufs are still present in its socket
1331*a50b1900SMark Johnston 	 * buffer, so perform an exhaustive search before giving up and freeing
1332*a50b1900SMark Johnston 	 * the mbufs.
1333*a50b1900SMark Johnston 	 */
1334*a50b1900SMark Johnston 	UNP_LINK_RLOCK();
1335*a50b1900SMark Johnston 	LIST_FOREACH(unp, &unp_shead, unp_link) {
1336*a50b1900SMark Johnston 		if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1337*a50b1900SMark Johnston 			break;
1338*a50b1900SMark Johnston 	}
1339*a50b1900SMark Johnston 	UNP_LINK_RUNLOCK();
1340*a50b1900SMark Johnston 
1341*a50b1900SMark Johnston 	if (unp == NULL) {
1342*a50b1900SMark Johnston 		for (i = 0; i < count; i++)
1343a62b4665SMatt Macy 			m = m_free(m);
1344*a50b1900SMark Johnston 		error = ECONNRESET;
1345*a50b1900SMark Johnston 	}
1346*a50b1900SMark Johnston 	return (error);
1347c80ea19bSGleb Smirnoff }
1348c80ea19bSGleb Smirnoff 
1349c80ea19bSGleb Smirnoff static int
1350a29f300eSGarrett Wollman uipc_sense(struct socket *so, struct stat *sb)
1351a29f300eSGarrett Wollman {
1352c2090e73SAlan Somers 	struct unpcb *unp;
1353a29f300eSGarrett Wollman 
135440f2ac28SRobert Watson 	unp = sotounpcb(so);
13554d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1356e7c33e29SRobert Watson 
1357a29f300eSGarrett Wollman 	sb->st_blksize = so->so_snd.sb_hiwat;
1358f3732fd1SPoul-Henning Kamp 	sb->st_dev = NODEV;
1359a29f300eSGarrett Wollman 	sb->st_ino = unp->unp_ino;
1360df8bae1dSRodney W. Grimes 	return (0);
1361a29f300eSGarrett Wollman }
1362df8bae1dSRodney W. Grimes 
1363a29f300eSGarrett Wollman static int
1364a29f300eSGarrett Wollman uipc_shutdown(struct socket *so)
1365a29f300eSGarrett Wollman {
136640f2ac28SRobert Watson 	struct unpcb *unp;
1367df8bae1dSRodney W. Grimes 
136840f2ac28SRobert Watson 	unp = sotounpcb(so);
13694d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1370e7c33e29SRobert Watson 
1371e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1372a29f300eSGarrett Wollman 	socantsendmore(so);
1373a29f300eSGarrett Wollman 	unp_shutdown(unp);
1374e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1375e5aeaa0cSDag-Erling Smørgrav 	return (0);
1376a29f300eSGarrett Wollman }
1377df8bae1dSRodney W. Grimes 
1378a29f300eSGarrett Wollman static int
137957bf258eSGarrett Wollman uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1380a29f300eSGarrett Wollman {
138140f2ac28SRobert Watson 	struct unpcb *unp;
13820d9ce3a1SRobert Watson 	const struct sockaddr *sa;
1383a29f300eSGarrett Wollman 
13844d4b555eSRobert Watson 	unp = sotounpcb(so);
13854d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1386e7c33e29SRobert Watson 
13870d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1388e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1389fc3fcacfSRobert Watson 	if (unp->unp_addr != NULL)
13900d9ce3a1SRobert Watson 		sa = (struct sockaddr *) unp->unp_addr;
139183f3198bSThomas Moestl 	else
13920d9ce3a1SRobert Watson 		sa = &sun_noname;
13930d9ce3a1SRobert Watson 	bcopy(sa, *nam, sa->sa_len);
1394e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1395e5aeaa0cSDag-Erling Smørgrav 	return (0);
1396df8bae1dSRodney W. Grimes }
1397a29f300eSGarrett Wollman 
1398fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram = {
1399756d52a1SPoul-Henning Kamp 	.pru_abort = 		uipc_abort,
1400756d52a1SPoul-Henning Kamp 	.pru_accept =		uipc_accept,
1401756d52a1SPoul-Henning Kamp 	.pru_attach =		uipc_attach,
1402756d52a1SPoul-Henning Kamp 	.pru_bind =		uipc_bind,
14037493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1404756d52a1SPoul-Henning Kamp 	.pru_connect =		uipc_connect,
14057493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1406756d52a1SPoul-Henning Kamp 	.pru_connect2 =		uipc_connect2,
1407756d52a1SPoul-Henning Kamp 	.pru_detach =		uipc_detach,
1408756d52a1SPoul-Henning Kamp 	.pru_disconnect =	uipc_disconnect,
1409756d52a1SPoul-Henning Kamp 	.pru_listen =		uipc_listen,
1410756d52a1SPoul-Henning Kamp 	.pru_peeraddr =		uipc_peeraddr,
1411756d52a1SPoul-Henning Kamp 	.pru_rcvd =		uipc_rcvd,
1412756d52a1SPoul-Henning Kamp 	.pru_send =		uipc_send,
1413756d52a1SPoul-Henning Kamp 	.pru_sense =		uipc_sense,
1414756d52a1SPoul-Henning Kamp 	.pru_shutdown =		uipc_shutdown,
1415756d52a1SPoul-Henning Kamp 	.pru_sockaddr =		uipc_sockaddr,
1416fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_dgram,
1417fa9402f2SRobert Watson 	.pru_close =		uipc_close,
1418fa9402f2SRobert Watson };
1419fa9402f2SRobert Watson 
142084d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket = {
142184d61770SRobert Watson 	.pru_abort =		uipc_abort,
142284d61770SRobert Watson 	.pru_accept =		uipc_accept,
142384d61770SRobert Watson 	.pru_attach =		uipc_attach,
142484d61770SRobert Watson 	.pru_bind =		uipc_bind,
14257493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
142684d61770SRobert Watson 	.pru_connect =		uipc_connect,
14277493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
142884d61770SRobert Watson 	.pru_connect2 =		uipc_connect2,
142984d61770SRobert Watson 	.pru_detach =		uipc_detach,
143084d61770SRobert Watson 	.pru_disconnect =	uipc_disconnect,
143184d61770SRobert Watson 	.pru_listen =		uipc_listen,
143284d61770SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
143384d61770SRobert Watson 	.pru_rcvd =		uipc_rcvd,
143484d61770SRobert Watson 	.pru_send =		uipc_send,
143584d61770SRobert Watson 	.pru_sense =		uipc_sense,
143684d61770SRobert Watson 	.pru_shutdown =		uipc_shutdown,
143784d61770SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
143884d61770SRobert Watson 	.pru_soreceive =	soreceive_generic,	/* XXX: or...? */
143984d61770SRobert Watson 	.pru_close =		uipc_close,
144084d61770SRobert Watson };
144184d61770SRobert Watson 
1442fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_stream = {
1443fa9402f2SRobert Watson 	.pru_abort = 		uipc_abort,
1444fa9402f2SRobert Watson 	.pru_accept =		uipc_accept,
1445fa9402f2SRobert Watson 	.pru_attach =		uipc_attach,
1446fa9402f2SRobert Watson 	.pru_bind =		uipc_bind,
14477493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1448fa9402f2SRobert Watson 	.pru_connect =		uipc_connect,
14497493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1450fa9402f2SRobert Watson 	.pru_connect2 =		uipc_connect2,
1451fa9402f2SRobert Watson 	.pru_detach =		uipc_detach,
1452fa9402f2SRobert Watson 	.pru_disconnect =	uipc_disconnect,
1453fa9402f2SRobert Watson 	.pru_listen =		uipc_listen,
1454fa9402f2SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
1455fa9402f2SRobert Watson 	.pru_rcvd =		uipc_rcvd,
1456fa9402f2SRobert Watson 	.pru_send =		uipc_send,
1457c80ea19bSGleb Smirnoff 	.pru_ready =		uipc_ready,
1458fa9402f2SRobert Watson 	.pru_sense =		uipc_sense,
1459fa9402f2SRobert Watson 	.pru_shutdown =		uipc_shutdown,
1460fa9402f2SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
1461fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_generic,
1462a152f8a3SRobert Watson 	.pru_close =		uipc_close,
1463a29f300eSGarrett Wollman };
1464df8bae1dSRodney W. Grimes 
14650b36cd25SRobert Watson static int
1466892af6b9SRobert Watson uipc_ctloutput(struct socket *so, struct sockopt *sopt)
14670c1bb4fbSDima Dorfman {
146840f2ac28SRobert Watson 	struct unpcb *unp;
14690d9ce3a1SRobert Watson 	struct xucred xu;
14706a2989fdSMatthew N. Dodd 	int error, optval;
14716a2989fdSMatthew N. Dodd 
147296a041b5SMatthew N. Dodd 	if (sopt->sopt_level != 0)
147396a041b5SMatthew N. Dodd 		return (EINVAL);
147496a041b5SMatthew N. Dodd 
14756a2989fdSMatthew N. Dodd 	unp = sotounpcb(so);
14764d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
14776a2989fdSMatthew N. Dodd 	error = 0;
14780c1bb4fbSDima Dorfman 	switch (sopt->sopt_dir) {
14790c1bb4fbSDima Dorfman 	case SOPT_GET:
14800c1bb4fbSDima Dorfman 		switch (sopt->sopt_name) {
14810c1bb4fbSDima Dorfman 		case LOCAL_PEERCRED:
1482e7c33e29SRobert Watson 			UNP_PCB_LOCK(unp);
14830c1bb4fbSDima Dorfman 			if (unp->unp_flags & UNP_HAVEPC)
14840d9ce3a1SRobert Watson 				xu = unp->unp_peercred;
14850c1bb4fbSDima Dorfman 			else {
14860c1bb4fbSDima Dorfman 				if (so->so_type == SOCK_STREAM)
14870c1bb4fbSDima Dorfman 					error = ENOTCONN;
14880c1bb4fbSDima Dorfman 				else
14890c1bb4fbSDima Dorfman 					error = EINVAL;
14900c1bb4fbSDima Dorfman 			}
1491e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
14920d9ce3a1SRobert Watson 			if (error == 0)
14930d9ce3a1SRobert Watson 				error = sooptcopyout(sopt, &xu, sizeof(xu));
14940c1bb4fbSDima Dorfman 			break;
1495e7c33e29SRobert Watson 
14966a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
1497a6357845SRobert Watson 			/* Unlocked read. */
14986a2989fdSMatthew N. Dodd 			optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
14996a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
15006a2989fdSMatthew N. Dodd 			break;
1501e7c33e29SRobert Watson 
15026a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
1503a6357845SRobert Watson 			/* Unlocked read. */
15046a2989fdSMatthew N. Dodd 			optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
15056a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
15066a2989fdSMatthew N. Dodd 			break;
1507e7c33e29SRobert Watson 
15080c1bb4fbSDima Dorfman 		default:
15090c1bb4fbSDima Dorfman 			error = EOPNOTSUPP;
15100c1bb4fbSDima Dorfman 			break;
15110c1bb4fbSDima Dorfman 		}
15120c1bb4fbSDima Dorfman 		break;
1513e7c33e29SRobert Watson 
15140c1bb4fbSDima Dorfman 	case SOPT_SET:
15156a2989fdSMatthew N. Dodd 		switch (sopt->sopt_name) {
15166a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
15176a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
15186a2989fdSMatthew N. Dodd 			error = sooptcopyin(sopt, &optval, sizeof(optval),
15196a2989fdSMatthew N. Dodd 					    sizeof(optval));
15206a2989fdSMatthew N. Dodd 			if (error)
15216a2989fdSMatthew N. Dodd 				break;
15226a2989fdSMatthew N. Dodd 
1523e7c33e29SRobert Watson #define	OPTSET(bit) do {						\
1524e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);						\
15256a2989fdSMatthew N. Dodd 	if (optval)							\
15266a2989fdSMatthew N. Dodd 		unp->unp_flags |= bit;					\
15276a2989fdSMatthew N. Dodd 	else								\
1528e7c33e29SRobert Watson 		unp->unp_flags &= ~bit;					\
1529e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);						\
1530e7c33e29SRobert Watson } while (0)
15316a2989fdSMatthew N. Dodd 
15326a2989fdSMatthew N. Dodd 			switch (sopt->sopt_name) {
15336a2989fdSMatthew N. Dodd 			case LOCAL_CREDS:
15346a2989fdSMatthew N. Dodd 				OPTSET(UNP_WANTCRED);
15356a2989fdSMatthew N. Dodd 				break;
1536e7c33e29SRobert Watson 
15376a2989fdSMatthew N. Dodd 			case LOCAL_CONNWAIT:
15386a2989fdSMatthew N. Dodd 				OPTSET(UNP_CONNWAIT);
15396a2989fdSMatthew N. Dodd 				break;
1540e7c33e29SRobert Watson 
15416a2989fdSMatthew N. Dodd 			default:
15426a2989fdSMatthew N. Dodd 				break;
15436a2989fdSMatthew N. Dodd 			}
15446a2989fdSMatthew N. Dodd 			break;
15456a2989fdSMatthew N. Dodd #undef	OPTSET
15466a2989fdSMatthew N. Dodd 		default:
15476a2989fdSMatthew N. Dodd 			error = ENOPROTOOPT;
15486a2989fdSMatthew N. Dodd 			break;
15496a2989fdSMatthew N. Dodd 		}
1550abb886faSMatthew N. Dodd 		break;
1551e7c33e29SRobert Watson 
15520c1bb4fbSDima Dorfman 	default:
15530c1bb4fbSDima Dorfman 		error = EOPNOTSUPP;
15540c1bb4fbSDima Dorfman 		break;
15550c1bb4fbSDima Dorfman 	}
15560c1bb4fbSDima Dorfman 	return (error);
15570c1bb4fbSDima Dorfman }
15580c1bb4fbSDima Dorfman 
1559f708ef1bSPoul-Henning Kamp static int
1560892af6b9SRobert Watson unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1561df8bae1dSRodney W. Grimes {
15627493f24eSPawel Jakub Dawidek 
15637493f24eSPawel Jakub Dawidek 	return (unp_connectat(AT_FDCWD, so, nam, td));
15647493f24eSPawel Jakub Dawidek }
15657493f24eSPawel Jakub Dawidek 
15667493f24eSPawel Jakub Dawidek static int
15677493f24eSPawel Jakub Dawidek unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
15687493f24eSPawel Jakub Dawidek     struct thread *td)
15697493f24eSPawel Jakub Dawidek {
1570892af6b9SRobert Watson 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1571892af6b9SRobert Watson 	struct vnode *vp;
1572779f106aSGleb Smirnoff 	struct socket *so2;
1573b295bdcdSRobert Watson 	struct unpcb *unp, *unp2, *unp3;
1574df8bae1dSRodney W. Grimes 	struct nameidata nd;
157557bf258eSGarrett Wollman 	char buf[SOCK_MAXADDRLEN];
15760d9ce3a1SRobert Watson 	struct sockaddr *sa;
15777008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
157875a67bf3SMatt Macy 	int error, len, freed;
157975a67bf3SMatt Macy 	struct mtx *vplock;
15800d9ce3a1SRobert Watson 
1581cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
1582cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
1583a06534c3SBjoern A. Zeeb 	if (nam->sa_len > sizeof(struct sockaddr_un))
1584a06534c3SBjoern A. Zeeb 		return (EINVAL);
158557bf258eSGarrett Wollman 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
158657bf258eSGarrett Wollman 	if (len <= 0)
1587e5aeaa0cSDag-Erling Smørgrav 		return (EINVAL);
15887928893dSEd Maste 	bcopy(soun->sun_path, buf, len);
15897928893dSEd Maste 	buf[len] = 0;
1590e7c33e29SRobert Watson 
159175a67bf3SMatt Macy 	unp = sotounpcb(so);
1592e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
15934f1f0ef5SRobert Watson 	if (unp->unp_flags & UNP_CONNECTING) {
1594e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
15954f1f0ef5SRobert Watson 		return (EALREADY);
15964f1f0ef5SRobert Watson 	}
159705102f04SRobert Watson 	unp->unp_flags |= UNP_CONNECTING;
1598e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1599e7c33e29SRobert Watson 
16000d9ce3a1SRobert Watson 	sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
16017493f24eSPawel Jakub Dawidek 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
16027008be5bSPawel Jakub Dawidek 	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1603797f2d22SPoul-Henning Kamp 	error = namei(&nd);
1604797f2d22SPoul-Henning Kamp 	if (error)
16050d9ce3a1SRobert Watson 		vp = NULL;
16060d9ce3a1SRobert Watson 	else
1607df8bae1dSRodney W. Grimes 		vp = nd.ni_vp;
16080d9ce3a1SRobert Watson 	ASSERT_VOP_LOCKED(vp, "unp_connect");
1609762e6b85SEivind Eklund 	NDFREE(&nd, NDF_ONLY_PNBUF);
16100d9ce3a1SRobert Watson 	if (error)
16110d9ce3a1SRobert Watson 		goto bad;
16120d9ce3a1SRobert Watson 
1613df8bae1dSRodney W. Grimes 	if (vp->v_type != VSOCK) {
1614df8bae1dSRodney W. Grimes 		error = ENOTSOCK;
1615df8bae1dSRodney W. Grimes 		goto bad;
1616df8bae1dSRodney W. Grimes 	}
16176fac927cSRobert Watson #ifdef MAC
161830d239bcSRobert Watson 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
16196fac927cSRobert Watson 	if (error)
16206fac927cSRobert Watson 		goto bad;
16216fac927cSRobert Watson #endif
1622a854ed98SJohn Baldwin 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1623797f2d22SPoul-Henning Kamp 	if (error)
1624df8bae1dSRodney W. Grimes 		goto bad;
1625e7c33e29SRobert Watson 
1626b295bdcdSRobert Watson 	unp = sotounpcb(so);
16274d4b555eSRobert Watson 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1628e7c33e29SRobert Watson 
162975a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
163075a67bf3SMatt Macy 	mtx_lock(vplock);
16310c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp2);
16320c3c207fSGleb Smirnoff 	if (unp2 == NULL) {
1633df8bae1dSRodney W. Grimes 		error = ECONNREFUSED;
16342260c03dSRobert Watson 		goto bad2;
1635df8bae1dSRodney W. Grimes 	}
16360c3c207fSGleb Smirnoff 	so2 = unp2->unp_socket;
1637df8bae1dSRodney W. Grimes 	if (so->so_type != so2->so_type) {
1638df8bae1dSRodney W. Grimes 		error = EPROTOTYPE;
16392260c03dSRobert Watson 		goto bad2;
1640df8bae1dSRodney W. Grimes 	}
1641df8bae1dSRodney W. Grimes 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1642e7c33e29SRobert Watson 		if (so2->so_options & SO_ACCEPTCONN) {
16431fb51a12SBjoern A. Zeeb 			CURVNET_SET(so2->so_vnet);
1644779f106aSGleb Smirnoff 			so2 = sonewconn(so2, 0);
16451fb51a12SBjoern A. Zeeb 			CURVNET_RESTORE();
1646e7c33e29SRobert Watson 		} else
1647779f106aSGleb Smirnoff 			so2 = NULL;
1648779f106aSGleb Smirnoff 		if (so2 == NULL) {
1649df8bae1dSRodney W. Grimes 			error = ECONNREFUSED;
1650cb8f450bSMatt Macy 			goto bad2;
1651df8bae1dSRodney W. Grimes 		}
1652779f106aSGleb Smirnoff 		unp3 = sotounpcb(so2);
1653e10ef65dSMatt Macy 		unp_pcb_lock2(unp2, unp3);
16540d9ce3a1SRobert Watson 		if (unp2->unp_addr != NULL) {
16550d9ce3a1SRobert Watson 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
16560d9ce3a1SRobert Watson 			unp3->unp_addr = (struct sockaddr_un *) sa;
16570d9ce3a1SRobert Watson 			sa = NULL;
16580d9ce3a1SRobert Watson 		}
1659b523ec24SRobert Watson 
1660da446550SAlan Somers 		unp_copy_peercred(td, unp3, unp, unp2);
1661b523ec24SRobert Watson 
1662e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1663779f106aSGleb Smirnoff 		unp2 = unp3;
166475a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp2, unp, freed);
1665e10ef65dSMatt Macy 		if (__predict_false(freed)) {
1666e10ef65dSMatt Macy 			UNP_PCB_UNLOCK(unp2);
1667e10ef65dSMatt Macy 			error = ECONNREFUSED;
1668e10ef65dSMatt Macy 			goto bad2;
1669e10ef65dSMatt Macy 		}
1670335654d7SRobert Watson #ifdef MAC
1671779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so, so2);
1672779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so2, so);
1673335654d7SRobert Watson #endif
1674a3a73490SMatt Macy 	} else {
1675a3a73490SMatt Macy 		if (unp == unp2)
1676a3a73490SMatt Macy 			UNP_PCB_LOCK(unp);
1677a3a73490SMatt Macy 		else
1678e10ef65dSMatt Macy 			unp_pcb_lock2(unp, unp2);
1679a3a73490SMatt Macy 	}
1680779f106aSGleb Smirnoff 	KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1681779f106aSGleb Smirnoff 	    sotounpcb(so2) == unp2,
1682779f106aSGleb Smirnoff 	    ("%s: unp2 %p so2 %p", __func__, unp2, so2));
16836a2989fdSMatthew N. Dodd 	error = unp_connect2(so, so2, PRU_CONNECT);
1684a3a73490SMatt Macy 	if (unp != unp2)
1685e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1686e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
16870d9ce3a1SRobert Watson bad2:
168875a67bf3SMatt Macy 	mtx_unlock(vplock);
1689df8bae1dSRodney W. Grimes bad:
169075a67bf3SMatt Macy 	if (vp != NULL) {
1691df8bae1dSRodney W. Grimes 		vput(vp);
169275a67bf3SMatt Macy 	}
16930d9ce3a1SRobert Watson 	free(sa, M_SONAME);
1694e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
16954f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_CONNECTING;
1696e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1697df8bae1dSRodney W. Grimes 	return (error);
1698df8bae1dSRodney W. Grimes }
1699df8bae1dSRodney W. Grimes 
1700da446550SAlan Somers /*
1701da446550SAlan Somers  * Set socket peer credentials at connection time.
1702da446550SAlan Somers  *
1703da446550SAlan Somers  * The client's PCB credentials are copied from its process structure.  The
1704da446550SAlan Somers  * server's PCB credentials are copied from the socket on which it called
1705da446550SAlan Somers  * listen(2).  uipc_listen cached that process's credentials at the time.
1706da446550SAlan Somers  */
1707da446550SAlan Somers void
1708da446550SAlan Somers unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1709da446550SAlan Somers     struct unpcb *server_unp, struct unpcb *listen_unp)
1710da446550SAlan Somers {
1711c5afec6eSDmitry Chagin 	cru2xt(td, &client_unp->unp_peercred);
1712da446550SAlan Somers 	client_unp->unp_flags |= UNP_HAVEPC;
1713da446550SAlan Somers 
1714da446550SAlan Somers 	memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1715da446550SAlan Somers 	    sizeof(server_unp->unp_peercred));
1716da446550SAlan Somers 	server_unp->unp_flags |= UNP_HAVEPC;
1717da446550SAlan Somers 	if (listen_unp->unp_flags & UNP_WANTCRED)
1718da446550SAlan Somers 		client_unp->unp_flags |= UNP_WANTCRED;
1719da446550SAlan Somers }
1720da446550SAlan Somers 
1721db48c0d2SRobert Watson static int
17226a2989fdSMatthew N. Dodd unp_connect2(struct socket *so, struct socket *so2, int req)
1723df8bae1dSRodney W. Grimes {
1724e7c33e29SRobert Watson 	struct unpcb *unp;
1725892af6b9SRobert Watson 	struct unpcb *unp2;
1726df8bae1dSRodney W. Grimes 
1727e7c33e29SRobert Watson 	unp = sotounpcb(so);
1728e7c33e29SRobert Watson 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1729e7c33e29SRobert Watson 	unp2 = sotounpcb(so2);
1730e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1731e7c33e29SRobert Watson 
1732e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1733e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
17340d9ce3a1SRobert Watson 
1735df8bae1dSRodney W. Grimes 	if (so2->so_type != so->so_type)
1736df8bae1dSRodney W. Grimes 		return (EPROTOTYPE);
1737df8bae1dSRodney W. Grimes 	unp->unp_conn = unp2;
173875a67bf3SMatt Macy 	unp_pcb_hold(unp2);
173975a67bf3SMatt Macy 	unp_pcb_hold(unp);
1740df8bae1dSRodney W. Grimes 	switch (so->so_type) {
1741df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
174275a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
174398271db4SGarrett Wollman 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
174475a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
1745df8bae1dSRodney W. Grimes 		soisconnected(so);
1746df8bae1dSRodney W. Grimes 		break;
1747df8bae1dSRodney W. Grimes 
1748df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
174984d61770SRobert Watson 	case SOCK_SEQPACKET:
1750df8bae1dSRodney W. Grimes 		unp2->unp_conn = unp;
17516a2989fdSMatthew N. Dodd 		if (req == PRU_CONNECT &&
17526a2989fdSMatthew N. Dodd 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
17536a2989fdSMatthew N. Dodd 			soisconnecting(so);
17546a2989fdSMatthew N. Dodd 		else
1755df8bae1dSRodney W. Grimes 			soisconnected(so);
1756df8bae1dSRodney W. Grimes 		soisconnected(so2);
1757df8bae1dSRodney W. Grimes 		break;
1758df8bae1dSRodney W. Grimes 
1759df8bae1dSRodney W. Grimes 	default:
1760df8bae1dSRodney W. Grimes 		panic("unp_connect2");
1761df8bae1dSRodney W. Grimes 	}
1762df8bae1dSRodney W. Grimes 	return (0);
1763df8bae1dSRodney W. Grimes }
1764df8bae1dSRodney W. Grimes 
1765f708ef1bSPoul-Henning Kamp static void
1766e7c33e29SRobert Watson unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1767df8bae1dSRodney W. Grimes {
176875a67bf3SMatt Macy 	struct socket *so, *so2;
17694b06dee1SMatt Macy 	int freed __unused;
1770df8bae1dSRodney W. Grimes 
1771e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
17720d9ce3a1SRobert Watson 
1773e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1774e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
1775e7c33e29SRobert Watson 
177675a67bf3SMatt Macy 	if (unp->unp_conn == NULL && unp2->unp_conn == NULL)
177775a67bf3SMatt Macy 		return;
177875a67bf3SMatt Macy 
177975a67bf3SMatt Macy 	MPASS(unp->unp_conn == unp2);
1780fc3fcacfSRobert Watson 	unp->unp_conn = NULL;
178175a67bf3SMatt Macy 	so = unp->unp_socket;
178275a67bf3SMatt Macy 	so2 = unp2->unp_socket;
1783df8bae1dSRodney W. Grimes 	switch (unp->unp_socket->so_type) {
1784df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
178575a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
178698271db4SGarrett Wollman 		LIST_REMOVE(unp, unp_reflink);
178775a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
178875a67bf3SMatt Macy 		if (so) {
17891b2e3b4bSRobert Watson 			SOCK_LOCK(so);
17901b2e3b4bSRobert Watson 			so->so_state &= ~SS_ISCONNECTED;
17911b2e3b4bSRobert Watson 			SOCK_UNLOCK(so);
179275a67bf3SMatt Macy 		}
1793df8bae1dSRodney W. Grimes 		break;
1794df8bae1dSRodney W. Grimes 
1795df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
179684d61770SRobert Watson 	case SOCK_SEQPACKET:
179775a67bf3SMatt Macy 		if (so)
179875a67bf3SMatt Macy 			soisdisconnected(so);
179975a67bf3SMatt Macy 		MPASS(unp2->unp_conn == unp);
1800fc3fcacfSRobert Watson 		unp2->unp_conn = NULL;
180175a67bf3SMatt Macy 		if (so2)
180275a67bf3SMatt Macy 			soisdisconnected(so2);
1803df8bae1dSRodney W. Grimes 		break;
1804df8bae1dSRodney W. Grimes 	}
18054b06dee1SMatt Macy 	freed = unp_pcb_rele(unp);
180675a67bf3SMatt Macy 	MPASS(freed == 0);
18074b06dee1SMatt Macy 	freed = unp_pcb_rele(unp2);
180875a67bf3SMatt Macy 	MPASS(freed == 0);
1809df8bae1dSRodney W. Grimes }
1810df8bae1dSRodney W. Grimes 
18110d9ce3a1SRobert Watson /*
1812d7924b70SRobert Watson  * unp_pcblist() walks the global list of struct unpcb's to generate a
1813d7924b70SRobert Watson  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1814d7924b70SRobert Watson  * sequentially, validating the generation number on each to see if it has
1815d7924b70SRobert Watson  * been detached.  All of this is necessary because copyout() may sleep on
1816d7924b70SRobert Watson  * disk I/O.
18170d9ce3a1SRobert Watson  */
181898271db4SGarrett Wollman static int
181982d9ae4eSPoul-Henning Kamp unp_pcblist(SYSCTL_HANDLER_ARGS)
182098271db4SGarrett Wollman {
182198271db4SGarrett Wollman 	struct unpcb *unp, **unp_list;
182298271db4SGarrett Wollman 	unp_gen_t gencnt;
18238f364875SJulian Elischer 	struct xunpgen *xug;
182498271db4SGarrett Wollman 	struct unp_head *head;
18258f364875SJulian Elischer 	struct xunpcb *xu;
1826d821d364SPedro F. Giffuni 	u_int i;
182744c514b1SPedro F. Giffuni 	int error, freeunp, n;
182898271db4SGarrett Wollman 
182984d61770SRobert Watson 	switch ((intptr_t)arg1) {
183084d61770SRobert Watson 	case SOCK_STREAM:
183184d61770SRobert Watson 		head = &unp_shead;
183284d61770SRobert Watson 		break;
183384d61770SRobert Watson 
183484d61770SRobert Watson 	case SOCK_DGRAM:
183584d61770SRobert Watson 		head = &unp_dhead;
183684d61770SRobert Watson 		break;
183784d61770SRobert Watson 
183884d61770SRobert Watson 	case SOCK_SEQPACKET:
183984d61770SRobert Watson 		head = &unp_sphead;
184084d61770SRobert Watson 		break;
184184d61770SRobert Watson 
184284d61770SRobert Watson 	default:
1843604f19c9SRobert Watson 		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
184484d61770SRobert Watson 	}
184598271db4SGarrett Wollman 
184698271db4SGarrett Wollman 	/*
184798271db4SGarrett Wollman 	 * The process of preparing the PCB list is too time-consuming and
184898271db4SGarrett Wollman 	 * resource-intensive to repeat twice on every request.
184998271db4SGarrett Wollman 	 */
1850fc3fcacfSRobert Watson 	if (req->oldptr == NULL) {
185198271db4SGarrett Wollman 		n = unp_count;
18528f364875SJulian Elischer 		req->oldidx = 2 * (sizeof *xug)
185398271db4SGarrett Wollman 			+ (n + n/8) * sizeof(struct xunpcb);
1854e5aeaa0cSDag-Erling Smørgrav 		return (0);
185598271db4SGarrett Wollman 	}
185698271db4SGarrett Wollman 
1857fc3fcacfSRobert Watson 	if (req->newptr != NULL)
1858e5aeaa0cSDag-Erling Smørgrav 		return (EPERM);
185998271db4SGarrett Wollman 
186098271db4SGarrett Wollman 	/*
186198271db4SGarrett Wollman 	 * OK, now we're committed to doing something.
186298271db4SGarrett Wollman 	 */
186379db6fe7SMark Johnston 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1864779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
186598271db4SGarrett Wollman 	gencnt = unp_gencnt;
186698271db4SGarrett Wollman 	n = unp_count;
1867779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
186898271db4SGarrett Wollman 
18698f364875SJulian Elischer 	xug->xug_len = sizeof *xug;
18708f364875SJulian Elischer 	xug->xug_count = n;
18718f364875SJulian Elischer 	xug->xug_gen = gencnt;
18728f364875SJulian Elischer 	xug->xug_sogen = so_gencnt;
18738f364875SJulian Elischer 	error = SYSCTL_OUT(req, xug, sizeof *xug);
18748f364875SJulian Elischer 	if (error) {
18758f364875SJulian Elischer 		free(xug, M_TEMP);
1876e5aeaa0cSDag-Erling Smørgrav 		return (error);
18778f364875SJulian Elischer 	}
187898271db4SGarrett Wollman 
1879a163d034SWarner Losh 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
188098271db4SGarrett Wollman 
1881779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
18822e3c8fcbSPoul-Henning Kamp 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
18832e3c8fcbSPoul-Henning Kamp 	     unp = LIST_NEXT(unp, unp_link)) {
1884e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
18858a7d8cc6SRobert Watson 		if (unp->unp_gencnt <= gencnt) {
1886a854ed98SJohn Baldwin 			if (cr_cansee(req->td->td_ucred,
1887e7c33e29SRobert Watson 			    unp->unp_socket->so_cred)) {
1888e7c33e29SRobert Watson 				UNP_PCB_UNLOCK(unp);
18894787fd37SPaul Saab 				continue;
1890e7c33e29SRobert Watson 			}
189198271db4SGarrett Wollman 			unp_list[i++] = unp;
189275a67bf3SMatt Macy 			unp_pcb_hold(unp);
189398271db4SGarrett Wollman 		}
1894e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
18954787fd37SPaul Saab 	}
1896779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
18971c381b19SRobert Watson 	n = i;			/* In case we lost some during malloc. */
189898271db4SGarrett Wollman 
189998271db4SGarrett Wollman 	error = 0;
1900fe2eee82SColin Percival 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
190198271db4SGarrett Wollman 	for (i = 0; i < n; i++) {
190298271db4SGarrett Wollman 		unp = unp_list[i];
1903e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
190475a67bf3SMatt Macy 		freeunp = unp_pcb_rele(unp);
190575a67bf3SMatt Macy 
190675a67bf3SMatt Macy 		if (freeunp == 0 && unp->unp_gencnt <= gencnt) {
19078f364875SJulian Elischer 			xu->xu_len = sizeof *xu;
19083a20f06aSBrooks Davis 			xu->xu_unpp = (uintptr_t)unp;
190998271db4SGarrett Wollman 			/*
191098271db4SGarrett Wollman 			 * XXX - need more locking here to protect against
191198271db4SGarrett Wollman 			 * connect/disconnect races for SMP.
191298271db4SGarrett Wollman 			 */
1913fc3fcacfSRobert Watson 			if (unp->unp_addr != NULL)
19148f364875SJulian Elischer 				bcopy(unp->unp_addr, &xu->xu_addr,
191598271db4SGarrett Wollman 				      unp->unp_addr->sun_len);
19160e229f34SGleb Smirnoff 			else
19170e229f34SGleb Smirnoff 				bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1918fc3fcacfSRobert Watson 			if (unp->unp_conn != NULL &&
1919fc3fcacfSRobert Watson 			    unp->unp_conn->unp_addr != NULL)
192098271db4SGarrett Wollman 				bcopy(unp->unp_conn->unp_addr,
19218f364875SJulian Elischer 				      &xu->xu_caddr,
192298271db4SGarrett Wollman 				      unp->unp_conn->unp_addr->sun_len);
19230e229f34SGleb Smirnoff 			else
19240e229f34SGleb Smirnoff 				bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
19253a20f06aSBrooks Davis 			xu->unp_vnode = (uintptr_t)unp->unp_vnode;
19263a20f06aSBrooks Davis 			xu->unp_conn = (uintptr_t)unp->unp_conn;
19273a20f06aSBrooks Davis 			xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
19283a20f06aSBrooks Davis 			xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
19290e229f34SGleb Smirnoff 			xu->unp_gencnt = unp->unp_gencnt;
19308f364875SJulian Elischer 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1931e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
19328f364875SJulian Elischer 			error = SYSCTL_OUT(req, xu, sizeof *xu);
193375a67bf3SMatt Macy 		} else  if (freeunp == 0)
1934e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
1935e7c33e29SRobert Watson 	}
19368f364875SJulian Elischer 	free(xu, M_TEMP);
193798271db4SGarrett Wollman 	if (!error) {
193898271db4SGarrett Wollman 		/*
19391c381b19SRobert Watson 		 * Give the user an updated idea of our state.  If the
19401c381b19SRobert Watson 		 * generation differs from what we told her before, she knows
19411c381b19SRobert Watson 		 * that something happened while we were processing this
19421c381b19SRobert Watson 		 * request, and it might be necessary to retry.
194398271db4SGarrett Wollman 		 */
19448f364875SJulian Elischer 		xug->xug_gen = unp_gencnt;
19458f364875SJulian Elischer 		xug->xug_sogen = so_gencnt;
19468f364875SJulian Elischer 		xug->xug_count = unp_count;
19478f364875SJulian Elischer 		error = SYSCTL_OUT(req, xug, sizeof *xug);
194898271db4SGarrett Wollman 	}
194998271db4SGarrett Wollman 	free(unp_list, M_TEMP);
19508f364875SJulian Elischer 	free(xug, M_TEMP);
1951e5aeaa0cSDag-Erling Smørgrav 	return (error);
195298271db4SGarrett Wollman }
195398271db4SGarrett Wollman 
19547029da5cSPawel Biernacki SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
19557029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19562fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
195798271db4SGarrett Wollman     "List of active local datagram sockets");
19587029da5cSPawel Biernacki SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
19597029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19602fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
196198271db4SGarrett Wollman     "List of active local stream sockets");
19622fee06f0SMatthew D Fleming SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
19637029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19642fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
196584d61770SRobert Watson     "List of active local seqpacket sockets");
196698271db4SGarrett Wollman 
1967f708ef1bSPoul-Henning Kamp static void
1968892af6b9SRobert Watson unp_shutdown(struct unpcb *unp)
1969df8bae1dSRodney W. Grimes {
1970e7c33e29SRobert Watson 	struct unpcb *unp2;
1971df8bae1dSRodney W. Grimes 	struct socket *so;
1972df8bae1dSRodney W. Grimes 
1973e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
19740d9ce3a1SRobert Watson 
1975e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
197684d61770SRobert Watson 	if ((unp->unp_socket->so_type == SOCK_STREAM ||
197784d61770SRobert Watson 	    (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1978e7c33e29SRobert Watson 		so = unp2->unp_socket;
1979e7c33e29SRobert Watson 		if (so != NULL)
1980df8bae1dSRodney W. Grimes 			socantrcvmore(so);
1981df8bae1dSRodney W. Grimes 	}
1982e7c33e29SRobert Watson }
1983df8bae1dSRodney W. Grimes 
1984f708ef1bSPoul-Henning Kamp static void
1985afc055d9SEd Schouten unp_drop(struct unpcb *unp)
1986df8bae1dSRodney W. Grimes {
1987df8bae1dSRodney W. Grimes 	struct socket *so = unp->unp_socket;
1988e7c33e29SRobert Watson 	struct unpcb *unp2;
198975a67bf3SMatt Macy 	int freed;
19900d9ce3a1SRobert Watson 
1991afc055d9SEd Schouten 	/*
1992afc055d9SEd Schouten 	 * Regardless of whether the socket's peer dropped the connection
1993afc055d9SEd Schouten 	 * with this socket by aborting or disconnecting, POSIX requires
1994afc055d9SEd Schouten 	 * that ECONNRESET is returned.
1995afc055d9SEd Schouten 	 */
199675a67bf3SMatt Macy 	/* acquire a reference so that unp isn't freed from underneath us */
199775a67bf3SMatt Macy 
199875a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
199975a67bf3SMatt Macy 	if (so)
2000afc055d9SEd Schouten 		so->so_error = ECONNRESET;
2001e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
2002acf9fd05SMatt Macy 	if (unp2 == unp) {
2003acf9fd05SMatt Macy 		unp_disconnect(unp, unp2);
2004acf9fd05SMatt Macy 	} else if (unp2 != NULL) {
200575a67bf3SMatt Macy 		unp_pcb_hold(unp2);
200675a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp, unp2, freed);
2007e7c33e29SRobert Watson 		unp_disconnect(unp, unp2);
200875a67bf3SMatt Macy 		if (unp_pcb_rele(unp2) == 0)
2009e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp2);
2010df8bae1dSRodney W. Grimes 	}
201175a67bf3SMatt Macy 	if (unp_pcb_rele(unp) == 0)
201275a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
201375a67bf3SMatt Macy }
2014df8bae1dSRodney W. Grimes 
20152bc21ed9SDavid Malone static void
20168cb539f1SPawel Jakub Dawidek unp_freerights(struct filedescent **fdep, int fdcount)
2017df8bae1dSRodney W. Grimes {
20182bc21ed9SDavid Malone 	struct file *fp;
20192609222aSPawel Jakub Dawidek 	int i;
2020df8bae1dSRodney W. Grimes 
202182e825c4SGleb Smirnoff 	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
202282e825c4SGleb Smirnoff 
20238cb539f1SPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
20248cb539f1SPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
20258cb539f1SPawel Jakub Dawidek 		filecaps_free(&fdep[i]->fde_caps);
20268692c025SYoshinobu Inoue 		unp_discard(fp);
2027df8bae1dSRodney W. Grimes 	}
20288cb539f1SPawel Jakub Dawidek 	free(fdep[0], M_FILECAPS);
20292bc21ed9SDavid Malone }
20302bc21ed9SDavid Malone 
20310b36cd25SRobert Watson static int
2032c2e3c52eSJilles Tjoelker unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
20332bc21ed9SDavid Malone {
20342bc21ed9SDavid Malone 	struct thread *td = curthread;		/* XXX */
20352bc21ed9SDavid Malone 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
20362bc21ed9SDavid Malone 	int i;
20372bc21ed9SDavid Malone 	int *fdp;
20382609222aSPawel Jakub Dawidek 	struct filedesc *fdesc = td->td_proc->p_fd;
2039ea31808cSMateusz Guzik 	struct filedescent **fdep;
20402bc21ed9SDavid Malone 	void *data;
20412bc21ed9SDavid Malone 	socklen_t clen = control->m_len, datalen;
20422bc21ed9SDavid Malone 	int error, newfds;
20432bc21ed9SDavid Malone 	u_int newlen;
20442bc21ed9SDavid Malone 
20453dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
20464c5bc1caSRobert Watson 
20472bc21ed9SDavid Malone 	error = 0;
20482bc21ed9SDavid Malone 	if (controlp != NULL) /* controlp == NULL => free control messages */
20492bc21ed9SDavid Malone 		*controlp = NULL;
20502bc21ed9SDavid Malone 	while (cm != NULL) {
20512bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
20522bc21ed9SDavid Malone 			error = EINVAL;
20532bc21ed9SDavid Malone 			break;
20542bc21ed9SDavid Malone 		}
20552bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
20562bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
20572bc21ed9SDavid Malone 		if (cm->cmsg_level == SOL_SOCKET
20582bc21ed9SDavid Malone 		    && cm->cmsg_type == SCM_RIGHTS) {
20592609222aSPawel Jakub Dawidek 			newfds = datalen / sizeof(*fdep);
206082e825c4SGleb Smirnoff 			if (newfds == 0)
206182e825c4SGleb Smirnoff 				goto next;
20622609222aSPawel Jakub Dawidek 			fdep = data;
20632bc21ed9SDavid Malone 
2064e2f9a08bSOlivier Houchard 			/* If we're not outputting the descriptors free them. */
20652bc21ed9SDavid Malone 			if (error || controlp == NULL) {
20662609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20672bc21ed9SDavid Malone 				goto next;
20682bc21ed9SDavid Malone 			}
20692609222aSPawel Jakub Dawidek 			FILEDESC_XLOCK(fdesc);
207060a5ef26SRobert Watson 
2071ed5b7817SJulian Elischer 			/*
20721c381b19SRobert Watson 			 * Now change each pointer to an fd in the global
20731c381b19SRobert Watson 			 * table to an integer that is the index to the local
20741c381b19SRobert Watson 			 * fd table entry that we set up to point to the
20751c381b19SRobert Watson 			 * global one we are transferring.
2076ed5b7817SJulian Elischer 			 */
20772bc21ed9SDavid Malone 			newlen = newfds * sizeof(int);
20782bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
20792bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
20802bc21ed9SDavid Malone 			if (*controlp == NULL) {
20812609222aSPawel Jakub Dawidek 				FILEDESC_XUNLOCK(fdesc);
20822bc21ed9SDavid Malone 				error = E2BIG;
20832609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20842bc21ed9SDavid Malone 				goto next;
20852bc21ed9SDavid Malone 			}
20862bc21ed9SDavid Malone 
20872bc21ed9SDavid Malone 			fdp = (int *)
20882bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2089db8f33fdSMateusz Guzik 			if (fdallocn(td, 0, fdp, newfds) != 0) {
20903331a33aSMateusz Guzik 				FILEDESC_XUNLOCK(fdesc);
2091db8f33fdSMateusz Guzik 				error = EMSGSIZE;
2092db8f33fdSMateusz Guzik 				unp_freerights(fdep, newfds);
2093db8f33fdSMateusz Guzik 				m_freem(*controlp);
2094db8f33fdSMateusz Guzik 				*controlp = NULL;
2095db8f33fdSMateusz Guzik 				goto next;
2096db8f33fdSMateusz Guzik 			}
20978cb539f1SPawel Jakub Dawidek 			for (i = 0; i < newfds; i++, fdp++) {
2098ea31808cSMateusz Guzik 				_finstall(fdesc, fdep[i]->fde_file, *fdp,
2099ea31808cSMateusz Guzik 				    (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
2100ea31808cSMateusz Guzik 				    &fdep[i]->fde_caps);
2101ea31808cSMateusz Guzik 				unp_externalize_fp(fdep[i]->fde_file);
2102df8bae1dSRodney W. Grimes 			}
2103c7902fbeSMark Johnston 
2104c7902fbeSMark Johnston 			/*
2105c7902fbeSMark Johnston 			 * The new type indicates that the mbuf data refers to
2106c7902fbeSMark Johnston 			 * kernel resources that may need to be released before
2107c7902fbeSMark Johnston 			 * the mbuf is freed.
2108c7902fbeSMark Johnston 			 */
2109c7902fbeSMark Johnston 			m_chtype(*controlp, MT_EXTCONTROL);
21102609222aSPawel Jakub Dawidek 			FILEDESC_XUNLOCK(fdesc);
21118cb539f1SPawel Jakub Dawidek 			free(fdep[0], M_FILECAPS);
21121c381b19SRobert Watson 		} else {
21131c381b19SRobert Watson 			/* We can just copy anything else across. */
21142bc21ed9SDavid Malone 			if (error || controlp == NULL)
21152bc21ed9SDavid Malone 				goto next;
21162bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, datalen,
21172bc21ed9SDavid Malone 			    cm->cmsg_type, cm->cmsg_level);
21182bc21ed9SDavid Malone 			if (*controlp == NULL) {
21192bc21ed9SDavid Malone 				error = ENOBUFS;
21202bc21ed9SDavid Malone 				goto next;
21212bc21ed9SDavid Malone 			}
21222bc21ed9SDavid Malone 			bcopy(data,
21232bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
21242bc21ed9SDavid Malone 			    datalen);
21252bc21ed9SDavid Malone 		}
21262bc21ed9SDavid Malone 		controlp = &(*controlp)->m_next;
21272bc21ed9SDavid Malone 
21282bc21ed9SDavid Malone next:
21292bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
21302bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
21312bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
21322bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
21338692c025SYoshinobu Inoue 		} else {
21342bc21ed9SDavid Malone 			clen = 0;
21352bc21ed9SDavid Malone 			cm = NULL;
21368692c025SYoshinobu Inoue 		}
21378692c025SYoshinobu Inoue 	}
21388692c025SYoshinobu Inoue 
21392bc21ed9SDavid Malone 	m_freem(control);
21402bc21ed9SDavid Malone 	return (error);
2141df8bae1dSRodney W. Grimes }
2142df8bae1dSRodney W. Grimes 
21434f590175SPaul Saab static void
21444f590175SPaul Saab unp_zone_change(void *tag)
21454f590175SPaul Saab {
21464f590175SPaul Saab 
21474f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21484f590175SPaul Saab }
21494f590175SPaul Saab 
21500b36cd25SRobert Watson static void
215198271db4SGarrett Wollman unp_init(void)
215298271db4SGarrett Wollman {
21531c381b19SRobert Watson 
215421ca7b57SMarko Zec #ifdef VIMAGE
215521ca7b57SMarko Zec 	if (!IS_DEFAULT_VNET(curvnet))
215621ca7b57SMarko Zec 		return;
215721ca7b57SMarko Zec #endif
21589e9d298aSJeff Roberson 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
215975a67bf3SMatt Macy 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
2160fc3fcacfSRobert Watson 	if (unp_zone == NULL)
216198271db4SGarrett Wollman 		panic("unp_init");
21624f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21636e0b6746SPawel Jakub Dawidek 	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
21644f590175SPaul Saab 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
21654f590175SPaul Saab 	    NULL, EVENTHANDLER_PRI_ANY);
216698271db4SGarrett Wollman 	LIST_INIT(&unp_dhead);
216798271db4SGarrett Wollman 	LIST_INIT(&unp_shead);
216884d61770SRobert Watson 	LIST_INIT(&unp_sphead);
21690cb64678SKonstantin Belousov 	SLIST_INIT(&unp_defers);
2170daee0f0bSKonstantin Belousov 	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
21710cb64678SKonstantin Belousov 	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
21723dab55bcSRobert Watson 	UNP_LINK_LOCK_INIT();
21730cb64678SKonstantin Belousov 	UNP_DEFERRED_LOCK_INIT();
217498271db4SGarrett Wollman }
217598271db4SGarrett Wollman 
217647c3450eSKonstantin Belousov static void
217747c3450eSKonstantin Belousov unp_internalize_cleanup_rights(struct mbuf *control)
217847c3450eSKonstantin Belousov {
217947c3450eSKonstantin Belousov 	struct cmsghdr *cp;
218047c3450eSKonstantin Belousov 	struct mbuf *m;
218147c3450eSKonstantin Belousov 	void *data;
218247c3450eSKonstantin Belousov 	socklen_t datalen;
218347c3450eSKonstantin Belousov 
218447c3450eSKonstantin Belousov 	for (m = control; m != NULL; m = m->m_next) {
218547c3450eSKonstantin Belousov 		cp = mtod(m, struct cmsghdr *);
218647c3450eSKonstantin Belousov 		if (cp->cmsg_level != SOL_SOCKET ||
218747c3450eSKonstantin Belousov 		    cp->cmsg_type != SCM_RIGHTS)
218847c3450eSKonstantin Belousov 			continue;
218947c3450eSKonstantin Belousov 		data = CMSG_DATA(cp);
219047c3450eSKonstantin Belousov 		datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
219147c3450eSKonstantin Belousov 		unp_freerights(data, datalen / sizeof(struct filedesc *));
219247c3450eSKonstantin Belousov 	}
219347c3450eSKonstantin Belousov }
219447c3450eSKonstantin Belousov 
2195f708ef1bSPoul-Henning Kamp static int
2196892af6b9SRobert Watson unp_internalize(struct mbuf **controlp, struct thread *td)
2197df8bae1dSRodney W. Grimes {
219847c3450eSKonstantin Belousov 	struct mbuf *control, **initial_controlp;
219947c3450eSKonstantin Belousov 	struct proc *p;
220047c3450eSKonstantin Belousov 	struct filedesc *fdesc;
2201ab15d803SSergey Kandaurov 	struct bintime *bt;
220247c3450eSKonstantin Belousov 	struct cmsghdr *cm;
22032bc21ed9SDavid Malone 	struct cmsgcred *cmcred;
22048cb539f1SPawel Jakub Dawidek 	struct filedescent *fde, **fdep, *fdev;
22052bc21ed9SDavid Malone 	struct file *fp;
22062bc21ed9SDavid Malone 	struct timeval *tv;
2207339efd75SMaxim Sobolev 	struct timespec *ts;
22082bc21ed9SDavid Malone 	void *data;
220947c3450eSKonstantin Belousov 	socklen_t clen, datalen;
2210f1cf2b9dSKonstantin Belousov 	int i, j, error, *fdp, oldfds;
22118692c025SYoshinobu Inoue 	u_int newlen;
2212df8bae1dSRodney W. Grimes 
22133dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
22144c5bc1caSRobert Watson 
221547c3450eSKonstantin Belousov 	p = td->td_proc;
221647c3450eSKonstantin Belousov 	fdesc = p->p_fd;
22172bc21ed9SDavid Malone 	error = 0;
221847c3450eSKonstantin Belousov 	control = *controlp;
221947c3450eSKonstantin Belousov 	clen = control->m_len;
22202bc21ed9SDavid Malone 	*controlp = NULL;
222147c3450eSKonstantin Belousov 	initial_controlp = controlp;
222247c3450eSKonstantin Belousov 	for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
22232bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2224de966666SMateusz Guzik 		    || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
22252bc21ed9SDavid Malone 			error = EINVAL;
22262bc21ed9SDavid Malone 			goto out;
22272bc21ed9SDavid Malone 		}
22282bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
22292bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
22302bc21ed9SDavid Malone 
22312bc21ed9SDavid Malone 		switch (cm->cmsg_type) {
22320b788fa1SBill Paul 		/*
22330b788fa1SBill Paul 		 * Fill in credential information.
22340b788fa1SBill Paul 		 */
22352bc21ed9SDavid Malone 		case SCM_CREDS:
22362bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
22372bc21ed9SDavid Malone 			    SCM_CREDS, SOL_SOCKET);
22382bc21ed9SDavid Malone 			if (*controlp == NULL) {
22392bc21ed9SDavid Malone 				error = ENOBUFS;
22402bc21ed9SDavid Malone 				goto out;
22412bc21ed9SDavid Malone 			}
22422bc21ed9SDavid Malone 			cmcred = (struct cmsgcred *)
22432bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
22440b788fa1SBill Paul 			cmcred->cmcred_pid = p->p_pid;
2245a854ed98SJohn Baldwin 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2246a854ed98SJohn Baldwin 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2247a854ed98SJohn Baldwin 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
2248a854ed98SJohn Baldwin 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
22490b788fa1SBill Paul 			    CMGROUP_MAX);
22500b788fa1SBill Paul 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
22512bc21ed9SDavid Malone 				cmcred->cmcred_groups[i] =
2252a854ed98SJohn Baldwin 				    td->td_ucred->cr_groups[i];
22532bc21ed9SDavid Malone 			break;
22540b788fa1SBill Paul 
22552bc21ed9SDavid Malone 		case SCM_RIGHTS:
22562bc21ed9SDavid Malone 			oldfds = datalen / sizeof (int);
225782e825c4SGleb Smirnoff 			if (oldfds == 0)
225882e825c4SGleb Smirnoff 				break;
2259ed5b7817SJulian Elischer 			/*
22601c381b19SRobert Watson 			 * Check that all the FDs passed in refer to legal
22611c381b19SRobert Watson 			 * files.  If not, reject the entire operation.
2262ed5b7817SJulian Elischer 			 */
22632bc21ed9SDavid Malone 			fdp = data;
22642609222aSPawel Jakub Dawidek 			FILEDESC_SLOCK(fdesc);
22656a1cf96bSMateusz Guzik 			for (i = 0; i < oldfds; i++, fdp++) {
22666a1cf96bSMateusz Guzik 				fp = fget_locked(fdesc, *fdp);
22676a1cf96bSMateusz Guzik 				if (fp == NULL) {
22682609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
22692bc21ed9SDavid Malone 					error = EBADF;
22702bc21ed9SDavid Malone 					goto out;
22712bc21ed9SDavid Malone 				}
2272e7d6662fSAlfred Perlstein 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
22732609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
2274e7d6662fSAlfred Perlstein 					error = EOPNOTSUPP;
2275e7d6662fSAlfred Perlstein 					goto out;
2276e7d6662fSAlfred Perlstein 				}
2277e7d6662fSAlfred Perlstein 
2278df8bae1dSRodney W. Grimes 			}
22795e3f7694SRobert Watson 
2280ed5b7817SJulian Elischer 			/*
22810b36cd25SRobert Watson 			 * Now replace the integer FDs with pointers to the
22822609222aSPawel Jakub Dawidek 			 * file structure and capability rights.
2283ed5b7817SJulian Elischer 			 */
22848cb539f1SPawel Jakub Dawidek 			newlen = oldfds * sizeof(fdep[0]);
22852bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
22862bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
22872bc21ed9SDavid Malone 			if (*controlp == NULL) {
22882609222aSPawel Jakub Dawidek 				FILEDESC_SUNLOCK(fdesc);
22892bc21ed9SDavid Malone 				error = E2BIG;
22902bc21ed9SDavid Malone 				goto out;
22918692c025SYoshinobu Inoue 			}
22922bc21ed9SDavid Malone 			fdp = data;
2293f1cf2b9dSKonstantin Belousov 			for (i = 0; i < oldfds; i++, fdp++) {
2294f1cf2b9dSKonstantin Belousov 				if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2295f1cf2b9dSKonstantin Belousov 					fdp = data;
2296f1cf2b9dSKonstantin Belousov 					for (j = 0; j < i; j++, fdp++) {
2297f1cf2b9dSKonstantin Belousov 						fdrop(fdesc->fd_ofiles[*fdp].
2298f1cf2b9dSKonstantin Belousov 						    fde_file, td);
2299f1cf2b9dSKonstantin Belousov 					}
2300f1cf2b9dSKonstantin Belousov 					FILEDESC_SUNLOCK(fdesc);
2301f1cf2b9dSKonstantin Belousov 					error = EBADF;
2302f1cf2b9dSKonstantin Belousov 					goto out;
2303f1cf2b9dSKonstantin Belousov 				}
2304f1cf2b9dSKonstantin Belousov 			}
2305f1cf2b9dSKonstantin Belousov 			fdp = data;
23068cb539f1SPawel Jakub Dawidek 			fdep = (struct filedescent **)
23072bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23088cb539f1SPawel Jakub Dawidek 			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
23098cb539f1SPawel Jakub Dawidek 			    M_WAITOK);
23108cb539f1SPawel Jakub Dawidek 			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
23112609222aSPawel Jakub Dawidek 				fde = &fdesc->fd_ofiles[*fdp];
23128cb539f1SPawel Jakub Dawidek 				fdep[i] = fdev;
23138cb539f1SPawel Jakub Dawidek 				fdep[i]->fde_file = fde->fde_file;
23148cb539f1SPawel Jakub Dawidek 				filecaps_copy(&fde->fde_caps,
2315d7832811SMateusz Guzik 				    &fdep[i]->fde_caps, true);
23168cb539f1SPawel Jakub Dawidek 				unp_internalize_fp(fdep[i]->fde_file);
2317df8bae1dSRodney W. Grimes 			}
23182609222aSPawel Jakub Dawidek 			FILEDESC_SUNLOCK(fdesc);
23192bc21ed9SDavid Malone 			break;
23202bc21ed9SDavid Malone 
23212bc21ed9SDavid Malone 		case SCM_TIMESTAMP:
23222bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
23232bc21ed9SDavid Malone 			    SCM_TIMESTAMP, SOL_SOCKET);
23242bc21ed9SDavid Malone 			if (*controlp == NULL) {
23252bc21ed9SDavid Malone 				error = ENOBUFS;
23262bc21ed9SDavid Malone 				goto out;
23278692c025SYoshinobu Inoue 			}
23282bc21ed9SDavid Malone 			tv = (struct timeval *)
23292bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23302bc21ed9SDavid Malone 			microtime(tv);
23312bc21ed9SDavid Malone 			break;
23322bc21ed9SDavid Malone 
2333ab15d803SSergey Kandaurov 		case SCM_BINTIME:
2334ab15d803SSergey Kandaurov 			*controlp = sbcreatecontrol(NULL, sizeof(*bt),
2335ab15d803SSergey Kandaurov 			    SCM_BINTIME, SOL_SOCKET);
2336ab15d803SSergey Kandaurov 			if (*controlp == NULL) {
2337ab15d803SSergey Kandaurov 				error = ENOBUFS;
2338ab15d803SSergey Kandaurov 				goto out;
2339ab15d803SSergey Kandaurov 			}
2340ab15d803SSergey Kandaurov 			bt = (struct bintime *)
2341ab15d803SSergey Kandaurov 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2342ab15d803SSergey Kandaurov 			bintime(bt);
2343ab15d803SSergey Kandaurov 			break;
2344ab15d803SSergey Kandaurov 
2345339efd75SMaxim Sobolev 		case SCM_REALTIME:
2346339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2347339efd75SMaxim Sobolev 			    SCM_REALTIME, SOL_SOCKET);
2348339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2349339efd75SMaxim Sobolev 				error = ENOBUFS;
2350339efd75SMaxim Sobolev 				goto out;
2351339efd75SMaxim Sobolev 			}
2352339efd75SMaxim Sobolev 			ts = (struct timespec *)
2353339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2354339efd75SMaxim Sobolev 			nanotime(ts);
2355339efd75SMaxim Sobolev 			break;
2356339efd75SMaxim Sobolev 
2357339efd75SMaxim Sobolev 		case SCM_MONOTONIC:
2358339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2359339efd75SMaxim Sobolev 			    SCM_MONOTONIC, SOL_SOCKET);
2360339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2361339efd75SMaxim Sobolev 				error = ENOBUFS;
2362339efd75SMaxim Sobolev 				goto out;
2363339efd75SMaxim Sobolev 			}
2364339efd75SMaxim Sobolev 			ts = (struct timespec *)
2365339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2366339efd75SMaxim Sobolev 			nanouptime(ts);
2367339efd75SMaxim Sobolev 			break;
2368339efd75SMaxim Sobolev 
23692bc21ed9SDavid Malone 		default:
23702bc21ed9SDavid Malone 			error = EINVAL;
23712bc21ed9SDavid Malone 			goto out;
23722bc21ed9SDavid Malone 		}
23732bc21ed9SDavid Malone 
23744013d726SMark Johnston 		if (*controlp != NULL)
23752bc21ed9SDavid Malone 			controlp = &(*controlp)->m_next;
23762bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
23772bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
23782bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
23792bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
23802bc21ed9SDavid Malone 		} else {
23812bc21ed9SDavid Malone 			clen = 0;
23822bc21ed9SDavid Malone 			cm = NULL;
23832bc21ed9SDavid Malone 		}
23842bc21ed9SDavid Malone 	}
23852bc21ed9SDavid Malone 
23862bc21ed9SDavid Malone out:
238747c3450eSKonstantin Belousov 	if (error != 0 && initial_controlp != NULL)
238847c3450eSKonstantin Belousov 		unp_internalize_cleanup_rights(*initial_controlp);
23892bc21ed9SDavid Malone 	m_freem(control);
23902bc21ed9SDavid Malone 	return (error);
2391df8bae1dSRodney W. Grimes }
2392df8bae1dSRodney W. Grimes 
23935b950deaSRobert Watson static struct mbuf *
23946a2989fdSMatthew N. Dodd unp_addsockcred(struct thread *td, struct mbuf *control)
23956a2989fdSMatthew N. Dodd {
239670df31f4SMaxim Konovalov 	struct mbuf *m, *n, *n_prev;
23976a2989fdSMatthew N. Dodd 	struct sockcred *sc;
239870df31f4SMaxim Konovalov 	const struct cmsghdr *cm;
23996a2989fdSMatthew N. Dodd 	int ngroups;
24006a2989fdSMatthew N. Dodd 	int i;
24016a2989fdSMatthew N. Dodd 
24026a2989fdSMatthew N. Dodd 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
24036a2989fdSMatthew N. Dodd 	m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
24046a2989fdSMatthew N. Dodd 	if (m == NULL)
24056a2989fdSMatthew N. Dodd 		return (control);
24066a2989fdSMatthew N. Dodd 
24076a2989fdSMatthew N. Dodd 	sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
24086a2989fdSMatthew N. Dodd 	sc->sc_uid = td->td_ucred->cr_ruid;
24096a2989fdSMatthew N. Dodd 	sc->sc_euid = td->td_ucred->cr_uid;
24106a2989fdSMatthew N. Dodd 	sc->sc_gid = td->td_ucred->cr_rgid;
24116a2989fdSMatthew N. Dodd 	sc->sc_egid = td->td_ucred->cr_gid;
24126a2989fdSMatthew N. Dodd 	sc->sc_ngroups = ngroups;
24136a2989fdSMatthew N. Dodd 	for (i = 0; i < sc->sc_ngroups; i++)
24146a2989fdSMatthew N. Dodd 		sc->sc_groups[i] = td->td_ucred->cr_groups[i];
24156a2989fdSMatthew N. Dodd 
24166a2989fdSMatthew N. Dodd 	/*
24171c381b19SRobert Watson 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
24181c381b19SRobert Watson 	 * created SCM_CREDS control message (struct sockcred) has another
24191c381b19SRobert Watson 	 * format.
24206a2989fdSMatthew N. Dodd 	 */
242170df31f4SMaxim Konovalov 	if (control != NULL)
242270df31f4SMaxim Konovalov 		for (n = control, n_prev = NULL; n != NULL;) {
242370df31f4SMaxim Konovalov 			cm = mtod(n, struct cmsghdr *);
242470df31f4SMaxim Konovalov     			if (cm->cmsg_level == SOL_SOCKET &&
242570df31f4SMaxim Konovalov 			    cm->cmsg_type == SCM_CREDS) {
242670df31f4SMaxim Konovalov     				if (n_prev == NULL)
242770df31f4SMaxim Konovalov 					control = n->m_next;
242870df31f4SMaxim Konovalov 				else
242970df31f4SMaxim Konovalov 					n_prev->m_next = n->m_next;
243070df31f4SMaxim Konovalov 				n = m_free(n);
243170df31f4SMaxim Konovalov 			} else {
243270df31f4SMaxim Konovalov 				n_prev = n;
243370df31f4SMaxim Konovalov 				n = n->m_next;
243470df31f4SMaxim Konovalov 			}
243570df31f4SMaxim Konovalov 		}
24366a2989fdSMatthew N. Dodd 
243770df31f4SMaxim Konovalov 	/* Prepend it to the head. */
243870df31f4SMaxim Konovalov 	m->m_next = control;
243970df31f4SMaxim Konovalov 	return (m);
24406a2989fdSMatthew N. Dodd }
24416a2989fdSMatthew N. Dodd 
2442397c19d1SJeff Roberson static struct unpcb *
2443397c19d1SJeff Roberson fptounp(struct file *fp)
2444397c19d1SJeff Roberson {
2445397c19d1SJeff Roberson 	struct socket *so;
2446397c19d1SJeff Roberson 
2447397c19d1SJeff Roberson 	if (fp->f_type != DTYPE_SOCKET)
2448397c19d1SJeff Roberson 		return (NULL);
2449397c19d1SJeff Roberson 	if ((so = fp->f_data) == NULL)
2450397c19d1SJeff Roberson 		return (NULL);
2451397c19d1SJeff Roberson 	if (so->so_proto->pr_domain != &localdomain)
2452397c19d1SJeff Roberson 		return (NULL);
2453397c19d1SJeff Roberson 	return sotounpcb(so);
2454397c19d1SJeff Roberson }
2455397c19d1SJeff Roberson 
2456397c19d1SJeff Roberson static void
2457397c19d1SJeff Roberson unp_discard(struct file *fp)
2458397c19d1SJeff Roberson {
24590cb64678SKonstantin Belousov 	struct unp_defer *dr;
2460397c19d1SJeff Roberson 
24610cb64678SKonstantin Belousov 	if (unp_externalize_fp(fp)) {
24620cb64678SKonstantin Belousov 		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
24630cb64678SKonstantin Belousov 		dr->ud_fp = fp;
24640cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
24650cb64678SKonstantin Belousov 		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
24660cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
24670cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, 1);
24680cb64678SKonstantin Belousov 		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
24690cb64678SKonstantin Belousov 	} else
2470397c19d1SJeff Roberson 		(void) closef(fp, (struct thread *)NULL);
2471397c19d1SJeff Roberson }
2472397c19d1SJeff Roberson 
2473397c19d1SJeff Roberson static void
24740cb64678SKonstantin Belousov unp_process_defers(void *arg __unused, int pending)
24750cb64678SKonstantin Belousov {
24760cb64678SKonstantin Belousov 	struct unp_defer *dr;
24770cb64678SKonstantin Belousov 	SLIST_HEAD(, unp_defer) drl;
24780cb64678SKonstantin Belousov 	int count;
24790cb64678SKonstantin Belousov 
24800cb64678SKonstantin Belousov 	SLIST_INIT(&drl);
24810cb64678SKonstantin Belousov 	for (;;) {
24820cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
24830cb64678SKonstantin Belousov 		if (SLIST_FIRST(&unp_defers) == NULL) {
24840cb64678SKonstantin Belousov 			UNP_DEFERRED_UNLOCK();
24850cb64678SKonstantin Belousov 			break;
24860cb64678SKonstantin Belousov 		}
24870cb64678SKonstantin Belousov 		SLIST_SWAP(&unp_defers, &drl, unp_defer);
24880cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
24890cb64678SKonstantin Belousov 		count = 0;
24900cb64678SKonstantin Belousov 		while ((dr = SLIST_FIRST(&drl)) != NULL) {
24910cb64678SKonstantin Belousov 			SLIST_REMOVE_HEAD(&drl, ud_link);
24920cb64678SKonstantin Belousov 			closef(dr->ud_fp, NULL);
24930cb64678SKonstantin Belousov 			free(dr, M_TEMP);
24940cb64678SKonstantin Belousov 			count++;
24950cb64678SKonstantin Belousov 		}
24960cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, -count);
24970cb64678SKonstantin Belousov 	}
24980cb64678SKonstantin Belousov }
24990cb64678SKonstantin Belousov 
25000cb64678SKonstantin Belousov static void
2501397c19d1SJeff Roberson unp_internalize_fp(struct file *fp)
2502397c19d1SJeff Roberson {
2503397c19d1SJeff Roberson 	struct unpcb *unp;
2504397c19d1SJeff Roberson 
25053dab55bcSRobert Watson 	UNP_LINK_WLOCK();
2506397c19d1SJeff Roberson 	if ((unp = fptounp(fp)) != NULL) {
2507397c19d1SJeff Roberson 		unp->unp_file = fp;
2508397c19d1SJeff Roberson 		unp->unp_msgcount++;
2509397c19d1SJeff Roberson 	}
2510397c19d1SJeff Roberson 	unp_rights++;
25113dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
2512397c19d1SJeff Roberson }
2513397c19d1SJeff Roberson 
25140cb64678SKonstantin Belousov static int
2515397c19d1SJeff Roberson unp_externalize_fp(struct file *fp)
2516397c19d1SJeff Roberson {
2517397c19d1SJeff Roberson 	struct unpcb *unp;
25180cb64678SKonstantin Belousov 	int ret;
2519397c19d1SJeff Roberson 
25203dab55bcSRobert Watson 	UNP_LINK_WLOCK();
25210cb64678SKonstantin Belousov 	if ((unp = fptounp(fp)) != NULL) {
2522397c19d1SJeff Roberson 		unp->unp_msgcount--;
25230cb64678SKonstantin Belousov 		ret = 1;
25240cb64678SKonstantin Belousov 	} else
25250cb64678SKonstantin Belousov 		ret = 0;
2526397c19d1SJeff Roberson 	unp_rights--;
25273dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
25280cb64678SKonstantin Belousov 	return (ret);
2529397c19d1SJeff Roberson }
2530397c19d1SJeff Roberson 
2531161a0c7cSRobert Watson /*
2532a0ec558aSRobert Watson  * unp_defer indicates whether additional work has been defered for a future
2533a0ec558aSRobert Watson  * pass through unp_gc().  It is thread local and does not require explicit
2534a0ec558aSRobert Watson  * synchronization.
2535161a0c7cSRobert Watson  */
2536397c19d1SJeff Roberson static int	unp_marked;
2537a0ec558aSRobert Watson 
2538397c19d1SJeff Roberson static void
2539a9aa06f7SJason A. Harmening unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2540397c19d1SJeff Roberson {
2541397c19d1SJeff Roberson 	struct unpcb *unp;
2542be26ba7cSPawel Jakub Dawidek 	struct file *fp;
2543be26ba7cSPawel Jakub Dawidek 	int i;
2544397c19d1SJeff Roberson 
2545a9aa06f7SJason A. Harmening 	/*
2546a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2547a9aa06f7SJason A. Harmening 	 */
2548a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2549a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2550a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2551a9aa06f7SJason A. Harmening 
2552be26ba7cSPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
2553be26ba7cSPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
25546f552cb0SJeff Roberson 		if ((unp = fptounp(fp)) == NULL)
2555be26ba7cSPawel Jakub Dawidek 			continue;
2556a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2557be26ba7cSPawel Jakub Dawidek 			continue;
2558a9aa06f7SJason A. Harmening 		unp->unp_gcrefs--;
2559a9aa06f7SJason A. Harmening 	}
2560a9aa06f7SJason A. Harmening }
2561a9aa06f7SJason A. Harmening 
2562a9aa06f7SJason A. Harmening static void
2563a9aa06f7SJason A. Harmening unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2564a9aa06f7SJason A. Harmening {
2565a9aa06f7SJason A. Harmening 	struct unpcb *unp;
2566a9aa06f7SJason A. Harmening 	struct file *fp;
2567a9aa06f7SJason A. Harmening 	int i;
2568a9aa06f7SJason A. Harmening 
2569a9aa06f7SJason A. Harmening 	/*
2570a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2571a9aa06f7SJason A. Harmening 	 */
2572a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2573a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2574a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2575a9aa06f7SJason A. Harmening 
2576a9aa06f7SJason A. Harmening 	for (i = 0; i < fdcount; i++) {
2577a9aa06f7SJason A. Harmening 		fp = fdep[i]->fde_file;
2578a9aa06f7SJason A. Harmening 		if ((unp = fptounp(fp)) == NULL)
2579a9aa06f7SJason A. Harmening 			continue;
2580a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2581a9aa06f7SJason A. Harmening 			continue;
2582a9aa06f7SJason A. Harmening 		unp->unp_gcrefs++;
2583397c19d1SJeff Roberson 		unp_marked++;
2584397c19d1SJeff Roberson 	}
2585be26ba7cSPawel Jakub Dawidek }
2586397c19d1SJeff Roberson 
2587397c19d1SJeff Roberson static void
2588a9aa06f7SJason A. Harmening unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2589397c19d1SJeff Roberson {
2590779f106aSGleb Smirnoff 	struct socket *so, *soa;
259160a5ef26SRobert Watson 
2592397c19d1SJeff Roberson 	so = unp->unp_socket;
2593779f106aSGleb Smirnoff 	SOCK_LOCK(so);
2594779f106aSGleb Smirnoff 	if (SOLISTENING(so)) {
2595397c19d1SJeff Roberson 		/*
2596397c19d1SJeff Roberson 		 * Mark all sockets in our accept queue.
2597397c19d1SJeff Roberson 		 */
2598779f106aSGleb Smirnoff 		TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2599779f106aSGleb Smirnoff 			if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
26000c40f353SConrad Meyer 				continue;
2601397c19d1SJeff Roberson 			SOCKBUF_LOCK(&soa->so_rcv);
2602a9aa06f7SJason A. Harmening 			unp_scan(soa->so_rcv.sb_mb, op);
2603397c19d1SJeff Roberson 			SOCKBUF_UNLOCK(&soa->so_rcv);
2604397c19d1SJeff Roberson 		}
2605779f106aSGleb Smirnoff 	} else {
2606779f106aSGleb Smirnoff 		/*
2607779f106aSGleb Smirnoff 		 * Mark all sockets we reference with RIGHTS.
2608779f106aSGleb Smirnoff 		 */
2609779f106aSGleb Smirnoff 		if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2610779f106aSGleb Smirnoff 			SOCKBUF_LOCK(&so->so_rcv);
2611a9aa06f7SJason A. Harmening 			unp_scan(so->so_rcv.sb_mb, op);
2612779f106aSGleb Smirnoff 			SOCKBUF_UNLOCK(&so->so_rcv);
2613779f106aSGleb Smirnoff 		}
2614779f106aSGleb Smirnoff 	}
2615779f106aSGleb Smirnoff 	SOCK_UNLOCK(so);
2616397c19d1SJeff Roberson }
2617a0ec558aSRobert Watson 
2618a0ec558aSRobert Watson static int unp_recycled;
2619be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2620be6b1304STom Rhodes     "Number of unreachable sockets claimed by the garbage collector.");
2621df8bae1dSRodney W. Grimes 
2622397c19d1SJeff Roberson static int unp_taskcount;
2623be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2624be6b1304STom Rhodes     "Number of times the garbage collector has run.");
2625397c19d1SJeff Roberson 
2626a9aa06f7SJason A. Harmening SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
2627a9aa06f7SJason A. Harmening     "Number of active local sockets.");
2628a9aa06f7SJason A. Harmening 
2629f708ef1bSPoul-Henning Kamp static void
2630a0ec558aSRobert Watson unp_gc(__unused void *arg, int pending)
2631df8bae1dSRodney W. Grimes {
263284d61770SRobert Watson 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
263384d61770SRobert Watson 				    NULL };
2634397c19d1SJeff Roberson 	struct unp_head **head;
2635a9aa06f7SJason A. Harmening 	struct unp_head unp_deadhead;	/* List of potentially-dead sockets. */
2636f7780c61SKonstantin Belousov 	struct file *f, **unref;
2637a9aa06f7SJason A. Harmening 	struct unpcb *unp, *unptmp;
2638a9aa06f7SJason A. Harmening 	int i, total, unp_unreachable;
2639df8bae1dSRodney W. Grimes 
2640a9aa06f7SJason A. Harmening 	LIST_INIT(&unp_deadhead);
2641a0ec558aSRobert Watson 	unp_taskcount++;
2642779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
2643ed5b7817SJulian Elischer 	/*
2644a9aa06f7SJason A. Harmening 	 * First determine which sockets may be in cycles.
2645ed5b7817SJulian Elischer 	 */
2646a9aa06f7SJason A. Harmening 	unp_unreachable = 0;
2647a9aa06f7SJason A. Harmening 
2648397c19d1SJeff Roberson 	for (head = heads; *head != NULL; head++)
2649a9aa06f7SJason A. Harmening 		LIST_FOREACH(unp, *head, unp_link) {
2650a9aa06f7SJason A. Harmening 
2651a9aa06f7SJason A. Harmening 			KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2652a9aa06f7SJason A. Harmening 			    ("%s: unp %p has unexpected gc flags 0x%x",
2653a9aa06f7SJason A. Harmening 			    __func__, unp, (unsigned int)unp->unp_gcflag));
2654a9aa06f7SJason A. Harmening 
2655a9aa06f7SJason A. Harmening 			f = unp->unp_file;
265660a5ef26SRobert Watson 
2657397c19d1SJeff Roberson 			/*
2658a9aa06f7SJason A. Harmening 			 * Check for an unreachable socket potentially in a
2659a9aa06f7SJason A. Harmening 			 * cycle.  It must be in a queue as indicated by
2660a9aa06f7SJason A. Harmening 			 * msgcount, and this must equal the file reference
2661a9aa06f7SJason A. Harmening 			 * count.  Note that when msgcount is 0 the file is
2662a9aa06f7SJason A. Harmening 			 * NULL.
2663a9aa06f7SJason A. Harmening 			 */
2664a9aa06f7SJason A. Harmening 			if (f != NULL && unp->unp_msgcount != 0 &&
2665a9aa06f7SJason A. Harmening 			    f->f_count == unp->unp_msgcount) {
2666a9aa06f7SJason A. Harmening 				LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2667a9aa06f7SJason A. Harmening 				unp->unp_gcflag |= UNPGC_DEAD;
2668a9aa06f7SJason A. Harmening 				unp->unp_gcrefs = unp->unp_msgcount;
2669a9aa06f7SJason A. Harmening 				unp_unreachable++;
2670a9aa06f7SJason A. Harmening 			}
2671a9aa06f7SJason A. Harmening 		}
2672a9aa06f7SJason A. Harmening 
2673a9aa06f7SJason A. Harmening 	/*
2674a9aa06f7SJason A. Harmening 	 * Scan all sockets previously marked as potentially being in a cycle
2675a9aa06f7SJason A. Harmening 	 * and remove the references each socket holds on any UNPGC_DEAD
2676a9aa06f7SJason A. Harmening 	 * sockets in its queue.  After this step, all remaining references on
2677a9aa06f7SJason A. Harmening 	 * sockets marked UNPGC_DEAD should not be part of any cycle.
2678a9aa06f7SJason A. Harmening 	 */
2679a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead)
2680a9aa06f7SJason A. Harmening 		unp_gc_scan(unp, unp_remove_dead_ref);
2681a9aa06f7SJason A. Harmening 
2682a9aa06f7SJason A. Harmening 	/*
2683a9aa06f7SJason A. Harmening 	 * If a socket still has a non-negative refcount, it cannot be in a
2684a9aa06f7SJason A. Harmening 	 * cycle.  In this case increment refcount of all children iteratively.
2685397c19d1SJeff Roberson 	 * Stop the scan once we do a complete loop without discovering
2686397c19d1SJeff Roberson 	 * a new reachable socket.
2687397c19d1SJeff Roberson 	 */
2688df8bae1dSRodney W. Grimes 	do {
2689397c19d1SJeff Roberson 		unp_marked = 0;
2690a9aa06f7SJason A. Harmening 		LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
2691a9aa06f7SJason A. Harmening 			if (unp->unp_gcrefs > 0) {
2692a9aa06f7SJason A. Harmening 				unp->unp_gcflag &= ~UNPGC_DEAD;
2693a9aa06f7SJason A. Harmening 				LIST_REMOVE(unp, unp_dead);
2694a9aa06f7SJason A. Harmening 				KASSERT(unp_unreachable > 0,
2695a9aa06f7SJason A. Harmening 				    ("%s: unp_unreachable underflow.",
2696a9aa06f7SJason A. Harmening 				    __func__));
2697a9aa06f7SJason A. Harmening 				unp_unreachable--;
2698a9aa06f7SJason A. Harmening 				unp_gc_scan(unp, unp_restore_undead_ref);
2699a9aa06f7SJason A. Harmening 			}
2700397c19d1SJeff Roberson 	} while (unp_marked);
2701a9aa06f7SJason A. Harmening 
2702779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
2703a9aa06f7SJason A. Harmening 
2704397c19d1SJeff Roberson 	if (unp_unreachable == 0)
2705397c19d1SJeff Roberson 		return;
270660a5ef26SRobert Watson 
2707ed5b7817SJulian Elischer 	/*
2708a9aa06f7SJason A. Harmening 	 * Allocate space for a local array of dead unpcbs.
2709a9aa06f7SJason A. Harmening 	 * TODO: can this path be simplified by instead using the local
2710a9aa06f7SJason A. Harmening 	 * dead list at unp_deadhead, after taking out references
2711a9aa06f7SJason A. Harmening 	 * on the file object and/or unpcb and dropping the link lock?
2712ed5b7817SJulian Elischer 	 */
2713397c19d1SJeff Roberson 	unref = malloc(unp_unreachable * sizeof(struct file *),
2714397c19d1SJeff Roberson 	    M_TEMP, M_WAITOK);
271560a5ef26SRobert Watson 
2716ed5b7817SJulian Elischer 	/*
2717397c19d1SJeff Roberson 	 * Iterate looking for sockets which have been specifically marked
2718a9aa06f7SJason A. Harmening 	 * as unreachable and store them locally.
2719ed5b7817SJulian Elischer 	 */
2720f7780c61SKonstantin Belousov 	UNP_LINK_RLOCK();
2721a9aa06f7SJason A. Harmening 	total = 0;
2722a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
2723a9aa06f7SJason A. Harmening 		KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
2724a9aa06f7SJason A. Harmening 		    ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
2725a9aa06f7SJason A. Harmening 		unp->unp_gcflag &= ~UNPGC_DEAD;
2726f7780c61SKonstantin Belousov 		f = unp->unp_file;
2727f7780c61SKonstantin Belousov 		if (unp->unp_msgcount == 0 || f == NULL ||
2728f1cf2b9dSKonstantin Belousov 		    f->f_count != unp->unp_msgcount ||
2729f1cf2b9dSKonstantin Belousov 		    !fhold(f))
2730f7780c61SKonstantin Belousov 			continue;
2731f7780c61SKonstantin Belousov 		unref[total++] = f;
2732f7780c61SKonstantin Belousov 		KASSERT(total <= unp_unreachable,
2733a9aa06f7SJason A. Harmening 		    ("%s: incorrect unreachable count.", __func__));
2734397c19d1SJeff Roberson 	}
2735f7780c61SKonstantin Belousov 	UNP_LINK_RUNLOCK();
273660a5ef26SRobert Watson 
2737ed5b7817SJulian Elischer 	/*
2738397c19d1SJeff Roberson 	 * Now flush all sockets, free'ing rights.  This will free the
2739397c19d1SJeff Roberson 	 * struct files associated with these sockets but leave each socket
2740397c19d1SJeff Roberson 	 * with one remaining ref.
2741ed5b7817SJulian Elischer 	 */
27421fb51a12SBjoern A. Zeeb 	for (i = 0; i < total; i++) {
27431fb51a12SBjoern A. Zeeb 		struct socket *so;
27441fb51a12SBjoern A. Zeeb 
27451fb51a12SBjoern A. Zeeb 		so = unref[i]->f_data;
27461fb51a12SBjoern A. Zeeb 		CURVNET_SET(so->so_vnet);
27471fb51a12SBjoern A. Zeeb 		sorflush(so);
27481fb51a12SBjoern A. Zeeb 		CURVNET_RESTORE();
27491fb51a12SBjoern A. Zeeb 	}
275060a5ef26SRobert Watson 
2751ed5b7817SJulian Elischer 	/*
2752397c19d1SJeff Roberson 	 * And finally release the sockets so they can be reclaimed.
2753ed5b7817SJulian Elischer 	 */
2754f7780c61SKonstantin Belousov 	for (i = 0; i < total; i++)
2755397c19d1SJeff Roberson 		fdrop(unref[i], NULL);
2756f7780c61SKonstantin Belousov 	unp_recycled += total;
2757397c19d1SJeff Roberson 	free(unref, M_TEMP);
2758df8bae1dSRodney W. Grimes }
2759df8bae1dSRodney W. Grimes 
27600b36cd25SRobert Watson static void
276199ab95dbSMark Johnston unp_dispose_mbuf(struct mbuf *m)
2762df8bae1dSRodney W. Grimes {
2763996c772fSJohn Dyson 
2764df8bae1dSRodney W. Grimes 	if (m)
2765be26ba7cSPawel Jakub Dawidek 		unp_scan(m, unp_freerights);
2766df8bae1dSRodney W. Grimes }
2767df8bae1dSRodney W. Grimes 
27680c40f353SConrad Meyer /*
27690c40f353SConrad Meyer  * Synchronize against unp_gc, which can trip over data as we are freeing it.
27700c40f353SConrad Meyer  */
27710c40f353SConrad Meyer static void
277299ab95dbSMark Johnston unp_dispose(struct socket *so)
27730c40f353SConrad Meyer {
27740c40f353SConrad Meyer 	struct unpcb *unp;
27750c40f353SConrad Meyer 
27760c40f353SConrad Meyer 	unp = sotounpcb(so);
2777779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
27780c40f353SConrad Meyer 	unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2779779f106aSGleb Smirnoff 	UNP_LINK_WUNLOCK();
2780779f106aSGleb Smirnoff 	if (!SOLISTENING(so))
278199ab95dbSMark Johnston 		unp_dispose_mbuf(so->so_rcv.sb_mb);
27820c40f353SConrad Meyer }
27830c40f353SConrad Meyer 
2784f708ef1bSPoul-Henning Kamp static void
2785be26ba7cSPawel Jakub Dawidek unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2786df8bae1dSRodney W. Grimes {
27872bc21ed9SDavid Malone 	struct mbuf *m;
27882bc21ed9SDavid Malone 	struct cmsghdr *cm;
27892bc21ed9SDavid Malone 	void *data;
27902bc21ed9SDavid Malone 	socklen_t clen, datalen;
2791df8bae1dSRodney W. Grimes 
2792fc3fcacfSRobert Watson 	while (m0 != NULL) {
27932bc21ed9SDavid Malone 		for (m = m0; m; m = m->m_next) {
279412396bdcSDavid Malone 			if (m->m_type != MT_CONTROL)
2795df8bae1dSRodney W. Grimes 				continue;
27962bc21ed9SDavid Malone 
27972bc21ed9SDavid Malone 			cm = mtod(m, struct cmsghdr *);
27982bc21ed9SDavid Malone 			clen = m->m_len;
27992bc21ed9SDavid Malone 
28002bc21ed9SDavid Malone 			while (cm != NULL) {
28012bc21ed9SDavid Malone 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
28022bc21ed9SDavid Malone 					break;
28032bc21ed9SDavid Malone 
28042bc21ed9SDavid Malone 				data = CMSG_DATA(cm);
28052bc21ed9SDavid Malone 				datalen = (caddr_t)cm + cm->cmsg_len
28062bc21ed9SDavid Malone 				    - (caddr_t)data;
28072bc21ed9SDavid Malone 
28082bc21ed9SDavid Malone 				if (cm->cmsg_level == SOL_SOCKET &&
28092bc21ed9SDavid Malone 				    cm->cmsg_type == SCM_RIGHTS) {
2810be26ba7cSPawel Jakub Dawidek 					(*op)(data, datalen /
2811be26ba7cSPawel Jakub Dawidek 					    sizeof(struct filedescent *));
28122bc21ed9SDavid Malone 				}
28132bc21ed9SDavid Malone 
28142bc21ed9SDavid Malone 				if (CMSG_SPACE(datalen) < clen) {
28152bc21ed9SDavid Malone 					clen -= CMSG_SPACE(datalen);
28162bc21ed9SDavid Malone 					cm = (struct cmsghdr *)
28172bc21ed9SDavid Malone 					    ((caddr_t)cm + CMSG_SPACE(datalen));
28182bc21ed9SDavid Malone 				} else {
28192bc21ed9SDavid Malone 					clen = 0;
28202bc21ed9SDavid Malone 					cm = NULL;
28212bc21ed9SDavid Malone 				}
28222bc21ed9SDavid Malone 			}
2823df8bae1dSRodney W. Grimes 		}
2824c29a3321SKevin Lo 		m0 = m0->m_nextpkt;
2825df8bae1dSRodney W. Grimes 	}
2826df8bae1dSRodney W. Grimes }
2827df8bae1dSRodney W. Grimes 
2828662c901cSMikolaj Golub /*
2829662c901cSMikolaj Golub  * A helper function called by VFS before socket-type vnode reclamation.
2830662c901cSMikolaj Golub  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2831662c901cSMikolaj Golub  * use count.
2832662c901cSMikolaj Golub  */
2833662c901cSMikolaj Golub void
2834662c901cSMikolaj Golub vfs_unp_reclaim(struct vnode *vp)
2835662c901cSMikolaj Golub {
2836662c901cSMikolaj Golub 	struct unpcb *unp;
2837662c901cSMikolaj Golub 	int active;
283875a67bf3SMatt Macy 	struct mtx *vplock;
2839662c901cSMikolaj Golub 
2840662c901cSMikolaj Golub 	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2841662c901cSMikolaj Golub 	KASSERT(vp->v_type == VSOCK,
2842662c901cSMikolaj Golub 	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2843662c901cSMikolaj Golub 
2844662c901cSMikolaj Golub 	active = 0;
284575a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
284675a67bf3SMatt Macy 	mtx_lock(vplock);
28470c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp);
2848662c901cSMikolaj Golub 	if (unp == NULL)
2849662c901cSMikolaj Golub 		goto done;
2850662c901cSMikolaj Golub 	UNP_PCB_LOCK(unp);
2851c7e41c8bSMikolaj Golub 	if (unp->unp_vnode == vp) {
2852c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
2853662c901cSMikolaj Golub 		unp->unp_vnode = NULL;
2854662c901cSMikolaj Golub 		active = 1;
2855662c901cSMikolaj Golub 	}
2856662c901cSMikolaj Golub 	UNP_PCB_UNLOCK(unp);
2857662c901cSMikolaj Golub  done:
285875a67bf3SMatt Macy 	mtx_unlock(vplock);
2859662c901cSMikolaj Golub 	if (active)
2860662c901cSMikolaj Golub 		vunref(vp);
2861662c901cSMikolaj Golub }
2862662c901cSMikolaj Golub 
286303c96c31SRobert Watson #ifdef DDB
286403c96c31SRobert Watson static void
286503c96c31SRobert Watson db_print_indent(int indent)
286603c96c31SRobert Watson {
286703c96c31SRobert Watson 	int i;
286803c96c31SRobert Watson 
286903c96c31SRobert Watson 	for (i = 0; i < indent; i++)
287003c96c31SRobert Watson 		db_printf(" ");
287103c96c31SRobert Watson }
287203c96c31SRobert Watson 
287303c96c31SRobert Watson static void
287403c96c31SRobert Watson db_print_unpflags(int unp_flags)
287503c96c31SRobert Watson {
287603c96c31SRobert Watson 	int comma;
287703c96c31SRobert Watson 
287803c96c31SRobert Watson 	comma = 0;
287903c96c31SRobert Watson 	if (unp_flags & UNP_HAVEPC) {
288003c96c31SRobert Watson 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
288103c96c31SRobert Watson 		comma = 1;
288203c96c31SRobert Watson 	}
288303c96c31SRobert Watson 	if (unp_flags & UNP_WANTCRED) {
288403c96c31SRobert Watson 		db_printf("%sUNP_WANTCRED", comma ? ", " : "");
288503c96c31SRobert Watson 		comma = 1;
288603c96c31SRobert Watson 	}
288703c96c31SRobert Watson 	if (unp_flags & UNP_CONNWAIT) {
288803c96c31SRobert Watson 		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
288903c96c31SRobert Watson 		comma = 1;
289003c96c31SRobert Watson 	}
289103c96c31SRobert Watson 	if (unp_flags & UNP_CONNECTING) {
289203c96c31SRobert Watson 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
289303c96c31SRobert Watson 		comma = 1;
289403c96c31SRobert Watson 	}
289503c96c31SRobert Watson 	if (unp_flags & UNP_BINDING) {
289603c96c31SRobert Watson 		db_printf("%sUNP_BINDING", comma ? ", " : "");
289703c96c31SRobert Watson 		comma = 1;
289803c96c31SRobert Watson 	}
289903c96c31SRobert Watson }
290003c96c31SRobert Watson 
290103c96c31SRobert Watson static void
290203c96c31SRobert Watson db_print_xucred(int indent, struct xucred *xu)
290303c96c31SRobert Watson {
290403c96c31SRobert Watson 	int comma, i;
290503c96c31SRobert Watson 
290603c96c31SRobert Watson 	db_print_indent(indent);
2907c5afec6eSDmitry Chagin 	db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
2908c5afec6eSDmitry Chagin 	    xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
290903c96c31SRobert Watson 	db_print_indent(indent);
291003c96c31SRobert Watson 	db_printf("cr_groups: ");
291103c96c31SRobert Watson 	comma = 0;
291203c96c31SRobert Watson 	for (i = 0; i < xu->cr_ngroups; i++) {
291303c96c31SRobert Watson 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
291403c96c31SRobert Watson 		comma = 1;
291503c96c31SRobert Watson 	}
291603c96c31SRobert Watson 	db_printf("\n");
291703c96c31SRobert Watson }
291803c96c31SRobert Watson 
291903c96c31SRobert Watson static void
292003c96c31SRobert Watson db_print_unprefs(int indent, struct unp_head *uh)
292103c96c31SRobert Watson {
292203c96c31SRobert Watson 	struct unpcb *unp;
292303c96c31SRobert Watson 	int counter;
292403c96c31SRobert Watson 
292503c96c31SRobert Watson 	counter = 0;
292603c96c31SRobert Watson 	LIST_FOREACH(unp, uh, unp_reflink) {
292703c96c31SRobert Watson 		if (counter % 4 == 0)
292803c96c31SRobert Watson 			db_print_indent(indent);
292903c96c31SRobert Watson 		db_printf("%p  ", unp);
293003c96c31SRobert Watson 		if (counter % 4 == 3)
293103c96c31SRobert Watson 			db_printf("\n");
293203c96c31SRobert Watson 		counter++;
293303c96c31SRobert Watson 	}
293403c96c31SRobert Watson 	if (counter != 0 && counter % 4 != 0)
293503c96c31SRobert Watson 		db_printf("\n");
293603c96c31SRobert Watson }
293703c96c31SRobert Watson 
293803c96c31SRobert Watson DB_SHOW_COMMAND(unpcb, db_show_unpcb)
293903c96c31SRobert Watson {
294003c96c31SRobert Watson 	struct unpcb *unp;
294103c96c31SRobert Watson 
294203c96c31SRobert Watson         if (!have_addr) {
294303c96c31SRobert Watson                 db_printf("usage: show unpcb <addr>\n");
294403c96c31SRobert Watson                 return;
294503c96c31SRobert Watson         }
294603c96c31SRobert Watson         unp = (struct unpcb *)addr;
294703c96c31SRobert Watson 
294803c96c31SRobert Watson 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
294903c96c31SRobert Watson 	    unp->unp_vnode);
295003c96c31SRobert Watson 
2951fc8fdae0SMatthew D Fleming 	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
295203c96c31SRobert Watson 	    unp->unp_conn);
295303c96c31SRobert Watson 
295403c96c31SRobert Watson 	db_printf("unp_refs:\n");
295503c96c31SRobert Watson 	db_print_unprefs(2, &unp->unp_refs);
295603c96c31SRobert Watson 
295703c96c31SRobert Watson 	/* XXXRW: Would be nice to print the full address, if any. */
295803c96c31SRobert Watson 	db_printf("unp_addr: %p\n", unp->unp_addr);
295903c96c31SRobert Watson 
2960c2090e73SAlan Somers 	db_printf("unp_gencnt: %llu\n",
296103c96c31SRobert Watson 	    (unsigned long long)unp->unp_gencnt);
296203c96c31SRobert Watson 
296303c96c31SRobert Watson 	db_printf("unp_flags: %x (", unp->unp_flags);
296403c96c31SRobert Watson 	db_print_unpflags(unp->unp_flags);
296503c96c31SRobert Watson 	db_printf(")\n");
296603c96c31SRobert Watson 
296703c96c31SRobert Watson 	db_printf("unp_peercred:\n");
296803c96c31SRobert Watson 	db_print_xucred(2, &unp->unp_peercred);
296903c96c31SRobert Watson 
297003c96c31SRobert Watson 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
297103c96c31SRobert Watson }
297203c96c31SRobert Watson #endif
2973