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