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