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