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