uipc_usrreq.c revision 269490
1118611Snjl/*-
2118611Snjl * Copyright (c) 1982, 1986, 1989, 1991, 1993
3118611Snjl *	The Regents of the University of California.
4118611Snjl * Copyright (c) 2004-2009 Robert N. M. Watson
5118611Snjl * All rights reserved.
6118611Snjl *
7217365Sjkim * Redistribution and use in source and binary forms, with or without
8229989Sjkim * modification, are permitted provided that the following conditions
9118611Snjl * are met:
10118611Snjl * 1. Redistributions of source code must retain the above copyright
11217365Sjkim *    notice, this list of conditions and the following disclaimer.
12217365Sjkim * 2. Redistributions in binary form must reproduce the above copyright
13217365Sjkim *    notice, this list of conditions and the following disclaimer in the
14217365Sjkim *    documentation and/or other materials provided with the distribution.
15217365Sjkim * 4. Neither the name of the University nor the names of its contributors
16217365Sjkim *    may be used to endorse or promote products derived from this software
17217365Sjkim *    without specific prior written permission.
18217365Sjkim *
19217365Sjkim * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20217365Sjkim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21217365Sjkim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22217365Sjkim * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23217365Sjkim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24217365Sjkim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25118611Snjl * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26217365Sjkim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27217365Sjkim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28217365Sjkim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29118611Snjl * SUCH DAMAGE.
30217365Sjkim *
31217365Sjkim *	From: @(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
32217365Sjkim */
33217365Sjkim
34217365Sjkim/*
35217365Sjkim * UNIX Domain (Local) Sockets
36217365Sjkim *
37217365Sjkim * This is an implementation of UNIX (local) domain sockets.  Each socket has
38217365Sjkim * an associated struct unpcb (UNIX protocol control block).  Stream sockets
39217365Sjkim * may be connected to 0 or 1 other socket.  Datagram sockets may be
40217365Sjkim * connected to 0, 1, or many other sockets.  Sockets may be created and
41217365Sjkim * connected in pairs (socketpair(2)), or bound/connected to using the file
42217365Sjkim * system name space.  For most purposes, only the receive socket buffer is
43118611Snjl * used, as sending on one socket delivers directly to the receive socket
44217365Sjkim * buffer of a second socket.
45217365Sjkim *
46118611Snjl * The implementation is substantially complicated by the fact that
47151937Sjkim * "ancillary data", such as file descriptors or credentials, may be passed
48213806Sjkim * across UNIX domain sockets.  The potential for passing UNIX domain sockets
49118611Snjl * over other UNIX domain sockets requires the implementation of a simple
50118611Snjl * garbage collector to find and tear down cycles of disconnected sockets.
51118611Snjl *
52118611Snjl * TODO:
53243347Sjkim *	RDM
54243347Sjkim *	rethink name space problems
55243347Sjkim *	need a proper out-of-band
56243347Sjkim */
57243347Sjkim
58243347Sjkim#include <sys/cdefs.h>
59243347Sjkim__FBSDID("$FreeBSD: stable/10/sys/kern/uipc_usrreq.c 269490 2014-08-03 22:59:47Z peter $");
60243347Sjkim
61243347Sjkim#include "opt_ddb.h"
62151937Sjkim
63118611Snjl#include <sys/param.h>
64151937Sjkim#include <sys/capability.h>
65151937Sjkim#include <sys/domain.h>
66151937Sjkim#include <sys/fcntl.h>
67151937Sjkim#include <sys/malloc.h>		/* XXX must be before <sys/file.h> */
68212761Sjkim#include <sys/eventhandler.h>
69193529Sjkim#include <sys/file.h>
70235945Sjkim#include <sys/filedesc.h>
71193529Sjkim#include <sys/kernel.h>
72151937Sjkim#include <sys/lock.h>
73212761Sjkim#include <sys/mbuf.h>
74193529Sjkim#include <sys/mount.h>
75235945Sjkim#include <sys/mutex.h>
76193529Sjkim#include <sys/namei.h>
77193529Sjkim#include <sys/proc.h>
78237412Sjkim#include <sys/protosw.h>
79237412Sjkim#include <sys/queue.h>
80237412Sjkim#include <sys/resourcevar.h>
81193529Sjkim#include <sys/rwlock.h>
82237412Sjkim#include <sys/socket.h>
83118611Snjl#include <sys/socketvar.h>
84118611Snjl#include <sys/signalvar.h>
85118611Snjl#include <sys/stat.h>
86118611Snjl#include <sys/sx.h>
87118611Snjl#include <sys/sysctl.h>
88118611Snjl#include <sys/systm.h>
89118611Snjl#include <sys/taskqueue.h>
90118611Snjl#include <sys/un.h>
91118611Snjl#include <sys/unpcb.h>
92118611Snjl#include <sys/vnode.h>
93118611Snjl
94118611Snjl#include <net/vnet.h>
95118611Snjl
96118611Snjl#ifdef DDB
97118611Snjl#include <ddb/ddb.h>
98118611Snjl#endif
99118611Snjl
100213806Sjkim#include <security/mac/mac_framework.h>
101118611Snjl
102118611Snjl#include <vm/uma.h>
103151937Sjkim
104151937SjkimMALLOC_DECLARE(M_FILECAPS);
105118611Snjl
106118611Snjl/*
107118611Snjl * Locking key:
108118611Snjl * (l)	Locked using list lock
109118611Snjl * (g)	Locked using linkage lock
110118611Snjl */
111118611Snjl
112118611Snjlstatic uma_zone_t	unp_zone;
113118611Snjlstatic unp_gen_t	unp_gencnt;	/* (l) */
114118611Snjlstatic u_int		unp_count;	/* (l) Count of local sockets. */
115118611Snjlstatic ino_t		unp_ino;	/* Prototype for fake inode numbers. */
116118611Snjlstatic int		unp_rights;	/* (g) File descriptors in flight. */
117118611Snjlstatic struct unp_head	unp_shead;	/* (l) List of stream sockets. */
118118611Snjlstatic struct unp_head	unp_dhead;	/* (l) List of datagram sockets. */
119207344Sjkimstatic struct unp_head	unp_sphead;	/* (l) List of seqpacket sockets. */
120207344Sjkim
121118611Snjlstruct unp_defer {
122118611Snjl	SLIST_ENTRY(unp_defer) ud_link;
123118611Snjl	struct file *ud_fp;
124118611Snjl};
125118611Snjlstatic SLIST_HEAD(, unp_defer) unp_defers;
126118611Snjlstatic int unp_defers_count;
127118611Snjl
128118611Snjlstatic const struct sockaddr	sun_noname = { sizeof(sun_noname), AF_LOCAL };
129118611Snjl
130118611Snjl/*
131118611Snjl * Garbage collection of cyclic file descriptor/socket references occurs
132118611Snjl * asynchronously in a taskqueue context in order to avoid recursion and
133118611Snjl * reentrance in the UNIX domain socket, file descriptor, and socket layer
134118611Snjl * code.  See unp_gc() for a full description.
135118611Snjl */
136118611Snjlstatic struct timeout_task unp_gc_task;
137118611Snjl
138151937Sjkim/*
139151937Sjkim * The close of unix domain sockets attached as SCM_RIGHTS is
140151937Sjkim * postponed to the taskqueue, to avoid arbitrary recursion depth.
141151937Sjkim * The attached sockets might have another sockets attached.
142213806Sjkim */
143151937Sjkimstatic struct task	unp_defer_task;
144151937Sjkim
145151937Sjkim/*
146213806Sjkim * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
147151937Sjkim * stream sockets, although the total for sender and receiver is actually
148151937Sjkim * only PIPSIZ.
149213806Sjkim *
150151937Sjkim * Datagram sockets really use the sendspace as the maximum datagram size,
151213806Sjkim * and don't really want to reserve the sendspace.  Their recvspace should be
152213806Sjkim * large enough for at least one max-size datagram plus address.
153118611Snjl */
154118611Snjl#ifndef PIPSIZ
155118611Snjl#define	PIPSIZ	8192
156118611Snjl#endif
157118611Snjlstatic u_long	unpst_sendspace = PIPSIZ;
158118611Snjlstatic u_long	unpst_recvspace = PIPSIZ;
159118611Snjlstatic u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
160118611Snjlstatic u_long	unpdg_recvspace = 4*1024;
161118611Snjlstatic u_long	unpsp_sendspace = PIPSIZ;	/* really max datagram size */
162118611Snjlstatic u_long	unpsp_recvspace = PIPSIZ;
163118611Snjl
164118611Snjlstatic SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
165118611Snjlstatic SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0,
166118611Snjl    "SOCK_STREAM");
167118611Snjlstatic SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
168118611Snjlstatic SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, CTLFLAG_RW, 0,
169118611Snjl    "SOCK_SEQPACKET");
170118611Snjl
171118611SnjlSYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
172118611Snjl	   &unpst_sendspace, 0, "Default stream send space.");
173118611SnjlSYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
174118611Snjl	   &unpst_recvspace, 0, "Default stream receive space.");
175118611SnjlSYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
176118611Snjl	   &unpdg_sendspace, 0, "Default datagram send space.");
177151937SjkimSYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
178151937Sjkim	   &unpdg_recvspace, 0, "Default datagram receive space.");
179118611SnjlSYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
180118611Snjl	   &unpsp_sendspace, 0, "Default seqpacket send space.");
181118611SnjlSYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
182118611Snjl	   &unpsp_recvspace, 0, "Default seqpacket receive space.");
183118611SnjlSYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
184118611Snjl    "File descriptors in flight.");
185118611SnjlSYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
186118611Snjl    &unp_defers_count, 0,
187118611Snjl    "File descriptors deferred to taskqueue for close.");
188118611Snjl
189118611Snjl/*
190118611Snjl * Locking and synchronization:
191118611Snjl *
192118611Snjl * Three types of locks exit in the local domain socket implementation: a
193207344Sjkim * global list mutex, a global linkage rwlock, and per-unpcb mutexes.  Of the
194207344Sjkim * global locks, the list lock protects the socket count, global generation
195118611Snjl * number, and stream/datagram global lists.  The linkage lock protects the
196118611Snjl * interconnection of unpcbs, the v_socket and unp_vnode pointers, and can be
197118611Snjl * held exclusively over the acquisition of multiple unpcb locks to prevent
198118611Snjl * deadlock.
199118611Snjl *
200118611Snjl * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
201118611Snjl * allocated in pru_attach() and freed in pru_detach().  The validity of that
202118611Snjl * pointer is an invariant, so no lock is required to dereference the so_pcb
203118611Snjl * pointer if a valid socket reference is held by the caller.  In practice,
204118611Snjl * this is always true during operations performed on a socket.  Each unpcb
205118611Snjl * has a back-pointer to its socket, unp_socket, which will be stable under
206118611Snjl * the same circumstances.
207118611Snjl *
208118611Snjl * This pointer may only be safely dereferenced as long as a valid reference
209118611Snjl * to the unpcb is held.  Typically, this reference will be from the socket,
210118611Snjl * or from another unpcb when the referring unpcb's lock is held (in order
211118611Snjl * that the reference not be invalidated during use).  For example, to follow
212118611Snjl * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
213118611Snjl * as unp_socket remains valid as long as the reference to unp_conn is valid.
214118611Snjl *
215118611Snjl * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx.  Individual
216118611Snjl * atomic reads without the lock may be performed "lockless", but more
217118611Snjl * complex reads and read-modify-writes require the mutex to be held.  No
218118611Snjl * lock order is defined between unpcb locks -- multiple unpcb locks may be
219118611Snjl * acquired at the same time only when holding the linkage rwlock
220118611Snjl * exclusively, which prevents deadlocks.
221118611Snjl *
222118611Snjl * Blocking with UNIX domain sockets is a tricky issue: unlike most network
223118611Snjl * protocols, bind() is a non-atomic operation, and connect() requires
224118611Snjl * potential sleeping in the protocol, due to potentially waiting on local or
225118611Snjl * distributed file systems.  We try to separate "lookup" operations, which
226118611Snjl * may sleep, and the IPC operations themselves, which typically can occur
227118611Snjl * with relative atomicity as locks can be held over the entire operation.
228118611Snjl *
229118611Snjl * Another tricky issue is simultaneous multi-threaded or multi-process
230118611Snjl * access to a single UNIX domain socket.  These are handled by the flags
231118611Snjl * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
232118611Snjl * binding, both of which involve dropping UNIX domain socket locks in order
233118611Snjl * to perform namei() and other file system operations.
234118611Snjl */
235118611Snjlstatic struct rwlock	unp_link_rwlock;
236118611Snjlstatic struct mtx	unp_list_lock;
237118611Snjlstatic struct mtx	unp_defers_lock;
238118611Snjl
239118611Snjl#define	UNP_LINK_LOCK_INIT()		rw_init(&unp_link_rwlock,	\
240118611Snjl					    "unp_link_rwlock")
241118611Snjl
242118611Snjl#define	UNP_LINK_LOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
243118611Snjl					    RA_LOCKED)
244118611Snjl#define	UNP_LINK_UNLOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
245118611Snjl					    RA_UNLOCKED)
246118611Snjl
247118611Snjl#define	UNP_LINK_RLOCK()		rw_rlock(&unp_link_rwlock)
248151937Sjkim#define	UNP_LINK_RUNLOCK()		rw_runlock(&unp_link_rwlock)
249151937Sjkim#define	UNP_LINK_WLOCK()		rw_wlock(&unp_link_rwlock)
250151937Sjkim#define	UNP_LINK_WUNLOCK()		rw_wunlock(&unp_link_rwlock)
251118611Snjl#define	UNP_LINK_WLOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
252118611Snjl					    RA_WLOCKED)
253118611Snjl
254118611Snjl#define	UNP_LIST_LOCK_INIT()		mtx_init(&unp_list_lock,	\
255118611Snjl					    "unp_list_lock", NULL, MTX_DEF)
256118611Snjl#define	UNP_LIST_LOCK()			mtx_lock(&unp_list_lock)
257234623Sjkim#define	UNP_LIST_UNLOCK()		mtx_unlock(&unp_list_lock)
258118611Snjl
259118611Snjl#define	UNP_DEFERRED_LOCK_INIT()	mtx_init(&unp_defers_lock, \
260234623Sjkim					    "unp_defer", NULL, MTX_DEF)
261118611Snjl#define	UNP_DEFERRED_LOCK()		mtx_lock(&unp_defers_lock)
262118611Snjl#define	UNP_DEFERRED_UNLOCK()		mtx_unlock(&unp_defers_lock)
263118611Snjl
264118611Snjl#define UNP_PCB_LOCK_INIT(unp)		mtx_init(&(unp)->unp_mtx,	\
265118611Snjl					    "unp_mtx", "unp_mtx",	\
266167802Sjkim					    MTX_DUPOK|MTX_DEF|MTX_RECURSE)
267167802Sjkim#define	UNP_PCB_LOCK_DESTROY(unp)	mtx_destroy(&(unp)->unp_mtx)
268235945Sjkim#define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
269235945Sjkim#define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
270167802Sjkim#define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
271167802Sjkim
272167802Sjkimstatic int	uipc_connect2(struct socket *, struct socket *);
273167802Sjkimstatic int	uipc_ctloutput(struct socket *, struct sockopt *);
274167802Sjkimstatic int	unp_connect(struct socket *, struct sockaddr *,
275167802Sjkim		    struct thread *);
276167802Sjkimstatic int	unp_connectat(int, struct socket *, struct sockaddr *,
277212761Sjkim		    struct thread *);
278167802Sjkimstatic int	unp_connect2(struct socket *so, struct socket *so2, int);
279235945Sjkimstatic void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
280167802Sjkimstatic void	unp_dispose(struct mbuf *);
281167802Sjkimstatic void	unp_shutdown(struct unpcb *);
282167802Sjkimstatic void	unp_drop(struct unpcb *, int);
283167802Sjkimstatic void	unp_gc(__unused void *, int);
284167802Sjkimstatic void	unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
285167802Sjkimstatic void	unp_discard(struct file *);
286243347Sjkimstatic void	unp_freerights(struct filedescent **, int);
287167802Sjkimstatic void	unp_init(void);
288167802Sjkimstatic int	unp_internalize(struct mbuf **, struct thread *);
289167802Sjkimstatic void	unp_internalize_fp(struct file *);
290167802Sjkimstatic int	unp_externalize(struct mbuf *, struct mbuf **, int);
291167802Sjkimstatic int	unp_externalize_fp(struct file *);
292167802Sjkimstatic struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *);
293167802Sjkimstatic void	unp_process_defers(void * __unused, int);
294167802Sjkim
295167802Sjkim/*
296167802Sjkim * Definitions of protocols supported in the LOCAL domain.
297167802Sjkim */
298167802Sjkimstatic struct domain localdomain;
299167802Sjkimstatic struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
300167802Sjkimstatic struct pr_usrreqs uipc_usrreqs_seqpacket;
301167802Sjkimstatic struct protosw localsw[] = {
302167802Sjkim{
303167802Sjkim	.pr_type =		SOCK_STREAM,
304167802Sjkim	.pr_domain =		&localdomain,
305167802Sjkim	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
306167802Sjkim	.pr_ctloutput =		&uipc_ctloutput,
307167802Sjkim	.pr_usrreqs =		&uipc_usrreqs_stream
308167802Sjkim},
309167802Sjkim{
310167802Sjkim	.pr_type =		SOCK_DGRAM,
311167802Sjkim	.pr_domain =		&localdomain,
312167802Sjkim	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS,
313167802Sjkim	.pr_ctloutput =		&uipc_ctloutput,
314167802Sjkim	.pr_usrreqs =		&uipc_usrreqs_dgram
315167802Sjkim},
316167802Sjkim{
317167802Sjkim	.pr_type =		SOCK_SEQPACKET,
318167802Sjkim	.pr_domain =		&localdomain,
319167802Sjkim
320167802Sjkim	/*
321212761Sjkim	 * XXXRW: For now, PR_ADDR because soreceive will bump into them
322167802Sjkim	 * due to our use of sbappendaddr.  A new sbappend variants is needed
323235945Sjkim	 * that supports both atomic record writes and control data.
324167802Sjkim	 */
325167802Sjkim	.pr_flags =		PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
326167802Sjkim				    PR_RIGHTS,
327167802Sjkim	.pr_ctloutput =		&uipc_ctloutput,
328167802Sjkim	.pr_usrreqs =		&uipc_usrreqs_seqpacket,
329243347Sjkim},
330167802Sjkim};
331167802Sjkim
332167802Sjkimstatic struct domain localdomain = {
333167802Sjkim	.dom_family =		AF_LOCAL,
334167802Sjkim	.dom_name =		"local",
335167802Sjkim	.dom_init =		unp_init,
336167802Sjkim	.dom_externalize =	unp_externalize,
337167802Sjkim	.dom_dispose =		unp_dispose,
338167802Sjkim	.dom_protosw =		localsw,
339167802Sjkim	.dom_protoswNPROTOSW =	&localsw[sizeof(localsw)/sizeof(localsw[0])]
340167802Sjkim};
341167802SjkimDOMAIN_SET(local);
342167802Sjkim
343167802Sjkimstatic void
344167802Sjkimuipc_abort(struct socket *so)
345167802Sjkim{
346123315Snjl	struct unpcb *unp, *unp2;
347123315Snjl
348235945Sjkim	unp = sotounpcb(so);
349235945Sjkim	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
350235945Sjkim
351123315Snjl	UNP_LINK_WLOCK();
352151937Sjkim	UNP_PCB_LOCK(unp);
353123315Snjl	unp2 = unp->unp_conn;
354167802Sjkim	if (unp2 != NULL) {
355167802Sjkim		UNP_PCB_LOCK(unp2);
356167802Sjkim		unp_drop(unp2, ECONNABORTED);
357167802Sjkim		UNP_PCB_UNLOCK(unp2);
358167802Sjkim	}
359167802Sjkim	UNP_PCB_UNLOCK(unp);
360123315Snjl	UNP_LINK_WUNLOCK();
361123315Snjl}
362123315Snjl
363209746Sjkimstatic int
364123315Snjluipc_accept(struct socket *so, struct sockaddr **nam)
365235945Sjkim{
366235945Sjkim	struct unpcb *unp, *unp2;
367235945Sjkim	const struct sockaddr *sa;
368123315Snjl
369123315Snjl	/*
370123315Snjl	 * Pass back name of connected socket, if it was bound and we are
371167802Sjkim	 * still connected (our peer may have closed already!).
372167802Sjkim	 */
373123315Snjl	unp = sotounpcb(so);
374123315Snjl	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
375167802Sjkim
376167802Sjkim	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
377167802Sjkim	UNP_LINK_RLOCK();
378123315Snjl	unp2 = unp->unp_conn;
379123315Snjl	if (unp2 != NULL && unp2->unp_addr != NULL) {
380243347Sjkim		UNP_PCB_LOCK(unp2);
381123315Snjl		sa = (struct sockaddr *) unp2->unp_addr;
382167802Sjkim		bcopy(sa, *nam, sa->sa_len);
383167802Sjkim		UNP_PCB_UNLOCK(unp2);
384167802Sjkim	} else {
385167802Sjkim		sa = &sun_noname;
386167802Sjkim		bcopy(sa, *nam, sa->sa_len);
387167802Sjkim	}
388167802Sjkim	UNP_LINK_RUNLOCK();
389167802Sjkim	return (0);
390235945Sjkim}
391167802Sjkim
392167802Sjkimstatic int
393167802Sjkimuipc_attach(struct socket *so, int proto, struct thread *td)
394167802Sjkim{
395235945Sjkim	u_long sendspace, recvspace;
396167802Sjkim	struct unpcb *unp;
397167802Sjkim	int error;
398167802Sjkim
399167802Sjkim	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
400167802Sjkim	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
401167802Sjkim		switch (so->so_type) {
402167802Sjkim		case SOCK_STREAM:
403167802Sjkim			sendspace = unpst_sendspace;
404167802Sjkim			recvspace = unpst_recvspace;
405167802Sjkim			break;
406167802Sjkim
407123315Snjl		case SOCK_DGRAM:
408123315Snjl			sendspace = unpdg_sendspace;
409193529Sjkim			recvspace = unpdg_recvspace;
410123315Snjl			break;
411235945Sjkim
412123315Snjl		case SOCK_SEQPACKET:
413151937Sjkim			sendspace = unpsp_sendspace;
414167802Sjkim			recvspace = unpsp_recvspace;
415167802Sjkim			break;
416123315Snjl
417167802Sjkim		default:
418123315Snjl			panic("uipc_attach");
419123315Snjl		}
420167802Sjkim		error = soreserve(so, sendspace, recvspace);
421167802Sjkim		if (error)
422167802Sjkim			return (error);
423167802Sjkim	}
424167802Sjkim	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
425167802Sjkim	if (unp == NULL)
426167802Sjkim		return (ENOBUFS);
427167802Sjkim	LIST_INIT(&unp->unp_refs);
428167802Sjkim	UNP_PCB_LOCK_INIT(unp);
429123315Snjl	unp->unp_socket = so;
430123315Snjl	so->so_pcb = unp;
431151937Sjkim	unp->unp_refcount = 1;
432151937Sjkim
433235945Sjkim	UNP_LIST_LOCK();
434151937Sjkim	unp->unp_gencnt = ++unp_gencnt;
435123315Snjl	unp_count++;
436123315Snjl	switch (so->so_type) {
437123315Snjl	case SOCK_STREAM:
438123315Snjl		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
439235945Sjkim		break;
440235945Sjkim
441235945Sjkim	case SOCK_DGRAM:
442235945Sjkim		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
443235945Sjkim		break;
444235945Sjkim
445235945Sjkim	case SOCK_SEQPACKET:
446235945Sjkim		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
447123315Snjl		break;
448123315Snjl
449123315Snjl	default:
450235945Sjkim		panic("uipc_attach");
451123315Snjl	}
452123315Snjl	UNP_LIST_UNLOCK();
453123315Snjl
454123315Snjl	return (0);
455123315Snjl}
456123315Snjl
457123315Snjlstatic int
458118611Snjluipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
459118611Snjl{
460118611Snjl	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
461118611Snjl	struct vattr vattr;
462118611Snjl	int error, namelen;
463118611Snjl	struct nameidata nd;
464118611Snjl	struct unpcb *unp;
465118611Snjl	struct vnode *vp;
466118611Snjl	struct mount *mp;
467118611Snjl	cap_rights_t rights;
468118611Snjl	char *buf;
469151937Sjkim
470151937Sjkim	if (nam->sa_family != AF_UNIX)
471118611Snjl		return (EAFNOSUPPORT);
472118611Snjl
473151937Sjkim	unp = sotounpcb(so);
474151937Sjkim	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
475118611Snjl
476118611Snjl	if (soun->sun_len > sizeof(struct sockaddr_un))
477151937Sjkim		return (EINVAL);
478151937Sjkim	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
479151937Sjkim	if (namelen <= 0)
480118611Snjl		return (EINVAL);
481233250Sjkim
482234623Sjkim	/*
483233250Sjkim	 * We don't allow simultaneous bind() calls on a single UNIX domain
484234623Sjkim	 * socket, so flag in-progress operations, and return an error if an
485234623Sjkim	 * operation is already in progress.
486234623Sjkim	 *
487234623Sjkim	 * Historically, we have not allowed a socket to be rebound, so this
488234623Sjkim	 * also returns an error.  Not allowing re-binding simplifies the
489234623Sjkim	 * implementation and avoids a great many possible failure modes.
490234623Sjkim	 */
491241973Sjkim	UNP_PCB_LOCK(unp);
492234623Sjkim	if (unp->unp_vnode != NULL) {
493233250Sjkim		UNP_PCB_UNLOCK(unp);
494234623Sjkim		return (EINVAL);
495233250Sjkim	}
496118611Snjl	if (unp->unp_flags & UNP_BINDING) {
497118611Snjl		UNP_PCB_UNLOCK(unp);
498151937Sjkim		return (EALREADY);
499118611Snjl	}
500151937Sjkim	unp->unp_flags |= UNP_BINDING;
501118611Snjl	UNP_PCB_UNLOCK(unp);
502118611Snjl
503118611Snjl	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
504151937Sjkim	bcopy(soun->sun_path, buf, namelen);
505118611Snjl	buf[namelen] = 0;
506118611Snjl
507118611Snjlrestart:
508118611Snjl	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME,
509118611Snjl	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
510118611Snjl/* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
511234623Sjkim	error = namei(&nd);
512234623Sjkim	if (error)
513234623Sjkim		goto error;
514234623Sjkim	vp = nd.ni_vp;
515234623Sjkim	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
516234623Sjkim		NDFREE(&nd, NDF_ONLY_PNBUF);
517234623Sjkim		if (nd.ni_dvp == vp)
518234623Sjkim			vrele(nd.ni_dvp);
519234623Sjkim		else
520234623Sjkim			vput(nd.ni_dvp);
521234623Sjkim		if (vp != NULL) {
522233250Sjkim			vrele(vp);
523118611Snjl			error = EADDRINUSE;
524118611Snjl			goto error;
525167802Sjkim		}
526167802Sjkim		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
527167802Sjkim		if (error)
528167802Sjkim			goto error;
529118611Snjl		goto restart;
530151937Sjkim	}
531118611Snjl	VATTR_NULL(&vattr);
532118611Snjl	vattr.va_type = VSOCK;
533118611Snjl	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
534151937Sjkim#ifdef MAC
535118611Snjl	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
536151937Sjkim	    &vattr);
537151937Sjkim#endif
538151937Sjkim	if (error == 0)
539118611Snjl		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
540118611Snjl	NDFREE(&nd, NDF_ONLY_PNBUF);
541118611Snjl	vput(nd.ni_dvp);
542151937Sjkim	if (error) {
543118611Snjl		vn_finished_write(mp);
544151937Sjkim		goto error;
545151937Sjkim	}
546151937Sjkim	vp = nd.ni_vp;
547118611Snjl	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
548118611Snjl	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
549118611Snjl
550118611Snjl	UNP_LINK_WLOCK();
551118611Snjl	UNP_PCB_LOCK(unp);
552118611Snjl	VOP_UNP_BIND(vp, unp->unp_socket);
553151937Sjkim	unp->unp_vnode = vp;
554118611Snjl	unp->unp_addr = soun;
555233250Sjkim	unp->unp_flags &= ~UNP_BINDING;
556118611Snjl	UNP_PCB_UNLOCK(unp);
557118611Snjl	UNP_LINK_WUNLOCK();
558118611Snjl	VOP_UNLOCK(vp, 0);
559241973Sjkim	vn_finished_write(mp);
560118611Snjl	free(buf, M_TEMP);
561118611Snjl	return (0);
562118611Snjl
563118611Snjlerror:
564151937Sjkim	UNP_PCB_LOCK(unp);
565151937Sjkim	unp->unp_flags &= ~UNP_BINDING;
566151937Sjkim	UNP_PCB_UNLOCK(unp);
567151937Sjkim	free(buf, M_TEMP);
568151937Sjkim	return (error);
569151937Sjkim}
570118611Snjl
571151937Sjkimstatic int
572151937Sjkimuipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
573151937Sjkim{
574151937Sjkim
575151937Sjkim	return (uipc_bindat(AT_FDCWD, so, nam, td));
576151937Sjkim}
577151937Sjkim
578151937Sjkimstatic int
579151937Sjkimuipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
580118611Snjl{
581118611Snjl	int error;
582151937Sjkim
583118611Snjl	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
584151937Sjkim	UNP_LINK_WLOCK();
585151937Sjkim	error = unp_connect(so, nam, td);
586151937Sjkim	UNP_LINK_WUNLOCK();
587118611Snjl	return (error);
588118611Snjl}
589118611Snjl
590234623Sjkimstatic int
591234623Sjkimuipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
592118611Snjl    struct thread *td)
593118611Snjl{
594234623Sjkim	int error;
595118611Snjl
596234623Sjkim	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
597234623Sjkim	UNP_LINK_WLOCK();
598118611Snjl	error = unp_connectat(fd, so, nam, td);
599233250Sjkim	UNP_LINK_WUNLOCK();
600241973Sjkim	return (error);
601118611Snjl}
602118611Snjl
603118611Snjlstatic void
604118611Snjluipc_close(struct socket *so)
605118611Snjl{
606118611Snjl	struct unpcb *unp, *unp2;
607118611Snjl
608118611Snjl	unp = sotounpcb(so);
609151937Sjkim	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
610118611Snjl
611151937Sjkim	UNP_LINK_WLOCK();
612118611Snjl	UNP_PCB_LOCK(unp);
613118611Snjl	unp2 = unp->unp_conn;
614233250Sjkim	if (unp2 != NULL) {
615118611Snjl		UNP_PCB_LOCK(unp2);
616118611Snjl		unp_disconnect(unp, unp2);
617167802Sjkim		UNP_PCB_UNLOCK(unp2);
618118611Snjl	}
619151937Sjkim	UNP_PCB_UNLOCK(unp);
620118611Snjl	UNP_LINK_WUNLOCK();
621118611Snjl}
622118611Snjl
623233250Sjkimstatic int
624118611Snjluipc_connect2(struct socket *so1, struct socket *so2)
625118611Snjl{
626167802Sjkim	struct unpcb *unp, *unp2;
627167802Sjkim	int error;
628167802Sjkim
629167802Sjkim	UNP_LINK_WLOCK();
630167802Sjkim	unp = so1->so_pcb;
631118611Snjl	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
632241973Sjkim	UNP_PCB_LOCK(unp);
633118611Snjl	unp2 = so2->so_pcb;
634118611Snjl	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
635118611Snjl	UNP_PCB_LOCK(unp2);
636118611Snjl	error = unp_connect2(so1, so2, PRU_CONNECT2);
637151937Sjkim	UNP_PCB_UNLOCK(unp2);
638118611Snjl	UNP_PCB_UNLOCK(unp);
639118611Snjl	UNP_LINK_WUNLOCK();
640118611Snjl	return (error);
641151937Sjkim}
642151937Sjkim
643151937Sjkimstatic void
644151937Sjkimuipc_detach(struct socket *so)
645118611Snjl{
646118611Snjl	struct unpcb *unp, *unp2;
647118611Snjl	struct sockaddr_un *saved_unp_addr;
648151937Sjkim	struct vnode *vp;
649151937Sjkim	int freeunp, local_unp_rights;
650218590Sjkim
651218590Sjkim	unp = sotounpcb(so);
652151937Sjkim	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
653118611Snjl
654118611Snjl	UNP_LINK_WLOCK();
655118611Snjl	UNP_LIST_LOCK();
656151937Sjkim	UNP_PCB_LOCK(unp);
657151937Sjkim	LIST_REMOVE(unp, unp_link);
658218590Sjkim	unp->unp_gencnt = ++unp_gencnt;
659218590Sjkim	--unp_count;
660151937Sjkim	UNP_LIST_UNLOCK();
661118611Snjl
662118611Snjl	/*
663118611Snjl	 * XXXRW: Should assert vp->v_socket == so.
664151937Sjkim	 */
665151937Sjkim	if ((vp = unp->unp_vnode) != NULL) {
666218590Sjkim		VOP_UNP_DETACH(vp);
667151937Sjkim		unp->unp_vnode = NULL;
668218590Sjkim	}
669151937Sjkim	unp2 = unp->unp_conn;
670118611Snjl	if (unp2 != NULL) {
671118611Snjl		UNP_PCB_LOCK(unp2);
672118611Snjl		unp_disconnect(unp, unp2);
673151937Sjkim		UNP_PCB_UNLOCK(unp2);
674118611Snjl	}
675151937Sjkim
676151937Sjkim	/*
677151937Sjkim	 * We hold the linkage lock exclusively, so it's OK to acquire
678151937Sjkim	 * multiple pcb locks at a time.
679151937Sjkim	 */
680118611Snjl	while (!LIST_EMPTY(&unp->unp_refs)) {
681118611Snjl		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
682118611Snjl
683151937Sjkim		UNP_PCB_LOCK(ref);
684118611Snjl		unp_drop(ref, ECONNRESET);
685151937Sjkim		UNP_PCB_UNLOCK(ref);
686118611Snjl	}
687151937Sjkim	local_unp_rights = unp_rights;
688118611Snjl	UNP_LINK_WUNLOCK();
689151937Sjkim	unp->unp_socket->so_pcb = NULL;
690118611Snjl	saved_unp_addr = unp->unp_addr;
691151937Sjkim	unp->unp_addr = NULL;
692118611Snjl	unp->unp_refcount--;
693241973Sjkim	freeunp = (unp->unp_refcount == 0);
694233250Sjkim	if (saved_unp_addr != NULL)
695233250Sjkim		free(saved_unp_addr, M_SONAME);
696233250Sjkim	if (freeunp) {
697233250Sjkim		UNP_PCB_LOCK_DESTROY(unp);
698233250Sjkim		uma_zfree(unp_zone, unp);
699118611Snjl	} else
700118611Snjl		UNP_PCB_UNLOCK(unp);
701151937Sjkim	if (vp)
702151937Sjkim		vrele(vp);
703151937Sjkim	if (local_unp_rights)
704151937Sjkim		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
705151937Sjkim}
706151937Sjkim
707151937Sjkimstatic int
708151937Sjkimuipc_disconnect(struct socket *so)
709151937Sjkim{
710151937Sjkim	struct unpcb *unp, *unp2;
711151937Sjkim
712151937Sjkim	unp = sotounpcb(so);
713151937Sjkim	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
714118611Snjl
715151937Sjkim	UNP_LINK_WLOCK();
716151937Sjkim	UNP_PCB_LOCK(unp);
717118611Snjl	unp2 = unp->unp_conn;
718118611Snjl	if (unp2 != NULL) {
719118611Snjl		UNP_PCB_LOCK(unp2);
720118611Snjl		unp_disconnect(unp, unp2);
721118611Snjl		UNP_PCB_UNLOCK(unp2);
722118611Snjl	}
723118611Snjl	UNP_PCB_UNLOCK(unp);
724118611Snjl	UNP_LINK_WUNLOCK();
725118611Snjl	return (0);
726151937Sjkim}
727118611Snjl
728118611Snjlstatic int
729118611Snjluipc_listen(struct socket *so, int backlog, struct thread *td)
730118611Snjl{
731118611Snjl	struct unpcb *unp;
732237412Sjkim	int error;
733151937Sjkim
734237412Sjkim	unp = sotounpcb(so);
735151937Sjkim	KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
736151937Sjkim
737151937Sjkim	UNP_PCB_LOCK(unp);
738237412Sjkim	if (unp->unp_vnode == NULL) {
739151937Sjkim		UNP_PCB_UNLOCK(unp);
740151937Sjkim		return (EINVAL);
741151937Sjkim	}
742151937Sjkim
743237412Sjkim	SOCK_LOCK(so);
744237412Sjkim	error = solisten_proto_check(so);
745151937Sjkim	if (error == 0) {
746237412Sjkim		cru2x(td->td_ucred, &unp->unp_peercred);
747151937Sjkim		unp->unp_flags |= UNP_HAVEPCCACHED;
748151937Sjkim		solisten_proto(so, backlog);
749151937Sjkim	}
750237412Sjkim	SOCK_UNLOCK(so);
751151937Sjkim	UNP_PCB_UNLOCK(unp);
752237412Sjkim	return (error);
753237412Sjkim}
754237412Sjkim
755237412Sjkimstatic int
756237412Sjkimuipc_peeraddr(struct socket *so, struct sockaddr **nam)
757151937Sjkim{
758237412Sjkim	struct unpcb *unp, *unp2;
759151937Sjkim	const struct sockaddr *sa;
760151937Sjkim
761237412Sjkim	unp = sotounpcb(so);
762237412Sjkim	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
763237412Sjkim
764237412Sjkim	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
765237412Sjkim	UNP_LINK_RLOCK();
766151937Sjkim	/*
767237412Sjkim	 * XXX: It seems that this test always fails even when connection is
768151937Sjkim	 * established.  So, this else clause is added as workaround to
769237412Sjkim	 * return PF_LOCAL sockaddr.
770237412Sjkim	 */
771151937Sjkim	unp2 = unp->unp_conn;
772237412Sjkim	if (unp2 != NULL) {
773151937Sjkim		UNP_PCB_LOCK(unp2);
774237412Sjkim		if (unp2->unp_addr != NULL)
775237412Sjkim			sa = (struct sockaddr *) unp2->unp_addr;
776237412Sjkim		else
777237412Sjkim			sa = &sun_noname;
778237412Sjkim		bcopy(sa, *nam, sa->sa_len);
779237412Sjkim		UNP_PCB_UNLOCK(unp2);
780237412Sjkim	} else {
781237412Sjkim		sa = &sun_noname;
782237412Sjkim		bcopy(sa, *nam, sa->sa_len);
783237412Sjkim	}
784237412Sjkim	UNP_LINK_RUNLOCK();
785237412Sjkim	return (0);
786237412Sjkim}
787237412Sjkim
788237412Sjkimstatic int
789237412Sjkimuipc_rcvd(struct socket *so, int flags)
790151937Sjkim{
791151937Sjkim	struct unpcb *unp, *unp2;
792151937Sjkim	struct socket *so2;
793151937Sjkim	u_int mbcnt, sbcc;
794151937Sjkim
795151937Sjkim	unp = sotounpcb(so);
796118611Snjl	KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
797118611Snjl
798118611Snjl	if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
799118611Snjl		panic("uipc_rcvd socktype %d", so->so_type);
800118611Snjl
801118611Snjl	/*
802118611Snjl	 * Adjust backpressure on sender and wakeup any waiting to write.
803118611Snjl	 *
804118611Snjl	 * The unp lock is acquired to maintain the validity of the unp_conn
805118611Snjl	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
806118611Snjl	 * static as long as we don't permit unp2 to disconnect from unp,
807151937Sjkim	 * which is prevented by the lock on unp.  We cache values from
808151937Sjkim	 * so_rcv to avoid holding the so_rcv lock over the entire
809118611Snjl	 * transaction on the remote so_snd.
810118611Snjl	 */
811240716Sjkim	SOCKBUF_LOCK(&so->so_rcv);
812118611Snjl	mbcnt = so->so_rcv.sb_mbcnt;
813118611Snjl	sbcc = so->so_rcv.sb_cc;
814234623Sjkim	SOCKBUF_UNLOCK(&so->so_rcv);
815118611Snjl	/*
816118611Snjl	 * There is a benign race condition at this point.  If we're planning to
817234623Sjkim	 * clear SB_STOP, but uipc_send is called on the connected socket at
818118611Snjl	 * this instant, it might add data to the sockbuf and set SB_STOP.  Then
819234623Sjkim	 * we would erroneously clear SB_STOP below, even though the sockbuf is
820118611Snjl	 * full.  The race is benign because the only ill effect is to allow the
821118611Snjl	 * sockbuf to exceed its size limit, and the size limits are not
822237412Sjkim	 * strictly guaranteed anyway.
823118611Snjl	 */
824237412Sjkim	UNP_PCB_LOCK(unp);
825237412Sjkim	unp2 = unp->unp_conn;
826118611Snjl	if (unp2 == NULL) {
827118611Snjl		UNP_PCB_UNLOCK(unp);
828118611Snjl		return (0);
829118611Snjl	}
830118611Snjl	so2 = unp2->unp_socket;
831118611Snjl	SOCKBUF_LOCK(&so2->so_snd);
832118611Snjl	if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
833118611Snjl		so2->so_snd.sb_flags &= ~SB_STOP;
834118611Snjl	sowwakeup_locked(so2);
835118611Snjl	UNP_PCB_UNLOCK(unp);
836118611Snjl	return (0);
837118611Snjl}
838118611Snjl
839118611Snjlstatic int
840118611Snjluipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
841209746Sjkim    struct mbuf *control, struct thread *td)
842209746Sjkim{
843209746Sjkim	struct unpcb *unp, *unp2;
844209746Sjkim	struct socket *so2;
845209746Sjkim	u_int mbcnt, sbcc;
846151937Sjkim	int error = 0;
847209746Sjkim
848209746Sjkim	unp = sotounpcb(so);
849209746Sjkim	KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
850209746Sjkim
851209746Sjkim	if (flags & PRUS_OOB) {
852209746Sjkim		error = EOPNOTSUPP;
853118611Snjl		goto release;
854118611Snjl	}
855118611Snjl	if (control != NULL && (error = unp_internalize(&control, td)))
856118611Snjl		goto release;
857209746Sjkim	if ((nam != NULL) || (flags & PRUS_EOF))
858209746Sjkim		UNP_LINK_WLOCK();
859118611Snjl	else
860118611Snjl		UNP_LINK_RLOCK();
861118611Snjl	switch (so->so_type) {
862199337Sjkim	case SOCK_DGRAM:
863240716Sjkim	{
864240716Sjkim		const struct sockaddr *from;
865240716Sjkim
866240716Sjkim		unp2 = unp->unp_conn;
867240716Sjkim		if (nam != NULL) {
868240716Sjkim			UNP_LINK_WLOCK_ASSERT();
869240716Sjkim			if (unp2 != NULL) {
870240716Sjkim				error = EISCONN;
871240716Sjkim				break;
872240716Sjkim			}
873199337Sjkim			error = unp_connect(so, nam, td);
874199337Sjkim			if (error)
875233250Sjkim				break;
876233250Sjkim			unp2 = unp->unp_conn;
877233250Sjkim		}
878199337Sjkim
879199337Sjkim		/*
880199337Sjkim		 * Because connect() and send() are non-atomic in a sendto()
881200553Sjkim		 * with a target address, it's possible that the socket will
882200553Sjkim		 * have disconnected before the send() can run.  In that case
883200553Sjkim		 * return the slightly counter-intuitive but otherwise
884240716Sjkim		 * correct error that the socket is not connected.
885200553Sjkim		 */
886240716Sjkim		if (unp2 == NULL) {
887200553Sjkim			error = ENOTCONN;
888200553Sjkim			break;
889233250Sjkim		}
890233250Sjkim		/* Lockless read. */
891234623Sjkim		if (unp2->unp_flags & UNP_WANTCRED)
892240716Sjkim			control = unp_addsockcred(td, control);
893233250Sjkim		UNP_PCB_LOCK(unp);
894240716Sjkim		if (unp->unp_addr != NULL)
895233250Sjkim			from = (struct sockaddr *)unp->unp_addr;
896233250Sjkim		else
897200553Sjkim			from = &sun_noname;
898200553Sjkim		so2 = unp2->unp_socket;
899209746Sjkim		SOCKBUF_LOCK(&so2->so_rcv);
900209746Sjkim		if (sbappendaddr_locked(&so2->so_rcv, from, m,
901200553Sjkim		    control)) {
902209746Sjkim			sorwakeup_locked(so2);
903209746Sjkim			m = NULL;
904209746Sjkim			control = NULL;
905209746Sjkim		} else {
906209746Sjkim			SOCKBUF_UNLOCK(&so2->so_rcv);
907209746Sjkim			error = ENOBUFS;
908209746Sjkim		}
909200553Sjkim		if (nam != NULL) {
910200553Sjkim			UNP_LINK_WLOCK_ASSERT();
911240716Sjkim			UNP_PCB_LOCK(unp2);
912200553Sjkim			unp_disconnect(unp, unp2);
913240716Sjkim			UNP_PCB_UNLOCK(unp2);
914200553Sjkim		}
915118611Snjl		UNP_PCB_UNLOCK(unp);
916		break;
917	}
918
919	case SOCK_SEQPACKET:
920	case SOCK_STREAM:
921		if ((so->so_state & SS_ISCONNECTED) == 0) {
922			if (nam != NULL) {
923				UNP_LINK_WLOCK_ASSERT();
924				error = unp_connect(so, nam, td);
925				if (error)
926					break;	/* XXX */
927			} else {
928				error = ENOTCONN;
929				break;
930			}
931		}
932
933		/* Lockless read. */
934		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
935			error = EPIPE;
936			break;
937		}
938
939		/*
940		 * Because connect() and send() are non-atomic in a sendto()
941		 * with a target address, it's possible that the socket will
942		 * have disconnected before the send() can run.  In that case
943		 * return the slightly counter-intuitive but otherwise
944		 * correct error that the socket is not connected.
945		 *
946		 * Locking here must be done carefully: the linkage lock
947		 * prevents interconnections between unpcbs from changing, so
948		 * we can traverse from unp to unp2 without acquiring unp's
949		 * lock.  Socket buffer locks follow unpcb locks, so we can
950		 * acquire both remote and lock socket buffer locks.
951		 */
952		unp2 = unp->unp_conn;
953		if (unp2 == NULL) {
954			error = ENOTCONN;
955			break;
956		}
957		so2 = unp2->unp_socket;
958		UNP_PCB_LOCK(unp2);
959		SOCKBUF_LOCK(&so2->so_rcv);
960		if (unp2->unp_flags & UNP_WANTCRED) {
961			/*
962			 * Credentials are passed only once on SOCK_STREAM
963			 * and SOCK_SEQPACKET.
964			 */
965			unp2->unp_flags &= ~UNP_WANTCRED;
966			control = unp_addsockcred(td, control);
967		}
968		/*
969		 * Send to paired receive port, and then reduce send buffer
970		 * hiwater marks to maintain backpressure.  Wake up readers.
971		 */
972		switch (so->so_type) {
973		case SOCK_STREAM:
974			if (control != NULL) {
975				if (sbappendcontrol_locked(&so2->so_rcv, m,
976				    control))
977					control = NULL;
978			} else
979				sbappend_locked(&so2->so_rcv, m);
980			break;
981
982		case SOCK_SEQPACKET: {
983			const struct sockaddr *from;
984
985			from = &sun_noname;
986			/*
987			 * Don't check for space available in so2->so_rcv.
988			 * Unix domain sockets only check for space in the
989			 * sending sockbuf, and that check is performed one
990			 * level up the stack.
991			 */
992			if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
993				from, m, control))
994				control = NULL;
995			break;
996			}
997		}
998
999		mbcnt = so2->so_rcv.sb_mbcnt;
1000		sbcc = so2->so_rcv.sb_cc;
1001		sorwakeup_locked(so2);
1002
1003		/*
1004		 * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1005		 * it would be possible for uipc_rcvd to be called at this
1006		 * point, drain the receiving sockbuf, clear SB_STOP, and then
1007		 * we would set SB_STOP below.  That could lead to an empty
1008		 * sockbuf having SB_STOP set
1009		 */
1010		SOCKBUF_LOCK(&so->so_snd);
1011		if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1012			so->so_snd.sb_flags |= SB_STOP;
1013		SOCKBUF_UNLOCK(&so->so_snd);
1014		UNP_PCB_UNLOCK(unp2);
1015		m = NULL;
1016		break;
1017
1018	default:
1019		panic("uipc_send unknown socktype");
1020	}
1021
1022	/*
1023	 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1024	 */
1025	if (flags & PRUS_EOF) {
1026		UNP_PCB_LOCK(unp);
1027		socantsendmore(so);
1028		unp_shutdown(unp);
1029		UNP_PCB_UNLOCK(unp);
1030	}
1031
1032	if ((nam != NULL) || (flags & PRUS_EOF))
1033		UNP_LINK_WUNLOCK();
1034	else
1035		UNP_LINK_RUNLOCK();
1036
1037	if (control != NULL && error != 0)
1038		unp_dispose(control);
1039
1040release:
1041	if (control != NULL)
1042		m_freem(control);
1043	if (m != NULL)
1044		m_freem(m);
1045	return (error);
1046}
1047
1048static int
1049uipc_sense(struct socket *so, struct stat *sb)
1050{
1051	struct unpcb *unp;
1052
1053	unp = sotounpcb(so);
1054	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1055
1056	sb->st_blksize = so->so_snd.sb_hiwat;
1057	UNP_PCB_LOCK(unp);
1058	sb->st_dev = NODEV;
1059	if (unp->unp_ino == 0)
1060		unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
1061	sb->st_ino = unp->unp_ino;
1062	UNP_PCB_UNLOCK(unp);
1063	return (0);
1064}
1065
1066static int
1067uipc_shutdown(struct socket *so)
1068{
1069	struct unpcb *unp;
1070
1071	unp = sotounpcb(so);
1072	KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1073
1074	UNP_LINK_WLOCK();
1075	UNP_PCB_LOCK(unp);
1076	socantsendmore(so);
1077	unp_shutdown(unp);
1078	UNP_PCB_UNLOCK(unp);
1079	UNP_LINK_WUNLOCK();
1080	return (0);
1081}
1082
1083static int
1084uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1085{
1086	struct unpcb *unp;
1087	const struct sockaddr *sa;
1088
1089	unp = sotounpcb(so);
1090	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1091
1092	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1093	UNP_PCB_LOCK(unp);
1094	if (unp->unp_addr != NULL)
1095		sa = (struct sockaddr *) unp->unp_addr;
1096	else
1097		sa = &sun_noname;
1098	bcopy(sa, *nam, sa->sa_len);
1099	UNP_PCB_UNLOCK(unp);
1100	return (0);
1101}
1102
1103static struct pr_usrreqs uipc_usrreqs_dgram = {
1104	.pru_abort = 		uipc_abort,
1105	.pru_accept =		uipc_accept,
1106	.pru_attach =		uipc_attach,
1107	.pru_bind =		uipc_bind,
1108	.pru_bindat =		uipc_bindat,
1109	.pru_connect =		uipc_connect,
1110	.pru_connectat =	uipc_connectat,
1111	.pru_connect2 =		uipc_connect2,
1112	.pru_detach =		uipc_detach,
1113	.pru_disconnect =	uipc_disconnect,
1114	.pru_listen =		uipc_listen,
1115	.pru_peeraddr =		uipc_peeraddr,
1116	.pru_rcvd =		uipc_rcvd,
1117	.pru_send =		uipc_send,
1118	.pru_sense =		uipc_sense,
1119	.pru_shutdown =		uipc_shutdown,
1120	.pru_sockaddr =		uipc_sockaddr,
1121	.pru_soreceive =	soreceive_dgram,
1122	.pru_close =		uipc_close,
1123};
1124
1125static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1126	.pru_abort =		uipc_abort,
1127	.pru_accept =		uipc_accept,
1128	.pru_attach =		uipc_attach,
1129	.pru_bind =		uipc_bind,
1130	.pru_bindat =		uipc_bindat,
1131	.pru_connect =		uipc_connect,
1132	.pru_connectat =	uipc_connectat,
1133	.pru_connect2 =		uipc_connect2,
1134	.pru_detach =		uipc_detach,
1135	.pru_disconnect =	uipc_disconnect,
1136	.pru_listen =		uipc_listen,
1137	.pru_peeraddr =		uipc_peeraddr,
1138	.pru_rcvd =		uipc_rcvd,
1139	.pru_send =		uipc_send,
1140	.pru_sense =		uipc_sense,
1141	.pru_shutdown =		uipc_shutdown,
1142	.pru_sockaddr =		uipc_sockaddr,
1143	.pru_soreceive =	soreceive_generic,	/* XXX: or...? */
1144	.pru_close =		uipc_close,
1145};
1146
1147static struct pr_usrreqs uipc_usrreqs_stream = {
1148	.pru_abort = 		uipc_abort,
1149	.pru_accept =		uipc_accept,
1150	.pru_attach =		uipc_attach,
1151	.pru_bind =		uipc_bind,
1152	.pru_bindat =		uipc_bindat,
1153	.pru_connect =		uipc_connect,
1154	.pru_connectat =	uipc_connectat,
1155	.pru_connect2 =		uipc_connect2,
1156	.pru_detach =		uipc_detach,
1157	.pru_disconnect =	uipc_disconnect,
1158	.pru_listen =		uipc_listen,
1159	.pru_peeraddr =		uipc_peeraddr,
1160	.pru_rcvd =		uipc_rcvd,
1161	.pru_send =		uipc_send,
1162	.pru_sense =		uipc_sense,
1163	.pru_shutdown =		uipc_shutdown,
1164	.pru_sockaddr =		uipc_sockaddr,
1165	.pru_soreceive =	soreceive_generic,
1166	.pru_close =		uipc_close,
1167};
1168
1169static int
1170uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1171{
1172	struct unpcb *unp;
1173	struct xucred xu;
1174	int error, optval;
1175
1176	if (sopt->sopt_level != 0)
1177		return (EINVAL);
1178
1179	unp = sotounpcb(so);
1180	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1181	error = 0;
1182	switch (sopt->sopt_dir) {
1183	case SOPT_GET:
1184		switch (sopt->sopt_name) {
1185		case LOCAL_PEERCRED:
1186			UNP_PCB_LOCK(unp);
1187			if (unp->unp_flags & UNP_HAVEPC)
1188				xu = unp->unp_peercred;
1189			else {
1190				if (so->so_type == SOCK_STREAM)
1191					error = ENOTCONN;
1192				else
1193					error = EINVAL;
1194			}
1195			UNP_PCB_UNLOCK(unp);
1196			if (error == 0)
1197				error = sooptcopyout(sopt, &xu, sizeof(xu));
1198			break;
1199
1200		case LOCAL_CREDS:
1201			/* Unlocked read. */
1202			optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1203			error = sooptcopyout(sopt, &optval, sizeof(optval));
1204			break;
1205
1206		case LOCAL_CONNWAIT:
1207			/* Unlocked read. */
1208			optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1209			error = sooptcopyout(sopt, &optval, sizeof(optval));
1210			break;
1211
1212		default:
1213			error = EOPNOTSUPP;
1214			break;
1215		}
1216		break;
1217
1218	case SOPT_SET:
1219		switch (sopt->sopt_name) {
1220		case LOCAL_CREDS:
1221		case LOCAL_CONNWAIT:
1222			error = sooptcopyin(sopt, &optval, sizeof(optval),
1223					    sizeof(optval));
1224			if (error)
1225				break;
1226
1227#define	OPTSET(bit) do {						\
1228	UNP_PCB_LOCK(unp);						\
1229	if (optval)							\
1230		unp->unp_flags |= bit;					\
1231	else								\
1232		unp->unp_flags &= ~bit;					\
1233	UNP_PCB_UNLOCK(unp);						\
1234} while (0)
1235
1236			switch (sopt->sopt_name) {
1237			case LOCAL_CREDS:
1238				OPTSET(UNP_WANTCRED);
1239				break;
1240
1241			case LOCAL_CONNWAIT:
1242				OPTSET(UNP_CONNWAIT);
1243				break;
1244
1245			default:
1246				break;
1247			}
1248			break;
1249#undef	OPTSET
1250		default:
1251			error = ENOPROTOOPT;
1252			break;
1253		}
1254		break;
1255
1256	default:
1257		error = EOPNOTSUPP;
1258		break;
1259	}
1260	return (error);
1261}
1262
1263static int
1264unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1265{
1266
1267	return (unp_connectat(AT_FDCWD, so, nam, td));
1268}
1269
1270static int
1271unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1272    struct thread *td)
1273{
1274	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1275	struct vnode *vp;
1276	struct socket *so2, *so3;
1277	struct unpcb *unp, *unp2, *unp3;
1278	struct nameidata nd;
1279	char buf[SOCK_MAXADDRLEN];
1280	struct sockaddr *sa;
1281	cap_rights_t rights;
1282	int error, len;
1283
1284	if (nam->sa_family != AF_UNIX)
1285		return (EAFNOSUPPORT);
1286
1287	UNP_LINK_WLOCK_ASSERT();
1288
1289	unp = sotounpcb(so);
1290	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1291
1292	if (nam->sa_len > sizeof(struct sockaddr_un))
1293		return (EINVAL);
1294	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1295	if (len <= 0)
1296		return (EINVAL);
1297	bcopy(soun->sun_path, buf, len);
1298	buf[len] = 0;
1299
1300	UNP_PCB_LOCK(unp);
1301	if (unp->unp_flags & UNP_CONNECTING) {
1302		UNP_PCB_UNLOCK(unp);
1303		return (EALREADY);
1304	}
1305	UNP_LINK_WUNLOCK();
1306	unp->unp_flags |= UNP_CONNECTING;
1307	UNP_PCB_UNLOCK(unp);
1308
1309	sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1310	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1311	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1312	error = namei(&nd);
1313	if (error)
1314		vp = NULL;
1315	else
1316		vp = nd.ni_vp;
1317	ASSERT_VOP_LOCKED(vp, "unp_connect");
1318	NDFREE(&nd, NDF_ONLY_PNBUF);
1319	if (error)
1320		goto bad;
1321
1322	if (vp->v_type != VSOCK) {
1323		error = ENOTSOCK;
1324		goto bad;
1325	}
1326#ifdef MAC
1327	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1328	if (error)
1329		goto bad;
1330#endif
1331	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1332	if (error)
1333		goto bad;
1334
1335	unp = sotounpcb(so);
1336	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1337
1338	/*
1339	 * Lock linkage lock for two reasons: make sure v_socket is stable,
1340	 * and to protect simultaneous locking of multiple pcbs.
1341	 */
1342	UNP_LINK_WLOCK();
1343	VOP_UNP_CONNECT(vp, &so2);
1344	if (so2 == NULL) {
1345		error = ECONNREFUSED;
1346		goto bad2;
1347	}
1348	if (so->so_type != so2->so_type) {
1349		error = EPROTOTYPE;
1350		goto bad2;
1351	}
1352	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1353		if (so2->so_options & SO_ACCEPTCONN) {
1354			CURVNET_SET(so2->so_vnet);
1355			so3 = sonewconn(so2, 0);
1356			CURVNET_RESTORE();
1357		} else
1358			so3 = NULL;
1359		if (so3 == NULL) {
1360			error = ECONNREFUSED;
1361			goto bad2;
1362		}
1363		unp = sotounpcb(so);
1364		unp2 = sotounpcb(so2);
1365		unp3 = sotounpcb(so3);
1366		UNP_PCB_LOCK(unp);
1367		UNP_PCB_LOCK(unp2);
1368		UNP_PCB_LOCK(unp3);
1369		if (unp2->unp_addr != NULL) {
1370			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1371			unp3->unp_addr = (struct sockaddr_un *) sa;
1372			sa = NULL;
1373		}
1374
1375		/*
1376		 * The connector's (client's) credentials are copied from its
1377		 * process structure at the time of connect() (which is now).
1378		 */
1379		cru2x(td->td_ucred, &unp3->unp_peercred);
1380		unp3->unp_flags |= UNP_HAVEPC;
1381
1382		/*
1383		 * The receiver's (server's) credentials are copied from the
1384		 * unp_peercred member of socket on which the former called
1385		 * listen(); uipc_listen() cached that process's credentials
1386		 * at that time so we can use them now.
1387		 */
1388		KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1389		    ("unp_connect: listener without cached peercred"));
1390		memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1391		    sizeof(unp->unp_peercred));
1392		unp->unp_flags |= UNP_HAVEPC;
1393		if (unp2->unp_flags & UNP_WANTCRED)
1394			unp3->unp_flags |= UNP_WANTCRED;
1395		UNP_PCB_UNLOCK(unp3);
1396		UNP_PCB_UNLOCK(unp2);
1397		UNP_PCB_UNLOCK(unp);
1398#ifdef MAC
1399		mac_socketpeer_set_from_socket(so, so3);
1400		mac_socketpeer_set_from_socket(so3, so);
1401#endif
1402
1403		so2 = so3;
1404	}
1405	unp = sotounpcb(so);
1406	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1407	unp2 = sotounpcb(so2);
1408	KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1409	UNP_PCB_LOCK(unp);
1410	UNP_PCB_LOCK(unp2);
1411	error = unp_connect2(so, so2, PRU_CONNECT);
1412	UNP_PCB_UNLOCK(unp2);
1413	UNP_PCB_UNLOCK(unp);
1414bad2:
1415	UNP_LINK_WUNLOCK();
1416bad:
1417	if (vp != NULL)
1418		vput(vp);
1419	free(sa, M_SONAME);
1420	UNP_LINK_WLOCK();
1421	UNP_PCB_LOCK(unp);
1422	unp->unp_flags &= ~UNP_CONNECTING;
1423	UNP_PCB_UNLOCK(unp);
1424	return (error);
1425}
1426
1427static int
1428unp_connect2(struct socket *so, struct socket *so2, int req)
1429{
1430	struct unpcb *unp;
1431	struct unpcb *unp2;
1432
1433	unp = sotounpcb(so);
1434	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1435	unp2 = sotounpcb(so2);
1436	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1437
1438	UNP_LINK_WLOCK_ASSERT();
1439	UNP_PCB_LOCK_ASSERT(unp);
1440	UNP_PCB_LOCK_ASSERT(unp2);
1441
1442	if (so2->so_type != so->so_type)
1443		return (EPROTOTYPE);
1444	unp->unp_conn = unp2;
1445
1446	switch (so->so_type) {
1447	case SOCK_DGRAM:
1448		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1449		soisconnected(so);
1450		break;
1451
1452	case SOCK_STREAM:
1453	case SOCK_SEQPACKET:
1454		unp2->unp_conn = unp;
1455		if (req == PRU_CONNECT &&
1456		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1457			soisconnecting(so);
1458		else
1459			soisconnected(so);
1460		soisconnected(so2);
1461		break;
1462
1463	default:
1464		panic("unp_connect2");
1465	}
1466	return (0);
1467}
1468
1469static void
1470unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1471{
1472	struct socket *so;
1473
1474	KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1475
1476	UNP_LINK_WLOCK_ASSERT();
1477	UNP_PCB_LOCK_ASSERT(unp);
1478	UNP_PCB_LOCK_ASSERT(unp2);
1479
1480	unp->unp_conn = NULL;
1481	switch (unp->unp_socket->so_type) {
1482	case SOCK_DGRAM:
1483		LIST_REMOVE(unp, unp_reflink);
1484		so = unp->unp_socket;
1485		SOCK_LOCK(so);
1486		so->so_state &= ~SS_ISCONNECTED;
1487		SOCK_UNLOCK(so);
1488		break;
1489
1490	case SOCK_STREAM:
1491	case SOCK_SEQPACKET:
1492		soisdisconnected(unp->unp_socket);
1493		unp2->unp_conn = NULL;
1494		soisdisconnected(unp2->unp_socket);
1495		break;
1496	}
1497}
1498
1499/*
1500 * unp_pcblist() walks the global list of struct unpcb's to generate a
1501 * pointer list, bumping the refcount on each unpcb.  It then copies them out
1502 * sequentially, validating the generation number on each to see if it has
1503 * been detached.  All of this is necessary because copyout() may sleep on
1504 * disk I/O.
1505 */
1506static int
1507unp_pcblist(SYSCTL_HANDLER_ARGS)
1508{
1509	int error, i, n;
1510	int freeunp;
1511	struct unpcb *unp, **unp_list;
1512	unp_gen_t gencnt;
1513	struct xunpgen *xug;
1514	struct unp_head *head;
1515	struct xunpcb *xu;
1516
1517	switch ((intptr_t)arg1) {
1518	case SOCK_STREAM:
1519		head = &unp_shead;
1520		break;
1521
1522	case SOCK_DGRAM:
1523		head = &unp_dhead;
1524		break;
1525
1526	case SOCK_SEQPACKET:
1527		head = &unp_sphead;
1528		break;
1529
1530	default:
1531		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1532	}
1533
1534	/*
1535	 * The process of preparing the PCB list is too time-consuming and
1536	 * resource-intensive to repeat twice on every request.
1537	 */
1538	if (req->oldptr == NULL) {
1539		n = unp_count;
1540		req->oldidx = 2 * (sizeof *xug)
1541			+ (n + n/8) * sizeof(struct xunpcb);
1542		return (0);
1543	}
1544
1545	if (req->newptr != NULL)
1546		return (EPERM);
1547
1548	/*
1549	 * OK, now we're committed to doing something.
1550	 */
1551	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1552	UNP_LIST_LOCK();
1553	gencnt = unp_gencnt;
1554	n = unp_count;
1555	UNP_LIST_UNLOCK();
1556
1557	xug->xug_len = sizeof *xug;
1558	xug->xug_count = n;
1559	xug->xug_gen = gencnt;
1560	xug->xug_sogen = so_gencnt;
1561	error = SYSCTL_OUT(req, xug, sizeof *xug);
1562	if (error) {
1563		free(xug, M_TEMP);
1564		return (error);
1565	}
1566
1567	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1568
1569	UNP_LIST_LOCK();
1570	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1571	     unp = LIST_NEXT(unp, unp_link)) {
1572		UNP_PCB_LOCK(unp);
1573		if (unp->unp_gencnt <= gencnt) {
1574			if (cr_cansee(req->td->td_ucred,
1575			    unp->unp_socket->so_cred)) {
1576				UNP_PCB_UNLOCK(unp);
1577				continue;
1578			}
1579			unp_list[i++] = unp;
1580			unp->unp_refcount++;
1581		}
1582		UNP_PCB_UNLOCK(unp);
1583	}
1584	UNP_LIST_UNLOCK();
1585	n = i;			/* In case we lost some during malloc. */
1586
1587	error = 0;
1588	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1589	for (i = 0; i < n; i++) {
1590		unp = unp_list[i];
1591		UNP_PCB_LOCK(unp);
1592		unp->unp_refcount--;
1593	        if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1594			xu->xu_len = sizeof *xu;
1595			xu->xu_unpp = unp;
1596			/*
1597			 * XXX - need more locking here to protect against
1598			 * connect/disconnect races for SMP.
1599			 */
1600			if (unp->unp_addr != NULL)
1601				bcopy(unp->unp_addr, &xu->xu_addr,
1602				      unp->unp_addr->sun_len);
1603			if (unp->unp_conn != NULL &&
1604			    unp->unp_conn->unp_addr != NULL)
1605				bcopy(unp->unp_conn->unp_addr,
1606				      &xu->xu_caddr,
1607				      unp->unp_conn->unp_addr->sun_len);
1608			bcopy(unp, &xu->xu_unp, sizeof *unp);
1609			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1610			UNP_PCB_UNLOCK(unp);
1611			error = SYSCTL_OUT(req, xu, sizeof *xu);
1612		} else {
1613			freeunp = (unp->unp_refcount == 0);
1614			UNP_PCB_UNLOCK(unp);
1615			if (freeunp) {
1616				UNP_PCB_LOCK_DESTROY(unp);
1617				uma_zfree(unp_zone, unp);
1618			}
1619		}
1620	}
1621	free(xu, M_TEMP);
1622	if (!error) {
1623		/*
1624		 * Give the user an updated idea of our state.  If the
1625		 * generation differs from what we told her before, she knows
1626		 * that something happened while we were processing this
1627		 * request, and it might be necessary to retry.
1628		 */
1629		xug->xug_gen = unp_gencnt;
1630		xug->xug_sogen = so_gencnt;
1631		xug->xug_count = unp_count;
1632		error = SYSCTL_OUT(req, xug, sizeof *xug);
1633	}
1634	free(unp_list, M_TEMP);
1635	free(xug, M_TEMP);
1636	return (error);
1637}
1638
1639SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1640    (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1641    "List of active local datagram sockets");
1642SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1643    (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1644    "List of active local stream sockets");
1645SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1646    CTLTYPE_OPAQUE | CTLFLAG_RD,
1647    (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1648    "List of active local seqpacket sockets");
1649
1650static void
1651unp_shutdown(struct unpcb *unp)
1652{
1653	struct unpcb *unp2;
1654	struct socket *so;
1655
1656	UNP_LINK_WLOCK_ASSERT();
1657	UNP_PCB_LOCK_ASSERT(unp);
1658
1659	unp2 = unp->unp_conn;
1660	if ((unp->unp_socket->so_type == SOCK_STREAM ||
1661	    (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1662		so = unp2->unp_socket;
1663		if (so != NULL)
1664			socantrcvmore(so);
1665	}
1666}
1667
1668static void
1669unp_drop(struct unpcb *unp, int errno)
1670{
1671	struct socket *so = unp->unp_socket;
1672	struct unpcb *unp2;
1673
1674	UNP_LINK_WLOCK_ASSERT();
1675	UNP_PCB_LOCK_ASSERT(unp);
1676
1677	so->so_error = errno;
1678	unp2 = unp->unp_conn;
1679	if (unp2 == NULL)
1680		return;
1681	UNP_PCB_LOCK(unp2);
1682	unp_disconnect(unp, unp2);
1683	UNP_PCB_UNLOCK(unp2);
1684}
1685
1686static void
1687unp_freerights(struct filedescent **fdep, int fdcount)
1688{
1689	struct file *fp;
1690	int i;
1691
1692	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
1693
1694	for (i = 0; i < fdcount; i++) {
1695		fp = fdep[i]->fde_file;
1696		filecaps_free(&fdep[i]->fde_caps);
1697		unp_discard(fp);
1698	}
1699	free(fdep[0], M_FILECAPS);
1700}
1701
1702static int
1703unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
1704{
1705	struct thread *td = curthread;		/* XXX */
1706	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1707	int i;
1708	int *fdp;
1709	struct filedesc *fdesc = td->td_proc->p_fd;
1710	struct filedescent *fde, **fdep;
1711	void *data;
1712	socklen_t clen = control->m_len, datalen;
1713	int error, newfds;
1714	u_int newlen;
1715
1716	UNP_LINK_UNLOCK_ASSERT();
1717
1718	error = 0;
1719	if (controlp != NULL) /* controlp == NULL => free control messages */
1720		*controlp = NULL;
1721	while (cm != NULL) {
1722		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1723			error = EINVAL;
1724			break;
1725		}
1726		data = CMSG_DATA(cm);
1727		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1728		if (cm->cmsg_level == SOL_SOCKET
1729		    && cm->cmsg_type == SCM_RIGHTS) {
1730			newfds = datalen / sizeof(*fdep);
1731			if (newfds == 0)
1732				goto next;
1733			fdep = data;
1734
1735			/* If we're not outputting the descriptors free them. */
1736			if (error || controlp == NULL) {
1737				unp_freerights(fdep, newfds);
1738				goto next;
1739			}
1740			FILEDESC_XLOCK(fdesc);
1741
1742			/*
1743			 * Now change each pointer to an fd in the global
1744			 * table to an integer that is the index to the local
1745			 * fd table entry that we set up to point to the
1746			 * global one we are transferring.
1747			 */
1748			newlen = newfds * sizeof(int);
1749			*controlp = sbcreatecontrol(NULL, newlen,
1750			    SCM_RIGHTS, SOL_SOCKET);
1751			if (*controlp == NULL) {
1752				FILEDESC_XUNLOCK(fdesc);
1753				error = E2BIG;
1754				unp_freerights(fdep, newfds);
1755				goto next;
1756			}
1757
1758			fdp = (int *)
1759			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1760			if (fdallocn(td, 0, fdp, newfds) != 0) {
1761				FILEDESC_XUNLOCK(td->td_proc->p_fd);
1762				error = EMSGSIZE;
1763				unp_freerights(fdep, newfds);
1764				m_freem(*controlp);
1765				*controlp = NULL;
1766				goto next;
1767			}
1768			for (i = 0; i < newfds; i++, fdp++) {
1769				fde = &fdesc->fd_ofiles[*fdp];
1770				fde->fde_file = fdep[i]->fde_file;
1771				filecaps_move(&fdep[i]->fde_caps,
1772				    &fde->fde_caps);
1773				if ((flags & MSG_CMSG_CLOEXEC) != 0)
1774					fde->fde_flags |= UF_EXCLOSE;
1775				unp_externalize_fp(fde->fde_file);
1776			}
1777			FILEDESC_XUNLOCK(fdesc);
1778			free(fdep[0], M_FILECAPS);
1779		} else {
1780			/* We can just copy anything else across. */
1781			if (error || controlp == NULL)
1782				goto next;
1783			*controlp = sbcreatecontrol(NULL, datalen,
1784			    cm->cmsg_type, cm->cmsg_level);
1785			if (*controlp == NULL) {
1786				error = ENOBUFS;
1787				goto next;
1788			}
1789			bcopy(data,
1790			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1791			    datalen);
1792		}
1793		controlp = &(*controlp)->m_next;
1794
1795next:
1796		if (CMSG_SPACE(datalen) < clen) {
1797			clen -= CMSG_SPACE(datalen);
1798			cm = (struct cmsghdr *)
1799			    ((caddr_t)cm + CMSG_SPACE(datalen));
1800		} else {
1801			clen = 0;
1802			cm = NULL;
1803		}
1804	}
1805
1806	m_freem(control);
1807	return (error);
1808}
1809
1810static void
1811unp_zone_change(void *tag)
1812{
1813
1814	uma_zone_set_max(unp_zone, maxsockets);
1815}
1816
1817static void
1818unp_init(void)
1819{
1820
1821#ifdef VIMAGE
1822	if (!IS_DEFAULT_VNET(curvnet))
1823		return;
1824#endif
1825	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1826	    NULL, NULL, UMA_ALIGN_PTR, 0);
1827	if (unp_zone == NULL)
1828		panic("unp_init");
1829	uma_zone_set_max(unp_zone, maxsockets);
1830	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
1831	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1832	    NULL, EVENTHANDLER_PRI_ANY);
1833	LIST_INIT(&unp_dhead);
1834	LIST_INIT(&unp_shead);
1835	LIST_INIT(&unp_sphead);
1836	SLIST_INIT(&unp_defers);
1837	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
1838	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
1839	UNP_LINK_LOCK_INIT();
1840	UNP_LIST_LOCK_INIT();
1841	UNP_DEFERRED_LOCK_INIT();
1842}
1843
1844static int
1845unp_internalize(struct mbuf **controlp, struct thread *td)
1846{
1847	struct mbuf *control = *controlp;
1848	struct proc *p = td->td_proc;
1849	struct filedesc *fdesc = p->p_fd;
1850	struct bintime *bt;
1851	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1852	struct cmsgcred *cmcred;
1853	struct filedescent *fde, **fdep, *fdev;
1854	struct file *fp;
1855	struct timeval *tv;
1856	int i, fd, *fdp;
1857	void *data;
1858	socklen_t clen = control->m_len, datalen;
1859	int error, oldfds;
1860	u_int newlen;
1861
1862	UNP_LINK_UNLOCK_ASSERT();
1863
1864	error = 0;
1865	*controlp = NULL;
1866	while (cm != NULL) {
1867		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1868		    || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
1869			error = EINVAL;
1870			goto out;
1871		}
1872		data = CMSG_DATA(cm);
1873		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1874
1875		switch (cm->cmsg_type) {
1876		/*
1877		 * Fill in credential information.
1878		 */
1879		case SCM_CREDS:
1880			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1881			    SCM_CREDS, SOL_SOCKET);
1882			if (*controlp == NULL) {
1883				error = ENOBUFS;
1884				goto out;
1885			}
1886			cmcred = (struct cmsgcred *)
1887			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1888			cmcred->cmcred_pid = p->p_pid;
1889			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1890			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1891			cmcred->cmcred_euid = td->td_ucred->cr_uid;
1892			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1893			    CMGROUP_MAX);
1894			for (i = 0; i < cmcred->cmcred_ngroups; i++)
1895				cmcred->cmcred_groups[i] =
1896				    td->td_ucred->cr_groups[i];
1897			break;
1898
1899		case SCM_RIGHTS:
1900			oldfds = datalen / sizeof (int);
1901			if (oldfds == 0)
1902				break;
1903			/*
1904			 * Check that all the FDs passed in refer to legal
1905			 * files.  If not, reject the entire operation.
1906			 */
1907			fdp = data;
1908			FILEDESC_SLOCK(fdesc);
1909			for (i = 0; i < oldfds; i++) {
1910				fd = *fdp++;
1911				if (fget_locked(fdesc, fd) == NULL) {
1912					FILEDESC_SUNLOCK(fdesc);
1913					error = EBADF;
1914					goto out;
1915				}
1916				fp = fdesc->fd_ofiles[fd].fde_file;
1917				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1918					FILEDESC_SUNLOCK(fdesc);
1919					error = EOPNOTSUPP;
1920					goto out;
1921				}
1922
1923			}
1924
1925			/*
1926			 * Now replace the integer FDs with pointers to the
1927			 * file structure and capability rights.
1928			 */
1929			newlen = oldfds * sizeof(fdep[0]);
1930			*controlp = sbcreatecontrol(NULL, newlen,
1931			    SCM_RIGHTS, SOL_SOCKET);
1932			if (*controlp == NULL) {
1933				FILEDESC_SUNLOCK(fdesc);
1934				error = E2BIG;
1935				goto out;
1936			}
1937			fdp = data;
1938			fdep = (struct filedescent **)
1939			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1940			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
1941			    M_WAITOK);
1942			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
1943				fde = &fdesc->fd_ofiles[*fdp];
1944				fdep[i] = fdev;
1945				fdep[i]->fde_file = fde->fde_file;
1946				filecaps_copy(&fde->fde_caps,
1947				    &fdep[i]->fde_caps);
1948				unp_internalize_fp(fdep[i]->fde_file);
1949			}
1950			FILEDESC_SUNLOCK(fdesc);
1951			break;
1952
1953		case SCM_TIMESTAMP:
1954			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
1955			    SCM_TIMESTAMP, SOL_SOCKET);
1956			if (*controlp == NULL) {
1957				error = ENOBUFS;
1958				goto out;
1959			}
1960			tv = (struct timeval *)
1961			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1962			microtime(tv);
1963			break;
1964
1965		case SCM_BINTIME:
1966			*controlp = sbcreatecontrol(NULL, sizeof(*bt),
1967			    SCM_BINTIME, SOL_SOCKET);
1968			if (*controlp == NULL) {
1969				error = ENOBUFS;
1970				goto out;
1971			}
1972			bt = (struct bintime *)
1973			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1974			bintime(bt);
1975			break;
1976
1977		default:
1978			error = EINVAL;
1979			goto out;
1980		}
1981
1982		controlp = &(*controlp)->m_next;
1983		if (CMSG_SPACE(datalen) < clen) {
1984			clen -= CMSG_SPACE(datalen);
1985			cm = (struct cmsghdr *)
1986			    ((caddr_t)cm + CMSG_SPACE(datalen));
1987		} else {
1988			clen = 0;
1989			cm = NULL;
1990		}
1991	}
1992
1993out:
1994	m_freem(control);
1995	return (error);
1996}
1997
1998static struct mbuf *
1999unp_addsockcred(struct thread *td, struct mbuf *control)
2000{
2001	struct mbuf *m, *n, *n_prev;
2002	struct sockcred *sc;
2003	const struct cmsghdr *cm;
2004	int ngroups;
2005	int i;
2006
2007	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2008	m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2009	if (m == NULL)
2010		return (control);
2011
2012	sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2013	sc->sc_uid = td->td_ucred->cr_ruid;
2014	sc->sc_euid = td->td_ucred->cr_uid;
2015	sc->sc_gid = td->td_ucred->cr_rgid;
2016	sc->sc_egid = td->td_ucred->cr_gid;
2017	sc->sc_ngroups = ngroups;
2018	for (i = 0; i < sc->sc_ngroups; i++)
2019		sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2020
2021	/*
2022	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2023	 * created SCM_CREDS control message (struct sockcred) has another
2024	 * format.
2025	 */
2026	if (control != NULL)
2027		for (n = control, n_prev = NULL; n != NULL;) {
2028			cm = mtod(n, struct cmsghdr *);
2029    			if (cm->cmsg_level == SOL_SOCKET &&
2030			    cm->cmsg_type == SCM_CREDS) {
2031    				if (n_prev == NULL)
2032					control = n->m_next;
2033				else
2034					n_prev->m_next = n->m_next;
2035				n = m_free(n);
2036			} else {
2037				n_prev = n;
2038				n = n->m_next;
2039			}
2040		}
2041
2042	/* Prepend it to the head. */
2043	m->m_next = control;
2044	return (m);
2045}
2046
2047static struct unpcb *
2048fptounp(struct file *fp)
2049{
2050	struct socket *so;
2051
2052	if (fp->f_type != DTYPE_SOCKET)
2053		return (NULL);
2054	if ((so = fp->f_data) == NULL)
2055		return (NULL);
2056	if (so->so_proto->pr_domain != &localdomain)
2057		return (NULL);
2058	return sotounpcb(so);
2059}
2060
2061static void
2062unp_discard(struct file *fp)
2063{
2064	struct unp_defer *dr;
2065
2066	if (unp_externalize_fp(fp)) {
2067		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2068		dr->ud_fp = fp;
2069		UNP_DEFERRED_LOCK();
2070		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2071		UNP_DEFERRED_UNLOCK();
2072		atomic_add_int(&unp_defers_count, 1);
2073		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2074	} else
2075		(void) closef(fp, (struct thread *)NULL);
2076}
2077
2078static void
2079unp_process_defers(void *arg __unused, int pending)
2080{
2081	struct unp_defer *dr;
2082	SLIST_HEAD(, unp_defer) drl;
2083	int count;
2084
2085	SLIST_INIT(&drl);
2086	for (;;) {
2087		UNP_DEFERRED_LOCK();
2088		if (SLIST_FIRST(&unp_defers) == NULL) {
2089			UNP_DEFERRED_UNLOCK();
2090			break;
2091		}
2092		SLIST_SWAP(&unp_defers, &drl, unp_defer);
2093		UNP_DEFERRED_UNLOCK();
2094		count = 0;
2095		while ((dr = SLIST_FIRST(&drl)) != NULL) {
2096			SLIST_REMOVE_HEAD(&drl, ud_link);
2097			closef(dr->ud_fp, NULL);
2098			free(dr, M_TEMP);
2099			count++;
2100		}
2101		atomic_add_int(&unp_defers_count, -count);
2102	}
2103}
2104
2105static void
2106unp_internalize_fp(struct file *fp)
2107{
2108	struct unpcb *unp;
2109
2110	UNP_LINK_WLOCK();
2111	if ((unp = fptounp(fp)) != NULL) {
2112		unp->unp_file = fp;
2113		unp->unp_msgcount++;
2114	}
2115	fhold(fp);
2116	unp_rights++;
2117	UNP_LINK_WUNLOCK();
2118}
2119
2120static int
2121unp_externalize_fp(struct file *fp)
2122{
2123	struct unpcb *unp;
2124	int ret;
2125
2126	UNP_LINK_WLOCK();
2127	if ((unp = fptounp(fp)) != NULL) {
2128		unp->unp_msgcount--;
2129		ret = 1;
2130	} else
2131		ret = 0;
2132	unp_rights--;
2133	UNP_LINK_WUNLOCK();
2134	return (ret);
2135}
2136
2137/*
2138 * unp_defer indicates whether additional work has been defered for a future
2139 * pass through unp_gc().  It is thread local and does not require explicit
2140 * synchronization.
2141 */
2142static int	unp_marked;
2143static int	unp_unreachable;
2144
2145static void
2146unp_accessable(struct filedescent **fdep, int fdcount)
2147{
2148	struct unpcb *unp;
2149	struct file *fp;
2150	int i;
2151
2152	for (i = 0; i < fdcount; i++) {
2153		fp = fdep[i]->fde_file;
2154		if ((unp = fptounp(fp)) == NULL)
2155			continue;
2156		if (unp->unp_gcflag & UNPGC_REF)
2157			continue;
2158		unp->unp_gcflag &= ~UNPGC_DEAD;
2159		unp->unp_gcflag |= UNPGC_REF;
2160		unp_marked++;
2161	}
2162}
2163
2164static void
2165unp_gc_process(struct unpcb *unp)
2166{
2167	struct socket *soa;
2168	struct socket *so;
2169	struct file *fp;
2170
2171	/* Already processed. */
2172	if (unp->unp_gcflag & UNPGC_SCANNED)
2173		return;
2174	fp = unp->unp_file;
2175
2176	/*
2177	 * Check for a socket potentially in a cycle.  It must be in a
2178	 * queue as indicated by msgcount, and this must equal the file
2179	 * reference count.  Note that when msgcount is 0 the file is NULL.
2180	 */
2181	if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2182	    unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2183		unp->unp_gcflag |= UNPGC_DEAD;
2184		unp_unreachable++;
2185		return;
2186	}
2187
2188	/*
2189	 * Mark all sockets we reference with RIGHTS.
2190	 */
2191	so = unp->unp_socket;
2192	SOCKBUF_LOCK(&so->so_rcv);
2193	unp_scan(so->so_rcv.sb_mb, unp_accessable);
2194	SOCKBUF_UNLOCK(&so->so_rcv);
2195
2196	/*
2197	 * Mark all sockets in our accept queue.
2198	 */
2199	ACCEPT_LOCK();
2200	TAILQ_FOREACH(soa, &so->so_comp, so_list) {
2201		SOCKBUF_LOCK(&soa->so_rcv);
2202		unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2203		SOCKBUF_UNLOCK(&soa->so_rcv);
2204	}
2205	ACCEPT_UNLOCK();
2206	unp->unp_gcflag |= UNPGC_SCANNED;
2207}
2208
2209static int unp_recycled;
2210SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2211    "Number of unreachable sockets claimed by the garbage collector.");
2212
2213static int unp_taskcount;
2214SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2215    "Number of times the garbage collector has run.");
2216
2217static void
2218unp_gc(__unused void *arg, int pending)
2219{
2220	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2221				    NULL };
2222	struct unp_head **head;
2223	struct file *f, **unref;
2224	struct unpcb *unp;
2225	int i, total;
2226
2227	unp_taskcount++;
2228	UNP_LIST_LOCK();
2229	/*
2230	 * First clear all gc flags from previous runs.
2231	 */
2232	for (head = heads; *head != NULL; head++)
2233		LIST_FOREACH(unp, *head, unp_link)
2234			unp->unp_gcflag = 0;
2235
2236	/*
2237	 * Scan marking all reachable sockets with UNPGC_REF.  Once a socket
2238	 * is reachable all of the sockets it references are reachable.
2239	 * Stop the scan once we do a complete loop without discovering
2240	 * a new reachable socket.
2241	 */
2242	do {
2243		unp_unreachable = 0;
2244		unp_marked = 0;
2245		for (head = heads; *head != NULL; head++)
2246			LIST_FOREACH(unp, *head, unp_link)
2247				unp_gc_process(unp);
2248	} while (unp_marked);
2249	UNP_LIST_UNLOCK();
2250	if (unp_unreachable == 0)
2251		return;
2252
2253	/*
2254	 * Allocate space for a local list of dead unpcbs.
2255	 */
2256	unref = malloc(unp_unreachable * sizeof(struct file *),
2257	    M_TEMP, M_WAITOK);
2258
2259	/*
2260	 * Iterate looking for sockets which have been specifically marked
2261	 * as as unreachable and store them locally.
2262	 */
2263	UNP_LINK_RLOCK();
2264	UNP_LIST_LOCK();
2265	for (total = 0, head = heads; *head != NULL; head++)
2266		LIST_FOREACH(unp, *head, unp_link)
2267			if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
2268				f = unp->unp_file;
2269				if (unp->unp_msgcount == 0 || f == NULL ||
2270				    f->f_count != unp->unp_msgcount)
2271					continue;
2272				unref[total++] = f;
2273				fhold(f);
2274				KASSERT(total <= unp_unreachable,
2275				    ("unp_gc: incorrect unreachable count."));
2276			}
2277	UNP_LIST_UNLOCK();
2278	UNP_LINK_RUNLOCK();
2279
2280	/*
2281	 * Now flush all sockets, free'ing rights.  This will free the
2282	 * struct files associated with these sockets but leave each socket
2283	 * with one remaining ref.
2284	 */
2285	for (i = 0; i < total; i++) {
2286		struct socket *so;
2287
2288		so = unref[i]->f_data;
2289		CURVNET_SET(so->so_vnet);
2290		sorflush(so);
2291		CURVNET_RESTORE();
2292	}
2293
2294	/*
2295	 * And finally release the sockets so they can be reclaimed.
2296	 */
2297	for (i = 0; i < total; i++)
2298		fdrop(unref[i], NULL);
2299	unp_recycled += total;
2300	free(unref, M_TEMP);
2301}
2302
2303static void
2304unp_dispose(struct mbuf *m)
2305{
2306
2307	if (m)
2308		unp_scan(m, unp_freerights);
2309}
2310
2311static void
2312unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2313{
2314	struct mbuf *m;
2315	struct cmsghdr *cm;
2316	void *data;
2317	socklen_t clen, datalen;
2318
2319	while (m0 != NULL) {
2320		for (m = m0; m; m = m->m_next) {
2321			if (m->m_type != MT_CONTROL)
2322				continue;
2323
2324			cm = mtod(m, struct cmsghdr *);
2325			clen = m->m_len;
2326
2327			while (cm != NULL) {
2328				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2329					break;
2330
2331				data = CMSG_DATA(cm);
2332				datalen = (caddr_t)cm + cm->cmsg_len
2333				    - (caddr_t)data;
2334
2335				if (cm->cmsg_level == SOL_SOCKET &&
2336				    cm->cmsg_type == SCM_RIGHTS) {
2337					(*op)(data, datalen /
2338					    sizeof(struct filedescent *));
2339				}
2340
2341				if (CMSG_SPACE(datalen) < clen) {
2342					clen -= CMSG_SPACE(datalen);
2343					cm = (struct cmsghdr *)
2344					    ((caddr_t)cm + CMSG_SPACE(datalen));
2345				} else {
2346					clen = 0;
2347					cm = NULL;
2348				}
2349			}
2350		}
2351		m0 = m0->m_nextpkt;
2352	}
2353}
2354
2355/*
2356 * A helper function called by VFS before socket-type vnode reclamation.
2357 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2358 * use count.
2359 */
2360void
2361vfs_unp_reclaim(struct vnode *vp)
2362{
2363	struct socket *so;
2364	struct unpcb *unp;
2365	int active;
2366
2367	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2368	KASSERT(vp->v_type == VSOCK,
2369	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2370
2371	active = 0;
2372	UNP_LINK_WLOCK();
2373	VOP_UNP_CONNECT(vp, &so);
2374	if (so == NULL)
2375		goto done;
2376	unp = sotounpcb(so);
2377	if (unp == NULL)
2378		goto done;
2379	UNP_PCB_LOCK(unp);
2380	if (unp->unp_vnode == vp) {
2381		VOP_UNP_DETACH(vp);
2382		unp->unp_vnode = NULL;
2383		active = 1;
2384	}
2385	UNP_PCB_UNLOCK(unp);
2386done:
2387	UNP_LINK_WUNLOCK();
2388	if (active)
2389		vunref(vp);
2390}
2391
2392#ifdef DDB
2393static void
2394db_print_indent(int indent)
2395{
2396	int i;
2397
2398	for (i = 0; i < indent; i++)
2399		db_printf(" ");
2400}
2401
2402static void
2403db_print_unpflags(int unp_flags)
2404{
2405	int comma;
2406
2407	comma = 0;
2408	if (unp_flags & UNP_HAVEPC) {
2409		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2410		comma = 1;
2411	}
2412	if (unp_flags & UNP_HAVEPCCACHED) {
2413		db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2414		comma = 1;
2415	}
2416	if (unp_flags & UNP_WANTCRED) {
2417		db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2418		comma = 1;
2419	}
2420	if (unp_flags & UNP_CONNWAIT) {
2421		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2422		comma = 1;
2423	}
2424	if (unp_flags & UNP_CONNECTING) {
2425		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2426		comma = 1;
2427	}
2428	if (unp_flags & UNP_BINDING) {
2429		db_printf("%sUNP_BINDING", comma ? ", " : "");
2430		comma = 1;
2431	}
2432}
2433
2434static void
2435db_print_xucred(int indent, struct xucred *xu)
2436{
2437	int comma, i;
2438
2439	db_print_indent(indent);
2440	db_printf("cr_version: %u   cr_uid: %u   cr_ngroups: %d\n",
2441	    xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2442	db_print_indent(indent);
2443	db_printf("cr_groups: ");
2444	comma = 0;
2445	for (i = 0; i < xu->cr_ngroups; i++) {
2446		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2447		comma = 1;
2448	}
2449	db_printf("\n");
2450}
2451
2452static void
2453db_print_unprefs(int indent, struct unp_head *uh)
2454{
2455	struct unpcb *unp;
2456	int counter;
2457
2458	counter = 0;
2459	LIST_FOREACH(unp, uh, unp_reflink) {
2460		if (counter % 4 == 0)
2461			db_print_indent(indent);
2462		db_printf("%p  ", unp);
2463		if (counter % 4 == 3)
2464			db_printf("\n");
2465		counter++;
2466	}
2467	if (counter != 0 && counter % 4 != 0)
2468		db_printf("\n");
2469}
2470
2471DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2472{
2473	struct unpcb *unp;
2474
2475        if (!have_addr) {
2476                db_printf("usage: show unpcb <addr>\n");
2477                return;
2478        }
2479        unp = (struct unpcb *)addr;
2480
2481	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
2482	    unp->unp_vnode);
2483
2484	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2485	    unp->unp_conn);
2486
2487	db_printf("unp_refs:\n");
2488	db_print_unprefs(2, &unp->unp_refs);
2489
2490	/* XXXRW: Would be nice to print the full address, if any. */
2491	db_printf("unp_addr: %p\n", unp->unp_addr);
2492
2493	db_printf("unp_gencnt: %llu\n",
2494	    (unsigned long long)unp->unp_gencnt);
2495
2496	db_printf("unp_flags: %x (", unp->unp_flags);
2497	db_print_unpflags(unp->unp_flags);
2498	db_printf(")\n");
2499
2500	db_printf("unp_peercred:\n");
2501	db_print_xucred(2, &unp->unp_peercred);
2502
2503	db_printf("unp_refcount: %u\n", unp->unp_refcount);
2504}
2505#endif
2506