Home | History | Annotate | Line # | Download | only in kern
uipc_usrreq.c revision 1.173
      1 /*	$NetBSD: uipc_usrreq.c,v 1.173 2015/02/02 02:28:26 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 2000, 2004, 2008, 2009 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, and by Andrew Doran.
     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  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Copyright (c) 1982, 1986, 1989, 1991, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  * 3. Neither the name of the University nor the names of its contributors
     46  *    may be used to endorse or promote products derived from this software
     47  *    without specific prior written permission.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     59  * SUCH DAMAGE.
     60  *
     61  *	@(#)uipc_usrreq.c	8.9 (Berkeley) 5/14/95
     62  */
     63 
     64 /*
     65  * Copyright (c) 1997 Christopher G. Demetriou.  All rights reserved.
     66  *
     67  * Redistribution and use in source and binary forms, with or without
     68  * modification, are permitted provided that the following conditions
     69  * are met:
     70  * 1. Redistributions of source code must retain the above copyright
     71  *    notice, this list of conditions and the following disclaimer.
     72  * 2. Redistributions in binary form must reproduce the above copyright
     73  *    notice, this list of conditions and the following disclaimer in the
     74  *    documentation and/or other materials provided with the distribution.
     75  * 3. All advertising materials mentioning features or use of this software
     76  *    must display the following acknowledgement:
     77  *	This product includes software developed by the University of
     78  *	California, Berkeley and its contributors.
     79  * 4. Neither the name of the University nor the names of its contributors
     80  *    may be used to endorse or promote products derived from this software
     81  *    without specific prior written permission.
     82  *
     83  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     84  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     85  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     86  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     87  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     88  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     89  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     90  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     91  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     92  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     93  * SUCH DAMAGE.
     94  *
     95  *	@(#)uipc_usrreq.c	8.9 (Berkeley) 5/14/95
     96  */
     97 
     98 #include <sys/cdefs.h>
     99 __KERNEL_RCSID(0, "$NetBSD: uipc_usrreq.c,v 1.173 2015/02/02 02:28:26 christos Exp $");
    100 
    101 #include <sys/param.h>
    102 #include <sys/systm.h>
    103 #include <sys/proc.h>
    104 #include <sys/filedesc.h>
    105 #include <sys/domain.h>
    106 #include <sys/protosw.h>
    107 #include <sys/socket.h>
    108 #include <sys/socketvar.h>
    109 #include <sys/unpcb.h>
    110 #include <sys/un.h>
    111 #include <sys/namei.h>
    112 #include <sys/vnode.h>
    113 #include <sys/file.h>
    114 #include <sys/stat.h>
    115 #include <sys/mbuf.h>
    116 #include <sys/kauth.h>
    117 #include <sys/kmem.h>
    118 #include <sys/atomic.h>
    119 #include <sys/uidinfo.h>
    120 #include <sys/kernel.h>
    121 #include <sys/kthread.h>
    122 
    123 /*
    124  * Unix communications domain.
    125  *
    126  * TODO:
    127  *	RDM
    128  *	rethink name space problems
    129  *	need a proper out-of-band
    130  *
    131  * Notes on locking:
    132  *
    133  * The generic rules noted in uipc_socket2.c apply.  In addition:
    134  *
    135  * o We have a global lock, uipc_lock.
    136  *
    137  * o All datagram sockets are locked by uipc_lock.
    138  *
    139  * o For stream socketpairs, the two endpoints are created sharing the same
    140  *   independent lock.  Sockets presented to PRU_CONNECT2 must already have
    141  *   matching locks.
    142  *
    143  * o Stream sockets created via socket() start life with their own
    144  *   independent lock.
    145  *
    146  * o Stream connections to a named endpoint are slightly more complicated.
    147  *   Sockets that have called listen() have their lock pointer mutated to
    148  *   the global uipc_lock.  When establishing a connection, the connecting
    149  *   socket also has its lock mutated to uipc_lock, which matches the head
    150  *   (listening socket).  We create a new socket for accept() to return, and
    151  *   that also shares the head's lock.  Until the connection is completely
    152  *   done on both ends, all three sockets are locked by uipc_lock.  Once the
    153  *   connection is complete, the association with the head's lock is broken.
    154  *   The connecting socket and the socket returned from accept() have their
    155  *   lock pointers mutated away from uipc_lock, and back to the connecting
    156  *   socket's original, independent lock.  The head continues to be locked
    157  *   by uipc_lock.
    158  *
    159  * o If uipc_lock is determined to be a significant source of contention,
    160  *   it could easily be hashed out.  It is difficult to simply make it an
    161  *   independent lock because of visibility / garbage collection issues:
    162  *   if a socket has been associated with a lock at any point, that lock
    163  *   must remain valid until the socket is no longer visible in the system.
    164  *   The lock must not be freed or otherwise destroyed until any sockets
    165  *   that had referenced it have also been destroyed.
    166  */
    167 const struct sockaddr_un sun_noname = {
    168 	.sun_len = offsetof(struct sockaddr_un, sun_path),
    169 	.sun_family = AF_LOCAL,
    170 };
    171 ino_t	unp_ino;			/* prototype for fake inode numbers */
    172 
    173 static struct mbuf * unp_addsockcred(struct lwp *, struct mbuf *);
    174 static void   unp_discard_later(file_t *);
    175 static void   unp_discard_now(file_t *);
    176 static void   unp_disconnect1(struct unpcb *);
    177 static bool   unp_drop(struct unpcb *, int);
    178 static int    unp_internalize(struct mbuf **);
    179 static void   unp_mark(file_t *);
    180 static void   unp_scan(struct mbuf *, void (*)(file_t *), int);
    181 static void   unp_shutdown1(struct unpcb *);
    182 static void   unp_thread(void *);
    183 static void   unp_thread_kick(void);
    184 
    185 static kmutex_t *uipc_lock;
    186 
    187 static kcondvar_t unp_thread_cv;
    188 static lwp_t *unp_thread_lwp;
    189 static SLIST_HEAD(,file) unp_thread_discard;
    190 static int unp_defer;
    191 
    192 /*
    193  * Initialize Unix protocols.
    194  */
    195 void
    196 uipc_init(void)
    197 {
    198 	int error;
    199 
    200 	uipc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
    201 	cv_init(&unp_thread_cv, "unpgc");
    202 
    203 	error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL, unp_thread,
    204 	    NULL, &unp_thread_lwp, "unpgc");
    205 	if (error != 0)
    206 		panic("uipc_init %d", error);
    207 }
    208 
    209 /*
    210  * A connection succeeded: disassociate both endpoints from the head's
    211  * lock, and make them share their own lock.  There is a race here: for
    212  * a very brief time one endpoint will be locked by a different lock
    213  * than the other end.  However, since the current thread holds the old
    214  * lock (the listening socket's lock, the head) access can still only be
    215  * made to one side of the connection.
    216  */
    217 static void
    218 unp_setpeerlocks(struct socket *so, struct socket *so2)
    219 {
    220 	struct unpcb *unp;
    221 	kmutex_t *lock;
    222 
    223 	KASSERT(solocked2(so, so2));
    224 
    225 	/*
    226 	 * Bail out if either end of the socket is not yet fully
    227 	 * connected or accepted.  We only break the lock association
    228 	 * with the head when the pair of sockets stand completely
    229 	 * on their own.
    230 	 */
    231 	KASSERT(so->so_head == NULL);
    232 	if (so2->so_head != NULL)
    233 		return;
    234 
    235 	/*
    236 	 * Drop references to old lock.  A third reference (from the
    237 	 * queue head) must be held as we still hold its lock.  Bonus:
    238 	 * we don't need to worry about garbage collecting the lock.
    239 	 */
    240 	lock = so->so_lock;
    241 	KASSERT(lock == uipc_lock);
    242 	mutex_obj_free(lock);
    243 	mutex_obj_free(lock);
    244 
    245 	/*
    246 	 * Grab stream lock from the initiator and share between the two
    247 	 * endpoints.  Issue memory barrier to ensure all modifications
    248 	 * become globally visible before the lock change.  so2 is
    249 	 * assumed not to have a stream lock, because it was created
    250 	 * purely for the server side to accept this connection and
    251 	 * started out life using the domain-wide lock.
    252 	 */
    253 	unp = sotounpcb(so);
    254 	KASSERT(unp->unp_streamlock != NULL);
    255 	KASSERT(sotounpcb(so2)->unp_streamlock == NULL);
    256 	lock = unp->unp_streamlock;
    257 	unp->unp_streamlock = NULL;
    258 	mutex_obj_hold(lock);
    259 	membar_exit();
    260 	/*
    261 	 * possible race if lock is not held - see comment in
    262 	 * uipc_usrreq(PRU_ACCEPT).
    263 	 */
    264 	KASSERT(mutex_owned(lock));
    265 	solockreset(so, lock);
    266 	solockreset(so2, lock);
    267 }
    268 
    269 /*
    270  * Reset a socket's lock back to the domain-wide lock.
    271  */
    272 static void
    273 unp_resetlock(struct socket *so)
    274 {
    275 	kmutex_t *olock, *nlock;
    276 	struct unpcb *unp;
    277 
    278 	KASSERT(solocked(so));
    279 
    280 	olock = so->so_lock;
    281 	nlock = uipc_lock;
    282 	if (olock == nlock)
    283 		return;
    284 	unp = sotounpcb(so);
    285 	KASSERT(unp->unp_streamlock == NULL);
    286 	unp->unp_streamlock = olock;
    287 	mutex_obj_hold(nlock);
    288 	mutex_enter(nlock);
    289 	solockreset(so, nlock);
    290 	mutex_exit(olock);
    291 }
    292 
    293 static void
    294 unp_free(struct unpcb *unp)
    295 {
    296 	if (unp->unp_addr)
    297 		free(unp->unp_addr, M_SONAME);
    298 	if (unp->unp_streamlock != NULL)
    299 		mutex_obj_free(unp->unp_streamlock);
    300 	kmem_free(unp, sizeof(*unp));
    301 }
    302 
    303 static int
    304 unp_output(struct mbuf *m, struct mbuf *control, struct unpcb *unp)
    305 {
    306 	struct socket *so2;
    307 	const struct sockaddr_un *sun;
    308 
    309 	/* XXX: server side closed the socket */
    310 	if (unp->unp_conn == NULL)
    311 		return ECONNREFUSED;
    312 	so2 = unp->unp_conn->unp_socket;
    313 
    314 	KASSERT(solocked(so2));
    315 
    316 	if (unp->unp_addr)
    317 		sun = unp->unp_addr;
    318 	else
    319 		sun = &sun_noname;
    320 	if (unp->unp_conn->unp_flags & UNP_WANTCRED)
    321 		control = unp_addsockcred(curlwp, control);
    322 	if (sbappendaddr(&so2->so_rcv, (const struct sockaddr *)sun, m,
    323 	    control) == 0) {
    324 		so2->so_rcv.sb_overflowed++;
    325 		unp_dispose(control);
    326 		m_freem(control);
    327 		m_freem(m);
    328 		return (ENOBUFS);
    329 	} else {
    330 		sorwakeup(so2);
    331 		return (0);
    332 	}
    333 }
    334 
    335 static void
    336 unp_setaddr(struct socket *so, struct mbuf *nam, bool peeraddr)
    337 {
    338 	const struct sockaddr_un *sun;
    339 	struct unpcb *unp;
    340 	bool ext;
    341 
    342 	KASSERT(solocked(so));
    343 	unp = sotounpcb(so);
    344 	ext = false;
    345 
    346 	for (;;) {
    347 		sun = NULL;
    348 		if (peeraddr) {
    349 			if (unp->unp_conn && unp->unp_conn->unp_addr)
    350 				sun = unp->unp_conn->unp_addr;
    351 		} else {
    352 			if (unp->unp_addr)
    353 				sun = unp->unp_addr;
    354 		}
    355 		if (sun == NULL)
    356 			sun = &sun_noname;
    357 		nam->m_len = sun->sun_len;
    358 		if (nam->m_len > MLEN && !ext) {
    359 			sounlock(so);
    360 			MEXTMALLOC(nam, MAXPATHLEN * 2, M_WAITOK);
    361 			solock(so);
    362 			ext = true;
    363 		} else {
    364 			KASSERT(nam->m_len <= MAXPATHLEN * 2);
    365 			memcpy(mtod(nam, void *), sun, (size_t)nam->m_len);
    366 			break;
    367 		}
    368 	}
    369 }
    370 
    371 static int
    372 unp_rcvd(struct socket *so, int flags, struct lwp *l)
    373 {
    374 	struct unpcb *unp = sotounpcb(so);
    375 	struct socket *so2;
    376 	u_int newhiwat;
    377 
    378 	KASSERT(solocked(so));
    379 	KASSERT(unp != NULL);
    380 
    381 	switch (so->so_type) {
    382 
    383 	case SOCK_DGRAM:
    384 		panic("uipc 1");
    385 		/*NOTREACHED*/
    386 
    387 	case SOCK_SEQPACKET: /* FALLTHROUGH */
    388 	case SOCK_STREAM:
    389 #define	rcv (&so->so_rcv)
    390 #define snd (&so2->so_snd)
    391 		if (unp->unp_conn == 0)
    392 			break;
    393 		so2 = unp->unp_conn->unp_socket;
    394 		KASSERT(solocked2(so, so2));
    395 		/*
    396 		 * Adjust backpressure on sender
    397 		 * and wakeup any waiting to write.
    398 		 */
    399 		snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt;
    400 		unp->unp_mbcnt = rcv->sb_mbcnt;
    401 		newhiwat = snd->sb_hiwat + unp->unp_cc - rcv->sb_cc;
    402 		(void)chgsbsize(so2->so_uidinfo,
    403 		    &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
    404 		unp->unp_cc = rcv->sb_cc;
    405 		sowwakeup(so2);
    406 #undef snd
    407 #undef rcv
    408 		break;
    409 
    410 	default:
    411 		panic("uipc 2");
    412 	}
    413 
    414 	return 0;
    415 }
    416 
    417 static int
    418 unp_recvoob(struct socket *so, struct mbuf *m, int flags)
    419 {
    420 	KASSERT(solocked(so));
    421 
    422 	return EOPNOTSUPP;
    423 }
    424 
    425 static int
    426 unp_send(struct socket *so, struct mbuf *m, struct mbuf *nam,
    427     struct mbuf *control, struct lwp *l)
    428 {
    429 	struct unpcb *unp = sotounpcb(so);
    430 	int error = 0;
    431 	u_int newhiwat;
    432 	struct socket *so2;
    433 
    434 	KASSERT(solocked(so));
    435 	KASSERT(unp != NULL);
    436 	KASSERT(m != NULL);
    437 
    438 	/*
    439 	 * Note: unp_internalize() rejects any control message
    440 	 * other than SCM_RIGHTS, and only allows one.  This
    441 	 * has the side-effect of preventing a caller from
    442 	 * forging SCM_CREDS.
    443 	 */
    444 	if (control) {
    445 		sounlock(so);
    446 		error = unp_internalize(&control);
    447 		solock(so);
    448 		if (error != 0) {
    449 			m_freem(control);
    450 			m_freem(m);
    451 			return error;
    452 		}
    453 	}
    454 
    455 	switch (so->so_type) {
    456 
    457 	case SOCK_DGRAM: {
    458 		KASSERT(so->so_lock == uipc_lock);
    459 		if (nam) {
    460 			if ((so->so_state & SS_ISCONNECTED) != 0)
    461 				error = EISCONN;
    462 			else {
    463 				/*
    464 				 * Note: once connected, the
    465 				 * socket's lock must not be
    466 				 * dropped until we have sent
    467 				 * the message and disconnected.
    468 				 * This is necessary to prevent
    469 				 * intervening control ops, like
    470 				 * another connection.
    471 				 */
    472 				error = unp_connect(so, nam, l);
    473 			}
    474 		} else {
    475 			if ((so->so_state & SS_ISCONNECTED) == 0)
    476 				error = ENOTCONN;
    477 		}
    478 		if (error) {
    479 			unp_dispose(control);
    480 			m_freem(control);
    481 			m_freem(m);
    482 			return error;
    483 		}
    484 		error = unp_output(m, control, unp);
    485 		if (nam)
    486 			unp_disconnect1(unp);
    487 		break;
    488 	}
    489 
    490 	case SOCK_SEQPACKET: /* FALLTHROUGH */
    491 	case SOCK_STREAM:
    492 #define	rcv (&so2->so_rcv)
    493 #define	snd (&so->so_snd)
    494 		if (unp->unp_conn == NULL) {
    495 			error = ENOTCONN;
    496 			break;
    497 		}
    498 		so2 = unp->unp_conn->unp_socket;
    499 		KASSERT(solocked2(so, so2));
    500 		if (unp->unp_conn->unp_flags & UNP_WANTCRED) {
    501 			/*
    502 			 * Credentials are passed only once on
    503 			 * SOCK_STREAM and SOCK_SEQPACKET.
    504 			 */
    505 			unp->unp_conn->unp_flags &= ~UNP_WANTCRED;
    506 			control = unp_addsockcred(l, control);
    507 		}
    508 		/*
    509 		 * Send to paired receive port, and then reduce
    510 		 * send buffer hiwater marks to maintain backpressure.
    511 		 * Wake up readers.
    512 		 */
    513 		if (control) {
    514 			if (sbappendcontrol(rcv, m, control) != 0)
    515 				control = NULL;
    516 		} else {
    517 			switch(so->so_type) {
    518 			case SOCK_SEQPACKET:
    519 				sbappendrecord(rcv, m);
    520 				break;
    521 			case SOCK_STREAM:
    522 				sbappend(rcv, m);
    523 				break;
    524 			default:
    525 				panic("uipc_usrreq");
    526 				break;
    527 			}
    528 		}
    529 		snd->sb_mbmax -=
    530 		    rcv->sb_mbcnt - unp->unp_conn->unp_mbcnt;
    531 		unp->unp_conn->unp_mbcnt = rcv->sb_mbcnt;
    532 		newhiwat = snd->sb_hiwat -
    533 		    (rcv->sb_cc - unp->unp_conn->unp_cc);
    534 		(void)chgsbsize(so->so_uidinfo,
    535 		    &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
    536 		unp->unp_conn->unp_cc = rcv->sb_cc;
    537 		sorwakeup(so2);
    538 #undef snd
    539 #undef rcv
    540 		if (control != NULL) {
    541 			unp_dispose(control);
    542 			m_freem(control);
    543 		}
    544 		break;
    545 
    546 	default:
    547 		panic("uipc 4");
    548 	}
    549 
    550 	return error;
    551 }
    552 
    553 static int
    554 unp_sendoob(struct socket *so, struct mbuf *m, struct mbuf * control)
    555 {
    556 	KASSERT(solocked(so));
    557 
    558 	m_freem(m);
    559 	m_freem(control);
    560 
    561 	return EOPNOTSUPP;
    562 }
    563 
    564 static int
    565 unp_usrreq(struct socket *so, int req, struct mbuf *m, struct mbuf *nam,
    566     struct mbuf *control, struct lwp *l)
    567 {
    568 
    569 	KASSERT(req != PRU_ATTACH);
    570 	KASSERT(req != PRU_DETACH);
    571 	KASSERT(req != PRU_ACCEPT);
    572 	KASSERT(req != PRU_BIND);
    573 	KASSERT(req != PRU_LISTEN);
    574 	KASSERT(req != PRU_CONNECT);
    575 	KASSERT(req != PRU_CONNECT2);
    576 	KASSERT(req != PRU_DISCONNECT);
    577 	KASSERT(req != PRU_SHUTDOWN);
    578 	KASSERT(req != PRU_ABORT);
    579 	KASSERT(req != PRU_CONTROL);
    580 	KASSERT(req != PRU_SENSE);
    581 	KASSERT(req != PRU_PEERADDR);
    582 	KASSERT(req != PRU_SOCKADDR);
    583 	KASSERT(req != PRU_RCVD);
    584 	KASSERT(req != PRU_RCVOOB);
    585 	KASSERT(req != PRU_SEND);
    586 	KASSERT(req != PRU_SENDOOB);
    587 	KASSERT(req != PRU_PURGEIF);
    588 
    589 	KASSERT(solocked(so));
    590 
    591 	if (sotounpcb(so) == NULL)
    592 		return EINVAL;
    593 
    594 	panic("piusrreq");
    595 
    596 	return 0;
    597 }
    598 
    599 /*
    600  * Unix domain socket option processing.
    601  */
    602 int
    603 uipc_ctloutput(int op, struct socket *so, struct sockopt *sopt)
    604 {
    605 	struct unpcb *unp = sotounpcb(so);
    606 	int optval = 0, error = 0;
    607 
    608 	KASSERT(solocked(so));
    609 
    610 	if (sopt->sopt_level != 0) {
    611 		error = ENOPROTOOPT;
    612 	} else switch (op) {
    613 
    614 	case PRCO_SETOPT:
    615 		switch (sopt->sopt_name) {
    616 		case LOCAL_CREDS:
    617 		case LOCAL_CONNWAIT:
    618 			error = sockopt_getint(sopt, &optval);
    619 			if (error)
    620 				break;
    621 			switch (sopt->sopt_name) {
    622 #define	OPTSET(bit) \
    623 	if (optval) \
    624 		unp->unp_flags |= (bit); \
    625 	else \
    626 		unp->unp_flags &= ~(bit);
    627 
    628 			case LOCAL_CREDS:
    629 				OPTSET(UNP_WANTCRED);
    630 				break;
    631 			case LOCAL_CONNWAIT:
    632 				OPTSET(UNP_CONNWAIT);
    633 				break;
    634 			}
    635 			break;
    636 #undef OPTSET
    637 
    638 		default:
    639 			error = ENOPROTOOPT;
    640 			break;
    641 		}
    642 		break;
    643 
    644 	case PRCO_GETOPT:
    645 		sounlock(so);
    646 		switch (sopt->sopt_name) {
    647 		case LOCAL_PEEREID:
    648 			if (unp->unp_flags & UNP_EIDSVALID) {
    649 				error = sockopt_set(sopt,
    650 				    &unp->unp_connid, sizeof(unp->unp_connid));
    651 			} else {
    652 				error = EINVAL;
    653 			}
    654 			break;
    655 		case LOCAL_CREDS:
    656 #define	OPTBIT(bit)	(unp->unp_flags & (bit) ? 1 : 0)
    657 
    658 			optval = OPTBIT(UNP_WANTCRED);
    659 			error = sockopt_setint(sopt, optval);
    660 			break;
    661 #undef OPTBIT
    662 
    663 		default:
    664 			error = ENOPROTOOPT;
    665 			break;
    666 		}
    667 		solock(so);
    668 		break;
    669 	}
    670 	return (error);
    671 }
    672 
    673 /*
    674  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
    675  * for stream sockets, although the total for sender and receiver is
    676  * actually only PIPSIZ.
    677  * Datagram sockets really use the sendspace as the maximum datagram size,
    678  * and don't really want to reserve the sendspace.  Their recvspace should
    679  * be large enough for at least one max-size datagram plus address.
    680  */
    681 #define	PIPSIZ	4096
    682 u_long	unpst_sendspace = PIPSIZ;
    683 u_long	unpst_recvspace = PIPSIZ;
    684 u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
    685 u_long	unpdg_recvspace = 4*1024;
    686 
    687 u_int	unp_rights;			/* files in flight */
    688 u_int	unp_rights_ratio = 2;		/* limit, fraction of maxfiles */
    689 
    690 static int
    691 unp_attach(struct socket *so, int proto)
    692 {
    693 	struct unpcb *unp = sotounpcb(so);
    694 	u_long sndspc, rcvspc;
    695 	int error;
    696 
    697 	KASSERT(unp == NULL);
    698 
    699 	switch (so->so_type) {
    700 	case SOCK_SEQPACKET:
    701 		/* FALLTHROUGH */
    702 	case SOCK_STREAM:
    703 		if (so->so_lock == NULL) {
    704 			so->so_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
    705 			solock(so);
    706 		}
    707 		sndspc = unpst_sendspace;
    708 		rcvspc = unpst_recvspace;
    709 		break;
    710 
    711 	case SOCK_DGRAM:
    712 		if (so->so_lock == NULL) {
    713 			mutex_obj_hold(uipc_lock);
    714 			so->so_lock = uipc_lock;
    715 			solock(so);
    716 		}
    717 		sndspc = unpdg_sendspace;
    718 		rcvspc = unpdg_recvspace;
    719 		break;
    720 
    721 	default:
    722 		panic("unp_attach");
    723 	}
    724 
    725 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
    726 		error = soreserve(so, sndspc, rcvspc);
    727 		if (error) {
    728 			return error;
    729 		}
    730 	}
    731 
    732 	unp = kmem_zalloc(sizeof(*unp), KM_SLEEP);
    733 	nanotime(&unp->unp_ctime);
    734 	unp->unp_socket = so;
    735 	so->so_pcb = unp;
    736 
    737 	KASSERT(solocked(so));
    738 	return 0;
    739 }
    740 
    741 static void
    742 unp_detach(struct socket *so)
    743 {
    744 	struct unpcb *unp;
    745 	vnode_t *vp;
    746 
    747 	unp = sotounpcb(so);
    748 	KASSERT(unp != NULL);
    749 	KASSERT(solocked(so));
    750  retry:
    751 	if ((vp = unp->unp_vnode) != NULL) {
    752 		sounlock(so);
    753 		/* Acquire v_interlock to protect against unp_connect(). */
    754 		/* XXXAD racy */
    755 		mutex_enter(vp->v_interlock);
    756 		vp->v_socket = NULL;
    757 		mutex_exit(vp->v_interlock);
    758 		vrele(vp);
    759 		solock(so);
    760 		unp->unp_vnode = NULL;
    761 	}
    762 	if (unp->unp_conn)
    763 		unp_disconnect1(unp);
    764 	while (unp->unp_refs) {
    765 		KASSERT(solocked2(so, unp->unp_refs->unp_socket));
    766 		if (unp_drop(unp->unp_refs, ECONNRESET)) {
    767 			solock(so);
    768 			goto retry;
    769 		}
    770 	}
    771 	soisdisconnected(so);
    772 	so->so_pcb = NULL;
    773 	if (unp_rights) {
    774 		/*
    775 		 * Normally the receive buffer is flushed later, in sofree,
    776 		 * but if our receive buffer holds references to files that
    777 		 * are now garbage, we will enqueue those file references to
    778 		 * the garbage collector and kick it into action.
    779 		 */
    780 		sorflush(so);
    781 		unp_free(unp);
    782 		unp_thread_kick();
    783 	} else
    784 		unp_free(unp);
    785 }
    786 
    787 static int
    788 unp_accept(struct socket *so, struct mbuf *nam)
    789 {
    790 	struct unpcb *unp = sotounpcb(so);
    791 	struct socket *so2;
    792 
    793 	KASSERT(solocked(so));
    794 	KASSERT(nam != NULL);
    795 
    796 	/* XXX code review required to determine if unp can ever be NULL */
    797 	if (unp == NULL)
    798 		return EINVAL;
    799 
    800 	KASSERT(so->so_lock == uipc_lock);
    801 	/*
    802 	 * Mark the initiating STREAM socket as connected *ONLY*
    803 	 * after it's been accepted.  This prevents a client from
    804 	 * overrunning a server and receiving ECONNREFUSED.
    805 	 */
    806 	if (unp->unp_conn == NULL) {
    807 		/*
    808 		 * This will use the empty socket and will not
    809 		 * allocate.
    810 		 */
    811 		unp_setaddr(so, nam, true);
    812 		return 0;
    813 	}
    814 	so2 = unp->unp_conn->unp_socket;
    815 	if (so2->so_state & SS_ISCONNECTING) {
    816 		KASSERT(solocked2(so, so->so_head));
    817 		KASSERT(solocked2(so2, so->so_head));
    818 		soisconnected(so2);
    819 	}
    820 	/*
    821 	 * If the connection is fully established, break the
    822 	 * association with uipc_lock and give the connected
    823 	 * pair a separate lock to share.
    824 	 * There is a race here: sotounpcb(so2)->unp_streamlock
    825 	 * is not locked, so when changing so2->so_lock
    826 	 * another thread can grab it while so->so_lock is still
    827 	 * pointing to the (locked) uipc_lock.
    828 	 * this should be harmless, except that this makes
    829 	 * solocked2() and solocked() unreliable.
    830 	 * Another problem is that unp_setaddr() expects the
    831 	 * the socket locked. Grabing sotounpcb(so2)->unp_streamlock
    832 	 * fixes both issues.
    833 	 */
    834 	mutex_enter(sotounpcb(so2)->unp_streamlock);
    835 	unp_setpeerlocks(so2, so);
    836 	/*
    837 	 * Only now return peer's address, as we may need to
    838 	 * block in order to allocate memory.
    839 	 *
    840 	 * XXX Minor race: connection can be broken while
    841 	 * lock is dropped in unp_setaddr().  We will return
    842 	 * error == 0 and sun_noname as the peer address.
    843 	 */
    844 	unp_setaddr(so, nam, true);
    845 	/* so_lock now points to unp_streamlock */
    846 	mutex_exit(so2->so_lock);
    847 	return 0;
    848 }
    849 
    850 static int
    851 unp_ioctl(struct socket *so, u_long cmd, void *nam, struct ifnet *ifp)
    852 {
    853 	return EOPNOTSUPP;
    854 }
    855 
    856 static int
    857 unp_stat(struct socket *so, struct stat *ub)
    858 {
    859 	struct unpcb *unp;
    860 	struct socket *so2;
    861 
    862 	KASSERT(solocked(so));
    863 
    864 	unp = sotounpcb(so);
    865 	if (unp == NULL)
    866 		return EINVAL;
    867 
    868 	ub->st_blksize = so->so_snd.sb_hiwat;
    869 	switch (so->so_type) {
    870 	case SOCK_SEQPACKET: /* FALLTHROUGH */
    871 	case SOCK_STREAM:
    872 		if (unp->unp_conn == 0)
    873 			break;
    874 
    875 		so2 = unp->unp_conn->unp_socket;
    876 		KASSERT(solocked2(so, so2));
    877 		ub->st_blksize += so2->so_rcv.sb_cc;
    878 		break;
    879 	default:
    880 		break;
    881 	}
    882 	ub->st_dev = NODEV;
    883 	if (unp->unp_ino == 0)
    884 		unp->unp_ino = unp_ino++;
    885 	ub->st_atimespec = ub->st_mtimespec = ub->st_ctimespec = unp->unp_ctime;
    886 	ub->st_ino = unp->unp_ino;
    887 	return (0);
    888 }
    889 
    890 static int
    891 unp_peeraddr(struct socket *so, struct mbuf *nam)
    892 {
    893 	KASSERT(solocked(so));
    894 	KASSERT(sotounpcb(so) != NULL);
    895 	KASSERT(nam != NULL);
    896 
    897 	unp_setaddr(so, nam, true);
    898 	return 0;
    899 }
    900 
    901 static int
    902 unp_sockaddr(struct socket *so, struct mbuf *nam)
    903 {
    904 	KASSERT(solocked(so));
    905 	KASSERT(sotounpcb(so) != NULL);
    906 	KASSERT(nam != NULL);
    907 
    908 	unp_setaddr(so, nam, false);
    909 	return 0;
    910 }
    911 
    912 /*
    913  * Allocate the new sockaddr.  We have to allocate one
    914  * extra byte so that we can ensure that the pathname
    915  * is nul-terminated. Note that unlike linux, we don't
    916  * include in the address length the NUL in the path
    917  * component, because doing so, would exceed sizeof(sockaddr_un)
    918  * for fully occupied pathnames. Linux is also inconsistent,
    919  * because it does not include the NUL in the length of
    920  * what it calls "abstract" unix sockets.
    921  */
    922 static struct sockaddr_un *
    923 makeun(struct mbuf *nam, size_t *addrlen) {
    924 	struct sockaddr_un *sun;
    925 
    926 	*addrlen = nam->m_len + 1;
    927 	sun = malloc(*addrlen, M_SONAME, M_WAITOK);
    928 	m_copydata(nam, 0, nam->m_len, (void *)sun);
    929 	*(((char *)sun) + nam->m_len) = '\0';
    930 	return sun;
    931 }
    932 
    933 static int
    934 unp_bind(struct socket *so, struct mbuf *nam, struct lwp *l)
    935 {
    936 	struct sockaddr_un *sun;
    937 	struct unpcb *unp;
    938 	vnode_t *vp;
    939 	struct vattr vattr;
    940 	size_t addrlen;
    941 	int error;
    942 	struct pathbuf *pb;
    943 	struct nameidata nd;
    944 	proc_t *p;
    945 
    946 	unp = sotounpcb(so);
    947 
    948 	KASSERT(solocked(so));
    949 	KASSERT(unp != NULL);
    950 	KASSERT(nam != NULL);
    951 
    952 	if (unp->unp_vnode != NULL)
    953 		return (EINVAL);
    954 	if ((unp->unp_flags & UNP_BUSY) != 0) {
    955 		/*
    956 		 * EALREADY may not be strictly accurate, but since this
    957 		 * is a major application error it's hardly a big deal.
    958 		 */
    959 		return (EALREADY);
    960 	}
    961 	unp->unp_flags |= UNP_BUSY;
    962 	sounlock(so);
    963 
    964 	p = l->l_proc;
    965 	sun = makeun(nam, &addrlen);
    966 
    967 	pb = pathbuf_create(sun->sun_path);
    968 	if (pb == NULL) {
    969 		error = ENOMEM;
    970 		goto bad;
    971 	}
    972 	NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT | TRYEMULROOT, pb);
    973 
    974 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
    975 	if ((error = namei(&nd)) != 0) {
    976 		pathbuf_destroy(pb);
    977 		goto bad;
    978 	}
    979 	vp = nd.ni_vp;
    980 	if (vp != NULL) {
    981 		VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
    982 		if (nd.ni_dvp == vp)
    983 			vrele(nd.ni_dvp);
    984 		else
    985 			vput(nd.ni_dvp);
    986 		vrele(vp);
    987 		pathbuf_destroy(pb);
    988 		error = EADDRINUSE;
    989 		goto bad;
    990 	}
    991 	vattr_null(&vattr);
    992 	vattr.va_type = VSOCK;
    993 	vattr.va_mode = ACCESSPERMS & ~(p->p_cwdi->cwdi_cmask);
    994 	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
    995 	if (error) {
    996 		vput(nd.ni_dvp);
    997 		pathbuf_destroy(pb);
    998 		goto bad;
    999 	}
   1000 	vp = nd.ni_vp;
   1001 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
   1002 	solock(so);
   1003 	vp->v_socket = unp->unp_socket;
   1004 	unp->unp_vnode = vp;
   1005 	unp->unp_addrlen = addrlen;
   1006 	unp->unp_addr = sun;
   1007 	unp->unp_connid.unp_pid = p->p_pid;
   1008 	unp->unp_connid.unp_euid = kauth_cred_geteuid(l->l_cred);
   1009 	unp->unp_connid.unp_egid = kauth_cred_getegid(l->l_cred);
   1010 	unp->unp_flags |= UNP_EIDSBIND;
   1011 	VOP_UNLOCK(vp);
   1012 	vput(nd.ni_dvp);
   1013 	unp->unp_flags &= ~UNP_BUSY;
   1014 	pathbuf_destroy(pb);
   1015 	return (0);
   1016 
   1017  bad:
   1018 	free(sun, M_SONAME);
   1019 	solock(so);
   1020 	unp->unp_flags &= ~UNP_BUSY;
   1021 	return (error);
   1022 }
   1023 
   1024 static int
   1025 unp_listen(struct socket *so, struct lwp *l)
   1026 {
   1027 	struct unpcb *unp = sotounpcb(so);
   1028 
   1029 	KASSERT(solocked(so));
   1030 	KASSERT(unp != NULL);
   1031 
   1032 	/*
   1033 	 * If the socket can accept a connection, it must be
   1034 	 * locked by uipc_lock.
   1035 	 */
   1036 	unp_resetlock(so);
   1037 	if (unp->unp_vnode == NULL)
   1038 		return EINVAL;
   1039 
   1040 	return 0;
   1041 }
   1042 
   1043 static int
   1044 unp_disconnect(struct socket *so)
   1045 {
   1046 	KASSERT(solocked(so));
   1047 	KASSERT(sotounpcb(so) != NULL);
   1048 
   1049 	unp_disconnect1(sotounpcb(so));
   1050 	return 0;
   1051 }
   1052 
   1053 static int
   1054 unp_shutdown(struct socket *so)
   1055 {
   1056 	KASSERT(solocked(so));
   1057 	KASSERT(sotounpcb(so) != NULL);
   1058 
   1059 	socantsendmore(so);
   1060 	unp_shutdown1(sotounpcb(so));
   1061 	return 0;
   1062 }
   1063 
   1064 static int
   1065 unp_abort(struct socket *so)
   1066 {
   1067 	KASSERT(solocked(so));
   1068 	KASSERT(sotounpcb(so) != NULL);
   1069 
   1070 	(void)unp_drop(sotounpcb(so), ECONNABORTED);
   1071 	KASSERT(so->so_head == NULL);
   1072 	KASSERT(so->so_pcb != NULL);
   1073 	unp_detach(so);
   1074 	return 0;
   1075 }
   1076 
   1077 static int
   1078 unp_connect1(struct socket *so, struct socket *so2, struct lwp *l)
   1079 {
   1080 	struct unpcb *unp = sotounpcb(so);
   1081 	struct unpcb *unp2;
   1082 
   1083 	if (so2->so_type != so->so_type)
   1084 		return EPROTOTYPE;
   1085 
   1086 	/*
   1087 	 * All three sockets involved must be locked by same lock:
   1088 	 *
   1089 	 * local endpoint (so)
   1090 	 * remote endpoint (so2)
   1091 	 * queue head (so2->so_head, only if PR_CONNREQUIRED)
   1092 	 */
   1093 	KASSERT(solocked2(so, so2));
   1094 	KASSERT(so->so_head == NULL);
   1095 	if (so2->so_head != NULL) {
   1096 		KASSERT(so2->so_lock == uipc_lock);
   1097 		KASSERT(solocked2(so2, so2->so_head));
   1098 	}
   1099 
   1100 	unp2 = sotounpcb(so2);
   1101 	unp->unp_conn = unp2;
   1102 
   1103 	if ((so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
   1104 		unp2->unp_connid.unp_pid = l->l_proc->p_pid;
   1105 		unp2->unp_connid.unp_euid = kauth_cred_geteuid(l->l_cred);
   1106 		unp2->unp_connid.unp_egid = kauth_cred_getegid(l->l_cred);
   1107 		unp2->unp_flags |= UNP_EIDSVALID;
   1108 		if (unp2->unp_flags & UNP_EIDSBIND) {
   1109 			unp->unp_connid = unp2->unp_connid;
   1110 			unp->unp_flags |= UNP_EIDSVALID;
   1111 		}
   1112 	}
   1113 
   1114 	switch (so->so_type) {
   1115 
   1116 	case SOCK_DGRAM:
   1117 		unp->unp_nextref = unp2->unp_refs;
   1118 		unp2->unp_refs = unp;
   1119 		soisconnected(so);
   1120 		break;
   1121 
   1122 	case SOCK_SEQPACKET: /* FALLTHROUGH */
   1123 	case SOCK_STREAM:
   1124 
   1125 		/*
   1126 		 * SOCK_SEQPACKET and SOCK_STREAM cases are handled by callers
   1127 		 * which are unp_connect() or unp_connect2().
   1128 		 */
   1129 
   1130 		break;
   1131 
   1132 	default:
   1133 		panic("unp_connect1");
   1134 	}
   1135 
   1136 	return 0;
   1137 }
   1138 
   1139 int
   1140 unp_connect(struct socket *so, struct mbuf *nam, struct lwp *l)
   1141 {
   1142 	struct sockaddr_un *sun;
   1143 	vnode_t *vp;
   1144 	struct socket *so2, *so3;
   1145 	struct unpcb *unp, *unp2, *unp3;
   1146 	size_t addrlen;
   1147 	int error;
   1148 	struct pathbuf *pb;
   1149 	struct nameidata nd;
   1150 
   1151 	unp = sotounpcb(so);
   1152 	if ((unp->unp_flags & UNP_BUSY) != 0) {
   1153 		/*
   1154 		 * EALREADY may not be strictly accurate, but since this
   1155 		 * is a major application error it's hardly a big deal.
   1156 		 */
   1157 		return (EALREADY);
   1158 	}
   1159 	unp->unp_flags |= UNP_BUSY;
   1160 	sounlock(so);
   1161 
   1162 	sun = makeun(nam, &addrlen);
   1163 	pb = pathbuf_create(sun->sun_path);
   1164 	if (pb == NULL) {
   1165 		error = ENOMEM;
   1166 		goto bad2;
   1167 	}
   1168 
   1169 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | TRYEMULROOT, pb);
   1170 
   1171 	if ((error = namei(&nd)) != 0) {
   1172 		pathbuf_destroy(pb);
   1173 		goto bad2;
   1174 	}
   1175 	vp = nd.ni_vp;
   1176 	if (vp->v_type != VSOCK) {
   1177 		error = ENOTSOCK;
   1178 		goto bad;
   1179 	}
   1180 	pathbuf_destroy(pb);
   1181 	if ((error = VOP_ACCESS(vp, VWRITE, l->l_cred)) != 0)
   1182 		goto bad;
   1183 	/* Acquire v_interlock to protect against unp_detach(). */
   1184 	mutex_enter(vp->v_interlock);
   1185 	so2 = vp->v_socket;
   1186 	if (so2 == NULL) {
   1187 		mutex_exit(vp->v_interlock);
   1188 		error = ECONNREFUSED;
   1189 		goto bad;
   1190 	}
   1191 	if (so->so_type != so2->so_type) {
   1192 		mutex_exit(vp->v_interlock);
   1193 		error = EPROTOTYPE;
   1194 		goto bad;
   1195 	}
   1196 	solock(so);
   1197 	unp_resetlock(so);
   1198 	mutex_exit(vp->v_interlock);
   1199 	if ((so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
   1200 		/*
   1201 		 * This may seem somewhat fragile but is OK: if we can
   1202 		 * see SO_ACCEPTCONN set on the endpoint, then it must
   1203 		 * be locked by the domain-wide uipc_lock.
   1204 		 */
   1205 		KASSERT((so2->so_options & SO_ACCEPTCONN) == 0 ||
   1206 		    so2->so_lock == uipc_lock);
   1207 		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
   1208 		    (so3 = sonewconn(so2, false)) == NULL) {
   1209 			error = ECONNREFUSED;
   1210 			sounlock(so);
   1211 			goto bad;
   1212 		}
   1213 		unp2 = sotounpcb(so2);
   1214 		unp3 = sotounpcb(so3);
   1215 		if (unp2->unp_addr) {
   1216 			unp3->unp_addr = malloc(unp2->unp_addrlen,
   1217 			    M_SONAME, M_WAITOK);
   1218 			memcpy(unp3->unp_addr, unp2->unp_addr,
   1219 			    unp2->unp_addrlen);
   1220 			unp3->unp_addrlen = unp2->unp_addrlen;
   1221 		}
   1222 		unp3->unp_flags = unp2->unp_flags;
   1223 		so2 = so3;
   1224 	}
   1225 	error = unp_connect1(so, so2, l);
   1226 	if (error) {
   1227 		sounlock(so);
   1228 		goto bad;
   1229 	}
   1230 	unp2 = sotounpcb(so2);
   1231 	switch (so->so_type) {
   1232 
   1233 	/*
   1234 	 * SOCK_DGRAM and default cases are handled in prior call to
   1235 	 * unp_connect1(), do not add a default case without fixing
   1236 	 * unp_connect1().
   1237 	 */
   1238 
   1239 	case SOCK_SEQPACKET: /* FALLTHROUGH */
   1240 	case SOCK_STREAM:
   1241 		unp2->unp_conn = unp;
   1242 		if ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT)
   1243 			soisconnecting(so);
   1244 		else
   1245 			soisconnected(so);
   1246 		soisconnected(so2);
   1247 		/*
   1248 		 * If the connection is fully established, break the
   1249 		 * association with uipc_lock and give the connected
   1250 		 * pair a seperate lock to share.
   1251 		 */
   1252 		KASSERT(so2->so_head != NULL);
   1253 		unp_setpeerlocks(so, so2);
   1254 		break;
   1255 
   1256 	}
   1257 	sounlock(so);
   1258  bad:
   1259 	vput(vp);
   1260  bad2:
   1261 	free(sun, M_SONAME);
   1262 	solock(so);
   1263 	unp->unp_flags &= ~UNP_BUSY;
   1264 	return (error);
   1265 }
   1266 
   1267 int
   1268 unp_connect2(struct socket *so, struct socket *so2)
   1269 {
   1270 	struct unpcb *unp = sotounpcb(so);
   1271 	struct unpcb *unp2;
   1272 	int error = 0;
   1273 
   1274 	KASSERT(solocked2(so, so2));
   1275 
   1276 	error = unp_connect1(so, so2, curlwp);
   1277 	if (error)
   1278 		return error;
   1279 
   1280 	unp2 = sotounpcb(so2);
   1281 	switch (so->so_type) {
   1282 
   1283 	/*
   1284 	 * SOCK_DGRAM and default cases are handled in prior call to
   1285 	 * unp_connect1(), do not add a default case without fixing
   1286 	 * unp_connect1().
   1287 	 */
   1288 
   1289 	case SOCK_SEQPACKET: /* FALLTHROUGH */
   1290 	case SOCK_STREAM:
   1291 		unp2->unp_conn = unp;
   1292 		if ((so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
   1293 			unp->unp_connid = unp2->unp_connid;
   1294 			unp->unp_flags |= UNP_EIDSVALID;
   1295 		}
   1296 		soisconnected(so);
   1297 		soisconnected(so2);
   1298 		break;
   1299 
   1300 	}
   1301 	return error;
   1302 }
   1303 
   1304 static void
   1305 unp_disconnect1(struct unpcb *unp)
   1306 {
   1307 	struct unpcb *unp2 = unp->unp_conn;
   1308 	struct socket *so;
   1309 
   1310 	if (unp2 == 0)
   1311 		return;
   1312 	unp->unp_conn = 0;
   1313 	so = unp->unp_socket;
   1314 	switch (so->so_type) {
   1315 	case SOCK_DGRAM:
   1316 		if (unp2->unp_refs == unp)
   1317 			unp2->unp_refs = unp->unp_nextref;
   1318 		else {
   1319 			unp2 = unp2->unp_refs;
   1320 			for (;;) {
   1321 				KASSERT(solocked2(so, unp2->unp_socket));
   1322 				if (unp2 == 0)
   1323 					panic("unp_disconnect1");
   1324 				if (unp2->unp_nextref == unp)
   1325 					break;
   1326 				unp2 = unp2->unp_nextref;
   1327 			}
   1328 			unp2->unp_nextref = unp->unp_nextref;
   1329 		}
   1330 		unp->unp_nextref = 0;
   1331 		so->so_state &= ~SS_ISCONNECTED;
   1332 		break;
   1333 
   1334 	case SOCK_SEQPACKET: /* FALLTHROUGH */
   1335 	case SOCK_STREAM:
   1336 		KASSERT(solocked2(so, unp2->unp_socket));
   1337 		soisdisconnected(so);
   1338 		unp2->unp_conn = 0;
   1339 		soisdisconnected(unp2->unp_socket);
   1340 		break;
   1341 	}
   1342 }
   1343 
   1344 static void
   1345 unp_shutdown1(struct unpcb *unp)
   1346 {
   1347 	struct socket *so;
   1348 
   1349 	switch(unp->unp_socket->so_type) {
   1350 	case SOCK_SEQPACKET: /* FALLTHROUGH */
   1351 	case SOCK_STREAM:
   1352 		if (unp->unp_conn && (so = unp->unp_conn->unp_socket))
   1353 			socantrcvmore(so);
   1354 		break;
   1355 	default:
   1356 		break;
   1357 	}
   1358 }
   1359 
   1360 static bool
   1361 unp_drop(struct unpcb *unp, int errno)
   1362 {
   1363 	struct socket *so = unp->unp_socket;
   1364 
   1365 	KASSERT(solocked(so));
   1366 
   1367 	so->so_error = errno;
   1368 	unp_disconnect1(unp);
   1369 	if (so->so_head) {
   1370 		so->so_pcb = NULL;
   1371 		/* sofree() drops the socket lock */
   1372 		sofree(so);
   1373 		unp_free(unp);
   1374 		return true;
   1375 	}
   1376 	return false;
   1377 }
   1378 
   1379 #ifdef notdef
   1380 unp_drain(void)
   1381 {
   1382 
   1383 }
   1384 #endif
   1385 
   1386 int
   1387 unp_externalize(struct mbuf *rights, struct lwp *l, int flags)
   1388 {
   1389 	struct cmsghdr * const cm = mtod(rights, struct cmsghdr *);
   1390 	struct proc * const p = l->l_proc;
   1391 	file_t **rp;
   1392 	int error = 0;
   1393 
   1394 	const size_t nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
   1395 	    sizeof(file_t *);
   1396 	if (nfds == 0)
   1397 		goto noop;
   1398 
   1399 	int * const fdp = kmem_alloc(nfds * sizeof(int), KM_SLEEP);
   1400 	rw_enter(&p->p_cwdi->cwdi_lock, RW_READER);
   1401 
   1402 	/* Make sure the recipient should be able to see the files.. */
   1403 	rp = (file_t **)CMSG_DATA(cm);
   1404 	for (size_t i = 0; i < nfds; i++) {
   1405 		file_t * const fp = *rp++;
   1406 		if (fp == NULL) {
   1407 			error = EINVAL;
   1408 			goto out;
   1409 		}
   1410 		/*
   1411 		 * If we are in a chroot'ed directory, and
   1412 		 * someone wants to pass us a directory, make
   1413 		 * sure it's inside the subtree we're allowed
   1414 		 * to access.
   1415 		 */
   1416 		if (p->p_cwdi->cwdi_rdir != NULL && fp->f_type == DTYPE_VNODE) {
   1417 			vnode_t *vp = fp->f_vnode;
   1418 			if ((vp->v_type == VDIR) &&
   1419 			    !vn_isunder(vp, p->p_cwdi->cwdi_rdir, l)) {
   1420 				error = EPERM;
   1421 				goto out;
   1422 			}
   1423 		}
   1424 	}
   1425 
   1426  restart:
   1427 	/*
   1428 	 * First loop -- allocate file descriptor table slots for the
   1429 	 * new files.
   1430 	 */
   1431 	for (size_t i = 0; i < nfds; i++) {
   1432 		if ((error = fd_alloc(p, 0, &fdp[i])) != 0) {
   1433 			/*
   1434 			 * Back out what we've done so far.
   1435 			 */
   1436 			while (i-- > 0) {
   1437 				fd_abort(p, NULL, fdp[i]);
   1438 			}
   1439 			if (error == ENOSPC) {
   1440 				fd_tryexpand(p);
   1441 				error = 0;
   1442 				goto restart;
   1443 			}
   1444 			/*
   1445 			 * This is the error that has historically
   1446 			 * been returned, and some callers may
   1447 			 * expect it.
   1448 			 */
   1449 			error = EMSGSIZE;
   1450 			goto out;
   1451 		}
   1452 	}
   1453 
   1454 	/*
   1455 	 * Now that adding them has succeeded, update all of the
   1456 	 * file passing state and affix the descriptors.
   1457 	 */
   1458 	rp = (file_t **)CMSG_DATA(cm);
   1459 	int *ofdp = (int *)CMSG_DATA(cm);
   1460 	for (size_t i = 0; i < nfds; i++) {
   1461 		file_t * const fp = *rp++;
   1462 		const int fd = fdp[i];
   1463 		atomic_dec_uint(&unp_rights);
   1464 		fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0);
   1465 		fd_affix(p, fp, fd);
   1466 		/*
   1467 		 * Done with this file pointer, replace it with a fd;
   1468 		 */
   1469 		*ofdp++ = fd;
   1470 		mutex_enter(&fp->f_lock);
   1471 		fp->f_msgcount--;
   1472 		mutex_exit(&fp->f_lock);
   1473 		/*
   1474 		 * Note that fd_affix() adds a reference to the file.
   1475 		 * The file may already have been closed by another
   1476 		 * LWP in the process, so we must drop the reference
   1477 		 * added by unp_internalize() with closef().
   1478 		 */
   1479 		closef(fp);
   1480 	}
   1481 
   1482 	/*
   1483 	 * Adjust length, in case of transition from large file_t
   1484 	 * pointers to ints.
   1485 	 */
   1486 	if (sizeof(file_t *) != sizeof(int)) {
   1487 		cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
   1488 		rights->m_len = CMSG_SPACE(nfds * sizeof(int));
   1489 	}
   1490  out:
   1491 	if (__predict_false(error != 0)) {
   1492 		file_t **const fpp = (file_t **)CMSG_DATA(cm);
   1493 		for (size_t i = 0; i < nfds; i++)
   1494 			unp_discard_now(fpp[i]);
   1495 		/*
   1496 		 * Truncate the array so that nobody will try to interpret
   1497 		 * what is now garbage in it.
   1498 		 */
   1499 		cm->cmsg_len = CMSG_LEN(0);
   1500 		rights->m_len = CMSG_SPACE(0);
   1501 	}
   1502 	rw_exit(&p->p_cwdi->cwdi_lock);
   1503 	kmem_free(fdp, nfds * sizeof(int));
   1504 
   1505  noop:
   1506 	/*
   1507 	 * Don't disclose kernel memory in the alignment space.
   1508 	 */
   1509 	KASSERT(cm->cmsg_len <= rights->m_len);
   1510 	memset(&mtod(rights, char *)[cm->cmsg_len], 0, rights->m_len -
   1511 	    cm->cmsg_len);
   1512 	return error;
   1513 }
   1514 
   1515 static int
   1516 unp_internalize(struct mbuf **controlp)
   1517 {
   1518 	filedesc_t *fdescp = curlwp->l_fd;
   1519 	struct mbuf *control = *controlp;
   1520 	struct cmsghdr *newcm, *cm = mtod(control, struct cmsghdr *);
   1521 	file_t **rp, **files;
   1522 	file_t *fp;
   1523 	int i, fd, *fdp;
   1524 	int nfds, error;
   1525 	u_int maxmsg;
   1526 
   1527 	error = 0;
   1528 	newcm = NULL;
   1529 
   1530 	/* Sanity check the control message header. */
   1531 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
   1532 	    cm->cmsg_len > control->m_len ||
   1533 	    cm->cmsg_len < CMSG_ALIGN(sizeof(*cm)))
   1534 		return (EINVAL);
   1535 
   1536 	/*
   1537 	 * Verify that the file descriptors are valid, and acquire
   1538 	 * a reference to each.
   1539 	 */
   1540 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof(int);
   1541 	fdp = (int *)CMSG_DATA(cm);
   1542 	maxmsg = maxfiles / unp_rights_ratio;
   1543 	for (i = 0; i < nfds; i++) {
   1544 		fd = *fdp++;
   1545 		if (atomic_inc_uint_nv(&unp_rights) > maxmsg) {
   1546 			atomic_dec_uint(&unp_rights);
   1547 			nfds = i;
   1548 			error = EAGAIN;
   1549 			goto out;
   1550 		}
   1551 		if ((fp = fd_getfile(fd)) == NULL
   1552 		    || fp->f_type == DTYPE_KQUEUE) {
   1553 		    	if (fp)
   1554 		    		fd_putfile(fd);
   1555 			atomic_dec_uint(&unp_rights);
   1556 			nfds = i;
   1557 			error = EBADF;
   1558 			goto out;
   1559 		}
   1560 	}
   1561 
   1562 	/* Allocate new space and copy header into it. */
   1563 	newcm = malloc(CMSG_SPACE(nfds * sizeof(file_t *)), M_MBUF, M_WAITOK);
   1564 	if (newcm == NULL) {
   1565 		error = E2BIG;
   1566 		goto out;
   1567 	}
   1568 	memcpy(newcm, cm, sizeof(struct cmsghdr));
   1569 	files = (file_t **)CMSG_DATA(newcm);
   1570 
   1571 	/*
   1572 	 * Transform the file descriptors into file_t pointers, in
   1573 	 * reverse order so that if pointers are bigger than ints, the
   1574 	 * int won't get until we're done.  No need to lock, as we have
   1575 	 * already validated the descriptors with fd_getfile().
   1576 	 */
   1577 	fdp = (int *)CMSG_DATA(cm) + nfds;
   1578 	rp = files + nfds;
   1579 	for (i = 0; i < nfds; i++) {
   1580 		fp = fdescp->fd_dt->dt_ff[*--fdp]->ff_file;
   1581 		KASSERT(fp != NULL);
   1582 		mutex_enter(&fp->f_lock);
   1583 		*--rp = fp;
   1584 		fp->f_count++;
   1585 		fp->f_msgcount++;
   1586 		mutex_exit(&fp->f_lock);
   1587 	}
   1588 
   1589  out:
   1590  	/* Release descriptor references. */
   1591 	fdp = (int *)CMSG_DATA(cm);
   1592 	for (i = 0; i < nfds; i++) {
   1593 		fd_putfile(*fdp++);
   1594 		if (error != 0) {
   1595 			atomic_dec_uint(&unp_rights);
   1596 		}
   1597 	}
   1598 
   1599 	if (error == 0) {
   1600 		if (control->m_flags & M_EXT) {
   1601 			m_freem(control);
   1602 			*controlp = control = m_get(M_WAIT, MT_CONTROL);
   1603 		}
   1604 		MEXTADD(control, newcm, CMSG_SPACE(nfds * sizeof(file_t *)),
   1605 		    M_MBUF, NULL, NULL);
   1606 		cm = newcm;
   1607 		/*
   1608 		 * Adjust message & mbuf to note amount of space
   1609 		 * actually used.
   1610 		 */
   1611 		cm->cmsg_len = CMSG_LEN(nfds * sizeof(file_t *));
   1612 		control->m_len = CMSG_SPACE(nfds * sizeof(file_t *));
   1613 	}
   1614 
   1615 	return error;
   1616 }
   1617 
   1618 struct mbuf *
   1619 unp_addsockcred(struct lwp *l, struct mbuf *control)
   1620 {
   1621 	struct sockcred *sc;
   1622 	struct mbuf *m;
   1623 	void *p;
   1624 
   1625 	m = sbcreatecontrol1(&p, SOCKCREDSIZE(kauth_cred_ngroups(l->l_cred)),
   1626 		SCM_CREDS, SOL_SOCKET, M_WAITOK);
   1627 	if (m == NULL)
   1628 		return control;
   1629 
   1630 	sc = p;
   1631 	sc->sc_uid = kauth_cred_getuid(l->l_cred);
   1632 	sc->sc_euid = kauth_cred_geteuid(l->l_cred);
   1633 	sc->sc_gid = kauth_cred_getgid(l->l_cred);
   1634 	sc->sc_egid = kauth_cred_getegid(l->l_cred);
   1635 	sc->sc_ngroups = kauth_cred_ngroups(l->l_cred);
   1636 
   1637 	for (int i = 0; i < sc->sc_ngroups; i++)
   1638 		sc->sc_groups[i] = kauth_cred_group(l->l_cred, i);
   1639 
   1640 	return m_add(control, m);
   1641 }
   1642 
   1643 /*
   1644  * Do a mark-sweep GC of files in the system, to free up any which are
   1645  * caught in flight to an about-to-be-closed socket.  Additionally,
   1646  * process deferred file closures.
   1647  */
   1648 static void
   1649 unp_gc(file_t *dp)
   1650 {
   1651 	extern	struct domain unixdomain;
   1652 	file_t *fp, *np;
   1653 	struct socket *so, *so1;
   1654 	u_int i, oflags, rflags;
   1655 	bool didwork;
   1656 
   1657 	KASSERT(curlwp == unp_thread_lwp);
   1658 	KASSERT(mutex_owned(&filelist_lock));
   1659 
   1660 	/*
   1661 	 * First, process deferred file closures.
   1662 	 */
   1663 	while (!SLIST_EMPTY(&unp_thread_discard)) {
   1664 		fp = SLIST_FIRST(&unp_thread_discard);
   1665 		KASSERT(fp->f_unpcount > 0);
   1666 		KASSERT(fp->f_count > 0);
   1667 		KASSERT(fp->f_msgcount > 0);
   1668 		KASSERT(fp->f_count >= fp->f_unpcount);
   1669 		KASSERT(fp->f_count >= fp->f_msgcount);
   1670 		KASSERT(fp->f_msgcount >= fp->f_unpcount);
   1671 		SLIST_REMOVE_HEAD(&unp_thread_discard, f_unplist);
   1672 		i = fp->f_unpcount;
   1673 		fp->f_unpcount = 0;
   1674 		mutex_exit(&filelist_lock);
   1675 		for (; i != 0; i--) {
   1676 			unp_discard_now(fp);
   1677 		}
   1678 		mutex_enter(&filelist_lock);
   1679 	}
   1680 
   1681 	/*
   1682 	 * Clear mark bits.  Ensure that we don't consider new files
   1683 	 * entering the file table during this loop (they will not have
   1684 	 * FSCAN set).
   1685 	 */
   1686 	unp_defer = 0;
   1687 	LIST_FOREACH(fp, &filehead, f_list) {
   1688 		for (oflags = fp->f_flag;; oflags = rflags) {
   1689 			rflags = atomic_cas_uint(&fp->f_flag, oflags,
   1690 			    (oflags | FSCAN) & ~(FMARK|FDEFER));
   1691 			if (__predict_true(oflags == rflags)) {
   1692 				break;
   1693 			}
   1694 		}
   1695 	}
   1696 
   1697 	/*
   1698 	 * Iterate over the set of sockets, marking ones believed (based on
   1699 	 * refcount) to be referenced from a process, and marking for rescan
   1700 	 * sockets which are queued on a socket.  Recan continues descending
   1701 	 * and searching for sockets referenced by sockets (FDEFER), until
   1702 	 * there are no more socket->socket references to be discovered.
   1703 	 */
   1704 	do {
   1705 		didwork = false;
   1706 		for (fp = LIST_FIRST(&filehead); fp != NULL; fp = np) {
   1707 			KASSERT(mutex_owned(&filelist_lock));
   1708 			np = LIST_NEXT(fp, f_list);
   1709 			mutex_enter(&fp->f_lock);
   1710 			if ((fp->f_flag & FDEFER) != 0) {
   1711 				atomic_and_uint(&fp->f_flag, ~FDEFER);
   1712 				unp_defer--;
   1713 				KASSERT(fp->f_count != 0);
   1714 			} else {
   1715 				if (fp->f_count == 0 ||
   1716 				    (fp->f_flag & FMARK) != 0 ||
   1717 				    fp->f_count == fp->f_msgcount ||
   1718 				    fp->f_unpcount != 0) {
   1719 					mutex_exit(&fp->f_lock);
   1720 					continue;
   1721 				}
   1722 			}
   1723 			atomic_or_uint(&fp->f_flag, FMARK);
   1724 
   1725 			if (fp->f_type != DTYPE_SOCKET ||
   1726 			    (so = fp->f_socket) == NULL ||
   1727 			    so->so_proto->pr_domain != &unixdomain ||
   1728 			    (so->so_proto->pr_flags & PR_RIGHTS) == 0) {
   1729 				mutex_exit(&fp->f_lock);
   1730 				continue;
   1731 			}
   1732 
   1733 			/* Gain file ref, mark our position, and unlock. */
   1734 			didwork = true;
   1735 			LIST_INSERT_AFTER(fp, dp, f_list);
   1736 			fp->f_count++;
   1737 			mutex_exit(&fp->f_lock);
   1738 			mutex_exit(&filelist_lock);
   1739 
   1740 			/*
   1741 			 * Mark files referenced from sockets queued on the
   1742 			 * accept queue as well.
   1743 			 */
   1744 			solock(so);
   1745 			unp_scan(so->so_rcv.sb_mb, unp_mark, 0);
   1746 			if ((so->so_options & SO_ACCEPTCONN) != 0) {
   1747 				TAILQ_FOREACH(so1, &so->so_q0, so_qe) {
   1748 					unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
   1749 				}
   1750 				TAILQ_FOREACH(so1, &so->so_q, so_qe) {
   1751 					unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
   1752 				}
   1753 			}
   1754 			sounlock(so);
   1755 
   1756 			/* Re-lock and restart from where we left off. */
   1757 			closef(fp);
   1758 			mutex_enter(&filelist_lock);
   1759 			np = LIST_NEXT(dp, f_list);
   1760 			LIST_REMOVE(dp, f_list);
   1761 		}
   1762 		/*
   1763 		 * Bail early if we did nothing in the loop above.  Could
   1764 		 * happen because of concurrent activity causing unp_defer
   1765 		 * to get out of sync.
   1766 		 */
   1767 	} while (unp_defer != 0 && didwork);
   1768 
   1769 	/*
   1770 	 * Sweep pass.
   1771 	 *
   1772 	 * We grab an extra reference to each of the files that are
   1773 	 * not otherwise accessible and then free the rights that are
   1774 	 * stored in messages on them.
   1775 	 */
   1776 	for (fp = LIST_FIRST(&filehead); fp != NULL; fp = np) {
   1777 		KASSERT(mutex_owned(&filelist_lock));
   1778 		np = LIST_NEXT(fp, f_list);
   1779 		mutex_enter(&fp->f_lock);
   1780 
   1781 		/*
   1782 		 * Ignore non-sockets.
   1783 		 * Ignore dead sockets, or sockets with pending close.
   1784 		 * Ignore sockets obviously referenced elsewhere.
   1785 		 * Ignore sockets marked as referenced by our scan.
   1786 		 * Ignore new sockets that did not exist during the scan.
   1787 		 */
   1788 		if (fp->f_type != DTYPE_SOCKET ||
   1789 		    fp->f_count == 0 || fp->f_unpcount != 0 ||
   1790 		    fp->f_count != fp->f_msgcount ||
   1791 		    (fp->f_flag & (FMARK | FSCAN)) != FSCAN) {
   1792 			mutex_exit(&fp->f_lock);
   1793 			continue;
   1794 		}
   1795 
   1796 		/* Gain file ref, mark our position, and unlock. */
   1797 		LIST_INSERT_AFTER(fp, dp, f_list);
   1798 		fp->f_count++;
   1799 		mutex_exit(&fp->f_lock);
   1800 		mutex_exit(&filelist_lock);
   1801 
   1802 		/*
   1803 		 * Flush all data from the socket's receive buffer.
   1804 		 * This will cause files referenced only by the
   1805 		 * socket to be queued for close.
   1806 		 */
   1807 		so = fp->f_socket;
   1808 		solock(so);
   1809 		sorflush(so);
   1810 		sounlock(so);
   1811 
   1812 		/* Re-lock and restart from where we left off. */
   1813 		closef(fp);
   1814 		mutex_enter(&filelist_lock);
   1815 		np = LIST_NEXT(dp, f_list);
   1816 		LIST_REMOVE(dp, f_list);
   1817 	}
   1818 }
   1819 
   1820 /*
   1821  * Garbage collector thread.  While SCM_RIGHTS messages are in transit,
   1822  * wake once per second to garbage collect.  Run continually while we
   1823  * have deferred closes to process.
   1824  */
   1825 static void
   1826 unp_thread(void *cookie)
   1827 {
   1828 	file_t *dp;
   1829 
   1830 	/* Allocate a dummy file for our scans. */
   1831 	if ((dp = fgetdummy()) == NULL) {
   1832 		panic("unp_thread");
   1833 	}
   1834 
   1835 	mutex_enter(&filelist_lock);
   1836 	for (;;) {
   1837 		KASSERT(mutex_owned(&filelist_lock));
   1838 		if (SLIST_EMPTY(&unp_thread_discard)) {
   1839 			if (unp_rights != 0) {
   1840 				(void)cv_timedwait(&unp_thread_cv,
   1841 				    &filelist_lock, hz);
   1842 			} else {
   1843 				cv_wait(&unp_thread_cv, &filelist_lock);
   1844 			}
   1845 		}
   1846 		unp_gc(dp);
   1847 	}
   1848 	/* NOTREACHED */
   1849 }
   1850 
   1851 /*
   1852  * Kick the garbage collector into action if there is something for
   1853  * it to process.
   1854  */
   1855 static void
   1856 unp_thread_kick(void)
   1857 {
   1858 
   1859 	if (!SLIST_EMPTY(&unp_thread_discard) || unp_rights != 0) {
   1860 		mutex_enter(&filelist_lock);
   1861 		cv_signal(&unp_thread_cv);
   1862 		mutex_exit(&filelist_lock);
   1863 	}
   1864 }
   1865 
   1866 void
   1867 unp_dispose(struct mbuf *m)
   1868 {
   1869 
   1870 	if (m)
   1871 		unp_scan(m, unp_discard_later, 1);
   1872 }
   1873 
   1874 void
   1875 unp_scan(struct mbuf *m0, void (*op)(file_t *), int discard)
   1876 {
   1877 	struct mbuf *m;
   1878 	file_t **rp, *fp;
   1879 	struct cmsghdr *cm;
   1880 	int i, qfds;
   1881 
   1882 	while (m0) {
   1883 		for (m = m0; m; m = m->m_next) {
   1884 			if (m->m_type != MT_CONTROL ||
   1885 			    m->m_len < sizeof(*cm)) {
   1886 			    	continue;
   1887 			}
   1888 			cm = mtod(m, struct cmsghdr *);
   1889 			if (cm->cmsg_level != SOL_SOCKET ||
   1890 			    cm->cmsg_type != SCM_RIGHTS)
   1891 				continue;
   1892 			qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm)))
   1893 			    / sizeof(file_t *);
   1894 			rp = (file_t **)CMSG_DATA(cm);
   1895 			for (i = 0; i < qfds; i++) {
   1896 				fp = *rp;
   1897 				if (discard) {
   1898 					*rp = 0;
   1899 				}
   1900 				(*op)(fp);
   1901 				rp++;
   1902 			}
   1903 		}
   1904 		m0 = m0->m_nextpkt;
   1905 	}
   1906 }
   1907 
   1908 void
   1909 unp_mark(file_t *fp)
   1910 {
   1911 
   1912 	if (fp == NULL)
   1913 		return;
   1914 
   1915 	/* If we're already deferred, don't screw up the defer count */
   1916 	mutex_enter(&fp->f_lock);
   1917 	if (fp->f_flag & (FMARK | FDEFER)) {
   1918 		mutex_exit(&fp->f_lock);
   1919 		return;
   1920 	}
   1921 
   1922 	/*
   1923 	 * Minimize the number of deferrals...  Sockets are the only type of
   1924 	 * file which can hold references to another file, so just mark
   1925 	 * other files, and defer unmarked sockets for the next pass.
   1926 	 */
   1927 	if (fp->f_type == DTYPE_SOCKET) {
   1928 		unp_defer++;
   1929 		KASSERT(fp->f_count != 0);
   1930 		atomic_or_uint(&fp->f_flag, FDEFER);
   1931 	} else {
   1932 		atomic_or_uint(&fp->f_flag, FMARK);
   1933 	}
   1934 	mutex_exit(&fp->f_lock);
   1935 }
   1936 
   1937 static void
   1938 unp_discard_now(file_t *fp)
   1939 {
   1940 
   1941 	if (fp == NULL)
   1942 		return;
   1943 
   1944 	KASSERT(fp->f_count > 0);
   1945 	KASSERT(fp->f_msgcount > 0);
   1946 
   1947 	mutex_enter(&fp->f_lock);
   1948 	fp->f_msgcount--;
   1949 	mutex_exit(&fp->f_lock);
   1950 	atomic_dec_uint(&unp_rights);
   1951 	(void)closef(fp);
   1952 }
   1953 
   1954 static void
   1955 unp_discard_later(file_t *fp)
   1956 {
   1957 
   1958 	if (fp == NULL)
   1959 		return;
   1960 
   1961 	KASSERT(fp->f_count > 0);
   1962 	KASSERT(fp->f_msgcount > 0);
   1963 
   1964 	mutex_enter(&filelist_lock);
   1965 	if (fp->f_unpcount++ == 0) {
   1966 		SLIST_INSERT_HEAD(&unp_thread_discard, fp, f_unplist);
   1967 	}
   1968 	mutex_exit(&filelist_lock);
   1969 }
   1970 
   1971 const struct pr_usrreqs unp_usrreqs = {
   1972 	.pr_attach	= unp_attach,
   1973 	.pr_detach	= unp_detach,
   1974 	.pr_accept	= unp_accept,
   1975 	.pr_bind	= unp_bind,
   1976 	.pr_listen	= unp_listen,
   1977 	.pr_connect	= unp_connect,
   1978 	.pr_connect2	= unp_connect2,
   1979 	.pr_disconnect	= unp_disconnect,
   1980 	.pr_shutdown	= unp_shutdown,
   1981 	.pr_abort	= unp_abort,
   1982 	.pr_ioctl	= unp_ioctl,
   1983 	.pr_stat	= unp_stat,
   1984 	.pr_peeraddr	= unp_peeraddr,
   1985 	.pr_sockaddr	= unp_sockaddr,
   1986 	.pr_rcvd	= unp_rcvd,
   1987 	.pr_recvoob	= unp_recvoob,
   1988 	.pr_send	= unp_send,
   1989 	.pr_sendoob	= unp_sendoob,
   1990 	.pr_generic	= unp_usrreq,
   1991 };
   1992