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