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