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