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