xref: /freebsd/sys/kern/uipc_usrreq.c (revision 441eb16a953ac93d356e0cda28b45cb66ad70bcc)
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 *);
3115b950deaSRobert Watson static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *);
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;
385ccdadf1aSMark Johnston 	if (__predict_false(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,
431e4445a03SRobert Watson 	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
432e4445a03SRobert Watson 	.pr_ctloutput =		&uipc_ctloutput,
433fa9402f2SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_stream
434e4445a03SRobert Watson },
435e4445a03SRobert Watson {
436e4445a03SRobert Watson 	.pr_type =		SOCK_DGRAM,
437e4445a03SRobert Watson 	.pr_domain =		&localdomain,
438e4445a03SRobert Watson 	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS,
439aaf63435SGleb Smirnoff 	.pr_ctloutput =		&uipc_ctloutput,
440fa9402f2SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_dgram
441e4445a03SRobert Watson },
44284d61770SRobert Watson {
44384d61770SRobert Watson 	.pr_type =		SOCK_SEQPACKET,
44484d61770SRobert Watson 	.pr_domain =		&localdomain,
44584d61770SRobert Watson 
44684d61770SRobert Watson 	/*
44784d61770SRobert Watson 	 * XXXRW: For now, PR_ADDR because soreceive will bump into them
44884d61770SRobert Watson 	 * due to our use of sbappendaddr.  A new sbappend variants is needed
44984d61770SRobert Watson 	 * that supports both atomic record writes and control data.
45084d61770SRobert Watson 	 */
45184d61770SRobert Watson 	.pr_flags =		PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
45284d61770SRobert Watson 				    PR_RIGHTS,
453e0643280SGleb Smirnoff 	.pr_ctloutput =		&uipc_ctloutput,
45484d61770SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_seqpacket,
45584d61770SRobert Watson },
456e4445a03SRobert Watson };
457e4445a03SRobert Watson 
458e4445a03SRobert Watson static struct domain localdomain = {
459e4445a03SRobert Watson 	.dom_family =		AF_LOCAL,
460e4445a03SRobert Watson 	.dom_name =		"local",
461e4445a03SRobert Watson 	.dom_init =		unp_init,
462e4445a03SRobert Watson 	.dom_externalize =	unp_externalize,
46399ab95dbSMark Johnston 	.dom_dispose =		unp_dispose,
464e4445a03SRobert Watson 	.dom_protosw =		localsw,
46502abd400SPedro F. Giffuni 	.dom_protoswNPROTOSW =	&localsw[nitems(localsw)]
466e4445a03SRobert Watson };
467e4445a03SRobert Watson DOMAIN_SET(local);
468e4445a03SRobert Watson 
469ac45e92fSRobert Watson static void
470a29f300eSGarrett Wollman uipc_abort(struct socket *so)
471df8bae1dSRodney W. Grimes {
472e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
473df8bae1dSRodney W. Grimes 
47440f2ac28SRobert Watson 	unp = sotounpcb(so);
4754d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
47675a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
477e7c33e29SRobert Watson 
478e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
479e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
480e7c33e29SRobert Watson 	if (unp2 != NULL) {
48175a67bf3SMatt Macy 		unp_pcb_hold(unp2);
482e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
48375a67bf3SMatt Macy 		unp_drop(unp2);
48475a67bf3SMatt Macy 	} else
48575a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
486df8bae1dSRodney W. Grimes }
487df8bae1dSRodney W. Grimes 
488a29f300eSGarrett Wollman static int
48957bf258eSGarrett Wollman uipc_accept(struct socket *so, struct sockaddr **nam)
490a29f300eSGarrett Wollman {
491e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
4920d9ce3a1SRobert Watson 	const struct sockaddr *sa;
493df8bae1dSRodney W. Grimes 
494df8bae1dSRodney W. Grimes 	/*
4951c381b19SRobert Watson 	 * Pass back name of connected socket, if it was bound and we are
4961c381b19SRobert Watson 	 * still connected (our peer may have closed already!).
497df8bae1dSRodney W. Grimes 	 */
4984d4b555eSRobert Watson 	unp = sotounpcb(so);
4994d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
500e7c33e29SRobert Watson 
5010d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
50244800027SMark Johnston 	UNP_PCB_LOCK(unp);
50344800027SMark Johnston 	unp2 = unp_pcb_lock_peer(unp);
50444800027SMark Johnston 	if (unp2 != NULL && unp2->unp_addr != NULL)
505e7c33e29SRobert Watson 		sa = (struct sockaddr *)unp2->unp_addr;
50644800027SMark Johnston 	else
5070d9ce3a1SRobert Watson 		sa = &sun_noname;
5080d9ce3a1SRobert Watson 	bcopy(sa, *nam, sa->sa_len);
509b4e07e3dSMark Johnston 	if (unp2 != NULL)
51044800027SMark Johnston 		unp_pcb_unlock_pair(unp, unp2);
511b4e07e3dSMark Johnston 	else
512b4e07e3dSMark Johnston 		UNP_PCB_UNLOCK(unp);
513e5aeaa0cSDag-Erling Smørgrav 	return (0);
514a29f300eSGarrett Wollman }
515df8bae1dSRodney W. Grimes 
516a29f300eSGarrett Wollman static int
517b40ce416SJulian Elischer uipc_attach(struct socket *so, int proto, struct thread *td)
518a29f300eSGarrett Wollman {
519e7c33e29SRobert Watson 	u_long sendspace, recvspace;
5206d32873cSRobert Watson 	struct unpcb *unp;
5213dab55bcSRobert Watson 	int error;
522779f106aSGleb Smirnoff 	bool locked;
523df8bae1dSRodney W. Grimes 
5246d32873cSRobert Watson 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
5256d32873cSRobert Watson 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
5266d32873cSRobert Watson 		switch (so->so_type) {
5276d32873cSRobert Watson 		case SOCK_STREAM:
528e7c33e29SRobert Watson 			sendspace = unpst_sendspace;
529e7c33e29SRobert Watson 			recvspace = unpst_recvspace;
5306d32873cSRobert Watson 			break;
5316d32873cSRobert Watson 
5326d32873cSRobert Watson 		case SOCK_DGRAM:
533e7c33e29SRobert Watson 			sendspace = unpdg_sendspace;
534e7c33e29SRobert Watson 			recvspace = unpdg_recvspace;
5356d32873cSRobert Watson 			break;
5366d32873cSRobert Watson 
53784d61770SRobert Watson 		case SOCK_SEQPACKET:
53884d61770SRobert Watson 			sendspace = unpsp_sendspace;
53984d61770SRobert Watson 			recvspace = unpsp_recvspace;
54084d61770SRobert Watson 			break;
54184d61770SRobert Watson 
5426d32873cSRobert Watson 		default:
543e7c33e29SRobert Watson 			panic("uipc_attach");
5446d32873cSRobert Watson 		}
545e7c33e29SRobert Watson 		error = soreserve(so, sendspace, recvspace);
5466d32873cSRobert Watson 		if (error)
5476d32873cSRobert Watson 			return (error);
5486d32873cSRobert Watson 	}
54946a1d9bfSRobert Watson 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
5506d32873cSRobert Watson 	if (unp == NULL)
5516d32873cSRobert Watson 		return (ENOBUFS);
5526d32873cSRobert Watson 	LIST_INIT(&unp->unp_refs);
553e7c33e29SRobert Watson 	UNP_PCB_LOCK_INIT(unp);
5546d32873cSRobert Watson 	unp->unp_socket = so;
5556d32873cSRobert Watson 	so->so_pcb = unp;
5565362170dSMark Johnston 	refcount_init(&unp->unp_refcount, 1);
557e7c33e29SRobert Watson 
558779f106aSGleb Smirnoff 	if ((locked = UNP_LINK_WOWNED()) == false)
559779f106aSGleb Smirnoff 		UNP_LINK_WLOCK();
560779f106aSGleb Smirnoff 
5616d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
562f218ac50SMateusz Guzik 	unp->unp_ino = ++unp_ino;
5636d32873cSRobert Watson 	unp_count++;
56484d61770SRobert Watson 	switch (so->so_type) {
56584d61770SRobert Watson 	case SOCK_STREAM:
56684d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
56784d61770SRobert Watson 		break;
56884d61770SRobert Watson 
56984d61770SRobert Watson 	case SOCK_DGRAM:
57084d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
57184d61770SRobert Watson 		break;
57284d61770SRobert Watson 
57384d61770SRobert Watson 	case SOCK_SEQPACKET:
57484d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
57584d61770SRobert Watson 		break;
57684d61770SRobert Watson 
57784d61770SRobert Watson 	default:
57884d61770SRobert Watson 		panic("uipc_attach");
57984d61770SRobert Watson 	}
580779f106aSGleb Smirnoff 
581779f106aSGleb Smirnoff 	if (locked == false)
582779f106aSGleb Smirnoff 		UNP_LINK_WUNLOCK();
5836d32873cSRobert Watson 
5846d32873cSRobert Watson 	return (0);
585a29f300eSGarrett Wollman }
586a29f300eSGarrett Wollman 
587a29f300eSGarrett Wollman static int
5887493f24eSPawel Jakub Dawidek uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
589a29f300eSGarrett Wollman {
590dd47f5caSRobert Watson 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
591dd47f5caSRobert Watson 	struct vattr vattr;
5925050aa86SKonstantin Belousov 	int error, namelen;
593dd47f5caSRobert Watson 	struct nameidata nd;
59440f2ac28SRobert Watson 	struct unpcb *unp;
595dd47f5caSRobert Watson 	struct vnode *vp;
596dd47f5caSRobert Watson 	struct mount *mp;
5977008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
598dd47f5caSRobert Watson 	char *buf;
599a29f300eSGarrett Wollman 
600cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
601cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
602cb7df69bSKevin Lo 
60340f2ac28SRobert Watson 	unp = sotounpcb(so);
6044d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
6054f1f0ef5SRobert Watson 
606a06534c3SBjoern A. Zeeb 	if (soun->sun_len > sizeof(struct sockaddr_un))
607a06534c3SBjoern A. Zeeb 		return (EINVAL);
6084f1f0ef5SRobert Watson 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
6094f1f0ef5SRobert Watson 	if (namelen <= 0)
6104f1f0ef5SRobert Watson 		return (EINVAL);
611dd47f5caSRobert Watson 
612dd47f5caSRobert Watson 	/*
6134f1f0ef5SRobert Watson 	 * We don't allow simultaneous bind() calls on a single UNIX domain
6144f1f0ef5SRobert Watson 	 * socket, so flag in-progress operations, and return an error if an
6154f1f0ef5SRobert Watson 	 * operation is already in progress.
6164f1f0ef5SRobert Watson 	 *
6174f1f0ef5SRobert Watson 	 * Historically, we have not allowed a socket to be rebound, so this
618d7924b70SRobert Watson 	 * also returns an error.  Not allowing re-binding simplifies the
619d7924b70SRobert Watson 	 * implementation and avoids a great many possible failure modes.
620dd47f5caSRobert Watson 	 */
621e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
622dd47f5caSRobert Watson 	if (unp->unp_vnode != NULL) {
623e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
624dd47f5caSRobert Watson 		return (EINVAL);
625dd47f5caSRobert Watson 	}
6264f1f0ef5SRobert Watson 	if (unp->unp_flags & UNP_BINDING) {
627e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
6284f1f0ef5SRobert Watson 		return (EALREADY);
629dd47f5caSRobert Watson 	}
6304f1f0ef5SRobert Watson 	unp->unp_flags |= UNP_BINDING;
631e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
632dd47f5caSRobert Watson 
633dd47f5caSRobert Watson 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
6347928893dSEd Maste 	bcopy(soun->sun_path, buf, namelen);
6357928893dSEd Maste 	buf[namelen] = 0;
636dd47f5caSRobert Watson 
637dd47f5caSRobert Watson restart:
6386c21f6edSKonstantin Belousov 	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
6397008be5bSPawel Jakub Dawidek 	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
640dd47f5caSRobert Watson /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
641dd47f5caSRobert Watson 	error = namei(&nd);
642dd47f5caSRobert Watson 	if (error)
6434f1f0ef5SRobert Watson 		goto error;
644dd47f5caSRobert Watson 	vp = nd.ni_vp;
645dd47f5caSRobert Watson 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
646dd47f5caSRobert Watson 		NDFREE(&nd, NDF_ONLY_PNBUF);
647dd47f5caSRobert Watson 		if (nd.ni_dvp == vp)
648dd47f5caSRobert Watson 			vrele(nd.ni_dvp);
649dd47f5caSRobert Watson 		else
650dd47f5caSRobert Watson 			vput(nd.ni_dvp);
651dd47f5caSRobert Watson 		if (vp != NULL) {
652dd47f5caSRobert Watson 			vrele(vp);
653dd47f5caSRobert Watson 			error = EADDRINUSE;
6544f1f0ef5SRobert Watson 			goto error;
655dd47f5caSRobert Watson 		}
656dd47f5caSRobert Watson 		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
657dd47f5caSRobert Watson 		if (error)
6584f1f0ef5SRobert Watson 			goto error;
659dd47f5caSRobert Watson 		goto restart;
660dd47f5caSRobert Watson 	}
661dd47f5caSRobert Watson 	VATTR_NULL(&vattr);
662dd47f5caSRobert Watson 	vattr.va_type = VSOCK;
663dd47f5caSRobert Watson 	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
664dd47f5caSRobert Watson #ifdef MAC
66530d239bcSRobert Watson 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
666dd47f5caSRobert Watson 	    &vattr);
667dd47f5caSRobert Watson #endif
668885868cdSRobert Watson 	if (error == 0)
669dd47f5caSRobert Watson 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
670dd47f5caSRobert Watson 	NDFREE(&nd, NDF_ONLY_PNBUF);
671dd47f5caSRobert Watson 	vput(nd.ni_dvp);
672dd47f5caSRobert Watson 	if (error) {
673dd47f5caSRobert Watson 		vn_finished_write(mp);
674*441eb16aSKonstantin Belousov 		if (error == ERELOOKUP)
675*441eb16aSKonstantin Belousov 			goto restart;
6764f1f0ef5SRobert Watson 		goto error;
677dd47f5caSRobert Watson 	}
678dd47f5caSRobert Watson 	vp = nd.ni_vp;
67957fd3d55SPawel Jakub Dawidek 	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
680dd47f5caSRobert Watson 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
681e7c33e29SRobert Watson 
682e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6830c3c207fSGleb Smirnoff 	VOP_UNP_BIND(vp, unp);
684dd47f5caSRobert Watson 	unp->unp_vnode = vp;
685dd47f5caSRobert Watson 	unp->unp_addr = soun;
6864f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
687e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
688b249ce48SMateusz Guzik 	VOP_UNLOCK(vp);
689dd47f5caSRobert Watson 	vn_finished_write(mp);
6904f1f0ef5SRobert Watson 	free(buf, M_TEMP);
6914f1f0ef5SRobert Watson 	return (0);
692e7c33e29SRobert Watson 
6934f1f0ef5SRobert Watson error:
694e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6954f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
696e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
697dd47f5caSRobert Watson 	free(buf, M_TEMP);
69840f2ac28SRobert Watson 	return (error);
699a29f300eSGarrett Wollman }
700a29f300eSGarrett Wollman 
701a29f300eSGarrett Wollman static int
7027493f24eSPawel Jakub Dawidek uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
7037493f24eSPawel Jakub Dawidek {
7047493f24eSPawel Jakub Dawidek 
7057493f24eSPawel Jakub Dawidek 	return (uipc_bindat(AT_FDCWD, so, nam, td));
7067493f24eSPawel Jakub Dawidek }
7077493f24eSPawel Jakub Dawidek 
7087493f24eSPawel Jakub Dawidek static int
709b40ce416SJulian Elischer uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
710a29f300eSGarrett Wollman {
7110d9ce3a1SRobert Watson 	int error;
712a29f300eSGarrett Wollman 
713fd179ee9SRobert Watson 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
714fd179ee9SRobert Watson 	error = unp_connect(so, nam, td);
7150d9ce3a1SRobert Watson 	return (error);
716a29f300eSGarrett Wollman }
717a29f300eSGarrett Wollman 
7187493f24eSPawel Jakub Dawidek static int
7197493f24eSPawel Jakub Dawidek uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
7207493f24eSPawel Jakub Dawidek     struct thread *td)
7217493f24eSPawel Jakub Dawidek {
7227493f24eSPawel Jakub Dawidek 	int error;
7237493f24eSPawel Jakub Dawidek 
7247493f24eSPawel Jakub Dawidek 	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
7257493f24eSPawel Jakub Dawidek 	error = unp_connectat(fd, so, nam, td);
7267493f24eSPawel Jakub Dawidek 	return (error);
7277493f24eSPawel Jakub Dawidek }
7287493f24eSPawel Jakub Dawidek 
729a152f8a3SRobert Watson static void
730a152f8a3SRobert Watson uipc_close(struct socket *so)
731a152f8a3SRobert Watson {
732e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
733779f106aSGleb Smirnoff 	struct vnode *vp = NULL;
73475a67bf3SMatt Macy 	struct mtx *vplock;
735ccdadf1aSMark Johnston 
736a152f8a3SRobert Watson 	unp = sotounpcb(so);
737a152f8a3SRobert Watson 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
738e7c33e29SRobert Watson 
73975a67bf3SMatt Macy 	vplock = NULL;
74075a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
74175a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
74275a67bf3SMatt Macy 		mtx_lock(vplock);
743e7c33e29SRobert Watson 	}
74475a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
74575a67bf3SMatt Macy 	if (vp && unp->unp_vnode == NULL) {
74675a67bf3SMatt Macy 		mtx_unlock(vplock);
74775a67bf3SMatt Macy 		vp = NULL;
74875a67bf3SMatt Macy 	}
74975a67bf3SMatt Macy 	if (vp != NULL) {
750779f106aSGleb Smirnoff 		VOP_UNP_DETACH(vp);
751779f106aSGleb Smirnoff 		unp->unp_vnode = NULL;
752779f106aSGleb Smirnoff 	}
753ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
754acf9fd05SMatt Macy 		unp_disconnect(unp, unp2);
755ccdadf1aSMark Johnston 	else
756e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
75775a67bf3SMatt Macy 	if (vp) {
75875a67bf3SMatt Macy 		mtx_unlock(vplock);
759779f106aSGleb Smirnoff 		vrele(vp);
760a152f8a3SRobert Watson 	}
76175a67bf3SMatt Macy }
762a152f8a3SRobert Watson 
7632c899584SRobert Watson static int
764a29f300eSGarrett Wollman uipc_connect2(struct socket *so1, struct socket *so2)
765a29f300eSGarrett Wollman {
766e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
7670d9ce3a1SRobert Watson 	int error;
768a29f300eSGarrett Wollman 
769e7c33e29SRobert Watson 	unp = so1->so_pcb;
7704d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
771e7c33e29SRobert Watson 	unp2 = so2->so_pcb;
772e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
7734820bf6aSMark Johnston 	unp_pcb_lock_pair(unp, unp2);
7746a2989fdSMatthew N. Dodd 	error = unp_connect2(so1, so2, PRU_CONNECT2);
7754820bf6aSMark Johnston 	unp_pcb_unlock_pair(unp, unp2);
7760d9ce3a1SRobert Watson 	return (error);
777a29f300eSGarrett Wollman }
778a29f300eSGarrett Wollman 
779bc725eafSRobert Watson static void
780a29f300eSGarrett Wollman uipc_detach(struct socket *so)
781a29f300eSGarrett Wollman {
782e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
78375a67bf3SMatt Macy 	struct mtx *vplock;
7846d32873cSRobert Watson 	struct vnode *vp;
785ccdadf1aSMark Johnston 	int local_unp_rights;
786a29f300eSGarrett Wollman 
78740f2ac28SRobert Watson 	unp = sotounpcb(so);
7884d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
789e7c33e29SRobert Watson 
790434ac8b6SMark Johnston 	vp = NULL;
791c0874c34SMatt Macy 	vplock = NULL;
792434ac8b6SMark Johnston 
793a50b1900SMark Johnston 	SOCK_LOCK(so);
794a50b1900SMark Johnston 	if (!SOLISTENING(so)) {
795a50b1900SMark Johnston 		/*
796a50b1900SMark Johnston 		 * Once the socket is removed from the global lists,
797a50b1900SMark Johnston 		 * uipc_ready() will not be able to locate its socket buffer, so
798a50b1900SMark Johnston 		 * clear the buffer now.  At this point internalized rights have
799a50b1900SMark Johnston 		 * already been disposed of.
800a50b1900SMark Johnston 		 */
801a50b1900SMark Johnston 		sbrelease(&so->so_rcv, so);
802a50b1900SMark Johnston 	}
803a50b1900SMark Johnston 	SOCK_UNLOCK(so);
804a50b1900SMark Johnston 
805779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
8066d32873cSRobert Watson 	LIST_REMOVE(unp, unp_link);
807a9aa06f7SJason A. Harmening 	if (unp->unp_gcflag & UNPGC_DEAD)
808a9aa06f7SJason A. Harmening 		LIST_REMOVE(unp, unp_dead);
8096d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
8106d32873cSRobert Watson 	--unp_count;
81175a67bf3SMatt Macy 	UNP_LINK_WUNLOCK();
812434ac8b6SMark Johnston 
81375a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
81475a67bf3SMatt Macy  restart:
81575a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
81675a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
81775a67bf3SMatt Macy 		mtx_lock(vplock);
81875a67bf3SMatt Macy 	}
81975a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
820db38b699SMark Johnston 	if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
821c0874c34SMatt Macy 		if (vplock)
82275a67bf3SMatt Macy 			mtx_unlock(vplock);
82375a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
82475a67bf3SMatt Macy 		goto restart;
82575a67bf3SMatt Macy 	}
8266d32873cSRobert Watson 	if ((vp = unp->unp_vnode) != NULL) {
827c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
8286d32873cSRobert Watson 		unp->unp_vnode = NULL;
8296d32873cSRobert Watson 	}
830ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
831e7c33e29SRobert Watson 		unp_disconnect(unp, unp2);
832f0317f86SMark Johnston 	else
83375a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
834ccdadf1aSMark Johnston 
83575a67bf3SMatt Macy 	UNP_REF_LIST_LOCK();
8366d32873cSRobert Watson 	while (!LIST_EMPTY(&unp->unp_refs)) {
8376d32873cSRobert Watson 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
838e7c33e29SRobert Watson 
83975a67bf3SMatt Macy 		unp_pcb_hold(ref);
84075a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
84175a67bf3SMatt Macy 
84275a67bf3SMatt Macy 		MPASS(ref != unp);
84375a67bf3SMatt Macy 		UNP_PCB_UNLOCK_ASSERT(ref);
844afc055d9SEd Schouten 		unp_drop(ref);
84575a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
8466d32873cSRobert Watson 	}
84775a67bf3SMatt Macy 	UNP_REF_LIST_UNLOCK();
848ccdadf1aSMark Johnston 
84975a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
850397c19d1SJeff Roberson 	local_unp_rights = unp_rights;
8516d32873cSRobert Watson 	unp->unp_socket->so_pcb = NULL;
85275a67bf3SMatt Macy 	unp->unp_socket = NULL;
853db38b699SMark Johnston 	free(unp->unp_addr, M_SONAME);
854db38b699SMark Johnston 	unp->unp_addr = NULL;
855db38b699SMark Johnston 	if (!unp_pcb_rele(unp))
8566e2faa24SRobert Watson 		UNP_PCB_UNLOCK(unp);
85775a67bf3SMatt Macy 	if (vp) {
85875a67bf3SMatt Macy 		mtx_unlock(vplock);
8596d32873cSRobert Watson 		vrele(vp);
86075a67bf3SMatt Macy 	}
8616d32873cSRobert Watson 	if (local_unp_rights)
862daee0f0bSKonstantin Belousov 		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
863a29f300eSGarrett Wollman }
864a29f300eSGarrett Wollman 
865a29f300eSGarrett Wollman static int
866a29f300eSGarrett Wollman uipc_disconnect(struct socket *so)
867a29f300eSGarrett Wollman {
868e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
869a29f300eSGarrett Wollman 
87040f2ac28SRobert Watson 	unp = sotounpcb(so);
8714d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
872e7c33e29SRobert Watson 
873e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
874ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
87575a67bf3SMatt Macy 		unp_disconnect(unp, unp2);
876ccdadf1aSMark Johnston 	else
877ccdadf1aSMark Johnston 		UNP_PCB_UNLOCK(unp);
878e5aeaa0cSDag-Erling Smørgrav 	return (0);
879a29f300eSGarrett Wollman }
880a29f300eSGarrett Wollman 
881a29f300eSGarrett Wollman static int
882d374e81eSRobert Watson uipc_listen(struct socket *so, int backlog, struct thread *td)
883a29f300eSGarrett Wollman {
88440f2ac28SRobert Watson 	struct unpcb *unp;
8850d9ce3a1SRobert Watson 	int error;
886a29f300eSGarrett Wollman 
887beb4b312SGleb Smirnoff 	if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
888beb4b312SGleb Smirnoff 		return (EOPNOTSUPP);
889beb4b312SGleb Smirnoff 
89040f2ac28SRobert Watson 	unp = sotounpcb(so);
8914d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
892e7c33e29SRobert Watson 
893e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
8944d4b555eSRobert Watson 	if (unp->unp_vnode == NULL) {
89547a84387SEd Schouten 		/* Already connected or not bound to an address. */
89647a84387SEd Schouten 		error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
897e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
89847a84387SEd Schouten 		return (error);
89940f2ac28SRobert Watson 	}
900e7c33e29SRobert Watson 
901e7c33e29SRobert Watson 	SOCK_LOCK(so);
902e7c33e29SRobert Watson 	error = solisten_proto_check(so);
903e7c33e29SRobert Watson 	if (error == 0) {
904c5afec6eSDmitry Chagin 		cru2xt(td, &unp->unp_peercred);
905e7c33e29SRobert Watson 		solisten_proto(so, backlog);
906e7c33e29SRobert Watson 	}
907e7c33e29SRobert Watson 	SOCK_UNLOCK(so);
908e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
9090d9ce3a1SRobert Watson 	return (error);
910a29f300eSGarrett Wollman }
911a29f300eSGarrett Wollman 
912a29f300eSGarrett Wollman static int
91357bf258eSGarrett Wollman uipc_peeraddr(struct socket *so, struct sockaddr **nam)
914a29f300eSGarrett Wollman {
915e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
9160d9ce3a1SRobert Watson 	const struct sockaddr *sa;
917a29f300eSGarrett Wollman 
9184d4b555eSRobert Watson 	unp = sotounpcb(so);
9194d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
920e7c33e29SRobert Watson 
9210d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
922afd9f91cSJohn Baldwin 	UNP_LINK_RLOCK();
923bdc5f6a3SHajimu UMEMOTO 	/*
924e7c33e29SRobert Watson 	 * XXX: It seems that this test always fails even when connection is
925e7c33e29SRobert Watson 	 * established.  So, this else clause is added as workaround to
926e7c33e29SRobert Watson 	 * return PF_LOCAL sockaddr.
927bdc5f6a3SHajimu UMEMOTO 	 */
928e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
929e7c33e29SRobert Watson 	if (unp2 != NULL) {
930e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp2);
931e7c33e29SRobert Watson 		if (unp2->unp_addr != NULL)
932afd9f91cSJohn Baldwin 			sa = (struct sockaddr *) unp2->unp_addr;
933e7c33e29SRobert Watson 		else
9340d9ce3a1SRobert Watson 			sa = &sun_noname;
9350d9ce3a1SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
936e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
937e7c33e29SRobert Watson 	} else {
938e7c33e29SRobert Watson 		sa = &sun_noname;
939e7c33e29SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
940e7c33e29SRobert Watson 	}
941afd9f91cSJohn Baldwin 	UNP_LINK_RUNLOCK();
942e5aeaa0cSDag-Erling Smørgrav 	return (0);
943a29f300eSGarrett Wollman }
944a29f300eSGarrett Wollman 
945a29f300eSGarrett Wollman static int
946a29f300eSGarrett Wollman uipc_rcvd(struct socket *so, int flags)
947a29f300eSGarrett Wollman {
948e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
949a29f300eSGarrett Wollman 	struct socket *so2;
950337cc6b6SRobert Watson 	u_int mbcnt, sbcc;
951a29f300eSGarrett Wollman 
95240f2ac28SRobert Watson 	unp = sotounpcb(so);
9532b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
9542b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
9552b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
956e7c33e29SRobert Watson 
957df8bae1dSRodney W. Grimes 	/*
958e7c33e29SRobert Watson 	 * Adjust backpressure on sender and wakeup any waiting to write.
959e7c33e29SRobert Watson 	 *
960d7924b70SRobert Watson 	 * The unp lock is acquired to maintain the validity of the unp_conn
961d7924b70SRobert Watson 	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
962d7924b70SRobert Watson 	 * static as long as we don't permit unp2 to disconnect from unp,
963d7924b70SRobert Watson 	 * which is prevented by the lock on unp.  We cache values from
964d7924b70SRobert Watson 	 * so_rcv to avoid holding the so_rcv lock over the entire
965d7924b70SRobert Watson 	 * transaction on the remote so_snd.
966df8bae1dSRodney W. Grimes 	 */
967337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so->so_rcv);
968337cc6b6SRobert Watson 	mbcnt = so->so_rcv.sb_mbcnt;
9692b21d0e8SGleb Smirnoff 	sbcc = sbavail(&so->so_rcv);
970337cc6b6SRobert Watson 	SOCKBUF_UNLOCK(&so->so_rcv);
971c2090e73SAlan Somers 	/*
972c2090e73SAlan Somers 	 * There is a benign race condition at this point.  If we're planning to
973c2090e73SAlan Somers 	 * clear SB_STOP, but uipc_send is called on the connected socket at
974c2090e73SAlan Somers 	 * this instant, it might add data to the sockbuf and set SB_STOP.  Then
975c2090e73SAlan Somers 	 * we would erroneously clear SB_STOP below, even though the sockbuf is
976c2090e73SAlan Somers 	 * full.  The race is benign because the only ill effect is to allow the
977c2090e73SAlan Somers 	 * sockbuf to exceed its size limit, and the size limits are not
978c2090e73SAlan Somers 	 * strictly guaranteed anyway.
979c2090e73SAlan Somers 	 */
980e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
981e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
982e7c33e29SRobert Watson 	if (unp2 == NULL) {
983e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
984e7c33e29SRobert Watson 		return (0);
985337cc6b6SRobert Watson 	}
986e7c33e29SRobert Watson 	so2 = unp2->unp_socket;
987337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so2->so_snd);
988c2090e73SAlan Somers 	if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
989c2090e73SAlan Somers 		so2->so_snd.sb_flags &= ~SB_STOP;
9901e4d7da7SRobert Watson 	sowwakeup_locked(so2);
991e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
992e5aeaa0cSDag-Erling Smørgrav 	return (0);
993a29f300eSGarrett Wollman }
994df8bae1dSRodney W. Grimes 
995a29f300eSGarrett Wollman static int
99657bf258eSGarrett Wollman uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
997b40ce416SJulian Elischer     struct mbuf *control, struct thread *td)
998a29f300eSGarrett Wollman {
999f3f49bbbSRobert Watson 	struct unpcb *unp, *unp2;
1000a29f300eSGarrett Wollman 	struct socket *so2;
1001c2090e73SAlan Somers 	u_int mbcnt, sbcc;
100275a67bf3SMatt Macy 	int freed, error;
1003a29f300eSGarrett Wollman 
100440f2ac28SRobert Watson 	unp = sotounpcb(so);
10052b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
10062b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
10072b21d0e8SGleb Smirnoff 	    so->so_type == SOCK_SEQPACKET,
10082b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
1009e7c33e29SRobert Watson 
101075a67bf3SMatt Macy 	freed = error = 0;
1011a29f300eSGarrett Wollman 	if (flags & PRUS_OOB) {
1012a29f300eSGarrett Wollman 		error = EOPNOTSUPP;
1013a29f300eSGarrett Wollman 		goto release;
1014a29f300eSGarrett Wollman 	}
1015fc3fcacfSRobert Watson 	if (control != NULL && (error = unp_internalize(&control, td)))
1016a29f300eSGarrett Wollman 		goto release;
101775a67bf3SMatt Macy 
101875a67bf3SMatt Macy 	unp2 = NULL;
1019a29f300eSGarrett Wollman 	switch (so->so_type) {
1020a29f300eSGarrett Wollman 	case SOCK_DGRAM:
1021a29f300eSGarrett Wollman 	{
1022e7dd9a10SRobert Watson 		const struct sockaddr *from;
1023df8bae1dSRodney W. Grimes 
1024fc3fcacfSRobert Watson 		if (nam != NULL) {
1025ccdadf1aSMark Johnston 			error = unp_connect(so, nam, td);
1026ccdadf1aSMark Johnston 			if (error != 0)
1027df8bae1dSRodney W. Grimes 				break;
1028ccdadf1aSMark Johnston 		}
102975a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
103060a5ef26SRobert Watson 
1031b5ff0914SRobert Watson 		/*
1032b5ff0914SRobert Watson 		 * Because connect() and send() are non-atomic in a sendto()
1033b5ff0914SRobert Watson 		 * with a target address, it's possible that the socket will
1034b5ff0914SRobert Watson 		 * have disconnected before the send() can run.  In that case
1035b5ff0914SRobert Watson 		 * return the slightly counter-intuitive but otherwise
1036b5ff0914SRobert Watson 		 * correct error that the socket is not connected.
1037b5ff0914SRobert Watson 		 */
1038ccdadf1aSMark Johnston 		unp2 = unp_pcb_lock_peer(unp);
1039ccdadf1aSMark Johnston 		if (unp2 == NULL) {
104075a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
1041b5ff0914SRobert Watson 			error = ENOTCONN;
1042b5ff0914SRobert Watson 			break;
1043b5ff0914SRobert Watson 		}
1044ccdadf1aSMark Johnston 
10452de07e40SConrad Meyer 		if (unp2->unp_flags & UNP_WANTCRED_MASK)
1046ede6e136SRobert Watson 			control = unp_addsockcred(td, control);
1047fc3fcacfSRobert Watson 		if (unp->unp_addr != NULL)
104857bf258eSGarrett Wollman 			from = (struct sockaddr *)unp->unp_addr;
1049df8bae1dSRodney W. Grimes 		else
1050df8bae1dSRodney W. Grimes 			from = &sun_noname;
1051ede6e136SRobert Watson 		so2 = unp2->unp_socket;
1052a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
10536dde7ecbSPeter Wemm 		if (sbappendaddr_locked(&so2->so_rcv, from, m,
10548de34a88SAlan Somers 		    control)) {
10551e4d7da7SRobert Watson 			sorwakeup_locked(so2);
1056fc3fcacfSRobert Watson 			m = NULL;
1057fc3fcacfSRobert Watson 			control = NULL;
1058e5aeaa0cSDag-Erling Smørgrav 		} else {
1059a34b7046SRobert Watson 			SOCKBUF_UNLOCK(&so2->so_rcv);
1060df8bae1dSRodney W. Grimes 			error = ENOBUFS;
1061e5aeaa0cSDag-Erling Smørgrav 		}
106275a67bf3SMatt Macy 		if (nam != NULL)
1063e7c33e29SRobert Watson 			unp_disconnect(unp, unp2);
1064f0317f86SMark Johnston 		else
1065f0317f86SMark Johnston 			unp_pcb_unlock_pair(unp, unp2);
1066df8bae1dSRodney W. Grimes 		break;
1067df8bae1dSRodney W. Grimes 	}
1068df8bae1dSRodney W. Grimes 
106984d61770SRobert Watson 	case SOCK_SEQPACKET:
1070df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
1071402cc72dSDavid Greenman 		if ((so->so_state & SS_ISCONNECTED) == 0) {
1072fc3fcacfSRobert Watson 			if (nam != NULL) {
1073ccdadf1aSMark Johnston 				error = unp_connect(so, nam, td);
1074b36871afSMark Johnston 				if (error != 0)
107575a67bf3SMatt Macy 					break;
1076402cc72dSDavid Greenman 			} else {
1077402cc72dSDavid Greenman 				error = ENOTCONN;
1078402cc72dSDavid Greenman 				break;
1079402cc72dSDavid Greenman 			}
1080b36871afSMark Johnston 		}
1081b36871afSMark Johnston 
1082ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp);
1083ccdadf1aSMark Johnston 		if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
108475a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
1085b5ff0914SRobert Watson 			error = ENOTCONN;
1086b5ff0914SRobert Watson 			break;
1087b36871afSMark Johnston 		} else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1088ccdadf1aSMark Johnston 			unp_pcb_unlock_pair(unp, unp2);
1089b36871afSMark Johnston 			error = EPIPE;
1090b36871afSMark Johnston 			break;
109175a67bf3SMatt Macy 		}
109275a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
109375a67bf3SMatt Macy 		if ((so2 = unp2->unp_socket) == NULL) {
109475a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp2);
109575a67bf3SMatt Macy 			error = ENOTCONN;
109675a67bf3SMatt Macy 			break;
109775a67bf3SMatt Macy 		}
1098a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
10992de07e40SConrad Meyer 		if (unp2->unp_flags & UNP_WANTCRED_MASK) {
11006a2989fdSMatthew N. Dodd 			/*
11012de07e40SConrad Meyer 			 * Credentials are passed only once on SOCK_STREAM and
11022de07e40SConrad Meyer 			 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
11032de07e40SConrad Meyer 			 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
11046a2989fdSMatthew N. Dodd 			 */
11052de07e40SConrad Meyer 			unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
11066a2989fdSMatthew N. Dodd 			control = unp_addsockcred(td, control);
11076a2989fdSMatthew N. Dodd 		}
11085b0480f2SMark Johnston 
1109df8bae1dSRodney W. Grimes 		/*
11105b0480f2SMark Johnston 		 * Send to paired receive port and wake up readers.  Don't
11115b0480f2SMark Johnston 		 * check for space available in the receive buffer if we're
11125b0480f2SMark Johnston 		 * attaching ancillary data; Unix domain sockets only check
11135b0480f2SMark Johnston 		 * for space in the sending sockbuf, and that check is
11145b0480f2SMark Johnston 		 * performed one level up the stack.  At that level we cannot
11155b0480f2SMark Johnston 		 * precisely account for the amount of buffer space used
11165b0480f2SMark Johnston 		 * (e.g., because control messages are not yet internalized).
1117df8bae1dSRodney W. Grimes 		 */
111884d61770SRobert Watson 		switch (so->so_type) {
111984d61770SRobert Watson 		case SOCK_STREAM:
1120fc3fcacfSRobert Watson 			if (control != NULL) {
11215b0480f2SMark Johnston 				sbappendcontrol_locked(&so2->so_rcv, m,
112225f4ddfbSMark Johnston 				    control, flags);
1123fc3fcacfSRobert Watson 				control = NULL;
1124e7c33e29SRobert Watson 			} else
1125829fae90SGleb Smirnoff 				sbappend_locked(&so2->so_rcv, m, flags);
112684d61770SRobert Watson 			break;
112784d61770SRobert Watson 
1128b36871afSMark Johnston 		case SOCK_SEQPACKET:
11298de34a88SAlan Somers 			if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1130b36871afSMark Johnston 			    &sun_noname, m, control))
113184d61770SRobert Watson 				control = NULL;
113284d61770SRobert Watson 			break;
113384d61770SRobert Watson 		}
113484d61770SRobert Watson 
1135c2090e73SAlan Somers 		mbcnt = so2->so_rcv.sb_mbcnt;
11362b21d0e8SGleb Smirnoff 		sbcc = sbavail(&so2->so_rcv);
11372b21d0e8SGleb Smirnoff 		if (sbcc)
1138337cc6b6SRobert Watson 			sorwakeup_locked(so2);
11392b21d0e8SGleb Smirnoff 		else
11402b21d0e8SGleb Smirnoff 			SOCKBUF_UNLOCK(&so2->so_rcv);
1141337cc6b6SRobert Watson 
1142c2090e73SAlan Somers 		/*
1143c2090e73SAlan Somers 		 * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1144c2090e73SAlan Somers 		 * it would be possible for uipc_rcvd to be called at this
1145c2090e73SAlan Somers 		 * point, drain the receiving sockbuf, clear SB_STOP, and then
1146c2090e73SAlan Somers 		 * we would set SB_STOP below.  That could lead to an empty
1147c2090e73SAlan Somers 		 * sockbuf having SB_STOP set
1148c2090e73SAlan Somers 		 */
1149337cc6b6SRobert Watson 		SOCKBUF_LOCK(&so->so_snd);
1150c2090e73SAlan Somers 		if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1151c2090e73SAlan Somers 			so->so_snd.sb_flags |= SB_STOP;
11527abe2ac2SAlan Cox 		SOCKBUF_UNLOCK(&so->so_snd);
1153e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1154fc3fcacfSRobert Watson 		m = NULL;
1155df8bae1dSRodney W. Grimes 		break;
1156df8bae1dSRodney W. Grimes 	}
1157a29f300eSGarrett Wollman 
11586b8fda4dSGarrett Wollman 	/*
115960a5ef26SRobert Watson 	 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
11606b8fda4dSGarrett Wollman 	 */
1161a29f300eSGarrett Wollman 	if (flags & PRUS_EOF) {
1162ede6e136SRobert Watson 		UNP_PCB_LOCK(unp);
11636b8fda4dSGarrett Wollman 		socantsendmore(so);
11646b8fda4dSGarrett Wollman 		unp_shutdown(unp);
1165e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
1166ede6e136SRobert Watson 	}
1167fc3fcacfSRobert Watson 	if (control != NULL && error != 0)
116899ab95dbSMark Johnston 		unp_dispose_mbuf(control);
1169bd508d39SDon Lewis 
1170a29f300eSGarrett Wollman release:
1171fc3fcacfSRobert Watson 	if (control != NULL)
1172a29f300eSGarrett Wollman 		m_freem(control);
1173100db364SGleb Smirnoff 	/*
1174100db364SGleb Smirnoff 	 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1175100db364SGleb Smirnoff 	 * for freeing memory.
1176100db364SGleb Smirnoff 	 */
1177100db364SGleb Smirnoff 	if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1178a29f300eSGarrett Wollman 		m_freem(m);
1179e5aeaa0cSDag-Erling Smørgrav 	return (error);
1180a29f300eSGarrett Wollman }
1181df8bae1dSRodney W. Grimes 
1182a50b1900SMark Johnston static bool
1183a50b1900SMark Johnston uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1184a50b1900SMark Johnston {
1185a50b1900SMark Johnston 	struct mbuf *mb, *n;
1186a50b1900SMark Johnston 	struct sockbuf *sb;
1187a50b1900SMark Johnston 
1188a50b1900SMark Johnston 	SOCK_LOCK(so);
1189a50b1900SMark Johnston 	if (SOLISTENING(so)) {
1190a50b1900SMark Johnston 		SOCK_UNLOCK(so);
1191a50b1900SMark Johnston 		return (false);
1192a50b1900SMark Johnston 	}
1193a50b1900SMark Johnston 	mb = NULL;
1194a50b1900SMark Johnston 	sb = &so->so_rcv;
1195a50b1900SMark Johnston 	SOCKBUF_LOCK(sb);
1196a50b1900SMark Johnston 	if (sb->sb_fnrdy != NULL) {
1197a50b1900SMark Johnston 		for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1198a50b1900SMark Johnston 			if (mb == m) {
1199a50b1900SMark Johnston 				*errorp = sbready(sb, m, count);
1200a50b1900SMark Johnston 				break;
1201a50b1900SMark Johnston 			}
1202a50b1900SMark Johnston 			mb = mb->m_next;
1203a50b1900SMark Johnston 			if (mb == NULL) {
1204a50b1900SMark Johnston 				mb = n;
12051b778ba2SMark Johnston 				if (mb != NULL)
1206a50b1900SMark Johnston 					n = mb->m_nextpkt;
1207a50b1900SMark Johnston 			}
1208a50b1900SMark Johnston 		}
1209a50b1900SMark Johnston 	}
1210a50b1900SMark Johnston 	SOCKBUF_UNLOCK(sb);
1211a50b1900SMark Johnston 	SOCK_UNLOCK(so);
1212a50b1900SMark Johnston 	return (mb != NULL);
1213a50b1900SMark Johnston }
1214a50b1900SMark Johnston 
1215a29f300eSGarrett Wollman static int
1216c80ea19bSGleb Smirnoff uipc_ready(struct socket *so, struct mbuf *m, int count)
1217c80ea19bSGleb Smirnoff {
1218c80ea19bSGleb Smirnoff 	struct unpcb *unp, *unp2;
1219c80ea19bSGleb Smirnoff 	struct socket *so2;
1220a50b1900SMark Johnston 	int error, i;
1221c80ea19bSGleb Smirnoff 
1222c80ea19bSGleb Smirnoff 	unp = sotounpcb(so);
1223c80ea19bSGleb Smirnoff 
1224a50b1900SMark Johnston 	KASSERT(so->so_type == SOCK_STREAM,
1225a50b1900SMark Johnston 	    ("%s: unexpected socket type for %p", __func__, so));
1226a50b1900SMark Johnston 
1227a62b4665SMatt Macy 	UNP_PCB_LOCK(unp);
1228ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1229a62b4665SMatt Macy 		UNP_PCB_UNLOCK(unp);
1230c80ea19bSGleb Smirnoff 		so2 = unp2->unp_socket;
1231c80ea19bSGleb Smirnoff 		SOCKBUF_LOCK(&so2->so_rcv);
1232c80ea19bSGleb Smirnoff 		if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1233c80ea19bSGleb Smirnoff 			sorwakeup_locked(so2);
1234c80ea19bSGleb Smirnoff 		else
1235c80ea19bSGleb Smirnoff 			SOCKBUF_UNLOCK(&so2->so_rcv);
1236c80ea19bSGleb Smirnoff 		UNP_PCB_UNLOCK(unp2);
1237c80ea19bSGleb Smirnoff 		return (error);
1238ccdadf1aSMark Johnston 	}
1239ccdadf1aSMark Johnston 	UNP_PCB_UNLOCK(unp);
1240a50b1900SMark Johnston 
1241a50b1900SMark Johnston 	/*
1242a50b1900SMark Johnston 	 * The receiving socket has been disconnected, but may still be valid.
1243a50b1900SMark Johnston 	 * In this case, the now-ready mbufs are still present in its socket
1244a50b1900SMark Johnston 	 * buffer, so perform an exhaustive search before giving up and freeing
1245a50b1900SMark Johnston 	 * the mbufs.
1246a50b1900SMark Johnston 	 */
1247a50b1900SMark Johnston 	UNP_LINK_RLOCK();
1248a50b1900SMark Johnston 	LIST_FOREACH(unp, &unp_shead, unp_link) {
1249a50b1900SMark Johnston 		if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1250a50b1900SMark Johnston 			break;
1251a50b1900SMark Johnston 	}
1252a50b1900SMark Johnston 	UNP_LINK_RUNLOCK();
1253a50b1900SMark Johnston 
1254a50b1900SMark Johnston 	if (unp == NULL) {
1255a50b1900SMark Johnston 		for (i = 0; i < count; i++)
1256a62b4665SMatt Macy 			m = m_free(m);
1257a50b1900SMark Johnston 		error = ECONNRESET;
1258a50b1900SMark Johnston 	}
1259a50b1900SMark Johnston 	return (error);
1260c80ea19bSGleb Smirnoff }
1261c80ea19bSGleb Smirnoff 
1262c80ea19bSGleb Smirnoff static int
1263a29f300eSGarrett Wollman uipc_sense(struct socket *so, struct stat *sb)
1264a29f300eSGarrett Wollman {
1265c2090e73SAlan Somers 	struct unpcb *unp;
1266a29f300eSGarrett Wollman 
126740f2ac28SRobert Watson 	unp = sotounpcb(so);
12684d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1269e7c33e29SRobert Watson 
1270a29f300eSGarrett Wollman 	sb->st_blksize = so->so_snd.sb_hiwat;
1271f3732fd1SPoul-Henning Kamp 	sb->st_dev = NODEV;
1272a29f300eSGarrett Wollman 	sb->st_ino = unp->unp_ino;
1273df8bae1dSRodney W. Grimes 	return (0);
1274a29f300eSGarrett Wollman }
1275df8bae1dSRodney W. Grimes 
1276a29f300eSGarrett Wollman static int
1277a29f300eSGarrett Wollman uipc_shutdown(struct socket *so)
1278a29f300eSGarrett Wollman {
127940f2ac28SRobert Watson 	struct unpcb *unp;
1280df8bae1dSRodney W. Grimes 
128140f2ac28SRobert Watson 	unp = sotounpcb(so);
12824d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1283e7c33e29SRobert Watson 
1284e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1285a29f300eSGarrett Wollman 	socantsendmore(so);
1286a29f300eSGarrett Wollman 	unp_shutdown(unp);
1287e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1288e5aeaa0cSDag-Erling Smørgrav 	return (0);
1289a29f300eSGarrett Wollman }
1290df8bae1dSRodney W. Grimes 
1291a29f300eSGarrett Wollman static int
129257bf258eSGarrett Wollman uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1293a29f300eSGarrett Wollman {
129440f2ac28SRobert Watson 	struct unpcb *unp;
12950d9ce3a1SRobert Watson 	const struct sockaddr *sa;
1296a29f300eSGarrett Wollman 
12974d4b555eSRobert Watson 	unp = sotounpcb(so);
12984d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1299e7c33e29SRobert Watson 
13000d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1301e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1302fc3fcacfSRobert Watson 	if (unp->unp_addr != NULL)
13030d9ce3a1SRobert Watson 		sa = (struct sockaddr *) unp->unp_addr;
130483f3198bSThomas Moestl 	else
13050d9ce3a1SRobert Watson 		sa = &sun_noname;
13060d9ce3a1SRobert Watson 	bcopy(sa, *nam, sa->sa_len);
1307e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1308e5aeaa0cSDag-Erling Smørgrav 	return (0);
1309df8bae1dSRodney W. Grimes }
1310a29f300eSGarrett Wollman 
1311fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram = {
1312756d52a1SPoul-Henning Kamp 	.pru_abort = 		uipc_abort,
1313756d52a1SPoul-Henning Kamp 	.pru_accept =		uipc_accept,
1314756d52a1SPoul-Henning Kamp 	.pru_attach =		uipc_attach,
1315756d52a1SPoul-Henning Kamp 	.pru_bind =		uipc_bind,
13167493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1317756d52a1SPoul-Henning Kamp 	.pru_connect =		uipc_connect,
13187493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1319756d52a1SPoul-Henning Kamp 	.pru_connect2 =		uipc_connect2,
1320756d52a1SPoul-Henning Kamp 	.pru_detach =		uipc_detach,
1321756d52a1SPoul-Henning Kamp 	.pru_disconnect =	uipc_disconnect,
1322756d52a1SPoul-Henning Kamp 	.pru_listen =		uipc_listen,
1323756d52a1SPoul-Henning Kamp 	.pru_peeraddr =		uipc_peeraddr,
1324756d52a1SPoul-Henning Kamp 	.pru_rcvd =		uipc_rcvd,
1325756d52a1SPoul-Henning Kamp 	.pru_send =		uipc_send,
1326756d52a1SPoul-Henning Kamp 	.pru_sense =		uipc_sense,
1327756d52a1SPoul-Henning Kamp 	.pru_shutdown =		uipc_shutdown,
1328756d52a1SPoul-Henning Kamp 	.pru_sockaddr =		uipc_sockaddr,
1329fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_dgram,
1330fa9402f2SRobert Watson 	.pru_close =		uipc_close,
1331fa9402f2SRobert Watson };
1332fa9402f2SRobert Watson 
133384d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket = {
133484d61770SRobert Watson 	.pru_abort =		uipc_abort,
133584d61770SRobert Watson 	.pru_accept =		uipc_accept,
133684d61770SRobert Watson 	.pru_attach =		uipc_attach,
133784d61770SRobert Watson 	.pru_bind =		uipc_bind,
13387493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
133984d61770SRobert Watson 	.pru_connect =		uipc_connect,
13407493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
134184d61770SRobert Watson 	.pru_connect2 =		uipc_connect2,
134284d61770SRobert Watson 	.pru_detach =		uipc_detach,
134384d61770SRobert Watson 	.pru_disconnect =	uipc_disconnect,
134484d61770SRobert Watson 	.pru_listen =		uipc_listen,
134584d61770SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
134684d61770SRobert Watson 	.pru_rcvd =		uipc_rcvd,
134784d61770SRobert Watson 	.pru_send =		uipc_send,
134884d61770SRobert Watson 	.pru_sense =		uipc_sense,
134984d61770SRobert Watson 	.pru_shutdown =		uipc_shutdown,
135084d61770SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
135184d61770SRobert Watson 	.pru_soreceive =	soreceive_generic,	/* XXX: or...? */
135284d61770SRobert Watson 	.pru_close =		uipc_close,
135384d61770SRobert Watson };
135484d61770SRobert Watson 
1355fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_stream = {
1356fa9402f2SRobert Watson 	.pru_abort = 		uipc_abort,
1357fa9402f2SRobert Watson 	.pru_accept =		uipc_accept,
1358fa9402f2SRobert Watson 	.pru_attach =		uipc_attach,
1359fa9402f2SRobert Watson 	.pru_bind =		uipc_bind,
13607493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1361fa9402f2SRobert Watson 	.pru_connect =		uipc_connect,
13627493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1363fa9402f2SRobert Watson 	.pru_connect2 =		uipc_connect2,
1364fa9402f2SRobert Watson 	.pru_detach =		uipc_detach,
1365fa9402f2SRobert Watson 	.pru_disconnect =	uipc_disconnect,
1366fa9402f2SRobert Watson 	.pru_listen =		uipc_listen,
1367fa9402f2SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
1368fa9402f2SRobert Watson 	.pru_rcvd =		uipc_rcvd,
1369fa9402f2SRobert Watson 	.pru_send =		uipc_send,
1370c80ea19bSGleb Smirnoff 	.pru_ready =		uipc_ready,
1371fa9402f2SRobert Watson 	.pru_sense =		uipc_sense,
1372fa9402f2SRobert Watson 	.pru_shutdown =		uipc_shutdown,
1373fa9402f2SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
1374fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_generic,
1375a152f8a3SRobert Watson 	.pru_close =		uipc_close,
1376a29f300eSGarrett Wollman };
1377df8bae1dSRodney W. Grimes 
13780b36cd25SRobert Watson static int
1379892af6b9SRobert Watson uipc_ctloutput(struct socket *so, struct sockopt *sopt)
13800c1bb4fbSDima Dorfman {
138140f2ac28SRobert Watson 	struct unpcb *unp;
13820d9ce3a1SRobert Watson 	struct xucred xu;
13836a2989fdSMatthew N. Dodd 	int error, optval;
13846a2989fdSMatthew N. Dodd 
13856e0c8e1aSKonstantin Belousov 	if (sopt->sopt_level != SOL_LOCAL)
138696a041b5SMatthew N. Dodd 		return (EINVAL);
138796a041b5SMatthew N. Dodd 
13886a2989fdSMatthew N. Dodd 	unp = sotounpcb(so);
13894d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
13906a2989fdSMatthew N. Dodd 	error = 0;
13910c1bb4fbSDima Dorfman 	switch (sopt->sopt_dir) {
13920c1bb4fbSDima Dorfman 	case SOPT_GET:
13930c1bb4fbSDima Dorfman 		switch (sopt->sopt_name) {
13940c1bb4fbSDima Dorfman 		case LOCAL_PEERCRED:
1395e7c33e29SRobert Watson 			UNP_PCB_LOCK(unp);
13960c1bb4fbSDima Dorfman 			if (unp->unp_flags & UNP_HAVEPC)
13970d9ce3a1SRobert Watson 				xu = unp->unp_peercred;
13980c1bb4fbSDima Dorfman 			else {
13990c1bb4fbSDima Dorfman 				if (so->so_type == SOCK_STREAM)
14000c1bb4fbSDima Dorfman 					error = ENOTCONN;
14010c1bb4fbSDima Dorfman 				else
14020c1bb4fbSDima Dorfman 					error = EINVAL;
14030c1bb4fbSDima Dorfman 			}
1404e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
14050d9ce3a1SRobert Watson 			if (error == 0)
14060d9ce3a1SRobert Watson 				error = sooptcopyout(sopt, &xu, sizeof(xu));
14070c1bb4fbSDima Dorfman 			break;
1408e7c33e29SRobert Watson 
14096a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
1410a6357845SRobert Watson 			/* Unlocked read. */
14112de07e40SConrad Meyer 			optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
14122de07e40SConrad Meyer 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14132de07e40SConrad Meyer 			break;
14142de07e40SConrad Meyer 
14152de07e40SConrad Meyer 		case LOCAL_CREDS_PERSISTENT:
14162de07e40SConrad Meyer 			/* Unlocked read. */
14172de07e40SConrad Meyer 			optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
14186a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14196a2989fdSMatthew N. Dodd 			break;
1420e7c33e29SRobert Watson 
14216a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
1422a6357845SRobert Watson 			/* Unlocked read. */
14236a2989fdSMatthew N. Dodd 			optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
14246a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14256a2989fdSMatthew N. Dodd 			break;
1426e7c33e29SRobert Watson 
14270c1bb4fbSDima Dorfman 		default:
14280c1bb4fbSDima Dorfman 			error = EOPNOTSUPP;
14290c1bb4fbSDima Dorfman 			break;
14300c1bb4fbSDima Dorfman 		}
14310c1bb4fbSDima Dorfman 		break;
1432e7c33e29SRobert Watson 
14330c1bb4fbSDima Dorfman 	case SOPT_SET:
14346a2989fdSMatthew N. Dodd 		switch (sopt->sopt_name) {
14356a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
14362de07e40SConrad Meyer 		case LOCAL_CREDS_PERSISTENT:
14376a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
14386a2989fdSMatthew N. Dodd 			error = sooptcopyin(sopt, &optval, sizeof(optval),
14396a2989fdSMatthew N. Dodd 					    sizeof(optval));
14406a2989fdSMatthew N. Dodd 			if (error)
14416a2989fdSMatthew N. Dodd 				break;
14426a2989fdSMatthew N. Dodd 
14432de07e40SConrad Meyer #define	OPTSET(bit, exclusive) do {					\
1444e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);						\
14452de07e40SConrad Meyer 	if (optval) {							\
14462de07e40SConrad Meyer 		if ((unp->unp_flags & (exclusive)) != 0) {		\
14472de07e40SConrad Meyer 			UNP_PCB_UNLOCK(unp);				\
14482de07e40SConrad Meyer 			error = EINVAL;					\
14492de07e40SConrad Meyer 			break;						\
14502de07e40SConrad Meyer 		}							\
14512de07e40SConrad Meyer 		unp->unp_flags |= (bit);				\
14522de07e40SConrad Meyer 	} else								\
14532de07e40SConrad Meyer 		unp->unp_flags &= ~(bit);				\
1454e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);						\
1455e7c33e29SRobert Watson } while (0)
14566a2989fdSMatthew N. Dodd 
14576a2989fdSMatthew N. Dodd 			switch (sopt->sopt_name) {
14586a2989fdSMatthew N. Dodd 			case LOCAL_CREDS:
14592de07e40SConrad Meyer 				OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
14602de07e40SConrad Meyer 				break;
14612de07e40SConrad Meyer 
14622de07e40SConrad Meyer 			case LOCAL_CREDS_PERSISTENT:
14632de07e40SConrad Meyer 				OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
14646a2989fdSMatthew N. Dodd 				break;
1465e7c33e29SRobert Watson 
14666a2989fdSMatthew N. Dodd 			case LOCAL_CONNWAIT:
14672de07e40SConrad Meyer 				OPTSET(UNP_CONNWAIT, 0);
14686a2989fdSMatthew N. Dodd 				break;
1469e7c33e29SRobert Watson 
14706a2989fdSMatthew N. Dodd 			default:
14716a2989fdSMatthew N. Dodd 				break;
14726a2989fdSMatthew N. Dodd 			}
14736a2989fdSMatthew N. Dodd 			break;
14746a2989fdSMatthew N. Dodd #undef	OPTSET
14756a2989fdSMatthew N. Dodd 		default:
14766a2989fdSMatthew N. Dodd 			error = ENOPROTOOPT;
14776a2989fdSMatthew N. Dodd 			break;
14786a2989fdSMatthew N. Dodd 		}
1479abb886faSMatthew N. Dodd 		break;
1480e7c33e29SRobert Watson 
14810c1bb4fbSDima Dorfman 	default:
14820c1bb4fbSDima Dorfman 		error = EOPNOTSUPP;
14830c1bb4fbSDima Dorfman 		break;
14840c1bb4fbSDima Dorfman 	}
14850c1bb4fbSDima Dorfman 	return (error);
14860c1bb4fbSDima Dorfman }
14870c1bb4fbSDima Dorfman 
1488f708ef1bSPoul-Henning Kamp static int
1489892af6b9SRobert Watson unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1490df8bae1dSRodney W. Grimes {
14917493f24eSPawel Jakub Dawidek 
14927493f24eSPawel Jakub Dawidek 	return (unp_connectat(AT_FDCWD, so, nam, td));
14937493f24eSPawel Jakub Dawidek }
14947493f24eSPawel Jakub Dawidek 
14957493f24eSPawel Jakub Dawidek static int
14967493f24eSPawel Jakub Dawidek unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
14977493f24eSPawel Jakub Dawidek     struct thread *td)
14987493f24eSPawel Jakub Dawidek {
1499ed92e1c7SMark Johnston 	struct mtx *vplock;
1500ed92e1c7SMark Johnston 	struct sockaddr_un *soun;
1501892af6b9SRobert Watson 	struct vnode *vp;
1502779f106aSGleb Smirnoff 	struct socket *so2;
1503b295bdcdSRobert Watson 	struct unpcb *unp, *unp2, *unp3;
1504df8bae1dSRodney W. Grimes 	struct nameidata nd;
150557bf258eSGarrett Wollman 	char buf[SOCK_MAXADDRLEN];
15060d9ce3a1SRobert Watson 	struct sockaddr *sa;
15077008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
1508ccdadf1aSMark Johnston 	int error, len;
1509ed92e1c7SMark Johnston 	bool connreq;
15100d9ce3a1SRobert Watson 
1511cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
1512cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
1513a06534c3SBjoern A. Zeeb 	if (nam->sa_len > sizeof(struct sockaddr_un))
1514a06534c3SBjoern A. Zeeb 		return (EINVAL);
151557bf258eSGarrett Wollman 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
151657bf258eSGarrett Wollman 	if (len <= 0)
1517e5aeaa0cSDag-Erling Smørgrav 		return (EINVAL);
1518ed92e1c7SMark Johnston 	soun = (struct sockaddr_un *)nam;
15197928893dSEd Maste 	bcopy(soun->sun_path, buf, len);
15207928893dSEd Maste 	buf[len] = 0;
1521e7c33e29SRobert Watson 
152275a67bf3SMatt Macy 	unp = sotounpcb(so);
1523e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1524ccdadf1aSMark Johnston 	for (;;) {
1525ccdadf1aSMark Johnston 		/*
1526ccdadf1aSMark Johnston 		 * Wait for connection state to stabilize.  If a connection
1527ccdadf1aSMark Johnston 		 * already exists, give up.  For datagram sockets, which permit
1528ccdadf1aSMark Johnston 		 * multiple consecutive connect(2) calls, upper layers are
1529ccdadf1aSMark Johnston 		 * responsible for disconnecting in advance of a subsequent
1530ccdadf1aSMark Johnston 		 * connect(2), but this is not synchronized with PCB connection
1531ccdadf1aSMark Johnston 		 * state.
1532ccdadf1aSMark Johnston 		 *
1533ccdadf1aSMark Johnston 		 * Also make sure that no threads are currently attempting to
1534ccdadf1aSMark Johnston 		 * lock the peer socket, to ensure that unp_conn cannot
1535ccdadf1aSMark Johnston 		 * transition between two valid sockets while locks are dropped.
1536ccdadf1aSMark Johnston 		 */
1537ccdadf1aSMark Johnston 		if (unp->unp_conn != NULL) {
1538ccdadf1aSMark Johnston 			UNP_PCB_UNLOCK(unp);
1539ccdadf1aSMark Johnston 			return (EISCONN);
1540ccdadf1aSMark Johnston 		}
1541ccdadf1aSMark Johnston 		if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1542e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
15434f1f0ef5SRobert Watson 			return (EALREADY);
15444f1f0ef5SRobert Watson 		}
1545ccdadf1aSMark Johnston 		if (unp->unp_pairbusy > 0) {
1546ccdadf1aSMark Johnston 			unp->unp_flags |= UNP_WAITING;
1547ccdadf1aSMark Johnston 			mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1548ccdadf1aSMark Johnston 			continue;
1549ccdadf1aSMark Johnston 		}
1550ccdadf1aSMark Johnston 		break;
1551ccdadf1aSMark Johnston 	}
155205102f04SRobert Watson 	unp->unp_flags |= UNP_CONNECTING;
1553e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1554e7c33e29SRobert Watson 
1555ed92e1c7SMark Johnston 	connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1556ed92e1c7SMark Johnston 	if (connreq)
15570d9ce3a1SRobert Watson 		sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1558ed92e1c7SMark Johnston 	else
1559ed92e1c7SMark Johnston 		sa = NULL;
15607493f24eSPawel Jakub Dawidek 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
15617008be5bSPawel Jakub Dawidek 	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1562797f2d22SPoul-Henning Kamp 	error = namei(&nd);
1563797f2d22SPoul-Henning Kamp 	if (error)
15640d9ce3a1SRobert Watson 		vp = NULL;
15650d9ce3a1SRobert Watson 	else
1566df8bae1dSRodney W. Grimes 		vp = nd.ni_vp;
15670d9ce3a1SRobert Watson 	ASSERT_VOP_LOCKED(vp, "unp_connect");
1568762e6b85SEivind Eklund 	NDFREE(&nd, NDF_ONLY_PNBUF);
15690d9ce3a1SRobert Watson 	if (error)
15700d9ce3a1SRobert Watson 		goto bad;
15710d9ce3a1SRobert Watson 
1572df8bae1dSRodney W. Grimes 	if (vp->v_type != VSOCK) {
1573df8bae1dSRodney W. Grimes 		error = ENOTSOCK;
1574df8bae1dSRodney W. Grimes 		goto bad;
1575df8bae1dSRodney W. Grimes 	}
15766fac927cSRobert Watson #ifdef MAC
157730d239bcSRobert Watson 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
15786fac927cSRobert Watson 	if (error)
15796fac927cSRobert Watson 		goto bad;
15806fac927cSRobert Watson #endif
1581a854ed98SJohn Baldwin 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1582797f2d22SPoul-Henning Kamp 	if (error)
1583df8bae1dSRodney W. Grimes 		goto bad;
1584e7c33e29SRobert Watson 
1585b295bdcdSRobert Watson 	unp = sotounpcb(so);
15864d4b555eSRobert Watson 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1587e7c33e29SRobert Watson 
158875a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
158975a67bf3SMatt Macy 	mtx_lock(vplock);
15900c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp2);
15910c3c207fSGleb Smirnoff 	if (unp2 == NULL) {
1592df8bae1dSRodney W. Grimes 		error = ECONNREFUSED;
15932260c03dSRobert Watson 		goto bad2;
1594df8bae1dSRodney W. Grimes 	}
15950c3c207fSGleb Smirnoff 	so2 = unp2->unp_socket;
1596df8bae1dSRodney W. Grimes 	if (so->so_type != so2->so_type) {
1597df8bae1dSRodney W. Grimes 		error = EPROTOTYPE;
15982260c03dSRobert Watson 		goto bad2;
1599df8bae1dSRodney W. Grimes 	}
1600ed92e1c7SMark Johnston 	if (connreq) {
1601e7c33e29SRobert Watson 		if (so2->so_options & SO_ACCEPTCONN) {
16021fb51a12SBjoern A. Zeeb 			CURVNET_SET(so2->so_vnet);
1603779f106aSGleb Smirnoff 			so2 = sonewconn(so2, 0);
16041fb51a12SBjoern A. Zeeb 			CURVNET_RESTORE();
1605e7c33e29SRobert Watson 		} else
1606779f106aSGleb Smirnoff 			so2 = NULL;
1607779f106aSGleb Smirnoff 		if (so2 == NULL) {
1608df8bae1dSRodney W. Grimes 			error = ECONNREFUSED;
1609cb8f450bSMatt Macy 			goto bad2;
1610df8bae1dSRodney W. Grimes 		}
1611779f106aSGleb Smirnoff 		unp3 = sotounpcb(so2);
16124820bf6aSMark Johnston 		unp_pcb_lock_pair(unp2, unp3);
16130d9ce3a1SRobert Watson 		if (unp2->unp_addr != NULL) {
16140d9ce3a1SRobert Watson 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
16150d9ce3a1SRobert Watson 			unp3->unp_addr = (struct sockaddr_un *) sa;
16160d9ce3a1SRobert Watson 			sa = NULL;
16170d9ce3a1SRobert Watson 		}
1618b523ec24SRobert Watson 
1619da446550SAlan Somers 		unp_copy_peercred(td, unp3, unp, unp2);
1620b523ec24SRobert Watson 
1621e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1622779f106aSGleb Smirnoff 		unp2 = unp3;
1623ccdadf1aSMark Johnston 
1624ccdadf1aSMark Johnston 		/*
1625ccdadf1aSMark Johnston 		 * It is safe to block on the PCB lock here since unp2 is
1626ccdadf1aSMark Johnston 		 * nascent and cannot be connected to any other sockets.
1627ccdadf1aSMark Johnston 		 */
1628ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp);
1629335654d7SRobert Watson #ifdef MAC
1630779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so, so2);
1631779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so2, so);
1632335654d7SRobert Watson #endif
1633a3a73490SMatt Macy 	} else {
16344820bf6aSMark Johnston 		unp_pcb_lock_pair(unp, unp2);
1635a3a73490SMatt Macy 	}
1636779f106aSGleb Smirnoff 	KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1637779f106aSGleb Smirnoff 	    sotounpcb(so2) == unp2,
1638779f106aSGleb Smirnoff 	    ("%s: unp2 %p so2 %p", __func__, unp2, so2));
16396a2989fdSMatthew N. Dodd 	error = unp_connect2(so, so2, PRU_CONNECT);
16404820bf6aSMark Johnston 	unp_pcb_unlock_pair(unp, unp2);
16410d9ce3a1SRobert Watson bad2:
164275a67bf3SMatt Macy 	mtx_unlock(vplock);
1643df8bae1dSRodney W. Grimes bad:
164475a67bf3SMatt Macy 	if (vp != NULL) {
1645df8bae1dSRodney W. Grimes 		vput(vp);
164675a67bf3SMatt Macy 	}
16470d9ce3a1SRobert Watson 	free(sa, M_SONAME);
1648e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1649ccdadf1aSMark Johnston 	KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1650ccdadf1aSMark Johnston 	    ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
16514f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_CONNECTING;
1652e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1653df8bae1dSRodney W. Grimes 	return (error);
1654df8bae1dSRodney W. Grimes }
1655df8bae1dSRodney W. Grimes 
1656da446550SAlan Somers /*
1657da446550SAlan Somers  * Set socket peer credentials at connection time.
1658da446550SAlan Somers  *
1659da446550SAlan Somers  * The client's PCB credentials are copied from its process structure.  The
1660da446550SAlan Somers  * server's PCB credentials are copied from the socket on which it called
1661da446550SAlan Somers  * listen(2).  uipc_listen cached that process's credentials at the time.
1662da446550SAlan Somers  */
1663da446550SAlan Somers void
1664da446550SAlan Somers unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1665da446550SAlan Somers     struct unpcb *server_unp, struct unpcb *listen_unp)
1666da446550SAlan Somers {
1667c5afec6eSDmitry Chagin 	cru2xt(td, &client_unp->unp_peercred);
1668da446550SAlan Somers 	client_unp->unp_flags |= UNP_HAVEPC;
1669da446550SAlan Somers 
1670da446550SAlan Somers 	memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1671da446550SAlan Somers 	    sizeof(server_unp->unp_peercred));
1672da446550SAlan Somers 	server_unp->unp_flags |= UNP_HAVEPC;
16732de07e40SConrad Meyer 	client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
1674da446550SAlan Somers }
1675da446550SAlan Somers 
1676db48c0d2SRobert Watson static int
16776a2989fdSMatthew N. Dodd unp_connect2(struct socket *so, struct socket *so2, int req)
1678df8bae1dSRodney W. Grimes {
1679e7c33e29SRobert Watson 	struct unpcb *unp;
1680892af6b9SRobert Watson 	struct unpcb *unp2;
1681df8bae1dSRodney W. Grimes 
1682e7c33e29SRobert Watson 	unp = sotounpcb(so);
1683e7c33e29SRobert Watson 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1684e7c33e29SRobert Watson 	unp2 = sotounpcb(so2);
1685e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1686e7c33e29SRobert Watson 
1687e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1688e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
1689ccdadf1aSMark Johnston 	KASSERT(unp->unp_conn == NULL,
1690ccdadf1aSMark Johnston 	    ("%s: socket %p is already connected", __func__, unp));
16910d9ce3a1SRobert Watson 
1692df8bae1dSRodney W. Grimes 	if (so2->so_type != so->so_type)
1693df8bae1dSRodney W. Grimes 		return (EPROTOTYPE);
1694df8bae1dSRodney W. Grimes 	unp->unp_conn = unp2;
169575a67bf3SMatt Macy 	unp_pcb_hold(unp2);
169675a67bf3SMatt Macy 	unp_pcb_hold(unp);
1697df8bae1dSRodney W. Grimes 	switch (so->so_type) {
1698df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
169975a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
170098271db4SGarrett Wollman 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
170175a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
1702df8bae1dSRodney W. Grimes 		soisconnected(so);
1703df8bae1dSRodney W. Grimes 		break;
1704df8bae1dSRodney W. Grimes 
1705df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
170684d61770SRobert Watson 	case SOCK_SEQPACKET:
1707ccdadf1aSMark Johnston 		KASSERT(unp2->unp_conn == NULL,
1708ccdadf1aSMark Johnston 		    ("%s: socket %p is already connected", __func__, unp2));
1709df8bae1dSRodney W. Grimes 		unp2->unp_conn = unp;
17106a2989fdSMatthew N. Dodd 		if (req == PRU_CONNECT &&
17116a2989fdSMatthew N. Dodd 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
17126a2989fdSMatthew N. Dodd 			soisconnecting(so);
17136a2989fdSMatthew N. Dodd 		else
1714df8bae1dSRodney W. Grimes 			soisconnected(so);
1715df8bae1dSRodney W. Grimes 		soisconnected(so2);
1716df8bae1dSRodney W. Grimes 		break;
1717df8bae1dSRodney W. Grimes 
1718df8bae1dSRodney W. Grimes 	default:
1719df8bae1dSRodney W. Grimes 		panic("unp_connect2");
1720df8bae1dSRodney W. Grimes 	}
1721df8bae1dSRodney W. Grimes 	return (0);
1722df8bae1dSRodney W. Grimes }
1723df8bae1dSRodney W. Grimes 
1724f708ef1bSPoul-Henning Kamp static void
1725e7c33e29SRobert Watson unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1726df8bae1dSRodney W. Grimes {
172775a67bf3SMatt Macy 	struct socket *so, *so2;
1728f0317f86SMark Johnston #ifdef INVARIANTS
1729f0317f86SMark Johnston 	struct unpcb *unptmp;
1730f0317f86SMark Johnston #endif
17310d9ce3a1SRobert Watson 
1732e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1733e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
1734f0317f86SMark Johnston 	KASSERT(unp->unp_conn == unp2,
1735f0317f86SMark Johnston 	    ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
1736e7c33e29SRobert Watson 
1737fc3fcacfSRobert Watson 	unp->unp_conn = NULL;
173875a67bf3SMatt Macy 	so = unp->unp_socket;
173975a67bf3SMatt Macy 	so2 = unp2->unp_socket;
1740df8bae1dSRodney W. Grimes 	switch (unp->unp_socket->so_type) {
1741df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
174275a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
1743f0317f86SMark Johnston #ifdef INVARIANTS
1744f0317f86SMark Johnston 		LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
1745f0317f86SMark Johnston 			if (unptmp == unp)
1746f0317f86SMark Johnston 				break;
1747f0317f86SMark Johnston 		}
1748f0317f86SMark Johnston 		KASSERT(unptmp != NULL,
1749f0317f86SMark Johnston 		    ("%s: %p not found in reflist of %p", __func__, unp, unp2));
1750f0317f86SMark Johnston #endif
175198271db4SGarrett Wollman 		LIST_REMOVE(unp, unp_reflink);
175275a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
175375a67bf3SMatt Macy 		if (so) {
17541b2e3b4bSRobert Watson 			SOCK_LOCK(so);
17551b2e3b4bSRobert Watson 			so->so_state &= ~SS_ISCONNECTED;
17561b2e3b4bSRobert Watson 			SOCK_UNLOCK(so);
175775a67bf3SMatt Macy 		}
1758df8bae1dSRodney W. Grimes 		break;
1759df8bae1dSRodney W. Grimes 
1760df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
176184d61770SRobert Watson 	case SOCK_SEQPACKET:
176275a67bf3SMatt Macy 		if (so)
176375a67bf3SMatt Macy 			soisdisconnected(so);
176475a67bf3SMatt Macy 		MPASS(unp2->unp_conn == unp);
1765fc3fcacfSRobert Watson 		unp2->unp_conn = NULL;
176675a67bf3SMatt Macy 		if (so2)
176775a67bf3SMatt Macy 			soisdisconnected(so2);
1768df8bae1dSRodney W. Grimes 		break;
1769df8bae1dSRodney W. Grimes 	}
1770f0317f86SMark Johnston 
1771f0317f86SMark Johnston 	if (unp == unp2) {
1772f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
1773f0317f86SMark Johnston 		if (!unp_pcb_rele(unp))
1774f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp);
1775f0317f86SMark Johnston 	} else {
1776f0317f86SMark Johnston 		if (!unp_pcb_rele(unp))
1777f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp);
1778f0317f86SMark Johnston 		if (!unp_pcb_rele(unp2))
1779f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp2);
1780f0317f86SMark Johnston 	}
1781df8bae1dSRodney W. Grimes }
1782df8bae1dSRodney W. Grimes 
17830d9ce3a1SRobert Watson /*
1784d7924b70SRobert Watson  * unp_pcblist() walks the global list of struct unpcb's to generate a
1785d7924b70SRobert Watson  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1786d7924b70SRobert Watson  * sequentially, validating the generation number on each to see if it has
1787d7924b70SRobert Watson  * been detached.  All of this is necessary because copyout() may sleep on
1788d7924b70SRobert Watson  * disk I/O.
17890d9ce3a1SRobert Watson  */
179098271db4SGarrett Wollman static int
179182d9ae4eSPoul-Henning Kamp unp_pcblist(SYSCTL_HANDLER_ARGS)
179298271db4SGarrett Wollman {
179398271db4SGarrett Wollman 	struct unpcb *unp, **unp_list;
179498271db4SGarrett Wollman 	unp_gen_t gencnt;
17958f364875SJulian Elischer 	struct xunpgen *xug;
179698271db4SGarrett Wollman 	struct unp_head *head;
17978f364875SJulian Elischer 	struct xunpcb *xu;
1798d821d364SPedro F. Giffuni 	u_int i;
17995362170dSMark Johnston 	int error, n;
180098271db4SGarrett Wollman 
180184d61770SRobert Watson 	switch ((intptr_t)arg1) {
180284d61770SRobert Watson 	case SOCK_STREAM:
180384d61770SRobert Watson 		head = &unp_shead;
180484d61770SRobert Watson 		break;
180584d61770SRobert Watson 
180684d61770SRobert Watson 	case SOCK_DGRAM:
180784d61770SRobert Watson 		head = &unp_dhead;
180884d61770SRobert Watson 		break;
180984d61770SRobert Watson 
181084d61770SRobert Watson 	case SOCK_SEQPACKET:
181184d61770SRobert Watson 		head = &unp_sphead;
181284d61770SRobert Watson 		break;
181384d61770SRobert Watson 
181484d61770SRobert Watson 	default:
1815604f19c9SRobert Watson 		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
181684d61770SRobert Watson 	}
181798271db4SGarrett Wollman 
181898271db4SGarrett Wollman 	/*
181998271db4SGarrett Wollman 	 * The process of preparing the PCB list is too time-consuming and
182098271db4SGarrett Wollman 	 * resource-intensive to repeat twice on every request.
182198271db4SGarrett Wollman 	 */
1822fc3fcacfSRobert Watson 	if (req->oldptr == NULL) {
182398271db4SGarrett Wollman 		n = unp_count;
18248f364875SJulian Elischer 		req->oldidx = 2 * (sizeof *xug)
182598271db4SGarrett Wollman 			+ (n + n/8) * sizeof(struct xunpcb);
1826e5aeaa0cSDag-Erling Smørgrav 		return (0);
182798271db4SGarrett Wollman 	}
182898271db4SGarrett Wollman 
1829fc3fcacfSRobert Watson 	if (req->newptr != NULL)
1830e5aeaa0cSDag-Erling Smørgrav 		return (EPERM);
183198271db4SGarrett Wollman 
183298271db4SGarrett Wollman 	/*
183398271db4SGarrett Wollman 	 * OK, now we're committed to doing something.
183498271db4SGarrett Wollman 	 */
183579db6fe7SMark Johnston 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1836779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
183798271db4SGarrett Wollman 	gencnt = unp_gencnt;
183898271db4SGarrett Wollman 	n = unp_count;
1839779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
184098271db4SGarrett Wollman 
18418f364875SJulian Elischer 	xug->xug_len = sizeof *xug;
18428f364875SJulian Elischer 	xug->xug_count = n;
18438f364875SJulian Elischer 	xug->xug_gen = gencnt;
18448f364875SJulian Elischer 	xug->xug_sogen = so_gencnt;
18458f364875SJulian Elischer 	error = SYSCTL_OUT(req, xug, sizeof *xug);
18468f364875SJulian Elischer 	if (error) {
18478f364875SJulian Elischer 		free(xug, M_TEMP);
1848e5aeaa0cSDag-Erling Smørgrav 		return (error);
18498f364875SJulian Elischer 	}
185098271db4SGarrett Wollman 
1851a163d034SWarner Losh 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
185298271db4SGarrett Wollman 
1853779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
18542e3c8fcbSPoul-Henning Kamp 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
18552e3c8fcbSPoul-Henning Kamp 	     unp = LIST_NEXT(unp, unp_link)) {
1856e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
18578a7d8cc6SRobert Watson 		if (unp->unp_gencnt <= gencnt) {
1858a854ed98SJohn Baldwin 			if (cr_cansee(req->td->td_ucred,
1859e7c33e29SRobert Watson 			    unp->unp_socket->so_cred)) {
1860e7c33e29SRobert Watson 				UNP_PCB_UNLOCK(unp);
18614787fd37SPaul Saab 				continue;
1862e7c33e29SRobert Watson 			}
186398271db4SGarrett Wollman 			unp_list[i++] = unp;
186475a67bf3SMatt Macy 			unp_pcb_hold(unp);
186598271db4SGarrett Wollman 		}
1866e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
18674787fd37SPaul Saab 	}
1868779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
18691c381b19SRobert Watson 	n = i;			/* In case we lost some during malloc. */
187098271db4SGarrett Wollman 
187198271db4SGarrett Wollman 	error = 0;
1872fe2eee82SColin Percival 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
187398271db4SGarrett Wollman 	for (i = 0; i < n; i++) {
187498271db4SGarrett Wollman 		unp = unp_list[i];
1875e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
18765362170dSMark Johnston 		if (unp_pcb_rele(unp))
18775362170dSMark Johnston 			continue;
187875a67bf3SMatt Macy 
18795362170dSMark Johnston 		if (unp->unp_gencnt <= gencnt) {
18808f364875SJulian Elischer 			xu->xu_len = sizeof *xu;
18813a20f06aSBrooks Davis 			xu->xu_unpp = (uintptr_t)unp;
188298271db4SGarrett Wollman 			/*
188398271db4SGarrett Wollman 			 * XXX - need more locking here to protect against
188498271db4SGarrett Wollman 			 * connect/disconnect races for SMP.
188598271db4SGarrett Wollman 			 */
1886fc3fcacfSRobert Watson 			if (unp->unp_addr != NULL)
18878f364875SJulian Elischer 				bcopy(unp->unp_addr, &xu->xu_addr,
188898271db4SGarrett Wollman 				      unp->unp_addr->sun_len);
18890e229f34SGleb Smirnoff 			else
18900e229f34SGleb Smirnoff 				bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1891fc3fcacfSRobert Watson 			if (unp->unp_conn != NULL &&
1892fc3fcacfSRobert Watson 			    unp->unp_conn->unp_addr != NULL)
189398271db4SGarrett Wollman 				bcopy(unp->unp_conn->unp_addr,
18948f364875SJulian Elischer 				      &xu->xu_caddr,
189598271db4SGarrett Wollman 				      unp->unp_conn->unp_addr->sun_len);
18960e229f34SGleb Smirnoff 			else
18970e229f34SGleb Smirnoff 				bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
18983a20f06aSBrooks Davis 			xu->unp_vnode = (uintptr_t)unp->unp_vnode;
18993a20f06aSBrooks Davis 			xu->unp_conn = (uintptr_t)unp->unp_conn;
19003a20f06aSBrooks Davis 			xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
19013a20f06aSBrooks Davis 			xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
19020e229f34SGleb Smirnoff 			xu->unp_gencnt = unp->unp_gencnt;
19038f364875SJulian Elischer 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1904e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
19058f364875SJulian Elischer 			error = SYSCTL_OUT(req, xu, sizeof *xu);
19065362170dSMark Johnston 		} else {
1907e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
1908e7c33e29SRobert Watson 		}
19095362170dSMark Johnston 	}
19108f364875SJulian Elischer 	free(xu, M_TEMP);
191198271db4SGarrett Wollman 	if (!error) {
191298271db4SGarrett Wollman 		/*
19131c381b19SRobert Watson 		 * Give the user an updated idea of our state.  If the
19141c381b19SRobert Watson 		 * generation differs from what we told her before, she knows
19151c381b19SRobert Watson 		 * that something happened while we were processing this
19161c381b19SRobert Watson 		 * request, and it might be necessary to retry.
191798271db4SGarrett Wollman 		 */
19188f364875SJulian Elischer 		xug->xug_gen = unp_gencnt;
19198f364875SJulian Elischer 		xug->xug_sogen = so_gencnt;
19208f364875SJulian Elischer 		xug->xug_count = unp_count;
19218f364875SJulian Elischer 		error = SYSCTL_OUT(req, xug, sizeof *xug);
192298271db4SGarrett Wollman 	}
192398271db4SGarrett Wollman 	free(unp_list, M_TEMP);
19248f364875SJulian Elischer 	free(xug, M_TEMP);
1925e5aeaa0cSDag-Erling Smørgrav 	return (error);
192698271db4SGarrett Wollman }
192798271db4SGarrett Wollman 
19287029da5cSPawel Biernacki SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
19297029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19302fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
193198271db4SGarrett Wollman     "List of active local datagram sockets");
19327029da5cSPawel Biernacki SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
19337029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19342fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
193598271db4SGarrett Wollman     "List of active local stream sockets");
19362fee06f0SMatthew D Fleming SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
19377029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19382fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
193984d61770SRobert Watson     "List of active local seqpacket sockets");
194098271db4SGarrett Wollman 
1941f708ef1bSPoul-Henning Kamp static void
1942892af6b9SRobert Watson unp_shutdown(struct unpcb *unp)
1943df8bae1dSRodney W. Grimes {
1944e7c33e29SRobert Watson 	struct unpcb *unp2;
1945df8bae1dSRodney W. Grimes 	struct socket *so;
1946df8bae1dSRodney W. Grimes 
1947e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
19480d9ce3a1SRobert Watson 
1949e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
195084d61770SRobert Watson 	if ((unp->unp_socket->so_type == SOCK_STREAM ||
195184d61770SRobert Watson 	    (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1952e7c33e29SRobert Watson 		so = unp2->unp_socket;
1953e7c33e29SRobert Watson 		if (so != NULL)
1954df8bae1dSRodney W. Grimes 			socantrcvmore(so);
1955df8bae1dSRodney W. Grimes 	}
1956e7c33e29SRobert Watson }
1957df8bae1dSRodney W. Grimes 
1958f708ef1bSPoul-Henning Kamp static void
1959afc055d9SEd Schouten unp_drop(struct unpcb *unp)
1960df8bae1dSRodney W. Grimes {
1961df8bae1dSRodney W. Grimes 	struct socket *so = unp->unp_socket;
1962e7c33e29SRobert Watson 	struct unpcb *unp2;
19630d9ce3a1SRobert Watson 
1964afc055d9SEd Schouten 	/*
1965afc055d9SEd Schouten 	 * Regardless of whether the socket's peer dropped the connection
1966afc055d9SEd Schouten 	 * with this socket by aborting or disconnecting, POSIX requires
1967afc055d9SEd Schouten 	 * that ECONNRESET is returned.
1968afc055d9SEd Schouten 	 */
196975a67bf3SMatt Macy 
197075a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
197175a67bf3SMatt Macy 	if (so)
1972afc055d9SEd Schouten 		so->so_error = ECONNRESET;
1973ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1974f0317f86SMark Johnston 		/* Last reference dropped in unp_disconnect(). */
1975f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
1976e7c33e29SRobert Watson 		unp_disconnect(unp, unp2);
1977f0317f86SMark Johnston 	} else if (!unp_pcb_rele(unp)) {
197875a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
197975a67bf3SMatt Macy 	}
1980f0317f86SMark Johnston }
1981df8bae1dSRodney W. Grimes 
19822bc21ed9SDavid Malone static void
19838cb539f1SPawel Jakub Dawidek unp_freerights(struct filedescent **fdep, int fdcount)
1984df8bae1dSRodney W. Grimes {
19852bc21ed9SDavid Malone 	struct file *fp;
19862609222aSPawel Jakub Dawidek 	int i;
1987df8bae1dSRodney W. Grimes 
198882e825c4SGleb Smirnoff 	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
198982e825c4SGleb Smirnoff 
19908cb539f1SPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
19918cb539f1SPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
19928cb539f1SPawel Jakub Dawidek 		filecaps_free(&fdep[i]->fde_caps);
19938692c025SYoshinobu Inoue 		unp_discard(fp);
1994df8bae1dSRodney W. Grimes 	}
19958cb539f1SPawel Jakub Dawidek 	free(fdep[0], M_FILECAPS);
19962bc21ed9SDavid Malone }
19972bc21ed9SDavid Malone 
19980b36cd25SRobert Watson static int
1999c2e3c52eSJilles Tjoelker unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
20002bc21ed9SDavid Malone {
20012bc21ed9SDavid Malone 	struct thread *td = curthread;		/* XXX */
20022bc21ed9SDavid Malone 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
20032bc21ed9SDavid Malone 	int i;
20042bc21ed9SDavid Malone 	int *fdp;
20052609222aSPawel Jakub Dawidek 	struct filedesc *fdesc = td->td_proc->p_fd;
2006ea31808cSMateusz Guzik 	struct filedescent **fdep;
20072bc21ed9SDavid Malone 	void *data;
20082bc21ed9SDavid Malone 	socklen_t clen = control->m_len, datalen;
20092bc21ed9SDavid Malone 	int error, newfds;
20102bc21ed9SDavid Malone 	u_int newlen;
20112bc21ed9SDavid Malone 
20123dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
20134c5bc1caSRobert Watson 
20142bc21ed9SDavid Malone 	error = 0;
20152bc21ed9SDavid Malone 	if (controlp != NULL) /* controlp == NULL => free control messages */
20162bc21ed9SDavid Malone 		*controlp = NULL;
20172bc21ed9SDavid Malone 	while (cm != NULL) {
20182bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
20192bc21ed9SDavid Malone 			error = EINVAL;
20202bc21ed9SDavid Malone 			break;
20212bc21ed9SDavid Malone 		}
20222bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
20232bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
20242bc21ed9SDavid Malone 		if (cm->cmsg_level == SOL_SOCKET
20252bc21ed9SDavid Malone 		    && cm->cmsg_type == SCM_RIGHTS) {
20262609222aSPawel Jakub Dawidek 			newfds = datalen / sizeof(*fdep);
202782e825c4SGleb Smirnoff 			if (newfds == 0)
202882e825c4SGleb Smirnoff 				goto next;
20292609222aSPawel Jakub Dawidek 			fdep = data;
20302bc21ed9SDavid Malone 
2031e2f9a08bSOlivier Houchard 			/* If we're not outputting the descriptors free them. */
20322bc21ed9SDavid Malone 			if (error || controlp == NULL) {
20332609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20342bc21ed9SDavid Malone 				goto next;
20352bc21ed9SDavid Malone 			}
20362609222aSPawel Jakub Dawidek 			FILEDESC_XLOCK(fdesc);
203760a5ef26SRobert Watson 
2038ed5b7817SJulian Elischer 			/*
20391c381b19SRobert Watson 			 * Now change each pointer to an fd in the global
20401c381b19SRobert Watson 			 * table to an integer that is the index to the local
20411c381b19SRobert Watson 			 * fd table entry that we set up to point to the
20421c381b19SRobert Watson 			 * global one we are transferring.
2043ed5b7817SJulian Elischer 			 */
20442bc21ed9SDavid Malone 			newlen = newfds * sizeof(int);
20452bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
20462bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
20472bc21ed9SDavid Malone 			if (*controlp == NULL) {
20482609222aSPawel Jakub Dawidek 				FILEDESC_XUNLOCK(fdesc);
20492bc21ed9SDavid Malone 				error = E2BIG;
20502609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20512bc21ed9SDavid Malone 				goto next;
20522bc21ed9SDavid Malone 			}
20532bc21ed9SDavid Malone 
20542bc21ed9SDavid Malone 			fdp = (int *)
20552bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2056db8f33fdSMateusz Guzik 			if (fdallocn(td, 0, fdp, newfds) != 0) {
20573331a33aSMateusz Guzik 				FILEDESC_XUNLOCK(fdesc);
2058db8f33fdSMateusz Guzik 				error = EMSGSIZE;
2059db8f33fdSMateusz Guzik 				unp_freerights(fdep, newfds);
2060db8f33fdSMateusz Guzik 				m_freem(*controlp);
2061db8f33fdSMateusz Guzik 				*controlp = NULL;
2062db8f33fdSMateusz Guzik 				goto next;
2063db8f33fdSMateusz Guzik 			}
20648cb539f1SPawel Jakub Dawidek 			for (i = 0; i < newfds; i++, fdp++) {
2065ea31808cSMateusz Guzik 				_finstall(fdesc, fdep[i]->fde_file, *fdp,
2066ea31808cSMateusz Guzik 				    (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
2067ea31808cSMateusz Guzik 				    &fdep[i]->fde_caps);
2068ea31808cSMateusz Guzik 				unp_externalize_fp(fdep[i]->fde_file);
2069df8bae1dSRodney W. Grimes 			}
2070c7902fbeSMark Johnston 
2071c7902fbeSMark Johnston 			/*
2072c7902fbeSMark Johnston 			 * The new type indicates that the mbuf data refers to
2073c7902fbeSMark Johnston 			 * kernel resources that may need to be released before
2074c7902fbeSMark Johnston 			 * the mbuf is freed.
2075c7902fbeSMark Johnston 			 */
2076c7902fbeSMark Johnston 			m_chtype(*controlp, MT_EXTCONTROL);
20772609222aSPawel Jakub Dawidek 			FILEDESC_XUNLOCK(fdesc);
20788cb539f1SPawel Jakub Dawidek 			free(fdep[0], M_FILECAPS);
20791c381b19SRobert Watson 		} else {
20801c381b19SRobert Watson 			/* We can just copy anything else across. */
20812bc21ed9SDavid Malone 			if (error || controlp == NULL)
20822bc21ed9SDavid Malone 				goto next;
20832bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, datalen,
20842bc21ed9SDavid Malone 			    cm->cmsg_type, cm->cmsg_level);
20852bc21ed9SDavid Malone 			if (*controlp == NULL) {
20862bc21ed9SDavid Malone 				error = ENOBUFS;
20872bc21ed9SDavid Malone 				goto next;
20882bc21ed9SDavid Malone 			}
20892bc21ed9SDavid Malone 			bcopy(data,
20902bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
20912bc21ed9SDavid Malone 			    datalen);
20922bc21ed9SDavid Malone 		}
20932bc21ed9SDavid Malone 		controlp = &(*controlp)->m_next;
20942bc21ed9SDavid Malone 
20952bc21ed9SDavid Malone next:
20962bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
20972bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
20982bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
20992bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
21008692c025SYoshinobu Inoue 		} else {
21012bc21ed9SDavid Malone 			clen = 0;
21022bc21ed9SDavid Malone 			cm = NULL;
21038692c025SYoshinobu Inoue 		}
21048692c025SYoshinobu Inoue 	}
21058692c025SYoshinobu Inoue 
21062bc21ed9SDavid Malone 	m_freem(control);
21072bc21ed9SDavid Malone 	return (error);
2108df8bae1dSRodney W. Grimes }
2109df8bae1dSRodney W. Grimes 
21104f590175SPaul Saab static void
21114f590175SPaul Saab unp_zone_change(void *tag)
21124f590175SPaul Saab {
21134f590175SPaul Saab 
21144f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21154f590175SPaul Saab }
21164f590175SPaul Saab 
21175362170dSMark Johnston #ifdef INVARIANTS
21185362170dSMark Johnston static void
21195362170dSMark Johnston unp_zdtor(void *mem, int size __unused, void *arg __unused)
21205362170dSMark Johnston {
21215362170dSMark Johnston 	struct unpcb *unp;
21225362170dSMark Johnston 
21235362170dSMark Johnston 	unp = mem;
21245362170dSMark Johnston 
21255362170dSMark Johnston 	KASSERT(LIST_EMPTY(&unp->unp_refs),
21265362170dSMark Johnston 	    ("%s: unpcb %p has lingering refs", __func__, unp));
21275362170dSMark Johnston 	KASSERT(unp->unp_socket == NULL,
21285362170dSMark Johnston 	    ("%s: unpcb %p has socket backpointer", __func__, unp));
21295362170dSMark Johnston 	KASSERT(unp->unp_vnode == NULL,
21305362170dSMark Johnston 	    ("%s: unpcb %p has vnode references", __func__, unp));
21315362170dSMark Johnston 	KASSERT(unp->unp_conn == NULL,
21325362170dSMark Johnston 	    ("%s: unpcb %p is still connected", __func__, unp));
21335362170dSMark Johnston 	KASSERT(unp->unp_addr == NULL,
21345362170dSMark Johnston 	    ("%s: unpcb %p has leaked addr", __func__, unp));
21355362170dSMark Johnston }
21365362170dSMark Johnston #endif
21375362170dSMark Johnston 
21380b36cd25SRobert Watson static void
213998271db4SGarrett Wollman unp_init(void)
214098271db4SGarrett Wollman {
21415362170dSMark Johnston 	uma_dtor dtor;
21421c381b19SRobert Watson 
214321ca7b57SMarko Zec #ifdef VIMAGE
214421ca7b57SMarko Zec 	if (!IS_DEFAULT_VNET(curvnet))
214521ca7b57SMarko Zec 		return;
214621ca7b57SMarko Zec #endif
21475362170dSMark Johnston 
21485362170dSMark Johnston #ifdef INVARIANTS
21495362170dSMark Johnston 	dtor = unp_zdtor;
21505362170dSMark Johnston #else
21515362170dSMark Johnston 	dtor = NULL;
21525362170dSMark Johnston #endif
21535362170dSMark Johnston 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
215475a67bf3SMatt Macy 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
21554f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21566e0b6746SPawel Jakub Dawidek 	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
21574f590175SPaul Saab 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
21584f590175SPaul Saab 	    NULL, EVENTHANDLER_PRI_ANY);
215998271db4SGarrett Wollman 	LIST_INIT(&unp_dhead);
216098271db4SGarrett Wollman 	LIST_INIT(&unp_shead);
216184d61770SRobert Watson 	LIST_INIT(&unp_sphead);
21620cb64678SKonstantin Belousov 	SLIST_INIT(&unp_defers);
2163daee0f0bSKonstantin Belousov 	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
21640cb64678SKonstantin Belousov 	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
21653dab55bcSRobert Watson 	UNP_LINK_LOCK_INIT();
21660cb64678SKonstantin Belousov 	UNP_DEFERRED_LOCK_INIT();
216798271db4SGarrett Wollman }
216898271db4SGarrett Wollman 
216947c3450eSKonstantin Belousov static void
217047c3450eSKonstantin Belousov unp_internalize_cleanup_rights(struct mbuf *control)
217147c3450eSKonstantin Belousov {
217247c3450eSKonstantin Belousov 	struct cmsghdr *cp;
217347c3450eSKonstantin Belousov 	struct mbuf *m;
217447c3450eSKonstantin Belousov 	void *data;
217547c3450eSKonstantin Belousov 	socklen_t datalen;
217647c3450eSKonstantin Belousov 
217747c3450eSKonstantin Belousov 	for (m = control; m != NULL; m = m->m_next) {
217847c3450eSKonstantin Belousov 		cp = mtod(m, struct cmsghdr *);
217947c3450eSKonstantin Belousov 		if (cp->cmsg_level != SOL_SOCKET ||
218047c3450eSKonstantin Belousov 		    cp->cmsg_type != SCM_RIGHTS)
218147c3450eSKonstantin Belousov 			continue;
218247c3450eSKonstantin Belousov 		data = CMSG_DATA(cp);
218347c3450eSKonstantin Belousov 		datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
218447c3450eSKonstantin Belousov 		unp_freerights(data, datalen / sizeof(struct filedesc *));
218547c3450eSKonstantin Belousov 	}
218647c3450eSKonstantin Belousov }
218747c3450eSKonstantin Belousov 
2188f708ef1bSPoul-Henning Kamp static int
2189892af6b9SRobert Watson unp_internalize(struct mbuf **controlp, struct thread *td)
2190df8bae1dSRodney W. Grimes {
219147c3450eSKonstantin Belousov 	struct mbuf *control, **initial_controlp;
219247c3450eSKonstantin Belousov 	struct proc *p;
219347c3450eSKonstantin Belousov 	struct filedesc *fdesc;
2194ab15d803SSergey Kandaurov 	struct bintime *bt;
219547c3450eSKonstantin Belousov 	struct cmsghdr *cm;
21962bc21ed9SDavid Malone 	struct cmsgcred *cmcred;
21978cb539f1SPawel Jakub Dawidek 	struct filedescent *fde, **fdep, *fdev;
21982bc21ed9SDavid Malone 	struct file *fp;
21992bc21ed9SDavid Malone 	struct timeval *tv;
2200339efd75SMaxim Sobolev 	struct timespec *ts;
22012bc21ed9SDavid Malone 	void *data;
220247c3450eSKonstantin Belousov 	socklen_t clen, datalen;
2203f1cf2b9dSKonstantin Belousov 	int i, j, error, *fdp, oldfds;
22048692c025SYoshinobu Inoue 	u_int newlen;
2205df8bae1dSRodney W. Grimes 
22063dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
22074c5bc1caSRobert Watson 
220847c3450eSKonstantin Belousov 	p = td->td_proc;
220947c3450eSKonstantin Belousov 	fdesc = p->p_fd;
22102bc21ed9SDavid Malone 	error = 0;
221147c3450eSKonstantin Belousov 	control = *controlp;
221247c3450eSKonstantin Belousov 	clen = control->m_len;
22132bc21ed9SDavid Malone 	*controlp = NULL;
221447c3450eSKonstantin Belousov 	initial_controlp = controlp;
221547c3450eSKonstantin Belousov 	for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
22162bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2217de966666SMateusz Guzik 		    || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
22182bc21ed9SDavid Malone 			error = EINVAL;
22192bc21ed9SDavid Malone 			goto out;
22202bc21ed9SDavid Malone 		}
22212bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
22222bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
22232bc21ed9SDavid Malone 
22242bc21ed9SDavid Malone 		switch (cm->cmsg_type) {
22250b788fa1SBill Paul 		/*
22260b788fa1SBill Paul 		 * Fill in credential information.
22270b788fa1SBill Paul 		 */
22282bc21ed9SDavid Malone 		case SCM_CREDS:
22292bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
22302bc21ed9SDavid Malone 			    SCM_CREDS, SOL_SOCKET);
22312bc21ed9SDavid Malone 			if (*controlp == NULL) {
22322bc21ed9SDavid Malone 				error = ENOBUFS;
22332bc21ed9SDavid Malone 				goto out;
22342bc21ed9SDavid Malone 			}
22352bc21ed9SDavid Malone 			cmcred = (struct cmsgcred *)
22362bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
22370b788fa1SBill Paul 			cmcred->cmcred_pid = p->p_pid;
2238a854ed98SJohn Baldwin 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2239a854ed98SJohn Baldwin 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2240a854ed98SJohn Baldwin 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
2241a854ed98SJohn Baldwin 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
22420b788fa1SBill Paul 			    CMGROUP_MAX);
22430b788fa1SBill Paul 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
22442bc21ed9SDavid Malone 				cmcred->cmcred_groups[i] =
2245a854ed98SJohn Baldwin 				    td->td_ucred->cr_groups[i];
22462bc21ed9SDavid Malone 			break;
22470b788fa1SBill Paul 
22482bc21ed9SDavid Malone 		case SCM_RIGHTS:
22492bc21ed9SDavid Malone 			oldfds = datalen / sizeof (int);
225082e825c4SGleb Smirnoff 			if (oldfds == 0)
225182e825c4SGleb Smirnoff 				break;
2252ed5b7817SJulian Elischer 			/*
22531c381b19SRobert Watson 			 * Check that all the FDs passed in refer to legal
22541c381b19SRobert Watson 			 * files.  If not, reject the entire operation.
2255ed5b7817SJulian Elischer 			 */
22562bc21ed9SDavid Malone 			fdp = data;
22572609222aSPawel Jakub Dawidek 			FILEDESC_SLOCK(fdesc);
22586a1cf96bSMateusz Guzik 			for (i = 0; i < oldfds; i++, fdp++) {
22596a1cf96bSMateusz Guzik 				fp = fget_locked(fdesc, *fdp);
22606a1cf96bSMateusz Guzik 				if (fp == NULL) {
22612609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
22622bc21ed9SDavid Malone 					error = EBADF;
22632bc21ed9SDavid Malone 					goto out;
22642bc21ed9SDavid Malone 				}
2265e7d6662fSAlfred Perlstein 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
22662609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
2267e7d6662fSAlfred Perlstein 					error = EOPNOTSUPP;
2268e7d6662fSAlfred Perlstein 					goto out;
2269e7d6662fSAlfred Perlstein 				}
2270df8bae1dSRodney W. Grimes 			}
22715e3f7694SRobert Watson 
2272ed5b7817SJulian Elischer 			/*
22730b36cd25SRobert Watson 			 * Now replace the integer FDs with pointers to the
22742609222aSPawel Jakub Dawidek 			 * file structure and capability rights.
2275ed5b7817SJulian Elischer 			 */
22768cb539f1SPawel Jakub Dawidek 			newlen = oldfds * sizeof(fdep[0]);
22772bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
22782bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
22792bc21ed9SDavid Malone 			if (*controlp == NULL) {
22802609222aSPawel Jakub Dawidek 				FILEDESC_SUNLOCK(fdesc);
22812bc21ed9SDavid Malone 				error = E2BIG;
22822bc21ed9SDavid Malone 				goto out;
22838692c025SYoshinobu Inoue 			}
22842bc21ed9SDavid Malone 			fdp = data;
2285f1cf2b9dSKonstantin Belousov 			for (i = 0; i < oldfds; i++, fdp++) {
2286f1cf2b9dSKonstantin Belousov 				if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2287f1cf2b9dSKonstantin Belousov 					fdp = data;
2288f1cf2b9dSKonstantin Belousov 					for (j = 0; j < i; j++, fdp++) {
2289f1cf2b9dSKonstantin Belousov 						fdrop(fdesc->fd_ofiles[*fdp].
2290f1cf2b9dSKonstantin Belousov 						    fde_file, td);
2291f1cf2b9dSKonstantin Belousov 					}
2292f1cf2b9dSKonstantin Belousov 					FILEDESC_SUNLOCK(fdesc);
2293f1cf2b9dSKonstantin Belousov 					error = EBADF;
2294f1cf2b9dSKonstantin Belousov 					goto out;
2295f1cf2b9dSKonstantin Belousov 				}
2296f1cf2b9dSKonstantin Belousov 			}
2297f1cf2b9dSKonstantin Belousov 			fdp = data;
22988cb539f1SPawel Jakub Dawidek 			fdep = (struct filedescent **)
22992bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23008cb539f1SPawel Jakub Dawidek 			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
23018cb539f1SPawel Jakub Dawidek 			    M_WAITOK);
23028cb539f1SPawel Jakub Dawidek 			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
23032609222aSPawel Jakub Dawidek 				fde = &fdesc->fd_ofiles[*fdp];
23048cb539f1SPawel Jakub Dawidek 				fdep[i] = fdev;
23058cb539f1SPawel Jakub Dawidek 				fdep[i]->fde_file = fde->fde_file;
23068cb539f1SPawel Jakub Dawidek 				filecaps_copy(&fde->fde_caps,
2307d7832811SMateusz Guzik 				    &fdep[i]->fde_caps, true);
23088cb539f1SPawel Jakub Dawidek 				unp_internalize_fp(fdep[i]->fde_file);
2309df8bae1dSRodney W. Grimes 			}
23102609222aSPawel Jakub Dawidek 			FILEDESC_SUNLOCK(fdesc);
23112bc21ed9SDavid Malone 			break;
23122bc21ed9SDavid Malone 
23132bc21ed9SDavid Malone 		case SCM_TIMESTAMP:
23142bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
23152bc21ed9SDavid Malone 			    SCM_TIMESTAMP, SOL_SOCKET);
23162bc21ed9SDavid Malone 			if (*controlp == NULL) {
23172bc21ed9SDavid Malone 				error = ENOBUFS;
23182bc21ed9SDavid Malone 				goto out;
23198692c025SYoshinobu Inoue 			}
23202bc21ed9SDavid Malone 			tv = (struct timeval *)
23212bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23222bc21ed9SDavid Malone 			microtime(tv);
23232bc21ed9SDavid Malone 			break;
23242bc21ed9SDavid Malone 
2325ab15d803SSergey Kandaurov 		case SCM_BINTIME:
2326ab15d803SSergey Kandaurov 			*controlp = sbcreatecontrol(NULL, sizeof(*bt),
2327ab15d803SSergey Kandaurov 			    SCM_BINTIME, SOL_SOCKET);
2328ab15d803SSergey Kandaurov 			if (*controlp == NULL) {
2329ab15d803SSergey Kandaurov 				error = ENOBUFS;
2330ab15d803SSergey Kandaurov 				goto out;
2331ab15d803SSergey Kandaurov 			}
2332ab15d803SSergey Kandaurov 			bt = (struct bintime *)
2333ab15d803SSergey Kandaurov 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2334ab15d803SSergey Kandaurov 			bintime(bt);
2335ab15d803SSergey Kandaurov 			break;
2336ab15d803SSergey Kandaurov 
2337339efd75SMaxim Sobolev 		case SCM_REALTIME:
2338339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2339339efd75SMaxim Sobolev 			    SCM_REALTIME, SOL_SOCKET);
2340339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2341339efd75SMaxim Sobolev 				error = ENOBUFS;
2342339efd75SMaxim Sobolev 				goto out;
2343339efd75SMaxim Sobolev 			}
2344339efd75SMaxim Sobolev 			ts = (struct timespec *)
2345339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2346339efd75SMaxim Sobolev 			nanotime(ts);
2347339efd75SMaxim Sobolev 			break;
2348339efd75SMaxim Sobolev 
2349339efd75SMaxim Sobolev 		case SCM_MONOTONIC:
2350339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2351339efd75SMaxim Sobolev 			    SCM_MONOTONIC, SOL_SOCKET);
2352339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2353339efd75SMaxim Sobolev 				error = ENOBUFS;
2354339efd75SMaxim Sobolev 				goto out;
2355339efd75SMaxim Sobolev 			}
2356339efd75SMaxim Sobolev 			ts = (struct timespec *)
2357339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2358339efd75SMaxim Sobolev 			nanouptime(ts);
2359339efd75SMaxim Sobolev 			break;
2360339efd75SMaxim Sobolev 
23612bc21ed9SDavid Malone 		default:
23622bc21ed9SDavid Malone 			error = EINVAL;
23632bc21ed9SDavid Malone 			goto out;
23642bc21ed9SDavid Malone 		}
23652bc21ed9SDavid Malone 
23664013d726SMark Johnston 		if (*controlp != NULL)
23672bc21ed9SDavid Malone 			controlp = &(*controlp)->m_next;
23682bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
23692bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
23702bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
23712bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
23722bc21ed9SDavid Malone 		} else {
23732bc21ed9SDavid Malone 			clen = 0;
23742bc21ed9SDavid Malone 			cm = NULL;
23752bc21ed9SDavid Malone 		}
23762bc21ed9SDavid Malone 	}
23772bc21ed9SDavid Malone 
23782bc21ed9SDavid Malone out:
237947c3450eSKonstantin Belousov 	if (error != 0 && initial_controlp != NULL)
238047c3450eSKonstantin Belousov 		unp_internalize_cleanup_rights(*initial_controlp);
23812bc21ed9SDavid Malone 	m_freem(control);
23822bc21ed9SDavid Malone 	return (error);
2383df8bae1dSRodney W. Grimes }
2384df8bae1dSRodney W. Grimes 
23855b950deaSRobert Watson static struct mbuf *
23866a2989fdSMatthew N. Dodd unp_addsockcred(struct thread *td, struct mbuf *control)
23876a2989fdSMatthew N. Dodd {
238870df31f4SMaxim Konovalov 	struct mbuf *m, *n, *n_prev;
23896a2989fdSMatthew N. Dodd 	struct sockcred *sc;
239070df31f4SMaxim Konovalov 	const struct cmsghdr *cm;
23916a2989fdSMatthew N. Dodd 	int ngroups;
23926a2989fdSMatthew N. Dodd 	int i;
23936a2989fdSMatthew N. Dodd 
23946a2989fdSMatthew N. Dodd 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
23956a2989fdSMatthew N. Dodd 	m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
23966a2989fdSMatthew N. Dodd 	if (m == NULL)
23976a2989fdSMatthew N. Dodd 		return (control);
23986a2989fdSMatthew N. Dodd 
23996a2989fdSMatthew N. Dodd 	sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
24006a2989fdSMatthew N. Dodd 	sc->sc_uid = td->td_ucred->cr_ruid;
24016a2989fdSMatthew N. Dodd 	sc->sc_euid = td->td_ucred->cr_uid;
24026a2989fdSMatthew N. Dodd 	sc->sc_gid = td->td_ucred->cr_rgid;
24036a2989fdSMatthew N. Dodd 	sc->sc_egid = td->td_ucred->cr_gid;
24046a2989fdSMatthew N. Dodd 	sc->sc_ngroups = ngroups;
24056a2989fdSMatthew N. Dodd 	for (i = 0; i < sc->sc_ngroups; i++)
24066a2989fdSMatthew N. Dodd 		sc->sc_groups[i] = td->td_ucred->cr_groups[i];
24076a2989fdSMatthew N. Dodd 
24086a2989fdSMatthew N. Dodd 	/*
24091c381b19SRobert Watson 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
24101c381b19SRobert Watson 	 * created SCM_CREDS control message (struct sockcred) has another
24111c381b19SRobert Watson 	 * format.
24126a2989fdSMatthew N. Dodd 	 */
241370df31f4SMaxim Konovalov 	if (control != NULL)
241470df31f4SMaxim Konovalov 		for (n = control, n_prev = NULL; n != NULL;) {
241570df31f4SMaxim Konovalov 			cm = mtod(n, struct cmsghdr *);
241670df31f4SMaxim Konovalov     			if (cm->cmsg_level == SOL_SOCKET &&
241770df31f4SMaxim Konovalov 			    cm->cmsg_type == SCM_CREDS) {
241870df31f4SMaxim Konovalov     				if (n_prev == NULL)
241970df31f4SMaxim Konovalov 					control = n->m_next;
242070df31f4SMaxim Konovalov 				else
242170df31f4SMaxim Konovalov 					n_prev->m_next = n->m_next;
242270df31f4SMaxim Konovalov 				n = m_free(n);
242370df31f4SMaxim Konovalov 			} else {
242470df31f4SMaxim Konovalov 				n_prev = n;
242570df31f4SMaxim Konovalov 				n = n->m_next;
242670df31f4SMaxim Konovalov 			}
242770df31f4SMaxim Konovalov 		}
24286a2989fdSMatthew N. Dodd 
242970df31f4SMaxim Konovalov 	/* Prepend it to the head. */
243070df31f4SMaxim Konovalov 	m->m_next = control;
243170df31f4SMaxim Konovalov 	return (m);
24326a2989fdSMatthew N. Dodd }
24336a2989fdSMatthew N. Dodd 
2434397c19d1SJeff Roberson static struct unpcb *
2435397c19d1SJeff Roberson fptounp(struct file *fp)
2436397c19d1SJeff Roberson {
2437397c19d1SJeff Roberson 	struct socket *so;
2438397c19d1SJeff Roberson 
2439397c19d1SJeff Roberson 	if (fp->f_type != DTYPE_SOCKET)
2440397c19d1SJeff Roberson 		return (NULL);
2441397c19d1SJeff Roberson 	if ((so = fp->f_data) == NULL)
2442397c19d1SJeff Roberson 		return (NULL);
2443397c19d1SJeff Roberson 	if (so->so_proto->pr_domain != &localdomain)
2444397c19d1SJeff Roberson 		return (NULL);
2445397c19d1SJeff Roberson 	return sotounpcb(so);
2446397c19d1SJeff Roberson }
2447397c19d1SJeff Roberson 
2448397c19d1SJeff Roberson static void
2449397c19d1SJeff Roberson unp_discard(struct file *fp)
2450397c19d1SJeff Roberson {
24510cb64678SKonstantin Belousov 	struct unp_defer *dr;
2452397c19d1SJeff Roberson 
24530cb64678SKonstantin Belousov 	if (unp_externalize_fp(fp)) {
24540cb64678SKonstantin Belousov 		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
24550cb64678SKonstantin Belousov 		dr->ud_fp = fp;
24560cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
24570cb64678SKonstantin Belousov 		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
24580cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
24590cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, 1);
24600cb64678SKonstantin Belousov 		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
24610cb64678SKonstantin Belousov 	} else
2462397c19d1SJeff Roberson 		(void) closef(fp, (struct thread *)NULL);
2463397c19d1SJeff Roberson }
2464397c19d1SJeff Roberson 
2465397c19d1SJeff Roberson static void
24660cb64678SKonstantin Belousov unp_process_defers(void *arg __unused, int pending)
24670cb64678SKonstantin Belousov {
24680cb64678SKonstantin Belousov 	struct unp_defer *dr;
24690cb64678SKonstantin Belousov 	SLIST_HEAD(, unp_defer) drl;
24700cb64678SKonstantin Belousov 	int count;
24710cb64678SKonstantin Belousov 
24720cb64678SKonstantin Belousov 	SLIST_INIT(&drl);
24730cb64678SKonstantin Belousov 	for (;;) {
24740cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
24750cb64678SKonstantin Belousov 		if (SLIST_FIRST(&unp_defers) == NULL) {
24760cb64678SKonstantin Belousov 			UNP_DEFERRED_UNLOCK();
24770cb64678SKonstantin Belousov 			break;
24780cb64678SKonstantin Belousov 		}
24790cb64678SKonstantin Belousov 		SLIST_SWAP(&unp_defers, &drl, unp_defer);
24800cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
24810cb64678SKonstantin Belousov 		count = 0;
24820cb64678SKonstantin Belousov 		while ((dr = SLIST_FIRST(&drl)) != NULL) {
24830cb64678SKonstantin Belousov 			SLIST_REMOVE_HEAD(&drl, ud_link);
24840cb64678SKonstantin Belousov 			closef(dr->ud_fp, NULL);
24850cb64678SKonstantin Belousov 			free(dr, M_TEMP);
24860cb64678SKonstantin Belousov 			count++;
24870cb64678SKonstantin Belousov 		}
24880cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, -count);
24890cb64678SKonstantin Belousov 	}
24900cb64678SKonstantin Belousov }
24910cb64678SKonstantin Belousov 
24920cb64678SKonstantin Belousov static void
2493397c19d1SJeff Roberson unp_internalize_fp(struct file *fp)
2494397c19d1SJeff Roberson {
2495397c19d1SJeff Roberson 	struct unpcb *unp;
2496397c19d1SJeff Roberson 
24973dab55bcSRobert Watson 	UNP_LINK_WLOCK();
2498397c19d1SJeff Roberson 	if ((unp = fptounp(fp)) != NULL) {
2499397c19d1SJeff Roberson 		unp->unp_file = fp;
2500397c19d1SJeff Roberson 		unp->unp_msgcount++;
2501397c19d1SJeff Roberson 	}
2502397c19d1SJeff Roberson 	unp_rights++;
25033dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
2504397c19d1SJeff Roberson }
2505397c19d1SJeff Roberson 
25060cb64678SKonstantin Belousov static int
2507397c19d1SJeff Roberson unp_externalize_fp(struct file *fp)
2508397c19d1SJeff Roberson {
2509397c19d1SJeff Roberson 	struct unpcb *unp;
25100cb64678SKonstantin Belousov 	int ret;
2511397c19d1SJeff Roberson 
25123dab55bcSRobert Watson 	UNP_LINK_WLOCK();
25130cb64678SKonstantin Belousov 	if ((unp = fptounp(fp)) != NULL) {
2514397c19d1SJeff Roberson 		unp->unp_msgcount--;
25150cb64678SKonstantin Belousov 		ret = 1;
25160cb64678SKonstantin Belousov 	} else
25170cb64678SKonstantin Belousov 		ret = 0;
2518397c19d1SJeff Roberson 	unp_rights--;
25193dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
25200cb64678SKonstantin Belousov 	return (ret);
2521397c19d1SJeff Roberson }
2522397c19d1SJeff Roberson 
2523161a0c7cSRobert Watson /*
2524a0ec558aSRobert Watson  * unp_defer indicates whether additional work has been defered for a future
2525a0ec558aSRobert Watson  * pass through unp_gc().  It is thread local and does not require explicit
2526a0ec558aSRobert Watson  * synchronization.
2527161a0c7cSRobert Watson  */
2528397c19d1SJeff Roberson static int	unp_marked;
2529a0ec558aSRobert Watson 
2530397c19d1SJeff Roberson static void
2531a9aa06f7SJason A. Harmening unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2532397c19d1SJeff Roberson {
2533397c19d1SJeff Roberson 	struct unpcb *unp;
2534be26ba7cSPawel Jakub Dawidek 	struct file *fp;
2535be26ba7cSPawel Jakub Dawidek 	int i;
2536397c19d1SJeff Roberson 
2537a9aa06f7SJason A. Harmening 	/*
2538a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2539a9aa06f7SJason A. Harmening 	 */
2540a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2541a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2542a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2543a9aa06f7SJason A. Harmening 
2544be26ba7cSPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
2545be26ba7cSPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
25466f552cb0SJeff Roberson 		if ((unp = fptounp(fp)) == NULL)
2547be26ba7cSPawel Jakub Dawidek 			continue;
2548a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2549be26ba7cSPawel Jakub Dawidek 			continue;
2550a9aa06f7SJason A. Harmening 		unp->unp_gcrefs--;
2551a9aa06f7SJason A. Harmening 	}
2552a9aa06f7SJason A. Harmening }
2553a9aa06f7SJason A. Harmening 
2554a9aa06f7SJason A. Harmening static void
2555a9aa06f7SJason A. Harmening unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2556a9aa06f7SJason A. Harmening {
2557a9aa06f7SJason A. Harmening 	struct unpcb *unp;
2558a9aa06f7SJason A. Harmening 	struct file *fp;
2559a9aa06f7SJason A. Harmening 	int i;
2560a9aa06f7SJason A. Harmening 
2561a9aa06f7SJason A. Harmening 	/*
2562a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2563a9aa06f7SJason A. Harmening 	 */
2564a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2565a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2566a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2567a9aa06f7SJason A. Harmening 
2568a9aa06f7SJason A. Harmening 	for (i = 0; i < fdcount; i++) {
2569a9aa06f7SJason A. Harmening 		fp = fdep[i]->fde_file;
2570a9aa06f7SJason A. Harmening 		if ((unp = fptounp(fp)) == NULL)
2571a9aa06f7SJason A. Harmening 			continue;
2572a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2573a9aa06f7SJason A. Harmening 			continue;
2574a9aa06f7SJason A. Harmening 		unp->unp_gcrefs++;
2575397c19d1SJeff Roberson 		unp_marked++;
2576397c19d1SJeff Roberson 	}
2577be26ba7cSPawel Jakub Dawidek }
2578397c19d1SJeff Roberson 
2579397c19d1SJeff Roberson static void
2580a9aa06f7SJason A. Harmening unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2581397c19d1SJeff Roberson {
2582779f106aSGleb Smirnoff 	struct socket *so, *soa;
258360a5ef26SRobert Watson 
2584397c19d1SJeff Roberson 	so = unp->unp_socket;
2585779f106aSGleb Smirnoff 	SOCK_LOCK(so);
2586779f106aSGleb Smirnoff 	if (SOLISTENING(so)) {
2587397c19d1SJeff Roberson 		/*
2588397c19d1SJeff Roberson 		 * Mark all sockets in our accept queue.
2589397c19d1SJeff Roberson 		 */
2590779f106aSGleb Smirnoff 		TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2591779f106aSGleb Smirnoff 			if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
25920c40f353SConrad Meyer 				continue;
2593397c19d1SJeff Roberson 			SOCKBUF_LOCK(&soa->so_rcv);
2594a9aa06f7SJason A. Harmening 			unp_scan(soa->so_rcv.sb_mb, op);
2595397c19d1SJeff Roberson 			SOCKBUF_UNLOCK(&soa->so_rcv);
2596397c19d1SJeff Roberson 		}
2597779f106aSGleb Smirnoff 	} else {
2598779f106aSGleb Smirnoff 		/*
2599779f106aSGleb Smirnoff 		 * Mark all sockets we reference with RIGHTS.
2600779f106aSGleb Smirnoff 		 */
2601779f106aSGleb Smirnoff 		if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2602779f106aSGleb Smirnoff 			SOCKBUF_LOCK(&so->so_rcv);
2603a9aa06f7SJason A. Harmening 			unp_scan(so->so_rcv.sb_mb, op);
2604779f106aSGleb Smirnoff 			SOCKBUF_UNLOCK(&so->so_rcv);
2605779f106aSGleb Smirnoff 		}
2606779f106aSGleb Smirnoff 	}
2607779f106aSGleb Smirnoff 	SOCK_UNLOCK(so);
2608397c19d1SJeff Roberson }
2609a0ec558aSRobert Watson 
2610a0ec558aSRobert Watson static int unp_recycled;
2611be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2612be6b1304STom Rhodes     "Number of unreachable sockets claimed by the garbage collector.");
2613df8bae1dSRodney W. Grimes 
2614397c19d1SJeff Roberson static int unp_taskcount;
2615be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2616be6b1304STom Rhodes     "Number of times the garbage collector has run.");
2617397c19d1SJeff Roberson 
2618a9aa06f7SJason A. Harmening SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
2619a9aa06f7SJason A. Harmening     "Number of active local sockets.");
2620a9aa06f7SJason A. Harmening 
2621f708ef1bSPoul-Henning Kamp static void
2622a0ec558aSRobert Watson unp_gc(__unused void *arg, int pending)
2623df8bae1dSRodney W. Grimes {
262484d61770SRobert Watson 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
262584d61770SRobert Watson 				    NULL };
2626397c19d1SJeff Roberson 	struct unp_head **head;
2627a9aa06f7SJason A. Harmening 	struct unp_head unp_deadhead;	/* List of potentially-dead sockets. */
2628f7780c61SKonstantin Belousov 	struct file *f, **unref;
2629a9aa06f7SJason A. Harmening 	struct unpcb *unp, *unptmp;
2630a9aa06f7SJason A. Harmening 	int i, total, unp_unreachable;
2631df8bae1dSRodney W. Grimes 
2632a9aa06f7SJason A. Harmening 	LIST_INIT(&unp_deadhead);
2633a0ec558aSRobert Watson 	unp_taskcount++;
2634779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
2635ed5b7817SJulian Elischer 	/*
2636a9aa06f7SJason A. Harmening 	 * First determine which sockets may be in cycles.
2637ed5b7817SJulian Elischer 	 */
2638a9aa06f7SJason A. Harmening 	unp_unreachable = 0;
2639a9aa06f7SJason A. Harmening 
2640397c19d1SJeff Roberson 	for (head = heads; *head != NULL; head++)
2641a9aa06f7SJason A. Harmening 		LIST_FOREACH(unp, *head, unp_link) {
2642a9aa06f7SJason A. Harmening 			KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2643a9aa06f7SJason A. Harmening 			    ("%s: unp %p has unexpected gc flags 0x%x",
2644a9aa06f7SJason A. Harmening 			    __func__, unp, (unsigned int)unp->unp_gcflag));
2645a9aa06f7SJason A. Harmening 
2646a9aa06f7SJason A. Harmening 			f = unp->unp_file;
264760a5ef26SRobert Watson 
2648397c19d1SJeff Roberson 			/*
2649a9aa06f7SJason A. Harmening 			 * Check for an unreachable socket potentially in a
2650a9aa06f7SJason A. Harmening 			 * cycle.  It must be in a queue as indicated by
2651a9aa06f7SJason A. Harmening 			 * msgcount, and this must equal the file reference
2652a9aa06f7SJason A. Harmening 			 * count.  Note that when msgcount is 0 the file is
2653a9aa06f7SJason A. Harmening 			 * NULL.
2654a9aa06f7SJason A. Harmening 			 */
2655a9aa06f7SJason A. Harmening 			if (f != NULL && unp->unp_msgcount != 0 &&
26563c50616fSMateusz Guzik 			    refcount_load(&f->f_count) == unp->unp_msgcount) {
2657a9aa06f7SJason A. Harmening 				LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2658a9aa06f7SJason A. Harmening 				unp->unp_gcflag |= UNPGC_DEAD;
2659a9aa06f7SJason A. Harmening 				unp->unp_gcrefs = unp->unp_msgcount;
2660a9aa06f7SJason A. Harmening 				unp_unreachable++;
2661a9aa06f7SJason A. Harmening 			}
2662a9aa06f7SJason A. Harmening 		}
2663a9aa06f7SJason A. Harmening 
2664a9aa06f7SJason A. Harmening 	/*
2665a9aa06f7SJason A. Harmening 	 * Scan all sockets previously marked as potentially being in a cycle
2666a9aa06f7SJason A. Harmening 	 * and remove the references each socket holds on any UNPGC_DEAD
2667a9aa06f7SJason A. Harmening 	 * sockets in its queue.  After this step, all remaining references on
2668a9aa06f7SJason A. Harmening 	 * sockets marked UNPGC_DEAD should not be part of any cycle.
2669a9aa06f7SJason A. Harmening 	 */
2670a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead)
2671a9aa06f7SJason A. Harmening 		unp_gc_scan(unp, unp_remove_dead_ref);
2672a9aa06f7SJason A. Harmening 
2673a9aa06f7SJason A. Harmening 	/*
2674a9aa06f7SJason A. Harmening 	 * If a socket still has a non-negative refcount, it cannot be in a
2675a9aa06f7SJason A. Harmening 	 * cycle.  In this case increment refcount of all children iteratively.
2676397c19d1SJeff Roberson 	 * Stop the scan once we do a complete loop without discovering
2677397c19d1SJeff Roberson 	 * a new reachable socket.
2678397c19d1SJeff Roberson 	 */
2679df8bae1dSRodney W. Grimes 	do {
2680397c19d1SJeff Roberson 		unp_marked = 0;
2681a9aa06f7SJason A. Harmening 		LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
2682a9aa06f7SJason A. Harmening 			if (unp->unp_gcrefs > 0) {
2683a9aa06f7SJason A. Harmening 				unp->unp_gcflag &= ~UNPGC_DEAD;
2684a9aa06f7SJason A. Harmening 				LIST_REMOVE(unp, unp_dead);
2685a9aa06f7SJason A. Harmening 				KASSERT(unp_unreachable > 0,
2686a9aa06f7SJason A. Harmening 				    ("%s: unp_unreachable underflow.",
2687a9aa06f7SJason A. Harmening 				    __func__));
2688a9aa06f7SJason A. Harmening 				unp_unreachable--;
2689a9aa06f7SJason A. Harmening 				unp_gc_scan(unp, unp_restore_undead_ref);
2690a9aa06f7SJason A. Harmening 			}
2691397c19d1SJeff Roberson 	} while (unp_marked);
2692a9aa06f7SJason A. Harmening 
2693779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
2694a9aa06f7SJason A. Harmening 
2695397c19d1SJeff Roberson 	if (unp_unreachable == 0)
2696397c19d1SJeff Roberson 		return;
269760a5ef26SRobert Watson 
2698ed5b7817SJulian Elischer 	/*
2699a9aa06f7SJason A. Harmening 	 * Allocate space for a local array of dead unpcbs.
2700a9aa06f7SJason A. Harmening 	 * TODO: can this path be simplified by instead using the local
2701a9aa06f7SJason A. Harmening 	 * dead list at unp_deadhead, after taking out references
2702a9aa06f7SJason A. Harmening 	 * on the file object and/or unpcb and dropping the link lock?
2703ed5b7817SJulian Elischer 	 */
2704397c19d1SJeff Roberson 	unref = malloc(unp_unreachable * sizeof(struct file *),
2705397c19d1SJeff Roberson 	    M_TEMP, M_WAITOK);
270660a5ef26SRobert Watson 
2707ed5b7817SJulian Elischer 	/*
2708397c19d1SJeff Roberson 	 * Iterate looking for sockets which have been specifically marked
2709a9aa06f7SJason A. Harmening 	 * as unreachable and store them locally.
2710ed5b7817SJulian Elischer 	 */
2711f7780c61SKonstantin Belousov 	UNP_LINK_RLOCK();
2712a9aa06f7SJason A. Harmening 	total = 0;
2713a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
2714a9aa06f7SJason A. Harmening 		KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
2715a9aa06f7SJason A. Harmening 		    ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
2716a9aa06f7SJason A. Harmening 		unp->unp_gcflag &= ~UNPGC_DEAD;
2717f7780c61SKonstantin Belousov 		f = unp->unp_file;
2718f7780c61SKonstantin Belousov 		if (unp->unp_msgcount == 0 || f == NULL ||
27193c50616fSMateusz Guzik 		    refcount_load(&f->f_count) != unp->unp_msgcount ||
2720f1cf2b9dSKonstantin Belousov 		    !fhold(f))
2721f7780c61SKonstantin Belousov 			continue;
2722f7780c61SKonstantin Belousov 		unref[total++] = f;
2723f7780c61SKonstantin Belousov 		KASSERT(total <= unp_unreachable,
2724a9aa06f7SJason A. Harmening 		    ("%s: incorrect unreachable count.", __func__));
2725397c19d1SJeff Roberson 	}
2726f7780c61SKonstantin Belousov 	UNP_LINK_RUNLOCK();
272760a5ef26SRobert Watson 
2728ed5b7817SJulian Elischer 	/*
2729397c19d1SJeff Roberson 	 * Now flush all sockets, free'ing rights.  This will free the
2730397c19d1SJeff Roberson 	 * struct files associated with these sockets but leave each socket
2731397c19d1SJeff Roberson 	 * with one remaining ref.
2732ed5b7817SJulian Elischer 	 */
27331fb51a12SBjoern A. Zeeb 	for (i = 0; i < total; i++) {
27341fb51a12SBjoern A. Zeeb 		struct socket *so;
27351fb51a12SBjoern A. Zeeb 
27361fb51a12SBjoern A. Zeeb 		so = unref[i]->f_data;
27371fb51a12SBjoern A. Zeeb 		CURVNET_SET(so->so_vnet);
27381fb51a12SBjoern A. Zeeb 		sorflush(so);
27391fb51a12SBjoern A. Zeeb 		CURVNET_RESTORE();
27401fb51a12SBjoern A. Zeeb 	}
274160a5ef26SRobert Watson 
2742ed5b7817SJulian Elischer 	/*
2743397c19d1SJeff Roberson 	 * And finally release the sockets so they can be reclaimed.
2744ed5b7817SJulian Elischer 	 */
2745f7780c61SKonstantin Belousov 	for (i = 0; i < total; i++)
2746397c19d1SJeff Roberson 		fdrop(unref[i], NULL);
2747f7780c61SKonstantin Belousov 	unp_recycled += total;
2748397c19d1SJeff Roberson 	free(unref, M_TEMP);
2749df8bae1dSRodney W. Grimes }
2750df8bae1dSRodney W. Grimes 
27510b36cd25SRobert Watson static void
275299ab95dbSMark Johnston unp_dispose_mbuf(struct mbuf *m)
2753df8bae1dSRodney W. Grimes {
2754996c772fSJohn Dyson 
2755df8bae1dSRodney W. Grimes 	if (m)
2756be26ba7cSPawel Jakub Dawidek 		unp_scan(m, unp_freerights);
2757df8bae1dSRodney W. Grimes }
2758df8bae1dSRodney W. Grimes 
27590c40f353SConrad Meyer /*
27600c40f353SConrad Meyer  * Synchronize against unp_gc, which can trip over data as we are freeing it.
27610c40f353SConrad Meyer  */
27620c40f353SConrad Meyer static void
276399ab95dbSMark Johnston unp_dispose(struct socket *so)
27640c40f353SConrad Meyer {
27650c40f353SConrad Meyer 	struct unpcb *unp;
27660c40f353SConrad Meyer 
27670c40f353SConrad Meyer 	unp = sotounpcb(so);
2768779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
27690c40f353SConrad Meyer 	unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2770779f106aSGleb Smirnoff 	UNP_LINK_WUNLOCK();
2771779f106aSGleb Smirnoff 	if (!SOLISTENING(so))
277299ab95dbSMark Johnston 		unp_dispose_mbuf(so->so_rcv.sb_mb);
27730c40f353SConrad Meyer }
27740c40f353SConrad Meyer 
2775f708ef1bSPoul-Henning Kamp static void
2776be26ba7cSPawel Jakub Dawidek unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2777df8bae1dSRodney W. Grimes {
27782bc21ed9SDavid Malone 	struct mbuf *m;
27792bc21ed9SDavid Malone 	struct cmsghdr *cm;
27802bc21ed9SDavid Malone 	void *data;
27812bc21ed9SDavid Malone 	socklen_t clen, datalen;
2782df8bae1dSRodney W. Grimes 
2783fc3fcacfSRobert Watson 	while (m0 != NULL) {
27842bc21ed9SDavid Malone 		for (m = m0; m; m = m->m_next) {
278512396bdcSDavid Malone 			if (m->m_type != MT_CONTROL)
2786df8bae1dSRodney W. Grimes 				continue;
27872bc21ed9SDavid Malone 
27882bc21ed9SDavid Malone 			cm = mtod(m, struct cmsghdr *);
27892bc21ed9SDavid Malone 			clen = m->m_len;
27902bc21ed9SDavid Malone 
27912bc21ed9SDavid Malone 			while (cm != NULL) {
27922bc21ed9SDavid Malone 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
27932bc21ed9SDavid Malone 					break;
27942bc21ed9SDavid Malone 
27952bc21ed9SDavid Malone 				data = CMSG_DATA(cm);
27962bc21ed9SDavid Malone 				datalen = (caddr_t)cm + cm->cmsg_len
27972bc21ed9SDavid Malone 				    - (caddr_t)data;
27982bc21ed9SDavid Malone 
27992bc21ed9SDavid Malone 				if (cm->cmsg_level == SOL_SOCKET &&
28002bc21ed9SDavid Malone 				    cm->cmsg_type == SCM_RIGHTS) {
2801be26ba7cSPawel Jakub Dawidek 					(*op)(data, datalen /
2802be26ba7cSPawel Jakub Dawidek 					    sizeof(struct filedescent *));
28032bc21ed9SDavid Malone 				}
28042bc21ed9SDavid Malone 
28052bc21ed9SDavid Malone 				if (CMSG_SPACE(datalen) < clen) {
28062bc21ed9SDavid Malone 					clen -= CMSG_SPACE(datalen);
28072bc21ed9SDavid Malone 					cm = (struct cmsghdr *)
28082bc21ed9SDavid Malone 					    ((caddr_t)cm + CMSG_SPACE(datalen));
28092bc21ed9SDavid Malone 				} else {
28102bc21ed9SDavid Malone 					clen = 0;
28112bc21ed9SDavid Malone 					cm = NULL;
28122bc21ed9SDavid Malone 				}
28132bc21ed9SDavid Malone 			}
2814df8bae1dSRodney W. Grimes 		}
2815c29a3321SKevin Lo 		m0 = m0->m_nextpkt;
2816df8bae1dSRodney W. Grimes 	}
2817df8bae1dSRodney W. Grimes }
2818df8bae1dSRodney W. Grimes 
2819662c901cSMikolaj Golub /*
2820662c901cSMikolaj Golub  * A helper function called by VFS before socket-type vnode reclamation.
2821662c901cSMikolaj Golub  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2822662c901cSMikolaj Golub  * use count.
2823662c901cSMikolaj Golub  */
2824662c901cSMikolaj Golub void
2825662c901cSMikolaj Golub vfs_unp_reclaim(struct vnode *vp)
2826662c901cSMikolaj Golub {
2827662c901cSMikolaj Golub 	struct unpcb *unp;
2828662c901cSMikolaj Golub 	int active;
282975a67bf3SMatt Macy 	struct mtx *vplock;
2830662c901cSMikolaj Golub 
2831662c901cSMikolaj Golub 	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2832662c901cSMikolaj Golub 	KASSERT(vp->v_type == VSOCK,
2833662c901cSMikolaj Golub 	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2834662c901cSMikolaj Golub 
2835662c901cSMikolaj Golub 	active = 0;
283675a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
283775a67bf3SMatt Macy 	mtx_lock(vplock);
28380c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp);
2839662c901cSMikolaj Golub 	if (unp == NULL)
2840662c901cSMikolaj Golub 		goto done;
2841662c901cSMikolaj Golub 	UNP_PCB_LOCK(unp);
2842c7e41c8bSMikolaj Golub 	if (unp->unp_vnode == vp) {
2843c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
2844662c901cSMikolaj Golub 		unp->unp_vnode = NULL;
2845662c901cSMikolaj Golub 		active = 1;
2846662c901cSMikolaj Golub 	}
2847662c901cSMikolaj Golub 	UNP_PCB_UNLOCK(unp);
2848662c901cSMikolaj Golub  done:
284975a67bf3SMatt Macy 	mtx_unlock(vplock);
2850662c901cSMikolaj Golub 	if (active)
2851662c901cSMikolaj Golub 		vunref(vp);
2852662c901cSMikolaj Golub }
2853662c901cSMikolaj Golub 
285403c96c31SRobert Watson #ifdef DDB
285503c96c31SRobert Watson static void
285603c96c31SRobert Watson db_print_indent(int indent)
285703c96c31SRobert Watson {
285803c96c31SRobert Watson 	int i;
285903c96c31SRobert Watson 
286003c96c31SRobert Watson 	for (i = 0; i < indent; i++)
286103c96c31SRobert Watson 		db_printf(" ");
286203c96c31SRobert Watson }
286303c96c31SRobert Watson 
286403c96c31SRobert Watson static void
286503c96c31SRobert Watson db_print_unpflags(int unp_flags)
286603c96c31SRobert Watson {
286703c96c31SRobert Watson 	int comma;
286803c96c31SRobert Watson 
286903c96c31SRobert Watson 	comma = 0;
287003c96c31SRobert Watson 	if (unp_flags & UNP_HAVEPC) {
287103c96c31SRobert Watson 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
287203c96c31SRobert Watson 		comma = 1;
287303c96c31SRobert Watson 	}
28742de07e40SConrad Meyer 	if (unp_flags & UNP_WANTCRED_ALWAYS) {
28752de07e40SConrad Meyer 		db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
28762de07e40SConrad Meyer 		comma = 1;
28772de07e40SConrad Meyer 	}
28782de07e40SConrad Meyer 	if (unp_flags & UNP_WANTCRED_ONESHOT) {
28792de07e40SConrad Meyer 		db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
288003c96c31SRobert Watson 		comma = 1;
288103c96c31SRobert Watson 	}
288203c96c31SRobert Watson 	if (unp_flags & UNP_CONNWAIT) {
288303c96c31SRobert Watson 		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
288403c96c31SRobert Watson 		comma = 1;
288503c96c31SRobert Watson 	}
288603c96c31SRobert Watson 	if (unp_flags & UNP_CONNECTING) {
288703c96c31SRobert Watson 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
288803c96c31SRobert Watson 		comma = 1;
288903c96c31SRobert Watson 	}
289003c96c31SRobert Watson 	if (unp_flags & UNP_BINDING) {
289103c96c31SRobert Watson 		db_printf("%sUNP_BINDING", comma ? ", " : "");
289203c96c31SRobert Watson 		comma = 1;
289303c96c31SRobert Watson 	}
289403c96c31SRobert Watson }
289503c96c31SRobert Watson 
289603c96c31SRobert Watson static void
289703c96c31SRobert Watson db_print_xucred(int indent, struct xucred *xu)
289803c96c31SRobert Watson {
289903c96c31SRobert Watson 	int comma, i;
290003c96c31SRobert Watson 
290103c96c31SRobert Watson 	db_print_indent(indent);
2902c5afec6eSDmitry Chagin 	db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
2903c5afec6eSDmitry Chagin 	    xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
290403c96c31SRobert Watson 	db_print_indent(indent);
290503c96c31SRobert Watson 	db_printf("cr_groups: ");
290603c96c31SRobert Watson 	comma = 0;
290703c96c31SRobert Watson 	for (i = 0; i < xu->cr_ngroups; i++) {
290803c96c31SRobert Watson 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
290903c96c31SRobert Watson 		comma = 1;
291003c96c31SRobert Watson 	}
291103c96c31SRobert Watson 	db_printf("\n");
291203c96c31SRobert Watson }
291303c96c31SRobert Watson 
291403c96c31SRobert Watson static void
291503c96c31SRobert Watson db_print_unprefs(int indent, struct unp_head *uh)
291603c96c31SRobert Watson {
291703c96c31SRobert Watson 	struct unpcb *unp;
291803c96c31SRobert Watson 	int counter;
291903c96c31SRobert Watson 
292003c96c31SRobert Watson 	counter = 0;
292103c96c31SRobert Watson 	LIST_FOREACH(unp, uh, unp_reflink) {
292203c96c31SRobert Watson 		if (counter % 4 == 0)
292303c96c31SRobert Watson 			db_print_indent(indent);
292403c96c31SRobert Watson 		db_printf("%p  ", unp);
292503c96c31SRobert Watson 		if (counter % 4 == 3)
292603c96c31SRobert Watson 			db_printf("\n");
292703c96c31SRobert Watson 		counter++;
292803c96c31SRobert Watson 	}
292903c96c31SRobert Watson 	if (counter != 0 && counter % 4 != 0)
293003c96c31SRobert Watson 		db_printf("\n");
293103c96c31SRobert Watson }
293203c96c31SRobert Watson 
293303c96c31SRobert Watson DB_SHOW_COMMAND(unpcb, db_show_unpcb)
293403c96c31SRobert Watson {
293503c96c31SRobert Watson 	struct unpcb *unp;
293603c96c31SRobert Watson 
293703c96c31SRobert Watson         if (!have_addr) {
293803c96c31SRobert Watson                 db_printf("usage: show unpcb <addr>\n");
293903c96c31SRobert Watson                 return;
294003c96c31SRobert Watson         }
294103c96c31SRobert Watson         unp = (struct unpcb *)addr;
294203c96c31SRobert Watson 
294303c96c31SRobert Watson 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
294403c96c31SRobert Watson 	    unp->unp_vnode);
294503c96c31SRobert Watson 
2946fc8fdae0SMatthew D Fleming 	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
294703c96c31SRobert Watson 	    unp->unp_conn);
294803c96c31SRobert Watson 
294903c96c31SRobert Watson 	db_printf("unp_refs:\n");
295003c96c31SRobert Watson 	db_print_unprefs(2, &unp->unp_refs);
295103c96c31SRobert Watson 
295203c96c31SRobert Watson 	/* XXXRW: Would be nice to print the full address, if any. */
295303c96c31SRobert Watson 	db_printf("unp_addr: %p\n", unp->unp_addr);
295403c96c31SRobert Watson 
2955c2090e73SAlan Somers 	db_printf("unp_gencnt: %llu\n",
295603c96c31SRobert Watson 	    (unsigned long long)unp->unp_gencnt);
295703c96c31SRobert Watson 
295803c96c31SRobert Watson 	db_printf("unp_flags: %x (", unp->unp_flags);
295903c96c31SRobert Watson 	db_print_unpflags(unp->unp_flags);
296003c96c31SRobert Watson 	db_printf(")\n");
296103c96c31SRobert Watson 
296203c96c31SRobert Watson 	db_printf("unp_peercred:\n");
296303c96c31SRobert Watson 	db_print_xucred(2, &unp->unp_peercred);
296403c96c31SRobert Watson 
296503c96c31SRobert Watson 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
296603c96c31SRobert Watson }
296703c96c31SRobert Watson #endif
2968