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