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