xref: /freebsd/sys/kern/uipc_usrreq.c (revision ed92e1c78cba5edeb971390aab10c74ab3ad8519)
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)
282e7c33e29SRobert Watson #define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
28375a67bf3SMatt Macy #define	UNP_PCB_TRYLOCK(unp)		mtx_trylock(&(unp)->unp_mtx)
284e7c33e29SRobert Watson #define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
28575a67bf3SMatt Macy #define	UNP_PCB_OWNED(unp)		mtx_owned(&(unp)->unp_mtx)
286e7c33e29SRobert Watson #define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
28775a67bf3SMatt Macy #define	UNP_PCB_UNLOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
2880d9ce3a1SRobert Watson 
2892c899584SRobert Watson static int	uipc_connect2(struct socket *, struct socket *);
2900b36cd25SRobert Watson static int	uipc_ctloutput(struct socket *, struct sockopt *);
291aea52f1bSRobert Watson static int	unp_connect(struct socket *, struct sockaddr *,
292aea52f1bSRobert Watson 		    struct thread *);
2937493f24eSPawel Jakub Dawidek static int	unp_connectat(int, struct socket *, struct sockaddr *,
2947493f24eSPawel Jakub Dawidek 		    struct thread *);
2956a2989fdSMatthew N. Dodd static int	unp_connect2(struct socket *so, struct socket *so2, int);
296e7c33e29SRobert Watson static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
29799ab95dbSMark Johnston static void	unp_dispose(struct socket *so);
29899ab95dbSMark Johnston static void	unp_dispose_mbuf(struct mbuf *);
2994d77a549SAlfred Perlstein static void	unp_shutdown(struct unpcb *);
300afc055d9SEd Schouten static void	unp_drop(struct unpcb *);
301a0ec558aSRobert Watson static void	unp_gc(__unused void *, int);
302be26ba7cSPawel Jakub Dawidek static void	unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
3034d77a549SAlfred Perlstein static void	unp_discard(struct file *);
3048cb539f1SPawel Jakub Dawidek static void	unp_freerights(struct filedescent **, int);
3050b36cd25SRobert Watson static void	unp_init(void);
3064d77a549SAlfred Perlstein static int	unp_internalize(struct mbuf **, struct thread *);
307397c19d1SJeff Roberson static void	unp_internalize_fp(struct file *);
308c2e3c52eSJilles Tjoelker static int	unp_externalize(struct mbuf *, struct mbuf **, int);
3090cb64678SKonstantin Belousov static int	unp_externalize_fp(struct file *);
3105b950deaSRobert Watson static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *);
3110cb64678SKonstantin Belousov static void	unp_process_defers(void * __unused, int);
312f708ef1bSPoul-Henning Kamp 
31375a67bf3SMatt Macy static void
31475a67bf3SMatt Macy unp_pcb_hold(struct unpcb *unp)
31575a67bf3SMatt Macy {
3165362170dSMark Johnston 	u_int old __unused;
3175362170dSMark Johnston 
3185362170dSMark Johnston 	old = refcount_acquire(&unp->unp_refcount);
3195362170dSMark Johnston 	KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
32075a67bf3SMatt Macy }
32175a67bf3SMatt Macy 
3225362170dSMark Johnston static __result_use_check bool
32375a67bf3SMatt Macy unp_pcb_rele(struct unpcb *unp)
32475a67bf3SMatt Macy {
3255362170dSMark Johnston 	bool ret;
32675a67bf3SMatt Macy 
32775a67bf3SMatt Macy 	UNP_PCB_LOCK_ASSERT(unp);
3285362170dSMark Johnston 
3295362170dSMark Johnston 	if ((ret = refcount_release(&unp->unp_refcount))) {
33075a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
33175a67bf3SMatt Macy 		UNP_PCB_LOCK_DESTROY(unp);
33275a67bf3SMatt Macy 		uma_zfree(unp_zone, unp);
33375a67bf3SMatt Macy 	}
3345362170dSMark Johnston 	return (ret);
33575a67bf3SMatt Macy }
33675a67bf3SMatt Macy 
33775a67bf3SMatt Macy static void
338f0317f86SMark Johnston unp_pcb_rele_notlast(struct unpcb *unp)
339f0317f86SMark Johnston {
340f0317f86SMark Johnston 	bool ret __unused;
341f0317f86SMark Johnston 
342f0317f86SMark Johnston 	ret = refcount_release(&unp->unp_refcount);
343f0317f86SMark Johnston 	KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
344f0317f86SMark Johnston }
345f0317f86SMark Johnston 
346f0317f86SMark Johnston static void
3474820bf6aSMark Johnston unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
34875a67bf3SMatt Macy {
34975a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
35075a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp2);
3514820bf6aSMark Johnston 
3524820bf6aSMark Johnston 	if (unp == unp2) {
3534820bf6aSMark Johnston 		UNP_PCB_LOCK(unp);
3544820bf6aSMark Johnston 	} else if ((uintptr_t)unp2 > (uintptr_t)unp) {
35575a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
35675a67bf3SMatt Macy 		UNP_PCB_LOCK(unp2);
35775a67bf3SMatt Macy 	} else {
35875a67bf3SMatt Macy 		UNP_PCB_LOCK(unp2);
35975a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
36075a67bf3SMatt Macy 	}
36175a67bf3SMatt Macy }
36275a67bf3SMatt Macy 
3634820bf6aSMark Johnston static void
3644820bf6aSMark Johnston unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
3654820bf6aSMark Johnston {
3664820bf6aSMark Johnston 	UNP_PCB_UNLOCK(unp);
3674820bf6aSMark Johnston 	if (unp != unp2)
3684820bf6aSMark Johnston 		UNP_PCB_UNLOCK(unp2);
3694820bf6aSMark Johnston }
3704820bf6aSMark Johnston 
37175a67bf3SMatt Macy static __noinline void
372e62ca80bSMark Johnston unp_pcb_owned_lock2_slowpath(struct unpcb *unp, struct unpcb **unp2p,
373e62ca80bSMark Johnston     int *freed)
37475a67bf3SMatt Macy {
37575a67bf3SMatt Macy 	struct unpcb *unp2;
37675a67bf3SMatt Macy 
37775a67bf3SMatt Macy 	unp2 = *unp2p;
378e62ca80bSMark Johnston 	unp_pcb_hold(unp2);
379e62ca80bSMark Johnston 	UNP_PCB_UNLOCK(unp);
380e62ca80bSMark Johnston 	UNP_PCB_LOCK(unp2);
381e62ca80bSMark Johnston 	UNP_PCB_LOCK(unp);
382e62ca80bSMark Johnston 	*freed = unp_pcb_rele(unp2);
38375a67bf3SMatt Macy 	if (*freed)
38475a67bf3SMatt Macy 		*unp2p = NULL;
38575a67bf3SMatt Macy }
38675a67bf3SMatt Macy 
38775a67bf3SMatt Macy #define unp_pcb_owned_lock2(unp, unp2, freed) do {			\
38875a67bf3SMatt Macy 	freed = 0;							\
389e62ca80bSMark Johnston 	UNP_PCB_LOCK_ASSERT(unp);					\
390e62ca80bSMark Johnston 	UNP_PCB_UNLOCK_ASSERT(unp2);					\
391e62ca80bSMark Johnston 	MPASS((unp) != (unp2));						\
392e62ca80bSMark Johnston 	if (__predict_true(UNP_PCB_TRYLOCK(unp2)))			\
39375a67bf3SMatt Macy 		break;							\
39475a67bf3SMatt Macy 	else if ((uintptr_t)(unp2) > (uintptr_t)(unp))			\
395e62ca80bSMark Johnston 		UNP_PCB_LOCK(unp2);					\
396e62ca80bSMark Johnston 	else								\
39775a67bf3SMatt Macy 		unp_pcb_owned_lock2_slowpath((unp), &(unp2), &freed);	\
39875a67bf3SMatt Macy } while (0)
39975a67bf3SMatt Macy 
400e4445a03SRobert Watson /*
401e4445a03SRobert Watson  * Definitions of protocols supported in the LOCAL domain.
402e4445a03SRobert Watson  */
403e4445a03SRobert Watson static struct domain localdomain;
404fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
40584d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket;
406e4445a03SRobert Watson static struct protosw localsw[] = {
407e4445a03SRobert Watson {
408e4445a03SRobert Watson 	.pr_type =		SOCK_STREAM,
409e4445a03SRobert Watson 	.pr_domain =		&localdomain,
410e4445a03SRobert Watson 	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
411e4445a03SRobert Watson 	.pr_ctloutput =		&uipc_ctloutput,
412fa9402f2SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_stream
413e4445a03SRobert Watson },
414e4445a03SRobert Watson {
415e4445a03SRobert Watson 	.pr_type =		SOCK_DGRAM,
416e4445a03SRobert Watson 	.pr_domain =		&localdomain,
417e4445a03SRobert Watson 	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS,
418aaf63435SGleb Smirnoff 	.pr_ctloutput =		&uipc_ctloutput,
419fa9402f2SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_dgram
420e4445a03SRobert Watson },
42184d61770SRobert Watson {
42284d61770SRobert Watson 	.pr_type =		SOCK_SEQPACKET,
42384d61770SRobert Watson 	.pr_domain =		&localdomain,
42484d61770SRobert Watson 
42584d61770SRobert Watson 	/*
42684d61770SRobert Watson 	 * XXXRW: For now, PR_ADDR because soreceive will bump into them
42784d61770SRobert Watson 	 * due to our use of sbappendaddr.  A new sbappend variants is needed
42884d61770SRobert Watson 	 * that supports both atomic record writes and control data.
42984d61770SRobert Watson 	 */
43084d61770SRobert Watson 	.pr_flags =		PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
43184d61770SRobert Watson 				    PR_RIGHTS,
432e0643280SGleb Smirnoff 	.pr_ctloutput =		&uipc_ctloutput,
43384d61770SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_seqpacket,
43484d61770SRobert Watson },
435e4445a03SRobert Watson };
436e4445a03SRobert Watson 
437e4445a03SRobert Watson static struct domain localdomain = {
438e4445a03SRobert Watson 	.dom_family =		AF_LOCAL,
439e4445a03SRobert Watson 	.dom_name =		"local",
440e4445a03SRobert Watson 	.dom_init =		unp_init,
441e4445a03SRobert Watson 	.dom_externalize =	unp_externalize,
44299ab95dbSMark Johnston 	.dom_dispose =		unp_dispose,
443e4445a03SRobert Watson 	.dom_protosw =		localsw,
44402abd400SPedro F. Giffuni 	.dom_protoswNPROTOSW =	&localsw[nitems(localsw)]
445e4445a03SRobert Watson };
446e4445a03SRobert Watson DOMAIN_SET(local);
447e4445a03SRobert Watson 
448ac45e92fSRobert Watson static void
449a29f300eSGarrett Wollman uipc_abort(struct socket *so)
450df8bae1dSRodney W. Grimes {
451e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
452df8bae1dSRodney W. Grimes 
45340f2ac28SRobert Watson 	unp = sotounpcb(so);
4544d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
45575a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
456e7c33e29SRobert Watson 
457e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
458e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
459e7c33e29SRobert Watson 	if (unp2 != NULL) {
46075a67bf3SMatt Macy 		unp_pcb_hold(unp2);
461e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
46275a67bf3SMatt Macy 		unp_drop(unp2);
46375a67bf3SMatt Macy 	} else
46475a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
465df8bae1dSRodney W. Grimes }
466df8bae1dSRodney W. Grimes 
467a29f300eSGarrett Wollman static int
46857bf258eSGarrett Wollman uipc_accept(struct socket *so, struct sockaddr **nam)
469a29f300eSGarrett Wollman {
470e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
4710d9ce3a1SRobert Watson 	const struct sockaddr *sa;
472df8bae1dSRodney W. Grimes 
473df8bae1dSRodney W. Grimes 	/*
4741c381b19SRobert Watson 	 * Pass back name of connected socket, if it was bound and we are
4751c381b19SRobert Watson 	 * still connected (our peer may have closed already!).
476df8bae1dSRodney W. Grimes 	 */
4774d4b555eSRobert Watson 	unp = sotounpcb(so);
4784d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
479e7c33e29SRobert Watson 
4800d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
4813dab55bcSRobert Watson 	UNP_LINK_RLOCK();
482e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
483e7c33e29SRobert Watson 	if (unp2 != NULL && unp2->unp_addr != NULL) {
484e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp2);
485e7c33e29SRobert Watson 		sa = (struct sockaddr *) unp2->unp_addr;
486e7c33e29SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
487e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
488e7c33e29SRobert Watson 	} else {
4890d9ce3a1SRobert Watson 		sa = &sun_noname;
4900d9ce3a1SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
491e7c33e29SRobert Watson 	}
4923dab55bcSRobert Watson 	UNP_LINK_RUNLOCK();
493e5aeaa0cSDag-Erling Smørgrav 	return (0);
494a29f300eSGarrett Wollman }
495df8bae1dSRodney W. Grimes 
496a29f300eSGarrett Wollman static int
497b40ce416SJulian Elischer uipc_attach(struct socket *so, int proto, struct thread *td)
498a29f300eSGarrett Wollman {
499e7c33e29SRobert Watson 	u_long sendspace, recvspace;
5006d32873cSRobert Watson 	struct unpcb *unp;
5013dab55bcSRobert Watson 	int error;
502779f106aSGleb Smirnoff 	bool locked;
503df8bae1dSRodney W. Grimes 
5046d32873cSRobert Watson 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
5056d32873cSRobert Watson 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
5066d32873cSRobert Watson 		switch (so->so_type) {
5076d32873cSRobert Watson 		case SOCK_STREAM:
508e7c33e29SRobert Watson 			sendspace = unpst_sendspace;
509e7c33e29SRobert Watson 			recvspace = unpst_recvspace;
5106d32873cSRobert Watson 			break;
5116d32873cSRobert Watson 
5126d32873cSRobert Watson 		case SOCK_DGRAM:
513e7c33e29SRobert Watson 			sendspace = unpdg_sendspace;
514e7c33e29SRobert Watson 			recvspace = unpdg_recvspace;
5156d32873cSRobert Watson 			break;
5166d32873cSRobert Watson 
51784d61770SRobert Watson 		case SOCK_SEQPACKET:
51884d61770SRobert Watson 			sendspace = unpsp_sendspace;
51984d61770SRobert Watson 			recvspace = unpsp_recvspace;
52084d61770SRobert Watson 			break;
52184d61770SRobert Watson 
5226d32873cSRobert Watson 		default:
523e7c33e29SRobert Watson 			panic("uipc_attach");
5246d32873cSRobert Watson 		}
525e7c33e29SRobert Watson 		error = soreserve(so, sendspace, recvspace);
5266d32873cSRobert Watson 		if (error)
5276d32873cSRobert Watson 			return (error);
5286d32873cSRobert Watson 	}
52946a1d9bfSRobert Watson 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
5306d32873cSRobert Watson 	if (unp == NULL)
5316d32873cSRobert Watson 		return (ENOBUFS);
5326d32873cSRobert Watson 	LIST_INIT(&unp->unp_refs);
533e7c33e29SRobert Watson 	UNP_PCB_LOCK_INIT(unp);
5346d32873cSRobert Watson 	unp->unp_socket = so;
5356d32873cSRobert Watson 	so->so_pcb = unp;
5365362170dSMark Johnston 	refcount_init(&unp->unp_refcount, 1);
537e7c33e29SRobert Watson 
538779f106aSGleb Smirnoff 	if ((locked = UNP_LINK_WOWNED()) == false)
539779f106aSGleb Smirnoff 		UNP_LINK_WLOCK();
540779f106aSGleb Smirnoff 
5416d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
542f218ac50SMateusz Guzik 	unp->unp_ino = ++unp_ino;
5436d32873cSRobert Watson 	unp_count++;
54484d61770SRobert Watson 	switch (so->so_type) {
54584d61770SRobert Watson 	case SOCK_STREAM:
54684d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
54784d61770SRobert Watson 		break;
54884d61770SRobert Watson 
54984d61770SRobert Watson 	case SOCK_DGRAM:
55084d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
55184d61770SRobert Watson 		break;
55284d61770SRobert Watson 
55384d61770SRobert Watson 	case SOCK_SEQPACKET:
55484d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
55584d61770SRobert Watson 		break;
55684d61770SRobert Watson 
55784d61770SRobert Watson 	default:
55884d61770SRobert Watson 		panic("uipc_attach");
55984d61770SRobert Watson 	}
560779f106aSGleb Smirnoff 
561779f106aSGleb Smirnoff 	if (locked == false)
562779f106aSGleb Smirnoff 		UNP_LINK_WUNLOCK();
5636d32873cSRobert Watson 
5646d32873cSRobert Watson 	return (0);
565a29f300eSGarrett Wollman }
566a29f300eSGarrett Wollman 
567a29f300eSGarrett Wollman static int
5687493f24eSPawel Jakub Dawidek uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
569a29f300eSGarrett Wollman {
570dd47f5caSRobert Watson 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
571dd47f5caSRobert Watson 	struct vattr vattr;
5725050aa86SKonstantin Belousov 	int error, namelen;
573dd47f5caSRobert Watson 	struct nameidata nd;
57440f2ac28SRobert Watson 	struct unpcb *unp;
575dd47f5caSRobert Watson 	struct vnode *vp;
576dd47f5caSRobert Watson 	struct mount *mp;
5777008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
578dd47f5caSRobert Watson 	char *buf;
579a29f300eSGarrett Wollman 
580cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
581cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
582cb7df69bSKevin Lo 
58340f2ac28SRobert Watson 	unp = sotounpcb(so);
5844d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
5854f1f0ef5SRobert Watson 
586a06534c3SBjoern A. Zeeb 	if (soun->sun_len > sizeof(struct sockaddr_un))
587a06534c3SBjoern A. Zeeb 		return (EINVAL);
5884f1f0ef5SRobert Watson 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
5894f1f0ef5SRobert Watson 	if (namelen <= 0)
5904f1f0ef5SRobert Watson 		return (EINVAL);
591dd47f5caSRobert Watson 
592dd47f5caSRobert Watson 	/*
5934f1f0ef5SRobert Watson 	 * We don't allow simultaneous bind() calls on a single UNIX domain
5944f1f0ef5SRobert Watson 	 * socket, so flag in-progress operations, and return an error if an
5954f1f0ef5SRobert Watson 	 * operation is already in progress.
5964f1f0ef5SRobert Watson 	 *
5974f1f0ef5SRobert Watson 	 * Historically, we have not allowed a socket to be rebound, so this
598d7924b70SRobert Watson 	 * also returns an error.  Not allowing re-binding simplifies the
599d7924b70SRobert Watson 	 * implementation and avoids a great many possible failure modes.
600dd47f5caSRobert Watson 	 */
601e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
602dd47f5caSRobert Watson 	if (unp->unp_vnode != NULL) {
603e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
604dd47f5caSRobert Watson 		return (EINVAL);
605dd47f5caSRobert Watson 	}
6064f1f0ef5SRobert Watson 	if (unp->unp_flags & UNP_BINDING) {
607e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
6084f1f0ef5SRobert Watson 		return (EALREADY);
609dd47f5caSRobert Watson 	}
6104f1f0ef5SRobert Watson 	unp->unp_flags |= UNP_BINDING;
611e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
612dd47f5caSRobert Watson 
613dd47f5caSRobert Watson 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
6147928893dSEd Maste 	bcopy(soun->sun_path, buf, namelen);
6157928893dSEd Maste 	buf[namelen] = 0;
616dd47f5caSRobert Watson 
617dd47f5caSRobert Watson restart:
6186c21f6edSKonstantin Belousov 	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
6197008be5bSPawel Jakub Dawidek 	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
620dd47f5caSRobert Watson /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
621dd47f5caSRobert Watson 	error = namei(&nd);
622dd47f5caSRobert Watson 	if (error)
6234f1f0ef5SRobert Watson 		goto error;
624dd47f5caSRobert Watson 	vp = nd.ni_vp;
625dd47f5caSRobert Watson 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
626dd47f5caSRobert Watson 		NDFREE(&nd, NDF_ONLY_PNBUF);
627dd47f5caSRobert Watson 		if (nd.ni_dvp == vp)
628dd47f5caSRobert Watson 			vrele(nd.ni_dvp);
629dd47f5caSRobert Watson 		else
630dd47f5caSRobert Watson 			vput(nd.ni_dvp);
631dd47f5caSRobert Watson 		if (vp != NULL) {
632dd47f5caSRobert Watson 			vrele(vp);
633dd47f5caSRobert Watson 			error = EADDRINUSE;
6344f1f0ef5SRobert Watson 			goto error;
635dd47f5caSRobert Watson 		}
636dd47f5caSRobert Watson 		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
637dd47f5caSRobert Watson 		if (error)
6384f1f0ef5SRobert Watson 			goto error;
639dd47f5caSRobert Watson 		goto restart;
640dd47f5caSRobert Watson 	}
641dd47f5caSRobert Watson 	VATTR_NULL(&vattr);
642dd47f5caSRobert Watson 	vattr.va_type = VSOCK;
643dd47f5caSRobert Watson 	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
644dd47f5caSRobert Watson #ifdef MAC
64530d239bcSRobert Watson 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
646dd47f5caSRobert Watson 	    &vattr);
647dd47f5caSRobert Watson #endif
648885868cdSRobert Watson 	if (error == 0)
649dd47f5caSRobert Watson 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
650dd47f5caSRobert Watson 	NDFREE(&nd, NDF_ONLY_PNBUF);
651dd47f5caSRobert Watson 	vput(nd.ni_dvp);
652dd47f5caSRobert Watson 	if (error) {
653dd47f5caSRobert Watson 		vn_finished_write(mp);
6544f1f0ef5SRobert Watson 		goto error;
655dd47f5caSRobert Watson 	}
656dd47f5caSRobert Watson 	vp = nd.ni_vp;
65757fd3d55SPawel Jakub Dawidek 	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
658dd47f5caSRobert Watson 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
659e7c33e29SRobert Watson 
660e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6610c3c207fSGleb Smirnoff 	VOP_UNP_BIND(vp, unp);
662dd47f5caSRobert Watson 	unp->unp_vnode = vp;
663dd47f5caSRobert Watson 	unp->unp_addr = soun;
6644f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
665e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
666b249ce48SMateusz Guzik 	VOP_UNLOCK(vp);
667dd47f5caSRobert Watson 	vn_finished_write(mp);
6684f1f0ef5SRobert Watson 	free(buf, M_TEMP);
6694f1f0ef5SRobert Watson 	return (0);
670e7c33e29SRobert Watson 
6714f1f0ef5SRobert Watson error:
672e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6734f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
674e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
675dd47f5caSRobert Watson 	free(buf, M_TEMP);
67640f2ac28SRobert Watson 	return (error);
677a29f300eSGarrett Wollman }
678a29f300eSGarrett Wollman 
679a29f300eSGarrett Wollman static int
6807493f24eSPawel Jakub Dawidek uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
6817493f24eSPawel Jakub Dawidek {
6827493f24eSPawel Jakub Dawidek 
6837493f24eSPawel Jakub Dawidek 	return (uipc_bindat(AT_FDCWD, so, nam, td));
6847493f24eSPawel Jakub Dawidek }
6857493f24eSPawel Jakub Dawidek 
6867493f24eSPawel Jakub Dawidek static int
687b40ce416SJulian Elischer uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
688a29f300eSGarrett Wollman {
6890d9ce3a1SRobert Watson 	int error;
690a29f300eSGarrett Wollman 
691fd179ee9SRobert Watson 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
692fd179ee9SRobert Watson 	error = unp_connect(so, nam, td);
6930d9ce3a1SRobert Watson 	return (error);
694a29f300eSGarrett Wollman }
695a29f300eSGarrett Wollman 
6967493f24eSPawel Jakub Dawidek static int
6977493f24eSPawel Jakub Dawidek uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
6987493f24eSPawel Jakub Dawidek     struct thread *td)
6997493f24eSPawel Jakub Dawidek {
7007493f24eSPawel Jakub Dawidek 	int error;
7017493f24eSPawel Jakub Dawidek 
7027493f24eSPawel Jakub Dawidek 	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
7037493f24eSPawel Jakub Dawidek 	error = unp_connectat(fd, so, nam, td);
7047493f24eSPawel Jakub Dawidek 	return (error);
7057493f24eSPawel Jakub Dawidek }
7067493f24eSPawel Jakub Dawidek 
707a152f8a3SRobert Watson static void
708a152f8a3SRobert Watson uipc_close(struct socket *so)
709a152f8a3SRobert Watson {
710e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
711779f106aSGleb Smirnoff 	struct vnode *vp = NULL;
71275a67bf3SMatt Macy 	struct mtx *vplock;
71375a67bf3SMatt Macy 	int freed;
714a152f8a3SRobert Watson 	unp = sotounpcb(so);
715a152f8a3SRobert Watson 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
716e7c33e29SRobert Watson 
71775a67bf3SMatt Macy 	vplock = NULL;
71875a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
71975a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
72075a67bf3SMatt Macy 		mtx_lock(vplock);
721e7c33e29SRobert Watson 	}
72275a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
72375a67bf3SMatt Macy 	if (vp && unp->unp_vnode == NULL) {
72475a67bf3SMatt Macy 		mtx_unlock(vplock);
72575a67bf3SMatt Macy 		vp = NULL;
72675a67bf3SMatt Macy 	}
72775a67bf3SMatt Macy 	if (vp != NULL) {
728779f106aSGleb Smirnoff 		VOP_UNP_DETACH(vp);
729779f106aSGleb Smirnoff 		unp->unp_vnode = NULL;
730779f106aSGleb Smirnoff 	}
73175a67bf3SMatt Macy 	unp2 = unp->unp_conn;
732acf9fd05SMatt Macy 	if (__predict_false(unp == unp2)) {
733acf9fd05SMatt Macy 		unp_disconnect(unp, unp2);
734acf9fd05SMatt Macy 	} else if (unp2 != NULL) {
73575a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp, unp2, freed);
73675a67bf3SMatt Macy 		unp_disconnect(unp, unp2);
737f0317f86SMark Johnston 	} else {
738e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
739f0317f86SMark Johnston 	}
74075a67bf3SMatt Macy 	if (vp) {
74175a67bf3SMatt Macy 		mtx_unlock(vplock);
742779f106aSGleb Smirnoff 		vrele(vp);
743a152f8a3SRobert Watson 	}
74475a67bf3SMatt Macy }
745a152f8a3SRobert Watson 
7462c899584SRobert Watson static int
747a29f300eSGarrett Wollman uipc_connect2(struct socket *so1, struct socket *so2)
748a29f300eSGarrett Wollman {
749e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
7500d9ce3a1SRobert Watson 	int error;
751a29f300eSGarrett Wollman 
752e7c33e29SRobert Watson 	unp = so1->so_pcb;
7534d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
754e7c33e29SRobert Watson 	unp2 = so2->so_pcb;
755e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
7564820bf6aSMark Johnston 	unp_pcb_lock_pair(unp, unp2);
7576a2989fdSMatthew N. Dodd 	error = unp_connect2(so1, so2, PRU_CONNECT2);
7584820bf6aSMark Johnston 	unp_pcb_unlock_pair(unp, unp2);
7590d9ce3a1SRobert Watson 	return (error);
760a29f300eSGarrett Wollman }
761a29f300eSGarrett Wollman 
762bc725eafSRobert Watson static void
763a29f300eSGarrett Wollman uipc_detach(struct socket *so)
764a29f300eSGarrett Wollman {
765e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
76675a67bf3SMatt Macy 	struct mtx *vplock;
7676d32873cSRobert Watson 	struct vnode *vp;
7689ae328fcSJohn Baldwin 	int freeunp, local_unp_rights;
769a29f300eSGarrett Wollman 
77040f2ac28SRobert Watson 	unp = sotounpcb(so);
7714d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
772e7c33e29SRobert Watson 
773434ac8b6SMark Johnston 	vp = NULL;
774c0874c34SMatt Macy 	vplock = NULL;
775434ac8b6SMark Johnston 	local_unp_rights = 0;
776434ac8b6SMark Johnston 
777a50b1900SMark Johnston 	SOCK_LOCK(so);
778a50b1900SMark Johnston 	if (!SOLISTENING(so)) {
779a50b1900SMark Johnston 		/*
780a50b1900SMark Johnston 		 * Once the socket is removed from the global lists,
781a50b1900SMark Johnston 		 * uipc_ready() will not be able to locate its socket buffer, so
782a50b1900SMark Johnston 		 * clear the buffer now.  At this point internalized rights have
783a50b1900SMark Johnston 		 * already been disposed of.
784a50b1900SMark Johnston 		 */
785a50b1900SMark Johnston 		sbrelease(&so->so_rcv, so);
786a50b1900SMark Johnston 	}
787a50b1900SMark Johnston 	SOCK_UNLOCK(so);
788a50b1900SMark Johnston 
789779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
7906d32873cSRobert Watson 	LIST_REMOVE(unp, unp_link);
791a9aa06f7SJason A. Harmening 	if (unp->unp_gcflag & UNPGC_DEAD)
792a9aa06f7SJason A. Harmening 		LIST_REMOVE(unp, unp_dead);
7936d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
7946d32873cSRobert Watson 	--unp_count;
79575a67bf3SMatt Macy 	UNP_LINK_WUNLOCK();
796434ac8b6SMark Johnston 
79775a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
79875a67bf3SMatt Macy  restart:
79975a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
80075a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
80175a67bf3SMatt Macy 		mtx_lock(vplock);
80275a67bf3SMatt Macy 	}
80375a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
804db38b699SMark Johnston 	if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
805c0874c34SMatt Macy 		if (vplock)
80675a67bf3SMatt Macy 			mtx_unlock(vplock);
80775a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
80875a67bf3SMatt Macy 		goto restart;
80975a67bf3SMatt Macy 	}
8106d32873cSRobert Watson 	if ((vp = unp->unp_vnode) != NULL) {
811c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
8126d32873cSRobert Watson 		unp->unp_vnode = NULL;
8136d32873cSRobert Watson 	}
814acf9fd05SMatt Macy 	if (__predict_false(unp == unp->unp_conn)) {
815acf9fd05SMatt Macy 		unp_disconnect(unp, unp);
816acf9fd05SMatt Macy 		unp2 = NULL;
817db38b699SMark Johnston 	} else {
818acf9fd05SMatt Macy 		if ((unp2 = unp->unp_conn) != NULL) {
819acf9fd05SMatt Macy 			unp_pcb_owned_lock2(unp, unp2, freeunp);
820acf9fd05SMatt Macy 			if (freeunp)
821acf9fd05SMatt Macy 				unp2 = NULL;
822acf9fd05SMatt Macy 		}
82375a67bf3SMatt Macy 		unp_pcb_hold(unp);
824f0317f86SMark Johnston 		if (unp2 != NULL)
825e7c33e29SRobert Watson 			unp_disconnect(unp, unp2);
826f0317f86SMark Johnston 		else
82775a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
828f0317f86SMark Johnston 	}
82975a67bf3SMatt Macy 	UNP_REF_LIST_LOCK();
8306d32873cSRobert Watson 	while (!LIST_EMPTY(&unp->unp_refs)) {
8316d32873cSRobert Watson 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
832e7c33e29SRobert Watson 
83375a67bf3SMatt Macy 		unp_pcb_hold(ref);
83475a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
83575a67bf3SMatt Macy 
83675a67bf3SMatt Macy 		MPASS(ref != unp);
83775a67bf3SMatt Macy 		UNP_PCB_UNLOCK_ASSERT(ref);
838afc055d9SEd Schouten 		unp_drop(ref);
83975a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
8406d32873cSRobert Watson 	}
84175a67bf3SMatt Macy 
84275a67bf3SMatt Macy 	UNP_REF_LIST_UNLOCK();
84375a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
84475a67bf3SMatt Macy 	freeunp = unp_pcb_rele(unp);
84575a67bf3SMatt Macy 	MPASS(freeunp == 0);
846397c19d1SJeff Roberson 	local_unp_rights = unp_rights;
8476d32873cSRobert Watson 	unp->unp_socket->so_pcb = NULL;
84875a67bf3SMatt Macy 	unp->unp_socket = NULL;
849db38b699SMark Johnston 	free(unp->unp_addr, M_SONAME);
850db38b699SMark Johnston 	unp->unp_addr = NULL;
851db38b699SMark Johnston 	if (!unp_pcb_rele(unp))
8526e2faa24SRobert Watson 		UNP_PCB_UNLOCK(unp);
85375a67bf3SMatt Macy 	if (vp) {
85475a67bf3SMatt Macy 		mtx_unlock(vplock);
8556d32873cSRobert Watson 		vrele(vp);
85675a67bf3SMatt Macy 	}
8576d32873cSRobert Watson 	if (local_unp_rights)
858daee0f0bSKonstantin Belousov 		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
859a29f300eSGarrett Wollman }
860a29f300eSGarrett Wollman 
861a29f300eSGarrett Wollman static int
862a29f300eSGarrett Wollman uipc_disconnect(struct socket *so)
863a29f300eSGarrett Wollman {
864e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
86575a67bf3SMatt Macy 	int freed;
866a29f300eSGarrett Wollman 
86740f2ac28SRobert Watson 	unp = sotounpcb(so);
8684d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
869e7c33e29SRobert Watson 
870e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
87175a67bf3SMatt Macy 	if ((unp2 = unp->unp_conn) == NULL) {
872e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
87375a67bf3SMatt Macy 		return (0);
87475a67bf3SMatt Macy 	}
875fcabd541SMatt Macy 	if (__predict_true(unp != unp2)) {
87675a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp, unp2, freed);
87775a67bf3SMatt Macy 		if (__predict_false(freed)) {
87875a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
87975a67bf3SMatt Macy 			return (0);
88075a67bf3SMatt Macy 		}
881fcabd541SMatt Macy 	}
88275a67bf3SMatt Macy 	unp_disconnect(unp, unp2);
883e5aeaa0cSDag-Erling Smørgrav 	return (0);
884a29f300eSGarrett Wollman }
885a29f300eSGarrett Wollman 
886a29f300eSGarrett Wollman static int
887d374e81eSRobert Watson uipc_listen(struct socket *so, int backlog, struct thread *td)
888a29f300eSGarrett Wollman {
88940f2ac28SRobert Watson 	struct unpcb *unp;
8900d9ce3a1SRobert Watson 	int error;
891a29f300eSGarrett Wollman 
892beb4b312SGleb Smirnoff 	if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
893beb4b312SGleb Smirnoff 		return (EOPNOTSUPP);
894beb4b312SGleb Smirnoff 
89540f2ac28SRobert Watson 	unp = sotounpcb(so);
8964d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
897e7c33e29SRobert Watson 
898e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
8994d4b555eSRobert Watson 	if (unp->unp_vnode == NULL) {
90047a84387SEd Schouten 		/* Already connected or not bound to an address. */
90147a84387SEd Schouten 		error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
902e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
90347a84387SEd Schouten 		return (error);
90440f2ac28SRobert Watson 	}
905e7c33e29SRobert Watson 
906e7c33e29SRobert Watson 	SOCK_LOCK(so);
907e7c33e29SRobert Watson 	error = solisten_proto_check(so);
908e7c33e29SRobert Watson 	if (error == 0) {
909c5afec6eSDmitry Chagin 		cru2xt(td, &unp->unp_peercred);
910e7c33e29SRobert Watson 		solisten_proto(so, backlog);
911e7c33e29SRobert Watson 	}
912e7c33e29SRobert Watson 	SOCK_UNLOCK(so);
913e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
9140d9ce3a1SRobert Watson 	return (error);
915a29f300eSGarrett Wollman }
916a29f300eSGarrett Wollman 
917a29f300eSGarrett Wollman static int
91857bf258eSGarrett Wollman uipc_peeraddr(struct socket *so, struct sockaddr **nam)
919a29f300eSGarrett Wollman {
920e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
9210d9ce3a1SRobert Watson 	const struct sockaddr *sa;
922a29f300eSGarrett Wollman 
9234d4b555eSRobert Watson 	unp = sotounpcb(so);
9244d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
925e7c33e29SRobert Watson 
9260d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
927afd9f91cSJohn Baldwin 	UNP_LINK_RLOCK();
928bdc5f6a3SHajimu UMEMOTO 	/*
929e7c33e29SRobert Watson 	 * XXX: It seems that this test always fails even when connection is
930e7c33e29SRobert Watson 	 * established.  So, this else clause is added as workaround to
931e7c33e29SRobert Watson 	 * return PF_LOCAL sockaddr.
932bdc5f6a3SHajimu UMEMOTO 	 */
933e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
934e7c33e29SRobert Watson 	if (unp2 != NULL) {
935e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp2);
936e7c33e29SRobert Watson 		if (unp2->unp_addr != NULL)
937afd9f91cSJohn Baldwin 			sa = (struct sockaddr *) unp2->unp_addr;
938e7c33e29SRobert Watson 		else
9390d9ce3a1SRobert Watson 			sa = &sun_noname;
9400d9ce3a1SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
941e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
942e7c33e29SRobert Watson 	} else {
943e7c33e29SRobert Watson 		sa = &sun_noname;
944e7c33e29SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
945e7c33e29SRobert Watson 	}
946afd9f91cSJohn Baldwin 	UNP_LINK_RUNLOCK();
947e5aeaa0cSDag-Erling Smørgrav 	return (0);
948a29f300eSGarrett Wollman }
949a29f300eSGarrett Wollman 
950a29f300eSGarrett Wollman static int
951a29f300eSGarrett Wollman uipc_rcvd(struct socket *so, int flags)
952a29f300eSGarrett Wollman {
953e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
954a29f300eSGarrett Wollman 	struct socket *so2;
955337cc6b6SRobert Watson 	u_int mbcnt, sbcc;
956a29f300eSGarrett Wollman 
95740f2ac28SRobert Watson 	unp = sotounpcb(so);
9582b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
9592b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
9602b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
961e7c33e29SRobert Watson 
962df8bae1dSRodney W. Grimes 	/*
963e7c33e29SRobert Watson 	 * Adjust backpressure on sender and wakeup any waiting to write.
964e7c33e29SRobert Watson 	 *
965d7924b70SRobert Watson 	 * The unp lock is acquired to maintain the validity of the unp_conn
966d7924b70SRobert Watson 	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
967d7924b70SRobert Watson 	 * static as long as we don't permit unp2 to disconnect from unp,
968d7924b70SRobert Watson 	 * which is prevented by the lock on unp.  We cache values from
969d7924b70SRobert Watson 	 * so_rcv to avoid holding the so_rcv lock over the entire
970d7924b70SRobert Watson 	 * transaction on the remote so_snd.
971df8bae1dSRodney W. Grimes 	 */
972337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so->so_rcv);
973337cc6b6SRobert Watson 	mbcnt = so->so_rcv.sb_mbcnt;
9742b21d0e8SGleb Smirnoff 	sbcc = sbavail(&so->so_rcv);
975337cc6b6SRobert Watson 	SOCKBUF_UNLOCK(&so->so_rcv);
976c2090e73SAlan Somers 	/*
977c2090e73SAlan Somers 	 * There is a benign race condition at this point.  If we're planning to
978c2090e73SAlan Somers 	 * clear SB_STOP, but uipc_send is called on the connected socket at
979c2090e73SAlan Somers 	 * this instant, it might add data to the sockbuf and set SB_STOP.  Then
980c2090e73SAlan Somers 	 * we would erroneously clear SB_STOP below, even though the sockbuf is
981c2090e73SAlan Somers 	 * full.  The race is benign because the only ill effect is to allow the
982c2090e73SAlan Somers 	 * sockbuf to exceed its size limit, and the size limits are not
983c2090e73SAlan Somers 	 * strictly guaranteed anyway.
984c2090e73SAlan Somers 	 */
985e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
986e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
987e7c33e29SRobert Watson 	if (unp2 == NULL) {
988e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
989e7c33e29SRobert Watson 		return (0);
990337cc6b6SRobert Watson 	}
991e7c33e29SRobert Watson 	so2 = unp2->unp_socket;
992337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so2->so_snd);
993c2090e73SAlan Somers 	if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
994c2090e73SAlan Somers 		so2->so_snd.sb_flags &= ~SB_STOP;
9951e4d7da7SRobert Watson 	sowwakeup_locked(so2);
996e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
997e5aeaa0cSDag-Erling Smørgrav 	return (0);
998a29f300eSGarrett Wollman }
999df8bae1dSRodney W. Grimes 
1000a29f300eSGarrett Wollman static int
100175a67bf3SMatt Macy connect_internal(struct socket *so, struct sockaddr *nam, struct thread *td)
100275a67bf3SMatt Macy {
100375a67bf3SMatt Macy 	int error;
100475a67bf3SMatt Macy 	struct unpcb *unp;
100575a67bf3SMatt Macy 
100675a67bf3SMatt Macy 	unp = so->so_pcb;
100775a67bf3SMatt Macy 	if (unp->unp_conn != NULL)
100875a67bf3SMatt Macy 		return (EISCONN);
100975a67bf3SMatt Macy 	error = unp_connect(so, nam, td);
101075a67bf3SMatt Macy 	if (error)
101175a67bf3SMatt Macy 		return (error);
101275a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
101375a67bf3SMatt Macy 	if (unp->unp_conn == NULL) {
101475a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
101575a67bf3SMatt Macy 		if (error == 0)
101675a67bf3SMatt Macy 			error = ENOTCONN;
101775a67bf3SMatt Macy 	}
101875a67bf3SMatt Macy 	return (error);
101975a67bf3SMatt Macy }
102075a67bf3SMatt Macy 
102175a67bf3SMatt Macy static int
102257bf258eSGarrett Wollman uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1023b40ce416SJulian Elischer     struct mbuf *control, struct thread *td)
1024a29f300eSGarrett Wollman {
1025f3f49bbbSRobert Watson 	struct unpcb *unp, *unp2;
1026a29f300eSGarrett Wollman 	struct socket *so2;
1027c2090e73SAlan Somers 	u_int mbcnt, sbcc;
102875a67bf3SMatt Macy 	int freed, error;
1029a29f300eSGarrett Wollman 
103040f2ac28SRobert Watson 	unp = sotounpcb(so);
10312b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
10322b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
10332b21d0e8SGleb Smirnoff 	    so->so_type == SOCK_SEQPACKET,
10342b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
1035e7c33e29SRobert Watson 
103675a67bf3SMatt Macy 	freed = error = 0;
1037a29f300eSGarrett Wollman 	if (flags & PRUS_OOB) {
1038a29f300eSGarrett Wollman 		error = EOPNOTSUPP;
1039a29f300eSGarrett Wollman 		goto release;
1040a29f300eSGarrett Wollman 	}
1041fc3fcacfSRobert Watson 	if (control != NULL && (error = unp_internalize(&control, td)))
1042a29f300eSGarrett Wollman 		goto release;
104375a67bf3SMatt Macy 
104475a67bf3SMatt Macy 	unp2 = NULL;
1045a29f300eSGarrett Wollman 	switch (so->so_type) {
1046a29f300eSGarrett Wollman 	case SOCK_DGRAM:
1047a29f300eSGarrett Wollman 	{
1048e7dd9a10SRobert Watson 		const struct sockaddr *from;
1049df8bae1dSRodney W. Grimes 
1050fc3fcacfSRobert Watson 		if (nam != NULL) {
105175a67bf3SMatt Macy 			/*
105275a67bf3SMatt Macy 			 * We return with UNP_PCB_LOCK_HELD so we know that
105375a67bf3SMatt Macy 			 * the reference is live if the pointer is valid.
105475a67bf3SMatt Macy 			 */
105575a67bf3SMatt Macy 			if ((error = connect_internal(so, nam, td)))
1056df8bae1dSRodney W. Grimes 				break;
105775a67bf3SMatt Macy 			MPASS(unp->unp_conn != NULL);
1058e7c33e29SRobert Watson 			unp2 = unp->unp_conn;
105975a67bf3SMatt Macy 		} else  {
106075a67bf3SMatt Macy 			UNP_PCB_LOCK(unp);
106160a5ef26SRobert Watson 
1062b5ff0914SRobert Watson 			/*
1063b5ff0914SRobert Watson 			 * Because connect() and send() are non-atomic in a sendto()
1064b5ff0914SRobert Watson 			 * with a target address, it's possible that the socket will
1065b5ff0914SRobert Watson 			 * have disconnected before the send() can run.  In that case
1066b5ff0914SRobert Watson 			 * return the slightly counter-intuitive but otherwise
1067b5ff0914SRobert Watson 			 * correct error that the socket is not connected.
1068b5ff0914SRobert Watson 			 */
106975a67bf3SMatt Macy 			if ((unp2 = unp->unp_conn)  == NULL) {
107075a67bf3SMatt Macy 				UNP_PCB_UNLOCK(unp);
1071b5ff0914SRobert Watson 				error = ENOTCONN;
1072b5ff0914SRobert Watson 				break;
1073b5ff0914SRobert Watson 			}
107475a67bf3SMatt Macy 		}
1075c684c14cSMatt Macy 		if (__predict_false(unp == unp2)) {
1076c684c14cSMatt Macy 			if (unp->unp_socket == NULL) {
1077c684c14cSMatt Macy 				error = ENOTCONN;
1078c684c14cSMatt Macy 				break;
1079c684c14cSMatt Macy 			}
1080c684c14cSMatt Macy 			goto connect_self;
1081c684c14cSMatt Macy 		}
108275a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp, unp2, freed);
108375a67bf3SMatt Macy 		if (__predict_false(freed)) {
108475a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
108575a67bf3SMatt Macy 			error = ENOTCONN;
108675a67bf3SMatt Macy 			break;
108775a67bf3SMatt Macy 		}
108875a67bf3SMatt Macy 		/*
108975a67bf3SMatt Macy 		 * The socket referencing unp2 may have been closed
109075a67bf3SMatt Macy 		 * or unp may have been disconnected if the unp lock
109175a67bf3SMatt Macy 		 * was dropped to acquire unp2.
109275a67bf3SMatt Macy 		 */
109375a67bf3SMatt Macy 		if (__predict_false(unp->unp_conn == NULL) ||
109475a67bf3SMatt Macy 			unp2->unp_socket == NULL) {
109575a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
109675a67bf3SMatt Macy 			if (unp_pcb_rele(unp2) == 0)
109775a67bf3SMatt Macy 				UNP_PCB_UNLOCK(unp2);
109875a67bf3SMatt Macy 			error = ENOTCONN;
109975a67bf3SMatt Macy 			break;
110075a67bf3SMatt Macy 		}
1101c684c14cSMatt Macy 	connect_self:
1102ede6e136SRobert Watson 		if (unp2->unp_flags & UNP_WANTCRED)
1103ede6e136SRobert Watson 			control = unp_addsockcred(td, control);
1104fc3fcacfSRobert Watson 		if (unp->unp_addr != NULL)
110557bf258eSGarrett Wollman 			from = (struct sockaddr *)unp->unp_addr;
1106df8bae1dSRodney W. Grimes 		else
1107df8bae1dSRodney W. Grimes 			from = &sun_noname;
1108ede6e136SRobert Watson 		so2 = unp2->unp_socket;
1109a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
11106dde7ecbSPeter Wemm 		if (sbappendaddr_locked(&so2->so_rcv, from, m,
11118de34a88SAlan Somers 		    control)) {
11121e4d7da7SRobert Watson 			sorwakeup_locked(so2);
1113fc3fcacfSRobert Watson 			m = NULL;
1114fc3fcacfSRobert Watson 			control = NULL;
1115e5aeaa0cSDag-Erling Smørgrav 		} else {
1116a34b7046SRobert Watson 			SOCKBUF_UNLOCK(&so2->so_rcv);
1117df8bae1dSRodney W. Grimes 			error = ENOBUFS;
1118e5aeaa0cSDag-Erling Smørgrav 		}
111975a67bf3SMatt Macy 		if (nam != NULL)
1120e7c33e29SRobert Watson 			unp_disconnect(unp, unp2);
1121f0317f86SMark Johnston 		else
1122f0317f86SMark Johnston 			unp_pcb_unlock_pair(unp, unp2);
1123df8bae1dSRodney W. Grimes 		break;
1124df8bae1dSRodney W. Grimes 	}
1125df8bae1dSRodney W. Grimes 
112684d61770SRobert Watson 	case SOCK_SEQPACKET:
1127df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
1128402cc72dSDavid Greenman 		if ((so->so_state & SS_ISCONNECTED) == 0) {
1129fc3fcacfSRobert Watson 			if (nam != NULL) {
1130b36871afSMark Johnston 				error = connect_internal(so, nam, td);
1131b36871afSMark Johnston 				if (error != 0)
113275a67bf3SMatt Macy 					break;
1133402cc72dSDavid Greenman 			} else {
1134402cc72dSDavid Greenman 				error = ENOTCONN;
1135402cc72dSDavid Greenman 				break;
1136402cc72dSDavid Greenman 			}
113775a67bf3SMatt Macy 		} else {
113875a67bf3SMatt Macy 			UNP_PCB_LOCK(unp);
1139b36871afSMark Johnston 		}
1140b36871afSMark Johnston 
114175a67bf3SMatt Macy 		if ((unp2 = unp->unp_conn) == NULL) {
114275a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
1143b5ff0914SRobert Watson 			error = ENOTCONN;
1144b5ff0914SRobert Watson 			break;
1145b36871afSMark Johnston 		} else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1146b36871afSMark Johnston 			UNP_PCB_UNLOCK(unp);
1147b36871afSMark Johnston 			error = EPIPE;
1148b36871afSMark Johnston 			break;
1149b36871afSMark Johnston 		} else if ((unp2 = unp->unp_conn) == NULL) {
1150b36871afSMark Johnston 			UNP_PCB_UNLOCK(unp);
1151b36871afSMark Johnston 			error = ENOTCONN;
1152b36871afSMark Johnston 			break;
115375a67bf3SMatt Macy 		}
115475a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp, unp2, freed);
115575a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
115675a67bf3SMatt Macy 		if (__predict_false(freed)) {
115775a67bf3SMatt Macy 			error = ENOTCONN;
115875a67bf3SMatt Macy 			break;
115975a67bf3SMatt Macy 		}
116075a67bf3SMatt Macy 		if ((so2 = unp2->unp_socket) == NULL) {
116175a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp2);
116275a67bf3SMatt Macy 			error = ENOTCONN;
116375a67bf3SMatt Macy 			break;
116475a67bf3SMatt Macy 		}
1165a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
1166f3f49bbbSRobert Watson 		if (unp2->unp_flags & UNP_WANTCRED) {
11676a2989fdSMatthew N. Dodd 			/*
1168716963cbSGleb Smirnoff 			 * Credentials are passed only once on SOCK_STREAM
1169716963cbSGleb Smirnoff 			 * and SOCK_SEQPACKET.
11706a2989fdSMatthew N. Dodd 			 */
1171f3f49bbbSRobert Watson 			unp2->unp_flags &= ~UNP_WANTCRED;
11726a2989fdSMatthew N. Dodd 			control = unp_addsockcred(td, control);
11736a2989fdSMatthew N. Dodd 		}
11745b0480f2SMark Johnston 
1175df8bae1dSRodney W. Grimes 		/*
11765b0480f2SMark Johnston 		 * Send to paired receive port and wake up readers.  Don't
11775b0480f2SMark Johnston 		 * check for space available in the receive buffer if we're
11785b0480f2SMark Johnston 		 * attaching ancillary data; Unix domain sockets only check
11795b0480f2SMark Johnston 		 * for space in the sending sockbuf, and that check is
11805b0480f2SMark Johnston 		 * performed one level up the stack.  At that level we cannot
11815b0480f2SMark Johnston 		 * precisely account for the amount of buffer space used
11825b0480f2SMark Johnston 		 * (e.g., because control messages are not yet internalized).
1183df8bae1dSRodney W. Grimes 		 */
118484d61770SRobert Watson 		switch (so->so_type) {
118584d61770SRobert Watson 		case SOCK_STREAM:
1186fc3fcacfSRobert Watson 			if (control != NULL) {
11875b0480f2SMark Johnston 				sbappendcontrol_locked(&so2->so_rcv, m,
118825f4ddfbSMark Johnston 				    control, flags);
1189fc3fcacfSRobert Watson 				control = NULL;
1190e7c33e29SRobert Watson 			} else
1191829fae90SGleb Smirnoff 				sbappend_locked(&so2->so_rcv, m, flags);
119284d61770SRobert Watson 			break;
119384d61770SRobert Watson 
1194b36871afSMark Johnston 		case SOCK_SEQPACKET:
11958de34a88SAlan Somers 			if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1196b36871afSMark Johnston 			    &sun_noname, m, control))
119784d61770SRobert Watson 				control = NULL;
119884d61770SRobert Watson 			break;
119984d61770SRobert Watson 		}
120084d61770SRobert Watson 
1201c2090e73SAlan Somers 		mbcnt = so2->so_rcv.sb_mbcnt;
12022b21d0e8SGleb Smirnoff 		sbcc = sbavail(&so2->so_rcv);
12032b21d0e8SGleb Smirnoff 		if (sbcc)
1204337cc6b6SRobert Watson 			sorwakeup_locked(so2);
12052b21d0e8SGleb Smirnoff 		else
12062b21d0e8SGleb Smirnoff 			SOCKBUF_UNLOCK(&so2->so_rcv);
1207337cc6b6SRobert Watson 
1208c2090e73SAlan Somers 		/*
1209c2090e73SAlan Somers 		 * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1210c2090e73SAlan Somers 		 * it would be possible for uipc_rcvd to be called at this
1211c2090e73SAlan Somers 		 * point, drain the receiving sockbuf, clear SB_STOP, and then
1212c2090e73SAlan Somers 		 * we would set SB_STOP below.  That could lead to an empty
1213c2090e73SAlan Somers 		 * sockbuf having SB_STOP set
1214c2090e73SAlan Somers 		 */
1215337cc6b6SRobert Watson 		SOCKBUF_LOCK(&so->so_snd);
1216c2090e73SAlan Somers 		if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1217c2090e73SAlan Somers 			so->so_snd.sb_flags |= SB_STOP;
12187abe2ac2SAlan Cox 		SOCKBUF_UNLOCK(&so->so_snd);
1219e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1220fc3fcacfSRobert Watson 		m = NULL;
1221df8bae1dSRodney W. Grimes 		break;
1222df8bae1dSRodney W. Grimes 	}
1223a29f300eSGarrett Wollman 
12246b8fda4dSGarrett Wollman 	/*
122560a5ef26SRobert Watson 	 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
12266b8fda4dSGarrett Wollman 	 */
1227a29f300eSGarrett Wollman 	if (flags & PRUS_EOF) {
1228ede6e136SRobert Watson 		UNP_PCB_LOCK(unp);
12296b8fda4dSGarrett Wollman 		socantsendmore(so);
12306b8fda4dSGarrett Wollman 		unp_shutdown(unp);
1231e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
1232ede6e136SRobert Watson 	}
1233fc3fcacfSRobert Watson 	if (control != NULL && error != 0)
123499ab95dbSMark Johnston 		unp_dispose_mbuf(control);
1235bd508d39SDon Lewis 
1236a29f300eSGarrett Wollman release:
1237fc3fcacfSRobert Watson 	if (control != NULL)
1238a29f300eSGarrett Wollman 		m_freem(control);
1239100db364SGleb Smirnoff 	/*
1240100db364SGleb Smirnoff 	 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1241100db364SGleb Smirnoff 	 * for freeing memory.
1242100db364SGleb Smirnoff 	 */
1243100db364SGleb Smirnoff 	if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1244a29f300eSGarrett Wollman 		m_freem(m);
1245e5aeaa0cSDag-Erling Smørgrav 	return (error);
1246a29f300eSGarrett Wollman }
1247df8bae1dSRodney W. Grimes 
1248a50b1900SMark Johnston static bool
1249a50b1900SMark Johnston uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1250a50b1900SMark Johnston {
1251a50b1900SMark Johnston 	struct mbuf *mb, *n;
1252a50b1900SMark Johnston 	struct sockbuf *sb;
1253a50b1900SMark Johnston 
1254a50b1900SMark Johnston 	SOCK_LOCK(so);
1255a50b1900SMark Johnston 	if (SOLISTENING(so)) {
1256a50b1900SMark Johnston 		SOCK_UNLOCK(so);
1257a50b1900SMark Johnston 		return (false);
1258a50b1900SMark Johnston 	}
1259a50b1900SMark Johnston 	mb = NULL;
1260a50b1900SMark Johnston 	sb = &so->so_rcv;
1261a50b1900SMark Johnston 	SOCKBUF_LOCK(sb);
1262a50b1900SMark Johnston 	if (sb->sb_fnrdy != NULL) {
1263a50b1900SMark Johnston 		for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1264a50b1900SMark Johnston 			if (mb == m) {
1265a50b1900SMark Johnston 				*errorp = sbready(sb, m, count);
1266a50b1900SMark Johnston 				break;
1267a50b1900SMark Johnston 			}
1268a50b1900SMark Johnston 			mb = mb->m_next;
1269a50b1900SMark Johnston 			if (mb == NULL) {
1270a50b1900SMark Johnston 				mb = n;
12711b778ba2SMark Johnston 				if (mb != NULL)
1272a50b1900SMark Johnston 					n = mb->m_nextpkt;
1273a50b1900SMark Johnston 			}
1274a50b1900SMark Johnston 		}
1275a50b1900SMark Johnston 	}
1276a50b1900SMark Johnston 	SOCKBUF_UNLOCK(sb);
1277a50b1900SMark Johnston 	SOCK_UNLOCK(so);
1278a50b1900SMark Johnston 	return (mb != NULL);
1279a50b1900SMark Johnston }
1280a50b1900SMark Johnston 
1281a29f300eSGarrett Wollman static int
1282c80ea19bSGleb Smirnoff uipc_ready(struct socket *so, struct mbuf *m, int count)
1283c80ea19bSGleb Smirnoff {
1284c80ea19bSGleb Smirnoff 	struct unpcb *unp, *unp2;
1285c80ea19bSGleb Smirnoff 	struct socket *so2;
1286a50b1900SMark Johnston 	int error, i;
1287c80ea19bSGleb Smirnoff 
1288c80ea19bSGleb Smirnoff 	unp = sotounpcb(so);
1289c80ea19bSGleb Smirnoff 
1290a50b1900SMark Johnston 	KASSERT(so->so_type == SOCK_STREAM,
1291a50b1900SMark Johnston 	    ("%s: unexpected socket type for %p", __func__, so));
1292a50b1900SMark Johnston 
1293a62b4665SMatt Macy 	UNP_PCB_LOCK(unp);
1294100db364SGleb Smirnoff 	if ((unp2 = unp->unp_conn) == NULL) {
1295a62b4665SMatt Macy 		UNP_PCB_UNLOCK(unp);
1296a50b1900SMark Johnston 		goto search;
1297100db364SGleb Smirnoff 	}
1298a62b4665SMatt Macy 	if (unp != unp2) {
1299a62b4665SMatt Macy 		if (UNP_PCB_TRYLOCK(unp2) == 0) {
1300a62b4665SMatt Macy 			unp_pcb_hold(unp2);
1301a62b4665SMatt Macy 			UNP_PCB_UNLOCK(unp);
1302c80ea19bSGleb Smirnoff 			UNP_PCB_LOCK(unp2);
1303a62b4665SMatt Macy 			if (unp_pcb_rele(unp2))
1304a50b1900SMark Johnston 				goto search;
1305a62b4665SMatt Macy 		} else
1306a62b4665SMatt Macy 			UNP_PCB_UNLOCK(unp);
1307a62b4665SMatt Macy 	}
1308c80ea19bSGleb Smirnoff 	so2 = unp2->unp_socket;
1309c80ea19bSGleb Smirnoff 	SOCKBUF_LOCK(&so2->so_rcv);
1310c80ea19bSGleb Smirnoff 	if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1311c80ea19bSGleb Smirnoff 		sorwakeup_locked(so2);
1312c80ea19bSGleb Smirnoff 	else
1313c80ea19bSGleb Smirnoff 		SOCKBUF_UNLOCK(&so2->so_rcv);
1314c80ea19bSGleb Smirnoff 	UNP_PCB_UNLOCK(unp2);
1315c80ea19bSGleb Smirnoff 	return (error);
1316a50b1900SMark Johnston 
1317a50b1900SMark Johnston search:
1318a50b1900SMark Johnston 	/*
1319a50b1900SMark Johnston 	 * The receiving socket has been disconnected, but may still be valid.
1320a50b1900SMark Johnston 	 * In this case, the now-ready mbufs are still present in its socket
1321a50b1900SMark Johnston 	 * buffer, so perform an exhaustive search before giving up and freeing
1322a50b1900SMark Johnston 	 * the mbufs.
1323a50b1900SMark Johnston 	 */
1324a50b1900SMark Johnston 	UNP_LINK_RLOCK();
1325a50b1900SMark Johnston 	LIST_FOREACH(unp, &unp_shead, unp_link) {
1326a50b1900SMark Johnston 		if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1327a50b1900SMark Johnston 			break;
1328a50b1900SMark Johnston 	}
1329a50b1900SMark Johnston 	UNP_LINK_RUNLOCK();
1330a50b1900SMark Johnston 
1331a50b1900SMark Johnston 	if (unp == NULL) {
1332a50b1900SMark Johnston 		for (i = 0; i < count; i++)
1333a62b4665SMatt Macy 			m = m_free(m);
1334a50b1900SMark Johnston 		error = ECONNRESET;
1335a50b1900SMark Johnston 	}
1336a50b1900SMark Johnston 	return (error);
1337c80ea19bSGleb Smirnoff }
1338c80ea19bSGleb Smirnoff 
1339c80ea19bSGleb Smirnoff static int
1340a29f300eSGarrett Wollman uipc_sense(struct socket *so, struct stat *sb)
1341a29f300eSGarrett Wollman {
1342c2090e73SAlan Somers 	struct unpcb *unp;
1343a29f300eSGarrett Wollman 
134440f2ac28SRobert Watson 	unp = sotounpcb(so);
13454d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1346e7c33e29SRobert Watson 
1347a29f300eSGarrett Wollman 	sb->st_blksize = so->so_snd.sb_hiwat;
1348f3732fd1SPoul-Henning Kamp 	sb->st_dev = NODEV;
1349a29f300eSGarrett Wollman 	sb->st_ino = unp->unp_ino;
1350df8bae1dSRodney W. Grimes 	return (0);
1351a29f300eSGarrett Wollman }
1352df8bae1dSRodney W. Grimes 
1353a29f300eSGarrett Wollman static int
1354a29f300eSGarrett Wollman uipc_shutdown(struct socket *so)
1355a29f300eSGarrett Wollman {
135640f2ac28SRobert Watson 	struct unpcb *unp;
1357df8bae1dSRodney W. Grimes 
135840f2ac28SRobert Watson 	unp = sotounpcb(so);
13594d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1360e7c33e29SRobert Watson 
1361e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1362a29f300eSGarrett Wollman 	socantsendmore(so);
1363a29f300eSGarrett Wollman 	unp_shutdown(unp);
1364e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1365e5aeaa0cSDag-Erling Smørgrav 	return (0);
1366a29f300eSGarrett Wollman }
1367df8bae1dSRodney W. Grimes 
1368a29f300eSGarrett Wollman static int
136957bf258eSGarrett Wollman uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1370a29f300eSGarrett Wollman {
137140f2ac28SRobert Watson 	struct unpcb *unp;
13720d9ce3a1SRobert Watson 	const struct sockaddr *sa;
1373a29f300eSGarrett Wollman 
13744d4b555eSRobert Watson 	unp = sotounpcb(so);
13754d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1376e7c33e29SRobert Watson 
13770d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1378e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1379fc3fcacfSRobert Watson 	if (unp->unp_addr != NULL)
13800d9ce3a1SRobert Watson 		sa = (struct sockaddr *) unp->unp_addr;
138183f3198bSThomas Moestl 	else
13820d9ce3a1SRobert Watson 		sa = &sun_noname;
13830d9ce3a1SRobert Watson 	bcopy(sa, *nam, sa->sa_len);
1384e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1385e5aeaa0cSDag-Erling Smørgrav 	return (0);
1386df8bae1dSRodney W. Grimes }
1387a29f300eSGarrett Wollman 
1388fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram = {
1389756d52a1SPoul-Henning Kamp 	.pru_abort = 		uipc_abort,
1390756d52a1SPoul-Henning Kamp 	.pru_accept =		uipc_accept,
1391756d52a1SPoul-Henning Kamp 	.pru_attach =		uipc_attach,
1392756d52a1SPoul-Henning Kamp 	.pru_bind =		uipc_bind,
13937493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1394756d52a1SPoul-Henning Kamp 	.pru_connect =		uipc_connect,
13957493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1396756d52a1SPoul-Henning Kamp 	.pru_connect2 =		uipc_connect2,
1397756d52a1SPoul-Henning Kamp 	.pru_detach =		uipc_detach,
1398756d52a1SPoul-Henning Kamp 	.pru_disconnect =	uipc_disconnect,
1399756d52a1SPoul-Henning Kamp 	.pru_listen =		uipc_listen,
1400756d52a1SPoul-Henning Kamp 	.pru_peeraddr =		uipc_peeraddr,
1401756d52a1SPoul-Henning Kamp 	.pru_rcvd =		uipc_rcvd,
1402756d52a1SPoul-Henning Kamp 	.pru_send =		uipc_send,
1403756d52a1SPoul-Henning Kamp 	.pru_sense =		uipc_sense,
1404756d52a1SPoul-Henning Kamp 	.pru_shutdown =		uipc_shutdown,
1405756d52a1SPoul-Henning Kamp 	.pru_sockaddr =		uipc_sockaddr,
1406fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_dgram,
1407fa9402f2SRobert Watson 	.pru_close =		uipc_close,
1408fa9402f2SRobert Watson };
1409fa9402f2SRobert Watson 
141084d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket = {
141184d61770SRobert Watson 	.pru_abort =		uipc_abort,
141284d61770SRobert Watson 	.pru_accept =		uipc_accept,
141384d61770SRobert Watson 	.pru_attach =		uipc_attach,
141484d61770SRobert Watson 	.pru_bind =		uipc_bind,
14157493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
141684d61770SRobert Watson 	.pru_connect =		uipc_connect,
14177493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
141884d61770SRobert Watson 	.pru_connect2 =		uipc_connect2,
141984d61770SRobert Watson 	.pru_detach =		uipc_detach,
142084d61770SRobert Watson 	.pru_disconnect =	uipc_disconnect,
142184d61770SRobert Watson 	.pru_listen =		uipc_listen,
142284d61770SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
142384d61770SRobert Watson 	.pru_rcvd =		uipc_rcvd,
142484d61770SRobert Watson 	.pru_send =		uipc_send,
142584d61770SRobert Watson 	.pru_sense =		uipc_sense,
142684d61770SRobert Watson 	.pru_shutdown =		uipc_shutdown,
142784d61770SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
142884d61770SRobert Watson 	.pru_soreceive =	soreceive_generic,	/* XXX: or...? */
142984d61770SRobert Watson 	.pru_close =		uipc_close,
143084d61770SRobert Watson };
143184d61770SRobert Watson 
1432fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_stream = {
1433fa9402f2SRobert Watson 	.pru_abort = 		uipc_abort,
1434fa9402f2SRobert Watson 	.pru_accept =		uipc_accept,
1435fa9402f2SRobert Watson 	.pru_attach =		uipc_attach,
1436fa9402f2SRobert Watson 	.pru_bind =		uipc_bind,
14377493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1438fa9402f2SRobert Watson 	.pru_connect =		uipc_connect,
14397493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1440fa9402f2SRobert Watson 	.pru_connect2 =		uipc_connect2,
1441fa9402f2SRobert Watson 	.pru_detach =		uipc_detach,
1442fa9402f2SRobert Watson 	.pru_disconnect =	uipc_disconnect,
1443fa9402f2SRobert Watson 	.pru_listen =		uipc_listen,
1444fa9402f2SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
1445fa9402f2SRobert Watson 	.pru_rcvd =		uipc_rcvd,
1446fa9402f2SRobert Watson 	.pru_send =		uipc_send,
1447c80ea19bSGleb Smirnoff 	.pru_ready =		uipc_ready,
1448fa9402f2SRobert Watson 	.pru_sense =		uipc_sense,
1449fa9402f2SRobert Watson 	.pru_shutdown =		uipc_shutdown,
1450fa9402f2SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
1451fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_generic,
1452a152f8a3SRobert Watson 	.pru_close =		uipc_close,
1453a29f300eSGarrett Wollman };
1454df8bae1dSRodney W. Grimes 
14550b36cd25SRobert Watson static int
1456892af6b9SRobert Watson uipc_ctloutput(struct socket *so, struct sockopt *sopt)
14570c1bb4fbSDima Dorfman {
145840f2ac28SRobert Watson 	struct unpcb *unp;
14590d9ce3a1SRobert Watson 	struct xucred xu;
14606a2989fdSMatthew N. Dodd 	int error, optval;
14616a2989fdSMatthew N. Dodd 
14626e0c8e1aSKonstantin Belousov 	if (sopt->sopt_level != SOL_LOCAL)
146396a041b5SMatthew N. Dodd 		return (EINVAL);
146496a041b5SMatthew N. Dodd 
14656a2989fdSMatthew N. Dodd 	unp = sotounpcb(so);
14664d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
14676a2989fdSMatthew N. Dodd 	error = 0;
14680c1bb4fbSDima Dorfman 	switch (sopt->sopt_dir) {
14690c1bb4fbSDima Dorfman 	case SOPT_GET:
14700c1bb4fbSDima Dorfman 		switch (sopt->sopt_name) {
14710c1bb4fbSDima Dorfman 		case LOCAL_PEERCRED:
1472e7c33e29SRobert Watson 			UNP_PCB_LOCK(unp);
14730c1bb4fbSDima Dorfman 			if (unp->unp_flags & UNP_HAVEPC)
14740d9ce3a1SRobert Watson 				xu = unp->unp_peercred;
14750c1bb4fbSDima Dorfman 			else {
14760c1bb4fbSDima Dorfman 				if (so->so_type == SOCK_STREAM)
14770c1bb4fbSDima Dorfman 					error = ENOTCONN;
14780c1bb4fbSDima Dorfman 				else
14790c1bb4fbSDima Dorfman 					error = EINVAL;
14800c1bb4fbSDima Dorfman 			}
1481e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
14820d9ce3a1SRobert Watson 			if (error == 0)
14830d9ce3a1SRobert Watson 				error = sooptcopyout(sopt, &xu, sizeof(xu));
14840c1bb4fbSDima Dorfman 			break;
1485e7c33e29SRobert Watson 
14866a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
1487a6357845SRobert Watson 			/* Unlocked read. */
14886a2989fdSMatthew N. Dodd 			optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
14896a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14906a2989fdSMatthew N. Dodd 			break;
1491e7c33e29SRobert Watson 
14926a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
1493a6357845SRobert Watson 			/* Unlocked read. */
14946a2989fdSMatthew N. Dodd 			optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
14956a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14966a2989fdSMatthew N. Dodd 			break;
1497e7c33e29SRobert Watson 
14980c1bb4fbSDima Dorfman 		default:
14990c1bb4fbSDima Dorfman 			error = EOPNOTSUPP;
15000c1bb4fbSDima Dorfman 			break;
15010c1bb4fbSDima Dorfman 		}
15020c1bb4fbSDima Dorfman 		break;
1503e7c33e29SRobert Watson 
15040c1bb4fbSDima Dorfman 	case SOPT_SET:
15056a2989fdSMatthew N. Dodd 		switch (sopt->sopt_name) {
15066a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
15076a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
15086a2989fdSMatthew N. Dodd 			error = sooptcopyin(sopt, &optval, sizeof(optval),
15096a2989fdSMatthew N. Dodd 					    sizeof(optval));
15106a2989fdSMatthew N. Dodd 			if (error)
15116a2989fdSMatthew N. Dodd 				break;
15126a2989fdSMatthew N. Dodd 
1513e7c33e29SRobert Watson #define	OPTSET(bit) do {						\
1514e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);						\
15156a2989fdSMatthew N. Dodd 	if (optval)							\
15166a2989fdSMatthew N. Dodd 		unp->unp_flags |= bit;					\
15176a2989fdSMatthew N. Dodd 	else								\
1518e7c33e29SRobert Watson 		unp->unp_flags &= ~bit;					\
1519e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);						\
1520e7c33e29SRobert Watson } while (0)
15216a2989fdSMatthew N. Dodd 
15226a2989fdSMatthew N. Dodd 			switch (sopt->sopt_name) {
15236a2989fdSMatthew N. Dodd 			case LOCAL_CREDS:
15246a2989fdSMatthew N. Dodd 				OPTSET(UNP_WANTCRED);
15256a2989fdSMatthew N. Dodd 				break;
1526e7c33e29SRobert Watson 
15276a2989fdSMatthew N. Dodd 			case LOCAL_CONNWAIT:
15286a2989fdSMatthew N. Dodd 				OPTSET(UNP_CONNWAIT);
15296a2989fdSMatthew N. Dodd 				break;
1530e7c33e29SRobert Watson 
15316a2989fdSMatthew N. Dodd 			default:
15326a2989fdSMatthew N. Dodd 				break;
15336a2989fdSMatthew N. Dodd 			}
15346a2989fdSMatthew N. Dodd 			break;
15356a2989fdSMatthew N. Dodd #undef	OPTSET
15366a2989fdSMatthew N. Dodd 		default:
15376a2989fdSMatthew N. Dodd 			error = ENOPROTOOPT;
15386a2989fdSMatthew N. Dodd 			break;
15396a2989fdSMatthew N. Dodd 		}
1540abb886faSMatthew N. Dodd 		break;
1541e7c33e29SRobert Watson 
15420c1bb4fbSDima Dorfman 	default:
15430c1bb4fbSDima Dorfman 		error = EOPNOTSUPP;
15440c1bb4fbSDima Dorfman 		break;
15450c1bb4fbSDima Dorfman 	}
15460c1bb4fbSDima Dorfman 	return (error);
15470c1bb4fbSDima Dorfman }
15480c1bb4fbSDima Dorfman 
1549f708ef1bSPoul-Henning Kamp static int
1550892af6b9SRobert Watson unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1551df8bae1dSRodney W. Grimes {
15527493f24eSPawel Jakub Dawidek 
15537493f24eSPawel Jakub Dawidek 	return (unp_connectat(AT_FDCWD, so, nam, td));
15547493f24eSPawel Jakub Dawidek }
15557493f24eSPawel Jakub Dawidek 
15567493f24eSPawel Jakub Dawidek static int
15577493f24eSPawel Jakub Dawidek unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
15587493f24eSPawel Jakub Dawidek     struct thread *td)
15597493f24eSPawel Jakub Dawidek {
1560*ed92e1c7SMark Johnston 	struct mtx *vplock;
1561*ed92e1c7SMark Johnston 	struct sockaddr_un *soun;
1562892af6b9SRobert Watson 	struct vnode *vp;
1563779f106aSGleb Smirnoff 	struct socket *so2;
1564b295bdcdSRobert Watson 	struct unpcb *unp, *unp2, *unp3;
1565df8bae1dSRodney W. Grimes 	struct nameidata nd;
156657bf258eSGarrett Wollman 	char buf[SOCK_MAXADDRLEN];
15670d9ce3a1SRobert Watson 	struct sockaddr *sa;
15687008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
156975a67bf3SMatt Macy 	int error, len, freed;
1570*ed92e1c7SMark Johnston 	bool connreq;
15710d9ce3a1SRobert Watson 
1572cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
1573cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
1574a06534c3SBjoern A. Zeeb 	if (nam->sa_len > sizeof(struct sockaddr_un))
1575a06534c3SBjoern A. Zeeb 		return (EINVAL);
157657bf258eSGarrett Wollman 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
157757bf258eSGarrett Wollman 	if (len <= 0)
1578e5aeaa0cSDag-Erling Smørgrav 		return (EINVAL);
1579*ed92e1c7SMark Johnston 	soun = (struct sockaddr_un *)nam;
15807928893dSEd Maste 	bcopy(soun->sun_path, buf, len);
15817928893dSEd Maste 	buf[len] = 0;
1582e7c33e29SRobert Watson 
158375a67bf3SMatt Macy 	unp = sotounpcb(so);
1584e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
15854f1f0ef5SRobert Watson 	if (unp->unp_flags & UNP_CONNECTING) {
1586e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
15874f1f0ef5SRobert Watson 		return (EALREADY);
15884f1f0ef5SRobert Watson 	}
158905102f04SRobert Watson 	unp->unp_flags |= UNP_CONNECTING;
1590e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1591e7c33e29SRobert Watson 
1592*ed92e1c7SMark Johnston 	connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1593*ed92e1c7SMark Johnston 	if (connreq)
15940d9ce3a1SRobert Watson 		sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1595*ed92e1c7SMark Johnston 	else
1596*ed92e1c7SMark Johnston 		sa = NULL;
15977493f24eSPawel Jakub Dawidek 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
15987008be5bSPawel Jakub Dawidek 	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1599797f2d22SPoul-Henning Kamp 	error = namei(&nd);
1600797f2d22SPoul-Henning Kamp 	if (error)
16010d9ce3a1SRobert Watson 		vp = NULL;
16020d9ce3a1SRobert Watson 	else
1603df8bae1dSRodney W. Grimes 		vp = nd.ni_vp;
16040d9ce3a1SRobert Watson 	ASSERT_VOP_LOCKED(vp, "unp_connect");
1605762e6b85SEivind Eklund 	NDFREE(&nd, NDF_ONLY_PNBUF);
16060d9ce3a1SRobert Watson 	if (error)
16070d9ce3a1SRobert Watson 		goto bad;
16080d9ce3a1SRobert Watson 
1609df8bae1dSRodney W. Grimes 	if (vp->v_type != VSOCK) {
1610df8bae1dSRodney W. Grimes 		error = ENOTSOCK;
1611df8bae1dSRodney W. Grimes 		goto bad;
1612df8bae1dSRodney W. Grimes 	}
16136fac927cSRobert Watson #ifdef MAC
161430d239bcSRobert Watson 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
16156fac927cSRobert Watson 	if (error)
16166fac927cSRobert Watson 		goto bad;
16176fac927cSRobert Watson #endif
1618a854ed98SJohn Baldwin 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1619797f2d22SPoul-Henning Kamp 	if (error)
1620df8bae1dSRodney W. Grimes 		goto bad;
1621e7c33e29SRobert Watson 
1622b295bdcdSRobert Watson 	unp = sotounpcb(so);
16234d4b555eSRobert Watson 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1624e7c33e29SRobert Watson 
162575a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
162675a67bf3SMatt Macy 	mtx_lock(vplock);
16270c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp2);
16280c3c207fSGleb Smirnoff 	if (unp2 == NULL) {
1629df8bae1dSRodney W. Grimes 		error = ECONNREFUSED;
16302260c03dSRobert Watson 		goto bad2;
1631df8bae1dSRodney W. Grimes 	}
16320c3c207fSGleb Smirnoff 	so2 = unp2->unp_socket;
1633df8bae1dSRodney W. Grimes 	if (so->so_type != so2->so_type) {
1634df8bae1dSRodney W. Grimes 		error = EPROTOTYPE;
16352260c03dSRobert Watson 		goto bad2;
1636df8bae1dSRodney W. Grimes 	}
1637*ed92e1c7SMark Johnston 	if (connreq) {
1638e7c33e29SRobert Watson 		if (so2->so_options & SO_ACCEPTCONN) {
16391fb51a12SBjoern A. Zeeb 			CURVNET_SET(so2->so_vnet);
1640779f106aSGleb Smirnoff 			so2 = sonewconn(so2, 0);
16411fb51a12SBjoern A. Zeeb 			CURVNET_RESTORE();
1642e7c33e29SRobert Watson 		} else
1643779f106aSGleb Smirnoff 			so2 = NULL;
1644779f106aSGleb Smirnoff 		if (so2 == NULL) {
1645df8bae1dSRodney W. Grimes 			error = ECONNREFUSED;
1646cb8f450bSMatt Macy 			goto bad2;
1647df8bae1dSRodney W. Grimes 		}
1648779f106aSGleb Smirnoff 		unp3 = sotounpcb(so2);
16494820bf6aSMark Johnston 		unp_pcb_lock_pair(unp2, unp3);
16500d9ce3a1SRobert Watson 		if (unp2->unp_addr != NULL) {
16510d9ce3a1SRobert Watson 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
16520d9ce3a1SRobert Watson 			unp3->unp_addr = (struct sockaddr_un *) sa;
16530d9ce3a1SRobert Watson 			sa = NULL;
16540d9ce3a1SRobert Watson 		}
1655b523ec24SRobert Watson 
1656da446550SAlan Somers 		unp_copy_peercred(td, unp3, unp, unp2);
1657b523ec24SRobert Watson 
1658e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1659779f106aSGleb Smirnoff 		unp2 = unp3;
166075a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp2, unp, freed);
1661e10ef65dSMatt Macy 		if (__predict_false(freed)) {
1662e10ef65dSMatt Macy 			UNP_PCB_UNLOCK(unp2);
1663e10ef65dSMatt Macy 			error = ECONNREFUSED;
1664e10ef65dSMatt Macy 			goto bad2;
1665e10ef65dSMatt Macy 		}
1666335654d7SRobert Watson #ifdef MAC
1667779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so, so2);
1668779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so2, so);
1669335654d7SRobert Watson #endif
1670a3a73490SMatt Macy 	} else {
16714820bf6aSMark Johnston 		unp_pcb_lock_pair(unp, unp2);
1672a3a73490SMatt Macy 	}
1673779f106aSGleb Smirnoff 	KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1674779f106aSGleb Smirnoff 	    sotounpcb(so2) == unp2,
1675779f106aSGleb Smirnoff 	    ("%s: unp2 %p so2 %p", __func__, unp2, so2));
16766a2989fdSMatthew N. Dodd 	error = unp_connect2(so, so2, PRU_CONNECT);
16774820bf6aSMark Johnston 	unp_pcb_unlock_pair(unp, unp2);
16780d9ce3a1SRobert Watson bad2:
167975a67bf3SMatt Macy 	mtx_unlock(vplock);
1680df8bae1dSRodney W. Grimes bad:
168175a67bf3SMatt Macy 	if (vp != NULL) {
1682df8bae1dSRodney W. Grimes 		vput(vp);
168375a67bf3SMatt Macy 	}
16840d9ce3a1SRobert Watson 	free(sa, M_SONAME);
1685e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
16864f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_CONNECTING;
1687e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1688df8bae1dSRodney W. Grimes 	return (error);
1689df8bae1dSRodney W. Grimes }
1690df8bae1dSRodney W. Grimes 
1691da446550SAlan Somers /*
1692da446550SAlan Somers  * Set socket peer credentials at connection time.
1693da446550SAlan Somers  *
1694da446550SAlan Somers  * The client's PCB credentials are copied from its process structure.  The
1695da446550SAlan Somers  * server's PCB credentials are copied from the socket on which it called
1696da446550SAlan Somers  * listen(2).  uipc_listen cached that process's credentials at the time.
1697da446550SAlan Somers  */
1698da446550SAlan Somers void
1699da446550SAlan Somers unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1700da446550SAlan Somers     struct unpcb *server_unp, struct unpcb *listen_unp)
1701da446550SAlan Somers {
1702c5afec6eSDmitry Chagin 	cru2xt(td, &client_unp->unp_peercred);
1703da446550SAlan Somers 	client_unp->unp_flags |= UNP_HAVEPC;
1704da446550SAlan Somers 
1705da446550SAlan Somers 	memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1706da446550SAlan Somers 	    sizeof(server_unp->unp_peercred));
1707da446550SAlan Somers 	server_unp->unp_flags |= UNP_HAVEPC;
1708da446550SAlan Somers 	if (listen_unp->unp_flags & UNP_WANTCRED)
1709da446550SAlan Somers 		client_unp->unp_flags |= UNP_WANTCRED;
1710da446550SAlan Somers }
1711da446550SAlan Somers 
1712db48c0d2SRobert Watson static int
17136a2989fdSMatthew N. Dodd unp_connect2(struct socket *so, struct socket *so2, int req)
1714df8bae1dSRodney W. Grimes {
1715e7c33e29SRobert Watson 	struct unpcb *unp;
1716892af6b9SRobert Watson 	struct unpcb *unp2;
1717df8bae1dSRodney W. Grimes 
1718e7c33e29SRobert Watson 	unp = sotounpcb(so);
1719e7c33e29SRobert Watson 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1720e7c33e29SRobert Watson 	unp2 = sotounpcb(so2);
1721e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1722e7c33e29SRobert Watson 
1723e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1724e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
17250d9ce3a1SRobert Watson 
1726df8bae1dSRodney W. Grimes 	if (so2->so_type != so->so_type)
1727df8bae1dSRodney W. Grimes 		return (EPROTOTYPE);
1728df8bae1dSRodney W. Grimes 	unp->unp_conn = unp2;
172975a67bf3SMatt Macy 	unp_pcb_hold(unp2);
173075a67bf3SMatt Macy 	unp_pcb_hold(unp);
1731df8bae1dSRodney W. Grimes 	switch (so->so_type) {
1732df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
173375a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
173498271db4SGarrett Wollman 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
173575a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
1736df8bae1dSRodney W. Grimes 		soisconnected(so);
1737df8bae1dSRodney W. Grimes 		break;
1738df8bae1dSRodney W. Grimes 
1739df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
174084d61770SRobert Watson 	case SOCK_SEQPACKET:
1741df8bae1dSRodney W. Grimes 		unp2->unp_conn = unp;
17426a2989fdSMatthew N. Dodd 		if (req == PRU_CONNECT &&
17436a2989fdSMatthew N. Dodd 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
17446a2989fdSMatthew N. Dodd 			soisconnecting(so);
17456a2989fdSMatthew N. Dodd 		else
1746df8bae1dSRodney W. Grimes 			soisconnected(so);
1747df8bae1dSRodney W. Grimes 		soisconnected(so2);
1748df8bae1dSRodney W. Grimes 		break;
1749df8bae1dSRodney W. Grimes 
1750df8bae1dSRodney W. Grimes 	default:
1751df8bae1dSRodney W. Grimes 		panic("unp_connect2");
1752df8bae1dSRodney W. Grimes 	}
1753df8bae1dSRodney W. Grimes 	return (0);
1754df8bae1dSRodney W. Grimes }
1755df8bae1dSRodney W. Grimes 
1756f708ef1bSPoul-Henning Kamp static void
1757e7c33e29SRobert Watson unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1758df8bae1dSRodney W. Grimes {
175975a67bf3SMatt Macy 	struct socket *so, *so2;
1760f0317f86SMark Johnston #ifdef INVARIANTS
1761f0317f86SMark Johnston 	struct unpcb *unptmp;
1762f0317f86SMark Johnston #endif
17630d9ce3a1SRobert Watson 
1764e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1765e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
1766f0317f86SMark Johnston 	KASSERT(unp->unp_conn == unp2,
1767f0317f86SMark Johnston 	    ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
1768e7c33e29SRobert Watson 
1769fc3fcacfSRobert Watson 	unp->unp_conn = NULL;
177075a67bf3SMatt Macy 	so = unp->unp_socket;
177175a67bf3SMatt Macy 	so2 = unp2->unp_socket;
1772df8bae1dSRodney W. Grimes 	switch (unp->unp_socket->so_type) {
1773df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
177475a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
1775f0317f86SMark Johnston #ifdef INVARIANTS
1776f0317f86SMark Johnston 		LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
1777f0317f86SMark Johnston 			if (unptmp == unp)
1778f0317f86SMark Johnston 				break;
1779f0317f86SMark Johnston 		}
1780f0317f86SMark Johnston 		KASSERT(unptmp != NULL,
1781f0317f86SMark Johnston 		    ("%s: %p not found in reflist of %p", __func__, unp, unp2));
1782f0317f86SMark Johnston #endif
178398271db4SGarrett Wollman 		LIST_REMOVE(unp, unp_reflink);
178475a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
178575a67bf3SMatt Macy 		if (so) {
17861b2e3b4bSRobert Watson 			SOCK_LOCK(so);
17871b2e3b4bSRobert Watson 			so->so_state &= ~SS_ISCONNECTED;
17881b2e3b4bSRobert Watson 			SOCK_UNLOCK(so);
178975a67bf3SMatt Macy 		}
1790df8bae1dSRodney W. Grimes 		break;
1791df8bae1dSRodney W. Grimes 
1792df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
179384d61770SRobert Watson 	case SOCK_SEQPACKET:
179475a67bf3SMatt Macy 		if (so)
179575a67bf3SMatt Macy 			soisdisconnected(so);
179675a67bf3SMatt Macy 		MPASS(unp2->unp_conn == unp);
1797fc3fcacfSRobert Watson 		unp2->unp_conn = NULL;
179875a67bf3SMatt Macy 		if (so2)
179975a67bf3SMatt Macy 			soisdisconnected(so2);
1800df8bae1dSRodney W. Grimes 		break;
1801df8bae1dSRodney W. Grimes 	}
1802f0317f86SMark Johnston 
1803f0317f86SMark Johnston 	if (unp == unp2) {
1804f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
1805f0317f86SMark Johnston 		if (!unp_pcb_rele(unp))
1806f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp);
1807f0317f86SMark Johnston 	} else {
1808f0317f86SMark Johnston 		if (!unp_pcb_rele(unp))
1809f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp);
1810f0317f86SMark Johnston 		if (!unp_pcb_rele(unp2))
1811f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp2);
1812f0317f86SMark Johnston 	}
1813df8bae1dSRodney W. Grimes }
1814df8bae1dSRodney W. Grimes 
18150d9ce3a1SRobert Watson /*
1816d7924b70SRobert Watson  * unp_pcblist() walks the global list of struct unpcb's to generate a
1817d7924b70SRobert Watson  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1818d7924b70SRobert Watson  * sequentially, validating the generation number on each to see if it has
1819d7924b70SRobert Watson  * been detached.  All of this is necessary because copyout() may sleep on
1820d7924b70SRobert Watson  * disk I/O.
18210d9ce3a1SRobert Watson  */
182298271db4SGarrett Wollman static int
182382d9ae4eSPoul-Henning Kamp unp_pcblist(SYSCTL_HANDLER_ARGS)
182498271db4SGarrett Wollman {
182598271db4SGarrett Wollman 	struct unpcb *unp, **unp_list;
182698271db4SGarrett Wollman 	unp_gen_t gencnt;
18278f364875SJulian Elischer 	struct xunpgen *xug;
182898271db4SGarrett Wollman 	struct unp_head *head;
18298f364875SJulian Elischer 	struct xunpcb *xu;
1830d821d364SPedro F. Giffuni 	u_int i;
18315362170dSMark Johnston 	int error, n;
183298271db4SGarrett Wollman 
183384d61770SRobert Watson 	switch ((intptr_t)arg1) {
183484d61770SRobert Watson 	case SOCK_STREAM:
183584d61770SRobert Watson 		head = &unp_shead;
183684d61770SRobert Watson 		break;
183784d61770SRobert Watson 
183884d61770SRobert Watson 	case SOCK_DGRAM:
183984d61770SRobert Watson 		head = &unp_dhead;
184084d61770SRobert Watson 		break;
184184d61770SRobert Watson 
184284d61770SRobert Watson 	case SOCK_SEQPACKET:
184384d61770SRobert Watson 		head = &unp_sphead;
184484d61770SRobert Watson 		break;
184584d61770SRobert Watson 
184684d61770SRobert Watson 	default:
1847604f19c9SRobert Watson 		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
184884d61770SRobert Watson 	}
184998271db4SGarrett Wollman 
185098271db4SGarrett Wollman 	/*
185198271db4SGarrett Wollman 	 * The process of preparing the PCB list is too time-consuming and
185298271db4SGarrett Wollman 	 * resource-intensive to repeat twice on every request.
185398271db4SGarrett Wollman 	 */
1854fc3fcacfSRobert Watson 	if (req->oldptr == NULL) {
185598271db4SGarrett Wollman 		n = unp_count;
18568f364875SJulian Elischer 		req->oldidx = 2 * (sizeof *xug)
185798271db4SGarrett Wollman 			+ (n + n/8) * sizeof(struct xunpcb);
1858e5aeaa0cSDag-Erling Smørgrav 		return (0);
185998271db4SGarrett Wollman 	}
186098271db4SGarrett Wollman 
1861fc3fcacfSRobert Watson 	if (req->newptr != NULL)
1862e5aeaa0cSDag-Erling Smørgrav 		return (EPERM);
186398271db4SGarrett Wollman 
186498271db4SGarrett Wollman 	/*
186598271db4SGarrett Wollman 	 * OK, now we're committed to doing something.
186698271db4SGarrett Wollman 	 */
186779db6fe7SMark Johnston 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1868779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
186998271db4SGarrett Wollman 	gencnt = unp_gencnt;
187098271db4SGarrett Wollman 	n = unp_count;
1871779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
187298271db4SGarrett Wollman 
18738f364875SJulian Elischer 	xug->xug_len = sizeof *xug;
18748f364875SJulian Elischer 	xug->xug_count = n;
18758f364875SJulian Elischer 	xug->xug_gen = gencnt;
18768f364875SJulian Elischer 	xug->xug_sogen = so_gencnt;
18778f364875SJulian Elischer 	error = SYSCTL_OUT(req, xug, sizeof *xug);
18788f364875SJulian Elischer 	if (error) {
18798f364875SJulian Elischer 		free(xug, M_TEMP);
1880e5aeaa0cSDag-Erling Smørgrav 		return (error);
18818f364875SJulian Elischer 	}
188298271db4SGarrett Wollman 
1883a163d034SWarner Losh 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
188498271db4SGarrett Wollman 
1885779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
18862e3c8fcbSPoul-Henning Kamp 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
18872e3c8fcbSPoul-Henning Kamp 	     unp = LIST_NEXT(unp, unp_link)) {
1888e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
18898a7d8cc6SRobert Watson 		if (unp->unp_gencnt <= gencnt) {
1890a854ed98SJohn Baldwin 			if (cr_cansee(req->td->td_ucred,
1891e7c33e29SRobert Watson 			    unp->unp_socket->so_cred)) {
1892e7c33e29SRobert Watson 				UNP_PCB_UNLOCK(unp);
18934787fd37SPaul Saab 				continue;
1894e7c33e29SRobert Watson 			}
189598271db4SGarrett Wollman 			unp_list[i++] = unp;
189675a67bf3SMatt Macy 			unp_pcb_hold(unp);
189798271db4SGarrett Wollman 		}
1898e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
18994787fd37SPaul Saab 	}
1900779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
19011c381b19SRobert Watson 	n = i;			/* In case we lost some during malloc. */
190298271db4SGarrett Wollman 
190398271db4SGarrett Wollman 	error = 0;
1904fe2eee82SColin Percival 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
190598271db4SGarrett Wollman 	for (i = 0; i < n; i++) {
190698271db4SGarrett Wollman 		unp = unp_list[i];
1907e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
19085362170dSMark Johnston 		if (unp_pcb_rele(unp))
19095362170dSMark Johnston 			continue;
191075a67bf3SMatt Macy 
19115362170dSMark Johnston 		if (unp->unp_gencnt <= gencnt) {
19128f364875SJulian Elischer 			xu->xu_len = sizeof *xu;
19133a20f06aSBrooks Davis 			xu->xu_unpp = (uintptr_t)unp;
191498271db4SGarrett Wollman 			/*
191598271db4SGarrett Wollman 			 * XXX - need more locking here to protect against
191698271db4SGarrett Wollman 			 * connect/disconnect races for SMP.
191798271db4SGarrett Wollman 			 */
1918fc3fcacfSRobert Watson 			if (unp->unp_addr != NULL)
19198f364875SJulian Elischer 				bcopy(unp->unp_addr, &xu->xu_addr,
192098271db4SGarrett Wollman 				      unp->unp_addr->sun_len);
19210e229f34SGleb Smirnoff 			else
19220e229f34SGleb Smirnoff 				bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1923fc3fcacfSRobert Watson 			if (unp->unp_conn != NULL &&
1924fc3fcacfSRobert Watson 			    unp->unp_conn->unp_addr != NULL)
192598271db4SGarrett Wollman 				bcopy(unp->unp_conn->unp_addr,
19268f364875SJulian Elischer 				      &xu->xu_caddr,
192798271db4SGarrett Wollman 				      unp->unp_conn->unp_addr->sun_len);
19280e229f34SGleb Smirnoff 			else
19290e229f34SGleb Smirnoff 				bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
19303a20f06aSBrooks Davis 			xu->unp_vnode = (uintptr_t)unp->unp_vnode;
19313a20f06aSBrooks Davis 			xu->unp_conn = (uintptr_t)unp->unp_conn;
19323a20f06aSBrooks Davis 			xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
19333a20f06aSBrooks Davis 			xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
19340e229f34SGleb Smirnoff 			xu->unp_gencnt = unp->unp_gencnt;
19358f364875SJulian Elischer 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1936e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
19378f364875SJulian Elischer 			error = SYSCTL_OUT(req, xu, sizeof *xu);
19385362170dSMark Johnston 		} else {
1939e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
1940e7c33e29SRobert Watson 		}
19415362170dSMark Johnston 	}
19428f364875SJulian Elischer 	free(xu, M_TEMP);
194398271db4SGarrett Wollman 	if (!error) {
194498271db4SGarrett Wollman 		/*
19451c381b19SRobert Watson 		 * Give the user an updated idea of our state.  If the
19461c381b19SRobert Watson 		 * generation differs from what we told her before, she knows
19471c381b19SRobert Watson 		 * that something happened while we were processing this
19481c381b19SRobert Watson 		 * request, and it might be necessary to retry.
194998271db4SGarrett Wollman 		 */
19508f364875SJulian Elischer 		xug->xug_gen = unp_gencnt;
19518f364875SJulian Elischer 		xug->xug_sogen = so_gencnt;
19528f364875SJulian Elischer 		xug->xug_count = unp_count;
19538f364875SJulian Elischer 		error = SYSCTL_OUT(req, xug, sizeof *xug);
195498271db4SGarrett Wollman 	}
195598271db4SGarrett Wollman 	free(unp_list, M_TEMP);
19568f364875SJulian Elischer 	free(xug, M_TEMP);
1957e5aeaa0cSDag-Erling Smørgrav 	return (error);
195898271db4SGarrett Wollman }
195998271db4SGarrett Wollman 
19607029da5cSPawel Biernacki SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
19617029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19622fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
196398271db4SGarrett Wollman     "List of active local datagram sockets");
19647029da5cSPawel Biernacki SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
19657029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19662fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
196798271db4SGarrett Wollman     "List of active local stream sockets");
19682fee06f0SMatthew D Fleming SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
19697029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19702fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
197184d61770SRobert Watson     "List of active local seqpacket sockets");
197298271db4SGarrett Wollman 
1973f708ef1bSPoul-Henning Kamp static void
1974892af6b9SRobert Watson unp_shutdown(struct unpcb *unp)
1975df8bae1dSRodney W. Grimes {
1976e7c33e29SRobert Watson 	struct unpcb *unp2;
1977df8bae1dSRodney W. Grimes 	struct socket *so;
1978df8bae1dSRodney W. Grimes 
1979e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
19800d9ce3a1SRobert Watson 
1981e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
198284d61770SRobert Watson 	if ((unp->unp_socket->so_type == SOCK_STREAM ||
198384d61770SRobert Watson 	    (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1984e7c33e29SRobert Watson 		so = unp2->unp_socket;
1985e7c33e29SRobert Watson 		if (so != NULL)
1986df8bae1dSRodney W. Grimes 			socantrcvmore(so);
1987df8bae1dSRodney W. Grimes 	}
1988e7c33e29SRobert Watson }
1989df8bae1dSRodney W. Grimes 
1990f708ef1bSPoul-Henning Kamp static void
1991afc055d9SEd Schouten unp_drop(struct unpcb *unp)
1992df8bae1dSRodney W. Grimes {
1993df8bae1dSRodney W. Grimes 	struct socket *so = unp->unp_socket;
1994e7c33e29SRobert Watson 	struct unpcb *unp2;
199575a67bf3SMatt Macy 	int freed;
19960d9ce3a1SRobert Watson 
1997afc055d9SEd Schouten 	/*
1998afc055d9SEd Schouten 	 * Regardless of whether the socket's peer dropped the connection
1999afc055d9SEd Schouten 	 * with this socket by aborting or disconnecting, POSIX requires
2000afc055d9SEd Schouten 	 * that ECONNRESET is returned.
2001afc055d9SEd Schouten 	 */
200275a67bf3SMatt Macy 	/* acquire a reference so that unp isn't freed from underneath us */
200375a67bf3SMatt Macy 
200475a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
200575a67bf3SMatt Macy 	if (so)
2006afc055d9SEd Schouten 		so->so_error = ECONNRESET;
2007e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
2008f0317f86SMark Johnston 	/* Last reference dropped in unp_disconnect(). */
2009acf9fd05SMatt Macy 	if (unp2 == unp) {
2010f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
2011acf9fd05SMatt Macy 		unp_disconnect(unp, unp2);
2012acf9fd05SMatt Macy 	} else if (unp2 != NULL) {
201375a67bf3SMatt Macy 		unp_pcb_owned_lock2(unp, unp2, freed);
2014f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
2015e7c33e29SRobert Watson 		unp_disconnect(unp, unp2);
2016f0317f86SMark Johnston 	} else if (!unp_pcb_rele(unp)) {
201775a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
201875a67bf3SMatt Macy 	}
2019f0317f86SMark Johnston }
2020df8bae1dSRodney W. Grimes 
20212bc21ed9SDavid Malone static void
20228cb539f1SPawel Jakub Dawidek unp_freerights(struct filedescent **fdep, int fdcount)
2023df8bae1dSRodney W. Grimes {
20242bc21ed9SDavid Malone 	struct file *fp;
20252609222aSPawel Jakub Dawidek 	int i;
2026df8bae1dSRodney W. Grimes 
202782e825c4SGleb Smirnoff 	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
202882e825c4SGleb Smirnoff 
20298cb539f1SPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
20308cb539f1SPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
20318cb539f1SPawel Jakub Dawidek 		filecaps_free(&fdep[i]->fde_caps);
20328692c025SYoshinobu Inoue 		unp_discard(fp);
2033df8bae1dSRodney W. Grimes 	}
20348cb539f1SPawel Jakub Dawidek 	free(fdep[0], M_FILECAPS);
20352bc21ed9SDavid Malone }
20362bc21ed9SDavid Malone 
20370b36cd25SRobert Watson static int
2038c2e3c52eSJilles Tjoelker unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
20392bc21ed9SDavid Malone {
20402bc21ed9SDavid Malone 	struct thread *td = curthread;		/* XXX */
20412bc21ed9SDavid Malone 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
20422bc21ed9SDavid Malone 	int i;
20432bc21ed9SDavid Malone 	int *fdp;
20442609222aSPawel Jakub Dawidek 	struct filedesc *fdesc = td->td_proc->p_fd;
2045ea31808cSMateusz Guzik 	struct filedescent **fdep;
20462bc21ed9SDavid Malone 	void *data;
20472bc21ed9SDavid Malone 	socklen_t clen = control->m_len, datalen;
20482bc21ed9SDavid Malone 	int error, newfds;
20492bc21ed9SDavid Malone 	u_int newlen;
20502bc21ed9SDavid Malone 
20513dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
20524c5bc1caSRobert Watson 
20532bc21ed9SDavid Malone 	error = 0;
20542bc21ed9SDavid Malone 	if (controlp != NULL) /* controlp == NULL => free control messages */
20552bc21ed9SDavid Malone 		*controlp = NULL;
20562bc21ed9SDavid Malone 	while (cm != NULL) {
20572bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
20582bc21ed9SDavid Malone 			error = EINVAL;
20592bc21ed9SDavid Malone 			break;
20602bc21ed9SDavid Malone 		}
20612bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
20622bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
20632bc21ed9SDavid Malone 		if (cm->cmsg_level == SOL_SOCKET
20642bc21ed9SDavid Malone 		    && cm->cmsg_type == SCM_RIGHTS) {
20652609222aSPawel Jakub Dawidek 			newfds = datalen / sizeof(*fdep);
206682e825c4SGleb Smirnoff 			if (newfds == 0)
206782e825c4SGleb Smirnoff 				goto next;
20682609222aSPawel Jakub Dawidek 			fdep = data;
20692bc21ed9SDavid Malone 
2070e2f9a08bSOlivier Houchard 			/* If we're not outputting the descriptors free them. */
20712bc21ed9SDavid Malone 			if (error || controlp == NULL) {
20722609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20732bc21ed9SDavid Malone 				goto next;
20742bc21ed9SDavid Malone 			}
20752609222aSPawel Jakub Dawidek 			FILEDESC_XLOCK(fdesc);
207660a5ef26SRobert Watson 
2077ed5b7817SJulian Elischer 			/*
20781c381b19SRobert Watson 			 * Now change each pointer to an fd in the global
20791c381b19SRobert Watson 			 * table to an integer that is the index to the local
20801c381b19SRobert Watson 			 * fd table entry that we set up to point to the
20811c381b19SRobert Watson 			 * global one we are transferring.
2082ed5b7817SJulian Elischer 			 */
20832bc21ed9SDavid Malone 			newlen = newfds * sizeof(int);
20842bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
20852bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
20862bc21ed9SDavid Malone 			if (*controlp == NULL) {
20872609222aSPawel Jakub Dawidek 				FILEDESC_XUNLOCK(fdesc);
20882bc21ed9SDavid Malone 				error = E2BIG;
20892609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20902bc21ed9SDavid Malone 				goto next;
20912bc21ed9SDavid Malone 			}
20922bc21ed9SDavid Malone 
20932bc21ed9SDavid Malone 			fdp = (int *)
20942bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2095db8f33fdSMateusz Guzik 			if (fdallocn(td, 0, fdp, newfds) != 0) {
20963331a33aSMateusz Guzik 				FILEDESC_XUNLOCK(fdesc);
2097db8f33fdSMateusz Guzik 				error = EMSGSIZE;
2098db8f33fdSMateusz Guzik 				unp_freerights(fdep, newfds);
2099db8f33fdSMateusz Guzik 				m_freem(*controlp);
2100db8f33fdSMateusz Guzik 				*controlp = NULL;
2101db8f33fdSMateusz Guzik 				goto next;
2102db8f33fdSMateusz Guzik 			}
21038cb539f1SPawel Jakub Dawidek 			for (i = 0; i < newfds; i++, fdp++) {
2104ea31808cSMateusz Guzik 				_finstall(fdesc, fdep[i]->fde_file, *fdp,
2105ea31808cSMateusz Guzik 				    (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
2106ea31808cSMateusz Guzik 				    &fdep[i]->fde_caps);
2107ea31808cSMateusz Guzik 				unp_externalize_fp(fdep[i]->fde_file);
2108df8bae1dSRodney W. Grimes 			}
2109c7902fbeSMark Johnston 
2110c7902fbeSMark Johnston 			/*
2111c7902fbeSMark Johnston 			 * The new type indicates that the mbuf data refers to
2112c7902fbeSMark Johnston 			 * kernel resources that may need to be released before
2113c7902fbeSMark Johnston 			 * the mbuf is freed.
2114c7902fbeSMark Johnston 			 */
2115c7902fbeSMark Johnston 			m_chtype(*controlp, MT_EXTCONTROL);
21162609222aSPawel Jakub Dawidek 			FILEDESC_XUNLOCK(fdesc);
21178cb539f1SPawel Jakub Dawidek 			free(fdep[0], M_FILECAPS);
21181c381b19SRobert Watson 		} else {
21191c381b19SRobert Watson 			/* We can just copy anything else across. */
21202bc21ed9SDavid Malone 			if (error || controlp == NULL)
21212bc21ed9SDavid Malone 				goto next;
21222bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, datalen,
21232bc21ed9SDavid Malone 			    cm->cmsg_type, cm->cmsg_level);
21242bc21ed9SDavid Malone 			if (*controlp == NULL) {
21252bc21ed9SDavid Malone 				error = ENOBUFS;
21262bc21ed9SDavid Malone 				goto next;
21272bc21ed9SDavid Malone 			}
21282bc21ed9SDavid Malone 			bcopy(data,
21292bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
21302bc21ed9SDavid Malone 			    datalen);
21312bc21ed9SDavid Malone 		}
21322bc21ed9SDavid Malone 		controlp = &(*controlp)->m_next;
21332bc21ed9SDavid Malone 
21342bc21ed9SDavid Malone next:
21352bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
21362bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
21372bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
21382bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
21398692c025SYoshinobu Inoue 		} else {
21402bc21ed9SDavid Malone 			clen = 0;
21412bc21ed9SDavid Malone 			cm = NULL;
21428692c025SYoshinobu Inoue 		}
21438692c025SYoshinobu Inoue 	}
21448692c025SYoshinobu Inoue 
21452bc21ed9SDavid Malone 	m_freem(control);
21462bc21ed9SDavid Malone 	return (error);
2147df8bae1dSRodney W. Grimes }
2148df8bae1dSRodney W. Grimes 
21494f590175SPaul Saab static void
21504f590175SPaul Saab unp_zone_change(void *tag)
21514f590175SPaul Saab {
21524f590175SPaul Saab 
21534f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21544f590175SPaul Saab }
21554f590175SPaul Saab 
21565362170dSMark Johnston #ifdef INVARIANTS
21575362170dSMark Johnston static void
21585362170dSMark Johnston unp_zdtor(void *mem, int size __unused, void *arg __unused)
21595362170dSMark Johnston {
21605362170dSMark Johnston 	struct unpcb *unp;
21615362170dSMark Johnston 
21625362170dSMark Johnston 	unp = mem;
21635362170dSMark Johnston 
21645362170dSMark Johnston 	KASSERT(LIST_EMPTY(&unp->unp_refs),
21655362170dSMark Johnston 	    ("%s: unpcb %p has lingering refs", __func__, unp));
21665362170dSMark Johnston 	KASSERT(unp->unp_socket == NULL,
21675362170dSMark Johnston 	    ("%s: unpcb %p has socket backpointer", __func__, unp));
21685362170dSMark Johnston 	KASSERT(unp->unp_vnode == NULL,
21695362170dSMark Johnston 	    ("%s: unpcb %p has vnode references", __func__, unp));
21705362170dSMark Johnston 	KASSERT(unp->unp_conn == NULL,
21715362170dSMark Johnston 	    ("%s: unpcb %p is still connected", __func__, unp));
21725362170dSMark Johnston 	KASSERT(unp->unp_addr == NULL,
21735362170dSMark Johnston 	    ("%s: unpcb %p has leaked addr", __func__, unp));
21745362170dSMark Johnston }
21755362170dSMark Johnston #endif
21765362170dSMark Johnston 
21770b36cd25SRobert Watson static void
217898271db4SGarrett Wollman unp_init(void)
217998271db4SGarrett Wollman {
21805362170dSMark Johnston 	uma_dtor dtor;
21811c381b19SRobert Watson 
218221ca7b57SMarko Zec #ifdef VIMAGE
218321ca7b57SMarko Zec 	if (!IS_DEFAULT_VNET(curvnet))
218421ca7b57SMarko Zec 		return;
218521ca7b57SMarko Zec #endif
21865362170dSMark Johnston 
21875362170dSMark Johnston #ifdef INVARIANTS
21885362170dSMark Johnston 	dtor = unp_zdtor;
21895362170dSMark Johnston #else
21905362170dSMark Johnston 	dtor = NULL;
21915362170dSMark Johnston #endif
21925362170dSMark Johnston 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
219375a67bf3SMatt Macy 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
21944f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21956e0b6746SPawel Jakub Dawidek 	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
21964f590175SPaul Saab 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
21974f590175SPaul Saab 	    NULL, EVENTHANDLER_PRI_ANY);
219898271db4SGarrett Wollman 	LIST_INIT(&unp_dhead);
219998271db4SGarrett Wollman 	LIST_INIT(&unp_shead);
220084d61770SRobert Watson 	LIST_INIT(&unp_sphead);
22010cb64678SKonstantin Belousov 	SLIST_INIT(&unp_defers);
2202daee0f0bSKonstantin Belousov 	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
22030cb64678SKonstantin Belousov 	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
22043dab55bcSRobert Watson 	UNP_LINK_LOCK_INIT();
22050cb64678SKonstantin Belousov 	UNP_DEFERRED_LOCK_INIT();
220698271db4SGarrett Wollman }
220798271db4SGarrett Wollman 
220847c3450eSKonstantin Belousov static void
220947c3450eSKonstantin Belousov unp_internalize_cleanup_rights(struct mbuf *control)
221047c3450eSKonstantin Belousov {
221147c3450eSKonstantin Belousov 	struct cmsghdr *cp;
221247c3450eSKonstantin Belousov 	struct mbuf *m;
221347c3450eSKonstantin Belousov 	void *data;
221447c3450eSKonstantin Belousov 	socklen_t datalen;
221547c3450eSKonstantin Belousov 
221647c3450eSKonstantin Belousov 	for (m = control; m != NULL; m = m->m_next) {
221747c3450eSKonstantin Belousov 		cp = mtod(m, struct cmsghdr *);
221847c3450eSKonstantin Belousov 		if (cp->cmsg_level != SOL_SOCKET ||
221947c3450eSKonstantin Belousov 		    cp->cmsg_type != SCM_RIGHTS)
222047c3450eSKonstantin Belousov 			continue;
222147c3450eSKonstantin Belousov 		data = CMSG_DATA(cp);
222247c3450eSKonstantin Belousov 		datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
222347c3450eSKonstantin Belousov 		unp_freerights(data, datalen / sizeof(struct filedesc *));
222447c3450eSKonstantin Belousov 	}
222547c3450eSKonstantin Belousov }
222647c3450eSKonstantin Belousov 
2227f708ef1bSPoul-Henning Kamp static int
2228892af6b9SRobert Watson unp_internalize(struct mbuf **controlp, struct thread *td)
2229df8bae1dSRodney W. Grimes {
223047c3450eSKonstantin Belousov 	struct mbuf *control, **initial_controlp;
223147c3450eSKonstantin Belousov 	struct proc *p;
223247c3450eSKonstantin Belousov 	struct filedesc *fdesc;
2233ab15d803SSergey Kandaurov 	struct bintime *bt;
223447c3450eSKonstantin Belousov 	struct cmsghdr *cm;
22352bc21ed9SDavid Malone 	struct cmsgcred *cmcred;
22368cb539f1SPawel Jakub Dawidek 	struct filedescent *fde, **fdep, *fdev;
22372bc21ed9SDavid Malone 	struct file *fp;
22382bc21ed9SDavid Malone 	struct timeval *tv;
2239339efd75SMaxim Sobolev 	struct timespec *ts;
22402bc21ed9SDavid Malone 	void *data;
224147c3450eSKonstantin Belousov 	socklen_t clen, datalen;
2242f1cf2b9dSKonstantin Belousov 	int i, j, error, *fdp, oldfds;
22438692c025SYoshinobu Inoue 	u_int newlen;
2244df8bae1dSRodney W. Grimes 
22453dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
22464c5bc1caSRobert Watson 
224747c3450eSKonstantin Belousov 	p = td->td_proc;
224847c3450eSKonstantin Belousov 	fdesc = p->p_fd;
22492bc21ed9SDavid Malone 	error = 0;
225047c3450eSKonstantin Belousov 	control = *controlp;
225147c3450eSKonstantin Belousov 	clen = control->m_len;
22522bc21ed9SDavid Malone 	*controlp = NULL;
225347c3450eSKonstantin Belousov 	initial_controlp = controlp;
225447c3450eSKonstantin Belousov 	for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
22552bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2256de966666SMateusz Guzik 		    || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
22572bc21ed9SDavid Malone 			error = EINVAL;
22582bc21ed9SDavid Malone 			goto out;
22592bc21ed9SDavid Malone 		}
22602bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
22612bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
22622bc21ed9SDavid Malone 
22632bc21ed9SDavid Malone 		switch (cm->cmsg_type) {
22640b788fa1SBill Paul 		/*
22650b788fa1SBill Paul 		 * Fill in credential information.
22660b788fa1SBill Paul 		 */
22672bc21ed9SDavid Malone 		case SCM_CREDS:
22682bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
22692bc21ed9SDavid Malone 			    SCM_CREDS, SOL_SOCKET);
22702bc21ed9SDavid Malone 			if (*controlp == NULL) {
22712bc21ed9SDavid Malone 				error = ENOBUFS;
22722bc21ed9SDavid Malone 				goto out;
22732bc21ed9SDavid Malone 			}
22742bc21ed9SDavid Malone 			cmcred = (struct cmsgcred *)
22752bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
22760b788fa1SBill Paul 			cmcred->cmcred_pid = p->p_pid;
2277a854ed98SJohn Baldwin 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2278a854ed98SJohn Baldwin 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2279a854ed98SJohn Baldwin 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
2280a854ed98SJohn Baldwin 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
22810b788fa1SBill Paul 			    CMGROUP_MAX);
22820b788fa1SBill Paul 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
22832bc21ed9SDavid Malone 				cmcred->cmcred_groups[i] =
2284a854ed98SJohn Baldwin 				    td->td_ucred->cr_groups[i];
22852bc21ed9SDavid Malone 			break;
22860b788fa1SBill Paul 
22872bc21ed9SDavid Malone 		case SCM_RIGHTS:
22882bc21ed9SDavid Malone 			oldfds = datalen / sizeof (int);
228982e825c4SGleb Smirnoff 			if (oldfds == 0)
229082e825c4SGleb Smirnoff 				break;
2291ed5b7817SJulian Elischer 			/*
22921c381b19SRobert Watson 			 * Check that all the FDs passed in refer to legal
22931c381b19SRobert Watson 			 * files.  If not, reject the entire operation.
2294ed5b7817SJulian Elischer 			 */
22952bc21ed9SDavid Malone 			fdp = data;
22962609222aSPawel Jakub Dawidek 			FILEDESC_SLOCK(fdesc);
22976a1cf96bSMateusz Guzik 			for (i = 0; i < oldfds; i++, fdp++) {
22986a1cf96bSMateusz Guzik 				fp = fget_locked(fdesc, *fdp);
22996a1cf96bSMateusz Guzik 				if (fp == NULL) {
23002609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
23012bc21ed9SDavid Malone 					error = EBADF;
23022bc21ed9SDavid Malone 					goto out;
23032bc21ed9SDavid Malone 				}
2304e7d6662fSAlfred Perlstein 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
23052609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
2306e7d6662fSAlfred Perlstein 					error = EOPNOTSUPP;
2307e7d6662fSAlfred Perlstein 					goto out;
2308e7d6662fSAlfred Perlstein 				}
2309df8bae1dSRodney W. Grimes 			}
23105e3f7694SRobert Watson 
2311ed5b7817SJulian Elischer 			/*
23120b36cd25SRobert Watson 			 * Now replace the integer FDs with pointers to the
23132609222aSPawel Jakub Dawidek 			 * file structure and capability rights.
2314ed5b7817SJulian Elischer 			 */
23158cb539f1SPawel Jakub Dawidek 			newlen = oldfds * sizeof(fdep[0]);
23162bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
23172bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
23182bc21ed9SDavid Malone 			if (*controlp == NULL) {
23192609222aSPawel Jakub Dawidek 				FILEDESC_SUNLOCK(fdesc);
23202bc21ed9SDavid Malone 				error = E2BIG;
23212bc21ed9SDavid Malone 				goto out;
23228692c025SYoshinobu Inoue 			}
23232bc21ed9SDavid Malone 			fdp = data;
2324f1cf2b9dSKonstantin Belousov 			for (i = 0; i < oldfds; i++, fdp++) {
2325f1cf2b9dSKonstantin Belousov 				if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2326f1cf2b9dSKonstantin Belousov 					fdp = data;
2327f1cf2b9dSKonstantin Belousov 					for (j = 0; j < i; j++, fdp++) {
2328f1cf2b9dSKonstantin Belousov 						fdrop(fdesc->fd_ofiles[*fdp].
2329f1cf2b9dSKonstantin Belousov 						    fde_file, td);
2330f1cf2b9dSKonstantin Belousov 					}
2331f1cf2b9dSKonstantin Belousov 					FILEDESC_SUNLOCK(fdesc);
2332f1cf2b9dSKonstantin Belousov 					error = EBADF;
2333f1cf2b9dSKonstantin Belousov 					goto out;
2334f1cf2b9dSKonstantin Belousov 				}
2335f1cf2b9dSKonstantin Belousov 			}
2336f1cf2b9dSKonstantin Belousov 			fdp = data;
23378cb539f1SPawel Jakub Dawidek 			fdep = (struct filedescent **)
23382bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23398cb539f1SPawel Jakub Dawidek 			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
23408cb539f1SPawel Jakub Dawidek 			    M_WAITOK);
23418cb539f1SPawel Jakub Dawidek 			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
23422609222aSPawel Jakub Dawidek 				fde = &fdesc->fd_ofiles[*fdp];
23438cb539f1SPawel Jakub Dawidek 				fdep[i] = fdev;
23448cb539f1SPawel Jakub Dawidek 				fdep[i]->fde_file = fde->fde_file;
23458cb539f1SPawel Jakub Dawidek 				filecaps_copy(&fde->fde_caps,
2346d7832811SMateusz Guzik 				    &fdep[i]->fde_caps, true);
23478cb539f1SPawel Jakub Dawidek 				unp_internalize_fp(fdep[i]->fde_file);
2348df8bae1dSRodney W. Grimes 			}
23492609222aSPawel Jakub Dawidek 			FILEDESC_SUNLOCK(fdesc);
23502bc21ed9SDavid Malone 			break;
23512bc21ed9SDavid Malone 
23522bc21ed9SDavid Malone 		case SCM_TIMESTAMP:
23532bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
23542bc21ed9SDavid Malone 			    SCM_TIMESTAMP, SOL_SOCKET);
23552bc21ed9SDavid Malone 			if (*controlp == NULL) {
23562bc21ed9SDavid Malone 				error = ENOBUFS;
23572bc21ed9SDavid Malone 				goto out;
23588692c025SYoshinobu Inoue 			}
23592bc21ed9SDavid Malone 			tv = (struct timeval *)
23602bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23612bc21ed9SDavid Malone 			microtime(tv);
23622bc21ed9SDavid Malone 			break;
23632bc21ed9SDavid Malone 
2364ab15d803SSergey Kandaurov 		case SCM_BINTIME:
2365ab15d803SSergey Kandaurov 			*controlp = sbcreatecontrol(NULL, sizeof(*bt),
2366ab15d803SSergey Kandaurov 			    SCM_BINTIME, SOL_SOCKET);
2367ab15d803SSergey Kandaurov 			if (*controlp == NULL) {
2368ab15d803SSergey Kandaurov 				error = ENOBUFS;
2369ab15d803SSergey Kandaurov 				goto out;
2370ab15d803SSergey Kandaurov 			}
2371ab15d803SSergey Kandaurov 			bt = (struct bintime *)
2372ab15d803SSergey Kandaurov 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2373ab15d803SSergey Kandaurov 			bintime(bt);
2374ab15d803SSergey Kandaurov 			break;
2375ab15d803SSergey Kandaurov 
2376339efd75SMaxim Sobolev 		case SCM_REALTIME:
2377339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2378339efd75SMaxim Sobolev 			    SCM_REALTIME, SOL_SOCKET);
2379339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2380339efd75SMaxim Sobolev 				error = ENOBUFS;
2381339efd75SMaxim Sobolev 				goto out;
2382339efd75SMaxim Sobolev 			}
2383339efd75SMaxim Sobolev 			ts = (struct timespec *)
2384339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2385339efd75SMaxim Sobolev 			nanotime(ts);
2386339efd75SMaxim Sobolev 			break;
2387339efd75SMaxim Sobolev 
2388339efd75SMaxim Sobolev 		case SCM_MONOTONIC:
2389339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2390339efd75SMaxim Sobolev 			    SCM_MONOTONIC, SOL_SOCKET);
2391339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2392339efd75SMaxim Sobolev 				error = ENOBUFS;
2393339efd75SMaxim Sobolev 				goto out;
2394339efd75SMaxim Sobolev 			}
2395339efd75SMaxim Sobolev 			ts = (struct timespec *)
2396339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2397339efd75SMaxim Sobolev 			nanouptime(ts);
2398339efd75SMaxim Sobolev 			break;
2399339efd75SMaxim Sobolev 
24002bc21ed9SDavid Malone 		default:
24012bc21ed9SDavid Malone 			error = EINVAL;
24022bc21ed9SDavid Malone 			goto out;
24032bc21ed9SDavid Malone 		}
24042bc21ed9SDavid Malone 
24054013d726SMark Johnston 		if (*controlp != NULL)
24062bc21ed9SDavid Malone 			controlp = &(*controlp)->m_next;
24072bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
24082bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
24092bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
24102bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
24112bc21ed9SDavid Malone 		} else {
24122bc21ed9SDavid Malone 			clen = 0;
24132bc21ed9SDavid Malone 			cm = NULL;
24142bc21ed9SDavid Malone 		}
24152bc21ed9SDavid Malone 	}
24162bc21ed9SDavid Malone 
24172bc21ed9SDavid Malone out:
241847c3450eSKonstantin Belousov 	if (error != 0 && initial_controlp != NULL)
241947c3450eSKonstantin Belousov 		unp_internalize_cleanup_rights(*initial_controlp);
24202bc21ed9SDavid Malone 	m_freem(control);
24212bc21ed9SDavid Malone 	return (error);
2422df8bae1dSRodney W. Grimes }
2423df8bae1dSRodney W. Grimes 
24245b950deaSRobert Watson static struct mbuf *
24256a2989fdSMatthew N. Dodd unp_addsockcred(struct thread *td, struct mbuf *control)
24266a2989fdSMatthew N. Dodd {
242770df31f4SMaxim Konovalov 	struct mbuf *m, *n, *n_prev;
24286a2989fdSMatthew N. Dodd 	struct sockcred *sc;
242970df31f4SMaxim Konovalov 	const struct cmsghdr *cm;
24306a2989fdSMatthew N. Dodd 	int ngroups;
24316a2989fdSMatthew N. Dodd 	int i;
24326a2989fdSMatthew N. Dodd 
24336a2989fdSMatthew N. Dodd 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
24346a2989fdSMatthew N. Dodd 	m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
24356a2989fdSMatthew N. Dodd 	if (m == NULL)
24366a2989fdSMatthew N. Dodd 		return (control);
24376a2989fdSMatthew N. Dodd 
24386a2989fdSMatthew N. Dodd 	sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
24396a2989fdSMatthew N. Dodd 	sc->sc_uid = td->td_ucred->cr_ruid;
24406a2989fdSMatthew N. Dodd 	sc->sc_euid = td->td_ucred->cr_uid;
24416a2989fdSMatthew N. Dodd 	sc->sc_gid = td->td_ucred->cr_rgid;
24426a2989fdSMatthew N. Dodd 	sc->sc_egid = td->td_ucred->cr_gid;
24436a2989fdSMatthew N. Dodd 	sc->sc_ngroups = ngroups;
24446a2989fdSMatthew N. Dodd 	for (i = 0; i < sc->sc_ngroups; i++)
24456a2989fdSMatthew N. Dodd 		sc->sc_groups[i] = td->td_ucred->cr_groups[i];
24466a2989fdSMatthew N. Dodd 
24476a2989fdSMatthew N. Dodd 	/*
24481c381b19SRobert Watson 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
24491c381b19SRobert Watson 	 * created SCM_CREDS control message (struct sockcred) has another
24501c381b19SRobert Watson 	 * format.
24516a2989fdSMatthew N. Dodd 	 */
245270df31f4SMaxim Konovalov 	if (control != NULL)
245370df31f4SMaxim Konovalov 		for (n = control, n_prev = NULL; n != NULL;) {
245470df31f4SMaxim Konovalov 			cm = mtod(n, struct cmsghdr *);
245570df31f4SMaxim Konovalov     			if (cm->cmsg_level == SOL_SOCKET &&
245670df31f4SMaxim Konovalov 			    cm->cmsg_type == SCM_CREDS) {
245770df31f4SMaxim Konovalov     				if (n_prev == NULL)
245870df31f4SMaxim Konovalov 					control = n->m_next;
245970df31f4SMaxim Konovalov 				else
246070df31f4SMaxim Konovalov 					n_prev->m_next = n->m_next;
246170df31f4SMaxim Konovalov 				n = m_free(n);
246270df31f4SMaxim Konovalov 			} else {
246370df31f4SMaxim Konovalov 				n_prev = n;
246470df31f4SMaxim Konovalov 				n = n->m_next;
246570df31f4SMaxim Konovalov 			}
246670df31f4SMaxim Konovalov 		}
24676a2989fdSMatthew N. Dodd 
246870df31f4SMaxim Konovalov 	/* Prepend it to the head. */
246970df31f4SMaxim Konovalov 	m->m_next = control;
247070df31f4SMaxim Konovalov 	return (m);
24716a2989fdSMatthew N. Dodd }
24726a2989fdSMatthew N. Dodd 
2473397c19d1SJeff Roberson static struct unpcb *
2474397c19d1SJeff Roberson fptounp(struct file *fp)
2475397c19d1SJeff Roberson {
2476397c19d1SJeff Roberson 	struct socket *so;
2477397c19d1SJeff Roberson 
2478397c19d1SJeff Roberson 	if (fp->f_type != DTYPE_SOCKET)
2479397c19d1SJeff Roberson 		return (NULL);
2480397c19d1SJeff Roberson 	if ((so = fp->f_data) == NULL)
2481397c19d1SJeff Roberson 		return (NULL);
2482397c19d1SJeff Roberson 	if (so->so_proto->pr_domain != &localdomain)
2483397c19d1SJeff Roberson 		return (NULL);
2484397c19d1SJeff Roberson 	return sotounpcb(so);
2485397c19d1SJeff Roberson }
2486397c19d1SJeff Roberson 
2487397c19d1SJeff Roberson static void
2488397c19d1SJeff Roberson unp_discard(struct file *fp)
2489397c19d1SJeff Roberson {
24900cb64678SKonstantin Belousov 	struct unp_defer *dr;
2491397c19d1SJeff Roberson 
24920cb64678SKonstantin Belousov 	if (unp_externalize_fp(fp)) {
24930cb64678SKonstantin Belousov 		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
24940cb64678SKonstantin Belousov 		dr->ud_fp = fp;
24950cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
24960cb64678SKonstantin Belousov 		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
24970cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
24980cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, 1);
24990cb64678SKonstantin Belousov 		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
25000cb64678SKonstantin Belousov 	} else
2501397c19d1SJeff Roberson 		(void) closef(fp, (struct thread *)NULL);
2502397c19d1SJeff Roberson }
2503397c19d1SJeff Roberson 
2504397c19d1SJeff Roberson static void
25050cb64678SKonstantin Belousov unp_process_defers(void *arg __unused, int pending)
25060cb64678SKonstantin Belousov {
25070cb64678SKonstantin Belousov 	struct unp_defer *dr;
25080cb64678SKonstantin Belousov 	SLIST_HEAD(, unp_defer) drl;
25090cb64678SKonstantin Belousov 	int count;
25100cb64678SKonstantin Belousov 
25110cb64678SKonstantin Belousov 	SLIST_INIT(&drl);
25120cb64678SKonstantin Belousov 	for (;;) {
25130cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
25140cb64678SKonstantin Belousov 		if (SLIST_FIRST(&unp_defers) == NULL) {
25150cb64678SKonstantin Belousov 			UNP_DEFERRED_UNLOCK();
25160cb64678SKonstantin Belousov 			break;
25170cb64678SKonstantin Belousov 		}
25180cb64678SKonstantin Belousov 		SLIST_SWAP(&unp_defers, &drl, unp_defer);
25190cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
25200cb64678SKonstantin Belousov 		count = 0;
25210cb64678SKonstantin Belousov 		while ((dr = SLIST_FIRST(&drl)) != NULL) {
25220cb64678SKonstantin Belousov 			SLIST_REMOVE_HEAD(&drl, ud_link);
25230cb64678SKonstantin Belousov 			closef(dr->ud_fp, NULL);
25240cb64678SKonstantin Belousov 			free(dr, M_TEMP);
25250cb64678SKonstantin Belousov 			count++;
25260cb64678SKonstantin Belousov 		}
25270cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, -count);
25280cb64678SKonstantin Belousov 	}
25290cb64678SKonstantin Belousov }
25300cb64678SKonstantin Belousov 
25310cb64678SKonstantin Belousov static void
2532397c19d1SJeff Roberson unp_internalize_fp(struct file *fp)
2533397c19d1SJeff Roberson {
2534397c19d1SJeff Roberson 	struct unpcb *unp;
2535397c19d1SJeff Roberson 
25363dab55bcSRobert Watson 	UNP_LINK_WLOCK();
2537397c19d1SJeff Roberson 	if ((unp = fptounp(fp)) != NULL) {
2538397c19d1SJeff Roberson 		unp->unp_file = fp;
2539397c19d1SJeff Roberson 		unp->unp_msgcount++;
2540397c19d1SJeff Roberson 	}
2541397c19d1SJeff Roberson 	unp_rights++;
25423dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
2543397c19d1SJeff Roberson }
2544397c19d1SJeff Roberson 
25450cb64678SKonstantin Belousov static int
2546397c19d1SJeff Roberson unp_externalize_fp(struct file *fp)
2547397c19d1SJeff Roberson {
2548397c19d1SJeff Roberson 	struct unpcb *unp;
25490cb64678SKonstantin Belousov 	int ret;
2550397c19d1SJeff Roberson 
25513dab55bcSRobert Watson 	UNP_LINK_WLOCK();
25520cb64678SKonstantin Belousov 	if ((unp = fptounp(fp)) != NULL) {
2553397c19d1SJeff Roberson 		unp->unp_msgcount--;
25540cb64678SKonstantin Belousov 		ret = 1;
25550cb64678SKonstantin Belousov 	} else
25560cb64678SKonstantin Belousov 		ret = 0;
2557397c19d1SJeff Roberson 	unp_rights--;
25583dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
25590cb64678SKonstantin Belousov 	return (ret);
2560397c19d1SJeff Roberson }
2561397c19d1SJeff Roberson 
2562161a0c7cSRobert Watson /*
2563a0ec558aSRobert Watson  * unp_defer indicates whether additional work has been defered for a future
2564a0ec558aSRobert Watson  * pass through unp_gc().  It is thread local and does not require explicit
2565a0ec558aSRobert Watson  * synchronization.
2566161a0c7cSRobert Watson  */
2567397c19d1SJeff Roberson static int	unp_marked;
2568a0ec558aSRobert Watson 
2569397c19d1SJeff Roberson static void
2570a9aa06f7SJason A. Harmening unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2571397c19d1SJeff Roberson {
2572397c19d1SJeff Roberson 	struct unpcb *unp;
2573be26ba7cSPawel Jakub Dawidek 	struct file *fp;
2574be26ba7cSPawel Jakub Dawidek 	int i;
2575397c19d1SJeff Roberson 
2576a9aa06f7SJason A. Harmening 	/*
2577a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2578a9aa06f7SJason A. Harmening 	 */
2579a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2580a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2581a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2582a9aa06f7SJason A. Harmening 
2583be26ba7cSPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
2584be26ba7cSPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
25856f552cb0SJeff Roberson 		if ((unp = fptounp(fp)) == NULL)
2586be26ba7cSPawel Jakub Dawidek 			continue;
2587a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2588be26ba7cSPawel Jakub Dawidek 			continue;
2589a9aa06f7SJason A. Harmening 		unp->unp_gcrefs--;
2590a9aa06f7SJason A. Harmening 	}
2591a9aa06f7SJason A. Harmening }
2592a9aa06f7SJason A. Harmening 
2593a9aa06f7SJason A. Harmening static void
2594a9aa06f7SJason A. Harmening unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2595a9aa06f7SJason A. Harmening {
2596a9aa06f7SJason A. Harmening 	struct unpcb *unp;
2597a9aa06f7SJason A. Harmening 	struct file *fp;
2598a9aa06f7SJason A. Harmening 	int i;
2599a9aa06f7SJason A. Harmening 
2600a9aa06f7SJason A. Harmening 	/*
2601a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2602a9aa06f7SJason A. Harmening 	 */
2603a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2604a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2605a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2606a9aa06f7SJason A. Harmening 
2607a9aa06f7SJason A. Harmening 	for (i = 0; i < fdcount; i++) {
2608a9aa06f7SJason A. Harmening 		fp = fdep[i]->fde_file;
2609a9aa06f7SJason A. Harmening 		if ((unp = fptounp(fp)) == NULL)
2610a9aa06f7SJason A. Harmening 			continue;
2611a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2612a9aa06f7SJason A. Harmening 			continue;
2613a9aa06f7SJason A. Harmening 		unp->unp_gcrefs++;
2614397c19d1SJeff Roberson 		unp_marked++;
2615397c19d1SJeff Roberson 	}
2616be26ba7cSPawel Jakub Dawidek }
2617397c19d1SJeff Roberson 
2618397c19d1SJeff Roberson static void
2619a9aa06f7SJason A. Harmening unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2620397c19d1SJeff Roberson {
2621779f106aSGleb Smirnoff 	struct socket *so, *soa;
262260a5ef26SRobert Watson 
2623397c19d1SJeff Roberson 	so = unp->unp_socket;
2624779f106aSGleb Smirnoff 	SOCK_LOCK(so);
2625779f106aSGleb Smirnoff 	if (SOLISTENING(so)) {
2626397c19d1SJeff Roberson 		/*
2627397c19d1SJeff Roberson 		 * Mark all sockets in our accept queue.
2628397c19d1SJeff Roberson 		 */
2629779f106aSGleb Smirnoff 		TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2630779f106aSGleb Smirnoff 			if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
26310c40f353SConrad Meyer 				continue;
2632397c19d1SJeff Roberson 			SOCKBUF_LOCK(&soa->so_rcv);
2633a9aa06f7SJason A. Harmening 			unp_scan(soa->so_rcv.sb_mb, op);
2634397c19d1SJeff Roberson 			SOCKBUF_UNLOCK(&soa->so_rcv);
2635397c19d1SJeff Roberson 		}
2636779f106aSGleb Smirnoff 	} else {
2637779f106aSGleb Smirnoff 		/*
2638779f106aSGleb Smirnoff 		 * Mark all sockets we reference with RIGHTS.
2639779f106aSGleb Smirnoff 		 */
2640779f106aSGleb Smirnoff 		if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2641779f106aSGleb Smirnoff 			SOCKBUF_LOCK(&so->so_rcv);
2642a9aa06f7SJason A. Harmening 			unp_scan(so->so_rcv.sb_mb, op);
2643779f106aSGleb Smirnoff 			SOCKBUF_UNLOCK(&so->so_rcv);
2644779f106aSGleb Smirnoff 		}
2645779f106aSGleb Smirnoff 	}
2646779f106aSGleb Smirnoff 	SOCK_UNLOCK(so);
2647397c19d1SJeff Roberson }
2648a0ec558aSRobert Watson 
2649a0ec558aSRobert Watson static int unp_recycled;
2650be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2651be6b1304STom Rhodes     "Number of unreachable sockets claimed by the garbage collector.");
2652df8bae1dSRodney W. Grimes 
2653397c19d1SJeff Roberson static int unp_taskcount;
2654be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2655be6b1304STom Rhodes     "Number of times the garbage collector has run.");
2656397c19d1SJeff Roberson 
2657a9aa06f7SJason A. Harmening SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
2658a9aa06f7SJason A. Harmening     "Number of active local sockets.");
2659a9aa06f7SJason A. Harmening 
2660f708ef1bSPoul-Henning Kamp static void
2661a0ec558aSRobert Watson unp_gc(__unused void *arg, int pending)
2662df8bae1dSRodney W. Grimes {
266384d61770SRobert Watson 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
266484d61770SRobert Watson 				    NULL };
2665397c19d1SJeff Roberson 	struct unp_head **head;
2666a9aa06f7SJason A. Harmening 	struct unp_head unp_deadhead;	/* List of potentially-dead sockets. */
2667f7780c61SKonstantin Belousov 	struct file *f, **unref;
2668a9aa06f7SJason A. Harmening 	struct unpcb *unp, *unptmp;
2669a9aa06f7SJason A. Harmening 	int i, total, unp_unreachable;
2670df8bae1dSRodney W. Grimes 
2671a9aa06f7SJason A. Harmening 	LIST_INIT(&unp_deadhead);
2672a0ec558aSRobert Watson 	unp_taskcount++;
2673779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
2674ed5b7817SJulian Elischer 	/*
2675a9aa06f7SJason A. Harmening 	 * First determine which sockets may be in cycles.
2676ed5b7817SJulian Elischer 	 */
2677a9aa06f7SJason A. Harmening 	unp_unreachable = 0;
2678a9aa06f7SJason A. Harmening 
2679397c19d1SJeff Roberson 	for (head = heads; *head != NULL; head++)
2680a9aa06f7SJason A. Harmening 		LIST_FOREACH(unp, *head, unp_link) {
2681a9aa06f7SJason A. Harmening 			KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2682a9aa06f7SJason A. Harmening 			    ("%s: unp %p has unexpected gc flags 0x%x",
2683a9aa06f7SJason A. Harmening 			    __func__, unp, (unsigned int)unp->unp_gcflag));
2684a9aa06f7SJason A. Harmening 
2685a9aa06f7SJason A. Harmening 			f = unp->unp_file;
268660a5ef26SRobert Watson 
2687397c19d1SJeff Roberson 			/*
2688a9aa06f7SJason A. Harmening 			 * Check for an unreachable socket potentially in a
2689a9aa06f7SJason A. Harmening 			 * cycle.  It must be in a queue as indicated by
2690a9aa06f7SJason A. Harmening 			 * msgcount, and this must equal the file reference
2691a9aa06f7SJason A. Harmening 			 * count.  Note that when msgcount is 0 the file is
2692a9aa06f7SJason A. Harmening 			 * NULL.
2693a9aa06f7SJason A. Harmening 			 */
2694a9aa06f7SJason A. Harmening 			if (f != NULL && unp->unp_msgcount != 0 &&
2695a9aa06f7SJason A. Harmening 			    f->f_count == unp->unp_msgcount) {
2696a9aa06f7SJason A. Harmening 				LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2697a9aa06f7SJason A. Harmening 				unp->unp_gcflag |= UNPGC_DEAD;
2698a9aa06f7SJason A. Harmening 				unp->unp_gcrefs = unp->unp_msgcount;
2699a9aa06f7SJason A. Harmening 				unp_unreachable++;
2700a9aa06f7SJason A. Harmening 			}
2701a9aa06f7SJason A. Harmening 		}
2702a9aa06f7SJason A. Harmening 
2703a9aa06f7SJason A. Harmening 	/*
2704a9aa06f7SJason A. Harmening 	 * Scan all sockets previously marked as potentially being in a cycle
2705a9aa06f7SJason A. Harmening 	 * and remove the references each socket holds on any UNPGC_DEAD
2706a9aa06f7SJason A. Harmening 	 * sockets in its queue.  After this step, all remaining references on
2707a9aa06f7SJason A. Harmening 	 * sockets marked UNPGC_DEAD should not be part of any cycle.
2708a9aa06f7SJason A. Harmening 	 */
2709a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead)
2710a9aa06f7SJason A. Harmening 		unp_gc_scan(unp, unp_remove_dead_ref);
2711a9aa06f7SJason A. Harmening 
2712a9aa06f7SJason A. Harmening 	/*
2713a9aa06f7SJason A. Harmening 	 * If a socket still has a non-negative refcount, it cannot be in a
2714a9aa06f7SJason A. Harmening 	 * cycle.  In this case increment refcount of all children iteratively.
2715397c19d1SJeff Roberson 	 * Stop the scan once we do a complete loop without discovering
2716397c19d1SJeff Roberson 	 * a new reachable socket.
2717397c19d1SJeff Roberson 	 */
2718df8bae1dSRodney W. Grimes 	do {
2719397c19d1SJeff Roberson 		unp_marked = 0;
2720a9aa06f7SJason A. Harmening 		LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
2721a9aa06f7SJason A. Harmening 			if (unp->unp_gcrefs > 0) {
2722a9aa06f7SJason A. Harmening 				unp->unp_gcflag &= ~UNPGC_DEAD;
2723a9aa06f7SJason A. Harmening 				LIST_REMOVE(unp, unp_dead);
2724a9aa06f7SJason A. Harmening 				KASSERT(unp_unreachable > 0,
2725a9aa06f7SJason A. Harmening 				    ("%s: unp_unreachable underflow.",
2726a9aa06f7SJason A. Harmening 				    __func__));
2727a9aa06f7SJason A. Harmening 				unp_unreachable--;
2728a9aa06f7SJason A. Harmening 				unp_gc_scan(unp, unp_restore_undead_ref);
2729a9aa06f7SJason A. Harmening 			}
2730397c19d1SJeff Roberson 	} while (unp_marked);
2731a9aa06f7SJason A. Harmening 
2732779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
2733a9aa06f7SJason A. Harmening 
2734397c19d1SJeff Roberson 	if (unp_unreachable == 0)
2735397c19d1SJeff Roberson 		return;
273660a5ef26SRobert Watson 
2737ed5b7817SJulian Elischer 	/*
2738a9aa06f7SJason A. Harmening 	 * Allocate space for a local array of dead unpcbs.
2739a9aa06f7SJason A. Harmening 	 * TODO: can this path be simplified by instead using the local
2740a9aa06f7SJason A. Harmening 	 * dead list at unp_deadhead, after taking out references
2741a9aa06f7SJason A. Harmening 	 * on the file object and/or unpcb and dropping the link lock?
2742ed5b7817SJulian Elischer 	 */
2743397c19d1SJeff Roberson 	unref = malloc(unp_unreachable * sizeof(struct file *),
2744397c19d1SJeff Roberson 	    M_TEMP, M_WAITOK);
274560a5ef26SRobert Watson 
2746ed5b7817SJulian Elischer 	/*
2747397c19d1SJeff Roberson 	 * Iterate looking for sockets which have been specifically marked
2748a9aa06f7SJason A. Harmening 	 * as unreachable and store them locally.
2749ed5b7817SJulian Elischer 	 */
2750f7780c61SKonstantin Belousov 	UNP_LINK_RLOCK();
2751a9aa06f7SJason A. Harmening 	total = 0;
2752a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
2753a9aa06f7SJason A. Harmening 		KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
2754a9aa06f7SJason A. Harmening 		    ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
2755a9aa06f7SJason A. Harmening 		unp->unp_gcflag &= ~UNPGC_DEAD;
2756f7780c61SKonstantin Belousov 		f = unp->unp_file;
2757f7780c61SKonstantin Belousov 		if (unp->unp_msgcount == 0 || f == NULL ||
2758f1cf2b9dSKonstantin Belousov 		    f->f_count != unp->unp_msgcount ||
2759f1cf2b9dSKonstantin Belousov 		    !fhold(f))
2760f7780c61SKonstantin Belousov 			continue;
2761f7780c61SKonstantin Belousov 		unref[total++] = f;
2762f7780c61SKonstantin Belousov 		KASSERT(total <= unp_unreachable,
2763a9aa06f7SJason A. Harmening 		    ("%s: incorrect unreachable count.", __func__));
2764397c19d1SJeff Roberson 	}
2765f7780c61SKonstantin Belousov 	UNP_LINK_RUNLOCK();
276660a5ef26SRobert Watson 
2767ed5b7817SJulian Elischer 	/*
2768397c19d1SJeff Roberson 	 * Now flush all sockets, free'ing rights.  This will free the
2769397c19d1SJeff Roberson 	 * struct files associated with these sockets but leave each socket
2770397c19d1SJeff Roberson 	 * with one remaining ref.
2771ed5b7817SJulian Elischer 	 */
27721fb51a12SBjoern A. Zeeb 	for (i = 0; i < total; i++) {
27731fb51a12SBjoern A. Zeeb 		struct socket *so;
27741fb51a12SBjoern A. Zeeb 
27751fb51a12SBjoern A. Zeeb 		so = unref[i]->f_data;
27761fb51a12SBjoern A. Zeeb 		CURVNET_SET(so->so_vnet);
27771fb51a12SBjoern A. Zeeb 		sorflush(so);
27781fb51a12SBjoern A. Zeeb 		CURVNET_RESTORE();
27791fb51a12SBjoern A. Zeeb 	}
278060a5ef26SRobert Watson 
2781ed5b7817SJulian Elischer 	/*
2782397c19d1SJeff Roberson 	 * And finally release the sockets so they can be reclaimed.
2783ed5b7817SJulian Elischer 	 */
2784f7780c61SKonstantin Belousov 	for (i = 0; i < total; i++)
2785397c19d1SJeff Roberson 		fdrop(unref[i], NULL);
2786f7780c61SKonstantin Belousov 	unp_recycled += total;
2787397c19d1SJeff Roberson 	free(unref, M_TEMP);
2788df8bae1dSRodney W. Grimes }
2789df8bae1dSRodney W. Grimes 
27900b36cd25SRobert Watson static void
279199ab95dbSMark Johnston unp_dispose_mbuf(struct mbuf *m)
2792df8bae1dSRodney W. Grimes {
2793996c772fSJohn Dyson 
2794df8bae1dSRodney W. Grimes 	if (m)
2795be26ba7cSPawel Jakub Dawidek 		unp_scan(m, unp_freerights);
2796df8bae1dSRodney W. Grimes }
2797df8bae1dSRodney W. Grimes 
27980c40f353SConrad Meyer /*
27990c40f353SConrad Meyer  * Synchronize against unp_gc, which can trip over data as we are freeing it.
28000c40f353SConrad Meyer  */
28010c40f353SConrad Meyer static void
280299ab95dbSMark Johnston unp_dispose(struct socket *so)
28030c40f353SConrad Meyer {
28040c40f353SConrad Meyer 	struct unpcb *unp;
28050c40f353SConrad Meyer 
28060c40f353SConrad Meyer 	unp = sotounpcb(so);
2807779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
28080c40f353SConrad Meyer 	unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2809779f106aSGleb Smirnoff 	UNP_LINK_WUNLOCK();
2810779f106aSGleb Smirnoff 	if (!SOLISTENING(so))
281199ab95dbSMark Johnston 		unp_dispose_mbuf(so->so_rcv.sb_mb);
28120c40f353SConrad Meyer }
28130c40f353SConrad Meyer 
2814f708ef1bSPoul-Henning Kamp static void
2815be26ba7cSPawel Jakub Dawidek unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2816df8bae1dSRodney W. Grimes {
28172bc21ed9SDavid Malone 	struct mbuf *m;
28182bc21ed9SDavid Malone 	struct cmsghdr *cm;
28192bc21ed9SDavid Malone 	void *data;
28202bc21ed9SDavid Malone 	socklen_t clen, datalen;
2821df8bae1dSRodney W. Grimes 
2822fc3fcacfSRobert Watson 	while (m0 != NULL) {
28232bc21ed9SDavid Malone 		for (m = m0; m; m = m->m_next) {
282412396bdcSDavid Malone 			if (m->m_type != MT_CONTROL)
2825df8bae1dSRodney W. Grimes 				continue;
28262bc21ed9SDavid Malone 
28272bc21ed9SDavid Malone 			cm = mtod(m, struct cmsghdr *);
28282bc21ed9SDavid Malone 			clen = m->m_len;
28292bc21ed9SDavid Malone 
28302bc21ed9SDavid Malone 			while (cm != NULL) {
28312bc21ed9SDavid Malone 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
28322bc21ed9SDavid Malone 					break;
28332bc21ed9SDavid Malone 
28342bc21ed9SDavid Malone 				data = CMSG_DATA(cm);
28352bc21ed9SDavid Malone 				datalen = (caddr_t)cm + cm->cmsg_len
28362bc21ed9SDavid Malone 				    - (caddr_t)data;
28372bc21ed9SDavid Malone 
28382bc21ed9SDavid Malone 				if (cm->cmsg_level == SOL_SOCKET &&
28392bc21ed9SDavid Malone 				    cm->cmsg_type == SCM_RIGHTS) {
2840be26ba7cSPawel Jakub Dawidek 					(*op)(data, datalen /
2841be26ba7cSPawel Jakub Dawidek 					    sizeof(struct filedescent *));
28422bc21ed9SDavid Malone 				}
28432bc21ed9SDavid Malone 
28442bc21ed9SDavid Malone 				if (CMSG_SPACE(datalen) < clen) {
28452bc21ed9SDavid Malone 					clen -= CMSG_SPACE(datalen);
28462bc21ed9SDavid Malone 					cm = (struct cmsghdr *)
28472bc21ed9SDavid Malone 					    ((caddr_t)cm + CMSG_SPACE(datalen));
28482bc21ed9SDavid Malone 				} else {
28492bc21ed9SDavid Malone 					clen = 0;
28502bc21ed9SDavid Malone 					cm = NULL;
28512bc21ed9SDavid Malone 				}
28522bc21ed9SDavid Malone 			}
2853df8bae1dSRodney W. Grimes 		}
2854c29a3321SKevin Lo 		m0 = m0->m_nextpkt;
2855df8bae1dSRodney W. Grimes 	}
2856df8bae1dSRodney W. Grimes }
2857df8bae1dSRodney W. Grimes 
2858662c901cSMikolaj Golub /*
2859662c901cSMikolaj Golub  * A helper function called by VFS before socket-type vnode reclamation.
2860662c901cSMikolaj Golub  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2861662c901cSMikolaj Golub  * use count.
2862662c901cSMikolaj Golub  */
2863662c901cSMikolaj Golub void
2864662c901cSMikolaj Golub vfs_unp_reclaim(struct vnode *vp)
2865662c901cSMikolaj Golub {
2866662c901cSMikolaj Golub 	struct unpcb *unp;
2867662c901cSMikolaj Golub 	int active;
286875a67bf3SMatt Macy 	struct mtx *vplock;
2869662c901cSMikolaj Golub 
2870662c901cSMikolaj Golub 	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2871662c901cSMikolaj Golub 	KASSERT(vp->v_type == VSOCK,
2872662c901cSMikolaj Golub 	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2873662c901cSMikolaj Golub 
2874662c901cSMikolaj Golub 	active = 0;
287575a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
287675a67bf3SMatt Macy 	mtx_lock(vplock);
28770c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp);
2878662c901cSMikolaj Golub 	if (unp == NULL)
2879662c901cSMikolaj Golub 		goto done;
2880662c901cSMikolaj Golub 	UNP_PCB_LOCK(unp);
2881c7e41c8bSMikolaj Golub 	if (unp->unp_vnode == vp) {
2882c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
2883662c901cSMikolaj Golub 		unp->unp_vnode = NULL;
2884662c901cSMikolaj Golub 		active = 1;
2885662c901cSMikolaj Golub 	}
2886662c901cSMikolaj Golub 	UNP_PCB_UNLOCK(unp);
2887662c901cSMikolaj Golub  done:
288875a67bf3SMatt Macy 	mtx_unlock(vplock);
2889662c901cSMikolaj Golub 	if (active)
2890662c901cSMikolaj Golub 		vunref(vp);
2891662c901cSMikolaj Golub }
2892662c901cSMikolaj Golub 
289303c96c31SRobert Watson #ifdef DDB
289403c96c31SRobert Watson static void
289503c96c31SRobert Watson db_print_indent(int indent)
289603c96c31SRobert Watson {
289703c96c31SRobert Watson 	int i;
289803c96c31SRobert Watson 
289903c96c31SRobert Watson 	for (i = 0; i < indent; i++)
290003c96c31SRobert Watson 		db_printf(" ");
290103c96c31SRobert Watson }
290203c96c31SRobert Watson 
290303c96c31SRobert Watson static void
290403c96c31SRobert Watson db_print_unpflags(int unp_flags)
290503c96c31SRobert Watson {
290603c96c31SRobert Watson 	int comma;
290703c96c31SRobert Watson 
290803c96c31SRobert Watson 	comma = 0;
290903c96c31SRobert Watson 	if (unp_flags & UNP_HAVEPC) {
291003c96c31SRobert Watson 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
291103c96c31SRobert Watson 		comma = 1;
291203c96c31SRobert Watson 	}
291303c96c31SRobert Watson 	if (unp_flags & UNP_WANTCRED) {
291403c96c31SRobert Watson 		db_printf("%sUNP_WANTCRED", comma ? ", " : "");
291503c96c31SRobert Watson 		comma = 1;
291603c96c31SRobert Watson 	}
291703c96c31SRobert Watson 	if (unp_flags & UNP_CONNWAIT) {
291803c96c31SRobert Watson 		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
291903c96c31SRobert Watson 		comma = 1;
292003c96c31SRobert Watson 	}
292103c96c31SRobert Watson 	if (unp_flags & UNP_CONNECTING) {
292203c96c31SRobert Watson 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
292303c96c31SRobert Watson 		comma = 1;
292403c96c31SRobert Watson 	}
292503c96c31SRobert Watson 	if (unp_flags & UNP_BINDING) {
292603c96c31SRobert Watson 		db_printf("%sUNP_BINDING", comma ? ", " : "");
292703c96c31SRobert Watson 		comma = 1;
292803c96c31SRobert Watson 	}
292903c96c31SRobert Watson }
293003c96c31SRobert Watson 
293103c96c31SRobert Watson static void
293203c96c31SRobert Watson db_print_xucred(int indent, struct xucred *xu)
293303c96c31SRobert Watson {
293403c96c31SRobert Watson 	int comma, i;
293503c96c31SRobert Watson 
293603c96c31SRobert Watson 	db_print_indent(indent);
2937c5afec6eSDmitry Chagin 	db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
2938c5afec6eSDmitry Chagin 	    xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
293903c96c31SRobert Watson 	db_print_indent(indent);
294003c96c31SRobert Watson 	db_printf("cr_groups: ");
294103c96c31SRobert Watson 	comma = 0;
294203c96c31SRobert Watson 	for (i = 0; i < xu->cr_ngroups; i++) {
294303c96c31SRobert Watson 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
294403c96c31SRobert Watson 		comma = 1;
294503c96c31SRobert Watson 	}
294603c96c31SRobert Watson 	db_printf("\n");
294703c96c31SRobert Watson }
294803c96c31SRobert Watson 
294903c96c31SRobert Watson static void
295003c96c31SRobert Watson db_print_unprefs(int indent, struct unp_head *uh)
295103c96c31SRobert Watson {
295203c96c31SRobert Watson 	struct unpcb *unp;
295303c96c31SRobert Watson 	int counter;
295403c96c31SRobert Watson 
295503c96c31SRobert Watson 	counter = 0;
295603c96c31SRobert Watson 	LIST_FOREACH(unp, uh, unp_reflink) {
295703c96c31SRobert Watson 		if (counter % 4 == 0)
295803c96c31SRobert Watson 			db_print_indent(indent);
295903c96c31SRobert Watson 		db_printf("%p  ", unp);
296003c96c31SRobert Watson 		if (counter % 4 == 3)
296103c96c31SRobert Watson 			db_printf("\n");
296203c96c31SRobert Watson 		counter++;
296303c96c31SRobert Watson 	}
296403c96c31SRobert Watson 	if (counter != 0 && counter % 4 != 0)
296503c96c31SRobert Watson 		db_printf("\n");
296603c96c31SRobert Watson }
296703c96c31SRobert Watson 
296803c96c31SRobert Watson DB_SHOW_COMMAND(unpcb, db_show_unpcb)
296903c96c31SRobert Watson {
297003c96c31SRobert Watson 	struct unpcb *unp;
297103c96c31SRobert Watson 
297203c96c31SRobert Watson         if (!have_addr) {
297303c96c31SRobert Watson                 db_printf("usage: show unpcb <addr>\n");
297403c96c31SRobert Watson                 return;
297503c96c31SRobert Watson         }
297603c96c31SRobert Watson         unp = (struct unpcb *)addr;
297703c96c31SRobert Watson 
297803c96c31SRobert Watson 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
297903c96c31SRobert Watson 	    unp->unp_vnode);
298003c96c31SRobert Watson 
2981fc8fdae0SMatthew D Fleming 	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
298203c96c31SRobert Watson 	    unp->unp_conn);
298303c96c31SRobert Watson 
298403c96c31SRobert Watson 	db_printf("unp_refs:\n");
298503c96c31SRobert Watson 	db_print_unprefs(2, &unp->unp_refs);
298603c96c31SRobert Watson 
298703c96c31SRobert Watson 	/* XXXRW: Would be nice to print the full address, if any. */
298803c96c31SRobert Watson 	db_printf("unp_addr: %p\n", unp->unp_addr);
298903c96c31SRobert Watson 
2990c2090e73SAlan Somers 	db_printf("unp_gencnt: %llu\n",
299103c96c31SRobert Watson 	    (unsigned long long)unp->unp_gencnt);
299203c96c31SRobert Watson 
299303c96c31SRobert Watson 	db_printf("unp_flags: %x (", unp->unp_flags);
299403c96c31SRobert Watson 	db_print_unpflags(unp->unp_flags);
299503c96c31SRobert Watson 	db_printf(")\n");
299603c96c31SRobert Watson 
299703c96c31SRobert Watson 	db_printf("unp_peercred:\n");
299803c96c31SRobert Watson 	db_print_xucred(2, &unp->unp_peercred);
299903c96c31SRobert Watson 
300003c96c31SRobert Watson 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
300103c96c31SRobert Watson }
300203c96c31SRobert Watson #endif
3003