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