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