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