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