uipc_usrreq.c revision 183650
1/*-
2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 *	The Regents of the University of California.
4 * Copyright (c) 2004-2008 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 183650 2008-10-06 18:43:11Z rwatson $");
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, "Default stream send space.");
143SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
144	   &unpst_recvspace, 0, "Default stream receive space.");
145SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
146	   &unpdg_sendspace, 0, "Default datagram send space.");
147SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
148	   &unpdg_recvspace, 0, "Default datagram receive space.");
149SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
150    "File descriptors in flight.");
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	uipc_connect2(struct socket *, struct socket *);
229static int	uipc_ctloutput(struct socket *, struct sockopt *);
230static int	unp_connect(struct socket *, struct sockaddr *,
231		    struct thread *);
232static int	unp_connect2(struct socket *so, struct socket *so2, int);
233static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
234static void	unp_dispose(struct mbuf *);
235static void	unp_shutdown(struct unpcb *);
236static void	unp_drop(struct unpcb *, int);
237static void	unp_gc(__unused void *, int);
238static void	unp_scan(struct mbuf *, void (*)(struct file *));
239static void	unp_discard(struct file *);
240static void	unp_freerights(struct file **, int);
241static void	unp_init(void);
242static int	unp_internalize(struct mbuf **, struct thread *);
243static void	unp_internalize_fp(struct file *);
244static int	unp_externalize(struct mbuf *, struct mbuf **);
245static void	unp_externalize_fp(struct file *);
246static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *);
247
248/*
249 * Definitions of protocols supported in the LOCAL domain.
250 */
251static struct domain localdomain;
252static struct pr_usrreqs uipc_usrreqs;
253static struct protosw localsw[] = {
254{
255	.pr_type =		SOCK_STREAM,
256	.pr_domain =		&localdomain,
257	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
258	.pr_ctloutput =		&uipc_ctloutput,
259	.pr_usrreqs =		&uipc_usrreqs
260},
261{
262	.pr_type =		SOCK_DGRAM,
263	.pr_domain =		&localdomain,
264	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS,
265	.pr_usrreqs =		&uipc_usrreqs
266},
267};
268
269static struct domain localdomain = {
270	.dom_family =		AF_LOCAL,
271	.dom_name =		"local",
272	.dom_init =		unp_init,
273	.dom_externalize =	unp_externalize,
274	.dom_dispose =		unp_dispose,
275	.dom_protosw =		localsw,
276	.dom_protoswNPROTOSW =	&localsw[sizeof(localsw)/sizeof(localsw[0])]
277};
278DOMAIN_SET(local);
279
280static void
281uipc_abort(struct socket *so)
282{
283	struct unpcb *unp, *unp2;
284
285	unp = sotounpcb(so);
286	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
287
288	UNP_GLOBAL_WLOCK();
289	UNP_PCB_LOCK(unp);
290	unp2 = unp->unp_conn;
291	if (unp2 != NULL) {
292		UNP_PCB_LOCK(unp2);
293		unp_drop(unp2, ECONNABORTED);
294		UNP_PCB_UNLOCK(unp2);
295	}
296	UNP_PCB_UNLOCK(unp);
297	UNP_GLOBAL_WUNLOCK();
298}
299
300static int
301uipc_accept(struct socket *so, struct sockaddr **nam)
302{
303	struct unpcb *unp, *unp2;
304	const struct sockaddr *sa;
305
306	/*
307	 * Pass back name of connected socket, if it was bound and we are
308	 * still connected (our peer may have closed already!).
309	 */
310	unp = sotounpcb(so);
311	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
312
313	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
314	UNP_GLOBAL_RLOCK();
315	unp2 = unp->unp_conn;
316	if (unp2 != NULL && unp2->unp_addr != NULL) {
317		UNP_PCB_LOCK(unp2);
318		sa = (struct sockaddr *) unp2->unp_addr;
319		bcopy(sa, *nam, sa->sa_len);
320		UNP_PCB_UNLOCK(unp2);
321	} else {
322		sa = &sun_noname;
323		bcopy(sa, *nam, sa->sa_len);
324	}
325	UNP_GLOBAL_RUNLOCK();
326	return (0);
327}
328
329static int
330uipc_attach(struct socket *so, int proto, struct thread *td)
331{
332	u_long sendspace, recvspace;
333	struct unpcb *unp;
334	int error, locked;
335
336	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
337	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
338		switch (so->so_type) {
339		case SOCK_STREAM:
340			sendspace = unpst_sendspace;
341			recvspace = unpst_recvspace;
342			break;
343
344		case SOCK_DGRAM:
345			sendspace = unpdg_sendspace;
346			recvspace = unpdg_recvspace;
347			break;
348
349		default:
350			panic("uipc_attach");
351		}
352		error = soreserve(so, sendspace, recvspace);
353		if (error)
354			return (error);
355	}
356	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
357	if (unp == NULL)
358		return (ENOBUFS);
359	LIST_INIT(&unp->unp_refs);
360	UNP_PCB_LOCK_INIT(unp);
361	unp->unp_socket = so;
362	so->so_pcb = unp;
363	unp->unp_refcount = 1;
364
365	/*
366	 * uipc_attach() may be called indirectly from within the UNIX domain
367	 * socket code via sonewconn() in unp_connect().  Since rwlocks can
368	 * not be recursed, we do the closest thing.
369	 */
370	locked = 0;
371	if (!UNP_GLOBAL_WOWNED()) {
372		UNP_GLOBAL_WLOCK();
373		locked = 1;
374	}
375	unp->unp_gencnt = ++unp_gencnt;
376	unp_count++;
377	LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead : &unp_shead,
378	    unp, unp_link);
379	if (locked)
380		UNP_GLOBAL_WUNLOCK();
381
382	return (0);
383}
384
385static int
386uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
387{
388	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
389	struct vattr vattr;
390	int error, namelen, vfslocked;
391	struct nameidata nd;
392	struct unpcb *unp;
393	struct vnode *vp;
394	struct mount *mp;
395	char *buf;
396
397	unp = sotounpcb(so);
398	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
399
400	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
401	if (namelen <= 0)
402		return (EINVAL);
403
404	/*
405	 * We don't allow simultaneous bind() calls on a single UNIX domain
406	 * socket, so flag in-progress operations, and return an error if an
407	 * operation is already in progress.
408	 *
409	 * Historically, we have not allowed a socket to be rebound, so this
410	 * also returns an error.  Not allowing re-binding simplifies the
411	 * implementation and avoids a great many possible failure modes.
412	 */
413	UNP_PCB_LOCK(unp);
414	if (unp->unp_vnode != NULL) {
415		UNP_PCB_UNLOCK(unp);
416		return (EINVAL);
417	}
418	if (unp->unp_flags & UNP_BINDING) {
419		UNP_PCB_UNLOCK(unp);
420		return (EALREADY);
421	}
422	unp->unp_flags |= UNP_BINDING;
423	UNP_PCB_UNLOCK(unp);
424
425	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
426	bcopy(soun->sun_path, buf, namelen);
427	buf[namelen] = 0;
428
429restart:
430	vfslocked = 0;
431	NDINIT(&nd, CREATE, MPSAFE | NOFOLLOW | LOCKPARENT | SAVENAME,
432	    UIO_SYSSPACE, buf, td);
433/* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
434	error = namei(&nd);
435	if (error)
436		goto error;
437	vp = nd.ni_vp;
438	vfslocked = NDHASGIANT(&nd);
439	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
440		NDFREE(&nd, NDF_ONLY_PNBUF);
441		if (nd.ni_dvp == vp)
442			vrele(nd.ni_dvp);
443		else
444			vput(nd.ni_dvp);
445		if (vp != NULL) {
446			vrele(vp);
447			error = EADDRINUSE;
448			goto error;
449		}
450		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
451		if (error)
452			goto error;
453		VFS_UNLOCK_GIANT(vfslocked);
454		goto restart;
455	}
456	VATTR_NULL(&vattr);
457	vattr.va_type = VSOCK;
458	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
459#ifdef MAC
460	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
461	    &vattr);
462#endif
463	if (error == 0) {
464		VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
465		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
466	}
467	NDFREE(&nd, NDF_ONLY_PNBUF);
468	vput(nd.ni_dvp);
469	if (error) {
470		vn_finished_write(mp);
471		goto error;
472	}
473	vp = nd.ni_vp;
474	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
475	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
476
477	UNP_GLOBAL_WLOCK();
478	UNP_PCB_LOCK(unp);
479	vp->v_socket = unp->unp_socket;
480	unp->unp_vnode = vp;
481	unp->unp_addr = soun;
482	unp->unp_flags &= ~UNP_BINDING;
483	UNP_PCB_UNLOCK(unp);
484	UNP_GLOBAL_WUNLOCK();
485	VOP_UNLOCK(vp, 0);
486	vn_finished_write(mp);
487	VFS_UNLOCK_GIANT(vfslocked);
488	free(buf, M_TEMP);
489	return (0);
490
491error:
492	VFS_UNLOCK_GIANT(vfslocked);
493	UNP_PCB_LOCK(unp);
494	unp->unp_flags &= ~UNP_BINDING;
495	UNP_PCB_UNLOCK(unp);
496	free(buf, M_TEMP);
497	return (error);
498}
499
500static int
501uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
502{
503	int error;
504
505	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
506	UNP_GLOBAL_WLOCK();
507	error = unp_connect(so, nam, td);
508	UNP_GLOBAL_WUNLOCK();
509	return (error);
510}
511
512static void
513uipc_close(struct socket *so)
514{
515	struct unpcb *unp, *unp2;
516
517	unp = sotounpcb(so);
518	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
519
520	UNP_GLOBAL_WLOCK();
521	UNP_PCB_LOCK(unp);
522	unp2 = unp->unp_conn;
523	if (unp2 != NULL) {
524		UNP_PCB_LOCK(unp2);
525		unp_disconnect(unp, unp2);
526		UNP_PCB_UNLOCK(unp2);
527	}
528	UNP_PCB_UNLOCK(unp);
529	UNP_GLOBAL_WUNLOCK();
530}
531
532/*
533 * uipc_connect2() is not static as it is invoked directly by fifofs.
534 */
535static int
536uipc_connect2(struct socket *so1, struct socket *so2)
537{
538	struct unpcb *unp, *unp2;
539	int error;
540
541	UNP_GLOBAL_WLOCK();
542	unp = so1->so_pcb;
543	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
544	UNP_PCB_LOCK(unp);
545	unp2 = so2->so_pcb;
546	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
547	UNP_PCB_LOCK(unp2);
548	error = unp_connect2(so1, so2, PRU_CONNECT2);
549	UNP_PCB_UNLOCK(unp2);
550	UNP_PCB_UNLOCK(unp);
551	UNP_GLOBAL_WUNLOCK();
552	return (error);
553}
554
555static void
556uipc_detach(struct socket *so)
557{
558	struct unpcb *unp, *unp2;
559	struct sockaddr_un *saved_unp_addr;
560	struct vnode *vp;
561	int freeunp, local_unp_rights;
562
563	unp = sotounpcb(so);
564	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
565
566	UNP_GLOBAL_WLOCK();
567	UNP_PCB_LOCK(unp);
568
569	LIST_REMOVE(unp, unp_link);
570	unp->unp_gencnt = ++unp_gencnt;
571	--unp_count;
572
573	/*
574	 * XXXRW: Should assert vp->v_socket == so.
575	 */
576	if ((vp = unp->unp_vnode) != NULL) {
577		unp->unp_vnode->v_socket = NULL;
578		unp->unp_vnode = NULL;
579	}
580	unp2 = unp->unp_conn;
581	if (unp2 != NULL) {
582		UNP_PCB_LOCK(unp2);
583		unp_disconnect(unp, unp2);
584		UNP_PCB_UNLOCK(unp2);
585	}
586
587	/*
588	 * We hold the global lock exclusively, so it's OK to acquire
589	 * multiple pcb locks at a time.
590	 */
591	while (!LIST_EMPTY(&unp->unp_refs)) {
592		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
593
594		UNP_PCB_LOCK(ref);
595		unp_drop(ref, ECONNRESET);
596		UNP_PCB_UNLOCK(ref);
597	}
598	local_unp_rights = unp_rights;
599	UNP_GLOBAL_WUNLOCK();
600	unp->unp_socket->so_pcb = NULL;
601	saved_unp_addr = unp->unp_addr;
602	unp->unp_addr = NULL;
603	unp->unp_refcount--;
604	freeunp = (unp->unp_refcount == 0);
605	if (saved_unp_addr != NULL)
606		FREE(saved_unp_addr, M_SONAME);
607	if (freeunp) {
608		UNP_PCB_LOCK_DESTROY(unp);
609		uma_zfree(unp_zone, unp);
610	} else
611		UNP_PCB_UNLOCK(unp);
612	if (vp) {
613		int vfslocked;
614
615		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
616		vrele(vp);
617		VFS_UNLOCK_GIANT(vfslocked);
618	}
619	if (local_unp_rights)
620		taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
621}
622
623static int
624uipc_disconnect(struct socket *so)
625{
626	struct unpcb *unp, *unp2;
627
628	unp = sotounpcb(so);
629	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
630
631	UNP_GLOBAL_WLOCK();
632	UNP_PCB_LOCK(unp);
633	unp2 = unp->unp_conn;
634	if (unp2 != NULL) {
635		UNP_PCB_LOCK(unp2);
636		unp_disconnect(unp, unp2);
637		UNP_PCB_UNLOCK(unp2);
638	}
639	UNP_PCB_UNLOCK(unp);
640	UNP_GLOBAL_WUNLOCK();
641	return (0);
642}
643
644static int
645uipc_listen(struct socket *so, int backlog, struct thread *td)
646{
647	struct unpcb *unp;
648	int error;
649
650	unp = sotounpcb(so);
651	KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
652
653	UNP_PCB_LOCK(unp);
654	if (unp->unp_vnode == NULL) {
655		UNP_PCB_UNLOCK(unp);
656		return (EINVAL);
657	}
658
659	SOCK_LOCK(so);
660	error = solisten_proto_check(so);
661	if (error == 0) {
662		cru2x(td->td_ucred, &unp->unp_peercred);
663		unp->unp_flags |= UNP_HAVEPCCACHED;
664		solisten_proto(so, backlog);
665	}
666	SOCK_UNLOCK(so);
667	UNP_PCB_UNLOCK(unp);
668	return (error);
669}
670
671static int
672uipc_peeraddr(struct socket *so, struct sockaddr **nam)
673{
674	struct unpcb *unp, *unp2;
675	const struct sockaddr *sa;
676
677	unp = sotounpcb(so);
678	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
679
680	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
681	UNP_PCB_LOCK(unp);
682	/*
683	 * XXX: It seems that this test always fails even when connection is
684	 * established.  So, this else clause is added as workaround to
685	 * return PF_LOCAL sockaddr.
686	 */
687	unp2 = unp->unp_conn;
688	if (unp2 != NULL) {
689		UNP_PCB_LOCK(unp2);
690		if (unp2->unp_addr != NULL)
691			sa = (struct sockaddr *) unp->unp_conn->unp_addr;
692		else
693			sa = &sun_noname;
694		bcopy(sa, *nam, sa->sa_len);
695		UNP_PCB_UNLOCK(unp2);
696	} else {
697		sa = &sun_noname;
698		bcopy(sa, *nam, sa->sa_len);
699	}
700	UNP_PCB_UNLOCK(unp);
701	return (0);
702}
703
704static int
705uipc_rcvd(struct socket *so, int flags)
706{
707	struct unpcb *unp, *unp2;
708	struct socket *so2;
709	u_int mbcnt, sbcc;
710	u_long newhiwat;
711
712	unp = sotounpcb(so);
713	KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
714
715	if (so->so_type == SOCK_DGRAM)
716		panic("uipc_rcvd DGRAM?");
717
718	if (so->so_type != SOCK_STREAM)
719		panic("uipc_rcvd unknown socktype");
720
721	/*
722	 * Adjust backpressure on sender and wakeup any waiting to write.
723	 *
724	 * The unp lock is acquired to maintain the validity of the unp_conn
725	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
726	 * static as long as we don't permit unp2 to disconnect from unp,
727	 * which is prevented by the lock on unp.  We cache values from
728	 * so_rcv to avoid holding the so_rcv lock over the entire
729	 * transaction on the remote so_snd.
730	 */
731	SOCKBUF_LOCK(&so->so_rcv);
732	mbcnt = so->so_rcv.sb_mbcnt;
733	sbcc = so->so_rcv.sb_cc;
734	SOCKBUF_UNLOCK(&so->so_rcv);
735	UNP_PCB_LOCK(unp);
736	unp2 = unp->unp_conn;
737	if (unp2 == NULL) {
738		UNP_PCB_UNLOCK(unp);
739		return (0);
740	}
741	so2 = unp2->unp_socket;
742	SOCKBUF_LOCK(&so2->so_snd);
743	so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
744	newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
745	(void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
746	    newhiwat, RLIM_INFINITY);
747	sowwakeup_locked(so2);
748	unp->unp_mbcnt = mbcnt;
749	unp->unp_cc = sbcc;
750	UNP_PCB_UNLOCK(unp);
751	return (0);
752}
753
754static int
755uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
756    struct mbuf *control, struct thread *td)
757{
758	struct unpcb *unp, *unp2;
759	struct socket *so2;
760	u_int mbcnt, sbcc;
761	u_long newhiwat;
762	int error = 0;
763
764	unp = sotounpcb(so);
765	KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
766
767	if (flags & PRUS_OOB) {
768		error = EOPNOTSUPP;
769		goto release;
770	}
771	if (control != NULL && (error = unp_internalize(&control, td)))
772		goto release;
773	if ((nam != NULL) || (flags & PRUS_EOF))
774		UNP_GLOBAL_WLOCK();
775	else
776		UNP_GLOBAL_RLOCK();
777	switch (so->so_type) {
778	case SOCK_DGRAM:
779	{
780		const struct sockaddr *from;
781
782		unp2 = unp->unp_conn;
783		if (nam != NULL) {
784			UNP_GLOBAL_WLOCK_ASSERT();
785			if (unp2 != NULL) {
786				error = EISCONN;
787				break;
788			}
789			error = unp_connect(so, nam, td);
790			if (error)
791				break;
792			unp2 = unp->unp_conn;
793		}
794
795		/*
796		 * Because connect() and send() are non-atomic in a sendto()
797		 * with a target address, it's possible that the socket will
798		 * have disconnected before the send() can run.  In that case
799		 * return the slightly counter-intuitive but otherwise
800		 * correct error that the socket is not connected.
801		 */
802		if (unp2 == NULL) {
803			error = ENOTCONN;
804			break;
805		}
806		/* Lockless read. */
807		if (unp2->unp_flags & UNP_WANTCRED)
808			control = unp_addsockcred(td, control);
809		UNP_PCB_LOCK(unp);
810		if (unp->unp_addr != NULL)
811			from = (struct sockaddr *)unp->unp_addr;
812		else
813			from = &sun_noname;
814		so2 = unp2->unp_socket;
815		SOCKBUF_LOCK(&so2->so_rcv);
816		if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
817			sorwakeup_locked(so2);
818			m = NULL;
819			control = NULL;
820		} else {
821			SOCKBUF_UNLOCK(&so2->so_rcv);
822			error = ENOBUFS;
823		}
824		if (nam != NULL) {
825			UNP_GLOBAL_WLOCK_ASSERT();
826			UNP_PCB_LOCK(unp2);
827			unp_disconnect(unp, unp2);
828			UNP_PCB_UNLOCK(unp2);
829		}
830		UNP_PCB_UNLOCK(unp);
831		break;
832	}
833
834	case SOCK_STREAM:
835		if ((so->so_state & SS_ISCONNECTED) == 0) {
836			if (nam != NULL) {
837				UNP_GLOBAL_WLOCK_ASSERT();
838				error = unp_connect(so, nam, td);
839				if (error)
840					break;	/* XXX */
841			} else {
842				error = ENOTCONN;
843				break;
844			}
845		}
846
847		/* Lockless read. */
848		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
849			error = EPIPE;
850			break;
851		}
852
853		/*
854		 * Because connect() and send() are non-atomic in a sendto()
855		 * with a target address, it's possible that the socket will
856		 * have disconnected before the send() can run.  In that case
857		 * return the slightly counter-intuitive but otherwise
858		 * correct error that the socket is not connected.
859		 *
860		 * Locking here must be done carefully: the global lock
861		 * prevents interconnections between unpcbs from changing, so
862		 * we can traverse from unp to unp2 without acquiring unp's
863		 * lock.  Socket buffer locks follow unpcb locks, so we can
864		 * acquire both remote and lock socket buffer locks.
865		 */
866		unp2 = unp->unp_conn;
867		if (unp2 == NULL) {
868			error = ENOTCONN;
869			break;
870		}
871		so2 = unp2->unp_socket;
872		UNP_PCB_LOCK(unp2);
873		SOCKBUF_LOCK(&so2->so_rcv);
874		if (unp2->unp_flags & UNP_WANTCRED) {
875			/*
876			 * Credentials are passed only once on SOCK_STREAM.
877			 */
878			unp2->unp_flags &= ~UNP_WANTCRED;
879			control = unp_addsockcred(td, control);
880		}
881		/*
882		 * Send to paired receive port, and then reduce send buffer
883		 * hiwater marks to maintain backpressure.  Wake up readers.
884		 */
885		if (control != NULL) {
886			if (sbappendcontrol_locked(&so2->so_rcv, m, control))
887				control = NULL;
888		} else
889			sbappend_locked(&so2->so_rcv, m);
890		mbcnt = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
891		unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
892		sbcc = so2->so_rcv.sb_cc;
893		sorwakeup_locked(so2);
894
895		SOCKBUF_LOCK(&so->so_snd);
896		newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
897		(void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
898		    newhiwat, RLIM_INFINITY);
899		so->so_snd.sb_mbmax -= mbcnt;
900		SOCKBUF_UNLOCK(&so->so_snd);
901		unp2->unp_cc = sbcc;
902		UNP_PCB_UNLOCK(unp2);
903		m = NULL;
904		break;
905
906	default:
907		panic("uipc_send unknown socktype");
908	}
909
910	/*
911	 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
912	 */
913	if (flags & PRUS_EOF) {
914		UNP_PCB_LOCK(unp);
915		socantsendmore(so);
916		unp_shutdown(unp);
917		UNP_PCB_UNLOCK(unp);
918	}
919
920	if ((nam != NULL) || (flags & PRUS_EOF))
921		UNP_GLOBAL_WUNLOCK();
922	else
923		UNP_GLOBAL_RUNLOCK();
924
925	if (control != NULL && error != 0)
926		unp_dispose(control);
927
928release:
929	if (control != NULL)
930		m_freem(control);
931	if (m != NULL)
932		m_freem(m);
933	return (error);
934}
935
936static int
937uipc_sense(struct socket *so, struct stat *sb)
938{
939	struct unpcb *unp, *unp2;
940	struct socket *so2;
941
942	unp = sotounpcb(so);
943	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
944
945	sb->st_blksize = so->so_snd.sb_hiwat;
946	UNP_GLOBAL_RLOCK();
947	UNP_PCB_LOCK(unp);
948	unp2 = unp->unp_conn;
949	if (so->so_type == SOCK_STREAM && unp2 != NULL) {
950		so2 = unp2->unp_socket;
951		sb->st_blksize += so2->so_rcv.sb_cc;
952	}
953	sb->st_dev = NODEV;
954	if (unp->unp_ino == 0)
955		unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
956	sb->st_ino = unp->unp_ino;
957	UNP_PCB_UNLOCK(unp);
958	UNP_GLOBAL_RUNLOCK();
959	return (0);
960}
961
962static int
963uipc_shutdown(struct socket *so)
964{
965	struct unpcb *unp;
966
967	unp = sotounpcb(so);
968	KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
969
970	UNP_GLOBAL_WLOCK();
971	UNP_PCB_LOCK(unp);
972	socantsendmore(so);
973	unp_shutdown(unp);
974	UNP_PCB_UNLOCK(unp);
975	UNP_GLOBAL_WUNLOCK();
976	return (0);
977}
978
979static int
980uipc_sockaddr(struct socket *so, struct sockaddr **nam)
981{
982	struct unpcb *unp;
983	const struct sockaddr *sa;
984
985	unp = sotounpcb(so);
986	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
987
988	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
989	UNP_PCB_LOCK(unp);
990	if (unp->unp_addr != NULL)
991		sa = (struct sockaddr *) unp->unp_addr;
992	else
993		sa = &sun_noname;
994	bcopy(sa, *nam, sa->sa_len);
995	UNP_PCB_UNLOCK(unp);
996	return (0);
997}
998
999static struct pr_usrreqs uipc_usrreqs = {
1000	.pru_abort = 		uipc_abort,
1001	.pru_accept =		uipc_accept,
1002	.pru_attach =		uipc_attach,
1003	.pru_bind =		uipc_bind,
1004	.pru_connect =		uipc_connect,
1005	.pru_connect2 =		uipc_connect2,
1006	.pru_detach =		uipc_detach,
1007	.pru_disconnect =	uipc_disconnect,
1008	.pru_listen =		uipc_listen,
1009	.pru_peeraddr =		uipc_peeraddr,
1010	.pru_rcvd =		uipc_rcvd,
1011	.pru_send =		uipc_send,
1012	.pru_sense =		uipc_sense,
1013	.pru_shutdown =		uipc_shutdown,
1014	.pru_sockaddr =		uipc_sockaddr,
1015	.pru_close =		uipc_close,
1016};
1017
1018static int
1019uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1020{
1021	struct unpcb *unp;
1022	struct xucred xu;
1023	int error, optval;
1024
1025	if (sopt->sopt_level != 0)
1026		return (EINVAL);
1027
1028	unp = sotounpcb(so);
1029	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1030	error = 0;
1031	switch (sopt->sopt_dir) {
1032	case SOPT_GET:
1033		switch (sopt->sopt_name) {
1034		case LOCAL_PEERCRED:
1035			UNP_PCB_LOCK(unp);
1036			if (unp->unp_flags & UNP_HAVEPC)
1037				xu = unp->unp_peercred;
1038			else {
1039				if (so->so_type == SOCK_STREAM)
1040					error = ENOTCONN;
1041				else
1042					error = EINVAL;
1043			}
1044			UNP_PCB_UNLOCK(unp);
1045			if (error == 0)
1046				error = sooptcopyout(sopt, &xu, sizeof(xu));
1047			break;
1048
1049		case LOCAL_CREDS:
1050			/* Unlocked read. */
1051			optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1052			error = sooptcopyout(sopt, &optval, sizeof(optval));
1053			break;
1054
1055		case LOCAL_CONNWAIT:
1056			/* Unlocked read. */
1057			optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1058			error = sooptcopyout(sopt, &optval, sizeof(optval));
1059			break;
1060
1061		default:
1062			error = EOPNOTSUPP;
1063			break;
1064		}
1065		break;
1066
1067	case SOPT_SET:
1068		switch (sopt->sopt_name) {
1069		case LOCAL_CREDS:
1070		case LOCAL_CONNWAIT:
1071			error = sooptcopyin(sopt, &optval, sizeof(optval),
1072					    sizeof(optval));
1073			if (error)
1074				break;
1075
1076#define	OPTSET(bit) do {						\
1077	UNP_PCB_LOCK(unp);						\
1078	if (optval)							\
1079		unp->unp_flags |= bit;					\
1080	else								\
1081		unp->unp_flags &= ~bit;					\
1082	UNP_PCB_UNLOCK(unp);						\
1083} while (0)
1084
1085			switch (sopt->sopt_name) {
1086			case LOCAL_CREDS:
1087				OPTSET(UNP_WANTCRED);
1088				break;
1089
1090			case LOCAL_CONNWAIT:
1091				OPTSET(UNP_CONNWAIT);
1092				break;
1093
1094			default:
1095				break;
1096			}
1097			break;
1098#undef	OPTSET
1099		default:
1100			error = ENOPROTOOPT;
1101			break;
1102		}
1103		break;
1104
1105	default:
1106		error = EOPNOTSUPP;
1107		break;
1108	}
1109	return (error);
1110}
1111
1112static int
1113unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1114{
1115	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1116	struct vnode *vp;
1117	struct socket *so2, *so3;
1118	struct unpcb *unp, *unp2, *unp3;
1119	int error, len, vfslocked;
1120	struct nameidata nd;
1121	char buf[SOCK_MAXADDRLEN];
1122	struct sockaddr *sa;
1123
1124	UNP_GLOBAL_WLOCK_ASSERT();
1125
1126	unp = sotounpcb(so);
1127	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1128
1129	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1130	if (len <= 0)
1131		return (EINVAL);
1132	bcopy(soun->sun_path, buf, len);
1133	buf[len] = 0;
1134
1135	UNP_PCB_LOCK(unp);
1136	if (unp->unp_flags & UNP_CONNECTING) {
1137		UNP_PCB_UNLOCK(unp);
1138		return (EALREADY);
1139	}
1140	UNP_GLOBAL_WUNLOCK();
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	UNP_PCB_LOCK(unp2);
1509	unp_disconnect(unp, unp2);
1510	UNP_PCB_UNLOCK(unp2);
1511}
1512
1513static void
1514unp_freerights(struct file **rp, int fdcount)
1515{
1516	int i;
1517	struct file *fp;
1518
1519	for (i = 0; i < fdcount; i++) {
1520		/*
1521		 * Zero the pointer before calling unp_discard since it may
1522		 * end up in unp_gc()..
1523		 *
1524		 * XXXRW: This is less true than it used to be.
1525		 */
1526		fp = *rp;
1527		*rp++ = NULL;
1528		unp_discard(fp);
1529	}
1530}
1531
1532static int
1533unp_externalize(struct mbuf *control, struct mbuf **controlp)
1534{
1535	struct thread *td = curthread;		/* XXX */
1536	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1537	int i;
1538	int *fdp;
1539	struct file **rp;
1540	struct file *fp;
1541	void *data;
1542	socklen_t clen = control->m_len, datalen;
1543	int error, newfds;
1544	int f;
1545	u_int newlen;
1546
1547	UNP_GLOBAL_UNLOCK_ASSERT();
1548
1549	error = 0;
1550	if (controlp != NULL) /* controlp == NULL => free control messages */
1551		*controlp = NULL;
1552	while (cm != NULL) {
1553		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1554			error = EINVAL;
1555			break;
1556		}
1557		data = CMSG_DATA(cm);
1558		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1559		if (cm->cmsg_level == SOL_SOCKET
1560		    && cm->cmsg_type == SCM_RIGHTS) {
1561			newfds = datalen / sizeof(struct file *);
1562			rp = data;
1563
1564			/* If we're not outputting the descriptors free them. */
1565			if (error || controlp == NULL) {
1566				unp_freerights(rp, newfds);
1567				goto next;
1568			}
1569			FILEDESC_XLOCK(td->td_proc->p_fd);
1570			/* if the new FD's will not fit free them.  */
1571			if (!fdavail(td, newfds)) {
1572				FILEDESC_XUNLOCK(td->td_proc->p_fd);
1573				error = EMSGSIZE;
1574				unp_freerights(rp, newfds);
1575				goto next;
1576			}
1577
1578			/*
1579			 * Now change each pointer to an fd in the global
1580			 * table to an integer that is the index to the local
1581			 * fd table entry that we set up to point to the
1582			 * global one we are transferring.
1583			 */
1584			newlen = newfds * sizeof(int);
1585			*controlp = sbcreatecontrol(NULL, newlen,
1586			    SCM_RIGHTS, SOL_SOCKET);
1587			if (*controlp == NULL) {
1588				FILEDESC_XUNLOCK(td->td_proc->p_fd);
1589				error = E2BIG;
1590				unp_freerights(rp, newfds);
1591				goto next;
1592			}
1593
1594			fdp = (int *)
1595			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1596			for (i = 0; i < newfds; i++) {
1597				if (fdalloc(td, 0, &f))
1598					panic("unp_externalize fdalloc failed");
1599				fp = *rp++;
1600				td->td_proc->p_fd->fd_ofiles[f] = fp;
1601				unp_externalize_fp(fp);
1602				*fdp++ = f;
1603			}
1604			FILEDESC_XUNLOCK(td->td_proc->p_fd);
1605		} else {
1606			/* We can just copy anything else across. */
1607			if (error || controlp == NULL)
1608				goto next;
1609			*controlp = sbcreatecontrol(NULL, datalen,
1610			    cm->cmsg_type, cm->cmsg_level);
1611			if (*controlp == NULL) {
1612				error = ENOBUFS;
1613				goto next;
1614			}
1615			bcopy(data,
1616			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1617			    datalen);
1618		}
1619		controlp = &(*controlp)->m_next;
1620
1621next:
1622		if (CMSG_SPACE(datalen) < clen) {
1623			clen -= CMSG_SPACE(datalen);
1624			cm = (struct cmsghdr *)
1625			    ((caddr_t)cm + CMSG_SPACE(datalen));
1626		} else {
1627			clen = 0;
1628			cm = NULL;
1629		}
1630	}
1631
1632	m_freem(control);
1633	return (error);
1634}
1635
1636static void
1637unp_zone_change(void *tag)
1638{
1639
1640	uma_zone_set_max(unp_zone, maxsockets);
1641}
1642
1643static void
1644unp_init(void)
1645{
1646
1647	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1648	    NULL, NULL, UMA_ALIGN_PTR, 0);
1649	if (unp_zone == NULL)
1650		panic("unp_init");
1651	uma_zone_set_max(unp_zone, maxsockets);
1652	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1653	    NULL, EVENTHANDLER_PRI_ANY);
1654	LIST_INIT(&unp_dhead);
1655	LIST_INIT(&unp_shead);
1656	TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1657	UNP_GLOBAL_LOCK_INIT();
1658}
1659
1660static int
1661unp_internalize(struct mbuf **controlp, struct thread *td)
1662{
1663	struct mbuf *control = *controlp;
1664	struct proc *p = td->td_proc;
1665	struct filedesc *fdescp = p->p_fd;
1666	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1667	struct cmsgcred *cmcred;
1668	struct file **rp;
1669	struct file *fp;
1670	struct timeval *tv;
1671	int i, fd, *fdp;
1672	void *data;
1673	socklen_t clen = control->m_len, datalen;
1674	int error, oldfds;
1675	u_int newlen;
1676
1677	UNP_GLOBAL_UNLOCK_ASSERT();
1678
1679	error = 0;
1680	*controlp = NULL;
1681	while (cm != NULL) {
1682		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1683		    || cm->cmsg_len > clen) {
1684			error = EINVAL;
1685			goto out;
1686		}
1687		data = CMSG_DATA(cm);
1688		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1689
1690		switch (cm->cmsg_type) {
1691		/*
1692		 * Fill in credential information.
1693		 */
1694		case SCM_CREDS:
1695			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1696			    SCM_CREDS, SOL_SOCKET);
1697			if (*controlp == NULL) {
1698				error = ENOBUFS;
1699				goto out;
1700			}
1701			cmcred = (struct cmsgcred *)
1702			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1703			cmcred->cmcred_pid = p->p_pid;
1704			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1705			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1706			cmcred->cmcred_euid = td->td_ucred->cr_uid;
1707			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1708			    CMGROUP_MAX);
1709			for (i = 0; i < cmcred->cmcred_ngroups; i++)
1710				cmcred->cmcred_groups[i] =
1711				    td->td_ucred->cr_groups[i];
1712			break;
1713
1714		case SCM_RIGHTS:
1715			oldfds = datalen / sizeof (int);
1716			/*
1717			 * Check that all the FDs passed in refer to legal
1718			 * files.  If not, reject the entire operation.
1719			 */
1720			fdp = data;
1721			FILEDESC_SLOCK(fdescp);
1722			for (i = 0; i < oldfds; i++) {
1723				fd = *fdp++;
1724				if ((unsigned)fd >= fdescp->fd_nfiles ||
1725				    fdescp->fd_ofiles[fd] == NULL) {
1726					FILEDESC_SUNLOCK(fdescp);
1727					error = EBADF;
1728					goto out;
1729				}
1730				fp = fdescp->fd_ofiles[fd];
1731				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1732					FILEDESC_SUNLOCK(fdescp);
1733					error = EOPNOTSUPP;
1734					goto out;
1735				}
1736
1737			}
1738
1739			/*
1740			 * Now replace the integer FDs with pointers to the
1741			 * associated global file table entry..
1742			 */
1743			newlen = oldfds * sizeof(struct file *);
1744			*controlp = sbcreatecontrol(NULL, newlen,
1745			    SCM_RIGHTS, SOL_SOCKET);
1746			if (*controlp == NULL) {
1747				FILEDESC_SUNLOCK(fdescp);
1748				error = E2BIG;
1749				goto out;
1750			}
1751			fdp = data;
1752			rp = (struct file **)
1753			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1754			for (i = 0; i < oldfds; i++) {
1755				fp = fdescp->fd_ofiles[*fdp++];
1756				*rp++ = fp;
1757				unp_internalize_fp(fp);
1758			}
1759			FILEDESC_SUNLOCK(fdescp);
1760			break;
1761
1762		case SCM_TIMESTAMP:
1763			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
1764			    SCM_TIMESTAMP, SOL_SOCKET);
1765			if (*controlp == NULL) {
1766				error = ENOBUFS;
1767				goto out;
1768			}
1769			tv = (struct timeval *)
1770			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1771			microtime(tv);
1772			break;
1773
1774		default:
1775			error = EINVAL;
1776			goto out;
1777		}
1778
1779		controlp = &(*controlp)->m_next;
1780		if (CMSG_SPACE(datalen) < clen) {
1781			clen -= CMSG_SPACE(datalen);
1782			cm = (struct cmsghdr *)
1783			    ((caddr_t)cm + CMSG_SPACE(datalen));
1784		} else {
1785			clen = 0;
1786			cm = NULL;
1787		}
1788	}
1789
1790out:
1791	m_freem(control);
1792	return (error);
1793}
1794
1795static struct mbuf *
1796unp_addsockcred(struct thread *td, struct mbuf *control)
1797{
1798	struct mbuf *m, *n, *n_prev;
1799	struct sockcred *sc;
1800	const struct cmsghdr *cm;
1801	int ngroups;
1802	int i;
1803
1804	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1805	m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1806	if (m == NULL)
1807		return (control);
1808
1809	sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1810	sc->sc_uid = td->td_ucred->cr_ruid;
1811	sc->sc_euid = td->td_ucred->cr_uid;
1812	sc->sc_gid = td->td_ucred->cr_rgid;
1813	sc->sc_egid = td->td_ucred->cr_gid;
1814	sc->sc_ngroups = ngroups;
1815	for (i = 0; i < sc->sc_ngroups; i++)
1816		sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1817
1818	/*
1819	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1820	 * created SCM_CREDS control message (struct sockcred) has another
1821	 * format.
1822	 */
1823	if (control != NULL)
1824		for (n = control, n_prev = NULL; n != NULL;) {
1825			cm = mtod(n, struct cmsghdr *);
1826    			if (cm->cmsg_level == SOL_SOCKET &&
1827			    cm->cmsg_type == SCM_CREDS) {
1828    				if (n_prev == NULL)
1829					control = n->m_next;
1830				else
1831					n_prev->m_next = n->m_next;
1832				n = m_free(n);
1833			} else {
1834				n_prev = n;
1835				n = n->m_next;
1836			}
1837		}
1838
1839	/* Prepend it to the head. */
1840	m->m_next = control;
1841	return (m);
1842}
1843
1844static struct unpcb *
1845fptounp(struct file *fp)
1846{
1847	struct socket *so;
1848
1849	if (fp->f_type != DTYPE_SOCKET)
1850		return (NULL);
1851	if ((so = fp->f_data) == NULL)
1852		return (NULL);
1853	if (so->so_proto->pr_domain != &localdomain)
1854		return (NULL);
1855	return sotounpcb(so);
1856}
1857
1858static void
1859unp_discard(struct file *fp)
1860{
1861
1862	unp_externalize_fp(fp);
1863	(void) closef(fp, (struct thread *)NULL);
1864}
1865
1866static void
1867unp_internalize_fp(struct file *fp)
1868{
1869	struct unpcb *unp;
1870
1871	UNP_GLOBAL_WLOCK();
1872	if ((unp = fptounp(fp)) != NULL) {
1873		unp->unp_file = fp;
1874		unp->unp_msgcount++;
1875	}
1876	fhold(fp);
1877	unp_rights++;
1878	UNP_GLOBAL_WUNLOCK();
1879}
1880
1881static void
1882unp_externalize_fp(struct file *fp)
1883{
1884	struct unpcb *unp;
1885
1886	UNP_GLOBAL_WLOCK();
1887	if ((unp = fptounp(fp)) != NULL)
1888		unp->unp_msgcount--;
1889	unp_rights--;
1890	UNP_GLOBAL_WUNLOCK();
1891}
1892
1893/*
1894 * unp_defer indicates whether additional work has been defered for a future
1895 * pass through unp_gc().  It is thread local and does not require explicit
1896 * synchronization.
1897 */
1898static int	unp_marked;
1899static int	unp_unreachable;
1900
1901static void
1902unp_accessable(struct file *fp)
1903{
1904	struct unpcb *unp;
1905
1906	if ((unp = fptounp(fp)) == NULL)
1907		return;
1908	if (unp->unp_gcflag & UNPGC_REF)
1909		return;
1910	unp->unp_gcflag &= ~UNPGC_DEAD;
1911	unp->unp_gcflag |= UNPGC_REF;
1912	unp_marked++;
1913}
1914
1915static void
1916unp_gc_process(struct unpcb *unp)
1917{
1918	struct socket *soa;
1919	struct socket *so;
1920	struct file *fp;
1921
1922	/* Already processed. */
1923	if (unp->unp_gcflag & UNPGC_SCANNED)
1924		return;
1925	fp = unp->unp_file;
1926
1927	/*
1928	 * Check for a socket potentially in a cycle.  It must be in a
1929	 * queue as indicated by msgcount, and this must equal the file
1930	 * reference count.  Note that when msgcount is 0 the file is NULL.
1931	 */
1932	if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
1933	    unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
1934		unp->unp_gcflag |= UNPGC_DEAD;
1935		unp_unreachable++;
1936		return;
1937	}
1938
1939	/*
1940	 * Mark all sockets we reference with RIGHTS.
1941	 */
1942	so = unp->unp_socket;
1943	SOCKBUF_LOCK(&so->so_rcv);
1944	unp_scan(so->so_rcv.sb_mb, unp_accessable);
1945	SOCKBUF_UNLOCK(&so->so_rcv);
1946
1947	/*
1948	 * Mark all sockets in our accept queue.
1949	 */
1950	ACCEPT_LOCK();
1951	TAILQ_FOREACH(soa, &so->so_comp, so_list) {
1952		SOCKBUF_LOCK(&soa->so_rcv);
1953		unp_scan(soa->so_rcv.sb_mb, unp_accessable);
1954		SOCKBUF_UNLOCK(&soa->so_rcv);
1955	}
1956	ACCEPT_UNLOCK();
1957	unp->unp_gcflag |= UNPGC_SCANNED;
1958}
1959
1960static int unp_recycled;
1961SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
1962    "Number of unreachable sockets claimed by the garbage collector.");
1963
1964static int unp_taskcount;
1965SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
1966    "Number of times the garbage collector has run.");
1967
1968static void
1969unp_gc(__unused void *arg, int pending)
1970{
1971	struct unp_head *heads[] = { &unp_dhead, &unp_shead, NULL };
1972	struct unp_head **head;
1973	struct file **unref;
1974	struct unpcb *unp;
1975	int i;
1976
1977	unp_taskcount++;
1978	UNP_GLOBAL_RLOCK();
1979	/*
1980	 * First clear all gc flags from previous runs.
1981	 */
1982	for (head = heads; *head != NULL; head++)
1983		LIST_FOREACH(unp, *head, unp_link)
1984			unp->unp_gcflag = 0;
1985
1986	/*
1987	 * Scan marking all reachable sockets with UNPGC_REF.  Once a socket
1988	 * is reachable all of the sockets it references are reachable.
1989	 * Stop the scan once we do a complete loop without discovering
1990	 * a new reachable socket.
1991	 */
1992	do {
1993		unp_unreachable = 0;
1994		unp_marked = 0;
1995		for (head = heads; *head != NULL; head++)
1996			LIST_FOREACH(unp, *head, unp_link)
1997				unp_gc_process(unp);
1998	} while (unp_marked);
1999	UNP_GLOBAL_RUNLOCK();
2000	if (unp_unreachable == 0)
2001		return;
2002
2003	/*
2004	 * Allocate space for a local list of dead unpcbs.
2005	 */
2006	unref = malloc(unp_unreachable * sizeof(struct file *),
2007	    M_TEMP, M_WAITOK);
2008
2009	/*
2010	 * Iterate looking for sockets which have been specifically marked
2011	 * as as unreachable and store them locally.
2012	 */
2013	UNP_GLOBAL_RLOCK();
2014	for (i = 0, head = heads; *head != NULL; head++)
2015		LIST_FOREACH(unp, *head, unp_link)
2016			if (unp->unp_gcflag & UNPGC_DEAD) {
2017				unref[i++] = unp->unp_file;
2018				fhold(unp->unp_file);
2019				KASSERT(unp->unp_file != NULL,
2020				    ("unp_gc: Invalid unpcb."));
2021				KASSERT(i <= unp_unreachable,
2022				    ("unp_gc: incorrect unreachable count."));
2023			}
2024	UNP_GLOBAL_RUNLOCK();
2025
2026	/*
2027	 * Now flush all sockets, free'ing rights.  This will free the
2028	 * struct files associated with these sockets but leave each socket
2029	 * with one remaining ref.
2030	 */
2031	for (i = 0; i < unp_unreachable; i++)
2032		sorflush(unref[i]->f_data);
2033
2034	/*
2035	 * And finally release the sockets so they can be reclaimed.
2036	 */
2037	for (i = 0; i < unp_unreachable; i++)
2038		fdrop(unref[i], NULL);
2039	unp_recycled += unp_unreachable;
2040	free(unref, M_TEMP);
2041}
2042
2043static void
2044unp_dispose(struct mbuf *m)
2045{
2046
2047	if (m)
2048		unp_scan(m, unp_discard);
2049}
2050
2051static void
2052unp_scan(struct mbuf *m0, void (*op)(struct file *))
2053{
2054	struct mbuf *m;
2055	struct file **rp;
2056	struct cmsghdr *cm;
2057	void *data;
2058	int i;
2059	socklen_t clen, datalen;
2060	int qfds;
2061
2062	while (m0 != NULL) {
2063		for (m = m0; m; m = m->m_next) {
2064			if (m->m_type != MT_CONTROL)
2065				continue;
2066
2067			cm = mtod(m, struct cmsghdr *);
2068			clen = m->m_len;
2069
2070			while (cm != NULL) {
2071				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2072					break;
2073
2074				data = CMSG_DATA(cm);
2075				datalen = (caddr_t)cm + cm->cmsg_len
2076				    - (caddr_t)data;
2077
2078				if (cm->cmsg_level == SOL_SOCKET &&
2079				    cm->cmsg_type == SCM_RIGHTS) {
2080					qfds = datalen / sizeof (struct file *);
2081					rp = data;
2082					for (i = 0; i < qfds; i++)
2083						(*op)(*rp++);
2084				}
2085
2086				if (CMSG_SPACE(datalen) < clen) {
2087					clen -= CMSG_SPACE(datalen);
2088					cm = (struct cmsghdr *)
2089					    ((caddr_t)cm + CMSG_SPACE(datalen));
2090				} else {
2091					clen = 0;
2092					cm = NULL;
2093				}
2094			}
2095		}
2096		m0 = m0->m_act;
2097	}
2098}
2099
2100#ifdef DDB
2101static void
2102db_print_indent(int indent)
2103{
2104	int i;
2105
2106	for (i = 0; i < indent; i++)
2107		db_printf(" ");
2108}
2109
2110static void
2111db_print_unpflags(int unp_flags)
2112{
2113	int comma;
2114
2115	comma = 0;
2116	if (unp_flags & UNP_HAVEPC) {
2117		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2118		comma = 1;
2119	}
2120	if (unp_flags & UNP_HAVEPCCACHED) {
2121		db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2122		comma = 1;
2123	}
2124	if (unp_flags & UNP_WANTCRED) {
2125		db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2126		comma = 1;
2127	}
2128	if (unp_flags & UNP_CONNWAIT) {
2129		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2130		comma = 1;
2131	}
2132	if (unp_flags & UNP_CONNECTING) {
2133		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2134		comma = 1;
2135	}
2136	if (unp_flags & UNP_BINDING) {
2137		db_printf("%sUNP_BINDING", comma ? ", " : "");
2138		comma = 1;
2139	}
2140}
2141
2142static void
2143db_print_xucred(int indent, struct xucred *xu)
2144{
2145	int comma, i;
2146
2147	db_print_indent(indent);
2148	db_printf("cr_version: %u   cr_uid: %u   cr_ngroups: %d\n",
2149	    xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2150	db_print_indent(indent);
2151	db_printf("cr_groups: ");
2152	comma = 0;
2153	for (i = 0; i < xu->cr_ngroups; i++) {
2154		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2155		comma = 1;
2156	}
2157	db_printf("\n");
2158}
2159
2160static void
2161db_print_unprefs(int indent, struct unp_head *uh)
2162{
2163	struct unpcb *unp;
2164	int counter;
2165
2166	counter = 0;
2167	LIST_FOREACH(unp, uh, unp_reflink) {
2168		if (counter % 4 == 0)
2169			db_print_indent(indent);
2170		db_printf("%p  ", unp);
2171		if (counter % 4 == 3)
2172			db_printf("\n");
2173		counter++;
2174	}
2175	if (counter != 0 && counter % 4 != 0)
2176		db_printf("\n");
2177}
2178
2179DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2180{
2181	struct unpcb *unp;
2182
2183        if (!have_addr) {
2184                db_printf("usage: show unpcb <addr>\n");
2185                return;
2186        }
2187        unp = (struct unpcb *)addr;
2188
2189	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
2190	    unp->unp_vnode);
2191
2192	db_printf("unp_ino: %d   unp_conn: %p\n", unp->unp_ino,
2193	    unp->unp_conn);
2194
2195	db_printf("unp_refs:\n");
2196	db_print_unprefs(2, &unp->unp_refs);
2197
2198	/* XXXRW: Would be nice to print the full address, if any. */
2199	db_printf("unp_addr: %p\n", unp->unp_addr);
2200
2201	db_printf("unp_cc: %d   unp_mbcnt: %d   unp_gencnt: %llu\n",
2202	    unp->unp_cc, unp->unp_mbcnt,
2203	    (unsigned long long)unp->unp_gencnt);
2204
2205	db_printf("unp_flags: %x (", unp->unp_flags);
2206	db_print_unpflags(unp->unp_flags);
2207	db_printf(")\n");
2208
2209	db_printf("unp_peercred:\n");
2210	db_print_xucred(2, &unp->unp_peercred);
2211
2212	db_printf("unp_refcount: %u\n", unp->unp_refcount);
2213}
2214#endif
2215