uipc: Use token for rights counting
[dragonfly.git] / sys / kern / uipc_usrreq.c
blob6a6e5d3400eedf43ee9a93d8141bb83baca520b5
1 /*
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
7 * are met:
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
27 * SUCH DAMAGE.
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> */
39 #include <sys/proc.h>
40 #include <sys/file.h>
41 #include <sys/filedesc.h>
42 #include <sys/mbuf.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>
48 #include <sys/stat.h>
49 #include <sys/mount.h>
50 #include <sys/sysctl.h>
51 #include <sys/un.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>
62 #define UNP_DETACHED UNP_PRIVATE1
63 #define UNP_CONNECTING UNP_PRIVATE2
64 #define UNP_DROPPED UNP_PRIVATE3
65 #define UNP_MARKER UNP_PRIVATE4
67 /* For unp_internalize() and unp_externalize() */
68 CTASSERT(sizeof(struct file *) >= sizeof(int));
70 #define UNP_ISATTACHED(unp) \
71 ((unp) != NULL && ((unp)->unp_flags & UNP_DETACHED) == 0)
73 #ifdef INVARIANTS
74 #define UNP_ASSERT_TOKEN_HELD(unp) \
75 ASSERT_LWKT_TOKEN_HELD(lwkt_token_pool_lookup((unp)))
76 #else /* !INVARIANTS */
77 #define UNP_ASSERT_TOKEN_HELD(unp)
78 #endif /* INVARIANTS */
80 struct unp_defdiscard {
81 SLIST_ENTRY(unp_defdiscard) next;
82 struct file *fp;
84 SLIST_HEAD(unp_defdiscard_list, unp_defdiscard);
86 TAILQ_HEAD(unpcb_qhead, unpcb);
87 struct unp_global_head {
88 struct unpcb_qhead list;
89 int count;
92 static MALLOC_DEFINE(M_UNPCB, "unpcb", "unpcb struct");
93 static unp_gen_t unp_gencnt;
95 static struct unp_global_head unp_stream_head;
96 static struct unp_global_head unp_dgram_head;
97 static struct unp_global_head unp_seqpkt_head;
99 static struct lwkt_token unp_token = LWKT_TOKEN_INITIALIZER(unp_token);
100 static struct taskqueue *unp_taskqueue;
102 static struct unp_defdiscard_list unp_defdiscard_head;
103 static struct spinlock unp_defdiscard_spin;
104 static struct task unp_defdiscard_task;
107 * Unix communications domain.
109 * TODO:
110 * RDM
111 * rethink name space problems
112 * need a proper out-of-band
113 * lock pushdown
115 static struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
116 static ino_t unp_ino = 1; /* prototype for fake inode numbers */
118 static int unp_attach (struct socket *, struct pru_attach_info *);
119 static void unp_detach (struct unpcb *);
120 static int unp_bind (struct unpcb *,struct sockaddr *, struct thread *);
121 static int unp_connect (struct socket *,struct sockaddr *,
122 struct thread *);
123 static void unp_disconnect(struct unpcb *, int);
124 static void unp_shutdown (struct unpcb *);
125 static void unp_gc (void);
126 static int unp_gc_clearmarks(struct file *, void *);
127 static int unp_gc_checkmarks(struct file *, void *);
128 static int unp_gc_checkrefs(struct file *, void *);
129 static void unp_scan (struct mbuf *, void (*)(struct file *, void *),
130 void *data);
131 static void unp_mark (struct file *, void *data);
132 static void unp_discard (struct file *, void *);
133 static int unp_internalize (struct mbuf *, struct thread *);
134 static int unp_listen (struct unpcb *, struct thread *);
135 static void unp_fp_externalize(struct lwp *lp, struct file *fp, int fd,
136 int flags);
137 static int unp_find_lockref(struct sockaddr *nam, struct thread *td,
138 short type, struct unpcb **unp_ret);
139 static int unp_connect_pair(struct unpcb *unp, struct unpcb *unp2);
140 static void unp_drop(struct unpcb *unp, int error);
141 static void unp_defdiscard_taskfunc(void *, int);
143 static int unp_rights; /* file descriptors in flight */
144 static struct lwkt_token unp_rights_token =
145 LWKT_TOKEN_INITIALIZER(unp_rights_token);
147 SYSCTL_DECL(_net_local);
148 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
149 "File descriptors in flight");
152 * SMP Considerations:
154 * Since unp_token will be automaticly released upon execution of
155 * blocking code, we need to reference unp_conn before any possible
156 * blocking code to prevent it from being ripped behind our back.
158 * Any adjustment to unp->unp_conn requires both the global unp_token
159 * AND the per-unp token (lwkt_token_pool_lookup(unp)) to be held.
161 * Any access to so_pcb to obtain unp requires the pool token for
162 * unp to be held.
165 static __inline void
166 unp_reference(struct unpcb *unp)
168 /* 0->1 transition will not work */
169 KKASSERT(unp->unp_refcnt > 0);
170 atomic_add_int(&unp->unp_refcnt, 1);
173 static __inline void
174 unp_free(struct unpcb *unp)
176 KKASSERT(unp->unp_refcnt > 0);
177 if (atomic_fetchadd_int(&unp->unp_refcnt, -1) == 1)
178 unp_detach(unp);
181 static __inline struct unpcb *
182 unp_getsocktoken(struct socket *so)
184 struct unpcb *unp;
187 * The unp pointer is invalid until we verify that it is
188 * good by re-checking so_pcb AFTER obtaining the token.
190 while ((unp = so->so_pcb) != NULL) {
191 lwkt_getpooltoken(unp);
192 if (unp == so->so_pcb)
193 break;
194 lwkt_relpooltoken(unp);
196 return unp;
199 static __inline void
200 unp_reltoken(struct unpcb *unp)
202 if (unp != NULL)
203 lwkt_relpooltoken(unp);
206 static __inline void
207 unp_setflags(struct unpcb *unp, int flags)
209 atomic_set_int(&unp->unp_flags, flags);
212 static __inline void
213 unp_clrflags(struct unpcb *unp, int flags)
215 atomic_clear_int(&unp->unp_flags, flags);
218 static __inline struct unp_global_head *
219 unp_globalhead(short type)
221 switch (type) {
222 case SOCK_STREAM:
223 return &unp_stream_head;
224 case SOCK_DGRAM:
225 return &unp_dgram_head;
226 case SOCK_SEQPACKET:
227 return &unp_seqpkt_head;
228 default:
229 panic("unknown socket type %d", type);
233 static __inline void
234 unp_add_right(struct file *fp)
236 ASSERT_LWKT_TOKEN_HELD(&unp_rights_token);
237 fp->f_msgcount++;
238 unp_rights++;
241 static __inline void
242 unp_del_right(struct file *fp)
244 ASSERT_LWKT_TOKEN_HELD(&unp_rights_token);
245 fp->f_msgcount--;
246 unp_rights--;
250 * NOTE: (so) is referenced from soabort*() and netmsg_pru_abort()
251 * will sofree() it when we return.
253 static void
254 uipc_abort(netmsg_t msg)
256 struct unpcb *unp;
257 int error;
259 lwkt_gettoken(&unp_token);
260 unp = unp_getsocktoken(msg->base.nm_so);
262 if (UNP_ISATTACHED(unp)) {
263 unp_drop(unp, ECONNABORTED);
264 error = 0;
265 } else {
266 error = EINVAL;
269 unp_reltoken(unp);
270 lwkt_reltoken(&unp_token);
272 lwkt_replymsg(&msg->lmsg, error);
275 static void
276 uipc_accept(netmsg_t msg)
278 struct unpcb *unp;
279 int error;
281 lwkt_gettoken(&unp_token);
282 unp = unp_getsocktoken(msg->base.nm_so);
284 if (!UNP_ISATTACHED(unp)) {
285 error = EINVAL;
286 } else {
287 struct unpcb *unp2 = unp->unp_conn;
290 * Pass back name of connected socket,
291 * if it was bound and we are still connected
292 * (our peer may have closed already!).
294 if (unp2 && unp2->unp_addr) {
295 unp_reference(unp2);
296 *msg->accept.nm_nam = dup_sockaddr(
297 (struct sockaddr *)unp2->unp_addr);
298 unp_free(unp2);
299 } else {
300 *msg->accept.nm_nam = dup_sockaddr(&sun_noname);
302 error = 0;
305 unp_reltoken(unp);
306 lwkt_reltoken(&unp_token);
308 lwkt_replymsg(&msg->lmsg, error);
311 static void
312 uipc_attach(netmsg_t msg)
314 int error;
316 lwkt_gettoken(&unp_token);
318 KASSERT(msg->base.nm_so->so_pcb == NULL, ("double unp attach"));
319 error = unp_attach(msg->base.nm_so, msg->attach.nm_ai);
321 lwkt_reltoken(&unp_token);
322 lwkt_replymsg(&msg->lmsg, error);
325 static void
326 uipc_bind(netmsg_t msg)
328 struct unpcb *unp;
329 int error;
331 lwkt_gettoken(&unp_token);
332 unp = unp_getsocktoken(msg->base.nm_so);
334 if (UNP_ISATTACHED(unp))
335 error = unp_bind(unp, msg->bind.nm_nam, msg->bind.nm_td);
336 else
337 error = EINVAL;
339 unp_reltoken(unp);
340 lwkt_reltoken(&unp_token);
342 lwkt_replymsg(&msg->lmsg, error);
345 static void
346 uipc_connect(netmsg_t msg)
348 int error;
350 error = unp_connect(msg->base.nm_so, msg->connect.nm_nam,
351 msg->connect.nm_td);
352 lwkt_replymsg(&msg->lmsg, error);
355 static void
356 uipc_connect2(netmsg_t msg)
358 int error;
360 error = unp_connect2(msg->connect2.nm_so1, msg->connect2.nm_so2);
361 lwkt_replymsg(&msg->lmsg, error);
364 /* control is EOPNOTSUPP */
366 static void
367 uipc_detach(netmsg_t msg)
369 struct unpcb *unp;
370 int error;
372 lwkt_gettoken(&unp_token);
373 unp = unp_getsocktoken(msg->base.nm_so);
375 if (UNP_ISATTACHED(unp)) {
376 unp_drop(unp, 0);
377 error = 0;
378 } else {
379 error = EINVAL;
382 unp_reltoken(unp);
383 lwkt_reltoken(&unp_token);
385 lwkt_replymsg(&msg->lmsg, error);
388 static void
389 uipc_disconnect(netmsg_t msg)
391 struct unpcb *unp;
392 int error;
394 lwkt_gettoken(&unp_token);
395 unp = unp_getsocktoken(msg->base.nm_so);
397 if (UNP_ISATTACHED(unp)) {
398 unp_disconnect(unp, 0);
399 error = 0;
400 } else {
401 error = EINVAL;
404 unp_reltoken(unp);
405 lwkt_reltoken(&unp_token);
407 lwkt_replymsg(&msg->lmsg, error);
410 static void
411 uipc_listen(netmsg_t msg)
413 struct unpcb *unp;
414 int error;
416 lwkt_gettoken(&unp_token);
417 unp = unp_getsocktoken(msg->base.nm_so);
419 if (!UNP_ISATTACHED(unp) || unp->unp_vnode == NULL)
420 error = EINVAL;
421 else
422 error = unp_listen(unp, msg->listen.nm_td);
424 unp_reltoken(unp);
425 lwkt_reltoken(&unp_token);
427 lwkt_replymsg(&msg->lmsg, error);
430 static void
431 uipc_peeraddr(netmsg_t msg)
433 struct unpcb *unp;
434 int error;
436 lwkt_gettoken(&unp_token);
437 unp = unp_getsocktoken(msg->base.nm_so);
439 if (!UNP_ISATTACHED(unp)) {
440 error = EINVAL;
441 } else if (unp->unp_conn && unp->unp_conn->unp_addr) {
442 struct unpcb *unp2 = unp->unp_conn;
444 unp_reference(unp2);
445 *msg->peeraddr.nm_nam = dup_sockaddr(
446 (struct sockaddr *)unp2->unp_addr);
447 unp_free(unp2);
448 error = 0;
449 } else {
451 * XXX: It seems that this test always fails even when
452 * connection is established. So, this else clause is
453 * added as workaround to return PF_LOCAL sockaddr.
455 *msg->peeraddr.nm_nam = dup_sockaddr(&sun_noname);
456 error = 0;
459 unp_reltoken(unp);
460 lwkt_reltoken(&unp_token);
462 lwkt_replymsg(&msg->lmsg, error);
465 static void
466 uipc_rcvd(netmsg_t msg)
468 struct unpcb *unp, *unp2;
469 struct socket *so;
470 struct socket *so2;
471 int error;
474 * so_pcb is only modified with both the global and the unp
475 * pool token held.
477 so = msg->base.nm_so;
478 unp = unp_getsocktoken(so);
480 if (!UNP_ISATTACHED(unp)) {
481 error = EINVAL;
482 goto done;
485 switch (so->so_type) {
486 case SOCK_DGRAM:
487 panic("uipc_rcvd DGRAM?");
488 /*NOTREACHED*/
489 case SOCK_STREAM:
490 case SOCK_SEQPACKET:
491 if (unp->unp_conn == NULL)
492 break;
493 unp2 = unp->unp_conn; /* protected by pool token */
496 * Because we are transfering mbufs directly to the
497 * peer socket we have to use SSB_STOP on the sender
498 * to prevent it from building up infinite mbufs.
500 * As in several places in this module w ehave to ref unp2
501 * to ensure that it does not get ripped out from under us
502 * if we block on the so2 token or in sowwakeup().
504 so2 = unp2->unp_socket;
505 unp_reference(unp2);
506 lwkt_gettoken(&so2->so_rcv.ssb_token);
507 if (so->so_rcv.ssb_cc < so2->so_snd.ssb_hiwat &&
508 so->so_rcv.ssb_mbcnt < so2->so_snd.ssb_mbmax
510 atomic_clear_int(&so2->so_snd.ssb_flags, SSB_STOP);
512 sowwakeup(so2);
514 lwkt_reltoken(&so2->so_rcv.ssb_token);
515 unp_free(unp2);
516 break;
517 default:
518 panic("uipc_rcvd unknown socktype");
519 /*NOTREACHED*/
521 error = 0;
522 done:
523 unp_reltoken(unp);
524 lwkt_replymsg(&msg->lmsg, error);
527 /* pru_rcvoob is EOPNOTSUPP */
529 static void
530 uipc_send(netmsg_t msg)
532 struct unpcb *unp, *unp2;
533 struct socket *so;
534 struct socket *so2;
535 struct mbuf *control;
536 struct mbuf *m;
537 int error = 0;
539 so = msg->base.nm_so;
540 control = msg->send.nm_control;
541 m = msg->send.nm_m;
544 * so_pcb is only modified with both the global and the unp
545 * pool token held.
547 so = msg->base.nm_so;
548 unp = unp_getsocktoken(so);
550 if (!UNP_ISATTACHED(unp)) {
551 error = EINVAL;
552 goto release;
555 if (msg->send.nm_flags & PRUS_OOB) {
556 error = EOPNOTSUPP;
557 goto release;
560 wakeup_start_delayed();
562 if (control && (error = unp_internalize(control, msg->send.nm_td)))
563 goto release;
565 switch (so->so_type) {
566 case SOCK_DGRAM:
568 struct sockaddr *from;
570 if (msg->send.nm_addr) {
571 if (unp->unp_conn) {
572 error = EISCONN;
573 break;
575 lwkt_gettoken(&unp_token);
576 error = unp_find_lockref(msg->send.nm_addr,
577 msg->send.nm_td, so->so_type, &unp2);
578 lwkt_reltoken(&unp_token);
579 if (error)
580 break;
582 * NOTE:
583 * unp2 is locked and referenced.
585 * We could unlock unp2 now, since it was checked
586 * and referenced.
588 unp_reltoken(unp2);
589 } else {
590 if (unp->unp_conn == NULL) {
591 error = ENOTCONN;
592 break;
594 unp2 = unp->unp_conn;
595 unp_reference(unp2);
597 /* NOTE: unp2 is referenced. */
598 so2 = unp2->unp_socket;
600 if (unp->unp_addr)
601 from = (struct sockaddr *)unp->unp_addr;
602 else
603 from = &sun_noname;
605 lwkt_gettoken(&so2->so_rcv.ssb_token);
606 if (ssb_appendaddr(&so2->so_rcv, from, m, control)) {
607 sorwakeup(so2);
608 m = NULL;
609 control = NULL;
610 } else {
611 error = ENOBUFS;
613 lwkt_reltoken(&so2->so_rcv.ssb_token);
615 unp_free(unp2);
616 break;
619 case SOCK_STREAM:
620 case SOCK_SEQPACKET:
621 /* Connect if not connected yet. */
623 * Note: A better implementation would complain
624 * if not equal to the peer's address.
626 if (unp->unp_conn == NULL) {
627 if (msg->send.nm_addr) {
628 error = unp_connect(so,
629 msg->send.nm_addr,
630 msg->send.nm_td);
631 if (error)
632 break; /* XXX */
635 * NOTE:
636 * unp_conn still could be NULL, even if the
637 * above unp_connect() succeeds; since the
638 * current unp's token could be released due
639 * to blocking operations after unp_conn is
640 * assigned.
642 if (unp->unp_conn == NULL) {
643 error = ENOTCONN;
644 break;
647 if (so->so_state & SS_CANTSENDMORE) {
648 error = EPIPE;
649 break;
652 unp2 = unp->unp_conn;
653 KASSERT(unp2 != NULL, ("unp is not connected"));
654 so2 = unp2->unp_socket;
656 unp_reference(unp2);
659 * Send to paired receive port, and then reduce
660 * send buffer hiwater marks to maintain backpressure.
661 * Wake up readers.
663 lwkt_gettoken(&so2->so_rcv.ssb_token);
664 if (control) {
665 if (ssb_appendcontrol(&so2->so_rcv, m, control)) {
666 control = NULL;
667 m = NULL;
669 } else if (so->so_type == SOCK_SEQPACKET) {
670 sbappendrecord(&so2->so_rcv.sb, m);
671 m = NULL;
672 } else {
673 sbappend(&so2->so_rcv.sb, m);
674 m = NULL;
678 * Because we are transfering mbufs directly to the
679 * peer socket we have to use SSB_STOP on the sender
680 * to prevent it from building up infinite mbufs.
682 if (so2->so_rcv.ssb_cc >= so->so_snd.ssb_hiwat ||
683 so2->so_rcv.ssb_mbcnt >= so->so_snd.ssb_mbmax
685 atomic_set_int(&so->so_snd.ssb_flags, SSB_STOP);
687 lwkt_reltoken(&so2->so_rcv.ssb_token);
688 sorwakeup(so2);
690 unp_free(unp2);
691 break;
693 default:
694 panic("uipc_send unknown socktype");
698 * SEND_EOF is equivalent to a SEND followed by a SHUTDOWN.
700 if (msg->send.nm_flags & PRUS_EOF) {
701 socantsendmore(so);
702 unp_shutdown(unp);
705 if (control && error != 0)
706 unp_dispose(control);
707 release:
708 unp_reltoken(unp);
709 wakeup_end_delayed();
711 if (control)
712 m_freem(control);
713 if (m)
714 m_freem(m);
715 lwkt_replymsg(&msg->lmsg, error);
719 * MPSAFE
721 static void
722 uipc_sense(netmsg_t msg)
724 struct unpcb *unp;
725 struct socket *so;
726 struct stat *sb;
727 int error;
729 so = msg->base.nm_so;
730 sb = msg->sense.nm_stat;
733 * so_pcb is only modified with both the global and the unp
734 * pool token held.
736 unp = unp_getsocktoken(so);
738 if (!UNP_ISATTACHED(unp)) {
739 error = EINVAL;
740 goto done;
743 sb->st_blksize = so->so_snd.ssb_hiwat;
744 sb->st_dev = NOUDEV;
745 if (unp->unp_ino == 0) { /* make up a non-zero inode number */
746 unp->unp_ino = atomic_fetchadd_long(&unp_ino, 1);
747 if (__predict_false(unp->unp_ino == 0))
748 unp->unp_ino = atomic_fetchadd_long(&unp_ino, 1);
750 sb->st_ino = unp->unp_ino;
751 error = 0;
752 done:
753 unp_reltoken(unp);
754 lwkt_replymsg(&msg->lmsg, error);
757 static void
758 uipc_shutdown(netmsg_t msg)
760 struct socket *so;
761 struct unpcb *unp;
762 int error;
765 * so_pcb is only modified with both the global and the unp
766 * pool token held.
768 so = msg->base.nm_so;
769 unp = unp_getsocktoken(so);
771 if (UNP_ISATTACHED(unp)) {
772 socantsendmore(so);
773 unp_shutdown(unp);
774 error = 0;
775 } else {
776 error = EINVAL;
779 unp_reltoken(unp);
780 lwkt_replymsg(&msg->lmsg, error);
783 static void
784 uipc_sockaddr(netmsg_t msg)
786 struct unpcb *unp;
787 int error;
790 * so_pcb is only modified with both the global and the unp
791 * pool token held.
793 unp = unp_getsocktoken(msg->base.nm_so);
795 if (UNP_ISATTACHED(unp)) {
796 if (unp->unp_addr) {
797 *msg->sockaddr.nm_nam =
798 dup_sockaddr((struct sockaddr *)unp->unp_addr);
800 error = 0;
801 } else {
802 error = EINVAL;
805 unp_reltoken(unp);
806 lwkt_replymsg(&msg->lmsg, error);
809 struct pr_usrreqs uipc_usrreqs = {
810 .pru_abort = uipc_abort,
811 .pru_accept = uipc_accept,
812 .pru_attach = uipc_attach,
813 .pru_bind = uipc_bind,
814 .pru_connect = uipc_connect,
815 .pru_connect2 = uipc_connect2,
816 .pru_control = pr_generic_notsupp,
817 .pru_detach = uipc_detach,
818 .pru_disconnect = uipc_disconnect,
819 .pru_listen = uipc_listen,
820 .pru_peeraddr = uipc_peeraddr,
821 .pru_rcvd = uipc_rcvd,
822 .pru_rcvoob = pr_generic_notsupp,
823 .pru_send = uipc_send,
824 .pru_sense = uipc_sense,
825 .pru_shutdown = uipc_shutdown,
826 .pru_sockaddr = uipc_sockaddr,
827 .pru_sosend = sosend,
828 .pru_soreceive = soreceive
831 void
832 uipc_ctloutput(netmsg_t msg)
834 struct socket *so;
835 struct sockopt *sopt;
836 struct unpcb *unp;
837 int error = 0;
839 so = msg->base.nm_so;
840 sopt = msg->ctloutput.nm_sopt;
842 lwkt_gettoken(&unp_token);
843 unp = unp_getsocktoken(so);
845 if (!UNP_ISATTACHED(unp)) {
846 error = EINVAL;
847 goto done;
850 switch (sopt->sopt_dir) {
851 case SOPT_GET:
852 switch (sopt->sopt_name) {
853 case LOCAL_PEERCRED:
854 if (unp->unp_flags & UNP_HAVEPC)
855 soopt_from_kbuf(sopt, &unp->unp_peercred,
856 sizeof(unp->unp_peercred));
857 else {
858 if (so->so_type == SOCK_STREAM)
859 error = ENOTCONN;
860 else if (so->so_type == SOCK_SEQPACKET)
861 error = ENOTCONN;
862 else
863 error = EINVAL;
865 break;
866 default:
867 error = EOPNOTSUPP;
868 break;
870 break;
871 case SOPT_SET:
872 default:
873 error = EOPNOTSUPP;
874 break;
877 done:
878 unp_reltoken(unp);
879 lwkt_reltoken(&unp_token);
881 lwkt_replymsg(&msg->lmsg, error);
885 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
886 * for stream sockets, although the total for sender and receiver is
887 * actually only PIPSIZ.
889 * Datagram sockets really use the sendspace as the maximum datagram size,
890 * and don't really want to reserve the sendspace. Their recvspace should
891 * be large enough for at least one max-size datagram plus address.
893 * We want the local send/recv space to be significant larger then lo0's
894 * mtu of 16384.
896 #ifndef PIPSIZ
897 #define PIPSIZ 57344
898 #endif
899 static u_long unpst_sendspace = PIPSIZ;
900 static u_long unpst_recvspace = PIPSIZ;
901 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
902 static u_long unpdg_recvspace = 4*1024;
904 SYSCTL_DECL(_net_local_seqpacket);
905 SYSCTL_DECL(_net_local_stream);
906 SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
907 &unpst_sendspace, 0, "Size of stream socket send buffer");
908 SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
909 &unpst_recvspace, 0, "Size of stream socket receive buffer");
911 SYSCTL_DECL(_net_local_dgram);
912 SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
913 &unpdg_sendspace, 0, "Max datagram socket size");
914 SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
915 &unpdg_recvspace, 0, "Size of datagram socket receive buffer");
917 static int
918 unp_attach(struct socket *so, struct pru_attach_info *ai)
920 struct unp_global_head *head;
921 struct unpcb *unp;
922 int error;
924 lwkt_gettoken(&unp_token);
926 if (so->so_snd.ssb_hiwat == 0 || so->so_rcv.ssb_hiwat == 0) {
927 switch (so->so_type) {
928 case SOCK_STREAM:
929 case SOCK_SEQPACKET:
930 error = soreserve(so, unpst_sendspace, unpst_recvspace,
931 ai->sb_rlimit);
932 break;
934 case SOCK_DGRAM:
935 error = soreserve(so, unpdg_sendspace, unpdg_recvspace,
936 ai->sb_rlimit);
937 break;
939 default:
940 panic("unp_attach");
942 if (error)
943 goto failed;
947 * In order to support sendfile we have to set either SSB_STOPSUPP
948 * or SSB_PREALLOC. Unix domain sockets use the SSB_STOP flow
949 * control mechanism.
951 if (so->so_type == SOCK_STREAM) {
952 atomic_set_int(&so->so_rcv.ssb_flags, SSB_STOPSUPP);
953 atomic_set_int(&so->so_snd.ssb_flags, SSB_STOPSUPP);
956 unp = kmalloc(sizeof(*unp), M_UNPCB, M_WAITOK | M_ZERO | M_NULLOK);
957 if (unp == NULL) {
958 error = ENOBUFS;
959 goto failed;
961 unp->unp_refcnt = 1;
962 unp->unp_gencnt = ++unp_gencnt;
963 LIST_INIT(&unp->unp_refs);
964 unp->unp_socket = so;
965 unp->unp_rvnode = ai->fd_rdir; /* jail cruft XXX JH */
966 so->so_pcb = (caddr_t)unp;
967 soreference(so);
969 head = unp_globalhead(so->so_type);
970 TAILQ_INSERT_TAIL(&head->list, unp, unp_link);
971 head->count++;
972 error = 0;
973 failed:
974 lwkt_reltoken(&unp_token);
975 return error;
978 static void
979 unp_detach(struct unpcb *unp)
981 struct socket *so;
983 lwkt_gettoken(&unp_token);
984 lwkt_getpooltoken(unp);
986 so = unp->unp_socket;
988 unp->unp_gencnt = ++unp_gencnt;
989 if (unp->unp_vnode) {
990 unp->unp_vnode->v_socket = NULL;
991 vrele(unp->unp_vnode);
992 unp->unp_vnode = NULL;
994 soisdisconnected(so);
995 KKASSERT(so->so_pcb == unp);
996 so->so_pcb = NULL; /* both tokens required */
997 unp->unp_socket = NULL;
999 lwkt_relpooltoken(unp);
1000 lwkt_reltoken(&unp_token);
1002 if (unp_rights) {
1004 * Normally the receive buffer is flushed later,
1005 * in sofree, but if our receive buffer holds references
1006 * to descriptors that are now garbage, we will dispose
1007 * of those descriptor references after the garbage collector
1008 * gets them (resulting in a "panic: fdrop: invalid f_count").
1010 sorflush(so);
1011 unp_gc();
1013 sofree(so);
1015 KASSERT(unp->unp_conn == NULL, ("unp is still connected"));
1016 KASSERT(LIST_EMPTY(&unp->unp_refs), ("unp still has references"));
1018 if (unp->unp_addr)
1019 kfree(unp->unp_addr, M_SONAME);
1020 kfree(unp, M_UNPCB);
1023 static int
1024 unp_bind(struct unpcb *unp, struct sockaddr *nam, struct thread *td)
1026 struct proc *p = td->td_proc;
1027 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1028 struct vnode *vp;
1029 struct vattr vattr;
1030 int error, namelen;
1031 struct nlookupdata nd;
1032 char buf[SOCK_MAXADDRLEN];
1034 ASSERT_LWKT_TOKEN_HELD(&unp_token);
1035 UNP_ASSERT_TOKEN_HELD(unp);
1037 if (unp->unp_vnode != NULL)
1038 return EINVAL;
1040 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
1041 if (namelen <= 0)
1042 return EINVAL;
1043 strncpy(buf, soun->sun_path, namelen);
1044 buf[namelen] = 0; /* null-terminate the string */
1045 error = nlookup_init(&nd, buf, UIO_SYSSPACE,
1046 NLC_LOCKVP | NLC_CREATE | NLC_REFDVP);
1047 if (error == 0)
1048 error = nlookup(&nd);
1049 if (error == 0 && nd.nl_nch.ncp->nc_vp != NULL)
1050 error = EADDRINUSE;
1051 if (error)
1052 goto done;
1054 VATTR_NULL(&vattr);
1055 vattr.va_type = VSOCK;
1056 vattr.va_mode = (ACCESSPERMS & ~p->p_fd->fd_cmask);
1057 error = VOP_NCREATE(&nd.nl_nch, nd.nl_dvp, &vp, nd.nl_cred, &vattr);
1058 if (error == 0) {
1059 if (unp->unp_vnode == NULL) {
1060 vp->v_socket = unp->unp_socket;
1061 unp->unp_vnode = vp;
1062 unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam);
1063 vn_unlock(vp);
1064 } else {
1065 vput(vp); /* late race */
1066 error = EINVAL;
1069 done:
1070 nlookup_done(&nd);
1071 return (error);
1074 static int
1075 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1077 struct unpcb *unp, *unp2;
1078 int error, flags = 0;
1080 lwkt_gettoken(&unp_token);
1082 unp = unp_getsocktoken(so);
1083 if (!UNP_ISATTACHED(unp)) {
1084 error = EINVAL;
1085 goto failed;
1088 if ((unp->unp_flags & UNP_CONNECTING) || unp->unp_conn != NULL) {
1089 error = EISCONN;
1090 goto failed;
1093 flags = UNP_CONNECTING;
1094 unp_setflags(unp, flags);
1096 error = unp_find_lockref(nam, td, so->so_type, &unp2);
1097 if (error)
1098 goto failed;
1100 * NOTE:
1101 * unp2 is locked and referenced.
1104 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1105 struct socket *so2, *so3;
1106 struct unpcb *unp3;
1108 so2 = unp2->unp_socket;
1109 if (!(so2->so_options & SO_ACCEPTCONN) ||
1110 (so3 = sonewconn_faddr(so2, 0, NULL,
1111 TRUE /* keep ref */)) == NULL) {
1112 error = ECONNREFUSED;
1113 goto done;
1115 /* so3 has a socket reference. */
1117 unp3 = unp_getsocktoken(so3);
1118 if (!UNP_ISATTACHED(unp3)) {
1119 unp_reltoken(unp3);
1121 * Already aborted; we only need to drop the
1122 * socket reference held by sonewconn_faddr().
1124 sofree(so3);
1125 error = ECONNREFUSED;
1126 goto done;
1128 unp_reference(unp3);
1130 * NOTE:
1131 * unp3 is locked and referenced.
1135 * Release so3 socket reference held by sonewconn_faddr().
1136 * Since we have referenced unp3, neither unp3 nor so3 will
1137 * be destroyed here.
1139 sofree(so3);
1141 if (unp2->unp_addr != NULL) {
1142 unp3->unp_addr = (struct sockaddr_un *)
1143 dup_sockaddr((struct sockaddr *)unp2->unp_addr);
1147 * unp_peercred management:
1149 * The connecter's (client's) credentials are copied
1150 * from its process structure at the time of connect()
1151 * (which is now).
1153 cru2x(td->td_proc->p_ucred, &unp3->unp_peercred);
1154 unp_setflags(unp3, UNP_HAVEPC);
1156 * The receiver's (server's) credentials are copied
1157 * from the unp_peercred member of socket on which the
1158 * former called listen(); unp_listen() cached that
1159 * process's credentials at that time so we can use
1160 * them now.
1162 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1163 ("unp_connect: listener without cached peercred"));
1164 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1165 sizeof(unp->unp_peercred));
1166 unp_setflags(unp, UNP_HAVEPC);
1168 error = unp_connect_pair(unp, unp3);
1169 if (error)
1170 soabort_direct(so3);
1172 /* Done with unp3 */
1173 unp_free(unp3);
1174 unp_reltoken(unp3);
1175 } else {
1176 error = unp_connect_pair(unp, unp2);
1178 done:
1179 unp_free(unp2);
1180 unp_reltoken(unp2);
1181 failed:
1182 if (flags)
1183 unp_clrflags(unp, flags);
1184 unp_reltoken(unp);
1186 lwkt_reltoken(&unp_token);
1187 return (error);
1191 * Connect two unix domain sockets together.
1193 * NOTE: Semantics for any change to unp_conn requires that the per-unp
1194 * pool token also be held.
1197 unp_connect2(struct socket *so, struct socket *so2)
1199 struct unpcb *unp, *unp2;
1200 int error;
1202 lwkt_gettoken(&unp_token);
1203 if (so2->so_type != so->so_type) {
1204 lwkt_reltoken(&unp_token);
1205 return (EPROTOTYPE);
1207 unp = unp_getsocktoken(so);
1208 unp2 = unp_getsocktoken(so2);
1210 if (!UNP_ISATTACHED(unp)) {
1211 error = EINVAL;
1212 goto done;
1214 if (!UNP_ISATTACHED(unp2)) {
1215 error = ECONNREFUSED;
1216 goto done;
1219 if (unp->unp_conn != NULL) {
1220 error = EISCONN;
1221 goto done;
1223 if ((so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET) &&
1224 unp2->unp_conn != NULL) {
1225 error = EISCONN;
1226 goto done;
1229 error = unp_connect_pair(unp, unp2);
1230 done:
1231 unp_reltoken(unp2);
1232 unp_reltoken(unp);
1233 lwkt_reltoken(&unp_token);
1234 return (error);
1238 * Disconnect a unix domain socket pair.
1240 * NOTE: Semantics for any change to unp_conn requires that the per-unp
1241 * pool token also be held.
1243 static void
1244 unp_disconnect(struct unpcb *unp, int error)
1246 struct socket *so = unp->unp_socket;
1247 struct unpcb *unp2;
1249 ASSERT_LWKT_TOKEN_HELD(&unp_token);
1250 UNP_ASSERT_TOKEN_HELD(unp);
1252 if (error)
1253 so->so_error = error;
1255 while ((unp2 = unp->unp_conn) != NULL) {
1256 lwkt_getpooltoken(unp2);
1257 if (unp2 == unp->unp_conn)
1258 break;
1259 lwkt_relpooltoken(unp2);
1261 if (unp2 == NULL)
1262 return;
1263 /* unp2 is locked. */
1265 KASSERT((unp2->unp_flags & UNP_DROPPED) == 0, ("unp2 was dropped"));
1267 unp->unp_conn = NULL;
1269 switch (so->so_type) {
1270 case SOCK_DGRAM:
1271 LIST_REMOVE(unp, unp_reflink);
1272 soclrstate(so, SS_ISCONNECTED);
1273 break;
1275 case SOCK_STREAM:
1276 case SOCK_SEQPACKET:
1278 * Keep a reference before clearing the unp_conn
1279 * to avoid racing uipc_detach()/uipc_abort() in
1280 * other thread.
1282 unp_reference(unp2);
1283 KASSERT(unp2->unp_conn == unp, ("unp_conn mismatch"));
1284 unp2->unp_conn = NULL;
1286 soisdisconnected(so);
1287 soisdisconnected(unp2->unp_socket);
1289 unp_free(unp2);
1290 break;
1293 lwkt_relpooltoken(unp2);
1296 #ifdef notdef
1297 void
1298 unp_abort(struct unpcb *unp)
1300 lwkt_gettoken(&unp_token);
1301 unp_free(unp);
1302 lwkt_reltoken(&unp_token);
1304 #endif
1306 static int
1307 prison_unpcb(struct thread *td, struct unpcb *unp)
1309 struct proc *p;
1311 if (td == NULL)
1312 return (0);
1313 if ((p = td->td_proc) == NULL)
1314 return (0);
1315 if (!p->p_ucred->cr_prison)
1316 return (0);
1317 if (p->p_fd->fd_rdir == unp->unp_rvnode)
1318 return (0);
1319 return (1);
1322 static int
1323 unp_pcblist(SYSCTL_HANDLER_ARGS)
1325 struct unp_global_head *head = arg1;
1326 int error, i, n;
1327 struct unpcb *unp, *marker;
1329 KKASSERT(curproc != NULL);
1332 * The process of preparing the PCB list is too time-consuming and
1333 * resource-intensive to repeat twice on every request.
1335 if (req->oldptr == NULL) {
1336 n = head->count;
1337 req->oldidx = (n + n/8) * sizeof(struct xunpcb);
1338 return 0;
1341 if (req->newptr != NULL)
1342 return EPERM;
1344 marker = kmalloc(sizeof(*marker), M_UNPCB, M_WAITOK | M_ZERO);
1345 marker->unp_flags |= UNP_MARKER;
1347 lwkt_gettoken(&unp_token);
1349 n = head->count;
1350 i = 0;
1351 error = 0;
1353 TAILQ_INSERT_HEAD(&head->list, marker, unp_link);
1354 while ((unp = TAILQ_NEXT(marker, unp_link)) != NULL && i < n) {
1355 struct xunpcb xu;
1357 TAILQ_REMOVE(&head->list, marker, unp_link);
1358 TAILQ_INSERT_AFTER(&head->list, unp, marker, unp_link);
1360 if (unp->unp_flags & UNP_MARKER)
1361 continue;
1362 if (prison_unpcb(req->td, unp))
1363 continue;
1365 xu.xu_len = sizeof(xu);
1366 xu.xu_unpp = unp;
1369 * NOTE:
1370 * unp->unp_addr and unp->unp_conn are protected by
1371 * unp_token. So if we want to get rid of unp_token
1372 * or reduce the coverage of unp_token, care must be
1373 * taken.
1375 if (unp->unp_addr) {
1376 bcopy(unp->unp_addr, &xu.xu_addr,
1377 unp->unp_addr->sun_len);
1379 if (unp->unp_conn && unp->unp_conn->unp_addr) {
1380 bcopy(unp->unp_conn->unp_addr,
1381 &xu.xu_caddr,
1382 unp->unp_conn->unp_addr->sun_len);
1384 bcopy(unp, &xu.xu_unp, sizeof(*unp));
1385 sotoxsocket(unp->unp_socket, &xu.xu_socket);
1387 /* NOTE: This could block and temporarily release unp_token */
1388 error = SYSCTL_OUT(req, &xu, sizeof(xu));
1389 if (error)
1390 break;
1391 ++i;
1393 TAILQ_REMOVE(&head->list, marker, unp_link);
1395 lwkt_reltoken(&unp_token);
1397 kfree(marker, M_UNPCB);
1398 return error;
1401 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1402 &unp_dgram_head, 0, unp_pcblist, "S,xunpcb",
1403 "List of active local datagram sockets");
1404 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1405 &unp_stream_head, 0, unp_pcblist, "S,xunpcb",
1406 "List of active local stream sockets");
1407 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist, CTLFLAG_RD,
1408 &unp_seqpkt_head, 0, unp_pcblist, "S,xunpcb",
1409 "List of active local seqpacket sockets");
1411 static void
1412 unp_shutdown(struct unpcb *unp)
1414 struct socket *so;
1416 if ((unp->unp_socket->so_type == SOCK_STREAM ||
1417 unp->unp_socket->so_type == SOCK_SEQPACKET) &&
1418 unp->unp_conn != NULL && (so = unp->unp_conn->unp_socket)) {
1419 socantrcvmore(so);
1423 #ifdef notdef
1424 void
1425 unp_drain(void)
1427 lwkt_gettoken(&unp_token);
1428 lwkt_reltoken(&unp_token);
1430 #endif
1433 unp_externalize(struct mbuf *rights, int flags)
1435 struct thread *td = curthread;
1436 struct proc *p = td->td_proc; /* XXX */
1437 struct lwp *lp = td->td_lwp;
1438 struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
1439 int *fdp;
1440 int i;
1441 struct file **rp;
1442 struct file *fp;
1443 int newfds = (cm->cmsg_len - (CMSG_DATA(cm) - (u_char *)cm))
1444 / sizeof(struct file *);
1445 int f;
1447 lwkt_gettoken(&unp_rights_token);
1450 * if the new FD's will not fit, then we free them all
1452 if (!fdavail(p, newfds)) {
1453 rp = (struct file **)CMSG_DATA(cm);
1454 for (i = 0; i < newfds; i++) {
1455 fp = *rp;
1457 * zero the pointer before calling unp_discard,
1458 * since it may end up in unp_gc()..
1460 *rp++ = NULL;
1461 unp_discard(fp, NULL);
1463 lwkt_reltoken(&unp_rights_token);
1464 return (EMSGSIZE);
1468 * now change each pointer to an fd in the global table to
1469 * an integer that is the index to the local fd table entry
1470 * that we set up to point to the global one we are transferring.
1471 * Since the sizeof(struct file *) is bigger than or equal to
1472 * the sizeof(int), we do it in forward order. In that case,
1473 * an integer will always come in the same place or before its
1474 * corresponding struct file pointer.
1476 * Hold revoke_token in 'shared' mode, so that we won't miss
1477 * the FREVOKED update on fps being externalized (fsetfd).
1479 lwkt_gettoken_shared(&revoke_token);
1480 fdp = (int *)CMSG_DATA(cm);
1481 rp = (struct file **)CMSG_DATA(cm);
1482 for (i = 0; i < newfds; i++) {
1483 if (fdalloc(p, 0, &f)) {
1484 int j;
1487 * Previous fdavail() can't garantee
1488 * fdalloc() success due to SMP race.
1489 * Just clean up and return the same
1490 * error value as if fdavail() failed.
1492 lwkt_reltoken(&revoke_token);
1494 /* Close externalized files */
1495 for (j = 0; j < i; j++)
1496 kern_close(fdp[j]);
1497 /* Discard the rest of internal files */
1498 for (; i < newfds; i++)
1499 unp_discard(rp[i], NULL);
1500 /* Wipe out the control message */
1501 for (i = 0; i < newfds; i++)
1502 rp[i] = NULL;
1504 lwkt_reltoken(&unp_rights_token);
1505 return (EMSGSIZE);
1507 fp = rp[i];
1508 unp_fp_externalize(lp, fp, f, flags);
1509 fdp[i] = f;
1511 lwkt_reltoken(&revoke_token);
1513 lwkt_reltoken(&unp_rights_token);
1516 * Adjust length, in case sizeof(struct file *) and sizeof(int)
1517 * differs.
1519 cm->cmsg_len = CMSG_LEN(newfds * sizeof(int));
1520 rights->m_len = cm->cmsg_len;
1522 return (0);
1525 static void
1526 unp_fp_externalize(struct lwp *lp, struct file *fp, int fd, int flags)
1528 if (lp) {
1529 struct filedesc *fdp = lp->lwp_proc->p_fd;
1531 KKASSERT(fd >= 0);
1532 if (fp->f_flag & FREVOKED) {
1533 struct file *fx;
1534 int error;
1536 kprintf("Warning: revoked fp exiting unix socket\n");
1537 error = falloc(lp, &fx, NULL);
1538 if (error == 0) {
1539 if (flags & MSG_CMSG_CLOEXEC)
1540 fdp->fd_files[fd].fileflags |= UF_EXCLOSE;
1541 fsetfd(fdp, fx, fd);
1542 fdrop(fx);
1543 } else {
1544 fsetfd(fdp, NULL, fd);
1546 } else {
1547 if (flags & MSG_CMSG_CLOEXEC)
1548 fdp->fd_files[fd].fileflags |= UF_EXCLOSE;
1549 fsetfd(fdp, fp, fd);
1552 unp_del_right(fp);
1553 fdrop(fp);
1556 void
1557 unp_init(void)
1559 TAILQ_INIT(&unp_stream_head.list);
1560 TAILQ_INIT(&unp_dgram_head.list);
1561 TAILQ_INIT(&unp_seqpkt_head.list);
1563 SLIST_INIT(&unp_defdiscard_head);
1564 spin_init(&unp_defdiscard_spin, "unpdisc");
1565 TASK_INIT(&unp_defdiscard_task, 0, unp_defdiscard_taskfunc, NULL);
1568 * Create taskqueue for defered discard, and stick it to
1569 * the last CPU.
1571 unp_taskqueue = taskqueue_create("unp_taskq", M_WAITOK,
1572 taskqueue_thread_enqueue, &unp_taskqueue);
1573 taskqueue_start_threads(&unp_taskqueue, 1, TDPRI_KERN_DAEMON,
1574 ncpus - 1, "unp taskq");
1577 static int
1578 unp_internalize(struct mbuf *control, struct thread *td)
1580 struct proc *p = td->td_proc;
1581 struct filedesc *fdescp;
1582 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1583 struct file **rp;
1584 struct file *fp;
1585 int i, fd, *fdp;
1586 struct cmsgcred *cmcred;
1587 int oldfds;
1588 u_int newlen;
1589 int error;
1591 KKASSERT(p);
1593 if ((cm->cmsg_type != SCM_RIGHTS && cm->cmsg_type != SCM_CREDS) ||
1594 cm->cmsg_level != SOL_SOCKET ||
1595 CMSG_ALIGN(cm->cmsg_len) != control->m_len)
1596 return EINVAL;
1599 * Fill in credential information.
1601 if (cm->cmsg_type == SCM_CREDS) {
1602 cmcred = (struct cmsgcred *)CMSG_DATA(cm);
1603 cmcred->cmcred_pid = p->p_pid;
1604 cmcred->cmcred_uid = p->p_ucred->cr_ruid;
1605 cmcred->cmcred_gid = p->p_ucred->cr_rgid;
1606 cmcred->cmcred_euid = p->p_ucred->cr_uid;
1607 cmcred->cmcred_ngroups = MIN(p->p_ucred->cr_ngroups,
1608 CMGROUP_MAX);
1609 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1610 cmcred->cmcred_groups[i] = p->p_ucred->cr_groups[i];
1611 return 0;
1615 * cmsghdr may not be aligned, do not allow calculation(s) to
1616 * go negative.
1618 if (cm->cmsg_len < CMSG_LEN(0))
1619 return EINVAL;
1621 oldfds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1624 * Now replace the integer FDs with pointers to
1625 * the associated global file table entry..
1626 * Allocate a bigger buffer as necessary. But if an cluster is not
1627 * enough, return E2BIG.
1629 newlen = CMSG_LEN(oldfds * sizeof(struct file *));
1630 if (newlen > MCLBYTES)
1631 return E2BIG;
1632 if (newlen - control->m_len > M_TRAILINGSPACE(control)) {
1633 if (control->m_flags & M_EXT)
1634 return E2BIG;
1635 MCLGET(control, M_WAITOK);
1636 if (!(control->m_flags & M_EXT))
1637 return ENOBUFS;
1639 /* copy the data to the cluster */
1640 memcpy(mtod(control, char *), cm, cm->cmsg_len);
1641 cm = mtod(control, struct cmsghdr *);
1644 lwkt_gettoken(&unp_rights_token);
1646 fdescp = p->p_fd;
1647 spin_lock_shared(&fdescp->fd_spin);
1650 * check that all the FDs passed in refer to legal OPEN files
1651 * If not, reject the entire operation.
1653 fdp = (int *)CMSG_DATA(cm);
1654 for (i = 0; i < oldfds; i++) {
1655 fd = *fdp++;
1656 if ((unsigned)fd >= fdescp->fd_nfiles ||
1657 fdescp->fd_files[fd].fp == NULL) {
1658 error = EBADF;
1659 goto done;
1661 if (fdescp->fd_files[fd].fp->f_type == DTYPE_KQUEUE) {
1662 error = EOPNOTSUPP;
1663 goto done;
1668 * Adjust length, in case sizeof(struct file *) and sizeof(int)
1669 * differs.
1671 cm->cmsg_len = newlen;
1672 control->m_len = CMSG_ALIGN(newlen);
1675 * Transform the file descriptors into struct file pointers.
1676 * Since the sizeof(struct file *) is bigger than or equal to
1677 * the sizeof(int), we do it in reverse order so that the int
1678 * won't get trashed until we're done.
1680 fdp = (int *)CMSG_DATA(cm) + oldfds - 1;
1681 rp = (struct file **)CMSG_DATA(cm) + oldfds - 1;
1682 for (i = 0; i < oldfds; i++) {
1683 fp = fdescp->fd_files[*fdp--].fp;
1684 *rp-- = fp;
1685 fhold(fp);
1686 unp_add_right(fp);
1688 error = 0;
1689 done:
1690 spin_unlock_shared(&fdescp->fd_spin);
1691 lwkt_reltoken(&unp_rights_token);
1692 return error;
1696 * Garbage collect in-transit file descriptors that get lost due to
1697 * loops (i.e. when a socket is sent to another process over itself,
1698 * and more complex situations).
1700 * NOT MPSAFE - TODO socket flush code and maybe fdrop. Rest is MPSAFE.
1703 struct unp_gc_info {
1704 struct file **extra_ref;
1705 struct file *locked_fp;
1706 int defer;
1707 int index;
1708 int maxindex;
1711 static void
1712 unp_gc(void)
1714 struct unp_gc_info info;
1715 static boolean_t unp_gcing;
1716 struct file **fpp;
1717 int i;
1720 * Only one gc can be in-progress at any given moment
1722 lwkt_gettoken(&unp_rights_token);
1723 if (unp_gcing) {
1724 lwkt_reltoken(&unp_rights_token);
1725 return;
1727 unp_gcing = TRUE;
1730 * Before going through all this, set all FDs to be NOT defered
1731 * and NOT externally accessible (not marked). During the scan
1732 * a fd can be marked externally accessible but we may or may not
1733 * be able to immediately process it (controlled by FDEFER).
1735 * If we loop sleep a bit. The complexity of the topology can cause
1736 * multiple loops. Also failure to acquire the socket's so_rcv
1737 * token can cause us to loop.
1739 allfiles_scan_exclusive(unp_gc_clearmarks, NULL);
1740 do {
1741 info.defer = 0;
1742 allfiles_scan_exclusive(unp_gc_checkmarks, &info);
1743 if (info.defer)
1744 tsleep(&info, 0, "gcagain", 1);
1745 } while (info.defer);
1748 * We grab an extra reference to each of the file table entries
1749 * that are not otherwise accessible and then free the rights
1750 * that are stored in messages on them.
1752 * The bug in the orginal code is a little tricky, so I'll describe
1753 * what's wrong with it here.
1755 * It is incorrect to simply unp_discard each entry for f_msgcount
1756 * times -- consider the case of sockets A and B that contain
1757 * references to each other. On a last close of some other socket,
1758 * we trigger a gc since the number of outstanding rights (unp_rights)
1759 * is non-zero. If during the sweep phase the gc code unp_discards,
1760 * we end up doing a (full) fdrop on the descriptor. A fdrop on A
1761 * results in the following chain. Closef calls soo_close, which
1762 * calls soclose. Soclose calls first (through the switch
1763 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1764 * returns because the previous instance had set unp_gcing, and
1765 * we return all the way back to soclose, which marks the socket
1766 * with SS_NOFDREF, and then calls sofree. Sofree calls sorflush
1767 * to free up the rights that are queued in messages on the socket A,
1768 * i.e., the reference on B. The sorflush calls via the dom_dispose
1769 * switch unp_dispose, which unp_scans with unp_discard. This second
1770 * instance of unp_discard just calls fdrop on B.
1772 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1773 * which results in another fdrop on A. Unfortunately, A is already
1774 * being closed, and the descriptor has already been marked with
1775 * SS_NOFDREF, and soclose panics at this point.
1777 * Here, we first take an extra reference to each inaccessible
1778 * descriptor. Then, we call sorflush ourself, since we know
1779 * it is a Unix domain socket anyhow. After we destroy all the
1780 * rights carried in messages, we do a last fdrop to get rid
1781 * of our extra reference. This is the last close, and the
1782 * unp_detach etc will shut down the socket.
1784 * 91/09/19, bsy@cs.cmu.edu
1786 info.extra_ref = kmalloc(256 * sizeof(struct file *), M_FILE, M_WAITOK);
1787 info.maxindex = 256;
1789 do {
1791 * Look for matches
1793 info.index = 0;
1794 allfiles_scan_exclusive(unp_gc_checkrefs, &info);
1797 * For each FD on our hit list, do the following two things
1799 for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp) {
1800 struct file *tfp = *fpp;
1801 if (tfp->f_type == DTYPE_SOCKET && tfp->f_data != NULL)
1802 sorflush((struct socket *)(tfp->f_data));
1804 for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp)
1805 fdrop(*fpp);
1806 } while (info.index == info.maxindex);
1808 kfree((caddr_t)info.extra_ref, M_FILE);
1809 unp_gcing = FALSE;
1811 lwkt_reltoken(&unp_rights_token);
1815 * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1817 static int
1818 unp_gc_checkrefs(struct file *fp, void *data)
1820 struct unp_gc_info *info = data;
1822 if (fp->f_count == 0)
1823 return(0);
1824 if (info->index == info->maxindex)
1825 return(-1);
1828 * If all refs are from msgs, and it's not marked accessible
1829 * then it must be referenced from some unreachable cycle
1830 * of (shut-down) FDs, so include it in our
1831 * list of FDs to remove
1833 if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1834 info->extra_ref[info->index++] = fp;
1835 fhold(fp);
1837 return(0);
1841 * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1843 static int
1844 unp_gc_clearmarks(struct file *fp, void *data __unused)
1846 atomic_clear_int(&fp->f_flag, FMARK | FDEFER);
1847 return(0);
1851 * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1853 static int
1854 unp_gc_checkmarks(struct file *fp, void *data)
1856 struct unp_gc_info *info = data;
1857 struct socket *so;
1860 * If the file is not open, skip it. Make sure it isn't marked
1861 * defered or we could loop forever, in case we somehow race
1862 * something.
1864 if (fp->f_count == 0) {
1865 if (fp->f_flag & FDEFER)
1866 atomic_clear_int(&fp->f_flag, FDEFER);
1867 return(0);
1870 * If we already marked it as 'defer' in a
1871 * previous pass, then try process it this time
1872 * and un-mark it
1874 if (fp->f_flag & FDEFER) {
1875 atomic_clear_int(&fp->f_flag, FDEFER);
1876 } else {
1878 * if it's not defered, then check if it's
1879 * already marked.. if so skip it
1881 if (fp->f_flag & FMARK)
1882 return(0);
1884 * If all references are from messages
1885 * in transit, then skip it. it's not
1886 * externally accessible.
1888 if (fp->f_count == fp->f_msgcount)
1889 return(0);
1891 * If it got this far then it must be
1892 * externally accessible.
1894 atomic_set_int(&fp->f_flag, FMARK);
1898 * either it was defered, or it is externally
1899 * accessible and not already marked so.
1900 * Now check if it is possibly one of OUR sockets.
1902 if (fp->f_type != DTYPE_SOCKET ||
1903 (so = (struct socket *)fp->f_data) == NULL) {
1904 return(0);
1906 if (so->so_proto->pr_domain != &localdomain ||
1907 !(so->so_proto->pr_flags & PR_RIGHTS)) {
1908 return(0);
1912 * So, Ok, it's one of our sockets and it IS externally accessible
1913 * (or was defered). Now we look to see if we hold any file
1914 * descriptors in its message buffers. Follow those links and mark
1915 * them as accessible too.
1917 * We are holding multiple spinlocks here, if we cannot get the
1918 * token non-blocking defer until the next loop.
1920 info->locked_fp = fp;
1921 if (lwkt_trytoken(&so->so_rcv.ssb_token)) {
1922 unp_scan(so->so_rcv.ssb_mb, unp_mark, info);
1923 lwkt_reltoken(&so->so_rcv.ssb_token);
1924 } else {
1925 atomic_set_int(&fp->f_flag, FDEFER);
1926 ++info->defer;
1928 return (0);
1932 * Dispose of the fp's stored in a mbuf.
1934 * The dds loop can cause additional fps to be entered onto the
1935 * list while it is running, flattening out the operation and avoiding
1936 * a deep kernel stack recursion.
1938 void
1939 unp_dispose(struct mbuf *m)
1941 lwkt_gettoken(&unp_rights_token);
1942 if (m)
1943 unp_scan(m, unp_discard, NULL);
1944 lwkt_reltoken(&unp_rights_token);
1947 static int
1948 unp_listen(struct unpcb *unp, struct thread *td)
1950 struct proc *p = td->td_proc;
1952 ASSERT_LWKT_TOKEN_HELD(&unp_token);
1953 UNP_ASSERT_TOKEN_HELD(unp);
1955 KKASSERT(p);
1956 cru2x(p->p_ucred, &unp->unp_peercred);
1957 unp_setflags(unp, UNP_HAVEPCCACHED);
1958 return (0);
1961 static void
1962 unp_scan(struct mbuf *m0, void (*op)(struct file *, void *), void *data)
1964 struct mbuf *m;
1965 struct file **rp;
1966 struct cmsghdr *cm;
1967 int i;
1968 int qfds;
1970 while (m0) {
1971 for (m = m0; m; m = m->m_next) {
1972 if (m->m_type == MT_CONTROL &&
1973 m->m_len >= sizeof(*cm)) {
1974 cm = mtod(m, struct cmsghdr *);
1975 if (cm->cmsg_level != SOL_SOCKET ||
1976 cm->cmsg_type != SCM_RIGHTS)
1977 continue;
1978 qfds = (cm->cmsg_len - CMSG_LEN(0)) /
1979 sizeof(void *);
1980 rp = (struct file **)CMSG_DATA(cm);
1981 for (i = 0; i < qfds; i++)
1982 (*op)(*rp++, data);
1983 break; /* XXX, but saves time */
1986 m0 = m0->m_nextpkt;
1991 * Mark visibility. info->defer is recalculated on every pass.
1993 static void
1994 unp_mark(struct file *fp, void *data)
1996 struct unp_gc_info *info = data;
1998 if ((fp->f_flag & FMARK) == 0) {
1999 ++info->defer;
2000 atomic_set_int(&fp->f_flag, FMARK | FDEFER);
2001 } else if (fp->f_flag & FDEFER) {
2002 ++info->defer;
2007 * Discard a fp previously held in a unix domain socket mbuf. To
2008 * avoid blowing out the kernel stack due to contrived chain-reactions
2009 * we may have to defer the operation to a higher procedural level.
2011 * Caller holds unp_token
2013 static void
2014 unp_discard(struct file *fp, void *data __unused)
2016 struct unp_defdiscard *d;
2018 unp_del_right(fp);
2020 d = kmalloc(sizeof(*d), M_UNPCB, M_WAITOK);
2021 d->fp = fp;
2023 spin_lock(&unp_defdiscard_spin);
2024 SLIST_INSERT_HEAD(&unp_defdiscard_head, d, next);
2025 spin_unlock(&unp_defdiscard_spin);
2027 taskqueue_enqueue(unp_taskqueue, &unp_defdiscard_task);
2031 * NOTE:
2032 * unp_token must be held before calling this function to avoid name
2033 * resolution and v_socket accessing races, especially racing against
2034 * the unp_detach().
2036 * NOTE:
2037 * For anyone caring about unconnected unix socket sending performance,
2038 * other approach could be taken...
2040 static int
2041 unp_find_lockref(struct sockaddr *nam, struct thread *td, short type,
2042 struct unpcb **unp_ret)
2044 struct proc *p = td->td_proc;
2045 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
2046 struct vnode *vp = NULL;
2047 struct socket *so;
2048 struct unpcb *unp;
2049 int error, len;
2050 struct nlookupdata nd;
2051 char buf[SOCK_MAXADDRLEN];
2053 ASSERT_LWKT_TOKEN_HELD(&unp_token);
2055 *unp_ret = NULL;
2057 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
2058 if (len <= 0) {
2059 error = EINVAL;
2060 goto failed;
2062 strncpy(buf, soun->sun_path, len);
2063 buf[len] = 0;
2065 error = nlookup_init(&nd, buf, UIO_SYSSPACE, NLC_FOLLOW);
2066 if (error == 0)
2067 error = nlookup(&nd);
2068 if (error == 0)
2069 error = cache_vget(&nd.nl_nch, nd.nl_cred, LK_EXCLUSIVE, &vp);
2070 nlookup_done(&nd);
2071 if (error) {
2072 vp = NULL;
2073 goto failed;
2076 if (vp->v_type != VSOCK) {
2077 error = ENOTSOCK;
2078 goto failed;
2080 error = VOP_EACCESS(vp, VWRITE, p->p_ucred);
2081 if (error)
2082 goto failed;
2083 so = vp->v_socket;
2084 if (so == NULL) {
2085 error = ECONNREFUSED;
2086 goto failed;
2088 if (so->so_type != type) {
2089 error = EPROTOTYPE;
2090 goto failed;
2093 /* Lock this unp. */
2094 unp = unp_getsocktoken(so);
2095 if (!UNP_ISATTACHED(unp)) {
2096 unp_reltoken(unp);
2097 error = ECONNREFUSED;
2098 goto failed;
2100 /* And keep this unp referenced. */
2101 unp_reference(unp);
2103 /* Done! */
2104 *unp_ret = unp;
2105 error = 0;
2106 failed:
2107 if (vp != NULL)
2108 vput(vp);
2109 return error;
2112 static int
2113 unp_connect_pair(struct unpcb *unp, struct unpcb *unp2)
2115 struct socket *so = unp->unp_socket;
2116 struct socket *so2 = unp2->unp_socket;
2118 ASSERT_LWKT_TOKEN_HELD(&unp_token);
2119 UNP_ASSERT_TOKEN_HELD(unp);
2120 UNP_ASSERT_TOKEN_HELD(unp2);
2122 KASSERT(so->so_type == so2->so_type,
2123 ("socket type mismatch, so %d, so2 %d", so->so_type, so2->so_type));
2125 if (!UNP_ISATTACHED(unp))
2126 return EINVAL;
2127 if (!UNP_ISATTACHED(unp2))
2128 return ECONNREFUSED;
2130 KASSERT(unp->unp_conn == NULL, ("unp is already connected"));
2131 unp->unp_conn = unp2;
2133 switch (so->so_type) {
2134 case SOCK_DGRAM:
2135 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2136 soisconnected(so);
2137 break;
2139 case SOCK_STREAM:
2140 case SOCK_SEQPACKET:
2141 KASSERT(unp2->unp_conn == NULL, ("unp2 is already connected"));
2142 unp2->unp_conn = unp;
2143 soisconnected(so);
2144 soisconnected(so2);
2145 break;
2147 default:
2148 panic("unp_connect_pair: unknown socket type %d", so->so_type);
2150 return 0;
2153 static void
2154 unp_drop(struct unpcb *unp, int error)
2156 struct unp_global_head *head;
2157 struct unpcb *unp2;
2159 ASSERT_LWKT_TOKEN_HELD(&unp_token);
2160 UNP_ASSERT_TOKEN_HELD(unp);
2162 KASSERT((unp->unp_flags & (UNP_DETACHED | UNP_DROPPED)) == 0,
2163 ("unp is dropped"));
2165 /* Mark this unp as detached. */
2166 unp_setflags(unp, UNP_DETACHED);
2168 /* Remove this unp from the global unp list. */
2169 head = unp_globalhead(unp->unp_socket->so_type);
2170 KASSERT(head->count > 0, ("invalid unp count"));
2171 TAILQ_REMOVE(&head->list, unp, unp_link);
2172 head->count--;
2174 /* Disconnect all. */
2175 unp_disconnect(unp, error);
2176 while ((unp2 = LIST_FIRST(&unp->unp_refs)) != NULL) {
2177 lwkt_getpooltoken(unp2);
2178 unp_disconnect(unp2, ECONNRESET);
2179 lwkt_relpooltoken(unp2);
2181 unp_setflags(unp, UNP_DROPPED);
2183 /* Try freeing this unp. */
2184 unp_free(unp);
2187 static void
2188 unp_defdiscard_taskfunc(void *arg __unused, int pending __unused)
2190 struct unp_defdiscard *d;
2192 spin_lock(&unp_defdiscard_spin);
2193 while ((d = SLIST_FIRST(&unp_defdiscard_head)) != NULL) {
2194 SLIST_REMOVE_HEAD(&unp_defdiscard_head, next);
2195 spin_unlock(&unp_defdiscard_spin);
2197 fdrop(d->fp);
2198 kfree(d, M_UNPCB);
2200 spin_lock(&unp_defdiscard_spin);
2202 spin_unlock(&unp_defdiscard_spin);