Home | History | Annotate | Line # | Download | only in kern
uipc_usrreq.c revision 1.73
      1 /*	$NetBSD: uipc_usrreq.c,v 1.73 2003/12/29 22:08:02 martin Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 2000 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.73 2003/12/29 22:08:02 martin 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 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 __P((struct proc *, struct mbuf *));
    136 
    137 int
    138 unp_output(m, control, unp, p)
    139 	struct mbuf *m, *control;
    140 	struct unpcb *unp;
    141 	struct proc *p;
    142 {
    143 	struct socket *so2;
    144 	struct sockaddr_un *sun;
    145 
    146 	so2 = unp->unp_conn->unp_socket;
    147 	if (unp->unp_addr)
    148 		sun = unp->unp_addr;
    149 	else
    150 		sun = &sun_noname;
    151 	if (unp->unp_conn->unp_flags & UNP_WANTCRED)
    152 		control = unp_addsockcred(p, control);
    153 	if (sbappendaddr(&so2->so_rcv, (struct sockaddr *)sun, m,
    154 	    control) == 0) {
    155 		m_freem(control);
    156 		m_freem(m);
    157 		return (ENOBUFS);
    158 	} else {
    159 		sorwakeup(so2);
    160 		return (0);
    161 	}
    162 }
    163 
    164 void
    165 unp_setsockaddr(unp, nam)
    166 	struct unpcb *unp;
    167 	struct mbuf *nam;
    168 {
    169 	struct sockaddr_un *sun;
    170 
    171 	if (unp->unp_addr)
    172 		sun = unp->unp_addr;
    173 	else
    174 		sun = &sun_noname;
    175 	nam->m_len = sun->sun_len;
    176 	if (nam->m_len > MLEN)
    177 		MEXTMALLOC(nam, nam->m_len, M_WAITOK);
    178 	memcpy(mtod(nam, caddr_t), sun, (size_t)nam->m_len);
    179 }
    180 
    181 void
    182 unp_setpeeraddr(unp, nam)
    183 	struct unpcb *unp;
    184 	struct mbuf *nam;
    185 {
    186 	struct sockaddr_un *sun;
    187 
    188 	if (unp->unp_conn && unp->unp_conn->unp_addr)
    189 		sun = unp->unp_conn->unp_addr;
    190 	else
    191 		sun = &sun_noname;
    192 	nam->m_len = sun->sun_len;
    193 	if (nam->m_len > MLEN)
    194 		MEXTMALLOC(nam, nam->m_len, M_WAITOK);
    195 	memcpy(mtod(nam, caddr_t), sun, (size_t)nam->m_len);
    196 }
    197 
    198 /*ARGSUSED*/
    199 int
    200 uipc_usrreq(so, req, m, nam, control, p)
    201 	struct socket *so;
    202 	int req;
    203 	struct mbuf *m, *nam, *control;
    204 	struct proc *p;
    205 {
    206 	struct unpcb *unp = sotounpcb(so);
    207 	struct socket *so2;
    208 	int error = 0;
    209 
    210 	if (req == PRU_CONTROL)
    211 		return (EOPNOTSUPP);
    212 
    213 #ifdef DIAGNOSTIC
    214 	if (req != PRU_SEND && req != PRU_SENDOOB && control)
    215 		panic("uipc_usrreq: unexpected control mbuf");
    216 #endif
    217 	if (unp == 0 && req != PRU_ATTACH) {
    218 		error = EINVAL;
    219 		goto release;
    220 	}
    221 
    222 	switch (req) {
    223 
    224 	case PRU_ATTACH:
    225 		if (unp != 0) {
    226 			error = EISCONN;
    227 			break;
    228 		}
    229 		error = unp_attach(so);
    230 		break;
    231 
    232 	case PRU_DETACH:
    233 		unp_detach(unp);
    234 		break;
    235 
    236 	case PRU_BIND:
    237 		error = unp_bind(unp, nam, p);
    238 		break;
    239 
    240 	case PRU_LISTEN:
    241 		if (unp->unp_vnode == 0)
    242 			error = EINVAL;
    243 		break;
    244 
    245 	case PRU_CONNECT:
    246 		error = unp_connect(so, nam, p);
    247 		break;
    248 
    249 	case PRU_CONNECT2:
    250 		error = unp_connect2(so, (struct socket *)nam, PRU_CONNECT2);
    251 		break;
    252 
    253 	case PRU_DISCONNECT:
    254 		unp_disconnect(unp);
    255 		break;
    256 
    257 	case PRU_ACCEPT:
    258 		unp_setpeeraddr(unp, nam);
    259 		/*
    260 		 * Mark the initiating STREAM socket as connected *ONLY*
    261 		 * after it's been accepted.  This prevents a client from
    262 		 * overrunning a server and receiving ECONNREFUSED.
    263 		 */
    264 		if (unp->unp_conn != NULL &&
    265 		    (unp->unp_conn->unp_socket->so_state & SS_ISCONNECTING))
    266 			soisconnected(unp->unp_conn->unp_socket);
    267 		break;
    268 
    269 	case PRU_SHUTDOWN:
    270 		socantsendmore(so);
    271 		unp_shutdown(unp);
    272 		break;
    273 
    274 	case PRU_RCVD:
    275 		switch (so->so_type) {
    276 
    277 		case SOCK_DGRAM:
    278 			panic("uipc 1");
    279 			/*NOTREACHED*/
    280 
    281 		case SOCK_STREAM:
    282 #define	rcv (&so->so_rcv)
    283 #define snd (&so2->so_snd)
    284 			if (unp->unp_conn == 0)
    285 				break;
    286 			so2 = unp->unp_conn->unp_socket;
    287 			/*
    288 			 * Adjust backpressure on sender
    289 			 * and wakeup any waiting to write.
    290 			 */
    291 			snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt;
    292 			unp->unp_mbcnt = rcv->sb_mbcnt;
    293 			snd->sb_hiwat += unp->unp_cc - rcv->sb_cc;
    294 			unp->unp_cc = rcv->sb_cc;
    295 			sowwakeup(so2);
    296 #undef snd
    297 #undef rcv
    298 			break;
    299 
    300 		default:
    301 			panic("uipc 2");
    302 		}
    303 		break;
    304 
    305 	case PRU_SEND:
    306 		/*
    307 		 * Note: unp_internalize() rejects any control message
    308 		 * other than SCM_RIGHTS, and only allows one.  This
    309 		 * has the side-effect of preventing a caller from
    310 		 * forging SCM_CREDS.
    311 		 */
    312 		if (control && (error = unp_internalize(control, p)))
    313 			break;
    314 		switch (so->so_type) {
    315 
    316 		case SOCK_DGRAM: {
    317 			if (nam) {
    318 				if ((so->so_state & SS_ISCONNECTED) != 0) {
    319 					error = EISCONN;
    320 					goto die;
    321 				}
    322 				error = unp_connect(so, nam, p);
    323 				if (error) {
    324 				die:
    325 					m_freem(control);
    326 					m_freem(m);
    327 					break;
    328 				}
    329 			} else {
    330 				if ((so->so_state & SS_ISCONNECTED) == 0) {
    331 					error = ENOTCONN;
    332 					goto die;
    333 				}
    334 			}
    335 			error = unp_output(m, control, unp, p);
    336 			if (nam)
    337 				unp_disconnect(unp);
    338 			break;
    339 		}
    340 
    341 		case SOCK_STREAM:
    342 #define	rcv (&so2->so_rcv)
    343 #define	snd (&so->so_snd)
    344 			if (unp->unp_conn == 0)
    345 				panic("uipc 3");
    346 			so2 = unp->unp_conn->unp_socket;
    347 			if (unp->unp_conn->unp_flags & UNP_WANTCRED) {
    348 				/*
    349 				 * Credentials are passed only once on
    350 				 * SOCK_STREAM.
    351 				 */
    352 				unp->unp_conn->unp_flags &= ~UNP_WANTCRED;
    353 				control = unp_addsockcred(p, control);
    354 			}
    355 			/*
    356 			 * Send to paired receive port, and then reduce
    357 			 * send buffer hiwater marks to maintain backpressure.
    358 			 * Wake up readers.
    359 			 */
    360 			if (control) {
    361 				if (sbappendcontrol(rcv, m, control) == 0)
    362 					m_freem(control);
    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 			snd->sb_hiwat -= rcv->sb_cc - unp->unp_conn->unp_cc;
    369 			unp->unp_conn->unp_cc = rcv->sb_cc;
    370 			sorwakeup(so2);
    371 #undef snd
    372 #undef rcv
    373 			break;
    374 
    375 		default:
    376 			panic("uipc 4");
    377 		}
    378 		break;
    379 
    380 	case PRU_ABORT:
    381 		unp_drop(unp, ECONNABORTED);
    382 
    383 #ifdef DIAGNOSTIC
    384 		if (so->so_pcb == 0)
    385 			panic("uipc 5: drop killed pcb");
    386 #endif
    387 		unp_detach(unp);
    388 		break;
    389 
    390 	case PRU_SENSE:
    391 		((struct stat *) m)->st_blksize = so->so_snd.sb_hiwat;
    392 		if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
    393 			so2 = unp->unp_conn->unp_socket;
    394 			((struct stat *) m)->st_blksize += so2->so_rcv.sb_cc;
    395 		}
    396 		((struct stat *) m)->st_dev = NODEV;
    397 		if (unp->unp_ino == 0)
    398 			unp->unp_ino = unp_ino++;
    399 		((struct stat *) m)->st_atimespec =
    400 		    ((struct stat *) m)->st_mtimespec =
    401 		    ((struct stat *) m)->st_ctimespec = unp->unp_ctime;
    402 		((struct stat *) m)->st_ino = unp->unp_ino;
    403 		return (0);
    404 
    405 	case PRU_RCVOOB:
    406 		error = EOPNOTSUPP;
    407 		break;
    408 
    409 	case PRU_SENDOOB:
    410 		m_freem(control);
    411 		m_freem(m);
    412 		error = EOPNOTSUPP;
    413 		break;
    414 
    415 	case PRU_SOCKADDR:
    416 		unp_setsockaddr(unp, nam);
    417 		break;
    418 
    419 	case PRU_PEERADDR:
    420 		unp_setpeeraddr(unp, nam);
    421 		break;
    422 
    423 	default:
    424 		panic("piusrreq");
    425 	}
    426 
    427 release:
    428 	return (error);
    429 }
    430 
    431 /*
    432  * Unix domain socket option processing.
    433  */
    434 int
    435 uipc_ctloutput(op, so, level, optname, mp)
    436 	int op;
    437 	struct socket *so;
    438 	int level, 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 
    527 int
    528 unp_attach(so)
    529 	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(unp)
    565 	struct unpcb *unp;
    566 {
    567 
    568 	if (unp->unp_vnode) {
    569 		unp->unp_vnode->v_socket = 0;
    570 		vrele(unp->unp_vnode);
    571 		unp->unp_vnode = 0;
    572 	}
    573 	if (unp->unp_conn)
    574 		unp_disconnect(unp);
    575 	while (unp->unp_refs)
    576 		unp_drop(unp->unp_refs, ECONNRESET);
    577 	soisdisconnected(unp->unp_socket);
    578 	unp->unp_socket->so_pcb = 0;
    579 	if (unp->unp_addr)
    580 		free(unp->unp_addr, M_SONAME);
    581 	if (unp_rights) {
    582 		/*
    583 		 * Normally the receive buffer is flushed later,
    584 		 * in sofree, but if our receive buffer holds references
    585 		 * to descriptors that are now garbage, we will dispose
    586 		 * of those descriptor references after the garbage collector
    587 		 * gets them (resulting in a "panic: closef: count < 0").
    588 		 */
    589 		sorflush(unp->unp_socket);
    590 		free(unp, M_PCB);
    591 		unp_gc();
    592 	} else
    593 		free(unp, M_PCB);
    594 }
    595 
    596 int
    597 unp_bind(unp, nam, p)
    598 	struct unpcb *unp;
    599 	struct mbuf *nam;
    600 	struct proc *p;
    601 {
    602 	struct sockaddr_un *sun;
    603 	struct vnode *vp;
    604 	struct mount *mp;
    605 	struct vattr vattr;
    606 	size_t addrlen;
    607 	int error;
    608 	struct nameidata nd;
    609 
    610 	if (unp->unp_vnode != 0)
    611 		return (EINVAL);
    612 
    613 	/*
    614 	 * Allocate the new sockaddr.  We have to allocate one
    615 	 * extra byte so that we can ensure that the pathname
    616 	 * is nul-terminated.
    617 	 */
    618 	addrlen = nam->m_len + 1;
    619 	sun = malloc(addrlen, M_SONAME, M_WAITOK);
    620 	m_copydata(nam, 0, nam->m_len, (caddr_t)sun);
    621 	*(((char *)sun) + nam->m_len) = '\0';
    622 
    623 restart:
    624 	NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT, UIO_SYSSPACE,
    625 	    sun->sun_path, p);
    626 
    627 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
    628 	if ((error = namei(&nd)) != 0)
    629 		goto bad;
    630 	vp = nd.ni_vp;
    631 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
    632 		VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
    633 		if (nd.ni_dvp == vp)
    634 			vrele(nd.ni_dvp);
    635 		else
    636 			vput(nd.ni_dvp);
    637 		vrele(vp);
    638 		if (vp != NULL) {
    639 			error = EADDRINUSE;
    640 			goto bad;
    641 		}
    642 		error = vn_start_write(NULL, &mp,
    643 		    V_WAIT | V_SLEEPONLY | V_PCATCH);
    644 		if (error)
    645 			goto bad;
    646 		goto restart;
    647 	}
    648 	VATTR_NULL(&vattr);
    649 	vattr.va_type = VSOCK;
    650 	vattr.va_mode = ACCESSPERMS;
    651 	VOP_LEASE(nd.ni_dvp, p, p->p_ucred, LEASE_WRITE);
    652 	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
    653 	vn_finished_write(mp, 0);
    654 	if (error)
    655 		goto bad;
    656 	vp = nd.ni_vp;
    657 	vp->v_socket = unp->unp_socket;
    658 	unp->unp_vnode = vp;
    659 	unp->unp_addrlen = addrlen;
    660 	unp->unp_addr = sun;
    661 	VOP_UNLOCK(vp, 0);
    662 	return (0);
    663 
    664  bad:
    665 	free(sun, M_SONAME);
    666 	return (error);
    667 }
    668 
    669 int
    670 unp_connect(so, nam, p)
    671 	struct socket *so;
    672 	struct mbuf *nam;
    673 	struct proc *p;
    674 {
    675 	struct sockaddr_un *sun;
    676 	struct vnode *vp;
    677 	struct socket *so2, *so3;
    678 	struct unpcb *unp2, *unp3;
    679 	size_t addrlen;
    680 	int error;
    681 	struct nameidata nd;
    682 
    683 	/*
    684 	 * Allocate a temporary sockaddr.  We have to allocate one extra
    685 	 * byte so that we can ensure that the pathname is nul-terminated.
    686 	 * When we establish the connection, we copy the other PCB's
    687 	 * sockaddr to our own.
    688 	 */
    689 	addrlen = nam->m_len + 1;
    690 	sun = malloc(addrlen, M_SONAME, M_WAITOK);
    691 	m_copydata(nam, 0, nam->m_len, (caddr_t)sun);
    692 	*(((char *)sun) + nam->m_len) = '\0';
    693 
    694 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, sun->sun_path, p);
    695 
    696 	if ((error = namei(&nd)) != 0)
    697 		goto bad2;
    698 	vp = nd.ni_vp;
    699 	if (vp->v_type != VSOCK) {
    700 		error = ENOTSOCK;
    701 		goto bad;
    702 	}
    703 	if ((error = VOP_ACCESS(vp, VWRITE, p->p_ucred, p)) != 0)
    704 		goto bad;
    705 	so2 = vp->v_socket;
    706 	if (so2 == 0) {
    707 		error = ECONNREFUSED;
    708 		goto bad;
    709 	}
    710 	if (so->so_type != so2->so_type) {
    711 		error = EPROTOTYPE;
    712 		goto bad;
    713 	}
    714 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
    715 		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
    716 		    (so3 = sonewconn(so2, 0)) == 0) {
    717 			error = ECONNREFUSED;
    718 			goto bad;
    719 		}
    720 		unp2 = sotounpcb(so2);
    721 		unp3 = sotounpcb(so3);
    722 		if (unp2->unp_addr) {
    723 			unp3->unp_addr = malloc(unp2->unp_addrlen,
    724 			    M_SONAME, M_WAITOK);
    725 			memcpy(unp3->unp_addr, unp2->unp_addr,
    726 			    unp2->unp_addrlen);
    727 			unp3->unp_addrlen = unp2->unp_addrlen;
    728 		}
    729 		unp3->unp_flags = unp2->unp_flags;
    730 		so2 = so3;
    731 	}
    732 	error = unp_connect2(so, so2, PRU_CONNECT);
    733  bad:
    734 	vput(vp);
    735  bad2:
    736 	free(sun, M_SONAME);
    737 	return (error);
    738 }
    739 
    740 int
    741 unp_connect2(so, so2, req)
    742 	struct socket *so;
    743 	struct socket *so2;
    744 	int req;
    745 {
    746 	struct unpcb *unp = sotounpcb(so);
    747 	struct unpcb *unp2;
    748 
    749 	if (so2->so_type != so->so_type)
    750 		return (EPROTOTYPE);
    751 	unp2 = sotounpcb(so2);
    752 	unp->unp_conn = unp2;
    753 	switch (so->so_type) {
    754 
    755 	case SOCK_DGRAM:
    756 		unp->unp_nextref = unp2->unp_refs;
    757 		unp2->unp_refs = unp;
    758 		soisconnected(so);
    759 		break;
    760 
    761 	case SOCK_STREAM:
    762 		unp2->unp_conn = unp;
    763 		if (req == PRU_CONNECT &&
    764 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
    765 			soisconnecting(so);
    766 		else
    767 			soisconnected(so);
    768 		soisconnected(so2);
    769 		break;
    770 
    771 	default:
    772 		panic("unp_connect2");
    773 	}
    774 	return (0);
    775 }
    776 
    777 void
    778 unp_disconnect(unp)
    779 	struct unpcb *unp;
    780 {
    781 	struct unpcb *unp2 = unp->unp_conn;
    782 
    783 	if (unp2 == 0)
    784 		return;
    785 	unp->unp_conn = 0;
    786 	switch (unp->unp_socket->so_type) {
    787 
    788 	case SOCK_DGRAM:
    789 		if (unp2->unp_refs == unp)
    790 			unp2->unp_refs = unp->unp_nextref;
    791 		else {
    792 			unp2 = unp2->unp_refs;
    793 			for (;;) {
    794 				if (unp2 == 0)
    795 					panic("unp_disconnect");
    796 				if (unp2->unp_nextref == unp)
    797 					break;
    798 				unp2 = unp2->unp_nextref;
    799 			}
    800 			unp2->unp_nextref = unp->unp_nextref;
    801 		}
    802 		unp->unp_nextref = 0;
    803 		unp->unp_socket->so_state &= ~SS_ISCONNECTED;
    804 		break;
    805 
    806 	case SOCK_STREAM:
    807 		soisdisconnected(unp->unp_socket);
    808 		unp2->unp_conn = 0;
    809 		soisdisconnected(unp2->unp_socket);
    810 		break;
    811 	}
    812 }
    813 
    814 #ifdef notdef
    815 unp_abort(unp)
    816 	struct unpcb *unp;
    817 {
    818 
    819 	unp_detach(unp);
    820 }
    821 #endif
    822 
    823 void
    824 unp_shutdown(unp)
    825 	struct unpcb *unp;
    826 {
    827 	struct socket *so;
    828 
    829 	if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
    830 	    (so = unp->unp_conn->unp_socket))
    831 		socantrcvmore(so);
    832 }
    833 
    834 void
    835 unp_drop(unp, errno)
    836 	struct unpcb *unp;
    837 	int errno;
    838 {
    839 	struct socket *so = unp->unp_socket;
    840 
    841 	so->so_error = errno;
    842 	unp_disconnect(unp);
    843 	if (so->so_head) {
    844 		so->so_pcb = 0;
    845 		sofree(so);
    846 		if (unp->unp_addr)
    847 			free(unp->unp_addr, M_SONAME);
    848 		free(unp, M_PCB);
    849 	}
    850 }
    851 
    852 #ifdef notdef
    853 unp_drain()
    854 {
    855 
    856 }
    857 #endif
    858 
    859 int
    860 unp_externalize(rights)
    861 	struct mbuf *rights;
    862 {
    863 	struct proc *p = curproc;		/* XXX */
    864 	struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
    865 	int i, *fdp;
    866 	struct file **rp;
    867 	struct file *fp;
    868 	int nfds, error = 0;
    869 
    870 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
    871 	    sizeof(struct file *);
    872 	rp = (struct file **)CMSG_DATA(cm);
    873 
    874 	fdp = malloc(nfds * sizeof(int), M_TEMP, M_WAITOK);
    875 
    876 	/* Make sure the recipient should be able to see the descriptors.. */
    877 	if (p->p_cwdi->cwdi_rdir != NULL) {
    878 		rp = (struct file **)CMSG_DATA(cm);
    879 		for (i = 0; i < nfds; i++) {
    880 			fp = *rp++;
    881 			/*
    882 			 * If we are in a chroot'ed directory, and
    883 			 * someone wants to pass us a directory, make
    884 			 * sure it's inside the subtree we're allowed
    885 			 * to access.
    886 			 */
    887 			if (fp->f_type == DTYPE_VNODE) {
    888 				struct vnode *vp = (struct vnode *)fp->f_data;
    889 				if ((vp->v_type == VDIR) &&
    890 				    !vn_isunder(vp, p->p_cwdi->cwdi_rdir, p)) {
    891 					error = EPERM;
    892 					break;
    893 				}
    894 			}
    895 		}
    896 	}
    897 
    898  restart:
    899 	rp = (struct file **)CMSG_DATA(cm);
    900 	if (error != 0) {
    901 		for (i = 0; i < nfds; i++) {
    902 			fp = *rp;
    903 			/*
    904 			 * zero the pointer before calling unp_discard,
    905 			 * since it may end up in unp_gc()..
    906 			 */
    907 			*rp++ = 0;
    908 			unp_discard(fp);
    909 		}
    910 		goto out;
    911 	}
    912 
    913 	/*
    914 	 * First loop -- allocate file descriptor table slots for the
    915 	 * new descriptors.
    916 	 */
    917 	for (i = 0; i < nfds; i++) {
    918 		fp = *rp++;
    919 		if ((error = fdalloc(p, 0, &fdp[i])) != 0) {
    920 			/*
    921 			 * Back out what we've done so far.
    922 			 */
    923 			for (--i; i >= 0; i--)
    924 				fdremove(p->p_fd, fdp[i]);
    925 
    926 			if (error == ENOSPC) {
    927 				fdexpand(p);
    928 				error = 0;
    929 			} else {
    930 				/*
    931 				 * This is the error that has historically
    932 				 * been returned, and some callers may
    933 				 * expect it.
    934 				 */
    935 				error = EMSGSIZE;
    936 			}
    937 			goto restart;
    938 		}
    939 
    940 		/*
    941 		 * Make the slot reference the descriptor so that
    942 		 * fdalloc() works properly.. We finalize it all
    943 		 * in the loop below.
    944 		 */
    945 		p->p_fd->fd_ofiles[fdp[i]] = fp;
    946 	}
    947 
    948 	/*
    949 	 * Now that adding them has succeeded, update all of the
    950 	 * descriptor passing state.
    951 	 */
    952 	rp = (struct file **)CMSG_DATA(cm);
    953 	for (i = 0; i < nfds; i++) {
    954 		fp = *rp++;
    955 		fp->f_msgcount--;
    956 		unp_rights--;
    957 	}
    958 
    959 	/*
    960 	 * Copy temporary array to message and adjust length, in case of
    961 	 * transition from large struct file pointers to ints.
    962 	 */
    963 	memcpy(CMSG_DATA(cm), fdp, nfds * sizeof(int));
    964 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
    965 	rights->m_len = CMSG_SPACE(nfds * sizeof(int));
    966  out:
    967 	free(fdp, M_TEMP);
    968 	return (error);
    969 }
    970 
    971 int
    972 unp_internalize(control, p)
    973 	struct mbuf *control;
    974 	struct proc *p;
    975 {
    976 	struct filedesc *fdescp = p->p_fd;
    977 	struct cmsghdr *newcm, *cm = mtod(control, struct cmsghdr *);
    978 	struct file **rp, **files;
    979 	struct file *fp;
    980 	int i, fd, *fdp;
    981 	int nfds;
    982 	u_int neededspace;
    983 
    984 	/* Sanity check the control message header */
    985 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
    986 	    cm->cmsg_len != control->m_len)
    987 		return (EINVAL);
    988 
    989 	/* Verify that the file descriptors are valid */
    990 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof(int);
    991 	fdp = (int *)CMSG_DATA(cm);
    992 	for (i = 0; i < nfds; i++) {
    993 		fd = *fdp++;
    994 		if ((fp = fd_getfile(fdescp, fd)) == NULL)
    995 			return (EBADF);
    996 		simple_unlock(&fp->f_slock);
    997 	}
    998 
    999 	/* Make sure we have room for the struct file pointers */
   1000 	neededspace = CMSG_SPACE(nfds * sizeof(struct file *)) -
   1001 	    control->m_len;
   1002 	if (neededspace > M_TRAILINGSPACE(control)) {
   1003 
   1004 		/* allocate new space and copy header into it */
   1005 		newcm = malloc(
   1006 		    CMSG_SPACE(nfds * sizeof(struct file *)),
   1007 		    M_MBUF, M_WAITOK);
   1008 		if (newcm == NULL)
   1009 			return (E2BIG);
   1010 		memcpy(newcm, cm, sizeof(struct cmsghdr));
   1011 		files = (struct file **)CMSG_DATA(newcm);
   1012 	} else {
   1013 		/* we can convert in-place */
   1014 		newcm = NULL;
   1015 		files = (struct file **)CMSG_DATA(cm);
   1016 	}
   1017 
   1018 	/*
   1019 	 * Transform the file descriptors into struct file pointers, in
   1020 	 * reverse order so that if pointers are bigger than ints, the
   1021 	 * int won't get until we're done.
   1022 	 */
   1023 	fdp = (int *)CMSG_DATA(cm) + nfds - 1;
   1024 	rp = files + nfds - 1;
   1025 	for (i = 0; i < nfds; i++) {
   1026 		fp = fdescp->fd_ofiles[*fdp--];
   1027 		simple_lock(&fp->f_slock);
   1028 #ifdef DIAGNOSTIC
   1029 		if (fp->f_iflags & FIF_WANTCLOSE)
   1030 			panic("unp_internalize: file already closed");
   1031 #endif
   1032 		*rp-- = fp;
   1033 		fp->f_count++;
   1034 		fp->f_msgcount++;
   1035 		simple_unlock(&fp->f_slock);
   1036 		unp_rights++;
   1037 	}
   1038 
   1039 	if (newcm) {
   1040 		if (control->m_flags & M_EXT)
   1041 			MEXTREMOVE(control);
   1042 		MEXTADD(control, newcm,
   1043 		    CMSG_SPACE(nfds * sizeof(struct file *)),
   1044 		    M_MBUF, NULL, NULL);
   1045 		cm = newcm;
   1046 	}
   1047 
   1048 	/* adjust message & mbuf to note amount of space actually used. */
   1049 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(struct file *));
   1050 	control->m_len = CMSG_SPACE(nfds * sizeof(struct file *));
   1051 
   1052 	return (0);
   1053 }
   1054 
   1055 struct mbuf *
   1056 unp_addsockcred(p, control)
   1057 	struct proc *p;
   1058 	struct mbuf *control;
   1059 {
   1060 	struct cmsghdr *cmp;
   1061 	struct sockcred *sc;
   1062 	struct mbuf *m, *n;
   1063 	int len, space, i;
   1064 
   1065 	len = CMSG_LEN(SOCKCREDSIZE(p->p_ucred->cr_ngroups));
   1066 	space = CMSG_SPACE(SOCKCREDSIZE(p->p_ucred->cr_ngroups));
   1067 
   1068 	m = m_get(M_WAIT, MT_CONTROL);
   1069 	if (space > MLEN) {
   1070 		if (space > MCLBYTES)
   1071 			MEXTMALLOC(m, space, M_WAITOK);
   1072 		else
   1073 			m_clget(m, M_WAIT);
   1074 		if ((m->m_flags & M_EXT) == 0) {
   1075 			m_free(m);
   1076 			return (control);
   1077 		}
   1078 	}
   1079 
   1080 	m->m_len = space;
   1081 	m->m_next = NULL;
   1082 	cmp = mtod(m, struct cmsghdr *);
   1083 	sc = (struct sockcred *)CMSG_DATA(cmp);
   1084 	cmp->cmsg_len = len;
   1085 	cmp->cmsg_level = SOL_SOCKET;
   1086 	cmp->cmsg_type = SCM_CREDS;
   1087 	sc->sc_uid = p->p_cred->p_ruid;
   1088 	sc->sc_euid = p->p_ucred->cr_uid;
   1089 	sc->sc_gid = p->p_cred->p_rgid;
   1090 	sc->sc_egid = p->p_ucred->cr_gid;
   1091 	sc->sc_ngroups = p->p_ucred->cr_ngroups;
   1092 	for (i = 0; i < sc->sc_ngroups; i++)
   1093 		sc->sc_groups[i] = p->p_ucred->cr_groups[i];
   1094 
   1095 	/*
   1096 	 * If a control message already exists, append us to the end.
   1097 	 */
   1098 	if (control != NULL) {
   1099 		for (n = control; n->m_next != NULL; n = n->m_next)
   1100 			;
   1101 		n->m_next = m;
   1102 	} else
   1103 		control = m;
   1104 
   1105 	return (control);
   1106 }
   1107 
   1108 int	unp_defer, unp_gcing;
   1109 extern	struct domain unixdomain;
   1110 
   1111 /*
   1112  * Comment added long after the fact explaining what's going on here.
   1113  * Do a mark-sweep GC of file descriptors on the system, to free up
   1114  * any which are caught in flight to an about-to-be-closed socket.
   1115  *
   1116  * Traditional mark-sweep gc's start at the "root", and mark
   1117  * everything reachable from the root (which, in our case would be the
   1118  * process table).  The mark bits are cleared during the sweep.
   1119  *
   1120  * XXX For some inexplicable reason (perhaps because the file
   1121  * descriptor tables used to live in the u area which could be swapped
   1122  * out and thus hard to reach), we do multiple scans over the set of
   1123  * descriptors, using use *two* mark bits per object (DEFER and MARK).
   1124  * Whenever we find a descriptor which references other descriptors,
   1125  * the ones it references are marked with both bits, and we iterate
   1126  * over the whole file table until there are no more DEFER bits set.
   1127  * We also make an extra pass *before* the GC to clear the mark bits,
   1128  * which could have been cleared at almost no cost during the previous
   1129  * sweep.
   1130  *
   1131  * XXX MP: this needs to run with locks such that no other thread of
   1132  * control can create or destroy references to file descriptors. it
   1133  * may be necessary to defer the GC until later (when the locking
   1134  * situation is more hospitable); it may be necessary to push this
   1135  * into a separate thread.
   1136  */
   1137 void
   1138 unp_gc()
   1139 {
   1140 	struct file *fp, *nextfp;
   1141 	struct socket *so, *so1;
   1142 	struct file **extra_ref, **fpp;
   1143 	int nunref, i;
   1144 
   1145 	if (unp_gcing)
   1146 		return;
   1147 	unp_gcing = 1;
   1148 	unp_defer = 0;
   1149 
   1150 	/* Clear mark bits */
   1151 	LIST_FOREACH(fp, &filehead, f_list)
   1152 		fp->f_flag &= ~(FMARK|FDEFER);
   1153 
   1154 	/*
   1155 	 * Iterate over the set of descriptors, marking ones believed
   1156 	 * (based on refcount) to be referenced from a process, and
   1157 	 * marking for rescan descriptors which are queued on a socket.
   1158 	 */
   1159 	do {
   1160 		LIST_FOREACH(fp, &filehead, f_list) {
   1161 			if (fp->f_flag & FDEFER) {
   1162 				fp->f_flag &= ~FDEFER;
   1163 				unp_defer--;
   1164 #ifdef DIAGNOSTIC
   1165 				if (fp->f_count == 0)
   1166 					panic("unp_gc: deferred unreferenced socket");
   1167 #endif
   1168 			} else {
   1169 				if (fp->f_count == 0)
   1170 					continue;
   1171 				if (fp->f_flag & FMARK)
   1172 					continue;
   1173 				if (fp->f_count == fp->f_msgcount)
   1174 					continue;
   1175 			}
   1176 			fp->f_flag |= FMARK;
   1177 
   1178 			if (fp->f_type != DTYPE_SOCKET ||
   1179 			    (so = (struct socket *)fp->f_data) == 0)
   1180 				continue;
   1181 			if (so->so_proto->pr_domain != &unixdomain ||
   1182 			    (so->so_proto->pr_flags&PR_RIGHTS) == 0)
   1183 				continue;
   1184 #ifdef notdef
   1185 			if (so->so_rcv.sb_flags & SB_LOCK) {
   1186 				/*
   1187 				 * This is problematical; it's not clear
   1188 				 * we need to wait for the sockbuf to be
   1189 				 * unlocked (on a uniprocessor, at least),
   1190 				 * and it's also not clear what to do
   1191 				 * if sbwait returns an error due to receipt
   1192 				 * of a signal.  If sbwait does return
   1193 				 * an error, we'll go into an infinite
   1194 				 * loop.  Delete all of this for now.
   1195 				 */
   1196 				(void) sbwait(&so->so_rcv);
   1197 				goto restart;
   1198 			}
   1199 #endif
   1200 			unp_scan(so->so_rcv.sb_mb, unp_mark, 0);
   1201 			/*
   1202 			 * mark descriptors referenced from sockets queued on the accept queue as well.
   1203 			 */
   1204 			if (so->so_options & SO_ACCEPTCONN) {
   1205 				TAILQ_FOREACH(so1, &so->so_q0, so_qe) {
   1206 					unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
   1207 				}
   1208 				TAILQ_FOREACH(so1, &so->so_q, so_qe) {
   1209 					unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
   1210 				}
   1211 			}
   1212 
   1213 		}
   1214 	} while (unp_defer);
   1215 	/*
   1216 	 * Sweep pass.  Find unmarked descriptors, and free them.
   1217 	 *
   1218 	 * We grab an extra reference to each of the file table entries
   1219 	 * that are not otherwise accessible and then free the rights
   1220 	 * that are stored in messages on them.
   1221 	 *
   1222 	 * The bug in the original code is a little tricky, so I'll describe
   1223 	 * what's wrong with it here.
   1224 	 *
   1225 	 * It is incorrect to simply unp_discard each entry for f_msgcount
   1226 	 * times -- consider the case of sockets A and B that contain
   1227 	 * references to each other.  On a last close of some other socket,
   1228 	 * we trigger a gc since the number of outstanding rights (unp_rights)
   1229 	 * is non-zero.  If during the sweep phase the gc code un_discards,
   1230 	 * we end up doing a (full) closef on the descriptor.  A closef on A
   1231 	 * results in the following chain.  Closef calls soo_close, which
   1232 	 * calls soclose.   Soclose calls first (through the switch
   1233 	 * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
   1234 	 * returns because the previous instance had set unp_gcing, and
   1235 	 * we return all the way back to soclose, which marks the socket
   1236 	 * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
   1237 	 * to free up the rights that are queued in messages on the socket A,
   1238 	 * i.e., the reference on B.  The sorflush calls via the dom_dispose
   1239 	 * switch unp_dispose, which unp_scans with unp_discard.  This second
   1240 	 * instance of unp_discard just calls closef on B.
   1241 	 *
   1242 	 * Well, a similar chain occurs on B, resulting in a sorflush on B,
   1243 	 * which results in another closef on A.  Unfortunately, A is already
   1244 	 * being closed, and the descriptor has already been marked with
   1245 	 * SS_NOFDREF, and soclose panics at this point.
   1246 	 *
   1247 	 * Here, we first take an extra reference to each inaccessible
   1248 	 * descriptor.  Then, if the inaccessible descriptor is a
   1249 	 * socket, we call sorflush in case it is a Unix domain
   1250 	 * socket.  After we destroy all the rights carried in
   1251 	 * messages, we do a last closef to get rid of our extra
   1252 	 * reference.  This is the last close, and the unp_detach etc
   1253 	 * will shut down the socket.
   1254 	 *
   1255 	 * 91/09/19, bsy (at) cs.cmu.edu
   1256 	 */
   1257 	extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
   1258 	for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref; fp != 0;
   1259 	    fp = nextfp) {
   1260 		nextfp = LIST_NEXT(fp, f_list);
   1261 		simple_lock(&fp->f_slock);
   1262 		if (fp->f_count != 0 &&
   1263 		    fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
   1264 			*fpp++ = fp;
   1265 			nunref++;
   1266 			fp->f_count++;
   1267 		}
   1268 		simple_unlock(&fp->f_slock);
   1269 	}
   1270 	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
   1271 		fp = *fpp;
   1272 		simple_lock(&fp->f_slock);
   1273 		FILE_USE(fp);
   1274 		if (fp->f_type == DTYPE_SOCKET)
   1275 			sorflush((struct socket *)fp->f_data);
   1276 		FILE_UNUSE(fp, NULL);
   1277 	}
   1278 	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
   1279 		fp = *fpp;
   1280 		simple_lock(&fp->f_slock);
   1281 		FILE_USE(fp);
   1282 		(void) closef(fp, (struct proc *)0);
   1283 	}
   1284 	free((caddr_t)extra_ref, M_FILE);
   1285 	unp_gcing = 0;
   1286 }
   1287 
   1288 void
   1289 unp_dispose(m)
   1290 	struct mbuf *m;
   1291 {
   1292 
   1293 	if (m)
   1294 		unp_scan(m, unp_discard, 1);
   1295 }
   1296 
   1297 void
   1298 unp_scan(m0, op, discard)
   1299 	struct mbuf *m0;
   1300 	void (*op) __P((struct file *));
   1301 	int discard;
   1302 {
   1303 	struct mbuf *m;
   1304 	struct file **rp;
   1305 	struct cmsghdr *cm;
   1306 	int i;
   1307 	int qfds;
   1308 
   1309 	while (m0) {
   1310 		for (m = m0; m; m = m->m_next) {
   1311 			if (m->m_type == MT_CONTROL &&
   1312 			    m->m_len >= sizeof(*cm)) {
   1313 				cm = mtod(m, struct cmsghdr *);
   1314 				if (cm->cmsg_level != SOL_SOCKET ||
   1315 				    cm->cmsg_type != SCM_RIGHTS)
   1316 					continue;
   1317 				qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm)))
   1318 				    / sizeof(struct file *);
   1319 				rp = (struct file **)CMSG_DATA(cm);
   1320 				for (i = 0; i < qfds; i++) {
   1321 					struct file *fp = *rp;
   1322 					if (discard)
   1323 						*rp = 0;
   1324 					(*op)(fp);
   1325 					rp++;
   1326 				}
   1327 				break;		/* XXX, but saves time */
   1328 			}
   1329 		}
   1330 		m0 = m0->m_nextpkt;
   1331 	}
   1332 }
   1333 
   1334 void
   1335 unp_mark(fp)
   1336 	struct file *fp;
   1337 {
   1338 	if (fp == NULL)
   1339 		return;
   1340 
   1341 	if (fp->f_flag & FMARK)
   1342 		return;
   1343 
   1344 	/* If we're already deferred, don't screw up the defer count */
   1345 	if (fp->f_flag & FDEFER)
   1346 		return;
   1347 
   1348 	/*
   1349 	 * Minimize the number of deferrals...  Sockets are the only
   1350 	 * type of descriptor which can hold references to another
   1351 	 * descriptor, so just mark other descriptors, and defer
   1352 	 * unmarked sockets for the next pass.
   1353 	 */
   1354 	if (fp->f_type == DTYPE_SOCKET) {
   1355 		unp_defer++;
   1356 		if (fp->f_count == 0)
   1357 			panic("unp_mark: queued unref");
   1358 		fp->f_flag |= FDEFER;
   1359 	} else {
   1360 		fp->f_flag |= FMARK;
   1361 	}
   1362 	return;
   1363 }
   1364 
   1365 void
   1366 unp_discard(fp)
   1367 	struct file *fp;
   1368 {
   1369 	if (fp == NULL)
   1370 		return;
   1371 	simple_lock(&fp->f_slock);
   1372 	fp->f_usecount++;	/* i.e. FILE_USE(fp) sans locking */
   1373 	fp->f_msgcount--;
   1374 	simple_unlock(&fp->f_slock);
   1375 	unp_rights--;
   1376 	(void) closef(fp, (struct proc *)0);
   1377 }
   1378