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