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