xref: /freebsd/sys/kern/uipc_usrreq.c (revision 62a52c15422470f97fc7b311d89c83f910bcc1b1)
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  * Copyright (c) 2022 Gleb Smirnoff <glebius@FreeBSD.org>
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * UNIX Domain (Local) Sockets
37  *
38  * This is an implementation of UNIX (local) domain sockets.  Each socket has
39  * an associated struct unpcb (UNIX protocol control block).  Stream sockets
40  * may be connected to 0 or 1 other socket.  Datagram sockets may be
41  * connected to 0, 1, or many other sockets.  Sockets may be created and
42  * connected in pairs (socketpair(2)), or bound/connected to using the file
43  * system name space.  For most purposes, only the receive socket buffer is
44  * used, as sending on one socket delivers directly to the receive socket
45  * buffer of a second socket.
46  *
47  * The implementation is substantially complicated by the fact that
48  * "ancillary data", such as file descriptors or credentials, may be passed
49  * across UNIX domain sockets.  The potential for passing UNIX domain sockets
50  * over other UNIX domain sockets requires the implementation of a simple
51  * garbage collector to find and tear down cycles of disconnected sockets.
52  *
53  * TODO:
54  *	RDM
55  *	rethink name space problems
56  *	need a proper out-of-band
57  */
58 
59 #include <sys/cdefs.h>
60 #include "opt_ddb.h"
61 
62 #include <sys/param.h>
63 #include <sys/capsicum.h>
64 #include <sys/domain.h>
65 #include <sys/eventhandler.h>
66 #include <sys/fcntl.h>
67 #include <sys/file.h>
68 #include <sys/filedesc.h>
69 #include <sys/kernel.h>
70 #include <sys/lock.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/mount.h>
74 #include <sys/mutex.h>
75 #include <sys/namei.h>
76 #include <sys/proc.h>
77 #include <sys/protosw.h>
78 #include <sys/queue.h>
79 #include <sys/resourcevar.h>
80 #include <sys/rwlock.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/signalvar.h>
84 #include <sys/stat.h>
85 #include <sys/sx.h>
86 #include <sys/sysctl.h>
87 #include <sys/systm.h>
88 #include <sys/taskqueue.h>
89 #include <sys/un.h>
90 #include <sys/unpcb.h>
91 #include <sys/vnode.h>
92 
93 #include <net/vnet.h>
94 
95 #ifdef DDB
96 #include <ddb/ddb.h>
97 #endif
98 
99 #include <security/mac/mac_framework.h>
100 
101 #include <vm/uma.h>
102 
103 MALLOC_DECLARE(M_FILECAPS);
104 
105 static struct domain localdomain;
106 
107 static uma_zone_t	unp_zone;
108 static unp_gen_t	unp_gencnt;	/* (l) */
109 static u_int		unp_count;	/* (l) Count of local sockets. */
110 static ino_t		unp_ino;	/* Prototype for fake inode numbers. */
111 static int		unp_rights;	/* (g) File descriptors in flight. */
112 static struct unp_head	unp_shead;	/* (l) List of stream sockets. */
113 static struct unp_head	unp_dhead;	/* (l) List of datagram sockets. */
114 static struct unp_head	unp_sphead;	/* (l) List of seqpacket sockets. */
115 
116 struct unp_defer {
117 	SLIST_ENTRY(unp_defer) ud_link;
118 	struct file *ud_fp;
119 };
120 static SLIST_HEAD(, unp_defer) unp_defers;
121 static int unp_defers_count;
122 
123 static const struct sockaddr	sun_noname = {
124 	.sa_len = sizeof(sun_noname),
125 	.sa_family = AF_LOCAL,
126 };
127 
128 /*
129  * Garbage collection of cyclic file descriptor/socket references occurs
130  * asynchronously in a taskqueue context in order to avoid recursion and
131  * reentrance in the UNIX domain socket, file descriptor, and socket layer
132  * code.  See unp_gc() for a full description.
133  */
134 static struct timeout_task unp_gc_task;
135 
136 /*
137  * The close of unix domain sockets attached as SCM_RIGHTS is
138  * postponed to the taskqueue, to avoid arbitrary recursion depth.
139  * The attached sockets might have another sockets attached.
140  */
141 static struct task	unp_defer_task;
142 
143 /*
144  * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
145  * stream sockets, although the total for sender and receiver is actually
146  * only PIPSIZ.
147  *
148  * Datagram sockets really use the sendspace as the maximum datagram size,
149  * and don't really want to reserve the sendspace.  Their recvspace should be
150  * large enough for at least one max-size datagram plus address.
151  */
152 #ifndef PIPSIZ
153 #define	PIPSIZ	8192
154 #endif
155 static u_long	unpst_sendspace = PIPSIZ;
156 static u_long	unpst_recvspace = PIPSIZ;
157 static u_long	unpdg_maxdgram = 8*1024;	/* support 8KB syslog msgs */
158 static u_long	unpdg_recvspace = 16*1024;
159 static u_long	unpsp_sendspace = PIPSIZ;	/* really max datagram size */
160 static u_long	unpsp_recvspace = PIPSIZ;
161 
162 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
163     "Local domain");
164 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
165     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
166     "SOCK_STREAM");
167 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
168     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
169     "SOCK_DGRAM");
170 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
171     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
172     "SOCK_SEQPACKET");
173 
174 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
175 	   &unpst_sendspace, 0, "Default stream send space.");
176 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
177 	   &unpst_recvspace, 0, "Default stream receive space.");
178 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
179 	   &unpdg_maxdgram, 0, "Maximum datagram size.");
180 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
181 	   &unpdg_recvspace, 0, "Default datagram receive space.");
182 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
183 	   &unpsp_sendspace, 0, "Default seqpacket send space.");
184 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
185 	   &unpsp_recvspace, 0, "Default seqpacket receive space.");
186 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
187     "File descriptors in flight.");
188 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
189     &unp_defers_count, 0,
190     "File descriptors deferred to taskqueue for close.");
191 
192 /*
193  * Locking and synchronization:
194  *
195  * Several types of locks exist in the local domain socket implementation:
196  * - a global linkage lock
197  * - a global connection list lock
198  * - the mtxpool lock
199  * - per-unpcb mutexes
200  *
201  * The linkage lock protects the global socket lists, the generation number
202  * counter and garbage collector state.
203  *
204  * The connection list lock protects the list of referring sockets in a datagram
205  * socket PCB.  This lock is also overloaded to protect a global list of
206  * sockets whose buffers contain socket references in the form of SCM_RIGHTS
207  * messages.  To avoid recursion, such references are released by a dedicated
208  * thread.
209  *
210  * The mtxpool lock protects the vnode from being modified while referenced.
211  * Lock ordering rules require that it be acquired before any PCB locks.
212  *
213  * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
214  * unpcb.  This includes the unp_conn field, which either links two connected
215  * PCBs together (for connected socket types) or points at the destination
216  * socket (for connectionless socket types).  The operations of creating or
217  * destroying a connection therefore involve locking multiple PCBs.  To avoid
218  * lock order reversals, in some cases this involves dropping a PCB lock and
219  * using a reference counter to maintain liveness.
220  *
221  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
222  * allocated in pr_attach() and freed in pr_detach().  The validity of that
223  * pointer is an invariant, so no lock is required to dereference the so_pcb
224  * pointer if a valid socket reference is held by the caller.  In practice,
225  * this is always true during operations performed on a socket.  Each unpcb
226  * has a back-pointer to its socket, unp_socket, which will be stable under
227  * the same circumstances.
228  *
229  * This pointer may only be safely dereferenced as long as a valid reference
230  * to the unpcb is held.  Typically, this reference will be from the socket,
231  * or from another unpcb when the referring unpcb's lock is held (in order
232  * that the reference not be invalidated during use).  For example, to follow
233  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
234  * that detach is not run clearing unp_socket.
235  *
236  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
237  * protocols, bind() is a non-atomic operation, and connect() requires
238  * potential sleeping in the protocol, due to potentially waiting on local or
239  * distributed file systems.  We try to separate "lookup" operations, which
240  * may sleep, and the IPC operations themselves, which typically can occur
241  * with relative atomicity as locks can be held over the entire operation.
242  *
243  * Another tricky issue is simultaneous multi-threaded or multi-process
244  * access to a single UNIX domain socket.  These are handled by the flags
245  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
246  * binding, both of which involve dropping UNIX domain socket locks in order
247  * to perform namei() and other file system operations.
248  */
249 static struct rwlock	unp_link_rwlock;
250 static struct mtx	unp_defers_lock;
251 
252 #define	UNP_LINK_LOCK_INIT()		rw_init(&unp_link_rwlock,	\
253 					    "unp_link_rwlock")
254 
255 #define	UNP_LINK_LOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
256 					    RA_LOCKED)
257 #define	UNP_LINK_UNLOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
258 					    RA_UNLOCKED)
259 
260 #define	UNP_LINK_RLOCK()		rw_rlock(&unp_link_rwlock)
261 #define	UNP_LINK_RUNLOCK()		rw_runlock(&unp_link_rwlock)
262 #define	UNP_LINK_WLOCK()		rw_wlock(&unp_link_rwlock)
263 #define	UNP_LINK_WUNLOCK()		rw_wunlock(&unp_link_rwlock)
264 #define	UNP_LINK_WLOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
265 					    RA_WLOCKED)
266 #define	UNP_LINK_WOWNED()		rw_wowned(&unp_link_rwlock)
267 
268 #define	UNP_DEFERRED_LOCK_INIT()	mtx_init(&unp_defers_lock, \
269 					    "unp_defer", NULL, MTX_DEF)
270 #define	UNP_DEFERRED_LOCK()		mtx_lock(&unp_defers_lock)
271 #define	UNP_DEFERRED_UNLOCK()		mtx_unlock(&unp_defers_lock)
272 
273 #define UNP_REF_LIST_LOCK()		UNP_DEFERRED_LOCK();
274 #define UNP_REF_LIST_UNLOCK()		UNP_DEFERRED_UNLOCK();
275 
276 #define UNP_PCB_LOCK_INIT(unp)		mtx_init(&(unp)->unp_mtx,	\
277 					    "unp", "unp",	\
278 					    MTX_DUPOK|MTX_DEF)
279 #define	UNP_PCB_LOCK_DESTROY(unp)	mtx_destroy(&(unp)->unp_mtx)
280 #define	UNP_PCB_LOCKPTR(unp)		(&(unp)->unp_mtx)
281 #define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
282 #define	UNP_PCB_TRYLOCK(unp)		mtx_trylock(&(unp)->unp_mtx)
283 #define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
284 #define	UNP_PCB_OWNED(unp)		mtx_owned(&(unp)->unp_mtx)
285 #define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
286 #define	UNP_PCB_UNLOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
287 
288 static int	uipc_connect2(struct socket *, struct socket *);
289 static int	uipc_ctloutput(struct socket *, struct sockopt *);
290 static int	unp_connect(struct socket *, struct sockaddr *,
291 		    struct thread *);
292 static int	unp_connectat(int, struct socket *, struct sockaddr *,
293 		    struct thread *, bool);
294 static void	unp_connect2(struct socket *so, struct socket *so2);
295 static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
296 static void	unp_dispose(struct socket *so);
297 static void	unp_shutdown(struct unpcb *);
298 static void	unp_drop(struct unpcb *);
299 static void	unp_gc(__unused void *, int);
300 static void	unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
301 static void	unp_discard(struct file *);
302 static void	unp_freerights(struct filedescent **, int);
303 static int	unp_internalize(struct mbuf **, struct thread *,
304 		    struct mbuf **, u_int *, u_int *);
305 static void	unp_internalize_fp(struct file *);
306 static int	unp_externalize(struct mbuf *, struct mbuf **, int);
307 static int	unp_externalize_fp(struct file *);
308 static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *,
309 		    int, struct mbuf **, u_int *, u_int *);
310 static void	unp_process_defers(void * __unused, int);
311 
312 static void
313 unp_pcb_hold(struct unpcb *unp)
314 {
315 	u_int old __unused;
316 
317 	old = refcount_acquire(&unp->unp_refcount);
318 	KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
319 }
320 
321 static __result_use_check bool
322 unp_pcb_rele(struct unpcb *unp)
323 {
324 	bool ret;
325 
326 	UNP_PCB_LOCK_ASSERT(unp);
327 
328 	if ((ret = refcount_release(&unp->unp_refcount))) {
329 		UNP_PCB_UNLOCK(unp);
330 		UNP_PCB_LOCK_DESTROY(unp);
331 		uma_zfree(unp_zone, unp);
332 	}
333 	return (ret);
334 }
335 
336 static void
337 unp_pcb_rele_notlast(struct unpcb *unp)
338 {
339 	bool ret __unused;
340 
341 	ret = refcount_release(&unp->unp_refcount);
342 	KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
343 }
344 
345 static void
346 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
347 {
348 	UNP_PCB_UNLOCK_ASSERT(unp);
349 	UNP_PCB_UNLOCK_ASSERT(unp2);
350 
351 	if (unp == unp2) {
352 		UNP_PCB_LOCK(unp);
353 	} else if ((uintptr_t)unp2 > (uintptr_t)unp) {
354 		UNP_PCB_LOCK(unp);
355 		UNP_PCB_LOCK(unp2);
356 	} else {
357 		UNP_PCB_LOCK(unp2);
358 		UNP_PCB_LOCK(unp);
359 	}
360 }
361 
362 static void
363 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
364 {
365 	UNP_PCB_UNLOCK(unp);
366 	if (unp != unp2)
367 		UNP_PCB_UNLOCK(unp2);
368 }
369 
370 /*
371  * Try to lock the connected peer of an already locked socket.  In some cases
372  * this requires that we unlock the current socket.  The pairbusy counter is
373  * used to block concurrent connection attempts while the lock is dropped.  The
374  * caller must be careful to revalidate PCB state.
375  */
376 static struct unpcb *
377 unp_pcb_lock_peer(struct unpcb *unp)
378 {
379 	struct unpcb *unp2;
380 
381 	UNP_PCB_LOCK_ASSERT(unp);
382 	unp2 = unp->unp_conn;
383 	if (unp2 == NULL)
384 		return (NULL);
385 	if (__predict_false(unp == unp2))
386 		return (unp);
387 
388 	UNP_PCB_UNLOCK_ASSERT(unp2);
389 
390 	if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
391 		return (unp2);
392 	if ((uintptr_t)unp2 > (uintptr_t)unp) {
393 		UNP_PCB_LOCK(unp2);
394 		return (unp2);
395 	}
396 	unp->unp_pairbusy++;
397 	unp_pcb_hold(unp2);
398 	UNP_PCB_UNLOCK(unp);
399 
400 	UNP_PCB_LOCK(unp2);
401 	UNP_PCB_LOCK(unp);
402 	KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
403 	    ("%s: socket %p was reconnected", __func__, unp));
404 	if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
405 		unp->unp_flags &= ~UNP_WAITING;
406 		wakeup(unp);
407 	}
408 	if (unp_pcb_rele(unp2)) {
409 		/* unp2 is unlocked. */
410 		return (NULL);
411 	}
412 	if (unp->unp_conn == NULL) {
413 		UNP_PCB_UNLOCK(unp2);
414 		return (NULL);
415 	}
416 	return (unp2);
417 }
418 
419 static void
420 uipc_abort(struct socket *so)
421 {
422 	struct unpcb *unp, *unp2;
423 
424 	unp = sotounpcb(so);
425 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
426 	UNP_PCB_UNLOCK_ASSERT(unp);
427 
428 	UNP_PCB_LOCK(unp);
429 	unp2 = unp->unp_conn;
430 	if (unp2 != NULL) {
431 		unp_pcb_hold(unp2);
432 		UNP_PCB_UNLOCK(unp);
433 		unp_drop(unp2);
434 	} else
435 		UNP_PCB_UNLOCK(unp);
436 }
437 
438 static int
439 uipc_attach(struct socket *so, int proto, struct thread *td)
440 {
441 	u_long sendspace, recvspace;
442 	struct unpcb *unp;
443 	int error;
444 	bool locked;
445 
446 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
447 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
448 		switch (so->so_type) {
449 		case SOCK_STREAM:
450 			sendspace = unpst_sendspace;
451 			recvspace = unpst_recvspace;
452 			break;
453 
454 		case SOCK_DGRAM:
455 			STAILQ_INIT(&so->so_rcv.uxdg_mb);
456 			STAILQ_INIT(&so->so_snd.uxdg_mb);
457 			TAILQ_INIT(&so->so_rcv.uxdg_conns);
458 			/*
459 			 * Since send buffer is either bypassed or is a part
460 			 * of one-to-many receive buffer, we assign both space
461 			 * limits to unpdg_recvspace.
462 			 */
463 			sendspace = recvspace = unpdg_recvspace;
464 			break;
465 
466 		case SOCK_SEQPACKET:
467 			sendspace = unpsp_sendspace;
468 			recvspace = unpsp_recvspace;
469 			break;
470 
471 		default:
472 			panic("uipc_attach");
473 		}
474 		error = soreserve(so, sendspace, recvspace);
475 		if (error)
476 			return (error);
477 	}
478 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
479 	if (unp == NULL)
480 		return (ENOBUFS);
481 	LIST_INIT(&unp->unp_refs);
482 	UNP_PCB_LOCK_INIT(unp);
483 	unp->unp_socket = so;
484 	so->so_pcb = unp;
485 	refcount_init(&unp->unp_refcount, 1);
486 
487 	if ((locked = UNP_LINK_WOWNED()) == false)
488 		UNP_LINK_WLOCK();
489 
490 	unp->unp_gencnt = ++unp_gencnt;
491 	unp->unp_ino = ++unp_ino;
492 	unp_count++;
493 	switch (so->so_type) {
494 	case SOCK_STREAM:
495 		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
496 		break;
497 
498 	case SOCK_DGRAM:
499 		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
500 		break;
501 
502 	case SOCK_SEQPACKET:
503 		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
504 		break;
505 
506 	default:
507 		panic("uipc_attach");
508 	}
509 
510 	if (locked == false)
511 		UNP_LINK_WUNLOCK();
512 
513 	return (0);
514 }
515 
516 static int
517 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
518 {
519 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
520 	struct vattr vattr;
521 	int error, namelen;
522 	struct nameidata nd;
523 	struct unpcb *unp;
524 	struct vnode *vp;
525 	struct mount *mp;
526 	cap_rights_t rights;
527 	char *buf;
528 
529 	if (nam->sa_family != AF_UNIX)
530 		return (EAFNOSUPPORT);
531 
532 	unp = sotounpcb(so);
533 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
534 
535 	if (soun->sun_len > sizeof(struct sockaddr_un))
536 		return (EINVAL);
537 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
538 	if (namelen <= 0)
539 		return (EINVAL);
540 
541 	/*
542 	 * We don't allow simultaneous bind() calls on a single UNIX domain
543 	 * socket, so flag in-progress operations, and return an error if an
544 	 * operation is already in progress.
545 	 *
546 	 * Historically, we have not allowed a socket to be rebound, so this
547 	 * also returns an error.  Not allowing re-binding simplifies the
548 	 * implementation and avoids a great many possible failure modes.
549 	 */
550 	UNP_PCB_LOCK(unp);
551 	if (unp->unp_vnode != NULL) {
552 		UNP_PCB_UNLOCK(unp);
553 		return (EINVAL);
554 	}
555 	if (unp->unp_flags & UNP_BINDING) {
556 		UNP_PCB_UNLOCK(unp);
557 		return (EALREADY);
558 	}
559 	unp->unp_flags |= UNP_BINDING;
560 	UNP_PCB_UNLOCK(unp);
561 
562 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
563 	bcopy(soun->sun_path, buf, namelen);
564 	buf[namelen] = 0;
565 
566 restart:
567 	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | NOCACHE,
568 	    UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
569 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
570 	error = namei(&nd);
571 	if (error)
572 		goto error;
573 	vp = nd.ni_vp;
574 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
575 		NDFREE_PNBUF(&nd);
576 		if (nd.ni_dvp == vp)
577 			vrele(nd.ni_dvp);
578 		else
579 			vput(nd.ni_dvp);
580 		if (vp != NULL) {
581 			vrele(vp);
582 			error = EADDRINUSE;
583 			goto error;
584 		}
585 		error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH);
586 		if (error)
587 			goto error;
588 		goto restart;
589 	}
590 	VATTR_NULL(&vattr);
591 	vattr.va_type = VSOCK;
592 	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
593 #ifdef MAC
594 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
595 	    &vattr);
596 #endif
597 	if (error == 0)
598 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
599 	NDFREE_PNBUF(&nd);
600 	if (error) {
601 		VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
602 		vn_finished_write(mp);
603 		if (error == ERELOOKUP)
604 			goto restart;
605 		goto error;
606 	}
607 	vp = nd.ni_vp;
608 	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
609 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
610 
611 	UNP_PCB_LOCK(unp);
612 	VOP_UNP_BIND(vp, unp);
613 	unp->unp_vnode = vp;
614 	unp->unp_addr = soun;
615 	unp->unp_flags &= ~UNP_BINDING;
616 	UNP_PCB_UNLOCK(unp);
617 	vref(vp);
618 	VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
619 	vn_finished_write(mp);
620 	free(buf, M_TEMP);
621 	return (0);
622 
623 error:
624 	UNP_PCB_LOCK(unp);
625 	unp->unp_flags &= ~UNP_BINDING;
626 	UNP_PCB_UNLOCK(unp);
627 	free(buf, M_TEMP);
628 	return (error);
629 }
630 
631 static int
632 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
633 {
634 
635 	return (uipc_bindat(AT_FDCWD, so, nam, td));
636 }
637 
638 static int
639 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
640 {
641 	int error;
642 
643 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
644 	error = unp_connect(so, nam, td);
645 	return (error);
646 }
647 
648 static int
649 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
650     struct thread *td)
651 {
652 	int error;
653 
654 	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
655 	error = unp_connectat(fd, so, nam, td, false);
656 	return (error);
657 }
658 
659 static void
660 uipc_close(struct socket *so)
661 {
662 	struct unpcb *unp, *unp2;
663 	struct vnode *vp = NULL;
664 	struct mtx *vplock;
665 
666 	unp = sotounpcb(so);
667 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
668 
669 	vplock = NULL;
670 	if ((vp = unp->unp_vnode) != NULL) {
671 		vplock = mtx_pool_find(mtxpool_sleep, vp);
672 		mtx_lock(vplock);
673 	}
674 	UNP_PCB_LOCK(unp);
675 	if (vp && unp->unp_vnode == NULL) {
676 		mtx_unlock(vplock);
677 		vp = NULL;
678 	}
679 	if (vp != NULL) {
680 		VOP_UNP_DETACH(vp);
681 		unp->unp_vnode = NULL;
682 	}
683 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
684 		unp_disconnect(unp, unp2);
685 	else
686 		UNP_PCB_UNLOCK(unp);
687 	if (vp) {
688 		mtx_unlock(vplock);
689 		vrele(vp);
690 	}
691 }
692 
693 static int
694 uipc_connect2(struct socket *so1, struct socket *so2)
695 {
696 	struct unpcb *unp, *unp2;
697 
698 	if (so1->so_type != so2->so_type)
699 		return (EPROTOTYPE);
700 
701 	unp = so1->so_pcb;
702 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
703 	unp2 = so2->so_pcb;
704 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
705 	unp_pcb_lock_pair(unp, unp2);
706 	unp_connect2(so1, so2);
707 	unp_pcb_unlock_pair(unp, unp2);
708 
709 	return (0);
710 }
711 
712 static void
713 uipc_detach(struct socket *so)
714 {
715 	struct unpcb *unp, *unp2;
716 	struct mtx *vplock;
717 	struct vnode *vp;
718 	int local_unp_rights;
719 
720 	unp = sotounpcb(so);
721 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
722 
723 	vp = NULL;
724 	vplock = NULL;
725 
726 	if (!SOLISTENING(so))
727 		unp_dispose(so);
728 
729 	UNP_LINK_WLOCK();
730 	LIST_REMOVE(unp, unp_link);
731 	if (unp->unp_gcflag & UNPGC_DEAD)
732 		LIST_REMOVE(unp, unp_dead);
733 	unp->unp_gencnt = ++unp_gencnt;
734 	--unp_count;
735 	UNP_LINK_WUNLOCK();
736 
737 	UNP_PCB_UNLOCK_ASSERT(unp);
738  restart:
739 	if ((vp = unp->unp_vnode) != NULL) {
740 		vplock = mtx_pool_find(mtxpool_sleep, vp);
741 		mtx_lock(vplock);
742 	}
743 	UNP_PCB_LOCK(unp);
744 	if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
745 		if (vplock)
746 			mtx_unlock(vplock);
747 		UNP_PCB_UNLOCK(unp);
748 		goto restart;
749 	}
750 	if ((vp = unp->unp_vnode) != NULL) {
751 		VOP_UNP_DETACH(vp);
752 		unp->unp_vnode = NULL;
753 	}
754 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
755 		unp_disconnect(unp, unp2);
756 	else
757 		UNP_PCB_UNLOCK(unp);
758 
759 	UNP_REF_LIST_LOCK();
760 	while (!LIST_EMPTY(&unp->unp_refs)) {
761 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
762 
763 		unp_pcb_hold(ref);
764 		UNP_REF_LIST_UNLOCK();
765 
766 		MPASS(ref != unp);
767 		UNP_PCB_UNLOCK_ASSERT(ref);
768 		unp_drop(ref);
769 		UNP_REF_LIST_LOCK();
770 	}
771 	UNP_REF_LIST_UNLOCK();
772 
773 	UNP_PCB_LOCK(unp);
774 	local_unp_rights = unp_rights;
775 	unp->unp_socket->so_pcb = NULL;
776 	unp->unp_socket = NULL;
777 	free(unp->unp_addr, M_SONAME);
778 	unp->unp_addr = NULL;
779 	if (!unp_pcb_rele(unp))
780 		UNP_PCB_UNLOCK(unp);
781 	if (vp) {
782 		mtx_unlock(vplock);
783 		vrele(vp);
784 	}
785 	if (local_unp_rights)
786 		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
787 
788 	switch (so->so_type) {
789 	case SOCK_DGRAM:
790 		/*
791 		 * Everything should have been unlinked/freed by unp_dispose()
792 		 * and/or unp_disconnect().
793 		 */
794 		MPASS(so->so_rcv.uxdg_peeked == NULL);
795 		MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb));
796 		MPASS(TAILQ_EMPTY(&so->so_rcv.uxdg_conns));
797 		MPASS(STAILQ_EMPTY(&so->so_snd.uxdg_mb));
798 	}
799 }
800 
801 static int
802 uipc_disconnect(struct socket *so)
803 {
804 	struct unpcb *unp, *unp2;
805 
806 	unp = sotounpcb(so);
807 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
808 
809 	UNP_PCB_LOCK(unp);
810 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
811 		unp_disconnect(unp, unp2);
812 	else
813 		UNP_PCB_UNLOCK(unp);
814 	return (0);
815 }
816 
817 static int
818 uipc_listen(struct socket *so, int backlog, struct thread *td)
819 {
820 	struct unpcb *unp;
821 	int error;
822 
823 	MPASS(so->so_type != SOCK_DGRAM);
824 
825 	/*
826 	 * Synchronize with concurrent connection attempts.
827 	 */
828 	error = 0;
829 	unp = sotounpcb(so);
830 	UNP_PCB_LOCK(unp);
831 	if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
832 		error = EINVAL;
833 	else if (unp->unp_vnode == NULL)
834 		error = EDESTADDRREQ;
835 	if (error != 0) {
836 		UNP_PCB_UNLOCK(unp);
837 		return (error);
838 	}
839 
840 	SOCK_LOCK(so);
841 	error = solisten_proto_check(so);
842 	if (error == 0) {
843 		cru2xt(td, &unp->unp_peercred);
844 		solisten_proto(so, backlog);
845 	}
846 	SOCK_UNLOCK(so);
847 	UNP_PCB_UNLOCK(unp);
848 	return (error);
849 }
850 
851 static int
852 uipc_peeraddr(struct socket *so, struct sockaddr *ret)
853 {
854 	struct unpcb *unp, *unp2;
855 	const struct sockaddr *sa;
856 
857 	unp = sotounpcb(so);
858 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
859 
860 	UNP_PCB_LOCK(unp);
861 	unp2 = unp_pcb_lock_peer(unp);
862 	if (unp2 != NULL) {
863 		if (unp2->unp_addr != NULL)
864 			sa = (struct sockaddr *)unp2->unp_addr;
865 		else
866 			sa = &sun_noname;
867 		bcopy(sa, ret, sa->sa_len);
868 		unp_pcb_unlock_pair(unp, unp2);
869 	} else {
870 		UNP_PCB_UNLOCK(unp);
871 		sa = &sun_noname;
872 		bcopy(sa, ret, sa->sa_len);
873 	}
874 	return (0);
875 }
876 
877 static int
878 uipc_rcvd(struct socket *so, int flags)
879 {
880 	struct unpcb *unp, *unp2;
881 	struct socket *so2;
882 	u_int mbcnt, sbcc;
883 
884 	unp = sotounpcb(so);
885 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
886 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
887 	    ("%s: socktype %d", __func__, so->so_type));
888 
889 	/*
890 	 * Adjust backpressure on sender and wakeup any waiting to write.
891 	 *
892 	 * The unp lock is acquired to maintain the validity of the unp_conn
893 	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
894 	 * static as long as we don't permit unp2 to disconnect from unp,
895 	 * which is prevented by the lock on unp.  We cache values from
896 	 * so_rcv to avoid holding the so_rcv lock over the entire
897 	 * transaction on the remote so_snd.
898 	 */
899 	SOCKBUF_LOCK(&so->so_rcv);
900 	mbcnt = so->so_rcv.sb_mbcnt;
901 	sbcc = sbavail(&so->so_rcv);
902 	SOCKBUF_UNLOCK(&so->so_rcv);
903 	/*
904 	 * There is a benign race condition at this point.  If we're planning to
905 	 * clear SB_STOP, but uipc_send is called on the connected socket at
906 	 * this instant, it might add data to the sockbuf and set SB_STOP.  Then
907 	 * we would erroneously clear SB_STOP below, even though the sockbuf is
908 	 * full.  The race is benign because the only ill effect is to allow the
909 	 * sockbuf to exceed its size limit, and the size limits are not
910 	 * strictly guaranteed anyway.
911 	 */
912 	UNP_PCB_LOCK(unp);
913 	unp2 = unp->unp_conn;
914 	if (unp2 == NULL) {
915 		UNP_PCB_UNLOCK(unp);
916 		return (0);
917 	}
918 	so2 = unp2->unp_socket;
919 	SOCKBUF_LOCK(&so2->so_snd);
920 	if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
921 		so2->so_snd.sb_flags &= ~SB_STOP;
922 	sowwakeup_locked(so2);
923 	UNP_PCB_UNLOCK(unp);
924 	return (0);
925 }
926 
927 static int
928 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
929     struct mbuf *control, struct thread *td)
930 {
931 	struct unpcb *unp, *unp2;
932 	struct socket *so2;
933 	u_int mbcnt, sbcc;
934 	int error;
935 
936 	unp = sotounpcb(so);
937 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
938 	KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
939 	    ("%s: socktype %d", __func__, so->so_type));
940 
941 	error = 0;
942 	if (flags & PRUS_OOB) {
943 		error = EOPNOTSUPP;
944 		goto release;
945 	}
946 	if (control != NULL &&
947 	    (error = unp_internalize(&control, td, NULL, NULL, NULL)))
948 		goto release;
949 
950 	unp2 = NULL;
951 	if ((so->so_state & SS_ISCONNECTED) == 0) {
952 		if (nam != NULL) {
953 			if ((error = unp_connect(so, nam, td)) != 0)
954 				goto out;
955 		} else {
956 			error = ENOTCONN;
957 			goto out;
958 		}
959 	}
960 
961 	UNP_PCB_LOCK(unp);
962 	if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
963 		UNP_PCB_UNLOCK(unp);
964 		error = ENOTCONN;
965 		goto out;
966 	} else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
967 		unp_pcb_unlock_pair(unp, unp2);
968 		error = EPIPE;
969 		goto out;
970 	}
971 	UNP_PCB_UNLOCK(unp);
972 	if ((so2 = unp2->unp_socket) == NULL) {
973 		UNP_PCB_UNLOCK(unp2);
974 		error = ENOTCONN;
975 		goto out;
976 	}
977 	SOCKBUF_LOCK(&so2->so_rcv);
978 	if (unp2->unp_flags & UNP_WANTCRED_MASK) {
979 		/*
980 		 * Credentials are passed only once on SOCK_STREAM and
981 		 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
982 		 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
983 		 */
984 		control = unp_addsockcred(td, control, unp2->unp_flags, NULL,
985 		    NULL, NULL);
986 		unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
987 	}
988 
989 	/*
990 	 * Send to paired receive port and wake up readers.  Don't
991 	 * check for space available in the receive buffer if we're
992 	 * attaching ancillary data; Unix domain sockets only check
993 	 * for space in the sending sockbuf, and that check is
994 	 * performed one level up the stack.  At that level we cannot
995 	 * precisely account for the amount of buffer space used
996 	 * (e.g., because control messages are not yet internalized).
997 	 */
998 	switch (so->so_type) {
999 	case SOCK_STREAM:
1000 		if (control != NULL) {
1001 			sbappendcontrol_locked(&so2->so_rcv,
1002 			    m->m_len > 0 ?  m : NULL, control, flags);
1003 			control = NULL;
1004 		} else
1005 			sbappend_locked(&so2->so_rcv, m, flags);
1006 		break;
1007 
1008 	case SOCK_SEQPACKET:
1009 		if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1010 		    &sun_noname, m, control))
1011 			control = NULL;
1012 		break;
1013 	}
1014 
1015 	mbcnt = so2->so_rcv.sb_mbcnt;
1016 	sbcc = sbavail(&so2->so_rcv);
1017 	if (sbcc)
1018 		sorwakeup_locked(so2);
1019 	else
1020 		SOCKBUF_UNLOCK(&so2->so_rcv);
1021 
1022 	/*
1023 	 * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1024 	 * it would be possible for uipc_rcvd to be called at this
1025 	 * point, drain the receiving sockbuf, clear SB_STOP, and then
1026 	 * we would set SB_STOP below.  That could lead to an empty
1027 	 * sockbuf having SB_STOP set
1028 	 */
1029 	SOCKBUF_LOCK(&so->so_snd);
1030 	if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1031 		so->so_snd.sb_flags |= SB_STOP;
1032 	SOCKBUF_UNLOCK(&so->so_snd);
1033 	UNP_PCB_UNLOCK(unp2);
1034 	m = NULL;
1035 out:
1036 	/*
1037 	 * PRUS_EOF is equivalent to pr_send followed by pr_shutdown.
1038 	 */
1039 	if (flags & PRUS_EOF) {
1040 		UNP_PCB_LOCK(unp);
1041 		socantsendmore(so);
1042 		unp_shutdown(unp);
1043 		UNP_PCB_UNLOCK(unp);
1044 	}
1045 	if (control != NULL && error != 0)
1046 		unp_scan(control, unp_freerights);
1047 
1048 release:
1049 	if (control != NULL)
1050 		m_freem(control);
1051 	/*
1052 	 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1053 	 * for freeing memory.
1054 	 */
1055 	if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1056 		m_freem(m);
1057 	return (error);
1058 }
1059 
1060 /* PF_UNIX/SOCK_DGRAM version of sbspace() */
1061 static inline bool
1062 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt)
1063 {
1064 	u_int bleft, mleft;
1065 
1066 	/*
1067 	 * Negative space may happen if send(2) is followed by
1068 	 * setsockopt(SO_SNDBUF/SO_RCVBUF) that shrinks maximum.
1069 	 */
1070 	if (__predict_false(sb->sb_hiwat < sb->uxdg_cc ||
1071 	    sb->sb_mbmax < sb->uxdg_mbcnt))
1072 		return (false);
1073 
1074 	if (__predict_false(sb->sb_state & SBS_CANTRCVMORE))
1075 		return (false);
1076 
1077 	bleft = sb->sb_hiwat - sb->uxdg_cc;
1078 	mleft = sb->sb_mbmax - sb->uxdg_mbcnt;
1079 
1080 	return (bleft >= cc && mleft >= mbcnt);
1081 }
1082 
1083 /*
1084  * PF_UNIX/SOCK_DGRAM send
1085  *
1086  * Allocate a record consisting of 3 mbufs in the sequence of
1087  * from -> control -> data and append it to the socket buffer.
1088  *
1089  * The first mbuf carries sender's name and is a pkthdr that stores
1090  * overall length of datagram, its memory consumption and control length.
1091  */
1092 #define	ctllen	PH_loc.thirtytwo[1]
1093 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <=
1094     offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen");
1095 static int
1096 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1097     struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
1098 {
1099 	struct unpcb *unp, *unp2;
1100 	const struct sockaddr *from;
1101 	struct socket *so2;
1102 	struct sockbuf *sb;
1103 	struct mbuf *f, *clast;
1104 	u_int cc, ctl, mbcnt;
1105 	u_int dcc __diagused, dctl __diagused, dmbcnt __diagused;
1106 	int error;
1107 
1108 	MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
1109 
1110 	error = 0;
1111 	f = NULL;
1112 	ctl = 0;
1113 
1114 	if (__predict_false(flags & MSG_OOB)) {
1115 		error = EOPNOTSUPP;
1116 		goto out;
1117 	}
1118 	if (m == NULL) {
1119 		if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
1120 			error = EMSGSIZE;
1121 			goto out;
1122 		}
1123 		m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
1124 		if (__predict_false(m == NULL)) {
1125 			error = EFAULT;
1126 			goto out;
1127 		}
1128 		f = m_gethdr(M_WAITOK, MT_SONAME);
1129 		cc = m->m_pkthdr.len;
1130 		mbcnt = MSIZE + m->m_pkthdr.memlen;
1131 		if (c != NULL &&
1132 		    (error = unp_internalize(&c, td, &clast, &ctl, &mbcnt)))
1133 			goto out;
1134 	} else {
1135 		/* pr_sosend() with mbuf usually is a kernel thread. */
1136 
1137 		M_ASSERTPKTHDR(m);
1138 		if (__predict_false(c != NULL))
1139 			panic("%s: control from a kernel thread", __func__);
1140 
1141 		if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
1142 			error = EMSGSIZE;
1143 			goto out;
1144 		}
1145 		if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) {
1146 			error = ENOBUFS;
1147 			goto out;
1148 		}
1149 		/* Condition the foreign mbuf to our standards. */
1150 		m_clrprotoflags(m);
1151 		m_tag_delete_chain(m, NULL);
1152 		m->m_pkthdr.rcvif = NULL;
1153 		m->m_pkthdr.flowid = 0;
1154 		m->m_pkthdr.csum_flags = 0;
1155 		m->m_pkthdr.fibnum = 0;
1156 		m->m_pkthdr.rsstype = 0;
1157 
1158 		cc = m->m_pkthdr.len;
1159 		mbcnt = MSIZE;
1160 		for (struct mbuf *mb = m; mb != NULL; mb = mb->m_next) {
1161 			mbcnt += MSIZE;
1162 			if (mb->m_flags & M_EXT)
1163 				mbcnt += mb->m_ext.ext_size;
1164 		}
1165 	}
1166 
1167 	unp = sotounpcb(so);
1168 	MPASS(unp);
1169 
1170 	/*
1171 	 * XXXGL: would be cool to fully remove so_snd out of the equation
1172 	 * and avoid this lock, which is not only extraneous, but also being
1173 	 * released, thus still leaving possibility for a race.  We can easily
1174 	 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
1175 	 * is more difficult to invent something to handle so_error.
1176 	 */
1177 	error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1178 	if (error)
1179 		goto out2;
1180 	SOCK_SENDBUF_LOCK(so);
1181 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1182 		SOCK_SENDBUF_UNLOCK(so);
1183 		error = EPIPE;
1184 		goto out3;
1185 	}
1186 	if (so->so_error != 0) {
1187 		error = so->so_error;
1188 		so->so_error = 0;
1189 		SOCK_SENDBUF_UNLOCK(so);
1190 		goto out3;
1191 	}
1192 	if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
1193 		SOCK_SENDBUF_UNLOCK(so);
1194 		error = EDESTADDRREQ;
1195 		goto out3;
1196 	}
1197 	SOCK_SENDBUF_UNLOCK(so);
1198 
1199 	if (addr != NULL) {
1200 		if ((error = unp_connectat(AT_FDCWD, so, addr, td, true)))
1201 			goto out3;
1202 		UNP_PCB_LOCK_ASSERT(unp);
1203 		unp2 = unp->unp_conn;
1204 		UNP_PCB_LOCK_ASSERT(unp2);
1205 	} else {
1206 		UNP_PCB_LOCK(unp);
1207 		unp2 = unp_pcb_lock_peer(unp);
1208 		if (unp2 == NULL) {
1209 			UNP_PCB_UNLOCK(unp);
1210 			error = ENOTCONN;
1211 			goto out3;
1212 		}
1213 	}
1214 
1215 	if (unp2->unp_flags & UNP_WANTCRED_MASK)
1216 		c = unp_addsockcred(td, c, unp2->unp_flags, &clast, &ctl,
1217 		    &mbcnt);
1218 	if (unp->unp_addr != NULL)
1219 		from = (struct sockaddr *)unp->unp_addr;
1220 	else
1221 		from = &sun_noname;
1222 	f->m_len = from->sa_len;
1223 	MPASS(from->sa_len <= MLEN);
1224 	bcopy(from, mtod(f, void *), from->sa_len);
1225 	ctl += f->m_len;
1226 
1227 	/*
1228 	 * Concatenate mbufs: from -> control -> data.
1229 	 * Save overall cc and mbcnt in "from" mbuf.
1230 	 */
1231 	if (c != NULL) {
1232 #ifdef INVARIANTS
1233 		struct mbuf *mc;
1234 
1235 		for (mc = c; mc->m_next != NULL; mc = mc->m_next);
1236 		MPASS(mc == clast);
1237 #endif
1238 		f->m_next = c;
1239 		clast->m_next = m;
1240 		c = NULL;
1241 	} else
1242 		f->m_next = m;
1243 	m = NULL;
1244 #ifdef INVARIANTS
1245 	dcc = dctl = dmbcnt = 0;
1246 	for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) {
1247 		if (mb->m_type == MT_DATA)
1248 			dcc += mb->m_len;
1249 		else
1250 			dctl += mb->m_len;
1251 		dmbcnt += MSIZE;
1252 		if (mb->m_flags & M_EXT)
1253 			dmbcnt += mb->m_ext.ext_size;
1254 	}
1255 	MPASS(dcc == cc);
1256 	MPASS(dctl == ctl);
1257 	MPASS(dmbcnt == mbcnt);
1258 #endif
1259 	f->m_pkthdr.len = cc + ctl;
1260 	f->m_pkthdr.memlen = mbcnt;
1261 	f->m_pkthdr.ctllen = ctl;
1262 
1263 	/*
1264 	 * Destination socket buffer selection.
1265 	 *
1266 	 * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the
1267 	 * destination address is supplied, create a temporary connection for
1268 	 * the run time of the function (see call to unp_connectat() above and
1269 	 * to unp_disconnect() below).  We distinguish them by condition of
1270 	 * (addr != NULL).  We intentionally avoid adding 'bool connected' for
1271 	 * that condition, since, again, through the run time of this code we
1272 	 * are always connected.  For such "unconnected" sends, the destination
1273 	 * buffer would be the receive buffer of destination socket so2.
1274 	 *
1275 	 * For connected sends, data lands on the send buffer of the sender's
1276 	 * socket "so".  Then, if we just added the very first datagram
1277 	 * on this send buffer, we need to add the send buffer on to the
1278 	 * receiving socket's buffer list.  We put ourselves on top of the
1279 	 * list.  Such logic gives infrequent senders priority over frequent
1280 	 * senders.
1281 	 *
1282 	 * Note on byte count management. As long as event methods kevent(2),
1283 	 * select(2) are not protocol specific (yet), we need to maintain
1284 	 * meaningful values on the receive buffer.  So, the receive buffer
1285 	 * would accumulate counters from all connected buffers potentially
1286 	 * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax.
1287 	 */
1288 	so2 = unp2->unp_socket;
1289 	sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv;
1290 	SOCK_RECVBUF_LOCK(so2);
1291 	if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) {
1292 		if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb))
1293 			TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd,
1294 			    uxdg_clist);
1295 		STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
1296 		sb->uxdg_cc += cc + ctl;
1297 		sb->uxdg_ctl += ctl;
1298 		sb->uxdg_mbcnt += mbcnt;
1299 		so2->so_rcv.sb_acc += cc + ctl;
1300 		so2->so_rcv.sb_ccc += cc + ctl;
1301 		so2->so_rcv.sb_ctl += ctl;
1302 		so2->so_rcv.sb_mbcnt += mbcnt;
1303 		sorwakeup_locked(so2);
1304 		f = NULL;
1305 	} else {
1306 		soroverflow_locked(so2);
1307 		error = ENOBUFS;
1308 		if (f->m_next->m_type == MT_CONTROL) {
1309 			c = f->m_next;
1310 			f->m_next = NULL;
1311 		}
1312 	}
1313 
1314 	if (addr != NULL)
1315 		unp_disconnect(unp, unp2);
1316 	else
1317 		unp_pcb_unlock_pair(unp, unp2);
1318 
1319 	td->td_ru.ru_msgsnd++;
1320 
1321 out3:
1322 	SOCK_IO_SEND_UNLOCK(so);
1323 out2:
1324 	if (c)
1325 		unp_scan(c, unp_freerights);
1326 out:
1327 	if (f)
1328 		m_freem(f);
1329 	if (c)
1330 		m_freem(c);
1331 	if (m)
1332 		m_freem(m);
1333 
1334 	return (error);
1335 }
1336 
1337 /*
1338  * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK.
1339  * The mbuf has already been unlinked from the uxdg_mb of socket buffer
1340  * and needs to be linked onto uxdg_peeked of receive socket buffer.
1341  */
1342 static int
1343 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa,
1344     struct uio *uio, struct mbuf **controlp, int *flagsp)
1345 {
1346 	ssize_t len = 0;
1347 	int error;
1348 
1349 	so->so_rcv.uxdg_peeked = m;
1350 	so->so_rcv.uxdg_cc += m->m_pkthdr.len;
1351 	so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen;
1352 	so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen;
1353 	SOCK_RECVBUF_UNLOCK(so);
1354 
1355 	KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1356 	if (psa != NULL)
1357 		*psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1358 
1359 	m = m->m_next;
1360 	KASSERT(m, ("%s: no data or control after soname", __func__));
1361 
1362 	/*
1363 	 * With MSG_PEEK the control isn't executed, just copied.
1364 	 */
1365 	while (m != NULL && m->m_type == MT_CONTROL) {
1366 		if (controlp != NULL) {
1367 			*controlp = m_copym(m, 0, m->m_len, M_WAITOK);
1368 			controlp = &(*controlp)->m_next;
1369 		}
1370 		m = m->m_next;
1371 	}
1372 	KASSERT(m == NULL || m->m_type == MT_DATA,
1373 	    ("%s: not MT_DATA mbuf %p", __func__, m));
1374 	while (m != NULL && uio->uio_resid > 0) {
1375 		len = uio->uio_resid;
1376 		if (len > m->m_len)
1377 			len = m->m_len;
1378 		error = uiomove(mtod(m, char *), (int)len, uio);
1379 		if (error) {
1380 			SOCK_IO_RECV_UNLOCK(so);
1381 			return (error);
1382 		}
1383 		if (len == m->m_len)
1384 			m = m->m_next;
1385 	}
1386 	SOCK_IO_RECV_UNLOCK(so);
1387 
1388 	if (flagsp != NULL) {
1389 		if (m != NULL) {
1390 			if (*flagsp & MSG_TRUNC) {
1391 				/* Report real length of the packet */
1392 				uio->uio_resid -= m_length(m, NULL) - len;
1393 			}
1394 			*flagsp |= MSG_TRUNC;
1395 		} else
1396 			*flagsp &= ~MSG_TRUNC;
1397 	}
1398 
1399 	return (0);
1400 }
1401 
1402 /*
1403  * PF_UNIX/SOCK_DGRAM receive
1404  */
1405 static int
1406 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1407     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1408 {
1409 	struct sockbuf *sb = NULL;
1410 	struct mbuf *m;
1411 	int flags, error;
1412 	ssize_t len = 0;
1413 	bool nonblock;
1414 
1415 	MPASS(mp0 == NULL);
1416 
1417 	if (psa != NULL)
1418 		*psa = NULL;
1419 	if (controlp != NULL)
1420 		*controlp = NULL;
1421 
1422 	flags = flagsp != NULL ? *flagsp : 0;
1423 	nonblock = (so->so_state & SS_NBIO) ||
1424 	    (flags & (MSG_DONTWAIT | MSG_NBIO));
1425 
1426 	error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
1427 	if (__predict_false(error))
1428 		return (error);
1429 
1430 	/*
1431 	 * Loop blocking while waiting for a datagram.  Prioritize connected
1432 	 * peers over unconnected sends.  Set sb to selected socket buffer
1433 	 * containing an mbuf on exit from the wait loop.  A datagram that
1434 	 * had already been peeked at has top priority.
1435 	 */
1436 	SOCK_RECVBUF_LOCK(so);
1437 	while ((m = so->so_rcv.uxdg_peeked) == NULL &&
1438 	    (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL &&
1439 	    (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
1440 		if (so->so_error) {
1441 			error = so->so_error;
1442 			if (!(flags & MSG_PEEK))
1443 				so->so_error = 0;
1444 			SOCK_RECVBUF_UNLOCK(so);
1445 			SOCK_IO_RECV_UNLOCK(so);
1446 			return (error);
1447 		}
1448 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1449 		    uio->uio_resid == 0) {
1450 			SOCK_RECVBUF_UNLOCK(so);
1451 			SOCK_IO_RECV_UNLOCK(so);
1452 			return (0);
1453 		}
1454 		if (nonblock) {
1455 			SOCK_RECVBUF_UNLOCK(so);
1456 			SOCK_IO_RECV_UNLOCK(so);
1457 			return (EWOULDBLOCK);
1458 		}
1459 		error = sbwait(so, SO_RCV);
1460 		if (error) {
1461 			SOCK_RECVBUF_UNLOCK(so);
1462 			SOCK_IO_RECV_UNLOCK(so);
1463 			return (error);
1464 		}
1465 	}
1466 
1467 	if (sb == NULL)
1468 		sb = &so->so_rcv;
1469 	else if (m == NULL)
1470 		m = STAILQ_FIRST(&sb->uxdg_mb);
1471 	else
1472 		MPASS(m == so->so_rcv.uxdg_peeked);
1473 
1474 	MPASS(sb->uxdg_cc > 0);
1475 	M_ASSERTPKTHDR(m);
1476 	KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1477 
1478 	if (uio->uio_td)
1479 		uio->uio_td->td_ru.ru_msgrcv++;
1480 
1481 	if (__predict_true(m != so->so_rcv.uxdg_peeked)) {
1482 		STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt);
1483 		if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv)
1484 			TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
1485 	} else
1486 		so->so_rcv.uxdg_peeked = NULL;
1487 
1488 	sb->uxdg_cc -= m->m_pkthdr.len;
1489 	sb->uxdg_ctl -= m->m_pkthdr.ctllen;
1490 	sb->uxdg_mbcnt -= m->m_pkthdr.memlen;
1491 
1492 	if (__predict_false(flags & MSG_PEEK))
1493 		return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp));
1494 
1495 	so->so_rcv.sb_acc -= m->m_pkthdr.len;
1496 	so->so_rcv.sb_ccc -= m->m_pkthdr.len;
1497 	so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen;
1498 	so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen;
1499 	SOCK_RECVBUF_UNLOCK(so);
1500 
1501 	if (psa != NULL)
1502 		*psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1503 	m = m_free(m);
1504 	KASSERT(m, ("%s: no data or control after soname", __func__));
1505 
1506 	/*
1507 	 * Packet to copyout() is now in 'm' and it is disconnected from the
1508 	 * queue.
1509 	 *
1510 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1511 	 * in the first mbuf chain on the socket buffer.  We call into the
1512 	 * unp_externalize() to perform externalization (or freeing if
1513 	 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
1514 	 * without MT_DATA mbufs.
1515 	 */
1516 	while (m != NULL && m->m_type == MT_CONTROL) {
1517 		struct mbuf *cm;
1518 
1519 		/* XXXGL: unp_externalize() is also dom_externalize() KBI and
1520 		 * it frees whole chain, so we must disconnect the mbuf.
1521 		 */
1522 		cm = m; m = m->m_next; cm->m_next = NULL;
1523 		error = unp_externalize(cm, controlp, flags);
1524 		if (error != 0) {
1525 			SOCK_IO_RECV_UNLOCK(so);
1526 			unp_scan(m, unp_freerights);
1527 			m_freem(m);
1528 			return (error);
1529 		}
1530 		if (controlp != NULL) {
1531 			while (*controlp != NULL)
1532 				controlp = &(*controlp)->m_next;
1533 		}
1534 	}
1535 	KASSERT(m == NULL || m->m_type == MT_DATA,
1536 	    ("%s: not MT_DATA mbuf %p", __func__, m));
1537 	while (m != NULL && uio->uio_resid > 0) {
1538 		len = uio->uio_resid;
1539 		if (len > m->m_len)
1540 			len = m->m_len;
1541 		error = uiomove(mtod(m, char *), (int)len, uio);
1542 		if (error) {
1543 			SOCK_IO_RECV_UNLOCK(so);
1544 			m_freem(m);
1545 			return (error);
1546 		}
1547 		if (len == m->m_len)
1548 			m = m_free(m);
1549 		else {
1550 			m->m_data += len;
1551 			m->m_len -= len;
1552 		}
1553 	}
1554 	SOCK_IO_RECV_UNLOCK(so);
1555 
1556 	if (m != NULL) {
1557 		if (flagsp != NULL) {
1558 			if (flags & MSG_TRUNC) {
1559 				/* Report real length of the packet */
1560 				uio->uio_resid -= m_length(m, NULL);
1561 			}
1562 			*flagsp |= MSG_TRUNC;
1563 		}
1564 		m_freem(m);
1565 	} else if (flagsp != NULL)
1566 		*flagsp &= ~MSG_TRUNC;
1567 
1568 	return (0);
1569 }
1570 
1571 static bool
1572 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1573 {
1574 	struct mbuf *mb, *n;
1575 	struct sockbuf *sb;
1576 
1577 	SOCK_LOCK(so);
1578 	if (SOLISTENING(so)) {
1579 		SOCK_UNLOCK(so);
1580 		return (false);
1581 	}
1582 	mb = NULL;
1583 	sb = &so->so_rcv;
1584 	SOCKBUF_LOCK(sb);
1585 	if (sb->sb_fnrdy != NULL) {
1586 		for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1587 			if (mb == m) {
1588 				*errorp = sbready(sb, m, count);
1589 				break;
1590 			}
1591 			mb = mb->m_next;
1592 			if (mb == NULL) {
1593 				mb = n;
1594 				if (mb != NULL)
1595 					n = mb->m_nextpkt;
1596 			}
1597 		}
1598 	}
1599 	SOCKBUF_UNLOCK(sb);
1600 	SOCK_UNLOCK(so);
1601 	return (mb != NULL);
1602 }
1603 
1604 static int
1605 uipc_ready(struct socket *so, struct mbuf *m, int count)
1606 {
1607 	struct unpcb *unp, *unp2;
1608 	struct socket *so2;
1609 	int error, i;
1610 
1611 	unp = sotounpcb(so);
1612 
1613 	KASSERT(so->so_type == SOCK_STREAM,
1614 	    ("%s: unexpected socket type for %p", __func__, so));
1615 
1616 	UNP_PCB_LOCK(unp);
1617 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1618 		UNP_PCB_UNLOCK(unp);
1619 		so2 = unp2->unp_socket;
1620 		SOCKBUF_LOCK(&so2->so_rcv);
1621 		if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1622 			sorwakeup_locked(so2);
1623 		else
1624 			SOCKBUF_UNLOCK(&so2->so_rcv);
1625 		UNP_PCB_UNLOCK(unp2);
1626 		return (error);
1627 	}
1628 	UNP_PCB_UNLOCK(unp);
1629 
1630 	/*
1631 	 * The receiving socket has been disconnected, but may still be valid.
1632 	 * In this case, the now-ready mbufs are still present in its socket
1633 	 * buffer, so perform an exhaustive search before giving up and freeing
1634 	 * the mbufs.
1635 	 */
1636 	UNP_LINK_RLOCK();
1637 	LIST_FOREACH(unp, &unp_shead, unp_link) {
1638 		if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1639 			break;
1640 	}
1641 	UNP_LINK_RUNLOCK();
1642 
1643 	if (unp == NULL) {
1644 		for (i = 0; i < count; i++)
1645 			m = m_free(m);
1646 		error = ECONNRESET;
1647 	}
1648 	return (error);
1649 }
1650 
1651 static int
1652 uipc_sense(struct socket *so, struct stat *sb)
1653 {
1654 	struct unpcb *unp;
1655 
1656 	unp = sotounpcb(so);
1657 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1658 
1659 	sb->st_blksize = so->so_snd.sb_hiwat;
1660 	sb->st_dev = NODEV;
1661 	sb->st_ino = unp->unp_ino;
1662 	return (0);
1663 }
1664 
1665 static int
1666 uipc_shutdown(struct socket *so, enum shutdown_how how)
1667 {
1668 	struct unpcb *unp = sotounpcb(so);
1669 	int error;
1670 
1671 	SOCK_LOCK(so);
1672 	if ((so->so_state &
1673 	    (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
1674 		/*
1675 		 * POSIX mandates us to just return ENOTCONN when shutdown(2) is
1676 		 * invoked on a datagram sockets, however historically we would
1677 		 * actually tear socket down.  This is known to be leveraged by
1678 		 * some applications to unblock process waiting in recv(2) by
1679 		 * other process that it shares that socket with.  Try to meet
1680 		 * both backward-compatibility and POSIX requirements by forcing
1681 		 * ENOTCONN but still flushing buffers and performing wakeup(9).
1682 		 *
1683 		 * XXXGL: it remains unknown what applications expect this
1684 		 * behavior and is this isolated to unix/dgram or inet/dgram or
1685 		 * both.  See: D10351, D3039.
1686 		 */
1687 		error = ENOTCONN;
1688 		if (so->so_type != SOCK_DGRAM) {
1689 			SOCK_UNLOCK(so);
1690 			return (error);
1691 		}
1692 	} else
1693 		error = 0;
1694 	if (SOLISTENING(so)) {
1695 		if (how != SHUT_WR) {
1696 			so->so_error = ECONNABORTED;
1697 			solisten_wakeup(so);    /* unlocks so */
1698 		} else
1699 			SOCK_UNLOCK(so);
1700 		return (0);
1701 	}
1702 	SOCK_UNLOCK(so);
1703 
1704 	switch (how) {
1705 	case SHUT_RD:
1706 		socantrcvmore(so);
1707 		unp_dispose(so);
1708 		break;
1709 	case SHUT_RDWR:
1710 		socantrcvmore(so);
1711 		unp_dispose(so);
1712 		/* FALLTHROUGH */
1713 	case SHUT_WR:
1714 		UNP_PCB_LOCK(unp);
1715 		socantsendmore(so);
1716 		unp_shutdown(unp);
1717 		UNP_PCB_UNLOCK(unp);
1718 	}
1719 	wakeup(&so->so_timeo);
1720 
1721 	return (error);
1722 }
1723 
1724 static int
1725 uipc_sockaddr(struct socket *so, struct sockaddr *ret)
1726 {
1727 	struct unpcb *unp;
1728 	const struct sockaddr *sa;
1729 
1730 	unp = sotounpcb(so);
1731 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1732 
1733 	UNP_PCB_LOCK(unp);
1734 	if (unp->unp_addr != NULL)
1735 		sa = (struct sockaddr *) unp->unp_addr;
1736 	else
1737 		sa = &sun_noname;
1738 	bcopy(sa, ret, sa->sa_len);
1739 	UNP_PCB_UNLOCK(unp);
1740 	return (0);
1741 }
1742 
1743 static int
1744 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1745 {
1746 	struct unpcb *unp;
1747 	struct xucred xu;
1748 	int error, optval;
1749 
1750 	if (sopt->sopt_level != SOL_LOCAL)
1751 		return (EINVAL);
1752 
1753 	unp = sotounpcb(so);
1754 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1755 	error = 0;
1756 	switch (sopt->sopt_dir) {
1757 	case SOPT_GET:
1758 		switch (sopt->sopt_name) {
1759 		case LOCAL_PEERCRED:
1760 			UNP_PCB_LOCK(unp);
1761 			if (unp->unp_flags & UNP_HAVEPC)
1762 				xu = unp->unp_peercred;
1763 			else {
1764 				if (so->so_type == SOCK_STREAM)
1765 					error = ENOTCONN;
1766 				else
1767 					error = EINVAL;
1768 			}
1769 			UNP_PCB_UNLOCK(unp);
1770 			if (error == 0)
1771 				error = sooptcopyout(sopt, &xu, sizeof(xu));
1772 			break;
1773 
1774 		case LOCAL_CREDS:
1775 			/* Unlocked read. */
1776 			optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
1777 			error = sooptcopyout(sopt, &optval, sizeof(optval));
1778 			break;
1779 
1780 		case LOCAL_CREDS_PERSISTENT:
1781 			/* Unlocked read. */
1782 			optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
1783 			error = sooptcopyout(sopt, &optval, sizeof(optval));
1784 			break;
1785 
1786 		default:
1787 			error = EOPNOTSUPP;
1788 			break;
1789 		}
1790 		break;
1791 
1792 	case SOPT_SET:
1793 		switch (sopt->sopt_name) {
1794 		case LOCAL_CREDS:
1795 		case LOCAL_CREDS_PERSISTENT:
1796 			error = sooptcopyin(sopt, &optval, sizeof(optval),
1797 					    sizeof(optval));
1798 			if (error)
1799 				break;
1800 
1801 #define	OPTSET(bit, exclusive) do {					\
1802 	UNP_PCB_LOCK(unp);						\
1803 	if (optval) {							\
1804 		if ((unp->unp_flags & (exclusive)) != 0) {		\
1805 			UNP_PCB_UNLOCK(unp);				\
1806 			error = EINVAL;					\
1807 			break;						\
1808 		}							\
1809 		unp->unp_flags |= (bit);				\
1810 	} else								\
1811 		unp->unp_flags &= ~(bit);				\
1812 	UNP_PCB_UNLOCK(unp);						\
1813 } while (0)
1814 
1815 			switch (sopt->sopt_name) {
1816 			case LOCAL_CREDS:
1817 				OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
1818 				break;
1819 
1820 			case LOCAL_CREDS_PERSISTENT:
1821 				OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
1822 				break;
1823 
1824 			default:
1825 				break;
1826 			}
1827 			break;
1828 #undef	OPTSET
1829 		default:
1830 			error = ENOPROTOOPT;
1831 			break;
1832 		}
1833 		break;
1834 
1835 	default:
1836 		error = EOPNOTSUPP;
1837 		break;
1838 	}
1839 	return (error);
1840 }
1841 
1842 static int
1843 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1844 {
1845 
1846 	return (unp_connectat(AT_FDCWD, so, nam, td, false));
1847 }
1848 
1849 static int
1850 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1851     struct thread *td, bool return_locked)
1852 {
1853 	struct mtx *vplock;
1854 	struct sockaddr_un *soun;
1855 	struct vnode *vp;
1856 	struct socket *so2;
1857 	struct unpcb *unp, *unp2, *unp3;
1858 	struct nameidata nd;
1859 	char buf[SOCK_MAXADDRLEN];
1860 	struct sockaddr *sa;
1861 	cap_rights_t rights;
1862 	int error, len;
1863 	bool connreq;
1864 
1865 	if (nam->sa_family != AF_UNIX)
1866 		return (EAFNOSUPPORT);
1867 	if (nam->sa_len > sizeof(struct sockaddr_un))
1868 		return (EINVAL);
1869 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1870 	if (len <= 0)
1871 		return (EINVAL);
1872 	soun = (struct sockaddr_un *)nam;
1873 	bcopy(soun->sun_path, buf, len);
1874 	buf[len] = 0;
1875 
1876 	error = 0;
1877 	unp = sotounpcb(so);
1878 	UNP_PCB_LOCK(unp);
1879 	for (;;) {
1880 		/*
1881 		 * Wait for connection state to stabilize.  If a connection
1882 		 * already exists, give up.  For datagram sockets, which permit
1883 		 * multiple consecutive connect(2) calls, upper layers are
1884 		 * responsible for disconnecting in advance of a subsequent
1885 		 * connect(2), but this is not synchronized with PCB connection
1886 		 * state.
1887 		 *
1888 		 * Also make sure that no threads are currently attempting to
1889 		 * lock the peer socket, to ensure that unp_conn cannot
1890 		 * transition between two valid sockets while locks are dropped.
1891 		 */
1892 		if (SOLISTENING(so))
1893 			error = EOPNOTSUPP;
1894 		else if (unp->unp_conn != NULL)
1895 			error = EISCONN;
1896 		else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1897 			error = EALREADY;
1898 		}
1899 		if (error != 0) {
1900 			UNP_PCB_UNLOCK(unp);
1901 			return (error);
1902 		}
1903 		if (unp->unp_pairbusy > 0) {
1904 			unp->unp_flags |= UNP_WAITING;
1905 			mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1906 			continue;
1907 		}
1908 		break;
1909 	}
1910 	unp->unp_flags |= UNP_CONNECTING;
1911 	UNP_PCB_UNLOCK(unp);
1912 
1913 	connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1914 	if (connreq)
1915 		sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1916 	else
1917 		sa = NULL;
1918 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1919 	    UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
1920 	error = namei(&nd);
1921 	if (error)
1922 		vp = NULL;
1923 	else
1924 		vp = nd.ni_vp;
1925 	ASSERT_VOP_LOCKED(vp, "unp_connect");
1926 	if (error)
1927 		goto bad;
1928 	NDFREE_PNBUF(&nd);
1929 
1930 	if (vp->v_type != VSOCK) {
1931 		error = ENOTSOCK;
1932 		goto bad;
1933 	}
1934 #ifdef MAC
1935 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1936 	if (error)
1937 		goto bad;
1938 #endif
1939 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1940 	if (error)
1941 		goto bad;
1942 
1943 	unp = sotounpcb(so);
1944 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1945 
1946 	vplock = mtx_pool_find(mtxpool_sleep, vp);
1947 	mtx_lock(vplock);
1948 	VOP_UNP_CONNECT(vp, &unp2);
1949 	if (unp2 == NULL) {
1950 		error = ECONNREFUSED;
1951 		goto bad2;
1952 	}
1953 	so2 = unp2->unp_socket;
1954 	if (so->so_type != so2->so_type) {
1955 		error = EPROTOTYPE;
1956 		goto bad2;
1957 	}
1958 	if (connreq) {
1959 		if (SOLISTENING(so2)) {
1960 			CURVNET_SET(so2->so_vnet);
1961 			so2 = sonewconn(so2, 0);
1962 			CURVNET_RESTORE();
1963 		} else
1964 			so2 = NULL;
1965 		if (so2 == NULL) {
1966 			error = ECONNREFUSED;
1967 			goto bad2;
1968 		}
1969 		unp3 = sotounpcb(so2);
1970 		unp_pcb_lock_pair(unp2, unp3);
1971 		if (unp2->unp_addr != NULL) {
1972 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1973 			unp3->unp_addr = (struct sockaddr_un *) sa;
1974 			sa = NULL;
1975 		}
1976 
1977 		unp_copy_peercred(td, unp3, unp, unp2);
1978 
1979 		UNP_PCB_UNLOCK(unp2);
1980 		unp2 = unp3;
1981 
1982 		/*
1983 		 * It is safe to block on the PCB lock here since unp2 is
1984 		 * nascent and cannot be connected to any other sockets.
1985 		 */
1986 		UNP_PCB_LOCK(unp);
1987 #ifdef MAC
1988 		mac_socketpeer_set_from_socket(so, so2);
1989 		mac_socketpeer_set_from_socket(so2, so);
1990 #endif
1991 	} else {
1992 		unp_pcb_lock_pair(unp, unp2);
1993 	}
1994 	KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1995 	    sotounpcb(so2) == unp2,
1996 	    ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1997 	unp_connect2(so, so2);
1998 	KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1999 	    ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
2000 	unp->unp_flags &= ~UNP_CONNECTING;
2001 	if (!return_locked)
2002 		unp_pcb_unlock_pair(unp, unp2);
2003 bad2:
2004 	mtx_unlock(vplock);
2005 bad:
2006 	if (vp != NULL) {
2007 		/*
2008 		 * If we are returning locked (called via uipc_sosend_dgram()),
2009 		 * we need to be sure that vput() won't sleep.  This is
2010 		 * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock.
2011 		 * SOCK_STREAM/SEQPACKET can't request return_locked (yet).
2012 		 */
2013 		MPASS(!(return_locked && connreq));
2014 		vput(vp);
2015 	}
2016 	free(sa, M_SONAME);
2017 	if (__predict_false(error)) {
2018 		UNP_PCB_LOCK(unp);
2019 		KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
2020 		    ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
2021 		unp->unp_flags &= ~UNP_CONNECTING;
2022 		UNP_PCB_UNLOCK(unp);
2023 	}
2024 	return (error);
2025 }
2026 
2027 /*
2028  * Set socket peer credentials at connection time.
2029  *
2030  * The client's PCB credentials are copied from its process structure.  The
2031  * server's PCB credentials are copied from the socket on which it called
2032  * listen(2).  uipc_listen cached that process's credentials at the time.
2033  */
2034 void
2035 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
2036     struct unpcb *server_unp, struct unpcb *listen_unp)
2037 {
2038 	cru2xt(td, &client_unp->unp_peercred);
2039 	client_unp->unp_flags |= UNP_HAVEPC;
2040 
2041 	memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
2042 	    sizeof(server_unp->unp_peercred));
2043 	server_unp->unp_flags |= UNP_HAVEPC;
2044 	client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
2045 }
2046 
2047 static void
2048 unp_connect2(struct socket *so, struct socket *so2)
2049 {
2050 	struct unpcb *unp;
2051 	struct unpcb *unp2;
2052 
2053 	MPASS(so2->so_type == so->so_type);
2054 	unp = sotounpcb(so);
2055 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
2056 	unp2 = sotounpcb(so2);
2057 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
2058 
2059 	UNP_PCB_LOCK_ASSERT(unp);
2060 	UNP_PCB_LOCK_ASSERT(unp2);
2061 	KASSERT(unp->unp_conn == NULL,
2062 	    ("%s: socket %p is already connected", __func__, unp));
2063 
2064 	unp->unp_conn = unp2;
2065 	unp_pcb_hold(unp2);
2066 	unp_pcb_hold(unp);
2067 	switch (so->so_type) {
2068 	case SOCK_DGRAM:
2069 		UNP_REF_LIST_LOCK();
2070 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2071 		UNP_REF_LIST_UNLOCK();
2072 		soisconnected(so);
2073 		break;
2074 
2075 	case SOCK_STREAM:
2076 	case SOCK_SEQPACKET:
2077 		KASSERT(unp2->unp_conn == NULL,
2078 		    ("%s: socket %p is already connected", __func__, unp2));
2079 		unp2->unp_conn = unp;
2080 		soisconnected(so);
2081 		soisconnected(so2);
2082 		break;
2083 
2084 	default:
2085 		panic("unp_connect2");
2086 	}
2087 }
2088 
2089 static void
2090 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
2091 {
2092 	struct socket *so, *so2;
2093 	struct mbuf *m = NULL;
2094 #ifdef INVARIANTS
2095 	struct unpcb *unptmp;
2096 #endif
2097 
2098 	UNP_PCB_LOCK_ASSERT(unp);
2099 	UNP_PCB_LOCK_ASSERT(unp2);
2100 	KASSERT(unp->unp_conn == unp2,
2101 	    ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
2102 
2103 	unp->unp_conn = NULL;
2104 	so = unp->unp_socket;
2105 	so2 = unp2->unp_socket;
2106 	switch (unp->unp_socket->so_type) {
2107 	case SOCK_DGRAM:
2108 		/*
2109 		 * Remove our send socket buffer from the peer's receive buffer.
2110 		 * Move the data to the receive buffer only if it is empty.
2111 		 * This is a protection against a scenario where a peer
2112 		 * connects, floods and disconnects, effectively blocking
2113 		 * sendto() from unconnected sockets.
2114 		 */
2115 		SOCK_RECVBUF_LOCK(so2);
2116 		if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) {
2117 			TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd,
2118 			    uxdg_clist);
2119 			if (__predict_true((so2->so_rcv.sb_state &
2120 			    SBS_CANTRCVMORE) == 0) &&
2121 			    STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) {
2122 				STAILQ_CONCAT(&so2->so_rcv.uxdg_mb,
2123 				    &so->so_snd.uxdg_mb);
2124 				so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc;
2125 				so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl;
2126 				so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt;
2127 			} else {
2128 				m = STAILQ_FIRST(&so->so_snd.uxdg_mb);
2129 				STAILQ_INIT(&so->so_snd.uxdg_mb);
2130 				so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc;
2131 				so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc;
2132 				so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl;
2133 				so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt;
2134 			}
2135 			/* Note: so may reconnect. */
2136 			so->so_snd.uxdg_cc = 0;
2137 			so->so_snd.uxdg_ctl = 0;
2138 			so->so_snd.uxdg_mbcnt = 0;
2139 		}
2140 		SOCK_RECVBUF_UNLOCK(so2);
2141 		UNP_REF_LIST_LOCK();
2142 #ifdef INVARIANTS
2143 		LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
2144 			if (unptmp == unp)
2145 				break;
2146 		}
2147 		KASSERT(unptmp != NULL,
2148 		    ("%s: %p not found in reflist of %p", __func__, unp, unp2));
2149 #endif
2150 		LIST_REMOVE(unp, unp_reflink);
2151 		UNP_REF_LIST_UNLOCK();
2152 		if (so) {
2153 			SOCK_LOCK(so);
2154 			so->so_state &= ~SS_ISCONNECTED;
2155 			SOCK_UNLOCK(so);
2156 		}
2157 		break;
2158 
2159 	case SOCK_STREAM:
2160 	case SOCK_SEQPACKET:
2161 		if (so)
2162 			soisdisconnected(so);
2163 		MPASS(unp2->unp_conn == unp);
2164 		unp2->unp_conn = NULL;
2165 		if (so2)
2166 			soisdisconnected(so2);
2167 		break;
2168 	}
2169 
2170 	if (unp == unp2) {
2171 		unp_pcb_rele_notlast(unp);
2172 		if (!unp_pcb_rele(unp))
2173 			UNP_PCB_UNLOCK(unp);
2174 	} else {
2175 		if (!unp_pcb_rele(unp))
2176 			UNP_PCB_UNLOCK(unp);
2177 		if (!unp_pcb_rele(unp2))
2178 			UNP_PCB_UNLOCK(unp2);
2179 	}
2180 
2181 	if (m != NULL) {
2182 		unp_scan(m, unp_freerights);
2183 		m_freem(m);
2184 	}
2185 }
2186 
2187 /*
2188  * unp_pcblist() walks the global list of struct unpcb's to generate a
2189  * pointer list, bumping the refcount on each unpcb.  It then copies them out
2190  * sequentially, validating the generation number on each to see if it has
2191  * been detached.  All of this is necessary because copyout() may sleep on
2192  * disk I/O.
2193  */
2194 static int
2195 unp_pcblist(SYSCTL_HANDLER_ARGS)
2196 {
2197 	struct unpcb *unp, **unp_list;
2198 	unp_gen_t gencnt;
2199 	struct xunpgen *xug;
2200 	struct unp_head *head;
2201 	struct xunpcb *xu;
2202 	u_int i;
2203 	int error, n;
2204 
2205 	switch ((intptr_t)arg1) {
2206 	case SOCK_STREAM:
2207 		head = &unp_shead;
2208 		break;
2209 
2210 	case SOCK_DGRAM:
2211 		head = &unp_dhead;
2212 		break;
2213 
2214 	case SOCK_SEQPACKET:
2215 		head = &unp_sphead;
2216 		break;
2217 
2218 	default:
2219 		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
2220 	}
2221 
2222 	/*
2223 	 * The process of preparing the PCB list is too time-consuming and
2224 	 * resource-intensive to repeat twice on every request.
2225 	 */
2226 	if (req->oldptr == NULL) {
2227 		n = unp_count;
2228 		req->oldidx = 2 * (sizeof *xug)
2229 			+ (n + n/8) * sizeof(struct xunpcb);
2230 		return (0);
2231 	}
2232 
2233 	if (req->newptr != NULL)
2234 		return (EPERM);
2235 
2236 	/*
2237 	 * OK, now we're committed to doing something.
2238 	 */
2239 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
2240 	UNP_LINK_RLOCK();
2241 	gencnt = unp_gencnt;
2242 	n = unp_count;
2243 	UNP_LINK_RUNLOCK();
2244 
2245 	xug->xug_len = sizeof *xug;
2246 	xug->xug_count = n;
2247 	xug->xug_gen = gencnt;
2248 	xug->xug_sogen = so_gencnt;
2249 	error = SYSCTL_OUT(req, xug, sizeof *xug);
2250 	if (error) {
2251 		free(xug, M_TEMP);
2252 		return (error);
2253 	}
2254 
2255 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
2256 
2257 	UNP_LINK_RLOCK();
2258 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
2259 	     unp = LIST_NEXT(unp, unp_link)) {
2260 		UNP_PCB_LOCK(unp);
2261 		if (unp->unp_gencnt <= gencnt) {
2262 			if (cr_cansee(req->td->td_ucred,
2263 			    unp->unp_socket->so_cred)) {
2264 				UNP_PCB_UNLOCK(unp);
2265 				continue;
2266 			}
2267 			unp_list[i++] = unp;
2268 			unp_pcb_hold(unp);
2269 		}
2270 		UNP_PCB_UNLOCK(unp);
2271 	}
2272 	UNP_LINK_RUNLOCK();
2273 	n = i;			/* In case we lost some during malloc. */
2274 
2275 	error = 0;
2276 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
2277 	for (i = 0; i < n; i++) {
2278 		unp = unp_list[i];
2279 		UNP_PCB_LOCK(unp);
2280 		if (unp_pcb_rele(unp))
2281 			continue;
2282 
2283 		if (unp->unp_gencnt <= gencnt) {
2284 			xu->xu_len = sizeof *xu;
2285 			xu->xu_unpp = (uintptr_t)unp;
2286 			/*
2287 			 * XXX - need more locking here to protect against
2288 			 * connect/disconnect races for SMP.
2289 			 */
2290 			if (unp->unp_addr != NULL)
2291 				bcopy(unp->unp_addr, &xu->xu_addr,
2292 				      unp->unp_addr->sun_len);
2293 			else
2294 				bzero(&xu->xu_addr, sizeof(xu->xu_addr));
2295 			if (unp->unp_conn != NULL &&
2296 			    unp->unp_conn->unp_addr != NULL)
2297 				bcopy(unp->unp_conn->unp_addr,
2298 				      &xu->xu_caddr,
2299 				      unp->unp_conn->unp_addr->sun_len);
2300 			else
2301 				bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
2302 			xu->unp_vnode = (uintptr_t)unp->unp_vnode;
2303 			xu->unp_conn = (uintptr_t)unp->unp_conn;
2304 			xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
2305 			xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
2306 			xu->unp_gencnt = unp->unp_gencnt;
2307 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
2308 			UNP_PCB_UNLOCK(unp);
2309 			error = SYSCTL_OUT(req, xu, sizeof *xu);
2310 		} else {
2311 			UNP_PCB_UNLOCK(unp);
2312 		}
2313 	}
2314 	free(xu, M_TEMP);
2315 	if (!error) {
2316 		/*
2317 		 * Give the user an updated idea of our state.  If the
2318 		 * generation differs from what we told her before, she knows
2319 		 * that something happened while we were processing this
2320 		 * request, and it might be necessary to retry.
2321 		 */
2322 		xug->xug_gen = unp_gencnt;
2323 		xug->xug_sogen = so_gencnt;
2324 		xug->xug_count = unp_count;
2325 		error = SYSCTL_OUT(req, xug, sizeof *xug);
2326 	}
2327 	free(unp_list, M_TEMP);
2328 	free(xug, M_TEMP);
2329 	return (error);
2330 }
2331 
2332 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
2333     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2334     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
2335     "List of active local datagram sockets");
2336 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
2337     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2338     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
2339     "List of active local stream sockets");
2340 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
2341     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2342     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
2343     "List of active local seqpacket sockets");
2344 
2345 static void
2346 unp_shutdown(struct unpcb *unp)
2347 {
2348 	struct unpcb *unp2;
2349 	struct socket *so;
2350 
2351 	UNP_PCB_LOCK_ASSERT(unp);
2352 
2353 	unp2 = unp->unp_conn;
2354 	if ((unp->unp_socket->so_type == SOCK_STREAM ||
2355 	    (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
2356 		so = unp2->unp_socket;
2357 		if (so != NULL)
2358 			socantrcvmore(so);
2359 	}
2360 }
2361 
2362 static void
2363 unp_drop(struct unpcb *unp)
2364 {
2365 	struct socket *so;
2366 	struct unpcb *unp2;
2367 
2368 	/*
2369 	 * Regardless of whether the socket's peer dropped the connection
2370 	 * with this socket by aborting or disconnecting, POSIX requires
2371 	 * that ECONNRESET is returned.
2372 	 */
2373 
2374 	UNP_PCB_LOCK(unp);
2375 	so = unp->unp_socket;
2376 	if (so)
2377 		so->so_error = ECONNRESET;
2378 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
2379 		/* Last reference dropped in unp_disconnect(). */
2380 		unp_pcb_rele_notlast(unp);
2381 		unp_disconnect(unp, unp2);
2382 	} else if (!unp_pcb_rele(unp)) {
2383 		UNP_PCB_UNLOCK(unp);
2384 	}
2385 }
2386 
2387 static void
2388 unp_freerights(struct filedescent **fdep, int fdcount)
2389 {
2390 	struct file *fp;
2391 	int i;
2392 
2393 	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
2394 
2395 	for (i = 0; i < fdcount; i++) {
2396 		fp = fdep[i]->fde_file;
2397 		filecaps_free(&fdep[i]->fde_caps);
2398 		unp_discard(fp);
2399 	}
2400 	free(fdep[0], M_FILECAPS);
2401 }
2402 
2403 static int
2404 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2405 {
2406 	struct thread *td = curthread;		/* XXX */
2407 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2408 	int i;
2409 	int *fdp;
2410 	struct filedesc *fdesc = td->td_proc->p_fd;
2411 	struct filedescent **fdep;
2412 	void *data;
2413 	socklen_t clen = control->m_len, datalen;
2414 	int error, newfds;
2415 	u_int newlen;
2416 
2417 	UNP_LINK_UNLOCK_ASSERT();
2418 
2419 	error = 0;
2420 	if (controlp != NULL) /* controlp == NULL => free control messages */
2421 		*controlp = NULL;
2422 	while (cm != NULL) {
2423 		MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
2424 
2425 		data = CMSG_DATA(cm);
2426 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2427 		if (cm->cmsg_level == SOL_SOCKET
2428 		    && cm->cmsg_type == SCM_RIGHTS) {
2429 			newfds = datalen / sizeof(*fdep);
2430 			if (newfds == 0)
2431 				goto next;
2432 			fdep = data;
2433 
2434 			/* If we're not outputting the descriptors free them. */
2435 			if (error || controlp == NULL) {
2436 				unp_freerights(fdep, newfds);
2437 				goto next;
2438 			}
2439 			FILEDESC_XLOCK(fdesc);
2440 
2441 			/*
2442 			 * Now change each pointer to an fd in the global
2443 			 * table to an integer that is the index to the local
2444 			 * fd table entry that we set up to point to the
2445 			 * global one we are transferring.
2446 			 */
2447 			newlen = newfds * sizeof(int);
2448 			*controlp = sbcreatecontrol(NULL, newlen,
2449 			    SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2450 
2451 			fdp = (int *)
2452 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2453 			if ((error = fdallocn(td, 0, fdp, newfds))) {
2454 				FILEDESC_XUNLOCK(fdesc);
2455 				unp_freerights(fdep, newfds);
2456 				m_freem(*controlp);
2457 				*controlp = NULL;
2458 				goto next;
2459 			}
2460 			for (i = 0; i < newfds; i++, fdp++) {
2461 				_finstall(fdesc, fdep[i]->fde_file, *fdp,
2462 				    (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2463 				    &fdep[i]->fde_caps);
2464 				unp_externalize_fp(fdep[i]->fde_file);
2465 			}
2466 
2467 			/*
2468 			 * The new type indicates that the mbuf data refers to
2469 			 * kernel resources that may need to be released before
2470 			 * the mbuf is freed.
2471 			 */
2472 			m_chtype(*controlp, MT_EXTCONTROL);
2473 			FILEDESC_XUNLOCK(fdesc);
2474 			free(fdep[0], M_FILECAPS);
2475 		} else {
2476 			/* We can just copy anything else across. */
2477 			if (error || controlp == NULL)
2478 				goto next;
2479 			*controlp = sbcreatecontrol(NULL, datalen,
2480 			    cm->cmsg_type, cm->cmsg_level, M_WAITOK);
2481 			bcopy(data,
2482 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2483 			    datalen);
2484 		}
2485 		controlp = &(*controlp)->m_next;
2486 
2487 next:
2488 		if (CMSG_SPACE(datalen) < clen) {
2489 			clen -= CMSG_SPACE(datalen);
2490 			cm = (struct cmsghdr *)
2491 			    ((caddr_t)cm + CMSG_SPACE(datalen));
2492 		} else {
2493 			clen = 0;
2494 			cm = NULL;
2495 		}
2496 	}
2497 
2498 	m_freem(control);
2499 	return (error);
2500 }
2501 
2502 static void
2503 unp_zone_change(void *tag)
2504 {
2505 
2506 	uma_zone_set_max(unp_zone, maxsockets);
2507 }
2508 
2509 #ifdef INVARIANTS
2510 static void
2511 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2512 {
2513 	struct unpcb *unp;
2514 
2515 	unp = mem;
2516 
2517 	KASSERT(LIST_EMPTY(&unp->unp_refs),
2518 	    ("%s: unpcb %p has lingering refs", __func__, unp));
2519 	KASSERT(unp->unp_socket == NULL,
2520 	    ("%s: unpcb %p has socket backpointer", __func__, unp));
2521 	KASSERT(unp->unp_vnode == NULL,
2522 	    ("%s: unpcb %p has vnode references", __func__, unp));
2523 	KASSERT(unp->unp_conn == NULL,
2524 	    ("%s: unpcb %p is still connected", __func__, unp));
2525 	KASSERT(unp->unp_addr == NULL,
2526 	    ("%s: unpcb %p has leaked addr", __func__, unp));
2527 }
2528 #endif
2529 
2530 static void
2531 unp_init(void *arg __unused)
2532 {
2533 	uma_dtor dtor;
2534 
2535 #ifdef INVARIANTS
2536 	dtor = unp_zdtor;
2537 #else
2538 	dtor = NULL;
2539 #endif
2540 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2541 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
2542 	uma_zone_set_max(unp_zone, maxsockets);
2543 	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2544 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2545 	    NULL, EVENTHANDLER_PRI_ANY);
2546 	LIST_INIT(&unp_dhead);
2547 	LIST_INIT(&unp_shead);
2548 	LIST_INIT(&unp_sphead);
2549 	SLIST_INIT(&unp_defers);
2550 	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2551 	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2552 	UNP_LINK_LOCK_INIT();
2553 	UNP_DEFERRED_LOCK_INIT();
2554 }
2555 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
2556 
2557 static void
2558 unp_internalize_cleanup_rights(struct mbuf *control)
2559 {
2560 	struct cmsghdr *cp;
2561 	struct mbuf *m;
2562 	void *data;
2563 	socklen_t datalen;
2564 
2565 	for (m = control; m != NULL; m = m->m_next) {
2566 		cp = mtod(m, struct cmsghdr *);
2567 		if (cp->cmsg_level != SOL_SOCKET ||
2568 		    cp->cmsg_type != SCM_RIGHTS)
2569 			continue;
2570 		data = CMSG_DATA(cp);
2571 		datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2572 		unp_freerights(data, datalen / sizeof(struct filedesc *));
2573 	}
2574 }
2575 
2576 static int
2577 unp_internalize(struct mbuf **controlp, struct thread *td,
2578     struct mbuf **clast, u_int *space, u_int *mbcnt)
2579 {
2580 	struct mbuf *control, **initial_controlp;
2581 	struct proc *p;
2582 	struct filedesc *fdesc;
2583 	struct bintime *bt;
2584 	struct cmsghdr *cm;
2585 	struct cmsgcred *cmcred;
2586 	struct filedescent *fde, **fdep, *fdev;
2587 	struct file *fp;
2588 	struct timeval *tv;
2589 	struct timespec *ts;
2590 	void *data;
2591 	socklen_t clen, datalen;
2592 	int i, j, error, *fdp, oldfds;
2593 	u_int newlen;
2594 
2595 	MPASS((*controlp)->m_next == NULL); /* COMPAT_OLDSOCK may violate */
2596 	UNP_LINK_UNLOCK_ASSERT();
2597 
2598 	p = td->td_proc;
2599 	fdesc = p->p_fd;
2600 	error = 0;
2601 	control = *controlp;
2602 	*controlp = NULL;
2603 	initial_controlp = controlp;
2604 	for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
2605 	    data = CMSG_DATA(cm);
2606 
2607 	    clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
2608 	    clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
2609 	    (char *)cm + cm->cmsg_len >= (char *)data;
2610 
2611 	    clen -= min(CMSG_SPACE(datalen), clen),
2612 	    cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
2613 	    data = CMSG_DATA(cm)) {
2614 		datalen = (char *)cm + cm->cmsg_len - (char *)data;
2615 		switch (cm->cmsg_type) {
2616 		case SCM_CREDS:
2617 			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2618 			    SCM_CREDS, SOL_SOCKET, M_WAITOK);
2619 			cmcred = (struct cmsgcred *)
2620 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2621 			cmcred->cmcred_pid = p->p_pid;
2622 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2623 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2624 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
2625 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2626 			    CMGROUP_MAX);
2627 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
2628 				cmcred->cmcred_groups[i] =
2629 				    td->td_ucred->cr_groups[i];
2630 			break;
2631 
2632 		case SCM_RIGHTS:
2633 			oldfds = datalen / sizeof (int);
2634 			if (oldfds == 0)
2635 				continue;
2636 			/* On some machines sizeof pointer is bigger than
2637 			 * sizeof int, so we need to check if data fits into
2638 			 * single mbuf.  We could allocate several mbufs, and
2639 			 * unp_externalize() should even properly handle that.
2640 			 * But it is not worth to complicate the code for an
2641 			 * insane scenario of passing over 200 file descriptors
2642 			 * at once.
2643 			 */
2644 			newlen = oldfds * sizeof(fdep[0]);
2645 			if (CMSG_SPACE(newlen) > MCLBYTES) {
2646 				error = EMSGSIZE;
2647 				goto out;
2648 			}
2649 			/*
2650 			 * Check that all the FDs passed in refer to legal
2651 			 * files.  If not, reject the entire operation.
2652 			 */
2653 			fdp = data;
2654 			FILEDESC_SLOCK(fdesc);
2655 			for (i = 0; i < oldfds; i++, fdp++) {
2656 				fp = fget_noref(fdesc, *fdp);
2657 				if (fp == NULL) {
2658 					FILEDESC_SUNLOCK(fdesc);
2659 					error = EBADF;
2660 					goto out;
2661 				}
2662 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2663 					FILEDESC_SUNLOCK(fdesc);
2664 					error = EOPNOTSUPP;
2665 					goto out;
2666 				}
2667 			}
2668 
2669 			/*
2670 			 * Now replace the integer FDs with pointers to the
2671 			 * file structure and capability rights.
2672 			 */
2673 			*controlp = sbcreatecontrol(NULL, newlen,
2674 			    SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2675 			fdp = data;
2676 			for (i = 0; i < oldfds; i++, fdp++) {
2677 				if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2678 					fdp = data;
2679 					for (j = 0; j < i; j++, fdp++) {
2680 						fdrop(fdesc->fd_ofiles[*fdp].
2681 						    fde_file, td);
2682 					}
2683 					FILEDESC_SUNLOCK(fdesc);
2684 					error = EBADF;
2685 					goto out;
2686 				}
2687 			}
2688 			fdp = data;
2689 			fdep = (struct filedescent **)
2690 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2691 			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2692 			    M_WAITOK);
2693 			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2694 				fde = &fdesc->fd_ofiles[*fdp];
2695 				fdep[i] = fdev;
2696 				fdep[i]->fde_file = fde->fde_file;
2697 				filecaps_copy(&fde->fde_caps,
2698 				    &fdep[i]->fde_caps, true);
2699 				unp_internalize_fp(fdep[i]->fde_file);
2700 			}
2701 			FILEDESC_SUNLOCK(fdesc);
2702 			break;
2703 
2704 		case SCM_TIMESTAMP:
2705 			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
2706 			    SCM_TIMESTAMP, SOL_SOCKET, M_WAITOK);
2707 			tv = (struct timeval *)
2708 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2709 			microtime(tv);
2710 			break;
2711 
2712 		case SCM_BINTIME:
2713 			*controlp = sbcreatecontrol(NULL, sizeof(*bt),
2714 			    SCM_BINTIME, SOL_SOCKET, M_WAITOK);
2715 			bt = (struct bintime *)
2716 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2717 			bintime(bt);
2718 			break;
2719 
2720 		case SCM_REALTIME:
2721 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2722 			    SCM_REALTIME, SOL_SOCKET, M_WAITOK);
2723 			ts = (struct timespec *)
2724 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2725 			nanotime(ts);
2726 			break;
2727 
2728 		case SCM_MONOTONIC:
2729 			*controlp = sbcreatecontrol(NULL, sizeof(*ts),
2730 			    SCM_MONOTONIC, SOL_SOCKET, M_WAITOK);
2731 			ts = (struct timespec *)
2732 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2733 			nanouptime(ts);
2734 			break;
2735 
2736 		default:
2737 			error = EINVAL;
2738 			goto out;
2739 		}
2740 
2741 		if (space != NULL) {
2742 			*space += (*controlp)->m_len;
2743 			*mbcnt += MSIZE;
2744 			if ((*controlp)->m_flags & M_EXT)
2745 				*mbcnt += (*controlp)->m_ext.ext_size;
2746 			*clast = *controlp;
2747 		}
2748 		controlp = &(*controlp)->m_next;
2749 	}
2750 	if (clen > 0)
2751 		error = EINVAL;
2752 
2753 out:
2754 	if (error != 0 && initial_controlp != NULL)
2755 		unp_internalize_cleanup_rights(*initial_controlp);
2756 	m_freem(control);
2757 	return (error);
2758 }
2759 
2760 static struct mbuf *
2761 unp_addsockcred(struct thread *td, struct mbuf *control, int mode,
2762     struct mbuf **clast, u_int *space, u_int *mbcnt)
2763 {
2764 	struct mbuf *m, *n, *n_prev;
2765 	const struct cmsghdr *cm;
2766 	int ngroups, i, cmsgtype;
2767 	size_t ctrlsz;
2768 
2769 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2770 	if (mode & UNP_WANTCRED_ALWAYS) {
2771 		ctrlsz = SOCKCRED2SIZE(ngroups);
2772 		cmsgtype = SCM_CREDS2;
2773 	} else {
2774 		ctrlsz = SOCKCREDSIZE(ngroups);
2775 		cmsgtype = SCM_CREDS;
2776 	}
2777 
2778 	m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
2779 	if (m == NULL)
2780 		return (control);
2781 	MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL);
2782 
2783 	if (mode & UNP_WANTCRED_ALWAYS) {
2784 		struct sockcred2 *sc;
2785 
2786 		sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2787 		sc->sc_version = 0;
2788 		sc->sc_pid = td->td_proc->p_pid;
2789 		sc->sc_uid = td->td_ucred->cr_ruid;
2790 		sc->sc_euid = td->td_ucred->cr_uid;
2791 		sc->sc_gid = td->td_ucred->cr_rgid;
2792 		sc->sc_egid = td->td_ucred->cr_gid;
2793 		sc->sc_ngroups = ngroups;
2794 		for (i = 0; i < sc->sc_ngroups; i++)
2795 			sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2796 	} else {
2797 		struct sockcred *sc;
2798 
2799 		sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2800 		sc->sc_uid = td->td_ucred->cr_ruid;
2801 		sc->sc_euid = td->td_ucred->cr_uid;
2802 		sc->sc_gid = td->td_ucred->cr_rgid;
2803 		sc->sc_egid = td->td_ucred->cr_gid;
2804 		sc->sc_ngroups = ngroups;
2805 		for (i = 0; i < sc->sc_ngroups; i++)
2806 			sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2807 	}
2808 
2809 	/*
2810 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2811 	 * created SCM_CREDS control message (struct sockcred) has another
2812 	 * format.
2813 	 */
2814 	if (control != NULL && cmsgtype == SCM_CREDS)
2815 		for (n = control, n_prev = NULL; n != NULL;) {
2816 			cm = mtod(n, struct cmsghdr *);
2817     			if (cm->cmsg_level == SOL_SOCKET &&
2818 			    cm->cmsg_type == SCM_CREDS) {
2819     				if (n_prev == NULL)
2820 					control = n->m_next;
2821 				else
2822 					n_prev->m_next = n->m_next;
2823 				if (space != NULL) {
2824 					MPASS(*space >= n->m_len);
2825 					*space -= n->m_len;
2826 					MPASS(*mbcnt >= MSIZE);
2827 					*mbcnt -= MSIZE;
2828 					if (n->m_flags & M_EXT) {
2829 						MPASS(*mbcnt >=
2830 						    n->m_ext.ext_size);
2831 						*mbcnt -= n->m_ext.ext_size;
2832 					}
2833 					MPASS(clast);
2834 					if (*clast == n) {
2835 						MPASS(n->m_next == NULL);
2836 						if (n_prev == NULL)
2837 							*clast = m;
2838 						else
2839 							*clast = n_prev;
2840 					}
2841 				}
2842 				n = m_free(n);
2843 			} else {
2844 				n_prev = n;
2845 				n = n->m_next;
2846 			}
2847 		}
2848 
2849 	/* Prepend it to the head. */
2850 	m->m_next = control;
2851 	if (space != NULL) {
2852 		*space += m->m_len;
2853 		*mbcnt += MSIZE;
2854 		if (control == NULL)
2855 			*clast = m;
2856 	}
2857 	return (m);
2858 }
2859 
2860 static struct unpcb *
2861 fptounp(struct file *fp)
2862 {
2863 	struct socket *so;
2864 
2865 	if (fp->f_type != DTYPE_SOCKET)
2866 		return (NULL);
2867 	if ((so = fp->f_data) == NULL)
2868 		return (NULL);
2869 	if (so->so_proto->pr_domain != &localdomain)
2870 		return (NULL);
2871 	return sotounpcb(so);
2872 }
2873 
2874 static void
2875 unp_discard(struct file *fp)
2876 {
2877 	struct unp_defer *dr;
2878 
2879 	if (unp_externalize_fp(fp)) {
2880 		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2881 		dr->ud_fp = fp;
2882 		UNP_DEFERRED_LOCK();
2883 		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2884 		UNP_DEFERRED_UNLOCK();
2885 		atomic_add_int(&unp_defers_count, 1);
2886 		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2887 	} else
2888 		closef_nothread(fp);
2889 }
2890 
2891 static void
2892 unp_process_defers(void *arg __unused, int pending)
2893 {
2894 	struct unp_defer *dr;
2895 	SLIST_HEAD(, unp_defer) drl;
2896 	int count;
2897 
2898 	SLIST_INIT(&drl);
2899 	for (;;) {
2900 		UNP_DEFERRED_LOCK();
2901 		if (SLIST_FIRST(&unp_defers) == NULL) {
2902 			UNP_DEFERRED_UNLOCK();
2903 			break;
2904 		}
2905 		SLIST_SWAP(&unp_defers, &drl, unp_defer);
2906 		UNP_DEFERRED_UNLOCK();
2907 		count = 0;
2908 		while ((dr = SLIST_FIRST(&drl)) != NULL) {
2909 			SLIST_REMOVE_HEAD(&drl, ud_link);
2910 			closef_nothread(dr->ud_fp);
2911 			free(dr, M_TEMP);
2912 			count++;
2913 		}
2914 		atomic_add_int(&unp_defers_count, -count);
2915 	}
2916 }
2917 
2918 static void
2919 unp_internalize_fp(struct file *fp)
2920 {
2921 	struct unpcb *unp;
2922 
2923 	UNP_LINK_WLOCK();
2924 	if ((unp = fptounp(fp)) != NULL) {
2925 		unp->unp_file = fp;
2926 		unp->unp_msgcount++;
2927 	}
2928 	unp_rights++;
2929 	UNP_LINK_WUNLOCK();
2930 }
2931 
2932 static int
2933 unp_externalize_fp(struct file *fp)
2934 {
2935 	struct unpcb *unp;
2936 	int ret;
2937 
2938 	UNP_LINK_WLOCK();
2939 	if ((unp = fptounp(fp)) != NULL) {
2940 		unp->unp_msgcount--;
2941 		ret = 1;
2942 	} else
2943 		ret = 0;
2944 	unp_rights--;
2945 	UNP_LINK_WUNLOCK();
2946 	return (ret);
2947 }
2948 
2949 /*
2950  * unp_defer indicates whether additional work has been defered for a future
2951  * pass through unp_gc().  It is thread local and does not require explicit
2952  * synchronization.
2953  */
2954 static int	unp_marked;
2955 
2956 static void
2957 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2958 {
2959 	struct unpcb *unp;
2960 	struct file *fp;
2961 	int i;
2962 
2963 	/*
2964 	 * This function can only be called from the gc task.
2965 	 */
2966 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2967 	    ("%s: not on gc callout", __func__));
2968 	UNP_LINK_LOCK_ASSERT();
2969 
2970 	for (i = 0; i < fdcount; i++) {
2971 		fp = fdep[i]->fde_file;
2972 		if ((unp = fptounp(fp)) == NULL)
2973 			continue;
2974 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2975 			continue;
2976 		unp->unp_gcrefs--;
2977 	}
2978 }
2979 
2980 static void
2981 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2982 {
2983 	struct unpcb *unp;
2984 	struct file *fp;
2985 	int i;
2986 
2987 	/*
2988 	 * This function can only be called from the gc task.
2989 	 */
2990 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2991 	    ("%s: not on gc callout", __func__));
2992 	UNP_LINK_LOCK_ASSERT();
2993 
2994 	for (i = 0; i < fdcount; i++) {
2995 		fp = fdep[i]->fde_file;
2996 		if ((unp = fptounp(fp)) == NULL)
2997 			continue;
2998 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2999 			continue;
3000 		unp->unp_gcrefs++;
3001 		unp_marked++;
3002 	}
3003 }
3004 
3005 static void
3006 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
3007 {
3008 	struct sockbuf *sb;
3009 
3010 	SOCK_LOCK_ASSERT(so);
3011 
3012 	if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
3013 		return;
3014 
3015 	SOCK_RECVBUF_LOCK(so);
3016 	switch (so->so_type) {
3017 	case SOCK_DGRAM:
3018 		unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
3019 		unp_scan(so->so_rcv.uxdg_peeked, op);
3020 		TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist)
3021 			unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op);
3022 		break;
3023 	case SOCK_STREAM:
3024 	case SOCK_SEQPACKET:
3025 		unp_scan(so->so_rcv.sb_mb, op);
3026 		break;
3027 	}
3028 	SOCK_RECVBUF_UNLOCK(so);
3029 }
3030 
3031 static void
3032 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
3033 {
3034 	struct socket *so, *soa;
3035 
3036 	so = unp->unp_socket;
3037 	SOCK_LOCK(so);
3038 	if (SOLISTENING(so)) {
3039 		/*
3040 		 * Mark all sockets in our accept queue.
3041 		 */
3042 		TAILQ_FOREACH(soa, &so->sol_comp, so_list)
3043 			unp_scan_socket(soa, op);
3044 	} else {
3045 		/*
3046 		 * Mark all sockets we reference with RIGHTS.
3047 		 */
3048 		unp_scan_socket(so, op);
3049 	}
3050 	SOCK_UNLOCK(so);
3051 }
3052 
3053 static int unp_recycled;
3054 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
3055     "Number of unreachable sockets claimed by the garbage collector.");
3056 
3057 static int unp_taskcount;
3058 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
3059     "Number of times the garbage collector has run.");
3060 
3061 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
3062     "Number of active local sockets.");
3063 
3064 static void
3065 unp_gc(__unused void *arg, int pending)
3066 {
3067 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
3068 				    NULL };
3069 	struct unp_head **head;
3070 	struct unp_head unp_deadhead;	/* List of potentially-dead sockets. */
3071 	struct file *f, **unref;
3072 	struct unpcb *unp, *unptmp;
3073 	int i, total, unp_unreachable;
3074 
3075 	LIST_INIT(&unp_deadhead);
3076 	unp_taskcount++;
3077 	UNP_LINK_RLOCK();
3078 	/*
3079 	 * First determine which sockets may be in cycles.
3080 	 */
3081 	unp_unreachable = 0;
3082 
3083 	for (head = heads; *head != NULL; head++)
3084 		LIST_FOREACH(unp, *head, unp_link) {
3085 			KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
3086 			    ("%s: unp %p has unexpected gc flags 0x%x",
3087 			    __func__, unp, (unsigned int)unp->unp_gcflag));
3088 
3089 			f = unp->unp_file;
3090 
3091 			/*
3092 			 * Check for an unreachable socket potentially in a
3093 			 * cycle.  It must be in a queue as indicated by
3094 			 * msgcount, and this must equal the file reference
3095 			 * count.  Note that when msgcount is 0 the file is
3096 			 * NULL.
3097 			 */
3098 			if (f != NULL && unp->unp_msgcount != 0 &&
3099 			    refcount_load(&f->f_count) == unp->unp_msgcount) {
3100 				LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
3101 				unp->unp_gcflag |= UNPGC_DEAD;
3102 				unp->unp_gcrefs = unp->unp_msgcount;
3103 				unp_unreachable++;
3104 			}
3105 		}
3106 
3107 	/*
3108 	 * Scan all sockets previously marked as potentially being in a cycle
3109 	 * and remove the references each socket holds on any UNPGC_DEAD
3110 	 * sockets in its queue.  After this step, all remaining references on
3111 	 * sockets marked UNPGC_DEAD should not be part of any cycle.
3112 	 */
3113 	LIST_FOREACH(unp, &unp_deadhead, unp_dead)
3114 		unp_gc_scan(unp, unp_remove_dead_ref);
3115 
3116 	/*
3117 	 * If a socket still has a non-negative refcount, it cannot be in a
3118 	 * cycle.  In this case increment refcount of all children iteratively.
3119 	 * Stop the scan once we do a complete loop without discovering
3120 	 * a new reachable socket.
3121 	 */
3122 	do {
3123 		unp_marked = 0;
3124 		LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
3125 			if (unp->unp_gcrefs > 0) {
3126 				unp->unp_gcflag &= ~UNPGC_DEAD;
3127 				LIST_REMOVE(unp, unp_dead);
3128 				KASSERT(unp_unreachable > 0,
3129 				    ("%s: unp_unreachable underflow.",
3130 				    __func__));
3131 				unp_unreachable--;
3132 				unp_gc_scan(unp, unp_restore_undead_ref);
3133 			}
3134 	} while (unp_marked);
3135 
3136 	UNP_LINK_RUNLOCK();
3137 
3138 	if (unp_unreachable == 0)
3139 		return;
3140 
3141 	/*
3142 	 * Allocate space for a local array of dead unpcbs.
3143 	 * TODO: can this path be simplified by instead using the local
3144 	 * dead list at unp_deadhead, after taking out references
3145 	 * on the file object and/or unpcb and dropping the link lock?
3146 	 */
3147 	unref = malloc(unp_unreachable * sizeof(struct file *),
3148 	    M_TEMP, M_WAITOK);
3149 
3150 	/*
3151 	 * Iterate looking for sockets which have been specifically marked
3152 	 * as unreachable and store them locally.
3153 	 */
3154 	UNP_LINK_RLOCK();
3155 	total = 0;
3156 	LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
3157 		KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
3158 		    ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
3159 		unp->unp_gcflag &= ~UNPGC_DEAD;
3160 		f = unp->unp_file;
3161 		if (unp->unp_msgcount == 0 || f == NULL ||
3162 		    refcount_load(&f->f_count) != unp->unp_msgcount ||
3163 		    !fhold(f))
3164 			continue;
3165 		unref[total++] = f;
3166 		KASSERT(total <= unp_unreachable,
3167 		    ("%s: incorrect unreachable count.", __func__));
3168 	}
3169 	UNP_LINK_RUNLOCK();
3170 
3171 	/*
3172 	 * Now flush all sockets, free'ing rights.  This will free the
3173 	 * struct files associated with these sockets but leave each socket
3174 	 * with one remaining ref.
3175 	 */
3176 	for (i = 0; i < total; i++) {
3177 		struct socket *so;
3178 
3179 		so = unref[i]->f_data;
3180 		CURVNET_SET(so->so_vnet);
3181 		socantrcvmore(so);
3182 		unp_dispose(so);
3183 		CURVNET_RESTORE();
3184 	}
3185 
3186 	/*
3187 	 * And finally release the sockets so they can be reclaimed.
3188 	 */
3189 	for (i = 0; i < total; i++)
3190 		fdrop(unref[i], NULL);
3191 	unp_recycled += total;
3192 	free(unref, M_TEMP);
3193 }
3194 
3195 /*
3196  * Synchronize against unp_gc, which can trip over data as we are freeing it.
3197  */
3198 static void
3199 unp_dispose(struct socket *so)
3200 {
3201 	struct sockbuf *sb;
3202 	struct unpcb *unp;
3203 	struct mbuf *m;
3204 	int error __diagused;
3205 
3206 	MPASS(!SOLISTENING(so));
3207 
3208 	unp = sotounpcb(so);
3209 	UNP_LINK_WLOCK();
3210 	unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
3211 	UNP_LINK_WUNLOCK();
3212 
3213 	/*
3214 	 * Grab our special mbufs before calling sbrelease().
3215 	 */
3216 	error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR);
3217 	MPASS(!error);
3218 	SOCK_RECVBUF_LOCK(so);
3219 	switch (so->so_type) {
3220 	case SOCK_DGRAM:
3221 		while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) {
3222 			STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb);
3223 			TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
3224 			/* Note: socket of sb may reconnect. */
3225 			sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0;
3226 		}
3227 		sb = &so->so_rcv;
3228 		if (sb->uxdg_peeked != NULL) {
3229 			STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked,
3230 			    m_stailqpkt);
3231 			sb->uxdg_peeked = NULL;
3232 		}
3233 		m = STAILQ_FIRST(&sb->uxdg_mb);
3234 		STAILQ_INIT(&sb->uxdg_mb);
3235 		/* XXX: our shortened sbrelease() */
3236 		(void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
3237 		    RLIM_INFINITY);
3238 		/*
3239 		 * XXXGL Mark sb with SBS_CANTRCVMORE.  This is needed to
3240 		 * prevent uipc_sosend_dgram() or unp_disconnect() adding more
3241 		 * data to the socket.
3242 		 * We came here either through shutdown(2) or from the final
3243 		 * sofree().  The sofree() case is simple as it guarantees
3244 		 * that no more sends will happen, however we can race with
3245 		 * unp_disconnect() from our peer.  The shutdown(2) case is
3246 		 * more exotic.  It would call into unp_dispose() only if
3247 		 * socket is SS_ISCONNECTED.  This is possible if we did
3248 		 * connect(2) on this socket and we also had it bound with
3249 		 * bind(2) and receive connections from other sockets.
3250 		 * Because uipc_shutdown() violates POSIX (see comment
3251 		 * there) we will end up here shutting down our receive side.
3252 		 * Of course this will have affect not only on the peer we
3253 		 * connect(2)ed to, but also on all of the peers who had
3254 		 * connect(2)ed to us.  Their sends would end up with ENOBUFS.
3255 		 */
3256 		sb->sb_state |= SBS_CANTRCVMORE;
3257 		break;
3258 	case SOCK_STREAM:
3259 	case SOCK_SEQPACKET:
3260 		sb = &so->so_rcv;
3261 		m = sbcut_locked(sb, sb->sb_ccc);
3262 		KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
3263 		    ("%s: ccc %u mb %p mbcnt %u", __func__,
3264 		    sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
3265 		sbrelease_locked(so, SO_RCV);
3266 		break;
3267 	}
3268 	SOCK_RECVBUF_UNLOCK(so);
3269 	SOCK_IO_RECV_UNLOCK(so);
3270 
3271 	if (m != NULL) {
3272 		unp_scan(m, unp_freerights);
3273 		m_freem(m);
3274 	}
3275 }
3276 
3277 static void
3278 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
3279 {
3280 	struct mbuf *m;
3281 	struct cmsghdr *cm;
3282 	void *data;
3283 	socklen_t clen, datalen;
3284 
3285 	while (m0 != NULL) {
3286 		for (m = m0; m; m = m->m_next) {
3287 			if (m->m_type != MT_CONTROL)
3288 				continue;
3289 
3290 			cm = mtod(m, struct cmsghdr *);
3291 			clen = m->m_len;
3292 
3293 			while (cm != NULL) {
3294 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
3295 					break;
3296 
3297 				data = CMSG_DATA(cm);
3298 				datalen = (caddr_t)cm + cm->cmsg_len
3299 				    - (caddr_t)data;
3300 
3301 				if (cm->cmsg_level == SOL_SOCKET &&
3302 				    cm->cmsg_type == SCM_RIGHTS) {
3303 					(*op)(data, datalen /
3304 					    sizeof(struct filedescent *));
3305 				}
3306 
3307 				if (CMSG_SPACE(datalen) < clen) {
3308 					clen -= CMSG_SPACE(datalen);
3309 					cm = (struct cmsghdr *)
3310 					    ((caddr_t)cm + CMSG_SPACE(datalen));
3311 				} else {
3312 					clen = 0;
3313 					cm = NULL;
3314 				}
3315 			}
3316 		}
3317 		m0 = m0->m_nextpkt;
3318 	}
3319 }
3320 
3321 /*
3322  * Definitions of protocols supported in the LOCAL domain.
3323  */
3324 static struct protosw streamproto = {
3325 	.pr_type =		SOCK_STREAM,
3326 	.pr_flags =		PR_CONNREQUIRED | PR_WANTRCVD | PR_CAPATTACH,
3327 	.pr_ctloutput =		&uipc_ctloutput,
3328 	.pr_abort = 		uipc_abort,
3329 	.pr_accept =		uipc_peeraddr,
3330 	.pr_attach =		uipc_attach,
3331 	.pr_bind =		uipc_bind,
3332 	.pr_bindat =		uipc_bindat,
3333 	.pr_connect =		uipc_connect,
3334 	.pr_connectat =		uipc_connectat,
3335 	.pr_connect2 =		uipc_connect2,
3336 	.pr_detach =		uipc_detach,
3337 	.pr_disconnect =	uipc_disconnect,
3338 	.pr_listen =		uipc_listen,
3339 	.pr_peeraddr =		uipc_peeraddr,
3340 	.pr_rcvd =		uipc_rcvd,
3341 	.pr_send =		uipc_send,
3342 	.pr_ready =		uipc_ready,
3343 	.pr_sense =		uipc_sense,
3344 	.pr_shutdown =		uipc_shutdown,
3345 	.pr_sockaddr =		uipc_sockaddr,
3346 	.pr_soreceive =		soreceive_generic,
3347 	.pr_close =		uipc_close,
3348 };
3349 
3350 static struct protosw dgramproto = {
3351 	.pr_type =		SOCK_DGRAM,
3352 	.pr_flags =		PR_ATOMIC | PR_ADDR | PR_CAPATTACH | PR_SOCKBUF,
3353 	.pr_ctloutput =		&uipc_ctloutput,
3354 	.pr_abort = 		uipc_abort,
3355 	.pr_accept =		uipc_peeraddr,
3356 	.pr_attach =		uipc_attach,
3357 	.pr_bind =		uipc_bind,
3358 	.pr_bindat =		uipc_bindat,
3359 	.pr_connect =		uipc_connect,
3360 	.pr_connectat =		uipc_connectat,
3361 	.pr_connect2 =		uipc_connect2,
3362 	.pr_detach =		uipc_detach,
3363 	.pr_disconnect =	uipc_disconnect,
3364 	.pr_peeraddr =		uipc_peeraddr,
3365 	.pr_sosend =		uipc_sosend_dgram,
3366 	.pr_sense =		uipc_sense,
3367 	.pr_shutdown =		uipc_shutdown,
3368 	.pr_sockaddr =		uipc_sockaddr,
3369 	.pr_soreceive =		uipc_soreceive_dgram,
3370 	.pr_close =		uipc_close,
3371 };
3372 
3373 static struct protosw seqpacketproto = {
3374 	.pr_type =		SOCK_SEQPACKET,
3375 	/*
3376 	 * XXXRW: For now, PR_ADDR because soreceive will bump into them
3377 	 * due to our use of sbappendaddr.  A new sbappend variants is needed
3378 	 * that supports both atomic record writes and control data.
3379 	 */
3380 	.pr_flags =		PR_ADDR | PR_ATOMIC | PR_CONNREQUIRED |
3381 				PR_WANTRCVD | PR_CAPATTACH,
3382 	.pr_ctloutput =		&uipc_ctloutput,
3383 	.pr_abort =		uipc_abort,
3384 	.pr_accept =		uipc_peeraddr,
3385 	.pr_attach =		uipc_attach,
3386 	.pr_bind =		uipc_bind,
3387 	.pr_bindat =		uipc_bindat,
3388 	.pr_connect =		uipc_connect,
3389 	.pr_connectat =		uipc_connectat,
3390 	.pr_connect2 =		uipc_connect2,
3391 	.pr_detach =		uipc_detach,
3392 	.pr_disconnect =	uipc_disconnect,
3393 	.pr_listen =		uipc_listen,
3394 	.pr_peeraddr =		uipc_peeraddr,
3395 	.pr_rcvd =		uipc_rcvd,
3396 	.pr_send =		uipc_send,
3397 	.pr_sense =		uipc_sense,
3398 	.pr_shutdown =		uipc_shutdown,
3399 	.pr_sockaddr =		uipc_sockaddr,
3400 	.pr_soreceive =		soreceive_generic,	/* XXX: or...? */
3401 	.pr_close =		uipc_close,
3402 };
3403 
3404 static struct domain localdomain = {
3405 	.dom_family =		AF_LOCAL,
3406 	.dom_name =		"local",
3407 	.dom_externalize =	unp_externalize,
3408 	.dom_nprotosw =		3,
3409 	.dom_protosw =		{
3410 		&streamproto,
3411 		&dgramproto,
3412 		&seqpacketproto,
3413 	}
3414 };
3415 DOMAIN_SET(local);
3416 
3417 /*
3418  * A helper function called by VFS before socket-type vnode reclamation.
3419  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
3420  * use count.
3421  */
3422 void
3423 vfs_unp_reclaim(struct vnode *vp)
3424 {
3425 	struct unpcb *unp;
3426 	int active;
3427 	struct mtx *vplock;
3428 
3429 	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
3430 	KASSERT(vp->v_type == VSOCK,
3431 	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
3432 
3433 	active = 0;
3434 	vplock = mtx_pool_find(mtxpool_sleep, vp);
3435 	mtx_lock(vplock);
3436 	VOP_UNP_CONNECT(vp, &unp);
3437 	if (unp == NULL)
3438 		goto done;
3439 	UNP_PCB_LOCK(unp);
3440 	if (unp->unp_vnode == vp) {
3441 		VOP_UNP_DETACH(vp);
3442 		unp->unp_vnode = NULL;
3443 		active = 1;
3444 	}
3445 	UNP_PCB_UNLOCK(unp);
3446  done:
3447 	mtx_unlock(vplock);
3448 	if (active)
3449 		vunref(vp);
3450 }
3451 
3452 #ifdef DDB
3453 static void
3454 db_print_indent(int indent)
3455 {
3456 	int i;
3457 
3458 	for (i = 0; i < indent; i++)
3459 		db_printf(" ");
3460 }
3461 
3462 static void
3463 db_print_unpflags(int unp_flags)
3464 {
3465 	int comma;
3466 
3467 	comma = 0;
3468 	if (unp_flags & UNP_HAVEPC) {
3469 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
3470 		comma = 1;
3471 	}
3472 	if (unp_flags & UNP_WANTCRED_ALWAYS) {
3473 		db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
3474 		comma = 1;
3475 	}
3476 	if (unp_flags & UNP_WANTCRED_ONESHOT) {
3477 		db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
3478 		comma = 1;
3479 	}
3480 	if (unp_flags & UNP_CONNECTING) {
3481 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
3482 		comma = 1;
3483 	}
3484 	if (unp_flags & UNP_BINDING) {
3485 		db_printf("%sUNP_BINDING", comma ? ", " : "");
3486 		comma = 1;
3487 	}
3488 }
3489 
3490 static void
3491 db_print_xucred(int indent, struct xucred *xu)
3492 {
3493 	int comma, i;
3494 
3495 	db_print_indent(indent);
3496 	db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
3497 	    xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
3498 	db_print_indent(indent);
3499 	db_printf("cr_groups: ");
3500 	comma = 0;
3501 	for (i = 0; i < xu->cr_ngroups; i++) {
3502 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
3503 		comma = 1;
3504 	}
3505 	db_printf("\n");
3506 }
3507 
3508 static void
3509 db_print_unprefs(int indent, struct unp_head *uh)
3510 {
3511 	struct unpcb *unp;
3512 	int counter;
3513 
3514 	counter = 0;
3515 	LIST_FOREACH(unp, uh, unp_reflink) {
3516 		if (counter % 4 == 0)
3517 			db_print_indent(indent);
3518 		db_printf("%p  ", unp);
3519 		if (counter % 4 == 3)
3520 			db_printf("\n");
3521 		counter++;
3522 	}
3523 	if (counter != 0 && counter % 4 != 0)
3524 		db_printf("\n");
3525 }
3526 
3527 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
3528 {
3529 	struct unpcb *unp;
3530 
3531         if (!have_addr) {
3532                 db_printf("usage: show unpcb <addr>\n");
3533                 return;
3534         }
3535         unp = (struct unpcb *)addr;
3536 
3537 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
3538 	    unp->unp_vnode);
3539 
3540 	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
3541 	    unp->unp_conn);
3542 
3543 	db_printf("unp_refs:\n");
3544 	db_print_unprefs(2, &unp->unp_refs);
3545 
3546 	/* XXXRW: Would be nice to print the full address, if any. */
3547 	db_printf("unp_addr: %p\n", unp->unp_addr);
3548 
3549 	db_printf("unp_gencnt: %llu\n",
3550 	    (unsigned long long)unp->unp_gencnt);
3551 
3552 	db_printf("unp_flags: %x (", unp->unp_flags);
3553 	db_print_unpflags(unp->unp_flags);
3554 	db_printf(")\n");
3555 
3556 	db_printf("unp_peercred:\n");
3557 	db_print_xucred(2, &unp->unp_peercred);
3558 
3559 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
3560 }
3561 #endif
3562