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