xref: /freebsd/sys/kern/uipc_usrreq.c (revision ccdadf1a9bb64156e4a62bb6207c37b841467cb7)
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)
282*ccdadf1aSMark Johnston #define	UNP_PCB_LOCKPTR(unp)		(&(unp)->unp_mtx)
283e7c33e29SRobert Watson #define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
28475a67bf3SMatt Macy #define	UNP_PCB_TRYLOCK(unp)		mtx_trylock(&(unp)->unp_mtx)
285e7c33e29SRobert Watson #define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
28675a67bf3SMatt Macy #define	UNP_PCB_OWNED(unp)		mtx_owned(&(unp)->unp_mtx)
287e7c33e29SRobert Watson #define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
28875a67bf3SMatt Macy #define	UNP_PCB_UNLOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
2890d9ce3a1SRobert Watson 
2902c899584SRobert Watson static int	uipc_connect2(struct socket *, struct socket *);
2910b36cd25SRobert Watson static int	uipc_ctloutput(struct socket *, struct sockopt *);
292aea52f1bSRobert Watson static int	unp_connect(struct socket *, struct sockaddr *,
293aea52f1bSRobert Watson 		    struct thread *);
2947493f24eSPawel Jakub Dawidek static int	unp_connectat(int, struct socket *, struct sockaddr *,
2957493f24eSPawel Jakub Dawidek 		    struct thread *);
2966a2989fdSMatthew N. Dodd static int	unp_connect2(struct socket *so, struct socket *so2, int);
297e7c33e29SRobert Watson static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
29899ab95dbSMark Johnston static void	unp_dispose(struct socket *so);
29999ab95dbSMark Johnston static void	unp_dispose_mbuf(struct mbuf *);
3004d77a549SAlfred Perlstein static void	unp_shutdown(struct unpcb *);
301afc055d9SEd Schouten static void	unp_drop(struct unpcb *);
302a0ec558aSRobert Watson static void	unp_gc(__unused void *, int);
303be26ba7cSPawel Jakub Dawidek static void	unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
3044d77a549SAlfred Perlstein static void	unp_discard(struct file *);
3058cb539f1SPawel Jakub Dawidek static void	unp_freerights(struct filedescent **, int);
3060b36cd25SRobert Watson static void	unp_init(void);
3074d77a549SAlfred Perlstein static int	unp_internalize(struct mbuf **, struct thread *);
308397c19d1SJeff Roberson static void	unp_internalize_fp(struct file *);
309c2e3c52eSJilles Tjoelker static int	unp_externalize(struct mbuf *, struct mbuf **, int);
3100cb64678SKonstantin Belousov static int	unp_externalize_fp(struct file *);
3115b950deaSRobert Watson static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *);
3120cb64678SKonstantin Belousov static void	unp_process_defers(void * __unused, int);
313f708ef1bSPoul-Henning Kamp 
31475a67bf3SMatt Macy static void
31575a67bf3SMatt Macy unp_pcb_hold(struct unpcb *unp)
31675a67bf3SMatt Macy {
3175362170dSMark Johnston 	u_int old __unused;
3185362170dSMark Johnston 
3195362170dSMark Johnston 	old = refcount_acquire(&unp->unp_refcount);
3205362170dSMark Johnston 	KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
32175a67bf3SMatt Macy }
32275a67bf3SMatt Macy 
3235362170dSMark Johnston static __result_use_check bool
32475a67bf3SMatt Macy unp_pcb_rele(struct unpcb *unp)
32575a67bf3SMatt Macy {
3265362170dSMark Johnston 	bool ret;
32775a67bf3SMatt Macy 
32875a67bf3SMatt Macy 	UNP_PCB_LOCK_ASSERT(unp);
3295362170dSMark Johnston 
3305362170dSMark Johnston 	if ((ret = refcount_release(&unp->unp_refcount))) {
33175a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
33275a67bf3SMatt Macy 		UNP_PCB_LOCK_DESTROY(unp);
33375a67bf3SMatt Macy 		uma_zfree(unp_zone, unp);
33475a67bf3SMatt Macy 	}
3355362170dSMark Johnston 	return (ret);
33675a67bf3SMatt Macy }
33775a67bf3SMatt Macy 
33875a67bf3SMatt Macy static void
339f0317f86SMark Johnston unp_pcb_rele_notlast(struct unpcb *unp)
340f0317f86SMark Johnston {
341f0317f86SMark Johnston 	bool ret __unused;
342f0317f86SMark Johnston 
343f0317f86SMark Johnston 	ret = refcount_release(&unp->unp_refcount);
344f0317f86SMark Johnston 	KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
345f0317f86SMark Johnston }
346f0317f86SMark Johnston 
347f0317f86SMark Johnston static void
3484820bf6aSMark Johnston unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
34975a67bf3SMatt Macy {
35075a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
35175a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp2);
3524820bf6aSMark Johnston 
3534820bf6aSMark Johnston 	if (unp == unp2) {
3544820bf6aSMark Johnston 		UNP_PCB_LOCK(unp);
3554820bf6aSMark Johnston 	} else if ((uintptr_t)unp2 > (uintptr_t)unp) {
35675a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
35775a67bf3SMatt Macy 		UNP_PCB_LOCK(unp2);
35875a67bf3SMatt Macy 	} else {
35975a67bf3SMatt Macy 		UNP_PCB_LOCK(unp2);
36075a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
36175a67bf3SMatt Macy 	}
36275a67bf3SMatt Macy }
36375a67bf3SMatt Macy 
3644820bf6aSMark Johnston static void
3654820bf6aSMark Johnston unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
3664820bf6aSMark Johnston {
3674820bf6aSMark Johnston 	UNP_PCB_UNLOCK(unp);
3684820bf6aSMark Johnston 	if (unp != unp2)
3694820bf6aSMark Johnston 		UNP_PCB_UNLOCK(unp2);
3704820bf6aSMark Johnston }
3714820bf6aSMark Johnston 
372*ccdadf1aSMark Johnston /*
373*ccdadf1aSMark Johnston  * Try to lock the connected peer of an already locked socket.  In some cases
374*ccdadf1aSMark Johnston  * this requires that we unlock the current socket.  The pairbusy counter is
375*ccdadf1aSMark Johnston  * used to block concurrent connection attempts while the lock is dropped.  The
376*ccdadf1aSMark Johnston  * caller must be careful to revalidate PCB state.
377*ccdadf1aSMark Johnston  */
378*ccdadf1aSMark Johnston static struct unpcb *
379*ccdadf1aSMark Johnston unp_pcb_lock_peer(struct unpcb *unp)
38075a67bf3SMatt Macy {
38175a67bf3SMatt Macy 	struct unpcb *unp2;
38275a67bf3SMatt Macy 
383*ccdadf1aSMark Johnston 	UNP_PCB_LOCK_ASSERT(unp);
384*ccdadf1aSMark Johnston 	unp2 = unp->unp_conn;
385*ccdadf1aSMark Johnston 	if (__predict_false(unp2 == NULL))
386*ccdadf1aSMark Johnston 		return (NULL);
387*ccdadf1aSMark Johnston 	if (__predict_false(unp == unp2))
388*ccdadf1aSMark Johnston 		return (unp);
389*ccdadf1aSMark Johnston 
390*ccdadf1aSMark Johnston 	UNP_PCB_UNLOCK_ASSERT(unp2);
391*ccdadf1aSMark Johnston 
392*ccdadf1aSMark Johnston 	if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
393*ccdadf1aSMark Johnston 		return (unp2);
394*ccdadf1aSMark Johnston 	if ((uintptr_t)unp2 > (uintptr_t)unp) {
395*ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp2);
396*ccdadf1aSMark Johnston 		return (unp2);
397*ccdadf1aSMark Johnston 	}
398*ccdadf1aSMark Johnston 	unp->unp_pairbusy++;
399e62ca80bSMark Johnston 	unp_pcb_hold(unp2);
400e62ca80bSMark Johnston 	UNP_PCB_UNLOCK(unp);
401*ccdadf1aSMark Johnston 
402e62ca80bSMark Johnston 	UNP_PCB_LOCK(unp2);
403e62ca80bSMark Johnston 	UNP_PCB_LOCK(unp);
404*ccdadf1aSMark Johnston 	KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
405*ccdadf1aSMark Johnston 	    ("%s: socket %p was reconnected", __func__, unp));
406*ccdadf1aSMark Johnston 	if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
407*ccdadf1aSMark Johnston 		unp->unp_flags &= ~UNP_WAITING;
408*ccdadf1aSMark Johnston 		wakeup(unp);
40975a67bf3SMatt Macy 	}
410*ccdadf1aSMark Johnston 	if (unp_pcb_rele(unp2)) {
411*ccdadf1aSMark Johnston 		/* unp2 is unlocked. */
412*ccdadf1aSMark Johnston 		return (NULL);
413*ccdadf1aSMark Johnston 	}
414*ccdadf1aSMark Johnston 	if (unp->unp_conn == NULL) {
415*ccdadf1aSMark Johnston 		UNP_PCB_UNLOCK(unp2);
416*ccdadf1aSMark Johnston 		return (NULL);
417*ccdadf1aSMark Johnston 	}
418*ccdadf1aSMark Johnston 	return (unp2);
419*ccdadf1aSMark Johnston }
42075a67bf3SMatt Macy 
421e4445a03SRobert Watson /*
422e4445a03SRobert Watson  * Definitions of protocols supported in the LOCAL domain.
423e4445a03SRobert Watson  */
424e4445a03SRobert Watson static struct domain localdomain;
425fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
42684d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket;
427e4445a03SRobert Watson static struct protosw localsw[] = {
428e4445a03SRobert Watson {
429e4445a03SRobert Watson 	.pr_type =		SOCK_STREAM,
430e4445a03SRobert Watson 	.pr_domain =		&localdomain,
431e4445a03SRobert Watson 	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
432e4445a03SRobert Watson 	.pr_ctloutput =		&uipc_ctloutput,
433fa9402f2SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_stream
434e4445a03SRobert Watson },
435e4445a03SRobert Watson {
436e4445a03SRobert Watson 	.pr_type =		SOCK_DGRAM,
437e4445a03SRobert Watson 	.pr_domain =		&localdomain,
438e4445a03SRobert Watson 	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS,
439aaf63435SGleb Smirnoff 	.pr_ctloutput =		&uipc_ctloutput,
440fa9402f2SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_dgram
441e4445a03SRobert Watson },
44284d61770SRobert Watson {
44384d61770SRobert Watson 	.pr_type =		SOCK_SEQPACKET,
44484d61770SRobert Watson 	.pr_domain =		&localdomain,
44584d61770SRobert Watson 
44684d61770SRobert Watson 	/*
44784d61770SRobert Watson 	 * XXXRW: For now, PR_ADDR because soreceive will bump into them
44884d61770SRobert Watson 	 * due to our use of sbappendaddr.  A new sbappend variants is needed
44984d61770SRobert Watson 	 * that supports both atomic record writes and control data.
45084d61770SRobert Watson 	 */
45184d61770SRobert Watson 	.pr_flags =		PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
45284d61770SRobert Watson 				    PR_RIGHTS,
453e0643280SGleb Smirnoff 	.pr_ctloutput =		&uipc_ctloutput,
45484d61770SRobert Watson 	.pr_usrreqs =		&uipc_usrreqs_seqpacket,
45584d61770SRobert Watson },
456e4445a03SRobert Watson };
457e4445a03SRobert Watson 
458e4445a03SRobert Watson static struct domain localdomain = {
459e4445a03SRobert Watson 	.dom_family =		AF_LOCAL,
460e4445a03SRobert Watson 	.dom_name =		"local",
461e4445a03SRobert Watson 	.dom_init =		unp_init,
462e4445a03SRobert Watson 	.dom_externalize =	unp_externalize,
46399ab95dbSMark Johnston 	.dom_dispose =		unp_dispose,
464e4445a03SRobert Watson 	.dom_protosw =		localsw,
46502abd400SPedro F. Giffuni 	.dom_protoswNPROTOSW =	&localsw[nitems(localsw)]
466e4445a03SRobert Watson };
467e4445a03SRobert Watson DOMAIN_SET(local);
468e4445a03SRobert Watson 
469ac45e92fSRobert Watson static void
470a29f300eSGarrett Wollman uipc_abort(struct socket *so)
471df8bae1dSRodney W. Grimes {
472e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
473df8bae1dSRodney W. Grimes 
47440f2ac28SRobert Watson 	unp = sotounpcb(so);
4754d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
47675a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
477e7c33e29SRobert Watson 
478e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
479e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
480e7c33e29SRobert Watson 	if (unp2 != NULL) {
48175a67bf3SMatt Macy 		unp_pcb_hold(unp2);
482e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
48375a67bf3SMatt Macy 		unp_drop(unp2);
48475a67bf3SMatt Macy 	} else
48575a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
486df8bae1dSRodney W. Grimes }
487df8bae1dSRodney W. Grimes 
488a29f300eSGarrett Wollman static int
48957bf258eSGarrett Wollman uipc_accept(struct socket *so, struct sockaddr **nam)
490a29f300eSGarrett Wollman {
491e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
4920d9ce3a1SRobert Watson 	const struct sockaddr *sa;
493df8bae1dSRodney W. Grimes 
494df8bae1dSRodney W. Grimes 	/*
4951c381b19SRobert Watson 	 * Pass back name of connected socket, if it was bound and we are
4961c381b19SRobert Watson 	 * still connected (our peer may have closed already!).
497df8bae1dSRodney W. Grimes 	 */
4984d4b555eSRobert Watson 	unp = sotounpcb(so);
4994d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
500e7c33e29SRobert Watson 
5010d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
5023dab55bcSRobert Watson 	UNP_LINK_RLOCK();
503e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
504e7c33e29SRobert Watson 	if (unp2 != NULL && unp2->unp_addr != NULL) {
505e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp2);
506e7c33e29SRobert Watson 		sa = (struct sockaddr *) unp2->unp_addr;
507e7c33e29SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
508e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
509e7c33e29SRobert Watson 	} else {
5100d9ce3a1SRobert Watson 		sa = &sun_noname;
5110d9ce3a1SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
512e7c33e29SRobert Watson 	}
5133dab55bcSRobert Watson 	UNP_LINK_RUNLOCK();
514e5aeaa0cSDag-Erling Smørgrav 	return (0);
515a29f300eSGarrett Wollman }
516df8bae1dSRodney W. Grimes 
517a29f300eSGarrett Wollman static int
518b40ce416SJulian Elischer uipc_attach(struct socket *so, int proto, struct thread *td)
519a29f300eSGarrett Wollman {
520e7c33e29SRobert Watson 	u_long sendspace, recvspace;
5216d32873cSRobert Watson 	struct unpcb *unp;
5223dab55bcSRobert Watson 	int error;
523779f106aSGleb Smirnoff 	bool locked;
524df8bae1dSRodney W. Grimes 
5256d32873cSRobert Watson 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
5266d32873cSRobert Watson 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
5276d32873cSRobert Watson 		switch (so->so_type) {
5286d32873cSRobert Watson 		case SOCK_STREAM:
529e7c33e29SRobert Watson 			sendspace = unpst_sendspace;
530e7c33e29SRobert Watson 			recvspace = unpst_recvspace;
5316d32873cSRobert Watson 			break;
5326d32873cSRobert Watson 
5336d32873cSRobert Watson 		case SOCK_DGRAM:
534e7c33e29SRobert Watson 			sendspace = unpdg_sendspace;
535e7c33e29SRobert Watson 			recvspace = unpdg_recvspace;
5366d32873cSRobert Watson 			break;
5376d32873cSRobert Watson 
53884d61770SRobert Watson 		case SOCK_SEQPACKET:
53984d61770SRobert Watson 			sendspace = unpsp_sendspace;
54084d61770SRobert Watson 			recvspace = unpsp_recvspace;
54184d61770SRobert Watson 			break;
54284d61770SRobert Watson 
5436d32873cSRobert Watson 		default:
544e7c33e29SRobert Watson 			panic("uipc_attach");
5456d32873cSRobert Watson 		}
546e7c33e29SRobert Watson 		error = soreserve(so, sendspace, recvspace);
5476d32873cSRobert Watson 		if (error)
5486d32873cSRobert Watson 			return (error);
5496d32873cSRobert Watson 	}
55046a1d9bfSRobert Watson 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
5516d32873cSRobert Watson 	if (unp == NULL)
5526d32873cSRobert Watson 		return (ENOBUFS);
5536d32873cSRobert Watson 	LIST_INIT(&unp->unp_refs);
554e7c33e29SRobert Watson 	UNP_PCB_LOCK_INIT(unp);
5556d32873cSRobert Watson 	unp->unp_socket = so;
5566d32873cSRobert Watson 	so->so_pcb = unp;
5575362170dSMark Johnston 	refcount_init(&unp->unp_refcount, 1);
558e7c33e29SRobert Watson 
559779f106aSGleb Smirnoff 	if ((locked = UNP_LINK_WOWNED()) == false)
560779f106aSGleb Smirnoff 		UNP_LINK_WLOCK();
561779f106aSGleb Smirnoff 
5626d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
563f218ac50SMateusz Guzik 	unp->unp_ino = ++unp_ino;
5646d32873cSRobert Watson 	unp_count++;
56584d61770SRobert Watson 	switch (so->so_type) {
56684d61770SRobert Watson 	case SOCK_STREAM:
56784d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
56884d61770SRobert Watson 		break;
56984d61770SRobert Watson 
57084d61770SRobert Watson 	case SOCK_DGRAM:
57184d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
57284d61770SRobert Watson 		break;
57384d61770SRobert Watson 
57484d61770SRobert Watson 	case SOCK_SEQPACKET:
57584d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
57684d61770SRobert Watson 		break;
57784d61770SRobert Watson 
57884d61770SRobert Watson 	default:
57984d61770SRobert Watson 		panic("uipc_attach");
58084d61770SRobert Watson 	}
581779f106aSGleb Smirnoff 
582779f106aSGleb Smirnoff 	if (locked == false)
583779f106aSGleb Smirnoff 		UNP_LINK_WUNLOCK();
5846d32873cSRobert Watson 
5856d32873cSRobert Watson 	return (0);
586a29f300eSGarrett Wollman }
587a29f300eSGarrett Wollman 
588a29f300eSGarrett Wollman static int
5897493f24eSPawel Jakub Dawidek uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
590a29f300eSGarrett Wollman {
591dd47f5caSRobert Watson 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
592dd47f5caSRobert Watson 	struct vattr vattr;
5935050aa86SKonstantin Belousov 	int error, namelen;
594dd47f5caSRobert Watson 	struct nameidata nd;
59540f2ac28SRobert Watson 	struct unpcb *unp;
596dd47f5caSRobert Watson 	struct vnode *vp;
597dd47f5caSRobert Watson 	struct mount *mp;
5987008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
599dd47f5caSRobert Watson 	char *buf;
600a29f300eSGarrett Wollman 
601cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
602cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
603cb7df69bSKevin Lo 
60440f2ac28SRobert Watson 	unp = sotounpcb(so);
6054d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
6064f1f0ef5SRobert Watson 
607a06534c3SBjoern A. Zeeb 	if (soun->sun_len > sizeof(struct sockaddr_un))
608a06534c3SBjoern A. Zeeb 		return (EINVAL);
6094f1f0ef5SRobert Watson 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
6104f1f0ef5SRobert Watson 	if (namelen <= 0)
6114f1f0ef5SRobert Watson 		return (EINVAL);
612dd47f5caSRobert Watson 
613dd47f5caSRobert Watson 	/*
6144f1f0ef5SRobert Watson 	 * We don't allow simultaneous bind() calls on a single UNIX domain
6154f1f0ef5SRobert Watson 	 * socket, so flag in-progress operations, and return an error if an
6164f1f0ef5SRobert Watson 	 * operation is already in progress.
6174f1f0ef5SRobert Watson 	 *
6184f1f0ef5SRobert Watson 	 * Historically, we have not allowed a socket to be rebound, so this
619d7924b70SRobert Watson 	 * also returns an error.  Not allowing re-binding simplifies the
620d7924b70SRobert Watson 	 * implementation and avoids a great many possible failure modes.
621dd47f5caSRobert Watson 	 */
622e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
623dd47f5caSRobert Watson 	if (unp->unp_vnode != NULL) {
624e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
625dd47f5caSRobert Watson 		return (EINVAL);
626dd47f5caSRobert Watson 	}
6274f1f0ef5SRobert Watson 	if (unp->unp_flags & UNP_BINDING) {
628e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
6294f1f0ef5SRobert Watson 		return (EALREADY);
630dd47f5caSRobert Watson 	}
6314f1f0ef5SRobert Watson 	unp->unp_flags |= UNP_BINDING;
632e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
633dd47f5caSRobert Watson 
634dd47f5caSRobert Watson 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
6357928893dSEd Maste 	bcopy(soun->sun_path, buf, namelen);
6367928893dSEd Maste 	buf[namelen] = 0;
637dd47f5caSRobert Watson 
638dd47f5caSRobert Watson restart:
6396c21f6edSKonstantin Belousov 	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
6407008be5bSPawel Jakub Dawidek 	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
641dd47f5caSRobert Watson /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
642dd47f5caSRobert Watson 	error = namei(&nd);
643dd47f5caSRobert Watson 	if (error)
6444f1f0ef5SRobert Watson 		goto error;
645dd47f5caSRobert Watson 	vp = nd.ni_vp;
646dd47f5caSRobert Watson 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
647dd47f5caSRobert Watson 		NDFREE(&nd, NDF_ONLY_PNBUF);
648dd47f5caSRobert Watson 		if (nd.ni_dvp == vp)
649dd47f5caSRobert Watson 			vrele(nd.ni_dvp);
650dd47f5caSRobert Watson 		else
651dd47f5caSRobert Watson 			vput(nd.ni_dvp);
652dd47f5caSRobert Watson 		if (vp != NULL) {
653dd47f5caSRobert Watson 			vrele(vp);
654dd47f5caSRobert Watson 			error = EADDRINUSE;
6554f1f0ef5SRobert Watson 			goto error;
656dd47f5caSRobert Watson 		}
657dd47f5caSRobert Watson 		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
658dd47f5caSRobert Watson 		if (error)
6594f1f0ef5SRobert Watson 			goto error;
660dd47f5caSRobert Watson 		goto restart;
661dd47f5caSRobert Watson 	}
662dd47f5caSRobert Watson 	VATTR_NULL(&vattr);
663dd47f5caSRobert Watson 	vattr.va_type = VSOCK;
664dd47f5caSRobert Watson 	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
665dd47f5caSRobert Watson #ifdef MAC
66630d239bcSRobert Watson 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
667dd47f5caSRobert Watson 	    &vattr);
668dd47f5caSRobert Watson #endif
669885868cdSRobert Watson 	if (error == 0)
670dd47f5caSRobert Watson 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
671dd47f5caSRobert Watson 	NDFREE(&nd, NDF_ONLY_PNBUF);
672dd47f5caSRobert Watson 	vput(nd.ni_dvp);
673dd47f5caSRobert Watson 	if (error) {
674dd47f5caSRobert Watson 		vn_finished_write(mp);
6754f1f0ef5SRobert Watson 		goto error;
676dd47f5caSRobert Watson 	}
677dd47f5caSRobert Watson 	vp = nd.ni_vp;
67857fd3d55SPawel Jakub Dawidek 	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
679dd47f5caSRobert Watson 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
680e7c33e29SRobert Watson 
681e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6820c3c207fSGleb Smirnoff 	VOP_UNP_BIND(vp, unp);
683dd47f5caSRobert Watson 	unp->unp_vnode = vp;
684dd47f5caSRobert Watson 	unp->unp_addr = soun;
6854f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
686e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
687b249ce48SMateusz Guzik 	VOP_UNLOCK(vp);
688dd47f5caSRobert Watson 	vn_finished_write(mp);
6894f1f0ef5SRobert Watson 	free(buf, M_TEMP);
6904f1f0ef5SRobert Watson 	return (0);
691e7c33e29SRobert Watson 
6924f1f0ef5SRobert Watson error:
693e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6944f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
695e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
696dd47f5caSRobert Watson 	free(buf, M_TEMP);
69740f2ac28SRobert Watson 	return (error);
698a29f300eSGarrett Wollman }
699a29f300eSGarrett Wollman 
700a29f300eSGarrett Wollman static int
7017493f24eSPawel Jakub Dawidek uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
7027493f24eSPawel Jakub Dawidek {
7037493f24eSPawel Jakub Dawidek 
7047493f24eSPawel Jakub Dawidek 	return (uipc_bindat(AT_FDCWD, so, nam, td));
7057493f24eSPawel Jakub Dawidek }
7067493f24eSPawel Jakub Dawidek 
7077493f24eSPawel Jakub Dawidek static int
708b40ce416SJulian Elischer uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
709a29f300eSGarrett Wollman {
7100d9ce3a1SRobert Watson 	int error;
711a29f300eSGarrett Wollman 
712fd179ee9SRobert Watson 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
713fd179ee9SRobert Watson 	error = unp_connect(so, nam, td);
7140d9ce3a1SRobert Watson 	return (error);
715a29f300eSGarrett Wollman }
716a29f300eSGarrett Wollman 
7177493f24eSPawel Jakub Dawidek static int
7187493f24eSPawel Jakub Dawidek uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
7197493f24eSPawel Jakub Dawidek     struct thread *td)
7207493f24eSPawel Jakub Dawidek {
7217493f24eSPawel Jakub Dawidek 	int error;
7227493f24eSPawel Jakub Dawidek 
7237493f24eSPawel Jakub Dawidek 	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
7247493f24eSPawel Jakub Dawidek 	error = unp_connectat(fd, so, nam, td);
7257493f24eSPawel Jakub Dawidek 	return (error);
7267493f24eSPawel Jakub Dawidek }
7277493f24eSPawel Jakub Dawidek 
728a152f8a3SRobert Watson static void
729a152f8a3SRobert Watson uipc_close(struct socket *so)
730a152f8a3SRobert Watson {
731e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
732779f106aSGleb Smirnoff 	struct vnode *vp = NULL;
73375a67bf3SMatt Macy 	struct mtx *vplock;
734*ccdadf1aSMark Johnston 
735a152f8a3SRobert Watson 	unp = sotounpcb(so);
736a152f8a3SRobert Watson 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
737e7c33e29SRobert Watson 
73875a67bf3SMatt Macy 	vplock = NULL;
73975a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
74075a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
74175a67bf3SMatt Macy 		mtx_lock(vplock);
742e7c33e29SRobert Watson 	}
74375a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
74475a67bf3SMatt Macy 	if (vp && unp->unp_vnode == NULL) {
74575a67bf3SMatt Macy 		mtx_unlock(vplock);
74675a67bf3SMatt Macy 		vp = NULL;
74775a67bf3SMatt Macy 	}
74875a67bf3SMatt Macy 	if (vp != NULL) {
749779f106aSGleb Smirnoff 		VOP_UNP_DETACH(vp);
750779f106aSGleb Smirnoff 		unp->unp_vnode = NULL;
751779f106aSGleb Smirnoff 	}
752*ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
753acf9fd05SMatt Macy 		unp_disconnect(unp, unp2);
754*ccdadf1aSMark Johnston 	else
755e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
75675a67bf3SMatt Macy 	if (vp) {
75775a67bf3SMatt Macy 		mtx_unlock(vplock);
758779f106aSGleb Smirnoff 		vrele(vp);
759a152f8a3SRobert Watson 	}
76075a67bf3SMatt Macy }
761a152f8a3SRobert Watson 
7622c899584SRobert Watson static int
763a29f300eSGarrett Wollman uipc_connect2(struct socket *so1, struct socket *so2)
764a29f300eSGarrett Wollman {
765e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
7660d9ce3a1SRobert Watson 	int error;
767a29f300eSGarrett Wollman 
768e7c33e29SRobert Watson 	unp = so1->so_pcb;
7694d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
770e7c33e29SRobert Watson 	unp2 = so2->so_pcb;
771e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
7724820bf6aSMark Johnston 	unp_pcb_lock_pair(unp, unp2);
7736a2989fdSMatthew N. Dodd 	error = unp_connect2(so1, so2, PRU_CONNECT2);
7744820bf6aSMark Johnston 	unp_pcb_unlock_pair(unp, unp2);
7750d9ce3a1SRobert Watson 	return (error);
776a29f300eSGarrett Wollman }
777a29f300eSGarrett Wollman 
778bc725eafSRobert Watson static void
779a29f300eSGarrett Wollman uipc_detach(struct socket *so)
780a29f300eSGarrett Wollman {
781e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
78275a67bf3SMatt Macy 	struct mtx *vplock;
7836d32873cSRobert Watson 	struct vnode *vp;
784*ccdadf1aSMark Johnston 	int local_unp_rights;
785a29f300eSGarrett Wollman 
78640f2ac28SRobert Watson 	unp = sotounpcb(so);
7874d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
788e7c33e29SRobert Watson 
789434ac8b6SMark Johnston 	vp = NULL;
790c0874c34SMatt Macy 	vplock = NULL;
791434ac8b6SMark Johnston 
792a50b1900SMark Johnston 	SOCK_LOCK(so);
793a50b1900SMark Johnston 	if (!SOLISTENING(so)) {
794a50b1900SMark Johnston 		/*
795a50b1900SMark Johnston 		 * Once the socket is removed from the global lists,
796a50b1900SMark Johnston 		 * uipc_ready() will not be able to locate its socket buffer, so
797a50b1900SMark Johnston 		 * clear the buffer now.  At this point internalized rights have
798a50b1900SMark Johnston 		 * already been disposed of.
799a50b1900SMark Johnston 		 */
800a50b1900SMark Johnston 		sbrelease(&so->so_rcv, so);
801a50b1900SMark Johnston 	}
802a50b1900SMark Johnston 	SOCK_UNLOCK(so);
803a50b1900SMark Johnston 
804779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
8056d32873cSRobert Watson 	LIST_REMOVE(unp, unp_link);
806a9aa06f7SJason A. Harmening 	if (unp->unp_gcflag & UNPGC_DEAD)
807a9aa06f7SJason A. Harmening 		LIST_REMOVE(unp, unp_dead);
8086d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
8096d32873cSRobert Watson 	--unp_count;
81075a67bf3SMatt Macy 	UNP_LINK_WUNLOCK();
811434ac8b6SMark Johnston 
81275a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
81375a67bf3SMatt Macy  restart:
81475a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
81575a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
81675a67bf3SMatt Macy 		mtx_lock(vplock);
81775a67bf3SMatt Macy 	}
81875a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
819db38b699SMark Johnston 	if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
820c0874c34SMatt Macy 		if (vplock)
82175a67bf3SMatt Macy 			mtx_unlock(vplock);
82275a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
82375a67bf3SMatt Macy 		goto restart;
82475a67bf3SMatt Macy 	}
8256d32873cSRobert Watson 	if ((vp = unp->unp_vnode) != NULL) {
826c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
8276d32873cSRobert Watson 		unp->unp_vnode = NULL;
8286d32873cSRobert Watson 	}
829*ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
830e7c33e29SRobert Watson 		unp_disconnect(unp, unp2);
831f0317f86SMark Johnston 	else
83275a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
833*ccdadf1aSMark Johnston 
83475a67bf3SMatt Macy 	UNP_REF_LIST_LOCK();
8356d32873cSRobert Watson 	while (!LIST_EMPTY(&unp->unp_refs)) {
8366d32873cSRobert Watson 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
837e7c33e29SRobert Watson 
83875a67bf3SMatt Macy 		unp_pcb_hold(ref);
83975a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
84075a67bf3SMatt Macy 
84175a67bf3SMatt Macy 		MPASS(ref != unp);
84275a67bf3SMatt Macy 		UNP_PCB_UNLOCK_ASSERT(ref);
843afc055d9SEd Schouten 		unp_drop(ref);
84475a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
8456d32873cSRobert Watson 	}
84675a67bf3SMatt Macy 	UNP_REF_LIST_UNLOCK();
847*ccdadf1aSMark Johnston 
84875a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
849397c19d1SJeff Roberson 	local_unp_rights = unp_rights;
8506d32873cSRobert Watson 	unp->unp_socket->so_pcb = NULL;
85175a67bf3SMatt Macy 	unp->unp_socket = NULL;
852db38b699SMark Johnston 	free(unp->unp_addr, M_SONAME);
853db38b699SMark Johnston 	unp->unp_addr = NULL;
854db38b699SMark Johnston 	if (!unp_pcb_rele(unp))
8556e2faa24SRobert Watson 		UNP_PCB_UNLOCK(unp);
85675a67bf3SMatt Macy 	if (vp) {
85775a67bf3SMatt Macy 		mtx_unlock(vplock);
8586d32873cSRobert Watson 		vrele(vp);
85975a67bf3SMatt Macy 	}
8606d32873cSRobert Watson 	if (local_unp_rights)
861daee0f0bSKonstantin Belousov 		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
862a29f300eSGarrett Wollman }
863a29f300eSGarrett Wollman 
864a29f300eSGarrett Wollman static int
865a29f300eSGarrett Wollman uipc_disconnect(struct socket *so)
866a29f300eSGarrett Wollman {
867e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
868a29f300eSGarrett Wollman 
86940f2ac28SRobert Watson 	unp = sotounpcb(so);
8704d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
871e7c33e29SRobert Watson 
872e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
873*ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
87475a67bf3SMatt Macy 		unp_disconnect(unp, unp2);
875*ccdadf1aSMark Johnston 	else
876*ccdadf1aSMark Johnston 		UNP_PCB_UNLOCK(unp);
877e5aeaa0cSDag-Erling Smørgrav 	return (0);
878a29f300eSGarrett Wollman }
879a29f300eSGarrett Wollman 
880a29f300eSGarrett Wollman static int
881d374e81eSRobert Watson uipc_listen(struct socket *so, int backlog, struct thread *td)
882a29f300eSGarrett Wollman {
88340f2ac28SRobert Watson 	struct unpcb *unp;
8840d9ce3a1SRobert Watson 	int error;
885a29f300eSGarrett Wollman 
886beb4b312SGleb Smirnoff 	if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
887beb4b312SGleb Smirnoff 		return (EOPNOTSUPP);
888beb4b312SGleb Smirnoff 
88940f2ac28SRobert Watson 	unp = sotounpcb(so);
8904d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
891e7c33e29SRobert Watson 
892e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
8934d4b555eSRobert Watson 	if (unp->unp_vnode == NULL) {
89447a84387SEd Schouten 		/* Already connected or not bound to an address. */
89547a84387SEd Schouten 		error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
896e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
89747a84387SEd Schouten 		return (error);
89840f2ac28SRobert Watson 	}
899e7c33e29SRobert Watson 
900e7c33e29SRobert Watson 	SOCK_LOCK(so);
901e7c33e29SRobert Watson 	error = solisten_proto_check(so);
902e7c33e29SRobert Watson 	if (error == 0) {
903c5afec6eSDmitry Chagin 		cru2xt(td, &unp->unp_peercred);
904e7c33e29SRobert Watson 		solisten_proto(so, backlog);
905e7c33e29SRobert Watson 	}
906e7c33e29SRobert Watson 	SOCK_UNLOCK(so);
907e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
9080d9ce3a1SRobert Watson 	return (error);
909a29f300eSGarrett Wollman }
910a29f300eSGarrett Wollman 
911a29f300eSGarrett Wollman static int
91257bf258eSGarrett Wollman uipc_peeraddr(struct socket *so, struct sockaddr **nam)
913a29f300eSGarrett Wollman {
914e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
9150d9ce3a1SRobert Watson 	const struct sockaddr *sa;
916a29f300eSGarrett Wollman 
9174d4b555eSRobert Watson 	unp = sotounpcb(so);
9184d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
919e7c33e29SRobert Watson 
9200d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
921afd9f91cSJohn Baldwin 	UNP_LINK_RLOCK();
922bdc5f6a3SHajimu UMEMOTO 	/*
923e7c33e29SRobert Watson 	 * XXX: It seems that this test always fails even when connection is
924e7c33e29SRobert Watson 	 * established.  So, this else clause is added as workaround to
925e7c33e29SRobert Watson 	 * return PF_LOCAL sockaddr.
926bdc5f6a3SHajimu UMEMOTO 	 */
927e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
928e7c33e29SRobert Watson 	if (unp2 != NULL) {
929e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp2);
930e7c33e29SRobert Watson 		if (unp2->unp_addr != NULL)
931afd9f91cSJohn Baldwin 			sa = (struct sockaddr *) unp2->unp_addr;
932e7c33e29SRobert Watson 		else
9330d9ce3a1SRobert Watson 			sa = &sun_noname;
9340d9ce3a1SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
935e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
936e7c33e29SRobert Watson 	} else {
937e7c33e29SRobert Watson 		sa = &sun_noname;
938e7c33e29SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
939e7c33e29SRobert Watson 	}
940afd9f91cSJohn Baldwin 	UNP_LINK_RUNLOCK();
941e5aeaa0cSDag-Erling Smørgrav 	return (0);
942a29f300eSGarrett Wollman }
943a29f300eSGarrett Wollman 
944a29f300eSGarrett Wollman static int
945a29f300eSGarrett Wollman uipc_rcvd(struct socket *so, int flags)
946a29f300eSGarrett Wollman {
947e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
948a29f300eSGarrett Wollman 	struct socket *so2;
949337cc6b6SRobert Watson 	u_int mbcnt, sbcc;
950a29f300eSGarrett Wollman 
95140f2ac28SRobert Watson 	unp = sotounpcb(so);
9522b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
9532b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
9542b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
955e7c33e29SRobert Watson 
956df8bae1dSRodney W. Grimes 	/*
957e7c33e29SRobert Watson 	 * Adjust backpressure on sender and wakeup any waiting to write.
958e7c33e29SRobert Watson 	 *
959d7924b70SRobert Watson 	 * The unp lock is acquired to maintain the validity of the unp_conn
960d7924b70SRobert Watson 	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
961d7924b70SRobert Watson 	 * static as long as we don't permit unp2 to disconnect from unp,
962d7924b70SRobert Watson 	 * which is prevented by the lock on unp.  We cache values from
963d7924b70SRobert Watson 	 * so_rcv to avoid holding the so_rcv lock over the entire
964d7924b70SRobert Watson 	 * transaction on the remote so_snd.
965df8bae1dSRodney W. Grimes 	 */
966337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so->so_rcv);
967337cc6b6SRobert Watson 	mbcnt = so->so_rcv.sb_mbcnt;
9682b21d0e8SGleb Smirnoff 	sbcc = sbavail(&so->so_rcv);
969337cc6b6SRobert Watson 	SOCKBUF_UNLOCK(&so->so_rcv);
970c2090e73SAlan Somers 	/*
971c2090e73SAlan Somers 	 * There is a benign race condition at this point.  If we're planning to
972c2090e73SAlan Somers 	 * clear SB_STOP, but uipc_send is called on the connected socket at
973c2090e73SAlan Somers 	 * this instant, it might add data to the sockbuf and set SB_STOP.  Then
974c2090e73SAlan Somers 	 * we would erroneously clear SB_STOP below, even though the sockbuf is
975c2090e73SAlan Somers 	 * full.  The race is benign because the only ill effect is to allow the
976c2090e73SAlan Somers 	 * sockbuf to exceed its size limit, and the size limits are not
977c2090e73SAlan Somers 	 * strictly guaranteed anyway.
978c2090e73SAlan Somers 	 */
979e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
980e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
981e7c33e29SRobert Watson 	if (unp2 == NULL) {
982e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
983e7c33e29SRobert Watson 		return (0);
984337cc6b6SRobert Watson 	}
985e7c33e29SRobert Watson 	so2 = unp2->unp_socket;
986337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so2->so_snd);
987c2090e73SAlan Somers 	if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
988c2090e73SAlan Somers 		so2->so_snd.sb_flags &= ~SB_STOP;
9891e4d7da7SRobert Watson 	sowwakeup_locked(so2);
990e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
991e5aeaa0cSDag-Erling Smørgrav 	return (0);
992a29f300eSGarrett Wollman }
993df8bae1dSRodney W. Grimes 
994a29f300eSGarrett Wollman static int
99557bf258eSGarrett Wollman uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
996b40ce416SJulian Elischer     struct mbuf *control, struct thread *td)
997a29f300eSGarrett Wollman {
998f3f49bbbSRobert Watson 	struct unpcb *unp, *unp2;
999a29f300eSGarrett Wollman 	struct socket *so2;
1000c2090e73SAlan Somers 	u_int mbcnt, sbcc;
100175a67bf3SMatt Macy 	int freed, error;
1002a29f300eSGarrett Wollman 
100340f2ac28SRobert Watson 	unp = sotounpcb(so);
10042b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
10052b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
10062b21d0e8SGleb Smirnoff 	    so->so_type == SOCK_SEQPACKET,
10072b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
1008e7c33e29SRobert Watson 
100975a67bf3SMatt Macy 	freed = error = 0;
1010a29f300eSGarrett Wollman 	if (flags & PRUS_OOB) {
1011a29f300eSGarrett Wollman 		error = EOPNOTSUPP;
1012a29f300eSGarrett Wollman 		goto release;
1013a29f300eSGarrett Wollman 	}
1014fc3fcacfSRobert Watson 	if (control != NULL && (error = unp_internalize(&control, td)))
1015a29f300eSGarrett Wollman 		goto release;
101675a67bf3SMatt Macy 
101775a67bf3SMatt Macy 	unp2 = NULL;
1018a29f300eSGarrett Wollman 	switch (so->so_type) {
1019a29f300eSGarrett Wollman 	case SOCK_DGRAM:
1020a29f300eSGarrett Wollman 	{
1021e7dd9a10SRobert Watson 		const struct sockaddr *from;
1022df8bae1dSRodney W. Grimes 
1023fc3fcacfSRobert Watson 		if (nam != NULL) {
1024*ccdadf1aSMark Johnston 			error = unp_connect(so, nam, td);
1025*ccdadf1aSMark Johnston 			if (error != 0)
1026df8bae1dSRodney W. Grimes 				break;
1027*ccdadf1aSMark Johnston 		}
102875a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
102960a5ef26SRobert Watson 
1030b5ff0914SRobert Watson 		/*
1031b5ff0914SRobert Watson 		 * Because connect() and send() are non-atomic in a sendto()
1032b5ff0914SRobert Watson 		 * with a target address, it's possible that the socket will
1033b5ff0914SRobert Watson 		 * have disconnected before the send() can run.  In that case
1034b5ff0914SRobert Watson 		 * return the slightly counter-intuitive but otherwise
1035b5ff0914SRobert Watson 		 * correct error that the socket is not connected.
1036b5ff0914SRobert Watson 		 */
1037*ccdadf1aSMark Johnston 		unp2 = unp_pcb_lock_peer(unp);
1038*ccdadf1aSMark Johnston 		if (unp2 == NULL) {
103975a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
1040b5ff0914SRobert Watson 			error = ENOTCONN;
1041b5ff0914SRobert Watson 			break;
1042b5ff0914SRobert Watson 		}
1043*ccdadf1aSMark Johnston 
1044ede6e136SRobert Watson 		if (unp2->unp_flags & UNP_WANTCRED)
1045ede6e136SRobert Watson 			control = unp_addsockcred(td, control);
1046fc3fcacfSRobert Watson 		if (unp->unp_addr != NULL)
104757bf258eSGarrett Wollman 			from = (struct sockaddr *)unp->unp_addr;
1048df8bae1dSRodney W. Grimes 		else
1049df8bae1dSRodney W. Grimes 			from = &sun_noname;
1050ede6e136SRobert Watson 		so2 = unp2->unp_socket;
1051a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
10526dde7ecbSPeter Wemm 		if (sbappendaddr_locked(&so2->so_rcv, from, m,
10538de34a88SAlan Somers 		    control)) {
10541e4d7da7SRobert Watson 			sorwakeup_locked(so2);
1055fc3fcacfSRobert Watson 			m = NULL;
1056fc3fcacfSRobert Watson 			control = NULL;
1057e5aeaa0cSDag-Erling Smørgrav 		} else {
1058a34b7046SRobert Watson 			SOCKBUF_UNLOCK(&so2->so_rcv);
1059df8bae1dSRodney W. Grimes 			error = ENOBUFS;
1060e5aeaa0cSDag-Erling Smørgrav 		}
106175a67bf3SMatt Macy 		if (nam != NULL)
1062e7c33e29SRobert Watson 			unp_disconnect(unp, unp2);
1063f0317f86SMark Johnston 		else
1064f0317f86SMark Johnston 			unp_pcb_unlock_pair(unp, unp2);
1065df8bae1dSRodney W. Grimes 		break;
1066df8bae1dSRodney W. Grimes 	}
1067df8bae1dSRodney W. Grimes 
106884d61770SRobert Watson 	case SOCK_SEQPACKET:
1069df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
1070402cc72dSDavid Greenman 		if ((so->so_state & SS_ISCONNECTED) == 0) {
1071fc3fcacfSRobert Watson 			if (nam != NULL) {
1072*ccdadf1aSMark Johnston 				error = unp_connect(so, nam, td);
1073b36871afSMark Johnston 				if (error != 0)
107475a67bf3SMatt Macy 					break;
1075402cc72dSDavid Greenman 			} else {
1076402cc72dSDavid Greenman 				error = ENOTCONN;
1077402cc72dSDavid Greenman 				break;
1078402cc72dSDavid Greenman 			}
1079b36871afSMark Johnston 		}
1080b36871afSMark Johnston 
1081*ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp);
1082*ccdadf1aSMark Johnston 		if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
108375a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
1084b5ff0914SRobert Watson 			error = ENOTCONN;
1085b5ff0914SRobert Watson 			break;
1086b36871afSMark Johnston 		} else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1087*ccdadf1aSMark Johnston 			unp_pcb_unlock_pair(unp, unp2);
1088b36871afSMark Johnston 			error = EPIPE;
1089b36871afSMark Johnston 			break;
109075a67bf3SMatt Macy 		}
109175a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
109275a67bf3SMatt Macy 		if ((so2 = unp2->unp_socket) == NULL) {
109375a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp2);
109475a67bf3SMatt Macy 			error = ENOTCONN;
109575a67bf3SMatt Macy 			break;
109675a67bf3SMatt Macy 		}
1097a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
1098f3f49bbbSRobert Watson 		if (unp2->unp_flags & UNP_WANTCRED) {
10996a2989fdSMatthew N. Dodd 			/*
1100716963cbSGleb Smirnoff 			 * Credentials are passed only once on SOCK_STREAM
1101716963cbSGleb Smirnoff 			 * and SOCK_SEQPACKET.
11026a2989fdSMatthew N. Dodd 			 */
1103f3f49bbbSRobert Watson 			unp2->unp_flags &= ~UNP_WANTCRED;
11046a2989fdSMatthew N. Dodd 			control = unp_addsockcred(td, control);
11056a2989fdSMatthew N. Dodd 		}
11065b0480f2SMark Johnston 
1107df8bae1dSRodney W. Grimes 		/*
11085b0480f2SMark Johnston 		 * Send to paired receive port and wake up readers.  Don't
11095b0480f2SMark Johnston 		 * check for space available in the receive buffer if we're
11105b0480f2SMark Johnston 		 * attaching ancillary data; Unix domain sockets only check
11115b0480f2SMark Johnston 		 * for space in the sending sockbuf, and that check is
11125b0480f2SMark Johnston 		 * performed one level up the stack.  At that level we cannot
11135b0480f2SMark Johnston 		 * precisely account for the amount of buffer space used
11145b0480f2SMark Johnston 		 * (e.g., because control messages are not yet internalized).
1115df8bae1dSRodney W. Grimes 		 */
111684d61770SRobert Watson 		switch (so->so_type) {
111784d61770SRobert Watson 		case SOCK_STREAM:
1118fc3fcacfSRobert Watson 			if (control != NULL) {
11195b0480f2SMark Johnston 				sbappendcontrol_locked(&so2->so_rcv, m,
112025f4ddfbSMark Johnston 				    control, flags);
1121fc3fcacfSRobert Watson 				control = NULL;
1122e7c33e29SRobert Watson 			} else
1123829fae90SGleb Smirnoff 				sbappend_locked(&so2->so_rcv, m, flags);
112484d61770SRobert Watson 			break;
112584d61770SRobert Watson 
1126b36871afSMark Johnston 		case SOCK_SEQPACKET:
11278de34a88SAlan Somers 			if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1128b36871afSMark Johnston 			    &sun_noname, m, control))
112984d61770SRobert Watson 				control = NULL;
113084d61770SRobert Watson 			break;
113184d61770SRobert Watson 		}
113284d61770SRobert Watson 
1133c2090e73SAlan Somers 		mbcnt = so2->so_rcv.sb_mbcnt;
11342b21d0e8SGleb Smirnoff 		sbcc = sbavail(&so2->so_rcv);
11352b21d0e8SGleb Smirnoff 		if (sbcc)
1136337cc6b6SRobert Watson 			sorwakeup_locked(so2);
11372b21d0e8SGleb Smirnoff 		else
11382b21d0e8SGleb Smirnoff 			SOCKBUF_UNLOCK(&so2->so_rcv);
1139337cc6b6SRobert Watson 
1140c2090e73SAlan Somers 		/*
1141c2090e73SAlan Somers 		 * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1142c2090e73SAlan Somers 		 * it would be possible for uipc_rcvd to be called at this
1143c2090e73SAlan Somers 		 * point, drain the receiving sockbuf, clear SB_STOP, and then
1144c2090e73SAlan Somers 		 * we would set SB_STOP below.  That could lead to an empty
1145c2090e73SAlan Somers 		 * sockbuf having SB_STOP set
1146c2090e73SAlan Somers 		 */
1147337cc6b6SRobert Watson 		SOCKBUF_LOCK(&so->so_snd);
1148c2090e73SAlan Somers 		if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1149c2090e73SAlan Somers 			so->so_snd.sb_flags |= SB_STOP;
11507abe2ac2SAlan Cox 		SOCKBUF_UNLOCK(&so->so_snd);
1151e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1152fc3fcacfSRobert Watson 		m = NULL;
1153df8bae1dSRodney W. Grimes 		break;
1154df8bae1dSRodney W. Grimes 	}
1155a29f300eSGarrett Wollman 
11566b8fda4dSGarrett Wollman 	/*
115760a5ef26SRobert Watson 	 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
11586b8fda4dSGarrett Wollman 	 */
1159a29f300eSGarrett Wollman 	if (flags & PRUS_EOF) {
1160ede6e136SRobert Watson 		UNP_PCB_LOCK(unp);
11616b8fda4dSGarrett Wollman 		socantsendmore(so);
11626b8fda4dSGarrett Wollman 		unp_shutdown(unp);
1163e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
1164ede6e136SRobert Watson 	}
1165fc3fcacfSRobert Watson 	if (control != NULL && error != 0)
116699ab95dbSMark Johnston 		unp_dispose_mbuf(control);
1167bd508d39SDon Lewis 
1168a29f300eSGarrett Wollman release:
1169fc3fcacfSRobert Watson 	if (control != NULL)
1170a29f300eSGarrett Wollman 		m_freem(control);
1171100db364SGleb Smirnoff 	/*
1172100db364SGleb Smirnoff 	 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1173100db364SGleb Smirnoff 	 * for freeing memory.
1174100db364SGleb Smirnoff 	 */
1175100db364SGleb Smirnoff 	if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1176a29f300eSGarrett Wollman 		m_freem(m);
1177e5aeaa0cSDag-Erling Smørgrav 	return (error);
1178a29f300eSGarrett Wollman }
1179df8bae1dSRodney W. Grimes 
1180a50b1900SMark Johnston static bool
1181a50b1900SMark Johnston uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1182a50b1900SMark Johnston {
1183a50b1900SMark Johnston 	struct mbuf *mb, *n;
1184a50b1900SMark Johnston 	struct sockbuf *sb;
1185a50b1900SMark Johnston 
1186a50b1900SMark Johnston 	SOCK_LOCK(so);
1187a50b1900SMark Johnston 	if (SOLISTENING(so)) {
1188a50b1900SMark Johnston 		SOCK_UNLOCK(so);
1189a50b1900SMark Johnston 		return (false);
1190a50b1900SMark Johnston 	}
1191a50b1900SMark Johnston 	mb = NULL;
1192a50b1900SMark Johnston 	sb = &so->so_rcv;
1193a50b1900SMark Johnston 	SOCKBUF_LOCK(sb);
1194a50b1900SMark Johnston 	if (sb->sb_fnrdy != NULL) {
1195a50b1900SMark Johnston 		for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1196a50b1900SMark Johnston 			if (mb == m) {
1197a50b1900SMark Johnston 				*errorp = sbready(sb, m, count);
1198a50b1900SMark Johnston 				break;
1199a50b1900SMark Johnston 			}
1200a50b1900SMark Johnston 			mb = mb->m_next;
1201a50b1900SMark Johnston 			if (mb == NULL) {
1202a50b1900SMark Johnston 				mb = n;
12031b778ba2SMark Johnston 				if (mb != NULL)
1204a50b1900SMark Johnston 					n = mb->m_nextpkt;
1205a50b1900SMark Johnston 			}
1206a50b1900SMark Johnston 		}
1207a50b1900SMark Johnston 	}
1208a50b1900SMark Johnston 	SOCKBUF_UNLOCK(sb);
1209a50b1900SMark Johnston 	SOCK_UNLOCK(so);
1210a50b1900SMark Johnston 	return (mb != NULL);
1211a50b1900SMark Johnston }
1212a50b1900SMark Johnston 
1213a29f300eSGarrett Wollman static int
1214c80ea19bSGleb Smirnoff uipc_ready(struct socket *so, struct mbuf *m, int count)
1215c80ea19bSGleb Smirnoff {
1216c80ea19bSGleb Smirnoff 	struct unpcb *unp, *unp2;
1217c80ea19bSGleb Smirnoff 	struct socket *so2;
1218a50b1900SMark Johnston 	int error, i;
1219c80ea19bSGleb Smirnoff 
1220c80ea19bSGleb Smirnoff 	unp = sotounpcb(so);
1221c80ea19bSGleb Smirnoff 
1222a50b1900SMark Johnston 	KASSERT(so->so_type == SOCK_STREAM,
1223a50b1900SMark Johnston 	    ("%s: unexpected socket type for %p", __func__, so));
1224a50b1900SMark Johnston 
1225a62b4665SMatt Macy 	UNP_PCB_LOCK(unp);
1226*ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1227a62b4665SMatt Macy 		UNP_PCB_UNLOCK(unp);
1228c80ea19bSGleb Smirnoff 		so2 = unp2->unp_socket;
1229c80ea19bSGleb Smirnoff 		SOCKBUF_LOCK(&so2->so_rcv);
1230c80ea19bSGleb Smirnoff 		if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1231c80ea19bSGleb Smirnoff 			sorwakeup_locked(so2);
1232c80ea19bSGleb Smirnoff 		else
1233c80ea19bSGleb Smirnoff 			SOCKBUF_UNLOCK(&so2->so_rcv);
1234c80ea19bSGleb Smirnoff 		UNP_PCB_UNLOCK(unp2);
1235c80ea19bSGleb Smirnoff 		return (error);
1236*ccdadf1aSMark Johnston 	}
1237*ccdadf1aSMark Johnston 	UNP_PCB_UNLOCK(unp);
1238a50b1900SMark Johnston 
1239a50b1900SMark Johnston 	/*
1240a50b1900SMark Johnston 	 * The receiving socket has been disconnected, but may still be valid.
1241a50b1900SMark Johnston 	 * In this case, the now-ready mbufs are still present in its socket
1242a50b1900SMark Johnston 	 * buffer, so perform an exhaustive search before giving up and freeing
1243a50b1900SMark Johnston 	 * the mbufs.
1244a50b1900SMark Johnston 	 */
1245a50b1900SMark Johnston 	UNP_LINK_RLOCK();
1246a50b1900SMark Johnston 	LIST_FOREACH(unp, &unp_shead, unp_link) {
1247a50b1900SMark Johnston 		if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1248a50b1900SMark Johnston 			break;
1249a50b1900SMark Johnston 	}
1250a50b1900SMark Johnston 	UNP_LINK_RUNLOCK();
1251a50b1900SMark Johnston 
1252a50b1900SMark Johnston 	if (unp == NULL) {
1253a50b1900SMark Johnston 		for (i = 0; i < count; i++)
1254a62b4665SMatt Macy 			m = m_free(m);
1255a50b1900SMark Johnston 		error = ECONNRESET;
1256a50b1900SMark Johnston 	}
1257a50b1900SMark Johnston 	return (error);
1258c80ea19bSGleb Smirnoff }
1259c80ea19bSGleb Smirnoff 
1260c80ea19bSGleb Smirnoff static int
1261a29f300eSGarrett Wollman uipc_sense(struct socket *so, struct stat *sb)
1262a29f300eSGarrett Wollman {
1263c2090e73SAlan Somers 	struct unpcb *unp;
1264a29f300eSGarrett Wollman 
126540f2ac28SRobert Watson 	unp = sotounpcb(so);
12664d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1267e7c33e29SRobert Watson 
1268a29f300eSGarrett Wollman 	sb->st_blksize = so->so_snd.sb_hiwat;
1269f3732fd1SPoul-Henning Kamp 	sb->st_dev = NODEV;
1270a29f300eSGarrett Wollman 	sb->st_ino = unp->unp_ino;
1271df8bae1dSRodney W. Grimes 	return (0);
1272a29f300eSGarrett Wollman }
1273df8bae1dSRodney W. Grimes 
1274a29f300eSGarrett Wollman static int
1275a29f300eSGarrett Wollman uipc_shutdown(struct socket *so)
1276a29f300eSGarrett Wollman {
127740f2ac28SRobert Watson 	struct unpcb *unp;
1278df8bae1dSRodney W. Grimes 
127940f2ac28SRobert Watson 	unp = sotounpcb(so);
12804d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1281e7c33e29SRobert Watson 
1282e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1283a29f300eSGarrett Wollman 	socantsendmore(so);
1284a29f300eSGarrett Wollman 	unp_shutdown(unp);
1285e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1286e5aeaa0cSDag-Erling Smørgrav 	return (0);
1287a29f300eSGarrett Wollman }
1288df8bae1dSRodney W. Grimes 
1289a29f300eSGarrett Wollman static int
129057bf258eSGarrett Wollman uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1291a29f300eSGarrett Wollman {
129240f2ac28SRobert Watson 	struct unpcb *unp;
12930d9ce3a1SRobert Watson 	const struct sockaddr *sa;
1294a29f300eSGarrett Wollman 
12954d4b555eSRobert Watson 	unp = sotounpcb(so);
12964d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1297e7c33e29SRobert Watson 
12980d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1299e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1300fc3fcacfSRobert Watson 	if (unp->unp_addr != NULL)
13010d9ce3a1SRobert Watson 		sa = (struct sockaddr *) unp->unp_addr;
130283f3198bSThomas Moestl 	else
13030d9ce3a1SRobert Watson 		sa = &sun_noname;
13040d9ce3a1SRobert Watson 	bcopy(sa, *nam, sa->sa_len);
1305e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1306e5aeaa0cSDag-Erling Smørgrav 	return (0);
1307df8bae1dSRodney W. Grimes }
1308a29f300eSGarrett Wollman 
1309fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram = {
1310756d52a1SPoul-Henning Kamp 	.pru_abort = 		uipc_abort,
1311756d52a1SPoul-Henning Kamp 	.pru_accept =		uipc_accept,
1312756d52a1SPoul-Henning Kamp 	.pru_attach =		uipc_attach,
1313756d52a1SPoul-Henning Kamp 	.pru_bind =		uipc_bind,
13147493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1315756d52a1SPoul-Henning Kamp 	.pru_connect =		uipc_connect,
13167493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1317756d52a1SPoul-Henning Kamp 	.pru_connect2 =		uipc_connect2,
1318756d52a1SPoul-Henning Kamp 	.pru_detach =		uipc_detach,
1319756d52a1SPoul-Henning Kamp 	.pru_disconnect =	uipc_disconnect,
1320756d52a1SPoul-Henning Kamp 	.pru_listen =		uipc_listen,
1321756d52a1SPoul-Henning Kamp 	.pru_peeraddr =		uipc_peeraddr,
1322756d52a1SPoul-Henning Kamp 	.pru_rcvd =		uipc_rcvd,
1323756d52a1SPoul-Henning Kamp 	.pru_send =		uipc_send,
1324756d52a1SPoul-Henning Kamp 	.pru_sense =		uipc_sense,
1325756d52a1SPoul-Henning Kamp 	.pru_shutdown =		uipc_shutdown,
1326756d52a1SPoul-Henning Kamp 	.pru_sockaddr =		uipc_sockaddr,
1327fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_dgram,
1328fa9402f2SRobert Watson 	.pru_close =		uipc_close,
1329fa9402f2SRobert Watson };
1330fa9402f2SRobert Watson 
133184d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket = {
133284d61770SRobert Watson 	.pru_abort =		uipc_abort,
133384d61770SRobert Watson 	.pru_accept =		uipc_accept,
133484d61770SRobert Watson 	.pru_attach =		uipc_attach,
133584d61770SRobert Watson 	.pru_bind =		uipc_bind,
13367493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
133784d61770SRobert Watson 	.pru_connect =		uipc_connect,
13387493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
133984d61770SRobert Watson 	.pru_connect2 =		uipc_connect2,
134084d61770SRobert Watson 	.pru_detach =		uipc_detach,
134184d61770SRobert Watson 	.pru_disconnect =	uipc_disconnect,
134284d61770SRobert Watson 	.pru_listen =		uipc_listen,
134384d61770SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
134484d61770SRobert Watson 	.pru_rcvd =		uipc_rcvd,
134584d61770SRobert Watson 	.pru_send =		uipc_send,
134684d61770SRobert Watson 	.pru_sense =		uipc_sense,
134784d61770SRobert Watson 	.pru_shutdown =		uipc_shutdown,
134884d61770SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
134984d61770SRobert Watson 	.pru_soreceive =	soreceive_generic,	/* XXX: or...? */
135084d61770SRobert Watson 	.pru_close =		uipc_close,
135184d61770SRobert Watson };
135284d61770SRobert Watson 
1353fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_stream = {
1354fa9402f2SRobert Watson 	.pru_abort = 		uipc_abort,
1355fa9402f2SRobert Watson 	.pru_accept =		uipc_accept,
1356fa9402f2SRobert Watson 	.pru_attach =		uipc_attach,
1357fa9402f2SRobert Watson 	.pru_bind =		uipc_bind,
13587493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1359fa9402f2SRobert Watson 	.pru_connect =		uipc_connect,
13607493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1361fa9402f2SRobert Watson 	.pru_connect2 =		uipc_connect2,
1362fa9402f2SRobert Watson 	.pru_detach =		uipc_detach,
1363fa9402f2SRobert Watson 	.pru_disconnect =	uipc_disconnect,
1364fa9402f2SRobert Watson 	.pru_listen =		uipc_listen,
1365fa9402f2SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
1366fa9402f2SRobert Watson 	.pru_rcvd =		uipc_rcvd,
1367fa9402f2SRobert Watson 	.pru_send =		uipc_send,
1368c80ea19bSGleb Smirnoff 	.pru_ready =		uipc_ready,
1369fa9402f2SRobert Watson 	.pru_sense =		uipc_sense,
1370fa9402f2SRobert Watson 	.pru_shutdown =		uipc_shutdown,
1371fa9402f2SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
1372fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_generic,
1373a152f8a3SRobert Watson 	.pru_close =		uipc_close,
1374a29f300eSGarrett Wollman };
1375df8bae1dSRodney W. Grimes 
13760b36cd25SRobert Watson static int
1377892af6b9SRobert Watson uipc_ctloutput(struct socket *so, struct sockopt *sopt)
13780c1bb4fbSDima Dorfman {
137940f2ac28SRobert Watson 	struct unpcb *unp;
13800d9ce3a1SRobert Watson 	struct xucred xu;
13816a2989fdSMatthew N. Dodd 	int error, optval;
13826a2989fdSMatthew N. Dodd 
13836e0c8e1aSKonstantin Belousov 	if (sopt->sopt_level != SOL_LOCAL)
138496a041b5SMatthew N. Dodd 		return (EINVAL);
138596a041b5SMatthew N. Dodd 
13866a2989fdSMatthew N. Dodd 	unp = sotounpcb(so);
13874d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
13886a2989fdSMatthew N. Dodd 	error = 0;
13890c1bb4fbSDima Dorfman 	switch (sopt->sopt_dir) {
13900c1bb4fbSDima Dorfman 	case SOPT_GET:
13910c1bb4fbSDima Dorfman 		switch (sopt->sopt_name) {
13920c1bb4fbSDima Dorfman 		case LOCAL_PEERCRED:
1393e7c33e29SRobert Watson 			UNP_PCB_LOCK(unp);
13940c1bb4fbSDima Dorfman 			if (unp->unp_flags & UNP_HAVEPC)
13950d9ce3a1SRobert Watson 				xu = unp->unp_peercred;
13960c1bb4fbSDima Dorfman 			else {
13970c1bb4fbSDima Dorfman 				if (so->so_type == SOCK_STREAM)
13980c1bb4fbSDima Dorfman 					error = ENOTCONN;
13990c1bb4fbSDima Dorfman 				else
14000c1bb4fbSDima Dorfman 					error = EINVAL;
14010c1bb4fbSDima Dorfman 			}
1402e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
14030d9ce3a1SRobert Watson 			if (error == 0)
14040d9ce3a1SRobert Watson 				error = sooptcopyout(sopt, &xu, sizeof(xu));
14050c1bb4fbSDima Dorfman 			break;
1406e7c33e29SRobert Watson 
14076a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
1408a6357845SRobert Watson 			/* Unlocked read. */
14096a2989fdSMatthew N. Dodd 			optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
14106a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14116a2989fdSMatthew N. Dodd 			break;
1412e7c33e29SRobert Watson 
14136a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
1414a6357845SRobert Watson 			/* Unlocked read. */
14156a2989fdSMatthew N. Dodd 			optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
14166a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14176a2989fdSMatthew N. Dodd 			break;
1418e7c33e29SRobert Watson 
14190c1bb4fbSDima Dorfman 		default:
14200c1bb4fbSDima Dorfman 			error = EOPNOTSUPP;
14210c1bb4fbSDima Dorfman 			break;
14220c1bb4fbSDima Dorfman 		}
14230c1bb4fbSDima Dorfman 		break;
1424e7c33e29SRobert Watson 
14250c1bb4fbSDima Dorfman 	case SOPT_SET:
14266a2989fdSMatthew N. Dodd 		switch (sopt->sopt_name) {
14276a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
14286a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
14296a2989fdSMatthew N. Dodd 			error = sooptcopyin(sopt, &optval, sizeof(optval),
14306a2989fdSMatthew N. Dodd 					    sizeof(optval));
14316a2989fdSMatthew N. Dodd 			if (error)
14326a2989fdSMatthew N. Dodd 				break;
14336a2989fdSMatthew N. Dodd 
1434e7c33e29SRobert Watson #define	OPTSET(bit) do {						\
1435e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);						\
14366a2989fdSMatthew N. Dodd 	if (optval)							\
14376a2989fdSMatthew N. Dodd 		unp->unp_flags |= bit;					\
14386a2989fdSMatthew N. Dodd 	else								\
1439e7c33e29SRobert Watson 		unp->unp_flags &= ~bit;					\
1440e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);						\
1441e7c33e29SRobert Watson } while (0)
14426a2989fdSMatthew N. Dodd 
14436a2989fdSMatthew N. Dodd 			switch (sopt->sopt_name) {
14446a2989fdSMatthew N. Dodd 			case LOCAL_CREDS:
14456a2989fdSMatthew N. Dodd 				OPTSET(UNP_WANTCRED);
14466a2989fdSMatthew N. Dodd 				break;
1447e7c33e29SRobert Watson 
14486a2989fdSMatthew N. Dodd 			case LOCAL_CONNWAIT:
14496a2989fdSMatthew N. Dodd 				OPTSET(UNP_CONNWAIT);
14506a2989fdSMatthew N. Dodd 				break;
1451e7c33e29SRobert Watson 
14526a2989fdSMatthew N. Dodd 			default:
14536a2989fdSMatthew N. Dodd 				break;
14546a2989fdSMatthew N. Dodd 			}
14556a2989fdSMatthew N. Dodd 			break;
14566a2989fdSMatthew N. Dodd #undef	OPTSET
14576a2989fdSMatthew N. Dodd 		default:
14586a2989fdSMatthew N. Dodd 			error = ENOPROTOOPT;
14596a2989fdSMatthew N. Dodd 			break;
14606a2989fdSMatthew N. Dodd 		}
1461abb886faSMatthew N. Dodd 		break;
1462e7c33e29SRobert Watson 
14630c1bb4fbSDima Dorfman 	default:
14640c1bb4fbSDima Dorfman 		error = EOPNOTSUPP;
14650c1bb4fbSDima Dorfman 		break;
14660c1bb4fbSDima Dorfman 	}
14670c1bb4fbSDima Dorfman 	return (error);
14680c1bb4fbSDima Dorfman }
14690c1bb4fbSDima Dorfman 
1470f708ef1bSPoul-Henning Kamp static int
1471892af6b9SRobert Watson unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1472df8bae1dSRodney W. Grimes {
14737493f24eSPawel Jakub Dawidek 
14747493f24eSPawel Jakub Dawidek 	return (unp_connectat(AT_FDCWD, so, nam, td));
14757493f24eSPawel Jakub Dawidek }
14767493f24eSPawel Jakub Dawidek 
14777493f24eSPawel Jakub Dawidek static int
14787493f24eSPawel Jakub Dawidek unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
14797493f24eSPawel Jakub Dawidek     struct thread *td)
14807493f24eSPawel Jakub Dawidek {
1481ed92e1c7SMark Johnston 	struct mtx *vplock;
1482ed92e1c7SMark Johnston 	struct sockaddr_un *soun;
1483892af6b9SRobert Watson 	struct vnode *vp;
1484779f106aSGleb Smirnoff 	struct socket *so2;
1485b295bdcdSRobert Watson 	struct unpcb *unp, *unp2, *unp3;
1486df8bae1dSRodney W. Grimes 	struct nameidata nd;
148757bf258eSGarrett Wollman 	char buf[SOCK_MAXADDRLEN];
14880d9ce3a1SRobert Watson 	struct sockaddr *sa;
14897008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
1490*ccdadf1aSMark Johnston 	int error, len;
1491ed92e1c7SMark Johnston 	bool connreq;
14920d9ce3a1SRobert Watson 
1493cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
1494cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
1495a06534c3SBjoern A. Zeeb 	if (nam->sa_len > sizeof(struct sockaddr_un))
1496a06534c3SBjoern A. Zeeb 		return (EINVAL);
149757bf258eSGarrett Wollman 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
149857bf258eSGarrett Wollman 	if (len <= 0)
1499e5aeaa0cSDag-Erling Smørgrav 		return (EINVAL);
1500ed92e1c7SMark Johnston 	soun = (struct sockaddr_un *)nam;
15017928893dSEd Maste 	bcopy(soun->sun_path, buf, len);
15027928893dSEd Maste 	buf[len] = 0;
1503e7c33e29SRobert Watson 
150475a67bf3SMatt Macy 	unp = sotounpcb(so);
1505e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1506*ccdadf1aSMark Johnston 	for (;;) {
1507*ccdadf1aSMark Johnston 		/*
1508*ccdadf1aSMark Johnston 		 * Wait for connection state to stabilize.  If a connection
1509*ccdadf1aSMark Johnston 		 * already exists, give up.  For datagram sockets, which permit
1510*ccdadf1aSMark Johnston 		 * multiple consecutive connect(2) calls, upper layers are
1511*ccdadf1aSMark Johnston 		 * responsible for disconnecting in advance of a subsequent
1512*ccdadf1aSMark Johnston 		 * connect(2), but this is not synchronized with PCB connection
1513*ccdadf1aSMark Johnston 		 * state.
1514*ccdadf1aSMark Johnston 		 *
1515*ccdadf1aSMark Johnston 		 * Also make sure that no threads are currently attempting to
1516*ccdadf1aSMark Johnston 		 * lock the peer socket, to ensure that unp_conn cannot
1517*ccdadf1aSMark Johnston 		 * transition between two valid sockets while locks are dropped.
1518*ccdadf1aSMark Johnston 		 */
1519*ccdadf1aSMark Johnston 		if (unp->unp_conn != NULL) {
1520*ccdadf1aSMark Johnston 			UNP_PCB_UNLOCK(unp);
1521*ccdadf1aSMark Johnston 			return (EISCONN);
1522*ccdadf1aSMark Johnston 		}
1523*ccdadf1aSMark Johnston 		if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1524e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
15254f1f0ef5SRobert Watson 			return (EALREADY);
15264f1f0ef5SRobert Watson 		}
1527*ccdadf1aSMark Johnston 		if (unp->unp_pairbusy > 0) {
1528*ccdadf1aSMark Johnston 			unp->unp_flags |= UNP_WAITING;
1529*ccdadf1aSMark Johnston 			mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1530*ccdadf1aSMark Johnston 			continue;
1531*ccdadf1aSMark Johnston 		}
1532*ccdadf1aSMark Johnston 		break;
1533*ccdadf1aSMark Johnston 	}
153405102f04SRobert Watson 	unp->unp_flags |= UNP_CONNECTING;
1535e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1536e7c33e29SRobert Watson 
1537ed92e1c7SMark Johnston 	connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1538ed92e1c7SMark Johnston 	if (connreq)
15390d9ce3a1SRobert Watson 		sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1540ed92e1c7SMark Johnston 	else
1541ed92e1c7SMark Johnston 		sa = NULL;
15427493f24eSPawel Jakub Dawidek 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
15437008be5bSPawel Jakub Dawidek 	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1544797f2d22SPoul-Henning Kamp 	error = namei(&nd);
1545797f2d22SPoul-Henning Kamp 	if (error)
15460d9ce3a1SRobert Watson 		vp = NULL;
15470d9ce3a1SRobert Watson 	else
1548df8bae1dSRodney W. Grimes 		vp = nd.ni_vp;
15490d9ce3a1SRobert Watson 	ASSERT_VOP_LOCKED(vp, "unp_connect");
1550762e6b85SEivind Eklund 	NDFREE(&nd, NDF_ONLY_PNBUF);
15510d9ce3a1SRobert Watson 	if (error)
15520d9ce3a1SRobert Watson 		goto bad;
15530d9ce3a1SRobert Watson 
1554df8bae1dSRodney W. Grimes 	if (vp->v_type != VSOCK) {
1555df8bae1dSRodney W. Grimes 		error = ENOTSOCK;
1556df8bae1dSRodney W. Grimes 		goto bad;
1557df8bae1dSRodney W. Grimes 	}
15586fac927cSRobert Watson #ifdef MAC
155930d239bcSRobert Watson 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
15606fac927cSRobert Watson 	if (error)
15616fac927cSRobert Watson 		goto bad;
15626fac927cSRobert Watson #endif
1563a854ed98SJohn Baldwin 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1564797f2d22SPoul-Henning Kamp 	if (error)
1565df8bae1dSRodney W. Grimes 		goto bad;
1566e7c33e29SRobert Watson 
1567b295bdcdSRobert Watson 	unp = sotounpcb(so);
15684d4b555eSRobert Watson 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1569e7c33e29SRobert Watson 
157075a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
157175a67bf3SMatt Macy 	mtx_lock(vplock);
15720c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp2);
15730c3c207fSGleb Smirnoff 	if (unp2 == NULL) {
1574df8bae1dSRodney W. Grimes 		error = ECONNREFUSED;
15752260c03dSRobert Watson 		goto bad2;
1576df8bae1dSRodney W. Grimes 	}
15770c3c207fSGleb Smirnoff 	so2 = unp2->unp_socket;
1578df8bae1dSRodney W. Grimes 	if (so->so_type != so2->so_type) {
1579df8bae1dSRodney W. Grimes 		error = EPROTOTYPE;
15802260c03dSRobert Watson 		goto bad2;
1581df8bae1dSRodney W. Grimes 	}
1582ed92e1c7SMark Johnston 	if (connreq) {
1583e7c33e29SRobert Watson 		if (so2->so_options & SO_ACCEPTCONN) {
15841fb51a12SBjoern A. Zeeb 			CURVNET_SET(so2->so_vnet);
1585779f106aSGleb Smirnoff 			so2 = sonewconn(so2, 0);
15861fb51a12SBjoern A. Zeeb 			CURVNET_RESTORE();
1587e7c33e29SRobert Watson 		} else
1588779f106aSGleb Smirnoff 			so2 = NULL;
1589779f106aSGleb Smirnoff 		if (so2 == NULL) {
1590df8bae1dSRodney W. Grimes 			error = ECONNREFUSED;
1591cb8f450bSMatt Macy 			goto bad2;
1592df8bae1dSRodney W. Grimes 		}
1593779f106aSGleb Smirnoff 		unp3 = sotounpcb(so2);
15944820bf6aSMark Johnston 		unp_pcb_lock_pair(unp2, unp3);
15950d9ce3a1SRobert Watson 		if (unp2->unp_addr != NULL) {
15960d9ce3a1SRobert Watson 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
15970d9ce3a1SRobert Watson 			unp3->unp_addr = (struct sockaddr_un *) sa;
15980d9ce3a1SRobert Watson 			sa = NULL;
15990d9ce3a1SRobert Watson 		}
1600b523ec24SRobert Watson 
1601da446550SAlan Somers 		unp_copy_peercred(td, unp3, unp, unp2);
1602b523ec24SRobert Watson 
1603e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1604779f106aSGleb Smirnoff 		unp2 = unp3;
1605*ccdadf1aSMark Johnston 
1606*ccdadf1aSMark Johnston 		/*
1607*ccdadf1aSMark Johnston 		 * It is safe to block on the PCB lock here since unp2 is
1608*ccdadf1aSMark Johnston 		 * nascent and cannot be connected to any other sockets.
1609*ccdadf1aSMark Johnston 		 */
1610*ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp);
1611335654d7SRobert Watson #ifdef MAC
1612779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so, so2);
1613779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so2, so);
1614335654d7SRobert Watson #endif
1615a3a73490SMatt Macy 	} else {
16164820bf6aSMark Johnston 		unp_pcb_lock_pair(unp, unp2);
1617a3a73490SMatt Macy 	}
1618779f106aSGleb Smirnoff 	KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1619779f106aSGleb Smirnoff 	    sotounpcb(so2) == unp2,
1620779f106aSGleb Smirnoff 	    ("%s: unp2 %p so2 %p", __func__, unp2, so2));
16216a2989fdSMatthew N. Dodd 	error = unp_connect2(so, so2, PRU_CONNECT);
16224820bf6aSMark Johnston 	unp_pcb_unlock_pair(unp, unp2);
16230d9ce3a1SRobert Watson bad2:
162475a67bf3SMatt Macy 	mtx_unlock(vplock);
1625df8bae1dSRodney W. Grimes bad:
162675a67bf3SMatt Macy 	if (vp != NULL) {
1627df8bae1dSRodney W. Grimes 		vput(vp);
162875a67bf3SMatt Macy 	}
16290d9ce3a1SRobert Watson 	free(sa, M_SONAME);
1630e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1631*ccdadf1aSMark Johnston 	KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1632*ccdadf1aSMark Johnston 	    ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
16334f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_CONNECTING;
1634e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1635df8bae1dSRodney W. Grimes 	return (error);
1636df8bae1dSRodney W. Grimes }
1637df8bae1dSRodney W. Grimes 
1638da446550SAlan Somers /*
1639da446550SAlan Somers  * Set socket peer credentials at connection time.
1640da446550SAlan Somers  *
1641da446550SAlan Somers  * The client's PCB credentials are copied from its process structure.  The
1642da446550SAlan Somers  * server's PCB credentials are copied from the socket on which it called
1643da446550SAlan Somers  * listen(2).  uipc_listen cached that process's credentials at the time.
1644da446550SAlan Somers  */
1645da446550SAlan Somers void
1646da446550SAlan Somers unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1647da446550SAlan Somers     struct unpcb *server_unp, struct unpcb *listen_unp)
1648da446550SAlan Somers {
1649c5afec6eSDmitry Chagin 	cru2xt(td, &client_unp->unp_peercred);
1650da446550SAlan Somers 	client_unp->unp_flags |= UNP_HAVEPC;
1651da446550SAlan Somers 
1652da446550SAlan Somers 	memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1653da446550SAlan Somers 	    sizeof(server_unp->unp_peercred));
1654da446550SAlan Somers 	server_unp->unp_flags |= UNP_HAVEPC;
1655da446550SAlan Somers 	if (listen_unp->unp_flags & UNP_WANTCRED)
1656da446550SAlan Somers 		client_unp->unp_flags |= UNP_WANTCRED;
1657da446550SAlan Somers }
1658da446550SAlan Somers 
1659db48c0d2SRobert Watson static int
16606a2989fdSMatthew N. Dodd unp_connect2(struct socket *so, struct socket *so2, int req)
1661df8bae1dSRodney W. Grimes {
1662e7c33e29SRobert Watson 	struct unpcb *unp;
1663892af6b9SRobert Watson 	struct unpcb *unp2;
1664df8bae1dSRodney W. Grimes 
1665e7c33e29SRobert Watson 	unp = sotounpcb(so);
1666e7c33e29SRobert Watson 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1667e7c33e29SRobert Watson 	unp2 = sotounpcb(so2);
1668e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1669e7c33e29SRobert Watson 
1670e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1671e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
1672*ccdadf1aSMark Johnston 	KASSERT(unp->unp_conn == NULL,
1673*ccdadf1aSMark Johnston 	    ("%s: socket %p is already connected", __func__, unp));
16740d9ce3a1SRobert Watson 
1675df8bae1dSRodney W. Grimes 	if (so2->so_type != so->so_type)
1676df8bae1dSRodney W. Grimes 		return (EPROTOTYPE);
1677df8bae1dSRodney W. Grimes 	unp->unp_conn = unp2;
167875a67bf3SMatt Macy 	unp_pcb_hold(unp2);
167975a67bf3SMatt Macy 	unp_pcb_hold(unp);
1680df8bae1dSRodney W. Grimes 	switch (so->so_type) {
1681df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
168275a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
168398271db4SGarrett Wollman 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
168475a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
1685df8bae1dSRodney W. Grimes 		soisconnected(so);
1686df8bae1dSRodney W. Grimes 		break;
1687df8bae1dSRodney W. Grimes 
1688df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
168984d61770SRobert Watson 	case SOCK_SEQPACKET:
1690*ccdadf1aSMark Johnston 		KASSERT(unp2->unp_conn == NULL,
1691*ccdadf1aSMark Johnston 		    ("%s: socket %p is already connected", __func__, unp2));
1692df8bae1dSRodney W. Grimes 		unp2->unp_conn = unp;
16936a2989fdSMatthew N. Dodd 		if (req == PRU_CONNECT &&
16946a2989fdSMatthew N. Dodd 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
16956a2989fdSMatthew N. Dodd 			soisconnecting(so);
16966a2989fdSMatthew N. Dodd 		else
1697df8bae1dSRodney W. Grimes 			soisconnected(so);
1698df8bae1dSRodney W. Grimes 		soisconnected(so2);
1699df8bae1dSRodney W. Grimes 		break;
1700df8bae1dSRodney W. Grimes 
1701df8bae1dSRodney W. Grimes 	default:
1702df8bae1dSRodney W. Grimes 		panic("unp_connect2");
1703df8bae1dSRodney W. Grimes 	}
1704df8bae1dSRodney W. Grimes 	return (0);
1705df8bae1dSRodney W. Grimes }
1706df8bae1dSRodney W. Grimes 
1707f708ef1bSPoul-Henning Kamp static void
1708e7c33e29SRobert Watson unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1709df8bae1dSRodney W. Grimes {
171075a67bf3SMatt Macy 	struct socket *so, *so2;
1711f0317f86SMark Johnston #ifdef INVARIANTS
1712f0317f86SMark Johnston 	struct unpcb *unptmp;
1713f0317f86SMark Johnston #endif
17140d9ce3a1SRobert Watson 
1715e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1716e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
1717f0317f86SMark Johnston 	KASSERT(unp->unp_conn == unp2,
1718f0317f86SMark Johnston 	    ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
1719e7c33e29SRobert Watson 
1720fc3fcacfSRobert Watson 	unp->unp_conn = NULL;
172175a67bf3SMatt Macy 	so = unp->unp_socket;
172275a67bf3SMatt Macy 	so2 = unp2->unp_socket;
1723df8bae1dSRodney W. Grimes 	switch (unp->unp_socket->so_type) {
1724df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
172575a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
1726f0317f86SMark Johnston #ifdef INVARIANTS
1727f0317f86SMark Johnston 		LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
1728f0317f86SMark Johnston 			if (unptmp == unp)
1729f0317f86SMark Johnston 				break;
1730f0317f86SMark Johnston 		}
1731f0317f86SMark Johnston 		KASSERT(unptmp != NULL,
1732f0317f86SMark Johnston 		    ("%s: %p not found in reflist of %p", __func__, unp, unp2));
1733f0317f86SMark Johnston #endif
173498271db4SGarrett Wollman 		LIST_REMOVE(unp, unp_reflink);
173575a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
173675a67bf3SMatt Macy 		if (so) {
17371b2e3b4bSRobert Watson 			SOCK_LOCK(so);
17381b2e3b4bSRobert Watson 			so->so_state &= ~SS_ISCONNECTED;
17391b2e3b4bSRobert Watson 			SOCK_UNLOCK(so);
174075a67bf3SMatt Macy 		}
1741df8bae1dSRodney W. Grimes 		break;
1742df8bae1dSRodney W. Grimes 
1743df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
174484d61770SRobert Watson 	case SOCK_SEQPACKET:
174575a67bf3SMatt Macy 		if (so)
174675a67bf3SMatt Macy 			soisdisconnected(so);
174775a67bf3SMatt Macy 		MPASS(unp2->unp_conn == unp);
1748fc3fcacfSRobert Watson 		unp2->unp_conn = NULL;
174975a67bf3SMatt Macy 		if (so2)
175075a67bf3SMatt Macy 			soisdisconnected(so2);
1751df8bae1dSRodney W. Grimes 		break;
1752df8bae1dSRodney W. Grimes 	}
1753f0317f86SMark Johnston 
1754f0317f86SMark Johnston 	if (unp == unp2) {
1755f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
1756f0317f86SMark Johnston 		if (!unp_pcb_rele(unp))
1757f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp);
1758f0317f86SMark Johnston 	} else {
1759f0317f86SMark Johnston 		if (!unp_pcb_rele(unp))
1760f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp);
1761f0317f86SMark Johnston 		if (!unp_pcb_rele(unp2))
1762f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp2);
1763f0317f86SMark Johnston 	}
1764df8bae1dSRodney W. Grimes }
1765df8bae1dSRodney W. Grimes 
17660d9ce3a1SRobert Watson /*
1767d7924b70SRobert Watson  * unp_pcblist() walks the global list of struct unpcb's to generate a
1768d7924b70SRobert Watson  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1769d7924b70SRobert Watson  * sequentially, validating the generation number on each to see if it has
1770d7924b70SRobert Watson  * been detached.  All of this is necessary because copyout() may sleep on
1771d7924b70SRobert Watson  * disk I/O.
17720d9ce3a1SRobert Watson  */
177398271db4SGarrett Wollman static int
177482d9ae4eSPoul-Henning Kamp unp_pcblist(SYSCTL_HANDLER_ARGS)
177598271db4SGarrett Wollman {
177698271db4SGarrett Wollman 	struct unpcb *unp, **unp_list;
177798271db4SGarrett Wollman 	unp_gen_t gencnt;
17788f364875SJulian Elischer 	struct xunpgen *xug;
177998271db4SGarrett Wollman 	struct unp_head *head;
17808f364875SJulian Elischer 	struct xunpcb *xu;
1781d821d364SPedro F. Giffuni 	u_int i;
17825362170dSMark Johnston 	int error, n;
178398271db4SGarrett Wollman 
178484d61770SRobert Watson 	switch ((intptr_t)arg1) {
178584d61770SRobert Watson 	case SOCK_STREAM:
178684d61770SRobert Watson 		head = &unp_shead;
178784d61770SRobert Watson 		break;
178884d61770SRobert Watson 
178984d61770SRobert Watson 	case SOCK_DGRAM:
179084d61770SRobert Watson 		head = &unp_dhead;
179184d61770SRobert Watson 		break;
179284d61770SRobert Watson 
179384d61770SRobert Watson 	case SOCK_SEQPACKET:
179484d61770SRobert Watson 		head = &unp_sphead;
179584d61770SRobert Watson 		break;
179684d61770SRobert Watson 
179784d61770SRobert Watson 	default:
1798604f19c9SRobert Watson 		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
179984d61770SRobert Watson 	}
180098271db4SGarrett Wollman 
180198271db4SGarrett Wollman 	/*
180298271db4SGarrett Wollman 	 * The process of preparing the PCB list is too time-consuming and
180398271db4SGarrett Wollman 	 * resource-intensive to repeat twice on every request.
180498271db4SGarrett Wollman 	 */
1805fc3fcacfSRobert Watson 	if (req->oldptr == NULL) {
180698271db4SGarrett Wollman 		n = unp_count;
18078f364875SJulian Elischer 		req->oldidx = 2 * (sizeof *xug)
180898271db4SGarrett Wollman 			+ (n + n/8) * sizeof(struct xunpcb);
1809e5aeaa0cSDag-Erling Smørgrav 		return (0);
181098271db4SGarrett Wollman 	}
181198271db4SGarrett Wollman 
1812fc3fcacfSRobert Watson 	if (req->newptr != NULL)
1813e5aeaa0cSDag-Erling Smørgrav 		return (EPERM);
181498271db4SGarrett Wollman 
181598271db4SGarrett Wollman 	/*
181698271db4SGarrett Wollman 	 * OK, now we're committed to doing something.
181798271db4SGarrett Wollman 	 */
181879db6fe7SMark Johnston 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1819779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
182098271db4SGarrett Wollman 	gencnt = unp_gencnt;
182198271db4SGarrett Wollman 	n = unp_count;
1822779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
182398271db4SGarrett Wollman 
18248f364875SJulian Elischer 	xug->xug_len = sizeof *xug;
18258f364875SJulian Elischer 	xug->xug_count = n;
18268f364875SJulian Elischer 	xug->xug_gen = gencnt;
18278f364875SJulian Elischer 	xug->xug_sogen = so_gencnt;
18288f364875SJulian Elischer 	error = SYSCTL_OUT(req, xug, sizeof *xug);
18298f364875SJulian Elischer 	if (error) {
18308f364875SJulian Elischer 		free(xug, M_TEMP);
1831e5aeaa0cSDag-Erling Smørgrav 		return (error);
18328f364875SJulian Elischer 	}
183398271db4SGarrett Wollman 
1834a163d034SWarner Losh 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
183598271db4SGarrett Wollman 
1836779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
18372e3c8fcbSPoul-Henning Kamp 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
18382e3c8fcbSPoul-Henning Kamp 	     unp = LIST_NEXT(unp, unp_link)) {
1839e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
18408a7d8cc6SRobert Watson 		if (unp->unp_gencnt <= gencnt) {
1841a854ed98SJohn Baldwin 			if (cr_cansee(req->td->td_ucred,
1842e7c33e29SRobert Watson 			    unp->unp_socket->so_cred)) {
1843e7c33e29SRobert Watson 				UNP_PCB_UNLOCK(unp);
18444787fd37SPaul Saab 				continue;
1845e7c33e29SRobert Watson 			}
184698271db4SGarrett Wollman 			unp_list[i++] = unp;
184775a67bf3SMatt Macy 			unp_pcb_hold(unp);
184898271db4SGarrett Wollman 		}
1849e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
18504787fd37SPaul Saab 	}
1851779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
18521c381b19SRobert Watson 	n = i;			/* In case we lost some during malloc. */
185398271db4SGarrett Wollman 
185498271db4SGarrett Wollman 	error = 0;
1855fe2eee82SColin Percival 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
185698271db4SGarrett Wollman 	for (i = 0; i < n; i++) {
185798271db4SGarrett Wollman 		unp = unp_list[i];
1858e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
18595362170dSMark Johnston 		if (unp_pcb_rele(unp))
18605362170dSMark Johnston 			continue;
186175a67bf3SMatt Macy 
18625362170dSMark Johnston 		if (unp->unp_gencnt <= gencnt) {
18638f364875SJulian Elischer 			xu->xu_len = sizeof *xu;
18643a20f06aSBrooks Davis 			xu->xu_unpp = (uintptr_t)unp;
186598271db4SGarrett Wollman 			/*
186698271db4SGarrett Wollman 			 * XXX - need more locking here to protect against
186798271db4SGarrett Wollman 			 * connect/disconnect races for SMP.
186898271db4SGarrett Wollman 			 */
1869fc3fcacfSRobert Watson 			if (unp->unp_addr != NULL)
18708f364875SJulian Elischer 				bcopy(unp->unp_addr, &xu->xu_addr,
187198271db4SGarrett Wollman 				      unp->unp_addr->sun_len);
18720e229f34SGleb Smirnoff 			else
18730e229f34SGleb Smirnoff 				bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1874fc3fcacfSRobert Watson 			if (unp->unp_conn != NULL &&
1875fc3fcacfSRobert Watson 			    unp->unp_conn->unp_addr != NULL)
187698271db4SGarrett Wollman 				bcopy(unp->unp_conn->unp_addr,
18778f364875SJulian Elischer 				      &xu->xu_caddr,
187898271db4SGarrett Wollman 				      unp->unp_conn->unp_addr->sun_len);
18790e229f34SGleb Smirnoff 			else
18800e229f34SGleb Smirnoff 				bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
18813a20f06aSBrooks Davis 			xu->unp_vnode = (uintptr_t)unp->unp_vnode;
18823a20f06aSBrooks Davis 			xu->unp_conn = (uintptr_t)unp->unp_conn;
18833a20f06aSBrooks Davis 			xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
18843a20f06aSBrooks Davis 			xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
18850e229f34SGleb Smirnoff 			xu->unp_gencnt = unp->unp_gencnt;
18868f364875SJulian Elischer 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1887e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
18888f364875SJulian Elischer 			error = SYSCTL_OUT(req, xu, sizeof *xu);
18895362170dSMark Johnston 		} else {
1890e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
1891e7c33e29SRobert Watson 		}
18925362170dSMark Johnston 	}
18938f364875SJulian Elischer 	free(xu, M_TEMP);
189498271db4SGarrett Wollman 	if (!error) {
189598271db4SGarrett Wollman 		/*
18961c381b19SRobert Watson 		 * Give the user an updated idea of our state.  If the
18971c381b19SRobert Watson 		 * generation differs from what we told her before, she knows
18981c381b19SRobert Watson 		 * that something happened while we were processing this
18991c381b19SRobert Watson 		 * request, and it might be necessary to retry.
190098271db4SGarrett Wollman 		 */
19018f364875SJulian Elischer 		xug->xug_gen = unp_gencnt;
19028f364875SJulian Elischer 		xug->xug_sogen = so_gencnt;
19038f364875SJulian Elischer 		xug->xug_count = unp_count;
19048f364875SJulian Elischer 		error = SYSCTL_OUT(req, xug, sizeof *xug);
190598271db4SGarrett Wollman 	}
190698271db4SGarrett Wollman 	free(unp_list, M_TEMP);
19078f364875SJulian Elischer 	free(xug, M_TEMP);
1908e5aeaa0cSDag-Erling Smørgrav 	return (error);
190998271db4SGarrett Wollman }
191098271db4SGarrett Wollman 
19117029da5cSPawel Biernacki SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
19127029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19132fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
191498271db4SGarrett Wollman     "List of active local datagram sockets");
19157029da5cSPawel Biernacki SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
19167029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19172fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
191898271db4SGarrett Wollman     "List of active local stream sockets");
19192fee06f0SMatthew D Fleming SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
19207029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19212fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
192284d61770SRobert Watson     "List of active local seqpacket sockets");
192398271db4SGarrett Wollman 
1924f708ef1bSPoul-Henning Kamp static void
1925892af6b9SRobert Watson unp_shutdown(struct unpcb *unp)
1926df8bae1dSRodney W. Grimes {
1927e7c33e29SRobert Watson 	struct unpcb *unp2;
1928df8bae1dSRodney W. Grimes 	struct socket *so;
1929df8bae1dSRodney W. Grimes 
1930e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
19310d9ce3a1SRobert Watson 
1932e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
193384d61770SRobert Watson 	if ((unp->unp_socket->so_type == SOCK_STREAM ||
193484d61770SRobert Watson 	    (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1935e7c33e29SRobert Watson 		so = unp2->unp_socket;
1936e7c33e29SRobert Watson 		if (so != NULL)
1937df8bae1dSRodney W. Grimes 			socantrcvmore(so);
1938df8bae1dSRodney W. Grimes 	}
1939e7c33e29SRobert Watson }
1940df8bae1dSRodney W. Grimes 
1941f708ef1bSPoul-Henning Kamp static void
1942afc055d9SEd Schouten unp_drop(struct unpcb *unp)
1943df8bae1dSRodney W. Grimes {
1944df8bae1dSRodney W. Grimes 	struct socket *so = unp->unp_socket;
1945e7c33e29SRobert Watson 	struct unpcb *unp2;
19460d9ce3a1SRobert Watson 
1947afc055d9SEd Schouten 	/*
1948afc055d9SEd Schouten 	 * Regardless of whether the socket's peer dropped the connection
1949afc055d9SEd Schouten 	 * with this socket by aborting or disconnecting, POSIX requires
1950afc055d9SEd Schouten 	 * that ECONNRESET is returned.
1951afc055d9SEd Schouten 	 */
195275a67bf3SMatt Macy 
195375a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
195475a67bf3SMatt Macy 	if (so)
1955afc055d9SEd Schouten 		so->so_error = ECONNRESET;
1956*ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1957f0317f86SMark Johnston 		/* Last reference dropped in unp_disconnect(). */
1958f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
1959e7c33e29SRobert Watson 		unp_disconnect(unp, unp2);
1960f0317f86SMark Johnston 	} else if (!unp_pcb_rele(unp)) {
196175a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
196275a67bf3SMatt Macy 	}
1963f0317f86SMark Johnston }
1964df8bae1dSRodney W. Grimes 
19652bc21ed9SDavid Malone static void
19668cb539f1SPawel Jakub Dawidek unp_freerights(struct filedescent **fdep, int fdcount)
1967df8bae1dSRodney W. Grimes {
19682bc21ed9SDavid Malone 	struct file *fp;
19692609222aSPawel Jakub Dawidek 	int i;
1970df8bae1dSRodney W. Grimes 
197182e825c4SGleb Smirnoff 	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
197282e825c4SGleb Smirnoff 
19738cb539f1SPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
19748cb539f1SPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
19758cb539f1SPawel Jakub Dawidek 		filecaps_free(&fdep[i]->fde_caps);
19768692c025SYoshinobu Inoue 		unp_discard(fp);
1977df8bae1dSRodney W. Grimes 	}
19788cb539f1SPawel Jakub Dawidek 	free(fdep[0], M_FILECAPS);
19792bc21ed9SDavid Malone }
19802bc21ed9SDavid Malone 
19810b36cd25SRobert Watson static int
1982c2e3c52eSJilles Tjoelker unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
19832bc21ed9SDavid Malone {
19842bc21ed9SDavid Malone 	struct thread *td = curthread;		/* XXX */
19852bc21ed9SDavid Malone 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
19862bc21ed9SDavid Malone 	int i;
19872bc21ed9SDavid Malone 	int *fdp;
19882609222aSPawel Jakub Dawidek 	struct filedesc *fdesc = td->td_proc->p_fd;
1989ea31808cSMateusz Guzik 	struct filedescent **fdep;
19902bc21ed9SDavid Malone 	void *data;
19912bc21ed9SDavid Malone 	socklen_t clen = control->m_len, datalen;
19922bc21ed9SDavid Malone 	int error, newfds;
19932bc21ed9SDavid Malone 	u_int newlen;
19942bc21ed9SDavid Malone 
19953dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
19964c5bc1caSRobert Watson 
19972bc21ed9SDavid Malone 	error = 0;
19982bc21ed9SDavid Malone 	if (controlp != NULL) /* controlp == NULL => free control messages */
19992bc21ed9SDavid Malone 		*controlp = NULL;
20002bc21ed9SDavid Malone 	while (cm != NULL) {
20012bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
20022bc21ed9SDavid Malone 			error = EINVAL;
20032bc21ed9SDavid Malone 			break;
20042bc21ed9SDavid Malone 		}
20052bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
20062bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
20072bc21ed9SDavid Malone 		if (cm->cmsg_level == SOL_SOCKET
20082bc21ed9SDavid Malone 		    && cm->cmsg_type == SCM_RIGHTS) {
20092609222aSPawel Jakub Dawidek 			newfds = datalen / sizeof(*fdep);
201082e825c4SGleb Smirnoff 			if (newfds == 0)
201182e825c4SGleb Smirnoff 				goto next;
20122609222aSPawel Jakub Dawidek 			fdep = data;
20132bc21ed9SDavid Malone 
2014e2f9a08bSOlivier Houchard 			/* If we're not outputting the descriptors free them. */
20152bc21ed9SDavid Malone 			if (error || controlp == NULL) {
20162609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20172bc21ed9SDavid Malone 				goto next;
20182bc21ed9SDavid Malone 			}
20192609222aSPawel Jakub Dawidek 			FILEDESC_XLOCK(fdesc);
202060a5ef26SRobert Watson 
2021ed5b7817SJulian Elischer 			/*
20221c381b19SRobert Watson 			 * Now change each pointer to an fd in the global
20231c381b19SRobert Watson 			 * table to an integer that is the index to the local
20241c381b19SRobert Watson 			 * fd table entry that we set up to point to the
20251c381b19SRobert Watson 			 * global one we are transferring.
2026ed5b7817SJulian Elischer 			 */
20272bc21ed9SDavid Malone 			newlen = newfds * sizeof(int);
20282bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
20292bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
20302bc21ed9SDavid Malone 			if (*controlp == NULL) {
20312609222aSPawel Jakub Dawidek 				FILEDESC_XUNLOCK(fdesc);
20322bc21ed9SDavid Malone 				error = E2BIG;
20332609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20342bc21ed9SDavid Malone 				goto next;
20352bc21ed9SDavid Malone 			}
20362bc21ed9SDavid Malone 
20372bc21ed9SDavid Malone 			fdp = (int *)
20382bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2039db8f33fdSMateusz Guzik 			if (fdallocn(td, 0, fdp, newfds) != 0) {
20403331a33aSMateusz Guzik 				FILEDESC_XUNLOCK(fdesc);
2041db8f33fdSMateusz Guzik 				error = EMSGSIZE;
2042db8f33fdSMateusz Guzik 				unp_freerights(fdep, newfds);
2043db8f33fdSMateusz Guzik 				m_freem(*controlp);
2044db8f33fdSMateusz Guzik 				*controlp = NULL;
2045db8f33fdSMateusz Guzik 				goto next;
2046db8f33fdSMateusz Guzik 			}
20478cb539f1SPawel Jakub Dawidek 			for (i = 0; i < newfds; i++, fdp++) {
2048ea31808cSMateusz Guzik 				_finstall(fdesc, fdep[i]->fde_file, *fdp,
2049ea31808cSMateusz Guzik 				    (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
2050ea31808cSMateusz Guzik 				    &fdep[i]->fde_caps);
2051ea31808cSMateusz Guzik 				unp_externalize_fp(fdep[i]->fde_file);
2052df8bae1dSRodney W. Grimes 			}
2053c7902fbeSMark Johnston 
2054c7902fbeSMark Johnston 			/*
2055c7902fbeSMark Johnston 			 * The new type indicates that the mbuf data refers to
2056c7902fbeSMark Johnston 			 * kernel resources that may need to be released before
2057c7902fbeSMark Johnston 			 * the mbuf is freed.
2058c7902fbeSMark Johnston 			 */
2059c7902fbeSMark Johnston 			m_chtype(*controlp, MT_EXTCONTROL);
20602609222aSPawel Jakub Dawidek 			FILEDESC_XUNLOCK(fdesc);
20618cb539f1SPawel Jakub Dawidek 			free(fdep[0], M_FILECAPS);
20621c381b19SRobert Watson 		} else {
20631c381b19SRobert Watson 			/* We can just copy anything else across. */
20642bc21ed9SDavid Malone 			if (error || controlp == NULL)
20652bc21ed9SDavid Malone 				goto next;
20662bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, datalen,
20672bc21ed9SDavid Malone 			    cm->cmsg_type, cm->cmsg_level);
20682bc21ed9SDavid Malone 			if (*controlp == NULL) {
20692bc21ed9SDavid Malone 				error = ENOBUFS;
20702bc21ed9SDavid Malone 				goto next;
20712bc21ed9SDavid Malone 			}
20722bc21ed9SDavid Malone 			bcopy(data,
20732bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
20742bc21ed9SDavid Malone 			    datalen);
20752bc21ed9SDavid Malone 		}
20762bc21ed9SDavid Malone 		controlp = &(*controlp)->m_next;
20772bc21ed9SDavid Malone 
20782bc21ed9SDavid Malone next:
20792bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
20802bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
20812bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
20822bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
20838692c025SYoshinobu Inoue 		} else {
20842bc21ed9SDavid Malone 			clen = 0;
20852bc21ed9SDavid Malone 			cm = NULL;
20868692c025SYoshinobu Inoue 		}
20878692c025SYoshinobu Inoue 	}
20888692c025SYoshinobu Inoue 
20892bc21ed9SDavid Malone 	m_freem(control);
20902bc21ed9SDavid Malone 	return (error);
2091df8bae1dSRodney W. Grimes }
2092df8bae1dSRodney W. Grimes 
20934f590175SPaul Saab static void
20944f590175SPaul Saab unp_zone_change(void *tag)
20954f590175SPaul Saab {
20964f590175SPaul Saab 
20974f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
20984f590175SPaul Saab }
20994f590175SPaul Saab 
21005362170dSMark Johnston #ifdef INVARIANTS
21015362170dSMark Johnston static void
21025362170dSMark Johnston unp_zdtor(void *mem, int size __unused, void *arg __unused)
21035362170dSMark Johnston {
21045362170dSMark Johnston 	struct unpcb *unp;
21055362170dSMark Johnston 
21065362170dSMark Johnston 	unp = mem;
21075362170dSMark Johnston 
21085362170dSMark Johnston 	KASSERT(LIST_EMPTY(&unp->unp_refs),
21095362170dSMark Johnston 	    ("%s: unpcb %p has lingering refs", __func__, unp));
21105362170dSMark Johnston 	KASSERT(unp->unp_socket == NULL,
21115362170dSMark Johnston 	    ("%s: unpcb %p has socket backpointer", __func__, unp));
21125362170dSMark Johnston 	KASSERT(unp->unp_vnode == NULL,
21135362170dSMark Johnston 	    ("%s: unpcb %p has vnode references", __func__, unp));
21145362170dSMark Johnston 	KASSERT(unp->unp_conn == NULL,
21155362170dSMark Johnston 	    ("%s: unpcb %p is still connected", __func__, unp));
21165362170dSMark Johnston 	KASSERT(unp->unp_addr == NULL,
21175362170dSMark Johnston 	    ("%s: unpcb %p has leaked addr", __func__, unp));
21185362170dSMark Johnston }
21195362170dSMark Johnston #endif
21205362170dSMark Johnston 
21210b36cd25SRobert Watson static void
212298271db4SGarrett Wollman unp_init(void)
212398271db4SGarrett Wollman {
21245362170dSMark Johnston 	uma_dtor dtor;
21251c381b19SRobert Watson 
212621ca7b57SMarko Zec #ifdef VIMAGE
212721ca7b57SMarko Zec 	if (!IS_DEFAULT_VNET(curvnet))
212821ca7b57SMarko Zec 		return;
212921ca7b57SMarko Zec #endif
21305362170dSMark Johnston 
21315362170dSMark Johnston #ifdef INVARIANTS
21325362170dSMark Johnston 	dtor = unp_zdtor;
21335362170dSMark Johnston #else
21345362170dSMark Johnston 	dtor = NULL;
21355362170dSMark Johnston #endif
21365362170dSMark Johnston 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
213775a67bf3SMatt Macy 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
21384f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21396e0b6746SPawel Jakub Dawidek 	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
21404f590175SPaul Saab 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
21414f590175SPaul Saab 	    NULL, EVENTHANDLER_PRI_ANY);
214298271db4SGarrett Wollman 	LIST_INIT(&unp_dhead);
214398271db4SGarrett Wollman 	LIST_INIT(&unp_shead);
214484d61770SRobert Watson 	LIST_INIT(&unp_sphead);
21450cb64678SKonstantin Belousov 	SLIST_INIT(&unp_defers);
2146daee0f0bSKonstantin Belousov 	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
21470cb64678SKonstantin Belousov 	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
21483dab55bcSRobert Watson 	UNP_LINK_LOCK_INIT();
21490cb64678SKonstantin Belousov 	UNP_DEFERRED_LOCK_INIT();
215098271db4SGarrett Wollman }
215198271db4SGarrett Wollman 
215247c3450eSKonstantin Belousov static void
215347c3450eSKonstantin Belousov unp_internalize_cleanup_rights(struct mbuf *control)
215447c3450eSKonstantin Belousov {
215547c3450eSKonstantin Belousov 	struct cmsghdr *cp;
215647c3450eSKonstantin Belousov 	struct mbuf *m;
215747c3450eSKonstantin Belousov 	void *data;
215847c3450eSKonstantin Belousov 	socklen_t datalen;
215947c3450eSKonstantin Belousov 
216047c3450eSKonstantin Belousov 	for (m = control; m != NULL; m = m->m_next) {
216147c3450eSKonstantin Belousov 		cp = mtod(m, struct cmsghdr *);
216247c3450eSKonstantin Belousov 		if (cp->cmsg_level != SOL_SOCKET ||
216347c3450eSKonstantin Belousov 		    cp->cmsg_type != SCM_RIGHTS)
216447c3450eSKonstantin Belousov 			continue;
216547c3450eSKonstantin Belousov 		data = CMSG_DATA(cp);
216647c3450eSKonstantin Belousov 		datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
216747c3450eSKonstantin Belousov 		unp_freerights(data, datalen / sizeof(struct filedesc *));
216847c3450eSKonstantin Belousov 	}
216947c3450eSKonstantin Belousov }
217047c3450eSKonstantin Belousov 
2171f708ef1bSPoul-Henning Kamp static int
2172892af6b9SRobert Watson unp_internalize(struct mbuf **controlp, struct thread *td)
2173df8bae1dSRodney W. Grimes {
217447c3450eSKonstantin Belousov 	struct mbuf *control, **initial_controlp;
217547c3450eSKonstantin Belousov 	struct proc *p;
217647c3450eSKonstantin Belousov 	struct filedesc *fdesc;
2177ab15d803SSergey Kandaurov 	struct bintime *bt;
217847c3450eSKonstantin Belousov 	struct cmsghdr *cm;
21792bc21ed9SDavid Malone 	struct cmsgcred *cmcred;
21808cb539f1SPawel Jakub Dawidek 	struct filedescent *fde, **fdep, *fdev;
21812bc21ed9SDavid Malone 	struct file *fp;
21822bc21ed9SDavid Malone 	struct timeval *tv;
2183339efd75SMaxim Sobolev 	struct timespec *ts;
21842bc21ed9SDavid Malone 	void *data;
218547c3450eSKonstantin Belousov 	socklen_t clen, datalen;
2186f1cf2b9dSKonstantin Belousov 	int i, j, error, *fdp, oldfds;
21878692c025SYoshinobu Inoue 	u_int newlen;
2188df8bae1dSRodney W. Grimes 
21893dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
21904c5bc1caSRobert Watson 
219147c3450eSKonstantin Belousov 	p = td->td_proc;
219247c3450eSKonstantin Belousov 	fdesc = p->p_fd;
21932bc21ed9SDavid Malone 	error = 0;
219447c3450eSKonstantin Belousov 	control = *controlp;
219547c3450eSKonstantin Belousov 	clen = control->m_len;
21962bc21ed9SDavid Malone 	*controlp = NULL;
219747c3450eSKonstantin Belousov 	initial_controlp = controlp;
219847c3450eSKonstantin Belousov 	for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
21992bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2200de966666SMateusz Guzik 		    || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
22012bc21ed9SDavid Malone 			error = EINVAL;
22022bc21ed9SDavid Malone 			goto out;
22032bc21ed9SDavid Malone 		}
22042bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
22052bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
22062bc21ed9SDavid Malone 
22072bc21ed9SDavid Malone 		switch (cm->cmsg_type) {
22080b788fa1SBill Paul 		/*
22090b788fa1SBill Paul 		 * Fill in credential information.
22100b788fa1SBill Paul 		 */
22112bc21ed9SDavid Malone 		case SCM_CREDS:
22122bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
22132bc21ed9SDavid Malone 			    SCM_CREDS, SOL_SOCKET);
22142bc21ed9SDavid Malone 			if (*controlp == NULL) {
22152bc21ed9SDavid Malone 				error = ENOBUFS;
22162bc21ed9SDavid Malone 				goto out;
22172bc21ed9SDavid Malone 			}
22182bc21ed9SDavid Malone 			cmcred = (struct cmsgcred *)
22192bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
22200b788fa1SBill Paul 			cmcred->cmcred_pid = p->p_pid;
2221a854ed98SJohn Baldwin 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2222a854ed98SJohn Baldwin 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2223a854ed98SJohn Baldwin 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
2224a854ed98SJohn Baldwin 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
22250b788fa1SBill Paul 			    CMGROUP_MAX);
22260b788fa1SBill Paul 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
22272bc21ed9SDavid Malone 				cmcred->cmcred_groups[i] =
2228a854ed98SJohn Baldwin 				    td->td_ucred->cr_groups[i];
22292bc21ed9SDavid Malone 			break;
22300b788fa1SBill Paul 
22312bc21ed9SDavid Malone 		case SCM_RIGHTS:
22322bc21ed9SDavid Malone 			oldfds = datalen / sizeof (int);
223382e825c4SGleb Smirnoff 			if (oldfds == 0)
223482e825c4SGleb Smirnoff 				break;
2235ed5b7817SJulian Elischer 			/*
22361c381b19SRobert Watson 			 * Check that all the FDs passed in refer to legal
22371c381b19SRobert Watson 			 * files.  If not, reject the entire operation.
2238ed5b7817SJulian Elischer 			 */
22392bc21ed9SDavid Malone 			fdp = data;
22402609222aSPawel Jakub Dawidek 			FILEDESC_SLOCK(fdesc);
22416a1cf96bSMateusz Guzik 			for (i = 0; i < oldfds; i++, fdp++) {
22426a1cf96bSMateusz Guzik 				fp = fget_locked(fdesc, *fdp);
22436a1cf96bSMateusz Guzik 				if (fp == NULL) {
22442609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
22452bc21ed9SDavid Malone 					error = EBADF;
22462bc21ed9SDavid Malone 					goto out;
22472bc21ed9SDavid Malone 				}
2248e7d6662fSAlfred Perlstein 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
22492609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
2250e7d6662fSAlfred Perlstein 					error = EOPNOTSUPP;
2251e7d6662fSAlfred Perlstein 					goto out;
2252e7d6662fSAlfred Perlstein 				}
2253df8bae1dSRodney W. Grimes 			}
22545e3f7694SRobert Watson 
2255ed5b7817SJulian Elischer 			/*
22560b36cd25SRobert Watson 			 * Now replace the integer FDs with pointers to the
22572609222aSPawel Jakub Dawidek 			 * file structure and capability rights.
2258ed5b7817SJulian Elischer 			 */
22598cb539f1SPawel Jakub Dawidek 			newlen = oldfds * sizeof(fdep[0]);
22602bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
22612bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
22622bc21ed9SDavid Malone 			if (*controlp == NULL) {
22632609222aSPawel Jakub Dawidek 				FILEDESC_SUNLOCK(fdesc);
22642bc21ed9SDavid Malone 				error = E2BIG;
22652bc21ed9SDavid Malone 				goto out;
22668692c025SYoshinobu Inoue 			}
22672bc21ed9SDavid Malone 			fdp = data;
2268f1cf2b9dSKonstantin Belousov 			for (i = 0; i < oldfds; i++, fdp++) {
2269f1cf2b9dSKonstantin Belousov 				if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2270f1cf2b9dSKonstantin Belousov 					fdp = data;
2271f1cf2b9dSKonstantin Belousov 					for (j = 0; j < i; j++, fdp++) {
2272f1cf2b9dSKonstantin Belousov 						fdrop(fdesc->fd_ofiles[*fdp].
2273f1cf2b9dSKonstantin Belousov 						    fde_file, td);
2274f1cf2b9dSKonstantin Belousov 					}
2275f1cf2b9dSKonstantin Belousov 					FILEDESC_SUNLOCK(fdesc);
2276f1cf2b9dSKonstantin Belousov 					error = EBADF;
2277f1cf2b9dSKonstantin Belousov 					goto out;
2278f1cf2b9dSKonstantin Belousov 				}
2279f1cf2b9dSKonstantin Belousov 			}
2280f1cf2b9dSKonstantin Belousov 			fdp = data;
22818cb539f1SPawel Jakub Dawidek 			fdep = (struct filedescent **)
22822bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
22838cb539f1SPawel Jakub Dawidek 			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
22848cb539f1SPawel Jakub Dawidek 			    M_WAITOK);
22858cb539f1SPawel Jakub Dawidek 			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
22862609222aSPawel Jakub Dawidek 				fde = &fdesc->fd_ofiles[*fdp];
22878cb539f1SPawel Jakub Dawidek 				fdep[i] = fdev;
22888cb539f1SPawel Jakub Dawidek 				fdep[i]->fde_file = fde->fde_file;
22898cb539f1SPawel Jakub Dawidek 				filecaps_copy(&fde->fde_caps,
2290d7832811SMateusz Guzik 				    &fdep[i]->fde_caps, true);
22918cb539f1SPawel Jakub Dawidek 				unp_internalize_fp(fdep[i]->fde_file);
2292df8bae1dSRodney W. Grimes 			}
22932609222aSPawel Jakub Dawidek 			FILEDESC_SUNLOCK(fdesc);
22942bc21ed9SDavid Malone 			break;
22952bc21ed9SDavid Malone 
22962bc21ed9SDavid Malone 		case SCM_TIMESTAMP:
22972bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
22982bc21ed9SDavid Malone 			    SCM_TIMESTAMP, SOL_SOCKET);
22992bc21ed9SDavid Malone 			if (*controlp == NULL) {
23002bc21ed9SDavid Malone 				error = ENOBUFS;
23012bc21ed9SDavid Malone 				goto out;
23028692c025SYoshinobu Inoue 			}
23032bc21ed9SDavid Malone 			tv = (struct timeval *)
23042bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23052bc21ed9SDavid Malone 			microtime(tv);
23062bc21ed9SDavid Malone 			break;
23072bc21ed9SDavid Malone 
2308ab15d803SSergey Kandaurov 		case SCM_BINTIME:
2309ab15d803SSergey Kandaurov 			*controlp = sbcreatecontrol(NULL, sizeof(*bt),
2310ab15d803SSergey Kandaurov 			    SCM_BINTIME, SOL_SOCKET);
2311ab15d803SSergey Kandaurov 			if (*controlp == NULL) {
2312ab15d803SSergey Kandaurov 				error = ENOBUFS;
2313ab15d803SSergey Kandaurov 				goto out;
2314ab15d803SSergey Kandaurov 			}
2315ab15d803SSergey Kandaurov 			bt = (struct bintime *)
2316ab15d803SSergey Kandaurov 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2317ab15d803SSergey Kandaurov 			bintime(bt);
2318ab15d803SSergey Kandaurov 			break;
2319ab15d803SSergey Kandaurov 
2320339efd75SMaxim Sobolev 		case SCM_REALTIME:
2321339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2322339efd75SMaxim Sobolev 			    SCM_REALTIME, SOL_SOCKET);
2323339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2324339efd75SMaxim Sobolev 				error = ENOBUFS;
2325339efd75SMaxim Sobolev 				goto out;
2326339efd75SMaxim Sobolev 			}
2327339efd75SMaxim Sobolev 			ts = (struct timespec *)
2328339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2329339efd75SMaxim Sobolev 			nanotime(ts);
2330339efd75SMaxim Sobolev 			break;
2331339efd75SMaxim Sobolev 
2332339efd75SMaxim Sobolev 		case SCM_MONOTONIC:
2333339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2334339efd75SMaxim Sobolev 			    SCM_MONOTONIC, SOL_SOCKET);
2335339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2336339efd75SMaxim Sobolev 				error = ENOBUFS;
2337339efd75SMaxim Sobolev 				goto out;
2338339efd75SMaxim Sobolev 			}
2339339efd75SMaxim Sobolev 			ts = (struct timespec *)
2340339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2341339efd75SMaxim Sobolev 			nanouptime(ts);
2342339efd75SMaxim Sobolev 			break;
2343339efd75SMaxim Sobolev 
23442bc21ed9SDavid Malone 		default:
23452bc21ed9SDavid Malone 			error = EINVAL;
23462bc21ed9SDavid Malone 			goto out;
23472bc21ed9SDavid Malone 		}
23482bc21ed9SDavid Malone 
23494013d726SMark Johnston 		if (*controlp != NULL)
23502bc21ed9SDavid Malone 			controlp = &(*controlp)->m_next;
23512bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
23522bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
23532bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
23542bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
23552bc21ed9SDavid Malone 		} else {
23562bc21ed9SDavid Malone 			clen = 0;
23572bc21ed9SDavid Malone 			cm = NULL;
23582bc21ed9SDavid Malone 		}
23592bc21ed9SDavid Malone 	}
23602bc21ed9SDavid Malone 
23612bc21ed9SDavid Malone out:
236247c3450eSKonstantin Belousov 	if (error != 0 && initial_controlp != NULL)
236347c3450eSKonstantin Belousov 		unp_internalize_cleanup_rights(*initial_controlp);
23642bc21ed9SDavid Malone 	m_freem(control);
23652bc21ed9SDavid Malone 	return (error);
2366df8bae1dSRodney W. Grimes }
2367df8bae1dSRodney W. Grimes 
23685b950deaSRobert Watson static struct mbuf *
23696a2989fdSMatthew N. Dodd unp_addsockcred(struct thread *td, struct mbuf *control)
23706a2989fdSMatthew N. Dodd {
237170df31f4SMaxim Konovalov 	struct mbuf *m, *n, *n_prev;
23726a2989fdSMatthew N. Dodd 	struct sockcred *sc;
237370df31f4SMaxim Konovalov 	const struct cmsghdr *cm;
23746a2989fdSMatthew N. Dodd 	int ngroups;
23756a2989fdSMatthew N. Dodd 	int i;
23766a2989fdSMatthew N. Dodd 
23776a2989fdSMatthew N. Dodd 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
23786a2989fdSMatthew N. Dodd 	m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
23796a2989fdSMatthew N. Dodd 	if (m == NULL)
23806a2989fdSMatthew N. Dodd 		return (control);
23816a2989fdSMatthew N. Dodd 
23826a2989fdSMatthew N. Dodd 	sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
23836a2989fdSMatthew N. Dodd 	sc->sc_uid = td->td_ucred->cr_ruid;
23846a2989fdSMatthew N. Dodd 	sc->sc_euid = td->td_ucred->cr_uid;
23856a2989fdSMatthew N. Dodd 	sc->sc_gid = td->td_ucred->cr_rgid;
23866a2989fdSMatthew N. Dodd 	sc->sc_egid = td->td_ucred->cr_gid;
23876a2989fdSMatthew N. Dodd 	sc->sc_ngroups = ngroups;
23886a2989fdSMatthew N. Dodd 	for (i = 0; i < sc->sc_ngroups; i++)
23896a2989fdSMatthew N. Dodd 		sc->sc_groups[i] = td->td_ucred->cr_groups[i];
23906a2989fdSMatthew N. Dodd 
23916a2989fdSMatthew N. Dodd 	/*
23921c381b19SRobert Watson 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
23931c381b19SRobert Watson 	 * created SCM_CREDS control message (struct sockcred) has another
23941c381b19SRobert Watson 	 * format.
23956a2989fdSMatthew N. Dodd 	 */
239670df31f4SMaxim Konovalov 	if (control != NULL)
239770df31f4SMaxim Konovalov 		for (n = control, n_prev = NULL; n != NULL;) {
239870df31f4SMaxim Konovalov 			cm = mtod(n, struct cmsghdr *);
239970df31f4SMaxim Konovalov     			if (cm->cmsg_level == SOL_SOCKET &&
240070df31f4SMaxim Konovalov 			    cm->cmsg_type == SCM_CREDS) {
240170df31f4SMaxim Konovalov     				if (n_prev == NULL)
240270df31f4SMaxim Konovalov 					control = n->m_next;
240370df31f4SMaxim Konovalov 				else
240470df31f4SMaxim Konovalov 					n_prev->m_next = n->m_next;
240570df31f4SMaxim Konovalov 				n = m_free(n);
240670df31f4SMaxim Konovalov 			} else {
240770df31f4SMaxim Konovalov 				n_prev = n;
240870df31f4SMaxim Konovalov 				n = n->m_next;
240970df31f4SMaxim Konovalov 			}
241070df31f4SMaxim Konovalov 		}
24116a2989fdSMatthew N. Dodd 
241270df31f4SMaxim Konovalov 	/* Prepend it to the head. */
241370df31f4SMaxim Konovalov 	m->m_next = control;
241470df31f4SMaxim Konovalov 	return (m);
24156a2989fdSMatthew N. Dodd }
24166a2989fdSMatthew N. Dodd 
2417397c19d1SJeff Roberson static struct unpcb *
2418397c19d1SJeff Roberson fptounp(struct file *fp)
2419397c19d1SJeff Roberson {
2420397c19d1SJeff Roberson 	struct socket *so;
2421397c19d1SJeff Roberson 
2422397c19d1SJeff Roberson 	if (fp->f_type != DTYPE_SOCKET)
2423397c19d1SJeff Roberson 		return (NULL);
2424397c19d1SJeff Roberson 	if ((so = fp->f_data) == NULL)
2425397c19d1SJeff Roberson 		return (NULL);
2426397c19d1SJeff Roberson 	if (so->so_proto->pr_domain != &localdomain)
2427397c19d1SJeff Roberson 		return (NULL);
2428397c19d1SJeff Roberson 	return sotounpcb(so);
2429397c19d1SJeff Roberson }
2430397c19d1SJeff Roberson 
2431397c19d1SJeff Roberson static void
2432397c19d1SJeff Roberson unp_discard(struct file *fp)
2433397c19d1SJeff Roberson {
24340cb64678SKonstantin Belousov 	struct unp_defer *dr;
2435397c19d1SJeff Roberson 
24360cb64678SKonstantin Belousov 	if (unp_externalize_fp(fp)) {
24370cb64678SKonstantin Belousov 		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
24380cb64678SKonstantin Belousov 		dr->ud_fp = fp;
24390cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
24400cb64678SKonstantin Belousov 		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
24410cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
24420cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, 1);
24430cb64678SKonstantin Belousov 		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
24440cb64678SKonstantin Belousov 	} else
2445397c19d1SJeff Roberson 		(void) closef(fp, (struct thread *)NULL);
2446397c19d1SJeff Roberson }
2447397c19d1SJeff Roberson 
2448397c19d1SJeff Roberson static void
24490cb64678SKonstantin Belousov unp_process_defers(void *arg __unused, int pending)
24500cb64678SKonstantin Belousov {
24510cb64678SKonstantin Belousov 	struct unp_defer *dr;
24520cb64678SKonstantin Belousov 	SLIST_HEAD(, unp_defer) drl;
24530cb64678SKonstantin Belousov 	int count;
24540cb64678SKonstantin Belousov 
24550cb64678SKonstantin Belousov 	SLIST_INIT(&drl);
24560cb64678SKonstantin Belousov 	for (;;) {
24570cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
24580cb64678SKonstantin Belousov 		if (SLIST_FIRST(&unp_defers) == NULL) {
24590cb64678SKonstantin Belousov 			UNP_DEFERRED_UNLOCK();
24600cb64678SKonstantin Belousov 			break;
24610cb64678SKonstantin Belousov 		}
24620cb64678SKonstantin Belousov 		SLIST_SWAP(&unp_defers, &drl, unp_defer);
24630cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
24640cb64678SKonstantin Belousov 		count = 0;
24650cb64678SKonstantin Belousov 		while ((dr = SLIST_FIRST(&drl)) != NULL) {
24660cb64678SKonstantin Belousov 			SLIST_REMOVE_HEAD(&drl, ud_link);
24670cb64678SKonstantin Belousov 			closef(dr->ud_fp, NULL);
24680cb64678SKonstantin Belousov 			free(dr, M_TEMP);
24690cb64678SKonstantin Belousov 			count++;
24700cb64678SKonstantin Belousov 		}
24710cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, -count);
24720cb64678SKonstantin Belousov 	}
24730cb64678SKonstantin Belousov }
24740cb64678SKonstantin Belousov 
24750cb64678SKonstantin Belousov static void
2476397c19d1SJeff Roberson unp_internalize_fp(struct file *fp)
2477397c19d1SJeff Roberson {
2478397c19d1SJeff Roberson 	struct unpcb *unp;
2479397c19d1SJeff Roberson 
24803dab55bcSRobert Watson 	UNP_LINK_WLOCK();
2481397c19d1SJeff Roberson 	if ((unp = fptounp(fp)) != NULL) {
2482397c19d1SJeff Roberson 		unp->unp_file = fp;
2483397c19d1SJeff Roberson 		unp->unp_msgcount++;
2484397c19d1SJeff Roberson 	}
2485397c19d1SJeff Roberson 	unp_rights++;
24863dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
2487397c19d1SJeff Roberson }
2488397c19d1SJeff Roberson 
24890cb64678SKonstantin Belousov static int
2490397c19d1SJeff Roberson unp_externalize_fp(struct file *fp)
2491397c19d1SJeff Roberson {
2492397c19d1SJeff Roberson 	struct unpcb *unp;
24930cb64678SKonstantin Belousov 	int ret;
2494397c19d1SJeff Roberson 
24953dab55bcSRobert Watson 	UNP_LINK_WLOCK();
24960cb64678SKonstantin Belousov 	if ((unp = fptounp(fp)) != NULL) {
2497397c19d1SJeff Roberson 		unp->unp_msgcount--;
24980cb64678SKonstantin Belousov 		ret = 1;
24990cb64678SKonstantin Belousov 	} else
25000cb64678SKonstantin Belousov 		ret = 0;
2501397c19d1SJeff Roberson 	unp_rights--;
25023dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
25030cb64678SKonstantin Belousov 	return (ret);
2504397c19d1SJeff Roberson }
2505397c19d1SJeff Roberson 
2506161a0c7cSRobert Watson /*
2507a0ec558aSRobert Watson  * unp_defer indicates whether additional work has been defered for a future
2508a0ec558aSRobert Watson  * pass through unp_gc().  It is thread local and does not require explicit
2509a0ec558aSRobert Watson  * synchronization.
2510161a0c7cSRobert Watson  */
2511397c19d1SJeff Roberson static int	unp_marked;
2512a0ec558aSRobert Watson 
2513397c19d1SJeff Roberson static void
2514a9aa06f7SJason A. Harmening unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2515397c19d1SJeff Roberson {
2516397c19d1SJeff Roberson 	struct unpcb *unp;
2517be26ba7cSPawel Jakub Dawidek 	struct file *fp;
2518be26ba7cSPawel Jakub Dawidek 	int i;
2519397c19d1SJeff Roberson 
2520a9aa06f7SJason A. Harmening 	/*
2521a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2522a9aa06f7SJason A. Harmening 	 */
2523a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2524a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2525a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2526a9aa06f7SJason A. Harmening 
2527be26ba7cSPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
2528be26ba7cSPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
25296f552cb0SJeff Roberson 		if ((unp = fptounp(fp)) == NULL)
2530be26ba7cSPawel Jakub Dawidek 			continue;
2531a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2532be26ba7cSPawel Jakub Dawidek 			continue;
2533a9aa06f7SJason A. Harmening 		unp->unp_gcrefs--;
2534a9aa06f7SJason A. Harmening 	}
2535a9aa06f7SJason A. Harmening }
2536a9aa06f7SJason A. Harmening 
2537a9aa06f7SJason A. Harmening static void
2538a9aa06f7SJason A. Harmening unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2539a9aa06f7SJason A. Harmening {
2540a9aa06f7SJason A. Harmening 	struct unpcb *unp;
2541a9aa06f7SJason A. Harmening 	struct file *fp;
2542a9aa06f7SJason A. Harmening 	int i;
2543a9aa06f7SJason A. Harmening 
2544a9aa06f7SJason A. Harmening 	/*
2545a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2546a9aa06f7SJason A. Harmening 	 */
2547a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2548a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2549a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2550a9aa06f7SJason A. Harmening 
2551a9aa06f7SJason A. Harmening 	for (i = 0; i < fdcount; i++) {
2552a9aa06f7SJason A. Harmening 		fp = fdep[i]->fde_file;
2553a9aa06f7SJason A. Harmening 		if ((unp = fptounp(fp)) == NULL)
2554a9aa06f7SJason A. Harmening 			continue;
2555a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2556a9aa06f7SJason A. Harmening 			continue;
2557a9aa06f7SJason A. Harmening 		unp->unp_gcrefs++;
2558397c19d1SJeff Roberson 		unp_marked++;
2559397c19d1SJeff Roberson 	}
2560be26ba7cSPawel Jakub Dawidek }
2561397c19d1SJeff Roberson 
2562397c19d1SJeff Roberson static void
2563a9aa06f7SJason A. Harmening unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2564397c19d1SJeff Roberson {
2565779f106aSGleb Smirnoff 	struct socket *so, *soa;
256660a5ef26SRobert Watson 
2567397c19d1SJeff Roberson 	so = unp->unp_socket;
2568779f106aSGleb Smirnoff 	SOCK_LOCK(so);
2569779f106aSGleb Smirnoff 	if (SOLISTENING(so)) {
2570397c19d1SJeff Roberson 		/*
2571397c19d1SJeff Roberson 		 * Mark all sockets in our accept queue.
2572397c19d1SJeff Roberson 		 */
2573779f106aSGleb Smirnoff 		TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2574779f106aSGleb Smirnoff 			if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
25750c40f353SConrad Meyer 				continue;
2576397c19d1SJeff Roberson 			SOCKBUF_LOCK(&soa->so_rcv);
2577a9aa06f7SJason A. Harmening 			unp_scan(soa->so_rcv.sb_mb, op);
2578397c19d1SJeff Roberson 			SOCKBUF_UNLOCK(&soa->so_rcv);
2579397c19d1SJeff Roberson 		}
2580779f106aSGleb Smirnoff 	} else {
2581779f106aSGleb Smirnoff 		/*
2582779f106aSGleb Smirnoff 		 * Mark all sockets we reference with RIGHTS.
2583779f106aSGleb Smirnoff 		 */
2584779f106aSGleb Smirnoff 		if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2585779f106aSGleb Smirnoff 			SOCKBUF_LOCK(&so->so_rcv);
2586a9aa06f7SJason A. Harmening 			unp_scan(so->so_rcv.sb_mb, op);
2587779f106aSGleb Smirnoff 			SOCKBUF_UNLOCK(&so->so_rcv);
2588779f106aSGleb Smirnoff 		}
2589779f106aSGleb Smirnoff 	}
2590779f106aSGleb Smirnoff 	SOCK_UNLOCK(so);
2591397c19d1SJeff Roberson }
2592a0ec558aSRobert Watson 
2593a0ec558aSRobert Watson static int unp_recycled;
2594be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2595be6b1304STom Rhodes     "Number of unreachable sockets claimed by the garbage collector.");
2596df8bae1dSRodney W. Grimes 
2597397c19d1SJeff Roberson static int unp_taskcount;
2598be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2599be6b1304STom Rhodes     "Number of times the garbage collector has run.");
2600397c19d1SJeff Roberson 
2601a9aa06f7SJason A. Harmening SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
2602a9aa06f7SJason A. Harmening     "Number of active local sockets.");
2603a9aa06f7SJason A. Harmening 
2604f708ef1bSPoul-Henning Kamp static void
2605a0ec558aSRobert Watson unp_gc(__unused void *arg, int pending)
2606df8bae1dSRodney W. Grimes {
260784d61770SRobert Watson 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
260884d61770SRobert Watson 				    NULL };
2609397c19d1SJeff Roberson 	struct unp_head **head;
2610a9aa06f7SJason A. Harmening 	struct unp_head unp_deadhead;	/* List of potentially-dead sockets. */
2611f7780c61SKonstantin Belousov 	struct file *f, **unref;
2612a9aa06f7SJason A. Harmening 	struct unpcb *unp, *unptmp;
2613a9aa06f7SJason A. Harmening 	int i, total, unp_unreachable;
2614df8bae1dSRodney W. Grimes 
2615a9aa06f7SJason A. Harmening 	LIST_INIT(&unp_deadhead);
2616a0ec558aSRobert Watson 	unp_taskcount++;
2617779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
2618ed5b7817SJulian Elischer 	/*
2619a9aa06f7SJason A. Harmening 	 * First determine which sockets may be in cycles.
2620ed5b7817SJulian Elischer 	 */
2621a9aa06f7SJason A. Harmening 	unp_unreachable = 0;
2622a9aa06f7SJason A. Harmening 
2623397c19d1SJeff Roberson 	for (head = heads; *head != NULL; head++)
2624a9aa06f7SJason A. Harmening 		LIST_FOREACH(unp, *head, unp_link) {
2625a9aa06f7SJason A. Harmening 			KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2626a9aa06f7SJason A. Harmening 			    ("%s: unp %p has unexpected gc flags 0x%x",
2627a9aa06f7SJason A. Harmening 			    __func__, unp, (unsigned int)unp->unp_gcflag));
2628a9aa06f7SJason A. Harmening 
2629a9aa06f7SJason A. Harmening 			f = unp->unp_file;
263060a5ef26SRobert Watson 
2631397c19d1SJeff Roberson 			/*
2632a9aa06f7SJason A. Harmening 			 * Check for an unreachable socket potentially in a
2633a9aa06f7SJason A. Harmening 			 * cycle.  It must be in a queue as indicated by
2634a9aa06f7SJason A. Harmening 			 * msgcount, and this must equal the file reference
2635a9aa06f7SJason A. Harmening 			 * count.  Note that when msgcount is 0 the file is
2636a9aa06f7SJason A. Harmening 			 * NULL.
2637a9aa06f7SJason A. Harmening 			 */
2638a9aa06f7SJason A. Harmening 			if (f != NULL && unp->unp_msgcount != 0 &&
2639a9aa06f7SJason A. Harmening 			    f->f_count == unp->unp_msgcount) {
2640a9aa06f7SJason A. Harmening 				LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2641a9aa06f7SJason A. Harmening 				unp->unp_gcflag |= UNPGC_DEAD;
2642a9aa06f7SJason A. Harmening 				unp->unp_gcrefs = unp->unp_msgcount;
2643a9aa06f7SJason A. Harmening 				unp_unreachable++;
2644a9aa06f7SJason A. Harmening 			}
2645a9aa06f7SJason A. Harmening 		}
2646a9aa06f7SJason A. Harmening 
2647a9aa06f7SJason A. Harmening 	/*
2648a9aa06f7SJason A. Harmening 	 * Scan all sockets previously marked as potentially being in a cycle
2649a9aa06f7SJason A. Harmening 	 * and remove the references each socket holds on any UNPGC_DEAD
2650a9aa06f7SJason A. Harmening 	 * sockets in its queue.  After this step, all remaining references on
2651a9aa06f7SJason A. Harmening 	 * sockets marked UNPGC_DEAD should not be part of any cycle.
2652a9aa06f7SJason A. Harmening 	 */
2653a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead)
2654a9aa06f7SJason A. Harmening 		unp_gc_scan(unp, unp_remove_dead_ref);
2655a9aa06f7SJason A. Harmening 
2656a9aa06f7SJason A. Harmening 	/*
2657a9aa06f7SJason A. Harmening 	 * If a socket still has a non-negative refcount, it cannot be in a
2658a9aa06f7SJason A. Harmening 	 * cycle.  In this case increment refcount of all children iteratively.
2659397c19d1SJeff Roberson 	 * Stop the scan once we do a complete loop without discovering
2660397c19d1SJeff Roberson 	 * a new reachable socket.
2661397c19d1SJeff Roberson 	 */
2662df8bae1dSRodney W. Grimes 	do {
2663397c19d1SJeff Roberson 		unp_marked = 0;
2664a9aa06f7SJason A. Harmening 		LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
2665a9aa06f7SJason A. Harmening 			if (unp->unp_gcrefs > 0) {
2666a9aa06f7SJason A. Harmening 				unp->unp_gcflag &= ~UNPGC_DEAD;
2667a9aa06f7SJason A. Harmening 				LIST_REMOVE(unp, unp_dead);
2668a9aa06f7SJason A. Harmening 				KASSERT(unp_unreachable > 0,
2669a9aa06f7SJason A. Harmening 				    ("%s: unp_unreachable underflow.",
2670a9aa06f7SJason A. Harmening 				    __func__));
2671a9aa06f7SJason A. Harmening 				unp_unreachable--;
2672a9aa06f7SJason A. Harmening 				unp_gc_scan(unp, unp_restore_undead_ref);
2673a9aa06f7SJason A. Harmening 			}
2674397c19d1SJeff Roberson 	} while (unp_marked);
2675a9aa06f7SJason A. Harmening 
2676779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
2677a9aa06f7SJason A. Harmening 
2678397c19d1SJeff Roberson 	if (unp_unreachable == 0)
2679397c19d1SJeff Roberson 		return;
268060a5ef26SRobert Watson 
2681ed5b7817SJulian Elischer 	/*
2682a9aa06f7SJason A. Harmening 	 * Allocate space for a local array of dead unpcbs.
2683a9aa06f7SJason A. Harmening 	 * TODO: can this path be simplified by instead using the local
2684a9aa06f7SJason A. Harmening 	 * dead list at unp_deadhead, after taking out references
2685a9aa06f7SJason A. Harmening 	 * on the file object and/or unpcb and dropping the link lock?
2686ed5b7817SJulian Elischer 	 */
2687397c19d1SJeff Roberson 	unref = malloc(unp_unreachable * sizeof(struct file *),
2688397c19d1SJeff Roberson 	    M_TEMP, M_WAITOK);
268960a5ef26SRobert Watson 
2690ed5b7817SJulian Elischer 	/*
2691397c19d1SJeff Roberson 	 * Iterate looking for sockets which have been specifically marked
2692a9aa06f7SJason A. Harmening 	 * as unreachable and store them locally.
2693ed5b7817SJulian Elischer 	 */
2694f7780c61SKonstantin Belousov 	UNP_LINK_RLOCK();
2695a9aa06f7SJason A. Harmening 	total = 0;
2696a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
2697a9aa06f7SJason A. Harmening 		KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
2698a9aa06f7SJason A. Harmening 		    ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
2699a9aa06f7SJason A. Harmening 		unp->unp_gcflag &= ~UNPGC_DEAD;
2700f7780c61SKonstantin Belousov 		f = unp->unp_file;
2701f7780c61SKonstantin Belousov 		if (unp->unp_msgcount == 0 || f == NULL ||
2702f1cf2b9dSKonstantin Belousov 		    f->f_count != unp->unp_msgcount ||
2703f1cf2b9dSKonstantin Belousov 		    !fhold(f))
2704f7780c61SKonstantin Belousov 			continue;
2705f7780c61SKonstantin Belousov 		unref[total++] = f;
2706f7780c61SKonstantin Belousov 		KASSERT(total <= unp_unreachable,
2707a9aa06f7SJason A. Harmening 		    ("%s: incorrect unreachable count.", __func__));
2708397c19d1SJeff Roberson 	}
2709f7780c61SKonstantin Belousov 	UNP_LINK_RUNLOCK();
271060a5ef26SRobert Watson 
2711ed5b7817SJulian Elischer 	/*
2712397c19d1SJeff Roberson 	 * Now flush all sockets, free'ing rights.  This will free the
2713397c19d1SJeff Roberson 	 * struct files associated with these sockets but leave each socket
2714397c19d1SJeff Roberson 	 * with one remaining ref.
2715ed5b7817SJulian Elischer 	 */
27161fb51a12SBjoern A. Zeeb 	for (i = 0; i < total; i++) {
27171fb51a12SBjoern A. Zeeb 		struct socket *so;
27181fb51a12SBjoern A. Zeeb 
27191fb51a12SBjoern A. Zeeb 		so = unref[i]->f_data;
27201fb51a12SBjoern A. Zeeb 		CURVNET_SET(so->so_vnet);
27211fb51a12SBjoern A. Zeeb 		sorflush(so);
27221fb51a12SBjoern A. Zeeb 		CURVNET_RESTORE();
27231fb51a12SBjoern A. Zeeb 	}
272460a5ef26SRobert Watson 
2725ed5b7817SJulian Elischer 	/*
2726397c19d1SJeff Roberson 	 * And finally release the sockets so they can be reclaimed.
2727ed5b7817SJulian Elischer 	 */
2728f7780c61SKonstantin Belousov 	for (i = 0; i < total; i++)
2729397c19d1SJeff Roberson 		fdrop(unref[i], NULL);
2730f7780c61SKonstantin Belousov 	unp_recycled += total;
2731397c19d1SJeff Roberson 	free(unref, M_TEMP);
2732df8bae1dSRodney W. Grimes }
2733df8bae1dSRodney W. Grimes 
27340b36cd25SRobert Watson static void
273599ab95dbSMark Johnston unp_dispose_mbuf(struct mbuf *m)
2736df8bae1dSRodney W. Grimes {
2737996c772fSJohn Dyson 
2738df8bae1dSRodney W. Grimes 	if (m)
2739be26ba7cSPawel Jakub Dawidek 		unp_scan(m, unp_freerights);
2740df8bae1dSRodney W. Grimes }
2741df8bae1dSRodney W. Grimes 
27420c40f353SConrad Meyer /*
27430c40f353SConrad Meyer  * Synchronize against unp_gc, which can trip over data as we are freeing it.
27440c40f353SConrad Meyer  */
27450c40f353SConrad Meyer static void
274699ab95dbSMark Johnston unp_dispose(struct socket *so)
27470c40f353SConrad Meyer {
27480c40f353SConrad Meyer 	struct unpcb *unp;
27490c40f353SConrad Meyer 
27500c40f353SConrad Meyer 	unp = sotounpcb(so);
2751779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
27520c40f353SConrad Meyer 	unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2753779f106aSGleb Smirnoff 	UNP_LINK_WUNLOCK();
2754779f106aSGleb Smirnoff 	if (!SOLISTENING(so))
275599ab95dbSMark Johnston 		unp_dispose_mbuf(so->so_rcv.sb_mb);
27560c40f353SConrad Meyer }
27570c40f353SConrad Meyer 
2758f708ef1bSPoul-Henning Kamp static void
2759be26ba7cSPawel Jakub Dawidek unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2760df8bae1dSRodney W. Grimes {
27612bc21ed9SDavid Malone 	struct mbuf *m;
27622bc21ed9SDavid Malone 	struct cmsghdr *cm;
27632bc21ed9SDavid Malone 	void *data;
27642bc21ed9SDavid Malone 	socklen_t clen, datalen;
2765df8bae1dSRodney W. Grimes 
2766fc3fcacfSRobert Watson 	while (m0 != NULL) {
27672bc21ed9SDavid Malone 		for (m = m0; m; m = m->m_next) {
276812396bdcSDavid Malone 			if (m->m_type != MT_CONTROL)
2769df8bae1dSRodney W. Grimes 				continue;
27702bc21ed9SDavid Malone 
27712bc21ed9SDavid Malone 			cm = mtod(m, struct cmsghdr *);
27722bc21ed9SDavid Malone 			clen = m->m_len;
27732bc21ed9SDavid Malone 
27742bc21ed9SDavid Malone 			while (cm != NULL) {
27752bc21ed9SDavid Malone 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
27762bc21ed9SDavid Malone 					break;
27772bc21ed9SDavid Malone 
27782bc21ed9SDavid Malone 				data = CMSG_DATA(cm);
27792bc21ed9SDavid Malone 				datalen = (caddr_t)cm + cm->cmsg_len
27802bc21ed9SDavid Malone 				    - (caddr_t)data;
27812bc21ed9SDavid Malone 
27822bc21ed9SDavid Malone 				if (cm->cmsg_level == SOL_SOCKET &&
27832bc21ed9SDavid Malone 				    cm->cmsg_type == SCM_RIGHTS) {
2784be26ba7cSPawel Jakub Dawidek 					(*op)(data, datalen /
2785be26ba7cSPawel Jakub Dawidek 					    sizeof(struct filedescent *));
27862bc21ed9SDavid Malone 				}
27872bc21ed9SDavid Malone 
27882bc21ed9SDavid Malone 				if (CMSG_SPACE(datalen) < clen) {
27892bc21ed9SDavid Malone 					clen -= CMSG_SPACE(datalen);
27902bc21ed9SDavid Malone 					cm = (struct cmsghdr *)
27912bc21ed9SDavid Malone 					    ((caddr_t)cm + CMSG_SPACE(datalen));
27922bc21ed9SDavid Malone 				} else {
27932bc21ed9SDavid Malone 					clen = 0;
27942bc21ed9SDavid Malone 					cm = NULL;
27952bc21ed9SDavid Malone 				}
27962bc21ed9SDavid Malone 			}
2797df8bae1dSRodney W. Grimes 		}
2798c29a3321SKevin Lo 		m0 = m0->m_nextpkt;
2799df8bae1dSRodney W. Grimes 	}
2800df8bae1dSRodney W. Grimes }
2801df8bae1dSRodney W. Grimes 
2802662c901cSMikolaj Golub /*
2803662c901cSMikolaj Golub  * A helper function called by VFS before socket-type vnode reclamation.
2804662c901cSMikolaj Golub  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2805662c901cSMikolaj Golub  * use count.
2806662c901cSMikolaj Golub  */
2807662c901cSMikolaj Golub void
2808662c901cSMikolaj Golub vfs_unp_reclaim(struct vnode *vp)
2809662c901cSMikolaj Golub {
2810662c901cSMikolaj Golub 	struct unpcb *unp;
2811662c901cSMikolaj Golub 	int active;
281275a67bf3SMatt Macy 	struct mtx *vplock;
2813662c901cSMikolaj Golub 
2814662c901cSMikolaj Golub 	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2815662c901cSMikolaj Golub 	KASSERT(vp->v_type == VSOCK,
2816662c901cSMikolaj Golub 	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2817662c901cSMikolaj Golub 
2818662c901cSMikolaj Golub 	active = 0;
281975a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
282075a67bf3SMatt Macy 	mtx_lock(vplock);
28210c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp);
2822662c901cSMikolaj Golub 	if (unp == NULL)
2823662c901cSMikolaj Golub 		goto done;
2824662c901cSMikolaj Golub 	UNP_PCB_LOCK(unp);
2825c7e41c8bSMikolaj Golub 	if (unp->unp_vnode == vp) {
2826c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
2827662c901cSMikolaj Golub 		unp->unp_vnode = NULL;
2828662c901cSMikolaj Golub 		active = 1;
2829662c901cSMikolaj Golub 	}
2830662c901cSMikolaj Golub 	UNP_PCB_UNLOCK(unp);
2831662c901cSMikolaj Golub  done:
283275a67bf3SMatt Macy 	mtx_unlock(vplock);
2833662c901cSMikolaj Golub 	if (active)
2834662c901cSMikolaj Golub 		vunref(vp);
2835662c901cSMikolaj Golub }
2836662c901cSMikolaj Golub 
283703c96c31SRobert Watson #ifdef DDB
283803c96c31SRobert Watson static void
283903c96c31SRobert Watson db_print_indent(int indent)
284003c96c31SRobert Watson {
284103c96c31SRobert Watson 	int i;
284203c96c31SRobert Watson 
284303c96c31SRobert Watson 	for (i = 0; i < indent; i++)
284403c96c31SRobert Watson 		db_printf(" ");
284503c96c31SRobert Watson }
284603c96c31SRobert Watson 
284703c96c31SRobert Watson static void
284803c96c31SRobert Watson db_print_unpflags(int unp_flags)
284903c96c31SRobert Watson {
285003c96c31SRobert Watson 	int comma;
285103c96c31SRobert Watson 
285203c96c31SRobert Watson 	comma = 0;
285303c96c31SRobert Watson 	if (unp_flags & UNP_HAVEPC) {
285403c96c31SRobert Watson 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
285503c96c31SRobert Watson 		comma = 1;
285603c96c31SRobert Watson 	}
285703c96c31SRobert Watson 	if (unp_flags & UNP_WANTCRED) {
285803c96c31SRobert Watson 		db_printf("%sUNP_WANTCRED", comma ? ", " : "");
285903c96c31SRobert Watson 		comma = 1;
286003c96c31SRobert Watson 	}
286103c96c31SRobert Watson 	if (unp_flags & UNP_CONNWAIT) {
286203c96c31SRobert Watson 		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
286303c96c31SRobert Watson 		comma = 1;
286403c96c31SRobert Watson 	}
286503c96c31SRobert Watson 	if (unp_flags & UNP_CONNECTING) {
286603c96c31SRobert Watson 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
286703c96c31SRobert Watson 		comma = 1;
286803c96c31SRobert Watson 	}
286903c96c31SRobert Watson 	if (unp_flags & UNP_BINDING) {
287003c96c31SRobert Watson 		db_printf("%sUNP_BINDING", comma ? ", " : "");
287103c96c31SRobert Watson 		comma = 1;
287203c96c31SRobert Watson 	}
287303c96c31SRobert Watson }
287403c96c31SRobert Watson 
287503c96c31SRobert Watson static void
287603c96c31SRobert Watson db_print_xucred(int indent, struct xucred *xu)
287703c96c31SRobert Watson {
287803c96c31SRobert Watson 	int comma, i;
287903c96c31SRobert Watson 
288003c96c31SRobert Watson 	db_print_indent(indent);
2881c5afec6eSDmitry Chagin 	db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
2882c5afec6eSDmitry Chagin 	    xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
288303c96c31SRobert Watson 	db_print_indent(indent);
288403c96c31SRobert Watson 	db_printf("cr_groups: ");
288503c96c31SRobert Watson 	comma = 0;
288603c96c31SRobert Watson 	for (i = 0; i < xu->cr_ngroups; i++) {
288703c96c31SRobert Watson 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
288803c96c31SRobert Watson 		comma = 1;
288903c96c31SRobert Watson 	}
289003c96c31SRobert Watson 	db_printf("\n");
289103c96c31SRobert Watson }
289203c96c31SRobert Watson 
289303c96c31SRobert Watson static void
289403c96c31SRobert Watson db_print_unprefs(int indent, struct unp_head *uh)
289503c96c31SRobert Watson {
289603c96c31SRobert Watson 	struct unpcb *unp;
289703c96c31SRobert Watson 	int counter;
289803c96c31SRobert Watson 
289903c96c31SRobert Watson 	counter = 0;
290003c96c31SRobert Watson 	LIST_FOREACH(unp, uh, unp_reflink) {
290103c96c31SRobert Watson 		if (counter % 4 == 0)
290203c96c31SRobert Watson 			db_print_indent(indent);
290303c96c31SRobert Watson 		db_printf("%p  ", unp);
290403c96c31SRobert Watson 		if (counter % 4 == 3)
290503c96c31SRobert Watson 			db_printf("\n");
290603c96c31SRobert Watson 		counter++;
290703c96c31SRobert Watson 	}
290803c96c31SRobert Watson 	if (counter != 0 && counter % 4 != 0)
290903c96c31SRobert Watson 		db_printf("\n");
291003c96c31SRobert Watson }
291103c96c31SRobert Watson 
291203c96c31SRobert Watson DB_SHOW_COMMAND(unpcb, db_show_unpcb)
291303c96c31SRobert Watson {
291403c96c31SRobert Watson 	struct unpcb *unp;
291503c96c31SRobert Watson 
291603c96c31SRobert Watson         if (!have_addr) {
291703c96c31SRobert Watson                 db_printf("usage: show unpcb <addr>\n");
291803c96c31SRobert Watson                 return;
291903c96c31SRobert Watson         }
292003c96c31SRobert Watson         unp = (struct unpcb *)addr;
292103c96c31SRobert Watson 
292203c96c31SRobert Watson 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
292303c96c31SRobert Watson 	    unp->unp_vnode);
292403c96c31SRobert Watson 
2925fc8fdae0SMatthew D Fleming 	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
292603c96c31SRobert Watson 	    unp->unp_conn);
292703c96c31SRobert Watson 
292803c96c31SRobert Watson 	db_printf("unp_refs:\n");
292903c96c31SRobert Watson 	db_print_unprefs(2, &unp->unp_refs);
293003c96c31SRobert Watson 
293103c96c31SRobert Watson 	/* XXXRW: Would be nice to print the full address, if any. */
293203c96c31SRobert Watson 	db_printf("unp_addr: %p\n", unp->unp_addr);
293303c96c31SRobert Watson 
2934c2090e73SAlan Somers 	db_printf("unp_gencnt: %llu\n",
293503c96c31SRobert Watson 	    (unsigned long long)unp->unp_gencnt);
293603c96c31SRobert Watson 
293703c96c31SRobert Watson 	db_printf("unp_flags: %x (", unp->unp_flags);
293803c96c31SRobert Watson 	db_print_unpflags(unp->unp_flags);
293903c96c31SRobert Watson 	db_printf(")\n");
294003c96c31SRobert Watson 
294103c96c31SRobert Watson 	db_printf("unp_peercred:\n");
294203c96c31SRobert Watson 	db_print_xucred(2, &unp->unp_peercred);
294303c96c31SRobert Watson 
294403c96c31SRobert Watson 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
294503c96c31SRobert Watson }
294603c96c31SRobert Watson #endif
2947