<sys/signal.h>: Adjust the type of stack_t's ss_sp from char * to void *.
[dragonfly.git] / sys / kern / uipc_usrreq.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
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.
16  *
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.
28  *
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 $
31  */
32
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>
56
57 #include <sys/file2.h>
58 #include <sys/spinlock2.h>
59 #include <sys/socketvar2.h>
60 #include <sys/msgport2.h>
61
62 /*
63  * Unix communications domain.
64  *
65  * TODO:
66  *      RDM
67  *      rethink name space problems
68  *      need a proper out-of-band
69  *      lock pushdown
70  *
71  *
72  * Unix domain sockets GC.
73  *
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.
80  *
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.
91  */
92
93 #define UNP_DETACHED            UNP_PRIVATE1
94 #define UNP_CONNECTING          UNP_PRIVATE2
95 #define UNP_DROPPED             UNP_PRIVATE3
96 #define UNP_MARKER              UNP_PRIVATE4
97
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. */
101
102 #define UNP_GCFILE_MAX          256
103
104 /* For unp_internalize() and unp_externalize() */
105 CTASSERT(sizeof(struct file *) >= sizeof(int));
106
107 #define UNP_ISATTACHED(unp)     \
108     ((unp) != NULL && ((unp)->unp_flags & UNP_DETACHED) == 0)
109
110 #ifdef INVARIANTS
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 */
116
117 struct unp_defdiscard {
118         SLIST_ENTRY(unp_defdiscard) next;
119         struct file *fp;
120 };
121 SLIST_HEAD(unp_defdiscard_list, unp_defdiscard);
122
123 TAILQ_HEAD(unpcb_qhead, unpcb);
124 struct unp_global_head {
125         struct unpcb_qhead      list;
126         int                     count;
127 };
128
129 static  MALLOC_DEFINE(M_UNPCB, "unpcb", "unpcb struct");
130 static  unp_gen_t unp_gencnt;
131
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;
135
136 static struct unp_global_head * const unp_heads[] =
137     { &unp_stream_head, &unp_dgram_head, &unp_seqpkt_head, NULL };
138
139 static struct lwkt_token unp_token = LWKT_TOKEN_INITIALIZER(unp_token);
140 static struct taskqueue *unp_taskqueue;
141
142 static struct unp_defdiscard_list unp_defdiscard_head;
143 static struct spinlock unp_defdiscard_spin;
144 static struct task unp_defdiscard_task;
145
146 static struct   sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
147
148 static int     unp_attach (struct socket *, struct pru_attach_info *);
149 static void    unp_detach (struct unpcb *);
150 static int     unp_bind (struct unpcb *,struct sockaddr *, struct thread *);
151 static int     unp_connect (struct socket *,struct sockaddr *,
152                                 struct thread *);
153 static void    unp_disconnect(struct unpcb *, int);
154 static void    unp_shutdown (struct unpcb *);
155 static void    unp_gc(void *, int);
156 #ifdef UNP_GC_ALLFILES
157 static int     unp_gc_clearmarks(struct file *, void *);
158 static int     unp_gc_checkmarks(struct file *, void *);
159 static int     unp_gc_checkrefs(struct file *, void *);
160 static void    unp_mark(struct file *, void *data);
161 #endif
162 static void    unp_scan (struct mbuf *, void (*)(struct file *, void *),
163                                 void *data);
164 static void    unp_discard (struct file *, void *);
165 static int     unp_internalize (struct mbuf *, struct thread *);
166 static int     unp_listen (struct unpcb *, struct thread *);
167 static void    unp_fp_externalize(struct lwp *lp, struct file *fp, int fd,
168                    int flags);
169 static int     unp_find_lockref(struct sockaddr *nam, struct thread *td,
170                    short type, struct unpcb **unp_ret);
171 static int     unp_connect_pair(struct unpcb *unp, struct unpcb *unp2);
172 static void    unp_drop(struct unpcb *unp, int error);
173 static void    unp_defdiscard_taskfunc(void *, int);
174
175 static int      unp_rights;                     /* file descriptors in flight */
176 static struct lwkt_token unp_rights_token =
177     LWKT_TOKEN_INITIALIZER(unp_rights_token);
178 static struct task unp_gc_task;
179 static struct unpcb *unp_gc_marker;
180
181 SYSCTL_DECL(_net_local);
182 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
183    "File descriptors in flight");
184
185 /*
186  * SMP Considerations:
187  *
188  *      Since unp_token will be automaticly released upon execution of
189  *      blocking code, we need to reference unp_conn before any possible
190  *      blocking code to prevent it from being ripped behind our back.
191  *
192  *      Any adjustment to unp->unp_conn requires both the global unp_token
193  *      AND the per-unp token (lwkt_token_pool_lookup(unp)) to be held.
194  *
195  *      Any access to so_pcb to obtain unp requires the pool token for
196  *      unp to be held.
197  */
198
199 static __inline void
200 unp_reference(struct unpcb *unp)
201 {
202         /* 0->1 transition will not work */
203         KKASSERT(unp->unp_refcnt > 0);
204         atomic_add_int(&unp->unp_refcnt, 1);
205 }
206
207 static __inline void
208 unp_free(struct unpcb *unp)
209 {
210         KKASSERT(unp->unp_refcnt > 0);
211         if (atomic_fetchadd_int(&unp->unp_refcnt, -1) == 1)
212                 unp_detach(unp);
213 }
214
215 static __inline struct unpcb *
216 unp_getsocktoken(struct socket *so)
217 {
218         struct unpcb *unp;
219
220         /*
221          * The unp pointer is invalid until we verify that it is
222          * good by re-checking so_pcb AFTER obtaining the token.
223          */
224         while ((unp = so->so_pcb) != NULL) {
225                 lwkt_getpooltoken(unp);
226                 if (unp == so->so_pcb)
227                         break;
228                 lwkt_relpooltoken(unp);
229         }
230         return unp;
231 }
232
233 static __inline void
234 unp_reltoken(struct unpcb *unp)
235 {
236         if (unp != NULL)
237                 lwkt_relpooltoken(unp);
238 }
239
240 static __inline void
241 unp_setflags(struct unpcb *unp, int flags)
242 {
243         atomic_set_int(&unp->unp_flags, flags);
244 }
245
246 static __inline void
247 unp_clrflags(struct unpcb *unp, int flags)
248 {
249         atomic_clear_int(&unp->unp_flags, flags);
250 }
251
252 static __inline struct unp_global_head *
253 unp_globalhead(short type)
254 {
255         switch (type) {
256         case SOCK_STREAM:
257                 return &unp_stream_head;
258         case SOCK_DGRAM:
259                 return &unp_dgram_head;
260         case SOCK_SEQPACKET:
261                 return &unp_seqpkt_head;
262         default:
263                 panic("unknown socket type %d", type);
264         }
265 }
266
267 static __inline struct unpcb *
268 unp_fp2unpcb(struct file *fp)
269 {
270         struct socket *so;
271
272         if (fp->f_type != DTYPE_SOCKET)
273                 return NULL;
274
275         so = fp->f_data;
276         if (so == NULL)
277                 return NULL;
278
279         if (so->so_proto->pr_domain != &localdomain)
280                 return NULL;
281
282         return so->so_pcb;
283 }
284
285 static __inline void
286 unp_add_right(struct file *fp)
287 {
288         struct unpcb *unp;
289
290         ASSERT_LWKT_TOKEN_HELD(&unp_rights_token);
291         KASSERT(fp->f_count > 0, ("invalid f_count %d", fp->f_count));
292
293         unp = unp_fp2unpcb(fp);
294         if (unp != NULL) {
295                 unp->unp_fp = fp;
296                 unp->unp_msgcount++;
297         }
298         fp->f_msgcount++;
299         unp_rights++;
300 }
301
302 static __inline void
303 unp_del_right(struct file *fp)
304 {
305         struct unpcb *unp;
306
307         ASSERT_LWKT_TOKEN_HELD(&unp_rights_token);
308         KASSERT(fp->f_count > 0, ("invalid f_count %d", fp->f_count));
309
310         unp = unp_fp2unpcb(fp);
311         if (unp != NULL) {
312                 KASSERT(unp->unp_msgcount > 0,
313                     ("invalid unp msgcount %d", unp->unp_msgcount));
314                 unp->unp_msgcount--;
315                 if (unp->unp_msgcount == 0)
316                         unp->unp_fp = NULL;
317         }
318         fp->f_msgcount--;
319         unp_rights--;
320 }
321
322 /*
323  * NOTE: (so) is referenced from soabort*() and netmsg_pru_abort()
324  *       will sofree() it when we return.
325  */
326 static void
327 uipc_abort(netmsg_t msg)
328 {
329         struct unpcb *unp;
330         int error;
331
332         lwkt_gettoken(&unp_token);
333         unp = unp_getsocktoken(msg->base.nm_so);
334
335         if (UNP_ISATTACHED(unp)) {
336                 unp_drop(unp, ECONNABORTED);
337                 error = 0;
338         } else {
339                 error = EINVAL;
340         }
341
342         unp_reltoken(unp);
343         lwkt_reltoken(&unp_token);
344
345         lwkt_replymsg(&msg->lmsg, error);
346 }
347
348 static void
349 uipc_accept(netmsg_t msg)
350 {
351         struct unpcb *unp;
352         int error;
353
354         lwkt_gettoken(&unp_token);
355         unp = unp_getsocktoken(msg->base.nm_so);
356
357         if (!UNP_ISATTACHED(unp)) {
358                 error = EINVAL;
359         } else {
360                 struct unpcb *unp2 = unp->unp_conn;
361
362                 /*
363                  * Pass back name of connected socket,
364                  * if it was bound and we are still connected
365                  * (our peer may have closed already!).
366                  */
367                 if (unp2 && unp2->unp_addr) {
368                         unp_reference(unp2);
369                         *msg->accept.nm_nam = dup_sockaddr(
370                                 (struct sockaddr *)unp2->unp_addr);
371                         unp_free(unp2);
372                 } else {
373                         *msg->accept.nm_nam = dup_sockaddr(&sun_noname);
374                 }
375                 error = 0;
376         }
377
378         unp_reltoken(unp);
379         lwkt_reltoken(&unp_token);
380
381         lwkt_replymsg(&msg->lmsg, error);
382 }
383
384 static void
385 uipc_attach(netmsg_t msg)
386 {
387         int error;
388
389         lwkt_gettoken(&unp_token);
390
391         KASSERT(msg->base.nm_so->so_pcb == NULL, ("double unp attach"));
392         error = unp_attach(msg->base.nm_so, msg->attach.nm_ai);
393
394         lwkt_reltoken(&unp_token);
395         lwkt_replymsg(&msg->lmsg, error);
396 }
397
398 static void
399 uipc_bind(netmsg_t msg)
400 {
401         struct unpcb *unp;
402         int error;
403
404         lwkt_gettoken(&unp_token);
405         unp = unp_getsocktoken(msg->base.nm_so);
406
407         if (UNP_ISATTACHED(unp))
408                 error = unp_bind(unp, msg->bind.nm_nam, msg->bind.nm_td);
409         else
410                 error = EINVAL;
411
412         unp_reltoken(unp);
413         lwkt_reltoken(&unp_token);
414
415         lwkt_replymsg(&msg->lmsg, error);
416 }
417
418 static void
419 uipc_connect(netmsg_t msg)
420 {
421         int error;
422
423         error = unp_connect(msg->base.nm_so, msg->connect.nm_nam,
424             msg->connect.nm_td);
425         lwkt_replymsg(&msg->lmsg, error);
426 }
427
428 static void
429 uipc_connect2(netmsg_t msg)
430 {
431         int error;
432
433         error = unp_connect2(msg->connect2.nm_so1, msg->connect2.nm_so2);
434         lwkt_replymsg(&msg->lmsg, error);
435 }
436
437 /* control is EOPNOTSUPP */
438
439 static void
440 uipc_detach(netmsg_t msg)
441 {
442         struct unpcb *unp;
443         int error;
444
445         lwkt_gettoken(&unp_token);
446         unp = unp_getsocktoken(msg->base.nm_so);
447
448         if (UNP_ISATTACHED(unp)) {
449                 unp_drop(unp, 0);
450                 error = 0;
451         } else {
452                 error = EINVAL;
453         }
454
455         unp_reltoken(unp);
456         lwkt_reltoken(&unp_token);
457
458         lwkt_replymsg(&msg->lmsg, error);
459 }
460
461 static void
462 uipc_disconnect(netmsg_t msg)
463 {
464         struct unpcb *unp;
465         int error;
466
467         lwkt_gettoken(&unp_token);
468         unp = unp_getsocktoken(msg->base.nm_so);
469
470         if (UNP_ISATTACHED(unp)) {
471                 unp_disconnect(unp, 0);
472                 error = 0;
473         } else {
474                 error = EINVAL;
475         }
476
477         unp_reltoken(unp);
478         lwkt_reltoken(&unp_token);
479
480         lwkt_replymsg(&msg->lmsg, error);
481 }
482
483 static void
484 uipc_listen(netmsg_t msg)
485 {
486         struct unpcb *unp;
487         int error;
488
489         lwkt_gettoken(&unp_token);
490         unp = unp_getsocktoken(msg->base.nm_so);
491
492         if (!UNP_ISATTACHED(unp) || unp->unp_vnode == NULL)
493                 error = EINVAL;
494         else
495                 error = unp_listen(unp, msg->listen.nm_td);
496
497         unp_reltoken(unp);
498         lwkt_reltoken(&unp_token);
499
500         lwkt_replymsg(&msg->lmsg, error);
501 }
502
503 static void
504 uipc_peeraddr(netmsg_t msg)
505 {
506         struct unpcb *unp;
507         int error;
508
509         lwkt_gettoken(&unp_token);
510         unp = unp_getsocktoken(msg->base.nm_so);
511
512         if (!UNP_ISATTACHED(unp)) {
513                 error = EINVAL;
514         } else if (unp->unp_conn && unp->unp_conn->unp_addr) {
515                 struct unpcb *unp2 = unp->unp_conn;
516
517                 unp_reference(unp2);
518                 *msg->peeraddr.nm_nam = dup_sockaddr(
519                                 (struct sockaddr *)unp2->unp_addr);
520                 unp_free(unp2);
521                 error = 0;
522         } else {
523                 /*
524                  * XXX: It seems that this test always fails even when
525                  * connection is established.  So, this else clause is
526                  * added as workaround to return PF_LOCAL sockaddr.
527                  */
528                 *msg->peeraddr.nm_nam = dup_sockaddr(&sun_noname);
529                 error = 0;
530         }
531
532         unp_reltoken(unp);
533         lwkt_reltoken(&unp_token);
534
535         lwkt_replymsg(&msg->lmsg, error);
536 }
537
538 static void
539 uipc_rcvd(netmsg_t msg)
540 {
541         struct unpcb *unp, *unp2;
542         struct socket *so;
543         struct socket *so2;
544         int error;
545
546         /*
547          * so_pcb is only modified with both the global and the unp
548          * pool token held.
549          */
550         so = msg->base.nm_so;
551         unp = unp_getsocktoken(so);
552
553         if (!UNP_ISATTACHED(unp)) {
554                 error = EINVAL;
555                 goto done;
556         }
557
558         switch (so->so_type) {
559         case SOCK_DGRAM:
560                 panic("uipc_rcvd DGRAM?");
561                 /*NOTREACHED*/
562         case SOCK_STREAM:
563         case SOCK_SEQPACKET:
564                 if (unp->unp_conn == NULL)
565                         break;
566                 unp2 = unp->unp_conn;   /* protected by pool token */
567
568                 /*
569                  * Because we are transfering mbufs directly to the
570                  * peer socket we have to use SSB_STOP on the sender
571                  * to prevent it from building up infinite mbufs.
572                  *
573                  * As in several places in this module w ehave to ref unp2
574                  * to ensure that it does not get ripped out from under us
575                  * if we block on the so2 token or in sowwakeup().
576                  */
577                 so2 = unp2->unp_socket;
578                 unp_reference(unp2);
579                 lwkt_gettoken(&so2->so_rcv.ssb_token);
580                 if (so->so_rcv.ssb_cc < so2->so_snd.ssb_hiwat &&
581                     so->so_rcv.ssb_mbcnt < so2->so_snd.ssb_mbmax
582                 ) {
583                         atomic_clear_int(&so2->so_snd.ssb_flags, SSB_STOP);
584
585                         sowwakeup(so2);
586                 }
587                 lwkt_reltoken(&so2->so_rcv.ssb_token);
588                 unp_free(unp2);
589                 break;
590         default:
591                 panic("uipc_rcvd unknown socktype");
592                 /*NOTREACHED*/
593         }
594         error = 0;
595 done:
596         unp_reltoken(unp);
597         lwkt_replymsg(&msg->lmsg, error);
598 }
599
600 /* pru_rcvoob is EOPNOTSUPP */
601
602 static void
603 uipc_send(netmsg_t msg)
604 {
605         struct unpcb *unp, *unp2;
606         struct socket *so;
607         struct socket *so2;
608         struct mbuf *control;
609         struct mbuf *m;
610         int error = 0;
611
612         so = msg->base.nm_so;
613         control = msg->send.nm_control;
614         m = msg->send.nm_m;
615
616         /*
617          * so_pcb is only modified with both the global and the unp
618          * pool token held.
619          */
620         so = msg->base.nm_so;
621         unp = unp_getsocktoken(so);
622
623         if (!UNP_ISATTACHED(unp)) {
624                 error = EINVAL;
625                 goto release;
626         }
627
628         if (msg->send.nm_flags & PRUS_OOB) {
629                 error = EOPNOTSUPP;
630                 goto release;
631         }
632
633         wakeup_start_delayed();
634
635         if (control && (error = unp_internalize(control, msg->send.nm_td)))
636                 goto release;
637
638         switch (so->so_type) {
639         case SOCK_DGRAM: 
640         {
641                 struct sockaddr *from;
642
643                 if (msg->send.nm_addr) {
644                         if (unp->unp_conn) {
645                                 error = EISCONN;
646                                 break;
647                         }
648                         lwkt_gettoken(&unp_token);
649                         error = unp_find_lockref(msg->send.nm_addr,
650                             msg->send.nm_td, so->so_type, &unp2);
651                         if (error) {
652                                 lwkt_reltoken(&unp_token);
653                                 break;
654                         }
655                         /*
656                          * NOTE:
657                          * unp2 is locked and referenced.
658                          *
659                          * We could unlock unp2 now, since it was checked
660                          * and referenced.
661                          */
662                         unp_reltoken(unp2);
663                         lwkt_reltoken(&unp_token);
664                 } else {
665                         if (unp->unp_conn == NULL) {
666                                 error = ENOTCONN;
667                                 break;
668                         }
669                         unp2 = unp->unp_conn;
670                         unp_reference(unp2);
671                 }
672                 /* NOTE: unp2 is referenced. */
673                 so2 = unp2->unp_socket;
674
675                 if (unp->unp_addr)
676                         from = (struct sockaddr *)unp->unp_addr;
677                 else
678                         from = &sun_noname;
679
680                 lwkt_gettoken(&so2->so_rcv.ssb_token);
681                 if (ssb_appendaddr(&so2->so_rcv, from, m, control)) {
682                         sorwakeup(so2);
683                         m = NULL;
684                         control = NULL;
685                 } else {
686                         error = ENOBUFS;
687                 }
688                 lwkt_reltoken(&so2->so_rcv.ssb_token);
689
690                 unp_free(unp2);
691                 break;
692         }
693
694         case SOCK_STREAM:
695         case SOCK_SEQPACKET:
696                 /* Connect if not connected yet. */
697                 /*
698                  * Note: A better implementation would complain
699                  * if not equal to the peer's address.
700                  */
701                 if (unp->unp_conn == NULL) {
702                         if (msg->send.nm_addr) {
703                                 error = unp_connect(so,
704                                                     msg->send.nm_addr,
705                                                     msg->send.nm_td);
706                                 if (error)
707                                         break;  /* XXX */
708                         }
709                         /*
710                          * NOTE:
711                          * unp_conn still could be NULL, even if the
712                          * above unp_connect() succeeds; since the
713                          * current unp's token could be released due
714                          * to blocking operations after unp_conn is
715                          * assigned.
716                          */
717                         if (unp->unp_conn == NULL) {
718                                 error = ENOTCONN;
719                                 break;
720                         }
721                 }
722                 if (so->so_state & SS_CANTSENDMORE) {
723                         error = EPIPE;
724                         break;
725                 }
726
727                 unp2 = unp->unp_conn;
728                 KASSERT(unp2 != NULL, ("unp is not connected"));
729                 so2 = unp2->unp_socket;
730
731                 unp_reference(unp2);
732
733                 /*
734                  * Send to paired receive port, and then reduce
735                  * send buffer hiwater marks to maintain backpressure.
736                  * Wake up readers.
737                  */
738                 lwkt_gettoken(&so2->so_rcv.ssb_token);
739                 if (control) {
740                         if (ssb_appendcontrol(&so2->so_rcv, m, control)) {
741                                 control = NULL;
742                                 m = NULL;
743                         }
744                 } else if (so->so_type == SOCK_SEQPACKET) {
745                         sbappendrecord(&so2->so_rcv.sb, m);
746                         m = NULL;
747                 } else {
748                         sbappend(&so2->so_rcv.sb, m);
749                         m = NULL;
750                 }
751
752                 /*
753                  * Because we are transfering mbufs directly to the
754                  * peer socket we have to use SSB_STOP on the sender
755                  * to prevent it from building up infinite mbufs.
756                  */
757                 if (so2->so_rcv.ssb_cc >= so->so_snd.ssb_hiwat ||
758                     so2->so_rcv.ssb_mbcnt >= so->so_snd.ssb_mbmax
759                 ) {
760                         atomic_set_int(&so->so_snd.ssb_flags, SSB_STOP);
761                 }
762                 lwkt_reltoken(&so2->so_rcv.ssb_token);
763                 sorwakeup(so2);
764
765                 unp_free(unp2);
766                 break;
767
768         default:
769                 panic("uipc_send unknown socktype");
770         }
771
772         /*
773          * SEND_EOF is equivalent to a SEND followed by a SHUTDOWN.
774          */
775         if (msg->send.nm_flags & PRUS_EOF) {
776                 socantsendmore(so);
777                 unp_shutdown(unp);
778         }
779
780         if (control && error != 0)
781                 unp_dispose(control);
782 release:
783         unp_reltoken(unp);
784         wakeup_end_delayed();
785
786         if (control)
787                 m_freem(control);
788         if (m)
789                 m_freem(m);
790         lwkt_replymsg(&msg->lmsg, error);
791 }
792
793 /*
794  * MPSAFE
795  */
796 static void
797 uipc_sense(netmsg_t msg)
798 {
799         struct unpcb *unp;
800         struct socket *so;
801         struct stat *sb;
802         int error;
803
804         so = msg->base.nm_so;
805         sb = msg->sense.nm_stat;
806
807         /*
808          * so_pcb is only modified with both the global and the unp
809          * pool token held.
810          */
811         unp = unp_getsocktoken(so);
812
813         if (!UNP_ISATTACHED(unp)) {
814                 error = EINVAL;
815                 goto done;
816         }
817
818         sb->st_blksize = so->so_snd.ssb_hiwat;
819         sb->st_dev = NOUDEV;
820         error = 0;
821 done:
822         unp_reltoken(unp);
823         lwkt_replymsg(&msg->lmsg, error);
824 }
825
826 static void
827 uipc_shutdown(netmsg_t msg)
828 {
829         struct socket *so;
830         struct unpcb *unp;
831         int error;
832
833         /*
834          * so_pcb is only modified with both the global and the unp
835          * pool token held.
836          */
837         so = msg->base.nm_so;
838         unp = unp_getsocktoken(so);
839
840         if (UNP_ISATTACHED(unp)) {
841                 socantsendmore(so);
842                 unp_shutdown(unp);
843                 error = 0;
844         } else {
845                 error = EINVAL;
846         }
847
848         unp_reltoken(unp);
849         lwkt_replymsg(&msg->lmsg, error);
850 }
851
852 static void
853 uipc_sockaddr(netmsg_t msg)
854 {
855         struct unpcb *unp;
856         int error;
857
858         /*
859          * so_pcb is only modified with both the global and the unp
860          * pool token held.
861          */
862         unp = unp_getsocktoken(msg->base.nm_so);
863
864         if (UNP_ISATTACHED(unp)) {
865                 if (unp->unp_addr) {
866                         *msg->sockaddr.nm_nam =
867                                 dup_sockaddr((struct sockaddr *)unp->unp_addr);
868                 }
869                 error = 0;
870         } else {
871                 error = EINVAL;
872         }
873
874         unp_reltoken(unp);
875         lwkt_replymsg(&msg->lmsg, error);
876 }
877
878 struct pr_usrreqs uipc_usrreqs = {
879         .pru_abort = uipc_abort,
880         .pru_accept = uipc_accept,
881         .pru_attach = uipc_attach,
882         .pru_bind = uipc_bind,
883         .pru_connect = uipc_connect,
884         .pru_connect2 = uipc_connect2,
885         .pru_control = pr_generic_notsupp,
886         .pru_detach = uipc_detach,
887         .pru_disconnect = uipc_disconnect,
888         .pru_listen = uipc_listen,
889         .pru_peeraddr = uipc_peeraddr,
890         .pru_rcvd = uipc_rcvd,
891         .pru_rcvoob = pr_generic_notsupp,
892         .pru_send = uipc_send,
893         .pru_sense = uipc_sense,
894         .pru_shutdown = uipc_shutdown,
895         .pru_sockaddr = uipc_sockaddr,
896         .pru_sosend = sosend,
897         .pru_soreceive = soreceive
898 };
899
900 void
901 uipc_ctloutput(netmsg_t msg)
902 {
903         struct socket *so;
904         struct sockopt *sopt;
905         struct unpcb *unp;
906         int error = 0;
907
908         so = msg->base.nm_so;
909         sopt = msg->ctloutput.nm_sopt;
910
911         lwkt_gettoken(&unp_token);
912         unp = unp_getsocktoken(so);
913
914         if (!UNP_ISATTACHED(unp)) {
915                 error = EINVAL;
916                 goto done;
917         }
918
919         switch (sopt->sopt_dir) {
920         case SOPT_GET:
921                 switch (sopt->sopt_name) {
922                 case LOCAL_PEERCRED:
923                         if (unp->unp_flags & UNP_HAVEPC)
924                                 soopt_from_kbuf(sopt, &unp->unp_peercred,
925                                                 sizeof(unp->unp_peercred));
926                         else {
927                                 if (so->so_type == SOCK_STREAM)
928                                         error = ENOTCONN;
929                                 else if (so->so_type == SOCK_SEQPACKET)
930                                         error = ENOTCONN;
931                                 else
932                                         error = EINVAL;
933                         }
934                         break;
935                 default:
936                         error = EOPNOTSUPP;
937                         break;
938                 }
939                 break;
940         case SOPT_SET:
941         default:
942                 error = EOPNOTSUPP;
943                 break;
944         }
945
946 done:
947         unp_reltoken(unp);
948         lwkt_reltoken(&unp_token);
949
950         lwkt_replymsg(&msg->lmsg, error);
951 }
952         
953 /*
954  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
955  * for stream sockets, although the total for sender and receiver is
956  * actually only PIPSIZ.
957  *
958  * Datagram sockets really use the sendspace as the maximum datagram size,
959  * and don't really want to reserve the sendspace.  Their recvspace should
960  * be large enough for at least one max-size datagram plus address.
961  *
962  * We want the local send/recv space to be significant larger then lo0's
963  * mtu of 16384.
964  *
965  * We no longer need to worry about avoiding the windows scaling option.
966  * Programs which use unix domain sockets expect larger defaults these days.
967  */
968 #ifndef PIPSIZ
969 #define PIPSIZ  65536
970 #endif
971 static u_long   unpst_sendspace = PIPSIZ;
972 static u_long   unpst_recvspace = PIPSIZ;
973 static u_long   unpdg_sendspace = PIPSIZ;       /* really max datagram size */
974 static u_long   unpdg_recvspace = PIPSIZ;
975 static u_long   unpsp_sendspace = PIPSIZ;       /* really max datagram size */
976 static u_long   unpsp_recvspace = PIPSIZ;
977
978 SYSCTL_DECL(_net_local_stream);
979 SYSCTL_DECL(_net_local_dgram);
980 SYSCTL_DECL(_net_local_seqpacket);
981
982 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
983     &unpst_sendspace, 0, "Size of stream socket send buffer");
984 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
985     &unpst_recvspace, 0, "Size of stream socket receive buffer");
986
987 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
988     &unpdg_sendspace, 0, "Max datagram socket size");
989 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
990     &unpdg_recvspace, 0, "Size of datagram socket receive buffer");
991
992 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
993     &unpsp_sendspace, 0, "Default seqpacket send space.");
994 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
995     &unpsp_recvspace, 0, "Default seqpacket receive space.");
996
997
998 static int
999 unp_attach(struct socket *so, struct pru_attach_info *ai)
1000 {
1001         struct unp_global_head *head;
1002         struct unpcb *unp;
1003         int error;
1004
1005         lwkt_gettoken(&unp_token);
1006
1007         if (so->so_snd.ssb_hiwat == 0 || so->so_rcv.ssb_hiwat == 0) {
1008                 switch (so->so_type) {
1009                 case SOCK_STREAM:
1010                         error = soreserve(so, unpst_sendspace, unpst_recvspace,
1011                                           ai->sb_rlimit);
1012                         break;
1013                 case SOCK_DGRAM:
1014                         error = soreserve(so, unpdg_sendspace, unpdg_recvspace,
1015                                           ai->sb_rlimit);
1016                         break;
1017                 case SOCK_SEQPACKET:
1018                         error = soreserve(so, unpsp_sendspace, unpsp_recvspace,
1019                                           ai->sb_rlimit);
1020                         break;
1021                 default:
1022                         panic("unp_attach");
1023                 }
1024                 if (error)
1025                         goto failed;
1026         }
1027
1028         /*
1029          * In order to support sendfile we have to set either SSB_STOPSUPP
1030          * or SSB_PREALLOC.  Unix domain sockets use the SSB_STOP flow
1031          * control mechanism.
1032          */
1033         if (so->so_type == SOCK_STREAM) {
1034                 atomic_set_int(&so->so_rcv.ssb_flags, SSB_STOPSUPP);
1035                 atomic_set_int(&so->so_snd.ssb_flags, SSB_STOPSUPP);
1036         }
1037
1038         unp = kmalloc(sizeof(*unp), M_UNPCB, M_WAITOK | M_ZERO | M_NULLOK);
1039         if (unp == NULL) {
1040                 error = ENOBUFS;
1041                 goto failed;
1042         }
1043         unp->unp_refcnt = 1;
1044         unp->unp_gencnt = ++unp_gencnt;
1045         LIST_INIT(&unp->unp_refs);
1046         unp->unp_socket = so;
1047         unp->unp_rvnode = ai->fd_rdir;          /* jail cruft XXX JH */
1048         so->so_pcb = (caddr_t)unp;
1049         soreference(so);
1050
1051         head = unp_globalhead(so->so_type);
1052         TAILQ_INSERT_TAIL(&head->list, unp, unp_link);
1053         head->count++;
1054         error = 0;
1055 failed:
1056         lwkt_reltoken(&unp_token);
1057         return error;
1058 }
1059
1060 static void
1061 unp_detach(struct unpcb *unp)
1062 {
1063         struct socket *so;
1064
1065         lwkt_gettoken(&unp_token);
1066         lwkt_getpooltoken(unp);
1067
1068         so = unp->unp_socket;
1069
1070         unp->unp_gencnt = ++unp_gencnt;
1071         if (unp->unp_vnode) {
1072                 unp->unp_vnode->v_socket = NULL;
1073                 vrele(unp->unp_vnode);
1074                 unp->unp_vnode = NULL;
1075         }
1076         soisdisconnected(so);
1077         KKASSERT(so->so_pcb == unp);
1078         so->so_pcb = NULL;              /* both tokens required */
1079         unp->unp_socket = NULL;
1080
1081         lwkt_relpooltoken(unp);
1082         lwkt_reltoken(&unp_token);
1083
1084         sofree(so);
1085
1086         KASSERT(unp->unp_conn == NULL, ("unp is still connected"));
1087         KASSERT(LIST_EMPTY(&unp->unp_refs), ("unp still has references"));
1088
1089         if (unp->unp_addr)
1090                 kfree(unp->unp_addr, M_SONAME);
1091         kfree(unp, M_UNPCB);
1092
1093         if (unp_rights)
1094                 taskqueue_enqueue(unp_taskqueue, &unp_gc_task);
1095 }
1096
1097 static int
1098 unp_bind(struct unpcb *unp, struct sockaddr *nam, struct thread *td)
1099 {
1100         struct proc *p = td->td_proc;
1101         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1102         struct vnode *vp;
1103         struct vattr vattr;
1104         int error, namelen;
1105         struct nlookupdata nd;
1106         char buf[SOCK_MAXADDRLEN];
1107
1108         ASSERT_LWKT_TOKEN_HELD(&unp_token);
1109         UNP_ASSERT_TOKEN_HELD(unp);
1110
1111         if (unp->unp_vnode != NULL)
1112                 return EINVAL;
1113
1114         namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
1115         if (namelen <= 0)
1116                 return EINVAL;
1117         strncpy(buf, soun->sun_path, namelen);
1118         buf[namelen] = 0;       /* null-terminate the string */
1119         error = nlookup_init(&nd, buf, UIO_SYSSPACE,
1120                              NLC_LOCKVP | NLC_CREATE | NLC_REFDVP);
1121         if (error == 0)
1122                 error = nlookup(&nd);
1123         if (error == 0 && nd.nl_nch.ncp->nc_vp != NULL)
1124                 error = EADDRINUSE;
1125         if (error)
1126                 goto done;
1127
1128         VATTR_NULL(&vattr);
1129         vattr.va_type = VSOCK;
1130         vattr.va_mode = (ACCESSPERMS & ~p->p_fd->fd_cmask);
1131         error = VOP_NCREATE(&nd.nl_nch, nd.nl_dvp, &vp, nd.nl_cred, &vattr);
1132         if (error == 0) {
1133                 if (unp->unp_vnode == NULL) {
1134                         vp->v_socket = unp->unp_socket;
1135                         unp->unp_vnode = vp;
1136                         unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam);
1137                         vn_unlock(vp);
1138                 } else {
1139                         vput(vp);               /* late race */
1140                         error = EINVAL;
1141                 }
1142         }
1143 done:
1144         nlookup_done(&nd);
1145         return (error);
1146 }
1147
1148 static int
1149 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1150 {
1151         struct unpcb *unp, *unp2;
1152         int error, flags = 0;
1153
1154         lwkt_gettoken(&unp_token);
1155
1156         unp = unp_getsocktoken(so);
1157         if (!UNP_ISATTACHED(unp)) {
1158                 error = EINVAL;
1159                 goto failed;
1160         }
1161
1162         if ((unp->unp_flags & UNP_CONNECTING) || unp->unp_conn != NULL) {
1163                 error = EISCONN;
1164                 goto failed;
1165         }
1166
1167         flags = UNP_CONNECTING;
1168         unp_setflags(unp, flags);
1169
1170         error = unp_find_lockref(nam, td, so->so_type, &unp2);
1171         if (error)
1172                 goto failed;
1173         /*
1174          * NOTE:
1175          * unp2 is locked and referenced.
1176          */
1177
1178         if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1179                 struct socket *so2, *so3;
1180                 struct unpcb *unp3;
1181
1182                 so2 = unp2->unp_socket;
1183                 if (!(so2->so_options & SO_ACCEPTCONN) ||
1184                     /* listen is not completed yet */
1185                     !(unp2->unp_flags & UNP_HAVEPCCACHED) ||
1186                     (so3 = sonewconn_faddr(so2, 0, NULL,
1187                      TRUE /* keep ref */)) == NULL) {
1188                         error = ECONNREFUSED;
1189                         goto done;
1190                 }
1191                 /* so3 has a socket reference. */
1192
1193                 unp3 = unp_getsocktoken(so3);
1194                 if (!UNP_ISATTACHED(unp3)) {
1195                         unp_reltoken(unp3);
1196                         /*
1197                          * Already aborted; we only need to drop the
1198                          * socket reference held by sonewconn_faddr().
1199                          */
1200                         sofree(so3);
1201                         error = ECONNREFUSED;
1202                         goto done;
1203                 }
1204                 unp_reference(unp3);
1205                 /*
1206                  * NOTE:
1207                  * unp3 is locked and referenced.
1208                  */
1209
1210                 /*
1211                  * Release so3 socket reference held by sonewconn_faddr().
1212                  * Since we have referenced unp3, neither unp3 nor so3 will
1213                  * be destroyed here.
1214                  */
1215                 sofree(so3);
1216
1217                 if (unp2->unp_addr != NULL) {
1218                         unp3->unp_addr = (struct sockaddr_un *)
1219                             dup_sockaddr((struct sockaddr *)unp2->unp_addr);
1220                 }
1221
1222                 /*
1223                  * unp_peercred management:
1224                  *
1225                  * The connecter's (client's) credentials are copied
1226                  * from its process structure at the time of connect()
1227                  * (which is now).
1228                  */
1229                 cru2x(td->td_proc->p_ucred, &unp3->unp_peercred);
1230                 unp_setflags(unp3, UNP_HAVEPC);
1231                 /*
1232                  * The receiver's (server's) credentials are copied
1233                  * from the unp_peercred member of socket on which the
1234                  * former called listen(); unp_listen() cached that
1235                  * process's credentials at that time so we can use
1236                  * them now.
1237                  */
1238                 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1239                     ("unp_connect: listener without cached peercred"));
1240                 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1241                     sizeof(unp->unp_peercred));
1242                 unp_setflags(unp, UNP_HAVEPC);
1243
1244                 error = unp_connect_pair(unp, unp3);
1245                 if (error)
1246                         soabort_direct(so3);
1247
1248                 /* Done with unp3 */
1249                 unp_free(unp3);
1250                 unp_reltoken(unp3);
1251         } else {
1252                 error = unp_connect_pair(unp, unp2);
1253         }
1254 done:
1255         unp_free(unp2);
1256         unp_reltoken(unp2);
1257 failed:
1258         if (flags)
1259                 unp_clrflags(unp, flags);
1260         unp_reltoken(unp);
1261
1262         lwkt_reltoken(&unp_token);
1263         return (error);
1264 }
1265
1266 /*
1267  * Connect two unix domain sockets together.
1268  *
1269  * NOTE: Semantics for any change to unp_conn requires that the per-unp
1270  *       pool token also be held.
1271  */
1272 int
1273 unp_connect2(struct socket *so, struct socket *so2)
1274 {
1275         struct unpcb *unp, *unp2;
1276         int error;
1277
1278         lwkt_gettoken(&unp_token);
1279         if (so2->so_type != so->so_type) {
1280                 lwkt_reltoken(&unp_token);
1281                 return (EPROTOTYPE);
1282         }
1283         unp = unp_getsocktoken(so);
1284         unp2 = unp_getsocktoken(so2);
1285
1286         if (!UNP_ISATTACHED(unp)) {
1287                 error = EINVAL;
1288                 goto done;
1289         }
1290         if (!UNP_ISATTACHED(unp2)) {
1291                 error = ECONNREFUSED;
1292                 goto done;
1293         }
1294
1295         if (unp->unp_conn != NULL) {
1296                 error = EISCONN;
1297                 goto done;
1298         }
1299         if ((so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET) &&
1300             unp2->unp_conn != NULL) {
1301                 error = EISCONN;
1302                 goto done;
1303         }
1304
1305         error = unp_connect_pair(unp, unp2);
1306 done:
1307         unp_reltoken(unp2);
1308         unp_reltoken(unp);
1309         lwkt_reltoken(&unp_token);
1310         return (error);
1311 }
1312
1313 /*
1314  * Disconnect a unix domain socket pair.
1315  *
1316  * NOTE: Semantics for any change to unp_conn requires that the per-unp
1317  *       pool token also be held.
1318  */
1319 static void
1320 unp_disconnect(struct unpcb *unp, int error)
1321 {
1322         struct socket *so = unp->unp_socket;
1323         struct unpcb *unp2;
1324
1325         ASSERT_LWKT_TOKEN_HELD(&unp_token);
1326         UNP_ASSERT_TOKEN_HELD(unp);
1327
1328         if (error)
1329                 so->so_error = error;
1330
1331         while ((unp2 = unp->unp_conn) != NULL) {
1332                 lwkt_getpooltoken(unp2);
1333                 if (unp2 == unp->unp_conn)
1334                         break;
1335                 lwkt_relpooltoken(unp2);
1336         }
1337         if (unp2 == NULL)
1338                 return;
1339         /* unp2 is locked. */
1340
1341         KASSERT((unp2->unp_flags & UNP_DROPPED) == 0, ("unp2 was dropped"));
1342
1343         unp->unp_conn = NULL;
1344
1345         switch (so->so_type) {
1346         case SOCK_DGRAM:
1347                 LIST_REMOVE(unp, unp_reflink);
1348                 soclrstate(so, SS_ISCONNECTED);
1349                 break;
1350
1351         case SOCK_STREAM:
1352         case SOCK_SEQPACKET:
1353                 /*
1354                  * Keep a reference before clearing the unp_conn
1355                  * to avoid racing uipc_detach()/uipc_abort() in
1356                  * other thread.
1357                  */
1358                 unp_reference(unp2);
1359                 KASSERT(unp2->unp_conn == unp, ("unp_conn mismatch"));
1360                 unp2->unp_conn = NULL;
1361
1362                 soisdisconnected(so);
1363                 soisdisconnected(unp2->unp_socket);
1364
1365                 unp_free(unp2);
1366                 break;
1367         }
1368
1369         lwkt_relpooltoken(unp2);
1370 }
1371
1372 #ifdef notdef
1373 void
1374 unp_abort(struct unpcb *unp)
1375 {
1376         lwkt_gettoken(&unp_token);
1377         unp_free(unp);
1378         lwkt_reltoken(&unp_token);
1379 }
1380 #endif
1381
1382 static int
1383 prison_unpcb(struct thread *td, struct unpcb *unp)
1384 {
1385         struct proc *p;
1386
1387         if (td == NULL)
1388                 return (0);
1389         if ((p = td->td_proc) == NULL)
1390                 return (0);
1391         if (!p->p_ucred->cr_prison)
1392                 return (0);
1393         if (p->p_fd->fd_rdir == unp->unp_rvnode)
1394                 return (0);
1395         return (1);
1396 }
1397
1398 static int
1399 unp_pcblist(SYSCTL_HANDLER_ARGS)
1400 {
1401         struct unp_global_head *head = arg1;
1402         int error, i, n;
1403         struct unpcb *unp, *marker;
1404
1405         KKASSERT(curproc != NULL);
1406
1407         /*
1408          * The process of preparing the PCB list is too time-consuming and
1409          * resource-intensive to repeat twice on every request.
1410          */
1411         if (req->oldptr == NULL) {
1412                 n = head->count;
1413                 req->oldidx = (n + n/8) * sizeof(struct xunpcb);
1414                 return 0;
1415         }
1416
1417         if (req->newptr != NULL)
1418                 return EPERM;
1419
1420         marker = kmalloc(sizeof(*marker), M_UNPCB, M_WAITOK | M_ZERO);
1421         marker->unp_flags |= UNP_MARKER;
1422
1423         lwkt_gettoken(&unp_token);
1424
1425         n = head->count;
1426         i = 0;
1427         error = 0;
1428
1429         TAILQ_INSERT_HEAD(&head->list, marker, unp_link);
1430         while ((unp = TAILQ_NEXT(marker, unp_link)) != NULL && i < n) {
1431                 struct xunpcb xu;
1432
1433                 TAILQ_REMOVE(&head->list, marker, unp_link);
1434                 TAILQ_INSERT_AFTER(&head->list, unp, marker, unp_link);
1435
1436                 if (unp->unp_flags & UNP_MARKER)
1437                         continue;
1438                 if (prison_unpcb(req->td, unp))
1439                         continue;
1440
1441                 xu.xu_len = sizeof(xu);
1442                 xu.xu_unpp = unp;
1443
1444                 /*
1445                  * NOTE:
1446                  * unp->unp_addr and unp->unp_conn are protected by
1447                  * unp_token.  So if we want to get rid of unp_token
1448                  * or reduce the coverage of unp_token, care must be
1449                  * taken.
1450                  */
1451                 if (unp->unp_addr) {
1452                         bcopy(unp->unp_addr, &xu.xu_addr, 
1453                               unp->unp_addr->sun_len);
1454                 }
1455                 if (unp->unp_conn && unp->unp_conn->unp_addr) {
1456                         bcopy(unp->unp_conn->unp_addr,
1457                               &xu.xu_caddr,
1458                               unp->unp_conn->unp_addr->sun_len);
1459                 }
1460                 bcopy(unp, &xu.xu_unp, sizeof(*unp));
1461                 sotoxsocket(unp->unp_socket, &xu.xu_socket);
1462
1463                 /* NOTE: This could block and temporarily release unp_token */
1464                 error = SYSCTL_OUT(req, &xu, sizeof(xu));
1465                 if (error)
1466                         break;
1467                 ++i;
1468         }
1469         TAILQ_REMOVE(&head->list, marker, unp_link);
1470
1471         lwkt_reltoken(&unp_token);
1472
1473         kfree(marker, M_UNPCB);
1474         return error;
1475 }
1476
1477 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD, 
1478             &unp_dgram_head, 0, unp_pcblist, "S,xunpcb",
1479             "List of active local datagram sockets");
1480 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD, 
1481             &unp_stream_head, 0, unp_pcblist, "S,xunpcb",
1482             "List of active local stream sockets");
1483 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist, CTLFLAG_RD, 
1484             &unp_seqpkt_head, 0, unp_pcblist, "S,xunpcb",
1485             "List of active local seqpacket sockets");
1486
1487 static void
1488 unp_shutdown(struct unpcb *unp)
1489 {
1490         struct socket *so;
1491
1492         if ((unp->unp_socket->so_type == SOCK_STREAM ||
1493              unp->unp_socket->so_type == SOCK_SEQPACKET) &&
1494             unp->unp_conn != NULL && (so = unp->unp_conn->unp_socket)) {
1495                 socantrcvmore(so);
1496         }
1497 }
1498
1499 #ifdef notdef
1500 void
1501 unp_drain(void)
1502 {
1503         lwkt_gettoken(&unp_token);
1504         lwkt_reltoken(&unp_token);
1505 }
1506 #endif
1507
1508 int
1509 unp_externalize(struct mbuf *rights, int flags)
1510 {
1511         struct thread *td = curthread;
1512         struct proc *p = td->td_proc;           /* XXX */
1513         struct lwp *lp = td->td_lwp;
1514         struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
1515         int *fdp;
1516         int i;
1517         struct file **rp;
1518         struct file *fp;
1519         int newfds = (cm->cmsg_len - (CMSG_DATA(cm) - (u_char *)cm))
1520                 / sizeof(struct file *);
1521         int f;
1522
1523         lwkt_gettoken(&unp_rights_token);
1524
1525         /*
1526          * if the new FD's will not fit, then we free them all
1527          */
1528         if (!fdavail(p, newfds)) {
1529                 rp = (struct file **)CMSG_DATA(cm);
1530                 for (i = 0; i < newfds; i++) {
1531                         fp = *rp;
1532                         /*
1533                          * zero the pointer before calling unp_discard,
1534                          * since it may end up in unp_gc()..
1535                          */
1536                         *rp++ = NULL;
1537                         unp_discard(fp, NULL);
1538                 }
1539                 lwkt_reltoken(&unp_rights_token);
1540                 return (EMSGSIZE);
1541         }
1542
1543         /*
1544          * now change each pointer to an fd in the global table to 
1545          * an integer that is the index to the local fd table entry
1546          * that we set up to point to the global one we are transferring.
1547          * Since the sizeof(struct file *) is bigger than or equal to
1548          * the sizeof(int), we do it in forward order.  In that case,
1549          * an integer will always come in the same place or before its
1550          * corresponding struct file pointer.
1551          *
1552          * Hold revoke_token in 'shared' mode, so that we won't miss
1553          * the FREVOKED update on fps being externalized (fsetfd).
1554          */
1555         lwkt_gettoken_shared(&revoke_token);
1556         fdp = (int *)CMSG_DATA(cm);
1557         rp = (struct file **)CMSG_DATA(cm);
1558         for (i = 0; i < newfds; i++) {
1559                 if (fdalloc(p, 0, &f)) {
1560                         int j;
1561
1562                         /*
1563                          * Previous fdavail() can't garantee
1564                          * fdalloc() success due to SMP race.
1565                          * Just clean up and return the same
1566                          * error value as if fdavail() failed.
1567                          */
1568                         lwkt_reltoken(&revoke_token);
1569
1570                         /* Close externalized files */
1571                         for (j = 0; j < i; j++)
1572                                 kern_close(fdp[j]);
1573                         /* Discard the rest of internal files */
1574                         for (; i < newfds; i++)
1575                                 unp_discard(rp[i], NULL);
1576                         /* Wipe out the control message */
1577                         for (i = 0; i < newfds; i++)
1578                                 rp[i] = NULL;
1579
1580                         lwkt_reltoken(&unp_rights_token);
1581                         return (EMSGSIZE);
1582                 }
1583                 fp = rp[i];
1584                 unp_fp_externalize(lp, fp, f, flags);
1585                 fdp[i] = f;
1586         }
1587         lwkt_reltoken(&revoke_token);
1588
1589         lwkt_reltoken(&unp_rights_token);
1590
1591         /*
1592          * Adjust length, in case sizeof(struct file *) and sizeof(int)
1593          * differs.
1594          */
1595         cm->cmsg_len = CMSG_LEN(newfds * sizeof(int));
1596         rights->m_len = cm->cmsg_len;
1597
1598         return (0);
1599 }
1600
1601 static void
1602 unp_fp_externalize(struct lwp *lp, struct file *fp, int fd, int flags)
1603 {
1604         if (lp) {
1605                 struct filedesc *fdp = lp->lwp_proc->p_fd;
1606
1607                 KKASSERT(fd >= 0);
1608                 if (fp->f_flag & FREVOKED) {
1609                         struct file *fx;
1610                         int error;
1611
1612                         kprintf("Warning: revoked fp exiting unix socket\n");
1613                         error = falloc(lp, &fx, NULL);
1614                         if (error == 0) {
1615                                 if (flags & MSG_CMSG_CLOEXEC)
1616                                         fdp->fd_files[fd].fileflags |= UF_EXCLOSE;
1617                                 fsetfd(fdp, fx, fd);
1618                                 fdrop(fx);
1619                         } else {
1620                                 fsetfd(fdp, NULL, fd);
1621                         }
1622                 } else {
1623                         if (flags & MSG_CMSG_CLOEXEC)
1624                                 fdp->fd_files[fd].fileflags |= UF_EXCLOSE;
1625                         fsetfd(fdp, fp, fd);
1626                 }
1627         }
1628         unp_del_right(fp);
1629         fdrop(fp);
1630 }
1631
1632 void
1633 unp_init(void)
1634 {
1635         TAILQ_INIT(&unp_stream_head.list);
1636         TAILQ_INIT(&unp_dgram_head.list);
1637         TAILQ_INIT(&unp_seqpkt_head.list);
1638
1639         SLIST_INIT(&unp_defdiscard_head);
1640         spin_init(&unp_defdiscard_spin, "unpdisc");
1641         TASK_INIT(&unp_defdiscard_task, 0, unp_defdiscard_taskfunc, NULL);
1642
1643         /*
1644          * This implies that only one gc can be in-progress at any
1645          * given moment.
1646          */
1647         TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1648
1649         unp_gc_marker = kmalloc(sizeof(*unp_gc_marker), M_UNPCB,
1650             M_WAITOK | M_ZERO);
1651         unp_gc_marker->unp_flags |= UNP_MARKER;
1652
1653         /*
1654          * Create taskqueue for defered discard, and stick it to
1655          * the last CPU.
1656          */
1657         unp_taskqueue = taskqueue_create("unp_taskq", M_WAITOK,
1658             taskqueue_thread_enqueue, &unp_taskqueue);
1659         taskqueue_start_threads(&unp_taskqueue, 1, TDPRI_KERN_DAEMON,
1660             ncpus - 1, "unp taskq");
1661 }
1662
1663 static int
1664 unp_internalize(struct mbuf *control, struct thread *td)
1665 {
1666         struct proc *p = td->td_proc;
1667         struct filedesc *fdescp;
1668         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1669         struct file **rp;
1670         struct file *fp;
1671         int i, fd, *fdp;
1672         struct cmsgcred *cmcred;
1673         int oldfds;
1674         u_int newlen;
1675         int error;
1676
1677         KKASSERT(p);
1678
1679         if ((cm->cmsg_type != SCM_RIGHTS && cm->cmsg_type != SCM_CREDS) ||
1680             cm->cmsg_level != SOL_SOCKET ||
1681             CMSG_ALIGN(cm->cmsg_len) != control->m_len)
1682                 return EINVAL;
1683
1684         /*
1685          * Fill in credential information.
1686          */
1687         if (cm->cmsg_type == SCM_CREDS) {
1688                 cmcred = (struct cmsgcred *)CMSG_DATA(cm);
1689                 cmcred->cmcred_pid = p->p_pid;
1690                 cmcred->cmcred_uid = p->p_ucred->cr_ruid;
1691                 cmcred->cmcred_gid = p->p_ucred->cr_rgid;
1692                 cmcred->cmcred_euid = p->p_ucred->cr_uid;
1693                 cmcred->cmcred_ngroups = MIN(p->p_ucred->cr_ngroups,
1694                                                         CMGROUP_MAX);
1695                 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1696                         cmcred->cmcred_groups[i] = p->p_ucred->cr_groups[i];
1697                 return 0;
1698         }
1699
1700         /*
1701          * cmsghdr may not be aligned, do not allow calculation(s) to
1702          * go negative.
1703          */
1704         if (cm->cmsg_len < CMSG_LEN(0))
1705                 return EINVAL;
1706
1707         oldfds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1708
1709         /*
1710          * Now replace the integer FDs with pointers to
1711          * the associated global file table entry..
1712          * Allocate a bigger buffer as necessary. But if an cluster is not
1713          * enough, return E2BIG.
1714          */
1715         newlen = CMSG_LEN(oldfds * sizeof(struct file *));
1716         if (newlen > MCLBYTES)
1717                 return E2BIG;
1718         if (newlen - control->m_len > M_TRAILINGSPACE(control)) {
1719                 if (control->m_flags & M_EXT)
1720                         return E2BIG;
1721                 MCLGET(control, M_WAITOK);
1722                 if (!(control->m_flags & M_EXT))
1723                         return ENOBUFS;
1724
1725                 /* copy the data to the cluster */
1726                 memcpy(mtod(control, char *), cm, cm->cmsg_len);
1727                 cm = mtod(control, struct cmsghdr *);
1728         }
1729
1730         lwkt_gettoken(&unp_rights_token);
1731
1732         fdescp = p->p_fd;
1733         spin_lock_shared(&fdescp->fd_spin);
1734
1735         /*
1736          * check that all the FDs passed in refer to legal OPEN files
1737          * If not, reject the entire operation.
1738          */
1739         fdp = (int *)CMSG_DATA(cm);
1740         for (i = 0; i < oldfds; i++) {
1741                 fd = *fdp++;
1742                 if ((unsigned)fd >= fdescp->fd_nfiles ||
1743                     fdescp->fd_files[fd].fp == NULL) {
1744                         error = EBADF;
1745                         goto done;
1746                 }
1747                 if (fdescp->fd_files[fd].fp->f_type == DTYPE_KQUEUE) {
1748                         error = EOPNOTSUPP;
1749                         goto done;
1750                 }
1751         }
1752
1753         /*
1754          * Adjust length, in case sizeof(struct file *) and sizeof(int)
1755          * differs.
1756          */
1757         cm->cmsg_len = newlen;
1758         control->m_len = CMSG_ALIGN(newlen);
1759
1760         /*
1761          * Transform the file descriptors into struct file pointers.
1762          * Since the sizeof(struct file *) is bigger than or equal to
1763          * the sizeof(int), we do it in reverse order so that the int
1764          * won't get trashed until we're done.
1765          */
1766         fdp = (int *)CMSG_DATA(cm) + oldfds - 1;
1767         rp = (struct file **)CMSG_DATA(cm) + oldfds - 1;
1768         for (i = 0; i < oldfds; i++) {
1769                 fp = fdescp->fd_files[*fdp--].fp;
1770                 *rp-- = fp;
1771                 fhold(fp);
1772                 unp_add_right(fp);
1773         }
1774         error = 0;
1775 done:
1776         spin_unlock_shared(&fdescp->fd_spin);
1777         lwkt_reltoken(&unp_rights_token);
1778         return error;
1779 }
1780
1781 #ifdef UNP_GC_ALLFILES
1782
1783 /*
1784  * Garbage collect in-transit file descriptors that get lost due to
1785  * loops (i.e. when a socket is sent to another process over itself,
1786  * and more complex situations).
1787  *
1788  * NOT MPSAFE - TODO socket flush code and maybe fdrop.  Rest is MPSAFE.
1789  */
1790
1791 struct unp_gc_info {
1792         struct file **extra_ref;
1793         struct file *locked_fp;
1794         int defer;
1795         int index;
1796         int maxindex;
1797 };
1798
1799 static void
1800 unp_gc(void *arg __unused, int pending __unused)
1801 {
1802         struct unp_gc_info info;
1803         struct file **fpp;
1804         int i;
1805
1806         lwkt_gettoken(&unp_rights_token);
1807
1808         /* 
1809          * Before going through all this, set all FDs to be NOT defered
1810          * and NOT externally accessible (not marked).  During the scan
1811          * a fd can be marked externally accessible but we may or may not
1812          * be able to immediately process it (controlled by FDEFER).
1813          *
1814          * If we loop sleep a bit.  The complexity of the topology can cause
1815          * multiple loops.  Also failure to acquire the socket's so_rcv
1816          * token can cause us to loop.
1817          */
1818         allfiles_scan_exclusive(unp_gc_clearmarks, NULL);
1819         do {
1820                 info.defer = 0;
1821                 allfiles_scan_exclusive(unp_gc_checkmarks, &info);
1822                 if (info.defer)
1823                         tsleep(&info, 0, "gcagain", 1);
1824         } while (info.defer);
1825
1826         /*
1827          * We grab an extra reference to each of the file table entries
1828          * that are not otherwise accessible and then free the rights
1829          * that are stored in messages on them.
1830          *
1831          * The bug in the orginal code is a little tricky, so I'll describe
1832          * what's wrong with it here.
1833          *
1834          * It is incorrect to simply unp_discard each entry for f_msgcount
1835          * times -- consider the case of sockets A and B that contain
1836          * references to each other.  On a last close of some other socket,
1837          * we trigger a gc since the number of outstanding rights (unp_rights)
1838          * is non-zero.  If during the sweep phase the gc code unp_discards,
1839          * we end up doing a (full) fdrop on the descriptor.  A fdrop on A
1840          * results in the following chain.  Closef calls soo_close, which
1841          * calls soclose.   Soclose calls first (through the switch
1842          * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
1843          * returns because the previous instance had set unp_gcing, and
1844          * we return all the way back to soclose, which marks the socket
1845          * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
1846          * to free up the rights that are queued in messages on the socket A,
1847          * i.e., the reference on B.  The sorflush calls via the dom_dispose
1848          * switch unp_dispose, which unp_scans with unp_discard.  This second
1849          * instance of unp_discard just calls fdrop on B.
1850          *
1851          * Well, a similar chain occurs on B, resulting in a sorflush on B,
1852          * which results in another fdrop on A.  Unfortunately, A is already
1853          * being closed, and the descriptor has already been marked with
1854          * SS_NOFDREF, and soclose panics at this point.
1855          *
1856          * Here, we first take an extra reference to each inaccessible
1857          * descriptor.  Then, we call sorflush ourself, since we know
1858          * it is a Unix domain socket anyhow.  After we destroy all the
1859          * rights carried in messages, we do a last fdrop to get rid
1860          * of our extra reference.  This is the last close, and the
1861          * unp_detach etc will shut down the socket.
1862          *
1863          * 91/09/19, bsy@cs.cmu.edu
1864          */
1865         info.extra_ref = kmalloc(256 * sizeof(struct file *), M_FILE, M_WAITOK);
1866         info.maxindex = 256;
1867
1868         do {
1869                 /*
1870                  * Look for matches
1871                  */
1872                 info.index = 0;
1873                 allfiles_scan_exclusive(unp_gc_checkrefs, &info);
1874
1875                 /* 
1876                  * For each FD on our hit list, do the following two things
1877                  */
1878                 for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp) {
1879                         struct file *tfp = *fpp;
1880                         if (tfp->f_type == DTYPE_SOCKET && tfp->f_data != NULL)
1881                                 sorflush((struct socket *)(tfp->f_data));
1882                 }
1883                 for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp)
1884                         fdrop(*fpp);
1885         } while (info.index == info.maxindex);
1886
1887         kfree((caddr_t)info.extra_ref, M_FILE);
1888
1889         lwkt_reltoken(&unp_rights_token);
1890 }
1891
1892 /*
1893  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1894  */
1895 static int
1896 unp_gc_checkrefs(struct file *fp, void *data)
1897 {
1898         struct unp_gc_info *info = data;
1899
1900         if (fp->f_count == 0)
1901                 return(0);
1902         if (info->index == info->maxindex)
1903                 return(-1);
1904
1905         /* 
1906          * If all refs are from msgs, and it's not marked accessible
1907          * then it must be referenced from some unreachable cycle
1908          * of (shut-down) FDs, so include it in our
1909          * list of FDs to remove
1910          */
1911         if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1912                 info->extra_ref[info->index++] = fp;
1913                 fhold(fp);
1914         }
1915         return(0);
1916 }
1917
1918 /*
1919  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1920  */
1921 static int
1922 unp_gc_clearmarks(struct file *fp, void *data __unused)
1923 {
1924         atomic_clear_int(&fp->f_flag, FMARK | FDEFER);
1925         return(0);
1926 }
1927
1928 /*
1929  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1930  */
1931 static int
1932 unp_gc_checkmarks(struct file *fp, void *data)
1933 {
1934         struct unp_gc_info *info = data;
1935         struct socket *so;
1936
1937         /*
1938          * If the file is not open, skip it.  Make sure it isn't marked
1939          * defered or we could loop forever, in case we somehow race
1940          * something.
1941          */
1942         if (fp->f_count == 0) {
1943                 if (fp->f_flag & FDEFER)
1944                         atomic_clear_int(&fp->f_flag, FDEFER);
1945                 return(0);
1946         }
1947         /*
1948          * If we already marked it as 'defer'  in a
1949          * previous pass, then try process it this time
1950          * and un-mark it
1951          */
1952         if (fp->f_flag & FDEFER) {
1953                 atomic_clear_int(&fp->f_flag, FDEFER);
1954         } else {
1955                 /*
1956                  * if it's not defered, then check if it's
1957                  * already marked.. if so skip it
1958                  */
1959                 if (fp->f_flag & FMARK)
1960                         return(0);
1961                 /* 
1962                  * If all references are from messages
1963                  * in transit, then skip it. it's not 
1964                  * externally accessible.
1965                  */ 
1966                 if (fp->f_count == fp->f_msgcount)
1967                         return(0);
1968                 /* 
1969                  * If it got this far then it must be
1970                  * externally accessible.
1971                  */
1972                 atomic_set_int(&fp->f_flag, FMARK);
1973         }
1974
1975         /*
1976          * either it was defered, or it is externally 
1977          * accessible and not already marked so.
1978          * Now check if it is possibly one of OUR sockets.
1979          */ 
1980         if (fp->f_type != DTYPE_SOCKET ||
1981             (so = (struct socket *)fp->f_data) == NULL) {
1982                 return(0);
1983         }
1984         if (so->so_proto->pr_domain != &localdomain ||
1985             !(so->so_proto->pr_flags & PR_RIGHTS)) {
1986                 return(0);
1987         }
1988
1989         /*
1990          * So, Ok, it's one of our sockets and it IS externally accessible
1991          * (or was defered).  Now we look to see if we hold any file
1992          * descriptors in its message buffers.  Follow those links and mark
1993          * them as accessible too.
1994          *
1995          * We are holding multiple spinlocks here, if we cannot get the
1996          * token non-blocking defer until the next loop.
1997          */
1998         info->locked_fp = fp;
1999         if (lwkt_trytoken(&so->so_rcv.ssb_token)) {
2000                 unp_scan(so->so_rcv.ssb_mb, unp_mark, info);
2001                 lwkt_reltoken(&so->so_rcv.ssb_token);
2002         } else {
2003                 atomic_set_int(&fp->f_flag, FDEFER);
2004                 ++info->defer;
2005         }
2006         return (0);
2007 }
2008
2009 /*
2010  * Mark visibility.  info->defer is recalculated on every pass.
2011  */
2012 static void
2013 unp_mark(struct file *fp, void *data)
2014 {
2015         struct unp_gc_info *info = data;
2016
2017         if ((fp->f_flag & FMARK) == 0) {
2018                 ++info->defer;
2019                 atomic_set_int(&fp->f_flag, FMARK | FDEFER);
2020         } else if (fp->f_flag & FDEFER) {
2021                 ++info->defer;
2022         }
2023 }
2024
2025 #else   /* !UNP_GC_ALLFILES */
2026
2027 /*
2028  * They are thread local and do not require explicit synchronization.
2029  */
2030 static int      unp_marked;
2031 static int      unp_unreachable;
2032
2033 static void
2034 unp_accessable(struct file *fp, void *data __unused)
2035 {
2036         struct unpcb *unp;
2037
2038         if ((unp = unp_fp2unpcb(fp)) == NULL)
2039                 return;
2040         if (unp->unp_gcflags & UNPGC_REF)
2041                 return;
2042         unp->unp_gcflags &= ~UNPGC_DEAD;
2043         unp->unp_gcflags |= UNPGC_REF;
2044         unp_marked++;
2045 }
2046
2047 static void
2048 unp_gc_process(struct unpcb *unp)
2049 {
2050         struct file *fp;
2051
2052         /* Already processed. */
2053         if (unp->unp_gcflags & UNPGC_SCANNED)
2054                 return;
2055         fp = unp->unp_fp;
2056
2057         /*
2058          * Check for a socket potentially in a cycle.  It must be in a
2059          * queue as indicated by msgcount, and this must equal the file
2060          * reference count.  Note that when msgcount is 0 the file is NULL.
2061          */
2062         if ((unp->unp_gcflags & UNPGC_REF) == 0 && fp &&
2063             unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2064                 unp->unp_gcflags |= UNPGC_DEAD;
2065                 unp_unreachable++;
2066                 return;
2067         }
2068
2069         /*
2070          * Mark all sockets we reference with RIGHTS.
2071          */
2072         if (UNP_ISATTACHED(unp)) {
2073                 struct signalsockbuf *ssb = &unp->unp_socket->so_rcv;
2074
2075                 unp_reference(unp);
2076                 lwkt_gettoken(&ssb->ssb_token);
2077                 /*
2078                  * unp_token would be temporarily dropped, if getting
2079                  * so_rcv token blocks, so we need to check unp state
2080                  * here again.
2081                  */
2082                 if (UNP_ISATTACHED(unp))
2083                         unp_scan(ssb->ssb_mb, unp_accessable, NULL);
2084                 lwkt_reltoken(&ssb->ssb_token);
2085                 unp->unp_gcflags |= UNPGC_SCANNED;
2086                 unp_free(unp);
2087         } else {
2088                 unp->unp_gcflags |= UNPGC_SCANNED;
2089         }
2090 }
2091
2092 static void
2093 unp_gc(void *arg __unused, int pending __unused)
2094 {
2095         struct unp_global_head *head;
2096         int h, filemax, fileidx, filetot;
2097         struct file **unref;
2098         struct unpcb *unp;
2099
2100         lwkt_gettoken(&unp_rights_token);
2101         lwkt_gettoken(&unp_token);
2102
2103         /*
2104          * First clear all gc flags from previous runs.
2105          */
2106         for (h = 0; unp_heads[h] != NULL; ++h) {
2107                 /* 
2108                  * NOTE: This loop does not block, so it is safe
2109                  * to use TAILQ_FOREACH here.
2110                  */
2111                 head = unp_heads[h];
2112                 TAILQ_FOREACH(unp, &head->list, unp_link)
2113                         unp->unp_gcflags = 0;
2114         }
2115
2116         /*
2117          * Scan marking all reachable sockets with UNPGC_REF.  Once a socket
2118          * is reachable all of the sockets it references are reachable.
2119          * Stop the scan once we do a complete loop without discovering
2120          * a new reachable socket.
2121          */
2122         do {
2123                 unp_unreachable = 0;
2124                 unp_marked = 0;
2125                 for (h = 0; unp_heads[h] != NULL; ++h) {
2126                         head = unp_heads[h];
2127                         TAILQ_INSERT_HEAD(&head->list, unp_gc_marker, unp_link);
2128                         while ((unp = TAILQ_NEXT(unp_gc_marker, unp_link))
2129                             != NULL) {
2130                                 TAILQ_REMOVE(&head->list, unp_gc_marker,
2131                                     unp_link);
2132                                 TAILQ_INSERT_AFTER(&head->list, unp,
2133                                     unp_gc_marker, unp_link);
2134
2135                                 if (unp->unp_flags & UNP_MARKER)
2136                                         continue;
2137                                 unp_gc_process(unp);
2138                         }
2139                         TAILQ_REMOVE(&head->list, unp_gc_marker, unp_link);
2140                 }
2141         } while (unp_marked);
2142
2143         if (unp_unreachable == 0)
2144                 goto done;
2145
2146         /*
2147          * We grab an extra reference to each of the file table entries
2148          * that are not otherwise accessible and then free the rights
2149          * that are stored in messages on them.
2150          *
2151          * The bug in the orginal code is a little tricky, so I'll describe
2152          * what's wrong with it here.
2153          *
2154          * It is incorrect to simply unp_discard each entry for f_msgcount
2155          * times -- consider the case of sockets A and B that contain
2156          * references to each other.  On a last close of some other socket,
2157          * we trigger a gc since the number of outstanding rights (unp_rights)
2158          * is non-zero.  If during the sweep phase the gc code unp_discards,
2159          * we end up doing a (full) fdrop on the descriptor.  A fdrop on A
2160          * results in the following chain.  Closef calls soo_close, which
2161          * calls soclose.   Soclose calls first (through the switch
2162          * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
2163          * returns because the previous instance had set unp_gcing, and
2164          * we return all the way back to soclose, which marks the socket
2165          * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
2166          * to free up the rights that are queued in messages on the socket A,
2167          * i.e., the reference on B.  The sorflush calls via the dom_dispose
2168          * switch unp_dispose, which unp_scans with unp_discard.  This second
2169          * instance of unp_discard just calls fdrop on B.
2170          *
2171          * Well, a similar chain occurs on B, resulting in a sorflush on B,
2172          * which results in another fdrop on A.  Unfortunately, A is already
2173          * being closed, and the descriptor has already been marked with
2174          * SS_NOFDREF, and soclose panics at this point.
2175          *
2176          * Here, we first take an extra reference to each inaccessible
2177          * descriptor.  Then, we call sorflush ourself, since we know
2178          * it is a Unix domain socket anyhow.  After we destroy all the
2179          * rights carried in messages, we do a last fdrop to get rid
2180          * of our extra reference.  This is the last close, and the
2181          * unp_detach etc will shut down the socket.
2182          *
2183          * 91/09/19, bsy@cs.cmu.edu
2184          */
2185
2186         filemax = unp_unreachable;
2187         if (filemax > UNP_GCFILE_MAX)
2188                 filemax = UNP_GCFILE_MAX;
2189         unref = kmalloc(filemax * sizeof(struct file *), M_TEMP, M_WAITOK);
2190
2191         filetot = 0;
2192         do {
2193                 int i;
2194
2195                 /*
2196                  * Iterate looking for sockets which have been specifically
2197                  * marked as as unreachable and store them locally.
2198                  */
2199                 fileidx = 0;
2200                 for (h = 0; unp_heads[h] != NULL; ++h) {
2201                         /*
2202                          * NOTE: This loop does not block, so it is safe
2203                          * to use TAILQ_FOREACH here.
2204                          */
2205                         head = unp_heads[h];
2206                         TAILQ_FOREACH(unp, &head->list, unp_link) {
2207                                 struct file *fp;
2208
2209                                 if ((unp->unp_gcflags & UNPGC_DEAD) == 0)
2210                                         continue;
2211                                 unp->unp_gcflags &= ~UNPGC_DEAD;
2212
2213                                 fp = unp->unp_fp;
2214                                 if (unp->unp_msgcount == 0 || fp == NULL ||
2215                                     fp->f_count != unp->unp_msgcount)
2216                                         continue;
2217                                 fhold(fp);
2218
2219                                 KASSERT(fileidx < filemax,
2220                                     ("invalid fileidx %d, filemax %d",
2221                                      fileidx, filemax));
2222                                 unref[fileidx++] = fp;
2223
2224                                 KASSERT(filetot < unp_unreachable,
2225                                     ("invalid filetot %d and "
2226                                      "unp_unreachable %d",
2227                                      filetot, unp_unreachable));
2228                                 ++filetot;
2229
2230                                 if (fileidx == filemax ||
2231                                     filetot == unp_unreachable)
2232                                         goto dogc;
2233                         }
2234                 }
2235 dogc:
2236                 /*
2237                  * For each Unix domain socket on our hit list, do the
2238                  * following two things.
2239                  */
2240                 for (i = 0; i < fileidx; ++i)
2241                         sorflush(unref[i]->f_data);
2242                 for (i = 0; i < fileidx; ++i)
2243                         fdrop(unref[i]);
2244         } while (fileidx == filemax && filetot < unp_unreachable);
2245         kfree(unref, M_TEMP);
2246 done:
2247         lwkt_reltoken(&unp_token);
2248         lwkt_reltoken(&unp_rights_token);
2249 }
2250
2251 #endif  /* UNP_GC_ALLFILES */
2252
2253 /*
2254  * Dispose of the fp's stored in a mbuf.
2255  *
2256  * The dds loop can cause additional fps to be entered onto the
2257  * list while it is running, flattening out the operation and avoiding
2258  * a deep kernel stack recursion.
2259  */
2260 void
2261 unp_dispose(struct mbuf *m)
2262 {
2263         lwkt_gettoken(&unp_rights_token);
2264         if (m)
2265                 unp_scan(m, unp_discard, NULL);
2266         lwkt_reltoken(&unp_rights_token);
2267 }
2268
2269 static int
2270 unp_listen(struct unpcb *unp, struct thread *td)
2271 {
2272         struct proc *p = td->td_proc;
2273
2274         ASSERT_LWKT_TOKEN_HELD(&unp_token);
2275         UNP_ASSERT_TOKEN_HELD(unp);
2276
2277         KKASSERT(p);
2278         cru2x(p->p_ucred, &unp->unp_peercred);
2279         unp_setflags(unp, UNP_HAVEPCCACHED);
2280         return (0);
2281 }
2282
2283 static void
2284 unp_scan(struct mbuf *m0, void (*op)(struct file *, void *), void *data)
2285 {
2286         struct mbuf *m;
2287         struct file **rp;
2288         struct cmsghdr *cm;
2289         int i;
2290         int qfds;
2291
2292         while (m0) {
2293                 for (m = m0; m; m = m->m_next) {
2294                         if (m->m_type == MT_CONTROL &&
2295                             m->m_len >= sizeof(*cm)) {
2296                                 cm = mtod(m, struct cmsghdr *);
2297                                 if (cm->cmsg_level != SOL_SOCKET ||
2298                                     cm->cmsg_type != SCM_RIGHTS)
2299                                         continue;
2300                                 qfds = (cm->cmsg_len - CMSG_LEN(0)) /
2301                                         sizeof(void *);
2302                                 rp = (struct file **)CMSG_DATA(cm);
2303                                 for (i = 0; i < qfds; i++)
2304                                         (*op)(*rp++, data);
2305                                 break;          /* XXX, but saves time */
2306                         }
2307                 }
2308                 m0 = m0->m_nextpkt;
2309         }
2310 }
2311
2312 /*
2313  * Discard a fp previously held in a unix domain socket mbuf.  To
2314  * avoid blowing out the kernel stack due to contrived chain-reactions
2315  * we may have to defer the operation to a dedicated taskqueue.
2316  *
2317  * Caller holds unp_rights_token.
2318  */
2319 static void
2320 unp_discard(struct file *fp, void *data __unused)
2321 {
2322         unp_del_right(fp);
2323         if (unp_fp2unpcb(fp) != NULL) {
2324                 struct unp_defdiscard *d;
2325
2326                 /*
2327                  * This fp is a Unix domain socket itself and fdrop()
2328                  * it here directly may cause deep unp_discard()
2329                  * recursion, so the fdrop() is defered to the
2330                  * dedicated taskqueue.
2331                  */
2332                 d = kmalloc(sizeof(*d), M_UNPCB, M_WAITOK);
2333                 d->fp = fp;
2334
2335                 spin_lock(&unp_defdiscard_spin);
2336                 SLIST_INSERT_HEAD(&unp_defdiscard_head, d, next);
2337                 spin_unlock(&unp_defdiscard_spin);
2338
2339                 taskqueue_enqueue(unp_taskqueue, &unp_defdiscard_task);
2340         } else {
2341                 /* This fp is not a Unix domain socket */
2342                 fdrop(fp);
2343         }
2344 }
2345
2346 /*
2347  * NOTE:
2348  * unp_token must be held before calling this function to avoid name
2349  * resolution and v_socket accessing races, especially racing against
2350  * the unp_detach().
2351  *
2352  * NOTE:
2353  * For anyone caring about unconnected Unix domain socket sending
2354  * performance, other approach could be taken...
2355  */
2356 static int
2357 unp_find_lockref(struct sockaddr *nam, struct thread *td, short type,
2358     struct unpcb **unp_ret)
2359 {
2360         struct proc *p = td->td_proc;
2361         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
2362         struct vnode *vp = NULL;
2363         struct socket *so;
2364         struct unpcb *unp;
2365         int error, len;
2366         struct nlookupdata nd;
2367         char buf[SOCK_MAXADDRLEN];
2368
2369         ASSERT_LWKT_TOKEN_HELD(&unp_token);
2370
2371         *unp_ret = NULL;
2372
2373         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
2374         if (len <= 0) {
2375                 error = EINVAL;
2376                 goto failed;
2377         }
2378         strncpy(buf, soun->sun_path, len);
2379         buf[len] = 0;
2380
2381         error = nlookup_init(&nd, buf, UIO_SYSSPACE, NLC_FOLLOW);
2382         if (error == 0)
2383                 error = nlookup(&nd);
2384         if (error == 0)
2385                 error = cache_vget(&nd.nl_nch, nd.nl_cred, LK_EXCLUSIVE, &vp);
2386         nlookup_done(&nd);
2387         if (error) {
2388                 vp = NULL;
2389                 goto failed;
2390         }
2391
2392         if (vp->v_type != VSOCK) {
2393                 error = ENOTSOCK;
2394                 goto failed;
2395         }
2396         error = VOP_EACCESS(vp, VWRITE, p->p_ucred);
2397         if (error)
2398                 goto failed;
2399         so = vp->v_socket;
2400         if (so == NULL) {
2401                 error = ECONNREFUSED;
2402                 goto failed;
2403         }
2404         if (so->so_type != type) {
2405                 error = EPROTOTYPE;
2406                 goto failed;
2407         }
2408
2409         /* Lock this unp. */
2410         unp = unp_getsocktoken(so);
2411         if (!UNP_ISATTACHED(unp)) {
2412                 unp_reltoken(unp);
2413                 error = ECONNREFUSED;
2414                 goto failed;
2415         }
2416         /* And keep this unp referenced. */
2417         unp_reference(unp);
2418
2419         /* Done! */
2420         *unp_ret = unp;
2421         error = 0;
2422 failed:
2423         if (vp != NULL)
2424                 vput(vp);
2425         return error;
2426 }
2427
2428 static int
2429 unp_connect_pair(struct unpcb *unp, struct unpcb *unp2)
2430 {
2431         struct socket *so = unp->unp_socket;
2432         struct socket *so2 = unp2->unp_socket;
2433
2434         ASSERT_LWKT_TOKEN_HELD(&unp_token);
2435         UNP_ASSERT_TOKEN_HELD(unp);
2436         UNP_ASSERT_TOKEN_HELD(unp2);
2437
2438         KASSERT(so->so_type == so2->so_type,
2439             ("socket type mismatch, so %d, so2 %d", so->so_type, so2->so_type));
2440
2441         if (!UNP_ISATTACHED(unp))
2442                 return EINVAL;
2443         if (!UNP_ISATTACHED(unp2))
2444                 return ECONNREFUSED;
2445
2446         KASSERT(unp->unp_conn == NULL, ("unp is already connected"));
2447         unp->unp_conn = unp2;
2448
2449         switch (so->so_type) {
2450         case SOCK_DGRAM:
2451                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2452                 soisconnected(so);
2453                 break;
2454
2455         case SOCK_STREAM:
2456         case SOCK_SEQPACKET:
2457                 KASSERT(unp2->unp_conn == NULL, ("unp2 is already connected"));
2458                 unp2->unp_conn = unp;
2459                 soisconnected(so);
2460                 soisconnected(so2);
2461                 break;
2462
2463         default:
2464                 panic("unp_connect_pair: unknown socket type %d", so->so_type);
2465         }
2466         return 0;
2467 }
2468
2469 static void
2470 unp_drop(struct unpcb *unp, int error)
2471 {
2472         struct unp_global_head *head;
2473         struct unpcb *unp2;
2474
2475         ASSERT_LWKT_TOKEN_HELD(&unp_token);
2476         UNP_ASSERT_TOKEN_HELD(unp);
2477
2478         KASSERT((unp->unp_flags & (UNP_DETACHED | UNP_DROPPED)) == 0,
2479             ("unp is dropped"));
2480
2481         /* Mark this unp as detached. */
2482         unp_setflags(unp, UNP_DETACHED);
2483
2484         /* Remove this unp from the global unp list. */
2485         head = unp_globalhead(unp->unp_socket->so_type);
2486         KASSERT(head->count > 0, ("invalid unp count"));
2487         TAILQ_REMOVE(&head->list, unp, unp_link);
2488         head->count--;
2489
2490         /* Disconnect all. */
2491         unp_disconnect(unp, error);
2492         while ((unp2 = LIST_FIRST(&unp->unp_refs)) != NULL) {
2493                 lwkt_getpooltoken(unp2);
2494                 unp_disconnect(unp2, ECONNRESET);
2495                 lwkt_relpooltoken(unp2);
2496         }
2497         unp_setflags(unp, UNP_DROPPED);
2498
2499         /* Try freeing this unp. */
2500         unp_free(unp);
2501 }
2502
2503 static void
2504 unp_defdiscard_taskfunc(void *arg __unused, int pending __unused)
2505 {
2506         struct unp_defdiscard *d;
2507
2508         spin_lock(&unp_defdiscard_spin);
2509         while ((d = SLIST_FIRST(&unp_defdiscard_head)) != NULL) {
2510                 SLIST_REMOVE_HEAD(&unp_defdiscard_head, next);
2511                 spin_unlock(&unp_defdiscard_spin);
2512
2513                 fdrop(d->fp);
2514                 kfree(d, M_UNPCB);
2515
2516                 spin_lock(&unp_defdiscard_spin);
2517         }
2518         spin_unlock(&unp_defdiscard_spin);
2519 }