2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
30 * $FreeBSD: src/sys/kern/uipc_usrreq.c,v 1.54.2.10 2003/03/04 17:28:09 nectar Exp $
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/domain.h>
37 #include <sys/fcntl.h>
38 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
41 #include <sys/filedesc.h>
43 #include <sys/nlookup.h>
44 #include <sys/protosw.h>
45 #include <sys/socket.h>
46 #include <sys/socketvar.h>
47 #include <sys/resourcevar.h>
49 #include <sys/mount.h>
50 #include <sys/sysctl.h>
52 #include <sys/unpcb.h>
53 #include <sys/vnode.h>
54 #include <sys/kern_syscall.h>
55 #include <sys/taskqueue.h>
57 #include <sys/file2.h>
58 #include <sys/spinlock2.h>
59 #include <sys/socketvar2.h>
60 #include <sys/msgport2.h>
63 * Unix communications domain.
67 * rethink name space problems
68 * need a proper out-of-band
72 * Unix domain sockets GC.
74 * It was originally designed to address following three cases:
75 * 1) Receiving unix domain socket can not accept the rights, e.g.
76 * when the so_rcv is full.
77 * 2) Caller of recvmsg(2) does not pass buffer to receive rights.
78 * 3) Unix domain sockets loop reference, e.g. s1 is on s2.so_rcv,
79 * while s2 on s1.so_rcv.
81 * Code under UNP_GC_ALLFILES is intended to address all above three
82 * cases. However, 1) was addressed a long time ago in uipc_send()
83 * (we inheritted the fix from FreeBSD when DragonFly forked). 2)
84 * was addressed in soreceive() by git-e62cfe62. 3) is the only
85 * case that needs GC. The new code (!UNP_GC_ALLFILES) addresses
86 * case 3) in the following way:
87 * - Record the struct file in unpcb, if the Unix domain socket is
88 * passed as one of the rights.
89 * - At GC time, only unpcbs are scanned, and only Unix domain sockets
90 * that are still used as rights are potential GC targets.
93 #define UNP_DETACHED UNP_PRIVATE1
94 #define UNP_CONNECTING UNP_PRIVATE2
95 #define UNP_DROPPED UNP_PRIVATE3
96 #define UNP_MARKER UNP_PRIVATE4
98 #define UNPGC_REF 0x1 /* unpcb has external ref. */
99 #define UNPGC_DEAD 0x2 /* unpcb might be dead. */
100 #define UNPGC_SCANNED 0x4 /* Has been scanned. */
102 #define UNP_GCFILE_MAX 256
104 /* For unp_internalize() and unp_externalize() */
105 CTASSERT(sizeof(struct file
*) >= sizeof(int));
107 #define UNP_ISATTACHED(unp) \
108 ((unp) != NULL && ((unp)->unp_flags & UNP_DETACHED) == 0)
111 #define UNP_ASSERT_TOKEN_HELD(unp) \
112 ASSERT_LWKT_TOKEN_HELD(lwkt_token_pool_lookup((unp)))
113 #else /* !INVARIANTS */
114 #define UNP_ASSERT_TOKEN_HELD(unp)
115 #endif /* INVARIANTS */
117 struct unp_defdiscard
{
118 SLIST_ENTRY(unp_defdiscard
) next
;
121 SLIST_HEAD(unp_defdiscard_list
, unp_defdiscard
);
123 TAILQ_HEAD(unpcb_qhead
, unpcb
);
124 struct unp_global_head
{
125 struct unpcb_qhead list
;
129 static MALLOC_DEFINE(M_UNPCB
, "unpcb", "unpcb struct");
130 static unp_gen_t unp_gencnt
;
132 static struct unp_global_head unp_stream_head
;
133 static struct unp_global_head unp_dgram_head
;
134 static struct unp_global_head unp_seqpkt_head
;
136 static struct unp_global_head
* const unp_heads
[] =
137 { &unp_stream_head
, &unp_dgram_head
, &unp_seqpkt_head
, NULL
};
139 static struct lwkt_token unp_token
= LWKT_TOKEN_INITIALIZER(unp_token
);
140 static struct taskqueue
*unp_taskqueue
;
142 static struct unp_defdiscard_list unp_defdiscard_head
;
143 static struct spinlock unp_defdiscard_spin
;
144 static struct task unp_defdiscard_task
;
146 static struct sockaddr sun_noname
= { sizeof(sun_noname
), AF_LOCAL
};
147 static ino_t unp_ino
= 1; /* prototype for fake inode numbers */
149 static int unp_attach (struct socket
*, struct pru_attach_info
*);
150 static void unp_detach (struct unpcb
*);
151 static int unp_bind (struct unpcb
*,struct sockaddr
*, struct thread
*);
152 static int unp_connect (struct socket
*,struct sockaddr
*,
154 static void unp_disconnect(struct unpcb
*, int);
155 static void unp_shutdown (struct unpcb
*);
156 static void unp_gc(void *, int);
157 #ifdef UNP_GC_ALLFILES
158 static int unp_gc_clearmarks(struct file
*, void *);
159 static int unp_gc_checkmarks(struct file
*, void *);
160 static int unp_gc_checkrefs(struct file
*, void *);
161 static void unp_mark(struct file
*, void *data
);
163 static void unp_scan (struct mbuf
*, void (*)(struct file
*, void *),
165 static void unp_discard (struct file
*, void *);
166 static int unp_internalize (struct mbuf
*, struct thread
*);
167 static int unp_listen (struct unpcb
*, struct thread
*);
168 static void unp_fp_externalize(struct lwp
*lp
, struct file
*fp
, int fd
,
170 static int unp_find_lockref(struct sockaddr
*nam
, struct thread
*td
,
171 short type
, struct unpcb
**unp_ret
);
172 static int unp_connect_pair(struct unpcb
*unp
, struct unpcb
*unp2
);
173 static void unp_drop(struct unpcb
*unp
, int error
);
174 static void unp_defdiscard_taskfunc(void *, int);
176 static int unp_rights
; /* file descriptors in flight */
177 static struct lwkt_token unp_rights_token
=
178 LWKT_TOKEN_INITIALIZER(unp_rights_token
);
179 static struct task unp_gc_task
;
180 static struct unpcb
*unp_gc_marker
;
182 SYSCTL_DECL(_net_local
);
183 SYSCTL_INT(_net_local
, OID_AUTO
, inflight
, CTLFLAG_RD
, &unp_rights
, 0,
184 "File descriptors in flight");
187 * SMP Considerations:
189 * Since unp_token will be automaticly released upon execution of
190 * blocking code, we need to reference unp_conn before any possible
191 * blocking code to prevent it from being ripped behind our back.
193 * Any adjustment to unp->unp_conn requires both the global unp_token
194 * AND the per-unp token (lwkt_token_pool_lookup(unp)) to be held.
196 * Any access to so_pcb to obtain unp requires the pool token for
201 unp_reference(struct unpcb
*unp
)
203 /* 0->1 transition will not work */
204 KKASSERT(unp
->unp_refcnt
> 0);
205 atomic_add_int(&unp
->unp_refcnt
, 1);
209 unp_free(struct unpcb
*unp
)
211 KKASSERT(unp
->unp_refcnt
> 0);
212 if (atomic_fetchadd_int(&unp
->unp_refcnt
, -1) == 1)
216 static __inline
struct unpcb
*
217 unp_getsocktoken(struct socket
*so
)
222 * The unp pointer is invalid until we verify that it is
223 * good by re-checking so_pcb AFTER obtaining the token.
225 while ((unp
= so
->so_pcb
) != NULL
) {
226 lwkt_getpooltoken(unp
);
227 if (unp
== so
->so_pcb
)
229 lwkt_relpooltoken(unp
);
235 unp_reltoken(struct unpcb
*unp
)
238 lwkt_relpooltoken(unp
);
242 unp_setflags(struct unpcb
*unp
, int flags
)
244 atomic_set_int(&unp
->unp_flags
, flags
);
248 unp_clrflags(struct unpcb
*unp
, int flags
)
250 atomic_clear_int(&unp
->unp_flags
, flags
);
253 static __inline
struct unp_global_head
*
254 unp_globalhead(short type
)
258 return &unp_stream_head
;
260 return &unp_dgram_head
;
262 return &unp_seqpkt_head
;
264 panic("unknown socket type %d", type
);
268 static __inline
struct unpcb
*
269 unp_fp2unpcb(struct file
*fp
)
273 if (fp
->f_type
!= DTYPE_SOCKET
)
280 if (so
->so_proto
->pr_domain
!= &localdomain
)
287 unp_add_right(struct file
*fp
)
291 ASSERT_LWKT_TOKEN_HELD(&unp_rights_token
);
292 KASSERT(fp
->f_count
> 0, ("invalid f_count %d", fp
->f_count
));
294 unp
= unp_fp2unpcb(fp
);
304 unp_del_right(struct file
*fp
)
308 ASSERT_LWKT_TOKEN_HELD(&unp_rights_token
);
309 KASSERT(fp
->f_count
> 0, ("invalid f_count %d", fp
->f_count
));
311 unp
= unp_fp2unpcb(fp
);
313 KASSERT(unp
->unp_msgcount
> 0,
314 ("invalid unp msgcount %d", unp
->unp_msgcount
));
316 if (unp
->unp_msgcount
== 0)
324 * NOTE: (so) is referenced from soabort*() and netmsg_pru_abort()
325 * will sofree() it when we return.
328 uipc_abort(netmsg_t msg
)
333 lwkt_gettoken(&unp_token
);
334 unp
= unp_getsocktoken(msg
->base
.nm_so
);
336 if (UNP_ISATTACHED(unp
)) {
337 unp_drop(unp
, ECONNABORTED
);
344 lwkt_reltoken(&unp_token
);
346 lwkt_replymsg(&msg
->lmsg
, error
);
350 uipc_accept(netmsg_t msg
)
355 lwkt_gettoken(&unp_token
);
356 unp
= unp_getsocktoken(msg
->base
.nm_so
);
358 if (!UNP_ISATTACHED(unp
)) {
361 struct unpcb
*unp2
= unp
->unp_conn
;
364 * Pass back name of connected socket,
365 * if it was bound and we are still connected
366 * (our peer may have closed already!).
368 if (unp2
&& unp2
->unp_addr
) {
370 *msg
->accept
.nm_nam
= dup_sockaddr(
371 (struct sockaddr
*)unp2
->unp_addr
);
374 *msg
->accept
.nm_nam
= dup_sockaddr(&sun_noname
);
380 lwkt_reltoken(&unp_token
);
382 lwkt_replymsg(&msg
->lmsg
, error
);
386 uipc_attach(netmsg_t msg
)
390 lwkt_gettoken(&unp_token
);
392 KASSERT(msg
->base
.nm_so
->so_pcb
== NULL
, ("double unp attach"));
393 error
= unp_attach(msg
->base
.nm_so
, msg
->attach
.nm_ai
);
395 lwkt_reltoken(&unp_token
);
396 lwkt_replymsg(&msg
->lmsg
, error
);
400 uipc_bind(netmsg_t msg
)
405 lwkt_gettoken(&unp_token
);
406 unp
= unp_getsocktoken(msg
->base
.nm_so
);
408 if (UNP_ISATTACHED(unp
))
409 error
= unp_bind(unp
, msg
->bind
.nm_nam
, msg
->bind
.nm_td
);
414 lwkt_reltoken(&unp_token
);
416 lwkt_replymsg(&msg
->lmsg
, error
);
420 uipc_connect(netmsg_t msg
)
424 error
= unp_connect(msg
->base
.nm_so
, msg
->connect
.nm_nam
,
426 lwkt_replymsg(&msg
->lmsg
, error
);
430 uipc_connect2(netmsg_t msg
)
434 error
= unp_connect2(msg
->connect2
.nm_so1
, msg
->connect2
.nm_so2
);
435 lwkt_replymsg(&msg
->lmsg
, error
);
438 /* control is EOPNOTSUPP */
441 uipc_detach(netmsg_t msg
)
446 lwkt_gettoken(&unp_token
);
447 unp
= unp_getsocktoken(msg
->base
.nm_so
);
449 if (UNP_ISATTACHED(unp
)) {
457 lwkt_reltoken(&unp_token
);
459 lwkt_replymsg(&msg
->lmsg
, error
);
463 uipc_disconnect(netmsg_t msg
)
468 lwkt_gettoken(&unp_token
);
469 unp
= unp_getsocktoken(msg
->base
.nm_so
);
471 if (UNP_ISATTACHED(unp
)) {
472 unp_disconnect(unp
, 0);
479 lwkt_reltoken(&unp_token
);
481 lwkt_replymsg(&msg
->lmsg
, error
);
485 uipc_listen(netmsg_t msg
)
490 lwkt_gettoken(&unp_token
);
491 unp
= unp_getsocktoken(msg
->base
.nm_so
);
493 if (!UNP_ISATTACHED(unp
) || unp
->unp_vnode
== NULL
)
496 error
= unp_listen(unp
, msg
->listen
.nm_td
);
499 lwkt_reltoken(&unp_token
);
501 lwkt_replymsg(&msg
->lmsg
, error
);
505 uipc_peeraddr(netmsg_t msg
)
510 lwkt_gettoken(&unp_token
);
511 unp
= unp_getsocktoken(msg
->base
.nm_so
);
513 if (!UNP_ISATTACHED(unp
)) {
515 } else if (unp
->unp_conn
&& unp
->unp_conn
->unp_addr
) {
516 struct unpcb
*unp2
= unp
->unp_conn
;
519 *msg
->peeraddr
.nm_nam
= dup_sockaddr(
520 (struct sockaddr
*)unp2
->unp_addr
);
525 * XXX: It seems that this test always fails even when
526 * connection is established. So, this else clause is
527 * added as workaround to return PF_LOCAL sockaddr.
529 *msg
->peeraddr
.nm_nam
= dup_sockaddr(&sun_noname
);
534 lwkt_reltoken(&unp_token
);
536 lwkt_replymsg(&msg
->lmsg
, error
);
540 uipc_rcvd(netmsg_t msg
)
542 struct unpcb
*unp
, *unp2
;
548 * so_pcb is only modified with both the global and the unp
551 so
= msg
->base
.nm_so
;
552 unp
= unp_getsocktoken(so
);
554 if (!UNP_ISATTACHED(unp
)) {
559 switch (so
->so_type
) {
561 panic("uipc_rcvd DGRAM?");
565 if (unp
->unp_conn
== NULL
)
567 unp2
= unp
->unp_conn
; /* protected by pool token */
570 * Because we are transfering mbufs directly to the
571 * peer socket we have to use SSB_STOP on the sender
572 * to prevent it from building up infinite mbufs.
574 * As in several places in this module w ehave to ref unp2
575 * to ensure that it does not get ripped out from under us
576 * if we block on the so2 token or in sowwakeup().
578 so2
= unp2
->unp_socket
;
580 lwkt_gettoken(&so2
->so_rcv
.ssb_token
);
581 if (so
->so_rcv
.ssb_cc
< so2
->so_snd
.ssb_hiwat
&&
582 so
->so_rcv
.ssb_mbcnt
< so2
->so_snd
.ssb_mbmax
584 atomic_clear_int(&so2
->so_snd
.ssb_flags
, SSB_STOP
);
588 lwkt_reltoken(&so2
->so_rcv
.ssb_token
);
592 panic("uipc_rcvd unknown socktype");
598 lwkt_replymsg(&msg
->lmsg
, error
);
601 /* pru_rcvoob is EOPNOTSUPP */
604 uipc_send(netmsg_t msg
)
606 struct unpcb
*unp
, *unp2
;
609 struct mbuf
*control
;
613 so
= msg
->base
.nm_so
;
614 control
= msg
->send
.nm_control
;
618 * so_pcb is only modified with both the global and the unp
621 so
= msg
->base
.nm_so
;
622 unp
= unp_getsocktoken(so
);
624 if (!UNP_ISATTACHED(unp
)) {
629 if (msg
->send
.nm_flags
& PRUS_OOB
) {
634 wakeup_start_delayed();
636 if (control
&& (error
= unp_internalize(control
, msg
->send
.nm_td
)))
639 switch (so
->so_type
) {
642 struct sockaddr
*from
;
644 if (msg
->send
.nm_addr
) {
649 lwkt_gettoken(&unp_token
);
650 error
= unp_find_lockref(msg
->send
.nm_addr
,
651 msg
->send
.nm_td
, so
->so_type
, &unp2
);
653 lwkt_reltoken(&unp_token
);
658 * unp2 is locked and referenced.
660 * We could unlock unp2 now, since it was checked
664 lwkt_reltoken(&unp_token
);
666 if (unp
->unp_conn
== NULL
) {
670 unp2
= unp
->unp_conn
;
673 /* NOTE: unp2 is referenced. */
674 so2
= unp2
->unp_socket
;
677 from
= (struct sockaddr
*)unp
->unp_addr
;
681 lwkt_gettoken(&so2
->so_rcv
.ssb_token
);
682 if (ssb_appendaddr(&so2
->so_rcv
, from
, m
, control
)) {
689 lwkt_reltoken(&so2
->so_rcv
.ssb_token
);
697 /* Connect if not connected yet. */
699 * Note: A better implementation would complain
700 * if not equal to the peer's address.
702 if (unp
->unp_conn
== NULL
) {
703 if (msg
->send
.nm_addr
) {
704 error
= unp_connect(so
,
712 * unp_conn still could be NULL, even if the
713 * above unp_connect() succeeds; since the
714 * current unp's token could be released due
715 * to blocking operations after unp_conn is
718 if (unp
->unp_conn
== NULL
) {
723 if (so
->so_state
& SS_CANTSENDMORE
) {
728 unp2
= unp
->unp_conn
;
729 KASSERT(unp2
!= NULL
, ("unp is not connected"));
730 so2
= unp2
->unp_socket
;
735 * Send to paired receive port, and then reduce
736 * send buffer hiwater marks to maintain backpressure.
739 lwkt_gettoken(&so2
->so_rcv
.ssb_token
);
741 if (ssb_appendcontrol(&so2
->so_rcv
, m
, control
)) {
745 } else if (so
->so_type
== SOCK_SEQPACKET
) {
746 sbappendrecord(&so2
->so_rcv
.sb
, m
);
749 sbappend(&so2
->so_rcv
.sb
, m
);
754 * Because we are transfering mbufs directly to the
755 * peer socket we have to use SSB_STOP on the sender
756 * to prevent it from building up infinite mbufs.
758 if (so2
->so_rcv
.ssb_cc
>= so
->so_snd
.ssb_hiwat
||
759 so2
->so_rcv
.ssb_mbcnt
>= so
->so_snd
.ssb_mbmax
761 atomic_set_int(&so
->so_snd
.ssb_flags
, SSB_STOP
);
763 lwkt_reltoken(&so2
->so_rcv
.ssb_token
);
770 panic("uipc_send unknown socktype");
774 * SEND_EOF is equivalent to a SEND followed by a SHUTDOWN.
776 if (msg
->send
.nm_flags
& PRUS_EOF
) {
781 if (control
&& error
!= 0)
782 unp_dispose(control
);
785 wakeup_end_delayed();
791 lwkt_replymsg(&msg
->lmsg
, error
);
798 uipc_sense(netmsg_t msg
)
805 so
= msg
->base
.nm_so
;
806 sb
= msg
->sense
.nm_stat
;
809 * so_pcb is only modified with both the global and the unp
812 unp
= unp_getsocktoken(so
);
814 if (!UNP_ISATTACHED(unp
)) {
819 sb
->st_blksize
= so
->so_snd
.ssb_hiwat
;
821 if (unp
->unp_ino
== 0) { /* make up a non-zero inode number */
822 unp
->unp_ino
= atomic_fetchadd_long(&unp_ino
, 1);
823 if (__predict_false(unp
->unp_ino
== 0))
824 unp
->unp_ino
= atomic_fetchadd_long(&unp_ino
, 1);
826 sb
->st_ino
= unp
->unp_ino
;
830 lwkt_replymsg(&msg
->lmsg
, error
);
834 uipc_shutdown(netmsg_t msg
)
841 * so_pcb is only modified with both the global and the unp
844 so
= msg
->base
.nm_so
;
845 unp
= unp_getsocktoken(so
);
847 if (UNP_ISATTACHED(unp
)) {
856 lwkt_replymsg(&msg
->lmsg
, error
);
860 uipc_sockaddr(netmsg_t msg
)
866 * so_pcb is only modified with both the global and the unp
869 unp
= unp_getsocktoken(msg
->base
.nm_so
);
871 if (UNP_ISATTACHED(unp
)) {
873 *msg
->sockaddr
.nm_nam
=
874 dup_sockaddr((struct sockaddr
*)unp
->unp_addr
);
882 lwkt_replymsg(&msg
->lmsg
, error
);
885 struct pr_usrreqs uipc_usrreqs
= {
886 .pru_abort
= uipc_abort
,
887 .pru_accept
= uipc_accept
,
888 .pru_attach
= uipc_attach
,
889 .pru_bind
= uipc_bind
,
890 .pru_connect
= uipc_connect
,
891 .pru_connect2
= uipc_connect2
,
892 .pru_control
= pr_generic_notsupp
,
893 .pru_detach
= uipc_detach
,
894 .pru_disconnect
= uipc_disconnect
,
895 .pru_listen
= uipc_listen
,
896 .pru_peeraddr
= uipc_peeraddr
,
897 .pru_rcvd
= uipc_rcvd
,
898 .pru_rcvoob
= pr_generic_notsupp
,
899 .pru_send
= uipc_send
,
900 .pru_sense
= uipc_sense
,
901 .pru_shutdown
= uipc_shutdown
,
902 .pru_sockaddr
= uipc_sockaddr
,
903 .pru_sosend
= sosend
,
904 .pru_soreceive
= soreceive
908 uipc_ctloutput(netmsg_t msg
)
911 struct sockopt
*sopt
;
915 so
= msg
->base
.nm_so
;
916 sopt
= msg
->ctloutput
.nm_sopt
;
918 lwkt_gettoken(&unp_token
);
919 unp
= unp_getsocktoken(so
);
921 if (!UNP_ISATTACHED(unp
)) {
926 switch (sopt
->sopt_dir
) {
928 switch (sopt
->sopt_name
) {
930 if (unp
->unp_flags
& UNP_HAVEPC
)
931 soopt_from_kbuf(sopt
, &unp
->unp_peercred
,
932 sizeof(unp
->unp_peercred
));
934 if (so
->so_type
== SOCK_STREAM
)
936 else if (so
->so_type
== SOCK_SEQPACKET
)
955 lwkt_reltoken(&unp_token
);
957 lwkt_replymsg(&msg
->lmsg
, error
);
961 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
962 * for stream sockets, although the total for sender and receiver is
963 * actually only PIPSIZ.
965 * Datagram sockets really use the sendspace as the maximum datagram size,
966 * and don't really want to reserve the sendspace. Their recvspace should
967 * be large enough for at least one max-size datagram plus address.
969 * We want the local send/recv space to be significant larger then lo0's
975 static u_long unpst_sendspace
= PIPSIZ
;
976 static u_long unpst_recvspace
= PIPSIZ
;
977 static u_long unpdg_sendspace
= 2*1024; /* really max datagram size */
978 static u_long unpdg_recvspace
= 4*1024;
980 SYSCTL_DECL(_net_local_seqpacket
);
981 SYSCTL_DECL(_net_local_stream
);
982 SYSCTL_INT(_net_local_stream
, OID_AUTO
, sendspace
, CTLFLAG_RW
,
983 &unpst_sendspace
, 0, "Size of stream socket send buffer");
984 SYSCTL_INT(_net_local_stream
, OID_AUTO
, recvspace
, CTLFLAG_RW
,
985 &unpst_recvspace
, 0, "Size of stream socket receive buffer");
987 SYSCTL_DECL(_net_local_dgram
);
988 SYSCTL_INT(_net_local_dgram
, OID_AUTO
, maxdgram
, CTLFLAG_RW
,
989 &unpdg_sendspace
, 0, "Max datagram socket size");
990 SYSCTL_INT(_net_local_dgram
, OID_AUTO
, recvspace
, CTLFLAG_RW
,
991 &unpdg_recvspace
, 0, "Size of datagram socket receive buffer");
994 unp_attach(struct socket
*so
, struct pru_attach_info
*ai
)
996 struct unp_global_head
*head
;
1000 lwkt_gettoken(&unp_token
);
1002 if (so
->so_snd
.ssb_hiwat
== 0 || so
->so_rcv
.ssb_hiwat
== 0) {
1003 switch (so
->so_type
) {
1005 case SOCK_SEQPACKET
:
1006 error
= soreserve(so
, unpst_sendspace
, unpst_recvspace
,
1011 error
= soreserve(so
, unpdg_sendspace
, unpdg_recvspace
,
1016 panic("unp_attach");
1023 * In order to support sendfile we have to set either SSB_STOPSUPP
1024 * or SSB_PREALLOC. Unix domain sockets use the SSB_STOP flow
1025 * control mechanism.
1027 if (so
->so_type
== SOCK_STREAM
) {
1028 atomic_set_int(&so
->so_rcv
.ssb_flags
, SSB_STOPSUPP
);
1029 atomic_set_int(&so
->so_snd
.ssb_flags
, SSB_STOPSUPP
);
1032 unp
= kmalloc(sizeof(*unp
), M_UNPCB
, M_WAITOK
| M_ZERO
| M_NULLOK
);
1037 unp
->unp_refcnt
= 1;
1038 unp
->unp_gencnt
= ++unp_gencnt
;
1039 LIST_INIT(&unp
->unp_refs
);
1040 unp
->unp_socket
= so
;
1041 unp
->unp_rvnode
= ai
->fd_rdir
; /* jail cruft XXX JH */
1042 so
->so_pcb
= (caddr_t
)unp
;
1045 head
= unp_globalhead(so
->so_type
);
1046 TAILQ_INSERT_TAIL(&head
->list
, unp
, unp_link
);
1050 lwkt_reltoken(&unp_token
);
1055 unp_detach(struct unpcb
*unp
)
1059 lwkt_gettoken(&unp_token
);
1060 lwkt_getpooltoken(unp
);
1062 so
= unp
->unp_socket
;
1064 unp
->unp_gencnt
= ++unp_gencnt
;
1065 if (unp
->unp_vnode
) {
1066 unp
->unp_vnode
->v_socket
= NULL
;
1067 vrele(unp
->unp_vnode
);
1068 unp
->unp_vnode
= NULL
;
1070 soisdisconnected(so
);
1071 KKASSERT(so
->so_pcb
== unp
);
1072 so
->so_pcb
= NULL
; /* both tokens required */
1073 unp
->unp_socket
= NULL
;
1075 lwkt_relpooltoken(unp
);
1076 lwkt_reltoken(&unp_token
);
1080 KASSERT(unp
->unp_conn
== NULL
, ("unp is still connected"));
1081 KASSERT(LIST_EMPTY(&unp
->unp_refs
), ("unp still has references"));
1084 kfree(unp
->unp_addr
, M_SONAME
);
1085 kfree(unp
, M_UNPCB
);
1088 taskqueue_enqueue(unp_taskqueue
, &unp_gc_task
);
1092 unp_bind(struct unpcb
*unp
, struct sockaddr
*nam
, struct thread
*td
)
1094 struct proc
*p
= td
->td_proc
;
1095 struct sockaddr_un
*soun
= (struct sockaddr_un
*)nam
;
1099 struct nlookupdata nd
;
1100 char buf
[SOCK_MAXADDRLEN
];
1102 ASSERT_LWKT_TOKEN_HELD(&unp_token
);
1103 UNP_ASSERT_TOKEN_HELD(unp
);
1105 if (unp
->unp_vnode
!= NULL
)
1108 namelen
= soun
->sun_len
- offsetof(struct sockaddr_un
, sun_path
);
1111 strncpy(buf
, soun
->sun_path
, namelen
);
1112 buf
[namelen
] = 0; /* null-terminate the string */
1113 error
= nlookup_init(&nd
, buf
, UIO_SYSSPACE
,
1114 NLC_LOCKVP
| NLC_CREATE
| NLC_REFDVP
);
1116 error
= nlookup(&nd
);
1117 if (error
== 0 && nd
.nl_nch
.ncp
->nc_vp
!= NULL
)
1123 vattr
.va_type
= VSOCK
;
1124 vattr
.va_mode
= (ACCESSPERMS
& ~p
->p_fd
->fd_cmask
);
1125 error
= VOP_NCREATE(&nd
.nl_nch
, nd
.nl_dvp
, &vp
, nd
.nl_cred
, &vattr
);
1127 if (unp
->unp_vnode
== NULL
) {
1128 vp
->v_socket
= unp
->unp_socket
;
1129 unp
->unp_vnode
= vp
;
1130 unp
->unp_addr
= (struct sockaddr_un
*)dup_sockaddr(nam
);
1133 vput(vp
); /* late race */
1143 unp_connect(struct socket
*so
, struct sockaddr
*nam
, struct thread
*td
)
1145 struct unpcb
*unp
, *unp2
;
1146 int error
, flags
= 0;
1148 lwkt_gettoken(&unp_token
);
1150 unp
= unp_getsocktoken(so
);
1151 if (!UNP_ISATTACHED(unp
)) {
1156 if ((unp
->unp_flags
& UNP_CONNECTING
) || unp
->unp_conn
!= NULL
) {
1161 flags
= UNP_CONNECTING
;
1162 unp_setflags(unp
, flags
);
1164 error
= unp_find_lockref(nam
, td
, so
->so_type
, &unp2
);
1169 * unp2 is locked and referenced.
1172 if (so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) {
1173 struct socket
*so2
, *so3
;
1176 so2
= unp2
->unp_socket
;
1177 if (!(so2
->so_options
& SO_ACCEPTCONN
) ||
1178 /* listen is not completed yet */
1179 !(unp2
->unp_flags
& UNP_HAVEPCCACHED
) ||
1180 (so3
= sonewconn_faddr(so2
, 0, NULL
,
1181 TRUE
/* keep ref */)) == NULL
) {
1182 error
= ECONNREFUSED
;
1185 /* so3 has a socket reference. */
1187 unp3
= unp_getsocktoken(so3
);
1188 if (!UNP_ISATTACHED(unp3
)) {
1191 * Already aborted; we only need to drop the
1192 * socket reference held by sonewconn_faddr().
1195 error
= ECONNREFUSED
;
1198 unp_reference(unp3
);
1201 * unp3 is locked and referenced.
1205 * Release so3 socket reference held by sonewconn_faddr().
1206 * Since we have referenced unp3, neither unp3 nor so3 will
1207 * be destroyed here.
1211 if (unp2
->unp_addr
!= NULL
) {
1212 unp3
->unp_addr
= (struct sockaddr_un
*)
1213 dup_sockaddr((struct sockaddr
*)unp2
->unp_addr
);
1217 * unp_peercred management:
1219 * The connecter's (client's) credentials are copied
1220 * from its process structure at the time of connect()
1223 cru2x(td
->td_proc
->p_ucred
, &unp3
->unp_peercred
);
1224 unp_setflags(unp3
, UNP_HAVEPC
);
1226 * The receiver's (server's) credentials are copied
1227 * from the unp_peercred member of socket on which the
1228 * former called listen(); unp_listen() cached that
1229 * process's credentials at that time so we can use
1232 KASSERT(unp2
->unp_flags
& UNP_HAVEPCCACHED
,
1233 ("unp_connect: listener without cached peercred"));
1234 memcpy(&unp
->unp_peercred
, &unp2
->unp_peercred
,
1235 sizeof(unp
->unp_peercred
));
1236 unp_setflags(unp
, UNP_HAVEPC
);
1238 error
= unp_connect_pair(unp
, unp3
);
1240 soabort_direct(so3
);
1242 /* Done with unp3 */
1246 error
= unp_connect_pair(unp
, unp2
);
1253 unp_clrflags(unp
, flags
);
1256 lwkt_reltoken(&unp_token
);
1261 * Connect two unix domain sockets together.
1263 * NOTE: Semantics for any change to unp_conn requires that the per-unp
1264 * pool token also be held.
1267 unp_connect2(struct socket
*so
, struct socket
*so2
)
1269 struct unpcb
*unp
, *unp2
;
1272 lwkt_gettoken(&unp_token
);
1273 if (so2
->so_type
!= so
->so_type
) {
1274 lwkt_reltoken(&unp_token
);
1275 return (EPROTOTYPE
);
1277 unp
= unp_getsocktoken(so
);
1278 unp2
= unp_getsocktoken(so2
);
1280 if (!UNP_ISATTACHED(unp
)) {
1284 if (!UNP_ISATTACHED(unp2
)) {
1285 error
= ECONNREFUSED
;
1289 if (unp
->unp_conn
!= NULL
) {
1293 if ((so
->so_type
== SOCK_STREAM
|| so
->so_type
== SOCK_SEQPACKET
) &&
1294 unp2
->unp_conn
!= NULL
) {
1299 error
= unp_connect_pair(unp
, unp2
);
1303 lwkt_reltoken(&unp_token
);
1308 * Disconnect a unix domain socket pair.
1310 * NOTE: Semantics for any change to unp_conn requires that the per-unp
1311 * pool token also be held.
1314 unp_disconnect(struct unpcb
*unp
, int error
)
1316 struct socket
*so
= unp
->unp_socket
;
1319 ASSERT_LWKT_TOKEN_HELD(&unp_token
);
1320 UNP_ASSERT_TOKEN_HELD(unp
);
1323 so
->so_error
= error
;
1325 while ((unp2
= unp
->unp_conn
) != NULL
) {
1326 lwkt_getpooltoken(unp2
);
1327 if (unp2
== unp
->unp_conn
)
1329 lwkt_relpooltoken(unp2
);
1333 /* unp2 is locked. */
1335 KASSERT((unp2
->unp_flags
& UNP_DROPPED
) == 0, ("unp2 was dropped"));
1337 unp
->unp_conn
= NULL
;
1339 switch (so
->so_type
) {
1341 LIST_REMOVE(unp
, unp_reflink
);
1342 soclrstate(so
, SS_ISCONNECTED
);
1346 case SOCK_SEQPACKET
:
1348 * Keep a reference before clearing the unp_conn
1349 * to avoid racing uipc_detach()/uipc_abort() in
1352 unp_reference(unp2
);
1353 KASSERT(unp2
->unp_conn
== unp
, ("unp_conn mismatch"));
1354 unp2
->unp_conn
= NULL
;
1356 soisdisconnected(so
);
1357 soisdisconnected(unp2
->unp_socket
);
1363 lwkt_relpooltoken(unp2
);
1368 unp_abort(struct unpcb
*unp
)
1370 lwkt_gettoken(&unp_token
);
1372 lwkt_reltoken(&unp_token
);
1377 prison_unpcb(struct thread
*td
, struct unpcb
*unp
)
1383 if ((p
= td
->td_proc
) == NULL
)
1385 if (!p
->p_ucred
->cr_prison
)
1387 if (p
->p_fd
->fd_rdir
== unp
->unp_rvnode
)
1393 unp_pcblist(SYSCTL_HANDLER_ARGS
)
1395 struct unp_global_head
*head
= arg1
;
1397 struct unpcb
*unp
, *marker
;
1399 KKASSERT(curproc
!= NULL
);
1402 * The process of preparing the PCB list is too time-consuming and
1403 * resource-intensive to repeat twice on every request.
1405 if (req
->oldptr
== NULL
) {
1407 req
->oldidx
= (n
+ n
/8) * sizeof(struct xunpcb
);
1411 if (req
->newptr
!= NULL
)
1414 marker
= kmalloc(sizeof(*marker
), M_UNPCB
, M_WAITOK
| M_ZERO
);
1415 marker
->unp_flags
|= UNP_MARKER
;
1417 lwkt_gettoken(&unp_token
);
1423 TAILQ_INSERT_HEAD(&head
->list
, marker
, unp_link
);
1424 while ((unp
= TAILQ_NEXT(marker
, unp_link
)) != NULL
&& i
< n
) {
1427 TAILQ_REMOVE(&head
->list
, marker
, unp_link
);
1428 TAILQ_INSERT_AFTER(&head
->list
, unp
, marker
, unp_link
);
1430 if (unp
->unp_flags
& UNP_MARKER
)
1432 if (prison_unpcb(req
->td
, unp
))
1435 xu
.xu_len
= sizeof(xu
);
1440 * unp->unp_addr and unp->unp_conn are protected by
1441 * unp_token. So if we want to get rid of unp_token
1442 * or reduce the coverage of unp_token, care must be
1445 if (unp
->unp_addr
) {
1446 bcopy(unp
->unp_addr
, &xu
.xu_addr
,
1447 unp
->unp_addr
->sun_len
);
1449 if (unp
->unp_conn
&& unp
->unp_conn
->unp_addr
) {
1450 bcopy(unp
->unp_conn
->unp_addr
,
1452 unp
->unp_conn
->unp_addr
->sun_len
);
1454 bcopy(unp
, &xu
.xu_unp
, sizeof(*unp
));
1455 sotoxsocket(unp
->unp_socket
, &xu
.xu_socket
);
1457 /* NOTE: This could block and temporarily release unp_token */
1458 error
= SYSCTL_OUT(req
, &xu
, sizeof(xu
));
1463 TAILQ_REMOVE(&head
->list
, marker
, unp_link
);
1465 lwkt_reltoken(&unp_token
);
1467 kfree(marker
, M_UNPCB
);
1471 SYSCTL_PROC(_net_local_dgram
, OID_AUTO
, pcblist
, CTLFLAG_RD
,
1472 &unp_dgram_head
, 0, unp_pcblist
, "S,xunpcb",
1473 "List of active local datagram sockets");
1474 SYSCTL_PROC(_net_local_stream
, OID_AUTO
, pcblist
, CTLFLAG_RD
,
1475 &unp_stream_head
, 0, unp_pcblist
, "S,xunpcb",
1476 "List of active local stream sockets");
1477 SYSCTL_PROC(_net_local_seqpacket
, OID_AUTO
, pcblist
, CTLFLAG_RD
,
1478 &unp_seqpkt_head
, 0, unp_pcblist
, "S,xunpcb",
1479 "List of active local seqpacket sockets");
1482 unp_shutdown(struct unpcb
*unp
)
1486 if ((unp
->unp_socket
->so_type
== SOCK_STREAM
||
1487 unp
->unp_socket
->so_type
== SOCK_SEQPACKET
) &&
1488 unp
->unp_conn
!= NULL
&& (so
= unp
->unp_conn
->unp_socket
)) {
1497 lwkt_gettoken(&unp_token
);
1498 lwkt_reltoken(&unp_token
);
1503 unp_externalize(struct mbuf
*rights
, int flags
)
1505 struct thread
*td
= curthread
;
1506 struct proc
*p
= td
->td_proc
; /* XXX */
1507 struct lwp
*lp
= td
->td_lwp
;
1508 struct cmsghdr
*cm
= mtod(rights
, struct cmsghdr
*);
1513 int newfds
= (cm
->cmsg_len
- (CMSG_DATA(cm
) - (u_char
*)cm
))
1514 / sizeof(struct file
*);
1517 lwkt_gettoken(&unp_rights_token
);
1520 * if the new FD's will not fit, then we free them all
1522 if (!fdavail(p
, newfds
)) {
1523 rp
= (struct file
**)CMSG_DATA(cm
);
1524 for (i
= 0; i
< newfds
; i
++) {
1527 * zero the pointer before calling unp_discard,
1528 * since it may end up in unp_gc()..
1531 unp_discard(fp
, NULL
);
1533 lwkt_reltoken(&unp_rights_token
);
1538 * now change each pointer to an fd in the global table to
1539 * an integer that is the index to the local fd table entry
1540 * that we set up to point to the global one we are transferring.
1541 * Since the sizeof(struct file *) is bigger than or equal to
1542 * the sizeof(int), we do it in forward order. In that case,
1543 * an integer will always come in the same place or before its
1544 * corresponding struct file pointer.
1546 * Hold revoke_token in 'shared' mode, so that we won't miss
1547 * the FREVOKED update on fps being externalized (fsetfd).
1549 lwkt_gettoken_shared(&revoke_token
);
1550 fdp
= (int *)CMSG_DATA(cm
);
1551 rp
= (struct file
**)CMSG_DATA(cm
);
1552 for (i
= 0; i
< newfds
; i
++) {
1553 if (fdalloc(p
, 0, &f
)) {
1557 * Previous fdavail() can't garantee
1558 * fdalloc() success due to SMP race.
1559 * Just clean up and return the same
1560 * error value as if fdavail() failed.
1562 lwkt_reltoken(&revoke_token
);
1564 /* Close externalized files */
1565 for (j
= 0; j
< i
; j
++)
1567 /* Discard the rest of internal files */
1568 for (; i
< newfds
; i
++)
1569 unp_discard(rp
[i
], NULL
);
1570 /* Wipe out the control message */
1571 for (i
= 0; i
< newfds
; i
++)
1574 lwkt_reltoken(&unp_rights_token
);
1578 unp_fp_externalize(lp
, fp
, f
, flags
);
1581 lwkt_reltoken(&revoke_token
);
1583 lwkt_reltoken(&unp_rights_token
);
1586 * Adjust length, in case sizeof(struct file *) and sizeof(int)
1589 cm
->cmsg_len
= CMSG_LEN(newfds
* sizeof(int));
1590 rights
->m_len
= cm
->cmsg_len
;
1596 unp_fp_externalize(struct lwp
*lp
, struct file
*fp
, int fd
, int flags
)
1599 struct filedesc
*fdp
= lp
->lwp_proc
->p_fd
;
1602 if (fp
->f_flag
& FREVOKED
) {
1606 kprintf("Warning: revoked fp exiting unix socket\n");
1607 error
= falloc(lp
, &fx
, NULL
);
1609 if (flags
& MSG_CMSG_CLOEXEC
)
1610 fdp
->fd_files
[fd
].fileflags
|= UF_EXCLOSE
;
1611 fsetfd(fdp
, fx
, fd
);
1614 fsetfd(fdp
, NULL
, fd
);
1617 if (flags
& MSG_CMSG_CLOEXEC
)
1618 fdp
->fd_files
[fd
].fileflags
|= UF_EXCLOSE
;
1619 fsetfd(fdp
, fp
, fd
);
1629 TAILQ_INIT(&unp_stream_head
.list
);
1630 TAILQ_INIT(&unp_dgram_head
.list
);
1631 TAILQ_INIT(&unp_seqpkt_head
.list
);
1633 SLIST_INIT(&unp_defdiscard_head
);
1634 spin_init(&unp_defdiscard_spin
, "unpdisc");
1635 TASK_INIT(&unp_defdiscard_task
, 0, unp_defdiscard_taskfunc
, NULL
);
1638 * This implies that only one gc can be in-progress at any
1641 TASK_INIT(&unp_gc_task
, 0, unp_gc
, NULL
);
1643 unp_gc_marker
= kmalloc(sizeof(*unp_gc_marker
), M_UNPCB
,
1645 unp_gc_marker
->unp_flags
|= UNP_MARKER
;
1648 * Create taskqueue for defered discard, and stick it to
1651 unp_taskqueue
= taskqueue_create("unp_taskq", M_WAITOK
,
1652 taskqueue_thread_enqueue
, &unp_taskqueue
);
1653 taskqueue_start_threads(&unp_taskqueue
, 1, TDPRI_KERN_DAEMON
,
1654 ncpus
- 1, "unp taskq");
1658 unp_internalize(struct mbuf
*control
, struct thread
*td
)
1660 struct proc
*p
= td
->td_proc
;
1661 struct filedesc
*fdescp
;
1662 struct cmsghdr
*cm
= mtod(control
, struct cmsghdr
*);
1666 struct cmsgcred
*cmcred
;
1673 if ((cm
->cmsg_type
!= SCM_RIGHTS
&& cm
->cmsg_type
!= SCM_CREDS
) ||
1674 cm
->cmsg_level
!= SOL_SOCKET
||
1675 CMSG_ALIGN(cm
->cmsg_len
) != control
->m_len
)
1679 * Fill in credential information.
1681 if (cm
->cmsg_type
== SCM_CREDS
) {
1682 cmcred
= (struct cmsgcred
*)CMSG_DATA(cm
);
1683 cmcred
->cmcred_pid
= p
->p_pid
;
1684 cmcred
->cmcred_uid
= p
->p_ucred
->cr_ruid
;
1685 cmcred
->cmcred_gid
= p
->p_ucred
->cr_rgid
;
1686 cmcred
->cmcred_euid
= p
->p_ucred
->cr_uid
;
1687 cmcred
->cmcred_ngroups
= MIN(p
->p_ucred
->cr_ngroups
,
1689 for (i
= 0; i
< cmcred
->cmcred_ngroups
; i
++)
1690 cmcred
->cmcred_groups
[i
] = p
->p_ucred
->cr_groups
[i
];
1695 * cmsghdr may not be aligned, do not allow calculation(s) to
1698 if (cm
->cmsg_len
< CMSG_LEN(0))
1701 oldfds
= (cm
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
1704 * Now replace the integer FDs with pointers to
1705 * the associated global file table entry..
1706 * Allocate a bigger buffer as necessary. But if an cluster is not
1707 * enough, return E2BIG.
1709 newlen
= CMSG_LEN(oldfds
* sizeof(struct file
*));
1710 if (newlen
> MCLBYTES
)
1712 if (newlen
- control
->m_len
> M_TRAILINGSPACE(control
)) {
1713 if (control
->m_flags
& M_EXT
)
1715 MCLGET(control
, M_WAITOK
);
1716 if (!(control
->m_flags
& M_EXT
))
1719 /* copy the data to the cluster */
1720 memcpy(mtod(control
, char *), cm
, cm
->cmsg_len
);
1721 cm
= mtod(control
, struct cmsghdr
*);
1724 lwkt_gettoken(&unp_rights_token
);
1727 spin_lock_shared(&fdescp
->fd_spin
);
1730 * check that all the FDs passed in refer to legal OPEN files
1731 * If not, reject the entire operation.
1733 fdp
= (int *)CMSG_DATA(cm
);
1734 for (i
= 0; i
< oldfds
; i
++) {
1736 if ((unsigned)fd
>= fdescp
->fd_nfiles
||
1737 fdescp
->fd_files
[fd
].fp
== NULL
) {
1741 if (fdescp
->fd_files
[fd
].fp
->f_type
== DTYPE_KQUEUE
) {
1748 * Adjust length, in case sizeof(struct file *) and sizeof(int)
1751 cm
->cmsg_len
= newlen
;
1752 control
->m_len
= CMSG_ALIGN(newlen
);
1755 * Transform the file descriptors into struct file pointers.
1756 * Since the sizeof(struct file *) is bigger than or equal to
1757 * the sizeof(int), we do it in reverse order so that the int
1758 * won't get trashed until we're done.
1760 fdp
= (int *)CMSG_DATA(cm
) + oldfds
- 1;
1761 rp
= (struct file
**)CMSG_DATA(cm
) + oldfds
- 1;
1762 for (i
= 0; i
< oldfds
; i
++) {
1763 fp
= fdescp
->fd_files
[*fdp
--].fp
;
1770 spin_unlock_shared(&fdescp
->fd_spin
);
1771 lwkt_reltoken(&unp_rights_token
);
1775 #ifdef UNP_GC_ALLFILES
1778 * Garbage collect in-transit file descriptors that get lost due to
1779 * loops (i.e. when a socket is sent to another process over itself,
1780 * and more complex situations).
1782 * NOT MPSAFE - TODO socket flush code and maybe fdrop. Rest is MPSAFE.
1785 struct unp_gc_info
{
1786 struct file
**extra_ref
;
1787 struct file
*locked_fp
;
1794 unp_gc(void *arg __unused
, int pending __unused
)
1796 struct unp_gc_info info
;
1800 lwkt_gettoken(&unp_rights_token
);
1803 * Before going through all this, set all FDs to be NOT defered
1804 * and NOT externally accessible (not marked). During the scan
1805 * a fd can be marked externally accessible but we may or may not
1806 * be able to immediately process it (controlled by FDEFER).
1808 * If we loop sleep a bit. The complexity of the topology can cause
1809 * multiple loops. Also failure to acquire the socket's so_rcv
1810 * token can cause us to loop.
1812 allfiles_scan_exclusive(unp_gc_clearmarks
, NULL
);
1815 allfiles_scan_exclusive(unp_gc_checkmarks
, &info
);
1817 tsleep(&info
, 0, "gcagain", 1);
1818 } while (info
.defer
);
1821 * We grab an extra reference to each of the file table entries
1822 * that are not otherwise accessible and then free the rights
1823 * that are stored in messages on them.
1825 * The bug in the orginal code is a little tricky, so I'll describe
1826 * what's wrong with it here.
1828 * It is incorrect to simply unp_discard each entry for f_msgcount
1829 * times -- consider the case of sockets A and B that contain
1830 * references to each other. On a last close of some other socket,
1831 * we trigger a gc since the number of outstanding rights (unp_rights)
1832 * is non-zero. If during the sweep phase the gc code unp_discards,
1833 * we end up doing a (full) fdrop on the descriptor. A fdrop on A
1834 * results in the following chain. Closef calls soo_close, which
1835 * calls soclose. Soclose calls first (through the switch
1836 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1837 * returns because the previous instance had set unp_gcing, and
1838 * we return all the way back to soclose, which marks the socket
1839 * with SS_NOFDREF, and then calls sofree. Sofree calls sorflush
1840 * to free up the rights that are queued in messages on the socket A,
1841 * i.e., the reference on B. The sorflush calls via the dom_dispose
1842 * switch unp_dispose, which unp_scans with unp_discard. This second
1843 * instance of unp_discard just calls fdrop on B.
1845 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1846 * which results in another fdrop on A. Unfortunately, A is already
1847 * being closed, and the descriptor has already been marked with
1848 * SS_NOFDREF, and soclose panics at this point.
1850 * Here, we first take an extra reference to each inaccessible
1851 * descriptor. Then, we call sorflush ourself, since we know
1852 * it is a Unix domain socket anyhow. After we destroy all the
1853 * rights carried in messages, we do a last fdrop to get rid
1854 * of our extra reference. This is the last close, and the
1855 * unp_detach etc will shut down the socket.
1857 * 91/09/19, bsy@cs.cmu.edu
1859 info
.extra_ref
= kmalloc(256 * sizeof(struct file
*), M_FILE
, M_WAITOK
);
1860 info
.maxindex
= 256;
1867 allfiles_scan_exclusive(unp_gc_checkrefs
, &info
);
1870 * For each FD on our hit list, do the following two things
1872 for (i
= info
.index
, fpp
= info
.extra_ref
; --i
>= 0; ++fpp
) {
1873 struct file
*tfp
= *fpp
;
1874 if (tfp
->f_type
== DTYPE_SOCKET
&& tfp
->f_data
!= NULL
)
1875 sorflush((struct socket
*)(tfp
->f_data
));
1877 for (i
= info
.index
, fpp
= info
.extra_ref
; --i
>= 0; ++fpp
)
1879 } while (info
.index
== info
.maxindex
);
1881 kfree((caddr_t
)info
.extra_ref
, M_FILE
);
1883 lwkt_reltoken(&unp_rights_token
);
1887 * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1890 unp_gc_checkrefs(struct file
*fp
, void *data
)
1892 struct unp_gc_info
*info
= data
;
1894 if (fp
->f_count
== 0)
1896 if (info
->index
== info
->maxindex
)
1900 * If all refs are from msgs, and it's not marked accessible
1901 * then it must be referenced from some unreachable cycle
1902 * of (shut-down) FDs, so include it in our
1903 * list of FDs to remove
1905 if (fp
->f_count
== fp
->f_msgcount
&& !(fp
->f_flag
& FMARK
)) {
1906 info
->extra_ref
[info
->index
++] = fp
;
1913 * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1916 unp_gc_clearmarks(struct file
*fp
, void *data __unused
)
1918 atomic_clear_int(&fp
->f_flag
, FMARK
| FDEFER
);
1923 * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1926 unp_gc_checkmarks(struct file
*fp
, void *data
)
1928 struct unp_gc_info
*info
= data
;
1932 * If the file is not open, skip it. Make sure it isn't marked
1933 * defered or we could loop forever, in case we somehow race
1936 if (fp
->f_count
== 0) {
1937 if (fp
->f_flag
& FDEFER
)
1938 atomic_clear_int(&fp
->f_flag
, FDEFER
);
1942 * If we already marked it as 'defer' in a
1943 * previous pass, then try process it this time
1946 if (fp
->f_flag
& FDEFER
) {
1947 atomic_clear_int(&fp
->f_flag
, FDEFER
);
1950 * if it's not defered, then check if it's
1951 * already marked.. if so skip it
1953 if (fp
->f_flag
& FMARK
)
1956 * If all references are from messages
1957 * in transit, then skip it. it's not
1958 * externally accessible.
1960 if (fp
->f_count
== fp
->f_msgcount
)
1963 * If it got this far then it must be
1964 * externally accessible.
1966 atomic_set_int(&fp
->f_flag
, FMARK
);
1970 * either it was defered, or it is externally
1971 * accessible and not already marked so.
1972 * Now check if it is possibly one of OUR sockets.
1974 if (fp
->f_type
!= DTYPE_SOCKET
||
1975 (so
= (struct socket
*)fp
->f_data
) == NULL
) {
1978 if (so
->so_proto
->pr_domain
!= &localdomain
||
1979 !(so
->so_proto
->pr_flags
& PR_RIGHTS
)) {
1984 * So, Ok, it's one of our sockets and it IS externally accessible
1985 * (or was defered). Now we look to see if we hold any file
1986 * descriptors in its message buffers. Follow those links and mark
1987 * them as accessible too.
1989 * We are holding multiple spinlocks here, if we cannot get the
1990 * token non-blocking defer until the next loop.
1992 info
->locked_fp
= fp
;
1993 if (lwkt_trytoken(&so
->so_rcv
.ssb_token
)) {
1994 unp_scan(so
->so_rcv
.ssb_mb
, unp_mark
, info
);
1995 lwkt_reltoken(&so
->so_rcv
.ssb_token
);
1997 atomic_set_int(&fp
->f_flag
, FDEFER
);
2004 * Mark visibility. info->defer is recalculated on every pass.
2007 unp_mark(struct file
*fp
, void *data
)
2009 struct unp_gc_info
*info
= data
;
2011 if ((fp
->f_flag
& FMARK
) == 0) {
2013 atomic_set_int(&fp
->f_flag
, FMARK
| FDEFER
);
2014 } else if (fp
->f_flag
& FDEFER
) {
2019 #else /* !UNP_GC_ALLFILES */
2022 * They are thread local and do not require explicit synchronization.
2024 static int unp_marked
;
2025 static int unp_unreachable
;
2028 unp_accessable(struct file
*fp
, void *data __unused
)
2032 if ((unp
= unp_fp2unpcb(fp
)) == NULL
)
2034 if (unp
->unp_gcflags
& UNPGC_REF
)
2036 unp
->unp_gcflags
&= ~UNPGC_DEAD
;
2037 unp
->unp_gcflags
|= UNPGC_REF
;
2042 unp_gc_process(struct unpcb
*unp
)
2046 /* Already processed. */
2047 if (unp
->unp_gcflags
& UNPGC_SCANNED
)
2052 * Check for a socket potentially in a cycle. It must be in a
2053 * queue as indicated by msgcount, and this must equal the file
2054 * reference count. Note that when msgcount is 0 the file is NULL.
2056 if ((unp
->unp_gcflags
& UNPGC_REF
) == 0 && fp
&&
2057 unp
->unp_msgcount
!= 0 && fp
->f_count
== unp
->unp_msgcount
) {
2058 unp
->unp_gcflags
|= UNPGC_DEAD
;
2064 * Mark all sockets we reference with RIGHTS.
2066 if (UNP_ISATTACHED(unp
)) {
2067 struct signalsockbuf
*ssb
= &unp
->unp_socket
->so_rcv
;
2070 lwkt_gettoken(&ssb
->ssb_token
);
2072 * unp_token would be temporarily dropped, if getting
2073 * so_rcv token blocks, so we need to check unp state
2076 if (UNP_ISATTACHED(unp
))
2077 unp_scan(ssb
->ssb_mb
, unp_accessable
, NULL
);
2078 lwkt_reltoken(&ssb
->ssb_token
);
2079 unp
->unp_gcflags
|= UNPGC_SCANNED
;
2082 unp
->unp_gcflags
|= UNPGC_SCANNED
;
2087 unp_gc(void *arg __unused
, int pending __unused
)
2089 struct unp_global_head
*head
;
2090 int h
, filemax
, fileidx
, filetot
;
2091 struct file
**unref
;
2094 lwkt_gettoken(&unp_rights_token
);
2095 lwkt_gettoken(&unp_token
);
2098 * First clear all gc flags from previous runs.
2100 for (h
= 0; unp_heads
[h
] != NULL
; ++h
) {
2102 * NOTE: This loop does not block, so it is safe
2103 * to use TAILQ_FOREACH here.
2105 head
= unp_heads
[h
];
2106 TAILQ_FOREACH(unp
, &head
->list
, unp_link
)
2107 unp
->unp_gcflags
= 0;
2111 * Scan marking all reachable sockets with UNPGC_REF. Once a socket
2112 * is reachable all of the sockets it references are reachable.
2113 * Stop the scan once we do a complete loop without discovering
2114 * a new reachable socket.
2117 unp_unreachable
= 0;
2119 for (h
= 0; unp_heads
[h
] != NULL
; ++h
) {
2120 head
= unp_heads
[h
];
2121 TAILQ_INSERT_HEAD(&head
->list
, unp_gc_marker
, unp_link
);
2122 while ((unp
= TAILQ_NEXT(unp_gc_marker
, unp_link
))
2124 TAILQ_REMOVE(&head
->list
, unp_gc_marker
,
2126 TAILQ_INSERT_AFTER(&head
->list
, unp
,
2127 unp_gc_marker
, unp_link
);
2129 if (unp
->unp_flags
& UNP_MARKER
)
2131 unp_gc_process(unp
);
2133 TAILQ_REMOVE(&head
->list
, unp_gc_marker
, unp_link
);
2135 } while (unp_marked
);
2137 if (unp_unreachable
== 0)
2141 * We grab an extra reference to each of the file table entries
2142 * that are not otherwise accessible and then free the rights
2143 * that are stored in messages on them.
2145 * The bug in the orginal code is a little tricky, so I'll describe
2146 * what's wrong with it here.
2148 * It is incorrect to simply unp_discard each entry for f_msgcount
2149 * times -- consider the case of sockets A and B that contain
2150 * references to each other. On a last close of some other socket,
2151 * we trigger a gc since the number of outstanding rights (unp_rights)
2152 * is non-zero. If during the sweep phase the gc code unp_discards,
2153 * we end up doing a (full) fdrop on the descriptor. A fdrop on A
2154 * results in the following chain. Closef calls soo_close, which
2155 * calls soclose. Soclose calls first (through the switch
2156 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
2157 * returns because the previous instance had set unp_gcing, and
2158 * we return all the way back to soclose, which marks the socket
2159 * with SS_NOFDREF, and then calls sofree. Sofree calls sorflush
2160 * to free up the rights that are queued in messages on the socket A,
2161 * i.e., the reference on B. The sorflush calls via the dom_dispose
2162 * switch unp_dispose, which unp_scans with unp_discard. This second
2163 * instance of unp_discard just calls fdrop on B.
2165 * Well, a similar chain occurs on B, resulting in a sorflush on B,
2166 * which results in another fdrop on A. Unfortunately, A is already
2167 * being closed, and the descriptor has already been marked with
2168 * SS_NOFDREF, and soclose panics at this point.
2170 * Here, we first take an extra reference to each inaccessible
2171 * descriptor. Then, we call sorflush ourself, since we know
2172 * it is a Unix domain socket anyhow. After we destroy all the
2173 * rights carried in messages, we do a last fdrop to get rid
2174 * of our extra reference. This is the last close, and the
2175 * unp_detach etc will shut down the socket.
2177 * 91/09/19, bsy@cs.cmu.edu
2180 filemax
= unp_unreachable
;
2181 if (filemax
> UNP_GCFILE_MAX
)
2182 filemax
= UNP_GCFILE_MAX
;
2183 unref
= kmalloc(filemax
* sizeof(struct file
*), M_TEMP
, M_WAITOK
);
2190 * Iterate looking for sockets which have been specifically
2191 * marked as as unreachable and store them locally.
2194 for (h
= 0; unp_heads
[h
] != NULL
; ++h
) {
2196 * NOTE: This loop does not block, so it is safe
2197 * to use TAILQ_FOREACH here.
2199 head
= unp_heads
[h
];
2200 TAILQ_FOREACH(unp
, &head
->list
, unp_link
) {
2203 if ((unp
->unp_gcflags
& UNPGC_DEAD
) == 0)
2205 unp
->unp_gcflags
&= ~UNPGC_DEAD
;
2208 if (unp
->unp_msgcount
== 0 || fp
== NULL
||
2209 fp
->f_count
!= unp
->unp_msgcount
)
2213 KASSERT(fileidx
< filemax
,
2214 ("invalid fileidx %d, filemax %d",
2216 unref
[fileidx
++] = fp
;
2218 KASSERT(filetot
< unp_unreachable
,
2219 ("invalid filetot %d and "
2220 "unp_unreachable %d",
2221 filetot
, unp_unreachable
));
2224 if (fileidx
== filemax
||
2225 filetot
== unp_unreachable
)
2231 * For each Unix domain socket on our hit list, do the
2232 * following two things.
2234 for (i
= 0; i
< fileidx
; ++i
)
2235 sorflush(unref
[i
]->f_data
);
2236 for (i
= 0; i
< fileidx
; ++i
)
2238 } while (fileidx
== filemax
&& filetot
< unp_unreachable
);
2239 kfree(unref
, M_TEMP
);
2241 lwkt_reltoken(&unp_token
);
2242 lwkt_reltoken(&unp_rights_token
);
2245 #endif /* UNP_GC_ALLFILES */
2248 * Dispose of the fp's stored in a mbuf.
2250 * The dds loop can cause additional fps to be entered onto the
2251 * list while it is running, flattening out the operation and avoiding
2252 * a deep kernel stack recursion.
2255 unp_dispose(struct mbuf
*m
)
2257 lwkt_gettoken(&unp_rights_token
);
2259 unp_scan(m
, unp_discard
, NULL
);
2260 lwkt_reltoken(&unp_rights_token
);
2264 unp_listen(struct unpcb
*unp
, struct thread
*td
)
2266 struct proc
*p
= td
->td_proc
;
2268 ASSERT_LWKT_TOKEN_HELD(&unp_token
);
2269 UNP_ASSERT_TOKEN_HELD(unp
);
2272 cru2x(p
->p_ucred
, &unp
->unp_peercred
);
2273 unp_setflags(unp
, UNP_HAVEPCCACHED
);
2278 unp_scan(struct mbuf
*m0
, void (*op
)(struct file
*, void *), void *data
)
2287 for (m
= m0
; m
; m
= m
->m_next
) {
2288 if (m
->m_type
== MT_CONTROL
&&
2289 m
->m_len
>= sizeof(*cm
)) {
2290 cm
= mtod(m
, struct cmsghdr
*);
2291 if (cm
->cmsg_level
!= SOL_SOCKET
||
2292 cm
->cmsg_type
!= SCM_RIGHTS
)
2294 qfds
= (cm
->cmsg_len
- CMSG_LEN(0)) /
2296 rp
= (struct file
**)CMSG_DATA(cm
);
2297 for (i
= 0; i
< qfds
; i
++)
2299 break; /* XXX, but saves time */
2307 * Discard a fp previously held in a unix domain socket mbuf. To
2308 * avoid blowing out the kernel stack due to contrived chain-reactions
2309 * we may have to defer the operation to a dedicated taskqueue.
2311 * Caller holds unp_rights_token.
2314 unp_discard(struct file
*fp
, void *data __unused
)
2317 if (unp_fp2unpcb(fp
) != NULL
) {
2318 struct unp_defdiscard
*d
;
2321 * This fp is a Unix domain socket itself and fdrop()
2322 * it here directly may cause deep unp_discard()
2323 * recursion, so the fdrop() is defered to the
2324 * dedicated taskqueue.
2326 d
= kmalloc(sizeof(*d
), M_UNPCB
, M_WAITOK
);
2329 spin_lock(&unp_defdiscard_spin
);
2330 SLIST_INSERT_HEAD(&unp_defdiscard_head
, d
, next
);
2331 spin_unlock(&unp_defdiscard_spin
);
2333 taskqueue_enqueue(unp_taskqueue
, &unp_defdiscard_task
);
2335 /* This fp is not a Unix domain socket */
2342 * unp_token must be held before calling this function to avoid name
2343 * resolution and v_socket accessing races, especially racing against
2347 * For anyone caring about unconnected Unix domain socket sending
2348 * performance, other approach could be taken...
2351 unp_find_lockref(struct sockaddr
*nam
, struct thread
*td
, short type
,
2352 struct unpcb
**unp_ret
)
2354 struct proc
*p
= td
->td_proc
;
2355 struct sockaddr_un
*soun
= (struct sockaddr_un
*)nam
;
2356 struct vnode
*vp
= NULL
;
2360 struct nlookupdata nd
;
2361 char buf
[SOCK_MAXADDRLEN
];
2363 ASSERT_LWKT_TOKEN_HELD(&unp_token
);
2367 len
= nam
->sa_len
- offsetof(struct sockaddr_un
, sun_path
);
2372 strncpy(buf
, soun
->sun_path
, len
);
2375 error
= nlookup_init(&nd
, buf
, UIO_SYSSPACE
, NLC_FOLLOW
);
2377 error
= nlookup(&nd
);
2379 error
= cache_vget(&nd
.nl_nch
, nd
.nl_cred
, LK_EXCLUSIVE
, &vp
);
2386 if (vp
->v_type
!= VSOCK
) {
2390 error
= VOP_EACCESS(vp
, VWRITE
, p
->p_ucred
);
2395 error
= ECONNREFUSED
;
2398 if (so
->so_type
!= type
) {
2403 /* Lock this unp. */
2404 unp
= unp_getsocktoken(so
);
2405 if (!UNP_ISATTACHED(unp
)) {
2407 error
= ECONNREFUSED
;
2410 /* And keep this unp referenced. */
2423 unp_connect_pair(struct unpcb
*unp
, struct unpcb
*unp2
)
2425 struct socket
*so
= unp
->unp_socket
;
2426 struct socket
*so2
= unp2
->unp_socket
;
2428 ASSERT_LWKT_TOKEN_HELD(&unp_token
);
2429 UNP_ASSERT_TOKEN_HELD(unp
);
2430 UNP_ASSERT_TOKEN_HELD(unp2
);
2432 KASSERT(so
->so_type
== so2
->so_type
,
2433 ("socket type mismatch, so %d, so2 %d", so
->so_type
, so2
->so_type
));
2435 if (!UNP_ISATTACHED(unp
))
2437 if (!UNP_ISATTACHED(unp2
))
2438 return ECONNREFUSED
;
2440 KASSERT(unp
->unp_conn
== NULL
, ("unp is already connected"));
2441 unp
->unp_conn
= unp2
;
2443 switch (so
->so_type
) {
2445 LIST_INSERT_HEAD(&unp2
->unp_refs
, unp
, unp_reflink
);
2450 case SOCK_SEQPACKET
:
2451 KASSERT(unp2
->unp_conn
== NULL
, ("unp2 is already connected"));
2452 unp2
->unp_conn
= unp
;
2458 panic("unp_connect_pair: unknown socket type %d", so
->so_type
);
2464 unp_drop(struct unpcb
*unp
, int error
)
2466 struct unp_global_head
*head
;
2469 ASSERT_LWKT_TOKEN_HELD(&unp_token
);
2470 UNP_ASSERT_TOKEN_HELD(unp
);
2472 KASSERT((unp
->unp_flags
& (UNP_DETACHED
| UNP_DROPPED
)) == 0,
2473 ("unp is dropped"));
2475 /* Mark this unp as detached. */
2476 unp_setflags(unp
, UNP_DETACHED
);
2478 /* Remove this unp from the global unp list. */
2479 head
= unp_globalhead(unp
->unp_socket
->so_type
);
2480 KASSERT(head
->count
> 0, ("invalid unp count"));
2481 TAILQ_REMOVE(&head
->list
, unp
, unp_link
);
2484 /* Disconnect all. */
2485 unp_disconnect(unp
, error
);
2486 while ((unp2
= LIST_FIRST(&unp
->unp_refs
)) != NULL
) {
2487 lwkt_getpooltoken(unp2
);
2488 unp_disconnect(unp2
, ECONNRESET
);
2489 lwkt_relpooltoken(unp2
);
2491 unp_setflags(unp
, UNP_DROPPED
);
2493 /* Try freeing this unp. */
2498 unp_defdiscard_taskfunc(void *arg __unused
, int pending __unused
)
2500 struct unp_defdiscard
*d
;
2502 spin_lock(&unp_defdiscard_spin
);
2503 while ((d
= SLIST_FIRST(&unp_defdiscard_head
)) != NULL
) {
2504 SLIST_REMOVE_HEAD(&unp_defdiscard_head
, next
);
2505 spin_unlock(&unp_defdiscard_spin
);
2510 spin_lock(&unp_defdiscard_spin
);
2512 spin_unlock(&unp_defdiscard_spin
);