xref: /freebsd/sys/kern/uipc_usrreq.c (revision 24e1c6ae7d3f7731a0884a62e9d5273e5ca1335a)
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 */
160d157f262SMark Johnston static u_long	unpdg_recvspace = 16*1024;	/* support 8KB syslog msgs */
16184d61770SRobert Watson static u_long	unpsp_sendspace = PIPSIZ;	/* really max datagram size */
16284d61770SRobert Watson static u_long	unpsp_recvspace = PIPSIZ;
1637e711c3aSRobert Watson 
1647029da5cSPawel Biernacki static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1657029da5cSPawel Biernacki     "Local domain");
1667029da5cSPawel Biernacki static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
1677029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1686472ac3dSEd Schouten     "SOCK_STREAM");
1697029da5cSPawel Biernacki static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
1707029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1717029da5cSPawel Biernacki     "SOCK_DGRAM");
1727029da5cSPawel Biernacki static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
1737029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
17484d61770SRobert Watson     "SOCK_SEQPACKET");
175e4445a03SRobert Watson 
1767e711c3aSRobert Watson SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
177be6b1304STom Rhodes 	   &unpst_sendspace, 0, "Default stream send space.");
1787e711c3aSRobert Watson SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
179be6b1304STom Rhodes 	   &unpst_recvspace, 0, "Default stream receive space.");
1807e711c3aSRobert Watson SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
181be6b1304STom Rhodes 	   &unpdg_sendspace, 0, "Default datagram send space.");
1827e711c3aSRobert Watson SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
183be6b1304STom Rhodes 	   &unpdg_recvspace, 0, "Default datagram receive space.");
18484d61770SRobert Watson SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
18584d61770SRobert Watson 	   &unpsp_sendspace, 0, "Default seqpacket send space.");
18684d61770SRobert Watson SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
18784d61770SRobert Watson 	   &unpsp_recvspace, 0, "Default seqpacket receive space.");
188be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
189be6b1304STom Rhodes     "File descriptors in flight.");
1900cb64678SKonstantin Belousov SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
1910cb64678SKonstantin Belousov     &unp_defers_count, 0,
1920cb64678SKonstantin Belousov     "File descriptors deferred to taskqueue for close.");
1937e711c3aSRobert Watson 
194175389cfSEdward Tomasz Napierala /*
195e7c33e29SRobert Watson  * Locking and synchronization:
196ce5f32deSRobert Watson  *
197d5cbccecSMark Johnston  * Several types of locks exist in the local domain socket implementation:
198d5cbccecSMark Johnston  * - a global linkage lock
199d5cbccecSMark Johnston  * - a global connection list lock
200d5cbccecSMark Johnston  * - the mtxpool lock
201d5cbccecSMark Johnston  * - per-unpcb mutexes
202d5cbccecSMark Johnston  *
203d5cbccecSMark Johnston  * The linkage lock protects the global socket lists, the generation number
204d5cbccecSMark Johnston  * counter and garbage collector state.
205d5cbccecSMark Johnston  *
206d5cbccecSMark Johnston  * The connection list lock protects the list of referring sockets in a datagram
207d5cbccecSMark Johnston  * socket PCB.  This lock is also overloaded to protect a global list of
208d5cbccecSMark Johnston  * sockets whose buffers contain socket references in the form of SCM_RIGHTS
209d5cbccecSMark Johnston  * messages.  To avoid recursion, such references are released by a dedicated
210d5cbccecSMark Johnston  * thread.
21175a67bf3SMatt Macy  *
21275a67bf3SMatt Macy  * The mtxpool lock protects the vnode from being modified while referenced.
213d5cbccecSMark Johnston  * Lock ordering rules require that it be acquired before any PCB locks.
21475a67bf3SMatt Macy  *
215d5cbccecSMark Johnston  * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
216d5cbccecSMark Johnston  * unpcb.  This includes the unp_conn field, which either links two connected
217d5cbccecSMark Johnston  * PCBs together (for connected socket types) or points at the destination
218d5cbccecSMark Johnston  * socket (for connectionless socket types).  The operations of creating or
219d5cbccecSMark Johnston  * destroying a connection therefore involve locking multiple PCBs.  To avoid
220d5cbccecSMark Johnston  * lock order reversals, in some cases this involves dropping a PCB lock and
221d5cbccecSMark Johnston  * using a reference counter to maintain liveness.
222ce5f32deSRobert Watson  *
223e7c33e29SRobert Watson  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
224e7c33e29SRobert Watson  * allocated in pru_attach() and freed in pru_detach().  The validity of that
225e7c33e29SRobert Watson  * pointer is an invariant, so no lock is required to dereference the so_pcb
226e7c33e29SRobert Watson  * pointer if a valid socket reference is held by the caller.  In practice,
227e7c33e29SRobert Watson  * this is always true during operations performed on a socket.  Each unpcb
228e7c33e29SRobert Watson  * has a back-pointer to its socket, unp_socket, which will be stable under
229e7c33e29SRobert Watson  * the same circumstances.
230e7c33e29SRobert Watson  *
231e7c33e29SRobert Watson  * This pointer may only be safely dereferenced as long as a valid reference
232e7c33e29SRobert Watson  * to the unpcb is held.  Typically, this reference will be from the socket,
233e7c33e29SRobert Watson  * or from another unpcb when the referring unpcb's lock is held (in order
234e7c33e29SRobert Watson  * that the reference not be invalidated during use).  For example, to follow
23575a67bf3SMatt Macy  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
23675a67bf3SMatt Macy  * that detach is not run clearing unp_socket.
237e7c33e29SRobert Watson  *
238e7c33e29SRobert Watson  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
239e7c33e29SRobert Watson  * protocols, bind() is a non-atomic operation, and connect() requires
240e7c33e29SRobert Watson  * potential sleeping in the protocol, due to potentially waiting on local or
241e7c33e29SRobert Watson  * distributed file systems.  We try to separate "lookup" operations, which
242e7c33e29SRobert Watson  * may sleep, and the IPC operations themselves, which typically can occur
243e7c33e29SRobert Watson  * with relative atomicity as locks can be held over the entire operation.
244e7c33e29SRobert Watson  *
245e7c33e29SRobert Watson  * Another tricky issue is simultaneous multi-threaded or multi-process
246e7c33e29SRobert Watson  * access to a single UNIX domain socket.  These are handled by the flags
247e7c33e29SRobert Watson  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
248e7c33e29SRobert Watson  * binding, both of which involve dropping UNIX domain socket locks in order
249e7c33e29SRobert Watson  * to perform namei() and other file system operations.
250ce5f32deSRobert Watson  */
2513dab55bcSRobert Watson static struct rwlock	unp_link_rwlock;
2520cb64678SKonstantin Belousov static struct mtx	unp_defers_lock;
253e7c33e29SRobert Watson 
2543dab55bcSRobert Watson #define	UNP_LINK_LOCK_INIT()		rw_init(&unp_link_rwlock,	\
2553dab55bcSRobert Watson 					    "unp_link_rwlock")
256e7c33e29SRobert Watson 
2573dab55bcSRobert Watson #define	UNP_LINK_LOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
258e7c33e29SRobert Watson 					    RA_LOCKED)
2593dab55bcSRobert Watson #define	UNP_LINK_UNLOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
260e7c33e29SRobert Watson 					    RA_UNLOCKED)
261e7c33e29SRobert Watson 
2623dab55bcSRobert Watson #define	UNP_LINK_RLOCK()		rw_rlock(&unp_link_rwlock)
2633dab55bcSRobert Watson #define	UNP_LINK_RUNLOCK()		rw_runlock(&unp_link_rwlock)
2643dab55bcSRobert Watson #define	UNP_LINK_WLOCK()		rw_wlock(&unp_link_rwlock)
2653dab55bcSRobert Watson #define	UNP_LINK_WUNLOCK()		rw_wunlock(&unp_link_rwlock)
2663dab55bcSRobert Watson #define	UNP_LINK_WLOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
267e7c33e29SRobert Watson 					    RA_WLOCKED)
268779f106aSGleb Smirnoff #define	UNP_LINK_WOWNED()		rw_wowned(&unp_link_rwlock)
269e7c33e29SRobert Watson 
2700cb64678SKonstantin Belousov #define	UNP_DEFERRED_LOCK_INIT()	mtx_init(&unp_defers_lock, \
2710cb64678SKonstantin Belousov 					    "unp_defer", NULL, MTX_DEF)
2720cb64678SKonstantin Belousov #define	UNP_DEFERRED_LOCK()		mtx_lock(&unp_defers_lock)
2730cb64678SKonstantin Belousov #define	UNP_DEFERRED_UNLOCK()		mtx_unlock(&unp_defers_lock)
2740cb64678SKonstantin Belousov 
27575a67bf3SMatt Macy #define UNP_REF_LIST_LOCK()		UNP_DEFERRED_LOCK();
27675a67bf3SMatt Macy #define UNP_REF_LIST_UNLOCK()		UNP_DEFERRED_UNLOCK();
27775a67bf3SMatt Macy 
278e7c33e29SRobert Watson #define UNP_PCB_LOCK_INIT(unp)		mtx_init(&(unp)->unp_mtx,	\
279d9525340SMatt Macy 					    "unp", "unp",	\
28075a67bf3SMatt Macy 					    MTX_DUPOK|MTX_DEF)
281e7c33e29SRobert Watson #define	UNP_PCB_LOCK_DESTROY(unp)	mtx_destroy(&(unp)->unp_mtx)
282ccdadf1aSMark Johnston #define	UNP_PCB_LOCKPTR(unp)		(&(unp)->unp_mtx)
283e7c33e29SRobert Watson #define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
28475a67bf3SMatt Macy #define	UNP_PCB_TRYLOCK(unp)		mtx_trylock(&(unp)->unp_mtx)
285e7c33e29SRobert Watson #define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
28675a67bf3SMatt Macy #define	UNP_PCB_OWNED(unp)		mtx_owned(&(unp)->unp_mtx)
287e7c33e29SRobert Watson #define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
28875a67bf3SMatt Macy #define	UNP_PCB_UNLOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
2890d9ce3a1SRobert Watson 
2902c899584SRobert Watson static int	uipc_connect2(struct socket *, struct socket *);
2910b36cd25SRobert Watson static int	uipc_ctloutput(struct socket *, struct sockopt *);
292aea52f1bSRobert Watson static int	unp_connect(struct socket *, struct sockaddr *,
293aea52f1bSRobert Watson 		    struct thread *);
2947493f24eSPawel Jakub Dawidek static int	unp_connectat(int, struct socket *, struct sockaddr *,
2957493f24eSPawel Jakub Dawidek 		    struct thread *);
2966a2989fdSMatthew N. Dodd static int	unp_connect2(struct socket *so, struct socket *so2, int);
297e7c33e29SRobert Watson static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
29899ab95dbSMark Johnston static void	unp_dispose(struct socket *so);
29999ab95dbSMark Johnston static void	unp_dispose_mbuf(struct mbuf *);
3004d77a549SAlfred Perlstein static void	unp_shutdown(struct unpcb *);
301afc055d9SEd Schouten static void	unp_drop(struct unpcb *);
302a0ec558aSRobert Watson static void	unp_gc(__unused void *, int);
303be26ba7cSPawel Jakub Dawidek static void	unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
3044d77a549SAlfred Perlstein static void	unp_discard(struct file *);
3058cb539f1SPawel Jakub Dawidek static void	unp_freerights(struct filedescent **, int);
3064d77a549SAlfred Perlstein static int	unp_internalize(struct mbuf **, struct thread *);
307397c19d1SJeff Roberson static void	unp_internalize_fp(struct file *);
308c2e3c52eSJilles Tjoelker static int	unp_externalize(struct mbuf *, struct mbuf **, int);
3090cb64678SKonstantin Belousov static int	unp_externalize_fp(struct file *);
310ede4af47SConrad Meyer static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *, int);
3110cb64678SKonstantin Belousov static void	unp_process_defers(void * __unused, int);
312f708ef1bSPoul-Henning Kamp 
31375a67bf3SMatt Macy static void
31475a67bf3SMatt Macy unp_pcb_hold(struct unpcb *unp)
31575a67bf3SMatt Macy {
3165362170dSMark Johnston 	u_int old __unused;
3175362170dSMark Johnston 
3185362170dSMark Johnston 	old = refcount_acquire(&unp->unp_refcount);
3195362170dSMark Johnston 	KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
32075a67bf3SMatt Macy }
32175a67bf3SMatt Macy 
3225362170dSMark Johnston static __result_use_check bool
32375a67bf3SMatt Macy unp_pcb_rele(struct unpcb *unp)
32475a67bf3SMatt Macy {
3255362170dSMark Johnston 	bool ret;
32675a67bf3SMatt Macy 
32775a67bf3SMatt Macy 	UNP_PCB_LOCK_ASSERT(unp);
3285362170dSMark Johnston 
3295362170dSMark Johnston 	if ((ret = refcount_release(&unp->unp_refcount))) {
33075a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
33175a67bf3SMatt Macy 		UNP_PCB_LOCK_DESTROY(unp);
33275a67bf3SMatt Macy 		uma_zfree(unp_zone, unp);
33375a67bf3SMatt Macy 	}
3345362170dSMark Johnston 	return (ret);
33575a67bf3SMatt Macy }
33675a67bf3SMatt Macy 
33775a67bf3SMatt Macy static void
338f0317f86SMark Johnston unp_pcb_rele_notlast(struct unpcb *unp)
339f0317f86SMark Johnston {
340f0317f86SMark Johnston 	bool ret __unused;
341f0317f86SMark Johnston 
342f0317f86SMark Johnston 	ret = refcount_release(&unp->unp_refcount);
343f0317f86SMark Johnston 	KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
344f0317f86SMark Johnston }
345f0317f86SMark Johnston 
346f0317f86SMark Johnston static void
3474820bf6aSMark Johnston unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
34875a67bf3SMatt Macy {
34975a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
35075a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp2);
3514820bf6aSMark Johnston 
3524820bf6aSMark Johnston 	if (unp == unp2) {
3534820bf6aSMark Johnston 		UNP_PCB_LOCK(unp);
3544820bf6aSMark Johnston 	} else if ((uintptr_t)unp2 > (uintptr_t)unp) {
35575a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
35675a67bf3SMatt Macy 		UNP_PCB_LOCK(unp2);
35775a67bf3SMatt Macy 	} else {
35875a67bf3SMatt Macy 		UNP_PCB_LOCK(unp2);
35975a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
36075a67bf3SMatt Macy 	}
36175a67bf3SMatt Macy }
36275a67bf3SMatt Macy 
3634820bf6aSMark Johnston static void
3644820bf6aSMark Johnston unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
3654820bf6aSMark Johnston {
3664820bf6aSMark Johnston 	UNP_PCB_UNLOCK(unp);
3674820bf6aSMark Johnston 	if (unp != unp2)
3684820bf6aSMark Johnston 		UNP_PCB_UNLOCK(unp2);
3694820bf6aSMark Johnston }
3704820bf6aSMark Johnston 
371ccdadf1aSMark Johnston /*
372ccdadf1aSMark Johnston  * Try to lock the connected peer of an already locked socket.  In some cases
373ccdadf1aSMark Johnston  * this requires that we unlock the current socket.  The pairbusy counter is
374ccdadf1aSMark Johnston  * used to block concurrent connection attempts while the lock is dropped.  The
375ccdadf1aSMark Johnston  * caller must be careful to revalidate PCB state.
376ccdadf1aSMark Johnston  */
377ccdadf1aSMark Johnston static struct unpcb *
378ccdadf1aSMark Johnston unp_pcb_lock_peer(struct unpcb *unp)
37975a67bf3SMatt Macy {
38075a67bf3SMatt Macy 	struct unpcb *unp2;
38175a67bf3SMatt Macy 
382ccdadf1aSMark Johnston 	UNP_PCB_LOCK_ASSERT(unp);
383ccdadf1aSMark Johnston 	unp2 = unp->unp_conn;
3846404d7ffSMateusz Guzik 	if (unp2 == NULL)
385ccdadf1aSMark Johnston 		return (NULL);
386ccdadf1aSMark Johnston 	if (__predict_false(unp == unp2))
387ccdadf1aSMark Johnston 		return (unp);
388ccdadf1aSMark Johnston 
389ccdadf1aSMark Johnston 	UNP_PCB_UNLOCK_ASSERT(unp2);
390ccdadf1aSMark Johnston 
391ccdadf1aSMark Johnston 	if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
392ccdadf1aSMark Johnston 		return (unp2);
393ccdadf1aSMark Johnston 	if ((uintptr_t)unp2 > (uintptr_t)unp) {
394ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp2);
395ccdadf1aSMark Johnston 		return (unp2);
396ccdadf1aSMark Johnston 	}
397ccdadf1aSMark Johnston 	unp->unp_pairbusy++;
398e62ca80bSMark Johnston 	unp_pcb_hold(unp2);
399e62ca80bSMark Johnston 	UNP_PCB_UNLOCK(unp);
400ccdadf1aSMark Johnston 
401e62ca80bSMark Johnston 	UNP_PCB_LOCK(unp2);
402e62ca80bSMark Johnston 	UNP_PCB_LOCK(unp);
403ccdadf1aSMark Johnston 	KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
404ccdadf1aSMark Johnston 	    ("%s: socket %p was reconnected", __func__, unp));
405ccdadf1aSMark Johnston 	if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
406ccdadf1aSMark Johnston 		unp->unp_flags &= ~UNP_WAITING;
407ccdadf1aSMark Johnston 		wakeup(unp);
40875a67bf3SMatt Macy 	}
409ccdadf1aSMark Johnston 	if (unp_pcb_rele(unp2)) {
410ccdadf1aSMark Johnston 		/* unp2 is unlocked. */
411ccdadf1aSMark Johnston 		return (NULL);
412ccdadf1aSMark Johnston 	}
413ccdadf1aSMark Johnston 	if (unp->unp_conn == NULL) {
414ccdadf1aSMark Johnston 		UNP_PCB_UNLOCK(unp2);
415ccdadf1aSMark Johnston 		return (NULL);
416ccdadf1aSMark Johnston 	}
417ccdadf1aSMark Johnston 	return (unp2);
418ccdadf1aSMark Johnston }
41975a67bf3SMatt Macy 
420e4445a03SRobert Watson /*
421e4445a03SRobert Watson  * Definitions of protocols supported in the LOCAL domain.
422e4445a03SRobert Watson  */
423e4445a03SRobert Watson static struct domain localdomain;
424fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
42584d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket;
426e4445a03SRobert Watson static struct protosw localsw[] = {
427e4445a03SRobert Watson {
428e4445a03SRobert Watson 	.pr_type =		SOCK_STREAM,
429e4445a03SRobert Watson 	.pr_domain =		&localdomain,
43027457983SMark Johnston 	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|
43127457983SMark Johnston 				    PR_CAPATTACH,
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,
43827457983SMark Johnston 	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS|PR_CAPATTACH,
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 	 */
45127457983SMark Johnston 	.pr_flags =		PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|
45227457983SMark Johnston 				    PR_WANTRCVD|PR_RIGHTS|PR_CAPATTACH,
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_externalize =	unp_externalize,
46299ab95dbSMark Johnston 	.dom_dispose =		unp_dispose,
463e4445a03SRobert Watson 	.dom_protosw =		localsw,
46402abd400SPedro F. Giffuni 	.dom_protoswNPROTOSW =	&localsw[nitems(localsw)]
465e4445a03SRobert Watson };
466e4445a03SRobert Watson DOMAIN_SET(local);
467e4445a03SRobert Watson 
468ac45e92fSRobert Watson static void
469a29f300eSGarrett Wollman uipc_abort(struct socket *so)
470df8bae1dSRodney W. Grimes {
471e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
472df8bae1dSRodney W. Grimes 
47340f2ac28SRobert Watson 	unp = sotounpcb(so);
4744d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
47575a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
476e7c33e29SRobert Watson 
477e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
478e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
479e7c33e29SRobert Watson 	if (unp2 != NULL) {
48075a67bf3SMatt Macy 		unp_pcb_hold(unp2);
481e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
48275a67bf3SMatt Macy 		unp_drop(unp2);
48375a67bf3SMatt Macy 	} else
48475a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
485df8bae1dSRodney W. Grimes }
486df8bae1dSRodney W. Grimes 
487a29f300eSGarrett Wollman static int
48857bf258eSGarrett Wollman uipc_accept(struct socket *so, struct sockaddr **nam)
489a29f300eSGarrett Wollman {
490e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
4910d9ce3a1SRobert Watson 	const struct sockaddr *sa;
492df8bae1dSRodney W. Grimes 
493df8bae1dSRodney W. Grimes 	/*
4941c381b19SRobert Watson 	 * Pass back name of connected socket, if it was bound and we are
4951c381b19SRobert Watson 	 * still connected (our peer may have closed already!).
496df8bae1dSRodney W. Grimes 	 */
4974d4b555eSRobert Watson 	unp = sotounpcb(so);
4984d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
499e7c33e29SRobert Watson 
5000d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
50144800027SMark Johnston 	UNP_PCB_LOCK(unp);
50244800027SMark Johnston 	unp2 = unp_pcb_lock_peer(unp);
50344800027SMark Johnston 	if (unp2 != NULL && unp2->unp_addr != NULL)
504e7c33e29SRobert Watson 		sa = (struct sockaddr *)unp2->unp_addr;
50544800027SMark Johnston 	else
5060d9ce3a1SRobert Watson 		sa = &sun_noname;
5070d9ce3a1SRobert Watson 	bcopy(sa, *nam, sa->sa_len);
508b4e07e3dSMark Johnston 	if (unp2 != NULL)
50944800027SMark Johnston 		unp_pcb_unlock_pair(unp, unp2);
510b4e07e3dSMark Johnston 	else
511b4e07e3dSMark Johnston 		UNP_PCB_UNLOCK(unp);
512e5aeaa0cSDag-Erling Smørgrav 	return (0);
513a29f300eSGarrett Wollman }
514df8bae1dSRodney W. Grimes 
515a29f300eSGarrett Wollman static int
516b40ce416SJulian Elischer uipc_attach(struct socket *so, int proto, struct thread *td)
517a29f300eSGarrett Wollman {
518e7c33e29SRobert Watson 	u_long sendspace, recvspace;
5196d32873cSRobert Watson 	struct unpcb *unp;
5203dab55bcSRobert Watson 	int error;
521779f106aSGleb Smirnoff 	bool locked;
522df8bae1dSRodney W. Grimes 
5236d32873cSRobert Watson 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
5246d32873cSRobert Watson 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
5256d32873cSRobert Watson 		switch (so->so_type) {
5266d32873cSRobert Watson 		case SOCK_STREAM:
527e7c33e29SRobert Watson 			sendspace = unpst_sendspace;
528e7c33e29SRobert Watson 			recvspace = unpst_recvspace;
5296d32873cSRobert Watson 			break;
5306d32873cSRobert Watson 
5316d32873cSRobert Watson 		case SOCK_DGRAM:
532e7c33e29SRobert Watson 			sendspace = unpdg_sendspace;
533e7c33e29SRobert Watson 			recvspace = unpdg_recvspace;
5346d32873cSRobert Watson 			break;
5356d32873cSRobert Watson 
53684d61770SRobert Watson 		case SOCK_SEQPACKET:
53784d61770SRobert Watson 			sendspace = unpsp_sendspace;
53884d61770SRobert Watson 			recvspace = unpsp_recvspace;
53984d61770SRobert Watson 			break;
54084d61770SRobert Watson 
5416d32873cSRobert Watson 		default:
542e7c33e29SRobert Watson 			panic("uipc_attach");
5436d32873cSRobert Watson 		}
544e7c33e29SRobert Watson 		error = soreserve(so, sendspace, recvspace);
5456d32873cSRobert Watson 		if (error)
5466d32873cSRobert Watson 			return (error);
5476d32873cSRobert Watson 	}
54846a1d9bfSRobert Watson 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
5496d32873cSRobert Watson 	if (unp == NULL)
5506d32873cSRobert Watson 		return (ENOBUFS);
5516d32873cSRobert Watson 	LIST_INIT(&unp->unp_refs);
552e7c33e29SRobert Watson 	UNP_PCB_LOCK_INIT(unp);
5536d32873cSRobert Watson 	unp->unp_socket = so;
5546d32873cSRobert Watson 	so->so_pcb = unp;
5555362170dSMark Johnston 	refcount_init(&unp->unp_refcount, 1);
556e7c33e29SRobert Watson 
557779f106aSGleb Smirnoff 	if ((locked = UNP_LINK_WOWNED()) == false)
558779f106aSGleb Smirnoff 		UNP_LINK_WLOCK();
559779f106aSGleb Smirnoff 
5606d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
561f218ac50SMateusz Guzik 	unp->unp_ino = ++unp_ino;
5626d32873cSRobert Watson 	unp_count++;
56384d61770SRobert Watson 	switch (so->so_type) {
56484d61770SRobert Watson 	case SOCK_STREAM:
56584d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
56684d61770SRobert Watson 		break;
56784d61770SRobert Watson 
56884d61770SRobert Watson 	case SOCK_DGRAM:
56984d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
57084d61770SRobert Watson 		break;
57184d61770SRobert Watson 
57284d61770SRobert Watson 	case SOCK_SEQPACKET:
57384d61770SRobert Watson 		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
57484d61770SRobert Watson 		break;
57584d61770SRobert Watson 
57684d61770SRobert Watson 	default:
57784d61770SRobert Watson 		panic("uipc_attach");
57884d61770SRobert Watson 	}
579779f106aSGleb Smirnoff 
580779f106aSGleb Smirnoff 	if (locked == false)
581779f106aSGleb Smirnoff 		UNP_LINK_WUNLOCK();
5826d32873cSRobert Watson 
5836d32873cSRobert Watson 	return (0);
584a29f300eSGarrett Wollman }
585a29f300eSGarrett Wollman 
586a29f300eSGarrett Wollman static int
5877493f24eSPawel Jakub Dawidek uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
588a29f300eSGarrett Wollman {
589dd47f5caSRobert Watson 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
590dd47f5caSRobert Watson 	struct vattr vattr;
5915050aa86SKonstantin Belousov 	int error, namelen;
592dd47f5caSRobert Watson 	struct nameidata nd;
59340f2ac28SRobert Watson 	struct unpcb *unp;
594dd47f5caSRobert Watson 	struct vnode *vp;
595dd47f5caSRobert Watson 	struct mount *mp;
5967008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
597dd47f5caSRobert Watson 	char *buf;
598a29f300eSGarrett Wollman 
599cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
600cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
601cb7df69bSKevin Lo 
60240f2ac28SRobert Watson 	unp = sotounpcb(so);
6034d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
6044f1f0ef5SRobert Watson 
605a06534c3SBjoern A. Zeeb 	if (soun->sun_len > sizeof(struct sockaddr_un))
606a06534c3SBjoern A. Zeeb 		return (EINVAL);
6074f1f0ef5SRobert Watson 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
6084f1f0ef5SRobert Watson 	if (namelen <= 0)
6094f1f0ef5SRobert Watson 		return (EINVAL);
610dd47f5caSRobert Watson 
611dd47f5caSRobert Watson 	/*
6124f1f0ef5SRobert Watson 	 * We don't allow simultaneous bind() calls on a single UNIX domain
6134f1f0ef5SRobert Watson 	 * socket, so flag in-progress operations, and return an error if an
6144f1f0ef5SRobert Watson 	 * operation is already in progress.
6154f1f0ef5SRobert Watson 	 *
6164f1f0ef5SRobert Watson 	 * Historically, we have not allowed a socket to be rebound, so this
617d7924b70SRobert Watson 	 * also returns an error.  Not allowing re-binding simplifies the
618d7924b70SRobert Watson 	 * implementation and avoids a great many possible failure modes.
619dd47f5caSRobert Watson 	 */
620e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
621dd47f5caSRobert Watson 	if (unp->unp_vnode != NULL) {
622e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
623dd47f5caSRobert Watson 		return (EINVAL);
624dd47f5caSRobert Watson 	}
6254f1f0ef5SRobert Watson 	if (unp->unp_flags & UNP_BINDING) {
626e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
6274f1f0ef5SRobert Watson 		return (EALREADY);
628dd47f5caSRobert Watson 	}
6294f1f0ef5SRobert Watson 	unp->unp_flags |= UNP_BINDING;
630e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
631dd47f5caSRobert Watson 
632dd47f5caSRobert Watson 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
6337928893dSEd Maste 	bcopy(soun->sun_path, buf, namelen);
6347928893dSEd Maste 	buf[namelen] = 0;
635dd47f5caSRobert Watson 
636dd47f5caSRobert Watson restart:
6376c21f6edSKonstantin Belousov 	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
6387e1d3eefSMateusz Guzik 	    UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
639dd47f5caSRobert Watson /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
640dd47f5caSRobert Watson 	error = namei(&nd);
641dd47f5caSRobert Watson 	if (error)
6424f1f0ef5SRobert Watson 		goto error;
643dd47f5caSRobert Watson 	vp = nd.ni_vp;
644dd47f5caSRobert Watson 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
645dd47f5caSRobert Watson 		NDFREE(&nd, NDF_ONLY_PNBUF);
646dd47f5caSRobert Watson 		if (nd.ni_dvp == vp)
647dd47f5caSRobert Watson 			vrele(nd.ni_dvp);
648dd47f5caSRobert Watson 		else
649dd47f5caSRobert Watson 			vput(nd.ni_dvp);
650dd47f5caSRobert Watson 		if (vp != NULL) {
651dd47f5caSRobert Watson 			vrele(vp);
652dd47f5caSRobert Watson 			error = EADDRINUSE;
6534f1f0ef5SRobert Watson 			goto error;
654dd47f5caSRobert Watson 		}
655dd47f5caSRobert Watson 		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
656dd47f5caSRobert Watson 		if (error)
6574f1f0ef5SRobert Watson 			goto error;
658dd47f5caSRobert Watson 		goto restart;
659dd47f5caSRobert Watson 	}
660dd47f5caSRobert Watson 	VATTR_NULL(&vattr);
661dd47f5caSRobert Watson 	vattr.va_type = VSOCK;
66285078b85SConrad Meyer 	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
663dd47f5caSRobert Watson #ifdef MAC
66430d239bcSRobert Watson 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
665dd47f5caSRobert Watson 	    &vattr);
666dd47f5caSRobert Watson #endif
667885868cdSRobert Watson 	if (error == 0)
668dd47f5caSRobert Watson 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
669dd47f5caSRobert Watson 	NDFREE(&nd, NDF_ONLY_PNBUF);
670dd47f5caSRobert Watson 	if (error) {
6713b2aa360SKonstantin Belousov 		VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
672dd47f5caSRobert Watson 		vn_finished_write(mp);
673441eb16aSKonstantin Belousov 		if (error == ERELOOKUP)
674441eb16aSKonstantin Belousov 			goto restart;
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);
6873b2aa360SKonstantin Belousov 	vref(vp);
6883b2aa360SKonstantin Belousov 	VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
689dd47f5caSRobert Watson 	vn_finished_write(mp);
6904f1f0ef5SRobert Watson 	free(buf, M_TEMP);
6914f1f0ef5SRobert Watson 	return (0);
692e7c33e29SRobert Watson 
6934f1f0ef5SRobert Watson error:
694e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
6954f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_BINDING;
696e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
697dd47f5caSRobert Watson 	free(buf, M_TEMP);
69840f2ac28SRobert Watson 	return (error);
699a29f300eSGarrett Wollman }
700a29f300eSGarrett Wollman 
701a29f300eSGarrett Wollman static int
7027493f24eSPawel Jakub Dawidek uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
7037493f24eSPawel Jakub Dawidek {
7047493f24eSPawel Jakub Dawidek 
7057493f24eSPawel Jakub Dawidek 	return (uipc_bindat(AT_FDCWD, so, nam, td));
7067493f24eSPawel Jakub Dawidek }
7077493f24eSPawel Jakub Dawidek 
7087493f24eSPawel Jakub Dawidek static int
709b40ce416SJulian Elischer uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
710a29f300eSGarrett Wollman {
7110d9ce3a1SRobert Watson 	int error;
712a29f300eSGarrett Wollman 
713fd179ee9SRobert Watson 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
714fd179ee9SRobert Watson 	error = unp_connect(so, nam, td);
7150d9ce3a1SRobert Watson 	return (error);
716a29f300eSGarrett Wollman }
717a29f300eSGarrett Wollman 
7187493f24eSPawel Jakub Dawidek static int
7197493f24eSPawel Jakub Dawidek uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
7207493f24eSPawel Jakub Dawidek     struct thread *td)
7217493f24eSPawel Jakub Dawidek {
7227493f24eSPawel Jakub Dawidek 	int error;
7237493f24eSPawel Jakub Dawidek 
7247493f24eSPawel Jakub Dawidek 	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
7257493f24eSPawel Jakub Dawidek 	error = unp_connectat(fd, so, nam, td);
7267493f24eSPawel Jakub Dawidek 	return (error);
7277493f24eSPawel Jakub Dawidek }
7287493f24eSPawel Jakub Dawidek 
729a152f8a3SRobert Watson static void
730a152f8a3SRobert Watson uipc_close(struct socket *so)
731a152f8a3SRobert Watson {
732e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
733779f106aSGleb Smirnoff 	struct vnode *vp = NULL;
73475a67bf3SMatt Macy 	struct mtx *vplock;
735ccdadf1aSMark Johnston 
736a152f8a3SRobert Watson 	unp = sotounpcb(so);
737a152f8a3SRobert Watson 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
738e7c33e29SRobert Watson 
73975a67bf3SMatt Macy 	vplock = NULL;
74075a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
74175a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
74275a67bf3SMatt Macy 		mtx_lock(vplock);
743e7c33e29SRobert Watson 	}
74475a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
74575a67bf3SMatt Macy 	if (vp && unp->unp_vnode == NULL) {
74675a67bf3SMatt Macy 		mtx_unlock(vplock);
74775a67bf3SMatt Macy 		vp = NULL;
74875a67bf3SMatt Macy 	}
74975a67bf3SMatt Macy 	if (vp != NULL) {
750779f106aSGleb Smirnoff 		VOP_UNP_DETACH(vp);
751779f106aSGleb Smirnoff 		unp->unp_vnode = NULL;
752779f106aSGleb Smirnoff 	}
753ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
754acf9fd05SMatt Macy 		unp_disconnect(unp, unp2);
755ccdadf1aSMark Johnston 	else
756e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
75775a67bf3SMatt Macy 	if (vp) {
75875a67bf3SMatt Macy 		mtx_unlock(vplock);
759779f106aSGleb Smirnoff 		vrele(vp);
760a152f8a3SRobert Watson 	}
76175a67bf3SMatt Macy }
762a152f8a3SRobert Watson 
7632c899584SRobert Watson static int
764a29f300eSGarrett Wollman uipc_connect2(struct socket *so1, struct socket *so2)
765a29f300eSGarrett Wollman {
766e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
7670d9ce3a1SRobert Watson 	int error;
768a29f300eSGarrett Wollman 
769e7c33e29SRobert Watson 	unp = so1->so_pcb;
7704d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
771e7c33e29SRobert Watson 	unp2 = so2->so_pcb;
772e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
7734820bf6aSMark Johnston 	unp_pcb_lock_pair(unp, unp2);
7746a2989fdSMatthew N. Dodd 	error = unp_connect2(so1, so2, PRU_CONNECT2);
7754820bf6aSMark Johnston 	unp_pcb_unlock_pair(unp, unp2);
7760d9ce3a1SRobert Watson 	return (error);
777a29f300eSGarrett Wollman }
778a29f300eSGarrett Wollman 
779bc725eafSRobert Watson static void
780a29f300eSGarrett Wollman uipc_detach(struct socket *so)
781a29f300eSGarrett Wollman {
782e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
78375a67bf3SMatt Macy 	struct mtx *vplock;
7846d32873cSRobert Watson 	struct vnode *vp;
785ccdadf1aSMark Johnston 	int local_unp_rights;
786a29f300eSGarrett Wollman 
78740f2ac28SRobert Watson 	unp = sotounpcb(so);
7884d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
789e7c33e29SRobert Watson 
790434ac8b6SMark Johnston 	vp = NULL;
791c0874c34SMatt Macy 	vplock = NULL;
792434ac8b6SMark Johnston 
793a50b1900SMark Johnston 	SOCK_LOCK(so);
794a50b1900SMark Johnston 	if (!SOLISTENING(so)) {
795a50b1900SMark Johnston 		/*
796a50b1900SMark Johnston 		 * Once the socket is removed from the global lists,
797a50b1900SMark Johnston 		 * uipc_ready() will not be able to locate its socket buffer, so
798a50b1900SMark Johnston 		 * clear the buffer now.  At this point internalized rights have
799a50b1900SMark Johnston 		 * already been disposed of.
800a50b1900SMark Johnston 		 */
801a50b1900SMark Johnston 		sbrelease(&so->so_rcv, so);
802a50b1900SMark Johnston 	}
803a50b1900SMark Johnston 	SOCK_UNLOCK(so);
804a50b1900SMark Johnston 
805779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
8066d32873cSRobert Watson 	LIST_REMOVE(unp, unp_link);
807a9aa06f7SJason A. Harmening 	if (unp->unp_gcflag & UNPGC_DEAD)
808a9aa06f7SJason A. Harmening 		LIST_REMOVE(unp, unp_dead);
8096d32873cSRobert Watson 	unp->unp_gencnt = ++unp_gencnt;
8106d32873cSRobert Watson 	--unp_count;
81175a67bf3SMatt Macy 	UNP_LINK_WUNLOCK();
812434ac8b6SMark Johnston 
81375a67bf3SMatt Macy 	UNP_PCB_UNLOCK_ASSERT(unp);
81475a67bf3SMatt Macy  restart:
81575a67bf3SMatt Macy 	if ((vp = unp->unp_vnode) != NULL) {
81675a67bf3SMatt Macy 		vplock = mtx_pool_find(mtxpool_sleep, vp);
81775a67bf3SMatt Macy 		mtx_lock(vplock);
81875a67bf3SMatt Macy 	}
81975a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
820db38b699SMark Johnston 	if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
821c0874c34SMatt Macy 		if (vplock)
82275a67bf3SMatt Macy 			mtx_unlock(vplock);
82375a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
82475a67bf3SMatt Macy 		goto restart;
82575a67bf3SMatt Macy 	}
8266d32873cSRobert Watson 	if ((vp = unp->unp_vnode) != NULL) {
827c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
8286d32873cSRobert Watson 		unp->unp_vnode = NULL;
8296d32873cSRobert Watson 	}
830ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
831e7c33e29SRobert Watson 		unp_disconnect(unp, unp2);
832f0317f86SMark Johnston 	else
83375a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
834ccdadf1aSMark Johnston 
83575a67bf3SMatt Macy 	UNP_REF_LIST_LOCK();
8366d32873cSRobert Watson 	while (!LIST_EMPTY(&unp->unp_refs)) {
8376d32873cSRobert Watson 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
838e7c33e29SRobert Watson 
83975a67bf3SMatt Macy 		unp_pcb_hold(ref);
84075a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
84175a67bf3SMatt Macy 
84275a67bf3SMatt Macy 		MPASS(ref != unp);
84375a67bf3SMatt Macy 		UNP_PCB_UNLOCK_ASSERT(ref);
844afc055d9SEd Schouten 		unp_drop(ref);
84575a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
8466d32873cSRobert Watson 	}
84775a67bf3SMatt Macy 	UNP_REF_LIST_UNLOCK();
848ccdadf1aSMark Johnston 
84975a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
850397c19d1SJeff Roberson 	local_unp_rights = unp_rights;
8516d32873cSRobert Watson 	unp->unp_socket->so_pcb = NULL;
85275a67bf3SMatt Macy 	unp->unp_socket = NULL;
853db38b699SMark Johnston 	free(unp->unp_addr, M_SONAME);
854db38b699SMark Johnston 	unp->unp_addr = NULL;
855db38b699SMark Johnston 	if (!unp_pcb_rele(unp))
8566e2faa24SRobert Watson 		UNP_PCB_UNLOCK(unp);
85775a67bf3SMatt Macy 	if (vp) {
85875a67bf3SMatt Macy 		mtx_unlock(vplock);
8596d32873cSRobert Watson 		vrele(vp);
86075a67bf3SMatt Macy 	}
8616d32873cSRobert Watson 	if (local_unp_rights)
862daee0f0bSKonstantin Belousov 		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
863a29f300eSGarrett Wollman }
864a29f300eSGarrett Wollman 
865a29f300eSGarrett Wollman static int
866a29f300eSGarrett Wollman uipc_disconnect(struct socket *so)
867a29f300eSGarrett Wollman {
868e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
869a29f300eSGarrett Wollman 
87040f2ac28SRobert Watson 	unp = sotounpcb(so);
8714d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
872e7c33e29SRobert Watson 
873e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
874ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
87575a67bf3SMatt Macy 		unp_disconnect(unp, unp2);
876ccdadf1aSMark Johnston 	else
877ccdadf1aSMark Johnston 		UNP_PCB_UNLOCK(unp);
878e5aeaa0cSDag-Erling Smørgrav 	return (0);
879a29f300eSGarrett Wollman }
880a29f300eSGarrett Wollman 
881a29f300eSGarrett Wollman static int
882d374e81eSRobert Watson uipc_listen(struct socket *so, int backlog, struct thread *td)
883a29f300eSGarrett Wollman {
88440f2ac28SRobert Watson 	struct unpcb *unp;
8850d9ce3a1SRobert Watson 	int error;
886a29f300eSGarrett Wollman 
887beb4b312SGleb Smirnoff 	if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
888beb4b312SGleb Smirnoff 		return (EOPNOTSUPP);
889beb4b312SGleb Smirnoff 
890bd4a39ccSMark Johnston 	/*
891bd4a39ccSMark Johnston 	 * Synchronize with concurrent connection attempts.
892bd4a39ccSMark Johnston 	 */
893bd4a39ccSMark Johnston 	error = 0;
89440f2ac28SRobert Watson 	unp = sotounpcb(so);
895e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
896bd4a39ccSMark Johnston 	if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
897bd4a39ccSMark Johnston 		error = EINVAL;
898bd4a39ccSMark Johnston 	else if (unp->unp_vnode == NULL)
899bd4a39ccSMark Johnston 		error = EDESTADDRREQ;
900bd4a39ccSMark Johnston 	if (error != 0) {
901e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
90247a84387SEd Schouten 		return (error);
90340f2ac28SRobert Watson 	}
904e7c33e29SRobert Watson 
905e7c33e29SRobert Watson 	SOCK_LOCK(so);
906e7c33e29SRobert Watson 	error = solisten_proto_check(so);
907e7c33e29SRobert Watson 	if (error == 0) {
908c5afec6eSDmitry Chagin 		cru2xt(td, &unp->unp_peercred);
909e7c33e29SRobert Watson 		solisten_proto(so, backlog);
910e7c33e29SRobert Watson 	}
911e7c33e29SRobert Watson 	SOCK_UNLOCK(so);
912e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
9130d9ce3a1SRobert Watson 	return (error);
914a29f300eSGarrett Wollman }
915a29f300eSGarrett Wollman 
916a29f300eSGarrett Wollman static int
91757bf258eSGarrett Wollman uipc_peeraddr(struct socket *so, struct sockaddr **nam)
918a29f300eSGarrett Wollman {
919e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
9200d9ce3a1SRobert Watson 	const struct sockaddr *sa;
921a29f300eSGarrett Wollman 
9224d4b555eSRobert Watson 	unp = sotounpcb(so);
9234d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
924e7c33e29SRobert Watson 
9250d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
926afd9f91cSJohn Baldwin 	UNP_LINK_RLOCK();
927bdc5f6a3SHajimu UMEMOTO 	/*
928e7c33e29SRobert Watson 	 * XXX: It seems that this test always fails even when connection is
929e7c33e29SRobert Watson 	 * established.  So, this else clause is added as workaround to
930e7c33e29SRobert Watson 	 * return PF_LOCAL sockaddr.
931bdc5f6a3SHajimu UMEMOTO 	 */
932e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
933e7c33e29SRobert Watson 	if (unp2 != NULL) {
934e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp2);
935e7c33e29SRobert Watson 		if (unp2->unp_addr != NULL)
936afd9f91cSJohn Baldwin 			sa = (struct sockaddr *) unp2->unp_addr;
937e7c33e29SRobert Watson 		else
9380d9ce3a1SRobert Watson 			sa = &sun_noname;
9390d9ce3a1SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
940e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
941e7c33e29SRobert Watson 	} else {
942e7c33e29SRobert Watson 		sa = &sun_noname;
943e7c33e29SRobert Watson 		bcopy(sa, *nam, sa->sa_len);
944e7c33e29SRobert Watson 	}
945afd9f91cSJohn Baldwin 	UNP_LINK_RUNLOCK();
946e5aeaa0cSDag-Erling Smørgrav 	return (0);
947a29f300eSGarrett Wollman }
948a29f300eSGarrett Wollman 
949a29f300eSGarrett Wollman static int
950a29f300eSGarrett Wollman uipc_rcvd(struct socket *so, int flags)
951a29f300eSGarrett Wollman {
952e7c33e29SRobert Watson 	struct unpcb *unp, *unp2;
953a29f300eSGarrett Wollman 	struct socket *so2;
954337cc6b6SRobert Watson 	u_int mbcnt, sbcc;
955a29f300eSGarrett Wollman 
95640f2ac28SRobert Watson 	unp = sotounpcb(so);
9572b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
9582b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
9592b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
960e7c33e29SRobert Watson 
961df8bae1dSRodney W. Grimes 	/*
962e7c33e29SRobert Watson 	 * Adjust backpressure on sender and wakeup any waiting to write.
963e7c33e29SRobert Watson 	 *
964d7924b70SRobert Watson 	 * The unp lock is acquired to maintain the validity of the unp_conn
965d7924b70SRobert Watson 	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
966d7924b70SRobert Watson 	 * static as long as we don't permit unp2 to disconnect from unp,
967d7924b70SRobert Watson 	 * which is prevented by the lock on unp.  We cache values from
968d7924b70SRobert Watson 	 * so_rcv to avoid holding the so_rcv lock over the entire
969d7924b70SRobert Watson 	 * transaction on the remote so_snd.
970df8bae1dSRodney W. Grimes 	 */
971337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so->so_rcv);
972337cc6b6SRobert Watson 	mbcnt = so->so_rcv.sb_mbcnt;
9732b21d0e8SGleb Smirnoff 	sbcc = sbavail(&so->so_rcv);
974337cc6b6SRobert Watson 	SOCKBUF_UNLOCK(&so->so_rcv);
975c2090e73SAlan Somers 	/*
976c2090e73SAlan Somers 	 * There is a benign race condition at this point.  If we're planning to
977c2090e73SAlan Somers 	 * clear SB_STOP, but uipc_send is called on the connected socket at
978c2090e73SAlan Somers 	 * this instant, it might add data to the sockbuf and set SB_STOP.  Then
979c2090e73SAlan Somers 	 * we would erroneously clear SB_STOP below, even though the sockbuf is
980c2090e73SAlan Somers 	 * full.  The race is benign because the only ill effect is to allow the
981c2090e73SAlan Somers 	 * sockbuf to exceed its size limit, and the size limits are not
982c2090e73SAlan Somers 	 * strictly guaranteed anyway.
983c2090e73SAlan Somers 	 */
984e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
985e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
986e7c33e29SRobert Watson 	if (unp2 == NULL) {
987e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
988e7c33e29SRobert Watson 		return (0);
989337cc6b6SRobert Watson 	}
990e7c33e29SRobert Watson 	so2 = unp2->unp_socket;
991337cc6b6SRobert Watson 	SOCKBUF_LOCK(&so2->so_snd);
992c2090e73SAlan Somers 	if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
993c2090e73SAlan Somers 		so2->so_snd.sb_flags &= ~SB_STOP;
9941e4d7da7SRobert Watson 	sowwakeup_locked(so2);
995e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
996e5aeaa0cSDag-Erling Smørgrav 	return (0);
997a29f300eSGarrett Wollman }
998df8bae1dSRodney W. Grimes 
999a29f300eSGarrett Wollman static int
100057bf258eSGarrett Wollman uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1001b40ce416SJulian Elischer     struct mbuf *control, struct thread *td)
1002a29f300eSGarrett Wollman {
1003f3f49bbbSRobert Watson 	struct unpcb *unp, *unp2;
1004a29f300eSGarrett Wollman 	struct socket *so2;
1005c2090e73SAlan Somers 	u_int mbcnt, sbcc;
100642188bb5SMark Johnston 	int error;
1007a29f300eSGarrett Wollman 
100840f2ac28SRobert Watson 	unp = sotounpcb(so);
10092b21d0e8SGleb Smirnoff 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
10102b21d0e8SGleb Smirnoff 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
10112b21d0e8SGleb Smirnoff 	    so->so_type == SOCK_SEQPACKET,
10122b21d0e8SGleb Smirnoff 	    ("%s: socktype %d", __func__, so->so_type));
1013e7c33e29SRobert Watson 
101442188bb5SMark Johnston 	error = 0;
1015a29f300eSGarrett Wollman 	if (flags & PRUS_OOB) {
1016a29f300eSGarrett Wollman 		error = EOPNOTSUPP;
1017a29f300eSGarrett Wollman 		goto release;
1018a29f300eSGarrett Wollman 	}
1019fc3fcacfSRobert Watson 	if (control != NULL && (error = unp_internalize(&control, td)))
1020a29f300eSGarrett Wollman 		goto release;
102175a67bf3SMatt Macy 
102275a67bf3SMatt Macy 	unp2 = NULL;
1023a29f300eSGarrett Wollman 	switch (so->so_type) {
1024a29f300eSGarrett Wollman 	case SOCK_DGRAM:
1025a29f300eSGarrett Wollman 	{
1026e7dd9a10SRobert Watson 		const struct sockaddr *from;
1027df8bae1dSRodney W. Grimes 
1028fc3fcacfSRobert Watson 		if (nam != NULL) {
1029ccdadf1aSMark Johnston 			error = unp_connect(so, nam, td);
1030ccdadf1aSMark Johnston 			if (error != 0)
1031df8bae1dSRodney W. Grimes 				break;
1032ccdadf1aSMark Johnston 		}
103375a67bf3SMatt Macy 		UNP_PCB_LOCK(unp);
103460a5ef26SRobert Watson 
1035b5ff0914SRobert Watson 		/*
1036b5ff0914SRobert Watson 		 * Because connect() and send() are non-atomic in a sendto()
1037b5ff0914SRobert Watson 		 * with a target address, it's possible that the socket will
1038b5ff0914SRobert Watson 		 * have disconnected before the send() can run.  In that case
1039b5ff0914SRobert Watson 		 * return the slightly counter-intuitive but otherwise
1040b5ff0914SRobert Watson 		 * correct error that the socket is not connected.
1041b5ff0914SRobert Watson 		 */
1042ccdadf1aSMark Johnston 		unp2 = unp_pcb_lock_peer(unp);
1043ccdadf1aSMark Johnston 		if (unp2 == NULL) {
104475a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
1045b5ff0914SRobert Watson 			error = ENOTCONN;
1046b5ff0914SRobert Watson 			break;
1047b5ff0914SRobert Watson 		}
1048ccdadf1aSMark Johnston 
10492de07e40SConrad Meyer 		if (unp2->unp_flags & UNP_WANTCRED_MASK)
1050ede4af47SConrad Meyer 			control = unp_addsockcred(td, control,
1051ede4af47SConrad Meyer 			    unp2->unp_flags);
1052fc3fcacfSRobert Watson 		if (unp->unp_addr != NULL)
105357bf258eSGarrett Wollman 			from = (struct sockaddr *)unp->unp_addr;
1054df8bae1dSRodney W. Grimes 		else
1055df8bae1dSRodney W. Grimes 			from = &sun_noname;
1056ede6e136SRobert Watson 		so2 = unp2->unp_socket;
1057a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
10586dde7ecbSPeter Wemm 		if (sbappendaddr_locked(&so2->so_rcv, from, m,
10598de34a88SAlan Somers 		    control)) {
10601e4d7da7SRobert Watson 			sorwakeup_locked(so2);
1061fc3fcacfSRobert Watson 			m = NULL;
1062fc3fcacfSRobert Watson 			control = NULL;
1063e5aeaa0cSDag-Erling Smørgrav 		} else {
10647045b160SRoy Marples 			soroverflow_locked(so2);
1065df8bae1dSRodney W. Grimes 			error = ENOBUFS;
1066e5aeaa0cSDag-Erling Smørgrav 		}
106775a67bf3SMatt Macy 		if (nam != NULL)
1068e7c33e29SRobert Watson 			unp_disconnect(unp, unp2);
1069f0317f86SMark Johnston 		else
1070f0317f86SMark Johnston 			unp_pcb_unlock_pair(unp, unp2);
1071df8bae1dSRodney W. Grimes 		break;
1072df8bae1dSRodney W. Grimes 	}
1073df8bae1dSRodney W. Grimes 
107484d61770SRobert Watson 	case SOCK_SEQPACKET:
1075df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
1076402cc72dSDavid Greenman 		if ((so->so_state & SS_ISCONNECTED) == 0) {
1077fc3fcacfSRobert Watson 			if (nam != NULL) {
1078ccdadf1aSMark Johnston 				error = unp_connect(so, nam, td);
1079b36871afSMark Johnston 				if (error != 0)
108075a67bf3SMatt Macy 					break;
1081402cc72dSDavid Greenman 			} else {
1082402cc72dSDavid Greenman 				error = ENOTCONN;
1083402cc72dSDavid Greenman 				break;
1084402cc72dSDavid Greenman 			}
1085b36871afSMark Johnston 		}
1086b36871afSMark Johnston 
1087ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp);
1088ccdadf1aSMark Johnston 		if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
108975a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp);
1090b5ff0914SRobert Watson 			error = ENOTCONN;
1091b5ff0914SRobert Watson 			break;
1092b36871afSMark Johnston 		} else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1093ccdadf1aSMark Johnston 			unp_pcb_unlock_pair(unp, unp2);
1094b36871afSMark Johnston 			error = EPIPE;
1095b36871afSMark Johnston 			break;
109675a67bf3SMatt Macy 		}
109775a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
109875a67bf3SMatt Macy 		if ((so2 = unp2->unp_socket) == NULL) {
109975a67bf3SMatt Macy 			UNP_PCB_UNLOCK(unp2);
110075a67bf3SMatt Macy 			error = ENOTCONN;
110175a67bf3SMatt Macy 			break;
110275a67bf3SMatt Macy 		}
1103a34b7046SRobert Watson 		SOCKBUF_LOCK(&so2->so_rcv);
11042de07e40SConrad Meyer 		if (unp2->unp_flags & UNP_WANTCRED_MASK) {
11056a2989fdSMatthew N. Dodd 			/*
11062de07e40SConrad Meyer 			 * Credentials are passed only once on SOCK_STREAM and
11072de07e40SConrad Meyer 			 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
11082de07e40SConrad Meyer 			 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
11096a2989fdSMatthew N. Dodd 			 */
1110ede4af47SConrad Meyer 			control = unp_addsockcred(td, control, unp2->unp_flags);
11112de07e40SConrad Meyer 			unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
11126a2989fdSMatthew N. Dodd 		}
11135b0480f2SMark Johnston 
1114df8bae1dSRodney W. Grimes 		/*
11155b0480f2SMark Johnston 		 * Send to paired receive port and wake up readers.  Don't
11165b0480f2SMark Johnston 		 * check for space available in the receive buffer if we're
11175b0480f2SMark Johnston 		 * attaching ancillary data; Unix domain sockets only check
11185b0480f2SMark Johnston 		 * for space in the sending sockbuf, and that check is
11195b0480f2SMark Johnston 		 * performed one level up the stack.  At that level we cannot
11205b0480f2SMark Johnston 		 * precisely account for the amount of buffer space used
11215b0480f2SMark Johnston 		 * (e.g., because control messages are not yet internalized).
1122df8bae1dSRodney W. Grimes 		 */
112384d61770SRobert Watson 		switch (so->so_type) {
112484d61770SRobert Watson 		case SOCK_STREAM:
1125fc3fcacfSRobert Watson 			if (control != NULL) {
11265b0480f2SMark Johnston 				sbappendcontrol_locked(&so2->so_rcv, m,
112725f4ddfbSMark Johnston 				    control, flags);
1128fc3fcacfSRobert Watson 				control = NULL;
1129e7c33e29SRobert Watson 			} else
1130829fae90SGleb Smirnoff 				sbappend_locked(&so2->so_rcv, m, flags);
113184d61770SRobert Watson 			break;
113284d61770SRobert Watson 
1133b36871afSMark Johnston 		case SOCK_SEQPACKET:
11348de34a88SAlan Somers 			if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1135b36871afSMark Johnston 			    &sun_noname, m, control))
113684d61770SRobert Watson 				control = NULL;
113784d61770SRobert Watson 			break;
113884d61770SRobert Watson 		}
113984d61770SRobert Watson 
1140c2090e73SAlan Somers 		mbcnt = so2->so_rcv.sb_mbcnt;
11412b21d0e8SGleb Smirnoff 		sbcc = sbavail(&so2->so_rcv);
11422b21d0e8SGleb Smirnoff 		if (sbcc)
1143337cc6b6SRobert Watson 			sorwakeup_locked(so2);
11442b21d0e8SGleb Smirnoff 		else
11452b21d0e8SGleb Smirnoff 			SOCKBUF_UNLOCK(&so2->so_rcv);
1146337cc6b6SRobert Watson 
1147c2090e73SAlan Somers 		/*
1148c2090e73SAlan Somers 		 * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1149c2090e73SAlan Somers 		 * it would be possible for uipc_rcvd to be called at this
1150c2090e73SAlan Somers 		 * point, drain the receiving sockbuf, clear SB_STOP, and then
1151c2090e73SAlan Somers 		 * we would set SB_STOP below.  That could lead to an empty
1152c2090e73SAlan Somers 		 * sockbuf having SB_STOP set
1153c2090e73SAlan Somers 		 */
1154337cc6b6SRobert Watson 		SOCKBUF_LOCK(&so->so_snd);
1155c2090e73SAlan Somers 		if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1156c2090e73SAlan Somers 			so->so_snd.sb_flags |= SB_STOP;
11577abe2ac2SAlan Cox 		SOCKBUF_UNLOCK(&so->so_snd);
1158e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1159fc3fcacfSRobert Watson 		m = NULL;
1160df8bae1dSRodney W. Grimes 		break;
1161df8bae1dSRodney W. Grimes 	}
1162a29f300eSGarrett Wollman 
11636b8fda4dSGarrett Wollman 	/*
116460a5ef26SRobert Watson 	 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
11656b8fda4dSGarrett Wollman 	 */
1166a29f300eSGarrett Wollman 	if (flags & PRUS_EOF) {
1167ede6e136SRobert Watson 		UNP_PCB_LOCK(unp);
11686b8fda4dSGarrett Wollman 		socantsendmore(so);
11696b8fda4dSGarrett Wollman 		unp_shutdown(unp);
1170e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
1171ede6e136SRobert Watson 	}
1172fc3fcacfSRobert Watson 	if (control != NULL && error != 0)
117399ab95dbSMark Johnston 		unp_dispose_mbuf(control);
1174bd508d39SDon Lewis 
1175a29f300eSGarrett Wollman release:
1176fc3fcacfSRobert Watson 	if (control != NULL)
1177a29f300eSGarrett Wollman 		m_freem(control);
1178100db364SGleb Smirnoff 	/*
1179100db364SGleb Smirnoff 	 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1180100db364SGleb Smirnoff 	 * for freeing memory.
1181100db364SGleb Smirnoff 	 */
1182100db364SGleb Smirnoff 	if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1183a29f300eSGarrett Wollman 		m_freem(m);
1184e5aeaa0cSDag-Erling Smørgrav 	return (error);
1185a29f300eSGarrett Wollman }
1186df8bae1dSRodney W. Grimes 
1187a50b1900SMark Johnston static bool
1188a50b1900SMark Johnston uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1189a50b1900SMark Johnston {
1190a50b1900SMark Johnston 	struct mbuf *mb, *n;
1191a50b1900SMark Johnston 	struct sockbuf *sb;
1192a50b1900SMark Johnston 
1193a50b1900SMark Johnston 	SOCK_LOCK(so);
1194a50b1900SMark Johnston 	if (SOLISTENING(so)) {
1195a50b1900SMark Johnston 		SOCK_UNLOCK(so);
1196a50b1900SMark Johnston 		return (false);
1197a50b1900SMark Johnston 	}
1198a50b1900SMark Johnston 	mb = NULL;
1199a50b1900SMark Johnston 	sb = &so->so_rcv;
1200a50b1900SMark Johnston 	SOCKBUF_LOCK(sb);
1201a50b1900SMark Johnston 	if (sb->sb_fnrdy != NULL) {
1202a50b1900SMark Johnston 		for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1203a50b1900SMark Johnston 			if (mb == m) {
1204a50b1900SMark Johnston 				*errorp = sbready(sb, m, count);
1205a50b1900SMark Johnston 				break;
1206a50b1900SMark Johnston 			}
1207a50b1900SMark Johnston 			mb = mb->m_next;
1208a50b1900SMark Johnston 			if (mb == NULL) {
1209a50b1900SMark Johnston 				mb = n;
12101b778ba2SMark Johnston 				if (mb != NULL)
1211a50b1900SMark Johnston 					n = mb->m_nextpkt;
1212a50b1900SMark Johnston 			}
1213a50b1900SMark Johnston 		}
1214a50b1900SMark Johnston 	}
1215a50b1900SMark Johnston 	SOCKBUF_UNLOCK(sb);
1216a50b1900SMark Johnston 	SOCK_UNLOCK(so);
1217a50b1900SMark Johnston 	return (mb != NULL);
1218a50b1900SMark Johnston }
1219a50b1900SMark Johnston 
1220a29f300eSGarrett Wollman static int
1221c80ea19bSGleb Smirnoff uipc_ready(struct socket *so, struct mbuf *m, int count)
1222c80ea19bSGleb Smirnoff {
1223c80ea19bSGleb Smirnoff 	struct unpcb *unp, *unp2;
1224c80ea19bSGleb Smirnoff 	struct socket *so2;
1225a50b1900SMark Johnston 	int error, i;
1226c80ea19bSGleb Smirnoff 
1227c80ea19bSGleb Smirnoff 	unp = sotounpcb(so);
1228c80ea19bSGleb Smirnoff 
1229a50b1900SMark Johnston 	KASSERT(so->so_type == SOCK_STREAM,
1230a50b1900SMark Johnston 	    ("%s: unexpected socket type for %p", __func__, so));
1231a50b1900SMark Johnston 
1232a62b4665SMatt Macy 	UNP_PCB_LOCK(unp);
1233ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1234a62b4665SMatt Macy 		UNP_PCB_UNLOCK(unp);
1235c80ea19bSGleb Smirnoff 		so2 = unp2->unp_socket;
1236c80ea19bSGleb Smirnoff 		SOCKBUF_LOCK(&so2->so_rcv);
1237c80ea19bSGleb Smirnoff 		if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1238c80ea19bSGleb Smirnoff 			sorwakeup_locked(so2);
1239c80ea19bSGleb Smirnoff 		else
1240c80ea19bSGleb Smirnoff 			SOCKBUF_UNLOCK(&so2->so_rcv);
1241c80ea19bSGleb Smirnoff 		UNP_PCB_UNLOCK(unp2);
1242c80ea19bSGleb Smirnoff 		return (error);
1243ccdadf1aSMark Johnston 	}
1244ccdadf1aSMark Johnston 	UNP_PCB_UNLOCK(unp);
1245a50b1900SMark Johnston 
1246a50b1900SMark Johnston 	/*
1247a50b1900SMark Johnston 	 * The receiving socket has been disconnected, but may still be valid.
1248a50b1900SMark Johnston 	 * In this case, the now-ready mbufs are still present in its socket
1249a50b1900SMark Johnston 	 * buffer, so perform an exhaustive search before giving up and freeing
1250a50b1900SMark Johnston 	 * the mbufs.
1251a50b1900SMark Johnston 	 */
1252a50b1900SMark Johnston 	UNP_LINK_RLOCK();
1253a50b1900SMark Johnston 	LIST_FOREACH(unp, &unp_shead, unp_link) {
1254a50b1900SMark Johnston 		if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1255a50b1900SMark Johnston 			break;
1256a50b1900SMark Johnston 	}
1257a50b1900SMark Johnston 	UNP_LINK_RUNLOCK();
1258a50b1900SMark Johnston 
1259a50b1900SMark Johnston 	if (unp == NULL) {
1260a50b1900SMark Johnston 		for (i = 0; i < count; i++)
1261a62b4665SMatt Macy 			m = m_free(m);
1262a50b1900SMark Johnston 		error = ECONNRESET;
1263a50b1900SMark Johnston 	}
1264a50b1900SMark Johnston 	return (error);
1265c80ea19bSGleb Smirnoff }
1266c80ea19bSGleb Smirnoff 
1267c80ea19bSGleb Smirnoff static int
1268a29f300eSGarrett Wollman uipc_sense(struct socket *so, struct stat *sb)
1269a29f300eSGarrett Wollman {
1270c2090e73SAlan Somers 	struct unpcb *unp;
1271a29f300eSGarrett Wollman 
127240f2ac28SRobert Watson 	unp = sotounpcb(so);
12734d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1274e7c33e29SRobert Watson 
1275a29f300eSGarrett Wollman 	sb->st_blksize = so->so_snd.sb_hiwat;
1276f3732fd1SPoul-Henning Kamp 	sb->st_dev = NODEV;
1277a29f300eSGarrett Wollman 	sb->st_ino = unp->unp_ino;
1278df8bae1dSRodney W. Grimes 	return (0);
1279a29f300eSGarrett Wollman }
1280df8bae1dSRodney W. Grimes 
1281a29f300eSGarrett Wollman static int
1282a29f300eSGarrett Wollman uipc_shutdown(struct socket *so)
1283a29f300eSGarrett Wollman {
128440f2ac28SRobert Watson 	struct unpcb *unp;
1285df8bae1dSRodney W. Grimes 
128640f2ac28SRobert Watson 	unp = sotounpcb(so);
12874d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1288e7c33e29SRobert Watson 
1289e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1290a29f300eSGarrett Wollman 	socantsendmore(so);
1291a29f300eSGarrett Wollman 	unp_shutdown(unp);
1292e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1293e5aeaa0cSDag-Erling Smørgrav 	return (0);
1294a29f300eSGarrett Wollman }
1295df8bae1dSRodney W. Grimes 
1296a29f300eSGarrett Wollman static int
129757bf258eSGarrett Wollman uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1298a29f300eSGarrett Wollman {
129940f2ac28SRobert Watson 	struct unpcb *unp;
13000d9ce3a1SRobert Watson 	const struct sockaddr *sa;
1301a29f300eSGarrett Wollman 
13024d4b555eSRobert Watson 	unp = sotounpcb(so);
13034d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1304e7c33e29SRobert Watson 
13050d9ce3a1SRobert Watson 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1306e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1307fc3fcacfSRobert Watson 	if (unp->unp_addr != NULL)
13080d9ce3a1SRobert Watson 		sa = (struct sockaddr *) unp->unp_addr;
130983f3198bSThomas Moestl 	else
13100d9ce3a1SRobert Watson 		sa = &sun_noname;
13110d9ce3a1SRobert Watson 	bcopy(sa, *nam, sa->sa_len);
1312e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1313e5aeaa0cSDag-Erling Smørgrav 	return (0);
1314df8bae1dSRodney W. Grimes }
1315a29f300eSGarrett Wollman 
1316fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_dgram = {
1317756d52a1SPoul-Henning Kamp 	.pru_abort = 		uipc_abort,
1318756d52a1SPoul-Henning Kamp 	.pru_accept =		uipc_accept,
1319756d52a1SPoul-Henning Kamp 	.pru_attach =		uipc_attach,
1320756d52a1SPoul-Henning Kamp 	.pru_bind =		uipc_bind,
13217493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1322756d52a1SPoul-Henning Kamp 	.pru_connect =		uipc_connect,
13237493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1324756d52a1SPoul-Henning Kamp 	.pru_connect2 =		uipc_connect2,
1325756d52a1SPoul-Henning Kamp 	.pru_detach =		uipc_detach,
1326756d52a1SPoul-Henning Kamp 	.pru_disconnect =	uipc_disconnect,
1327756d52a1SPoul-Henning Kamp 	.pru_listen =		uipc_listen,
1328756d52a1SPoul-Henning Kamp 	.pru_peeraddr =		uipc_peeraddr,
1329756d52a1SPoul-Henning Kamp 	.pru_rcvd =		uipc_rcvd,
1330756d52a1SPoul-Henning Kamp 	.pru_send =		uipc_send,
1331756d52a1SPoul-Henning Kamp 	.pru_sense =		uipc_sense,
1332756d52a1SPoul-Henning Kamp 	.pru_shutdown =		uipc_shutdown,
1333756d52a1SPoul-Henning Kamp 	.pru_sockaddr =		uipc_sockaddr,
1334fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_dgram,
1335fa9402f2SRobert Watson 	.pru_close =		uipc_close,
1336fa9402f2SRobert Watson };
1337fa9402f2SRobert Watson 
133884d61770SRobert Watson static struct pr_usrreqs uipc_usrreqs_seqpacket = {
133984d61770SRobert Watson 	.pru_abort =		uipc_abort,
134084d61770SRobert Watson 	.pru_accept =		uipc_accept,
134184d61770SRobert Watson 	.pru_attach =		uipc_attach,
134284d61770SRobert Watson 	.pru_bind =		uipc_bind,
13437493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
134484d61770SRobert Watson 	.pru_connect =		uipc_connect,
13457493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
134684d61770SRobert Watson 	.pru_connect2 =		uipc_connect2,
134784d61770SRobert Watson 	.pru_detach =		uipc_detach,
134884d61770SRobert Watson 	.pru_disconnect =	uipc_disconnect,
134984d61770SRobert Watson 	.pru_listen =		uipc_listen,
135084d61770SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
135184d61770SRobert Watson 	.pru_rcvd =		uipc_rcvd,
135284d61770SRobert Watson 	.pru_send =		uipc_send,
135384d61770SRobert Watson 	.pru_sense =		uipc_sense,
135484d61770SRobert Watson 	.pru_shutdown =		uipc_shutdown,
135584d61770SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
135684d61770SRobert Watson 	.pru_soreceive =	soreceive_generic,	/* XXX: or...? */
135784d61770SRobert Watson 	.pru_close =		uipc_close,
135884d61770SRobert Watson };
135984d61770SRobert Watson 
1360fa9402f2SRobert Watson static struct pr_usrreqs uipc_usrreqs_stream = {
1361fa9402f2SRobert Watson 	.pru_abort = 		uipc_abort,
1362fa9402f2SRobert Watson 	.pru_accept =		uipc_accept,
1363fa9402f2SRobert Watson 	.pru_attach =		uipc_attach,
1364fa9402f2SRobert Watson 	.pru_bind =		uipc_bind,
13657493f24eSPawel Jakub Dawidek 	.pru_bindat =		uipc_bindat,
1366fa9402f2SRobert Watson 	.pru_connect =		uipc_connect,
13677493f24eSPawel Jakub Dawidek 	.pru_connectat =	uipc_connectat,
1368fa9402f2SRobert Watson 	.pru_connect2 =		uipc_connect2,
1369fa9402f2SRobert Watson 	.pru_detach =		uipc_detach,
1370fa9402f2SRobert Watson 	.pru_disconnect =	uipc_disconnect,
1371fa9402f2SRobert Watson 	.pru_listen =		uipc_listen,
1372fa9402f2SRobert Watson 	.pru_peeraddr =		uipc_peeraddr,
1373fa9402f2SRobert Watson 	.pru_rcvd =		uipc_rcvd,
1374fa9402f2SRobert Watson 	.pru_send =		uipc_send,
1375c80ea19bSGleb Smirnoff 	.pru_ready =		uipc_ready,
1376fa9402f2SRobert Watson 	.pru_sense =		uipc_sense,
1377fa9402f2SRobert Watson 	.pru_shutdown =		uipc_shutdown,
1378fa9402f2SRobert Watson 	.pru_sockaddr =		uipc_sockaddr,
1379fa9402f2SRobert Watson 	.pru_soreceive =	soreceive_generic,
1380a152f8a3SRobert Watson 	.pru_close =		uipc_close,
1381a29f300eSGarrett Wollman };
1382df8bae1dSRodney W. Grimes 
13830b36cd25SRobert Watson static int
1384892af6b9SRobert Watson uipc_ctloutput(struct socket *so, struct sockopt *sopt)
13850c1bb4fbSDima Dorfman {
138640f2ac28SRobert Watson 	struct unpcb *unp;
13870d9ce3a1SRobert Watson 	struct xucred xu;
13886a2989fdSMatthew N. Dodd 	int error, optval;
13896a2989fdSMatthew N. Dodd 
13906e0c8e1aSKonstantin Belousov 	if (sopt->sopt_level != SOL_LOCAL)
139196a041b5SMatthew N. Dodd 		return (EINVAL);
139296a041b5SMatthew N. Dodd 
13936a2989fdSMatthew N. Dodd 	unp = sotounpcb(so);
13944d4b555eSRobert Watson 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
13956a2989fdSMatthew N. Dodd 	error = 0;
13960c1bb4fbSDima Dorfman 	switch (sopt->sopt_dir) {
13970c1bb4fbSDima Dorfman 	case SOPT_GET:
13980c1bb4fbSDima Dorfman 		switch (sopt->sopt_name) {
13990c1bb4fbSDima Dorfman 		case LOCAL_PEERCRED:
1400e7c33e29SRobert Watson 			UNP_PCB_LOCK(unp);
14010c1bb4fbSDima Dorfman 			if (unp->unp_flags & UNP_HAVEPC)
14020d9ce3a1SRobert Watson 				xu = unp->unp_peercred;
14030c1bb4fbSDima Dorfman 			else {
14040c1bb4fbSDima Dorfman 				if (so->so_type == SOCK_STREAM)
14050c1bb4fbSDima Dorfman 					error = ENOTCONN;
14060c1bb4fbSDima Dorfman 				else
14070c1bb4fbSDima Dorfman 					error = EINVAL;
14080c1bb4fbSDima Dorfman 			}
1409e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
14100d9ce3a1SRobert Watson 			if (error == 0)
14110d9ce3a1SRobert Watson 				error = sooptcopyout(sopt, &xu, sizeof(xu));
14120c1bb4fbSDima Dorfman 			break;
1413e7c33e29SRobert Watson 
14146a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
1415a6357845SRobert Watson 			/* Unlocked read. */
14162de07e40SConrad Meyer 			optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
14172de07e40SConrad Meyer 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14182de07e40SConrad Meyer 			break;
14192de07e40SConrad Meyer 
14202de07e40SConrad Meyer 		case LOCAL_CREDS_PERSISTENT:
14212de07e40SConrad Meyer 			/* Unlocked read. */
14222de07e40SConrad Meyer 			optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
14236a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14246a2989fdSMatthew N. Dodd 			break;
1425e7c33e29SRobert Watson 
14266a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
1427a6357845SRobert Watson 			/* Unlocked read. */
14286a2989fdSMatthew N. Dodd 			optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
14296a2989fdSMatthew N. Dodd 			error = sooptcopyout(sopt, &optval, sizeof(optval));
14306a2989fdSMatthew N. Dodd 			break;
1431e7c33e29SRobert Watson 
14320c1bb4fbSDima Dorfman 		default:
14330c1bb4fbSDima Dorfman 			error = EOPNOTSUPP;
14340c1bb4fbSDima Dorfman 			break;
14350c1bb4fbSDima Dorfman 		}
14360c1bb4fbSDima Dorfman 		break;
1437e7c33e29SRobert Watson 
14380c1bb4fbSDima Dorfman 	case SOPT_SET:
14396a2989fdSMatthew N. Dodd 		switch (sopt->sopt_name) {
14406a2989fdSMatthew N. Dodd 		case LOCAL_CREDS:
14412de07e40SConrad Meyer 		case LOCAL_CREDS_PERSISTENT:
14426a2989fdSMatthew N. Dodd 		case LOCAL_CONNWAIT:
14436a2989fdSMatthew N. Dodd 			error = sooptcopyin(sopt, &optval, sizeof(optval),
14446a2989fdSMatthew N. Dodd 					    sizeof(optval));
14456a2989fdSMatthew N. Dodd 			if (error)
14466a2989fdSMatthew N. Dodd 				break;
14476a2989fdSMatthew N. Dodd 
14482de07e40SConrad Meyer #define	OPTSET(bit, exclusive) do {					\
1449e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);						\
14502de07e40SConrad Meyer 	if (optval) {							\
14512de07e40SConrad Meyer 		if ((unp->unp_flags & (exclusive)) != 0) {		\
14522de07e40SConrad Meyer 			UNP_PCB_UNLOCK(unp);				\
14532de07e40SConrad Meyer 			error = EINVAL;					\
14542de07e40SConrad Meyer 			break;						\
14552de07e40SConrad Meyer 		}							\
14562de07e40SConrad Meyer 		unp->unp_flags |= (bit);				\
14572de07e40SConrad Meyer 	} else								\
14582de07e40SConrad Meyer 		unp->unp_flags &= ~(bit);				\
1459e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);						\
1460e7c33e29SRobert Watson } while (0)
14616a2989fdSMatthew N. Dodd 
14626a2989fdSMatthew N. Dodd 			switch (sopt->sopt_name) {
14636a2989fdSMatthew N. Dodd 			case LOCAL_CREDS:
14642de07e40SConrad Meyer 				OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
14652de07e40SConrad Meyer 				break;
14662de07e40SConrad Meyer 
14672de07e40SConrad Meyer 			case LOCAL_CREDS_PERSISTENT:
14682de07e40SConrad Meyer 				OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
14696a2989fdSMatthew N. Dodd 				break;
1470e7c33e29SRobert Watson 
14716a2989fdSMatthew N. Dodd 			case LOCAL_CONNWAIT:
14722de07e40SConrad Meyer 				OPTSET(UNP_CONNWAIT, 0);
14736a2989fdSMatthew N. Dodd 				break;
1474e7c33e29SRobert Watson 
14756a2989fdSMatthew N. Dodd 			default:
14766a2989fdSMatthew N. Dodd 				break;
14776a2989fdSMatthew N. Dodd 			}
14786a2989fdSMatthew N. Dodd 			break;
14796a2989fdSMatthew N. Dodd #undef	OPTSET
14806a2989fdSMatthew N. Dodd 		default:
14816a2989fdSMatthew N. Dodd 			error = ENOPROTOOPT;
14826a2989fdSMatthew N. Dodd 			break;
14836a2989fdSMatthew N. Dodd 		}
1484abb886faSMatthew N. Dodd 		break;
1485e7c33e29SRobert Watson 
14860c1bb4fbSDima Dorfman 	default:
14870c1bb4fbSDima Dorfman 		error = EOPNOTSUPP;
14880c1bb4fbSDima Dorfman 		break;
14890c1bb4fbSDima Dorfman 	}
14900c1bb4fbSDima Dorfman 	return (error);
14910c1bb4fbSDima Dorfman }
14920c1bb4fbSDima Dorfman 
1493f708ef1bSPoul-Henning Kamp static int
1494892af6b9SRobert Watson unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1495df8bae1dSRodney W. Grimes {
14967493f24eSPawel Jakub Dawidek 
14977493f24eSPawel Jakub Dawidek 	return (unp_connectat(AT_FDCWD, so, nam, td));
14987493f24eSPawel Jakub Dawidek }
14997493f24eSPawel Jakub Dawidek 
15007493f24eSPawel Jakub Dawidek static int
15017493f24eSPawel Jakub Dawidek unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
15027493f24eSPawel Jakub Dawidek     struct thread *td)
15037493f24eSPawel Jakub Dawidek {
1504ed92e1c7SMark Johnston 	struct mtx *vplock;
1505ed92e1c7SMark Johnston 	struct sockaddr_un *soun;
1506892af6b9SRobert Watson 	struct vnode *vp;
1507779f106aSGleb Smirnoff 	struct socket *so2;
1508b295bdcdSRobert Watson 	struct unpcb *unp, *unp2, *unp3;
1509df8bae1dSRodney W. Grimes 	struct nameidata nd;
151057bf258eSGarrett Wollman 	char buf[SOCK_MAXADDRLEN];
15110d9ce3a1SRobert Watson 	struct sockaddr *sa;
15127008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
1513ccdadf1aSMark Johnston 	int error, len;
1514ed92e1c7SMark Johnston 	bool connreq;
15150d9ce3a1SRobert Watson 
1516cb7df69bSKevin Lo 	if (nam->sa_family != AF_UNIX)
1517cb7df69bSKevin Lo 		return (EAFNOSUPPORT);
1518a06534c3SBjoern A. Zeeb 	if (nam->sa_len > sizeof(struct sockaddr_un))
1519a06534c3SBjoern A. Zeeb 		return (EINVAL);
152057bf258eSGarrett Wollman 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
152157bf258eSGarrett Wollman 	if (len <= 0)
1522e5aeaa0cSDag-Erling Smørgrav 		return (EINVAL);
1523ed92e1c7SMark Johnston 	soun = (struct sockaddr_un *)nam;
15247928893dSEd Maste 	bcopy(soun->sun_path, buf, len);
15257928893dSEd Maste 	buf[len] = 0;
1526e7c33e29SRobert Watson 
1527bd4a39ccSMark Johnston 	error = 0;
152875a67bf3SMatt Macy 	unp = sotounpcb(so);
1529e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1530ccdadf1aSMark Johnston 	for (;;) {
1531ccdadf1aSMark Johnston 		/*
1532ccdadf1aSMark Johnston 		 * Wait for connection state to stabilize.  If a connection
1533ccdadf1aSMark Johnston 		 * already exists, give up.  For datagram sockets, which permit
1534ccdadf1aSMark Johnston 		 * multiple consecutive connect(2) calls, upper layers are
1535ccdadf1aSMark Johnston 		 * responsible for disconnecting in advance of a subsequent
1536ccdadf1aSMark Johnston 		 * connect(2), but this is not synchronized with PCB connection
1537ccdadf1aSMark Johnston 		 * state.
1538ccdadf1aSMark Johnston 		 *
1539ccdadf1aSMark Johnston 		 * Also make sure that no threads are currently attempting to
1540ccdadf1aSMark Johnston 		 * lock the peer socket, to ensure that unp_conn cannot
1541ccdadf1aSMark Johnston 		 * transition between two valid sockets while locks are dropped.
1542ccdadf1aSMark Johnston 		 */
1543bd4a39ccSMark Johnston 		if (SOLISTENING(so))
1544bd4a39ccSMark Johnston 			error = EOPNOTSUPP;
1545bd4a39ccSMark Johnston 		else if (unp->unp_conn != NULL)
1546bd4a39ccSMark Johnston 			error = EISCONN;
1547bd4a39ccSMark Johnston 		else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1548bd4a39ccSMark Johnston 			error = EALREADY;
1549ccdadf1aSMark Johnston 		}
1550bd4a39ccSMark Johnston 		if (error != 0) {
1551e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
1552bd4a39ccSMark Johnston 			return (error);
15534f1f0ef5SRobert Watson 		}
1554ccdadf1aSMark Johnston 		if (unp->unp_pairbusy > 0) {
1555ccdadf1aSMark Johnston 			unp->unp_flags |= UNP_WAITING;
1556ccdadf1aSMark Johnston 			mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1557ccdadf1aSMark Johnston 			continue;
1558ccdadf1aSMark Johnston 		}
1559ccdadf1aSMark Johnston 		break;
1560ccdadf1aSMark Johnston 	}
156105102f04SRobert Watson 	unp->unp_flags |= UNP_CONNECTING;
1562e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1563e7c33e29SRobert Watson 
1564ed92e1c7SMark Johnston 	connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1565ed92e1c7SMark Johnston 	if (connreq)
15660d9ce3a1SRobert Watson 		sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1567ed92e1c7SMark Johnston 	else
1568ed92e1c7SMark Johnston 		sa = NULL;
15697493f24eSPawel Jakub Dawidek 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
15707e1d3eefSMateusz Guzik 	    UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
1571797f2d22SPoul-Henning Kamp 	error = namei(&nd);
1572797f2d22SPoul-Henning Kamp 	if (error)
15730d9ce3a1SRobert Watson 		vp = NULL;
15740d9ce3a1SRobert Watson 	else
1575df8bae1dSRodney W. Grimes 		vp = nd.ni_vp;
15760d9ce3a1SRobert Watson 	ASSERT_VOP_LOCKED(vp, "unp_connect");
1577cdb62ab7SMateusz Guzik 	NDFREE_NOTHING(&nd);
15780d9ce3a1SRobert Watson 	if (error)
15790d9ce3a1SRobert Watson 		goto bad;
15800d9ce3a1SRobert Watson 
1581df8bae1dSRodney W. Grimes 	if (vp->v_type != VSOCK) {
1582df8bae1dSRodney W. Grimes 		error = ENOTSOCK;
1583df8bae1dSRodney W. Grimes 		goto bad;
1584df8bae1dSRodney W. Grimes 	}
15856fac927cSRobert Watson #ifdef MAC
158630d239bcSRobert Watson 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
15876fac927cSRobert Watson 	if (error)
15886fac927cSRobert Watson 		goto bad;
15896fac927cSRobert Watson #endif
1590a854ed98SJohn Baldwin 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1591797f2d22SPoul-Henning Kamp 	if (error)
1592df8bae1dSRodney W. Grimes 		goto bad;
1593e7c33e29SRobert Watson 
1594b295bdcdSRobert Watson 	unp = sotounpcb(so);
15954d4b555eSRobert Watson 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1596e7c33e29SRobert Watson 
159775a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
159875a67bf3SMatt Macy 	mtx_lock(vplock);
15990c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp2);
16000c3c207fSGleb Smirnoff 	if (unp2 == NULL) {
1601df8bae1dSRodney W. Grimes 		error = ECONNREFUSED;
16022260c03dSRobert Watson 		goto bad2;
1603df8bae1dSRodney W. Grimes 	}
16040c3c207fSGleb Smirnoff 	so2 = unp2->unp_socket;
1605df8bae1dSRodney W. Grimes 	if (so->so_type != so2->so_type) {
1606df8bae1dSRodney W. Grimes 		error = EPROTOTYPE;
16072260c03dSRobert Watson 		goto bad2;
1608df8bae1dSRodney W. Grimes 	}
1609ed92e1c7SMark Johnston 	if (connreq) {
1610f4bb1869SMark Johnston 		if (SOLISTENING(so2)) {
16111fb51a12SBjoern A. Zeeb 			CURVNET_SET(so2->so_vnet);
1612779f106aSGleb Smirnoff 			so2 = sonewconn(so2, 0);
16131fb51a12SBjoern A. Zeeb 			CURVNET_RESTORE();
1614e7c33e29SRobert Watson 		} else
1615779f106aSGleb Smirnoff 			so2 = NULL;
1616779f106aSGleb Smirnoff 		if (so2 == NULL) {
1617df8bae1dSRodney W. Grimes 			error = ECONNREFUSED;
1618cb8f450bSMatt Macy 			goto bad2;
1619df8bae1dSRodney W. Grimes 		}
1620779f106aSGleb Smirnoff 		unp3 = sotounpcb(so2);
16214820bf6aSMark Johnston 		unp_pcb_lock_pair(unp2, unp3);
16220d9ce3a1SRobert Watson 		if (unp2->unp_addr != NULL) {
16230d9ce3a1SRobert Watson 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
16240d9ce3a1SRobert Watson 			unp3->unp_addr = (struct sockaddr_un *) sa;
16250d9ce3a1SRobert Watson 			sa = NULL;
16260d9ce3a1SRobert Watson 		}
1627b523ec24SRobert Watson 
1628da446550SAlan Somers 		unp_copy_peercred(td, unp3, unp, unp2);
1629b523ec24SRobert Watson 
1630e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp2);
1631779f106aSGleb Smirnoff 		unp2 = unp3;
1632ccdadf1aSMark Johnston 
1633ccdadf1aSMark Johnston 		/*
1634ccdadf1aSMark Johnston 		 * It is safe to block on the PCB lock here since unp2 is
1635ccdadf1aSMark Johnston 		 * nascent and cannot be connected to any other sockets.
1636ccdadf1aSMark Johnston 		 */
1637ccdadf1aSMark Johnston 		UNP_PCB_LOCK(unp);
1638335654d7SRobert Watson #ifdef MAC
1639779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so, so2);
1640779f106aSGleb Smirnoff 		mac_socketpeer_set_from_socket(so2, so);
1641335654d7SRobert Watson #endif
1642a3a73490SMatt Macy 	} else {
16434820bf6aSMark Johnston 		unp_pcb_lock_pair(unp, unp2);
1644a3a73490SMatt Macy 	}
1645779f106aSGleb Smirnoff 	KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1646779f106aSGleb Smirnoff 	    sotounpcb(so2) == unp2,
1647779f106aSGleb Smirnoff 	    ("%s: unp2 %p so2 %p", __func__, unp2, so2));
16486a2989fdSMatthew N. Dodd 	error = unp_connect2(so, so2, PRU_CONNECT);
16494820bf6aSMark Johnston 	unp_pcb_unlock_pair(unp, unp2);
16500d9ce3a1SRobert Watson bad2:
165175a67bf3SMatt Macy 	mtx_unlock(vplock);
1652df8bae1dSRodney W. Grimes bad:
165375a67bf3SMatt Macy 	if (vp != NULL) {
1654df8bae1dSRodney W. Grimes 		vput(vp);
165575a67bf3SMatt Macy 	}
16560d9ce3a1SRobert Watson 	free(sa, M_SONAME);
1657e7c33e29SRobert Watson 	UNP_PCB_LOCK(unp);
1658ccdadf1aSMark Johnston 	KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1659ccdadf1aSMark Johnston 	    ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
16604f1f0ef5SRobert Watson 	unp->unp_flags &= ~UNP_CONNECTING;
1661e7c33e29SRobert Watson 	UNP_PCB_UNLOCK(unp);
1662df8bae1dSRodney W. Grimes 	return (error);
1663df8bae1dSRodney W. Grimes }
1664df8bae1dSRodney W. Grimes 
1665da446550SAlan Somers /*
1666da446550SAlan Somers  * Set socket peer credentials at connection time.
1667da446550SAlan Somers  *
1668da446550SAlan Somers  * The client's PCB credentials are copied from its process structure.  The
1669da446550SAlan Somers  * server's PCB credentials are copied from the socket on which it called
1670da446550SAlan Somers  * listen(2).  uipc_listen cached that process's credentials at the time.
1671da446550SAlan Somers  */
1672da446550SAlan Somers void
1673da446550SAlan Somers unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1674da446550SAlan Somers     struct unpcb *server_unp, struct unpcb *listen_unp)
1675da446550SAlan Somers {
1676c5afec6eSDmitry Chagin 	cru2xt(td, &client_unp->unp_peercred);
1677da446550SAlan Somers 	client_unp->unp_flags |= UNP_HAVEPC;
1678da446550SAlan Somers 
1679da446550SAlan Somers 	memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1680da446550SAlan Somers 	    sizeof(server_unp->unp_peercred));
1681da446550SAlan Somers 	server_unp->unp_flags |= UNP_HAVEPC;
16822de07e40SConrad Meyer 	client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
1683da446550SAlan Somers }
1684da446550SAlan Somers 
1685db48c0d2SRobert Watson static int
16866a2989fdSMatthew N. Dodd unp_connect2(struct socket *so, struct socket *so2, int req)
1687df8bae1dSRodney W. Grimes {
1688e7c33e29SRobert Watson 	struct unpcb *unp;
1689892af6b9SRobert Watson 	struct unpcb *unp2;
1690df8bae1dSRodney W. Grimes 
1691e7c33e29SRobert Watson 	unp = sotounpcb(so);
1692e7c33e29SRobert Watson 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1693e7c33e29SRobert Watson 	unp2 = sotounpcb(so2);
1694e7c33e29SRobert Watson 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1695e7c33e29SRobert Watson 
1696e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1697e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
1698ccdadf1aSMark Johnston 	KASSERT(unp->unp_conn == NULL,
1699ccdadf1aSMark Johnston 	    ("%s: socket %p is already connected", __func__, unp));
17000d9ce3a1SRobert Watson 
1701df8bae1dSRodney W. Grimes 	if (so2->so_type != so->so_type)
1702df8bae1dSRodney W. Grimes 		return (EPROTOTYPE);
1703df8bae1dSRodney W. Grimes 	unp->unp_conn = unp2;
170475a67bf3SMatt Macy 	unp_pcb_hold(unp2);
170575a67bf3SMatt Macy 	unp_pcb_hold(unp);
1706df8bae1dSRodney W. Grimes 	switch (so->so_type) {
1707df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
170875a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
170998271db4SGarrett Wollman 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
171075a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
1711df8bae1dSRodney W. Grimes 		soisconnected(so);
1712df8bae1dSRodney W. Grimes 		break;
1713df8bae1dSRodney W. Grimes 
1714df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
171584d61770SRobert Watson 	case SOCK_SEQPACKET:
1716ccdadf1aSMark Johnston 		KASSERT(unp2->unp_conn == NULL,
1717ccdadf1aSMark Johnston 		    ("%s: socket %p is already connected", __func__, unp2));
1718df8bae1dSRodney W. Grimes 		unp2->unp_conn = unp;
17196a2989fdSMatthew N. Dodd 		if (req == PRU_CONNECT &&
17206a2989fdSMatthew N. Dodd 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
17216a2989fdSMatthew N. Dodd 			soisconnecting(so);
17226a2989fdSMatthew N. Dodd 		else
1723df8bae1dSRodney W. Grimes 			soisconnected(so);
1724df8bae1dSRodney W. Grimes 		soisconnected(so2);
1725df8bae1dSRodney W. Grimes 		break;
1726df8bae1dSRodney W. Grimes 
1727df8bae1dSRodney W. Grimes 	default:
1728df8bae1dSRodney W. Grimes 		panic("unp_connect2");
1729df8bae1dSRodney W. Grimes 	}
1730df8bae1dSRodney W. Grimes 	return (0);
1731df8bae1dSRodney W. Grimes }
1732df8bae1dSRodney W. Grimes 
1733f708ef1bSPoul-Henning Kamp static void
1734e7c33e29SRobert Watson unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1735df8bae1dSRodney W. Grimes {
173675a67bf3SMatt Macy 	struct socket *so, *so2;
1737f0317f86SMark Johnston #ifdef INVARIANTS
1738f0317f86SMark Johnston 	struct unpcb *unptmp;
1739f0317f86SMark Johnston #endif
17400d9ce3a1SRobert Watson 
1741e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
1742e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp2);
1743f0317f86SMark Johnston 	KASSERT(unp->unp_conn == unp2,
1744f0317f86SMark Johnston 	    ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
1745e7c33e29SRobert Watson 
1746fc3fcacfSRobert Watson 	unp->unp_conn = NULL;
174775a67bf3SMatt Macy 	so = unp->unp_socket;
174875a67bf3SMatt Macy 	so2 = unp2->unp_socket;
1749df8bae1dSRodney W. Grimes 	switch (unp->unp_socket->so_type) {
1750df8bae1dSRodney W. Grimes 	case SOCK_DGRAM:
175175a67bf3SMatt Macy 		UNP_REF_LIST_LOCK();
1752f0317f86SMark Johnston #ifdef INVARIANTS
1753f0317f86SMark Johnston 		LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
1754f0317f86SMark Johnston 			if (unptmp == unp)
1755f0317f86SMark Johnston 				break;
1756f0317f86SMark Johnston 		}
1757f0317f86SMark Johnston 		KASSERT(unptmp != NULL,
1758f0317f86SMark Johnston 		    ("%s: %p not found in reflist of %p", __func__, unp, unp2));
1759f0317f86SMark Johnston #endif
176098271db4SGarrett Wollman 		LIST_REMOVE(unp, unp_reflink);
176175a67bf3SMatt Macy 		UNP_REF_LIST_UNLOCK();
176275a67bf3SMatt Macy 		if (so) {
17631b2e3b4bSRobert Watson 			SOCK_LOCK(so);
17641b2e3b4bSRobert Watson 			so->so_state &= ~SS_ISCONNECTED;
17651b2e3b4bSRobert Watson 			SOCK_UNLOCK(so);
176675a67bf3SMatt Macy 		}
1767df8bae1dSRodney W. Grimes 		break;
1768df8bae1dSRodney W. Grimes 
1769df8bae1dSRodney W. Grimes 	case SOCK_STREAM:
177084d61770SRobert Watson 	case SOCK_SEQPACKET:
177175a67bf3SMatt Macy 		if (so)
177275a67bf3SMatt Macy 			soisdisconnected(so);
177375a67bf3SMatt Macy 		MPASS(unp2->unp_conn == unp);
1774fc3fcacfSRobert Watson 		unp2->unp_conn = NULL;
177575a67bf3SMatt Macy 		if (so2)
177675a67bf3SMatt Macy 			soisdisconnected(so2);
1777df8bae1dSRodney W. Grimes 		break;
1778df8bae1dSRodney W. Grimes 	}
1779f0317f86SMark Johnston 
1780f0317f86SMark Johnston 	if (unp == unp2) {
1781f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
1782f0317f86SMark Johnston 		if (!unp_pcb_rele(unp))
1783f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp);
1784f0317f86SMark Johnston 	} else {
1785f0317f86SMark Johnston 		if (!unp_pcb_rele(unp))
1786f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp);
1787f0317f86SMark Johnston 		if (!unp_pcb_rele(unp2))
1788f0317f86SMark Johnston 			UNP_PCB_UNLOCK(unp2);
1789f0317f86SMark Johnston 	}
1790df8bae1dSRodney W. Grimes }
1791df8bae1dSRodney W. Grimes 
17920d9ce3a1SRobert Watson /*
1793d7924b70SRobert Watson  * unp_pcblist() walks the global list of struct unpcb's to generate a
1794d7924b70SRobert Watson  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1795d7924b70SRobert Watson  * sequentially, validating the generation number on each to see if it has
1796d7924b70SRobert Watson  * been detached.  All of this is necessary because copyout() may sleep on
1797d7924b70SRobert Watson  * disk I/O.
17980d9ce3a1SRobert Watson  */
179998271db4SGarrett Wollman static int
180082d9ae4eSPoul-Henning Kamp unp_pcblist(SYSCTL_HANDLER_ARGS)
180198271db4SGarrett Wollman {
180298271db4SGarrett Wollman 	struct unpcb *unp, **unp_list;
180398271db4SGarrett Wollman 	unp_gen_t gencnt;
18048f364875SJulian Elischer 	struct xunpgen *xug;
180598271db4SGarrett Wollman 	struct unp_head *head;
18068f364875SJulian Elischer 	struct xunpcb *xu;
1807d821d364SPedro F. Giffuni 	u_int i;
18085362170dSMark Johnston 	int error, n;
180998271db4SGarrett Wollman 
181084d61770SRobert Watson 	switch ((intptr_t)arg1) {
181184d61770SRobert Watson 	case SOCK_STREAM:
181284d61770SRobert Watson 		head = &unp_shead;
181384d61770SRobert Watson 		break;
181484d61770SRobert Watson 
181584d61770SRobert Watson 	case SOCK_DGRAM:
181684d61770SRobert Watson 		head = &unp_dhead;
181784d61770SRobert Watson 		break;
181884d61770SRobert Watson 
181984d61770SRobert Watson 	case SOCK_SEQPACKET:
182084d61770SRobert Watson 		head = &unp_sphead;
182184d61770SRobert Watson 		break;
182284d61770SRobert Watson 
182384d61770SRobert Watson 	default:
1824604f19c9SRobert Watson 		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
182584d61770SRobert Watson 	}
182698271db4SGarrett Wollman 
182798271db4SGarrett Wollman 	/*
182898271db4SGarrett Wollman 	 * The process of preparing the PCB list is too time-consuming and
182998271db4SGarrett Wollman 	 * resource-intensive to repeat twice on every request.
183098271db4SGarrett Wollman 	 */
1831fc3fcacfSRobert Watson 	if (req->oldptr == NULL) {
183298271db4SGarrett Wollman 		n = unp_count;
18338f364875SJulian Elischer 		req->oldidx = 2 * (sizeof *xug)
183498271db4SGarrett Wollman 			+ (n + n/8) * sizeof(struct xunpcb);
1835e5aeaa0cSDag-Erling Smørgrav 		return (0);
183698271db4SGarrett Wollman 	}
183798271db4SGarrett Wollman 
1838fc3fcacfSRobert Watson 	if (req->newptr != NULL)
1839e5aeaa0cSDag-Erling Smørgrav 		return (EPERM);
184098271db4SGarrett Wollman 
184198271db4SGarrett Wollman 	/*
184298271db4SGarrett Wollman 	 * OK, now we're committed to doing something.
184398271db4SGarrett Wollman 	 */
184479db6fe7SMark Johnston 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1845779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
184698271db4SGarrett Wollman 	gencnt = unp_gencnt;
184798271db4SGarrett Wollman 	n = unp_count;
1848779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
184998271db4SGarrett Wollman 
18508f364875SJulian Elischer 	xug->xug_len = sizeof *xug;
18518f364875SJulian Elischer 	xug->xug_count = n;
18528f364875SJulian Elischer 	xug->xug_gen = gencnt;
18538f364875SJulian Elischer 	xug->xug_sogen = so_gencnt;
18548f364875SJulian Elischer 	error = SYSCTL_OUT(req, xug, sizeof *xug);
18558f364875SJulian Elischer 	if (error) {
18568f364875SJulian Elischer 		free(xug, M_TEMP);
1857e5aeaa0cSDag-Erling Smørgrav 		return (error);
18588f364875SJulian Elischer 	}
185998271db4SGarrett Wollman 
1860a163d034SWarner Losh 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
186198271db4SGarrett Wollman 
1862779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
18632e3c8fcbSPoul-Henning Kamp 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
18642e3c8fcbSPoul-Henning Kamp 	     unp = LIST_NEXT(unp, unp_link)) {
1865e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
18668a7d8cc6SRobert Watson 		if (unp->unp_gencnt <= gencnt) {
1867a854ed98SJohn Baldwin 			if (cr_cansee(req->td->td_ucred,
1868e7c33e29SRobert Watson 			    unp->unp_socket->so_cred)) {
1869e7c33e29SRobert Watson 				UNP_PCB_UNLOCK(unp);
18704787fd37SPaul Saab 				continue;
1871e7c33e29SRobert Watson 			}
187298271db4SGarrett Wollman 			unp_list[i++] = unp;
187375a67bf3SMatt Macy 			unp_pcb_hold(unp);
187498271db4SGarrett Wollman 		}
1875e7c33e29SRobert Watson 		UNP_PCB_UNLOCK(unp);
18764787fd37SPaul Saab 	}
1877779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
18781c381b19SRobert Watson 	n = i;			/* In case we lost some during malloc. */
187998271db4SGarrett Wollman 
188098271db4SGarrett Wollman 	error = 0;
1881fe2eee82SColin Percival 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
188298271db4SGarrett Wollman 	for (i = 0; i < n; i++) {
188398271db4SGarrett Wollman 		unp = unp_list[i];
1884e7c33e29SRobert Watson 		UNP_PCB_LOCK(unp);
18855362170dSMark Johnston 		if (unp_pcb_rele(unp))
18865362170dSMark Johnston 			continue;
188775a67bf3SMatt Macy 
18885362170dSMark Johnston 		if (unp->unp_gencnt <= gencnt) {
18898f364875SJulian Elischer 			xu->xu_len = sizeof *xu;
18903a20f06aSBrooks Davis 			xu->xu_unpp = (uintptr_t)unp;
189198271db4SGarrett Wollman 			/*
189298271db4SGarrett Wollman 			 * XXX - need more locking here to protect against
189398271db4SGarrett Wollman 			 * connect/disconnect races for SMP.
189498271db4SGarrett Wollman 			 */
1895fc3fcacfSRobert Watson 			if (unp->unp_addr != NULL)
18968f364875SJulian Elischer 				bcopy(unp->unp_addr, &xu->xu_addr,
189798271db4SGarrett Wollman 				      unp->unp_addr->sun_len);
18980e229f34SGleb Smirnoff 			else
18990e229f34SGleb Smirnoff 				bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1900fc3fcacfSRobert Watson 			if (unp->unp_conn != NULL &&
1901fc3fcacfSRobert Watson 			    unp->unp_conn->unp_addr != NULL)
190298271db4SGarrett Wollman 				bcopy(unp->unp_conn->unp_addr,
19038f364875SJulian Elischer 				      &xu->xu_caddr,
190498271db4SGarrett Wollman 				      unp->unp_conn->unp_addr->sun_len);
19050e229f34SGleb Smirnoff 			else
19060e229f34SGleb Smirnoff 				bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
19073a20f06aSBrooks Davis 			xu->unp_vnode = (uintptr_t)unp->unp_vnode;
19083a20f06aSBrooks Davis 			xu->unp_conn = (uintptr_t)unp->unp_conn;
19093a20f06aSBrooks Davis 			xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
19103a20f06aSBrooks Davis 			xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
19110e229f34SGleb Smirnoff 			xu->unp_gencnt = unp->unp_gencnt;
19128f364875SJulian Elischer 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1913e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
19148f364875SJulian Elischer 			error = SYSCTL_OUT(req, xu, sizeof *xu);
19155362170dSMark Johnston 		} else {
1916e7c33e29SRobert Watson 			UNP_PCB_UNLOCK(unp);
1917e7c33e29SRobert Watson 		}
19185362170dSMark Johnston 	}
19198f364875SJulian Elischer 	free(xu, M_TEMP);
192098271db4SGarrett Wollman 	if (!error) {
192198271db4SGarrett Wollman 		/*
19221c381b19SRobert Watson 		 * Give the user an updated idea of our state.  If the
19231c381b19SRobert Watson 		 * generation differs from what we told her before, she knows
19241c381b19SRobert Watson 		 * that something happened while we were processing this
19251c381b19SRobert Watson 		 * request, and it might be necessary to retry.
192698271db4SGarrett Wollman 		 */
19278f364875SJulian Elischer 		xug->xug_gen = unp_gencnt;
19288f364875SJulian Elischer 		xug->xug_sogen = so_gencnt;
19298f364875SJulian Elischer 		xug->xug_count = unp_count;
19308f364875SJulian Elischer 		error = SYSCTL_OUT(req, xug, sizeof *xug);
193198271db4SGarrett Wollman 	}
193298271db4SGarrett Wollman 	free(unp_list, M_TEMP);
19338f364875SJulian Elischer 	free(xug, M_TEMP);
1934e5aeaa0cSDag-Erling Smørgrav 	return (error);
193598271db4SGarrett Wollman }
193698271db4SGarrett Wollman 
19377029da5cSPawel Biernacki SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
19387029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19392fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
194098271db4SGarrett Wollman     "List of active local datagram sockets");
19417029da5cSPawel Biernacki SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
19427029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19432fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
194498271db4SGarrett Wollman     "List of active local stream sockets");
19452fee06f0SMatthew D Fleming SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
19467029da5cSPawel Biernacki     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
19472fee06f0SMatthew D Fleming     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
194884d61770SRobert Watson     "List of active local seqpacket sockets");
194998271db4SGarrett Wollman 
1950f708ef1bSPoul-Henning Kamp static void
1951892af6b9SRobert Watson unp_shutdown(struct unpcb *unp)
1952df8bae1dSRodney W. Grimes {
1953e7c33e29SRobert Watson 	struct unpcb *unp2;
1954df8bae1dSRodney W. Grimes 	struct socket *so;
1955df8bae1dSRodney W. Grimes 
1956e7c33e29SRobert Watson 	UNP_PCB_LOCK_ASSERT(unp);
19570d9ce3a1SRobert Watson 
1958e7c33e29SRobert Watson 	unp2 = unp->unp_conn;
195984d61770SRobert Watson 	if ((unp->unp_socket->so_type == SOCK_STREAM ||
196084d61770SRobert Watson 	    (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1961e7c33e29SRobert Watson 		so = unp2->unp_socket;
1962e7c33e29SRobert Watson 		if (so != NULL)
1963df8bae1dSRodney W. Grimes 			socantrcvmore(so);
1964df8bae1dSRodney W. Grimes 	}
1965e7c33e29SRobert Watson }
1966df8bae1dSRodney W. Grimes 
1967f708ef1bSPoul-Henning Kamp static void
1968afc055d9SEd Schouten unp_drop(struct unpcb *unp)
1969df8bae1dSRodney W. Grimes {
197050b07c1fSMark Johnston 	struct socket *so;
1971e7c33e29SRobert Watson 	struct unpcb *unp2;
19720d9ce3a1SRobert Watson 
1973afc055d9SEd Schouten 	/*
1974afc055d9SEd Schouten 	 * Regardless of whether the socket's peer dropped the connection
1975afc055d9SEd Schouten 	 * with this socket by aborting or disconnecting, POSIX requires
1976afc055d9SEd Schouten 	 * that ECONNRESET is returned.
1977afc055d9SEd Schouten 	 */
197875a67bf3SMatt Macy 
197975a67bf3SMatt Macy 	UNP_PCB_LOCK(unp);
198050b07c1fSMark Johnston 	so = unp->unp_socket;
198175a67bf3SMatt Macy 	if (so)
1982afc055d9SEd Schouten 		so->so_error = ECONNRESET;
1983ccdadf1aSMark Johnston 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1984f0317f86SMark Johnston 		/* Last reference dropped in unp_disconnect(). */
1985f0317f86SMark Johnston 		unp_pcb_rele_notlast(unp);
1986e7c33e29SRobert Watson 		unp_disconnect(unp, unp2);
1987f0317f86SMark Johnston 	} else if (!unp_pcb_rele(unp)) {
198875a67bf3SMatt Macy 		UNP_PCB_UNLOCK(unp);
198975a67bf3SMatt Macy 	}
1990f0317f86SMark Johnston }
1991df8bae1dSRodney W. Grimes 
19922bc21ed9SDavid Malone static void
19938cb539f1SPawel Jakub Dawidek unp_freerights(struct filedescent **fdep, int fdcount)
1994df8bae1dSRodney W. Grimes {
19952bc21ed9SDavid Malone 	struct file *fp;
19962609222aSPawel Jakub Dawidek 	int i;
1997df8bae1dSRodney W. Grimes 
199882e825c4SGleb Smirnoff 	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
199982e825c4SGleb Smirnoff 
20008cb539f1SPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
20018cb539f1SPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
20028cb539f1SPawel Jakub Dawidek 		filecaps_free(&fdep[i]->fde_caps);
20038692c025SYoshinobu Inoue 		unp_discard(fp);
2004df8bae1dSRodney W. Grimes 	}
20058cb539f1SPawel Jakub Dawidek 	free(fdep[0], M_FILECAPS);
20062bc21ed9SDavid Malone }
20072bc21ed9SDavid Malone 
20080b36cd25SRobert Watson static int
2009c2e3c52eSJilles Tjoelker unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
20102bc21ed9SDavid Malone {
20112bc21ed9SDavid Malone 	struct thread *td = curthread;		/* XXX */
20122bc21ed9SDavid Malone 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
20132bc21ed9SDavid Malone 	int i;
20142bc21ed9SDavid Malone 	int *fdp;
20152609222aSPawel Jakub Dawidek 	struct filedesc *fdesc = td->td_proc->p_fd;
2016ea31808cSMateusz Guzik 	struct filedescent **fdep;
20172bc21ed9SDavid Malone 	void *data;
20182bc21ed9SDavid Malone 	socklen_t clen = control->m_len, datalen;
20192bc21ed9SDavid Malone 	int error, newfds;
20202bc21ed9SDavid Malone 	u_int newlen;
20212bc21ed9SDavid Malone 
20223dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
20234c5bc1caSRobert Watson 
20242bc21ed9SDavid Malone 	error = 0;
20252bc21ed9SDavid Malone 	if (controlp != NULL) /* controlp == NULL => free control messages */
20262bc21ed9SDavid Malone 		*controlp = NULL;
20272bc21ed9SDavid Malone 	while (cm != NULL) {
20282bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
20292bc21ed9SDavid Malone 			error = EINVAL;
20302bc21ed9SDavid Malone 			break;
20312bc21ed9SDavid Malone 		}
20322bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
20332bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
20342bc21ed9SDavid Malone 		if (cm->cmsg_level == SOL_SOCKET
20352bc21ed9SDavid Malone 		    && cm->cmsg_type == SCM_RIGHTS) {
20362609222aSPawel Jakub Dawidek 			newfds = datalen / sizeof(*fdep);
203782e825c4SGleb Smirnoff 			if (newfds == 0)
203882e825c4SGleb Smirnoff 				goto next;
20392609222aSPawel Jakub Dawidek 			fdep = data;
20402bc21ed9SDavid Malone 
2041e2f9a08bSOlivier Houchard 			/* If we're not outputting the descriptors free them. */
20422bc21ed9SDavid Malone 			if (error || controlp == NULL) {
20432609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20442bc21ed9SDavid Malone 				goto next;
20452bc21ed9SDavid Malone 			}
20462609222aSPawel Jakub Dawidek 			FILEDESC_XLOCK(fdesc);
204760a5ef26SRobert Watson 
2048ed5b7817SJulian Elischer 			/*
20491c381b19SRobert Watson 			 * Now change each pointer to an fd in the global
20501c381b19SRobert Watson 			 * table to an integer that is the index to the local
20511c381b19SRobert Watson 			 * fd table entry that we set up to point to the
20521c381b19SRobert Watson 			 * global one we are transferring.
2053ed5b7817SJulian Elischer 			 */
20542bc21ed9SDavid Malone 			newlen = newfds * sizeof(int);
20552bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
20562bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
20572bc21ed9SDavid Malone 			if (*controlp == NULL) {
20582609222aSPawel Jakub Dawidek 				FILEDESC_XUNLOCK(fdesc);
20592bc21ed9SDavid Malone 				error = E2BIG;
20602609222aSPawel Jakub Dawidek 				unp_freerights(fdep, newfds);
20612bc21ed9SDavid Malone 				goto next;
20622bc21ed9SDavid Malone 			}
20632bc21ed9SDavid Malone 
20642bc21ed9SDavid Malone 			fdp = (int *)
20652bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2066db8f33fdSMateusz Guzik 			if (fdallocn(td, 0, fdp, newfds) != 0) {
20673331a33aSMateusz Guzik 				FILEDESC_XUNLOCK(fdesc);
2068db8f33fdSMateusz Guzik 				error = EMSGSIZE;
2069db8f33fdSMateusz Guzik 				unp_freerights(fdep, newfds);
2070db8f33fdSMateusz Guzik 				m_freem(*controlp);
2071db8f33fdSMateusz Guzik 				*controlp = NULL;
2072db8f33fdSMateusz Guzik 				goto next;
2073db8f33fdSMateusz Guzik 			}
20748cb539f1SPawel Jakub Dawidek 			for (i = 0; i < newfds; i++, fdp++) {
2075ea31808cSMateusz Guzik 				_finstall(fdesc, fdep[i]->fde_file, *fdp,
20766ceacebdSAlex Richardson 				    (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2077ea31808cSMateusz Guzik 				    &fdep[i]->fde_caps);
2078ea31808cSMateusz Guzik 				unp_externalize_fp(fdep[i]->fde_file);
2079df8bae1dSRodney W. Grimes 			}
2080c7902fbeSMark Johnston 
2081c7902fbeSMark Johnston 			/*
2082c7902fbeSMark Johnston 			 * The new type indicates that the mbuf data refers to
2083c7902fbeSMark Johnston 			 * kernel resources that may need to be released before
2084c7902fbeSMark Johnston 			 * the mbuf is freed.
2085c7902fbeSMark Johnston 			 */
2086c7902fbeSMark Johnston 			m_chtype(*controlp, MT_EXTCONTROL);
20872609222aSPawel Jakub Dawidek 			FILEDESC_XUNLOCK(fdesc);
20888cb539f1SPawel Jakub Dawidek 			free(fdep[0], M_FILECAPS);
20891c381b19SRobert Watson 		} else {
20901c381b19SRobert Watson 			/* We can just copy anything else across. */
20912bc21ed9SDavid Malone 			if (error || controlp == NULL)
20922bc21ed9SDavid Malone 				goto next;
20932bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, datalen,
20942bc21ed9SDavid Malone 			    cm->cmsg_type, cm->cmsg_level);
20952bc21ed9SDavid Malone 			if (*controlp == NULL) {
20962bc21ed9SDavid Malone 				error = ENOBUFS;
20972bc21ed9SDavid Malone 				goto next;
20982bc21ed9SDavid Malone 			}
20992bc21ed9SDavid Malone 			bcopy(data,
21002bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
21012bc21ed9SDavid Malone 			    datalen);
21022bc21ed9SDavid Malone 		}
21032bc21ed9SDavid Malone 		controlp = &(*controlp)->m_next;
21042bc21ed9SDavid Malone 
21052bc21ed9SDavid Malone next:
21062bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
21072bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
21082bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
21092bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
21108692c025SYoshinobu Inoue 		} else {
21112bc21ed9SDavid Malone 			clen = 0;
21122bc21ed9SDavid Malone 			cm = NULL;
21138692c025SYoshinobu Inoue 		}
21148692c025SYoshinobu Inoue 	}
21158692c025SYoshinobu Inoue 
21162bc21ed9SDavid Malone 	m_freem(control);
21172bc21ed9SDavid Malone 	return (error);
2118df8bae1dSRodney W. Grimes }
2119df8bae1dSRodney W. Grimes 
21204f590175SPaul Saab static void
21214f590175SPaul Saab unp_zone_change(void *tag)
21224f590175SPaul Saab {
21234f590175SPaul Saab 
21244f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21254f590175SPaul Saab }
21264f590175SPaul Saab 
21275362170dSMark Johnston #ifdef INVARIANTS
21285362170dSMark Johnston static void
21295362170dSMark Johnston unp_zdtor(void *mem, int size __unused, void *arg __unused)
21305362170dSMark Johnston {
21315362170dSMark Johnston 	struct unpcb *unp;
21325362170dSMark Johnston 
21335362170dSMark Johnston 	unp = mem;
21345362170dSMark Johnston 
21355362170dSMark Johnston 	KASSERT(LIST_EMPTY(&unp->unp_refs),
21365362170dSMark Johnston 	    ("%s: unpcb %p has lingering refs", __func__, unp));
21375362170dSMark Johnston 	KASSERT(unp->unp_socket == NULL,
21385362170dSMark Johnston 	    ("%s: unpcb %p has socket backpointer", __func__, unp));
21395362170dSMark Johnston 	KASSERT(unp->unp_vnode == NULL,
21405362170dSMark Johnston 	    ("%s: unpcb %p has vnode references", __func__, unp));
21415362170dSMark Johnston 	KASSERT(unp->unp_conn == NULL,
21425362170dSMark Johnston 	    ("%s: unpcb %p is still connected", __func__, unp));
21435362170dSMark Johnston 	KASSERT(unp->unp_addr == NULL,
21445362170dSMark Johnston 	    ("%s: unpcb %p has leaked addr", __func__, unp));
21455362170dSMark Johnston }
21465362170dSMark Johnston #endif
21475362170dSMark Johnston 
21480b36cd25SRobert Watson static void
2149*24e1c6aeSGleb Smirnoff unp_init(void *arg __unused)
215098271db4SGarrett Wollman {
21515362170dSMark Johnston 	uma_dtor dtor;
21521c381b19SRobert Watson 
21535362170dSMark Johnston #ifdef INVARIANTS
21545362170dSMark Johnston 	dtor = unp_zdtor;
21555362170dSMark Johnston #else
21565362170dSMark Johnston 	dtor = NULL;
21575362170dSMark Johnston #endif
21585362170dSMark Johnston 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
215975a67bf3SMatt Macy 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
21604f590175SPaul Saab 	uma_zone_set_max(unp_zone, maxsockets);
21616e0b6746SPawel Jakub Dawidek 	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
21624f590175SPaul Saab 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
21634f590175SPaul Saab 	    NULL, EVENTHANDLER_PRI_ANY);
216498271db4SGarrett Wollman 	LIST_INIT(&unp_dhead);
216598271db4SGarrett Wollman 	LIST_INIT(&unp_shead);
216684d61770SRobert Watson 	LIST_INIT(&unp_sphead);
21670cb64678SKonstantin Belousov 	SLIST_INIT(&unp_defers);
2168daee0f0bSKonstantin Belousov 	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
21690cb64678SKonstantin Belousov 	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
21703dab55bcSRobert Watson 	UNP_LINK_LOCK_INIT();
21710cb64678SKonstantin Belousov 	UNP_DEFERRED_LOCK_INIT();
217298271db4SGarrett Wollman }
2173*24e1c6aeSGleb Smirnoff SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
217498271db4SGarrett Wollman 
217547c3450eSKonstantin Belousov static void
217647c3450eSKonstantin Belousov unp_internalize_cleanup_rights(struct mbuf *control)
217747c3450eSKonstantin Belousov {
217847c3450eSKonstantin Belousov 	struct cmsghdr *cp;
217947c3450eSKonstantin Belousov 	struct mbuf *m;
218047c3450eSKonstantin Belousov 	void *data;
218147c3450eSKonstantin Belousov 	socklen_t datalen;
218247c3450eSKonstantin Belousov 
218347c3450eSKonstantin Belousov 	for (m = control; m != NULL; m = m->m_next) {
218447c3450eSKonstantin Belousov 		cp = mtod(m, struct cmsghdr *);
218547c3450eSKonstantin Belousov 		if (cp->cmsg_level != SOL_SOCKET ||
218647c3450eSKonstantin Belousov 		    cp->cmsg_type != SCM_RIGHTS)
218747c3450eSKonstantin Belousov 			continue;
218847c3450eSKonstantin Belousov 		data = CMSG_DATA(cp);
218947c3450eSKonstantin Belousov 		datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
219047c3450eSKonstantin Belousov 		unp_freerights(data, datalen / sizeof(struct filedesc *));
219147c3450eSKonstantin Belousov 	}
219247c3450eSKonstantin Belousov }
219347c3450eSKonstantin Belousov 
2194f708ef1bSPoul-Henning Kamp static int
2195892af6b9SRobert Watson unp_internalize(struct mbuf **controlp, struct thread *td)
2196df8bae1dSRodney W. Grimes {
219747c3450eSKonstantin Belousov 	struct mbuf *control, **initial_controlp;
219847c3450eSKonstantin Belousov 	struct proc *p;
219947c3450eSKonstantin Belousov 	struct filedesc *fdesc;
2200ab15d803SSergey Kandaurov 	struct bintime *bt;
220147c3450eSKonstantin Belousov 	struct cmsghdr *cm;
22022bc21ed9SDavid Malone 	struct cmsgcred *cmcred;
22038cb539f1SPawel Jakub Dawidek 	struct filedescent *fde, **fdep, *fdev;
22042bc21ed9SDavid Malone 	struct file *fp;
22052bc21ed9SDavid Malone 	struct timeval *tv;
2206339efd75SMaxim Sobolev 	struct timespec *ts;
22072bc21ed9SDavid Malone 	void *data;
220847c3450eSKonstantin Belousov 	socklen_t clen, datalen;
2209f1cf2b9dSKonstantin Belousov 	int i, j, error, *fdp, oldfds;
22108692c025SYoshinobu Inoue 	u_int newlen;
2211df8bae1dSRodney W. Grimes 
22123dab55bcSRobert Watson 	UNP_LINK_UNLOCK_ASSERT();
22134c5bc1caSRobert Watson 
221447c3450eSKonstantin Belousov 	p = td->td_proc;
221547c3450eSKonstantin Belousov 	fdesc = p->p_fd;
22162bc21ed9SDavid Malone 	error = 0;
221747c3450eSKonstantin Belousov 	control = *controlp;
221847c3450eSKonstantin Belousov 	clen = control->m_len;
22192bc21ed9SDavid Malone 	*controlp = NULL;
222047c3450eSKonstantin Belousov 	initial_controlp = controlp;
222147c3450eSKonstantin Belousov 	for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
22222bc21ed9SDavid Malone 		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2223de966666SMateusz Guzik 		    || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
22242bc21ed9SDavid Malone 			error = EINVAL;
22252bc21ed9SDavid Malone 			goto out;
22262bc21ed9SDavid Malone 		}
22272bc21ed9SDavid Malone 		data = CMSG_DATA(cm);
22282bc21ed9SDavid Malone 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
22292bc21ed9SDavid Malone 
22302bc21ed9SDavid Malone 		switch (cm->cmsg_type) {
22310b788fa1SBill Paul 		/*
22320b788fa1SBill Paul 		 * Fill in credential information.
22330b788fa1SBill Paul 		 */
22342bc21ed9SDavid Malone 		case SCM_CREDS:
22352bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
22362bc21ed9SDavid Malone 			    SCM_CREDS, SOL_SOCKET);
22372bc21ed9SDavid Malone 			if (*controlp == NULL) {
22382bc21ed9SDavid Malone 				error = ENOBUFS;
22392bc21ed9SDavid Malone 				goto out;
22402bc21ed9SDavid Malone 			}
22412bc21ed9SDavid Malone 			cmcred = (struct cmsgcred *)
22422bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
22430b788fa1SBill Paul 			cmcred->cmcred_pid = p->p_pid;
2244a854ed98SJohn Baldwin 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2245a854ed98SJohn Baldwin 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2246a854ed98SJohn Baldwin 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
2247a854ed98SJohn Baldwin 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
22480b788fa1SBill Paul 			    CMGROUP_MAX);
22490b788fa1SBill Paul 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
22502bc21ed9SDavid Malone 				cmcred->cmcred_groups[i] =
2251a854ed98SJohn Baldwin 				    td->td_ucred->cr_groups[i];
22522bc21ed9SDavid Malone 			break;
22530b788fa1SBill Paul 
22542bc21ed9SDavid Malone 		case SCM_RIGHTS:
22552bc21ed9SDavid Malone 			oldfds = datalen / sizeof (int);
225682e825c4SGleb Smirnoff 			if (oldfds == 0)
225782e825c4SGleb Smirnoff 				break;
2258ed5b7817SJulian Elischer 			/*
22591c381b19SRobert Watson 			 * Check that all the FDs passed in refer to legal
22601c381b19SRobert Watson 			 * files.  If not, reject the entire operation.
2261ed5b7817SJulian Elischer 			 */
22622bc21ed9SDavid Malone 			fdp = data;
22632609222aSPawel Jakub Dawidek 			FILEDESC_SLOCK(fdesc);
22646a1cf96bSMateusz Guzik 			for (i = 0; i < oldfds; i++, fdp++) {
22656a1cf96bSMateusz Guzik 				fp = fget_locked(fdesc, *fdp);
22666a1cf96bSMateusz Guzik 				if (fp == NULL) {
22672609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
22682bc21ed9SDavid Malone 					error = EBADF;
22692bc21ed9SDavid Malone 					goto out;
22702bc21ed9SDavid Malone 				}
2271e7d6662fSAlfred Perlstein 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
22722609222aSPawel Jakub Dawidek 					FILEDESC_SUNLOCK(fdesc);
2273e7d6662fSAlfred Perlstein 					error = EOPNOTSUPP;
2274e7d6662fSAlfred Perlstein 					goto out;
2275e7d6662fSAlfred Perlstein 				}
2276df8bae1dSRodney W. Grimes 			}
22775e3f7694SRobert Watson 
2278ed5b7817SJulian Elischer 			/*
22790b36cd25SRobert Watson 			 * Now replace the integer FDs with pointers to the
22802609222aSPawel Jakub Dawidek 			 * file structure and capability rights.
2281ed5b7817SJulian Elischer 			 */
22828cb539f1SPawel Jakub Dawidek 			newlen = oldfds * sizeof(fdep[0]);
22832bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, newlen,
22842bc21ed9SDavid Malone 			    SCM_RIGHTS, SOL_SOCKET);
22852bc21ed9SDavid Malone 			if (*controlp == NULL) {
22862609222aSPawel Jakub Dawidek 				FILEDESC_SUNLOCK(fdesc);
22872bc21ed9SDavid Malone 				error = E2BIG;
22882bc21ed9SDavid Malone 				goto out;
22898692c025SYoshinobu Inoue 			}
22902bc21ed9SDavid Malone 			fdp = data;
2291f1cf2b9dSKonstantin Belousov 			for (i = 0; i < oldfds; i++, fdp++) {
2292f1cf2b9dSKonstantin Belousov 				if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2293f1cf2b9dSKonstantin Belousov 					fdp = data;
2294f1cf2b9dSKonstantin Belousov 					for (j = 0; j < i; j++, fdp++) {
2295f1cf2b9dSKonstantin Belousov 						fdrop(fdesc->fd_ofiles[*fdp].
2296f1cf2b9dSKonstantin Belousov 						    fde_file, td);
2297f1cf2b9dSKonstantin Belousov 					}
2298f1cf2b9dSKonstantin Belousov 					FILEDESC_SUNLOCK(fdesc);
2299f1cf2b9dSKonstantin Belousov 					error = EBADF;
2300f1cf2b9dSKonstantin Belousov 					goto out;
2301f1cf2b9dSKonstantin Belousov 				}
2302f1cf2b9dSKonstantin Belousov 			}
2303f1cf2b9dSKonstantin Belousov 			fdp = data;
23048cb539f1SPawel Jakub Dawidek 			fdep = (struct filedescent **)
23052bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23068cb539f1SPawel Jakub Dawidek 			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
23078cb539f1SPawel Jakub Dawidek 			    M_WAITOK);
23088cb539f1SPawel Jakub Dawidek 			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
23092609222aSPawel Jakub Dawidek 				fde = &fdesc->fd_ofiles[*fdp];
23108cb539f1SPawel Jakub Dawidek 				fdep[i] = fdev;
23118cb539f1SPawel Jakub Dawidek 				fdep[i]->fde_file = fde->fde_file;
23128cb539f1SPawel Jakub Dawidek 				filecaps_copy(&fde->fde_caps,
2313d7832811SMateusz Guzik 				    &fdep[i]->fde_caps, true);
23148cb539f1SPawel Jakub Dawidek 				unp_internalize_fp(fdep[i]->fde_file);
2315df8bae1dSRodney W. Grimes 			}
23162609222aSPawel Jakub Dawidek 			FILEDESC_SUNLOCK(fdesc);
23172bc21ed9SDavid Malone 			break;
23182bc21ed9SDavid Malone 
23192bc21ed9SDavid Malone 		case SCM_TIMESTAMP:
23202bc21ed9SDavid Malone 			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
23212bc21ed9SDavid Malone 			    SCM_TIMESTAMP, SOL_SOCKET);
23222bc21ed9SDavid Malone 			if (*controlp == NULL) {
23232bc21ed9SDavid Malone 				error = ENOBUFS;
23242bc21ed9SDavid Malone 				goto out;
23258692c025SYoshinobu Inoue 			}
23262bc21ed9SDavid Malone 			tv = (struct timeval *)
23272bc21ed9SDavid Malone 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
23282bc21ed9SDavid Malone 			microtime(tv);
23292bc21ed9SDavid Malone 			break;
23302bc21ed9SDavid Malone 
2331ab15d803SSergey Kandaurov 		case SCM_BINTIME:
2332ab15d803SSergey Kandaurov 			*controlp = sbcreatecontrol(NULL, sizeof(*bt),
2333ab15d803SSergey Kandaurov 			    SCM_BINTIME, SOL_SOCKET);
2334ab15d803SSergey Kandaurov 			if (*controlp == NULL) {
2335ab15d803SSergey Kandaurov 				error = ENOBUFS;
2336ab15d803SSergey Kandaurov 				goto out;
2337ab15d803SSergey Kandaurov 			}
2338ab15d803SSergey Kandaurov 			bt = (struct bintime *)
2339ab15d803SSergey Kandaurov 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2340ab15d803SSergey Kandaurov 			bintime(bt);
2341ab15d803SSergey Kandaurov 			break;
2342ab15d803SSergey Kandaurov 
2343339efd75SMaxim Sobolev 		case SCM_REALTIME:
2344339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2345339efd75SMaxim Sobolev 			    SCM_REALTIME, SOL_SOCKET);
2346339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2347339efd75SMaxim Sobolev 				error = ENOBUFS;
2348339efd75SMaxim Sobolev 				goto out;
2349339efd75SMaxim Sobolev 			}
2350339efd75SMaxim Sobolev 			ts = (struct timespec *)
2351339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2352339efd75SMaxim Sobolev 			nanotime(ts);
2353339efd75SMaxim Sobolev 			break;
2354339efd75SMaxim Sobolev 
2355339efd75SMaxim Sobolev 		case SCM_MONOTONIC:
2356339efd75SMaxim Sobolev 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2357339efd75SMaxim Sobolev 			    SCM_MONOTONIC, SOL_SOCKET);
2358339efd75SMaxim Sobolev 			if (*controlp == NULL) {
2359339efd75SMaxim Sobolev 				error = ENOBUFS;
2360339efd75SMaxim Sobolev 				goto out;
2361339efd75SMaxim Sobolev 			}
2362339efd75SMaxim Sobolev 			ts = (struct timespec *)
2363339efd75SMaxim Sobolev 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2364339efd75SMaxim Sobolev 			nanouptime(ts);
2365339efd75SMaxim Sobolev 			break;
2366339efd75SMaxim Sobolev 
23672bc21ed9SDavid Malone 		default:
23682bc21ed9SDavid Malone 			error = EINVAL;
23692bc21ed9SDavid Malone 			goto out;
23702bc21ed9SDavid Malone 		}
23712bc21ed9SDavid Malone 
23724013d726SMark Johnston 		if (*controlp != NULL)
23732bc21ed9SDavid Malone 			controlp = &(*controlp)->m_next;
23742bc21ed9SDavid Malone 		if (CMSG_SPACE(datalen) < clen) {
23752bc21ed9SDavid Malone 			clen -= CMSG_SPACE(datalen);
23762bc21ed9SDavid Malone 			cm = (struct cmsghdr *)
23772bc21ed9SDavid Malone 			    ((caddr_t)cm + CMSG_SPACE(datalen));
23782bc21ed9SDavid Malone 		} else {
23792bc21ed9SDavid Malone 			clen = 0;
23802bc21ed9SDavid Malone 			cm = NULL;
23812bc21ed9SDavid Malone 		}
23822bc21ed9SDavid Malone 	}
23832bc21ed9SDavid Malone 
23842bc21ed9SDavid Malone out:
238547c3450eSKonstantin Belousov 	if (error != 0 && initial_controlp != NULL)
238647c3450eSKonstantin Belousov 		unp_internalize_cleanup_rights(*initial_controlp);
23872bc21ed9SDavid Malone 	m_freem(control);
23882bc21ed9SDavid Malone 	return (error);
2389df8bae1dSRodney W. Grimes }
2390df8bae1dSRodney W. Grimes 
23915b950deaSRobert Watson static struct mbuf *
2392ede4af47SConrad Meyer unp_addsockcred(struct thread *td, struct mbuf *control, int mode)
23936a2989fdSMatthew N. Dodd {
239470df31f4SMaxim Konovalov 	struct mbuf *m, *n, *n_prev;
239570df31f4SMaxim Konovalov 	const struct cmsghdr *cm;
2396ede4af47SConrad Meyer 	int ngroups, i, cmsgtype;
2397ede4af47SConrad Meyer 	size_t ctrlsz;
23986a2989fdSMatthew N. Dodd 
23996a2989fdSMatthew N. Dodd 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2400ede4af47SConrad Meyer 	if (mode & UNP_WANTCRED_ALWAYS) {
2401ede4af47SConrad Meyer 		ctrlsz = SOCKCRED2SIZE(ngroups);
2402ede4af47SConrad Meyer 		cmsgtype = SCM_CREDS2;
2403ede4af47SConrad Meyer 	} else {
2404ede4af47SConrad Meyer 		ctrlsz = SOCKCREDSIZE(ngroups);
2405ede4af47SConrad Meyer 		cmsgtype = SCM_CREDS;
2406ede4af47SConrad Meyer 	}
2407ede4af47SConrad Meyer 
2408ede4af47SConrad Meyer 	m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET);
24096a2989fdSMatthew N. Dodd 	if (m == NULL)
24106a2989fdSMatthew N. Dodd 		return (control);
24116a2989fdSMatthew N. Dodd 
2412ede4af47SConrad Meyer 	if (mode & UNP_WANTCRED_ALWAYS) {
2413ede4af47SConrad Meyer 		struct sockcred2 *sc;
2414ede4af47SConrad Meyer 
2415ede4af47SConrad Meyer 		sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2416ede4af47SConrad Meyer 		sc->sc_version = 0;
2417ede4af47SConrad Meyer 		sc->sc_pid = td->td_proc->p_pid;
24186a2989fdSMatthew N. Dodd 		sc->sc_uid = td->td_ucred->cr_ruid;
24196a2989fdSMatthew N. Dodd 		sc->sc_euid = td->td_ucred->cr_uid;
24206a2989fdSMatthew N. Dodd 		sc->sc_gid = td->td_ucred->cr_rgid;
24216a2989fdSMatthew N. Dodd 		sc->sc_egid = td->td_ucred->cr_gid;
24226a2989fdSMatthew N. Dodd 		sc->sc_ngroups = ngroups;
24236a2989fdSMatthew N. Dodd 		for (i = 0; i < sc->sc_ngroups; i++)
24246a2989fdSMatthew N. Dodd 			sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2425ede4af47SConrad Meyer 	} else {
2426ede4af47SConrad Meyer 		struct sockcred *sc;
2427ede4af47SConrad Meyer 
2428ede4af47SConrad Meyer 		sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2429ede4af47SConrad Meyer 		sc->sc_uid = td->td_ucred->cr_ruid;
2430ede4af47SConrad Meyer 		sc->sc_euid = td->td_ucred->cr_uid;
2431ede4af47SConrad Meyer 		sc->sc_gid = td->td_ucred->cr_rgid;
2432ede4af47SConrad Meyer 		sc->sc_egid = td->td_ucred->cr_gid;
2433ede4af47SConrad Meyer 		sc->sc_ngroups = ngroups;
2434ede4af47SConrad Meyer 		for (i = 0; i < sc->sc_ngroups; i++)
2435ede4af47SConrad Meyer 			sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2436ede4af47SConrad Meyer 	}
24376a2989fdSMatthew N. Dodd 
24386a2989fdSMatthew N. Dodd 	/*
24391c381b19SRobert Watson 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
24401c381b19SRobert Watson 	 * created SCM_CREDS control message (struct sockcred) has another
24411c381b19SRobert Watson 	 * format.
24426a2989fdSMatthew N. Dodd 	 */
2443ede4af47SConrad Meyer 	if (control != NULL && cmsgtype == SCM_CREDS)
244470df31f4SMaxim Konovalov 		for (n = control, n_prev = NULL; n != NULL;) {
244570df31f4SMaxim Konovalov 			cm = mtod(n, struct cmsghdr *);
244670df31f4SMaxim Konovalov     			if (cm->cmsg_level == SOL_SOCKET &&
244770df31f4SMaxim Konovalov 			    cm->cmsg_type == SCM_CREDS) {
244870df31f4SMaxim Konovalov     				if (n_prev == NULL)
244970df31f4SMaxim Konovalov 					control = n->m_next;
245070df31f4SMaxim Konovalov 				else
245170df31f4SMaxim Konovalov 					n_prev->m_next = n->m_next;
245270df31f4SMaxim Konovalov 				n = m_free(n);
245370df31f4SMaxim Konovalov 			} else {
245470df31f4SMaxim Konovalov 				n_prev = n;
245570df31f4SMaxim Konovalov 				n = n->m_next;
245670df31f4SMaxim Konovalov 			}
245770df31f4SMaxim Konovalov 		}
24586a2989fdSMatthew N. Dodd 
245970df31f4SMaxim Konovalov 	/* Prepend it to the head. */
246070df31f4SMaxim Konovalov 	m->m_next = control;
246170df31f4SMaxim Konovalov 	return (m);
24626a2989fdSMatthew N. Dodd }
24636a2989fdSMatthew N. Dodd 
2464397c19d1SJeff Roberson static struct unpcb *
2465397c19d1SJeff Roberson fptounp(struct file *fp)
2466397c19d1SJeff Roberson {
2467397c19d1SJeff Roberson 	struct socket *so;
2468397c19d1SJeff Roberson 
2469397c19d1SJeff Roberson 	if (fp->f_type != DTYPE_SOCKET)
2470397c19d1SJeff Roberson 		return (NULL);
2471397c19d1SJeff Roberson 	if ((so = fp->f_data) == NULL)
2472397c19d1SJeff Roberson 		return (NULL);
2473397c19d1SJeff Roberson 	if (so->so_proto->pr_domain != &localdomain)
2474397c19d1SJeff Roberson 		return (NULL);
2475397c19d1SJeff Roberson 	return sotounpcb(so);
2476397c19d1SJeff Roberson }
2477397c19d1SJeff Roberson 
2478397c19d1SJeff Roberson static void
2479397c19d1SJeff Roberson unp_discard(struct file *fp)
2480397c19d1SJeff Roberson {
24810cb64678SKonstantin Belousov 	struct unp_defer *dr;
2482397c19d1SJeff Roberson 
24830cb64678SKonstantin Belousov 	if (unp_externalize_fp(fp)) {
24840cb64678SKonstantin Belousov 		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
24850cb64678SKonstantin Belousov 		dr->ud_fp = fp;
24860cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
24870cb64678SKonstantin Belousov 		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
24880cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
24890cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, 1);
24900cb64678SKonstantin Belousov 		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
24910cb64678SKonstantin Belousov 	} else
24924faa375cSMateusz Guzik 		closef_nothread(fp);
2493397c19d1SJeff Roberson }
2494397c19d1SJeff Roberson 
2495397c19d1SJeff Roberson static void
24960cb64678SKonstantin Belousov unp_process_defers(void *arg __unused, int pending)
24970cb64678SKonstantin Belousov {
24980cb64678SKonstantin Belousov 	struct unp_defer *dr;
24990cb64678SKonstantin Belousov 	SLIST_HEAD(, unp_defer) drl;
25000cb64678SKonstantin Belousov 	int count;
25010cb64678SKonstantin Belousov 
25020cb64678SKonstantin Belousov 	SLIST_INIT(&drl);
25030cb64678SKonstantin Belousov 	for (;;) {
25040cb64678SKonstantin Belousov 		UNP_DEFERRED_LOCK();
25050cb64678SKonstantin Belousov 		if (SLIST_FIRST(&unp_defers) == NULL) {
25060cb64678SKonstantin Belousov 			UNP_DEFERRED_UNLOCK();
25070cb64678SKonstantin Belousov 			break;
25080cb64678SKonstantin Belousov 		}
25090cb64678SKonstantin Belousov 		SLIST_SWAP(&unp_defers, &drl, unp_defer);
25100cb64678SKonstantin Belousov 		UNP_DEFERRED_UNLOCK();
25110cb64678SKonstantin Belousov 		count = 0;
25120cb64678SKonstantin Belousov 		while ((dr = SLIST_FIRST(&drl)) != NULL) {
25130cb64678SKonstantin Belousov 			SLIST_REMOVE_HEAD(&drl, ud_link);
25144faa375cSMateusz Guzik 			closef_nothread(dr->ud_fp);
25150cb64678SKonstantin Belousov 			free(dr, M_TEMP);
25160cb64678SKonstantin Belousov 			count++;
25170cb64678SKonstantin Belousov 		}
25180cb64678SKonstantin Belousov 		atomic_add_int(&unp_defers_count, -count);
25190cb64678SKonstantin Belousov 	}
25200cb64678SKonstantin Belousov }
25210cb64678SKonstantin Belousov 
25220cb64678SKonstantin Belousov static void
2523397c19d1SJeff Roberson unp_internalize_fp(struct file *fp)
2524397c19d1SJeff Roberson {
2525397c19d1SJeff Roberson 	struct unpcb *unp;
2526397c19d1SJeff Roberson 
25273dab55bcSRobert Watson 	UNP_LINK_WLOCK();
2528397c19d1SJeff Roberson 	if ((unp = fptounp(fp)) != NULL) {
2529397c19d1SJeff Roberson 		unp->unp_file = fp;
2530397c19d1SJeff Roberson 		unp->unp_msgcount++;
2531397c19d1SJeff Roberson 	}
2532397c19d1SJeff Roberson 	unp_rights++;
25333dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
2534397c19d1SJeff Roberson }
2535397c19d1SJeff Roberson 
25360cb64678SKonstantin Belousov static int
2537397c19d1SJeff Roberson unp_externalize_fp(struct file *fp)
2538397c19d1SJeff Roberson {
2539397c19d1SJeff Roberson 	struct unpcb *unp;
25400cb64678SKonstantin Belousov 	int ret;
2541397c19d1SJeff Roberson 
25423dab55bcSRobert Watson 	UNP_LINK_WLOCK();
25430cb64678SKonstantin Belousov 	if ((unp = fptounp(fp)) != NULL) {
2544397c19d1SJeff Roberson 		unp->unp_msgcount--;
25450cb64678SKonstantin Belousov 		ret = 1;
25460cb64678SKonstantin Belousov 	} else
25470cb64678SKonstantin Belousov 		ret = 0;
2548397c19d1SJeff Roberson 	unp_rights--;
25493dab55bcSRobert Watson 	UNP_LINK_WUNLOCK();
25500cb64678SKonstantin Belousov 	return (ret);
2551397c19d1SJeff Roberson }
2552397c19d1SJeff Roberson 
2553161a0c7cSRobert Watson /*
2554a0ec558aSRobert Watson  * unp_defer indicates whether additional work has been defered for a future
2555a0ec558aSRobert Watson  * pass through unp_gc().  It is thread local and does not require explicit
2556a0ec558aSRobert Watson  * synchronization.
2557161a0c7cSRobert Watson  */
2558397c19d1SJeff Roberson static int	unp_marked;
2559a0ec558aSRobert Watson 
2560397c19d1SJeff Roberson static void
2561a9aa06f7SJason A. Harmening unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2562397c19d1SJeff Roberson {
2563397c19d1SJeff Roberson 	struct unpcb *unp;
2564be26ba7cSPawel Jakub Dawidek 	struct file *fp;
2565be26ba7cSPawel Jakub Dawidek 	int i;
2566397c19d1SJeff Roberson 
2567a9aa06f7SJason A. Harmening 	/*
2568a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2569a9aa06f7SJason A. Harmening 	 */
2570a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2571a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2572a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2573a9aa06f7SJason A. Harmening 
2574be26ba7cSPawel Jakub Dawidek 	for (i = 0; i < fdcount; i++) {
2575be26ba7cSPawel Jakub Dawidek 		fp = fdep[i]->fde_file;
25766f552cb0SJeff Roberson 		if ((unp = fptounp(fp)) == NULL)
2577be26ba7cSPawel Jakub Dawidek 			continue;
2578a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2579be26ba7cSPawel Jakub Dawidek 			continue;
2580a9aa06f7SJason A. Harmening 		unp->unp_gcrefs--;
2581a9aa06f7SJason A. Harmening 	}
2582a9aa06f7SJason A. Harmening }
2583a9aa06f7SJason A. Harmening 
2584a9aa06f7SJason A. Harmening static void
2585a9aa06f7SJason A. Harmening unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2586a9aa06f7SJason A. Harmening {
2587a9aa06f7SJason A. Harmening 	struct unpcb *unp;
2588a9aa06f7SJason A. Harmening 	struct file *fp;
2589a9aa06f7SJason A. Harmening 	int i;
2590a9aa06f7SJason A. Harmening 
2591a9aa06f7SJason A. Harmening 	/*
2592a9aa06f7SJason A. Harmening 	 * This function can only be called from the gc task.
2593a9aa06f7SJason A. Harmening 	 */
2594a9aa06f7SJason A. Harmening 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2595a9aa06f7SJason A. Harmening 	    ("%s: not on gc callout", __func__));
2596a9aa06f7SJason A. Harmening 	UNP_LINK_LOCK_ASSERT();
2597a9aa06f7SJason A. Harmening 
2598a9aa06f7SJason A. Harmening 	for (i = 0; i < fdcount; i++) {
2599a9aa06f7SJason A. Harmening 		fp = fdep[i]->fde_file;
2600a9aa06f7SJason A. Harmening 		if ((unp = fptounp(fp)) == NULL)
2601a9aa06f7SJason A. Harmening 			continue;
2602a9aa06f7SJason A. Harmening 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2603a9aa06f7SJason A. Harmening 			continue;
2604a9aa06f7SJason A. Harmening 		unp->unp_gcrefs++;
2605397c19d1SJeff Roberson 		unp_marked++;
2606397c19d1SJeff Roberson 	}
2607be26ba7cSPawel Jakub Dawidek }
2608397c19d1SJeff Roberson 
2609397c19d1SJeff Roberson static void
2610a9aa06f7SJason A. Harmening unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2611397c19d1SJeff Roberson {
2612779f106aSGleb Smirnoff 	struct socket *so, *soa;
261360a5ef26SRobert Watson 
2614397c19d1SJeff Roberson 	so = unp->unp_socket;
2615779f106aSGleb Smirnoff 	SOCK_LOCK(so);
2616779f106aSGleb Smirnoff 	if (SOLISTENING(so)) {
2617397c19d1SJeff Roberson 		/*
2618397c19d1SJeff Roberson 		 * Mark all sockets in our accept queue.
2619397c19d1SJeff Roberson 		 */
2620779f106aSGleb Smirnoff 		TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2621779f106aSGleb Smirnoff 			if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
26220c40f353SConrad Meyer 				continue;
2623397c19d1SJeff Roberson 			SOCKBUF_LOCK(&soa->so_rcv);
2624a9aa06f7SJason A. Harmening 			unp_scan(soa->so_rcv.sb_mb, op);
2625397c19d1SJeff Roberson 			SOCKBUF_UNLOCK(&soa->so_rcv);
2626397c19d1SJeff Roberson 		}
2627779f106aSGleb Smirnoff 	} else {
2628779f106aSGleb Smirnoff 		/*
2629779f106aSGleb Smirnoff 		 * Mark all sockets we reference with RIGHTS.
2630779f106aSGleb Smirnoff 		 */
2631779f106aSGleb Smirnoff 		if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2632779f106aSGleb Smirnoff 			SOCKBUF_LOCK(&so->so_rcv);
2633a9aa06f7SJason A. Harmening 			unp_scan(so->so_rcv.sb_mb, op);
2634779f106aSGleb Smirnoff 			SOCKBUF_UNLOCK(&so->so_rcv);
2635779f106aSGleb Smirnoff 		}
2636779f106aSGleb Smirnoff 	}
2637779f106aSGleb Smirnoff 	SOCK_UNLOCK(so);
2638397c19d1SJeff Roberson }
2639a0ec558aSRobert Watson 
2640a0ec558aSRobert Watson static int unp_recycled;
2641be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2642be6b1304STom Rhodes     "Number of unreachable sockets claimed by the garbage collector.");
2643df8bae1dSRodney W. Grimes 
2644397c19d1SJeff Roberson static int unp_taskcount;
2645be6b1304STom Rhodes SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2646be6b1304STom Rhodes     "Number of times the garbage collector has run.");
2647397c19d1SJeff Roberson 
2648a9aa06f7SJason A. Harmening SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
2649a9aa06f7SJason A. Harmening     "Number of active local sockets.");
2650a9aa06f7SJason A. Harmening 
2651f708ef1bSPoul-Henning Kamp static void
2652a0ec558aSRobert Watson unp_gc(__unused void *arg, int pending)
2653df8bae1dSRodney W. Grimes {
265484d61770SRobert Watson 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
265584d61770SRobert Watson 				    NULL };
2656397c19d1SJeff Roberson 	struct unp_head **head;
2657a9aa06f7SJason A. Harmening 	struct unp_head unp_deadhead;	/* List of potentially-dead sockets. */
2658f7780c61SKonstantin Belousov 	struct file *f, **unref;
2659a9aa06f7SJason A. Harmening 	struct unpcb *unp, *unptmp;
2660a9aa06f7SJason A. Harmening 	int i, total, unp_unreachable;
2661df8bae1dSRodney W. Grimes 
2662a9aa06f7SJason A. Harmening 	LIST_INIT(&unp_deadhead);
2663a0ec558aSRobert Watson 	unp_taskcount++;
2664779f106aSGleb Smirnoff 	UNP_LINK_RLOCK();
2665ed5b7817SJulian Elischer 	/*
2666a9aa06f7SJason A. Harmening 	 * First determine which sockets may be in cycles.
2667ed5b7817SJulian Elischer 	 */
2668a9aa06f7SJason A. Harmening 	unp_unreachable = 0;
2669a9aa06f7SJason A. Harmening 
2670397c19d1SJeff Roberson 	for (head = heads; *head != NULL; head++)
2671a9aa06f7SJason A. Harmening 		LIST_FOREACH(unp, *head, unp_link) {
2672a9aa06f7SJason A. Harmening 			KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2673a9aa06f7SJason A. Harmening 			    ("%s: unp %p has unexpected gc flags 0x%x",
2674a9aa06f7SJason A. Harmening 			    __func__, unp, (unsigned int)unp->unp_gcflag));
2675a9aa06f7SJason A. Harmening 
2676a9aa06f7SJason A. Harmening 			f = unp->unp_file;
267760a5ef26SRobert Watson 
2678397c19d1SJeff Roberson 			/*
2679a9aa06f7SJason A. Harmening 			 * Check for an unreachable socket potentially in a
2680a9aa06f7SJason A. Harmening 			 * cycle.  It must be in a queue as indicated by
2681a9aa06f7SJason A. Harmening 			 * msgcount, and this must equal the file reference
2682a9aa06f7SJason A. Harmening 			 * count.  Note that when msgcount is 0 the file is
2683a9aa06f7SJason A. Harmening 			 * NULL.
2684a9aa06f7SJason A. Harmening 			 */
2685a9aa06f7SJason A. Harmening 			if (f != NULL && unp->unp_msgcount != 0 &&
26863c50616fSMateusz Guzik 			    refcount_load(&f->f_count) == unp->unp_msgcount) {
2687a9aa06f7SJason A. Harmening 				LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2688a9aa06f7SJason A. Harmening 				unp->unp_gcflag |= UNPGC_DEAD;
2689a9aa06f7SJason A. Harmening 				unp->unp_gcrefs = unp->unp_msgcount;
2690a9aa06f7SJason A. Harmening 				unp_unreachable++;
2691a9aa06f7SJason A. Harmening 			}
2692a9aa06f7SJason A. Harmening 		}
2693a9aa06f7SJason A. Harmening 
2694a9aa06f7SJason A. Harmening 	/*
2695a9aa06f7SJason A. Harmening 	 * Scan all sockets previously marked as potentially being in a cycle
2696a9aa06f7SJason A. Harmening 	 * and remove the references each socket holds on any UNPGC_DEAD
2697a9aa06f7SJason A. Harmening 	 * sockets in its queue.  After this step, all remaining references on
2698a9aa06f7SJason A. Harmening 	 * sockets marked UNPGC_DEAD should not be part of any cycle.
2699a9aa06f7SJason A. Harmening 	 */
2700a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead)
2701a9aa06f7SJason A. Harmening 		unp_gc_scan(unp, unp_remove_dead_ref);
2702a9aa06f7SJason A. Harmening 
2703a9aa06f7SJason A. Harmening 	/*
2704a9aa06f7SJason A. Harmening 	 * If a socket still has a non-negative refcount, it cannot be in a
2705a9aa06f7SJason A. Harmening 	 * cycle.  In this case increment refcount of all children iteratively.
2706397c19d1SJeff Roberson 	 * Stop the scan once we do a complete loop without discovering
2707397c19d1SJeff Roberson 	 * a new reachable socket.
2708397c19d1SJeff Roberson 	 */
2709df8bae1dSRodney W. Grimes 	do {
2710397c19d1SJeff Roberson 		unp_marked = 0;
2711a9aa06f7SJason A. Harmening 		LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
2712a9aa06f7SJason A. Harmening 			if (unp->unp_gcrefs > 0) {
2713a9aa06f7SJason A. Harmening 				unp->unp_gcflag &= ~UNPGC_DEAD;
2714a9aa06f7SJason A. Harmening 				LIST_REMOVE(unp, unp_dead);
2715a9aa06f7SJason A. Harmening 				KASSERT(unp_unreachable > 0,
2716a9aa06f7SJason A. Harmening 				    ("%s: unp_unreachable underflow.",
2717a9aa06f7SJason A. Harmening 				    __func__));
2718a9aa06f7SJason A. Harmening 				unp_unreachable--;
2719a9aa06f7SJason A. Harmening 				unp_gc_scan(unp, unp_restore_undead_ref);
2720a9aa06f7SJason A. Harmening 			}
2721397c19d1SJeff Roberson 	} while (unp_marked);
2722a9aa06f7SJason A. Harmening 
2723779f106aSGleb Smirnoff 	UNP_LINK_RUNLOCK();
2724a9aa06f7SJason A. Harmening 
2725397c19d1SJeff Roberson 	if (unp_unreachable == 0)
2726397c19d1SJeff Roberson 		return;
272760a5ef26SRobert Watson 
2728ed5b7817SJulian Elischer 	/*
2729a9aa06f7SJason A. Harmening 	 * Allocate space for a local array of dead unpcbs.
2730a9aa06f7SJason A. Harmening 	 * TODO: can this path be simplified by instead using the local
2731a9aa06f7SJason A. Harmening 	 * dead list at unp_deadhead, after taking out references
2732a9aa06f7SJason A. Harmening 	 * on the file object and/or unpcb and dropping the link lock?
2733ed5b7817SJulian Elischer 	 */
2734397c19d1SJeff Roberson 	unref = malloc(unp_unreachable * sizeof(struct file *),
2735397c19d1SJeff Roberson 	    M_TEMP, M_WAITOK);
273660a5ef26SRobert Watson 
2737ed5b7817SJulian Elischer 	/*
2738397c19d1SJeff Roberson 	 * Iterate looking for sockets which have been specifically marked
2739a9aa06f7SJason A. Harmening 	 * as unreachable and store them locally.
2740ed5b7817SJulian Elischer 	 */
2741f7780c61SKonstantin Belousov 	UNP_LINK_RLOCK();
2742a9aa06f7SJason A. Harmening 	total = 0;
2743a9aa06f7SJason A. Harmening 	LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
2744a9aa06f7SJason A. Harmening 		KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
2745a9aa06f7SJason A. Harmening 		    ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
2746a9aa06f7SJason A. Harmening 		unp->unp_gcflag &= ~UNPGC_DEAD;
2747f7780c61SKonstantin Belousov 		f = unp->unp_file;
2748f7780c61SKonstantin Belousov 		if (unp->unp_msgcount == 0 || f == NULL ||
27493c50616fSMateusz Guzik 		    refcount_load(&f->f_count) != unp->unp_msgcount ||
2750f1cf2b9dSKonstantin Belousov 		    !fhold(f))
2751f7780c61SKonstantin Belousov 			continue;
2752f7780c61SKonstantin Belousov 		unref[total++] = f;
2753f7780c61SKonstantin Belousov 		KASSERT(total <= unp_unreachable,
2754a9aa06f7SJason A. Harmening 		    ("%s: incorrect unreachable count.", __func__));
2755397c19d1SJeff Roberson 	}
2756f7780c61SKonstantin Belousov 	UNP_LINK_RUNLOCK();
275760a5ef26SRobert Watson 
2758ed5b7817SJulian Elischer 	/*
2759397c19d1SJeff Roberson 	 * Now flush all sockets, free'ing rights.  This will free the
2760397c19d1SJeff Roberson 	 * struct files associated with these sockets but leave each socket
2761397c19d1SJeff Roberson 	 * with one remaining ref.
2762ed5b7817SJulian Elischer 	 */
27631fb51a12SBjoern A. Zeeb 	for (i = 0; i < total; i++) {
27641fb51a12SBjoern A. Zeeb 		struct socket *so;
27651fb51a12SBjoern A. Zeeb 
27661fb51a12SBjoern A. Zeeb 		so = unref[i]->f_data;
27671fb51a12SBjoern A. Zeeb 		CURVNET_SET(so->so_vnet);
27681fb51a12SBjoern A. Zeeb 		sorflush(so);
27691fb51a12SBjoern A. Zeeb 		CURVNET_RESTORE();
27701fb51a12SBjoern A. Zeeb 	}
277160a5ef26SRobert Watson 
2772ed5b7817SJulian Elischer 	/*
2773397c19d1SJeff Roberson 	 * And finally release the sockets so they can be reclaimed.
2774ed5b7817SJulian Elischer 	 */
2775f7780c61SKonstantin Belousov 	for (i = 0; i < total; i++)
2776397c19d1SJeff Roberson 		fdrop(unref[i], NULL);
2777f7780c61SKonstantin Belousov 	unp_recycled += total;
2778397c19d1SJeff Roberson 	free(unref, M_TEMP);
2779df8bae1dSRodney W. Grimes }
2780df8bae1dSRodney W. Grimes 
27810b36cd25SRobert Watson static void
278299ab95dbSMark Johnston unp_dispose_mbuf(struct mbuf *m)
2783df8bae1dSRodney W. Grimes {
2784996c772fSJohn Dyson 
2785df8bae1dSRodney W. Grimes 	if (m)
2786be26ba7cSPawel Jakub Dawidek 		unp_scan(m, unp_freerights);
2787df8bae1dSRodney W. Grimes }
2788df8bae1dSRodney W. Grimes 
27890c40f353SConrad Meyer /*
27900c40f353SConrad Meyer  * Synchronize against unp_gc, which can trip over data as we are freeing it.
27910c40f353SConrad Meyer  */
27920c40f353SConrad Meyer static void
279399ab95dbSMark Johnston unp_dispose(struct socket *so)
27940c40f353SConrad Meyer {
27950c40f353SConrad Meyer 	struct unpcb *unp;
27960c40f353SConrad Meyer 
27970c40f353SConrad Meyer 	unp = sotounpcb(so);
2798779f106aSGleb Smirnoff 	UNP_LINK_WLOCK();
27990c40f353SConrad Meyer 	unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2800779f106aSGleb Smirnoff 	UNP_LINK_WUNLOCK();
2801779f106aSGleb Smirnoff 	if (!SOLISTENING(so))
280299ab95dbSMark Johnston 		unp_dispose_mbuf(so->so_rcv.sb_mb);
28030c40f353SConrad Meyer }
28040c40f353SConrad Meyer 
2805f708ef1bSPoul-Henning Kamp static void
2806be26ba7cSPawel Jakub Dawidek unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2807df8bae1dSRodney W. Grimes {
28082bc21ed9SDavid Malone 	struct mbuf *m;
28092bc21ed9SDavid Malone 	struct cmsghdr *cm;
28102bc21ed9SDavid Malone 	void *data;
28112bc21ed9SDavid Malone 	socklen_t clen, datalen;
2812df8bae1dSRodney W. Grimes 
2813fc3fcacfSRobert Watson 	while (m0 != NULL) {
28142bc21ed9SDavid Malone 		for (m = m0; m; m = m->m_next) {
281512396bdcSDavid Malone 			if (m->m_type != MT_CONTROL)
2816df8bae1dSRodney W. Grimes 				continue;
28172bc21ed9SDavid Malone 
28182bc21ed9SDavid Malone 			cm = mtod(m, struct cmsghdr *);
28192bc21ed9SDavid Malone 			clen = m->m_len;
28202bc21ed9SDavid Malone 
28212bc21ed9SDavid Malone 			while (cm != NULL) {
28222bc21ed9SDavid Malone 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
28232bc21ed9SDavid Malone 					break;
28242bc21ed9SDavid Malone 
28252bc21ed9SDavid Malone 				data = CMSG_DATA(cm);
28262bc21ed9SDavid Malone 				datalen = (caddr_t)cm + cm->cmsg_len
28272bc21ed9SDavid Malone 				    - (caddr_t)data;
28282bc21ed9SDavid Malone 
28292bc21ed9SDavid Malone 				if (cm->cmsg_level == SOL_SOCKET &&
28302bc21ed9SDavid Malone 				    cm->cmsg_type == SCM_RIGHTS) {
2831be26ba7cSPawel Jakub Dawidek 					(*op)(data, datalen /
2832be26ba7cSPawel Jakub Dawidek 					    sizeof(struct filedescent *));
28332bc21ed9SDavid Malone 				}
28342bc21ed9SDavid Malone 
28352bc21ed9SDavid Malone 				if (CMSG_SPACE(datalen) < clen) {
28362bc21ed9SDavid Malone 					clen -= CMSG_SPACE(datalen);
28372bc21ed9SDavid Malone 					cm = (struct cmsghdr *)
28382bc21ed9SDavid Malone 					    ((caddr_t)cm + CMSG_SPACE(datalen));
28392bc21ed9SDavid Malone 				} else {
28402bc21ed9SDavid Malone 					clen = 0;
28412bc21ed9SDavid Malone 					cm = NULL;
28422bc21ed9SDavid Malone 				}
28432bc21ed9SDavid Malone 			}
2844df8bae1dSRodney W. Grimes 		}
2845c29a3321SKevin Lo 		m0 = m0->m_nextpkt;
2846df8bae1dSRodney W. Grimes 	}
2847df8bae1dSRodney W. Grimes }
2848df8bae1dSRodney W. Grimes 
2849662c901cSMikolaj Golub /*
2850662c901cSMikolaj Golub  * A helper function called by VFS before socket-type vnode reclamation.
2851662c901cSMikolaj Golub  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2852662c901cSMikolaj Golub  * use count.
2853662c901cSMikolaj Golub  */
2854662c901cSMikolaj Golub void
2855662c901cSMikolaj Golub vfs_unp_reclaim(struct vnode *vp)
2856662c901cSMikolaj Golub {
2857662c901cSMikolaj Golub 	struct unpcb *unp;
2858662c901cSMikolaj Golub 	int active;
285975a67bf3SMatt Macy 	struct mtx *vplock;
2860662c901cSMikolaj Golub 
2861662c901cSMikolaj Golub 	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2862662c901cSMikolaj Golub 	KASSERT(vp->v_type == VSOCK,
2863662c901cSMikolaj Golub 	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2864662c901cSMikolaj Golub 
2865662c901cSMikolaj Golub 	active = 0;
286675a67bf3SMatt Macy 	vplock = mtx_pool_find(mtxpool_sleep, vp);
286775a67bf3SMatt Macy 	mtx_lock(vplock);
28680c3c207fSGleb Smirnoff 	VOP_UNP_CONNECT(vp, &unp);
2869662c901cSMikolaj Golub 	if (unp == NULL)
2870662c901cSMikolaj Golub 		goto done;
2871662c901cSMikolaj Golub 	UNP_PCB_LOCK(unp);
2872c7e41c8bSMikolaj Golub 	if (unp->unp_vnode == vp) {
2873c7e41c8bSMikolaj Golub 		VOP_UNP_DETACH(vp);
2874662c901cSMikolaj Golub 		unp->unp_vnode = NULL;
2875662c901cSMikolaj Golub 		active = 1;
2876662c901cSMikolaj Golub 	}
2877662c901cSMikolaj Golub 	UNP_PCB_UNLOCK(unp);
2878662c901cSMikolaj Golub  done:
287975a67bf3SMatt Macy 	mtx_unlock(vplock);
2880662c901cSMikolaj Golub 	if (active)
2881662c901cSMikolaj Golub 		vunref(vp);
2882662c901cSMikolaj Golub }
2883662c901cSMikolaj Golub 
288403c96c31SRobert Watson #ifdef DDB
288503c96c31SRobert Watson static void
288603c96c31SRobert Watson db_print_indent(int indent)
288703c96c31SRobert Watson {
288803c96c31SRobert Watson 	int i;
288903c96c31SRobert Watson 
289003c96c31SRobert Watson 	for (i = 0; i < indent; i++)
289103c96c31SRobert Watson 		db_printf(" ");
289203c96c31SRobert Watson }
289303c96c31SRobert Watson 
289403c96c31SRobert Watson static void
289503c96c31SRobert Watson db_print_unpflags(int unp_flags)
289603c96c31SRobert Watson {
289703c96c31SRobert Watson 	int comma;
289803c96c31SRobert Watson 
289903c96c31SRobert Watson 	comma = 0;
290003c96c31SRobert Watson 	if (unp_flags & UNP_HAVEPC) {
290103c96c31SRobert Watson 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
290203c96c31SRobert Watson 		comma = 1;
290303c96c31SRobert Watson 	}
29042de07e40SConrad Meyer 	if (unp_flags & UNP_WANTCRED_ALWAYS) {
29052de07e40SConrad Meyer 		db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
29062de07e40SConrad Meyer 		comma = 1;
29072de07e40SConrad Meyer 	}
29082de07e40SConrad Meyer 	if (unp_flags & UNP_WANTCRED_ONESHOT) {
29092de07e40SConrad Meyer 		db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
291003c96c31SRobert Watson 		comma = 1;
291103c96c31SRobert Watson 	}
291203c96c31SRobert Watson 	if (unp_flags & UNP_CONNWAIT) {
291303c96c31SRobert Watson 		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
291403c96c31SRobert Watson 		comma = 1;
291503c96c31SRobert Watson 	}
291603c96c31SRobert Watson 	if (unp_flags & UNP_CONNECTING) {
291703c96c31SRobert Watson 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
291803c96c31SRobert Watson 		comma = 1;
291903c96c31SRobert Watson 	}
292003c96c31SRobert Watson 	if (unp_flags & UNP_BINDING) {
292103c96c31SRobert Watson 		db_printf("%sUNP_BINDING", comma ? ", " : "");
292203c96c31SRobert Watson 		comma = 1;
292303c96c31SRobert Watson 	}
292403c96c31SRobert Watson }
292503c96c31SRobert Watson 
292603c96c31SRobert Watson static void
292703c96c31SRobert Watson db_print_xucred(int indent, struct xucred *xu)
292803c96c31SRobert Watson {
292903c96c31SRobert Watson 	int comma, i;
293003c96c31SRobert Watson 
293103c96c31SRobert Watson 	db_print_indent(indent);
2932c5afec6eSDmitry Chagin 	db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
2933c5afec6eSDmitry Chagin 	    xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
293403c96c31SRobert Watson 	db_print_indent(indent);
293503c96c31SRobert Watson 	db_printf("cr_groups: ");
293603c96c31SRobert Watson 	comma = 0;
293703c96c31SRobert Watson 	for (i = 0; i < xu->cr_ngroups; i++) {
293803c96c31SRobert Watson 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
293903c96c31SRobert Watson 		comma = 1;
294003c96c31SRobert Watson 	}
294103c96c31SRobert Watson 	db_printf("\n");
294203c96c31SRobert Watson }
294303c96c31SRobert Watson 
294403c96c31SRobert Watson static void
294503c96c31SRobert Watson db_print_unprefs(int indent, struct unp_head *uh)
294603c96c31SRobert Watson {
294703c96c31SRobert Watson 	struct unpcb *unp;
294803c96c31SRobert Watson 	int counter;
294903c96c31SRobert Watson 
295003c96c31SRobert Watson 	counter = 0;
295103c96c31SRobert Watson 	LIST_FOREACH(unp, uh, unp_reflink) {
295203c96c31SRobert Watson 		if (counter % 4 == 0)
295303c96c31SRobert Watson 			db_print_indent(indent);
295403c96c31SRobert Watson 		db_printf("%p  ", unp);
295503c96c31SRobert Watson 		if (counter % 4 == 3)
295603c96c31SRobert Watson 			db_printf("\n");
295703c96c31SRobert Watson 		counter++;
295803c96c31SRobert Watson 	}
295903c96c31SRobert Watson 	if (counter != 0 && counter % 4 != 0)
296003c96c31SRobert Watson 		db_printf("\n");
296103c96c31SRobert Watson }
296203c96c31SRobert Watson 
296303c96c31SRobert Watson DB_SHOW_COMMAND(unpcb, db_show_unpcb)
296403c96c31SRobert Watson {
296503c96c31SRobert Watson 	struct unpcb *unp;
296603c96c31SRobert Watson 
296703c96c31SRobert Watson         if (!have_addr) {
296803c96c31SRobert Watson                 db_printf("usage: show unpcb <addr>\n");
296903c96c31SRobert Watson                 return;
297003c96c31SRobert Watson         }
297103c96c31SRobert Watson         unp = (struct unpcb *)addr;
297203c96c31SRobert Watson 
297303c96c31SRobert Watson 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
297403c96c31SRobert Watson 	    unp->unp_vnode);
297503c96c31SRobert Watson 
2976fc8fdae0SMatthew D Fleming 	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
297703c96c31SRobert Watson 	    unp->unp_conn);
297803c96c31SRobert Watson 
297903c96c31SRobert Watson 	db_printf("unp_refs:\n");
298003c96c31SRobert Watson 	db_print_unprefs(2, &unp->unp_refs);
298103c96c31SRobert Watson 
298203c96c31SRobert Watson 	/* XXXRW: Would be nice to print the full address, if any. */
298303c96c31SRobert Watson 	db_printf("unp_addr: %p\n", unp->unp_addr);
298403c96c31SRobert Watson 
2985c2090e73SAlan Somers 	db_printf("unp_gencnt: %llu\n",
298603c96c31SRobert Watson 	    (unsigned long long)unp->unp_gencnt);
298703c96c31SRobert Watson 
298803c96c31SRobert Watson 	db_printf("unp_flags: %x (", unp->unp_flags);
298903c96c31SRobert Watson 	db_print_unpflags(unp->unp_flags);
299003c96c31SRobert Watson 	db_printf(")\n");
299103c96c31SRobert Watson 
299203c96c31SRobert Watson 	db_printf("unp_peercred:\n");
299303c96c31SRobert Watson 	db_print_xucred(2, &unp->unp_peercred);
299403c96c31SRobert Watson 
299503c96c31SRobert Watson 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
299603c96c31SRobert Watson }
299703c96c31SRobert Watson #endif
2998