network - Major netmsg retooling, part 1
[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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
34  * $FreeBSD: src/sys/kern/uipc_usrreq.c,v 1.54.2.10 2003/03/04 17:28:09 nectar Exp $
35  * $DragonFly: src/sys/kern/uipc_usrreq.c,v 1.44 2008/09/06 05:44:58 dillon Exp $
36  */
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/domain.h>
42 #include <sys/fcntl.h>
43 #include <sys/malloc.h>         /* XXX must be before <sys/file.h> */
44 #include <sys/proc.h>
45 #include <sys/file.h>
46 #include <sys/filedesc.h>
47 #include <sys/mbuf.h>
48 #include <sys/nlookup.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/resourcevar.h>
53 #include <sys/stat.h>
54 #include <sys/mount.h>
55 #include <sys/sysctl.h>
56 #include <sys/un.h>
57 #include <sys/unpcb.h>
58 #include <sys/vnode.h>
59
60 #include <sys/file2.h>
61 #include <sys/spinlock2.h>
62 #include <sys/socketvar2.h>
63 #include <sys/msgport2.h>
64
65 static  MALLOC_DEFINE(M_UNPCB, "unpcb", "unpcb struct");
66 static  unp_gen_t unp_gencnt;
67 static  u_int unp_count;
68
69 static  struct unp_head unp_shead, unp_dhead;
70
71 static struct lwkt_token unp_token = LWKT_TOKEN_MP_INITIALIZER(unp_token);
72
73 /*
74  * Unix communications domain.
75  *
76  * TODO:
77  *      RDM
78  *      rethink name space problems
79  *      need a proper out-of-band
80  *      lock pushdown
81  */
82 static struct   sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
83 static ino_t    unp_ino = 1;            /* prototype for fake inode numbers */
84 static struct spinlock unp_ino_spin = SPINLOCK_INITIALIZER(&unp_ino_spin);
85
86 static int     unp_attach (struct socket *, struct pru_attach_info *);
87 static void    unp_detach (struct unpcb *);
88 static int     unp_bind (struct unpcb *,struct sockaddr *, struct thread *);
89 static int     unp_connect (struct socket *,struct sockaddr *,
90                                 struct thread *);
91 static void    unp_disconnect (struct unpcb *);
92 static void    unp_shutdown (struct unpcb *);
93 static void    unp_drop (struct unpcb *, int);
94 static void    unp_gc (void);
95 static int     unp_gc_clearmarks(struct file *, void *);
96 static int     unp_gc_checkmarks(struct file *, void *);
97 static int     unp_gc_checkrefs(struct file *, void *);
98 static int     unp_revoke_gc_check(struct file *, void *);
99 static void    unp_scan (struct mbuf *, void (*)(struct file *, void *),
100                                 void *data);
101 static void    unp_mark (struct file *, void *data);
102 static void    unp_discard (struct file *, void *);
103 static int     unp_internalize (struct mbuf *, struct thread *);
104 static int     unp_listen (struct unpcb *, struct thread *);
105 static void    unp_fp_externalize(struct lwp *lp, struct file *fp, int fd);
106
107 /*
108  * NOTE: (so) is referenced from soabort*() and netmsg_pru_abort()
109  *       will sofree() it when we return.
110  */
111 static void
112 uipc_abort(netmsg_t msg)
113 {
114         struct unpcb *unp;
115         int error;
116
117         lwkt_gettoken(&unp_token);
118         unp = msg->base.nm_so->so_pcb;
119         if (unp) {
120                 unp_drop(unp, ECONNABORTED);
121                 unp_detach(unp);
122                 error = 0;
123         } else {
124                 error = EINVAL;
125         }
126         lwkt_reltoken(&unp_token);
127
128         lwkt_replymsg(&msg->lmsg, error);
129 }
130
131 static void
132 uipc_accept(netmsg_t msg)
133 {
134         struct unpcb *unp;
135         int error;
136
137         lwkt_gettoken(&unp_token);
138         unp = msg->base.nm_so->so_pcb;
139         if (unp == NULL) {
140                 error = EINVAL;
141         } else {
142                 /*
143                  * Pass back name of connected socket,
144                  * if it was bound and we are still connected
145                  * (our peer may have closed already!).
146                  */
147                 if (unp->unp_conn && unp->unp_conn->unp_addr) {
148                         *msg->accept.nm_nam = dup_sockaddr(
149                                 (struct sockaddr *)unp->unp_conn->unp_addr);
150                 } else {
151                         *msg->accept.nm_nam = dup_sockaddr(
152                                 (struct sockaddr *)&sun_noname);
153                 }
154                 error = 0;
155         }
156         lwkt_reltoken(&unp_token);
157         lwkt_replymsg(&msg->lmsg, error);
158 }
159
160 static void
161 uipc_attach(netmsg_t msg)
162 {
163         struct unpcb *unp;
164         int error;
165
166         lwkt_gettoken(&unp_token);
167         unp = msg->base.nm_so->so_pcb;
168         if (unp)
169                 error = EISCONN;
170         else
171                 error = unp_attach(msg->base.nm_so, msg->attach.nm_ai);
172         lwkt_reltoken(&unp_token);
173         lwkt_replymsg(&msg->lmsg, error);
174 }
175
176 static void
177 uipc_bind(netmsg_t msg)
178 {
179         struct unpcb *unp;
180         int error;
181
182         lwkt_gettoken(&unp_token);
183         unp = msg->base.nm_so->so_pcb;
184         if (unp)
185                 error = unp_bind(unp, msg->bind.nm_nam, msg->bind.nm_td);
186         else
187                 error = EINVAL;
188         lwkt_reltoken(&unp_token);
189         lwkt_replymsg(&msg->lmsg, error);
190 }
191
192 static void
193 uipc_connect(netmsg_t msg)
194 {
195         struct unpcb *unp;
196         int error;
197
198         lwkt_gettoken(&unp_token);
199         unp = msg->base.nm_so->so_pcb;
200         if (unp) {
201                 error = unp_connect(msg->base.nm_so,
202                                     msg->connect.nm_nam,
203                                     msg->connect.nm_td);
204         } else {
205                 error = EINVAL;
206         }
207         lwkt_reltoken(&unp_token);
208         lwkt_replymsg(&msg->lmsg, error);
209 }
210
211 static void
212 uipc_connect2(netmsg_t msg)
213 {
214         struct unpcb *unp;
215         int error;
216
217         lwkt_gettoken(&unp_token);
218         unp = msg->connect2.nm_so1->so_pcb;
219         if (unp) {
220                 error = unp_connect2(msg->connect2.nm_so1,
221                                      msg->connect2.nm_so2);
222         } else {
223                 error = EINVAL;
224         }
225         lwkt_reltoken(&unp_token);
226         lwkt_replymsg(&msg->lmsg, error);
227 }
228
229 /* control is EOPNOTSUPP */
230
231 static void
232 uipc_detach(netmsg_t msg)
233 {
234         struct unpcb *unp;
235         int error;
236
237         lwkt_gettoken(&unp_token);
238         unp = msg->base.nm_so->so_pcb;
239         if (unp) {
240                 unp_detach(unp);
241                 error = 0;
242         } else {
243                 error = EINVAL;
244         }
245         lwkt_reltoken(&unp_token);
246         lwkt_replymsg(&msg->lmsg, error);
247 }
248
249 static void
250 uipc_disconnect(netmsg_t msg)
251 {
252         struct unpcb *unp;
253         int error;
254
255         lwkt_gettoken(&unp_token);
256         unp = msg->base.nm_so->so_pcb;
257         if (unp) {
258                 unp_disconnect(unp);
259                 error = 0;
260         } else {
261                 error = EINVAL;
262         }
263         lwkt_reltoken(&unp_token);
264         lwkt_replymsg(&msg->lmsg, error);
265 }
266
267 static void
268 uipc_listen(netmsg_t msg)
269 {
270         struct unpcb *unp;
271         int error;
272
273         lwkt_gettoken(&unp_token);
274         unp = msg->base.nm_so->so_pcb;
275         if (unp == NULL || unp->unp_vnode == NULL)
276                 error = EINVAL;
277         else
278                 error = unp_listen(unp, msg->listen.nm_td);
279         lwkt_reltoken(&unp_token);
280         lwkt_replymsg(&msg->lmsg, error);
281 }
282
283 static void
284 uipc_peeraddr(netmsg_t msg)
285 {
286         struct unpcb *unp;
287         int error;
288
289         lwkt_gettoken(&unp_token);
290         unp = msg->base.nm_so->so_pcb;
291         if (unp == NULL) {
292                 error = EINVAL;
293         } else if (unp->unp_conn && unp->unp_conn->unp_addr) {
294                 *msg->peeraddr.nm_nam = dup_sockaddr(
295                                 (struct sockaddr *)unp->unp_conn->unp_addr);
296                 error = 0;
297         } else {
298                 /*
299                  * XXX: It seems that this test always fails even when
300                  * connection is established.  So, this else clause is
301                  * added as workaround to return PF_LOCAL sockaddr.
302                  */
303                 *msg->peeraddr.nm_nam = dup_sockaddr(
304                                 (struct sockaddr *)&sun_noname);
305                 error = 0;
306         }
307         lwkt_reltoken(&unp_token);
308         lwkt_replymsg(&msg->lmsg, error);
309 }
310
311 static void
312 uipc_rcvd(netmsg_t msg)
313 {
314         struct unpcb *unp;
315         struct socket *so;
316         struct socket *so2;
317         int error;
318
319         lwkt_gettoken(&unp_token);
320         so = msg->base.nm_so;
321         unp = so->so_pcb;
322         if (unp == NULL) {
323                 error = EINVAL;
324                 goto done;
325         }
326
327         switch (so->so_type) {
328         case SOCK_DGRAM:
329                 panic("uipc_rcvd DGRAM?");
330                 /*NOTREACHED*/
331         case SOCK_STREAM:
332         case SOCK_SEQPACKET:
333                 if (unp->unp_conn == NULL)
334                         break;
335                 /*
336                  * Because we are transfering mbufs directly to the
337                  * peer socket we have to use SSB_STOP on the sender
338                  * to prevent it from building up infinite mbufs.
339                  */
340                 so2 = unp->unp_conn->unp_socket;
341                 if (so->so_rcv.ssb_cc < so2->so_snd.ssb_hiwat &&
342                     so->so_rcv.ssb_mbcnt < so2->so_snd.ssb_mbmax
343                 ) {
344                         atomic_clear_int(&so2->so_snd.ssb_flags, SSB_STOP);
345                         sowwakeup(so2);
346                 }
347                 break;
348         default:
349                 panic("uipc_rcvd unknown socktype");
350                 /*NOTREACHED*/
351         }
352         error = 0;
353 done:
354         lwkt_reltoken(&unp_token);
355         lwkt_replymsg(&msg->lmsg, error);
356 }
357
358 /* pru_rcvoob is EOPNOTSUPP */
359
360 static void
361 uipc_send(netmsg_t msg)
362 {
363         struct unpcb *unp;
364         struct socket *so;
365         struct socket *so2;
366         struct mbuf *control;
367         struct mbuf *m;
368         int error = 0;
369
370         lwkt_gettoken(&unp_token);
371         so = msg->base.nm_so;
372         control = msg->send.nm_control;
373         m = msg->send.nm_m;
374         unp = so->so_pcb;
375
376         if (unp == NULL) {
377                 error = EINVAL;
378                 goto release;
379         }
380         if (msg->send.nm_flags & PRUS_OOB) {
381                 error = EOPNOTSUPP;
382                 goto release;
383         }
384
385         if (control && (error = unp_internalize(control, msg->send.nm_td)))
386                 goto release;
387
388         switch (so->so_type) {
389         case SOCK_DGRAM: 
390         {
391                 struct sockaddr *from;
392
393                 if (msg->send.nm_addr) {
394                         if (unp->unp_conn) {
395                                 error = EISCONN;
396                                 break;
397                         }
398                         error = unp_connect(so,
399                                             msg->send.nm_addr,
400                                             msg->send.nm_td);
401                         if (error)
402                                 break;
403                 } else {
404                         if (unp->unp_conn == NULL) {
405                                 error = ENOTCONN;
406                                 break;
407                         }
408                 }
409                 so2 = unp->unp_conn->unp_socket;
410                 if (unp->unp_addr)
411                         from = (struct sockaddr *)unp->unp_addr;
412                 else
413                         from = &sun_noname;
414                 if (ssb_appendaddr(&so2->so_rcv, from, m, control)) {
415                         sorwakeup(so2);
416                         m = NULL;
417                         control = NULL;
418                 } else {
419                         error = ENOBUFS;
420                 }
421                 if (msg->send.nm_addr)
422                         unp_disconnect(unp);
423                 break;
424         }
425
426         case SOCK_STREAM:
427         case SOCK_SEQPACKET:
428                 /* Connect if not connected yet. */
429                 /*
430                  * Note: A better implementation would complain
431                  * if not equal to the peer's address.
432                  */
433                 if (!(so->so_state & SS_ISCONNECTED)) {
434                         if (msg->send.nm_addr) {
435                                 error = unp_connect(so,
436                                                     msg->send.nm_addr,
437                                                     msg->send.nm_td);
438                                 if (error)
439                                         break;  /* XXX */
440                         } else {
441                                 error = ENOTCONN;
442                                 break;
443                         }
444                 }
445
446                 if (so->so_state & SS_CANTSENDMORE) {
447                         error = EPIPE;
448                         break;
449                 }
450                 if (unp->unp_conn == NULL)
451                         panic("uipc_send connected but no connection?");
452                 so2 = unp->unp_conn->unp_socket;
453                 /*
454                  * Send to paired receive port, and then reduce
455                  * send buffer hiwater marks to maintain backpressure.
456                  * Wake up readers.
457                  */
458                 if (control) {
459                         if (ssb_appendcontrol(&so2->so_rcv, m, control)) {
460                                 control = NULL;
461                                 m = NULL;
462                         }
463                 } else if (so->so_type == SOCK_SEQPACKET) {
464                         sbappendrecord(&so2->so_rcv.sb, m);
465                         m = NULL;
466                 } else {
467                         sbappend(&so2->so_rcv.sb, m);
468                         m = NULL;
469                 }
470
471                 /*
472                  * Because we are transfering mbufs directly to the
473                  * peer socket we have to use SSB_STOP on the sender
474                  * to prevent it from building up infinite mbufs.
475                  */
476                 if (so2->so_rcv.ssb_cc >= so->so_snd.ssb_hiwat ||
477                     so2->so_rcv.ssb_mbcnt >= so->so_snd.ssb_mbmax
478                 ) {
479                         atomic_set_int(&so->so_snd.ssb_flags, SSB_STOP);
480                 }
481                 sorwakeup(so2);
482                 break;
483
484         default:
485                 panic("uipc_send unknown socktype");
486         }
487
488         /*
489          * SEND_EOF is equivalent to a SEND followed by a SHUTDOWN.
490          */
491         if (msg->send.nm_flags & PRUS_EOF) {
492                 socantsendmore(so);
493                 unp_shutdown(unp);
494         }
495
496         if (control && error != 0)
497                 unp_dispose(control);
498
499 release:
500         lwkt_reltoken(&unp_token);
501
502         if (control)
503                 m_freem(control);
504         if (m)
505                 m_freem(m);
506         lwkt_replymsg(&msg->lmsg, error);
507 }
508
509 /*
510  * MPSAFE
511  */
512 static void
513 uipc_sense(netmsg_t msg)
514 {
515         struct unpcb *unp;
516         struct socket *so;
517         struct stat *sb;
518         int error;
519
520         lwkt_gettoken(&unp_token);
521         so = msg->base.nm_so;
522         sb = msg->sense.nm_stat;
523         unp = so->so_pcb;
524         if (unp == NULL) {
525                 error = EINVAL;
526                 goto done;
527         }
528         sb->st_blksize = so->so_snd.ssb_hiwat;
529         sb->st_dev = NOUDEV;
530         if (unp->unp_ino == 0) {        /* make up a non-zero inode number */
531                 spin_lock(&unp_ino_spin);
532                 unp->unp_ino = unp_ino++;
533                 spin_unlock(&unp_ino_spin);
534         }
535         sb->st_ino = unp->unp_ino;
536         error = 0;
537 done:
538         lwkt_reltoken(&unp_token);
539         lwkt_replymsg(&msg->lmsg, error);
540 }
541
542 static void
543 uipc_shutdown(netmsg_t msg)
544 {
545         struct socket *so;
546         struct unpcb *unp;
547         int error;
548
549         lwkt_gettoken(&unp_token);
550         so = msg->base.nm_so;
551         unp = so->so_pcb;
552         if (unp) {
553                 socantsendmore(so);
554                 unp_shutdown(unp);
555                 error = 0;
556         } else {
557                 error = EINVAL;
558         }
559         lwkt_reltoken(&unp_token);
560         lwkt_replymsg(&msg->lmsg, error);
561 }
562
563 static void
564 uipc_sockaddr(netmsg_t msg)
565 {
566         struct unpcb *unp;
567         int error;
568
569         lwkt_gettoken(&unp_token);
570         unp = msg->base.nm_so->so_pcb;
571         if (unp) {
572                 if (unp->unp_addr) {
573                         *msg->sockaddr.nm_nam =
574                                 dup_sockaddr((struct sockaddr *)unp->unp_addr);
575                 }
576                 error = 0;
577         } else {
578                 error = EINVAL;
579         }
580         lwkt_reltoken(&unp_token);
581         lwkt_replymsg(&msg->lmsg, error);
582 }
583
584 struct pr_usrreqs uipc_usrreqs = {
585         .pru_abort = uipc_abort,
586         .pru_accept = uipc_accept,
587         .pru_attach = uipc_attach,
588         .pru_bind = uipc_bind,
589         .pru_connect = uipc_connect,
590         .pru_connect2 = uipc_connect2,
591         .pru_control = pr_generic_notsupp,
592         .pru_detach = uipc_detach,
593         .pru_disconnect = uipc_disconnect,
594         .pru_listen = uipc_listen,
595         .pru_peeraddr = uipc_peeraddr,
596         .pru_rcvd = uipc_rcvd,
597         .pru_rcvoob = pr_generic_notsupp,
598         .pru_send = uipc_send,
599         .pru_sense = uipc_sense,
600         .pru_shutdown = uipc_shutdown,
601         .pru_sockaddr = uipc_sockaddr,
602         .pru_sosend = sosend,
603         .pru_soreceive = soreceive
604 };
605
606 void
607 uipc_ctloutput(netmsg_t msg)
608 {
609         struct socket *so;
610         struct sockopt *sopt;
611         struct unpcb *unp;
612         int error = 0;
613
614         lwkt_gettoken(&unp_token);
615         so = msg->base.nm_so;
616         sopt = msg->ctloutput.nm_sopt;
617         unp = so->so_pcb;
618
619         switch (sopt->sopt_dir) {
620         case SOPT_GET:
621                 switch (sopt->sopt_name) {
622                 case LOCAL_PEERCRED:
623                         if (unp->unp_flags & UNP_HAVEPC)
624                                 soopt_from_kbuf(sopt, &unp->unp_peercred,
625                                                 sizeof(unp->unp_peercred));
626                         else {
627                                 if (so->so_type == SOCK_STREAM)
628                                         error = ENOTCONN;
629                                 else if (so->so_type == SOCK_SEQPACKET)
630                                         error = ENOTCONN;
631                                 else
632                                         error = EINVAL;
633                         }
634                         break;
635                 default:
636                         error = EOPNOTSUPP;
637                         break;
638                 }
639                 break;
640         case SOPT_SET:
641         default:
642                 error = EOPNOTSUPP;
643                 break;
644         }
645         lwkt_reltoken(&unp_token);
646         lwkt_replymsg(&msg->lmsg, error);
647 }
648         
649 /*
650  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
651  * for stream sockets, although the total for sender and receiver is
652  * actually only PIPSIZ.
653  *
654  * Datagram sockets really use the sendspace as the maximum datagram size,
655  * and don't really want to reserve the sendspace.  Their recvspace should
656  * be large enough for at least one max-size datagram plus address.
657  *
658  * We want the local send/recv space to be significant larger then lo0's
659  * mtu of 16384.
660  */
661 #ifndef PIPSIZ
662 #define PIPSIZ  57344
663 #endif
664 static u_long   unpst_sendspace = PIPSIZ;
665 static u_long   unpst_recvspace = PIPSIZ;
666 static u_long   unpdg_sendspace = 2*1024;       /* really max datagram size */
667 static u_long   unpdg_recvspace = 4*1024;
668
669 static int      unp_rights;                     /* file descriptors in flight */
670 static struct spinlock unp_spin = SPINLOCK_INITIALIZER(&unp_spin);
671
672 SYSCTL_DECL(_net_local_seqpacket);
673 SYSCTL_DECL(_net_local_stream);
674 SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW, 
675            &unpst_sendspace, 0, "");
676 SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
677            &unpst_recvspace, 0, "");
678
679 SYSCTL_DECL(_net_local_dgram);
680 SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
681            &unpdg_sendspace, 0, "");
682 SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
683            &unpdg_recvspace, 0, "");
684
685 SYSCTL_DECL(_net_local);
686 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
687
688 static int
689 unp_attach(struct socket *so, struct pru_attach_info *ai)
690 {
691         struct unpcb *unp;
692         int error;
693
694         lwkt_gettoken(&unp_token);
695
696         if (so->so_snd.ssb_hiwat == 0 || so->so_rcv.ssb_hiwat == 0) {
697                 switch (so->so_type) {
698
699                 case SOCK_STREAM:
700                 case SOCK_SEQPACKET:
701                         error = soreserve(so, unpst_sendspace, unpst_recvspace,
702                                           ai->sb_rlimit);
703                         break;
704
705                 case SOCK_DGRAM:
706                         error = soreserve(so, unpdg_sendspace, unpdg_recvspace,
707                                           ai->sb_rlimit);
708                         break;
709
710                 default:
711                         panic("unp_attach");
712                 }
713                 if (error)
714                         goto failed;
715         }
716         unp = kmalloc(sizeof(*unp), M_UNPCB, M_NOWAIT|M_ZERO);
717         if (unp == NULL) {
718                 error = ENOBUFS;
719                 goto failed;
720         }
721         unp->unp_gencnt = ++unp_gencnt;
722         unp_count++;
723         LIST_INIT(&unp->unp_refs);
724         unp->unp_socket = so;
725         unp->unp_rvnode = ai->fd_rdir;          /* jail cruft XXX JH */
726         LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
727                          : &unp_shead, unp, unp_link);
728         so->so_pcb = (caddr_t)unp;
729         soreference(so);
730         error = 0;
731 failed:
732         lwkt_reltoken(&unp_token);
733         return error;
734 }
735
736 static void
737 unp_detach(struct unpcb *unp)
738 {
739         struct socket *so;
740
741         lwkt_gettoken(&unp_token);
742
743         LIST_REMOVE(unp, unp_link);
744         unp->unp_gencnt = ++unp_gencnt;
745         --unp_count;
746         if (unp->unp_vnode) {
747                 unp->unp_vnode->v_socket = NULL;
748                 vrele(unp->unp_vnode);
749                 unp->unp_vnode = NULL;
750         }
751         if (unp->unp_conn)
752                 unp_disconnect(unp);
753         while (!LIST_EMPTY(&unp->unp_refs))
754                 unp_drop(LIST_FIRST(&unp->unp_refs), ECONNRESET);
755         soisdisconnected(unp->unp_socket);
756         so = unp->unp_socket;
757         soreference(so);        /* for delayed sorflush */
758         so->so_pcb = NULL;
759         unp->unp_socket = NULL;
760         sofree(so);             /* remove pcb ref */
761
762         if (unp_rights) {
763                 /*
764                  * Normally the receive buffer is flushed later,
765                  * in sofree, but if our receive buffer holds references
766                  * to descriptors that are now garbage, we will dispose
767                  * of those descriptor references after the garbage collector
768                  * gets them (resulting in a "panic: closef: count < 0").
769                  */
770                 sorflush(so);
771                 unp_gc();
772         }
773         sofree(so);
774         lwkt_reltoken(&unp_token);
775
776         if (unp->unp_addr)
777                 kfree(unp->unp_addr, M_SONAME);
778         kfree(unp, M_UNPCB);
779 }
780
781 static int
782 unp_bind(struct unpcb *unp, struct sockaddr *nam, struct thread *td)
783 {
784         struct proc *p = td->td_proc;
785         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
786         struct vnode *vp;
787         struct vattr vattr;
788         int error, namelen;
789         struct nlookupdata nd;
790         char buf[SOCK_MAXADDRLEN];
791
792         lwkt_gettoken(&unp_token);
793         if (unp->unp_vnode != NULL) {
794                 error = EINVAL;
795                 goto failed;
796         }
797         namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
798         if (namelen <= 0) {
799                 error = EINVAL;
800                 goto failed;
801         }
802         strncpy(buf, soun->sun_path, namelen);
803         buf[namelen] = 0;       /* null-terminate the string */
804         error = nlookup_init(&nd, buf, UIO_SYSSPACE,
805                              NLC_LOCKVP | NLC_CREATE | NLC_REFDVP);
806         if (error == 0)
807                 error = nlookup(&nd);
808         if (error == 0 && nd.nl_nch.ncp->nc_vp != NULL)
809                 error = EADDRINUSE;
810         if (error)
811                 goto done;
812
813         VATTR_NULL(&vattr);
814         vattr.va_type = VSOCK;
815         vattr.va_mode = (ACCESSPERMS & ~p->p_fd->fd_cmask);
816         error = VOP_NCREATE(&nd.nl_nch, nd.nl_dvp, &vp, nd.nl_cred, &vattr);
817         if (error == 0) {
818                 vp->v_socket = unp->unp_socket;
819                 unp->unp_vnode = vp;
820                 unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam);
821                 vn_unlock(vp);
822         }
823 done:
824         nlookup_done(&nd);
825 failed:
826         lwkt_reltoken(&unp_token);
827         return (error);
828 }
829
830 static int
831 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
832 {
833         struct proc *p = td->td_proc;
834         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
835         struct vnode *vp;
836         struct socket *so2, *so3;
837         struct unpcb *unp, *unp2, *unp3;
838         int error, len;
839         struct nlookupdata nd;
840         char buf[SOCK_MAXADDRLEN];
841
842         lwkt_gettoken(&unp_token);
843
844         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
845         if (len <= 0) {
846                 error = EINVAL;
847                 goto failed;
848         }
849         strncpy(buf, soun->sun_path, len);
850         buf[len] = 0;
851
852         vp = NULL;
853         error = nlookup_init(&nd, buf, UIO_SYSSPACE, NLC_FOLLOW);
854         if (error == 0)
855                 error = nlookup(&nd);
856         if (error == 0)
857                 error = cache_vget(&nd.nl_nch, nd.nl_cred, LK_EXCLUSIVE, &vp);
858         nlookup_done(&nd);
859         if (error)
860                 goto failed;
861
862         if (vp->v_type != VSOCK) {
863                 error = ENOTSOCK;
864                 goto bad;
865         }
866         error = VOP_ACCESS(vp, VWRITE, p->p_ucred);
867         if (error)
868                 goto bad;
869         so2 = vp->v_socket;
870         if (so2 == NULL) {
871                 error = ECONNREFUSED;
872                 goto bad;
873         }
874         if (so->so_type != so2->so_type) {
875                 error = EPROTOTYPE;
876                 goto bad;
877         }
878         if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
879                 if (!(so2->so_options & SO_ACCEPTCONN) ||
880                     (so3 = sonewconn(so2, 0)) == NULL) {
881                         error = ECONNREFUSED;
882                         goto bad;
883                 }
884                 unp = so->so_pcb;
885                 unp2 = so2->so_pcb;
886                 unp3 = so3->so_pcb;
887                 if (unp2->unp_addr)
888                         unp3->unp_addr = (struct sockaddr_un *)
889                                 dup_sockaddr((struct sockaddr *)unp2->unp_addr);
890
891                 /*
892                  * unp_peercred management:
893                  *
894                  * The connecter's (client's) credentials are copied
895                  * from its process structure at the time of connect()
896                  * (which is now).
897                  */
898                 cru2x(p->p_ucred, &unp3->unp_peercred);
899                 unp3->unp_flags |= UNP_HAVEPC;
900                 /*
901                  * The receiver's (server's) credentials are copied
902                  * from the unp_peercred member of socket on which the
903                  * former called listen(); unp_listen() cached that
904                  * process's credentials at that time so we can use
905                  * them now.
906                  */
907                 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
908                     ("unp_connect: listener without cached peercred"));
909                 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
910                     sizeof(unp->unp_peercred));
911                 unp->unp_flags |= UNP_HAVEPC;
912
913                 so2 = so3;
914         }
915         error = unp_connect2(so, so2);
916 bad:
917         vput(vp);
918 failed:
919         lwkt_reltoken(&unp_token);
920         return (error);
921 }
922
923 int
924 unp_connect2(struct socket *so, struct socket *so2)
925 {
926         struct unpcb *unp;
927         struct unpcb *unp2;
928
929         lwkt_gettoken(&unp_token);
930         unp = so->so_pcb;
931         if (so2->so_type != so->so_type) {
932                 lwkt_reltoken(&unp_token);
933                 return (EPROTOTYPE);
934         }
935         unp2 = so2->so_pcb;
936         unp->unp_conn = unp2;
937
938         switch (so->so_type) {
939         case SOCK_DGRAM:
940                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
941                 soisconnected(so);
942                 break;
943
944         case SOCK_STREAM:
945         case SOCK_SEQPACKET:
946                 unp2->unp_conn = unp;
947                 soisconnected(so);
948                 soisconnected(so2);
949                 break;
950
951         default:
952                 panic("unp_connect2");
953         }
954         lwkt_reltoken(&unp_token);
955         return (0);
956 }
957
958 static void
959 unp_disconnect(struct unpcb *unp)
960 {
961         struct unpcb *unp2;
962
963         lwkt_gettoken(&unp_token);
964
965         unp2 = unp->unp_conn;
966         if (unp2 == NULL) {
967                 lwkt_reltoken(&unp_token);
968                 return;
969         }
970
971         unp->unp_conn = NULL;
972
973         switch (unp->unp_socket->so_type) {
974         case SOCK_DGRAM:
975                 LIST_REMOVE(unp, unp_reflink);
976                 soclrstate(unp->unp_socket, SS_ISCONNECTED);
977                 break;
978         case SOCK_STREAM:
979         case SOCK_SEQPACKET:
980                 soisdisconnected(unp->unp_socket);
981                 unp2->unp_conn = NULL;
982                 soisdisconnected(unp2->unp_socket);
983                 break;
984         }
985         lwkt_reltoken(&unp_token);
986 }
987
988 #ifdef notdef
989 void
990 unp_abort(struct unpcb *unp)
991 {
992         lwkt_gettoken(&unp_token);
993         unp_detach(unp);
994         lwkt_reltoken(&unp_token);
995 }
996 #endif
997
998 static int
999 prison_unpcb(struct thread *td, struct unpcb *unp)
1000 {
1001         struct proc *p;
1002
1003         if (td == NULL)
1004                 return (0);
1005         if ((p = td->td_proc) == NULL)
1006                 return (0);
1007         if (!p->p_ucred->cr_prison)
1008                 return (0);
1009         if (p->p_fd->fd_rdir == unp->unp_rvnode)
1010                 return (0);
1011         return (1);
1012 }
1013
1014 static int
1015 unp_pcblist(SYSCTL_HANDLER_ARGS)
1016 {
1017         int error, i, n;
1018         struct unpcb *unp, **unp_list;
1019         unp_gen_t gencnt;
1020         struct unp_head *head;
1021
1022         head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1023
1024         KKASSERT(curproc != NULL);
1025
1026         /*
1027          * The process of preparing the PCB list is too time-consuming and
1028          * resource-intensive to repeat twice on every request.
1029          */
1030         if (req->oldptr == NULL) {
1031                 n = unp_count;
1032                 req->oldidx = (n + n/8) * sizeof(struct xunpcb);
1033                 return 0;
1034         }
1035
1036         if (req->newptr != NULL)
1037                 return EPERM;
1038
1039         lwkt_gettoken(&unp_token);
1040
1041         /*
1042          * OK, now we're committed to doing something.
1043          */
1044         gencnt = unp_gencnt;
1045         n = unp_count;
1046
1047         unp_list = kmalloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1048         
1049         for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1050              unp = LIST_NEXT(unp, unp_link)) {
1051                 if (unp->unp_gencnt <= gencnt && !prison_unpcb(req->td, unp))
1052                         unp_list[i++] = unp;
1053         }
1054         n = i;                  /* in case we lost some during malloc */
1055
1056         error = 0;
1057         for (i = 0; i < n; i++) {
1058                 unp = unp_list[i];
1059                 if (unp->unp_gencnt <= gencnt) {
1060                         struct xunpcb xu;
1061                         xu.xu_len = sizeof xu;
1062                         xu.xu_unpp = unp;
1063                         /*
1064                          * XXX - need more locking here to protect against
1065                          * connect/disconnect races for SMP.
1066                          */
1067                         if (unp->unp_addr)
1068                                 bcopy(unp->unp_addr, &xu.xu_addr, 
1069                                       unp->unp_addr->sun_len);
1070                         if (unp->unp_conn && unp->unp_conn->unp_addr)
1071                                 bcopy(unp->unp_conn->unp_addr,
1072                                       &xu.xu_caddr,
1073                                       unp->unp_conn->unp_addr->sun_len);
1074                         bcopy(unp, &xu.xu_unp, sizeof *unp);
1075                         sotoxsocket(unp->unp_socket, &xu.xu_socket);
1076                         error = SYSCTL_OUT(req, &xu, sizeof xu);
1077                 }
1078         }
1079         lwkt_reltoken(&unp_token);
1080         kfree(unp_list, M_TEMP);
1081
1082         return error;
1083 }
1084
1085 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD, 
1086             (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1087             "List of active local datagram sockets");
1088 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD, 
1089             (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1090             "List of active local stream sockets");
1091 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist, CTLFLAG_RD, 
1092             (caddr_t)(long)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1093             "List of active local seqpacket stream sockets");
1094
1095 static void
1096 unp_shutdown(struct unpcb *unp)
1097 {
1098         struct socket *so;
1099
1100         if ((unp->unp_socket->so_type == SOCK_STREAM ||
1101              unp->unp_socket->so_type == SOCK_SEQPACKET) &&
1102             unp->unp_conn != NULL && (so = unp->unp_conn->unp_socket)) {
1103                 socantrcvmore(so);
1104         }
1105 }
1106
1107 static void
1108 unp_drop(struct unpcb *unp, int err)
1109 {
1110         struct socket *so = unp->unp_socket;
1111
1112         so->so_error = err;
1113         unp_disconnect(unp);
1114 }
1115
1116 #ifdef notdef
1117 void
1118 unp_drain(void)
1119 {
1120         lwkt_gettoken(&unp_token);
1121         lwkt_reltoken(&unp_token);
1122 }
1123 #endif
1124
1125 int
1126 unp_externalize(struct mbuf *rights)
1127 {
1128         struct thread *td = curthread;
1129         struct proc *p = td->td_proc;           /* XXX */
1130         struct lwp *lp = td->td_lwp;
1131         struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
1132         int *fdp;
1133         int i;
1134         struct file **rp;
1135         struct file *fp;
1136         int newfds = (cm->cmsg_len - (CMSG_DATA(cm) - (u_char *)cm))
1137                 / sizeof (struct file *);
1138         int f;
1139
1140         lwkt_gettoken(&unp_token);
1141
1142         /*
1143          * if the new FD's will not fit, then we free them all
1144          */
1145         if (!fdavail(p, newfds)) {
1146                 rp = (struct file **)CMSG_DATA(cm);
1147                 for (i = 0; i < newfds; i++) {
1148                         fp = *rp;
1149                         /*
1150                          * zero the pointer before calling unp_discard,
1151                          * since it may end up in unp_gc()..
1152                          */
1153                         *rp++ = 0;
1154                         unp_discard(fp, NULL);
1155                 }
1156                 lwkt_reltoken(&unp_token);
1157                 return (EMSGSIZE);
1158         }
1159
1160         /*
1161          * now change each pointer to an fd in the global table to 
1162          * an integer that is the index to the local fd table entry
1163          * that we set up to point to the global one we are transferring.
1164          * If sizeof (struct file *) is bigger than or equal to sizeof int,
1165          * then do it in forward order. In that case, an integer will
1166          * always come in the same place or before its corresponding
1167          * struct file pointer.
1168          * If sizeof (struct file *) is smaller than sizeof int, then
1169          * do it in reverse order.
1170          */
1171         if (sizeof (struct file *) >= sizeof (int)) {
1172                 fdp = (int *)CMSG_DATA(cm);
1173                 rp = (struct file **)CMSG_DATA(cm);
1174                 for (i = 0; i < newfds; i++) {
1175                         if (fdalloc(p, 0, &f))
1176                                 panic("unp_externalize");
1177                         fp = *rp++;
1178                         unp_fp_externalize(lp, fp, f);
1179                         *fdp++ = f;
1180                 }
1181         } else {
1182                 fdp = (int *)CMSG_DATA(cm) + newfds - 1;
1183                 rp = (struct file **)CMSG_DATA(cm) + newfds - 1;
1184                 for (i = 0; i < newfds; i++) {
1185                         if (fdalloc(p, 0, &f))
1186                                 panic("unp_externalize");
1187                         fp = *rp--;
1188                         unp_fp_externalize(lp, fp, f);
1189                         *fdp-- = f;
1190                 }
1191         }
1192
1193         /*
1194          * Adjust length, in case sizeof(struct file *) and sizeof(int)
1195          * differs.
1196          */
1197         cm->cmsg_len = CMSG_LEN(newfds * sizeof(int));
1198         rights->m_len = cm->cmsg_len;
1199
1200         lwkt_reltoken(&unp_token);
1201         return (0);
1202 }
1203
1204 static void
1205 unp_fp_externalize(struct lwp *lp, struct file *fp, int fd)
1206 {
1207         struct file *fx;
1208         int error;
1209
1210         lwkt_gettoken(&unp_token);
1211
1212         if (lp) {
1213                 KKASSERT(fd >= 0);
1214                 if (fp->f_flag & FREVOKED) {
1215                         kprintf("Warning: revoked fp exiting unix socket\n");
1216                         fx = NULL;
1217                         error = falloc(lp, &fx, NULL);
1218                         if (error == 0)
1219                                 fsetfd(lp->lwp_proc->p_fd, fx, fd);
1220                         else
1221                                 fsetfd(lp->lwp_proc->p_fd, NULL, fd);
1222                         fdrop(fx);
1223                 } else {
1224                         fsetfd(lp->lwp_proc->p_fd, fp, fd);
1225                 }
1226         }
1227         spin_lock(&unp_spin);
1228         fp->f_msgcount--;
1229         unp_rights--;
1230         spin_unlock(&unp_spin);
1231         fdrop(fp);
1232
1233         lwkt_reltoken(&unp_token);
1234 }
1235
1236
1237 void
1238 unp_init(void)
1239 {
1240         LIST_INIT(&unp_dhead);
1241         LIST_INIT(&unp_shead);
1242         spin_init(&unp_spin);
1243 }
1244
1245 static int
1246 unp_internalize(struct mbuf *control, struct thread *td)
1247 {
1248         struct proc *p = td->td_proc;
1249         struct filedesc *fdescp;
1250         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1251         struct file **rp;
1252         struct file *fp;
1253         int i, fd, *fdp;
1254         struct cmsgcred *cmcred;
1255         int oldfds;
1256         u_int newlen;
1257         int error;
1258
1259         KKASSERT(p);
1260         lwkt_gettoken(&unp_token);
1261
1262         fdescp = p->p_fd;
1263         if ((cm->cmsg_type != SCM_RIGHTS && cm->cmsg_type != SCM_CREDS) ||
1264             cm->cmsg_level != SOL_SOCKET ||
1265             CMSG_ALIGN(cm->cmsg_len) != control->m_len) {
1266                 error = EINVAL;
1267                 goto done;
1268         }
1269
1270         /*
1271          * Fill in credential information.
1272          */
1273         if (cm->cmsg_type == SCM_CREDS) {
1274                 cmcred = (struct cmsgcred *)CMSG_DATA(cm);
1275                 cmcred->cmcred_pid = p->p_pid;
1276                 cmcred->cmcred_uid = p->p_ucred->cr_ruid;
1277                 cmcred->cmcred_gid = p->p_ucred->cr_rgid;
1278                 cmcred->cmcred_euid = p->p_ucred->cr_uid;
1279                 cmcred->cmcred_ngroups = MIN(p->p_ucred->cr_ngroups,
1280                                                         CMGROUP_MAX);
1281                 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1282                         cmcred->cmcred_groups[i] = p->p_ucred->cr_groups[i];
1283                 error = 0;
1284                 goto done;
1285         }
1286
1287         /*
1288          * cmsghdr may not be aligned, do not allow calculation(s) to
1289          * go negative.
1290          */
1291         if (cm->cmsg_len < CMSG_LEN(0)) {
1292                 error = EINVAL;
1293                 goto done;
1294         }
1295
1296         oldfds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof (int);
1297
1298         /*
1299          * check that all the FDs passed in refer to legal OPEN files
1300          * If not, reject the entire operation.
1301          */
1302         fdp = (int *)CMSG_DATA(cm);
1303         for (i = 0; i < oldfds; i++) {
1304                 fd = *fdp++;
1305                 if ((unsigned)fd >= fdescp->fd_nfiles ||
1306                     fdescp->fd_files[fd].fp == NULL) {
1307                         error = EBADF;
1308                         goto done;
1309                 }
1310                 if (fdescp->fd_files[fd].fp->f_type == DTYPE_KQUEUE) {
1311                         error = EOPNOTSUPP;
1312                         goto done;
1313                 }
1314         }
1315         /*
1316          * Now replace the integer FDs with pointers to
1317          * the associated global file table entry..
1318          * Allocate a bigger buffer as necessary. But if an cluster is not
1319          * enough, return E2BIG.
1320          */
1321         newlen = CMSG_LEN(oldfds * sizeof(struct file *));
1322         if (newlen > MCLBYTES) {
1323                 error = E2BIG;
1324                 goto done;
1325         }
1326         if (newlen - control->m_len > M_TRAILINGSPACE(control)) {
1327                 if (control->m_flags & M_EXT) {
1328                         error = E2BIG;
1329                         goto done;
1330                 }
1331                 MCLGET(control, MB_WAIT);
1332                 if (!(control->m_flags & M_EXT)) {
1333                         error = ENOBUFS;
1334                         goto done;
1335                 }
1336
1337                 /* copy the data to the cluster */
1338                 memcpy(mtod(control, char *), cm, cm->cmsg_len);
1339                 cm = mtod(control, struct cmsghdr *);
1340         }
1341
1342         /*
1343          * Adjust length, in case sizeof(struct file *) and sizeof(int)
1344          * differs.
1345          */
1346         cm->cmsg_len = newlen;
1347         control->m_len = CMSG_ALIGN(newlen);
1348
1349         /*
1350          * Transform the file descriptors into struct file pointers.
1351          * If sizeof (struct file *) is bigger than or equal to sizeof int,
1352          * then do it in reverse order so that the int won't get until
1353          * we're done.
1354          * If sizeof (struct file *) is smaller than sizeof int, then
1355          * do it in forward order.
1356          */
1357         if (sizeof (struct file *) >= sizeof (int)) {
1358                 fdp = (int *)CMSG_DATA(cm) + oldfds - 1;
1359                 rp = (struct file **)CMSG_DATA(cm) + oldfds - 1;
1360                 for (i = 0; i < oldfds; i++) {
1361                         fp = fdescp->fd_files[*fdp--].fp;
1362                         *rp-- = fp;
1363                         fhold(fp);
1364                         spin_lock(&unp_spin);
1365                         fp->f_msgcount++;
1366                         unp_rights++;
1367                         spin_unlock(&unp_spin);
1368                 }
1369         } else {
1370                 fdp = (int *)CMSG_DATA(cm);
1371                 rp = (struct file **)CMSG_DATA(cm);
1372                 for (i = 0; i < oldfds; i++) {
1373                         fp = fdescp->fd_files[*fdp++].fp;
1374                         *rp++ = fp;
1375                         fhold(fp);
1376                         spin_lock(&unp_spin);
1377                         fp->f_msgcount++;
1378                         unp_rights++;
1379                         spin_unlock(&unp_spin);
1380                 }
1381         }
1382         error = 0;
1383 done:
1384         lwkt_reltoken(&unp_token);
1385         return error;
1386 }
1387
1388 /*
1389  * Garbage collect in-transit file descriptors that get lost due to
1390  * loops (i.e. when a socket is sent to another process over itself,
1391  * and more complex situations).
1392  *
1393  * NOT MPSAFE - TODO socket flush code and maybe closef.  Rest is MPSAFE.
1394  */
1395
1396 struct unp_gc_info {
1397         struct file **extra_ref;
1398         struct file *locked_fp;
1399         int defer;
1400         int index;
1401         int maxindex;
1402 };
1403
1404 static void
1405 unp_gc(void)
1406 {
1407         struct unp_gc_info info;
1408         static boolean_t unp_gcing;
1409         struct file **fpp;
1410         int i;
1411
1412         spin_lock(&unp_spin);
1413         if (unp_gcing) {
1414                 spin_unlock(&unp_spin);
1415                 return;
1416         }
1417         unp_gcing = TRUE;
1418         spin_unlock(&unp_spin);
1419
1420         lwkt_gettoken(&unp_token);
1421
1422         /* 
1423          * before going through all this, set all FDs to 
1424          * be NOT defered and NOT externally accessible
1425          */
1426         info.defer = 0;
1427         allfiles_scan_exclusive(unp_gc_clearmarks, NULL);
1428         do {
1429                 allfiles_scan_exclusive(unp_gc_checkmarks, &info);
1430         } while (info.defer);
1431
1432         /*
1433          * We grab an extra reference to each of the file table entries
1434          * that are not otherwise accessible and then free the rights
1435          * that are stored in messages on them.
1436          *
1437          * The bug in the orginal code is a little tricky, so I'll describe
1438          * what's wrong with it here.
1439          *
1440          * It is incorrect to simply unp_discard each entry for f_msgcount
1441          * times -- consider the case of sockets A and B that contain
1442          * references to each other.  On a last close of some other socket,
1443          * we trigger a gc since the number of outstanding rights (unp_rights)
1444          * is non-zero.  If during the sweep phase the gc code un_discards,
1445          * we end up doing a (full) closef on the descriptor.  A closef on A
1446          * results in the following chain.  Closef calls soo_close, which
1447          * calls soclose.   Soclose calls first (through the switch
1448          * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
1449          * returns because the previous instance had set unp_gcing, and
1450          * we return all the way back to soclose, which marks the socket
1451          * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
1452          * to free up the rights that are queued in messages on the socket A,
1453          * i.e., the reference on B.  The sorflush calls via the dom_dispose
1454          * switch unp_dispose, which unp_scans with unp_discard.  This second
1455          * instance of unp_discard just calls closef on B.
1456          *
1457          * Well, a similar chain occurs on B, resulting in a sorflush on B,
1458          * which results in another closef on A.  Unfortunately, A is already
1459          * being closed, and the descriptor has already been marked with
1460          * SS_NOFDREF, and soclose panics at this point.
1461          *
1462          * Here, we first take an extra reference to each inaccessible
1463          * descriptor.  Then, we call sorflush ourself, since we know
1464          * it is a Unix domain socket anyhow.  After we destroy all the
1465          * rights carried in messages, we do a last closef to get rid
1466          * of our extra reference.  This is the last close, and the
1467          * unp_detach etc will shut down the socket.
1468          *
1469          * 91/09/19, bsy@cs.cmu.edu
1470          */
1471         info.extra_ref = kmalloc(256 * sizeof(struct file *), M_FILE, M_WAITOK);
1472         info.maxindex = 256;
1473
1474         do {
1475                 /*
1476                  * Look for matches
1477                  */
1478                 info.index = 0;
1479                 allfiles_scan_exclusive(unp_gc_checkrefs, &info);
1480
1481                 /* 
1482                  * For each FD on our hit list, do the following two things
1483                  */
1484                 for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp) {
1485                         struct file *tfp = *fpp;
1486                         if (tfp->f_type == DTYPE_SOCKET && tfp->f_data != NULL)
1487                                 sorflush((struct socket *)(tfp->f_data));
1488                 }
1489                 for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp)
1490                         closef(*fpp, NULL);
1491         } while (info.index == info.maxindex);
1492
1493         lwkt_reltoken(&unp_token);
1494
1495         kfree((caddr_t)info.extra_ref, M_FILE);
1496         unp_gcing = FALSE;
1497 }
1498
1499 /*
1500  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1501  */
1502 static int
1503 unp_gc_checkrefs(struct file *fp, void *data)
1504 {
1505         struct unp_gc_info *info = data;
1506
1507         if (fp->f_count == 0)
1508                 return(0);
1509         if (info->index == info->maxindex)
1510                 return(-1);
1511
1512         /* 
1513          * If all refs are from msgs, and it's not marked accessible
1514          * then it must be referenced from some unreachable cycle
1515          * of (shut-down) FDs, so include it in our
1516          * list of FDs to remove
1517          */
1518         if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1519                 info->extra_ref[info->index++] = fp;
1520                 fhold(fp);
1521         }
1522         return(0);
1523 }
1524
1525 /*
1526  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1527  */
1528 static int
1529 unp_gc_clearmarks(struct file *fp, void *data __unused)
1530 {
1531         atomic_clear_int(&fp->f_flag, FMARK | FDEFER);
1532         return(0);
1533 }
1534
1535 /*
1536  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1537  */
1538 static int
1539 unp_gc_checkmarks(struct file *fp, void *data)
1540 {
1541         struct unp_gc_info *info = data;
1542         struct socket *so;
1543
1544         /*
1545          * If the file is not open, skip it
1546          */
1547         if (fp->f_count == 0)
1548                 return(0);
1549         /*
1550          * If we already marked it as 'defer'  in a
1551          * previous pass, then try process it this time
1552          * and un-mark it
1553          */
1554         if (fp->f_flag & FDEFER) {
1555                 atomic_clear_int(&fp->f_flag, FDEFER);
1556                 --info->defer;
1557         } else {
1558                 /*
1559                  * if it's not defered, then check if it's
1560                  * already marked.. if so skip it
1561                  */
1562                 if (fp->f_flag & FMARK)
1563                         return(0);
1564                 /* 
1565                  * If all references are from messages
1566                  * in transit, then skip it. it's not 
1567                  * externally accessible.
1568                  */ 
1569                 if (fp->f_count == fp->f_msgcount)
1570                         return(0);
1571                 /* 
1572                  * If it got this far then it must be
1573                  * externally accessible.
1574                  */
1575                 atomic_set_int(&fp->f_flag, FMARK);
1576         }
1577
1578         /*
1579          * either it was defered, or it is externally 
1580          * accessible and not already marked so.
1581          * Now check if it is possibly one of OUR sockets.
1582          */ 
1583         if (fp->f_type != DTYPE_SOCKET ||
1584             (so = (struct socket *)fp->f_data) == NULL)
1585                 return(0);
1586         if (so->so_proto->pr_domain != &localdomain ||
1587             !(so->so_proto->pr_flags & PR_RIGHTS))
1588                 return(0);
1589 #ifdef notdef
1590         if (so->so_rcv.ssb_flags & SSB_LOCK) {
1591                 /*
1592                  * This is problematical; it's not clear
1593                  * we need to wait for the sockbuf to be
1594                  * unlocked (on a uniprocessor, at least),
1595                  * and it's also not clear what to do
1596                  * if sbwait returns an error due to receipt
1597                  * of a signal.  If sbwait does return
1598                  * an error, we'll go into an infinite
1599                  * loop.  Delete all of this for now.
1600                  */
1601                 sbwait(&so->so_rcv);
1602                 goto restart;
1603         }
1604 #endif
1605         /*
1606          * So, Ok, it's one of our sockets and it IS externally
1607          * accessible (or was defered). Now we look
1608          * to see if we hold any file descriptors in its
1609          * message buffers. Follow those links and mark them 
1610          * as accessible too.
1611          */
1612         info->locked_fp = fp;
1613 /*      spin_lock_wr(&so->so_rcv.sb_spin); */
1614         unp_scan(so->so_rcv.ssb_mb, unp_mark, info);
1615 /*      spin_unlock_wr(&so->so_rcv.sb_spin);*/
1616         return (0);
1617 }
1618
1619 /*
1620  * Scan all unix domain sockets and replace any revoked file pointers
1621  * found with the dummy file pointer fx.  We don't worry about races
1622  * against file pointers being read out as those are handled in the
1623  * externalize code.
1624  */
1625
1626 #define REVOKE_GC_MAXFILES      32
1627
1628 struct unp_revoke_gc_info {
1629         struct file     *fx;
1630         struct file     *fary[REVOKE_GC_MAXFILES];
1631         int             fcount;
1632 };
1633
1634 void
1635 unp_revoke_gc(struct file *fx)
1636 {
1637         struct unp_revoke_gc_info info;
1638         int i;
1639
1640         lwkt_gettoken(&unp_token);
1641         info.fx = fx;
1642         do {
1643                 info.fcount = 0;
1644                 allfiles_scan_exclusive(unp_revoke_gc_check, &info);
1645                 for (i = 0; i < info.fcount; ++i)
1646                         unp_fp_externalize(NULL, info.fary[i], -1);
1647         } while (info.fcount == REVOKE_GC_MAXFILES);
1648         lwkt_reltoken(&unp_token);
1649 }
1650
1651 /*
1652  * Check for and replace revoked descriptors.
1653  *
1654  * WARNING:  This routine is not allowed to block.
1655  */
1656 static int
1657 unp_revoke_gc_check(struct file *fps, void *vinfo)
1658 {
1659         struct unp_revoke_gc_info *info = vinfo;
1660         struct file *fp;
1661         struct socket *so;
1662         struct mbuf *m0;
1663         struct mbuf *m;
1664         struct file **rp;
1665         struct cmsghdr *cm;
1666         int i;
1667         int qfds;
1668
1669         /*
1670          * Is this a unix domain socket with rights-passing abilities?
1671          */
1672         if (fps->f_type != DTYPE_SOCKET)
1673                 return (0);
1674         if ((so = (struct socket *)fps->f_data) == NULL)
1675                 return(0);
1676         if (so->so_proto->pr_domain != &localdomain)
1677                 return(0);
1678         if ((so->so_proto->pr_flags & PR_RIGHTS) == 0)
1679                 return(0);
1680
1681         /*
1682          * Scan the mbufs for control messages and replace any revoked
1683          * descriptors we find.
1684          */
1685         m0 = so->so_rcv.ssb_mb;
1686         while (m0) {
1687                 for (m = m0; m; m = m->m_next) {
1688                         if (m->m_type != MT_CONTROL)
1689                                 continue;
1690                         if (m->m_len < sizeof(*cm))
1691                                 continue;
1692                         cm = mtod(m, struct cmsghdr *);
1693                         if (cm->cmsg_level != SOL_SOCKET ||
1694                             cm->cmsg_type != SCM_RIGHTS) {
1695                                 continue;
1696                         }
1697                         qfds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(void *);
1698                         rp = (struct file **)CMSG_DATA(cm);
1699                         for (i = 0; i < qfds; i++) {
1700                                 fp = rp[i];
1701                                 if (fp->f_flag & FREVOKED) {
1702                                         kprintf("Warning: Removing revoked fp from unix domain socket queue\n");
1703                                         fhold(info->fx);
1704                                         info->fx->f_msgcount++;
1705                                         unp_rights++;
1706                                         rp[i] = info->fx;
1707                                         info->fary[info->fcount++] = fp;
1708                                 }
1709                                 if (info->fcount == REVOKE_GC_MAXFILES)
1710                                         break;
1711                         }
1712                         if (info->fcount == REVOKE_GC_MAXFILES)
1713                                 break;
1714                 }
1715                 m0 = m0->m_nextpkt;
1716                 if (info->fcount == REVOKE_GC_MAXFILES)
1717                         break;
1718         }
1719
1720         /*
1721          * Stop the scan if we filled up our array.
1722          */
1723         if (info->fcount == REVOKE_GC_MAXFILES)
1724                 return(-1);
1725         return(0);
1726 }
1727
1728 void
1729 unp_dispose(struct mbuf *m)
1730 {
1731         lwkt_gettoken(&unp_token);
1732         if (m)
1733                 unp_scan(m, unp_discard, NULL);
1734         lwkt_reltoken(&unp_token);
1735 }
1736
1737 static int
1738 unp_listen(struct unpcb *unp, struct thread *td)
1739 {
1740         struct proc *p = td->td_proc;
1741
1742         KKASSERT(p);
1743         lwkt_gettoken(&unp_token);
1744         cru2x(p->p_ucred, &unp->unp_peercred);
1745         unp->unp_flags |= UNP_HAVEPCCACHED;
1746         lwkt_reltoken(&unp_token);
1747         return (0);
1748 }
1749
1750 static void
1751 unp_scan(struct mbuf *m0, void (*op)(struct file *, void *), void *data)
1752 {
1753         struct mbuf *m;
1754         struct file **rp;
1755         struct cmsghdr *cm;
1756         int i;
1757         int qfds;
1758
1759         while (m0) {
1760                 for (m = m0; m; m = m->m_next) {
1761                         if (m->m_type == MT_CONTROL &&
1762                             m->m_len >= sizeof(*cm)) {
1763                                 cm = mtod(m, struct cmsghdr *);
1764                                 if (cm->cmsg_level != SOL_SOCKET ||
1765                                     cm->cmsg_type != SCM_RIGHTS)
1766                                         continue;
1767                                 qfds = (cm->cmsg_len - CMSG_LEN(0)) /
1768                                         sizeof(void *);
1769                                 rp = (struct file **)CMSG_DATA(cm);
1770                                 for (i = 0; i < qfds; i++)
1771                                         (*op)(*rp++, data);
1772                                 break;          /* XXX, but saves time */
1773                         }
1774                 }
1775                 m0 = m0->m_nextpkt;
1776         }
1777 }
1778
1779 static void
1780 unp_mark(struct file *fp, void *data)
1781 {
1782         struct unp_gc_info *info = data;
1783
1784         if ((fp->f_flag & FMARK) == 0) {
1785                 ++info->defer;
1786                 atomic_set_int(&fp->f_flag, FMARK | FDEFER);
1787         }
1788 }
1789
1790 static void
1791 unp_discard(struct file *fp, void *data __unused)
1792 {
1793         spin_lock(&unp_spin);
1794         fp->f_msgcount--;
1795         unp_rights--;
1796         spin_unlock(&unp_spin);
1797         closef(fp, NULL);
1798 }
1799