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