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