xref: /freebsd/sys/kern/uipc_usrreq.c (revision 50b07c1f7131fd535bbe1b53a3a2e4dfcdcc2e51)
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>
684f590175SPaul Saab #include <sys/eventhandler.h>
69d5cbccecSMark Johnston #include <sys/fcntl.h>
70639acc13SGarrett Wollman #include <sys/file.h>
71960ed29cSSeigo Tanimura #include <sys/filedesc.h>
72960ed29cSSeigo Tanimura #include <sys/kernel.h>
73960ed29cSSeigo Tanimura #include <sys/lock.h>
74d5cbccecSMark Johnston #include <sys/malloc.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 /*
109d5cbccecSMark Johnston  * See unpcb.h for the locking key.
1103dab55bcSRobert Watson  */
1113dab55bcSRobert Watson 
1129e9d298aSJeff Roberson static uma_zone_t	unp_zone;
1133dab55bcSRobert Watson static unp_gen_t	unp_gencnt;	/* (l) */
1143dab55bcSRobert Watson static u_int		unp_count;	/* (l) Count of local sockets. */
115aea52f1bSRobert Watson static ino_t		unp_ino;	/* Prototype for fake inode numbers. */
1163dab55bcSRobert Watson static int		unp_rights;	/* (g) File descriptors in flight. */
1173dab55bcSRobert Watson static struct unp_head	unp_shead;	/* (l) List of stream sockets. */
1183dab55bcSRobert Watson static struct unp_head	unp_dhead;	/* (l) List of datagram sockets. */
11984d61770SRobert Watson static struct unp_head	unp_sphead;	/* (l) List of seqpacket sockets. */
12098271db4SGarrett Wollman 
1210cb64678SKonstantin Belousov struct unp_defer {
1220cb64678SKonstantin Belousov 	SLIST_ENTRY(unp_defer) ud_link;
1230cb64678SKonstantin Belousov 	struct file *ud_fp;
1240cb64678SKonstantin Belousov };
1250cb64678SKonstantin Belousov static SLIST_HEAD(, unp_defer) unp_defers;
1260cb64678SKonstantin Belousov static int unp_defers_count;
1270cb64678SKonstantin Belousov 
128aea52f1bSRobert Watson static const struct sockaddr	sun_noname = { sizeof(sun_noname), AF_LOCAL };
12998271db4SGarrett Wollman 
130df8bae1dSRodney W. Grimes /*
131aea52f1bSRobert Watson  * Garbage collection of cyclic file descriptor/socket references occurs
132aea52f1bSRobert Watson  * asynchronously in a taskqueue context in order to avoid recursion and
133aea52f1bSRobert Watson  * reentrance in the UNIX domain socket, file descriptor, and socket layer
134aea52f1bSRobert Watson  * code.  See unp_gc() for a full description.
135df8bae1dSRodney W. Grimes  */
136daee0f0bSKonstantin Belousov static struct timeout_task unp_gc_task;
137f708ef1bSPoul-Henning Kamp 
138ce5f32deSRobert Watson /*
1390cb64678SKonstantin Belousov  * The close of unix domain sockets attached as SCM_RIGHTS is
1400cb64678SKonstantin Belousov  * postponed to the taskqueue, to avoid arbitrary recursion depth.
1410cb64678SKonstantin Belousov  * The attached sockets might have another sockets attached.
1420cb64678SKonstantin Belousov  */
1430cb64678SKonstantin Belousov static struct task	unp_defer_task;
1440cb64678SKonstantin Belousov 
1450cb64678SKonstantin Belousov /*
1467e711c3aSRobert Watson  * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
1477e711c3aSRobert Watson  * stream sockets, although the total for sender and receiver is actually
1487e711c3aSRobert Watson  * only PIPSIZ.
1497e711c3aSRobert Watson  *
1507e711c3aSRobert Watson  * Datagram sockets really use the sendspace as the maximum datagram size,
1517e711c3aSRobert Watson  * and don't really want to reserve the sendspace.  Their recvspace should be
1527e711c3aSRobert Watson  * large enough for at least one max-size datagram plus address.
1537e711c3aSRobert Watson  */
1547e711c3aSRobert Watson #ifndef PIPSIZ
1557e711c3aSRobert Watson #define	PIPSIZ	8192
1567e711c3aSRobert Watson #endif
1577e711c3aSRobert Watson static u_long	unpst_sendspace = PIPSIZ;
1587e711c3aSRobert Watson static u_long	unpst_recvspace = PIPSIZ;
1597e711c3aSRobert Watson static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
1607e711c3aSRobert Watson static u_long	unpdg_recvspace = 4*1024;
16184d61770SRobert Watson static u_long	unpsp_sendspace = PIPSIZ;	/* really max datagram size */
16284d61770SRobert Watson static u_long	unpsp_recvspace = PIPSIZ;
1637e711c3aSRobert Watson 
1647029da5cSPawel Biernacki static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1657029da5cSPawel Biernacki     "Local domain");
1667029da5cSPawel Biernacki static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
1677029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1686472ac3dSEd Schouten     "SOCK_STREAM");
1697029da5cSPawel Biernacki static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
1707029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1717029da5cSPawel Biernacki     "SOCK_DGRAM");
1727029da5cSPawel Biernacki static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
1737029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
17484d61770SRobert Watson     "SOCK_SEQPACKET");
175e4445a03SRobert Watson 
1767e711c3aSRobert Watson SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
177be6b1304STom Rhodes 	   &unpst_sendspace, 0, "Default stream send space.");
1787e711c3aSRobert Watson SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
179be6b1304STom Rhodes 	   &unpst_recvspace, 0, "Default stream receive space.");
1807e711c3aSRobert Watson SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
181be6b1304STom Rhodes 	   &unpdg_sendspace, 0, "Default datagram send space.");
1827e711c3aSRobert Watson SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
183be6b1304STom Rhodes 	   &unpdg_recvspace, 0, "Default datagram receive space.");
18484d61770SRobert Watson SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
18584d61770SRobert Watson 	   &unpsp_sendspace, 0, "Default seqpacket send space.");
18684d61770SRobert Watson SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
18784d61770SRobert Watson 	   &unpsp_recvspace, 0, "Default seqpacket receive space.");
188be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
189be6b1304STom Rhodes     "File descriptors in flight.");
1900cb64678SKonstantin Belousov SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
1910cb64678SKonstantin Belousov     &unp_defers_count, 0,
1920cb64678SKonstantin Belousov     "File descriptors deferred to taskqueue for close.");
1937e711c3aSRobert Watson 
194175389cfSEdward Tomasz Napierala /*
195e7c33e29SRobert Watson  * Locking and synchronization:
196ce5f32deSRobert Watson  *
197d5cbccecSMark Johnston  * Several types of locks exist in the local domain socket implementation:
198d5cbccecSMark Johnston  * - a global linkage lock
199d5cbccecSMark Johnston  * - a global connection list lock
200d5cbccecSMark Johnston  * - the mtxpool lock
201d5cbccecSMark Johnston  * - per-unpcb mutexes
202d5cbccecSMark Johnston  *
203d5cbccecSMark Johnston  * The linkage lock protects the global socket lists, the generation number
204d5cbccecSMark Johnston  * counter and garbage collector state.
205d5cbccecSMark Johnston  *
206d5cbccecSMark Johnston  * The connection list lock protects the list of referring sockets in a datagram
207d5cbccecSMark Johnston  * socket PCB.  This lock is also overloaded to protect a global list of
208d5cbccecSMark Johnston  * sockets whose buffers contain socket references in the form of SCM_RIGHTS
209d5cbccecSMark Johnston  * messages.  To avoid recursion, such references are released by a dedicated
210d5cbccecSMark Johnston  * thread.
21175a67bf3SMatt Macy  *
21275a67bf3SMatt Macy  * The mtxpool lock protects the vnode from being modified while referenced.
213d5cbccecSMark Johnston  * Lock ordering rules require that it be acquired before any PCB locks.
21475a67bf3SMatt Macy  *
215d5cbccecSMark Johnston  * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
216d5cbccecSMark Johnston  * unpcb.  This includes the unp_conn field, which either links two connected
217d5cbccecSMark Johnston  * PCBs together (for connected socket types) or points at the destination
218d5cbccecSMark Johnston  * socket (for connectionless socket types).  The operations of creating or
219d5cbccecSMark Johnston  * destroying a connection therefore involve locking multiple PCBs.  To avoid
220d5cbccecSMark Johnston  * lock order reversals, in some cases this involves dropping a PCB lock and
221d5cbccecSMark Johnston  * using a reference counter to maintain liveness.
222ce5f32deSRobert Watson  *
223e7c33e29SRobert Watson  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
224e7c33e29SRobert Watson  * allocated in pru_attach() and freed in pru_detach().  The validity of that
225e7c33e29SRobert Watson  * pointer is an invariant, so no lock is required to dereference the so_pcb
226e7c33e29SRobert Watson  * pointer if a valid socket reference is held by the caller.  In practice,
227e7c33e29SRobert Watson  * this is always true during operations performed on a socket.  Each unpcb
228e7c33e29SRobert Watson  * has a back-pointer to its socket, unp_socket, which will be stable under
229e7c33e29SRobert Watson  * the same circumstances.
230e7c33e29SRobert Watson  *
231e7c33e29SRobert Watson  * This pointer may only be safely dereferenced as long as a valid reference
232e7c33e29SRobert Watson  * to the unpcb is held.  Typically, this reference will be from the socket,
233e7c33e29SRobert Watson  * or from another unpcb when the referring unpcb's lock is held (in order
234e7c33e29SRobert Watson  * that the reference not be invalidated during use).  For example, to follow
23575a67bf3SMatt Macy  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
23675a67bf3SMatt Macy  * that detach is not run clearing unp_socket.
237e7c33e29SRobert Watson  *
238e7c33e29SRobert Watson  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
239e7c33e29SRobert Watson  * protocols, bind() is a non-atomic operation, and connect() requires
240e7c33e29SRobert Watson  * potential sleeping in the protocol, due to potentially waiting on local or
241e7c33e29SRobert Watson  * distributed file systems.  We try to separate "lookup" operations, which
242e7c33e29SRobert Watson  * may sleep, and the IPC operations themselves, which typically can occur
243e7c33e29SRobert Watson  * with relative atomicity as locks can be held over the entire operation.
244e7c33e29SRobert Watson  *
245e7c33e29SRobert Watson  * Another tricky issue is simultaneous multi-threaded or multi-process
246e7c33e29SRobert Watson  * access to a single UNIX domain socket.  These are handled by the flags
247e7c33e29SRobert Watson  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
248e7c33e29SRobert Watson  * binding, both of which involve dropping UNIX domain socket locks in order
249e7c33e29SRobert Watson  * to perform namei() and other file system operations.
250ce5f32deSRobert Watson  */
2513dab55bcSRobert Watson static struct rwlock	unp_link_rwlock;
2520cb64678SKonstantin Belousov static struct mtx	unp_defers_lock;
253e7c33e29SRobert Watson 
2543dab55bcSRobert Watson #define	UNP_LINK_LOCK_INIT()		rw_init(&unp_link_rwlock,	\
2553dab55bcSRobert Watson 					    "unp_link_rwlock")
256e7c33e29SRobert Watson 
2573dab55bcSRobert Watson #define	UNP_LINK_LOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
258e7c33e29SRobert Watson 					    RA_LOCKED)
2593dab55bcSRobert Watson #define	UNP_LINK_UNLOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
260e7c33e29SRobert Watson 					    RA_UNLOCKED)
261e7c33e29SRobert Watson 
2623dab55bcSRobert Watson #define	UNP_LINK_RLOCK()		rw_rlock(&unp_link_rwlock)
2633dab55bcSRobert Watson #define	UNP_LINK_RUNLOCK()		rw_runlock(&unp_link_rwlock)
2643dab55bcSRobert Watson #define	UNP_LINK_WLOCK()		rw_wlock(&unp_link_rwlock)
2653dab55bcSRobert Watson #define	UNP_LINK_WUNLOCK()		rw_wunlock(&unp_link_rwlock)
2663dab55bcSRobert Watson #define	UNP_LINK_WLOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
267e7c33e29SRobert Watson 					    RA_WLOCKED)
268779f106aSGleb Smirnoff #define	UNP_LINK_WOWNED()		rw_wowned(&unp_link_rwlock)
269e7c33e29SRobert Watson 
2700cb64678SKonstantin Belousov #define	UNP_DEFERRED_LOCK_INIT()	mtx_init(&unp_defers_lock, \
2710cb64678SKonstantin Belousov 					    "unp_defer", NULL, MTX_DEF)
2720cb64678SKonstantin Belousov #define	UNP_DEFERRED_LOCK()		mtx_lock(&unp_defers_lock)
2730cb64678SKonstantin Belousov #define	UNP_DEFERRED_UNLOCK()		mtx_unlock(&unp_defers_lock)
2740cb64678SKonstantin Belousov 
27575a67bf3SMatt Macy #define UNP_REF_LIST_LOCK()		UNP_DEFERRED_LOCK();
27675a67bf3SMatt Macy #define UNP_REF_LIST_UNLOCK()		UNP_DEFERRED_UNLOCK();
27775a67bf3SMatt Macy 
278e7c33e29SRobert Watson #define UNP_PCB_LOCK_INIT(unp)		mtx_init(&(unp)->unp_mtx,	\
279d9525340SMatt Macy 					    "unp", "unp",	\
28075a67bf3SMatt Macy 					    MTX_DUPOK|MTX_DEF)
281e7c33e29SRobert Watson #define	UNP_PCB_LOCK_DESTROY(unp)	mtx_destroy(&(unp)->unp_mtx)
282ccdadf1aSMark Johnston #define	UNP_PCB_LOCKPTR(unp)		(&(unp)->unp_mtx)
283e7c33e29SRobert Watson #define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
28475a67bf3SMatt Macy #define	UNP_PCB_TRYLOCK(unp)		mtx_trylock(&(unp)->unp_mtx)
285e7c33e29SRobert Watson #define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
28675a67bf3SMatt Macy #define	UNP_PCB_OWNED(unp)		mtx_owned(&(unp)->unp_mtx)
287e7c33e29SRobert Watson #define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
28875a67bf3SMatt Macy #define	UNP_PCB_UNLOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
2890d9ce3a1SRobert Watson 
2902c899584SRobert Watson static int	uipc_connect2(struct socket *, struct socket *);
2910b36cd25SRobert Watson static int	uipc_ctloutput(struct socket *, struct sockopt *);
292aea52f1bSRobert Watson static int	unp_connect(struct socket *, struct sockaddr *,
293aea52f1bSRobert Watson 		    struct thread *);
2947493f24eSPawel Jakub Dawidek static int	unp_connectat(int, struct socket *, struct sockaddr *,
2957493f24eSPawel Jakub Dawidek 		    struct thread *);
2966a2989fdSMatthew N. Dodd static int	unp_connect2(struct socket *so, struct socket *so2, int);
297e7c33e29SRobert Watson static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
29899ab95dbSMark Johnston static void	unp_dispose(struct socket *so);
29999ab95dbSMark Johnston static void	unp_dispose_mbuf(struct mbuf *);
3004d77a549SAlfred Perlstein static void	unp_shutdown(struct unpcb *);
301afc055d9SEd Schouten static void	unp_drop(struct unpcb *);
302a0ec558aSRobert Watson static void	unp_gc(__unused void *, int);
303be26ba7cSPawel Jakub Dawidek static void	unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
3044d77a549SAlfred Perlstein static void	unp_discard(struct file *);
3058cb539f1SPawel Jakub Dawidek static void	unp_freerights(struct filedescent **, int);
3060b36cd25SRobert Watson static void	unp_init(void);
3074d77a549SAlfred Perlstein static int	unp_internalize(struct mbuf **, struct thread *);
308397c19d1SJeff Roberson static void	unp_internalize_fp(struct file *);
309c2e3c52eSJilles Tjoelker static int	unp_externalize(struct mbuf *, struct mbuf **, int);
3100cb64678SKonstantin Belousov static int	unp_externalize_fp(struct file *);
311ede4af47SConrad Meyer static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *, int);
3120cb64678SKonstantin Belousov static void	unp_process_defers(void * __unused, int);
313f708ef1bSPoul-Henning Kamp 
31475a67bf3SMatt Macy static void
31575a67bf3SMatt Macy unp_pcb_hold(struct unpcb *unp)
31675a67bf3SMatt Macy {
3175362170dSMark Johnston 	u_int old __unused;
3185362170dSMark Johnston 
3195362170dSMark Johnston 	old = refcount_acquire(&unp->unp_refcount);
3205362170dSMark Johnston 	KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
32175a67bf3SMatt Macy }
32275a67bf3SMatt Macy 
3235362170dSMark Johnston static __result_use_check bool
32475a67bf3SMatt Macy unp_pcb_rele(struct unpcb *unp)
32575a67bf3SMatt Macy {
3265362170dSMark Johnston 	bool ret;
32775a67bf3SMatt Macy 
32875a67bf3SMatt Macy 	UNP_PCB_LOCK_ASSERT(unp);
3295362170dSMark Johnston 
3305362170dSMark Johnston 	if ((ret = refcount_release(&unp->unp_refcount))) {
33175a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
33275a67bf3SMatt Macy 		UNP_PCB_LOCK_DESTROY(unp);
33375a67bf3SMatt Macy 		uma_zfree(unp_zone, unp);
33475a67bf3SMatt Macy 	}
3355362170dSMark Johnston 	return (ret);
33675a67bf3SMatt Macy }
33775a67bf3SMatt Macy 
33875a67bf3SMatt Macy static void
339f0317f86SMark Johnston unp_pcb_rele_notlast(struct unpcb *unp)
340f0317f86SMark Johnston {
341f0317f86SMark Johnston 	bool ret __unused;
342f0317f86SMark Johnston 
343f0317f86SMark Johnston 	ret = refcount_release(&unp->unp_refcount);
344f0317f86SMark Johnston 	KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
345f0317f86SMark Johnston }
346f0317f86SMark Johnston 
347f0317f86SMark Johnston static void
3484820bf6aSMark Johnston unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
34975a67bf3SMatt Macy {
35075a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
35175a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp2);
3524820bf6aSMark Johnston 
3534820bf6aSMark Johnston 	if (unp == unp2) {
3544820bf6aSMark Johnston 		UNP_PCB_LOCK(unp);
3554820bf6aSMark Johnston 	} else if ((uintptr_t)unp2 > (uintptr_t)unp) {
35675a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
35775a67bf3SMatt Macy 		UNP_PCB_LOCK(unp2);
35875a67bf3SMatt Macy 	} else {
35975a67bf3SMatt Macy 		UNP_PCB_LOCK(unp2);
36075a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
36175a67bf3SMatt Macy 	}
36275a67bf3SMatt Macy }
36375a67bf3SMatt Macy 
3644820bf6aSMark Johnston static void
3654820bf6aSMark Johnston unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
3664820bf6aSMark Johnston {
3674820bf6aSMark Johnston 	UNP_PCB_UNLOCK(unp);
3684820bf6aSMark Johnston 	if (unp != unp2)
3694820bf6aSMark Johnston 		UNP_PCB_UNLOCK(unp2);
3704820bf6aSMark Johnston }
3714820bf6aSMark Johnston 
372ccdadf1aSMark Johnston /*
373ccdadf1aSMark Johnston  * Try to lock the connected peer of an already locked socket.  In some cases
374ccdadf1aSMark Johnston  * this requires that we unlock the current socket.  The pairbusy counter is
375ccdadf1aSMark Johnston  * used to block concurrent connection attempts while the lock is dropped.  The
376ccdadf1aSMark Johnston  * caller must be careful to revalidate PCB state.
377ccdadf1aSMark Johnston  */
378ccdadf1aSMark Johnston static struct unpcb *
379ccdadf1aSMark Johnston unp_pcb_lock_peer(struct unpcb *unp)
38075a67bf3SMatt Macy {
38175a67bf3SMatt Macy 	struct unpcb *unp2;
38275a67bf3SMatt Macy 
383ccdadf1aSMark Johnston 	UNP_PCB_LOCK_ASSERT(unp);
384ccdadf1aSMark Johnston 	unp2 = unp->unp_conn;
3856404d7ffSMateusz Guzik 	if (unp2 == NULL)
386ccdadf1aSMark Johnston 		return (NULL);
387ccdadf1aSMark Johnston 	if (__predict_false(unp == unp2))
388ccdadf1aSMark Johnston 		return (unp);
389ccdadf1aSMark Johnston 
390ccdadf1aSMark Johnston 	UNP_PCB_UNLOCK_ASSERT(unp2);
391ccdadf1aSMark Johnston 
392ccdadf1aSMark Johnston 	if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
393ccdadf1aSMark Johnston 		return (unp2);
394ccdadf1aSMark Johnston 	if ((uintptr_t)unp2 > (uintptr_t)unp) {
395ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp2);
396ccdadf1aSMark Johnston 		return (unp2);
397ccdadf1aSMark Johnston 	}
398ccdadf1aSMark Johnston 	unp->unp_pairbusy++;
399e62ca80bSMark Johnston 	unp_pcb_hold(unp2);
400e62ca80bSMark Johnston 	UNP_PCB_UNLOCK(unp);
401ccdadf1aSMark Johnston 
402e62ca80bSMark Johnston 	UNP_PCB_LOCK(unp2);
403e62ca80bSMark Johnston 	UNP_PCB_LOCK(unp);
404ccdadf1aSMark Johnston 	KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
405ccdadf1aSMark Johnston 	    ("%s: socket %p was reconnected", __func__, unp));
406ccdadf1aSMark Johnston 	if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
407ccdadf1aSMark Johnston 		unp->unp_flags &= ~UNP_WAITING;
408ccdadf1aSMark Johnston 		wakeup(unp);
40975a67bf3SMatt Macy 	}
410ccdadf1aSMark Johnston 	if (unp_pcb_rele(unp2)) {
411ccdadf1aSMark Johnston 		/* unp2 is unlocked. */
412ccdadf1aSMark Johnston 		return (NULL);
413ccdadf1aSMark Johnston 	}
414ccdadf1aSMark Johnston 	if (unp->unp_conn == NULL) {
415ccdadf1aSMark Johnston 		UNP_PCB_UNLOCK(unp2);
416ccdadf1aSMark Johnston 		return (NULL);
417ccdadf1aSMark Johnston 	}
418ccdadf1aSMark Johnston 	return (unp2);
419ccdadf1aSMark Johnston }
42075a67bf3SMatt Macy 
421e4445a03SRobert Watson /*
422e4445a03SRobert Watson  * Definitions of protocols supported in the LOCAL domain.
423e4445a03SRobert Watson  */
424e4445a03SRobert Watson static struct domain localdomain;
425fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
42684d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket;
427e4445a03SRobert Watson static struct protosw localsw[] = {
428e4445a03SRobert Watson {
429e4445a03SRobert Watson 	.pr_type =		SOCK_STREAM,
430e4445a03SRobert Watson 	.pr_domain =		&localdomain,
43127457983SMark Johnston 	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|
43227457983SMark Johnston 				    PR_CAPATTACH,
433e4445a03SRobert Watson 	.pr_ctloutput =		&uipc_ctloutput,
434fa9402f2SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_stream
435e4445a03SRobert Watson },
436e4445a03SRobert Watson {
437e4445a03SRobert Watson 	.pr_type =		SOCK_DGRAM,
438e4445a03SRobert Watson 	.pr_domain =		&localdomain,
43927457983SMark Johnston 	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS|PR_CAPATTACH,
440aaf63435SGleb Smirnoff 	.pr_ctloutput =		&uipc_ctloutput,
441fa9402f2SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_dgram
442e4445a03SRobert Watson },
44384d61770SRobert Watson {
44484d61770SRobert Watson 	.pr_type =		SOCK_SEQPACKET,
44584d61770SRobert Watson 	.pr_domain =		&localdomain,
44684d61770SRobert Watson 
44784d61770SRobert Watson 	/*
44884d61770SRobert Watson 	 * XXXRW: For now, PR_ADDR because soreceive will bump into them
44984d61770SRobert Watson 	 * due to our use of sbappendaddr.  A new sbappend variants is needed
45084d61770SRobert Watson 	 * that supports both atomic record writes and control data.
45184d61770SRobert Watson 	 */
45227457983SMark Johnston 	.pr_flags =		PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|
45327457983SMark Johnston 				    PR_WANTRCVD|PR_RIGHTS|PR_CAPATTACH,
454e0643280SGleb Smirnoff 	.pr_ctloutput =		&uipc_ctloutput,
45584d61770SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_seqpacket,
45684d61770SRobert Watson },
457e4445a03SRobert Watson };
458e4445a03SRobert Watson 
459e4445a03SRobert Watson static struct domain localdomain = {
460e4445a03SRobert Watson 	.dom_family =		AF_LOCAL,
461e4445a03SRobert Watson 	.dom_name =		"local",
462e4445a03SRobert Watson 	.dom_init =		unp_init,
463e4445a03SRobert Watson 	.dom_externalize =	unp_externalize,
46499ab95dbSMark Johnston 	.dom_dispose =		unp_dispose,
465e4445a03SRobert Watson 	.dom_protosw =		localsw,
46602abd400SPedro F. Giffuni 	.dom_protoswNPROTOSW =	&localsw[nitems(localsw)]
467e4445a03SRobert Watson };
468e4445a03SRobert Watson DOMAIN_SET(local);
469e4445a03SRobert Watson 
470ac45e92fSRobert Watson static void
471a29f300eSGarrett Wollman uipc_abort(struct socket *so)
472df8bae1dSRodney W. Grimes {
473e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
474df8bae1dSRodney W. Grimes 
47540f2ac28SRobert Watson 	unp = sotounpcb(so);
4764d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
47775a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
478e7c33e29SRobert Watson 
479e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
480e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
481e7c33e29SRobert Watson 	if (unp2 != NULL) {
48275a67bf3SMatt Macy 		unp_pcb_hold(unp2);
483e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
48475a67bf3SMatt Macy 		unp_drop(unp2);
48575a67bf3SMatt Macy 	} else
48675a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
487df8bae1dSRodney W. Grimes }
488df8bae1dSRodney W. Grimes 
489a29f300eSGarrett Wollman static int
49057bf258eSGarrett Wollman uipc_accept(struct socket *so, struct sockaddr **nam)
491a29f300eSGarrett Wollman {
492e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
4930d9ce3a1SRobert Watson 	const struct sockaddr *sa;
494df8bae1dSRodney W. Grimes 
495df8bae1dSRodney W. Grimes 	/*
4961c381b19SRobert Watson 	 * Pass back name of connected socket, if it was bound and we are
4971c381b19SRobert Watson 	 * still connected (our peer may have closed already!).
498df8bae1dSRodney W. Grimes 	 */
4994d4b555eSRobert Watson 	unp = sotounpcb(so);
5004d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
501e7c33e29SRobert Watson 
5020d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
50344800027SMark Johnston 	UNP_PCB_LOCK(unp);
50444800027SMark Johnston 	unp2 = unp_pcb_lock_peer(unp);
50544800027SMark Johnston 	if (unp2 != NULL && unp2->unp_addr != NULL)
506e7c33e29SRobert Watson 		sa = (struct sockaddr *)unp2->unp_addr;
50744800027SMark Johnston 	else
5080d9ce3a1SRobert Watson 		sa = &sun_noname;
5090d9ce3a1SRobert Watson 	bcopy(sa, *nam, sa->sa_len);
510b4e07e3dSMark Johnston 	if (unp2 != NULL)
51144800027SMark Johnston 		unp_pcb_unlock_pair(unp, unp2);
512b4e07e3dSMark Johnston 	else
513b4e07e3dSMark Johnston 		UNP_PCB_UNLOCK(unp);
514e5aeaa0cSDag-Erling Smørgrav 	return (0);
515a29f300eSGarrett Wollman }
516df8bae1dSRodney W. Grimes 
517a29f300eSGarrett Wollman static int
518b40ce416SJulian Elischer uipc_attach(struct socket *so, int proto, struct thread *td)
519a29f300eSGarrett Wollman {
520e7c33e29SRobert Watson 	u_long sendspace, recvspace;
5216d32873cSRobert Watson 	struct unpcb *unp;
5223dab55bcSRobert Watson 	int error;
523779f106aSGleb Smirnoff 	bool locked;
524df8bae1dSRodney W. Grimes 
5256d32873cSRobert Watson 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
5266d32873cSRobert Watson 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
5276d32873cSRobert Watson 		switch (so->so_type) {
5286d32873cSRobert Watson 		case SOCK_STREAM:
529e7c33e29SRobert Watson 			sendspace = unpst_sendspace;
530e7c33e29SRobert Watson 			recvspace = unpst_recvspace;
5316d32873cSRobert Watson 			break;
5326d32873cSRobert Watson 
5336d32873cSRobert Watson 		case SOCK_DGRAM:
534e7c33e29SRobert Watson 			sendspace = unpdg_sendspace;
535e7c33e29SRobert Watson 			recvspace = unpdg_recvspace;
5366d32873cSRobert Watson 			break;
5376d32873cSRobert Watson 
53884d61770SRobert Watson 		case SOCK_SEQPACKET:
53984d61770SRobert Watson 			sendspace = unpsp_sendspace;
54084d61770SRobert Watson 			recvspace = unpsp_recvspace;
54184d61770SRobert Watson 			break;
54284d61770SRobert Watson 
5436d32873cSRobert Watson 		default:
544e7c33e29SRobert Watson 			panic("uipc_attach");
5456d32873cSRobert Watson 		}
546e7c33e29SRobert Watson 		error = soreserve(so, sendspace, recvspace);
5476d32873cSRobert Watson 		if (error)
5486d32873cSRobert Watson 			return (error);
5496d32873cSRobert Watson 	}
55046a1d9bfSRobert Watson 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
5516d32873cSRobert Watson 	if (unp == NULL)
5526d32873cSRobert Watson 		return (ENOBUFS);
5536d32873cSRobert Watson 	LIST_INIT(&unp->unp_refs);
554e7c33e29SRobert Watson 	UNP_PCB_LOCK_INIT(unp);
5556d32873cSRobert Watson 	unp->unp_socket = so;
5566d32873cSRobert Watson 	so->so_pcb = unp;
5575362170dSMark Johnston 	refcount_init(&unp->unp_refcount, 1);
558e7c33e29SRobert Watson 
559779f106aSGleb Smirnoff 	if ((locked = UNP_LINK_WOWNED()) == false)
560779f106aSGleb Smirnoff 		UNP_LINK_WLOCK();
561779f106aSGleb Smirnoff 
5626d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
563f218ac50SMateusz Guzik 	unp->unp_ino = ++unp_ino;
5646d32873cSRobert Watson 	unp_count++;
56584d61770SRobert Watson 	switch (so->so_type) {
56684d61770SRobert Watson 	case SOCK_STREAM:
56784d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
56884d61770SRobert Watson 		break;
56984d61770SRobert Watson 
57084d61770SRobert Watson 	case SOCK_DGRAM:
57184d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
57284d61770SRobert Watson 		break;
57384d61770SRobert Watson 
57484d61770SRobert Watson 	case SOCK_SEQPACKET:
57584d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
57684d61770SRobert Watson 		break;
57784d61770SRobert Watson 
57884d61770SRobert Watson 	default:
57984d61770SRobert Watson 		panic("uipc_attach");
58084d61770SRobert Watson 	}
581779f106aSGleb Smirnoff 
582779f106aSGleb Smirnoff 	if (locked == false)
583779f106aSGleb Smirnoff 		UNP_LINK_WUNLOCK();
5846d32873cSRobert Watson 
5856d32873cSRobert Watson 	return (0);
586a29f300eSGarrett Wollman }
587a29f300eSGarrett Wollman 
588a29f300eSGarrett Wollman static int
5897493f24eSPawel Jakub Dawidek uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
590a29f300eSGarrett Wollman {
591dd47f5caSRobert Watson 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
592dd47f5caSRobert Watson 	struct vattr vattr;
5935050aa86SKonstantin Belousov 	int error, namelen;
594dd47f5caSRobert Watson 	struct nameidata nd;
59540f2ac28SRobert Watson 	struct unpcb *unp;
596dd47f5caSRobert Watson 	struct vnode *vp;
597dd47f5caSRobert Watson 	struct mount *mp;
5987008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
599dd47f5caSRobert Watson 	char *buf;
600a29f300eSGarrett Wollman 
601cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
602cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
603cb7df69bSKevin Lo 
60440f2ac28SRobert Watson 	unp = sotounpcb(so);
6054d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
6064f1f0ef5SRobert Watson 
607a06534c3SBjoern A. Zeeb 	if (soun->sun_len > sizeof(struct sockaddr_un))
608a06534c3SBjoern A. Zeeb 		return (EINVAL);
6094f1f0ef5SRobert Watson 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
6104f1f0ef5SRobert Watson 	if (namelen <= 0)
6114f1f0ef5SRobert Watson 		return (EINVAL);
612dd47f5caSRobert Watson 
613dd47f5caSRobert Watson 	/*
6144f1f0ef5SRobert Watson 	 * We don't allow simultaneous bind() calls on a single UNIX domain
6154f1f0ef5SRobert Watson 	 * socket, so flag in-progress operations, and return an error if an
6164f1f0ef5SRobert Watson 	 * operation is already in progress.
6174f1f0ef5SRobert Watson 	 *
6184f1f0ef5SRobert Watson 	 * Historically, we have not allowed a socket to be rebound, so this
619d7924b70SRobert Watson 	 * also returns an error.  Not allowing re-binding simplifies the
620d7924b70SRobert Watson 	 * implementation and avoids a great many possible failure modes.
621dd47f5caSRobert Watson 	 */
622e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
623dd47f5caSRobert Watson 	if (unp->unp_vnode != NULL) {
624e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
625dd47f5caSRobert Watson 		return (EINVAL);
626dd47f5caSRobert Watson 	}
6274f1f0ef5SRobert Watson 	if (unp->unp_flags & UNP_BINDING) {
628e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
6294f1f0ef5SRobert Watson 		return (EALREADY);
630dd47f5caSRobert Watson 	}
6314f1f0ef5SRobert Watson 	unp->unp_flags |= UNP_BINDING;
632e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
633dd47f5caSRobert Watson 
634dd47f5caSRobert Watson 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
6357928893dSEd Maste 	bcopy(soun->sun_path, buf, namelen);
6367928893dSEd Maste 	buf[namelen] = 0;
637dd47f5caSRobert Watson 
638dd47f5caSRobert Watson restart:
6396c21f6edSKonstantin Belousov 	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
6406b3a9a0fSMateusz Guzik 	    UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT),
6416b3a9a0fSMateusz Guzik 	    td);
642dd47f5caSRobert Watson /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
643dd47f5caSRobert Watson 	error = namei(&nd);
644dd47f5caSRobert Watson 	if (error)
6454f1f0ef5SRobert Watson 		goto error;
646dd47f5caSRobert Watson 	vp = nd.ni_vp;
647dd47f5caSRobert Watson 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
648dd47f5caSRobert Watson 		NDFREE(&nd, NDF_ONLY_PNBUF);
649dd47f5caSRobert Watson 		if (nd.ni_dvp == vp)
650dd47f5caSRobert Watson 			vrele(nd.ni_dvp);
651dd47f5caSRobert Watson 		else
652dd47f5caSRobert Watson 			vput(nd.ni_dvp);
653dd47f5caSRobert Watson 		if (vp != NULL) {
654dd47f5caSRobert Watson 			vrele(vp);
655dd47f5caSRobert Watson 			error = EADDRINUSE;
6564f1f0ef5SRobert Watson 			goto error;
657dd47f5caSRobert Watson 		}
658dd47f5caSRobert Watson 		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
659dd47f5caSRobert Watson 		if (error)
6604f1f0ef5SRobert Watson 			goto error;
661dd47f5caSRobert Watson 		goto restart;
662dd47f5caSRobert Watson 	}
663dd47f5caSRobert Watson 	VATTR_NULL(&vattr);
664dd47f5caSRobert Watson 	vattr.va_type = VSOCK;
66585078b85SConrad Meyer 	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
666dd47f5caSRobert Watson #ifdef MAC
66730d239bcSRobert Watson 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
668dd47f5caSRobert Watson 	    &vattr);
669dd47f5caSRobert Watson #endif
670885868cdSRobert Watson 	if (error == 0)
671dd47f5caSRobert Watson 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
672dd47f5caSRobert Watson 	NDFREE(&nd, NDF_ONLY_PNBUF);
673dd47f5caSRobert Watson 	if (error) {
6743b2aa360SKonstantin Belousov 		VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
675dd47f5caSRobert Watson 		vn_finished_write(mp);
676441eb16aSKonstantin Belousov 		if (error == ERELOOKUP)
677441eb16aSKonstantin Belousov 			goto restart;
6784f1f0ef5SRobert Watson 		goto error;
679dd47f5caSRobert Watson 	}
680dd47f5caSRobert Watson 	vp = nd.ni_vp;
68157fd3d55SPawel Jakub Dawidek 	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
682dd47f5caSRobert Watson 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
683e7c33e29SRobert Watson 
684e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6850c3c207fSGleb Smirnoff 	VOP_UNP_BIND(vp, unp);
686dd47f5caSRobert Watson 	unp->unp_vnode = vp;
687dd47f5caSRobert Watson 	unp->unp_addr = soun;
6884f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
689e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
6903b2aa360SKonstantin Belousov 	vref(vp);
6913b2aa360SKonstantin Belousov 	VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
692dd47f5caSRobert Watson 	vn_finished_write(mp);
6934f1f0ef5SRobert Watson 	free(buf, M_TEMP);
6944f1f0ef5SRobert Watson 	return (0);
695e7c33e29SRobert Watson 
6964f1f0ef5SRobert Watson error:
697e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6984f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
699e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
700dd47f5caSRobert Watson 	free(buf, M_TEMP);
70140f2ac28SRobert Watson 	return (error);
702a29f300eSGarrett Wollman }
703a29f300eSGarrett Wollman 
704a29f300eSGarrett Wollman static int
7057493f24eSPawel Jakub Dawidek uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
7067493f24eSPawel Jakub Dawidek {
7077493f24eSPawel Jakub Dawidek 
7087493f24eSPawel Jakub Dawidek 	return (uipc_bindat(AT_FDCWD, so, nam, td));
7097493f24eSPawel Jakub Dawidek }
7107493f24eSPawel Jakub Dawidek 
7117493f24eSPawel Jakub Dawidek static int
712b40ce416SJulian Elischer uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
713a29f300eSGarrett Wollman {
7140d9ce3a1SRobert Watson 	int error;
715a29f300eSGarrett Wollman 
716fd179ee9SRobert Watson 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
717fd179ee9SRobert Watson 	error = unp_connect(so, nam, td);
7180d9ce3a1SRobert Watson 	return (error);
719a29f300eSGarrett Wollman }
720a29f300eSGarrett Wollman 
7217493f24eSPawel Jakub Dawidek static int
7227493f24eSPawel Jakub Dawidek uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
7237493f24eSPawel Jakub Dawidek     struct thread *td)
7247493f24eSPawel Jakub Dawidek {
7257493f24eSPawel Jakub Dawidek 	int error;
7267493f24eSPawel Jakub Dawidek 
7277493f24eSPawel Jakub Dawidek 	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
7287493f24eSPawel Jakub Dawidek 	error = unp_connectat(fd, so, nam, td);
7297493f24eSPawel Jakub Dawidek 	return (error);
7307493f24eSPawel Jakub Dawidek }
7317493f24eSPawel Jakub Dawidek 
732a152f8a3SRobert Watson static void
733a152f8a3SRobert Watson uipc_close(struct socket *so)
734a152f8a3SRobert Watson {
735e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
736779f106aSGleb Smirnoff 	struct vnode *vp = NULL;
73775a67bf3SMatt Macy 	struct mtx *vplock;
738ccdadf1aSMark Johnston 
739a152f8a3SRobert Watson 	unp = sotounpcb(so);
740a152f8a3SRobert Watson 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
741e7c33e29SRobert Watson 
74275a67bf3SMatt Macy 	vplock = NULL;
74375a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
74475a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
74575a67bf3SMatt Macy 		mtx_lock(vplock);
746e7c33e29SRobert Watson 	}
74775a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
74875a67bf3SMatt Macy 	if (vp && unp->unp_vnode == NULL) {
74975a67bf3SMatt Macy 		mtx_unlock(vplock);
75075a67bf3SMatt Macy 		vp = NULL;
75175a67bf3SMatt Macy 	}
75275a67bf3SMatt Macy 	if (vp != NULL) {
753779f106aSGleb Smirnoff 		VOP_UNP_DETACH(vp);
754779f106aSGleb Smirnoff 		unp->unp_vnode = NULL;
755779f106aSGleb Smirnoff 	}
756ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
757acf9fd05SMatt Macy 		unp_disconnect(unp, unp2);
758ccdadf1aSMark Johnston 	else
759e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
76075a67bf3SMatt Macy 	if (vp) {
76175a67bf3SMatt Macy 		mtx_unlock(vplock);
762779f106aSGleb Smirnoff 		vrele(vp);
763a152f8a3SRobert Watson 	}
76475a67bf3SMatt Macy }
765a152f8a3SRobert Watson 
7662c899584SRobert Watson static int
767a29f300eSGarrett Wollman uipc_connect2(struct socket *so1, struct socket *so2)
768a29f300eSGarrett Wollman {
769e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
7700d9ce3a1SRobert Watson 	int error;
771a29f300eSGarrett Wollman 
772e7c33e29SRobert Watson 	unp = so1->so_pcb;
7734d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
774e7c33e29SRobert Watson 	unp2 = so2->so_pcb;
775e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
7764820bf6aSMark Johnston 	unp_pcb_lock_pair(unp, unp2);
7776a2989fdSMatthew N. Dodd 	error = unp_connect2(so1, so2, PRU_CONNECT2);
7784820bf6aSMark Johnston 	unp_pcb_unlock_pair(unp, unp2);
7790d9ce3a1SRobert Watson 	return (error);
780a29f300eSGarrett Wollman }
781a29f300eSGarrett Wollman 
782bc725eafSRobert Watson static void
783a29f300eSGarrett Wollman uipc_detach(struct socket *so)
784a29f300eSGarrett Wollman {
785e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
78675a67bf3SMatt Macy 	struct mtx *vplock;
7876d32873cSRobert Watson 	struct vnode *vp;
788ccdadf1aSMark Johnston 	int local_unp_rights;
789a29f300eSGarrett Wollman 
79040f2ac28SRobert Watson 	unp = sotounpcb(so);
7914d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
792e7c33e29SRobert Watson 
793434ac8b6SMark Johnston 	vp = NULL;
794c0874c34SMatt Macy 	vplock = NULL;
795434ac8b6SMark Johnston 
796a50b1900SMark Johnston 	SOCK_LOCK(so);
797a50b1900SMark Johnston 	if (!SOLISTENING(so)) {
798a50b1900SMark Johnston 		/*
799a50b1900SMark Johnston 		 * Once the socket is removed from the global lists,
800a50b1900SMark Johnston 		 * uipc_ready() will not be able to locate its socket buffer, so
801a50b1900SMark Johnston 		 * clear the buffer now.  At this point internalized rights have
802a50b1900SMark Johnston 		 * already been disposed of.
803a50b1900SMark Johnston 		 */
804a50b1900SMark Johnston 		sbrelease(&so->so_rcv, so);
805a50b1900SMark Johnston 	}
806a50b1900SMark Johnston 	SOCK_UNLOCK(so);
807a50b1900SMark Johnston 
808779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
8096d32873cSRobert Watson 	LIST_REMOVE(unp, unp_link);
810a9aa06f7SJason A. Harmening 	if (unp->unp_gcflag & UNPGC_DEAD)
811a9aa06f7SJason A. Harmening 		LIST_REMOVE(unp, unp_dead);
8126d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
8136d32873cSRobert Watson 	--unp_count;
81475a67bf3SMatt Macy 	UNP_LINK_WUNLOCK();
815434ac8b6SMark Johnston 
81675a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
81775a67bf3SMatt Macy  restart:
81875a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
81975a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
82075a67bf3SMatt Macy 		mtx_lock(vplock);
82175a67bf3SMatt Macy 	}
82275a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
823db38b699SMark Johnston 	if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
824c0874c34SMatt Macy 		if (vplock)
82575a67bf3SMatt Macy 			mtx_unlock(vplock);
82675a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
82775a67bf3SMatt Macy 		goto restart;
82875a67bf3SMatt Macy 	}
8296d32873cSRobert Watson 	if ((vp = unp->unp_vnode) != NULL) {
830c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
8316d32873cSRobert Watson 		unp->unp_vnode = NULL;
8326d32873cSRobert Watson 	}
833ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
834e7c33e29SRobert Watson 		unp_disconnect(unp, unp2);
835f0317f86SMark Johnston 	else
83675a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
837ccdadf1aSMark Johnston 
83875a67bf3SMatt Macy 	UNP_REF_LIST_LOCK();
8396d32873cSRobert Watson 	while (!LIST_EMPTY(&unp->unp_refs)) {
8406d32873cSRobert Watson 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
841e7c33e29SRobert Watson 
84275a67bf3SMatt Macy 		unp_pcb_hold(ref);
84375a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
84475a67bf3SMatt Macy 
84575a67bf3SMatt Macy 		MPASS(ref != unp);
84675a67bf3SMatt Macy 		UNP_PCB_UNLOCK_ASSERT(ref);
847afc055d9SEd Schouten 		unp_drop(ref);
84875a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
8496d32873cSRobert Watson 	}
85075a67bf3SMatt Macy 	UNP_REF_LIST_UNLOCK();
851ccdadf1aSMark Johnston 
85275a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
853397c19d1SJeff Roberson 	local_unp_rights = unp_rights;
8546d32873cSRobert Watson 	unp->unp_socket->so_pcb = NULL;
85575a67bf3SMatt Macy 	unp->unp_socket = NULL;
856db38b699SMark Johnston 	free(unp->unp_addr, M_SONAME);
857db38b699SMark Johnston 	unp->unp_addr = NULL;
858db38b699SMark Johnston 	if (!unp_pcb_rele(unp))
8596e2faa24SRobert Watson 		UNP_PCB_UNLOCK(unp);
86075a67bf3SMatt Macy 	if (vp) {
86175a67bf3SMatt Macy 		mtx_unlock(vplock);
8626d32873cSRobert Watson 		vrele(vp);
86375a67bf3SMatt Macy 	}
8646d32873cSRobert Watson 	if (local_unp_rights)
865daee0f0bSKonstantin Belousov 		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
866a29f300eSGarrett Wollman }
867a29f300eSGarrett Wollman 
868a29f300eSGarrett Wollman static int
869a29f300eSGarrett Wollman uipc_disconnect(struct socket *so)
870a29f300eSGarrett Wollman {
871e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
872a29f300eSGarrett Wollman 
87340f2ac28SRobert Watson 	unp = sotounpcb(so);
8744d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
875e7c33e29SRobert Watson 
876e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
877ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
87875a67bf3SMatt Macy 		unp_disconnect(unp, unp2);
879ccdadf1aSMark Johnston 	else
880ccdadf1aSMark Johnston 		UNP_PCB_UNLOCK(unp);
881e5aeaa0cSDag-Erling Smørgrav 	return (0);
882a29f300eSGarrett Wollman }
883a29f300eSGarrett Wollman 
884a29f300eSGarrett Wollman static int
885d374e81eSRobert Watson uipc_listen(struct socket *so, int backlog, struct thread *td)
886a29f300eSGarrett Wollman {
88740f2ac28SRobert Watson 	struct unpcb *unp;
8880d9ce3a1SRobert Watson 	int error;
889a29f300eSGarrett Wollman 
890beb4b312SGleb Smirnoff 	if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
891beb4b312SGleb Smirnoff 		return (EOPNOTSUPP);
892beb4b312SGleb Smirnoff 
893bd4a39ccSMark Johnston 	/*
894bd4a39ccSMark Johnston 	 * Synchronize with concurrent connection attempts.
895bd4a39ccSMark Johnston 	 */
896bd4a39ccSMark Johnston 	error = 0;
89740f2ac28SRobert Watson 	unp = sotounpcb(so);
898e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
899bd4a39ccSMark Johnston 	if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
900bd4a39ccSMark Johnston 		error = EINVAL;
901bd4a39ccSMark Johnston 	else if (unp->unp_vnode == NULL)
902bd4a39ccSMark Johnston 		error = EDESTADDRREQ;
903bd4a39ccSMark Johnston 	if (error != 0) {
904e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
90547a84387SEd Schouten 		return (error);
90640f2ac28SRobert Watson 	}
907e7c33e29SRobert Watson 
908e7c33e29SRobert Watson 	SOCK_LOCK(so);
909e7c33e29SRobert Watson 	error = solisten_proto_check(so);
910e7c33e29SRobert Watson 	if (error == 0) {
911c5afec6eSDmitry Chagin 		cru2xt(td, &unp->unp_peercred);
912e7c33e29SRobert Watson 		solisten_proto(so, backlog);
913e7c33e29SRobert Watson 	}
914e7c33e29SRobert Watson 	SOCK_UNLOCK(so);
915e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
9160d9ce3a1SRobert Watson 	return (error);
917a29f300eSGarrett Wollman }
918a29f300eSGarrett Wollman 
919a29f300eSGarrett Wollman static int
92057bf258eSGarrett Wollman uipc_peeraddr(struct socket *so, struct sockaddr **nam)
921a29f300eSGarrett Wollman {
922e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
9230d9ce3a1SRobert Watson 	const struct sockaddr *sa;
924a29f300eSGarrett Wollman 
9254d4b555eSRobert Watson 	unp = sotounpcb(so);
9264d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
927e7c33e29SRobert Watson 
9280d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
929afd9f91cSJohn Baldwin 	UNP_LINK_RLOCK();
930bdc5f6a3SHajimu UMEMOTO 	/*
931e7c33e29SRobert Watson 	 * XXX: It seems that this test always fails even when connection is
932e7c33e29SRobert Watson 	 * established.  So, this else clause is added as workaround to
933e7c33e29SRobert Watson 	 * return PF_LOCAL sockaddr.
934bdc5f6a3SHajimu UMEMOTO 	 */
935e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
936e7c33e29SRobert Watson 	if (unp2 != NULL) {
937e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp2);
938e7c33e29SRobert Watson 		if (unp2->unp_addr != NULL)
939afd9f91cSJohn Baldwin 			sa = (struct sockaddr *) unp2->unp_addr;
940e7c33e29SRobert Watson 		else
9410d9ce3a1SRobert Watson 			sa = &sun_noname;
9420d9ce3a1SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
943e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
944e7c33e29SRobert Watson 	} else {
945e7c33e29SRobert Watson 		sa = &sun_noname;
946e7c33e29SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
947e7c33e29SRobert Watson 	}
948afd9f91cSJohn Baldwin 	UNP_LINK_RUNLOCK();
949e5aeaa0cSDag-Erling Smørgrav 	return (0);
950a29f300eSGarrett Wollman }
951a29f300eSGarrett Wollman 
952a29f300eSGarrett Wollman static int
953a29f300eSGarrett Wollman uipc_rcvd(struct socket *so, int flags)
954a29f300eSGarrett Wollman {
955e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
956a29f300eSGarrett Wollman 	struct socket *so2;
957337cc6b6SRobert Watson 	u_int mbcnt, sbcc;
958a29f300eSGarrett Wollman 
95940f2ac28SRobert Watson 	unp = sotounpcb(so);
9602b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
9612b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
9622b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
963e7c33e29SRobert Watson 
964df8bae1dSRodney W. Grimes 	/*
965e7c33e29SRobert Watson 	 * Adjust backpressure on sender and wakeup any waiting to write.
966e7c33e29SRobert Watson 	 *
967d7924b70SRobert Watson 	 * The unp lock is acquired to maintain the validity of the unp_conn
968d7924b70SRobert Watson 	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
969d7924b70SRobert Watson 	 * static as long as we don't permit unp2 to disconnect from unp,
970d7924b70SRobert Watson 	 * which is prevented by the lock on unp.  We cache values from
971d7924b70SRobert Watson 	 * so_rcv to avoid holding the so_rcv lock over the entire
972d7924b70SRobert Watson 	 * transaction on the remote so_snd.
973df8bae1dSRodney W. Grimes 	 */
974337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so->so_rcv);
975337cc6b6SRobert Watson 	mbcnt = so->so_rcv.sb_mbcnt;
9762b21d0e8SGleb Smirnoff 	sbcc = sbavail(&so->so_rcv);
977337cc6b6SRobert Watson 	SOCKBUF_UNLOCK(&so->so_rcv);
978c2090e73SAlan Somers 	/*
979c2090e73SAlan Somers 	 * There is a benign race condition at this point.  If we're planning to
980c2090e73SAlan Somers 	 * clear SB_STOP, but uipc_send is called on the connected socket at
981c2090e73SAlan Somers 	 * this instant, it might add data to the sockbuf and set SB_STOP.  Then
982c2090e73SAlan Somers 	 * we would erroneously clear SB_STOP below, even though the sockbuf is
983c2090e73SAlan Somers 	 * full.  The race is benign because the only ill effect is to allow the
984c2090e73SAlan Somers 	 * sockbuf to exceed its size limit, and the size limits are not
985c2090e73SAlan Somers 	 * strictly guaranteed anyway.
986c2090e73SAlan Somers 	 */
987e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
988e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
989e7c33e29SRobert Watson 	if (unp2 == NULL) {
990e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
991e7c33e29SRobert Watson 		return (0);
992337cc6b6SRobert Watson 	}
993e7c33e29SRobert Watson 	so2 = unp2->unp_socket;
994337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so2->so_snd);
995c2090e73SAlan Somers 	if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
996c2090e73SAlan Somers 		so2->so_snd.sb_flags &= ~SB_STOP;
9971e4d7da7SRobert Watson 	sowwakeup_locked(so2);
998e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
999e5aeaa0cSDag-Erling Smørgrav 	return (0);
1000a29f300eSGarrett Wollman }
1001df8bae1dSRodney W. Grimes 
1002a29f300eSGarrett Wollman static int
100357bf258eSGarrett Wollman uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1004b40ce416SJulian Elischer     struct mbuf *control, struct thread *td)
1005a29f300eSGarrett Wollman {
1006f3f49bbbSRobert Watson 	struct unpcb *unp, *unp2;
1007a29f300eSGarrett Wollman 	struct socket *so2;
1008c2090e73SAlan Somers 	u_int mbcnt, sbcc;
100975a67bf3SMatt Macy 	int freed, error;
1010a29f300eSGarrett Wollman 
101140f2ac28SRobert Watson 	unp = sotounpcb(so);
10122b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
10132b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
10142b21d0e8SGleb Smirnoff 	    so->so_type == SOCK_SEQPACKET,
10152b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
1016e7c33e29SRobert Watson 
101775a67bf3SMatt Macy 	freed = error = 0;
1018a29f300eSGarrett Wollman 	if (flags & PRUS_OOB) {
1019a29f300eSGarrett Wollman 		error = EOPNOTSUPP;
1020a29f300eSGarrett Wollman 		goto release;
1021a29f300eSGarrett Wollman 	}
1022fc3fcacfSRobert Watson 	if (control != NULL && (error = unp_internalize(&control, td)))
1023a29f300eSGarrett Wollman 		goto release;
102475a67bf3SMatt Macy 
102575a67bf3SMatt Macy 	unp2 = NULL;
1026a29f300eSGarrett Wollman 	switch (so->so_type) {
1027a29f300eSGarrett Wollman 	case SOCK_DGRAM:
1028a29f300eSGarrett Wollman 	{
1029e7dd9a10SRobert Watson 		const struct sockaddr *from;
1030df8bae1dSRodney W. Grimes 
1031fc3fcacfSRobert Watson 		if (nam != NULL) {
1032ccdadf1aSMark Johnston 			error = unp_connect(so, nam, td);
1033ccdadf1aSMark Johnston 			if (error != 0)
1034df8bae1dSRodney W. Grimes 				break;
1035ccdadf1aSMark Johnston 		}
103675a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
103760a5ef26SRobert Watson 
1038b5ff0914SRobert Watson 		/*
1039b5ff0914SRobert Watson 		 * Because connect() and send() are non-atomic in a sendto()
1040b5ff0914SRobert Watson 		 * with a target address, it's possible that the socket will
1041b5ff0914SRobert Watson 		 * have disconnected before the send() can run.  In that case
1042b5ff0914SRobert Watson 		 * return the slightly counter-intuitive but otherwise
1043b5ff0914SRobert Watson 		 * correct error that the socket is not connected.
1044b5ff0914SRobert Watson 		 */
1045ccdadf1aSMark Johnston 		unp2 = unp_pcb_lock_peer(unp);
1046ccdadf1aSMark Johnston 		if (unp2 == NULL) {
104775a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
1048b5ff0914SRobert Watson 			error = ENOTCONN;
1049b5ff0914SRobert Watson 			break;
1050b5ff0914SRobert Watson 		}
1051ccdadf1aSMark Johnston 
10522de07e40SConrad Meyer 		if (unp2->unp_flags & UNP_WANTCRED_MASK)
1053ede4af47SConrad Meyer 			control = unp_addsockcred(td, control,
1054ede4af47SConrad Meyer 			    unp2->unp_flags);
1055fc3fcacfSRobert Watson 		if (unp->unp_addr != NULL)
105657bf258eSGarrett Wollman 			from = (struct sockaddr *)unp->unp_addr;
1057df8bae1dSRodney W. Grimes 		else
1058df8bae1dSRodney W. Grimes 			from = &sun_noname;
1059ede6e136SRobert Watson 		so2 = unp2->unp_socket;
1060a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
10616dde7ecbSPeter Wemm 		if (sbappendaddr_locked(&so2->so_rcv, from, m,
10628de34a88SAlan Somers 		    control)) {
10631e4d7da7SRobert Watson 			sorwakeup_locked(so2);
1064fc3fcacfSRobert Watson 			m = NULL;
1065fc3fcacfSRobert Watson 			control = NULL;
1066e5aeaa0cSDag-Erling Smørgrav 		} else {
10677045b160SRoy Marples 			soroverflow_locked(so2);
1068df8bae1dSRodney W. Grimes 			error = ENOBUFS;
1069e5aeaa0cSDag-Erling Smørgrav 		}
107075a67bf3SMatt Macy 		if (nam != NULL)
1071e7c33e29SRobert Watson 			unp_disconnect(unp, unp2);
1072f0317f86SMark Johnston 		else
1073f0317f86SMark Johnston 			unp_pcb_unlock_pair(unp, unp2);
1074df8bae1dSRodney W. Grimes 		break;
1075df8bae1dSRodney W. Grimes 	}
1076df8bae1dSRodney W. Grimes 
107784d61770SRobert Watson 	case SOCK_SEQPACKET:
1078df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
1079402cc72dSDavid Greenman 		if ((so->so_state & SS_ISCONNECTED) == 0) {
1080fc3fcacfSRobert Watson 			if (nam != NULL) {
1081ccdadf1aSMark Johnston 				error = unp_connect(so, nam, td);
1082b36871afSMark Johnston 				if (error != 0)
108375a67bf3SMatt Macy 					break;
1084402cc72dSDavid Greenman 			} else {
1085402cc72dSDavid Greenman 				error = ENOTCONN;
1086402cc72dSDavid Greenman 				break;
1087402cc72dSDavid Greenman 			}
1088b36871afSMark Johnston 		}
1089b36871afSMark Johnston 
1090ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp);
1091ccdadf1aSMark Johnston 		if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
109275a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
1093b5ff0914SRobert Watson 			error = ENOTCONN;
1094b5ff0914SRobert Watson 			break;
1095b36871afSMark Johnston 		} else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1096ccdadf1aSMark Johnston 			unp_pcb_unlock_pair(unp, unp2);
1097b36871afSMark Johnston 			error = EPIPE;
1098b36871afSMark Johnston 			break;
109975a67bf3SMatt Macy 		}
110075a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
110175a67bf3SMatt Macy 		if ((so2 = unp2->unp_socket) == NULL) {
110275a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp2);
110375a67bf3SMatt Macy 			error = ENOTCONN;
110475a67bf3SMatt Macy 			break;
110575a67bf3SMatt Macy 		}
1106a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
11072de07e40SConrad Meyer 		if (unp2->unp_flags & UNP_WANTCRED_MASK) {
11086a2989fdSMatthew N. Dodd 			/*
11092de07e40SConrad Meyer 			 * Credentials are passed only once on SOCK_STREAM and
11102de07e40SConrad Meyer 			 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
11112de07e40SConrad Meyer 			 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
11126a2989fdSMatthew N. Dodd 			 */
1113ede4af47SConrad Meyer 			control = unp_addsockcred(td, control, unp2->unp_flags);
11142de07e40SConrad Meyer 			unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
11156a2989fdSMatthew N. Dodd 		}
11165b0480f2SMark Johnston 
1117df8bae1dSRodney W. Grimes 		/*
11185b0480f2SMark Johnston 		 * Send to paired receive port and wake up readers.  Don't
11195b0480f2SMark Johnston 		 * check for space available in the receive buffer if we're
11205b0480f2SMark Johnston 		 * attaching ancillary data; Unix domain sockets only check
11215b0480f2SMark Johnston 		 * for space in the sending sockbuf, and that check is
11225b0480f2SMark Johnston 		 * performed one level up the stack.  At that level we cannot
11235b0480f2SMark Johnston 		 * precisely account for the amount of buffer space used
11245b0480f2SMark Johnston 		 * (e.g., because control messages are not yet internalized).
1125df8bae1dSRodney W. Grimes 		 */
112684d61770SRobert Watson 		switch (so->so_type) {
112784d61770SRobert Watson 		case SOCK_STREAM:
1128fc3fcacfSRobert Watson 			if (control != NULL) {
11295b0480f2SMark Johnston 				sbappendcontrol_locked(&so2->so_rcv, m,
113025f4ddfbSMark Johnston 				    control, flags);
1131fc3fcacfSRobert Watson 				control = NULL;
1132e7c33e29SRobert Watson 			} else
1133829fae90SGleb Smirnoff 				sbappend_locked(&so2->so_rcv, m, flags);
113484d61770SRobert Watson 			break;
113584d61770SRobert Watson 
1136b36871afSMark Johnston 		case SOCK_SEQPACKET:
11378de34a88SAlan Somers 			if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1138b36871afSMark Johnston 			    &sun_noname, m, control))
113984d61770SRobert Watson 				control = NULL;
114084d61770SRobert Watson 			break;
114184d61770SRobert Watson 		}
114284d61770SRobert Watson 
1143c2090e73SAlan Somers 		mbcnt = so2->so_rcv.sb_mbcnt;
11442b21d0e8SGleb Smirnoff 		sbcc = sbavail(&so2->so_rcv);
11452b21d0e8SGleb Smirnoff 		if (sbcc)
1146337cc6b6SRobert Watson 			sorwakeup_locked(so2);
11472b21d0e8SGleb Smirnoff 		else
11482b21d0e8SGleb Smirnoff 			SOCKBUF_UNLOCK(&so2->so_rcv);
1149337cc6b6SRobert Watson 
1150c2090e73SAlan Somers 		/*
1151c2090e73SAlan Somers 		 * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1152c2090e73SAlan Somers 		 * it would be possible for uipc_rcvd to be called at this
1153c2090e73SAlan Somers 		 * point, drain the receiving sockbuf, clear SB_STOP, and then
1154c2090e73SAlan Somers 		 * we would set SB_STOP below.  That could lead to an empty
1155c2090e73SAlan Somers 		 * sockbuf having SB_STOP set
1156c2090e73SAlan Somers 		 */
1157337cc6b6SRobert Watson 		SOCKBUF_LOCK(&so->so_snd);
1158c2090e73SAlan Somers 		if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1159c2090e73SAlan Somers 			so->so_snd.sb_flags |= SB_STOP;
11607abe2ac2SAlan Cox 		SOCKBUF_UNLOCK(&so->so_snd);
1161e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1162fc3fcacfSRobert Watson 		m = NULL;
1163df8bae1dSRodney W. Grimes 		break;
1164df8bae1dSRodney W. Grimes 	}
1165a29f300eSGarrett Wollman 
11666b8fda4dSGarrett Wollman 	/*
116760a5ef26SRobert Watson 	 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
11686b8fda4dSGarrett Wollman 	 */
1169a29f300eSGarrett Wollman 	if (flags & PRUS_EOF) {
1170ede6e136SRobert Watson 		UNP_PCB_LOCK(unp);
11716b8fda4dSGarrett Wollman 		socantsendmore(so);
11726b8fda4dSGarrett Wollman 		unp_shutdown(unp);
1173e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
1174ede6e136SRobert Watson 	}
1175fc3fcacfSRobert Watson 	if (control != NULL && error != 0)
117699ab95dbSMark Johnston 		unp_dispose_mbuf(control);
1177bd508d39SDon Lewis 
1178a29f300eSGarrett Wollman release:
1179fc3fcacfSRobert Watson 	if (control != NULL)
1180a29f300eSGarrett Wollman 		m_freem(control);
1181100db364SGleb Smirnoff 	/*
1182100db364SGleb Smirnoff 	 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1183100db364SGleb Smirnoff 	 * for freeing memory.
1184100db364SGleb Smirnoff 	 */
1185100db364SGleb Smirnoff 	if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1186a29f300eSGarrett Wollman 		m_freem(m);
1187e5aeaa0cSDag-Erling Smørgrav 	return (error);
1188a29f300eSGarrett Wollman }
1189df8bae1dSRodney W. Grimes 
1190a50b1900SMark Johnston static bool
1191a50b1900SMark Johnston uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1192a50b1900SMark Johnston {
1193a50b1900SMark Johnston 	struct mbuf *mb, *n;
1194a50b1900SMark Johnston 	struct sockbuf *sb;
1195a50b1900SMark Johnston 
1196a50b1900SMark Johnston 	SOCK_LOCK(so);
1197a50b1900SMark Johnston 	if (SOLISTENING(so)) {
1198a50b1900SMark Johnston 		SOCK_UNLOCK(so);
1199a50b1900SMark Johnston 		return (false);
1200a50b1900SMark Johnston 	}
1201a50b1900SMark Johnston 	mb = NULL;
1202a50b1900SMark Johnston 	sb = &so->so_rcv;
1203a50b1900SMark Johnston 	SOCKBUF_LOCK(sb);
1204a50b1900SMark Johnston 	if (sb->sb_fnrdy != NULL) {
1205a50b1900SMark Johnston 		for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1206a50b1900SMark Johnston 			if (mb == m) {
1207a50b1900SMark Johnston 				*errorp = sbready(sb, m, count);
1208a50b1900SMark Johnston 				break;
1209a50b1900SMark Johnston 			}
1210a50b1900SMark Johnston 			mb = mb->m_next;
1211a50b1900SMark Johnston 			if (mb == NULL) {
1212a50b1900SMark Johnston 				mb = n;
12131b778ba2SMark Johnston 				if (mb != NULL)
1214a50b1900SMark Johnston 					n = mb->m_nextpkt;
1215a50b1900SMark Johnston 			}
1216a50b1900SMark Johnston 		}
1217a50b1900SMark Johnston 	}
1218a50b1900SMark Johnston 	SOCKBUF_UNLOCK(sb);
1219a50b1900SMark Johnston 	SOCK_UNLOCK(so);
1220a50b1900SMark Johnston 	return (mb != NULL);
1221a50b1900SMark Johnston }
1222a50b1900SMark Johnston 
1223a29f300eSGarrett Wollman static int
1224c80ea19bSGleb Smirnoff uipc_ready(struct socket *so, struct mbuf *m, int count)
1225c80ea19bSGleb Smirnoff {
1226c80ea19bSGleb Smirnoff 	struct unpcb *unp, *unp2;
1227c80ea19bSGleb Smirnoff 	struct socket *so2;
1228a50b1900SMark Johnston 	int error, i;
1229c80ea19bSGleb Smirnoff 
1230c80ea19bSGleb Smirnoff 	unp = sotounpcb(so);
1231c80ea19bSGleb Smirnoff 
1232a50b1900SMark Johnston 	KASSERT(so->so_type == SOCK_STREAM,
1233a50b1900SMark Johnston 	    ("%s: unexpected socket type for %p", __func__, so));
1234a50b1900SMark Johnston 
1235a62b4665SMatt Macy 	UNP_PCB_LOCK(unp);
1236ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1237a62b4665SMatt Macy 		UNP_PCB_UNLOCK(unp);
1238c80ea19bSGleb Smirnoff 		so2 = unp2->unp_socket;
1239c80ea19bSGleb Smirnoff 		SOCKBUF_LOCK(&so2->so_rcv);
1240c80ea19bSGleb Smirnoff 		if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1241c80ea19bSGleb Smirnoff 			sorwakeup_locked(so2);
1242c80ea19bSGleb Smirnoff 		else
1243c80ea19bSGleb Smirnoff 			SOCKBUF_UNLOCK(&so2->so_rcv);
1244c80ea19bSGleb Smirnoff 		UNP_PCB_UNLOCK(unp2);
1245c80ea19bSGleb Smirnoff 		return (error);
1246ccdadf1aSMark Johnston 	}
1247ccdadf1aSMark Johnston 	UNP_PCB_UNLOCK(unp);
1248a50b1900SMark Johnston 
1249a50b1900SMark Johnston 	/*
1250a50b1900SMark Johnston 	 * The receiving socket has been disconnected, but may still be valid.
1251a50b1900SMark Johnston 	 * In this case, the now-ready mbufs are still present in its socket
1252a50b1900SMark Johnston 	 * buffer, so perform an exhaustive search before giving up and freeing
1253a50b1900SMark Johnston 	 * the mbufs.
1254a50b1900SMark Johnston 	 */
1255a50b1900SMark Johnston 	UNP_LINK_RLOCK();
1256a50b1900SMark Johnston 	LIST_FOREACH(unp, &unp_shead, unp_link) {
1257a50b1900SMark Johnston 		if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1258a50b1900SMark Johnston 			break;
1259a50b1900SMark Johnston 	}
1260a50b1900SMark Johnston 	UNP_LINK_RUNLOCK();
1261a50b1900SMark Johnston 
1262a50b1900SMark Johnston 	if (unp == NULL) {
1263a50b1900SMark Johnston 		for (i = 0; i < count; i++)
1264a62b4665SMatt Macy 			m = m_free(m);
1265a50b1900SMark Johnston 		error = ECONNRESET;
1266a50b1900SMark Johnston 	}
1267a50b1900SMark Johnston 	return (error);
1268c80ea19bSGleb Smirnoff }
1269c80ea19bSGleb Smirnoff 
1270c80ea19bSGleb Smirnoff static int
1271a29f300eSGarrett Wollman uipc_sense(struct socket *so, struct stat *sb)
1272a29f300eSGarrett Wollman {
1273c2090e73SAlan Somers 	struct unpcb *unp;
1274a29f300eSGarrett Wollman 
127540f2ac28SRobert Watson 	unp = sotounpcb(so);
12764d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1277e7c33e29SRobert Watson 
1278a29f300eSGarrett Wollman 	sb->st_blksize = so->so_snd.sb_hiwat;
1279f3732fd1SPoul-Henning Kamp 	sb->st_dev = NODEV;
1280a29f300eSGarrett Wollman 	sb->st_ino = unp->unp_ino;
1281df8bae1dSRodney W. Grimes 	return (0);
1282a29f300eSGarrett Wollman }
1283df8bae1dSRodney W. Grimes 
1284a29f300eSGarrett Wollman static int
1285a29f300eSGarrett Wollman uipc_shutdown(struct socket *so)
1286a29f300eSGarrett Wollman {
128740f2ac28SRobert Watson 	struct unpcb *unp;
1288df8bae1dSRodney W. Grimes 
128940f2ac28SRobert Watson 	unp = sotounpcb(so);
12904d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1291e7c33e29SRobert Watson 
1292e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1293a29f300eSGarrett Wollman 	socantsendmore(so);
1294a29f300eSGarrett Wollman 	unp_shutdown(unp);
1295e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1296e5aeaa0cSDag-Erling Smørgrav 	return (0);
1297a29f300eSGarrett Wollman }
1298df8bae1dSRodney W. Grimes 
1299a29f300eSGarrett Wollman static int
130057bf258eSGarrett Wollman uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1301a29f300eSGarrett Wollman {
130240f2ac28SRobert Watson 	struct unpcb *unp;
13030d9ce3a1SRobert Watson 	const struct sockaddr *sa;
1304a29f300eSGarrett Wollman 
13054d4b555eSRobert Watson 	unp = sotounpcb(so);
13064d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1307e7c33e29SRobert Watson 
13080d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1309e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1310fc3fcacfSRobert Watson 	if (unp->unp_addr != NULL)
13110d9ce3a1SRobert Watson 		sa = (struct sockaddr *) unp->unp_addr;
131283f3198bSThomas Moestl 	else
13130d9ce3a1SRobert Watson 		sa = &sun_noname;
13140d9ce3a1SRobert Watson 	bcopy(sa, *nam, sa->sa_len);
1315e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1316e5aeaa0cSDag-Erling Smørgrav 	return (0);
1317df8bae1dSRodney W. Grimes }
1318a29f300eSGarrett Wollman 
1319fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram = {
1320756d52a1SPoul-Henning Kamp 	.pru_abort = 		uipc_abort,
1321756d52a1SPoul-Henning Kamp 	.pru_accept =		uipc_accept,
1322756d52a1SPoul-Henning Kamp 	.pru_attach =		uipc_attach,
1323756d52a1SPoul-Henning Kamp 	.pru_bind =		uipc_bind,
13247493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1325756d52a1SPoul-Henning Kamp 	.pru_connect =		uipc_connect,
13267493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1327756d52a1SPoul-Henning Kamp 	.pru_connect2 =		uipc_connect2,
1328756d52a1SPoul-Henning Kamp 	.pru_detach =		uipc_detach,
1329756d52a1SPoul-Henning Kamp 	.pru_disconnect =	uipc_disconnect,
1330756d52a1SPoul-Henning Kamp 	.pru_listen =		uipc_listen,
1331756d52a1SPoul-Henning Kamp 	.pru_peeraddr =		uipc_peeraddr,
1332756d52a1SPoul-Henning Kamp 	.pru_rcvd =		uipc_rcvd,
1333756d52a1SPoul-Henning Kamp 	.pru_send =		uipc_send,
1334756d52a1SPoul-Henning Kamp 	.pru_sense =		uipc_sense,
1335756d52a1SPoul-Henning Kamp 	.pru_shutdown =		uipc_shutdown,
1336756d52a1SPoul-Henning Kamp 	.pru_sockaddr =		uipc_sockaddr,
1337fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_dgram,
1338fa9402f2SRobert Watson 	.pru_close =		uipc_close,
1339fa9402f2SRobert Watson };
1340fa9402f2SRobert Watson 
134184d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket = {
134284d61770SRobert Watson 	.pru_abort =		uipc_abort,
134384d61770SRobert Watson 	.pru_accept =		uipc_accept,
134484d61770SRobert Watson 	.pru_attach =		uipc_attach,
134584d61770SRobert Watson 	.pru_bind =		uipc_bind,
13467493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
134784d61770SRobert Watson 	.pru_connect =		uipc_connect,
13487493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
134984d61770SRobert Watson 	.pru_connect2 =		uipc_connect2,
135084d61770SRobert Watson 	.pru_detach =		uipc_detach,
135184d61770SRobert Watson 	.pru_disconnect =	uipc_disconnect,
135284d61770SRobert Watson 	.pru_listen =		uipc_listen,
135384d61770SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
135484d61770SRobert Watson 	.pru_rcvd =		uipc_rcvd,
135584d61770SRobert Watson 	.pru_send =		uipc_send,
135684d61770SRobert Watson 	.pru_sense =		uipc_sense,
135784d61770SRobert Watson 	.pru_shutdown =		uipc_shutdown,
135884d61770SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
135984d61770SRobert Watson 	.pru_soreceive =	soreceive_generic,	/* XXX: or...? */
136084d61770SRobert Watson 	.pru_close =		uipc_close,
136184d61770SRobert Watson };
136284d61770SRobert Watson 
1363fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_stream = {
1364fa9402f2SRobert Watson 	.pru_abort = 		uipc_abort,
1365fa9402f2SRobert Watson 	.pru_accept =		uipc_accept,
1366fa9402f2SRobert Watson 	.pru_attach =		uipc_attach,
1367fa9402f2SRobert Watson 	.pru_bind =		uipc_bind,
13687493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1369fa9402f2SRobert Watson 	.pru_connect =		uipc_connect,
13707493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1371fa9402f2SRobert Watson 	.pru_connect2 =		uipc_connect2,
1372fa9402f2SRobert Watson 	.pru_detach =		uipc_detach,
1373fa9402f2SRobert Watson 	.pru_disconnect =	uipc_disconnect,
1374fa9402f2SRobert Watson 	.pru_listen =		uipc_listen,
1375fa9402f2SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
1376fa9402f2SRobert Watson 	.pru_rcvd =		uipc_rcvd,
1377fa9402f2SRobert Watson 	.pru_send =		uipc_send,
1378c80ea19bSGleb Smirnoff 	.pru_ready =		uipc_ready,
1379fa9402f2SRobert Watson 	.pru_sense =		uipc_sense,
1380fa9402f2SRobert Watson 	.pru_shutdown =		uipc_shutdown,
1381fa9402f2SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
1382fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_generic,
1383a152f8a3SRobert Watson 	.pru_close =		uipc_close,
1384a29f300eSGarrett Wollman };
1385df8bae1dSRodney W. Grimes 
13860b36cd25SRobert Watson static int
1387892af6b9SRobert Watson uipc_ctloutput(struct socket *so, struct sockopt *sopt)
13880c1bb4fbSDima Dorfman {
138940f2ac28SRobert Watson 	struct unpcb *unp;
13900d9ce3a1SRobert Watson 	struct xucred xu;
13916a2989fdSMatthew N. Dodd 	int error, optval;
13926a2989fdSMatthew N. Dodd 
13936e0c8e1aSKonstantin Belousov 	if (sopt->sopt_level != SOL_LOCAL)
139496a041b5SMatthew N. Dodd 		return (EINVAL);
139596a041b5SMatthew N. Dodd 
13966a2989fdSMatthew N. Dodd 	unp = sotounpcb(so);
13974d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
13986a2989fdSMatthew N. Dodd 	error = 0;
13990c1bb4fbSDima Dorfman 	switch (sopt->sopt_dir) {
14000c1bb4fbSDima Dorfman 	case SOPT_GET:
14010c1bb4fbSDima Dorfman 		switch (sopt->sopt_name) {
14020c1bb4fbSDima Dorfman 		case LOCAL_PEERCRED:
1403e7c33e29SRobert Watson 			UNP_PCB_LOCK(unp);
14040c1bb4fbSDima Dorfman 			if (unp->unp_flags & UNP_HAVEPC)
14050d9ce3a1SRobert Watson 				xu = unp->unp_peercred;
14060c1bb4fbSDima Dorfman 			else {
14070c1bb4fbSDima Dorfman 				if (so->so_type == SOCK_STREAM)
14080c1bb4fbSDima Dorfman 					error = ENOTCONN;
14090c1bb4fbSDima Dorfman 				else
14100c1bb4fbSDima Dorfman 					error = EINVAL;
14110c1bb4fbSDima Dorfman 			}
1412e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
14130d9ce3a1SRobert Watson 			if (error == 0)
14140d9ce3a1SRobert Watson 				error = sooptcopyout(sopt, &xu, sizeof(xu));
14150c1bb4fbSDima Dorfman 			break;
1416e7c33e29SRobert Watson 
14176a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
1418a6357845SRobert Watson 			/* Unlocked read. */
14192de07e40SConrad Meyer 			optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
14202de07e40SConrad Meyer 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14212de07e40SConrad Meyer 			break;
14222de07e40SConrad Meyer 
14232de07e40SConrad Meyer 		case LOCAL_CREDS_PERSISTENT:
14242de07e40SConrad Meyer 			/* Unlocked read. */
14252de07e40SConrad Meyer 			optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
14266a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14276a2989fdSMatthew N. Dodd 			break;
1428e7c33e29SRobert Watson 
14296a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
1430a6357845SRobert Watson 			/* Unlocked read. */
14316a2989fdSMatthew N. Dodd 			optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
14326a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14336a2989fdSMatthew N. Dodd 			break;
1434e7c33e29SRobert Watson 
14350c1bb4fbSDima Dorfman 		default:
14360c1bb4fbSDima Dorfman 			error = EOPNOTSUPP;
14370c1bb4fbSDima Dorfman 			break;
14380c1bb4fbSDima Dorfman 		}
14390c1bb4fbSDima Dorfman 		break;
1440e7c33e29SRobert Watson 
14410c1bb4fbSDima Dorfman 	case SOPT_SET:
14426a2989fdSMatthew N. Dodd 		switch (sopt->sopt_name) {
14436a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
14442de07e40SConrad Meyer 		case LOCAL_CREDS_PERSISTENT:
14456a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
14466a2989fdSMatthew N. Dodd 			error = sooptcopyin(sopt, &optval, sizeof(optval),
14476a2989fdSMatthew N. Dodd 					    sizeof(optval));
14486a2989fdSMatthew N. Dodd 			if (error)
14496a2989fdSMatthew N. Dodd 				break;
14506a2989fdSMatthew N. Dodd 
14512de07e40SConrad Meyer #define	OPTSET(bit, exclusive) do {					\
1452e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);						\
14532de07e40SConrad Meyer 	if (optval) {							\
14542de07e40SConrad Meyer 		if ((unp->unp_flags & (exclusive)) != 0) {		\
14552de07e40SConrad Meyer 			UNP_PCB_UNLOCK(unp);				\
14562de07e40SConrad Meyer 			error = EINVAL;					\
14572de07e40SConrad Meyer 			break;						\
14582de07e40SConrad Meyer 		}							\
14592de07e40SConrad Meyer 		unp->unp_flags |= (bit);				\
14602de07e40SConrad Meyer 	} else								\
14612de07e40SConrad Meyer 		unp->unp_flags &= ~(bit);				\
1462e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);						\
1463e7c33e29SRobert Watson } while (0)
14646a2989fdSMatthew N. Dodd 
14656a2989fdSMatthew N. Dodd 			switch (sopt->sopt_name) {
14666a2989fdSMatthew N. Dodd 			case LOCAL_CREDS:
14672de07e40SConrad Meyer 				OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
14682de07e40SConrad Meyer 				break;
14692de07e40SConrad Meyer 
14702de07e40SConrad Meyer 			case LOCAL_CREDS_PERSISTENT:
14712de07e40SConrad Meyer 				OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
14726a2989fdSMatthew N. Dodd 				break;
1473e7c33e29SRobert Watson 
14746a2989fdSMatthew N. Dodd 			case LOCAL_CONNWAIT:
14752de07e40SConrad Meyer 				OPTSET(UNP_CONNWAIT, 0);
14766a2989fdSMatthew N. Dodd 				break;
1477e7c33e29SRobert Watson 
14786a2989fdSMatthew N. Dodd 			default:
14796a2989fdSMatthew N. Dodd 				break;
14806a2989fdSMatthew N. Dodd 			}
14816a2989fdSMatthew N. Dodd 			break;
14826a2989fdSMatthew N. Dodd #undef	OPTSET
14836a2989fdSMatthew N. Dodd 		default:
14846a2989fdSMatthew N. Dodd 			error = ENOPROTOOPT;
14856a2989fdSMatthew N. Dodd 			break;
14866a2989fdSMatthew N. Dodd 		}
1487abb886faSMatthew N. Dodd 		break;
1488e7c33e29SRobert Watson 
14890c1bb4fbSDima Dorfman 	default:
14900c1bb4fbSDima Dorfman 		error = EOPNOTSUPP;
14910c1bb4fbSDima Dorfman 		break;
14920c1bb4fbSDima Dorfman 	}
14930c1bb4fbSDima Dorfman 	return (error);
14940c1bb4fbSDima Dorfman }
14950c1bb4fbSDima Dorfman 
1496f708ef1bSPoul-Henning Kamp static int
1497892af6b9SRobert Watson unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1498df8bae1dSRodney W. Grimes {
14997493f24eSPawel Jakub Dawidek 
15007493f24eSPawel Jakub Dawidek 	return (unp_connectat(AT_FDCWD, so, nam, td));
15017493f24eSPawel Jakub Dawidek }
15027493f24eSPawel Jakub Dawidek 
15037493f24eSPawel Jakub Dawidek static int
15047493f24eSPawel Jakub Dawidek unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
15057493f24eSPawel Jakub Dawidek     struct thread *td)
15067493f24eSPawel Jakub Dawidek {
1507ed92e1c7SMark Johnston 	struct mtx *vplock;
1508ed92e1c7SMark Johnston 	struct sockaddr_un *soun;
1509892af6b9SRobert Watson 	struct vnode *vp;
1510779f106aSGleb Smirnoff 	struct socket *so2;
1511b295bdcdSRobert Watson 	struct unpcb *unp, *unp2, *unp3;
1512df8bae1dSRodney W. Grimes 	struct nameidata nd;
151357bf258eSGarrett Wollman 	char buf[SOCK_MAXADDRLEN];
15140d9ce3a1SRobert Watson 	struct sockaddr *sa;
15157008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
1516ccdadf1aSMark Johnston 	int error, len;
1517ed92e1c7SMark Johnston 	bool connreq;
15180d9ce3a1SRobert Watson 
1519cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
1520cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
1521a06534c3SBjoern A. Zeeb 	if (nam->sa_len > sizeof(struct sockaddr_un))
1522a06534c3SBjoern A. Zeeb 		return (EINVAL);
152357bf258eSGarrett Wollman 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
152457bf258eSGarrett Wollman 	if (len <= 0)
1525e5aeaa0cSDag-Erling Smørgrav 		return (EINVAL);
1526ed92e1c7SMark Johnston 	soun = (struct sockaddr_un *)nam;
15277928893dSEd Maste 	bcopy(soun->sun_path, buf, len);
15287928893dSEd Maste 	buf[len] = 0;
1529e7c33e29SRobert Watson 
1530bd4a39ccSMark Johnston 	error = 0;
153175a67bf3SMatt Macy 	unp = sotounpcb(so);
1532e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1533ccdadf1aSMark Johnston 	for (;;) {
1534ccdadf1aSMark Johnston 		/*
1535ccdadf1aSMark Johnston 		 * Wait for connection state to stabilize.  If a connection
1536ccdadf1aSMark Johnston 		 * already exists, give up.  For datagram sockets, which permit
1537ccdadf1aSMark Johnston 		 * multiple consecutive connect(2) calls, upper layers are
1538ccdadf1aSMark Johnston 		 * responsible for disconnecting in advance of a subsequent
1539ccdadf1aSMark Johnston 		 * connect(2), but this is not synchronized with PCB connection
1540ccdadf1aSMark Johnston 		 * state.
1541ccdadf1aSMark Johnston 		 *
1542ccdadf1aSMark Johnston 		 * Also make sure that no threads are currently attempting to
1543ccdadf1aSMark Johnston 		 * lock the peer socket, to ensure that unp_conn cannot
1544ccdadf1aSMark Johnston 		 * transition between two valid sockets while locks are dropped.
1545ccdadf1aSMark Johnston 		 */
1546bd4a39ccSMark Johnston 		if (SOLISTENING(so))
1547bd4a39ccSMark Johnston 			error = EOPNOTSUPP;
1548bd4a39ccSMark Johnston 		else if (unp->unp_conn != NULL)
1549bd4a39ccSMark Johnston 			error = EISCONN;
1550bd4a39ccSMark Johnston 		else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1551bd4a39ccSMark Johnston 			error = EALREADY;
1552ccdadf1aSMark Johnston 		}
1553bd4a39ccSMark Johnston 		if (error != 0) {
1554e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
1555bd4a39ccSMark Johnston 			return (error);
15564f1f0ef5SRobert Watson 		}
1557ccdadf1aSMark Johnston 		if (unp->unp_pairbusy > 0) {
1558ccdadf1aSMark Johnston 			unp->unp_flags |= UNP_WAITING;
1559ccdadf1aSMark Johnston 			mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1560ccdadf1aSMark Johnston 			continue;
1561ccdadf1aSMark Johnston 		}
1562ccdadf1aSMark Johnston 		break;
1563ccdadf1aSMark Johnston 	}
156405102f04SRobert Watson 	unp->unp_flags |= UNP_CONNECTING;
1565e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1566e7c33e29SRobert Watson 
1567ed92e1c7SMark Johnston 	connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1568ed92e1c7SMark Johnston 	if (connreq)
15690d9ce3a1SRobert Watson 		sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1570ed92e1c7SMark Johnston 	else
1571ed92e1c7SMark Johnston 		sa = NULL;
15727493f24eSPawel Jakub Dawidek 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
15736b3a9a0fSMateusz Guzik 	    UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT),
15746b3a9a0fSMateusz Guzik 	    td);
1575797f2d22SPoul-Henning Kamp 	error = namei(&nd);
1576797f2d22SPoul-Henning Kamp 	if (error)
15770d9ce3a1SRobert Watson 		vp = NULL;
15780d9ce3a1SRobert Watson 	else
1579df8bae1dSRodney W. Grimes 		vp = nd.ni_vp;
15800d9ce3a1SRobert Watson 	ASSERT_VOP_LOCKED(vp, "unp_connect");
1581cdb62ab7SMateusz Guzik 	NDFREE_NOTHING(&nd);
15820d9ce3a1SRobert Watson 	if (error)
15830d9ce3a1SRobert Watson 		goto bad;
15840d9ce3a1SRobert Watson 
1585df8bae1dSRodney W. Grimes 	if (vp->v_type != VSOCK) {
1586df8bae1dSRodney W. Grimes 		error = ENOTSOCK;
1587df8bae1dSRodney W. Grimes 		goto bad;
1588df8bae1dSRodney W. Grimes 	}
15896fac927cSRobert Watson #ifdef MAC
159030d239bcSRobert Watson 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
15916fac927cSRobert Watson 	if (error)
15926fac927cSRobert Watson 		goto bad;
15936fac927cSRobert Watson #endif
1594a854ed98SJohn Baldwin 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1595797f2d22SPoul-Henning Kamp 	if (error)
1596df8bae1dSRodney W. Grimes 		goto bad;
1597e7c33e29SRobert Watson 
1598b295bdcdSRobert Watson 	unp = sotounpcb(so);
15994d4b555eSRobert Watson 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1600e7c33e29SRobert Watson 
160175a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
160275a67bf3SMatt Macy 	mtx_lock(vplock);
16030c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp2);
16040c3c207fSGleb Smirnoff 	if (unp2 == NULL) {
1605df8bae1dSRodney W. Grimes 		error = ECONNREFUSED;
16062260c03dSRobert Watson 		goto bad2;
1607df8bae1dSRodney W. Grimes 	}
16080c3c207fSGleb Smirnoff 	so2 = unp2->unp_socket;
1609df8bae1dSRodney W. Grimes 	if (so->so_type != so2->so_type) {
1610df8bae1dSRodney W. Grimes 		error = EPROTOTYPE;
16112260c03dSRobert Watson 		goto bad2;
1612df8bae1dSRodney W. Grimes 	}
1613ed92e1c7SMark Johnston 	if (connreq) {
1614f4bb1869SMark Johnston 		if (SOLISTENING(so2)) {
16151fb51a12SBjoern A. Zeeb 			CURVNET_SET(so2->so_vnet);
1616779f106aSGleb Smirnoff 			so2 = sonewconn(so2, 0);
16171fb51a12SBjoern A. Zeeb 			CURVNET_RESTORE();
1618e7c33e29SRobert Watson 		} else
1619779f106aSGleb Smirnoff 			so2 = NULL;
1620779f106aSGleb Smirnoff 		if (so2 == NULL) {
1621df8bae1dSRodney W. Grimes 			error = ECONNREFUSED;
1622cb8f450bSMatt Macy 			goto bad2;
1623df8bae1dSRodney W. Grimes 		}
1624779f106aSGleb Smirnoff 		unp3 = sotounpcb(so2);
16254820bf6aSMark Johnston 		unp_pcb_lock_pair(unp2, unp3);
16260d9ce3a1SRobert Watson 		if (unp2->unp_addr != NULL) {
16270d9ce3a1SRobert Watson 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
16280d9ce3a1SRobert Watson 			unp3->unp_addr = (struct sockaddr_un *) sa;
16290d9ce3a1SRobert Watson 			sa = NULL;
16300d9ce3a1SRobert Watson 		}
1631b523ec24SRobert Watson 
1632da446550SAlan Somers 		unp_copy_peercred(td, unp3, unp, unp2);
1633b523ec24SRobert Watson 
1634e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1635779f106aSGleb Smirnoff 		unp2 = unp3;
1636ccdadf1aSMark Johnston 
1637ccdadf1aSMark Johnston 		/*
1638ccdadf1aSMark Johnston 		 * It is safe to block on the PCB lock here since unp2 is
1639ccdadf1aSMark Johnston 		 * nascent and cannot be connected to any other sockets.
1640ccdadf1aSMark Johnston 		 */
1641ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp);
1642335654d7SRobert Watson #ifdef MAC
1643779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so, so2);
1644779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so2, so);
1645335654d7SRobert Watson #endif
1646a3a73490SMatt Macy 	} else {
16474820bf6aSMark Johnston 		unp_pcb_lock_pair(unp, unp2);
1648a3a73490SMatt Macy 	}
1649779f106aSGleb Smirnoff 	KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1650779f106aSGleb Smirnoff 	    sotounpcb(so2) == unp2,
1651779f106aSGleb Smirnoff 	    ("%s: unp2 %p so2 %p", __func__, unp2, so2));
16526a2989fdSMatthew N. Dodd 	error = unp_connect2(so, so2, PRU_CONNECT);
16534820bf6aSMark Johnston 	unp_pcb_unlock_pair(unp, unp2);
16540d9ce3a1SRobert Watson bad2:
165575a67bf3SMatt Macy 	mtx_unlock(vplock);
1656df8bae1dSRodney W. Grimes bad:
165775a67bf3SMatt Macy 	if (vp != NULL) {
1658df8bae1dSRodney W. Grimes 		vput(vp);
165975a67bf3SMatt Macy 	}
16600d9ce3a1SRobert Watson 	free(sa, M_SONAME);
1661e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1662ccdadf1aSMark Johnston 	KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1663ccdadf1aSMark Johnston 	    ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
16644f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_CONNECTING;
1665e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1666df8bae1dSRodney W. Grimes 	return (error);
1667df8bae1dSRodney W. Grimes }
1668df8bae1dSRodney W. Grimes 
1669da446550SAlan Somers /*
1670da446550SAlan Somers  * Set socket peer credentials at connection time.
1671da446550SAlan Somers  *
1672da446550SAlan Somers  * The client's PCB credentials are copied from its process structure.  The
1673da446550SAlan Somers  * server's PCB credentials are copied from the socket on which it called
1674da446550SAlan Somers  * listen(2).  uipc_listen cached that process's credentials at the time.
1675da446550SAlan Somers  */
1676da446550SAlan Somers void
1677da446550SAlan Somers unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1678da446550SAlan Somers     struct unpcb *server_unp, struct unpcb *listen_unp)
1679da446550SAlan Somers {
1680c5afec6eSDmitry Chagin 	cru2xt(td, &client_unp->unp_peercred);
1681da446550SAlan Somers 	client_unp->unp_flags |= UNP_HAVEPC;
1682da446550SAlan Somers 
1683da446550SAlan Somers 	memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1684da446550SAlan Somers 	    sizeof(server_unp->unp_peercred));
1685da446550SAlan Somers 	server_unp->unp_flags |= UNP_HAVEPC;
16862de07e40SConrad Meyer 	client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
1687da446550SAlan Somers }
1688da446550SAlan Somers 
1689db48c0d2SRobert Watson static int
16906a2989fdSMatthew N. Dodd unp_connect2(struct socket *so, struct socket *so2, int req)
1691df8bae1dSRodney W. Grimes {
1692e7c33e29SRobert Watson 	struct unpcb *unp;
1693892af6b9SRobert Watson 	struct unpcb *unp2;
1694df8bae1dSRodney W. Grimes 
1695e7c33e29SRobert Watson 	unp = sotounpcb(so);
1696e7c33e29SRobert Watson 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1697e7c33e29SRobert Watson 	unp2 = sotounpcb(so2);
1698e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1699e7c33e29SRobert Watson 
1700e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1701e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
1702ccdadf1aSMark Johnston 	KASSERT(unp->unp_conn == NULL,
1703ccdadf1aSMark Johnston 	    ("%s: socket %p is already connected", __func__, unp));
17040d9ce3a1SRobert Watson 
1705df8bae1dSRodney W. Grimes 	if (so2->so_type != so->so_type)
1706df8bae1dSRodney W. Grimes 		return (EPROTOTYPE);
1707df8bae1dSRodney W. Grimes 	unp->unp_conn = unp2;
170875a67bf3SMatt Macy 	unp_pcb_hold(unp2);
170975a67bf3SMatt Macy 	unp_pcb_hold(unp);
1710df8bae1dSRodney W. Grimes 	switch (so->so_type) {
1711df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
171275a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
171398271db4SGarrett Wollman 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
171475a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
1715df8bae1dSRodney W. Grimes 		soisconnected(so);
1716df8bae1dSRodney W. Grimes 		break;
1717df8bae1dSRodney W. Grimes 
1718df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
171984d61770SRobert Watson 	case SOCK_SEQPACKET:
1720ccdadf1aSMark Johnston 		KASSERT(unp2->unp_conn == NULL,
1721ccdadf1aSMark Johnston 		    ("%s: socket %p is already connected", __func__, unp2));
1722df8bae1dSRodney W. Grimes 		unp2->unp_conn = unp;
17236a2989fdSMatthew N. Dodd 		if (req == PRU_CONNECT &&
17246a2989fdSMatthew N. Dodd 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
17256a2989fdSMatthew N. Dodd 			soisconnecting(so);
17266a2989fdSMatthew N. Dodd 		else
1727df8bae1dSRodney W. Grimes 			soisconnected(so);
1728df8bae1dSRodney W. Grimes 		soisconnected(so2);
1729df8bae1dSRodney W. Grimes 		break;
1730df8bae1dSRodney W. Grimes 
1731df8bae1dSRodney W. Grimes 	default:
1732df8bae1dSRodney W. Grimes 		panic("unp_connect2");
1733df8bae1dSRodney W. Grimes 	}
1734df8bae1dSRodney W. Grimes 	return (0);
1735df8bae1dSRodney W. Grimes }
1736df8bae1dSRodney W. Grimes 
1737f708ef1bSPoul-Henning Kamp static void
1738e7c33e29SRobert Watson unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1739df8bae1dSRodney W. Grimes {
174075a67bf3SMatt Macy 	struct socket *so, *so2;
1741f0317f86SMark Johnston #ifdef INVARIANTS
1742f0317f86SMark Johnston 	struct unpcb *unptmp;
1743f0317f86SMark Johnston #endif
17440d9ce3a1SRobert Watson 
1745e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1746e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
1747f0317f86SMark Johnston 	KASSERT(unp->unp_conn == unp2,
1748f0317f86SMark Johnston 	    ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
1749e7c33e29SRobert Watson 
1750fc3fcacfSRobert Watson 	unp->unp_conn = NULL;
175175a67bf3SMatt Macy 	so = unp->unp_socket;
175275a67bf3SMatt Macy 	so2 = unp2->unp_socket;
1753df8bae1dSRodney W. Grimes 	switch (unp->unp_socket->so_type) {
1754df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
175575a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
1756f0317f86SMark Johnston #ifdef INVARIANTS
1757f0317f86SMark Johnston 		LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
1758f0317f86SMark Johnston 			if (unptmp == unp)
1759f0317f86SMark Johnston 				break;
1760f0317f86SMark Johnston 		}
1761f0317f86SMark Johnston 		KASSERT(unptmp != NULL,
1762f0317f86SMark Johnston 		    ("%s: %p not found in reflist of %p", __func__, unp, unp2));
1763f0317f86SMark Johnston #endif
176498271db4SGarrett Wollman 		LIST_REMOVE(unp, unp_reflink);
176575a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
176675a67bf3SMatt Macy 		if (so) {
17671b2e3b4bSRobert Watson 			SOCK_LOCK(so);
17681b2e3b4bSRobert Watson 			so->so_state &= ~SS_ISCONNECTED;
17691b2e3b4bSRobert Watson 			SOCK_UNLOCK(so);
177075a67bf3SMatt Macy 		}
1771df8bae1dSRodney W. Grimes 		break;
1772df8bae1dSRodney W. Grimes 
1773df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
177484d61770SRobert Watson 	case SOCK_SEQPACKET:
177575a67bf3SMatt Macy 		if (so)
177675a67bf3SMatt Macy 			soisdisconnected(so);
177775a67bf3SMatt Macy 		MPASS(unp2->unp_conn == unp);
1778fc3fcacfSRobert Watson 		unp2->unp_conn = NULL;
177975a67bf3SMatt Macy 		if (so2)
178075a67bf3SMatt Macy 			soisdisconnected(so2);
1781df8bae1dSRodney W. Grimes 		break;
1782df8bae1dSRodney W. Grimes 	}
1783f0317f86SMark Johnston 
1784f0317f86SMark Johnston 	if (unp == unp2) {
1785f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
1786f0317f86SMark Johnston 		if (!unp_pcb_rele(unp))
1787f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp);
1788f0317f86SMark Johnston 	} else {
1789f0317f86SMark Johnston 		if (!unp_pcb_rele(unp))
1790f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp);
1791f0317f86SMark Johnston 		if (!unp_pcb_rele(unp2))
1792f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp2);
1793f0317f86SMark Johnston 	}
1794df8bae1dSRodney W. Grimes }
1795df8bae1dSRodney W. Grimes 
17960d9ce3a1SRobert Watson /*
1797d7924b70SRobert Watson  * unp_pcblist() walks the global list of struct unpcb's to generate a
1798d7924b70SRobert Watson  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1799d7924b70SRobert Watson  * sequentially, validating the generation number on each to see if it has
1800d7924b70SRobert Watson  * been detached.  All of this is necessary because copyout() may sleep on
1801d7924b70SRobert Watson  * disk I/O.
18020d9ce3a1SRobert Watson  */
180398271db4SGarrett Wollman static int
180482d9ae4eSPoul-Henning Kamp unp_pcblist(SYSCTL_HANDLER_ARGS)
180598271db4SGarrett Wollman {
180698271db4SGarrett Wollman 	struct unpcb *unp, **unp_list;
180798271db4SGarrett Wollman 	unp_gen_t gencnt;
18088f364875SJulian Elischer 	struct xunpgen *xug;
180998271db4SGarrett Wollman 	struct unp_head *head;
18108f364875SJulian Elischer 	struct xunpcb *xu;
1811d821d364SPedro F. Giffuni 	u_int i;
18125362170dSMark Johnston 	int error, n;
181398271db4SGarrett Wollman 
181484d61770SRobert Watson 	switch ((intptr_t)arg1) {
181584d61770SRobert Watson 	case SOCK_STREAM:
181684d61770SRobert Watson 		head = &unp_shead;
181784d61770SRobert Watson 		break;
181884d61770SRobert Watson 
181984d61770SRobert Watson 	case SOCK_DGRAM:
182084d61770SRobert Watson 		head = &unp_dhead;
182184d61770SRobert Watson 		break;
182284d61770SRobert Watson 
182384d61770SRobert Watson 	case SOCK_SEQPACKET:
182484d61770SRobert Watson 		head = &unp_sphead;
182584d61770SRobert Watson 		break;
182684d61770SRobert Watson 
182784d61770SRobert Watson 	default:
1828604f19c9SRobert Watson 		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
182984d61770SRobert Watson 	}
183098271db4SGarrett Wollman 
183198271db4SGarrett Wollman 	/*
183298271db4SGarrett Wollman 	 * The process of preparing the PCB list is too time-consuming and
183398271db4SGarrett Wollman 	 * resource-intensive to repeat twice on every request.
183498271db4SGarrett Wollman 	 */
1835fc3fcacfSRobert Watson 	if (req->oldptr == NULL) {
183698271db4SGarrett Wollman 		n = unp_count;
18378f364875SJulian Elischer 		req->oldidx = 2 * (sizeof *xug)
183898271db4SGarrett Wollman 			+ (n + n/8) * sizeof(struct xunpcb);
1839e5aeaa0cSDag-Erling Smørgrav 		return (0);
184098271db4SGarrett Wollman 	}
184198271db4SGarrett Wollman 
1842fc3fcacfSRobert Watson 	if (req->newptr != NULL)
1843e5aeaa0cSDag-Erling Smørgrav 		return (EPERM);
184498271db4SGarrett Wollman 
184598271db4SGarrett Wollman 	/*
184698271db4SGarrett Wollman 	 * OK, now we're committed to doing something.
184798271db4SGarrett Wollman 	 */
184879db6fe7SMark Johnston 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1849779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
185098271db4SGarrett Wollman 	gencnt = unp_gencnt;
185198271db4SGarrett Wollman 	n = unp_count;
1852779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
185398271db4SGarrett Wollman 
18548f364875SJulian Elischer 	xug->xug_len = sizeof *xug;
18558f364875SJulian Elischer 	xug->xug_count = n;
18568f364875SJulian Elischer 	xug->xug_gen = gencnt;
18578f364875SJulian Elischer 	xug->xug_sogen = so_gencnt;
18588f364875SJulian Elischer 	error = SYSCTL_OUT(req, xug, sizeof *xug);
18598f364875SJulian Elischer 	if (error) {
18608f364875SJulian Elischer 		free(xug, M_TEMP);
1861e5aeaa0cSDag-Erling Smørgrav 		return (error);
18628f364875SJulian Elischer 	}
186398271db4SGarrett Wollman 
1864a163d034SWarner Losh 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
186598271db4SGarrett Wollman 
1866779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
18672e3c8fcbSPoul-Henning Kamp 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
18682e3c8fcbSPoul-Henning Kamp 	     unp = LIST_NEXT(unp, unp_link)) {
1869e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
18708a7d8cc6SRobert Watson 		if (unp->unp_gencnt <= gencnt) {
1871a854ed98SJohn Baldwin 			if (cr_cansee(req->td->td_ucred,
1872e7c33e29SRobert Watson 			    unp->unp_socket->so_cred)) {
1873e7c33e29SRobert Watson 				UNP_PCB_UNLOCK(unp);
18744787fd37SPaul Saab 				continue;
1875e7c33e29SRobert Watson 			}
187698271db4SGarrett Wollman 			unp_list[i++] = unp;
187775a67bf3SMatt Macy 			unp_pcb_hold(unp);
187898271db4SGarrett Wollman 		}
1879e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
18804787fd37SPaul Saab 	}
1881779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
18821c381b19SRobert Watson 	n = i;			/* In case we lost some during malloc. */
188398271db4SGarrett Wollman 
188498271db4SGarrett Wollman 	error = 0;
1885fe2eee82SColin Percival 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
188698271db4SGarrett Wollman 	for (i = 0; i < n; i++) {
188798271db4SGarrett Wollman 		unp = unp_list[i];
1888e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
18895362170dSMark Johnston 		if (unp_pcb_rele(unp))
18905362170dSMark Johnston 			continue;
189175a67bf3SMatt Macy 
18925362170dSMark Johnston 		if (unp->unp_gencnt <= gencnt) {
18938f364875SJulian Elischer 			xu->xu_len = sizeof *xu;
18943a20f06aSBrooks Davis 			xu->xu_unpp = (uintptr_t)unp;
189598271db4SGarrett Wollman 			/*
189698271db4SGarrett Wollman 			 * XXX - need more locking here to protect against
189798271db4SGarrett Wollman 			 * connect/disconnect races for SMP.
189898271db4SGarrett Wollman 			 */
1899fc3fcacfSRobert Watson 			if (unp->unp_addr != NULL)
19008f364875SJulian Elischer 				bcopy(unp->unp_addr, &xu->xu_addr,
190198271db4SGarrett Wollman 				      unp->unp_addr->sun_len);
19020e229f34SGleb Smirnoff 			else
19030e229f34SGleb Smirnoff 				bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1904fc3fcacfSRobert Watson 			if (unp->unp_conn != NULL &&
1905fc3fcacfSRobert Watson 			    unp->unp_conn->unp_addr != NULL)
190698271db4SGarrett Wollman 				bcopy(unp->unp_conn->unp_addr,
19078f364875SJulian Elischer 				      &xu->xu_caddr,
190898271db4SGarrett Wollman 				      unp->unp_conn->unp_addr->sun_len);
19090e229f34SGleb Smirnoff 			else
19100e229f34SGleb Smirnoff 				bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
19113a20f06aSBrooks Davis 			xu->unp_vnode = (uintptr_t)unp->unp_vnode;
19123a20f06aSBrooks Davis 			xu->unp_conn = (uintptr_t)unp->unp_conn;
19133a20f06aSBrooks Davis 			xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
19143a20f06aSBrooks Davis 			xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
19150e229f34SGleb Smirnoff 			xu->unp_gencnt = unp->unp_gencnt;
19168f364875SJulian Elischer 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1917e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
19188f364875SJulian Elischer 			error = SYSCTL_OUT(req, xu, sizeof *xu);
19195362170dSMark Johnston 		} else {
1920e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
1921e7c33e29SRobert Watson 		}
19225362170dSMark Johnston 	}
19238f364875SJulian Elischer 	free(xu, M_TEMP);
192498271db4SGarrett Wollman 	if (!error) {
192598271db4SGarrett Wollman 		/*
19261c381b19SRobert Watson 		 * Give the user an updated idea of our state.  If the
19271c381b19SRobert Watson 		 * generation differs from what we told her before, she knows
19281c381b19SRobert Watson 		 * that something happened while we were processing this
19291c381b19SRobert Watson 		 * request, and it might be necessary to retry.
193098271db4SGarrett Wollman 		 */
19318f364875SJulian Elischer 		xug->xug_gen = unp_gencnt;
19328f364875SJulian Elischer 		xug->xug_sogen = so_gencnt;
19338f364875SJulian Elischer 		xug->xug_count = unp_count;
19348f364875SJulian Elischer 		error = SYSCTL_OUT(req, xug, sizeof *xug);
193598271db4SGarrett Wollman 	}
193698271db4SGarrett Wollman 	free(unp_list, M_TEMP);
19378f364875SJulian Elischer 	free(xug, M_TEMP);
1938e5aeaa0cSDag-Erling Smørgrav 	return (error);
193998271db4SGarrett Wollman }
194098271db4SGarrett Wollman 
19417029da5cSPawel Biernacki SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
19427029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19432fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
194498271db4SGarrett Wollman     "List of active local datagram sockets");
19457029da5cSPawel Biernacki SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
19467029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19472fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
194898271db4SGarrett Wollman     "List of active local stream sockets");
19492fee06f0SMatthew D Fleming SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
19507029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19512fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
195284d61770SRobert Watson     "List of active local seqpacket sockets");
195398271db4SGarrett Wollman 
1954f708ef1bSPoul-Henning Kamp static void
1955892af6b9SRobert Watson unp_shutdown(struct unpcb *unp)
1956df8bae1dSRodney W. Grimes {
1957e7c33e29SRobert Watson 	struct unpcb *unp2;
1958df8bae1dSRodney W. Grimes 	struct socket *so;
1959df8bae1dSRodney W. Grimes 
1960e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
19610d9ce3a1SRobert Watson 
1962e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
196384d61770SRobert Watson 	if ((unp->unp_socket->so_type == SOCK_STREAM ||
196484d61770SRobert Watson 	    (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1965e7c33e29SRobert Watson 		so = unp2->unp_socket;
1966e7c33e29SRobert Watson 		if (so != NULL)
1967df8bae1dSRodney W. Grimes 			socantrcvmore(so);
1968df8bae1dSRodney W. Grimes 	}
1969e7c33e29SRobert Watson }
1970df8bae1dSRodney W. Grimes 
1971f708ef1bSPoul-Henning Kamp static void
1972afc055d9SEd Schouten unp_drop(struct unpcb *unp)
1973df8bae1dSRodney W. Grimes {
1974*50b07c1fSMark Johnston 	struct socket *so;
1975e7c33e29SRobert Watson 	struct unpcb *unp2;
19760d9ce3a1SRobert Watson 
1977afc055d9SEd Schouten 	/*
1978afc055d9SEd Schouten 	 * Regardless of whether the socket's peer dropped the connection
1979afc055d9SEd Schouten 	 * with this socket by aborting or disconnecting, POSIX requires
1980afc055d9SEd Schouten 	 * that ECONNRESET is returned.
1981afc055d9SEd Schouten 	 */
198275a67bf3SMatt Macy 
198375a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
1984*50b07c1fSMark Johnston 	so = unp->unp_socket;
198575a67bf3SMatt Macy 	if (so)
1986afc055d9SEd Schouten 		so->so_error = ECONNRESET;
1987ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1988f0317f86SMark Johnston 		/* Last reference dropped in unp_disconnect(). */
1989f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
1990e7c33e29SRobert Watson 		unp_disconnect(unp, unp2);
1991f0317f86SMark Johnston 	} else if (!unp_pcb_rele(unp)) {
199275a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
199375a67bf3SMatt Macy 	}
1994f0317f86SMark Johnston }
1995df8bae1dSRodney W. Grimes 
19962bc21ed9SDavid Malone static void
19978cb539f1SPawel Jakub Dawidek unp_freerights(struct filedescent **fdep, int fdcount)
1998df8bae1dSRodney W. Grimes {
19992bc21ed9SDavid Malone 	struct file *fp;
20002609222aSPawel Jakub Dawidek 	int i;
2001df8bae1dSRodney W. Grimes 
200282e825c4SGleb Smirnoff 	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
200382e825c4SGleb Smirnoff 
20048cb539f1SPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
20058cb539f1SPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
20068cb539f1SPawel Jakub Dawidek 		filecaps_free(&fdep[i]->fde_caps);
20078692c025SYoshinobu Inoue 		unp_discard(fp);
2008df8bae1dSRodney W. Grimes 	}
20098cb539f1SPawel Jakub Dawidek 	free(fdep[0], M_FILECAPS);
20102bc21ed9SDavid Malone }
20112bc21ed9SDavid Malone 
20120b36cd25SRobert Watson static int
2013c2e3c52eSJilles Tjoelker unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
20142bc21ed9SDavid Malone {
20152bc21ed9SDavid Malone 	struct thread *td = curthread;		/* XXX */
20162bc21ed9SDavid Malone 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
20172bc21ed9SDavid Malone 	int i;
20182bc21ed9SDavid Malone 	int *fdp;
20192609222aSPawel Jakub Dawidek 	struct filedesc *fdesc = td->td_proc->p_fd;
2020ea31808cSMateusz Guzik 	struct filedescent **fdep;
20212bc21ed9SDavid Malone 	void *data;
20222bc21ed9SDavid Malone 	socklen_t clen = control->m_len, datalen;
20232bc21ed9SDavid Malone 	int error, newfds;
20242bc21ed9SDavid Malone 	u_int newlen;
20252bc21ed9SDavid Malone 
20263dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
20274c5bc1caSRobert Watson 
20282bc21ed9SDavid Malone 	error = 0;
20292bc21ed9SDavid Malone 	if (controlp != NULL) /* controlp == NULL => free control messages */
20302bc21ed9SDavid Malone 		*controlp = NULL;
20312bc21ed9SDavid Malone 	while (cm != NULL) {
20322bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
20332bc21ed9SDavid Malone 			error = EINVAL;
20342bc21ed9SDavid Malone 			break;
20352bc21ed9SDavid Malone 		}
20362bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
20372bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
20382bc21ed9SDavid Malone 		if (cm->cmsg_level == SOL_SOCKET
20392bc21ed9SDavid Malone 		    && cm->cmsg_type == SCM_RIGHTS) {
20402609222aSPawel Jakub Dawidek 			newfds = datalen / sizeof(*fdep);
204182e825c4SGleb Smirnoff 			if (newfds == 0)
204282e825c4SGleb Smirnoff 				goto next;
20432609222aSPawel Jakub Dawidek 			fdep = data;
20442bc21ed9SDavid Malone 
2045e2f9a08bSOlivier Houchard 			/* If we're not outputting the descriptors free them. */
20462bc21ed9SDavid Malone 			if (error || controlp == NULL) {
20472609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20482bc21ed9SDavid Malone 				goto next;
20492bc21ed9SDavid Malone 			}
20502609222aSPawel Jakub Dawidek 			FILEDESC_XLOCK(fdesc);
205160a5ef26SRobert Watson 
2052ed5b7817SJulian Elischer 			/*
20531c381b19SRobert Watson 			 * Now change each pointer to an fd in the global
20541c381b19SRobert Watson 			 * table to an integer that is the index to the local
20551c381b19SRobert Watson 			 * fd table entry that we set up to point to the
20561c381b19SRobert Watson 			 * global one we are transferring.
2057ed5b7817SJulian Elischer 			 */
20582bc21ed9SDavid Malone 			newlen = newfds * sizeof(int);
20592bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
20602bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
20612bc21ed9SDavid Malone 			if (*controlp == NULL) {
20622609222aSPawel Jakub Dawidek 				FILEDESC_XUNLOCK(fdesc);
20632bc21ed9SDavid Malone 				error = E2BIG;
20642609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20652bc21ed9SDavid Malone 				goto next;
20662bc21ed9SDavid Malone 			}
20672bc21ed9SDavid Malone 
20682bc21ed9SDavid Malone 			fdp = (int *)
20692bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2070db8f33fdSMateusz Guzik 			if (fdallocn(td, 0, fdp, newfds) != 0) {
20713331a33aSMateusz Guzik 				FILEDESC_XUNLOCK(fdesc);
2072db8f33fdSMateusz Guzik 				error = EMSGSIZE;
2073db8f33fdSMateusz Guzik 				unp_freerights(fdep, newfds);
2074db8f33fdSMateusz Guzik 				m_freem(*controlp);
2075db8f33fdSMateusz Guzik 				*controlp = NULL;
2076db8f33fdSMateusz Guzik 				goto next;
2077db8f33fdSMateusz Guzik 			}
20788cb539f1SPawel Jakub Dawidek 			for (i = 0; i < newfds; i++, fdp++) {
2079ea31808cSMateusz Guzik 				_finstall(fdesc, fdep[i]->fde_file, *fdp,
20806ceacebdSAlex Richardson 				    (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2081ea31808cSMateusz Guzik 				    &fdep[i]->fde_caps);
2082ea31808cSMateusz Guzik 				unp_externalize_fp(fdep[i]->fde_file);
2083df8bae1dSRodney W. Grimes 			}
2084c7902fbeSMark Johnston 
2085c7902fbeSMark Johnston 			/*
2086c7902fbeSMark Johnston 			 * The new type indicates that the mbuf data refers to
2087c7902fbeSMark Johnston 			 * kernel resources that may need to be released before
2088c7902fbeSMark Johnston 			 * the mbuf is freed.
2089c7902fbeSMark Johnston 			 */
2090c7902fbeSMark Johnston 			m_chtype(*controlp, MT_EXTCONTROL);
20912609222aSPawel Jakub Dawidek 			FILEDESC_XUNLOCK(fdesc);
20928cb539f1SPawel Jakub Dawidek 			free(fdep[0], M_FILECAPS);
20931c381b19SRobert Watson 		} else {
20941c381b19SRobert Watson 			/* We can just copy anything else across. */
20952bc21ed9SDavid Malone 			if (error || controlp == NULL)
20962bc21ed9SDavid Malone 				goto next;
20972bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, datalen,
20982bc21ed9SDavid Malone 			    cm->cmsg_type, cm->cmsg_level);
20992bc21ed9SDavid Malone 			if (*controlp == NULL) {
21002bc21ed9SDavid Malone 				error = ENOBUFS;
21012bc21ed9SDavid Malone 				goto next;
21022bc21ed9SDavid Malone 			}
21032bc21ed9SDavid Malone 			bcopy(data,
21042bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
21052bc21ed9SDavid Malone 			    datalen);
21062bc21ed9SDavid Malone 		}
21072bc21ed9SDavid Malone 		controlp = &(*controlp)->m_next;
21082bc21ed9SDavid Malone 
21092bc21ed9SDavid Malone next:
21102bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
21112bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
21122bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
21132bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
21148692c025SYoshinobu Inoue 		} else {
21152bc21ed9SDavid Malone 			clen = 0;
21162bc21ed9SDavid Malone 			cm = NULL;
21178692c025SYoshinobu Inoue 		}
21188692c025SYoshinobu Inoue 	}
21198692c025SYoshinobu Inoue 
21202bc21ed9SDavid Malone 	m_freem(control);
21212bc21ed9SDavid Malone 	return (error);
2122df8bae1dSRodney W. Grimes }
2123df8bae1dSRodney W. Grimes 
21244f590175SPaul Saab static void
21254f590175SPaul Saab unp_zone_change(void *tag)
21264f590175SPaul Saab {
21274f590175SPaul Saab 
21284f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21294f590175SPaul Saab }
21304f590175SPaul Saab 
21315362170dSMark Johnston #ifdef INVARIANTS
21325362170dSMark Johnston static void
21335362170dSMark Johnston unp_zdtor(void *mem, int size __unused, void *arg __unused)
21345362170dSMark Johnston {
21355362170dSMark Johnston 	struct unpcb *unp;
21365362170dSMark Johnston 
21375362170dSMark Johnston 	unp = mem;
21385362170dSMark Johnston 
21395362170dSMark Johnston 	KASSERT(LIST_EMPTY(&unp->unp_refs),
21405362170dSMark Johnston 	    ("%s: unpcb %p has lingering refs", __func__, unp));
21415362170dSMark Johnston 	KASSERT(unp->unp_socket == NULL,
21425362170dSMark Johnston 	    ("%s: unpcb %p has socket backpointer", __func__, unp));
21435362170dSMark Johnston 	KASSERT(unp->unp_vnode == NULL,
21445362170dSMark Johnston 	    ("%s: unpcb %p has vnode references", __func__, unp));
21455362170dSMark Johnston 	KASSERT(unp->unp_conn == NULL,
21465362170dSMark Johnston 	    ("%s: unpcb %p is still connected", __func__, unp));
21475362170dSMark Johnston 	KASSERT(unp->unp_addr == NULL,
21485362170dSMark Johnston 	    ("%s: unpcb %p has leaked addr", __func__, unp));
21495362170dSMark Johnston }
21505362170dSMark Johnston #endif
21515362170dSMark Johnston 
21520b36cd25SRobert Watson static void
215398271db4SGarrett Wollman unp_init(void)
215498271db4SGarrett Wollman {
21555362170dSMark Johnston 	uma_dtor dtor;
21561c381b19SRobert Watson 
215721ca7b57SMarko Zec #ifdef VIMAGE
215821ca7b57SMarko Zec 	if (!IS_DEFAULT_VNET(curvnet))
215921ca7b57SMarko Zec 		return;
216021ca7b57SMarko Zec #endif
21615362170dSMark Johnston 
21625362170dSMark Johnston #ifdef INVARIANTS
21635362170dSMark Johnston 	dtor = unp_zdtor;
21645362170dSMark Johnston #else
21655362170dSMark Johnston 	dtor = NULL;
21665362170dSMark Johnston #endif
21675362170dSMark Johnston 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
216875a67bf3SMatt Macy 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
21694f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21706e0b6746SPawel Jakub Dawidek 	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
21714f590175SPaul Saab 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
21724f590175SPaul Saab 	    NULL, EVENTHANDLER_PRI_ANY);
217398271db4SGarrett Wollman 	LIST_INIT(&unp_dhead);
217498271db4SGarrett Wollman 	LIST_INIT(&unp_shead);
217584d61770SRobert Watson 	LIST_INIT(&unp_sphead);
21760cb64678SKonstantin Belousov 	SLIST_INIT(&unp_defers);
2177daee0f0bSKonstantin Belousov 	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
21780cb64678SKonstantin Belousov 	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
21793dab55bcSRobert Watson 	UNP_LINK_LOCK_INIT();
21800cb64678SKonstantin Belousov 	UNP_DEFERRED_LOCK_INIT();
218198271db4SGarrett Wollman }
218298271db4SGarrett Wollman 
218347c3450eSKonstantin Belousov static void
218447c3450eSKonstantin Belousov unp_internalize_cleanup_rights(struct mbuf *control)
218547c3450eSKonstantin Belousov {
218647c3450eSKonstantin Belousov 	struct cmsghdr *cp;
218747c3450eSKonstantin Belousov 	struct mbuf *m;
218847c3450eSKonstantin Belousov 	void *data;
218947c3450eSKonstantin Belousov 	socklen_t datalen;
219047c3450eSKonstantin Belousov 
219147c3450eSKonstantin Belousov 	for (m = control; m != NULL; m = m->m_next) {
219247c3450eSKonstantin Belousov 		cp = mtod(m, struct cmsghdr *);
219347c3450eSKonstantin Belousov 		if (cp->cmsg_level != SOL_SOCKET ||
219447c3450eSKonstantin Belousov 		    cp->cmsg_type != SCM_RIGHTS)
219547c3450eSKonstantin Belousov 			continue;
219647c3450eSKonstantin Belousov 		data = CMSG_DATA(cp);
219747c3450eSKonstantin Belousov 		datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
219847c3450eSKonstantin Belousov 		unp_freerights(data, datalen / sizeof(struct filedesc *));
219947c3450eSKonstantin Belousov 	}
220047c3450eSKonstantin Belousov }
220147c3450eSKonstantin Belousov 
2202f708ef1bSPoul-Henning Kamp static int
2203892af6b9SRobert Watson unp_internalize(struct mbuf **controlp, struct thread *td)
2204df8bae1dSRodney W. Grimes {
220547c3450eSKonstantin Belousov 	struct mbuf *control, **initial_controlp;
220647c3450eSKonstantin Belousov 	struct proc *p;
220747c3450eSKonstantin Belousov 	struct filedesc *fdesc;
2208ab15d803SSergey Kandaurov 	struct bintime *bt;
220947c3450eSKonstantin Belousov 	struct cmsghdr *cm;
22102bc21ed9SDavid Malone 	struct cmsgcred *cmcred;
22118cb539f1SPawel Jakub Dawidek 	struct filedescent *fde, **fdep, *fdev;
22122bc21ed9SDavid Malone 	struct file *fp;
22132bc21ed9SDavid Malone 	struct timeval *tv;
2214339efd75SMaxim Sobolev 	struct timespec *ts;
22152bc21ed9SDavid Malone 	void *data;
221647c3450eSKonstantin Belousov 	socklen_t clen, datalen;
2217f1cf2b9dSKonstantin Belousov 	int i, j, error, *fdp, oldfds;
22188692c025SYoshinobu Inoue 	u_int newlen;
2219df8bae1dSRodney W. Grimes 
22203dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
22214c5bc1caSRobert Watson 
222247c3450eSKonstantin Belousov 	p = td->td_proc;
222347c3450eSKonstantin Belousov 	fdesc = p->p_fd;
22242bc21ed9SDavid Malone 	error = 0;
222547c3450eSKonstantin Belousov 	control = *controlp;
222647c3450eSKonstantin Belousov 	clen = control->m_len;
22272bc21ed9SDavid Malone 	*controlp = NULL;
222847c3450eSKonstantin Belousov 	initial_controlp = controlp;
222947c3450eSKonstantin Belousov 	for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
22302bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2231de966666SMateusz Guzik 		    || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
22322bc21ed9SDavid Malone 			error = EINVAL;
22332bc21ed9SDavid Malone 			goto out;
22342bc21ed9SDavid Malone 		}
22352bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
22362bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
22372bc21ed9SDavid Malone 
22382bc21ed9SDavid Malone 		switch (cm->cmsg_type) {
22390b788fa1SBill Paul 		/*
22400b788fa1SBill Paul 		 * Fill in credential information.
22410b788fa1SBill Paul 		 */
22422bc21ed9SDavid Malone 		case SCM_CREDS:
22432bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
22442bc21ed9SDavid Malone 			    SCM_CREDS, SOL_SOCKET);
22452bc21ed9SDavid Malone 			if (*controlp == NULL) {
22462bc21ed9SDavid Malone 				error = ENOBUFS;
22472bc21ed9SDavid Malone 				goto out;
22482bc21ed9SDavid Malone 			}
22492bc21ed9SDavid Malone 			cmcred = (struct cmsgcred *)
22502bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
22510b788fa1SBill Paul 			cmcred->cmcred_pid = p->p_pid;
2252a854ed98SJohn Baldwin 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2253a854ed98SJohn Baldwin 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2254a854ed98SJohn Baldwin 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
2255a854ed98SJohn Baldwin 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
22560b788fa1SBill Paul 			    CMGROUP_MAX);
22570b788fa1SBill Paul 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
22582bc21ed9SDavid Malone 				cmcred->cmcred_groups[i] =
2259a854ed98SJohn Baldwin 				    td->td_ucred->cr_groups[i];
22602bc21ed9SDavid Malone 			break;
22610b788fa1SBill Paul 
22622bc21ed9SDavid Malone 		case SCM_RIGHTS:
22632bc21ed9SDavid Malone 			oldfds = datalen / sizeof (int);
226482e825c4SGleb Smirnoff 			if (oldfds == 0)
226582e825c4SGleb Smirnoff 				break;
2266ed5b7817SJulian Elischer 			/*
22671c381b19SRobert Watson 			 * Check that all the FDs passed in refer to legal
22681c381b19SRobert Watson 			 * files.  If not, reject the entire operation.
2269ed5b7817SJulian Elischer 			 */
22702bc21ed9SDavid Malone 			fdp = data;
22712609222aSPawel Jakub Dawidek 			FILEDESC_SLOCK(fdesc);
22726a1cf96bSMateusz Guzik 			for (i = 0; i < oldfds; i++, fdp++) {
22736a1cf96bSMateusz Guzik 				fp = fget_locked(fdesc, *fdp);
22746a1cf96bSMateusz Guzik 				if (fp == NULL) {
22752609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
22762bc21ed9SDavid Malone 					error = EBADF;
22772bc21ed9SDavid Malone 					goto out;
22782bc21ed9SDavid Malone 				}
2279e7d6662fSAlfred Perlstein 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
22802609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
2281e7d6662fSAlfred Perlstein 					error = EOPNOTSUPP;
2282e7d6662fSAlfred Perlstein 					goto out;
2283e7d6662fSAlfred Perlstein 				}
2284df8bae1dSRodney W. Grimes 			}
22855e3f7694SRobert Watson 
2286ed5b7817SJulian Elischer 			/*
22870b36cd25SRobert Watson 			 * Now replace the integer FDs with pointers to the
22882609222aSPawel Jakub Dawidek 			 * file structure and capability rights.
2289ed5b7817SJulian Elischer 			 */
22908cb539f1SPawel Jakub Dawidek 			newlen = oldfds * sizeof(fdep[0]);
22912bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
22922bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
22932bc21ed9SDavid Malone 			if (*controlp == NULL) {
22942609222aSPawel Jakub Dawidek 				FILEDESC_SUNLOCK(fdesc);
22952bc21ed9SDavid Malone 				error = E2BIG;
22962bc21ed9SDavid Malone 				goto out;
22978692c025SYoshinobu Inoue 			}
22982bc21ed9SDavid Malone 			fdp = data;
2299f1cf2b9dSKonstantin Belousov 			for (i = 0; i < oldfds; i++, fdp++) {
2300f1cf2b9dSKonstantin Belousov 				if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2301f1cf2b9dSKonstantin Belousov 					fdp = data;
2302f1cf2b9dSKonstantin Belousov 					for (j = 0; j < i; j++, fdp++) {
2303f1cf2b9dSKonstantin Belousov 						fdrop(fdesc->fd_ofiles[*fdp].
2304f1cf2b9dSKonstantin Belousov 						    fde_file, td);
2305f1cf2b9dSKonstantin Belousov 					}
2306f1cf2b9dSKonstantin Belousov 					FILEDESC_SUNLOCK(fdesc);
2307f1cf2b9dSKonstantin Belousov 					error = EBADF;
2308f1cf2b9dSKonstantin Belousov 					goto out;
2309f1cf2b9dSKonstantin Belousov 				}
2310f1cf2b9dSKonstantin Belousov 			}
2311f1cf2b9dSKonstantin Belousov 			fdp = data;
23128cb539f1SPawel Jakub Dawidek 			fdep = (struct filedescent **)
23132bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23148cb539f1SPawel Jakub Dawidek 			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
23158cb539f1SPawel Jakub Dawidek 			    M_WAITOK);
23168cb539f1SPawel Jakub Dawidek 			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
23172609222aSPawel Jakub Dawidek 				fde = &fdesc->fd_ofiles[*fdp];
23188cb539f1SPawel Jakub Dawidek 				fdep[i] = fdev;
23198cb539f1SPawel Jakub Dawidek 				fdep[i]->fde_file = fde->fde_file;
23208cb539f1SPawel Jakub Dawidek 				filecaps_copy(&fde->fde_caps,
2321d7832811SMateusz Guzik 				    &fdep[i]->fde_caps, true);
23228cb539f1SPawel Jakub Dawidek 				unp_internalize_fp(fdep[i]->fde_file);
2323df8bae1dSRodney W. Grimes 			}
23242609222aSPawel Jakub Dawidek 			FILEDESC_SUNLOCK(fdesc);
23252bc21ed9SDavid Malone 			break;
23262bc21ed9SDavid Malone 
23272bc21ed9SDavid Malone 		case SCM_TIMESTAMP:
23282bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
23292bc21ed9SDavid Malone 			    SCM_TIMESTAMP, SOL_SOCKET);
23302bc21ed9SDavid Malone 			if (*controlp == NULL) {
23312bc21ed9SDavid Malone 				error = ENOBUFS;
23322bc21ed9SDavid Malone 				goto out;
23338692c025SYoshinobu Inoue 			}
23342bc21ed9SDavid Malone 			tv = (struct timeval *)
23352bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23362bc21ed9SDavid Malone 			microtime(tv);
23372bc21ed9SDavid Malone 			break;
23382bc21ed9SDavid Malone 
2339ab15d803SSergey Kandaurov 		case SCM_BINTIME:
2340ab15d803SSergey Kandaurov 			*controlp = sbcreatecontrol(NULL, sizeof(*bt),
2341ab15d803SSergey Kandaurov 			    SCM_BINTIME, SOL_SOCKET);
2342ab15d803SSergey Kandaurov 			if (*controlp == NULL) {
2343ab15d803SSergey Kandaurov 				error = ENOBUFS;
2344ab15d803SSergey Kandaurov 				goto out;
2345ab15d803SSergey Kandaurov 			}
2346ab15d803SSergey Kandaurov 			bt = (struct bintime *)
2347ab15d803SSergey Kandaurov 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2348ab15d803SSergey Kandaurov 			bintime(bt);
2349ab15d803SSergey Kandaurov 			break;
2350ab15d803SSergey Kandaurov 
2351339efd75SMaxim Sobolev 		case SCM_REALTIME:
2352339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2353339efd75SMaxim Sobolev 			    SCM_REALTIME, SOL_SOCKET);
2354339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2355339efd75SMaxim Sobolev 				error = ENOBUFS;
2356339efd75SMaxim Sobolev 				goto out;
2357339efd75SMaxim Sobolev 			}
2358339efd75SMaxim Sobolev 			ts = (struct timespec *)
2359339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2360339efd75SMaxim Sobolev 			nanotime(ts);
2361339efd75SMaxim Sobolev 			break;
2362339efd75SMaxim Sobolev 
2363339efd75SMaxim Sobolev 		case SCM_MONOTONIC:
2364339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2365339efd75SMaxim Sobolev 			    SCM_MONOTONIC, SOL_SOCKET);
2366339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2367339efd75SMaxim Sobolev 				error = ENOBUFS;
2368339efd75SMaxim Sobolev 				goto out;
2369339efd75SMaxim Sobolev 			}
2370339efd75SMaxim Sobolev 			ts = (struct timespec *)
2371339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2372339efd75SMaxim Sobolev 			nanouptime(ts);
2373339efd75SMaxim Sobolev 			break;
2374339efd75SMaxim Sobolev 
23752bc21ed9SDavid Malone 		default:
23762bc21ed9SDavid Malone 			error = EINVAL;
23772bc21ed9SDavid Malone 			goto out;
23782bc21ed9SDavid Malone 		}
23792bc21ed9SDavid Malone 
23804013d726SMark Johnston 		if (*controlp != NULL)
23812bc21ed9SDavid Malone 			controlp = &(*controlp)->m_next;
23822bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
23832bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
23842bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
23852bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
23862bc21ed9SDavid Malone 		} else {
23872bc21ed9SDavid Malone 			clen = 0;
23882bc21ed9SDavid Malone 			cm = NULL;
23892bc21ed9SDavid Malone 		}
23902bc21ed9SDavid Malone 	}
23912bc21ed9SDavid Malone 
23922bc21ed9SDavid Malone out:
239347c3450eSKonstantin Belousov 	if (error != 0 && initial_controlp != NULL)
239447c3450eSKonstantin Belousov 		unp_internalize_cleanup_rights(*initial_controlp);
23952bc21ed9SDavid Malone 	m_freem(control);
23962bc21ed9SDavid Malone 	return (error);
2397df8bae1dSRodney W. Grimes }
2398df8bae1dSRodney W. Grimes 
23995b950deaSRobert Watson static struct mbuf *
2400ede4af47SConrad Meyer unp_addsockcred(struct thread *td, struct mbuf *control, int mode)
24016a2989fdSMatthew N. Dodd {
240270df31f4SMaxim Konovalov 	struct mbuf *m, *n, *n_prev;
240370df31f4SMaxim Konovalov 	const struct cmsghdr *cm;
2404ede4af47SConrad Meyer 	int ngroups, i, cmsgtype;
2405ede4af47SConrad Meyer 	size_t ctrlsz;
24066a2989fdSMatthew N. Dodd 
24076a2989fdSMatthew N. Dodd 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2408ede4af47SConrad Meyer 	if (mode & UNP_WANTCRED_ALWAYS) {
2409ede4af47SConrad Meyer 		ctrlsz = SOCKCRED2SIZE(ngroups);
2410ede4af47SConrad Meyer 		cmsgtype = SCM_CREDS2;
2411ede4af47SConrad Meyer 	} else {
2412ede4af47SConrad Meyer 		ctrlsz = SOCKCREDSIZE(ngroups);
2413ede4af47SConrad Meyer 		cmsgtype = SCM_CREDS;
2414ede4af47SConrad Meyer 	}
2415ede4af47SConrad Meyer 
2416ede4af47SConrad Meyer 	m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET);
24176a2989fdSMatthew N. Dodd 	if (m == NULL)
24186a2989fdSMatthew N. Dodd 		return (control);
24196a2989fdSMatthew N. Dodd 
2420ede4af47SConrad Meyer 	if (mode & UNP_WANTCRED_ALWAYS) {
2421ede4af47SConrad Meyer 		struct sockcred2 *sc;
2422ede4af47SConrad Meyer 
2423ede4af47SConrad Meyer 		sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2424ede4af47SConrad Meyer 		sc->sc_version = 0;
2425ede4af47SConrad Meyer 		sc->sc_pid = td->td_proc->p_pid;
24266a2989fdSMatthew N. Dodd 		sc->sc_uid = td->td_ucred->cr_ruid;
24276a2989fdSMatthew N. Dodd 		sc->sc_euid = td->td_ucred->cr_uid;
24286a2989fdSMatthew N. Dodd 		sc->sc_gid = td->td_ucred->cr_rgid;
24296a2989fdSMatthew N. Dodd 		sc->sc_egid = td->td_ucred->cr_gid;
24306a2989fdSMatthew N. Dodd 		sc->sc_ngroups = ngroups;
24316a2989fdSMatthew N. Dodd 		for (i = 0; i < sc->sc_ngroups; i++)
24326a2989fdSMatthew N. Dodd 			sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2433ede4af47SConrad Meyer 	} else {
2434ede4af47SConrad Meyer 		struct sockcred *sc;
2435ede4af47SConrad Meyer 
2436ede4af47SConrad Meyer 		sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2437ede4af47SConrad Meyer 		sc->sc_uid = td->td_ucred->cr_ruid;
2438ede4af47SConrad Meyer 		sc->sc_euid = td->td_ucred->cr_uid;
2439ede4af47SConrad Meyer 		sc->sc_gid = td->td_ucred->cr_rgid;
2440ede4af47SConrad Meyer 		sc->sc_egid = td->td_ucred->cr_gid;
2441ede4af47SConrad Meyer 		sc->sc_ngroups = ngroups;
2442ede4af47SConrad Meyer 		for (i = 0; i < sc->sc_ngroups; i++)
2443ede4af47SConrad Meyer 			sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2444ede4af47SConrad Meyer 	}
24456a2989fdSMatthew N. Dodd 
24466a2989fdSMatthew N. Dodd 	/*
24471c381b19SRobert Watson 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
24481c381b19SRobert Watson 	 * created SCM_CREDS control message (struct sockcred) has another
24491c381b19SRobert Watson 	 * format.
24506a2989fdSMatthew N. Dodd 	 */
2451ede4af47SConrad Meyer 	if (control != NULL && cmsgtype == SCM_CREDS)
245270df31f4SMaxim Konovalov 		for (n = control, n_prev = NULL; n != NULL;) {
245370df31f4SMaxim Konovalov 			cm = mtod(n, struct cmsghdr *);
245470df31f4SMaxim Konovalov     			if (cm->cmsg_level == SOL_SOCKET &&
245570df31f4SMaxim Konovalov 			    cm->cmsg_type == SCM_CREDS) {
245670df31f4SMaxim Konovalov     				if (n_prev == NULL)
245770df31f4SMaxim Konovalov 					control = n->m_next;
245870df31f4SMaxim Konovalov 				else
245970df31f4SMaxim Konovalov 					n_prev->m_next = n->m_next;
246070df31f4SMaxim Konovalov 				n = m_free(n);
246170df31f4SMaxim Konovalov 			} else {
246270df31f4SMaxim Konovalov 				n_prev = n;
246370df31f4SMaxim Konovalov 				n = n->m_next;
246470df31f4SMaxim Konovalov 			}
246570df31f4SMaxim Konovalov 		}
24666a2989fdSMatthew N. Dodd 
246770df31f4SMaxim Konovalov 	/* Prepend it to the head. */
246870df31f4SMaxim Konovalov 	m->m_next = control;
246970df31f4SMaxim Konovalov 	return (m);
24706a2989fdSMatthew N. Dodd }
24716a2989fdSMatthew N. Dodd 
2472397c19d1SJeff Roberson static struct unpcb *
2473397c19d1SJeff Roberson fptounp(struct file *fp)
2474397c19d1SJeff Roberson {
2475397c19d1SJeff Roberson 	struct socket *so;
2476397c19d1SJeff Roberson 
2477397c19d1SJeff Roberson 	if (fp->f_type != DTYPE_SOCKET)
2478397c19d1SJeff Roberson 		return (NULL);
2479397c19d1SJeff Roberson 	if ((so = fp->f_data) == NULL)
2480397c19d1SJeff Roberson 		return (NULL);
2481397c19d1SJeff Roberson 	if (so->so_proto->pr_domain != &localdomain)
2482397c19d1SJeff Roberson 		return (NULL);
2483397c19d1SJeff Roberson 	return sotounpcb(so);
2484397c19d1SJeff Roberson }
2485397c19d1SJeff Roberson 
2486397c19d1SJeff Roberson static void
2487397c19d1SJeff Roberson unp_discard(struct file *fp)
2488397c19d1SJeff Roberson {
24890cb64678SKonstantin Belousov 	struct unp_defer *dr;
2490397c19d1SJeff Roberson 
24910cb64678SKonstantin Belousov 	if (unp_externalize_fp(fp)) {
24920cb64678SKonstantin Belousov 		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
24930cb64678SKonstantin Belousov 		dr->ud_fp = fp;
24940cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
24950cb64678SKonstantin Belousov 		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
24960cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
24970cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, 1);
24980cb64678SKonstantin Belousov 		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
24990cb64678SKonstantin Belousov 	} else
25004faa375cSMateusz Guzik 		closef_nothread(fp);
2501397c19d1SJeff Roberson }
2502397c19d1SJeff Roberson 
2503397c19d1SJeff Roberson static void
25040cb64678SKonstantin Belousov unp_process_defers(void *arg __unused, int pending)
25050cb64678SKonstantin Belousov {
25060cb64678SKonstantin Belousov 	struct unp_defer *dr;
25070cb64678SKonstantin Belousov 	SLIST_HEAD(, unp_defer) drl;
25080cb64678SKonstantin Belousov 	int count;
25090cb64678SKonstantin Belousov 
25100cb64678SKonstantin Belousov 	SLIST_INIT(&drl);
25110cb64678SKonstantin Belousov 	for (;;) {
25120cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
25130cb64678SKonstantin Belousov 		if (SLIST_FIRST(&unp_defers) == NULL) {
25140cb64678SKonstantin Belousov 			UNP_DEFERRED_UNLOCK();
25150cb64678SKonstantin Belousov 			break;
25160cb64678SKonstantin Belousov 		}
25170cb64678SKonstantin Belousov 		SLIST_SWAP(&unp_defers, &drl, unp_defer);
25180cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
25190cb64678SKonstantin Belousov 		count = 0;
25200cb64678SKonstantin Belousov 		while ((dr = SLIST_FIRST(&drl)) != NULL) {
25210cb64678SKonstantin Belousov 			SLIST_REMOVE_HEAD(&drl, ud_link);
25224faa375cSMateusz Guzik 			closef_nothread(dr->ud_fp);
25230cb64678SKonstantin Belousov 			free(dr, M_TEMP);
25240cb64678SKonstantin Belousov 			count++;
25250cb64678SKonstantin Belousov 		}
25260cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, -count);
25270cb64678SKonstantin Belousov 	}
25280cb64678SKonstantin Belousov }
25290cb64678SKonstantin Belousov 
25300cb64678SKonstantin Belousov static void
2531397c19d1SJeff Roberson unp_internalize_fp(struct file *fp)
2532397c19d1SJeff Roberson {
2533397c19d1SJeff Roberson 	struct unpcb *unp;
2534397c19d1SJeff Roberson 
25353dab55bcSRobert Watson 	UNP_LINK_WLOCK();
2536397c19d1SJeff Roberson 	if ((unp = fptounp(fp)) != NULL) {
2537397c19d1SJeff Roberson 		unp->unp_file = fp;
2538397c19d1SJeff Roberson 		unp->unp_msgcount++;
2539397c19d1SJeff Roberson 	}
2540397c19d1SJeff Roberson 	unp_rights++;
25413dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
2542397c19d1SJeff Roberson }
2543397c19d1SJeff Roberson 
25440cb64678SKonstantin Belousov static int
2545397c19d1SJeff Roberson unp_externalize_fp(struct file *fp)
2546397c19d1SJeff Roberson {
2547397c19d1SJeff Roberson 	struct unpcb *unp;
25480cb64678SKonstantin Belousov 	int ret;
2549397c19d1SJeff Roberson 
25503dab55bcSRobert Watson 	UNP_LINK_WLOCK();
25510cb64678SKonstantin Belousov 	if ((unp = fptounp(fp)) != NULL) {
2552397c19d1SJeff Roberson 		unp->unp_msgcount--;
25530cb64678SKonstantin Belousov 		ret = 1;
25540cb64678SKonstantin Belousov 	} else
25550cb64678SKonstantin Belousov 		ret = 0;
2556397c19d1SJeff Roberson 	unp_rights--;
25573dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
25580cb64678SKonstantin Belousov 	return (ret);
2559397c19d1SJeff Roberson }
2560397c19d1SJeff Roberson 
2561161a0c7cSRobert Watson /*
2562a0ec558aSRobert Watson  * unp_defer indicates whether additional work has been defered for a future
2563a0ec558aSRobert Watson  * pass through unp_gc().  It is thread local and does not require explicit
2564a0ec558aSRobert Watson  * synchronization.
2565161a0c7cSRobert Watson  */
2566397c19d1SJeff Roberson static int	unp_marked;
2567a0ec558aSRobert Watson 
2568397c19d1SJeff Roberson static void
2569a9aa06f7SJason A. Harmening unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2570397c19d1SJeff Roberson {
2571397c19d1SJeff Roberson 	struct unpcb *unp;
2572be26ba7cSPawel Jakub Dawidek 	struct file *fp;
2573be26ba7cSPawel Jakub Dawidek 	int i;
2574397c19d1SJeff Roberson 
2575a9aa06f7SJason A. Harmening 	/*
2576a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2577a9aa06f7SJason A. Harmening 	 */
2578a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2579a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2580a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2581a9aa06f7SJason A. Harmening 
2582be26ba7cSPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
2583be26ba7cSPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
25846f552cb0SJeff Roberson 		if ((unp = fptounp(fp)) == NULL)
2585be26ba7cSPawel Jakub Dawidek 			continue;
2586a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2587be26ba7cSPawel Jakub Dawidek 			continue;
2588a9aa06f7SJason A. Harmening 		unp->unp_gcrefs--;
2589a9aa06f7SJason A. Harmening 	}
2590a9aa06f7SJason A. Harmening }
2591a9aa06f7SJason A. Harmening 
2592a9aa06f7SJason A. Harmening static void
2593a9aa06f7SJason A. Harmening unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2594a9aa06f7SJason A. Harmening {
2595a9aa06f7SJason A. Harmening 	struct unpcb *unp;
2596a9aa06f7SJason A. Harmening 	struct file *fp;
2597a9aa06f7SJason A. Harmening 	int i;
2598a9aa06f7SJason A. Harmening 
2599a9aa06f7SJason A. Harmening 	/*
2600a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2601a9aa06f7SJason A. Harmening 	 */
2602a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2603a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2604a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2605a9aa06f7SJason A. Harmening 
2606a9aa06f7SJason A. Harmening 	for (i = 0; i < fdcount; i++) {
2607a9aa06f7SJason A. Harmening 		fp = fdep[i]->fde_file;
2608a9aa06f7SJason A. Harmening 		if ((unp = fptounp(fp)) == NULL)
2609a9aa06f7SJason A. Harmening 			continue;
2610a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2611a9aa06f7SJason A. Harmening 			continue;
2612a9aa06f7SJason A. Harmening 		unp->unp_gcrefs++;
2613397c19d1SJeff Roberson 		unp_marked++;
2614397c19d1SJeff Roberson 	}
2615be26ba7cSPawel Jakub Dawidek }
2616397c19d1SJeff Roberson 
2617397c19d1SJeff Roberson static void
2618a9aa06f7SJason A. Harmening unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2619397c19d1SJeff Roberson {
2620779f106aSGleb Smirnoff 	struct socket *so, *soa;
262160a5ef26SRobert Watson 
2622397c19d1SJeff Roberson 	so = unp->unp_socket;
2623779f106aSGleb Smirnoff 	SOCK_LOCK(so);
2624779f106aSGleb Smirnoff 	if (SOLISTENING(so)) {
2625397c19d1SJeff Roberson 		/*
2626397c19d1SJeff Roberson 		 * Mark all sockets in our accept queue.
2627397c19d1SJeff Roberson 		 */
2628779f106aSGleb Smirnoff 		TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2629779f106aSGleb Smirnoff 			if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
26300c40f353SConrad Meyer 				continue;
2631397c19d1SJeff Roberson 			SOCKBUF_LOCK(&soa->so_rcv);
2632a9aa06f7SJason A. Harmening 			unp_scan(soa->so_rcv.sb_mb, op);
2633397c19d1SJeff Roberson 			SOCKBUF_UNLOCK(&soa->so_rcv);
2634397c19d1SJeff Roberson 		}
2635779f106aSGleb Smirnoff 	} else {
2636779f106aSGleb Smirnoff 		/*
2637779f106aSGleb Smirnoff 		 * Mark all sockets we reference with RIGHTS.
2638779f106aSGleb Smirnoff 		 */
2639779f106aSGleb Smirnoff 		if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2640779f106aSGleb Smirnoff 			SOCKBUF_LOCK(&so->so_rcv);
2641a9aa06f7SJason A. Harmening 			unp_scan(so->so_rcv.sb_mb, op);
2642779f106aSGleb Smirnoff 			SOCKBUF_UNLOCK(&so->so_rcv);
2643779f106aSGleb Smirnoff 		}
2644779f106aSGleb Smirnoff 	}
2645779f106aSGleb Smirnoff 	SOCK_UNLOCK(so);
2646397c19d1SJeff Roberson }
2647a0ec558aSRobert Watson 
2648a0ec558aSRobert Watson static int unp_recycled;
2649be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2650be6b1304STom Rhodes     "Number of unreachable sockets claimed by the garbage collector.");
2651df8bae1dSRodney W. Grimes 
2652397c19d1SJeff Roberson static int unp_taskcount;
2653be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2654be6b1304STom Rhodes     "Number of times the garbage collector has run.");
2655397c19d1SJeff Roberson 
2656a9aa06f7SJason A. Harmening SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
2657a9aa06f7SJason A. Harmening     "Number of active local sockets.");
2658a9aa06f7SJason A. Harmening 
2659f708ef1bSPoul-Henning Kamp static void
2660a0ec558aSRobert Watson unp_gc(__unused void *arg, int pending)
2661df8bae1dSRodney W. Grimes {
266284d61770SRobert Watson 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
266384d61770SRobert Watson 				    NULL };
2664397c19d1SJeff Roberson 	struct unp_head **head;
2665a9aa06f7SJason A. Harmening 	struct unp_head unp_deadhead;	/* List of potentially-dead sockets. */
2666f7780c61SKonstantin Belousov 	struct file *f, **unref;
2667a9aa06f7SJason A. Harmening 	struct unpcb *unp, *unptmp;
2668a9aa06f7SJason A. Harmening 	int i, total, unp_unreachable;
2669df8bae1dSRodney W. Grimes 
2670a9aa06f7SJason A. Harmening 	LIST_INIT(&unp_deadhead);
2671a0ec558aSRobert Watson 	unp_taskcount++;
2672779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
2673ed5b7817SJulian Elischer 	/*
2674a9aa06f7SJason A. Harmening 	 * First determine which sockets may be in cycles.
2675ed5b7817SJulian Elischer 	 */
2676a9aa06f7SJason A. Harmening 	unp_unreachable = 0;
2677a9aa06f7SJason A. Harmening 
2678397c19d1SJeff Roberson 	for (head = heads; *head != NULL; head++)
2679a9aa06f7SJason A. Harmening 		LIST_FOREACH(unp, *head, unp_link) {
2680a9aa06f7SJason A. Harmening 			KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2681a9aa06f7SJason A. Harmening 			    ("%s: unp %p has unexpected gc flags 0x%x",
2682a9aa06f7SJason A. Harmening 			    __func__, unp, (unsigned int)unp->unp_gcflag));
2683a9aa06f7SJason A. Harmening 
2684a9aa06f7SJason A. Harmening 			f = unp->unp_file;
268560a5ef26SRobert Watson 
2686397c19d1SJeff Roberson 			/*
2687a9aa06f7SJason A. Harmening 			 * Check for an unreachable socket potentially in a
2688a9aa06f7SJason A. Harmening 			 * cycle.  It must be in a queue as indicated by
2689a9aa06f7SJason A. Harmening 			 * msgcount, and this must equal the file reference
2690a9aa06f7SJason A. Harmening 			 * count.  Note that when msgcount is 0 the file is
2691a9aa06f7SJason A. Harmening 			 * NULL.
2692a9aa06f7SJason A. Harmening 			 */
2693a9aa06f7SJason A. Harmening 			if (f != NULL && unp->unp_msgcount != 0 &&
26943c50616fSMateusz Guzik 			    refcount_load(&f->f_count) == unp->unp_msgcount) {
2695a9aa06f7SJason A. Harmening 				LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2696a9aa06f7SJason A. Harmening 				unp->unp_gcflag |= UNPGC_DEAD;
2697a9aa06f7SJason A. Harmening 				unp->unp_gcrefs = unp->unp_msgcount;
2698a9aa06f7SJason A. Harmening 				unp_unreachable++;
2699a9aa06f7SJason A. Harmening 			}
2700a9aa06f7SJason A. Harmening 		}
2701a9aa06f7SJason A. Harmening 
2702a9aa06f7SJason A. Harmening 	/*
2703a9aa06f7SJason A. Harmening 	 * Scan all sockets previously marked as potentially being in a cycle
2704a9aa06f7SJason A. Harmening 	 * and remove the references each socket holds on any UNPGC_DEAD
2705a9aa06f7SJason A. Harmening 	 * sockets in its queue.  After this step, all remaining references on
2706a9aa06f7SJason A. Harmening 	 * sockets marked UNPGC_DEAD should not be part of any cycle.
2707a9aa06f7SJason A. Harmening 	 */
2708a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead)
2709a9aa06f7SJason A. Harmening 		unp_gc_scan(unp, unp_remove_dead_ref);
2710a9aa06f7SJason A. Harmening 
2711a9aa06f7SJason A. Harmening 	/*
2712a9aa06f7SJason A. Harmening 	 * If a socket still has a non-negative refcount, it cannot be in a
2713a9aa06f7SJason A. Harmening 	 * cycle.  In this case increment refcount of all children iteratively.
2714397c19d1SJeff Roberson 	 * Stop the scan once we do a complete loop without discovering
2715397c19d1SJeff Roberson 	 * a new reachable socket.
2716397c19d1SJeff Roberson 	 */
2717df8bae1dSRodney W. Grimes 	do {
2718397c19d1SJeff Roberson 		unp_marked = 0;
2719a9aa06f7SJason A. Harmening 		LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
2720a9aa06f7SJason A. Harmening 			if (unp->unp_gcrefs > 0) {
2721a9aa06f7SJason A. Harmening 				unp->unp_gcflag &= ~UNPGC_DEAD;
2722a9aa06f7SJason A. Harmening 				LIST_REMOVE(unp, unp_dead);
2723a9aa06f7SJason A. Harmening 				KASSERT(unp_unreachable > 0,
2724a9aa06f7SJason A. Harmening 				    ("%s: unp_unreachable underflow.",
2725a9aa06f7SJason A. Harmening 				    __func__));
2726a9aa06f7SJason A. Harmening 				unp_unreachable--;
2727a9aa06f7SJason A. Harmening 				unp_gc_scan(unp, unp_restore_undead_ref);
2728a9aa06f7SJason A. Harmening 			}
2729397c19d1SJeff Roberson 	} while (unp_marked);
2730a9aa06f7SJason A. Harmening 
2731779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
2732a9aa06f7SJason A. Harmening 
2733397c19d1SJeff Roberson 	if (unp_unreachable == 0)
2734397c19d1SJeff Roberson 		return;
273560a5ef26SRobert Watson 
2736ed5b7817SJulian Elischer 	/*
2737a9aa06f7SJason A. Harmening 	 * Allocate space for a local array of dead unpcbs.
2738a9aa06f7SJason A. Harmening 	 * TODO: can this path be simplified by instead using the local
2739a9aa06f7SJason A. Harmening 	 * dead list at unp_deadhead, after taking out references
2740a9aa06f7SJason A. Harmening 	 * on the file object and/or unpcb and dropping the link lock?
2741ed5b7817SJulian Elischer 	 */
2742397c19d1SJeff Roberson 	unref = malloc(unp_unreachable * sizeof(struct file *),
2743397c19d1SJeff Roberson 	    M_TEMP, M_WAITOK);
274460a5ef26SRobert Watson 
2745ed5b7817SJulian Elischer 	/*
2746397c19d1SJeff Roberson 	 * Iterate looking for sockets which have been specifically marked
2747a9aa06f7SJason A. Harmening 	 * as unreachable and store them locally.
2748ed5b7817SJulian Elischer 	 */
2749f7780c61SKonstantin Belousov 	UNP_LINK_RLOCK();
2750a9aa06f7SJason A. Harmening 	total = 0;
2751a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
2752a9aa06f7SJason A. Harmening 		KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
2753a9aa06f7SJason A. Harmening 		    ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
2754a9aa06f7SJason A. Harmening 		unp->unp_gcflag &= ~UNPGC_DEAD;
2755f7780c61SKonstantin Belousov 		f = unp->unp_file;
2756f7780c61SKonstantin Belousov 		if (unp->unp_msgcount == 0 || f == NULL ||
27573c50616fSMateusz Guzik 		    refcount_load(&f->f_count) != unp->unp_msgcount ||
2758f1cf2b9dSKonstantin Belousov 		    !fhold(f))
2759f7780c61SKonstantin Belousov 			continue;
2760f7780c61SKonstantin Belousov 		unref[total++] = f;
2761f7780c61SKonstantin Belousov 		KASSERT(total <= unp_unreachable,
2762a9aa06f7SJason A. Harmening 		    ("%s: incorrect unreachable count.", __func__));
2763397c19d1SJeff Roberson 	}
2764f7780c61SKonstantin Belousov 	UNP_LINK_RUNLOCK();
276560a5ef26SRobert Watson 
2766ed5b7817SJulian Elischer 	/*
2767397c19d1SJeff Roberson 	 * Now flush all sockets, free'ing rights.  This will free the
2768397c19d1SJeff Roberson 	 * struct files associated with these sockets but leave each socket
2769397c19d1SJeff Roberson 	 * with one remaining ref.
2770ed5b7817SJulian Elischer 	 */
27711fb51a12SBjoern A. Zeeb 	for (i = 0; i < total; i++) {
27721fb51a12SBjoern A. Zeeb 		struct socket *so;
27731fb51a12SBjoern A. Zeeb 
27741fb51a12SBjoern A. Zeeb 		so = unref[i]->f_data;
27751fb51a12SBjoern A. Zeeb 		CURVNET_SET(so->so_vnet);
27761fb51a12SBjoern A. Zeeb 		sorflush(so);
27771fb51a12SBjoern A. Zeeb 		CURVNET_RESTORE();
27781fb51a12SBjoern A. Zeeb 	}
277960a5ef26SRobert Watson 
2780ed5b7817SJulian Elischer 	/*
2781397c19d1SJeff Roberson 	 * And finally release the sockets so they can be reclaimed.
2782ed5b7817SJulian Elischer 	 */
2783f7780c61SKonstantin Belousov 	for (i = 0; i < total; i++)
2784397c19d1SJeff Roberson 		fdrop(unref[i], NULL);
2785f7780c61SKonstantin Belousov 	unp_recycled += total;
2786397c19d1SJeff Roberson 	free(unref, M_TEMP);
2787df8bae1dSRodney W. Grimes }
2788df8bae1dSRodney W. Grimes 
27890b36cd25SRobert Watson static void
279099ab95dbSMark Johnston unp_dispose_mbuf(struct mbuf *m)
2791df8bae1dSRodney W. Grimes {
2792996c772fSJohn Dyson 
2793df8bae1dSRodney W. Grimes 	if (m)
2794be26ba7cSPawel Jakub Dawidek 		unp_scan(m, unp_freerights);
2795df8bae1dSRodney W. Grimes }
2796df8bae1dSRodney W. Grimes 
27970c40f353SConrad Meyer /*
27980c40f353SConrad Meyer  * Synchronize against unp_gc, which can trip over data as we are freeing it.
27990c40f353SConrad Meyer  */
28000c40f353SConrad Meyer static void
280199ab95dbSMark Johnston unp_dispose(struct socket *so)
28020c40f353SConrad Meyer {
28030c40f353SConrad Meyer 	struct unpcb *unp;
28040c40f353SConrad Meyer 
28050c40f353SConrad Meyer 	unp = sotounpcb(so);
2806779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
28070c40f353SConrad Meyer 	unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2808779f106aSGleb Smirnoff 	UNP_LINK_WUNLOCK();
2809779f106aSGleb Smirnoff 	if (!SOLISTENING(so))
281099ab95dbSMark Johnston 		unp_dispose_mbuf(so->so_rcv.sb_mb);
28110c40f353SConrad Meyer }
28120c40f353SConrad Meyer 
2813f708ef1bSPoul-Henning Kamp static void
2814be26ba7cSPawel Jakub Dawidek unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2815df8bae1dSRodney W. Grimes {
28162bc21ed9SDavid Malone 	struct mbuf *m;
28172bc21ed9SDavid Malone 	struct cmsghdr *cm;
28182bc21ed9SDavid Malone 	void *data;
28192bc21ed9SDavid Malone 	socklen_t clen, datalen;
2820df8bae1dSRodney W. Grimes 
2821fc3fcacfSRobert Watson 	while (m0 != NULL) {
28222bc21ed9SDavid Malone 		for (m = m0; m; m = m->m_next) {
282312396bdcSDavid Malone 			if (m->m_type != MT_CONTROL)
2824df8bae1dSRodney W. Grimes 				continue;
28252bc21ed9SDavid Malone 
28262bc21ed9SDavid Malone 			cm = mtod(m, struct cmsghdr *);
28272bc21ed9SDavid Malone 			clen = m->m_len;
28282bc21ed9SDavid Malone 
28292bc21ed9SDavid Malone 			while (cm != NULL) {
28302bc21ed9SDavid Malone 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
28312bc21ed9SDavid Malone 					break;
28322bc21ed9SDavid Malone 
28332bc21ed9SDavid Malone 				data = CMSG_DATA(cm);
28342bc21ed9SDavid Malone 				datalen = (caddr_t)cm + cm->cmsg_len
28352bc21ed9SDavid Malone 				    - (caddr_t)data;
28362bc21ed9SDavid Malone 
28372bc21ed9SDavid Malone 				if (cm->cmsg_level == SOL_SOCKET &&
28382bc21ed9SDavid Malone 				    cm->cmsg_type == SCM_RIGHTS) {
2839be26ba7cSPawel Jakub Dawidek 					(*op)(data, datalen /
2840be26ba7cSPawel Jakub Dawidek 					    sizeof(struct filedescent *));
28412bc21ed9SDavid Malone 				}
28422bc21ed9SDavid Malone 
28432bc21ed9SDavid Malone 				if (CMSG_SPACE(datalen) < clen) {
28442bc21ed9SDavid Malone 					clen -= CMSG_SPACE(datalen);
28452bc21ed9SDavid Malone 					cm = (struct cmsghdr *)
28462bc21ed9SDavid Malone 					    ((caddr_t)cm + CMSG_SPACE(datalen));
28472bc21ed9SDavid Malone 				} else {
28482bc21ed9SDavid Malone 					clen = 0;
28492bc21ed9SDavid Malone 					cm = NULL;
28502bc21ed9SDavid Malone 				}
28512bc21ed9SDavid Malone 			}
2852df8bae1dSRodney W. Grimes 		}
2853c29a3321SKevin Lo 		m0 = m0->m_nextpkt;
2854df8bae1dSRodney W. Grimes 	}
2855df8bae1dSRodney W. Grimes }
2856df8bae1dSRodney W. Grimes 
2857662c901cSMikolaj Golub /*
2858662c901cSMikolaj Golub  * A helper function called by VFS before socket-type vnode reclamation.
2859662c901cSMikolaj Golub  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2860662c901cSMikolaj Golub  * use count.
2861662c901cSMikolaj Golub  */
2862662c901cSMikolaj Golub void
2863662c901cSMikolaj Golub vfs_unp_reclaim(struct vnode *vp)
2864662c901cSMikolaj Golub {
2865662c901cSMikolaj Golub 	struct unpcb *unp;
2866662c901cSMikolaj Golub 	int active;
286775a67bf3SMatt Macy 	struct mtx *vplock;
2868662c901cSMikolaj Golub 
2869662c901cSMikolaj Golub 	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2870662c901cSMikolaj Golub 	KASSERT(vp->v_type == VSOCK,
2871662c901cSMikolaj Golub 	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2872662c901cSMikolaj Golub 
2873662c901cSMikolaj Golub 	active = 0;
287475a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
287575a67bf3SMatt Macy 	mtx_lock(vplock);
28760c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp);
2877662c901cSMikolaj Golub 	if (unp == NULL)
2878662c901cSMikolaj Golub 		goto done;
2879662c901cSMikolaj Golub 	UNP_PCB_LOCK(unp);
2880c7e41c8bSMikolaj Golub 	if (unp->unp_vnode == vp) {
2881c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
2882662c901cSMikolaj Golub 		unp->unp_vnode = NULL;
2883662c901cSMikolaj Golub 		active = 1;
2884662c901cSMikolaj Golub 	}
2885662c901cSMikolaj Golub 	UNP_PCB_UNLOCK(unp);
2886662c901cSMikolaj Golub  done:
288775a67bf3SMatt Macy 	mtx_unlock(vplock);
2888662c901cSMikolaj Golub 	if (active)
2889662c901cSMikolaj Golub 		vunref(vp);
2890662c901cSMikolaj Golub }
2891662c901cSMikolaj Golub 
289203c96c31SRobert Watson #ifdef DDB
289303c96c31SRobert Watson static void
289403c96c31SRobert Watson db_print_indent(int indent)
289503c96c31SRobert Watson {
289603c96c31SRobert Watson 	int i;
289703c96c31SRobert Watson 
289803c96c31SRobert Watson 	for (i = 0; i < indent; i++)
289903c96c31SRobert Watson 		db_printf(" ");
290003c96c31SRobert Watson }
290103c96c31SRobert Watson 
290203c96c31SRobert Watson static void
290303c96c31SRobert Watson db_print_unpflags(int unp_flags)
290403c96c31SRobert Watson {
290503c96c31SRobert Watson 	int comma;
290603c96c31SRobert Watson 
290703c96c31SRobert Watson 	comma = 0;
290803c96c31SRobert Watson 	if (unp_flags & UNP_HAVEPC) {
290903c96c31SRobert Watson 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
291003c96c31SRobert Watson 		comma = 1;
291103c96c31SRobert Watson 	}
29122de07e40SConrad Meyer 	if (unp_flags & UNP_WANTCRED_ALWAYS) {
29132de07e40SConrad Meyer 		db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
29142de07e40SConrad Meyer 		comma = 1;
29152de07e40SConrad Meyer 	}
29162de07e40SConrad Meyer 	if (unp_flags & UNP_WANTCRED_ONESHOT) {
29172de07e40SConrad Meyer 		db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
291803c96c31SRobert Watson 		comma = 1;
291903c96c31SRobert Watson 	}
292003c96c31SRobert Watson 	if (unp_flags & UNP_CONNWAIT) {
292103c96c31SRobert Watson 		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
292203c96c31SRobert Watson 		comma = 1;
292303c96c31SRobert Watson 	}
292403c96c31SRobert Watson 	if (unp_flags & UNP_CONNECTING) {
292503c96c31SRobert Watson 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
292603c96c31SRobert Watson 		comma = 1;
292703c96c31SRobert Watson 	}
292803c96c31SRobert Watson 	if (unp_flags & UNP_BINDING) {
292903c96c31SRobert Watson 		db_printf("%sUNP_BINDING", comma ? ", " : "");
293003c96c31SRobert Watson 		comma = 1;
293103c96c31SRobert Watson 	}
293203c96c31SRobert Watson }
293303c96c31SRobert Watson 
293403c96c31SRobert Watson static void
293503c96c31SRobert Watson db_print_xucred(int indent, struct xucred *xu)
293603c96c31SRobert Watson {
293703c96c31SRobert Watson 	int comma, i;
293803c96c31SRobert Watson 
293903c96c31SRobert Watson 	db_print_indent(indent);
2940c5afec6eSDmitry Chagin 	db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
2941c5afec6eSDmitry Chagin 	    xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
294203c96c31SRobert Watson 	db_print_indent(indent);
294303c96c31SRobert Watson 	db_printf("cr_groups: ");
294403c96c31SRobert Watson 	comma = 0;
294503c96c31SRobert Watson 	for (i = 0; i < xu->cr_ngroups; i++) {
294603c96c31SRobert Watson 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
294703c96c31SRobert Watson 		comma = 1;
294803c96c31SRobert Watson 	}
294903c96c31SRobert Watson 	db_printf("\n");
295003c96c31SRobert Watson }
295103c96c31SRobert Watson 
295203c96c31SRobert Watson static void
295303c96c31SRobert Watson db_print_unprefs(int indent, struct unp_head *uh)
295403c96c31SRobert Watson {
295503c96c31SRobert Watson 	struct unpcb *unp;
295603c96c31SRobert Watson 	int counter;
295703c96c31SRobert Watson 
295803c96c31SRobert Watson 	counter = 0;
295903c96c31SRobert Watson 	LIST_FOREACH(unp, uh, unp_reflink) {
296003c96c31SRobert Watson 		if (counter % 4 == 0)
296103c96c31SRobert Watson 			db_print_indent(indent);
296203c96c31SRobert Watson 		db_printf("%p  ", unp);
296303c96c31SRobert Watson 		if (counter % 4 == 3)
296403c96c31SRobert Watson 			db_printf("\n");
296503c96c31SRobert Watson 		counter++;
296603c96c31SRobert Watson 	}
296703c96c31SRobert Watson 	if (counter != 0 && counter % 4 != 0)
296803c96c31SRobert Watson 		db_printf("\n");
296903c96c31SRobert Watson }
297003c96c31SRobert Watson 
297103c96c31SRobert Watson DB_SHOW_COMMAND(unpcb, db_show_unpcb)
297203c96c31SRobert Watson {
297303c96c31SRobert Watson 	struct unpcb *unp;
297403c96c31SRobert Watson 
297503c96c31SRobert Watson         if (!have_addr) {
297603c96c31SRobert Watson                 db_printf("usage: show unpcb <addr>\n");
297703c96c31SRobert Watson                 return;
297803c96c31SRobert Watson         }
297903c96c31SRobert Watson         unp = (struct unpcb *)addr;
298003c96c31SRobert Watson 
298103c96c31SRobert Watson 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
298203c96c31SRobert Watson 	    unp->unp_vnode);
298303c96c31SRobert Watson 
2984fc8fdae0SMatthew D Fleming 	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
298503c96c31SRobert Watson 	    unp->unp_conn);
298603c96c31SRobert Watson 
298703c96c31SRobert Watson 	db_printf("unp_refs:\n");
298803c96c31SRobert Watson 	db_print_unprefs(2, &unp->unp_refs);
298903c96c31SRobert Watson 
299003c96c31SRobert Watson 	/* XXXRW: Would be nice to print the full address, if any. */
299103c96c31SRobert Watson 	db_printf("unp_addr: %p\n", unp->unp_addr);
299203c96c31SRobert Watson 
2993c2090e73SAlan Somers 	db_printf("unp_gencnt: %llu\n",
299403c96c31SRobert Watson 	    (unsigned long long)unp->unp_gencnt);
299503c96c31SRobert Watson 
299603c96c31SRobert Watson 	db_printf("unp_flags: %x (", unp->unp_flags);
299703c96c31SRobert Watson 	db_print_unpflags(unp->unp_flags);
299803c96c31SRobert Watson 	db_printf(")\n");
299903c96c31SRobert Watson 
300003c96c31SRobert Watson 	db_printf("unp_peercred:\n");
300103c96c31SRobert Watson 	db_print_xucred(2, &unp->unp_peercred);
300203c96c31SRobert Watson 
300303c96c31SRobert Watson 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
300403c96c31SRobert Watson }
300503c96c31SRobert Watson #endif
3006