uipc_usrreq.c revision 174988
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 *	lock pushdown
57 */
58
59#include <sys/cdefs.h>
60__FBSDID("$FreeBSD: head/sys/kern/uipc_usrreq.c 174988 2007-12-30 01:42:15Z jeff $");
61
62#include "opt_ddb.h"
63#include "opt_mac.h"
64
65#include <sys/param.h>
66#include <sys/domain.h>
67#include <sys/fcntl.h>
68#include <sys/malloc.h>		/* XXX must be before <sys/file.h> */
69#include <sys/eventhandler.h>
70#include <sys/file.h>
71#include <sys/filedesc.h>
72#include <sys/jail.h>
73#include <sys/kernel.h>
74#include <sys/lock.h>
75#include <sys/mbuf.h>
76#include <sys/mount.h>
77#include <sys/mutex.h>
78#include <sys/namei.h>
79#include <sys/proc.h>
80#include <sys/protosw.h>
81#include <sys/resourcevar.h>
82#include <sys/rwlock.h>
83#include <sys/socket.h>
84#include <sys/socketvar.h>
85#include <sys/signalvar.h>
86#include <sys/stat.h>
87#include <sys/sx.h>
88#include <sys/sysctl.h>
89#include <sys/systm.h>
90#include <sys/taskqueue.h>
91#include <sys/un.h>
92#include <sys/unpcb.h>
93#include <sys/vnode.h>
94
95#ifdef DDB
96#include <ddb/ddb.h>
97#endif
98
99#include <security/mac/mac_framework.h>
100
101#include <vm/uma.h>
102
103static uma_zone_t	unp_zone;
104static unp_gen_t	unp_gencnt;
105static u_int		unp_count;	/* Count of local sockets. */
106static ino_t		unp_ino;	/* Prototype for fake inode numbers. */
107static int		unp_rights;	/* File descriptors in flight. */
108static struct unp_head	unp_shead;	/* List of local stream sockets. */
109static struct unp_head	unp_dhead;	/* List of local datagram sockets. */
110
111static const struct sockaddr	sun_noname = { sizeof(sun_noname), AF_LOCAL };
112
113/*
114 * Garbage collection of cyclic file descriptor/socket references occurs
115 * asynchronously in a taskqueue context in order to avoid recursion and
116 * reentrance in the UNIX domain socket, file descriptor, and socket layer
117 * code.  See unp_gc() for a full description.
118 */
119static struct task	unp_gc_task;
120
121/*
122 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
123 * stream sockets, although the total for sender and receiver is actually
124 * only PIPSIZ.
125 *
126 * Datagram sockets really use the sendspace as the maximum datagram size,
127 * and don't really want to reserve the sendspace.  Their recvspace should be
128 * large enough for at least one max-size datagram plus address.
129 */
130#ifndef PIPSIZ
131#define	PIPSIZ	8192
132#endif
133static u_long	unpst_sendspace = PIPSIZ;
134static u_long	unpst_recvspace = PIPSIZ;
135static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
136static u_long	unpdg_recvspace = 4*1024;
137
138SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
139SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0, "SOCK_STREAM");
140SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
141
142SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
143	   &unpst_sendspace, 0, "");
144SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
145	   &unpst_recvspace, 0, "");
146SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
147	   &unpdg_sendspace, 0, "");
148SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
149	   &unpdg_recvspace, 0, "");
150SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
151
152/*-
153 * Locking and synchronization:
154 *
155 * The global UNIX domain socket rwlock (unp_global_rwlock) protects all
156 * global variables, including the linked lists tracking the set of allocated
157 * UNIX domain sockets.  The global rwlock also serves to prevent deadlock
158 * when more than one PCB lock is acquired at a time (i.e., during
159 * connect()).  Finally, the global rwlock protects uncounted references from
160 * vnodes to sockets bound to those vnodes: to safely dereference the
161 * v_socket pointer, the global rwlock must be held while a full reference is
162 * acquired.
163 *
164 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
165 * allocated in pru_attach() and freed in pru_detach().  The validity of that
166 * pointer is an invariant, so no lock is required to dereference the so_pcb
167 * pointer if a valid socket reference is held by the caller.  In practice,
168 * this is always true during operations performed on a socket.  Each unpcb
169 * has a back-pointer to its socket, unp_socket, which will be stable under
170 * the same circumstances.
171 *
172 * This pointer may only be safely dereferenced as long as a valid reference
173 * to the unpcb is held.  Typically, this reference will be from the socket,
174 * or from another unpcb when the referring unpcb's lock is held (in order
175 * that the reference not be invalidated during use).  For example, to follow
176 * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
177 * as unp_socket remains valid as long as the reference to unp_conn is valid.
178 *
179 * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx.  Individual
180 * atomic reads without the lock may be performed "lockless", but more
181 * complex reads and read-modify-writes require the mutex to be held.  No
182 * lock order is defined between unpcb locks -- multiple unpcb locks may be
183 * acquired at the same time only when holding the global UNIX domain socket
184 * rwlock exclusively, which prevents deadlocks.
185 *
186 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
187 * protocols, bind() is a non-atomic operation, and connect() requires
188 * potential sleeping in the protocol, due to potentially waiting on local or
189 * distributed file systems.  We try to separate "lookup" operations, which
190 * may sleep, and the IPC operations themselves, which typically can occur
191 * with relative atomicity as locks can be held over the entire operation.
192 *
193 * Another tricky issue is simultaneous multi-threaded or multi-process
194 * access to a single UNIX domain socket.  These are handled by the flags
195 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
196 * binding, both of which involve dropping UNIX domain socket locks in order
197 * to perform namei() and other file system operations.
198 */
199static struct rwlock	unp_global_rwlock;
200
201#define	UNP_GLOBAL_LOCK_INIT()		rw_init(&unp_global_rwlock,	\
202					    "unp_global_rwlock")
203
204#define	UNP_GLOBAL_LOCK_ASSERT()	rw_assert(&unp_global_rwlock,	\
205					    RA_LOCKED)
206#define	UNP_GLOBAL_UNLOCK_ASSERT()	rw_assert(&unp_global_rwlock,	\
207					    RA_UNLOCKED)
208
209#define	UNP_GLOBAL_WLOCK()		rw_wlock(&unp_global_rwlock)
210#define	UNP_GLOBAL_WUNLOCK()		rw_wunlock(&unp_global_rwlock)
211#define	UNP_GLOBAL_WLOCK_ASSERT()	rw_assert(&unp_global_rwlock,	\
212					    RA_WLOCKED)
213#define	UNP_GLOBAL_WOWNED()		rw_wowned(&unp_global_rwlock)
214
215#define	UNP_GLOBAL_RLOCK()		rw_rlock(&unp_global_rwlock)
216#define	UNP_GLOBAL_RUNLOCK()		rw_runlock(&unp_global_rwlock)
217#define	UNP_GLOBAL_RLOCK_ASSERT()	rw_assert(&unp_global_rwlock,	\
218					    RA_RLOCKED)
219
220#define UNP_PCB_LOCK_INIT(unp)		mtx_init(&(unp)->unp_mtx,	\
221					    "unp_mtx", "unp_mtx",	\
222					    MTX_DUPOK|MTX_DEF|MTX_RECURSE)
223#define	UNP_PCB_LOCK_DESTROY(unp)	mtx_destroy(&(unp)->unp_mtx)
224#define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
225#define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
226#define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
227
228static int	unp_connect(struct socket *, struct sockaddr *,
229		    struct thread *);
230static int	unp_connect2(struct socket *so, struct socket *so2, int);
231static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
232static void	unp_shutdown(struct unpcb *);
233static void	unp_drop(struct unpcb *, int);
234static void	unp_gc(__unused void *, int);
235static void	unp_scan(struct mbuf *, void (*)(struct file *));
236static void	unp_discard(struct file *);
237static void	unp_freerights(struct file **, int);
238static int	unp_internalize(struct mbuf **, struct thread *);
239static void	unp_internalize_fp(struct file *);
240static void	unp_externalize_fp(struct file *);
241static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *);
242
243/*
244 * Definitions of protocols supported in the LOCAL domain.
245 */
246static struct domain localdomain;
247static struct protosw localsw[] = {
248{
249	.pr_type =		SOCK_STREAM,
250	.pr_domain =		&localdomain,
251	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
252	.pr_ctloutput =		&uipc_ctloutput,
253	.pr_usrreqs =		&uipc_usrreqs
254},
255{
256	.pr_type =		SOCK_DGRAM,
257	.pr_domain =		&localdomain,
258	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS,
259	.pr_usrreqs =		&uipc_usrreqs
260},
261};
262
263static struct domain localdomain = {
264	.dom_family =		AF_LOCAL,
265	.dom_name =		"local",
266	.dom_init =		unp_init,
267	.dom_externalize =	unp_externalize,
268	.dom_dispose =		unp_dispose,
269	.dom_protosw =		localsw,
270	.dom_protoswNPROTOSW =	&localsw[sizeof(localsw)/sizeof(localsw[0])]
271};
272DOMAIN_SET(local);
273
274static void
275uipc_abort(struct socket *so)
276{
277	struct unpcb *unp, *unp2;
278
279	unp = sotounpcb(so);
280	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
281
282	UNP_GLOBAL_WLOCK();
283	UNP_PCB_LOCK(unp);
284	unp2 = unp->unp_conn;
285	if (unp2 != NULL) {
286		UNP_PCB_LOCK(unp2);
287		unp_drop(unp2, ECONNABORTED);
288		UNP_PCB_UNLOCK(unp2);
289	}
290	UNP_PCB_UNLOCK(unp);
291	UNP_GLOBAL_WUNLOCK();
292}
293
294static int
295uipc_accept(struct socket *so, struct sockaddr **nam)
296{
297	struct unpcb *unp, *unp2;
298	const struct sockaddr *sa;
299
300	/*
301	 * Pass back name of connected socket, if it was bound and we are
302	 * still connected (our peer may have closed already!).
303	 */
304	unp = sotounpcb(so);
305	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
306
307	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
308	UNP_GLOBAL_RLOCK();
309	unp2 = unp->unp_conn;
310	if (unp2 != NULL && unp2->unp_addr != NULL) {
311		UNP_PCB_LOCK(unp2);
312		sa = (struct sockaddr *) unp2->unp_addr;
313		bcopy(sa, *nam, sa->sa_len);
314		UNP_PCB_UNLOCK(unp2);
315	} else {
316		sa = &sun_noname;
317		bcopy(sa, *nam, sa->sa_len);
318	}
319	UNP_GLOBAL_RUNLOCK();
320	return (0);
321}
322
323static int
324uipc_attach(struct socket *so, int proto, struct thread *td)
325{
326	u_long sendspace, recvspace;
327	struct unpcb *unp;
328	int error, locked;
329
330	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
331	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
332		switch (so->so_type) {
333		case SOCK_STREAM:
334			sendspace = unpst_sendspace;
335			recvspace = unpst_recvspace;
336			break;
337
338		case SOCK_DGRAM:
339			sendspace = unpdg_sendspace;
340			recvspace = unpdg_recvspace;
341			break;
342
343		default:
344			panic("uipc_attach");
345		}
346		error = soreserve(so, sendspace, recvspace);
347		if (error)
348			return (error);
349	}
350	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
351	if (unp == NULL)
352		return (ENOBUFS);
353	LIST_INIT(&unp->unp_refs);
354	UNP_PCB_LOCK_INIT(unp);
355	unp->unp_socket = so;
356	so->so_pcb = unp;
357	unp->unp_refcount = 1;
358
359	/*
360	 * uipc_attach() may be called indirectly from within the UNIX domain
361	 * socket code via sonewconn() in unp_connect().  Since rwlocks can
362	 * not be recursed, we do the closest thing.
363	 */
364	locked = 0;
365	if (!UNP_GLOBAL_WOWNED()) {
366		UNP_GLOBAL_WLOCK();
367		locked = 1;
368	}
369	unp->unp_gencnt = ++unp_gencnt;
370	unp_count++;
371	LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead : &unp_shead,
372	    unp, unp_link);
373	if (locked)
374		UNP_GLOBAL_WUNLOCK();
375
376	return (0);
377}
378
379static int
380uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
381{
382	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
383	struct vattr vattr;
384	int error, namelen, vfslocked;
385	struct nameidata nd;
386	struct unpcb *unp;
387	struct vnode *vp;
388	struct mount *mp;
389	char *buf;
390
391	unp = sotounpcb(so);
392	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
393
394	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
395	if (namelen <= 0)
396		return (EINVAL);
397
398	/*
399	 * We don't allow simultaneous bind() calls on a single UNIX domain
400	 * socket, so flag in-progress operations, and return an error if an
401	 * operation is already in progress.
402	 *
403	 * Historically, we have not allowed a socket to be rebound, so this
404	 * also returns an error.  Not allowing re-binding simplifies the
405	 * implementation and avoids a great many possible failure modes.
406	 */
407	UNP_PCB_LOCK(unp);
408	if (unp->unp_vnode != NULL) {
409		UNP_PCB_UNLOCK(unp);
410		return (EINVAL);
411	}
412	if (unp->unp_flags & UNP_BINDING) {
413		UNP_PCB_UNLOCK(unp);
414		return (EALREADY);
415	}
416	unp->unp_flags |= UNP_BINDING;
417	UNP_PCB_UNLOCK(unp);
418
419	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
420	strlcpy(buf, soun->sun_path, namelen + 1);
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, td);
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			/* Unocked 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			/* Unocked 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	UNP_GLOBAL_WUNLOCK();
1127
1128	unp = sotounpcb(so);
1129	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1130
1131	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1132	if (len <= 0)
1133		return (EINVAL);
1134	strlcpy(buf, soun->sun_path, len + 1);
1135
1136	UNP_PCB_LOCK(unp);
1137	if (unp->unp_flags & UNP_CONNECTING) {
1138		UNP_PCB_UNLOCK(unp);
1139		return (EALREADY);
1140	}
1141	unp->unp_flags |= UNP_CONNECTING;
1142	UNP_PCB_UNLOCK(unp);
1143
1144	sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1145	NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf,
1146	    td);
1147	error = namei(&nd);
1148	if (error)
1149		vp = NULL;
1150	else
1151		vp = nd.ni_vp;
1152	ASSERT_VOP_LOCKED(vp, "unp_connect");
1153	vfslocked = NDHASGIANT(&nd);
1154	NDFREE(&nd, NDF_ONLY_PNBUF);
1155	if (error)
1156		goto bad;
1157
1158	if (vp->v_type != VSOCK) {
1159		error = ENOTSOCK;
1160		goto bad;
1161	}
1162#ifdef MAC
1163	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1164	if (error)
1165		goto bad;
1166#endif
1167	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1168	if (error)
1169		goto bad;
1170	VFS_UNLOCK_GIANT(vfslocked);
1171
1172	unp = sotounpcb(so);
1173	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1174
1175	/*
1176	 * Lock global lock for two reasons: make sure v_socket is stable,
1177	 * and to protect simultaneous locking of multiple pcbs.
1178	 */
1179	UNP_GLOBAL_WLOCK();
1180	so2 = vp->v_socket;
1181	if (so2 == NULL) {
1182		error = ECONNREFUSED;
1183		goto bad2;
1184	}
1185	if (so->so_type != so2->so_type) {
1186		error = EPROTOTYPE;
1187		goto bad2;
1188	}
1189	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1190		if (so2->so_options & SO_ACCEPTCONN) {
1191			/*
1192			 * We can't drop the global lock here or 'so2' may
1193			 * become invalid.  As a result, we need to handle
1194			 * possibly lock recursion in uipc_attach.
1195			 */
1196			so3 = sonewconn(so2, 0);
1197		} else
1198			so3 = NULL;
1199		if (so3 == NULL) {
1200			error = ECONNREFUSED;
1201			goto bad2;
1202		}
1203		unp = sotounpcb(so);
1204		unp2 = sotounpcb(so2);
1205		unp3 = sotounpcb(so3);
1206		UNP_PCB_LOCK(unp);
1207		UNP_PCB_LOCK(unp2);
1208		UNP_PCB_LOCK(unp3);
1209		if (unp2->unp_addr != NULL) {
1210			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1211			unp3->unp_addr = (struct sockaddr_un *) sa;
1212			sa = NULL;
1213		}
1214		/*
1215		 * unp_peercred management:
1216		 *
1217		 * The connecter's (client's) credentials are copied from its
1218		 * process structure at the time of connect() (which is now).
1219		 */
1220		cru2x(td->td_ucred, &unp3->unp_peercred);
1221		unp3->unp_flags |= UNP_HAVEPC;
1222		/*
1223		 * The receiver's (server's) credentials are copied from the
1224		 * unp_peercred member of socket on which the former called
1225		 * listen(); uipc_listen() cached that process's credentials
1226		 * at that time so we can use them now.
1227		 */
1228		KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1229		    ("unp_connect: listener without cached peercred"));
1230		memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1231		    sizeof(unp->unp_peercred));
1232		unp->unp_flags |= UNP_HAVEPC;
1233		if (unp2->unp_flags & UNP_WANTCRED)
1234			unp3->unp_flags |= UNP_WANTCRED;
1235		UNP_PCB_UNLOCK(unp3);
1236		UNP_PCB_UNLOCK(unp2);
1237		UNP_PCB_UNLOCK(unp);
1238#ifdef MAC
1239		SOCK_LOCK(so);
1240		mac_socketpeer_set_from_socket(so, so3);
1241		mac_socketpeer_set_from_socket(so3, so);
1242		SOCK_UNLOCK(so);
1243#endif
1244
1245		so2 = so3;
1246	}
1247	unp = sotounpcb(so);
1248	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1249	unp2 = sotounpcb(so2);
1250	KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1251	UNP_PCB_LOCK(unp);
1252	UNP_PCB_LOCK(unp2);
1253	error = unp_connect2(so, so2, PRU_CONNECT);
1254	UNP_PCB_UNLOCK(unp2);
1255	UNP_PCB_UNLOCK(unp);
1256bad2:
1257	UNP_GLOBAL_WUNLOCK();
1258	if (vfslocked)
1259		/*
1260		 * Giant has been previously acquired. This means filesystem
1261		 * isn't MPSAFE. Do it once again.
1262		 */
1263		mtx_lock(&Giant);
1264bad:
1265	if (vp != NULL)
1266		vput(vp);
1267	VFS_UNLOCK_GIANT(vfslocked);
1268	free(sa, M_SONAME);
1269	UNP_GLOBAL_WLOCK();
1270	UNP_PCB_LOCK(unp);
1271	unp->unp_flags &= ~UNP_CONNECTING;
1272	UNP_PCB_UNLOCK(unp);
1273	return (error);
1274}
1275
1276static int
1277unp_connect2(struct socket *so, struct socket *so2, int req)
1278{
1279	struct unpcb *unp;
1280	struct unpcb *unp2;
1281
1282	unp = sotounpcb(so);
1283	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1284	unp2 = sotounpcb(so2);
1285	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1286
1287	UNP_GLOBAL_WLOCK_ASSERT();
1288	UNP_PCB_LOCK_ASSERT(unp);
1289	UNP_PCB_LOCK_ASSERT(unp2);
1290
1291	if (so2->so_type != so->so_type)
1292		return (EPROTOTYPE);
1293	unp->unp_conn = unp2;
1294
1295	switch (so->so_type) {
1296	case SOCK_DGRAM:
1297		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1298		soisconnected(so);
1299		break;
1300
1301	case SOCK_STREAM:
1302		unp2->unp_conn = unp;
1303		if (req == PRU_CONNECT &&
1304		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1305			soisconnecting(so);
1306		else
1307			soisconnected(so);
1308		soisconnected(so2);
1309		break;
1310
1311	default:
1312		panic("unp_connect2");
1313	}
1314	return (0);
1315}
1316
1317static void
1318unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1319{
1320	struct socket *so;
1321
1322	KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1323
1324	UNP_GLOBAL_WLOCK_ASSERT();
1325	UNP_PCB_LOCK_ASSERT(unp);
1326	UNP_PCB_LOCK_ASSERT(unp2);
1327
1328	unp->unp_conn = NULL;
1329	switch (unp->unp_socket->so_type) {
1330	case SOCK_DGRAM:
1331		LIST_REMOVE(unp, unp_reflink);
1332		so = unp->unp_socket;
1333		SOCK_LOCK(so);
1334		so->so_state &= ~SS_ISCONNECTED;
1335		SOCK_UNLOCK(so);
1336		break;
1337
1338	case SOCK_STREAM:
1339		soisdisconnected(unp->unp_socket);
1340		unp2->unp_conn = NULL;
1341		soisdisconnected(unp2->unp_socket);
1342		break;
1343	}
1344}
1345
1346/*
1347 * unp_pcblist() walks the global list of struct unpcb's to generate a
1348 * pointer list, bumping the refcount on each unpcb.  It then copies them out
1349 * sequentially, validating the generation number on each to see if it has
1350 * been detached.  All of this is necessary because copyout() may sleep on
1351 * disk I/O.
1352 */
1353static int
1354unp_pcblist(SYSCTL_HANDLER_ARGS)
1355{
1356	int error, i, n;
1357	int freeunp;
1358	struct unpcb *unp, **unp_list;
1359	unp_gen_t gencnt;
1360	struct xunpgen *xug;
1361	struct unp_head *head;
1362	struct xunpcb *xu;
1363
1364	head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1365
1366	/*
1367	 * The process of preparing the PCB list is too time-consuming and
1368	 * resource-intensive to repeat twice on every request.
1369	 */
1370	if (req->oldptr == NULL) {
1371		n = unp_count;
1372		req->oldidx = 2 * (sizeof *xug)
1373			+ (n + n/8) * sizeof(struct xunpcb);
1374		return (0);
1375	}
1376
1377	if (req->newptr != NULL)
1378		return (EPERM);
1379
1380	/*
1381	 * OK, now we're committed to doing something.
1382	 */
1383	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1384	UNP_GLOBAL_RLOCK();
1385	gencnt = unp_gencnt;
1386	n = unp_count;
1387	UNP_GLOBAL_RUNLOCK();
1388
1389	xug->xug_len = sizeof *xug;
1390	xug->xug_count = n;
1391	xug->xug_gen = gencnt;
1392	xug->xug_sogen = so_gencnt;
1393	error = SYSCTL_OUT(req, xug, sizeof *xug);
1394	if (error) {
1395		free(xug, M_TEMP);
1396		return (error);
1397	}
1398
1399	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1400
1401	UNP_GLOBAL_RLOCK();
1402	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1403	     unp = LIST_NEXT(unp, unp_link)) {
1404		UNP_PCB_LOCK(unp);
1405		if (unp->unp_gencnt <= gencnt) {
1406			if (cr_cansee(req->td->td_ucred,
1407			    unp->unp_socket->so_cred)) {
1408				UNP_PCB_UNLOCK(unp);
1409				continue;
1410			}
1411			unp_list[i++] = unp;
1412			unp->unp_refcount++;
1413		}
1414		UNP_PCB_UNLOCK(unp);
1415	}
1416	UNP_GLOBAL_RUNLOCK();
1417	n = i;			/* In case we lost some during malloc. */
1418
1419	error = 0;
1420	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1421	for (i = 0; i < n; i++) {
1422		unp = unp_list[i];
1423		UNP_PCB_LOCK(unp);
1424		unp->unp_refcount--;
1425	        if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1426			xu->xu_len = sizeof *xu;
1427			xu->xu_unpp = unp;
1428			/*
1429			 * XXX - need more locking here to protect against
1430			 * connect/disconnect races for SMP.
1431			 */
1432			if (unp->unp_addr != NULL)
1433				bcopy(unp->unp_addr, &xu->xu_addr,
1434				      unp->unp_addr->sun_len);
1435			if (unp->unp_conn != NULL &&
1436			    unp->unp_conn->unp_addr != NULL)
1437				bcopy(unp->unp_conn->unp_addr,
1438				      &xu->xu_caddr,
1439				      unp->unp_conn->unp_addr->sun_len);
1440			bcopy(unp, &xu->xu_unp, sizeof *unp);
1441			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1442			UNP_PCB_UNLOCK(unp);
1443			error = SYSCTL_OUT(req, xu, sizeof *xu);
1444		} else {
1445			freeunp = (unp->unp_refcount == 0);
1446			UNP_PCB_UNLOCK(unp);
1447			if (freeunp) {
1448				UNP_PCB_LOCK_DESTROY(unp);
1449				uma_zfree(unp_zone, unp);
1450			}
1451		}
1452	}
1453	free(xu, M_TEMP);
1454	if (!error) {
1455		/*
1456		 * Give the user an updated idea of our state.  If the
1457		 * generation differs from what we told her before, she knows
1458		 * that something happened while we were processing this
1459		 * request, and it might be necessary to retry.
1460		 */
1461		xug->xug_gen = unp_gencnt;
1462		xug->xug_sogen = so_gencnt;
1463		xug->xug_count = unp_count;
1464		error = SYSCTL_OUT(req, xug, sizeof *xug);
1465	}
1466	free(unp_list, M_TEMP);
1467	free(xug, M_TEMP);
1468	return (error);
1469}
1470
1471SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1472	    (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1473	    "List of active local datagram sockets");
1474SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1475	    (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1476	    "List of active local stream sockets");
1477
1478static void
1479unp_shutdown(struct unpcb *unp)
1480{
1481	struct unpcb *unp2;
1482	struct socket *so;
1483
1484	UNP_GLOBAL_WLOCK_ASSERT();
1485	UNP_PCB_LOCK_ASSERT(unp);
1486
1487	unp2 = unp->unp_conn;
1488	if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1489		so = unp2->unp_socket;
1490		if (so != NULL)
1491			socantrcvmore(so);
1492	}
1493}
1494
1495static void
1496unp_drop(struct unpcb *unp, int errno)
1497{
1498	struct socket *so = unp->unp_socket;
1499	struct unpcb *unp2;
1500
1501	UNP_GLOBAL_WLOCK_ASSERT();
1502	UNP_PCB_LOCK_ASSERT(unp);
1503
1504	so->so_error = errno;
1505	unp2 = unp->unp_conn;
1506	if (unp2 == NULL)
1507		return;
1508
1509	UNP_PCB_LOCK(unp2);
1510	unp_disconnect(unp, unp2);
1511	UNP_PCB_UNLOCK(unp2);
1512}
1513
1514static void
1515unp_freerights(struct file **rp, int fdcount)
1516{
1517	int i;
1518	struct file *fp;
1519
1520	for (i = 0; i < fdcount; i++) {
1521		/*
1522		 * Zero the pointer before calling unp_discard since it may
1523		 * end up in unp_gc()..
1524		 *
1525		 * XXXRW: This is less true than it used to be.
1526		 */
1527		fp = *rp;
1528		*rp++ = NULL;
1529		unp_discard(fp);
1530	}
1531}
1532
1533int
1534unp_externalize(struct mbuf *control, struct mbuf **controlp)
1535{
1536	struct thread *td = curthread;		/* XXX */
1537	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1538	int i;
1539	int *fdp;
1540	struct file **rp;
1541	struct file *fp;
1542	void *data;
1543	socklen_t clen = control->m_len, datalen;
1544	int error, newfds;
1545	int f;
1546	u_int newlen;
1547
1548	UNP_GLOBAL_UNLOCK_ASSERT();
1549
1550	error = 0;
1551	if (controlp != NULL) /* controlp == NULL => free control messages */
1552		*controlp = NULL;
1553
1554	while (cm != NULL) {
1555		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1556			error = EINVAL;
1557			break;
1558		}
1559
1560		data = CMSG_DATA(cm);
1561		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1562
1563		if (cm->cmsg_level == SOL_SOCKET
1564		    && cm->cmsg_type == SCM_RIGHTS) {
1565			newfds = datalen / sizeof(struct file *);
1566			rp = data;
1567
1568			/* If we're not outputting the descriptors free them. */
1569			if (error || controlp == NULL) {
1570				unp_freerights(rp, newfds);
1571				goto next;
1572			}
1573			FILEDESC_XLOCK(td->td_proc->p_fd);
1574			/* if the new FD's will not fit free them.  */
1575			if (!fdavail(td, newfds)) {
1576				FILEDESC_XUNLOCK(td->td_proc->p_fd);
1577				error = EMSGSIZE;
1578				unp_freerights(rp, newfds);
1579				goto next;
1580			}
1581			/*
1582			 * Now change each pointer to an fd in the global
1583			 * table to an integer that is the index to the local
1584			 * fd table entry that we set up to point to the
1585			 * global one we are transferring.
1586			 */
1587			newlen = newfds * sizeof(int);
1588			*controlp = sbcreatecontrol(NULL, newlen,
1589			    SCM_RIGHTS, SOL_SOCKET);
1590			if (*controlp == NULL) {
1591				FILEDESC_XUNLOCK(td->td_proc->p_fd);
1592				error = E2BIG;
1593				unp_freerights(rp, newfds);
1594				goto next;
1595			}
1596
1597			fdp = (int *)
1598			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1599			for (i = 0; i < newfds; i++) {
1600				if (fdalloc(td, 0, &f))
1601					panic("unp_externalize fdalloc failed");
1602				fp = *rp++;
1603				td->td_proc->p_fd->fd_ofiles[f] = fp;
1604				unp_externalize_fp(fp);
1605				*fdp++ = f;
1606			}
1607			FILEDESC_XUNLOCK(td->td_proc->p_fd);
1608		} else {
1609			/* We can just copy anything else across. */
1610			if (error || controlp == NULL)
1611				goto next;
1612			*controlp = sbcreatecontrol(NULL, datalen,
1613			    cm->cmsg_type, cm->cmsg_level);
1614			if (*controlp == NULL) {
1615				error = ENOBUFS;
1616				goto next;
1617			}
1618			bcopy(data,
1619			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1620			    datalen);
1621		}
1622
1623		controlp = &(*controlp)->m_next;
1624
1625next:
1626		if (CMSG_SPACE(datalen) < clen) {
1627			clen -= CMSG_SPACE(datalen);
1628			cm = (struct cmsghdr *)
1629			    ((caddr_t)cm + CMSG_SPACE(datalen));
1630		} else {
1631			clen = 0;
1632			cm = NULL;
1633		}
1634	}
1635
1636	m_freem(control);
1637
1638	return (error);
1639}
1640
1641static void
1642unp_zone_change(void *tag)
1643{
1644
1645	uma_zone_set_max(unp_zone, maxsockets);
1646}
1647
1648void
1649unp_init(void)
1650{
1651
1652	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1653	    NULL, NULL, UMA_ALIGN_PTR, 0);
1654	if (unp_zone == NULL)
1655		panic("unp_init");
1656	uma_zone_set_max(unp_zone, maxsockets);
1657	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1658	    NULL, EVENTHANDLER_PRI_ANY);
1659	LIST_INIT(&unp_dhead);
1660	LIST_INIT(&unp_shead);
1661	TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1662	UNP_GLOBAL_LOCK_INIT();
1663}
1664
1665static int
1666unp_internalize(struct mbuf **controlp, struct thread *td)
1667{
1668	struct mbuf *control = *controlp;
1669	struct proc *p = td->td_proc;
1670	struct filedesc *fdescp = p->p_fd;
1671	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1672	struct cmsgcred *cmcred;
1673	struct file **rp;
1674	struct file *fp;
1675	struct timeval *tv;
1676	int i, fd, *fdp;
1677	void *data;
1678	socklen_t clen = control->m_len, datalen;
1679	int error, oldfds;
1680	u_int newlen;
1681
1682	UNP_GLOBAL_UNLOCK_ASSERT();
1683
1684	error = 0;
1685	*controlp = NULL;
1686
1687	while (cm != NULL) {
1688		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1689		    || cm->cmsg_len > clen) {
1690			error = EINVAL;
1691			goto out;
1692		}
1693
1694		data = CMSG_DATA(cm);
1695		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1696
1697		switch (cm->cmsg_type) {
1698		/*
1699		 * Fill in credential information.
1700		 */
1701		case SCM_CREDS:
1702			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1703			    SCM_CREDS, SOL_SOCKET);
1704			if (*controlp == NULL) {
1705				error = ENOBUFS;
1706				goto out;
1707			}
1708
1709			cmcred = (struct cmsgcred *)
1710			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1711			cmcred->cmcred_pid = p->p_pid;
1712			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1713			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1714			cmcred->cmcred_euid = td->td_ucred->cr_uid;
1715			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1716							CMGROUP_MAX);
1717			for (i = 0; i < cmcred->cmcred_ngroups; i++)
1718				cmcred->cmcred_groups[i] =
1719				    td->td_ucred->cr_groups[i];
1720			break;
1721
1722		case SCM_RIGHTS:
1723			oldfds = datalen / sizeof (int);
1724			/*
1725			 * Check that all the FDs passed in refer to legal
1726			 * files.  If not, reject the entire operation.
1727			 */
1728			fdp = data;
1729			FILEDESC_SLOCK(fdescp);
1730			for (i = 0; i < oldfds; i++) {
1731				fd = *fdp++;
1732				if ((unsigned)fd >= fdescp->fd_nfiles ||
1733				    fdescp->fd_ofiles[fd] == NULL) {
1734					FILEDESC_SUNLOCK(fdescp);
1735					error = EBADF;
1736					goto out;
1737				}
1738				fp = fdescp->fd_ofiles[fd];
1739				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1740					FILEDESC_SUNLOCK(fdescp);
1741					error = EOPNOTSUPP;
1742					goto out;
1743				}
1744
1745			}
1746
1747			/*
1748			 * Now replace the integer FDs with pointers to
1749			 * the associated global file table entry..
1750			 */
1751			newlen = oldfds * sizeof(struct file *);
1752			*controlp = sbcreatecontrol(NULL, newlen,
1753			    SCM_RIGHTS, SOL_SOCKET);
1754			if (*controlp == NULL) {
1755				FILEDESC_SUNLOCK(fdescp);
1756				error = E2BIG;
1757				goto out;
1758			}
1759
1760			fdp = data;
1761			rp = (struct file **)
1762			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1763			for (i = 0; i < oldfds; i++) {
1764				fp = fdescp->fd_ofiles[*fdp++];
1765				*rp++ = fp;
1766				fhold(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	unp_rights++;
1891	UNP_GLOBAL_WUNLOCK();
1892}
1893
1894static void
1895unp_externalize_fp(struct file *fp)
1896{
1897	struct unpcb *unp;
1898
1899	UNP_GLOBAL_WLOCK();
1900	if ((unp = fptounp(fp)) != NULL)
1901		unp->unp_msgcount--;
1902	unp_rights--;
1903	UNP_GLOBAL_WUNLOCK();
1904}
1905
1906/*
1907 * unp_defer indicates whether additional work has been defered for a future
1908 * pass through unp_gc().  It is thread local and does not require explicit
1909 * synchronization.
1910 */
1911static int	unp_marked;
1912static int	unp_unreachable;
1913
1914static void
1915unp_accessable(struct file *fp)
1916{
1917	struct unpcb *unp;
1918
1919	unp = fptounp(fp);
1920	if (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_msgcount != 0 && fp->f_count != 0 &&
1946	    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 &= ~(UNPGC_REF|UNPGC_DEAD);
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				KASSERT(unp->unp_file != NULL,
2025				    ("unp_gc: Invalid unpcb."));
2026				KASSERT(i <= unp_unreachable,
2027				    ("unp_gc: incorrect unreachable count."));
2028			}
2029	UNP_GLOBAL_RUNLOCK();
2030	/*
2031	 * All further operation is now done on a local list.  We first ref
2032	 * all sockets to avoid closing them until all are flushed.
2033	 */
2034	for (i = 0; i < unp_unreachable; i++)
2035		fhold(unref[i]);
2036	/*
2037	 * Now flush all sockets, free'ing rights.  This will free the
2038	 * struct files associated with these sockets but leave each socket
2039	 * with one remaining ref.
2040	 */
2041	for (i = 0; i < unp_unreachable; i++)
2042		sorflush(unref[i]->f_data);
2043	/*
2044	 * And finally release the sockets so they can be reclaimed.
2045	 */
2046	for (i = 0; i < unp_unreachable; i++)
2047		fdrop(unref[i], NULL);
2048	unp_recycled += unp_unreachable;
2049	free(unref, M_TEMP);
2050}
2051
2052void
2053unp_dispose(struct mbuf *m)
2054{
2055
2056	if (m)
2057		unp_scan(m, unp_discard);
2058}
2059
2060static void
2061unp_scan(struct mbuf *m0, void (*op)(struct file *))
2062{
2063	struct mbuf *m;
2064	struct file **rp;
2065	struct cmsghdr *cm;
2066	void *data;
2067	int i;
2068	socklen_t clen, datalen;
2069	int qfds;
2070
2071	while (m0 != NULL) {
2072		for (m = m0; m; m = m->m_next) {
2073			if (m->m_type != MT_CONTROL)
2074				continue;
2075
2076			cm = mtod(m, struct cmsghdr *);
2077			clen = m->m_len;
2078
2079			while (cm != NULL) {
2080				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2081					break;
2082
2083				data = CMSG_DATA(cm);
2084				datalen = (caddr_t)cm + cm->cmsg_len
2085				    - (caddr_t)data;
2086
2087				if (cm->cmsg_level == SOL_SOCKET &&
2088				    cm->cmsg_type == SCM_RIGHTS) {
2089					qfds = datalen / sizeof (struct file *);
2090					rp = data;
2091					for (i = 0; i < qfds; i++)
2092						(*op)(*rp++);
2093				}
2094
2095				if (CMSG_SPACE(datalen) < clen) {
2096					clen -= CMSG_SPACE(datalen);
2097					cm = (struct cmsghdr *)
2098					    ((caddr_t)cm + CMSG_SPACE(datalen));
2099				} else {
2100					clen = 0;
2101					cm = NULL;
2102				}
2103			}
2104		}
2105		m0 = m0->m_act;
2106	}
2107}
2108
2109#ifdef DDB
2110static void
2111db_print_indent(int indent)
2112{
2113	int i;
2114
2115	for (i = 0; i < indent; i++)
2116		db_printf(" ");
2117}
2118
2119static void
2120db_print_unpflags(int unp_flags)
2121{
2122	int comma;
2123
2124	comma = 0;
2125	if (unp_flags & UNP_HAVEPC) {
2126		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2127		comma = 1;
2128	}
2129	if (unp_flags & UNP_HAVEPCCACHED) {
2130		db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2131		comma = 1;
2132	}
2133	if (unp_flags & UNP_WANTCRED) {
2134		db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2135		comma = 1;
2136	}
2137	if (unp_flags & UNP_CONNWAIT) {
2138		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2139		comma = 1;
2140	}
2141	if (unp_flags & UNP_CONNECTING) {
2142		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2143		comma = 1;
2144	}
2145	if (unp_flags & UNP_BINDING) {
2146		db_printf("%sUNP_BINDING", comma ? ", " : "");
2147		comma = 1;
2148	}
2149}
2150
2151static void
2152db_print_xucred(int indent, struct xucred *xu)
2153{
2154	int comma, i;
2155
2156	db_print_indent(indent);
2157	db_printf("cr_version: %u   cr_uid: %u   cr_ngroups: %d\n",
2158	    xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2159	db_print_indent(indent);
2160	db_printf("cr_groups: ");
2161	comma = 0;
2162	for (i = 0; i < xu->cr_ngroups; i++) {
2163		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2164		comma = 1;
2165	}
2166	db_printf("\n");
2167}
2168
2169static void
2170db_print_unprefs(int indent, struct unp_head *uh)
2171{
2172	struct unpcb *unp;
2173	int counter;
2174
2175	counter = 0;
2176	LIST_FOREACH(unp, uh, unp_reflink) {
2177		if (counter % 4 == 0)
2178			db_print_indent(indent);
2179		db_printf("%p  ", unp);
2180		if (counter % 4 == 3)
2181			db_printf("\n");
2182		counter++;
2183	}
2184	if (counter != 0 && counter % 4 != 0)
2185		db_printf("\n");
2186}
2187
2188DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2189{
2190	struct unpcb *unp;
2191
2192        if (!have_addr) {
2193                db_printf("usage: show unpcb <addr>\n");
2194                return;
2195        }
2196        unp = (struct unpcb *)addr;
2197
2198	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
2199	    unp->unp_vnode);
2200
2201	db_printf("unp_ino: %d   unp_conn: %p\n", unp->unp_ino,
2202	    unp->unp_conn);
2203
2204	db_printf("unp_refs:\n");
2205	db_print_unprefs(2, &unp->unp_refs);
2206
2207	/* XXXRW: Would be nice to print the full address, if any. */
2208	db_printf("unp_addr: %p\n", unp->unp_addr);
2209
2210	db_printf("unp_cc: %d   unp_mbcnt: %d   unp_gencnt: %llu\n",
2211	    unp->unp_cc, unp->unp_mbcnt,
2212	    (unsigned long long)unp->unp_gencnt);
2213
2214	db_printf("unp_flags: %x (", unp->unp_flags);
2215	db_print_unpflags(unp->unp_flags);
2216	db_printf(")\n");
2217
2218	db_printf("unp_peercred:\n");
2219	db_print_xucred(2, &unp->unp_peercred);
2220
2221	db_printf("unp_refcount: %u\n", unp->unp_refcount);
2222}
2223#endif
2224