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