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