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