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