2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1991, 1993
5 * The Regents of the University of California. All Rights Reserved.
6 * Copyright (c) 2004-2009 Robert N. M. Watson All Rights Reserved.
7 * Copyright (c) 2018 Matthew Macy
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
37 * UNIX Domain (Local) Sockets
39 * This is an implementation of UNIX (local) domain sockets. Each socket has
40 * an associated struct unpcb (UNIX protocol control block). Stream sockets
41 * may be connected to 0 or 1 other socket. Datagram sockets may be
42 * connected to 0, 1, or many other sockets. Sockets may be created and
43 * connected in pairs (socketpair(2)), or bound/connected to using the file
44 * system name space. For most purposes, only the receive socket buffer is
45 * used, as sending on one socket delivers directly to the receive socket
46 * buffer of a second socket.
48 * The implementation is substantially complicated by the fact that
49 * "ancillary data", such as file descriptors or credentials, may be passed
50 * across UNIX domain sockets. The potential for passing UNIX domain sockets
51 * over other UNIX domain sockets requires the implementation of a simple
52 * garbage collector to find and tear down cycles of disconnected sockets.
56 * rethink name space problems
57 * need a proper out-of-band
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
65 #include <sys/param.h>
66 #include <sys/capsicum.h>
67 #include <sys/domain.h>
68 #include <sys/eventhandler.h>
69 #include <sys/fcntl.h>
71 #include <sys/filedesc.h>
72 #include <sys/kernel.h>
74 #include <sys/malloc.h>
76 #include <sys/mount.h>
77 #include <sys/mutex.h>
78 #include <sys/namei.h>
80 #include <sys/protosw.h>
81 #include <sys/queue.h>
82 #include <sys/resourcevar.h>
83 #include <sys/rwlock.h>
84 #include <sys/socket.h>
85 #include <sys/socketvar.h>
86 #include <sys/signalvar.h>
89 #include <sys/sysctl.h>
90 #include <sys/systm.h>
91 #include <sys/taskqueue.h>
93 #include <sys/unpcb.h>
94 #include <sys/vnode.h>
102 #include <security/mac/mac_framework.h>
106 MALLOC_DECLARE(M_FILECAPS);
109 * See unpcb.h for the locking key.
112 static uma_zone_t unp_zone;
113 static unp_gen_t unp_gencnt; /* (l) */
114 static u_int unp_count; /* (l) Count of local sockets. */
115 static ino_t unp_ino; /* Prototype for fake inode numbers. */
116 static int unp_rights; /* (g) File descriptors in flight. */
117 static struct unp_head unp_shead; /* (l) List of stream sockets. */
118 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
119 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */
122 SLIST_ENTRY(unp_defer) ud_link;
125 static SLIST_HEAD(, unp_defer) unp_defers;
126 static int unp_defers_count;
128 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
131 * Garbage collection of cyclic file descriptor/socket references occurs
132 * asynchronously in a taskqueue context in order to avoid recursion and
133 * reentrance in the UNIX domain socket, file descriptor, and socket layer
134 * code. See unp_gc() for a full description.
136 static struct timeout_task unp_gc_task;
139 * The close of unix domain sockets attached as SCM_RIGHTS is
140 * postponed to the taskqueue, to avoid arbitrary recursion depth.
141 * The attached sockets might have another sockets attached.
143 static struct task unp_defer_task;
146 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
147 * stream sockets, although the total for sender and receiver is actually
150 * Datagram sockets really use the sendspace as the maximum datagram size,
151 * and don't really want to reserve the sendspace. Their recvspace should be
152 * large enough for at least one max-size datagram plus address.
157 static u_long unpst_sendspace = PIPSIZ;
158 static u_long unpst_recvspace = PIPSIZ;
159 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
160 static u_long unpdg_recvspace = 4*1024;
161 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */
162 static u_long unpsp_recvspace = PIPSIZ;
164 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
165 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0,
167 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
168 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, CTLFLAG_RW, 0,
171 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
172 &unpst_sendspace, 0, "Default stream send space.");
173 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
174 &unpst_recvspace, 0, "Default stream receive space.");
175 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
176 &unpdg_sendspace, 0, "Default datagram send space.");
177 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
178 &unpdg_recvspace, 0, "Default datagram receive space.");
179 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
180 &unpsp_sendspace, 0, "Default seqpacket send space.");
181 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
182 &unpsp_recvspace, 0, "Default seqpacket receive space.");
183 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
184 "File descriptors in flight.");
185 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
186 &unp_defers_count, 0,
187 "File descriptors deferred to taskqueue for close.");
190 * Locking and synchronization:
192 * Several types of locks exist in the local domain socket implementation:
193 * - a global linkage lock
194 * - a global connection list lock
196 * - per-unpcb mutexes
198 * The linkage lock protects the global socket lists, the generation number
199 * counter and garbage collector state.
201 * The connection list lock protects the list of referring sockets in a datagram
202 * socket PCB. This lock is also overloaded to protect a global list of
203 * sockets whose buffers contain socket references in the form of SCM_RIGHTS
204 * messages. To avoid recursion, such references are released by a dedicated
207 * The mtxpool lock protects the vnode from being modified while referenced.
208 * Lock ordering rules require that it be acquired before any PCB locks.
210 * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
211 * unpcb. This includes the unp_conn field, which either links two connected
212 * PCBs together (for connected socket types) or points at the destination
213 * socket (for connectionless socket types). The operations of creating or
214 * destroying a connection therefore involve locking multiple PCBs. To avoid
215 * lock order reversals, in some cases this involves dropping a PCB lock and
216 * using a reference counter to maintain liveness.
218 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
219 * allocated in pru_attach() and freed in pru_detach(). The validity of that
220 * pointer is an invariant, so no lock is required to dereference the so_pcb
221 * pointer if a valid socket reference is held by the caller. In practice,
222 * this is always true during operations performed on a socket. Each unpcb
223 * has a back-pointer to its socket, unp_socket, which will be stable under
224 * the same circumstances.
226 * This pointer may only be safely dereferenced as long as a valid reference
227 * to the unpcb is held. Typically, this reference will be from the socket,
228 * or from another unpcb when the referring unpcb's lock is held (in order
229 * that the reference not be invalidated during use). For example, to follow
230 * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
231 * that detach is not run clearing unp_socket.
233 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
234 * protocols, bind() is a non-atomic operation, and connect() requires
235 * potential sleeping in the protocol, due to potentially waiting on local or
236 * distributed file systems. We try to separate "lookup" operations, which
237 * may sleep, and the IPC operations themselves, which typically can occur
238 * with relative atomicity as locks can be held over the entire operation.
240 * Another tricky issue is simultaneous multi-threaded or multi-process
241 * access to a single UNIX domain socket. These are handled by the flags
242 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
243 * binding, both of which involve dropping UNIX domain socket locks in order
244 * to perform namei() and other file system operations.
246 static struct rwlock unp_link_rwlock;
247 static struct mtx unp_defers_lock;
249 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
252 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
254 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
257 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
258 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
259 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
260 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
261 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
263 #define UNP_LINK_WOWNED() rw_wowned(&unp_link_rwlock)
265 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
266 "unp_defer", NULL, MTX_DEF)
267 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
268 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
270 #define UNP_REF_LIST_LOCK() UNP_DEFERRED_LOCK();
271 #define UNP_REF_LIST_UNLOCK() UNP_DEFERRED_UNLOCK();
273 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
276 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
277 #define UNP_PCB_LOCKPTR(unp) (&(unp)->unp_mtx)
278 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
279 #define UNP_PCB_TRYLOCK(unp) mtx_trylock(&(unp)->unp_mtx)
280 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
281 #define UNP_PCB_OWNED(unp) mtx_owned(&(unp)->unp_mtx)
282 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
283 #define UNP_PCB_UNLOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
285 static int uipc_connect2(struct socket *, struct socket *);
286 static int uipc_ctloutput(struct socket *, struct sockopt *);
287 static int unp_connect(struct socket *, struct sockaddr *,
289 static int unp_connectat(int, struct socket *, struct sockaddr *,
291 static int unp_connect2(struct socket *so, struct socket *so2, int);
292 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
293 static void unp_dispose(struct socket *so);
294 static void unp_dispose_mbuf(struct mbuf *);
295 static void unp_shutdown(struct unpcb *);
296 static void unp_drop(struct unpcb *);
297 static void unp_gc(__unused void *, int);
298 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
299 static void unp_discard(struct file *);
300 static void unp_freerights(struct filedescent **, int);
301 static void unp_init(void);
302 static int unp_internalize(struct mbuf **, struct thread *);
303 static void unp_internalize_fp(struct file *);
304 static int unp_externalize(struct mbuf *, struct mbuf **, int);
305 static int unp_externalize_fp(struct file *);
306 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
307 static void unp_process_defers(void * __unused, int);
311 unp_pcb_hold(struct unpcb *unp)
313 refcount_acquire(&unp->unp_refcount);
316 static __result_use_check bool
317 unp_pcb_rele(struct unpcb *unp)
321 UNP_PCB_LOCK_ASSERT(unp);
323 if ((ret = refcount_release(&unp->unp_refcount))) {
325 UNP_PCB_LOCK_DESTROY(unp);
326 uma_zfree(unp_zone, unp);
332 unp_pcb_rele_notlast(struct unpcb *unp)
336 ret = refcount_release(&unp->unp_refcount);
337 KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
341 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
343 UNP_PCB_UNLOCK_ASSERT(unp);
344 UNP_PCB_UNLOCK_ASSERT(unp2);
348 } else if ((uintptr_t)unp2 > (uintptr_t)unp) {
358 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
362 UNP_PCB_UNLOCK(unp2);
366 * Try to lock the connected peer of an already locked socket. In some cases
367 * this requires that we unlock the current socket. The pairbusy counter is
368 * used to block concurrent connection attempts while the lock is dropped. The
369 * caller must be careful to revalidate PCB state.
371 static struct unpcb *
372 unp_pcb_lock_peer(struct unpcb *unp)
376 UNP_PCB_LOCK_ASSERT(unp);
377 unp2 = unp->unp_conn;
378 if (__predict_false(unp2 == NULL))
380 if (__predict_false(unp == unp2))
383 UNP_PCB_UNLOCK_ASSERT(unp2);
385 if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
387 if ((uintptr_t)unp2 > (uintptr_t)unp) {
397 KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
398 ("%s: socket %p was reconnected", __func__, unp));
399 if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
400 unp->unp_flags &= ~UNP_WAITING;
403 if (unp_pcb_rele(unp2)) {
404 /* unp2 is unlocked. */
407 if (unp->unp_conn == NULL) {
408 UNP_PCB_UNLOCK(unp2);
416 * Definitions of protocols supported in the LOCAL domain.
418 static struct domain localdomain;
419 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
420 static struct pr_usrreqs uipc_usrreqs_seqpacket;
421 static struct protosw localsw[] = {
423 .pr_type = SOCK_STREAM,
424 .pr_domain = &localdomain,
425 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
426 .pr_ctloutput = &uipc_ctloutput,
427 .pr_usrreqs = &uipc_usrreqs_stream
430 .pr_type = SOCK_DGRAM,
431 .pr_domain = &localdomain,
432 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
433 .pr_ctloutput = &uipc_ctloutput,
434 .pr_usrreqs = &uipc_usrreqs_dgram
437 .pr_type = SOCK_SEQPACKET,
438 .pr_domain = &localdomain,
441 * XXXRW: For now, PR_ADDR because soreceive will bump into them
442 * due to our use of sbappendaddr. A new sbappend variants is needed
443 * that supports both atomic record writes and control data.
445 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
447 .pr_ctloutput = &uipc_ctloutput,
448 .pr_usrreqs = &uipc_usrreqs_seqpacket,
452 static struct domain localdomain = {
453 .dom_family = AF_LOCAL,
455 .dom_init = unp_init,
456 .dom_externalize = unp_externalize,
457 .dom_dispose = unp_dispose,
458 .dom_protosw = localsw,
459 .dom_protoswNPROTOSW = &localsw[nitems(localsw)]
464 uipc_abort(struct socket *so)
466 struct unpcb *unp, *unp2;
469 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
470 UNP_PCB_UNLOCK_ASSERT(unp);
473 unp2 = unp->unp_conn;
483 uipc_accept(struct socket *so, struct sockaddr **nam)
485 struct unpcb *unp, *unp2;
486 const struct sockaddr *sa;
489 * Pass back name of connected socket, if it was bound and we are
490 * still connected (our peer may have closed already!).
493 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
495 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
497 unp2 = unp_pcb_lock_peer(unp);
498 if (unp2 != NULL && unp2->unp_addr != NULL)
499 sa = (struct sockaddr *)unp2->unp_addr;
502 bcopy(sa, *nam, sa->sa_len);
504 unp_pcb_unlock_pair(unp, unp2);
511 uipc_attach(struct socket *so, int proto, struct thread *td)
513 u_long sendspace, recvspace;
518 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
519 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
520 switch (so->so_type) {
522 sendspace = unpst_sendspace;
523 recvspace = unpst_recvspace;
527 sendspace = unpdg_sendspace;
528 recvspace = unpdg_recvspace;
532 sendspace = unpsp_sendspace;
533 recvspace = unpsp_recvspace;
537 panic("uipc_attach");
539 error = soreserve(so, sendspace, recvspace);
543 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
546 LIST_INIT(&unp->unp_refs);
547 UNP_PCB_LOCK_INIT(unp);
548 unp->unp_socket = so;
550 refcount_init(&unp->unp_refcount, 1);
552 if ((locked = UNP_LINK_WOWNED()) == false)
555 unp->unp_gencnt = ++unp_gencnt;
556 unp->unp_ino = ++unp_ino;
558 switch (so->so_type) {
560 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
564 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
568 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
572 panic("uipc_attach");
582 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
584 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
594 if (nam->sa_family != AF_UNIX)
595 return (EAFNOSUPPORT);
598 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
600 if (soun->sun_len > sizeof(struct sockaddr_un))
602 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
607 * We don't allow simultaneous bind() calls on a single UNIX domain
608 * socket, so flag in-progress operations, and return an error if an
609 * operation is already in progress.
611 * Historically, we have not allowed a socket to be rebound, so this
612 * also returns an error. Not allowing re-binding simplifies the
613 * implementation and avoids a great many possible failure modes.
616 if (unp->unp_vnode != NULL) {
620 if (unp->unp_flags & UNP_BINDING) {
624 unp->unp_flags |= UNP_BINDING;
627 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
628 bcopy(soun->sun_path, buf, namelen);
632 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
633 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
634 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
639 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
640 NDFREE(&nd, NDF_ONLY_PNBUF);
650 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
656 vattr.va_type = VSOCK;
657 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
659 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
663 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
664 NDFREE(&nd, NDF_ONLY_PNBUF);
667 vn_finished_write(mp);
671 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
672 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
675 VOP_UNP_BIND(vp, unp);
677 unp->unp_addr = soun;
678 unp->unp_flags &= ~UNP_BINDING;
681 vn_finished_write(mp);
687 unp->unp_flags &= ~UNP_BINDING;
694 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
697 return (uipc_bindat(AT_FDCWD, so, nam, td));
701 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
705 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
706 error = unp_connect(so, nam, td);
711 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
716 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
717 error = unp_connectat(fd, so, nam, td);
722 uipc_close(struct socket *so)
724 struct unpcb *unp, *unp2;
725 struct vnode *vp = NULL;
729 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
733 if ((vp = unp->unp_vnode) != NULL) {
734 vplock = mtx_pool_find(mtxpool_sleep, vp);
738 if (vp && unp->unp_vnode == NULL) {
744 unp->unp_vnode = NULL;
746 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
747 unp_disconnect(unp, unp2);
757 uipc_connect2(struct socket *so1, struct socket *so2)
759 struct unpcb *unp, *unp2;
763 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
765 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
766 unp_pcb_lock_pair(unp, unp2);
767 error = unp_connect2(so1, so2, PRU_CONNECT2);
768 unp_pcb_unlock_pair(unp, unp2);
773 uipc_detach(struct socket *so)
775 struct unpcb *unp, *unp2;
778 int local_unp_rights;
781 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
787 if (!SOLISTENING(so)) {
789 * Once the socket is removed from the global lists,
790 * uipc_ready() will not be able to locate its socket buffer, so
791 * clear the buffer now. At this point internalized rights have
792 * already been disposed of.
794 sbrelease(&so->so_rcv, so);
799 LIST_REMOVE(unp, unp_link);
800 unp->unp_gencnt = ++unp_gencnt;
804 UNP_PCB_UNLOCK_ASSERT(unp);
806 if ((vp = unp->unp_vnode) != NULL) {
807 vplock = mtx_pool_find(mtxpool_sleep, vp);
811 if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
817 if ((vp = unp->unp_vnode) != NULL) {
819 unp->unp_vnode = NULL;
821 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
822 unp_disconnect(unp, unp2);
827 while (!LIST_EMPTY(&unp->unp_refs)) {
828 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
831 UNP_REF_LIST_UNLOCK();
834 UNP_PCB_UNLOCK_ASSERT(ref);
838 UNP_REF_LIST_UNLOCK();
841 local_unp_rights = unp_rights;
842 unp->unp_socket->so_pcb = NULL;
843 unp->unp_socket = NULL;
844 free(unp->unp_addr, M_SONAME);
845 unp->unp_addr = NULL;
846 if (!unp_pcb_rele(unp))
852 if (local_unp_rights)
853 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
857 uipc_disconnect(struct socket *so)
859 struct unpcb *unp, *unp2;
862 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
865 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
866 unp_disconnect(unp, unp2);
873 uipc_listen(struct socket *so, int backlog, struct thread *td)
878 if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
882 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
885 if (unp->unp_vnode == NULL) {
886 /* Already connected or not bound to an address. */
887 error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
893 error = solisten_proto_check(so);
895 cru2xt(td, &unp->unp_peercred);
896 solisten_proto(so, backlog);
904 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
906 struct unpcb *unp, *unp2;
907 const struct sockaddr *sa;
910 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
912 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
915 * XXX: It seems that this test always fails even when connection is
916 * established. So, this else clause is added as workaround to
917 * return PF_LOCAL sockaddr.
919 unp2 = unp->unp_conn;
922 if (unp2->unp_addr != NULL)
923 sa = (struct sockaddr *) unp2->unp_addr;
926 bcopy(sa, *nam, sa->sa_len);
927 UNP_PCB_UNLOCK(unp2);
930 bcopy(sa, *nam, sa->sa_len);
937 uipc_rcvd(struct socket *so, int flags)
939 struct unpcb *unp, *unp2;
944 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
945 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
946 ("%s: socktype %d", __func__, so->so_type));
949 * Adjust backpressure on sender and wakeup any waiting to write.
951 * The unp lock is acquired to maintain the validity of the unp_conn
952 * pointer; no lock on unp2 is required as unp2->unp_socket will be
953 * static as long as we don't permit unp2 to disconnect from unp,
954 * which is prevented by the lock on unp. We cache values from
955 * so_rcv to avoid holding the so_rcv lock over the entire
956 * transaction on the remote so_snd.
958 SOCKBUF_LOCK(&so->so_rcv);
959 mbcnt = so->so_rcv.sb_mbcnt;
960 sbcc = sbavail(&so->so_rcv);
961 SOCKBUF_UNLOCK(&so->so_rcv);
963 * There is a benign race condition at this point. If we're planning to
964 * clear SB_STOP, but uipc_send is called on the connected socket at
965 * this instant, it might add data to the sockbuf and set SB_STOP. Then
966 * we would erroneously clear SB_STOP below, even though the sockbuf is
967 * full. The race is benign because the only ill effect is to allow the
968 * sockbuf to exceed its size limit, and the size limits are not
969 * strictly guaranteed anyway.
972 unp2 = unp->unp_conn;
977 so2 = unp2->unp_socket;
978 SOCKBUF_LOCK(&so2->so_snd);
979 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
980 so2->so_snd.sb_flags &= ~SB_STOP;
981 sowwakeup_locked(so2);
987 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
988 struct mbuf *control, struct thread *td)
990 struct unpcb *unp, *unp2;
996 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
997 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
998 so->so_type == SOCK_SEQPACKET,
999 ("%s: socktype %d", __func__, so->so_type));
1002 if (flags & PRUS_OOB) {
1006 if (control != NULL && (error = unp_internalize(&control, td)))
1010 switch (so->so_type) {
1013 const struct sockaddr *from;
1016 error = unp_connect(so, nam, td);
1023 * Because connect() and send() are non-atomic in a sendto()
1024 * with a target address, it's possible that the socket will
1025 * have disconnected before the send() can run. In that case
1026 * return the slightly counter-intuitive but otherwise
1027 * correct error that the socket is not connected.
1029 unp2 = unp_pcb_lock_peer(unp);
1031 UNP_PCB_UNLOCK(unp);
1036 if (unp2->unp_flags & UNP_WANTCRED)
1037 control = unp_addsockcred(td, control);
1038 if (unp->unp_addr != NULL)
1039 from = (struct sockaddr *)unp->unp_addr;
1042 so2 = unp2->unp_socket;
1043 SOCKBUF_LOCK(&so2->so_rcv);
1044 if (sbappendaddr_locked(&so2->so_rcv, from, m,
1046 sorwakeup_locked(so2);
1050 soroverflow_locked(so2);
1054 unp_disconnect(unp, unp2);
1056 unp_pcb_unlock_pair(unp, unp2);
1060 case SOCK_SEQPACKET:
1062 if ((so->so_state & SS_ISCONNECTED) == 0) {
1064 error = unp_connect(so, nam, td);
1074 if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
1075 UNP_PCB_UNLOCK(unp);
1078 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1079 unp_pcb_unlock_pair(unp, unp2);
1083 UNP_PCB_UNLOCK(unp);
1084 if ((so2 = unp2->unp_socket) == NULL) {
1085 UNP_PCB_UNLOCK(unp2);
1089 SOCKBUF_LOCK(&so2->so_rcv);
1090 if (unp2->unp_flags & UNP_WANTCRED) {
1092 * Credentials are passed only once on SOCK_STREAM
1093 * and SOCK_SEQPACKET.
1095 unp2->unp_flags &= ~UNP_WANTCRED;
1096 control = unp_addsockcred(td, control);
1100 * Send to paired receive port and wake up readers. Don't
1101 * check for space available in the receive buffer if we're
1102 * attaching ancillary data; Unix domain sockets only check
1103 * for space in the sending sockbuf, and that check is
1104 * performed one level up the stack. At that level we cannot
1105 * precisely account for the amount of buffer space used
1106 * (e.g., because control messages are not yet internalized).
1108 switch (so->so_type) {
1110 if (control != NULL) {
1111 sbappendcontrol_locked(&so2->so_rcv, m,
1115 sbappend_locked(&so2->so_rcv, m, flags);
1118 case SOCK_SEQPACKET:
1119 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1120 &sun_noname, m, control))
1125 mbcnt = so2->so_rcv.sb_mbcnt;
1126 sbcc = sbavail(&so2->so_rcv);
1128 sorwakeup_locked(so2);
1130 SOCKBUF_UNLOCK(&so2->so_rcv);
1133 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1134 * it would be possible for uipc_rcvd to be called at this
1135 * point, drain the receiving sockbuf, clear SB_STOP, and then
1136 * we would set SB_STOP below. That could lead to an empty
1137 * sockbuf having SB_STOP set
1139 SOCKBUF_LOCK(&so->so_snd);
1140 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1141 so->so_snd.sb_flags |= SB_STOP;
1142 SOCKBUF_UNLOCK(&so->so_snd);
1143 UNP_PCB_UNLOCK(unp2);
1149 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1151 if (flags & PRUS_EOF) {
1155 UNP_PCB_UNLOCK(unp);
1157 if (control != NULL && error != 0)
1158 unp_dispose_mbuf(control);
1161 if (control != NULL)
1164 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1165 * for freeing memory.
1167 if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1173 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1175 struct mbuf *mb, *n;
1179 if (SOLISTENING(so)) {
1186 if (sb->sb_fnrdy != NULL) {
1187 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1189 *errorp = sbready(sb, m, count);
1202 return (mb != NULL);
1206 uipc_ready(struct socket *so, struct mbuf *m, int count)
1208 struct unpcb *unp, *unp2;
1212 unp = sotounpcb(so);
1214 KASSERT(so->so_type == SOCK_STREAM,
1215 ("%s: unexpected socket type for %p", __func__, so));
1218 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1219 UNP_PCB_UNLOCK(unp);
1220 so2 = unp2->unp_socket;
1221 SOCKBUF_LOCK(&so2->so_rcv);
1222 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1223 sorwakeup_locked(so2);
1225 SOCKBUF_UNLOCK(&so2->so_rcv);
1226 UNP_PCB_UNLOCK(unp2);
1229 UNP_PCB_UNLOCK(unp);
1232 * The receiving socket has been disconnected, but may still be valid.
1233 * In this case, the now-ready mbufs are still present in its socket
1234 * buffer, so perform an exhaustive search before giving up and freeing
1238 LIST_FOREACH(unp, &unp_shead, unp_link) {
1239 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1245 for (i = 0; i < count; i++)
1253 uipc_sense(struct socket *so, struct stat *sb)
1257 unp = sotounpcb(so);
1258 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1260 sb->st_blksize = so->so_snd.sb_hiwat;
1262 sb->st_ino = unp->unp_ino;
1267 uipc_shutdown(struct socket *so)
1271 unp = sotounpcb(so);
1272 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1277 UNP_PCB_UNLOCK(unp);
1282 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1285 const struct sockaddr *sa;
1287 unp = sotounpcb(so);
1288 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1290 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1292 if (unp->unp_addr != NULL)
1293 sa = (struct sockaddr *) unp->unp_addr;
1296 bcopy(sa, *nam, sa->sa_len);
1297 UNP_PCB_UNLOCK(unp);
1301 static struct pr_usrreqs uipc_usrreqs_dgram = {
1302 .pru_abort = uipc_abort,
1303 .pru_accept = uipc_accept,
1304 .pru_attach = uipc_attach,
1305 .pru_bind = uipc_bind,
1306 .pru_bindat = uipc_bindat,
1307 .pru_connect = uipc_connect,
1308 .pru_connectat = uipc_connectat,
1309 .pru_connect2 = uipc_connect2,
1310 .pru_detach = uipc_detach,
1311 .pru_disconnect = uipc_disconnect,
1312 .pru_listen = uipc_listen,
1313 .pru_peeraddr = uipc_peeraddr,
1314 .pru_rcvd = uipc_rcvd,
1315 .pru_send = uipc_send,
1316 .pru_sense = uipc_sense,
1317 .pru_shutdown = uipc_shutdown,
1318 .pru_sockaddr = uipc_sockaddr,
1319 .pru_soreceive = soreceive_dgram,
1320 .pru_close = uipc_close,
1323 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1324 .pru_abort = uipc_abort,
1325 .pru_accept = uipc_accept,
1326 .pru_attach = uipc_attach,
1327 .pru_bind = uipc_bind,
1328 .pru_bindat = uipc_bindat,
1329 .pru_connect = uipc_connect,
1330 .pru_connectat = uipc_connectat,
1331 .pru_connect2 = uipc_connect2,
1332 .pru_detach = uipc_detach,
1333 .pru_disconnect = uipc_disconnect,
1334 .pru_listen = uipc_listen,
1335 .pru_peeraddr = uipc_peeraddr,
1336 .pru_rcvd = uipc_rcvd,
1337 .pru_send = uipc_send,
1338 .pru_sense = uipc_sense,
1339 .pru_shutdown = uipc_shutdown,
1340 .pru_sockaddr = uipc_sockaddr,
1341 .pru_soreceive = soreceive_generic, /* XXX: or...? */
1342 .pru_close = uipc_close,
1345 static struct pr_usrreqs uipc_usrreqs_stream = {
1346 .pru_abort = uipc_abort,
1347 .pru_accept = uipc_accept,
1348 .pru_attach = uipc_attach,
1349 .pru_bind = uipc_bind,
1350 .pru_bindat = uipc_bindat,
1351 .pru_connect = uipc_connect,
1352 .pru_connectat = uipc_connectat,
1353 .pru_connect2 = uipc_connect2,
1354 .pru_detach = uipc_detach,
1355 .pru_disconnect = uipc_disconnect,
1356 .pru_listen = uipc_listen,
1357 .pru_peeraddr = uipc_peeraddr,
1358 .pru_rcvd = uipc_rcvd,
1359 .pru_send = uipc_send,
1360 .pru_ready = uipc_ready,
1361 .pru_sense = uipc_sense,
1362 .pru_shutdown = uipc_shutdown,
1363 .pru_sockaddr = uipc_sockaddr,
1364 .pru_soreceive = soreceive_generic,
1365 .pru_close = uipc_close,
1369 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1375 if (sopt->sopt_level != SOL_LOCAL)
1378 unp = sotounpcb(so);
1379 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1381 switch (sopt->sopt_dir) {
1383 switch (sopt->sopt_name) {
1384 case LOCAL_PEERCRED:
1386 if (unp->unp_flags & UNP_HAVEPC)
1387 xu = unp->unp_peercred;
1389 if (so->so_type == SOCK_STREAM)
1394 UNP_PCB_UNLOCK(unp);
1396 error = sooptcopyout(sopt, &xu, sizeof(xu));
1400 /* Unlocked read. */
1401 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1402 error = sooptcopyout(sopt, &optval, sizeof(optval));
1405 case LOCAL_CONNWAIT:
1406 /* Unlocked read. */
1407 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1408 error = sooptcopyout(sopt, &optval, sizeof(optval));
1418 switch (sopt->sopt_name) {
1420 case LOCAL_CONNWAIT:
1421 error = sooptcopyin(sopt, &optval, sizeof(optval),
1426 #define OPTSET(bit) do { \
1427 UNP_PCB_LOCK(unp); \
1429 unp->unp_flags |= bit; \
1431 unp->unp_flags &= ~bit; \
1432 UNP_PCB_UNLOCK(unp); \
1435 switch (sopt->sopt_name) {
1437 OPTSET(UNP_WANTCRED);
1440 case LOCAL_CONNWAIT:
1441 OPTSET(UNP_CONNWAIT);
1450 error = ENOPROTOOPT;
1463 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1466 return (unp_connectat(AT_FDCWD, so, nam, td));
1470 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1474 struct sockaddr_un *soun;
1477 struct unpcb *unp, *unp2, *unp3;
1478 struct nameidata nd;
1479 char buf[SOCK_MAXADDRLEN];
1480 struct sockaddr *sa;
1481 cap_rights_t rights;
1485 if (nam->sa_family != AF_UNIX)
1486 return (EAFNOSUPPORT);
1487 if (nam->sa_len > sizeof(struct sockaddr_un))
1489 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1492 soun = (struct sockaddr_un *)nam;
1493 bcopy(soun->sun_path, buf, len);
1496 unp = sotounpcb(so);
1500 * Wait for connection state to stabilize. If a connection
1501 * already exists, give up. For datagram sockets, which permit
1502 * multiple consecutive connect(2) calls, upper layers are
1503 * responsible for disconnecting in advance of a subsequent
1504 * connect(2), but this is not synchronized with PCB connection
1507 * Also make sure that no threads are currently attempting to
1508 * lock the peer socket, to ensure that unp_conn cannot
1509 * transition between two valid sockets while locks are dropped.
1511 if (unp->unp_conn != NULL) {
1512 UNP_PCB_UNLOCK(unp);
1515 if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1516 UNP_PCB_UNLOCK(unp);
1519 if (unp->unp_pairbusy > 0) {
1520 unp->unp_flags |= UNP_WAITING;
1521 mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1526 unp->unp_flags |= UNP_CONNECTING;
1527 UNP_PCB_UNLOCK(unp);
1529 connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1531 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1534 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1535 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1541 ASSERT_VOP_LOCKED(vp, "unp_connect");
1542 NDFREE(&nd, NDF_ONLY_PNBUF);
1546 if (vp->v_type != VSOCK) {
1551 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1555 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1559 unp = sotounpcb(so);
1560 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1562 vplock = mtx_pool_find(mtxpool_sleep, vp);
1564 VOP_UNP_CONNECT(vp, &unp2);
1566 error = ECONNREFUSED;
1569 so2 = unp2->unp_socket;
1570 if (so->so_type != so2->so_type) {
1575 if (so2->so_options & SO_ACCEPTCONN) {
1576 CURVNET_SET(so2->so_vnet);
1577 so2 = sonewconn(so2, 0);
1582 error = ECONNREFUSED;
1585 unp3 = sotounpcb(so2);
1586 unp_pcb_lock_pair(unp2, unp3);
1587 if (unp2->unp_addr != NULL) {
1588 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1589 unp3->unp_addr = (struct sockaddr_un *) sa;
1593 unp_copy_peercred(td, unp3, unp, unp2);
1595 UNP_PCB_UNLOCK(unp2);
1599 * It is safe to block on the PCB lock here since unp2 is
1600 * nascent and cannot be connected to any other sockets.
1604 mac_socketpeer_set_from_socket(so, so2);
1605 mac_socketpeer_set_from_socket(so2, so);
1608 unp_pcb_lock_pair(unp, unp2);
1610 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1611 sotounpcb(so2) == unp2,
1612 ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1613 error = unp_connect2(so, so2, PRU_CONNECT);
1614 unp_pcb_unlock_pair(unp, unp2);
1623 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1624 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1625 unp->unp_flags &= ~UNP_CONNECTING;
1626 UNP_PCB_UNLOCK(unp);
1631 * Set socket peer credentials at connection time.
1633 * The client's PCB credentials are copied from its process structure. The
1634 * server's PCB credentials are copied from the socket on which it called
1635 * listen(2). uipc_listen cached that process's credentials at the time.
1638 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1639 struct unpcb *server_unp, struct unpcb *listen_unp)
1641 cru2xt(td, &client_unp->unp_peercred);
1642 client_unp->unp_flags |= UNP_HAVEPC;
1644 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1645 sizeof(server_unp->unp_peercred));
1646 server_unp->unp_flags |= UNP_HAVEPC;
1647 if (listen_unp->unp_flags & UNP_WANTCRED)
1648 client_unp->unp_flags |= UNP_WANTCRED;
1652 unp_connect2(struct socket *so, struct socket *so2, int req)
1657 unp = sotounpcb(so);
1658 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1659 unp2 = sotounpcb(so2);
1660 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1662 UNP_PCB_LOCK_ASSERT(unp);
1663 UNP_PCB_LOCK_ASSERT(unp2);
1664 KASSERT(unp->unp_conn == NULL,
1665 ("%s: socket %p is already connected", __func__, unp));
1667 if (so2->so_type != so->so_type)
1668 return (EPROTOTYPE);
1669 unp->unp_conn = unp2;
1672 switch (so->so_type) {
1674 UNP_REF_LIST_LOCK();
1675 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1676 UNP_REF_LIST_UNLOCK();
1681 case SOCK_SEQPACKET:
1682 KASSERT(unp2->unp_conn == NULL,
1683 ("%s: socket %p is already connected", __func__, unp2));
1684 unp2->unp_conn = unp;
1685 if (req == PRU_CONNECT &&
1686 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1694 panic("unp_connect2");
1700 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1702 struct socket *so, *so2;
1704 struct unpcb *unptmp;
1707 UNP_PCB_LOCK_ASSERT(unp);
1708 UNP_PCB_LOCK_ASSERT(unp2);
1709 KASSERT(unp->unp_conn == unp2,
1710 ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
1712 unp->unp_conn = NULL;
1713 so = unp->unp_socket;
1714 so2 = unp2->unp_socket;
1715 switch (unp->unp_socket->so_type) {
1717 UNP_REF_LIST_LOCK();
1719 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
1723 KASSERT(unptmp != NULL,
1724 ("%s: %p not found in reflist of %p", __func__, unp, unp2));
1726 LIST_REMOVE(unp, unp_reflink);
1727 UNP_REF_LIST_UNLOCK();
1730 so->so_state &= ~SS_ISCONNECTED;
1736 case SOCK_SEQPACKET:
1738 soisdisconnected(so);
1739 MPASS(unp2->unp_conn == unp);
1740 unp2->unp_conn = NULL;
1742 soisdisconnected(so2);
1747 unp_pcb_rele_notlast(unp);
1748 if (!unp_pcb_rele(unp))
1749 UNP_PCB_UNLOCK(unp);
1751 if (!unp_pcb_rele(unp))
1752 UNP_PCB_UNLOCK(unp);
1753 if (!unp_pcb_rele(unp2))
1754 UNP_PCB_UNLOCK(unp2);
1759 * unp_pcblist() walks the global list of struct unpcb's to generate a
1760 * pointer list, bumping the refcount on each unpcb. It then copies them out
1761 * sequentially, validating the generation number on each to see if it has
1762 * been detached. All of this is necessary because copyout() may sleep on
1766 unp_pcblist(SYSCTL_HANDLER_ARGS)
1768 struct unpcb *unp, **unp_list;
1770 struct xunpgen *xug;
1771 struct unp_head *head;
1776 switch ((intptr_t)arg1) {
1785 case SOCK_SEQPACKET:
1790 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1794 * The process of preparing the PCB list is too time-consuming and
1795 * resource-intensive to repeat twice on every request.
1797 if (req->oldptr == NULL) {
1799 req->oldidx = 2 * (sizeof *xug)
1800 + (n + n/8) * sizeof(struct xunpcb);
1804 if (req->newptr != NULL)
1808 * OK, now we're committed to doing something.
1810 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1812 gencnt = unp_gencnt;
1816 xug->xug_len = sizeof *xug;
1818 xug->xug_gen = gencnt;
1819 xug->xug_sogen = so_gencnt;
1820 error = SYSCTL_OUT(req, xug, sizeof *xug);
1826 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1829 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1830 unp = LIST_NEXT(unp, unp_link)) {
1832 if (unp->unp_gencnt <= gencnt) {
1833 if (cr_cansee(req->td->td_ucred,
1834 unp->unp_socket->so_cred)) {
1835 UNP_PCB_UNLOCK(unp);
1838 unp_list[i++] = unp;
1841 UNP_PCB_UNLOCK(unp);
1844 n = i; /* In case we lost some during malloc. */
1847 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1848 for (i = 0; i < n; i++) {
1851 if (unp_pcb_rele(unp))
1854 if (unp->unp_gencnt <= gencnt) {
1855 xu->xu_len = sizeof *xu;
1856 xu->xu_unpp = (uintptr_t)unp;
1858 * XXX - need more locking here to protect against
1859 * connect/disconnect races for SMP.
1861 if (unp->unp_addr != NULL)
1862 bcopy(unp->unp_addr, &xu->xu_addr,
1863 unp->unp_addr->sun_len);
1865 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1866 if (unp->unp_conn != NULL &&
1867 unp->unp_conn->unp_addr != NULL)
1868 bcopy(unp->unp_conn->unp_addr,
1870 unp->unp_conn->unp_addr->sun_len);
1872 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
1873 xu->unp_vnode = (uintptr_t)unp->unp_vnode;
1874 xu->unp_conn = (uintptr_t)unp->unp_conn;
1875 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
1876 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
1877 xu->unp_gencnt = unp->unp_gencnt;
1878 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1879 UNP_PCB_UNLOCK(unp);
1880 error = SYSCTL_OUT(req, xu, sizeof *xu);
1882 UNP_PCB_UNLOCK(unp);
1888 * Give the user an updated idea of our state. If the
1889 * generation differs from what we told her before, she knows
1890 * that something happened while we were processing this
1891 * request, and it might be necessary to retry.
1893 xug->xug_gen = unp_gencnt;
1894 xug->xug_sogen = so_gencnt;
1895 xug->xug_count = unp_count;
1896 error = SYSCTL_OUT(req, xug, sizeof *xug);
1898 free(unp_list, M_TEMP);
1903 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1904 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1905 "List of active local datagram sockets");
1906 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1907 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1908 "List of active local stream sockets");
1909 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1910 CTLTYPE_OPAQUE | CTLFLAG_RD,
1911 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1912 "List of active local seqpacket sockets");
1915 unp_shutdown(struct unpcb *unp)
1920 UNP_PCB_LOCK_ASSERT(unp);
1922 unp2 = unp->unp_conn;
1923 if ((unp->unp_socket->so_type == SOCK_STREAM ||
1924 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1925 so = unp2->unp_socket;
1932 unp_drop(struct unpcb *unp)
1934 struct socket *so = unp->unp_socket;
1938 * Regardless of whether the socket's peer dropped the connection
1939 * with this socket by aborting or disconnecting, POSIX requires
1940 * that ECONNRESET is returned.
1945 so->so_error = ECONNRESET;
1946 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1947 /* Last reference dropped in unp_disconnect(). */
1948 unp_pcb_rele_notlast(unp);
1949 unp_disconnect(unp, unp2);
1950 } else if (!unp_pcb_rele(unp)) {
1951 UNP_PCB_UNLOCK(unp);
1956 unp_freerights(struct filedescent **fdep, int fdcount)
1961 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
1963 for (i = 0; i < fdcount; i++) {
1964 fp = fdep[i]->fde_file;
1965 filecaps_free(&fdep[i]->fde_caps);
1968 free(fdep[0], M_FILECAPS);
1972 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
1974 struct thread *td = curthread; /* XXX */
1975 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1978 struct filedesc *fdesc = td->td_proc->p_fd;
1979 struct filedescent **fdep;
1981 socklen_t clen = control->m_len, datalen;
1985 UNP_LINK_UNLOCK_ASSERT();
1988 if (controlp != NULL) /* controlp == NULL => free control messages */
1990 while (cm != NULL) {
1991 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1995 data = CMSG_DATA(cm);
1996 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1997 if (cm->cmsg_level == SOL_SOCKET
1998 && cm->cmsg_type == SCM_RIGHTS) {
1999 newfds = datalen / sizeof(*fdep);
2004 /* If we're not outputting the descriptors free them. */
2005 if (error || controlp == NULL) {
2006 unp_freerights(fdep, newfds);
2009 FILEDESC_XLOCK(fdesc);
2012 * Now change each pointer to an fd in the global
2013 * table to an integer that is the index to the local
2014 * fd table entry that we set up to point to the
2015 * global one we are transferring.
2017 newlen = newfds * sizeof(int);
2018 *controlp = sbcreatecontrol(NULL, newlen,
2019 SCM_RIGHTS, SOL_SOCKET);
2020 if (*controlp == NULL) {
2021 FILEDESC_XUNLOCK(fdesc);
2023 unp_freerights(fdep, newfds);
2028 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2029 if (fdallocn(td, 0, fdp, newfds) != 0) {
2030 FILEDESC_XUNLOCK(fdesc);
2032 unp_freerights(fdep, newfds);
2037 for (i = 0; i < newfds; i++, fdp++) {
2038 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2039 (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
2040 &fdep[i]->fde_caps);
2041 unp_externalize_fp(fdep[i]->fde_file);
2045 * The new type indicates that the mbuf data refers to
2046 * kernel resources that may need to be released before
2047 * the mbuf is freed.
2049 m_chtype(*controlp, MT_EXTCONTROL);
2050 FILEDESC_XUNLOCK(fdesc);
2051 free(fdep[0], M_FILECAPS);
2053 /* We can just copy anything else across. */
2054 if (error || controlp == NULL)
2056 *controlp = sbcreatecontrol(NULL, datalen,
2057 cm->cmsg_type, cm->cmsg_level);
2058 if (*controlp == NULL) {
2063 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2066 controlp = &(*controlp)->m_next;
2069 if (CMSG_SPACE(datalen) < clen) {
2070 clen -= CMSG_SPACE(datalen);
2071 cm = (struct cmsghdr *)
2072 ((caddr_t)cm + CMSG_SPACE(datalen));
2084 unp_zone_change(void *tag)
2087 uma_zone_set_max(unp_zone, maxsockets);
2092 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2098 KASSERT(LIST_EMPTY(&unp->unp_refs),
2099 ("%s: unpcb %p has lingering refs", __func__, unp));
2100 KASSERT(unp->unp_socket == NULL,
2101 ("%s: unpcb %p has socket backpointer", __func__, unp));
2102 KASSERT(unp->unp_vnode == NULL,
2103 ("%s: unpcb %p has vnode references", __func__, unp));
2104 KASSERT(unp->unp_conn == NULL,
2105 ("%s: unpcb %p is still connected", __func__, unp));
2106 KASSERT(unp->unp_addr == NULL,
2107 ("%s: unpcb %p has leaked addr", __func__, unp));
2117 if (!IS_DEFAULT_VNET(curvnet))
2126 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2127 NULL, NULL, UMA_ALIGN_CACHE, 0);
2128 uma_zone_set_max(unp_zone, maxsockets);
2129 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2130 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2131 NULL, EVENTHANDLER_PRI_ANY);
2132 LIST_INIT(&unp_dhead);
2133 LIST_INIT(&unp_shead);
2134 LIST_INIT(&unp_sphead);
2135 SLIST_INIT(&unp_defers);
2136 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2137 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2138 UNP_LINK_LOCK_INIT();
2139 UNP_DEFERRED_LOCK_INIT();
2143 unp_internalize_cleanup_rights(struct mbuf *control)
2150 for (m = control; m != NULL; m = m->m_next) {
2151 cp = mtod(m, struct cmsghdr *);
2152 if (cp->cmsg_level != SOL_SOCKET ||
2153 cp->cmsg_type != SCM_RIGHTS)
2155 data = CMSG_DATA(cp);
2156 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2157 unp_freerights(data, datalen / sizeof(struct filedesc *));
2162 unp_internalize(struct mbuf **controlp, struct thread *td)
2164 struct mbuf *control, **initial_controlp;
2166 struct filedesc *fdesc;
2169 struct cmsgcred *cmcred;
2170 struct filedescent *fde, **fdep, *fdev;
2173 struct timespec *ts;
2175 socklen_t clen, datalen;
2176 int i, j, error, *fdp, oldfds;
2179 UNP_LINK_UNLOCK_ASSERT();
2184 control = *controlp;
2185 clen = control->m_len;
2187 initial_controlp = controlp;
2188 for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
2189 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2190 || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
2194 data = CMSG_DATA(cm);
2195 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2197 switch (cm->cmsg_type) {
2199 * Fill in credential information.
2202 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2203 SCM_CREDS, SOL_SOCKET);
2204 if (*controlp == NULL) {
2208 cmcred = (struct cmsgcred *)
2209 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2210 cmcred->cmcred_pid = p->p_pid;
2211 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2212 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2213 cmcred->cmcred_euid = td->td_ucred->cr_uid;
2214 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2216 for (i = 0; i < cmcred->cmcred_ngroups; i++)
2217 cmcred->cmcred_groups[i] =
2218 td->td_ucred->cr_groups[i];
2222 oldfds = datalen / sizeof (int);
2226 * Check that all the FDs passed in refer to legal
2227 * files. If not, reject the entire operation.
2230 FILEDESC_SLOCK(fdesc);
2231 for (i = 0; i < oldfds; i++, fdp++) {
2232 fp = fget_locked(fdesc, *fdp);
2234 FILEDESC_SUNLOCK(fdesc);
2238 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2239 FILEDESC_SUNLOCK(fdesc);
2247 * Now replace the integer FDs with pointers to the
2248 * file structure and capability rights.
2250 newlen = oldfds * sizeof(fdep[0]);
2251 *controlp = sbcreatecontrol(NULL, newlen,
2252 SCM_RIGHTS, SOL_SOCKET);
2253 if (*controlp == NULL) {
2254 FILEDESC_SUNLOCK(fdesc);
2259 for (i = 0; i < oldfds; i++, fdp++) {
2260 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2262 for (j = 0; j < i; j++, fdp++) {
2263 fdrop(fdesc->fd_ofiles[*fdp].
2266 FILEDESC_SUNLOCK(fdesc);
2272 fdep = (struct filedescent **)
2273 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2274 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2276 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2277 fde = &fdesc->fd_ofiles[*fdp];
2279 fdep[i]->fde_file = fde->fde_file;
2280 filecaps_copy(&fde->fde_caps,
2281 &fdep[i]->fde_caps, true);
2282 unp_internalize_fp(fdep[i]->fde_file);
2284 FILEDESC_SUNLOCK(fdesc);
2288 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2289 SCM_TIMESTAMP, SOL_SOCKET);
2290 if (*controlp == NULL) {
2294 tv = (struct timeval *)
2295 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2300 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2301 SCM_BINTIME, SOL_SOCKET);
2302 if (*controlp == NULL) {
2306 bt = (struct bintime *)
2307 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2312 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2313 SCM_REALTIME, SOL_SOCKET);
2314 if (*controlp == NULL) {
2318 ts = (struct timespec *)
2319 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2324 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2325 SCM_MONOTONIC, SOL_SOCKET);
2326 if (*controlp == NULL) {
2330 ts = (struct timespec *)
2331 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2340 if (*controlp != NULL)
2341 controlp = &(*controlp)->m_next;
2342 if (CMSG_SPACE(datalen) < clen) {
2343 clen -= CMSG_SPACE(datalen);
2344 cm = (struct cmsghdr *)
2345 ((caddr_t)cm + CMSG_SPACE(datalen));
2353 if (error != 0 && initial_controlp != NULL)
2354 unp_internalize_cleanup_rights(*initial_controlp);
2359 static struct mbuf *
2360 unp_addsockcred(struct thread *td, struct mbuf *control)
2362 struct mbuf *m, *n, *n_prev;
2363 struct sockcred *sc;
2364 const struct cmsghdr *cm;
2368 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2369 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2373 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2374 sc->sc_uid = td->td_ucred->cr_ruid;
2375 sc->sc_euid = td->td_ucred->cr_uid;
2376 sc->sc_gid = td->td_ucred->cr_rgid;
2377 sc->sc_egid = td->td_ucred->cr_gid;
2378 sc->sc_ngroups = ngroups;
2379 for (i = 0; i < sc->sc_ngroups; i++)
2380 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2383 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2384 * created SCM_CREDS control message (struct sockcred) has another
2387 if (control != NULL)
2388 for (n = control, n_prev = NULL; n != NULL;) {
2389 cm = mtod(n, struct cmsghdr *);
2390 if (cm->cmsg_level == SOL_SOCKET &&
2391 cm->cmsg_type == SCM_CREDS) {
2393 control = n->m_next;
2395 n_prev->m_next = n->m_next;
2403 /* Prepend it to the head. */
2404 m->m_next = control;
2408 static struct unpcb *
2409 fptounp(struct file *fp)
2413 if (fp->f_type != DTYPE_SOCKET)
2415 if ((so = fp->f_data) == NULL)
2417 if (so->so_proto->pr_domain != &localdomain)
2419 return sotounpcb(so);
2423 unp_discard(struct file *fp)
2425 struct unp_defer *dr;
2427 if (unp_externalize_fp(fp)) {
2428 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2430 UNP_DEFERRED_LOCK();
2431 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2432 UNP_DEFERRED_UNLOCK();
2433 atomic_add_int(&unp_defers_count, 1);
2434 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2436 (void) closef(fp, (struct thread *)NULL);
2440 unp_process_defers(void *arg __unused, int pending)
2442 struct unp_defer *dr;
2443 SLIST_HEAD(, unp_defer) drl;
2448 UNP_DEFERRED_LOCK();
2449 if (SLIST_FIRST(&unp_defers) == NULL) {
2450 UNP_DEFERRED_UNLOCK();
2453 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2454 UNP_DEFERRED_UNLOCK();
2456 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2457 SLIST_REMOVE_HEAD(&drl, ud_link);
2458 closef(dr->ud_fp, NULL);
2462 atomic_add_int(&unp_defers_count, -count);
2467 unp_internalize_fp(struct file *fp)
2472 if ((unp = fptounp(fp)) != NULL) {
2474 unp->unp_msgcount++;
2481 unp_externalize_fp(struct file *fp)
2487 if ((unp = fptounp(fp)) != NULL) {
2488 unp->unp_msgcount--;
2498 * unp_defer indicates whether additional work has been defered for a future
2499 * pass through unp_gc(). It is thread local and does not require explicit
2502 static int unp_marked;
2503 static int unp_unreachable;
2506 unp_accessable(struct filedescent **fdep, int fdcount)
2512 for (i = 0; i < fdcount; i++) {
2513 fp = fdep[i]->fde_file;
2514 if ((unp = fptounp(fp)) == NULL)
2516 if (unp->unp_gcflag & UNPGC_REF)
2518 unp->unp_gcflag &= ~UNPGC_DEAD;
2519 unp->unp_gcflag |= UNPGC_REF;
2525 unp_gc_process(struct unpcb *unp)
2527 struct socket *so, *soa;
2530 /* Already processed. */
2531 if (unp->unp_gcflag & UNPGC_SCANNED)
2536 * Check for a socket potentially in a cycle. It must be in a
2537 * queue as indicated by msgcount, and this must equal the file
2538 * reference count. Note that when msgcount is 0 the file is NULL.
2540 if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2541 unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2542 unp->unp_gcflag |= UNPGC_DEAD;
2547 so = unp->unp_socket;
2549 if (SOLISTENING(so)) {
2551 * Mark all sockets in our accept queue.
2553 TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2554 if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2556 SOCKBUF_LOCK(&soa->so_rcv);
2557 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2558 SOCKBUF_UNLOCK(&soa->so_rcv);
2562 * Mark all sockets we reference with RIGHTS.
2564 if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2565 SOCKBUF_LOCK(&so->so_rcv);
2566 unp_scan(so->so_rcv.sb_mb, unp_accessable);
2567 SOCKBUF_UNLOCK(&so->so_rcv);
2571 unp->unp_gcflag |= UNPGC_SCANNED;
2574 static int unp_recycled;
2575 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2576 "Number of unreachable sockets claimed by the garbage collector.");
2578 static int unp_taskcount;
2579 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2580 "Number of times the garbage collector has run.");
2583 unp_gc(__unused void *arg, int pending)
2585 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2587 struct unp_head **head;
2588 struct file *f, **unref;
2595 * First clear all gc flags from previous runs, apart from
2596 * UNPGC_IGNORE_RIGHTS.
2598 for (head = heads; *head != NULL; head++)
2599 LIST_FOREACH(unp, *head, unp_link)
2601 (unp->unp_gcflag & UNPGC_IGNORE_RIGHTS);
2604 * Scan marking all reachable sockets with UNPGC_REF. Once a socket
2605 * is reachable all of the sockets it references are reachable.
2606 * Stop the scan once we do a complete loop without discovering
2607 * a new reachable socket.
2610 unp_unreachable = 0;
2612 for (head = heads; *head != NULL; head++)
2613 LIST_FOREACH(unp, *head, unp_link)
2614 unp_gc_process(unp);
2615 } while (unp_marked);
2617 if (unp_unreachable == 0)
2621 * Allocate space for a local list of dead unpcbs.
2623 unref = malloc(unp_unreachable * sizeof(struct file *),
2627 * Iterate looking for sockets which have been specifically marked
2628 * as as unreachable and store them locally.
2631 for (total = 0, head = heads; *head != NULL; head++)
2632 LIST_FOREACH(unp, *head, unp_link)
2633 if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
2635 if (unp->unp_msgcount == 0 || f == NULL ||
2636 f->f_count != unp->unp_msgcount ||
2640 KASSERT(total <= unp_unreachable,
2641 ("unp_gc: incorrect unreachable count."));
2646 * Now flush all sockets, free'ing rights. This will free the
2647 * struct files associated with these sockets but leave each socket
2648 * with one remaining ref.
2650 for (i = 0; i < total; i++) {
2653 so = unref[i]->f_data;
2654 CURVNET_SET(so->so_vnet);
2660 * And finally release the sockets so they can be reclaimed.
2662 for (i = 0; i < total; i++)
2663 fdrop(unref[i], NULL);
2664 unp_recycled += total;
2665 free(unref, M_TEMP);
2669 unp_dispose_mbuf(struct mbuf *m)
2673 unp_scan(m, unp_freerights);
2677 * Synchronize against unp_gc, which can trip over data as we are freeing it.
2680 unp_dispose(struct socket *so)
2684 unp = sotounpcb(so);
2686 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2688 if (!SOLISTENING(so))
2689 unp_dispose_mbuf(so->so_rcv.sb_mb);
2693 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2698 socklen_t clen, datalen;
2700 while (m0 != NULL) {
2701 for (m = m0; m; m = m->m_next) {
2702 if (m->m_type != MT_CONTROL)
2705 cm = mtod(m, struct cmsghdr *);
2708 while (cm != NULL) {
2709 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2712 data = CMSG_DATA(cm);
2713 datalen = (caddr_t)cm + cm->cmsg_len
2716 if (cm->cmsg_level == SOL_SOCKET &&
2717 cm->cmsg_type == SCM_RIGHTS) {
2718 (*op)(data, datalen /
2719 sizeof(struct filedescent *));
2722 if (CMSG_SPACE(datalen) < clen) {
2723 clen -= CMSG_SPACE(datalen);
2724 cm = (struct cmsghdr *)
2725 ((caddr_t)cm + CMSG_SPACE(datalen));
2737 * A helper function called by VFS before socket-type vnode reclamation.
2738 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2742 vfs_unp_reclaim(struct vnode *vp)
2748 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2749 KASSERT(vp->v_type == VSOCK,
2750 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2753 vplock = mtx_pool_find(mtxpool_sleep, vp);
2755 VOP_UNP_CONNECT(vp, &unp);
2759 if (unp->unp_vnode == vp) {
2761 unp->unp_vnode = NULL;
2764 UNP_PCB_UNLOCK(unp);
2773 db_print_indent(int indent)
2777 for (i = 0; i < indent; i++)
2782 db_print_unpflags(int unp_flags)
2787 if (unp_flags & UNP_HAVEPC) {
2788 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2791 if (unp_flags & UNP_WANTCRED) {
2792 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2795 if (unp_flags & UNP_CONNWAIT) {
2796 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2799 if (unp_flags & UNP_CONNECTING) {
2800 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2803 if (unp_flags & UNP_BINDING) {
2804 db_printf("%sUNP_BINDING", comma ? ", " : "");
2810 db_print_xucred(int indent, struct xucred *xu)
2814 db_print_indent(indent);
2815 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n",
2816 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
2817 db_print_indent(indent);
2818 db_printf("cr_groups: ");
2820 for (i = 0; i < xu->cr_ngroups; i++) {
2821 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2828 db_print_unprefs(int indent, struct unp_head *uh)
2834 LIST_FOREACH(unp, uh, unp_reflink) {
2835 if (counter % 4 == 0)
2836 db_print_indent(indent);
2837 db_printf("%p ", unp);
2838 if (counter % 4 == 3)
2842 if (counter != 0 && counter % 4 != 0)
2846 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2851 db_printf("usage: show unpcb <addr>\n");
2854 unp = (struct unpcb *)addr;
2856 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2859 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2862 db_printf("unp_refs:\n");
2863 db_print_unprefs(2, &unp->unp_refs);
2865 /* XXXRW: Would be nice to print the full address, if any. */
2866 db_printf("unp_addr: %p\n", unp->unp_addr);
2868 db_printf("unp_gencnt: %llu\n",
2869 (unsigned long long)unp->unp_gencnt);
2871 db_printf("unp_flags: %x (", unp->unp_flags);
2872 db_print_unpflags(unp->unp_flags);
2875 db_printf("unp_peercred:\n");
2876 db_print_xucred(2, &unp->unp_peercred);
2878 db_printf("unp_refcount: %u\n", unp->unp_refcount);