The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/uipc_usrreq.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*      $NetBSD: uipc_usrreq.c,v 1.80.2.6 2009/04/14 09:02:25 jdc Exp $ */
    2 
    3 /*-
    4  * Copyright (c) 1998, 2000, 2004 The NetBSD Foundation, Inc.
    5  * All rights reserved.
    6  *
    7  * This code is derived from software contributed to The NetBSD Foundation
    8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
    9  * NASA Ames Research Center.
   10  *
   11  * Redistribution and use in source and binary forms, with or without
   12  * modification, are permitted provided that the following conditions
   13  * are met:
   14  * 1. Redistributions of source code must retain the above copyright
   15  *    notice, this list of conditions and the following disclaimer.
   16  * 2. Redistributions in binary form must reproduce the above copyright
   17  *    notice, this list of conditions and the following disclaimer in the
   18  *    documentation and/or other materials provided with the distribution.
   19  * 3. All advertising materials mentioning features or use of this software
   20  *    must display the following acknowledgement:
   21  *      This product includes software developed by the NetBSD
   22  *      Foundation, Inc. and its contributors.
   23  * 4. Neither the name of The NetBSD Foundation nor the names of its
   24  *    contributors may be used to endorse or promote products derived
   25  *    from this software without specific prior written permission.
   26  *
   27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
   28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
   31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   37  * POSSIBILITY OF SUCH DAMAGE.
   38  */
   39 
   40 /*
   41  * Copyright (c) 1982, 1986, 1989, 1991, 1993
   42  *      The Regents of the University of California.  All rights reserved.
   43  *
   44  * Redistribution and use in source and binary forms, with or without
   45  * modification, are permitted provided that the following conditions
   46  * are met:
   47  * 1. Redistributions of source code must retain the above copyright
   48  *    notice, this list of conditions and the following disclaimer.
   49  * 2. Redistributions in binary form must reproduce the above copyright
   50  *    notice, this list of conditions and the following disclaimer in the
   51  *    documentation and/or other materials provided with the distribution.
   52  * 3. Neither the name of the University nor the names of its contributors
   53  *    may be used to endorse or promote products derived from this software
   54  *    without specific prior written permission.
   55  *
   56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   66  * SUCH DAMAGE.
   67  *
   68  *      @(#)uipc_usrreq.c       8.9 (Berkeley) 5/14/95
   69  */
   70 
   71 /*
   72  * Copyright (c) 1997 Christopher G. Demetriou.  All rights reserved.
   73  *
   74  * Redistribution and use in source and binary forms, with or without
   75  * modification, are permitted provided that the following conditions
   76  * are met:
   77  * 1. Redistributions of source code must retain the above copyright
   78  *    notice, this list of conditions and the following disclaimer.
   79  * 2. Redistributions in binary form must reproduce the above copyright
   80  *    notice, this list of conditions and the following disclaimer in the
   81  *    documentation and/or other materials provided with the distribution.
   82  * 3. All advertising materials mentioning features or use of this software
   83  *    must display the following acknowledgement:
   84  *      This product includes software developed by the University of
   85  *      California, Berkeley and its contributors.
   86  * 4. Neither the name of the University nor the names of its contributors
   87  *    may be used to endorse or promote products derived from this software
   88  *    without specific prior written permission.
   89  *
   90  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   91  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   92  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   93  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   94  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   95  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   96  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   97  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   98  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   99  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  100  * SUCH DAMAGE.
  101  *
  102  *      @(#)uipc_usrreq.c       8.9 (Berkeley) 5/14/95
  103  */
  104 
  105 #include <sys/cdefs.h>
  106 __KERNEL_RCSID(0, "$NetBSD: uipc_usrreq.c,v 1.80.2.6 2009/04/14 09:02:25 jdc Exp $");
  107 
  108 #include <sys/param.h>
  109 #include <sys/systm.h>
  110 #include <sys/proc.h>
  111 #include <sys/filedesc.h>
  112 #include <sys/domain.h>
  113 #include <sys/protosw.h>
  114 #include <sys/socket.h>
  115 #include <sys/socketvar.h>
  116 #include <sys/unpcb.h>
  117 #include <sys/un.h>
  118 #include <sys/namei.h>
  119 #include <sys/vnode.h>
  120 #include <sys/file.h>
  121 #include <sys/stat.h>
  122 #include <sys/mbuf.h>
  123 
  124 /*
  125  * Unix communications domain.
  126  *
  127  * TODO:
  128  *      SEQPACKET, RDM
  129  *      rethink name space problems
  130  *      need a proper out-of-band
  131  */
  132 const struct    sockaddr_un sun_noname = { sizeof(sun_noname), AF_LOCAL };
  133 ino_t   unp_ino;                        /* prototype for fake inode numbers */
  134 
  135 struct mbuf *unp_addsockcred(struct proc *, struct mbuf *);
  136 
  137 int
  138 unp_output(struct mbuf *m, struct mbuf *control, struct unpcb *unp,
  139         struct proc *p)
  140 {
  141         struct socket *so2;
  142         const struct sockaddr_un *sun;
  143 
  144         so2 = unp->unp_conn->unp_socket;
  145         if (unp->unp_addr)
  146                 sun = unp->unp_addr;
  147         else
  148                 sun = &sun_noname;
  149         if (unp->unp_conn->unp_flags & UNP_WANTCRED)
  150                 control = unp_addsockcred(p, control);
  151         if (sbappendaddr(&so2->so_rcv, (struct sockaddr *)sun, m,
  152             control) == 0) {
  153                 unp_dispose(control);
  154                 m_freem(control);
  155                 m_freem(m);
  156                 so2->so_rcv.sb_overflowed++;
  157                 return (ENOBUFS);
  158         } else {
  159                 sorwakeup(so2);
  160                 return (0);
  161         }
  162 }
  163 
  164 void
  165 unp_setsockaddr(struct unpcb *unp, struct mbuf *nam)
  166 {
  167         const struct sockaddr_un *sun;
  168 
  169         if (unp->unp_addr)
  170                 sun = unp->unp_addr;
  171         else
  172                 sun = &sun_noname;
  173         nam->m_len = sun->sun_len;
  174         if (nam->m_len > MLEN)
  175                 MEXTMALLOC(nam, nam->m_len, M_WAITOK);
  176         memcpy(mtod(nam, caddr_t), sun, (size_t)nam->m_len);
  177 }
  178 
  179 void
  180 unp_setpeeraddr(struct unpcb *unp, struct mbuf *nam)
  181 {
  182         const struct sockaddr_un *sun;
  183 
  184         if (unp->unp_conn && unp->unp_conn->unp_addr)
  185                 sun = unp->unp_conn->unp_addr;
  186         else
  187                 sun = &sun_noname;
  188         nam->m_len = sun->sun_len;
  189         if (nam->m_len > MLEN)
  190                 MEXTMALLOC(nam, nam->m_len, M_WAITOK);
  191         memcpy(mtod(nam, caddr_t), sun, (size_t)nam->m_len);
  192 }
  193 
  194 /*ARGSUSED*/
  195 int
  196 uipc_usrreq(struct socket *so, int req, struct mbuf *m, struct mbuf *nam,
  197         struct mbuf *control, struct proc *p)
  198 {
  199         struct unpcb *unp = sotounpcb(so);
  200         struct socket *so2;
  201         u_int newhiwat;
  202         int error = 0;
  203 
  204         if (req == PRU_CONTROL)
  205                 return (EOPNOTSUPP);
  206 
  207 #ifdef DIAGNOSTIC
  208         if (req != PRU_SEND && req != PRU_SENDOOB && control)
  209                 panic("uipc_usrreq: unexpected control mbuf");
  210 #endif
  211         if (unp == 0 && req != PRU_ATTACH) {
  212                 error = EINVAL;
  213                 goto release;
  214         }
  215 
  216         switch (req) {
  217 
  218         case PRU_ATTACH:
  219                 if (unp != 0) {
  220                         error = EISCONN;
  221                         break;
  222                 }
  223                 error = unp_attach(so);
  224                 break;
  225 
  226         case PRU_DETACH:
  227                 unp_detach(unp);
  228                 break;
  229 
  230         case PRU_BIND:
  231                 error = unp_bind(unp, nam, p);
  232                 break;
  233 
  234         case PRU_LISTEN:
  235                 if (unp->unp_vnode == 0)
  236                         error = EINVAL;
  237                 break;
  238 
  239         case PRU_CONNECT:
  240                 error = unp_connect(so, nam, p);
  241                 break;
  242 
  243         case PRU_CONNECT2:
  244                 error = unp_connect2(so, (struct socket *)nam, PRU_CONNECT2);
  245                 break;
  246 
  247         case PRU_DISCONNECT:
  248                 unp_disconnect(unp);
  249                 break;
  250 
  251         case PRU_ACCEPT:
  252                 unp_setpeeraddr(unp, nam);
  253                 /*
  254                  * Mark the initiating STREAM socket as connected *ONLY*
  255                  * after it's been accepted.  This prevents a client from
  256                  * overrunning a server and receiving ECONNREFUSED.
  257                  */
  258                 if (unp->unp_conn != NULL &&
  259                     (unp->unp_conn->unp_socket->so_state & SS_ISCONNECTING))
  260                         soisconnected(unp->unp_conn->unp_socket);
  261                 break;
  262 
  263         case PRU_SHUTDOWN:
  264                 socantsendmore(so);
  265                 unp_shutdown(unp);
  266                 break;
  267 
  268         case PRU_RCVD:
  269                 switch (so->so_type) {
  270 
  271                 case SOCK_DGRAM:
  272                         panic("uipc 1");
  273                         /*NOTREACHED*/
  274 
  275                 case SOCK_STREAM:
  276 #define rcv (&so->so_rcv)
  277 #define snd (&so2->so_snd)
  278                         if (unp->unp_conn == 0)
  279                                 break;
  280                         so2 = unp->unp_conn->unp_socket;
  281                         /*
  282                          * Adjust backpressure on sender
  283                          * and wakeup any waiting to write.
  284                          */
  285                         snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt;
  286                         unp->unp_mbcnt = rcv->sb_mbcnt;
  287                         newhiwat = snd->sb_hiwat + unp->unp_cc - rcv->sb_cc;
  288                         (void)chgsbsize(so2->so_uid,
  289                             &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
  290                         unp->unp_cc = rcv->sb_cc;
  291                         sowwakeup(so2);
  292 #undef snd
  293 #undef rcv
  294                         break;
  295 
  296                 default:
  297                         panic("uipc 2");
  298                 }
  299                 break;
  300 
  301         case PRU_SEND:
  302                 /*
  303                  * Note: unp_internalize() rejects any control message
  304                  * other than SCM_RIGHTS, and only allows one.  This
  305                  * has the side-effect of preventing a caller from
  306                  * forging SCM_CREDS.
  307                  */
  308                 if (control) {
  309                         if ((error = unp_internalize(control, p)) != 0) {
  310                                 m_freem(control);
  311                                 m_freem(m);
  312                                 break;
  313                         }
  314                 }
  315                 switch (so->so_type) {
  316 
  317                 case SOCK_DGRAM: {
  318                         if (nam) {
  319                                 if ((so->so_state & SS_ISCONNECTED) != 0)
  320                                         error = EISCONN;
  321                                 else
  322                                         error = unp_connect(so, nam, p);
  323                         } else {
  324                                 if ((so->so_state & SS_ISCONNECTED) == 0)
  325                                         error = ENOTCONN;
  326                         }
  327                         if (error) {
  328                                 unp_dispose(control);
  329                                 m_freem(control);
  330                                 m_freem(m);
  331                                 break;
  332                         }
  333                         error = unp_output(m, control, unp, p);
  334                         if (nam)
  335                                 unp_disconnect(unp);
  336                         break;
  337                 }
  338 
  339                 case SOCK_STREAM:
  340 #define rcv (&so2->so_rcv)
  341 #define snd (&so->so_snd)
  342                         if (unp->unp_conn == 0)
  343                                 panic("uipc 3");
  344                         so2 = unp->unp_conn->unp_socket;
  345                         if (unp->unp_conn->unp_flags & UNP_WANTCRED) {
  346                                 /*
  347                                  * Credentials are passed only once on
  348                                  * SOCK_STREAM.
  349                                  */
  350                                 unp->unp_conn->unp_flags &= ~UNP_WANTCRED;
  351                                 control = unp_addsockcred(p, control);
  352                         }
  353                         /*
  354                          * Send to paired receive port, and then reduce
  355                          * send buffer hiwater marks to maintain backpressure.
  356                          * Wake up readers.
  357                          */
  358                         if (control) {
  359                                 if (sbappendcontrol(rcv, m, control) == 0) {
  360                                         unp_dispose(control);
  361                                         m_freem(control);
  362                                 }
  363                         } else
  364                                 sbappend(rcv, m);
  365                         snd->sb_mbmax -=
  366                             rcv->sb_mbcnt - unp->unp_conn->unp_mbcnt;
  367                         unp->unp_conn->unp_mbcnt = rcv->sb_mbcnt;
  368                         newhiwat = snd->sb_hiwat -
  369                             (rcv->sb_cc - unp->unp_conn->unp_cc);
  370                         (void)chgsbsize(so->so_uid,
  371                             &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
  372                         unp->unp_conn->unp_cc = rcv->sb_cc;
  373                         sorwakeup(so2);
  374 #undef snd
  375 #undef rcv
  376                         break;
  377 
  378                 default:
  379                         panic("uipc 4");
  380                 }
  381                 break;
  382 
  383         case PRU_ABORT:
  384                 unp_drop(unp, ECONNABORTED);
  385 
  386 #ifdef DIAGNOSTIC
  387                 if (so->so_pcb == 0)
  388                         panic("uipc 5: drop killed pcb");
  389 #endif
  390                 unp_detach(unp);
  391                 break;
  392 
  393         case PRU_SENSE:
  394                 ((struct stat *) m)->st_blksize = so->so_snd.sb_hiwat;
  395                 if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
  396                         so2 = unp->unp_conn->unp_socket;
  397                         ((struct stat *) m)->st_blksize += so2->so_rcv.sb_cc;
  398                 }
  399                 ((struct stat *) m)->st_dev = NODEV;
  400                 if (unp->unp_ino == 0)
  401                         unp->unp_ino = unp_ino++;
  402                 ((struct stat *) m)->st_atimespec =
  403                     ((struct stat *) m)->st_mtimespec =
  404                     ((struct stat *) m)->st_ctimespec = unp->unp_ctime;
  405                 ((struct stat *) m)->st_ino = unp->unp_ino;
  406                 return (0);
  407 
  408         case PRU_RCVOOB:
  409                 error = EOPNOTSUPP;
  410                 break;
  411 
  412         case PRU_SENDOOB:
  413                 m_freem(control);
  414                 m_freem(m);
  415                 error = EOPNOTSUPP;
  416                 break;
  417 
  418         case PRU_SOCKADDR:
  419                 unp_setsockaddr(unp, nam);
  420                 break;
  421 
  422         case PRU_PEERADDR:
  423                 unp_setpeeraddr(unp, nam);
  424                 break;
  425 
  426         default:
  427                 panic("piusrreq");
  428         }
  429 
  430 release:
  431         return (error);
  432 }
  433 
  434 /*
  435  * Unix domain socket option processing.
  436  */
  437 int
  438 uipc_ctloutput(int op, struct socket *so, int level, int optname,
  439         struct mbuf **mp)
  440 {
  441         struct unpcb *unp = sotounpcb(so);
  442         struct mbuf *m = *mp;
  443         int optval = 0, error = 0;
  444 
  445         if (level != 0) {
  446                 error = EINVAL;
  447                 if (op == PRCO_SETOPT && m)
  448                         (void) m_free(m);
  449         } else switch (op) {
  450 
  451         case PRCO_SETOPT:
  452                 switch (optname) {
  453                 case LOCAL_CREDS:
  454                 case LOCAL_CONNWAIT:
  455                         if (m == NULL || m->m_len != sizeof(int))
  456                                 error = EINVAL;
  457                         else {
  458                                 optval = *mtod(m, int *);
  459                                 switch (optname) {
  460 #define OPTSET(bit) \
  461         if (optval) \
  462                 unp->unp_flags |= (bit); \
  463         else \
  464                 unp->unp_flags &= ~(bit);
  465 
  466                                 case LOCAL_CREDS:
  467                                         OPTSET(UNP_WANTCRED);
  468                                         break;
  469                                 case LOCAL_CONNWAIT:
  470                                         OPTSET(UNP_CONNWAIT);
  471                                         break;
  472                                 }
  473                         }
  474                         break;
  475 #undef OPTSET
  476 
  477                 default:
  478                         error = ENOPROTOOPT;
  479                         break;
  480                 }
  481                 if (m)
  482                         (void) m_free(m);
  483                 break;
  484 
  485         case PRCO_GETOPT:
  486                 switch (optname) {
  487                 case LOCAL_CREDS:
  488                         *mp = m = m_get(M_WAIT, MT_SOOPTS);
  489                         m->m_len = sizeof(int);
  490                         switch (optname) {
  491 
  492 #define OPTBIT(bit)     (unp->unp_flags & (bit) ? 1 : 0)
  493 
  494                         case LOCAL_CREDS:
  495                                 optval = OPTBIT(UNP_WANTCRED);
  496                                 break;
  497                         }
  498                         *mtod(m, int *) = optval;
  499                         break;
  500 #undef OPTBIT
  501 
  502                 default:
  503                         error = ENOPROTOOPT;
  504                         break;
  505                 }
  506                 break;
  507         }
  508         return (error);
  509 }
  510 
  511 /*
  512  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
  513  * for stream sockets, although the total for sender and receiver is
  514  * actually only PIPSIZ.
  515  * Datagram sockets really use the sendspace as the maximum datagram size,
  516  * and don't really want to reserve the sendspace.  Their recvspace should
  517  * be large enough for at least one max-size datagram plus address.
  518  */
  519 #define PIPSIZ  4096
  520 u_long  unpst_sendspace = PIPSIZ;
  521 u_long  unpst_recvspace = PIPSIZ;
  522 u_long  unpdg_sendspace = 2*1024;       /* really max datagram size */
  523 u_long  unpdg_recvspace = 4*1024;
  524 
  525 int     unp_rights;                     /* file descriptors in flight */
  526 int     unp_rights_ratio = 2;           /* limit, fraction of maxfiles */
  527 
  528 int
  529 unp_attach(struct socket *so)
  530 {
  531         struct unpcb *unp;
  532         struct timeval tv;
  533         int error;
  534 
  535         if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
  536                 switch (so->so_type) {
  537 
  538                 case SOCK_STREAM:
  539                         error = soreserve(so, unpst_sendspace, unpst_recvspace);
  540                         break;
  541 
  542                 case SOCK_DGRAM:
  543                         error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
  544                         break;
  545 
  546                 default:
  547                         panic("unp_attach");
  548                 }
  549                 if (error)
  550                         return (error);
  551         }
  552         unp = malloc(sizeof(*unp), M_PCB, M_NOWAIT);
  553         if (unp == NULL)
  554                 return (ENOBUFS);
  555         memset((caddr_t)unp, 0, sizeof(*unp));
  556         unp->unp_socket = so;
  557         so->so_pcb = unp;
  558         microtime(&tv);
  559         TIMEVAL_TO_TIMESPEC(&tv, &unp->unp_ctime);
  560         return (0);
  561 }
  562 
  563 void
  564 unp_detach(struct unpcb *unp)
  565 {
  566 
  567         if (unp->unp_vnode) {
  568                 unp->unp_vnode->v_socket = 0;
  569                 vrele(unp->unp_vnode);
  570                 unp->unp_vnode = 0;
  571         }
  572         if (unp->unp_conn)
  573                 unp_disconnect(unp);
  574         while (unp->unp_refs)
  575                 unp_drop(unp->unp_refs, ECONNRESET);
  576         soisdisconnected(unp->unp_socket);
  577         unp->unp_socket->so_pcb = 0;
  578         if (unp->unp_addr)
  579                 free(unp->unp_addr, M_SONAME);
  580         if (unp_rights) {
  581                 /*
  582                  * Normally the receive buffer is flushed later,
  583                  * in sofree, but if our receive buffer holds references
  584                  * to descriptors that are now garbage, we will dispose
  585                  * of those descriptor references after the garbage collector
  586                  * gets them (resulting in a "panic: closef: count < 0").
  587                  */
  588                 sorflush(unp->unp_socket);
  589                 free(unp, M_PCB);
  590                 unp_gc();
  591         } else
  592                 free(unp, M_PCB);
  593 }
  594 
  595 int
  596 unp_bind(struct unpcb *unp, struct mbuf *nam, struct proc *p)
  597 {
  598         struct sockaddr_un *sun;
  599         struct vnode *vp;
  600         struct mount *mp;
  601         struct vattr vattr;
  602         size_t addrlen;
  603         int error;
  604         struct nameidata nd;
  605 
  606         if (unp->unp_vnode != 0)
  607                 return (EINVAL);
  608 
  609         /*
  610          * Allocate the new sockaddr.  We have to allocate one
  611          * extra byte so that we can ensure that the pathname
  612          * is nul-terminated.
  613          */
  614         addrlen = nam->m_len + 1;
  615         sun = malloc(addrlen, M_SONAME, M_WAITOK);
  616         m_copydata(nam, 0, nam->m_len, (caddr_t)sun);
  617         *(((char *)sun) + nam->m_len) = '\0';
  618 
  619 restart:
  620         NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT, UIO_SYSSPACE,
  621             sun->sun_path, p);
  622 
  623 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
  624         if ((error = namei(&nd)) != 0)
  625                 goto bad;
  626         vp = nd.ni_vp;
  627         if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
  628                 VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
  629                 if (nd.ni_dvp == vp)
  630                         vrele(nd.ni_dvp);
  631                 else
  632                         vput(nd.ni_dvp);
  633                 vrele(vp);
  634                 if (vp != NULL) {
  635                         error = EADDRINUSE;
  636                         goto bad;
  637                 }
  638                 error = vn_start_write(NULL, &mp,
  639                     V_WAIT | V_SLEEPONLY | V_PCATCH);
  640                 if (error)
  641                         goto bad;
  642                 goto restart;
  643         }
  644         VATTR_NULL(&vattr);
  645         vattr.va_type = VSOCK;
  646         vattr.va_mode = ACCESSPERMS & ~(p->p_cwdi->cwdi_cmask);
  647         VOP_LEASE(nd.ni_dvp, p, p->p_ucred, LEASE_WRITE);
  648         error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
  649         vn_finished_write(mp, 0);
  650         if (error)
  651                 goto bad;
  652         vp = nd.ni_vp;
  653         vp->v_socket = unp->unp_socket;
  654         unp->unp_vnode = vp;
  655         unp->unp_addrlen = addrlen;
  656         unp->unp_addr = sun;
  657         VOP_UNLOCK(vp, 0);
  658         return (0);
  659 
  660  bad:
  661         free(sun, M_SONAME);
  662         return (error);
  663 }
  664 
  665 int
  666 unp_connect(struct socket *so, struct mbuf *nam, struct proc *p)
  667 {
  668         struct sockaddr_un *sun;
  669         struct vnode *vp;
  670         struct socket *so2, *so3;
  671         struct unpcb *unp2, *unp3;
  672         size_t addrlen;
  673         int error;
  674         struct nameidata nd;
  675 
  676         /*
  677          * Allocate a temporary sockaddr.  We have to allocate one extra
  678          * byte so that we can ensure that the pathname is nul-terminated.
  679          * When we establish the connection, we copy the other PCB's
  680          * sockaddr to our own.
  681          */
  682         addrlen = nam->m_len + 1;
  683         sun = malloc(addrlen, M_SONAME, M_WAITOK);
  684         m_copydata(nam, 0, nam->m_len, (caddr_t)sun);
  685         *(((char *)sun) + nam->m_len) = '\0';
  686 
  687         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, sun->sun_path, p);
  688 
  689         if ((error = namei(&nd)) != 0)
  690                 goto bad2;
  691         vp = nd.ni_vp;
  692         if (vp->v_type != VSOCK) {
  693                 error = ENOTSOCK;
  694                 goto bad;
  695         }
  696         if ((error = VOP_ACCESS(vp, VWRITE, p->p_ucred, p)) != 0)
  697                 goto bad;
  698         so2 = vp->v_socket;
  699         if (so2 == 0) {
  700                 error = ECONNREFUSED;
  701                 goto bad;
  702         }
  703         if (so->so_type != so2->so_type) {
  704                 error = EPROTOTYPE;
  705                 goto bad;
  706         }
  707         if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
  708                 if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
  709                     (so3 = sonewconn(so2, 0)) == 0) {
  710                         error = ECONNREFUSED;
  711                         goto bad;
  712                 }
  713                 unp2 = sotounpcb(so2);
  714                 unp3 = sotounpcb(so3);
  715                 if (unp2->unp_addr) {
  716                         unp3->unp_addr = malloc(unp2->unp_addrlen,
  717                             M_SONAME, M_WAITOK);
  718                         memcpy(unp3->unp_addr, unp2->unp_addr,
  719                             unp2->unp_addrlen);
  720                         unp3->unp_addrlen = unp2->unp_addrlen;
  721                 }
  722                 unp3->unp_flags = unp2->unp_flags;
  723                 so2 = so3;
  724         }
  725         error = unp_connect2(so, so2, PRU_CONNECT);
  726  bad:
  727         vput(vp);
  728  bad2:
  729         free(sun, M_SONAME);
  730         return (error);
  731 }
  732 
  733 int
  734 unp_connect2(struct socket *so, struct socket *so2, int req)
  735 {
  736         struct unpcb *unp = sotounpcb(so);
  737         struct unpcb *unp2;
  738 
  739         if (so2->so_type != so->so_type)
  740                 return (EPROTOTYPE);
  741         unp2 = sotounpcb(so2);
  742         unp->unp_conn = unp2;
  743         switch (so->so_type) {
  744 
  745         case SOCK_DGRAM:
  746                 unp->unp_nextref = unp2->unp_refs;
  747                 unp2->unp_refs = unp;
  748                 soisconnected(so);
  749                 break;
  750 
  751         case SOCK_STREAM:
  752                 unp2->unp_conn = unp;
  753                 if (req == PRU_CONNECT &&
  754                     ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
  755                         soisconnecting(so);
  756                 else
  757                         soisconnected(so);
  758                 soisconnected(so2);
  759                 break;
  760 
  761         default:
  762                 panic("unp_connect2");
  763         }
  764         return (0);
  765 }
  766 
  767 void
  768 unp_disconnect(struct unpcb *unp)
  769 {
  770         struct unpcb *unp2 = unp->unp_conn;
  771 
  772         if (unp2 == 0)
  773                 return;
  774         unp->unp_conn = 0;
  775         switch (unp->unp_socket->so_type) {
  776 
  777         case SOCK_DGRAM:
  778                 if (unp2->unp_refs == unp)
  779                         unp2->unp_refs = unp->unp_nextref;
  780                 else {
  781                         unp2 = unp2->unp_refs;
  782                         for (;;) {
  783                                 if (unp2 == 0)
  784                                         panic("unp_disconnect");
  785                                 if (unp2->unp_nextref == unp)
  786                                         break;
  787                                 unp2 = unp2->unp_nextref;
  788                         }
  789                         unp2->unp_nextref = unp->unp_nextref;
  790                 }
  791                 unp->unp_nextref = 0;
  792                 unp->unp_socket->so_state &= ~SS_ISCONNECTED;
  793                 break;
  794 
  795         case SOCK_STREAM:
  796                 soisdisconnected(unp->unp_socket);
  797                 unp2->unp_conn = 0;
  798                 soisdisconnected(unp2->unp_socket);
  799                 break;
  800         }
  801 }
  802 
  803 #ifdef notdef
  804 unp_abort(struct unpcb *unp)
  805 {
  806         unp_detach(unp);
  807 }
  808 #endif
  809 
  810 void
  811 unp_shutdown(struct unpcb *unp)
  812 {
  813         struct socket *so;
  814 
  815         if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
  816             (so = unp->unp_conn->unp_socket))
  817                 socantrcvmore(so);
  818 }
  819 
  820 void
  821 unp_drop(struct unpcb *unp, int errno)
  822 {
  823         struct socket *so = unp->unp_socket;
  824 
  825         so->so_error = errno;
  826         unp_disconnect(unp);
  827         if (so->so_head) {
  828                 so->so_pcb = 0;
  829                 sofree(so);
  830                 if (unp->unp_addr)
  831                         free(unp->unp_addr, M_SONAME);
  832                 free(unp, M_PCB);
  833         }
  834 }
  835 
  836 #ifdef notdef
  837 unp_drain(void)
  838 {
  839 
  840 }
  841 #endif
  842 
  843 int
  844 unp_externalize(struct mbuf *rights, struct proc *p)
  845 {
  846         struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
  847         int i, *fdp;
  848         struct file **rp;
  849         struct file *fp;
  850         int nfds, error = 0;
  851 
  852         nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
  853             sizeof(struct file *);
  854         rp = (struct file **)CMSG_DATA(cm);
  855 
  856         fdp = malloc(nfds * sizeof(int), M_TEMP, M_WAITOK);
  857 
  858         /* Make sure the recipient should be able to see the descriptors.. */
  859         if (p->p_cwdi->cwdi_rdir != NULL) {
  860                 rp = (struct file **)CMSG_DATA(cm);
  861                 for (i = 0; i < nfds; i++) {
  862                         fp = *rp++;
  863                         /*
  864                          * If we are in a chroot'ed directory, and
  865                          * someone wants to pass us a directory, make
  866                          * sure it's inside the subtree we're allowed
  867                          * to access.
  868                          */
  869                         if (fp->f_type == DTYPE_VNODE) {
  870                                 struct vnode *vp = (struct vnode *)fp->f_data;
  871                                 if ((vp->v_type == VDIR) &&
  872                                     !vn_isunder(vp, p->p_cwdi->cwdi_rdir, p)) {
  873                                         error = EPERM;
  874                                         break;
  875                                 }
  876                         }
  877                 }
  878         }
  879 
  880  restart:
  881         rp = (struct file **)CMSG_DATA(cm);
  882         if (error != 0) {
  883                 for (i = 0; i < nfds; i++) {
  884                         fp = *rp;
  885                         /*
  886                          * zero the pointer before calling unp_discard,
  887                          * since it may end up in unp_gc()..
  888                          */
  889                         *rp++ = 0;
  890                         unp_discard(fp);
  891                 }
  892                 goto out;
  893         }
  894 
  895         /*
  896          * First loop -- allocate file descriptor table slots for the
  897          * new descriptors.
  898          */
  899         for (i = 0; i < nfds; i++) {
  900                 fp = *rp++;
  901                 if ((error = fdalloc(p, 0, &fdp[i])) != 0) {
  902                         /*
  903                          * Back out what we've done so far.
  904                          */
  905                         for (--i; i >= 0; i--)
  906                                 fdremove(p->p_fd, fdp[i]);
  907 
  908                         if (error == ENOSPC) {
  909                                 fdexpand(p);
  910                                 error = 0;
  911                         } else {
  912                                 /*
  913                                  * This is the error that has historically
  914                                  * been returned, and some callers may
  915                                  * expect it.
  916                                  */
  917                                 error = EMSGSIZE;
  918                         }
  919                         goto restart;
  920                 }
  921 
  922                 /*
  923                  * Make the slot reference the descriptor so that
  924                  * fdalloc() works properly.. We finalize it all
  925                  * in the loop below.
  926                  */
  927                 p->p_fd->fd_ofiles[fdp[i]] = fp;
  928         }
  929 
  930         /*
  931          * Now that adding them has succeeded, update all of the
  932          * descriptor passing state.
  933          */
  934         rp = (struct file **)CMSG_DATA(cm);
  935         for (i = 0; i < nfds; i++) {
  936                 fp = *rp++;
  937                 fp->f_msgcount--;
  938                 unp_rights--;
  939         }
  940 
  941         /*
  942          * Copy temporary array to message and adjust length, in case of
  943          * transition from large struct file pointers to ints.
  944          */
  945         memcpy(CMSG_DATA(cm), fdp, nfds * sizeof(int));
  946         cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
  947         rights->m_len = CMSG_SPACE(nfds * sizeof(int));
  948  out:
  949         free(fdp, M_TEMP);
  950         return (error);
  951 }
  952 
  953 int
  954 unp_internalize(struct mbuf *control, struct proc *p)
  955 {
  956         struct filedesc *fdescp = p->p_fd;
  957         struct cmsghdr *newcm, *cm = mtod(control, struct cmsghdr *);
  958         struct file **rp, **files;
  959         struct file *fp;
  960         int i, fd, *fdp;
  961         int nfds;
  962         u_int neededspace;
  963         u_int maxmsg;
  964 
  965         /* Sanity check the control message header */
  966         if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
  967             cm->cmsg_len != control->m_len)
  968                 return (EINVAL);
  969 
  970         /* Verify that the file descriptors are valid */
  971         nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof(int);
  972 
  973         maxmsg = maxfiles / unp_rights_ratio;
  974         if (unp_rights + nfds > maxmsg)
  975                 return (EAGAIN);
  976 
  977         fdp = (int *)CMSG_DATA(cm);
  978         for (i = 0; i < nfds; i++) {
  979                 fd = *fdp++;
  980                 if ((fp = fd_getfile(fdescp, fd)) == NULL)
  981                         return (EBADF);
  982                 simple_unlock(&fp->f_slock);
  983         }
  984 
  985         /* Make sure we have room for the struct file pointers */
  986         neededspace = CMSG_SPACE(nfds * sizeof(struct file *)) -
  987             control->m_len;
  988         if (neededspace > M_TRAILINGSPACE(control)) {
  989 
  990                 /* allocate new space and copy header into it */
  991                 newcm = malloc(
  992                     CMSG_SPACE(nfds * sizeof(struct file *)),
  993                     M_MBUF, M_WAITOK);
  994                 if (newcm == NULL)
  995                         return (E2BIG);
  996                 memcpy(newcm, cm, sizeof(struct cmsghdr));
  997                 files = (struct file **)CMSG_DATA(newcm);
  998         } else {
  999                 /* we can convert in-place */
 1000                 newcm = NULL;
 1001                 files = (struct file **)CMSG_DATA(cm);
 1002         }
 1003 
 1004         /*
 1005          * Transform the file descriptors into struct file pointers, in
 1006          * reverse order so that if pointers are bigger than ints, the
 1007          * int won't get until we're done.
 1008          */
 1009         fdp = (int *)CMSG_DATA(cm) + nfds - 1;
 1010         rp = files + nfds - 1;
 1011         for (i = 0; i < nfds; i++) {
 1012                 fp = fdescp->fd_ofiles[*fdp--];
 1013                 simple_lock(&fp->f_slock);
 1014 #ifdef DIAGNOSTIC
 1015                 if (fp->f_iflags & FIF_WANTCLOSE)
 1016                         panic("unp_internalize: file already closed");
 1017 #endif
 1018                 *rp-- = fp;
 1019                 fp->f_count++;
 1020                 fp->f_msgcount++;
 1021                 simple_unlock(&fp->f_slock);
 1022                 unp_rights++;
 1023         }
 1024 
 1025         if (newcm) {
 1026                 if (control->m_flags & M_EXT)
 1027                         MEXTREMOVE(control);
 1028                 MEXTADD(control, newcm,
 1029                     CMSG_SPACE(nfds * sizeof(struct file *)),
 1030                     M_MBUF, NULL, NULL);
 1031                 cm = newcm;
 1032         }
 1033 
 1034         /* adjust message & mbuf to note amount of space actually used. */
 1035         cm->cmsg_len = CMSG_LEN(nfds * sizeof(struct file *));
 1036         control->m_len = CMSG_SPACE(nfds * sizeof(struct file *));
 1037 
 1038         return (0);
 1039 }
 1040 
 1041 struct mbuf *
 1042 unp_addsockcred(struct proc *p, struct mbuf *control)
 1043 {
 1044         struct cmsghdr *cmp;
 1045         struct sockcred *sc;
 1046         struct mbuf *m, *n;
 1047         int len, space, i;
 1048 
 1049         len = CMSG_LEN(SOCKCREDSIZE(p->p_ucred->cr_ngroups));
 1050         space = CMSG_SPACE(SOCKCREDSIZE(p->p_ucred->cr_ngroups));
 1051 
 1052         m = m_get(M_WAIT, MT_CONTROL);
 1053         if (space > MLEN) {
 1054                 if (space > MCLBYTES)
 1055                         MEXTMALLOC(m, space, M_WAITOK);
 1056                 else
 1057                         m_clget(m, M_WAIT);
 1058                 if ((m->m_flags & M_EXT) == 0) {
 1059                         m_free(m);
 1060                         return (control);
 1061                 }
 1062         }
 1063 
 1064         m->m_len = space;
 1065         m->m_next = NULL;
 1066         cmp = mtod(m, struct cmsghdr *);
 1067         sc = (struct sockcred *)CMSG_DATA(cmp);
 1068         cmp->cmsg_len = len;
 1069         cmp->cmsg_level = SOL_SOCKET;
 1070         cmp->cmsg_type = SCM_CREDS;
 1071         sc->sc_uid = p->p_cred->p_ruid;
 1072         sc->sc_euid = p->p_ucred->cr_uid;
 1073         sc->sc_gid = p->p_cred->p_rgid;
 1074         sc->sc_egid = p->p_ucred->cr_gid;
 1075         sc->sc_ngroups = p->p_ucred->cr_ngroups;
 1076         for (i = 0; i < sc->sc_ngroups; i++)
 1077                 sc->sc_groups[i] = p->p_ucred->cr_groups[i];
 1078 
 1079         /*
 1080          * If a control message already exists, append us to the end.
 1081          */
 1082         if (control != NULL) {
 1083                 for (n = control; n->m_next != NULL; n = n->m_next)
 1084                         ;
 1085                 n->m_next = m;
 1086         } else
 1087                 control = m;
 1088 
 1089         return (control);
 1090 }
 1091 
 1092 int     unp_defer, unp_gcing;
 1093 extern  struct domain unixdomain;
 1094 
 1095 /*
 1096  * Comment added long after the fact explaining what's going on here.
 1097  * Do a mark-sweep GC of file descriptors on the system, to free up
 1098  * any which are caught in flight to an about-to-be-closed socket.
 1099  *
 1100  * Traditional mark-sweep gc's start at the "root", and mark
 1101  * everything reachable from the root (which, in our case would be the
 1102  * process table).  The mark bits are cleared during the sweep.
 1103  *
 1104  * XXX For some inexplicable reason (perhaps because the file
 1105  * descriptor tables used to live in the u area which could be swapped
 1106  * out and thus hard to reach), we do multiple scans over the set of
 1107  * descriptors, using use *two* mark bits per object (DEFER and MARK).
 1108  * Whenever we find a descriptor which references other descriptors,
 1109  * the ones it references are marked with both bits, and we iterate
 1110  * over the whole file table until there are no more DEFER bits set.
 1111  * We also make an extra pass *before* the GC to clear the mark bits,
 1112  * which could have been cleared at almost no cost during the previous
 1113  * sweep.
 1114  *
 1115  * XXX MP: this needs to run with locks such that no other thread of
 1116  * control can create or destroy references to file descriptors. it
 1117  * may be necessary to defer the GC until later (when the locking
 1118  * situation is more hospitable); it may be necessary to push this
 1119  * into a separate thread.
 1120  */
 1121 void
 1122 unp_gc(void)
 1123 {
 1124         struct file *fp, *nextfp;
 1125         struct socket *so, *so1;
 1126         struct file **extra_ref, **fpp;
 1127         int nunref, i;
 1128 
 1129         if (unp_gcing)
 1130                 return;
 1131         unp_gcing = 1;
 1132         unp_defer = 0;
 1133 
 1134         /* Clear mark bits */
 1135         LIST_FOREACH(fp, &filehead, f_list)
 1136                 fp->f_flag &= ~(FMARK|FDEFER);
 1137 
 1138         /*
 1139          * Iterate over the set of descriptors, marking ones believed
 1140          * (based on refcount) to be referenced from a process, and
 1141          * marking for rescan descriptors which are queued on a socket.
 1142          */
 1143         do {
 1144                 LIST_FOREACH(fp, &filehead, f_list) {
 1145                         if (fp->f_flag & FDEFER) {
 1146                                 fp->f_flag &= ~FDEFER;
 1147                                 unp_defer--;
 1148 #ifdef DIAGNOSTIC
 1149                                 if (fp->f_count == 0)
 1150                                         panic("unp_gc: deferred unreferenced socket");
 1151 #endif
 1152                         } else {
 1153                                 if (fp->f_count == 0)
 1154                                         continue;
 1155                                 if (fp->f_flag & FMARK)
 1156                                         continue;
 1157                                 if (fp->f_count == fp->f_msgcount)
 1158                                         continue;
 1159                         }
 1160                         if (fp->f_iflags & FIF_DISCARDED)
 1161                                 continue;
 1162                         fp->f_flag |= FMARK;
 1163 
 1164                         if (fp->f_type != DTYPE_SOCKET ||
 1165                             (so = (struct socket *)fp->f_data) == 0)
 1166                                 continue;
 1167                         if (so->so_proto->pr_domain != &unixdomain ||
 1168                             (so->so_proto->pr_flags&PR_RIGHTS) == 0)
 1169                                 continue;
 1170 #ifdef notdef
 1171                         if (so->so_rcv.sb_flags & SB_LOCK) {
 1172                                 /*
 1173                                  * This is problematical; it's not clear
 1174                                  * we need to wait for the sockbuf to be
 1175                                  * unlocked (on a uniprocessor, at least),
 1176                                  * and it's also not clear what to do
 1177                                  * if sbwait returns an error due to receipt
 1178                                  * of a signal.  If sbwait does return
 1179                                  * an error, we'll go into an infinite
 1180                                  * loop.  Delete all of this for now.
 1181                                  */
 1182                                 (void) sbwait(&so->so_rcv);
 1183                                 goto restart;
 1184                         }
 1185 #endif
 1186                         unp_scan(so->so_rcv.sb_mb, unp_mark, 0);
 1187                         /*
 1188                          * mark descriptors referenced from sockets queued on the accept queue as well.
 1189                          */
 1190                         if (so->so_options & SO_ACCEPTCONN) {
 1191                                 TAILQ_FOREACH(so1, &so->so_q0, so_qe) {
 1192                                         unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
 1193                                 }
 1194                                 TAILQ_FOREACH(so1, &so->so_q, so_qe) {
 1195                                         unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
 1196                                 }
 1197                         }
 1198 
 1199                 }
 1200         } while (unp_defer);
 1201         /*
 1202          * Sweep pass.  Find unmarked descriptors, and free them.
 1203          *
 1204          * We grab an extra reference to each of the file table entries
 1205          * that are not otherwise accessible and then free the rights
 1206          * that are stored in messages on them.
 1207          *
 1208          * The bug in the original code is a little tricky, so I'll describe
 1209          * what's wrong with it here.
 1210          *
 1211          * It is incorrect to simply unp_discard each entry for f_msgcount
 1212          * times -- consider the case of sockets A and B that contain
 1213          * references to each other.  On a last close of some other socket,
 1214          * we trigger a gc since the number of outstanding rights (unp_rights)
 1215          * is non-zero.  If during the sweep phase the gc code un_discards,
 1216          * we end up doing a (full) closef on the descriptor.  A closef on A
 1217          * results in the following chain.  Closef calls soo_close, which
 1218          * calls soclose.   Soclose calls first (through the switch
 1219          * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
 1220          * returns because the previous instance had set unp_gcing, and
 1221          * we return all the way back to soclose, which marks the socket
 1222          * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
 1223          * to free up the rights that are queued in messages on the socket A,
 1224          * i.e., the reference on B.  The sorflush calls via the dom_dispose
 1225          * switch unp_dispose, which unp_scans with unp_discard.  This second
 1226          * instance of unp_discard just calls closef on B.
 1227          *
 1228          * Well, a similar chain occurs on B, resulting in a sorflush on B,
 1229          * which results in another closef on A.  Unfortunately, A is already
 1230          * being closed, and the descriptor has already been marked with
 1231          * SS_NOFDREF, and soclose panics at this point.
 1232          *
 1233          * Here, we first take an extra reference to each inaccessible
 1234          * descriptor.  Then, if the inaccessible descriptor is a
 1235          * socket, we call sorflush in case it is a Unix domain
 1236          * socket.  After we destroy all the rights carried in
 1237          * messages, we do a last closef to get rid of our extra
 1238          * reference.  This is the last close, and the unp_detach etc
 1239          * will shut down the socket.
 1240          *
 1241          * 91/09/19, bsy@cs.cmu.edu
 1242          */
 1243         extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
 1244         for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref; fp != 0;
 1245             fp = nextfp) {
 1246                 nextfp = LIST_NEXT(fp, f_list);
 1247                 simple_lock(&fp->f_slock);
 1248                 if (fp->f_count != 0 &&
 1249                     fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
 1250                         *fpp++ = fp;
 1251                         nunref++;
 1252                         fp->f_count++;
 1253                 }
 1254                 simple_unlock(&fp->f_slock);
 1255         }
 1256         for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
 1257                 fp = *fpp;
 1258                 simple_lock(&fp->f_slock);
 1259                 FILE_USE(fp);
 1260                 if (fp->f_type == DTYPE_SOCKET)
 1261                         sorflush((struct socket *)fp->f_data);
 1262                 FILE_UNUSE(fp, NULL);
 1263         }
 1264         for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
 1265                 fp = *fpp;
 1266                 simple_lock(&fp->f_slock);
 1267                 if (fp->f_iflags & FIF_DISCARDED) {
 1268                         fp->f_usecount++;
 1269                         fp->f_msgcount--;
 1270                         simple_unlock(&fp->f_slock);
 1271                         unp_rights--;
 1272                         (void) closef(fp, (struct proc *)0);
 1273                         simple_lock(&fp->f_slock);
 1274                 }
 1275                 FILE_USE(fp);
 1276                 (void) closef(fp, (struct proc *)0);
 1277         }
 1278         free((caddr_t)extra_ref, M_FILE);
 1279         unp_gcing = 0;
 1280 }
 1281 
 1282 void
 1283 unp_dispose(struct mbuf *m)
 1284 {
 1285 
 1286         if (m)
 1287                 unp_scan(m, unp_discard, 1);
 1288 }
 1289 
 1290 void
 1291 unp_scan(struct mbuf *m0, void (*op)(struct file *), int discard)
 1292 {
 1293         struct mbuf *m;
 1294         struct file **rp;
 1295         struct cmsghdr *cm;
 1296         int i;
 1297         int qfds;
 1298 
 1299         while (m0) {
 1300                 for (m = m0; m; m = m->m_next) {
 1301                         if (m->m_type == MT_CONTROL &&
 1302                             m->m_len >= sizeof(*cm)) {
 1303                                 cm = mtod(m, struct cmsghdr *);
 1304                                 if (cm->cmsg_level != SOL_SOCKET ||
 1305                                     cm->cmsg_type != SCM_RIGHTS)
 1306                                         continue;
 1307                                 qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm)))
 1308                                     / sizeof(struct file *);
 1309                                 rp = (struct file **)CMSG_DATA(cm);
 1310                                 for (i = 0; i < qfds; i++) {
 1311                                         struct file *fp = *rp;
 1312                                         if (discard)
 1313                                                 *rp = 0;
 1314                                         (*op)(fp);
 1315                                         rp++;
 1316                                 }
 1317                                 break;          /* XXX, but saves time */
 1318                         }
 1319                 }
 1320                 m0 = m0->m_nextpkt;
 1321         }
 1322 }
 1323 
 1324 void
 1325 unp_mark(struct file *fp)
 1326 {
 1327         if (fp == NULL)
 1328                 return;
 1329 
 1330         if (fp->f_flag & FMARK)
 1331                 return;
 1332 
 1333         /* If we're already deferred, don't screw up the defer count */
 1334         if (fp->f_flag & FDEFER)
 1335                 return;
 1336 
 1337         /*
 1338          * Minimize the number of deferrals...  Sockets are the only
 1339          * type of descriptor which can hold references to another
 1340          * descriptor, so just mark other descriptors, and defer
 1341          * unmarked sockets for the next pass.
 1342          */
 1343         if (fp->f_type == DTYPE_SOCKET) {
 1344                 unp_defer++;
 1345                 if (fp->f_count == 0)
 1346                         panic("unp_mark: queued unref");
 1347                 fp->f_flag |= FDEFER;
 1348         } else {
 1349                 fp->f_flag |= FMARK;
 1350         }
 1351         return;
 1352 }
 1353 
 1354 void
 1355 unp_discard(struct file *fp)
 1356 {
 1357         if (fp == NULL)
 1358                 return;
 1359 
 1360         simple_lock(&fp->f_slock);
 1361         /*
 1362          * closing unix domain sockets may cause a deep
 1363          * recursion, so leave them open and mark them
 1364          * for the garbage collector to discard them safely.
 1365          */
 1366         if (fp->f_type == DTYPE_SOCKET && fp->f_count == 1) {
 1367                 struct socket *so;
 1368 
 1369                 so = (struct socket *)fp->f_data;
 1370                 if (so && so->so_proto->pr_domain == &unixdomain &&
 1371                     (so->so_proto->pr_flags&PR_RIGHTS) != 0) {
 1372                         fp->f_iflags |= FIF_DISCARDED;
 1373                         simple_unlock(&fp->f_slock);
 1374                         return;
 1375                 }
 1376         }
 1377         fp->f_usecount++;       /* i.e. FILE_USE(fp) sans locking */
 1378         fp->f_msgcount--;
 1379         simple_unlock(&fp->f_slock);
 1380         unp_rights--;
 1381         (void) closef(fp, (struct proc *)0);
 1382 }

Cache object: ae86acbe5888e63b8295783df6b48060


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.