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