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