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