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