xref: /freebsd/sys/kern/uipc_usrreq.c (revision 4928135658a9d0eaee37003df6137ab363fcb0b4)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California. All Rights Reserved.
6  * Copyright (c) 2004-2009 Robert N. M. Watson All Rights Reserved.
7  * Copyright (c) 2018 Matthew Macy
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	From: @(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
34  */
35 
36 /*
37  * UNIX Domain (Local) Sockets
38  *
39  * This is an implementation of UNIX (local) domain sockets.  Each socket has
40  * an associated struct unpcb (UNIX protocol control block).  Stream sockets
41  * may be connected to 0 or 1 other socket.  Datagram sockets may be
42  * connected to 0, 1, or many other sockets.  Sockets may be created and
43  * connected in pairs (socketpair(2)), or bound/connected to using the file
44  * system name space.  For most purposes, only the receive socket buffer is
45  * used, as sending on one socket delivers directly to the receive socket
46  * buffer of a second socket.
47  *
48  * The implementation is substantially complicated by the fact that
49  * "ancillary data", such as file descriptors or credentials, may be passed
50  * across UNIX domain sockets.  The potential for passing UNIX domain sockets
51  * over other UNIX domain sockets requires the implementation of a simple
52  * garbage collector to find and tear down cycles of disconnected sockets.
53  *
54  * TODO:
55  *	RDM
56  *	rethink name space problems
57  *	need a proper out-of-band
58  */
59 
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
62 
63 #include "opt_ddb.h"
64 
65 #include <sys/param.h>
66 #include <sys/capsicum.h>
67 #include <sys/domain.h>
68 #include <sys/fcntl.h>
69 #include <sys/malloc.h>		/* XXX must be before <sys/file.h> */
70 #include <sys/eventhandler.h>
71 #include <sys/file.h>
72 #include <sys/filedesc.h>
73 #include <sys/kernel.h>
74 #include <sys/lock.h>
75 #include <sys/mbuf.h>
76 #include <sys/mount.h>
77 #include <sys/mutex.h>
78 #include <sys/namei.h>
79 #include <sys/proc.h>
80 #include <sys/protosw.h>
81 #include <sys/queue.h>
82 #include <sys/resourcevar.h>
83 #include <sys/rwlock.h>
84 #include <sys/socket.h>
85 #include <sys/socketvar.h>
86 #include <sys/signalvar.h>
87 #include <sys/stat.h>
88 #include <sys/sx.h>
89 #include <sys/sysctl.h>
90 #include <sys/systm.h>
91 #include <sys/taskqueue.h>
92 #include <sys/un.h>
93 #include <sys/unpcb.h>
94 #include <sys/vnode.h>
95 
96 #include <net/vnet.h>
97 
98 #ifdef DDB
99 #include <ddb/ddb.h>
100 #endif
101 
102 #include <security/mac/mac_framework.h>
103 
104 #include <vm/uma.h>
105 
106 MALLOC_DECLARE(M_FILECAPS);
107 
108 /*
109  * Locking key:
110  * (l)	Locked using list lock
111  * (g)	Locked using linkage lock
112  */
113 
114 static uma_zone_t	unp_zone;
115 static unp_gen_t	unp_gencnt;	/* (l) */
116 static u_int		unp_count;	/* (l) Count of local sockets. */
117 static ino_t		unp_ino;	/* Prototype for fake inode numbers. */
118 static int		unp_rights;	/* (g) File descriptors in flight. */
119 static struct unp_head	unp_shead;	/* (l) List of stream sockets. */
120 static struct unp_head	unp_dhead;	/* (l) List of datagram sockets. */
121 static struct unp_head	unp_sphead;	/* (l) List of seqpacket sockets. */
122 
123 struct unp_defer {
124 	SLIST_ENTRY(unp_defer) ud_link;
125 	struct file *ud_fp;
126 };
127 static SLIST_HEAD(, unp_defer) unp_defers;
128 static int unp_defers_count;
129 
130 static const struct sockaddr	sun_noname = { sizeof(sun_noname), AF_LOCAL };
131 
132 /*
133  * Garbage collection of cyclic file descriptor/socket references occurs
134  * asynchronously in a taskqueue context in order to avoid recursion and
135  * reentrance in the UNIX domain socket, file descriptor, and socket layer
136  * code.  See unp_gc() for a full description.
137  */
138 static struct timeout_task unp_gc_task;
139 
140 /*
141  * The close of unix domain sockets attached as SCM_RIGHTS is
142  * postponed to the taskqueue, to avoid arbitrary recursion depth.
143  * The attached sockets might have another sockets attached.
144  */
145 static struct task	unp_defer_task;
146 
147 /*
148  * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
149  * stream sockets, although the total for sender and receiver is actually
150  * only PIPSIZ.
151  *
152  * Datagram sockets really use the sendspace as the maximum datagram size,
153  * and don't really want to reserve the sendspace.  Their recvspace should be
154  * large enough for at least one max-size datagram plus address.
155  */
156 #ifndef PIPSIZ
157 #define	PIPSIZ	8192
158 #endif
159 static u_long	unpst_sendspace = PIPSIZ;
160 static u_long	unpst_recvspace = PIPSIZ;
161 static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
162 static u_long	unpdg_recvspace = 4*1024;
163 static u_long	unpsp_sendspace = PIPSIZ;	/* really max datagram size */
164 static u_long	unpsp_recvspace = PIPSIZ;
165 
166 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
167 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0,
168     "SOCK_STREAM");
169 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
170 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, CTLFLAG_RW, 0,
171     "SOCK_SEQPACKET");
172 
173 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
174 	   &unpst_sendspace, 0, "Default stream send space.");
175 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
176 	   &unpst_recvspace, 0, "Default stream receive space.");
177 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
178 	   &unpdg_sendspace, 0, "Default datagram send space.");
179 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
180 	   &unpdg_recvspace, 0, "Default datagram receive space.");
181 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
182 	   &unpsp_sendspace, 0, "Default seqpacket send space.");
183 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
184 	   &unpsp_recvspace, 0, "Default seqpacket receive space.");
185 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
186     "File descriptors in flight.");
187 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
188     &unp_defers_count, 0,
189     "File descriptors deferred to taskqueue for close.");
190 
191 /*
192  * Locking and synchronization:
193  *
194  * Three types of locks exist in the local domain socket implementation: a
195  * a global linkage rwlock, the mtxpool lock, and per-unpcb mutexes.
196  * The linkage lock protects the socket count, global generation number,
197  * and stream/datagram global lists.
198  *
199  * The mtxpool lock protects the vnode from being modified while referenced.
200  * Lock ordering requires that it be acquired before any unpcb locks.
201  *
202  * The unpcb lock (unp_mtx) protects all fields in the unpcb. Of particular
203  * note is that this includes the unp_conn field. So long as the unpcb lock
204  * is held the reference to the unpcb pointed to by unp_conn is valid. If we
205  * require that the unpcb pointed to by unp_conn remain live in cases where
206  * we need to drop the unp_mtx as when we need to acquire the lock for a
207  * second unpcb the caller must first acquire an additional reference on the
208  * second unpcb and then revalidate any state (typically check that unp_conn
209  * is non-NULL) upon requiring the initial unpcb lock. The lock ordering
210  * between unpcbs is the conventional ascending address order. Two helper
211  * routines exist for this:
212  *
213  *   - unp_pcb_lock2(unp, unp2) - which just acquires the two locks in the
214  *     safe ordering.
215  *
216  *   - unp_pcb_owned_lock2(unp, unp2, freed) - the lock for unp is held
217  *     when called. If unp is unlocked and unp2 is subsequently freed
218  *     freed will be set to 1.
219  *
220  * The helper routines for references are:
221  *
222  *   - unp_pcb_hold(unp): Can be called any time we currently hold a valid
223  *     reference to unp.
224  *
225  *    - unp_pcb_rele(unp): The caller must hold the unp lock. If we are
226  *      releasing the last reference, detach must have been called thus
227  *      unp->unp_socket be NULL.
228  *
229  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
230  * allocated in pru_attach() and freed in pru_detach().  The validity of that
231  * pointer is an invariant, so no lock is required to dereference the so_pcb
232  * pointer if a valid socket reference is held by the caller.  In practice,
233  * this is always true during operations performed on a socket.  Each unpcb
234  * has a back-pointer to its socket, unp_socket, which will be stable under
235  * the same circumstances.
236  *
237  * This pointer may only be safely dereferenced as long as a valid reference
238  * to the unpcb is held.  Typically, this reference will be from the socket,
239  * or from another unpcb when the referring unpcb's lock is held (in order
240  * that the reference not be invalidated during use).  For example, to follow
241  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
242  * that detach is not run clearing unp_socket.
243  *
244  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
245  * protocols, bind() is a non-atomic operation, and connect() requires
246  * potential sleeping in the protocol, due to potentially waiting on local or
247  * distributed file systems.  We try to separate "lookup" operations, which
248  * may sleep, and the IPC operations themselves, which typically can occur
249  * with relative atomicity as locks can be held over the entire operation.
250  *
251  * Another tricky issue is simultaneous multi-threaded or multi-process
252  * access to a single UNIX domain socket.  These are handled by the flags
253  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
254  * binding, both of which involve dropping UNIX domain socket locks in order
255  * to perform namei() and other file system operations.
256  */
257 static struct rwlock	unp_link_rwlock;
258 static struct mtx	unp_defers_lock;
259 
260 #define	UNP_LINK_LOCK_INIT()		rw_init(&unp_link_rwlock,	\
261 					    "unp_link_rwlock")
262 
263 #define	UNP_LINK_LOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
264 					    RA_LOCKED)
265 #define	UNP_LINK_UNLOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
266 					    RA_UNLOCKED)
267 
268 #define	UNP_LINK_RLOCK()		rw_rlock(&unp_link_rwlock)
269 #define	UNP_LINK_RUNLOCK()		rw_runlock(&unp_link_rwlock)
270 #define	UNP_LINK_WLOCK()		rw_wlock(&unp_link_rwlock)
271 #define	UNP_LINK_WUNLOCK()		rw_wunlock(&unp_link_rwlock)
272 #define	UNP_LINK_WLOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
273 					    RA_WLOCKED)
274 #define	UNP_LINK_WOWNED()		rw_wowned(&unp_link_rwlock)
275 
276 #define	UNP_DEFERRED_LOCK_INIT()	mtx_init(&unp_defers_lock, \
277 					    "unp_defer", NULL, MTX_DEF)
278 #define	UNP_DEFERRED_LOCK()		mtx_lock(&unp_defers_lock)
279 #define	UNP_DEFERRED_UNLOCK()		mtx_unlock(&unp_defers_lock)
280 
281 #define UNP_REF_LIST_LOCK()		UNP_DEFERRED_LOCK();
282 #define UNP_REF_LIST_UNLOCK()		UNP_DEFERRED_UNLOCK();
283 
284 #define UNP_PCB_LOCK_INIT(unp)		mtx_init(&(unp)->unp_mtx,	\
285 					    "unp", "unp",	\
286 					    MTX_DUPOK|MTX_DEF)
287 #define	UNP_PCB_LOCK_DESTROY(unp)	mtx_destroy(&(unp)->unp_mtx)
288 #define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
289 #define	UNP_PCB_TRYLOCK(unp)		mtx_trylock(&(unp)->unp_mtx)
290 #define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
291 #define	UNP_PCB_OWNED(unp)		mtx_owned(&(unp)->unp_mtx)
292 #define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
293 #define	UNP_PCB_UNLOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
294 
295 static int	uipc_connect2(struct socket *, struct socket *);
296 static int	uipc_ctloutput(struct socket *, struct sockopt *);
297 static int	unp_connect(struct socket *, struct sockaddr *,
298 		    struct thread *);
299 static int	unp_connectat(int, struct socket *, struct sockaddr *,
300 		    struct thread *);
301 static int	unp_connect2(struct socket *so, struct socket *so2, int);
302 static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
303 static void	unp_dispose(struct socket *so);
304 static void	unp_dispose_mbuf(struct mbuf *);
305 static void	unp_shutdown(struct unpcb *);
306 static void	unp_drop(struct unpcb *);
307 static void	unp_gc(__unused void *, int);
308 static void	unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
309 static void	unp_discard(struct file *);
310 static void	unp_freerights(struct filedescent **, int);
311 static void	unp_init(void);
312 static int	unp_internalize(struct mbuf **, struct thread *);
313 static void	unp_internalize_fp(struct file *);
314 static int	unp_externalize(struct mbuf *, struct mbuf **, int);
315 static int	unp_externalize_fp(struct file *);
316 static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *);
317 static void	unp_process_defers(void * __unused, int);
318 
319 
320 static void
321 unp_pcb_hold(struct unpcb *unp)
322 {
323 	MPASS(unp->unp_refcount);
324 	refcount_acquire(&unp->unp_refcount);
325 }
326 
327 static int
328 unp_pcb_rele(struct unpcb *unp)
329 {
330 	int freed;
331 
332 	UNP_PCB_LOCK_ASSERT(unp);
333 	MPASS(unp->unp_refcount);
334 	if ((freed = refcount_release(&unp->unp_refcount))) {
335 		/* we got here with having detached? */
336 		MPASS(unp->unp_socket == NULL);
337 		UNP_PCB_UNLOCK(unp);
338 		UNP_PCB_LOCK_DESTROY(unp);
339 		uma_zfree(unp_zone, unp);
340 	}
341 	return (freed);
342 }
343 
344 static void
345 unp_pcb_lock2(struct unpcb *unp, struct unpcb *unp2)
346 {
347 	MPASS(unp != unp2);
348 	UNP_PCB_UNLOCK_ASSERT(unp);
349 	UNP_PCB_UNLOCK_ASSERT(unp2);
350 	if ((uintptr_t)unp2 > (uintptr_t)unp) {
351 		UNP_PCB_LOCK(unp);
352 		UNP_PCB_LOCK(unp2);
353 	} else {
354 		UNP_PCB_LOCK(unp2);
355 		UNP_PCB_LOCK(unp);
356 	}
357 }
358 
359 static __noinline void
360 unp_pcb_owned_lock2_slowpath(struct unpcb *unp, struct unpcb **unp2p, int *freed)
361 
362 {
363 	struct unpcb *unp2;
364 
365 	unp2 = *unp2p;
366 	unp_pcb_hold((unp2));
367 	UNP_PCB_UNLOCK((unp));
368 	UNP_PCB_LOCK((unp2));
369 	UNP_PCB_LOCK((unp));
370 	*freed = unp_pcb_rele((unp2));
371 	if (*freed)
372 		*unp2p = NULL;
373 }
374 
375 #define unp_pcb_owned_lock2(unp, unp2, freed) do {					\
376 		freed = 0;													\
377 		UNP_PCB_LOCK_ASSERT((unp));									\
378 		UNP_PCB_UNLOCK_ASSERT((unp2));								\
379 		MPASS(unp != unp2);											\
380 		if (__predict_true(UNP_PCB_TRYLOCK((unp2))))				\
381 			break;													\
382 		else if ((uintptr_t)(unp2) > (uintptr_t)(unp))				\
383 			UNP_PCB_LOCK((unp2));									\
384 		else {														\
385 			unp_pcb_owned_lock2_slowpath((unp), &(unp2), &freed);	\
386 		}															\
387 } while (0)
388 
389 
390 /*
391  * Definitions of protocols supported in the LOCAL domain.
392  */
393 static struct domain localdomain;
394 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
395 static struct pr_usrreqs uipc_usrreqs_seqpacket;
396 static struct protosw localsw[] = {
397 {
398 	.pr_type =		SOCK_STREAM,
399 	.pr_domain =		&localdomain,
400 	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
401 	.pr_ctloutput =		&uipc_ctloutput,
402 	.pr_usrreqs =		&uipc_usrreqs_stream
403 },
404 {
405 	.pr_type =		SOCK_DGRAM,
406 	.pr_domain =		&localdomain,
407 	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS,
408 	.pr_ctloutput =		&uipc_ctloutput,
409 	.pr_usrreqs =		&uipc_usrreqs_dgram
410 },
411 {
412 	.pr_type =		SOCK_SEQPACKET,
413 	.pr_domain =		&localdomain,
414 
415 	/*
416 	 * XXXRW: For now, PR_ADDR because soreceive will bump into them
417 	 * due to our use of sbappendaddr.  A new sbappend variants is needed
418 	 * that supports both atomic record writes and control data.
419 	 */
420 	.pr_flags =		PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
421 				    PR_RIGHTS,
422 	.pr_ctloutput =		&uipc_ctloutput,
423 	.pr_usrreqs =		&uipc_usrreqs_seqpacket,
424 },
425 };
426 
427 static struct domain localdomain = {
428 	.dom_family =		AF_LOCAL,
429 	.dom_name =		"local",
430 	.dom_init =		unp_init,
431 	.dom_externalize =	unp_externalize,
432 	.dom_dispose =		unp_dispose,
433 	.dom_protosw =		localsw,
434 	.dom_protoswNPROTOSW =	&localsw[nitems(localsw)]
435 };
436 DOMAIN_SET(local);
437 
438 static void
439 uipc_abort(struct socket *so)
440 {
441 	struct unpcb *unp, *unp2;
442 
443 	unp = sotounpcb(so);
444 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
445 	UNP_PCB_UNLOCK_ASSERT(unp);
446 
447 	UNP_PCB_LOCK(unp);
448 	unp2 = unp->unp_conn;
449 	if (unp2 != NULL) {
450 		unp_pcb_hold(unp2);
451 		UNP_PCB_UNLOCK(unp);
452 		unp_drop(unp2);
453 	} else
454 		UNP_PCB_UNLOCK(unp);
455 }
456 
457 static int
458 uipc_accept(struct socket *so, struct sockaddr **nam)
459 {
460 	struct unpcb *unp, *unp2;
461 	const struct sockaddr *sa;
462 
463 	/*
464 	 * Pass back name of connected socket, if it was bound and we are
465 	 * still connected (our peer may have closed already!).
466 	 */
467 	unp = sotounpcb(so);
468 	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
469 
470 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
471 	UNP_LINK_RLOCK();
472 	unp2 = unp->unp_conn;
473 	if (unp2 != NULL && unp2->unp_addr != NULL) {
474 		UNP_PCB_LOCK(unp2);
475 		sa = (struct sockaddr *) unp2->unp_addr;
476 		bcopy(sa, *nam, sa->sa_len);
477 		UNP_PCB_UNLOCK(unp2);
478 	} else {
479 		sa = &sun_noname;
480 		bcopy(sa, *nam, sa->sa_len);
481 	}
482 	UNP_LINK_RUNLOCK();
483 	return (0);
484 }
485 
486 static int
487 uipc_attach(struct socket *so, int proto, struct thread *td)
488 {
489 	u_long sendspace, recvspace;
490 	struct unpcb *unp;
491 	int error;
492 	bool locked;
493 
494 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
495 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
496 		switch (so->so_type) {
497 		case SOCK_STREAM:
498 			sendspace = unpst_sendspace;
499 			recvspace = unpst_recvspace;
500 			break;
501 
502 		case SOCK_DGRAM:
503 			sendspace = unpdg_sendspace;
504 			recvspace = unpdg_recvspace;
505 			break;
506 
507 		case SOCK_SEQPACKET:
508 			sendspace = unpsp_sendspace;
509 			recvspace = unpsp_recvspace;
510 			break;
511 
512 		default:
513 			panic("uipc_attach");
514 		}
515 		error = soreserve(so, sendspace, recvspace);
516 		if (error)
517 			return (error);
518 	}
519 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
520 	if (unp == NULL)
521 		return (ENOBUFS);
522 	LIST_INIT(&unp->unp_refs);
523 	UNP_PCB_LOCK_INIT(unp);
524 	unp->unp_socket = so;
525 	so->so_pcb = unp;
526 	unp->unp_refcount = 1;
527 	if (so->so_listen != NULL)
528 		unp->unp_flags |= UNP_NASCENT;
529 
530 	if ((locked = UNP_LINK_WOWNED()) == false)
531 		UNP_LINK_WLOCK();
532 
533 	unp->unp_gencnt = ++unp_gencnt;
534 	unp_count++;
535 	switch (so->so_type) {
536 	case SOCK_STREAM:
537 		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
538 		break;
539 
540 	case SOCK_DGRAM:
541 		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
542 		break;
543 
544 	case SOCK_SEQPACKET:
545 		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
546 		break;
547 
548 	default:
549 		panic("uipc_attach");
550 	}
551 
552 	if (locked == false)
553 		UNP_LINK_WUNLOCK();
554 
555 	return (0);
556 }
557 
558 static int
559 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
560 {
561 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
562 	struct vattr vattr;
563 	int error, namelen;
564 	struct nameidata nd;
565 	struct unpcb *unp;
566 	struct vnode *vp;
567 	struct mount *mp;
568 	cap_rights_t rights;
569 	char *buf;
570 
571 	if (nam->sa_family != AF_UNIX)
572 		return (EAFNOSUPPORT);
573 
574 	unp = sotounpcb(so);
575 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
576 
577 	if (soun->sun_len > sizeof(struct sockaddr_un))
578 		return (EINVAL);
579 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
580 	if (namelen <= 0)
581 		return (EINVAL);
582 
583 	/*
584 	 * We don't allow simultaneous bind() calls on a single UNIX domain
585 	 * socket, so flag in-progress operations, and return an error if an
586 	 * operation is already in progress.
587 	 *
588 	 * Historically, we have not allowed a socket to be rebound, so this
589 	 * also returns an error.  Not allowing re-binding simplifies the
590 	 * implementation and avoids a great many possible failure modes.
591 	 */
592 	UNP_PCB_LOCK(unp);
593 	if (unp->unp_vnode != NULL) {
594 		UNP_PCB_UNLOCK(unp);
595 		return (EINVAL);
596 	}
597 	if (unp->unp_flags & UNP_BINDING) {
598 		UNP_PCB_UNLOCK(unp);
599 		return (EALREADY);
600 	}
601 	unp->unp_flags |= UNP_BINDING;
602 	UNP_PCB_UNLOCK(unp);
603 
604 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
605 	bcopy(soun->sun_path, buf, namelen);
606 	buf[namelen] = 0;
607 
608 restart:
609 	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
610 	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
611 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
612 	error = namei(&nd);
613 	if (error)
614 		goto error;
615 	vp = nd.ni_vp;
616 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
617 		NDFREE(&nd, NDF_ONLY_PNBUF);
618 		if (nd.ni_dvp == vp)
619 			vrele(nd.ni_dvp);
620 		else
621 			vput(nd.ni_dvp);
622 		if (vp != NULL) {
623 			vrele(vp);
624 			error = EADDRINUSE;
625 			goto error;
626 		}
627 		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
628 		if (error)
629 			goto error;
630 		goto restart;
631 	}
632 	VATTR_NULL(&vattr);
633 	vattr.va_type = VSOCK;
634 	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
635 #ifdef MAC
636 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
637 	    &vattr);
638 #endif
639 	if (error == 0)
640 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
641 	NDFREE(&nd, NDF_ONLY_PNBUF);
642 	vput(nd.ni_dvp);
643 	if (error) {
644 		vn_finished_write(mp);
645 		goto error;
646 	}
647 	vp = nd.ni_vp;
648 	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
649 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
650 
651 	UNP_PCB_LOCK(unp);
652 	VOP_UNP_BIND(vp, unp);
653 	unp->unp_vnode = vp;
654 	unp->unp_addr = soun;
655 	unp->unp_flags &= ~UNP_BINDING;
656 	UNP_PCB_UNLOCK(unp);
657 	VOP_UNLOCK(vp, 0);
658 	vn_finished_write(mp);
659 	free(buf, M_TEMP);
660 	return (0);
661 
662 error:
663 	UNP_PCB_LOCK(unp);
664 	unp->unp_flags &= ~UNP_BINDING;
665 	UNP_PCB_UNLOCK(unp);
666 	free(buf, M_TEMP);
667 	return (error);
668 }
669 
670 static int
671 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
672 {
673 
674 	return (uipc_bindat(AT_FDCWD, so, nam, td));
675 }
676 
677 static int
678 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
679 {
680 	int error;
681 
682 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
683 	error = unp_connect(so, nam, td);
684 	return (error);
685 }
686 
687 static int
688 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
689     struct thread *td)
690 {
691 	int error;
692 
693 	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
694 	error = unp_connectat(fd, so, nam, td);
695 	return (error);
696 }
697 
698 static void
699 uipc_close(struct socket *so)
700 {
701 	struct unpcb *unp, *unp2;
702 	struct vnode *vp = NULL;
703 	struct mtx *vplock;
704 	int freed;
705 	unp = sotounpcb(so);
706 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
707 
708 
709 	vplock = NULL;
710 	if ((vp = unp->unp_vnode) != NULL) {
711 		vplock = mtx_pool_find(mtxpool_sleep, vp);
712 		mtx_lock(vplock);
713 	}
714 	UNP_PCB_LOCK(unp);
715 	if (vp && unp->unp_vnode == NULL) {
716 		mtx_unlock(vplock);
717 		vp = NULL;
718 	}
719 	if (vp != NULL) {
720 		VOP_UNP_DETACH(vp);
721 		unp->unp_vnode = NULL;
722 	}
723 	unp2 = unp->unp_conn;
724 	unp_pcb_hold(unp);
725 	if (__predict_false(unp == unp2)) {
726 		unp_disconnect(unp, unp2);
727 	} else if (unp2 != NULL) {
728 		unp_pcb_hold(unp2);
729 		unp_pcb_owned_lock2(unp, unp2, freed);
730 		unp_disconnect(unp, unp2);
731 		if (unp_pcb_rele(unp2) == 0)
732 			UNP_PCB_UNLOCK(unp2);
733 	}
734 	if (unp_pcb_rele(unp) == 0)
735 		UNP_PCB_UNLOCK(unp);
736 	if (vp) {
737 		mtx_unlock(vplock);
738 		vrele(vp);
739 	}
740 }
741 
742 static int
743 uipc_connect2(struct socket *so1, struct socket *so2)
744 {
745 	struct unpcb *unp, *unp2;
746 	int error;
747 
748 	unp = so1->so_pcb;
749 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
750 	unp2 = so2->so_pcb;
751 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
752 	if (unp != unp2)
753 		unp_pcb_lock2(unp, unp2);
754 	else
755 		UNP_PCB_LOCK(unp);
756 	error = unp_connect2(so1, so2, PRU_CONNECT2);
757 	if (unp != unp2)
758 		UNP_PCB_UNLOCK(unp2);
759 	UNP_PCB_UNLOCK(unp);
760 	return (error);
761 }
762 
763 static void
764 uipc_detach(struct socket *so)
765 {
766 	struct unpcb *unp, *unp2;
767 	struct mtx *vplock;
768 	struct sockaddr_un *saved_unp_addr;
769 	struct vnode *vp;
770 	int freeunp, local_unp_rights;
771 
772 	unp = sotounpcb(so);
773 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
774 
775 	vp = NULL;
776 	vplock = NULL;
777 	local_unp_rights = 0;
778 
779 	UNP_LINK_WLOCK();
780 	LIST_REMOVE(unp, unp_link);
781 	unp->unp_gencnt = ++unp_gencnt;
782 	--unp_count;
783 	UNP_LINK_WUNLOCK();
784 
785 	UNP_PCB_UNLOCK_ASSERT(unp);
786  restart:
787 	if ((vp = unp->unp_vnode) != NULL) {
788 		vplock = mtx_pool_find(mtxpool_sleep, vp);
789 		mtx_lock(vplock);
790 	}
791 	UNP_PCB_LOCK(unp);
792 	if (unp->unp_vnode != vp &&
793 		unp->unp_vnode != NULL) {
794 		if (vplock)
795 			mtx_unlock(vplock);
796 		UNP_PCB_UNLOCK(unp);
797 		goto restart;
798 	}
799 	if ((unp->unp_flags & UNP_NASCENT) != 0) {
800 		goto teardown;
801 	}
802 	if ((vp = unp->unp_vnode) != NULL) {
803 		VOP_UNP_DETACH(vp);
804 		unp->unp_vnode = NULL;
805 	}
806 	if (__predict_false(unp == unp->unp_conn)) {
807 		unp_disconnect(unp, unp);
808 		unp2 = NULL;
809 		goto connect_self;
810 	}
811 	if ((unp2 = unp->unp_conn) != NULL) {
812 		unp_pcb_owned_lock2(unp, unp2, freeunp);
813 		if (freeunp)
814 			unp2 = NULL;
815 	}
816 	unp_pcb_hold(unp);
817 	if (unp2 != NULL) {
818 		unp_pcb_hold(unp2);
819 		unp_disconnect(unp, unp2);
820 		if (unp_pcb_rele(unp2) == 0)
821 			UNP_PCB_UNLOCK(unp2);
822 	}
823  connect_self:
824 	UNP_PCB_UNLOCK(unp);
825 	UNP_REF_LIST_LOCK();
826 	while (!LIST_EMPTY(&unp->unp_refs)) {
827 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
828 
829 		unp_pcb_hold(ref);
830 		UNP_REF_LIST_UNLOCK();
831 
832 		MPASS(ref != unp);
833 		UNP_PCB_UNLOCK_ASSERT(ref);
834 		unp_drop(ref);
835 		UNP_REF_LIST_LOCK();
836 	}
837 
838 	UNP_REF_LIST_UNLOCK();
839 	UNP_PCB_LOCK(unp);
840 	freeunp = unp_pcb_rele(unp);
841 	MPASS(freeunp == 0);
842 	local_unp_rights = unp_rights;
843 teardown:
844 	unp->unp_socket->so_pcb = NULL;
845 	saved_unp_addr = unp->unp_addr;
846 	unp->unp_addr = NULL;
847 	unp->unp_socket = NULL;
848 	freeunp = unp_pcb_rele(unp);
849 	if (saved_unp_addr != NULL)
850 		free(saved_unp_addr, M_SONAME);
851 	if (!freeunp)
852 		UNP_PCB_UNLOCK(unp);
853 	if (vp) {
854 		mtx_unlock(vplock);
855 		vrele(vp);
856 	}
857 	if (local_unp_rights)
858 		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
859 }
860 
861 static int
862 uipc_disconnect(struct socket *so)
863 {
864 	struct unpcb *unp, *unp2;
865 	int freed;
866 
867 	unp = sotounpcb(so);
868 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
869 
870 	UNP_PCB_LOCK(unp);
871 	if ((unp2 = unp->unp_conn) == NULL) {
872 		UNP_PCB_UNLOCK(unp);
873 		return (0);
874 	}
875 	if (unp == unp2) {
876 		if (unp_pcb_rele(unp) == 0)
877 			UNP_PCB_UNLOCK(unp);
878 	}
879 	unp_pcb_owned_lock2(unp, unp2, freed);
880 	if (__predict_false(freed)) {
881 		UNP_PCB_UNLOCK(unp);
882 		return (0);
883 	}
884 	unp_pcb_hold(unp2);
885 	unp_pcb_hold(unp);
886 	unp_disconnect(unp, unp2);
887 	if (unp_pcb_rele(unp) == 0)
888 		UNP_PCB_UNLOCK(unp);
889 	if (unp_pcb_rele(unp2) == 0)
890 		UNP_PCB_UNLOCK(unp2);
891 	return (0);
892 }
893 
894 static int
895 uipc_listen(struct socket *so, int backlog, struct thread *td)
896 {
897 	struct unpcb *unp;
898 	int error;
899 
900 	if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
901 		return (EOPNOTSUPP);
902 
903 	unp = sotounpcb(so);
904 	KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
905 
906 	UNP_PCB_LOCK(unp);
907 	if (unp->unp_vnode == NULL) {
908 		/* Already connected or not bound to an address. */
909 		error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
910 		UNP_PCB_UNLOCK(unp);
911 		return (error);
912 	}
913 
914 	SOCK_LOCK(so);
915 	error = solisten_proto_check(so);
916 	if (error == 0) {
917 		cru2x(td->td_ucred, &unp->unp_peercred);
918 		solisten_proto(so, backlog);
919 	}
920 	SOCK_UNLOCK(so);
921 	UNP_PCB_UNLOCK(unp);
922 	return (error);
923 }
924 
925 static int
926 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
927 {
928 	struct unpcb *unp, *unp2;
929 	const struct sockaddr *sa;
930 
931 	unp = sotounpcb(so);
932 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
933 
934 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
935 	UNP_LINK_RLOCK();
936 	/*
937 	 * XXX: It seems that this test always fails even when connection is
938 	 * established.  So, this else clause is added as workaround to
939 	 * return PF_LOCAL sockaddr.
940 	 */
941 	unp2 = unp->unp_conn;
942 	if (unp2 != NULL) {
943 		UNP_PCB_LOCK(unp2);
944 		if (unp2->unp_addr != NULL)
945 			sa = (struct sockaddr *) unp2->unp_addr;
946 		else
947 			sa = &sun_noname;
948 		bcopy(sa, *nam, sa->sa_len);
949 		UNP_PCB_UNLOCK(unp2);
950 	} else {
951 		sa = &sun_noname;
952 		bcopy(sa, *nam, sa->sa_len);
953 	}
954 	UNP_LINK_RUNLOCK();
955 	return (0);
956 }
957 
958 static int
959 uipc_rcvd(struct socket *so, int flags)
960 {
961 	struct unpcb *unp, *unp2;
962 	struct socket *so2;
963 	u_int mbcnt, sbcc;
964 
965 	unp = sotounpcb(so);
966 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
967 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
968 	    ("%s: socktype %d", __func__, so->so_type));
969 
970 	/*
971 	 * Adjust backpressure on sender and wakeup any waiting to write.
972 	 *
973 	 * The unp lock is acquired to maintain the validity of the unp_conn
974 	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
975 	 * static as long as we don't permit unp2 to disconnect from unp,
976 	 * which is prevented by the lock on unp.  We cache values from
977 	 * so_rcv to avoid holding the so_rcv lock over the entire
978 	 * transaction on the remote so_snd.
979 	 */
980 	SOCKBUF_LOCK(&so->so_rcv);
981 	mbcnt = so->so_rcv.sb_mbcnt;
982 	sbcc = sbavail(&so->so_rcv);
983 	SOCKBUF_UNLOCK(&so->so_rcv);
984 	/*
985 	 * There is a benign race condition at this point.  If we're planning to
986 	 * clear SB_STOP, but uipc_send is called on the connected socket at
987 	 * this instant, it might add data to the sockbuf and set SB_STOP.  Then
988 	 * we would erroneously clear SB_STOP below, even though the sockbuf is
989 	 * full.  The race is benign because the only ill effect is to allow the
990 	 * sockbuf to exceed its size limit, and the size limits are not
991 	 * strictly guaranteed anyway.
992 	 */
993 	UNP_PCB_LOCK(unp);
994 	unp2 = unp->unp_conn;
995 	if (unp2 == NULL) {
996 		UNP_PCB_UNLOCK(unp);
997 		return (0);
998 	}
999 	so2 = unp2->unp_socket;
1000 	SOCKBUF_LOCK(&so2->so_snd);
1001 	if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
1002 		so2->so_snd.sb_flags &= ~SB_STOP;
1003 	sowwakeup_locked(so2);
1004 	UNP_PCB_UNLOCK(unp);
1005 	return (0);
1006 }
1007 
1008 static int
1009 connect_internal(struct socket *so, struct sockaddr *nam, struct thread *td)
1010 {
1011 	int error;
1012 	struct unpcb *unp;
1013 
1014 	unp = so->so_pcb;
1015 	if (unp->unp_conn != NULL)
1016 		return (EISCONN);
1017 	error = unp_connect(so, nam, td);
1018 	if (error)
1019 		return (error);
1020 	UNP_PCB_LOCK(unp);
1021 	if (unp->unp_conn == NULL) {
1022 		UNP_PCB_UNLOCK(unp);
1023 		if (error == 0)
1024 			error = ENOTCONN;
1025 	}
1026 	return (error);
1027 }
1028 
1029 
1030 static int
1031 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1032     struct mbuf *control, struct thread *td)
1033 {
1034 	struct unpcb *unp, *unp2;
1035 	struct socket *so2;
1036 	u_int mbcnt, sbcc;
1037 	int freed, error;
1038 
1039 	unp = sotounpcb(so);
1040 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
1041 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
1042 	    so->so_type == SOCK_SEQPACKET,
1043 	    ("%s: socktype %d", __func__, so->so_type));
1044 
1045 	freed = error = 0;
1046 	if (flags & PRUS_OOB) {
1047 		error = EOPNOTSUPP;
1048 		goto release;
1049 	}
1050 	if (control != NULL && (error = unp_internalize(&control, td)))
1051 		goto release;
1052 
1053 	unp2 = NULL;
1054 	switch (so->so_type) {
1055 	case SOCK_DGRAM:
1056 	{
1057 		const struct sockaddr *from;
1058 
1059 		if (nam != NULL) {
1060 			/*
1061 			 * We return with UNP_PCB_LOCK_HELD so we know that
1062 			 * the reference is live if the pointer is valid.
1063 			 */
1064 			if ((error = connect_internal(so, nam, td)))
1065 				break;
1066 			MPASS(unp->unp_conn != NULL);
1067 			unp2 = unp->unp_conn;
1068 		} else  {
1069 			UNP_PCB_LOCK(unp);
1070 
1071 			/*
1072 			 * Because connect() and send() are non-atomic in a sendto()
1073 			 * with a target address, it's possible that the socket will
1074 			 * have disconnected before the send() can run.  In that case
1075 			 * return the slightly counter-intuitive but otherwise
1076 			 * correct error that the socket is not connected.
1077 			 */
1078 			if ((unp2 = unp->unp_conn)  == NULL) {
1079 				UNP_PCB_UNLOCK(unp);
1080 				error = ENOTCONN;
1081 				break;
1082 			}
1083 		}
1084 		if (__predict_false(unp == unp2)) {
1085 			if (unp->unp_socket == NULL) {
1086 				error = ENOTCONN;
1087 				break;
1088 			}
1089 			goto connect_self;
1090 		}
1091 		unp_pcb_owned_lock2(unp, unp2, freed);
1092 		if (__predict_false(freed)) {
1093 			UNP_PCB_UNLOCK(unp);
1094 			error = ENOTCONN;
1095 			break;
1096 		}
1097 		/*
1098 		 * The socket referencing unp2 may have been closed
1099 		 * or unp may have been disconnected if the unp lock
1100 		 * was dropped to acquire unp2.
1101 		 */
1102 		if (__predict_false(unp->unp_conn == NULL) ||
1103 			unp2->unp_socket == NULL) {
1104 			UNP_PCB_UNLOCK(unp);
1105 			if (unp_pcb_rele(unp2) == 0)
1106 				UNP_PCB_UNLOCK(unp2);
1107 			error = ENOTCONN;
1108 			break;
1109 		}
1110 	connect_self:
1111 		if (unp2->unp_flags & UNP_WANTCRED)
1112 			control = unp_addsockcred(td, control);
1113 		if (unp->unp_addr != NULL)
1114 			from = (struct sockaddr *)unp->unp_addr;
1115 		else
1116 			from = &sun_noname;
1117 		so2 = unp2->unp_socket;
1118 		SOCKBUF_LOCK(&so2->so_rcv);
1119 		if (sbappendaddr_locked(&so2->so_rcv, from, m,
1120 		    control)) {
1121 			sorwakeup_locked(so2);
1122 			m = NULL;
1123 			control = NULL;
1124 		} else {
1125 			SOCKBUF_UNLOCK(&so2->so_rcv);
1126 			error = ENOBUFS;
1127 		}
1128 		if (nam != NULL)
1129 			unp_disconnect(unp, unp2);
1130 		if (__predict_true(unp != unp2))
1131 			UNP_PCB_UNLOCK(unp2);
1132 		UNP_PCB_UNLOCK(unp);
1133 		break;
1134 	}
1135 
1136 	case SOCK_SEQPACKET:
1137 	case SOCK_STREAM:
1138 		if ((so->so_state & SS_ISCONNECTED) == 0) {
1139 			if (nam != NULL) {
1140 				if ((error = connect_internal(so, nam, td)))
1141 					break;
1142 			} else  {
1143 				error = ENOTCONN;
1144 				break;
1145 			}
1146 		} else if ((unp2 = unp->unp_conn) == NULL) {
1147 			error = ENOTCONN;
1148 			break;
1149 		} else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1150 			error = EPIPE;
1151 			break;
1152 		} else {
1153 			UNP_PCB_LOCK(unp);
1154 			if ((unp2 = unp->unp_conn) == NULL) {
1155 				UNP_PCB_UNLOCK(unp);
1156 				error = ENOTCONN;
1157 				break;
1158 			}
1159 		}
1160 		unp_pcb_owned_lock2(unp, unp2, freed);
1161 		UNP_PCB_UNLOCK(unp);
1162 		if (__predict_false(freed)) {
1163 			error = ENOTCONN;
1164 			break;
1165 		}
1166 		if ((so2 = unp2->unp_socket) == NULL) {
1167 			UNP_PCB_UNLOCK(unp2);
1168 			error = ENOTCONN;
1169 			break;
1170 		}
1171 		SOCKBUF_LOCK(&so2->so_rcv);
1172 		if (unp2->unp_flags & UNP_WANTCRED) {
1173 			/*
1174 			 * Credentials are passed only once on SOCK_STREAM
1175 			 * and SOCK_SEQPACKET.
1176 			 */
1177 			unp2->unp_flags &= ~UNP_WANTCRED;
1178 			control = unp_addsockcred(td, control);
1179 		}
1180 		/*
1181 		 * Send to paired receive port, and then reduce send buffer
1182 		 * hiwater marks to maintain backpressure.  Wake up readers.
1183 		 */
1184 		switch (so->so_type) {
1185 		case SOCK_STREAM:
1186 			if (control != NULL) {
1187 				if (sbappendcontrol_locked(&so2->so_rcv, m,
1188 				    control))
1189 					control = NULL;
1190 			} else
1191 				sbappend_locked(&so2->so_rcv, m, flags);
1192 			break;
1193 
1194 		case SOCK_SEQPACKET: {
1195 			const struct sockaddr *from;
1196 
1197 			from = &sun_noname;
1198 			/*
1199 			 * Don't check for space available in so2->so_rcv.
1200 			 * Unix domain sockets only check for space in the
1201 			 * sending sockbuf, and that check is performed one
1202 			 * level up the stack.
1203 			 */
1204 			if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1205 				from, m, control))
1206 				control = NULL;
1207 			break;
1208 			}
1209 		}
1210 
1211 		mbcnt = so2->so_rcv.sb_mbcnt;
1212 		sbcc = sbavail(&so2->so_rcv);
1213 		if (sbcc)
1214 			sorwakeup_locked(so2);
1215 		else
1216 			SOCKBUF_UNLOCK(&so2->so_rcv);
1217 
1218 		/*
1219 		 * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1220 		 * it would be possible for uipc_rcvd to be called at this
1221 		 * point, drain the receiving sockbuf, clear SB_STOP, and then
1222 		 * we would set SB_STOP below.  That could lead to an empty
1223 		 * sockbuf having SB_STOP set
1224 		 */
1225 		SOCKBUF_LOCK(&so->so_snd);
1226 		if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1227 			so->so_snd.sb_flags |= SB_STOP;
1228 		SOCKBUF_UNLOCK(&so->so_snd);
1229 		UNP_PCB_UNLOCK(unp2);
1230 		m = NULL;
1231 		break;
1232 	}
1233 
1234 	/*
1235 	 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1236 	 */
1237 	if (flags & PRUS_EOF) {
1238 		UNP_PCB_LOCK(unp);
1239 		socantsendmore(so);
1240 		unp_shutdown(unp);
1241 		UNP_PCB_UNLOCK(unp);
1242 	}
1243 	if (control != NULL && error != 0)
1244 		unp_dispose_mbuf(control);
1245 
1246 release:
1247 	if (control != NULL)
1248 		m_freem(control);
1249 	/*
1250 	 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1251 	 * for freeing memory.
1252 	 */
1253 	if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1254 		m_freem(m);
1255 	return (error);
1256 }
1257 
1258 static int
1259 uipc_ready(struct socket *so, struct mbuf *m, int count)
1260 {
1261 	struct unpcb *unp, *unp2;
1262 	struct socket *so2;
1263 	int error;
1264 
1265 	unp = sotounpcb(so);
1266 
1267 	UNP_LINK_RLOCK();
1268 	if ((unp2 = unp->unp_conn) == NULL) {
1269 		UNP_LINK_RUNLOCK();
1270 		for (int i = 0; i < count; i++)
1271 			m = m_free(m);
1272 		return (ECONNRESET);
1273 	}
1274 	UNP_PCB_LOCK(unp2);
1275 	so2 = unp2->unp_socket;
1276 
1277 	SOCKBUF_LOCK(&so2->so_rcv);
1278 	if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1279 		sorwakeup_locked(so2);
1280 	else
1281 		SOCKBUF_UNLOCK(&so2->so_rcv);
1282 
1283 	UNP_PCB_UNLOCK(unp2);
1284 	UNP_LINK_RUNLOCK();
1285 
1286 	return (error);
1287 }
1288 
1289 static int
1290 uipc_sense(struct socket *so, struct stat *sb)
1291 {
1292 	struct unpcb *unp;
1293 
1294 	unp = sotounpcb(so);
1295 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1296 
1297 	sb->st_blksize = so->so_snd.sb_hiwat;
1298 	UNP_PCB_LOCK(unp);
1299 	sb->st_dev = NODEV;
1300 	if (unp->unp_ino == 0)
1301 		unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
1302 	sb->st_ino = unp->unp_ino;
1303 	UNP_PCB_UNLOCK(unp);
1304 	return (0);
1305 }
1306 
1307 static int
1308 uipc_shutdown(struct socket *so)
1309 {
1310 	struct unpcb *unp;
1311 
1312 	unp = sotounpcb(so);
1313 	KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1314 
1315 	UNP_PCB_LOCK(unp);
1316 	socantsendmore(so);
1317 	unp_shutdown(unp);
1318 	UNP_PCB_UNLOCK(unp);
1319 	return (0);
1320 }
1321 
1322 static int
1323 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1324 {
1325 	struct unpcb *unp;
1326 	const struct sockaddr *sa;
1327 
1328 	unp = sotounpcb(so);
1329 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1330 
1331 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1332 	UNP_PCB_LOCK(unp);
1333 	if (unp->unp_addr != NULL)
1334 		sa = (struct sockaddr *) unp->unp_addr;
1335 	else
1336 		sa = &sun_noname;
1337 	bcopy(sa, *nam, sa->sa_len);
1338 	UNP_PCB_UNLOCK(unp);
1339 	return (0);
1340 }
1341 
1342 static struct pr_usrreqs uipc_usrreqs_dgram = {
1343 	.pru_abort = 		uipc_abort,
1344 	.pru_accept =		uipc_accept,
1345 	.pru_attach =		uipc_attach,
1346 	.pru_bind =		uipc_bind,
1347 	.pru_bindat =		uipc_bindat,
1348 	.pru_connect =		uipc_connect,
1349 	.pru_connectat =	uipc_connectat,
1350 	.pru_connect2 =		uipc_connect2,
1351 	.pru_detach =		uipc_detach,
1352 	.pru_disconnect =	uipc_disconnect,
1353 	.pru_listen =		uipc_listen,
1354 	.pru_peeraddr =		uipc_peeraddr,
1355 	.pru_rcvd =		uipc_rcvd,
1356 	.pru_send =		uipc_send,
1357 	.pru_sense =		uipc_sense,
1358 	.pru_shutdown =		uipc_shutdown,
1359 	.pru_sockaddr =		uipc_sockaddr,
1360 	.pru_soreceive =	soreceive_dgram,
1361 	.pru_close =		uipc_close,
1362 };
1363 
1364 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1365 	.pru_abort =		uipc_abort,
1366 	.pru_accept =		uipc_accept,
1367 	.pru_attach =		uipc_attach,
1368 	.pru_bind =		uipc_bind,
1369 	.pru_bindat =		uipc_bindat,
1370 	.pru_connect =		uipc_connect,
1371 	.pru_connectat =	uipc_connectat,
1372 	.pru_connect2 =		uipc_connect2,
1373 	.pru_detach =		uipc_detach,
1374 	.pru_disconnect =	uipc_disconnect,
1375 	.pru_listen =		uipc_listen,
1376 	.pru_peeraddr =		uipc_peeraddr,
1377 	.pru_rcvd =		uipc_rcvd,
1378 	.pru_send =		uipc_send,
1379 	.pru_sense =		uipc_sense,
1380 	.pru_shutdown =		uipc_shutdown,
1381 	.pru_sockaddr =		uipc_sockaddr,
1382 	.pru_soreceive =	soreceive_generic,	/* XXX: or...? */
1383 	.pru_close =		uipc_close,
1384 };
1385 
1386 static struct pr_usrreqs uipc_usrreqs_stream = {
1387 	.pru_abort = 		uipc_abort,
1388 	.pru_accept =		uipc_accept,
1389 	.pru_attach =		uipc_attach,
1390 	.pru_bind =		uipc_bind,
1391 	.pru_bindat =		uipc_bindat,
1392 	.pru_connect =		uipc_connect,
1393 	.pru_connectat =	uipc_connectat,
1394 	.pru_connect2 =		uipc_connect2,
1395 	.pru_detach =		uipc_detach,
1396 	.pru_disconnect =	uipc_disconnect,
1397 	.pru_listen =		uipc_listen,
1398 	.pru_peeraddr =		uipc_peeraddr,
1399 	.pru_rcvd =		uipc_rcvd,
1400 	.pru_send =		uipc_send,
1401 	.pru_ready =		uipc_ready,
1402 	.pru_sense =		uipc_sense,
1403 	.pru_shutdown =		uipc_shutdown,
1404 	.pru_sockaddr =		uipc_sockaddr,
1405 	.pru_soreceive =	soreceive_generic,
1406 	.pru_close =		uipc_close,
1407 };
1408 
1409 static int
1410 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1411 {
1412 	struct unpcb *unp;
1413 	struct xucred xu;
1414 	int error, optval;
1415 
1416 	if (sopt->sopt_level != 0)
1417 		return (EINVAL);
1418 
1419 	unp = sotounpcb(so);
1420 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1421 	error = 0;
1422 	switch (sopt->sopt_dir) {
1423 	case SOPT_GET:
1424 		switch (sopt->sopt_name) {
1425 		case LOCAL_PEERCRED:
1426 			UNP_PCB_LOCK(unp);
1427 			if (unp->unp_flags & UNP_HAVEPC)
1428 				xu = unp->unp_peercred;
1429 			else {
1430 				if (so->so_type == SOCK_STREAM)
1431 					error = ENOTCONN;
1432 				else
1433 					error = EINVAL;
1434 			}
1435 			UNP_PCB_UNLOCK(unp);
1436 			if (error == 0)
1437 				error = sooptcopyout(sopt, &xu, sizeof(xu));
1438 			break;
1439 
1440 		case LOCAL_CREDS:
1441 			/* Unlocked read. */
1442 			optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1443 			error = sooptcopyout(sopt, &optval, sizeof(optval));
1444 			break;
1445 
1446 		case LOCAL_CONNWAIT:
1447 			/* Unlocked read. */
1448 			optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1449 			error = sooptcopyout(sopt, &optval, sizeof(optval));
1450 			break;
1451 
1452 		default:
1453 			error = EOPNOTSUPP;
1454 			break;
1455 		}
1456 		break;
1457 
1458 	case SOPT_SET:
1459 		switch (sopt->sopt_name) {
1460 		case LOCAL_CREDS:
1461 		case LOCAL_CONNWAIT:
1462 			error = sooptcopyin(sopt, &optval, sizeof(optval),
1463 					    sizeof(optval));
1464 			if (error)
1465 				break;
1466 
1467 #define	OPTSET(bit) do {						\
1468 	UNP_PCB_LOCK(unp);						\
1469 	if (optval)							\
1470 		unp->unp_flags |= bit;					\
1471 	else								\
1472 		unp->unp_flags &= ~bit;					\
1473 	UNP_PCB_UNLOCK(unp);						\
1474 } while (0)
1475 
1476 			switch (sopt->sopt_name) {
1477 			case LOCAL_CREDS:
1478 				OPTSET(UNP_WANTCRED);
1479 				break;
1480 
1481 			case LOCAL_CONNWAIT:
1482 				OPTSET(UNP_CONNWAIT);
1483 				break;
1484 
1485 			default:
1486 				break;
1487 			}
1488 			break;
1489 #undef	OPTSET
1490 		default:
1491 			error = ENOPROTOOPT;
1492 			break;
1493 		}
1494 		break;
1495 
1496 	default:
1497 		error = EOPNOTSUPP;
1498 		break;
1499 	}
1500 	return (error);
1501 }
1502 
1503 static int
1504 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1505 {
1506 
1507 	return (unp_connectat(AT_FDCWD, so, nam, td));
1508 }
1509 
1510 static int
1511 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1512     struct thread *td)
1513 {
1514 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1515 	struct vnode *vp;
1516 	struct socket *so2;
1517 	struct unpcb *unp, *unp2, *unp3;
1518 	struct nameidata nd;
1519 	char buf[SOCK_MAXADDRLEN];
1520 	struct sockaddr *sa;
1521 	cap_rights_t rights;
1522 	int error, len, freed;
1523 	struct mtx *vplock;
1524 
1525 	if (nam->sa_family != AF_UNIX)
1526 		return (EAFNOSUPPORT);
1527 	if (nam->sa_len > sizeof(struct sockaddr_un))
1528 		return (EINVAL);
1529 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1530 	if (len <= 0)
1531 		return (EINVAL);
1532 	bcopy(soun->sun_path, buf, len);
1533 	buf[len] = 0;
1534 
1535 	unp = sotounpcb(so);
1536 	UNP_PCB_LOCK(unp);
1537 	if (unp->unp_flags & UNP_CONNECTING) {
1538 		UNP_PCB_UNLOCK(unp);
1539 		return (EALREADY);
1540 	}
1541 	unp->unp_flags |= UNP_CONNECTING;
1542 	UNP_PCB_UNLOCK(unp);
1543 
1544 	sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1545 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1546 	    UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1547 	error = namei(&nd);
1548 	if (error)
1549 		vp = NULL;
1550 	else
1551 		vp = nd.ni_vp;
1552 	ASSERT_VOP_LOCKED(vp, "unp_connect");
1553 	NDFREE(&nd, NDF_ONLY_PNBUF);
1554 	if (error)
1555 		goto bad;
1556 
1557 	if (vp->v_type != VSOCK) {
1558 		error = ENOTSOCK;
1559 		goto bad;
1560 	}
1561 #ifdef MAC
1562 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1563 	if (error)
1564 		goto bad;
1565 #endif
1566 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1567 	if (error)
1568 		goto bad;
1569 
1570 	unp = sotounpcb(so);
1571 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1572 
1573 	vplock = mtx_pool_find(mtxpool_sleep, vp);
1574 	mtx_lock(vplock);
1575 	VOP_UNP_CONNECT(vp, &unp2);
1576 	if (unp2 == NULL) {
1577 		error = ECONNREFUSED;
1578 		goto bad2;
1579 	}
1580 	so2 = unp2->unp_socket;
1581 	if (so->so_type != so2->so_type) {
1582 		error = EPROTOTYPE;
1583 		goto bad2;
1584 	}
1585 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1586 		if (so2->so_options & SO_ACCEPTCONN) {
1587 			CURVNET_SET(so2->so_vnet);
1588 			so2 = sonewconn(so2, 0);
1589 			CURVNET_RESTORE();
1590 		} else
1591 			so2 = NULL;
1592 		if (so2 == NULL) {
1593 			error = ECONNREFUSED;
1594 			goto bad2;
1595 		}
1596 		unp3 = sotounpcb(so2);
1597 		unp_pcb_lock2(unp2, unp3);
1598 		if (unp2->unp_addr != NULL) {
1599 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1600 			unp3->unp_addr = (struct sockaddr_un *) sa;
1601 			sa = NULL;
1602 		}
1603 
1604 		/*
1605 		 * The connector's (client's) credentials are copied from its
1606 		 * process structure at the time of connect() (which is now).
1607 		 */
1608 		cru2x(td->td_ucred, &unp3->unp_peercred);
1609 		unp3->unp_flags |= UNP_HAVEPC;
1610 
1611 		/*
1612 		 * The receiver's (server's) credentials are copied from the
1613 		 * unp_peercred member of socket on which the former called
1614 		 * listen(); uipc_listen() cached that process's credentials
1615 		 * at that time so we can use them now.
1616 		 */
1617 		memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1618 		    sizeof(unp->unp_peercred));
1619 		unp->unp_flags |= UNP_HAVEPC;
1620 		if (unp2->unp_flags & UNP_WANTCRED)
1621 			unp3->unp_flags |= UNP_WANTCRED;
1622 		UNP_PCB_UNLOCK(unp2);
1623 		unp2 = unp3;
1624 		unp_pcb_owned_lock2(unp2, unp, freed);
1625 		if (__predict_false(freed)) {
1626 			UNP_PCB_UNLOCK(unp2);
1627 			error = ECONNREFUSED;
1628 			goto bad2;
1629 		}
1630 #ifdef MAC
1631 		mac_socketpeer_set_from_socket(so, so2);
1632 		mac_socketpeer_set_from_socket(so2, so);
1633 #endif
1634 	} else {
1635 		if (unp == unp2)
1636 			UNP_PCB_LOCK(unp);
1637 		else
1638 			unp_pcb_lock2(unp, unp2);
1639 	}
1640 	KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1641 	    sotounpcb(so2) == unp2,
1642 	    ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1643 	error = unp_connect2(so, so2, PRU_CONNECT);
1644 	if (unp != unp2)
1645 		UNP_PCB_UNLOCK(unp2);
1646 	UNP_PCB_UNLOCK(unp);
1647 bad2:
1648 	mtx_unlock(vplock);
1649 bad:
1650 	if (vp != NULL) {
1651 		vput(vp);
1652 	}
1653 	free(sa, M_SONAME);
1654 	UNP_PCB_LOCK(unp);
1655 	unp->unp_flags &= ~UNP_CONNECTING;
1656 	UNP_PCB_UNLOCK(unp);
1657 	return (error);
1658 }
1659 
1660 static int
1661 unp_connect2(struct socket *so, struct socket *so2, int req)
1662 {
1663 	struct unpcb *unp;
1664 	struct unpcb *unp2;
1665 
1666 	unp = sotounpcb(so);
1667 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1668 	unp2 = sotounpcb(so2);
1669 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1670 
1671 	UNP_PCB_LOCK_ASSERT(unp);
1672 	UNP_PCB_LOCK_ASSERT(unp2);
1673 
1674 	if (so2->so_type != so->so_type)
1675 		return (EPROTOTYPE);
1676 	unp2->unp_flags &= ~UNP_NASCENT;
1677 	unp->unp_conn = unp2;
1678 	unp_pcb_hold(unp2);
1679 	unp_pcb_hold(unp);
1680 	switch (so->so_type) {
1681 	case SOCK_DGRAM:
1682 		UNP_REF_LIST_LOCK();
1683 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1684 		UNP_REF_LIST_UNLOCK();
1685 		soisconnected(so);
1686 		break;
1687 
1688 	case SOCK_STREAM:
1689 	case SOCK_SEQPACKET:
1690 		unp2->unp_conn = unp;
1691 		if (req == PRU_CONNECT &&
1692 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1693 			soisconnecting(so);
1694 		else
1695 			soisconnected(so);
1696 		soisconnected(so2);
1697 		break;
1698 
1699 	default:
1700 		panic("unp_connect2");
1701 	}
1702 	return (0);
1703 }
1704 
1705 static void
1706 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1707 {
1708 	struct socket *so, *so2;
1709 	int freed __unused;
1710 
1711 	KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1712 
1713 	UNP_PCB_LOCK_ASSERT(unp);
1714 	UNP_PCB_LOCK_ASSERT(unp2);
1715 
1716 	if (unp->unp_conn == NULL && unp2->unp_conn == NULL)
1717 		return;
1718 
1719 	MPASS(unp->unp_conn == unp2);
1720 	unp->unp_conn = NULL;
1721 	so = unp->unp_socket;
1722 	so2 = unp2->unp_socket;
1723 	switch (unp->unp_socket->so_type) {
1724 	case SOCK_DGRAM:
1725 		UNP_REF_LIST_LOCK();
1726 		LIST_REMOVE(unp, unp_reflink);
1727 		UNP_REF_LIST_UNLOCK();
1728 		if (so) {
1729 			SOCK_LOCK(so);
1730 			so->so_state &= ~SS_ISCONNECTED;
1731 			SOCK_UNLOCK(so);
1732 		}
1733 		break;
1734 
1735 	case SOCK_STREAM:
1736 	case SOCK_SEQPACKET:
1737 		if (so)
1738 			soisdisconnected(so);
1739 		MPASS(unp2->unp_conn == unp);
1740 		unp2->unp_conn = NULL;
1741 		if (so2)
1742 			soisdisconnected(so2);
1743 		break;
1744 	}
1745 	freed = unp_pcb_rele(unp);
1746 	MPASS(freed == 0);
1747 	freed = unp_pcb_rele(unp2);
1748 	MPASS(freed == 0);
1749 }
1750 
1751 /*
1752  * unp_pcblist() walks the global list of struct unpcb's to generate a
1753  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1754  * sequentially, validating the generation number on each to see if it has
1755  * been detached.  All of this is necessary because copyout() may sleep on
1756  * disk I/O.
1757  */
1758 static int
1759 unp_pcblist(SYSCTL_HANDLER_ARGS)
1760 {
1761 	struct unpcb *unp, **unp_list;
1762 	unp_gen_t gencnt;
1763 	struct xunpgen *xug;
1764 	struct unp_head *head;
1765 	struct xunpcb *xu;
1766 	u_int i;
1767 	int error, freeunp, n;
1768 
1769 	switch ((intptr_t)arg1) {
1770 	case SOCK_STREAM:
1771 		head = &unp_shead;
1772 		break;
1773 
1774 	case SOCK_DGRAM:
1775 		head = &unp_dhead;
1776 		break;
1777 
1778 	case SOCK_SEQPACKET:
1779 		head = &unp_sphead;
1780 		break;
1781 
1782 	default:
1783 		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1784 	}
1785 
1786 	/*
1787 	 * The process of preparing the PCB list is too time-consuming and
1788 	 * resource-intensive to repeat twice on every request.
1789 	 */
1790 	if (req->oldptr == NULL) {
1791 		n = unp_count;
1792 		req->oldidx = 2 * (sizeof *xug)
1793 			+ (n + n/8) * sizeof(struct xunpcb);
1794 		return (0);
1795 	}
1796 
1797 	if (req->newptr != NULL)
1798 		return (EPERM);
1799 
1800 	/*
1801 	 * OK, now we're committed to doing something.
1802 	 */
1803 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1804 	UNP_LINK_RLOCK();
1805 	gencnt = unp_gencnt;
1806 	n = unp_count;
1807 	UNP_LINK_RUNLOCK();
1808 
1809 	xug->xug_len = sizeof *xug;
1810 	xug->xug_count = n;
1811 	xug->xug_gen = gencnt;
1812 	xug->xug_sogen = so_gencnt;
1813 	error = SYSCTL_OUT(req, xug, sizeof *xug);
1814 	if (error) {
1815 		free(xug, M_TEMP);
1816 		return (error);
1817 	}
1818 
1819 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1820 
1821 	UNP_LINK_RLOCK();
1822 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1823 	     unp = LIST_NEXT(unp, unp_link)) {
1824 		UNP_PCB_LOCK(unp);
1825 		if (unp->unp_gencnt <= gencnt) {
1826 			if (cr_cansee(req->td->td_ucred,
1827 			    unp->unp_socket->so_cred)) {
1828 				UNP_PCB_UNLOCK(unp);
1829 				continue;
1830 			}
1831 			unp_list[i++] = unp;
1832 			unp_pcb_hold(unp);
1833 		}
1834 		UNP_PCB_UNLOCK(unp);
1835 	}
1836 	UNP_LINK_RUNLOCK();
1837 	n = i;			/* In case we lost some during malloc. */
1838 
1839 	error = 0;
1840 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1841 	for (i = 0; i < n; i++) {
1842 		unp = unp_list[i];
1843 		UNP_PCB_LOCK(unp);
1844 		freeunp = unp_pcb_rele(unp);
1845 
1846 		if (freeunp == 0 && unp->unp_gencnt <= gencnt) {
1847 			xu->xu_len = sizeof *xu;
1848 			xu->xu_unpp = unp;
1849 			/*
1850 			 * XXX - need more locking here to protect against
1851 			 * connect/disconnect races for SMP.
1852 			 */
1853 			if (unp->unp_addr != NULL)
1854 				bcopy(unp->unp_addr, &xu->xu_addr,
1855 				      unp->unp_addr->sun_len);
1856 			else
1857 				bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1858 			if (unp->unp_conn != NULL &&
1859 			    unp->unp_conn->unp_addr != NULL)
1860 				bcopy(unp->unp_conn->unp_addr,
1861 				      &xu->xu_caddr,
1862 				      unp->unp_conn->unp_addr->sun_len);
1863 			else
1864 				bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
1865 			xu->unp_vnode = unp->unp_vnode;
1866 			xu->unp_conn = unp->unp_conn;
1867 			xu->xu_firstref = LIST_FIRST(&unp->unp_refs);
1868 			xu->xu_nextref = LIST_NEXT(unp, unp_reflink);
1869 			xu->unp_gencnt = unp->unp_gencnt;
1870 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1871 			UNP_PCB_UNLOCK(unp);
1872 			error = SYSCTL_OUT(req, xu, sizeof *xu);
1873 		} else  if (freeunp == 0)
1874 			UNP_PCB_UNLOCK(unp);
1875 	}
1876 	free(xu, M_TEMP);
1877 	if (!error) {
1878 		/*
1879 		 * Give the user an updated idea of our state.  If the
1880 		 * generation differs from what we told her before, she knows
1881 		 * that something happened while we were processing this
1882 		 * request, and it might be necessary to retry.
1883 		 */
1884 		xug->xug_gen = unp_gencnt;
1885 		xug->xug_sogen = so_gencnt;
1886 		xug->xug_count = unp_count;
1887 		error = SYSCTL_OUT(req, xug, sizeof *xug);
1888 	}
1889 	free(unp_list, M_TEMP);
1890 	free(xug, M_TEMP);
1891 	return (error);
1892 }
1893 
1894 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1895     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1896     "List of active local datagram sockets");
1897 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1898     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1899     "List of active local stream sockets");
1900 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1901     CTLTYPE_OPAQUE | CTLFLAG_RD,
1902     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1903     "List of active local seqpacket sockets");
1904 
1905 static void
1906 unp_shutdown(struct unpcb *unp)
1907 {
1908 	struct unpcb *unp2;
1909 	struct socket *so;
1910 
1911 	UNP_PCB_LOCK_ASSERT(unp);
1912 
1913 	unp2 = unp->unp_conn;
1914 	if ((unp->unp_socket->so_type == SOCK_STREAM ||
1915 	    (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1916 		so = unp2->unp_socket;
1917 		if (so != NULL)
1918 			socantrcvmore(so);
1919 	}
1920 }
1921 
1922 static void
1923 unp_drop(struct unpcb *unp)
1924 {
1925 	struct socket *so = unp->unp_socket;
1926 	struct unpcb *unp2;
1927 	int freed;
1928 
1929 	/*
1930 	 * Regardless of whether the socket's peer dropped the connection
1931 	 * with this socket by aborting or disconnecting, POSIX requires
1932 	 * that ECONNRESET is returned.
1933 	 */
1934 	/* acquire a reference so that unp isn't freed from underneath us */
1935 
1936 	UNP_PCB_LOCK(unp);
1937 	if (so)
1938 		so->so_error = ECONNRESET;
1939 	unp2 = unp->unp_conn;
1940 	if (unp2 == unp) {
1941 		unp_disconnect(unp, unp2);
1942 	} else if (unp2 != NULL) {
1943 		unp_pcb_hold(unp2);
1944 		unp_pcb_owned_lock2(unp, unp2, freed);
1945 		unp_disconnect(unp, unp2);
1946 		if (unp_pcb_rele(unp2) == 0)
1947 			UNP_PCB_UNLOCK(unp2);
1948 	}
1949 	if (unp_pcb_rele(unp) == 0)
1950 		UNP_PCB_UNLOCK(unp);
1951 }
1952 
1953 static void
1954 unp_freerights(struct filedescent **fdep, int fdcount)
1955 {
1956 	struct file *fp;
1957 	int i;
1958 
1959 	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
1960 
1961 	for (i = 0; i < fdcount; i++) {
1962 		fp = fdep[i]->fde_file;
1963 		filecaps_free(&fdep[i]->fde_caps);
1964 		unp_discard(fp);
1965 	}
1966 	free(fdep[0], M_FILECAPS);
1967 }
1968 
1969 static int
1970 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
1971 {
1972 	struct thread *td = curthread;		/* XXX */
1973 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1974 	int i;
1975 	int *fdp;
1976 	struct filedesc *fdesc = td->td_proc->p_fd;
1977 	struct filedescent **fdep;
1978 	void *data;
1979 	socklen_t clen = control->m_len, datalen;
1980 	int error, newfds;
1981 	u_int newlen;
1982 
1983 	UNP_LINK_UNLOCK_ASSERT();
1984 
1985 	error = 0;
1986 	if (controlp != NULL) /* controlp == NULL => free control messages */
1987 		*controlp = NULL;
1988 	while (cm != NULL) {
1989 		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1990 			error = EINVAL;
1991 			break;
1992 		}
1993 		data = CMSG_DATA(cm);
1994 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1995 		if (cm->cmsg_level == SOL_SOCKET
1996 		    && cm->cmsg_type == SCM_RIGHTS) {
1997 			newfds = datalen / sizeof(*fdep);
1998 			if (newfds == 0)
1999 				goto next;
2000 			fdep = data;
2001 
2002 			/* If we're not outputting the descriptors free them. */
2003 			if (error || controlp == NULL) {
2004 				unp_freerights(fdep, newfds);
2005 				goto next;
2006 			}
2007 			FILEDESC_XLOCK(fdesc);
2008 
2009 			/*
2010 			 * Now change each pointer to an fd in the global
2011 			 * table to an integer that is the index to the local
2012 			 * fd table entry that we set up to point to the
2013 			 * global one we are transferring.
2014 			 */
2015 			newlen = newfds * sizeof(int);
2016 			*controlp = sbcreatecontrol(NULL, newlen,
2017 			    SCM_RIGHTS, SOL_SOCKET);
2018 			if (*controlp == NULL) {
2019 				FILEDESC_XUNLOCK(fdesc);
2020 				error = E2BIG;
2021 				unp_freerights(fdep, newfds);
2022 				goto next;
2023 			}
2024 
2025 			fdp = (int *)
2026 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2027 			if (fdallocn(td, 0, fdp, newfds) != 0) {
2028 				FILEDESC_XUNLOCK(fdesc);
2029 				error = EMSGSIZE;
2030 				unp_freerights(fdep, newfds);
2031 				m_freem(*controlp);
2032 				*controlp = NULL;
2033 				goto next;
2034 			}
2035 			for (i = 0; i < newfds; i++, fdp++) {
2036 				_finstall(fdesc, fdep[i]->fde_file, *fdp,
2037 				    (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
2038 				    &fdep[i]->fde_caps);
2039 				unp_externalize_fp(fdep[i]->fde_file);
2040 			}
2041 			FILEDESC_XUNLOCK(fdesc);
2042 			free(fdep[0], M_FILECAPS);
2043 		} else {
2044 			/* We can just copy anything else across. */
2045 			if (error || controlp == NULL)
2046 				goto next;
2047 			*controlp = sbcreatecontrol(NULL, datalen,
2048 			    cm->cmsg_type, cm->cmsg_level);
2049 			if (*controlp == NULL) {
2050 				error = ENOBUFS;
2051 				goto next;
2052 			}
2053 			bcopy(data,
2054 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2055 			    datalen);
2056 		}
2057 		controlp = &(*controlp)->m_next;
2058 
2059 next:
2060 		if (CMSG_SPACE(datalen) < clen) {
2061 			clen -= CMSG_SPACE(datalen);
2062 			cm = (struct cmsghdr *)
2063 			    ((caddr_t)cm + CMSG_SPACE(datalen));
2064 		} else {
2065 			clen = 0;
2066 			cm = NULL;
2067 		}
2068 	}
2069 
2070 	m_freem(control);
2071 	return (error);
2072 }
2073 
2074 static void
2075 unp_zone_change(void *tag)
2076 {
2077 
2078 	uma_zone_set_max(unp_zone, maxsockets);
2079 }
2080 
2081 static void
2082 unp_init(void)
2083 {
2084 
2085 #ifdef VIMAGE
2086 	if (!IS_DEFAULT_VNET(curvnet))
2087 		return;
2088 #endif
2089 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
2090 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
2091 	if (unp_zone == NULL)
2092 		panic("unp_init");
2093 	uma_zone_set_max(unp_zone, maxsockets);
2094 	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2095 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2096 	    NULL, EVENTHANDLER_PRI_ANY);
2097 	LIST_INIT(&unp_dhead);
2098 	LIST_INIT(&unp_shead);
2099 	LIST_INIT(&unp_sphead);
2100 	SLIST_INIT(&unp_defers);
2101 	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2102 	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2103 	UNP_LINK_LOCK_INIT();
2104 	UNP_DEFERRED_LOCK_INIT();
2105 }
2106 
2107 static int
2108 unp_internalize(struct mbuf **controlp, struct thread *td)
2109 {
2110 	struct mbuf *control = *controlp;
2111 	struct proc *p = td->td_proc;
2112 	struct filedesc *fdesc = p->p_fd;
2113 	struct bintime *bt;
2114 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2115 	struct cmsgcred *cmcred;
2116 	struct filedescent *fde, **fdep, *fdev;
2117 	struct file *fp;
2118 	struct timeval *tv;
2119 	struct timespec *ts;
2120 	int i, *fdp;
2121 	void *data;
2122 	socklen_t clen = control->m_len, datalen;
2123 	int error, oldfds;
2124 	u_int newlen;
2125 
2126 	UNP_LINK_UNLOCK_ASSERT();
2127 
2128 	error = 0;
2129 	*controlp = NULL;
2130 	while (cm != NULL) {
2131 		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2132 		    || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
2133 			error = EINVAL;
2134 			goto out;
2135 		}
2136 		data = CMSG_DATA(cm);
2137 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2138 
2139 		switch (cm->cmsg_type) {
2140 		/*
2141 		 * Fill in credential information.
2142 		 */
2143 		case SCM_CREDS:
2144 			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2145 			    SCM_CREDS, SOL_SOCKET);
2146 			if (*controlp == NULL) {
2147 				error = ENOBUFS;
2148 				goto out;
2149 			}
2150 			cmcred = (struct cmsgcred *)
2151 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2152 			cmcred->cmcred_pid = p->p_pid;
2153 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2154 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2155 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
2156 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2157 			    CMGROUP_MAX);
2158 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
2159 				cmcred->cmcred_groups[i] =
2160 				    td->td_ucred->cr_groups[i];
2161 			break;
2162 
2163 		case SCM_RIGHTS:
2164 			oldfds = datalen / sizeof (int);
2165 			if (oldfds == 0)
2166 				break;
2167 			/*
2168 			 * Check that all the FDs passed in refer to legal
2169 			 * files.  If not, reject the entire operation.
2170 			 */
2171 			fdp = data;
2172 			FILEDESC_SLOCK(fdesc);
2173 			for (i = 0; i < oldfds; i++, fdp++) {
2174 				fp = fget_locked(fdesc, *fdp);
2175 				if (fp == NULL) {
2176 					FILEDESC_SUNLOCK(fdesc);
2177 					error = EBADF;
2178 					goto out;
2179 				}
2180 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2181 					FILEDESC_SUNLOCK(fdesc);
2182 					error = EOPNOTSUPP;
2183 					goto out;
2184 				}
2185 
2186 			}
2187 
2188 			/*
2189 			 * Now replace the integer FDs with pointers to the
2190 			 * file structure and capability rights.
2191 			 */
2192 			newlen = oldfds * sizeof(fdep[0]);
2193 			*controlp = sbcreatecontrol(NULL, newlen,
2194 			    SCM_RIGHTS, SOL_SOCKET);
2195 			if (*controlp == NULL) {
2196 				FILEDESC_SUNLOCK(fdesc);
2197 				error = E2BIG;
2198 				goto out;
2199 			}
2200 			fdp = data;
2201 			fdep = (struct filedescent **)
2202 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2203 			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2204 			    M_WAITOK);
2205 			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2206 				fde = &fdesc->fd_ofiles[*fdp];
2207 				fdep[i] = fdev;
2208 				fdep[i]->fde_file = fde->fde_file;
2209 				filecaps_copy(&fde->fde_caps,
2210 				    &fdep[i]->fde_caps, true);
2211 				unp_internalize_fp(fdep[i]->fde_file);
2212 			}
2213 			FILEDESC_SUNLOCK(fdesc);
2214 			break;
2215 
2216 		case SCM_TIMESTAMP:
2217 			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
2218 			    SCM_TIMESTAMP, SOL_SOCKET);
2219 			if (*controlp == NULL) {
2220 				error = ENOBUFS;
2221 				goto out;
2222 			}
2223 			tv = (struct timeval *)
2224 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2225 			microtime(tv);
2226 			break;
2227 
2228 		case SCM_BINTIME:
2229 			*controlp = sbcreatecontrol(NULL, sizeof(*bt),
2230 			    SCM_BINTIME, SOL_SOCKET);
2231 			if (*controlp == NULL) {
2232 				error = ENOBUFS;
2233 				goto out;
2234 			}
2235 			bt = (struct bintime *)
2236 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2237 			bintime(bt);
2238 			break;
2239 
2240 		case SCM_REALTIME:
2241 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2242 			    SCM_REALTIME, SOL_SOCKET);
2243 			if (*controlp == NULL) {
2244 				error = ENOBUFS;
2245 				goto out;
2246 			}
2247 			ts = (struct timespec *)
2248 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2249 			nanotime(ts);
2250 			break;
2251 
2252 		case SCM_MONOTONIC:
2253 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2254 			    SCM_MONOTONIC, SOL_SOCKET);
2255 			if (*controlp == NULL) {
2256 				error = ENOBUFS;
2257 				goto out;
2258 			}
2259 			ts = (struct timespec *)
2260 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2261 			nanouptime(ts);
2262 			break;
2263 
2264 		default:
2265 			error = EINVAL;
2266 			goto out;
2267 		}
2268 
2269 		controlp = &(*controlp)->m_next;
2270 		if (CMSG_SPACE(datalen) < clen) {
2271 			clen -= CMSG_SPACE(datalen);
2272 			cm = (struct cmsghdr *)
2273 			    ((caddr_t)cm + CMSG_SPACE(datalen));
2274 		} else {
2275 			clen = 0;
2276 			cm = NULL;
2277 		}
2278 	}
2279 
2280 out:
2281 	m_freem(control);
2282 	return (error);
2283 }
2284 
2285 static struct mbuf *
2286 unp_addsockcred(struct thread *td, struct mbuf *control)
2287 {
2288 	struct mbuf *m, *n, *n_prev;
2289 	struct sockcred *sc;
2290 	const struct cmsghdr *cm;
2291 	int ngroups;
2292 	int i;
2293 
2294 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2295 	m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2296 	if (m == NULL)
2297 		return (control);
2298 
2299 	sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2300 	sc->sc_uid = td->td_ucred->cr_ruid;
2301 	sc->sc_euid = td->td_ucred->cr_uid;
2302 	sc->sc_gid = td->td_ucred->cr_rgid;
2303 	sc->sc_egid = td->td_ucred->cr_gid;
2304 	sc->sc_ngroups = ngroups;
2305 	for (i = 0; i < sc->sc_ngroups; i++)
2306 		sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2307 
2308 	/*
2309 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2310 	 * created SCM_CREDS control message (struct sockcred) has another
2311 	 * format.
2312 	 */
2313 	if (control != NULL)
2314 		for (n = control, n_prev = NULL; n != NULL;) {
2315 			cm = mtod(n, struct cmsghdr *);
2316     			if (cm->cmsg_level == SOL_SOCKET &&
2317 			    cm->cmsg_type == SCM_CREDS) {
2318     				if (n_prev == NULL)
2319 					control = n->m_next;
2320 				else
2321 					n_prev->m_next = n->m_next;
2322 				n = m_free(n);
2323 			} else {
2324 				n_prev = n;
2325 				n = n->m_next;
2326 			}
2327 		}
2328 
2329 	/* Prepend it to the head. */
2330 	m->m_next = control;
2331 	return (m);
2332 }
2333 
2334 static struct unpcb *
2335 fptounp(struct file *fp)
2336 {
2337 	struct socket *so;
2338 
2339 	if (fp->f_type != DTYPE_SOCKET)
2340 		return (NULL);
2341 	if ((so = fp->f_data) == NULL)
2342 		return (NULL);
2343 	if (so->so_proto->pr_domain != &localdomain)
2344 		return (NULL);
2345 	return sotounpcb(so);
2346 }
2347 
2348 static void
2349 unp_discard(struct file *fp)
2350 {
2351 	struct unp_defer *dr;
2352 
2353 	if (unp_externalize_fp(fp)) {
2354 		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2355 		dr->ud_fp = fp;
2356 		UNP_DEFERRED_LOCK();
2357 		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2358 		UNP_DEFERRED_UNLOCK();
2359 		atomic_add_int(&unp_defers_count, 1);
2360 		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2361 	} else
2362 		(void) closef(fp, (struct thread *)NULL);
2363 }
2364 
2365 static void
2366 unp_process_defers(void *arg __unused, int pending)
2367 {
2368 	struct unp_defer *dr;
2369 	SLIST_HEAD(, unp_defer) drl;
2370 	int count;
2371 
2372 	SLIST_INIT(&drl);
2373 	for (;;) {
2374 		UNP_DEFERRED_LOCK();
2375 		if (SLIST_FIRST(&unp_defers) == NULL) {
2376 			UNP_DEFERRED_UNLOCK();
2377 			break;
2378 		}
2379 		SLIST_SWAP(&unp_defers, &drl, unp_defer);
2380 		UNP_DEFERRED_UNLOCK();
2381 		count = 0;
2382 		while ((dr = SLIST_FIRST(&drl)) != NULL) {
2383 			SLIST_REMOVE_HEAD(&drl, ud_link);
2384 			closef(dr->ud_fp, NULL);
2385 			free(dr, M_TEMP);
2386 			count++;
2387 		}
2388 		atomic_add_int(&unp_defers_count, -count);
2389 	}
2390 }
2391 
2392 static void
2393 unp_internalize_fp(struct file *fp)
2394 {
2395 	struct unpcb *unp;
2396 
2397 	UNP_LINK_WLOCK();
2398 	if ((unp = fptounp(fp)) != NULL) {
2399 		unp->unp_file = fp;
2400 		unp->unp_msgcount++;
2401 	}
2402 	fhold(fp);
2403 	unp_rights++;
2404 	UNP_LINK_WUNLOCK();
2405 }
2406 
2407 static int
2408 unp_externalize_fp(struct file *fp)
2409 {
2410 	struct unpcb *unp;
2411 	int ret;
2412 
2413 	UNP_LINK_WLOCK();
2414 	if ((unp = fptounp(fp)) != NULL) {
2415 		unp->unp_msgcount--;
2416 		ret = 1;
2417 	} else
2418 		ret = 0;
2419 	unp_rights--;
2420 	UNP_LINK_WUNLOCK();
2421 	return (ret);
2422 }
2423 
2424 /*
2425  * unp_defer indicates whether additional work has been defered for a future
2426  * pass through unp_gc().  It is thread local and does not require explicit
2427  * synchronization.
2428  */
2429 static int	unp_marked;
2430 static int	unp_unreachable;
2431 
2432 static void
2433 unp_accessable(struct filedescent **fdep, int fdcount)
2434 {
2435 	struct unpcb *unp;
2436 	struct file *fp;
2437 	int i;
2438 
2439 	for (i = 0; i < fdcount; i++) {
2440 		fp = fdep[i]->fde_file;
2441 		if ((unp = fptounp(fp)) == NULL)
2442 			continue;
2443 		if (unp->unp_gcflag & UNPGC_REF)
2444 			continue;
2445 		unp->unp_gcflag &= ~UNPGC_DEAD;
2446 		unp->unp_gcflag |= UNPGC_REF;
2447 		unp_marked++;
2448 	}
2449 }
2450 
2451 static void
2452 unp_gc_process(struct unpcb *unp)
2453 {
2454 	struct socket *so, *soa;
2455 	struct file *fp;
2456 
2457 	/* Already processed. */
2458 	if (unp->unp_gcflag & UNPGC_SCANNED)
2459 		return;
2460 	fp = unp->unp_file;
2461 
2462 	/*
2463 	 * Check for a socket potentially in a cycle.  It must be in a
2464 	 * queue as indicated by msgcount, and this must equal the file
2465 	 * reference count.  Note that when msgcount is 0 the file is NULL.
2466 	 */
2467 	if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2468 	    unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2469 		unp->unp_gcflag |= UNPGC_DEAD;
2470 		unp_unreachable++;
2471 		return;
2472 	}
2473 
2474 	so = unp->unp_socket;
2475 	SOCK_LOCK(so);
2476 	if (SOLISTENING(so)) {
2477 		/*
2478 		 * Mark all sockets in our accept queue.
2479 		 */
2480 		TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2481 			if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2482 				continue;
2483 			SOCKBUF_LOCK(&soa->so_rcv);
2484 			unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2485 			SOCKBUF_UNLOCK(&soa->so_rcv);
2486 		}
2487 	} else {
2488 		/*
2489 		 * Mark all sockets we reference with RIGHTS.
2490 		 */
2491 		if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2492 			SOCKBUF_LOCK(&so->so_rcv);
2493 			unp_scan(so->so_rcv.sb_mb, unp_accessable);
2494 			SOCKBUF_UNLOCK(&so->so_rcv);
2495 		}
2496 	}
2497 	SOCK_UNLOCK(so);
2498 	unp->unp_gcflag |= UNPGC_SCANNED;
2499 }
2500 
2501 static int unp_recycled;
2502 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2503     "Number of unreachable sockets claimed by the garbage collector.");
2504 
2505 static int unp_taskcount;
2506 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2507     "Number of times the garbage collector has run.");
2508 
2509 static void
2510 unp_gc(__unused void *arg, int pending)
2511 {
2512 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2513 				    NULL };
2514 	struct unp_head **head;
2515 	struct file *f, **unref;
2516 	struct unpcb *unp;
2517 	int i, total;
2518 
2519 	unp_taskcount++;
2520 	UNP_LINK_RLOCK();
2521 	/*
2522 	 * First clear all gc flags from previous runs, apart from
2523 	 * UNPGC_IGNORE_RIGHTS.
2524 	 */
2525 	for (head = heads; *head != NULL; head++)
2526 		LIST_FOREACH(unp, *head, unp_link)
2527 			unp->unp_gcflag =
2528 			    (unp->unp_gcflag & UNPGC_IGNORE_RIGHTS);
2529 
2530 	/*
2531 	 * Scan marking all reachable sockets with UNPGC_REF.  Once a socket
2532 	 * is reachable all of the sockets it references are reachable.
2533 	 * Stop the scan once we do a complete loop without discovering
2534 	 * a new reachable socket.
2535 	 */
2536 	do {
2537 		unp_unreachable = 0;
2538 		unp_marked = 0;
2539 		for (head = heads; *head != NULL; head++)
2540 			LIST_FOREACH(unp, *head, unp_link)
2541 				unp_gc_process(unp);
2542 	} while (unp_marked);
2543 	UNP_LINK_RUNLOCK();
2544 	if (unp_unreachable == 0)
2545 		return;
2546 
2547 	/*
2548 	 * Allocate space for a local list of dead unpcbs.
2549 	 */
2550 	unref = malloc(unp_unreachable * sizeof(struct file *),
2551 	    M_TEMP, M_WAITOK);
2552 
2553 	/*
2554 	 * Iterate looking for sockets which have been specifically marked
2555 	 * as as unreachable and store them locally.
2556 	 */
2557 	UNP_LINK_RLOCK();
2558 	for (total = 0, head = heads; *head != NULL; head++)
2559 		LIST_FOREACH(unp, *head, unp_link)
2560 			if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
2561 				f = unp->unp_file;
2562 				if (unp->unp_msgcount == 0 || f == NULL ||
2563 				    f->f_count != unp->unp_msgcount)
2564 					continue;
2565 				unref[total++] = f;
2566 				fhold(f);
2567 				KASSERT(total <= unp_unreachable,
2568 				    ("unp_gc: incorrect unreachable count."));
2569 			}
2570 	UNP_LINK_RUNLOCK();
2571 
2572 	/*
2573 	 * Now flush all sockets, free'ing rights.  This will free the
2574 	 * struct files associated with these sockets but leave each socket
2575 	 * with one remaining ref.
2576 	 */
2577 	for (i = 0; i < total; i++) {
2578 		struct socket *so;
2579 
2580 		so = unref[i]->f_data;
2581 		CURVNET_SET(so->so_vnet);
2582 		sorflush(so);
2583 		CURVNET_RESTORE();
2584 	}
2585 
2586 	/*
2587 	 * And finally release the sockets so they can be reclaimed.
2588 	 */
2589 	for (i = 0; i < total; i++)
2590 		fdrop(unref[i], NULL);
2591 	unp_recycled += total;
2592 	free(unref, M_TEMP);
2593 }
2594 
2595 static void
2596 unp_dispose_mbuf(struct mbuf *m)
2597 {
2598 
2599 	if (m)
2600 		unp_scan(m, unp_freerights);
2601 }
2602 
2603 /*
2604  * Synchronize against unp_gc, which can trip over data as we are freeing it.
2605  */
2606 static void
2607 unp_dispose(struct socket *so)
2608 {
2609 	struct unpcb *unp;
2610 
2611 	unp = sotounpcb(so);
2612 	UNP_LINK_WLOCK();
2613 	unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2614 	UNP_LINK_WUNLOCK();
2615 	if (!SOLISTENING(so))
2616 		unp_dispose_mbuf(so->so_rcv.sb_mb);
2617 }
2618 
2619 static void
2620 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2621 {
2622 	struct mbuf *m;
2623 	struct cmsghdr *cm;
2624 	void *data;
2625 	socklen_t clen, datalen;
2626 
2627 	while (m0 != NULL) {
2628 		for (m = m0; m; m = m->m_next) {
2629 			if (m->m_type != MT_CONTROL)
2630 				continue;
2631 
2632 			cm = mtod(m, struct cmsghdr *);
2633 			clen = m->m_len;
2634 
2635 			while (cm != NULL) {
2636 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2637 					break;
2638 
2639 				data = CMSG_DATA(cm);
2640 				datalen = (caddr_t)cm + cm->cmsg_len
2641 				    - (caddr_t)data;
2642 
2643 				if (cm->cmsg_level == SOL_SOCKET &&
2644 				    cm->cmsg_type == SCM_RIGHTS) {
2645 					(*op)(data, datalen /
2646 					    sizeof(struct filedescent *));
2647 				}
2648 
2649 				if (CMSG_SPACE(datalen) < clen) {
2650 					clen -= CMSG_SPACE(datalen);
2651 					cm = (struct cmsghdr *)
2652 					    ((caddr_t)cm + CMSG_SPACE(datalen));
2653 				} else {
2654 					clen = 0;
2655 					cm = NULL;
2656 				}
2657 			}
2658 		}
2659 		m0 = m0->m_nextpkt;
2660 	}
2661 }
2662 
2663 /*
2664  * A helper function called by VFS before socket-type vnode reclamation.
2665  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2666  * use count.
2667  */
2668 void
2669 vfs_unp_reclaim(struct vnode *vp)
2670 {
2671 	struct unpcb *unp;
2672 	int active;
2673 	struct mtx *vplock;
2674 
2675 	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2676 	KASSERT(vp->v_type == VSOCK,
2677 	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2678 
2679 	active = 0;
2680 	vplock = mtx_pool_find(mtxpool_sleep, vp);
2681 	mtx_lock(vplock);
2682 	VOP_UNP_CONNECT(vp, &unp);
2683 	if (unp == NULL)
2684 		goto done;
2685 	UNP_PCB_LOCK(unp);
2686 	if (unp->unp_vnode == vp) {
2687 		VOP_UNP_DETACH(vp);
2688 		unp->unp_vnode = NULL;
2689 		active = 1;
2690 	}
2691 	UNP_PCB_UNLOCK(unp);
2692  done:
2693 	mtx_unlock(vplock);
2694 	if (active)
2695 		vunref(vp);
2696 }
2697 
2698 #ifdef DDB
2699 static void
2700 db_print_indent(int indent)
2701 {
2702 	int i;
2703 
2704 	for (i = 0; i < indent; i++)
2705 		db_printf(" ");
2706 }
2707 
2708 static void
2709 db_print_unpflags(int unp_flags)
2710 {
2711 	int comma;
2712 
2713 	comma = 0;
2714 	if (unp_flags & UNP_HAVEPC) {
2715 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2716 		comma = 1;
2717 	}
2718 	if (unp_flags & UNP_WANTCRED) {
2719 		db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2720 		comma = 1;
2721 	}
2722 	if (unp_flags & UNP_CONNWAIT) {
2723 		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2724 		comma = 1;
2725 	}
2726 	if (unp_flags & UNP_CONNECTING) {
2727 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2728 		comma = 1;
2729 	}
2730 	if (unp_flags & UNP_BINDING) {
2731 		db_printf("%sUNP_BINDING", comma ? ", " : "");
2732 		comma = 1;
2733 	}
2734 }
2735 
2736 static void
2737 db_print_xucred(int indent, struct xucred *xu)
2738 {
2739 	int comma, i;
2740 
2741 	db_print_indent(indent);
2742 	db_printf("cr_version: %u   cr_uid: %u   cr_ngroups: %d\n",
2743 	    xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2744 	db_print_indent(indent);
2745 	db_printf("cr_groups: ");
2746 	comma = 0;
2747 	for (i = 0; i < xu->cr_ngroups; i++) {
2748 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2749 		comma = 1;
2750 	}
2751 	db_printf("\n");
2752 }
2753 
2754 static void
2755 db_print_unprefs(int indent, struct unp_head *uh)
2756 {
2757 	struct unpcb *unp;
2758 	int counter;
2759 
2760 	counter = 0;
2761 	LIST_FOREACH(unp, uh, unp_reflink) {
2762 		if (counter % 4 == 0)
2763 			db_print_indent(indent);
2764 		db_printf("%p  ", unp);
2765 		if (counter % 4 == 3)
2766 			db_printf("\n");
2767 		counter++;
2768 	}
2769 	if (counter != 0 && counter % 4 != 0)
2770 		db_printf("\n");
2771 }
2772 
2773 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2774 {
2775 	struct unpcb *unp;
2776 
2777         if (!have_addr) {
2778                 db_printf("usage: show unpcb <addr>\n");
2779                 return;
2780         }
2781         unp = (struct unpcb *)addr;
2782 
2783 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
2784 	    unp->unp_vnode);
2785 
2786 	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2787 	    unp->unp_conn);
2788 
2789 	db_printf("unp_refs:\n");
2790 	db_print_unprefs(2, &unp->unp_refs);
2791 
2792 	/* XXXRW: Would be nice to print the full address, if any. */
2793 	db_printf("unp_addr: %p\n", unp->unp_addr);
2794 
2795 	db_printf("unp_gencnt: %llu\n",
2796 	    (unsigned long long)unp->unp_gencnt);
2797 
2798 	db_printf("unp_flags: %x (", unp->unp_flags);
2799 	db_print_unpflags(unp->unp_flags);
2800 	db_printf(")\n");
2801 
2802 	db_printf("unp_peercred:\n");
2803 	db_print_xucred(2, &unp->unp_peercred);
2804 
2805 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
2806 }
2807 #endif
2808