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