xref: /dragonfly/sys/kern/uipc_usrreq.c (revision 6b47f3ea)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	From: @(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
30  * $FreeBSD: src/sys/kern/uipc_usrreq.c,v 1.54.2.10 2003/03/04 17:28:09 nectar Exp $
31  */
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/domain.h>
37 #include <sys/fcntl.h>
38 #include <sys/malloc.h>		/* XXX must be before <sys/file.h> */
39 #include <sys/proc.h>
40 #include <sys/file.h>
41 #include <sys/filedesc.h>
42 #include <sys/mbuf.h>
43 #include <sys/nlookup.h>
44 #include <sys/protosw.h>
45 #include <sys/socket.h>
46 #include <sys/socketvar.h>
47 #include <sys/resourcevar.h>
48 #include <sys/stat.h>
49 #include <sys/mount.h>
50 #include <sys/sysctl.h>
51 #include <sys/un.h>
52 #include <sys/unpcb.h>
53 #include <sys/vnode.h>
54 #include <sys/kern_syscall.h>
55 #include <sys/taskqueue.h>
56 
57 #include <sys/file2.h>
58 #include <sys/spinlock2.h>
59 #include <sys/socketvar2.h>
60 #include <sys/msgport2.h>
61 
62 /*
63  * Unix communications domain.
64  *
65  * TODO:
66  *	RDM
67  *	rethink name space problems
68  *	need a proper out-of-band
69  *	lock pushdown
70  *
71  *
72  * Unix domain sockets GC.
73  *
74  * It was originally designed to address following three cases:
75  * 1) Receiving unix domain socket can not accept the rights, e.g.
76  *    when the so_rcv is full.
77  * 2) Caller of recvmsg(2) does not pass buffer to receive rights.
78  * 3) Unix domain sockets loop reference, e.g. s1 is on s2.so_rcv,
79  *    while s2 on s1.so_rcv.
80  *
81  * Code under UNP_GC_ALLFILES is intended to address all above three
82  * cases.  However, 1) was addressed a long time ago in uipc_send()
83  * (we inheritted the fix from FreeBSD when DragonFly forked).  2)
84  * was addressed in soreceive() by git-e62cfe62.  3) is the only
85  * case that needs GC.  The new code (!UNP_GC_ALLFILES) addresses
86  * case 3) in the following way:
87  * - Record the struct file in unpcb, if the Unix domain socket is
88  *   passed as one of the rights.
89  * - At GC time, only unpcbs are scanned, and only Unix domain sockets
90  *   that are still used as rights are potential GC targets.
91  */
92 
93 #define UNP_DETACHED		UNP_PRIVATE1
94 #define UNP_CONNECTING		UNP_PRIVATE2
95 #define UNP_DROPPED		UNP_PRIVATE3
96 #define UNP_MARKER		UNP_PRIVATE4
97 
98 #define UNPGC_REF		0x1	/* unpcb has external ref. */
99 #define UNPGC_DEAD		0x2	/* unpcb might be dead. */
100 #define UNPGC_SCANNED		0x4	/* Has been scanned. */
101 
102 #define UNP_GCFILE_MAX		256
103 
104 /* For unp_internalize() and unp_externalize() */
105 CTASSERT(sizeof(struct file *) >= sizeof(int));
106 
107 #define UNP_ISATTACHED(unp)	\
108     ((unp) != NULL && ((unp)->unp_flags & UNP_DETACHED) == 0)
109 
110 #ifdef INVARIANTS
111 #define UNP_ASSERT_TOKEN_HELD(unp) \
112     ASSERT_LWKT_TOKEN_HELD(lwkt_token_pool_lookup((unp)))
113 #else	/* !INVARIANTS */
114 #define UNP_ASSERT_TOKEN_HELD(unp)
115 #endif	/* INVARIANTS */
116 
117 struct unp_defdiscard {
118 	SLIST_ENTRY(unp_defdiscard) next;
119 	struct file *fp;
120 };
121 SLIST_HEAD(unp_defdiscard_list, unp_defdiscard);
122 
123 TAILQ_HEAD(unpcb_qhead, unpcb);
124 struct unp_global_head {
125 	struct unpcb_qhead	list;
126 	int			count;
127 };
128 
129 static	MALLOC_DEFINE(M_UNPCB, "unpcb", "unpcb struct");
130 static	unp_gen_t unp_gencnt;
131 
132 static struct unp_global_head unp_stream_head;
133 static struct unp_global_head unp_dgram_head;
134 static struct unp_global_head unp_seqpkt_head;
135 
136 static struct unp_global_head * const unp_heads[] =
137     { &unp_stream_head, &unp_dgram_head, &unp_seqpkt_head, NULL };
138 
139 static struct lwkt_token unp_token = LWKT_TOKEN_INITIALIZER(unp_token);
140 static struct taskqueue *unp_taskqueue;
141 
142 static struct unp_defdiscard_list unp_defdiscard_head;
143 static struct spinlock unp_defdiscard_spin;
144 static struct task unp_defdiscard_task;
145 
146 static struct	sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
147 
148 static int     unp_attach (struct socket *, struct pru_attach_info *);
149 static void    unp_detach (struct unpcb *);
150 static int     unp_bind (struct unpcb *,struct sockaddr *, struct thread *);
151 static int     unp_connect (struct socket *,struct sockaddr *,
152 				struct thread *);
153 static void    unp_disconnect(struct unpcb *, int);
154 static void    unp_shutdown (struct unpcb *);
155 static void    unp_gc(void *, int);
156 #ifdef UNP_GC_ALLFILES
157 static int     unp_gc_clearmarks(struct file *, void *);
158 static int     unp_gc_checkmarks(struct file *, void *);
159 static int     unp_gc_checkrefs(struct file *, void *);
160 static void    unp_mark(struct file *, void *data);
161 #endif
162 static void    unp_scan (struct mbuf *, void (*)(struct file *, void *),
163 				void *data);
164 static void    unp_discard (struct file *, void *);
165 static int     unp_internalize (struct mbuf *, struct thread *);
166 static int     unp_listen (struct unpcb *, struct thread *);
167 static void    unp_fp_externalize(struct lwp *lp, struct file *fp, int fd,
168 		   int flags);
169 static int     unp_find_lockref(struct sockaddr *nam, struct thread *td,
170 		   short type, struct unpcb **unp_ret);
171 static int     unp_connect_pair(struct unpcb *unp, struct unpcb *unp2);
172 static void    unp_drop(struct unpcb *unp, int error);
173 static void    unp_defdiscard_taskfunc(void *, int);
174 
175 static int	unp_rights;			/* file descriptors in flight */
176 static struct lwkt_token unp_rights_token =
177     LWKT_TOKEN_INITIALIZER(unp_rights_token);
178 static struct task unp_gc_task;
179 static struct unpcb *unp_gc_marker;
180 
181 SYSCTL_DECL(_net_local);
182 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
183    "File descriptors in flight");
184 
185 /*
186  * SMP Considerations:
187  *
188  *	Since unp_token will be automaticly released upon execution of
189  *	blocking code, we need to reference unp_conn before any possible
190  *	blocking code to prevent it from being ripped behind our back.
191  *
192  *	Any adjustment to unp->unp_conn requires both the global unp_token
193  *	AND the per-unp token (lwkt_token_pool_lookup(unp)) to be held.
194  *
195  *	Any access to so_pcb to obtain unp requires the pool token for
196  *	unp to be held.
197  */
198 
199 static __inline void
200 unp_reference(struct unpcb *unp)
201 {
202 	/* 0->1 transition will not work */
203 	KKASSERT(unp->unp_refcnt > 0);
204 	atomic_add_int(&unp->unp_refcnt, 1);
205 }
206 
207 static __inline void
208 unp_free(struct unpcb *unp)
209 {
210 	KKASSERT(unp->unp_refcnt > 0);
211 	if (atomic_fetchadd_int(&unp->unp_refcnt, -1) == 1)
212 		unp_detach(unp);
213 }
214 
215 static __inline struct unpcb *
216 unp_getsocktoken(struct socket *so)
217 {
218 	struct unpcb *unp;
219 
220 	/*
221 	 * The unp pointer is invalid until we verify that it is
222 	 * good by re-checking so_pcb AFTER obtaining the token.
223 	 */
224 	while ((unp = so->so_pcb) != NULL) {
225 		lwkt_getpooltoken(unp);
226 		if (unp == so->so_pcb)
227 			break;
228 		lwkt_relpooltoken(unp);
229 	}
230 	return unp;
231 }
232 
233 static __inline void
234 unp_reltoken(struct unpcb *unp)
235 {
236 	if (unp != NULL)
237 		lwkt_relpooltoken(unp);
238 }
239 
240 static __inline void
241 unp_setflags(struct unpcb *unp, int flags)
242 {
243 	atomic_set_int(&unp->unp_flags, flags);
244 }
245 
246 static __inline void
247 unp_clrflags(struct unpcb *unp, int flags)
248 {
249 	atomic_clear_int(&unp->unp_flags, flags);
250 }
251 
252 static __inline struct unp_global_head *
253 unp_globalhead(short type)
254 {
255 	switch (type) {
256 	case SOCK_STREAM:
257 		return &unp_stream_head;
258 	case SOCK_DGRAM:
259 		return &unp_dgram_head;
260 	case SOCK_SEQPACKET:
261 		return &unp_seqpkt_head;
262 	default:
263 		panic("unknown socket type %d", type);
264 	}
265 }
266 
267 static __inline struct unpcb *
268 unp_fp2unpcb(struct file *fp)
269 {
270 	struct socket *so;
271 
272 	if (fp->f_type != DTYPE_SOCKET)
273 		return NULL;
274 
275 	so = fp->f_data;
276 	if (so == NULL)
277 		return NULL;
278 
279 	if (so->so_proto->pr_domain != &localdomain)
280 		return NULL;
281 
282 	return so->so_pcb;
283 }
284 
285 static __inline void
286 unp_add_right(struct file *fp)
287 {
288 	struct unpcb *unp;
289 
290 	ASSERT_LWKT_TOKEN_HELD(&unp_rights_token);
291 	KASSERT(fp->f_count > 0, ("invalid f_count %d", fp->f_count));
292 
293 	unp = unp_fp2unpcb(fp);
294 	if (unp != NULL) {
295 		unp->unp_fp = fp;
296 		unp->unp_msgcount++;
297 	}
298 	fp->f_msgcount++;
299 	unp_rights++;
300 }
301 
302 static __inline void
303 unp_del_right(struct file *fp)
304 {
305 	struct unpcb *unp;
306 
307 	ASSERT_LWKT_TOKEN_HELD(&unp_rights_token);
308 	KASSERT(fp->f_count > 0, ("invalid f_count %d", fp->f_count));
309 
310 	unp = unp_fp2unpcb(fp);
311 	if (unp != NULL) {
312 		KASSERT(unp->unp_msgcount > 0,
313 		    ("invalid unp msgcount %d", unp->unp_msgcount));
314 		unp->unp_msgcount--;
315 		if (unp->unp_msgcount == 0)
316 			unp->unp_fp = NULL;
317 	}
318 	fp->f_msgcount--;
319 	unp_rights--;
320 }
321 
322 /*
323  * NOTE: (so) is referenced from soabort*() and netmsg_pru_abort()
324  *	 will sofree() it when we return.
325  */
326 static void
327 uipc_abort(netmsg_t msg)
328 {
329 	struct unpcb *unp;
330 	int error;
331 
332 	lwkt_gettoken(&unp_token);
333 	unp = unp_getsocktoken(msg->base.nm_so);
334 
335 	if (UNP_ISATTACHED(unp)) {
336 		unp_drop(unp, ECONNABORTED);
337 		error = 0;
338 	} else {
339 		error = EINVAL;
340 	}
341 
342 	unp_reltoken(unp);
343 	lwkt_reltoken(&unp_token);
344 
345 	lwkt_replymsg(&msg->lmsg, error);
346 }
347 
348 static void
349 uipc_accept(netmsg_t msg)
350 {
351 	struct unpcb *unp;
352 	int error;
353 
354 	lwkt_gettoken(&unp_token);
355 	unp = unp_getsocktoken(msg->base.nm_so);
356 
357 	if (!UNP_ISATTACHED(unp)) {
358 		error = EINVAL;
359 	} else {
360 		struct unpcb *unp2 = unp->unp_conn;
361 
362 		/*
363 		 * Pass back name of connected socket,
364 		 * if it was bound and we are still connected
365 		 * (our peer may have closed already!).
366 		 */
367 		if (unp2 && unp2->unp_addr) {
368 			unp_reference(unp2);
369 			*msg->accept.nm_nam = dup_sockaddr(
370 				(struct sockaddr *)unp2->unp_addr);
371 			unp_free(unp2);
372 		} else {
373 			*msg->accept.nm_nam = dup_sockaddr(&sun_noname);
374 		}
375 		error = 0;
376 	}
377 
378 	unp_reltoken(unp);
379 	lwkt_reltoken(&unp_token);
380 
381 	lwkt_replymsg(&msg->lmsg, error);
382 }
383 
384 static void
385 uipc_attach(netmsg_t msg)
386 {
387 	int error;
388 
389 	lwkt_gettoken(&unp_token);
390 
391 	KASSERT(msg->base.nm_so->so_pcb == NULL, ("double unp attach"));
392 	error = unp_attach(msg->base.nm_so, msg->attach.nm_ai);
393 
394 	lwkt_reltoken(&unp_token);
395 	lwkt_replymsg(&msg->lmsg, error);
396 }
397 
398 static void
399 uipc_bind(netmsg_t msg)
400 {
401 	struct unpcb *unp;
402 	int error;
403 
404 	lwkt_gettoken(&unp_token);
405 	unp = unp_getsocktoken(msg->base.nm_so);
406 
407 	if (UNP_ISATTACHED(unp))
408 		error = unp_bind(unp, msg->bind.nm_nam, msg->bind.nm_td);
409 	else
410 		error = EINVAL;
411 
412 	unp_reltoken(unp);
413 	lwkt_reltoken(&unp_token);
414 
415 	lwkt_replymsg(&msg->lmsg, error);
416 }
417 
418 static void
419 uipc_connect(netmsg_t msg)
420 {
421 	int error;
422 
423 	error = unp_connect(msg->base.nm_so, msg->connect.nm_nam,
424 	    msg->connect.nm_td);
425 	lwkt_replymsg(&msg->lmsg, error);
426 }
427 
428 static void
429 uipc_connect2(netmsg_t msg)
430 {
431 	int error;
432 
433 	error = unp_connect2(msg->connect2.nm_so1, msg->connect2.nm_so2,
434 			     msg->connect2.nm_cred);
435 	lwkt_replymsg(&msg->lmsg, error);
436 }
437 
438 /* control is EOPNOTSUPP */
439 
440 static void
441 uipc_detach(netmsg_t msg)
442 {
443 	struct unpcb *unp;
444 	int error;
445 
446 	lwkt_gettoken(&unp_token);
447 	unp = unp_getsocktoken(msg->base.nm_so);
448 
449 	if (UNP_ISATTACHED(unp)) {
450 		unp_drop(unp, 0);
451 		error = 0;
452 	} else {
453 		error = EINVAL;
454 	}
455 
456 	unp_reltoken(unp);
457 	lwkt_reltoken(&unp_token);
458 
459 	lwkt_replymsg(&msg->lmsg, error);
460 }
461 
462 static void
463 uipc_disconnect(netmsg_t msg)
464 {
465 	struct unpcb *unp;
466 	int error;
467 
468 	lwkt_gettoken(&unp_token);
469 	unp = unp_getsocktoken(msg->base.nm_so);
470 
471 	if (UNP_ISATTACHED(unp)) {
472 		unp_disconnect(unp, 0);
473 		error = 0;
474 	} else {
475 		error = EINVAL;
476 	}
477 
478 	unp_reltoken(unp);
479 	lwkt_reltoken(&unp_token);
480 
481 	lwkt_replymsg(&msg->lmsg, error);
482 }
483 
484 static void
485 uipc_listen(netmsg_t msg)
486 {
487 	struct unpcb *unp;
488 	int error;
489 
490 	lwkt_gettoken(&unp_token);
491 	unp = unp_getsocktoken(msg->base.nm_so);
492 
493 	if (!UNP_ISATTACHED(unp) || unp->unp_vnode == NULL)
494 		error = EINVAL;
495 	else
496 		error = unp_listen(unp, msg->listen.nm_td);
497 
498 	unp_reltoken(unp);
499 	lwkt_reltoken(&unp_token);
500 
501 	lwkt_replymsg(&msg->lmsg, error);
502 }
503 
504 static void
505 uipc_peeraddr(netmsg_t msg)
506 {
507 	struct unpcb *unp;
508 	int error;
509 
510 	lwkt_gettoken(&unp_token);
511 	unp = unp_getsocktoken(msg->base.nm_so);
512 
513 	if (!UNP_ISATTACHED(unp)) {
514 		error = EINVAL;
515 	} else if (unp->unp_conn && unp->unp_conn->unp_addr) {
516 		struct unpcb *unp2 = unp->unp_conn;
517 
518 		unp_reference(unp2);
519 		*msg->peeraddr.nm_nam = dup_sockaddr(
520 				(struct sockaddr *)unp2->unp_addr);
521 		unp_free(unp2);
522 		error = 0;
523 	} else {
524 		/*
525 		 * XXX: It seems that this test always fails even when
526 		 * connection is established.  So, this else clause is
527 		 * added as workaround to return PF_LOCAL sockaddr.
528 		 */
529 		*msg->peeraddr.nm_nam = dup_sockaddr(&sun_noname);
530 		error = 0;
531 	}
532 
533 	unp_reltoken(unp);
534 	lwkt_reltoken(&unp_token);
535 
536 	lwkt_replymsg(&msg->lmsg, error);
537 }
538 
539 static void
540 uipc_rcvd(netmsg_t msg)
541 {
542 	struct unpcb *unp, *unp2;
543 	struct socket *so;
544 	struct socket *so2;
545 	int error;
546 
547 	/*
548 	 * so_pcb is only modified with both the global and the unp
549 	 * pool token held.
550 	 */
551 	so = msg->base.nm_so;
552 	unp = unp_getsocktoken(so);
553 
554 	if (!UNP_ISATTACHED(unp)) {
555 		error = EINVAL;
556 		goto done;
557 	}
558 
559 	switch (so->so_type) {
560 	case SOCK_DGRAM:
561 		panic("uipc_rcvd DGRAM?");
562 		/*NOTREACHED*/
563 	case SOCK_STREAM:
564 	case SOCK_SEQPACKET:
565 		if (unp->unp_conn == NULL)
566 			break;
567 		unp2 = unp->unp_conn;	/* protected by pool token */
568 
569 		/*
570 		 * Because we are transfering mbufs directly to the
571 		 * peer socket we have to use SSB_STOP on the sender
572 		 * to prevent it from building up infinite mbufs.
573 		 *
574 		 * As in several places in this module w ehave to ref unp2
575 		 * to ensure that it does not get ripped out from under us
576 		 * if we block on the so2 token or in sowwakeup().
577 		 */
578 		so2 = unp2->unp_socket;
579 		unp_reference(unp2);
580 		lwkt_gettoken(&so2->so_rcv.ssb_token);
581 		if (so->so_rcv.ssb_cc < so2->so_snd.ssb_hiwat &&
582 		    so->so_rcv.ssb_mbcnt < so2->so_snd.ssb_mbmax
583 		) {
584 			atomic_clear_int(&so2->so_snd.ssb_flags, SSB_STOP);
585 
586 			sowwakeup(so2);
587 		}
588 		lwkt_reltoken(&so2->so_rcv.ssb_token);
589 		unp_free(unp2);
590 		break;
591 	default:
592 		panic("uipc_rcvd unknown socktype");
593 		/*NOTREACHED*/
594 	}
595 	error = 0;
596 done:
597 	unp_reltoken(unp);
598 	lwkt_replymsg(&msg->lmsg, error);
599 }
600 
601 /* pru_rcvoob is EOPNOTSUPP */
602 
603 static void
604 uipc_send(netmsg_t msg)
605 {
606 	struct unpcb *unp, *unp2;
607 	struct socket *so;
608 	struct socket *so2;
609 	struct mbuf *control;
610 	struct mbuf *m;
611 	int error = 0;
612 
613 	so = msg->base.nm_so;
614 	control = msg->send.nm_control;
615 	m = msg->send.nm_m;
616 
617 	/*
618 	 * so_pcb is only modified with both the global and the unp
619 	 * pool token held.
620 	 */
621 	so = msg->base.nm_so;
622 	unp = unp_getsocktoken(so);
623 
624 	if (!UNP_ISATTACHED(unp)) {
625 		error = EINVAL;
626 		goto release;
627 	}
628 
629 	if (msg->send.nm_flags & PRUS_OOB) {
630 		error = EOPNOTSUPP;
631 		goto release;
632 	}
633 
634 	wakeup_start_delayed();
635 
636 	if (control && (error = unp_internalize(control, msg->send.nm_td)))
637 		goto release;
638 
639 	switch (so->so_type) {
640 	case SOCK_DGRAM:
641 	{
642 		struct sockaddr *from;
643 
644 		if (msg->send.nm_addr) {
645 			if (unp->unp_conn) {
646 				error = EISCONN;
647 				break;
648 			}
649 			lwkt_gettoken(&unp_token);
650 			error = unp_find_lockref(msg->send.nm_addr,
651 			    msg->send.nm_td, so->so_type, &unp2);
652 			if (error) {
653 				lwkt_reltoken(&unp_token);
654 				break;
655 			}
656 			/*
657 			 * NOTE:
658 			 * unp2 is locked and referenced.
659 			 *
660 			 * We could unlock unp2 now, since it was checked
661 			 * and referenced.
662 			 */
663 			unp_reltoken(unp2);
664 			lwkt_reltoken(&unp_token);
665 		} else {
666 			if (unp->unp_conn == NULL) {
667 				error = ENOTCONN;
668 				break;
669 			}
670 			unp2 = unp->unp_conn;
671 			unp_reference(unp2);
672 		}
673 		/* NOTE: unp2 is referenced. */
674 		so2 = unp2->unp_socket;
675 
676 		/*
677 		 * Include creds if the receive side wants them, even if
678 		 * the send side did not send them.
679 		 */
680 		if (so2->so_options & SO_PASSCRED) {
681 			struct mbuf **mp;
682 			struct cmsghdr *cm;
683 			struct cmsgcred cred;
684 			struct mbuf *ncon;
685 
686 			mp = &control;
687 			while ((ncon = *mp) != NULL) {
688 				cm = mtod(ncon, struct cmsghdr *);
689 				if (cm->cmsg_type == SCM_CREDS &&
690 				    cm->cmsg_level == SOL_SOCKET)
691 					break;
692 				mp = &ncon->m_next;
693 			}
694 			if (ncon == NULL) {
695 				ncon = sbcreatecontrol((caddr_t)&cred,
696 						       sizeof(cred),
697 						       SCM_CREDS, SOL_SOCKET);
698 				unp_internalize(ncon, msg->send.nm_td);
699 				*mp = ncon;
700 			}
701 		}
702 
703 		if (unp->unp_addr)
704 			from = (struct sockaddr *)unp->unp_addr;
705 		else
706 			from = &sun_noname;
707 
708 		lwkt_gettoken(&so2->so_rcv.ssb_token);
709 		if (ssb_appendaddr(&so2->so_rcv, from, m, control)) {
710 			sorwakeup(so2);
711 			m = NULL;
712 			control = NULL;
713 		} else {
714 			error = ENOBUFS;
715 		}
716 		lwkt_reltoken(&so2->so_rcv.ssb_token);
717 
718 		unp_free(unp2);
719 		break;
720 	}
721 
722 	case SOCK_STREAM:
723 	case SOCK_SEQPACKET:
724 		/* Connect if not connected yet. */
725 		/*
726 		 * Note: A better implementation would complain
727 		 * if not equal to the peer's address.
728 		 */
729 		if (unp->unp_conn == NULL) {
730 			if (msg->send.nm_addr) {
731 				error = unp_connect(so,
732 						    msg->send.nm_addr,
733 						    msg->send.nm_td);
734 				if (error)
735 					break;	/* XXX */
736 			}
737 			/*
738 			 * NOTE:
739 			 * unp_conn still could be NULL, even if the
740 			 * above unp_connect() succeeds; since the
741 			 * current unp's token could be released due
742 			 * to blocking operations after unp_conn is
743 			 * assigned.
744 			 */
745 			if (unp->unp_conn == NULL) {
746 				error = ENOTCONN;
747 				break;
748 			}
749 		}
750 		if (so->so_state & SS_CANTSENDMORE) {
751 			error = EPIPE;
752 			break;
753 		}
754 
755 		unp2 = unp->unp_conn;
756 		KASSERT(unp2 != NULL, ("unp is not connected"));
757 		so2 = unp2->unp_socket;
758 
759 		unp_reference(unp2);
760 
761 		/*
762 		 * Send to paired receive port, and then reduce
763 		 * send buffer hiwater marks to maintain backpressure.
764 		 * Wake up readers.
765 		 */
766 		lwkt_gettoken(&so2->so_rcv.ssb_token);
767 		if (control) {
768 			if (ssb_appendcontrol(&so2->so_rcv, m, control)) {
769 				control = NULL;
770 				m = NULL;
771 			}
772 		} else if (so->so_type == SOCK_SEQPACKET) {
773 			sbappendrecord(&so2->so_rcv.sb, m);
774 			m = NULL;
775 		} else {
776 			sbappend(&so2->so_rcv.sb, m);
777 			m = NULL;
778 		}
779 
780 		/*
781 		 * Because we are transfering mbufs directly to the
782 		 * peer socket we have to use SSB_STOP on the sender
783 		 * to prevent it from building up infinite mbufs.
784 		 */
785 		if (so2->so_rcv.ssb_cc >= so->so_snd.ssb_hiwat ||
786 		    so2->so_rcv.ssb_mbcnt >= so->so_snd.ssb_mbmax
787 		) {
788 			atomic_set_int(&so->so_snd.ssb_flags, SSB_STOP);
789 		}
790 		lwkt_reltoken(&so2->so_rcv.ssb_token);
791 		sorwakeup(so2);
792 
793 		unp_free(unp2);
794 		break;
795 
796 	default:
797 		panic("uipc_send unknown socktype");
798 	}
799 
800 	/*
801 	 * SEND_EOF is equivalent to a SEND followed by a SHUTDOWN.
802 	 */
803 	if (msg->send.nm_flags & PRUS_EOF) {
804 		socantsendmore(so);
805 		unp_shutdown(unp);
806 	}
807 
808 	if (control && error != 0)
809 		unp_dispose(control);
810 release:
811 	unp_reltoken(unp);
812 	wakeup_end_delayed();
813 
814 	if (control)
815 		m_freem(control);
816 	if (m)
817 		m_freem(m);
818 	lwkt_replymsg(&msg->lmsg, error);
819 }
820 
821 /*
822  * MPSAFE
823  */
824 static void
825 uipc_sense(netmsg_t msg)
826 {
827 	struct unpcb *unp;
828 	struct socket *so;
829 	struct stat *sb;
830 	int error;
831 
832 	so = msg->base.nm_so;
833 	sb = msg->sense.nm_stat;
834 
835 	/*
836 	 * so_pcb is only modified with both the global and the unp
837 	 * pool token held.
838 	 */
839 	unp = unp_getsocktoken(so);
840 
841 	if (!UNP_ISATTACHED(unp)) {
842 		error = EINVAL;
843 		goto done;
844 	}
845 
846 	sb->st_blksize = so->so_snd.ssb_hiwat;
847 	sb->st_dev = NOUDEV;
848 	error = 0;
849 done:
850 	unp_reltoken(unp);
851 	lwkt_replymsg(&msg->lmsg, error);
852 }
853 
854 static void
855 uipc_shutdown(netmsg_t msg)
856 {
857 	struct socket *so;
858 	struct unpcb *unp;
859 	int error;
860 
861 	/*
862 	 * so_pcb is only modified with both the global and the unp
863 	 * pool token held.
864 	 */
865 	so = msg->base.nm_so;
866 	unp = unp_getsocktoken(so);
867 
868 	if (UNP_ISATTACHED(unp)) {
869 		socantsendmore(so);
870 		unp_shutdown(unp);
871 		error = 0;
872 	} else {
873 		error = EINVAL;
874 	}
875 
876 	unp_reltoken(unp);
877 	lwkt_replymsg(&msg->lmsg, error);
878 }
879 
880 static void
881 uipc_sockaddr(netmsg_t msg)
882 {
883 	struct unpcb *unp;
884 	int error;
885 
886 	/*
887 	 * so_pcb is only modified with both the global and the unp
888 	 * pool token held.
889 	 */
890 	unp = unp_getsocktoken(msg->base.nm_so);
891 
892 	if (UNP_ISATTACHED(unp)) {
893 		if (unp->unp_addr) {
894 			*msg->sockaddr.nm_nam =
895 				dup_sockaddr((struct sockaddr *)unp->unp_addr);
896 		}
897 		error = 0;
898 	} else {
899 		error = EINVAL;
900 	}
901 
902 	unp_reltoken(unp);
903 	lwkt_replymsg(&msg->lmsg, error);
904 }
905 
906 struct pr_usrreqs uipc_usrreqs = {
907 	.pru_abort = uipc_abort,
908 	.pru_accept = uipc_accept,
909 	.pru_attach = uipc_attach,
910 	.pru_bind = uipc_bind,
911 	.pru_connect = uipc_connect,
912 	.pru_connect2 = uipc_connect2,
913 	.pru_control = pr_generic_notsupp,
914 	.pru_detach = uipc_detach,
915 	.pru_disconnect = uipc_disconnect,
916 	.pru_listen = uipc_listen,
917 	.pru_peeraddr = uipc_peeraddr,
918 	.pru_rcvd = uipc_rcvd,
919 	.pru_rcvoob = pr_generic_notsupp,
920 	.pru_send = uipc_send,
921 	.pru_sense = uipc_sense,
922 	.pru_shutdown = uipc_shutdown,
923 	.pru_sockaddr = uipc_sockaddr,
924 	.pru_sosend = sosend,
925 	.pru_soreceive = soreceive
926 };
927 
928 void
929 uipc_ctloutput(netmsg_t msg)
930 {
931 	struct socket *so;
932 	struct sockopt *sopt;
933 	struct unpcb *unp;
934 	int error = 0;
935 
936 	so = msg->base.nm_so;
937 	sopt = msg->ctloutput.nm_sopt;
938 
939 	lwkt_gettoken(&unp_token);
940 	unp = unp_getsocktoken(so);
941 
942 	if (!UNP_ISATTACHED(unp)) {
943 		error = EINVAL;
944 		goto done;
945 	}
946 
947 	switch (sopt->sopt_dir) {
948 	case SOPT_GET:
949 		switch (sopt->sopt_name) {
950 		case LOCAL_PEERCRED:
951 			if (unp->unp_flags & UNP_HAVEPC)
952 				soopt_from_kbuf(sopt, &unp->unp_peercred,
953 						sizeof(unp->unp_peercred));
954 			else {
955 				if (so->so_type == SOCK_STREAM)
956 					error = ENOTCONN;
957 				else if (so->so_type == SOCK_SEQPACKET)
958 					error = ENOTCONN;
959 				else
960 					error = EINVAL;
961 			}
962 			break;
963 		default:
964 			error = EOPNOTSUPP;
965 			break;
966 		}
967 		break;
968 	case SOPT_SET:
969 	default:
970 		error = EOPNOTSUPP;
971 		break;
972 	}
973 
974 done:
975 	unp_reltoken(unp);
976 	lwkt_reltoken(&unp_token);
977 
978 	lwkt_replymsg(&msg->lmsg, error);
979 }
980 
981 /*
982  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
983  * for stream sockets, although the total for sender and receiver is
984  * actually only PIPSIZ.
985  *
986  * Datagram sockets really use the sendspace as the maximum datagram size,
987  * and don't really want to reserve the sendspace.  Their recvspace should
988  * be large enough for at least one max-size datagram plus address.
989  *
990  * We want the local send/recv space to be significant larger then lo0's
991  * mtu of 16384.
992  *
993  * We no longer need to worry about avoiding the windows scaling option.
994  * Programs which use unix domain sockets expect larger defaults these days.
995  */
996 #ifndef PIPSIZ
997 #define	PIPSIZ	65536
998 #endif
999 static u_long	unpst_sendspace = PIPSIZ;
1000 static u_long	unpst_recvspace = PIPSIZ;
1001 static u_long	unpdg_sendspace = PIPSIZ;	/* really max datagram size */
1002 static u_long	unpdg_recvspace = PIPSIZ;
1003 static u_long	unpsp_sendspace = PIPSIZ;	/* really max datagram size */
1004 static u_long	unpsp_recvspace = PIPSIZ;
1005 
1006 SYSCTL_DECL(_net_local_stream);
1007 SYSCTL_DECL(_net_local_dgram);
1008 SYSCTL_DECL(_net_local_seqpacket);
1009 
1010 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
1011     &unpst_sendspace, 0, "Size of stream socket send buffer");
1012 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
1013     &unpst_recvspace, 0, "Size of stream socket receive buffer");
1014 
1015 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
1016     &unpdg_sendspace, 0, "Max datagram socket size");
1017 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
1018     &unpdg_recvspace, 0, "Size of datagram socket receive buffer");
1019 
1020 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
1021     &unpsp_sendspace, 0, "Default seqpacket send space.");
1022 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
1023     &unpsp_recvspace, 0, "Default seqpacket receive space.");
1024 
1025 
1026 static int
1027 unp_attach(struct socket *so, struct pru_attach_info *ai)
1028 {
1029 	struct unp_global_head *head;
1030 	struct unpcb *unp;
1031 	int error;
1032 
1033 	lwkt_gettoken(&unp_token);
1034 
1035 	if (so->so_snd.ssb_hiwat == 0 || so->so_rcv.ssb_hiwat == 0) {
1036 		switch (so->so_type) {
1037 		case SOCK_STREAM:
1038 			error = soreserve(so, unpst_sendspace, unpst_recvspace,
1039 					  ai->sb_rlimit);
1040 			break;
1041 		case SOCK_DGRAM:
1042 			error = soreserve(so, unpdg_sendspace, unpdg_recvspace,
1043 					  ai->sb_rlimit);
1044 			break;
1045 		case SOCK_SEQPACKET:
1046 			error = soreserve(so, unpsp_sendspace, unpsp_recvspace,
1047 					  ai->sb_rlimit);
1048 			break;
1049 		default:
1050 			panic("unp_attach");
1051 		}
1052 		if (error)
1053 			goto failed;
1054 	}
1055 
1056 	/*
1057 	 * In order to support sendfile we have to set either SSB_STOPSUPP
1058 	 * or SSB_PREALLOC.  Unix domain sockets use the SSB_STOP flow
1059 	 * control mechanism.
1060 	 */
1061 	if (so->so_type == SOCK_STREAM) {
1062 		atomic_set_int(&so->so_rcv.ssb_flags, SSB_STOPSUPP);
1063 		atomic_set_int(&so->so_snd.ssb_flags, SSB_STOPSUPP);
1064 	}
1065 
1066 	unp = kmalloc(sizeof(*unp), M_UNPCB, M_WAITOK | M_ZERO | M_NULLOK);
1067 	if (unp == NULL) {
1068 		error = ENOBUFS;
1069 		goto failed;
1070 	}
1071 	unp->unp_refcnt = 1;
1072 	unp->unp_gencnt = ++unp_gencnt;
1073 	LIST_INIT(&unp->unp_refs);
1074 	unp->unp_socket = so;
1075 	unp->unp_rvnode = ai->fd_rdir;		/* jail cruft XXX JH */
1076 	so->so_pcb = (caddr_t)unp;
1077 	soreference(so);
1078 
1079 	head = unp_globalhead(so->so_type);
1080 	TAILQ_INSERT_TAIL(&head->list, unp, unp_link);
1081 	head->count++;
1082 	error = 0;
1083 failed:
1084 	lwkt_reltoken(&unp_token);
1085 	return error;
1086 }
1087 
1088 static void
1089 unp_detach(struct unpcb *unp)
1090 {
1091 	struct socket *so;
1092 
1093 	lwkt_gettoken(&unp_token);
1094 	lwkt_getpooltoken(unp);
1095 
1096 	so = unp->unp_socket;
1097 
1098 	unp->unp_gencnt = ++unp_gencnt;
1099 	if (unp->unp_vnode) {
1100 		unp->unp_vnode->v_socket = NULL;
1101 		vrele(unp->unp_vnode);
1102 		unp->unp_vnode = NULL;
1103 	}
1104 	soisdisconnected(so);
1105 	KKASSERT(so->so_pcb == unp);
1106 	so->so_pcb = NULL;		/* both tokens required */
1107 	unp->unp_socket = NULL;
1108 
1109 	lwkt_relpooltoken(unp);
1110 	lwkt_reltoken(&unp_token);
1111 
1112 	sofree(so);
1113 
1114 	KASSERT(unp->unp_conn == NULL, ("unp is still connected"));
1115 	KASSERT(LIST_EMPTY(&unp->unp_refs), ("unp still has references"));
1116 
1117 	if (unp->unp_addr)
1118 		kfree(unp->unp_addr, M_SONAME);
1119 	kfree(unp, M_UNPCB);
1120 
1121 	if (unp_rights)
1122 		taskqueue_enqueue(unp_taskqueue, &unp_gc_task);
1123 }
1124 
1125 static int
1126 unp_bind(struct unpcb *unp, struct sockaddr *nam, struct thread *td)
1127 {
1128 	struct proc *p = td->td_proc;
1129 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1130 	struct vnode *vp;
1131 	struct vattr vattr;
1132 	int error, namelen;
1133 	struct nlookupdata nd;
1134 	char buf[SOCK_MAXADDRLEN];
1135 
1136 	ASSERT_LWKT_TOKEN_HELD(&unp_token);
1137 	UNP_ASSERT_TOKEN_HELD(unp);
1138 
1139 	if (unp->unp_vnode != NULL)
1140 		return EINVAL;
1141 
1142 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
1143 	if (namelen <= 0)
1144 		return EINVAL;
1145 	strncpy(buf, soun->sun_path, namelen);
1146 	buf[namelen] = 0;	/* null-terminate the string */
1147 	error = nlookup_init(&nd, buf, UIO_SYSSPACE,
1148 			     NLC_LOCKVP | NLC_CREATE | NLC_REFDVP);
1149 	if (error == 0)
1150 		error = nlookup(&nd);
1151 	if (error == 0 && nd.nl_nch.ncp->nc_vp != NULL)
1152 		error = EADDRINUSE;
1153 	if (error == 0 && nd.nl_dvp == NULL)	/* e.g. bind <mountpt> */
1154 		error = EINVAL;
1155 	if (error)
1156 		goto done;
1157 
1158 	VATTR_NULL(&vattr);
1159 	vattr.va_type = VSOCK;
1160 	vattr.va_mode = (ACCESSPERMS & ~p->p_fd->fd_cmask);
1161 	error = VOP_NCREATE(&nd.nl_nch, nd.nl_dvp, &vp, nd.nl_cred, &vattr);
1162 	if (error == 0) {
1163 		if (unp->unp_vnode == NULL) {
1164 			vp->v_socket = unp->unp_socket;
1165 			unp->unp_vnode = vp;
1166 			unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam);
1167 			vn_unlock(vp);
1168 		} else {
1169 			vput(vp);		/* late race */
1170 			error = EINVAL;
1171 		}
1172 	}
1173 done:
1174 	nlookup_done(&nd);
1175 	return (error);
1176 }
1177 
1178 static int
1179 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1180 {
1181 	struct unpcb *unp, *unp2;
1182 	int error, flags = 0;
1183 
1184 	lwkt_gettoken(&unp_token);
1185 
1186 	unp = unp_getsocktoken(so);
1187 	if (!UNP_ISATTACHED(unp)) {
1188 		error = EINVAL;
1189 		goto failed;
1190 	}
1191 
1192 	if ((unp->unp_flags & UNP_CONNECTING) || unp->unp_conn != NULL) {
1193 		error = EISCONN;
1194 		goto failed;
1195 	}
1196 
1197 	flags = UNP_CONNECTING;
1198 	unp_setflags(unp, flags);
1199 
1200 	error = unp_find_lockref(nam, td, so->so_type, &unp2);
1201 	if (error)
1202 		goto failed;
1203 	/*
1204 	 * NOTE:
1205 	 * unp2 is locked and referenced.
1206 	 */
1207 
1208 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1209 		struct socket *so2, *so3;
1210 		struct unpcb *unp3;
1211 
1212 		so2 = unp2->unp_socket;
1213 		if (!(so2->so_options & SO_ACCEPTCONN) ||
1214 		    /* listen is not completed yet */
1215 		    !(unp2->unp_flags & UNP_HAVEPCCACHED) ||
1216 		    (so3 = sonewconn_faddr(so2, 0, NULL,
1217 		     TRUE /* keep ref */)) == NULL) {
1218 			error = ECONNREFUSED;
1219 			goto done;
1220 		}
1221 		/* so3 has a socket reference. */
1222 
1223 		unp3 = unp_getsocktoken(so3);
1224 		if (!UNP_ISATTACHED(unp3)) {
1225 			unp_reltoken(unp3);
1226 			/*
1227 			 * Already aborted; we only need to drop the
1228 			 * socket reference held by sonewconn_faddr().
1229 			 */
1230 			sofree(so3);
1231 			error = ECONNREFUSED;
1232 			goto done;
1233 		}
1234 		unp_reference(unp3);
1235 		/*
1236 		 * NOTE:
1237 		 * unp3 is locked and referenced.
1238 		 */
1239 
1240 		/*
1241 		 * Release so3 socket reference held by sonewconn_faddr().
1242 		 * Since we have referenced unp3, neither unp3 nor so3 will
1243 		 * be destroyed here.
1244 		 */
1245 		sofree(so3);
1246 
1247 		if (unp2->unp_addr != NULL) {
1248 			unp3->unp_addr = (struct sockaddr_un *)
1249 			    dup_sockaddr((struct sockaddr *)unp2->unp_addr);
1250 		}
1251 
1252 		/*
1253 		 * unp_peercred management:
1254 		 *
1255 		 * The connecter's (client's) credentials are copied
1256 		 * from its process structure at the time of connect()
1257 		 * (which is now).
1258 		 */
1259 		cru2x(td->td_proc->p_ucred, &unp3->unp_peercred);
1260 		unp_setflags(unp3, UNP_HAVEPC);
1261 		/*
1262 		 * The receiver's (server's) credentials are copied
1263 		 * from the unp_peercred member of socket on which the
1264 		 * former called listen(); unp_listen() cached that
1265 		 * process's credentials at that time so we can use
1266 		 * them now.
1267 		 */
1268 		KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1269 		    ("unp_connect: listener without cached peercred"));
1270 		memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1271 		    sizeof(unp->unp_peercred));
1272 		unp_setflags(unp, UNP_HAVEPC);
1273 
1274 		error = unp_connect_pair(unp, unp3);
1275 		if (error)
1276 			soabort_direct(so3);
1277 
1278 		/* Done with unp3 */
1279 		unp_free(unp3);
1280 		unp_reltoken(unp3);
1281 	} else {
1282 		error = unp_connect_pair(unp, unp2);
1283 	}
1284 done:
1285 	unp_free(unp2);
1286 	unp_reltoken(unp2);
1287 failed:
1288 	if (flags)
1289 		unp_clrflags(unp, flags);
1290 	unp_reltoken(unp);
1291 
1292 	lwkt_reltoken(&unp_token);
1293 	return (error);
1294 }
1295 
1296 /*
1297  * Connect two unix domain sockets together.
1298  *
1299  * NOTE: Semantics for any change to unp_conn requires that the per-unp
1300  *	 pool token also be held.
1301  */
1302 int
1303 unp_connect2(struct socket *so, struct socket *so2, struct ucred *cred)
1304 {
1305 	struct unpcb *unp, *unp2;
1306 	int error;
1307 
1308 	lwkt_gettoken(&unp_token);
1309 	if (so2->so_type != so->so_type) {
1310 		lwkt_reltoken(&unp_token);
1311 		return (EPROTOTYPE);
1312 	}
1313 	unp = unp_getsocktoken(so);
1314 	unp2 = unp_getsocktoken(so2);
1315 
1316 	cru2x(cred, &unp->unp_peercred);
1317 	cru2x(cred, &unp2->unp_peercred);
1318 	unp_setflags(unp, UNP_HAVEPC);
1319 	unp_setflags(unp2, UNP_HAVEPC);
1320 
1321 	if (!UNP_ISATTACHED(unp)) {
1322 		error = EINVAL;
1323 		goto done;
1324 	}
1325 	if (!UNP_ISATTACHED(unp2)) {
1326 		error = ECONNREFUSED;
1327 		goto done;
1328 	}
1329 
1330 	if (unp->unp_conn != NULL) {
1331 		error = EISCONN;
1332 		goto done;
1333 	}
1334 	if ((so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET) &&
1335 	    unp2->unp_conn != NULL) {
1336 		error = EISCONN;
1337 		goto done;
1338 	}
1339 
1340 	error = unp_connect_pair(unp, unp2);
1341 done:
1342 	unp_reltoken(unp2);
1343 	unp_reltoken(unp);
1344 	lwkt_reltoken(&unp_token);
1345 	return (error);
1346 }
1347 
1348 /*
1349  * Disconnect a unix domain socket pair.
1350  *
1351  * NOTE: Semantics for any change to unp_conn requires that the per-unp
1352  *	 pool token also be held.
1353  */
1354 static void
1355 unp_disconnect(struct unpcb *unp, int error)
1356 {
1357 	struct socket *so = unp->unp_socket;
1358 	struct unpcb *unp2;
1359 
1360 	ASSERT_LWKT_TOKEN_HELD(&unp_token);
1361 	UNP_ASSERT_TOKEN_HELD(unp);
1362 
1363 	if (error)
1364 		so->so_error = error;
1365 
1366 	while ((unp2 = unp->unp_conn) != NULL) {
1367 		lwkt_getpooltoken(unp2);
1368 		if (unp2 == unp->unp_conn)
1369 			break;
1370 		lwkt_relpooltoken(unp2);
1371 	}
1372 	if (unp2 == NULL)
1373 		return;
1374 	/* unp2 is locked. */
1375 
1376 	KASSERT((unp2->unp_flags & UNP_DROPPED) == 0, ("unp2 was dropped"));
1377 
1378 	unp->unp_conn = NULL;
1379 
1380 	switch (so->so_type) {
1381 	case SOCK_DGRAM:
1382 		LIST_REMOVE(unp, unp_reflink);
1383 		soclrstate(so, SS_ISCONNECTED);
1384 		break;
1385 
1386 	case SOCK_STREAM:
1387 	case SOCK_SEQPACKET:
1388 		/*
1389 		 * Keep a reference before clearing the unp_conn
1390 		 * to avoid racing uipc_detach()/uipc_abort() in
1391 		 * other thread.
1392 		 */
1393 		unp_reference(unp2);
1394 		KASSERT(unp2->unp_conn == unp, ("unp_conn mismatch"));
1395 		unp2->unp_conn = NULL;
1396 
1397 		soisdisconnected(so);
1398 		soisdisconnected(unp2->unp_socket);
1399 
1400 		unp_free(unp2);
1401 		break;
1402 	}
1403 
1404 	lwkt_relpooltoken(unp2);
1405 }
1406 
1407 #ifdef notdef
1408 void
1409 unp_abort(struct unpcb *unp)
1410 {
1411 	lwkt_gettoken(&unp_token);
1412 	unp_free(unp);
1413 	lwkt_reltoken(&unp_token);
1414 }
1415 #endif
1416 
1417 static int
1418 prison_unpcb(struct thread *td, struct unpcb *unp)
1419 {
1420 	struct proc *p;
1421 
1422 	if (td == NULL)
1423 		return (0);
1424 	if ((p = td->td_proc) == NULL)
1425 		return (0);
1426 	if (!p->p_ucred->cr_prison)
1427 		return (0);
1428 	if (p->p_fd->fd_rdir == unp->unp_rvnode)
1429 		return (0);
1430 	return (1);
1431 }
1432 
1433 static int
1434 unp_pcblist(SYSCTL_HANDLER_ARGS)
1435 {
1436 	struct unp_global_head *head = arg1;
1437 	int error, i, n;
1438 	struct unpcb *unp, *marker;
1439 
1440 	KKASSERT(curproc != NULL);
1441 
1442 	/*
1443 	 * The process of preparing the PCB list is too time-consuming and
1444 	 * resource-intensive to repeat twice on every request.
1445 	 */
1446 	if (req->oldptr == NULL) {
1447 		n = head->count;
1448 		req->oldidx = (n + n/8) * sizeof(struct xunpcb);
1449 		return 0;
1450 	}
1451 
1452 	if (req->newptr != NULL)
1453 		return EPERM;
1454 
1455 	marker = kmalloc(sizeof(*marker), M_UNPCB, M_WAITOK | M_ZERO);
1456 	marker->unp_flags |= UNP_MARKER;
1457 
1458 	lwkt_gettoken(&unp_token);
1459 
1460 	n = head->count;
1461 	i = 0;
1462 	error = 0;
1463 
1464 	TAILQ_INSERT_HEAD(&head->list, marker, unp_link);
1465 	while ((unp = TAILQ_NEXT(marker, unp_link)) != NULL && i < n) {
1466 		struct xunpcb xu;
1467 
1468 		TAILQ_REMOVE(&head->list, marker, unp_link);
1469 		TAILQ_INSERT_AFTER(&head->list, unp, marker, unp_link);
1470 
1471 		if (unp->unp_flags & UNP_MARKER)
1472 			continue;
1473 		if (prison_unpcb(req->td, unp))
1474 			continue;
1475 
1476 		xu.xu_len = sizeof(xu);
1477 		xu.xu_unpp = unp;
1478 
1479 		/*
1480 		 * NOTE:
1481 		 * unp->unp_addr and unp->unp_conn are protected by
1482 		 * unp_token.  So if we want to get rid of unp_token
1483 		 * or reduce the coverage of unp_token, care must be
1484 		 * taken.
1485 		 */
1486 		if (unp->unp_addr) {
1487 			bcopy(unp->unp_addr, &xu.xu_addr,
1488 			      unp->unp_addr->sun_len);
1489 		}
1490 		if (unp->unp_conn && unp->unp_conn->unp_addr) {
1491 			bcopy(unp->unp_conn->unp_addr,
1492 			      &xu.xu_caddr,
1493 			      unp->unp_conn->unp_addr->sun_len);
1494 		}
1495 		bcopy(unp, &xu.xu_unp, sizeof(*unp));
1496 		sotoxsocket(unp->unp_socket, &xu.xu_socket);
1497 
1498 		/* NOTE: This could block and temporarily release unp_token */
1499 		error = SYSCTL_OUT(req, &xu, sizeof(xu));
1500 		if (error)
1501 			break;
1502 		++i;
1503 	}
1504 	TAILQ_REMOVE(&head->list, marker, unp_link);
1505 
1506 	lwkt_reltoken(&unp_token);
1507 
1508 	kfree(marker, M_UNPCB);
1509 	return error;
1510 }
1511 
1512 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1513 	    &unp_dgram_head, 0, unp_pcblist, "S,xunpcb",
1514 	    "List of active local datagram sockets");
1515 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1516 	    &unp_stream_head, 0, unp_pcblist, "S,xunpcb",
1517 	    "List of active local stream sockets");
1518 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist, CTLFLAG_RD,
1519 	    &unp_seqpkt_head, 0, unp_pcblist, "S,xunpcb",
1520 	    "List of active local seqpacket sockets");
1521 
1522 static void
1523 unp_shutdown(struct unpcb *unp)
1524 {
1525 	struct socket *so;
1526 
1527 	if ((unp->unp_socket->so_type == SOCK_STREAM ||
1528 	     unp->unp_socket->so_type == SOCK_SEQPACKET) &&
1529 	    unp->unp_conn != NULL && (so = unp->unp_conn->unp_socket)) {
1530 		socantrcvmore(so);
1531 	}
1532 }
1533 
1534 #ifdef notdef
1535 void
1536 unp_drain(void)
1537 {
1538 	lwkt_gettoken(&unp_token);
1539 	lwkt_reltoken(&unp_token);
1540 }
1541 #endif
1542 
1543 int
1544 unp_externalize(struct mbuf *rights, int flags)
1545 {
1546 	struct thread *td = curthread;
1547 	struct proc *p = td->td_proc;		/* XXX */
1548 	struct lwp *lp = td->td_lwp;
1549 	struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
1550 	int *fdp;
1551 	int i;
1552 	struct file **rp;
1553 	struct file *fp;
1554 	int newfds = (cm->cmsg_len - (CMSG_DATA(cm) - (u_char *)cm))
1555 		/ sizeof(struct file *);
1556 	int f;
1557 
1558 	lwkt_gettoken(&unp_rights_token);
1559 
1560 	/*
1561 	 * if the new FD's will not fit, then we free them all
1562 	 */
1563 	if (!fdavail(p, newfds)) {
1564 		rp = (struct file **)CMSG_DATA(cm);
1565 		for (i = 0; i < newfds; i++) {
1566 			fp = *rp;
1567 			/*
1568 			 * zero the pointer before calling unp_discard,
1569 			 * since it may end up in unp_gc()..
1570 			 */
1571 			*rp++ = NULL;
1572 			unp_discard(fp, NULL);
1573 		}
1574 		lwkt_reltoken(&unp_rights_token);
1575 		return (EMSGSIZE);
1576 	}
1577 
1578 	/*
1579 	 * now change each pointer to an fd in the global table to
1580 	 * an integer that is the index to the local fd table entry
1581 	 * that we set up to point to the global one we are transferring.
1582 	 * Since the sizeof(struct file *) is bigger than or equal to
1583 	 * the sizeof(int), we do it in forward order.  In that case,
1584 	 * an integer will always come in the same place or before its
1585 	 * corresponding struct file pointer.
1586 	 *
1587 	 * Hold revoke_token in 'shared' mode, so that we won't miss
1588 	 * the FREVOKED update on fps being externalized (fsetfd).
1589 	 */
1590 	lwkt_gettoken_shared(&revoke_token);
1591 	fdp = (int *)CMSG_DATA(cm);
1592 	rp = (struct file **)CMSG_DATA(cm);
1593 	for (i = 0; i < newfds; i++) {
1594 		if (fdalloc(p, 0, &f)) {
1595 			int j;
1596 
1597 			/*
1598 			 * Previous fdavail() can't garantee
1599 			 * fdalloc() success due to SMP race.
1600 			 * Just clean up and return the same
1601 			 * error value as if fdavail() failed.
1602 			 */
1603 			lwkt_reltoken(&revoke_token);
1604 
1605 			/* Close externalized files */
1606 			for (j = 0; j < i; j++)
1607 				kern_close(fdp[j]);
1608 			/* Discard the rest of internal files */
1609 			for (; i < newfds; i++)
1610 				unp_discard(rp[i], NULL);
1611 			/* Wipe out the control message */
1612 			for (i = 0; i < newfds; i++)
1613 				rp[i] = NULL;
1614 
1615 			lwkt_reltoken(&unp_rights_token);
1616 			return (EMSGSIZE);
1617 		}
1618 		fp = rp[i];
1619 		unp_fp_externalize(lp, fp, f, flags);
1620 		fdp[i] = f;
1621 	}
1622 	lwkt_reltoken(&revoke_token);
1623 
1624 	lwkt_reltoken(&unp_rights_token);
1625 
1626 	/*
1627 	 * Adjust length, in case sizeof(struct file *) and sizeof(int)
1628 	 * differs.
1629 	 */
1630 	cm->cmsg_len = CMSG_LEN(newfds * sizeof(int));
1631 	rights->m_len = cm->cmsg_len;
1632 
1633 	return (0);
1634 }
1635 
1636 static void
1637 unp_fp_externalize(struct lwp *lp, struct file *fp, int fd, int flags)
1638 {
1639 	if (lp) {
1640 		struct filedesc *fdp = lp->lwp_proc->p_fd;
1641 
1642 		KKASSERT(fd >= 0);
1643 		if (fp->f_flag & FREVOKED) {
1644 			struct file *fx;
1645 			int error;
1646 
1647 			kprintf("Warning: revoked fp exiting unix socket\n");
1648 			error = falloc(lp, &fx, NULL);
1649 			if (error == 0) {
1650 				if (flags & MSG_CMSG_CLOEXEC)
1651 					fdp->fd_files[fd].fileflags |= UF_EXCLOSE;
1652 				fsetfd(fdp, fx, fd);
1653 				fdrop(fx);
1654 			} else {
1655 				fsetfd(fdp, NULL, fd);
1656 			}
1657 		} else {
1658 			if (flags & MSG_CMSG_CLOEXEC)
1659 				fdp->fd_files[fd].fileflags |= UF_EXCLOSE;
1660 			fsetfd(fdp, fp, fd);
1661 		}
1662 	}
1663 	unp_del_right(fp);
1664 	fdrop(fp);
1665 }
1666 
1667 void
1668 unp_init(void)
1669 {
1670 	TAILQ_INIT(&unp_stream_head.list);
1671 	TAILQ_INIT(&unp_dgram_head.list);
1672 	TAILQ_INIT(&unp_seqpkt_head.list);
1673 
1674 	SLIST_INIT(&unp_defdiscard_head);
1675 	spin_init(&unp_defdiscard_spin, "unpdisc");
1676 	TASK_INIT(&unp_defdiscard_task, 0, unp_defdiscard_taskfunc, NULL);
1677 
1678 	/*
1679 	 * This implies that only one gc can be in-progress at any
1680 	 * given moment.
1681 	 */
1682 	TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1683 
1684 	unp_gc_marker = kmalloc(sizeof(*unp_gc_marker), M_UNPCB,
1685 	    M_WAITOK | M_ZERO);
1686 	unp_gc_marker->unp_flags |= UNP_MARKER;
1687 
1688 	/*
1689 	 * Create taskqueue for defered discard, and stick it to
1690 	 * the last CPU.
1691 	 */
1692 	unp_taskqueue = taskqueue_create("unp_taskq", M_WAITOK,
1693 	    taskqueue_thread_enqueue, &unp_taskqueue);
1694 	taskqueue_start_threads(&unp_taskqueue, 1, TDPRI_KERN_DAEMON,
1695 	    ncpus - 1, "unp taskq");
1696 }
1697 
1698 static int
1699 unp_internalize(struct mbuf *control, struct thread *td)
1700 {
1701 	struct proc *p = td->td_proc;
1702 	struct filedesc *fdescp;
1703 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1704 	struct file **rp;
1705 	struct file *fp;
1706 	int i, fd, *fdp;
1707 	struct cmsgcred *cmcred;
1708 	int oldfds;
1709 	u_int newlen;
1710 	int error;
1711 
1712 	KKASSERT(p);
1713 
1714 	/*
1715 	 * Make sure the message is reasonable, and either CREDS or RIGHTS.
1716 	 *
1717 	 * NOTE: overall message length does not have to be aligned, but the
1718 	 *	 data start does.
1719 	 */
1720 	if ((cm->cmsg_type != SCM_RIGHTS && cm->cmsg_type != SCM_CREDS) ||
1721 	    cm->cmsg_level != SOL_SOCKET ||
1722 	    control->m_len < sizeof(*cm) ||	/* control too small */
1723 	    cm->cmsg_len < sizeof(*cm) ||	/* cmsg_len too small */
1724 	    cm->cmsg_len > control->m_len) {	/* cmsg_len too big */
1725 		return EINVAL;
1726 	}
1727 
1728 	/*
1729 	 * Fill in credential information.
1730 	 */
1731 	if (cm->cmsg_type == SCM_CREDS) {
1732 		cmcred = (struct cmsgcred *)CMSG_DATA(cm);
1733 		cmcred->cmcred_pid = p->p_pid;
1734 		cmcred->cmcred_uid = p->p_ucred->cr_ruid;
1735 		cmcred->cmcred_gid = p->p_ucred->cr_rgid;
1736 		cmcred->cmcred_euid = p->p_ucred->cr_uid;
1737 		cmcred->cmcred_ngroups = MIN(p->p_ucred->cr_ngroups,
1738 							CMGROUP_MAX);
1739 		for (i = 0; i < cmcred->cmcred_ngroups; i++)
1740 			cmcred->cmcred_groups[i] = p->p_ucred->cr_groups[i];
1741 		return 0;
1742 	}
1743 
1744 	/*
1745 	 * cmsghdr may not be aligned, do not allow calculation(s) to
1746 	 * go negative.
1747 	 *
1748 	 * Data must be aligned but the data length does not have to be.
1749 	 *
1750 	 * If there are multiple headers (XXX not supported) then the
1751 	 * next header will be aligned after the end of the possibly
1752 	 * unaligned data.
1753 	 */
1754 	if (cm->cmsg_len < CMSG_LEN(0)) {
1755 		return EINVAL;
1756 	}
1757 
1758 	oldfds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1759 
1760 	/*
1761 	 * Now replace the integer FDs with pointers to
1762 	 * the associated global file table entry..
1763 	 * Allocate a bigger buffer as necessary. But if an cluster is not
1764 	 * enough, return E2BIG.
1765 	 */
1766 	newlen = CMSG_LEN(oldfds * sizeof(struct file *));
1767 	if (newlen > MCLBYTES)
1768 		return E2BIG;
1769 	if (newlen - control->m_len > M_TRAILINGSPACE(control)) {
1770 		if (control->m_flags & M_EXT)
1771 			return E2BIG;
1772 		MCLGET(control, M_WAITOK);
1773 
1774 		/* copy the data to the cluster */
1775 		memcpy(mtod(control, char *), cm, cm->cmsg_len);
1776 		cm = mtod(control, struct cmsghdr *);
1777 	}
1778 
1779 	lwkt_gettoken(&unp_rights_token);
1780 
1781 	fdescp = p->p_fd;
1782 	spin_lock_shared(&fdescp->fd_spin);
1783 
1784 	/*
1785 	 * check that all the FDs passed in refer to legal OPEN files
1786 	 * If not, reject the entire operation.
1787 	 */
1788 	fdp = (int *)CMSG_DATA(cm);
1789 	for (i = 0; i < oldfds; i++) {
1790 		fd = *fdp++;
1791 		if ((unsigned)fd >= fdescp->fd_nfiles ||
1792 		    fdescp->fd_files[fd].fp == NULL) {
1793 			error = EBADF;
1794 			goto done;
1795 		}
1796 		if (fdescp->fd_files[fd].fp->f_type == DTYPE_KQUEUE) {
1797 			error = EOPNOTSUPP;
1798 			goto done;
1799 		}
1800 	}
1801 
1802 	/*
1803 	 * Adjust length, in case sizeof(struct file *) and sizeof(int)
1804 	 * differs.
1805 	 */
1806 	cm->cmsg_len = newlen;
1807 	control->m_len = CMSG_ALIGN(newlen);
1808 
1809 	/*
1810 	 * Transform the file descriptors into struct file pointers.
1811 	 * Since the sizeof(struct file *) is bigger than or equal to
1812 	 * the sizeof(int), we do it in reverse order so that the int
1813 	 * won't get trashed until we're done.
1814 	 */
1815 	fdp = (int *)CMSG_DATA(cm) + oldfds - 1;
1816 	rp = (struct file **)CMSG_DATA(cm) + oldfds - 1;
1817 	for (i = 0; i < oldfds; i++) {
1818 		fp = fdescp->fd_files[*fdp--].fp;
1819 		*rp-- = fp;
1820 		fhold(fp);
1821 		unp_add_right(fp);
1822 	}
1823 	error = 0;
1824 done:
1825 	spin_unlock_shared(&fdescp->fd_spin);
1826 	lwkt_reltoken(&unp_rights_token);
1827 	return error;
1828 }
1829 
1830 #ifdef UNP_GC_ALLFILES
1831 
1832 /*
1833  * Garbage collect in-transit file descriptors that get lost due to
1834  * loops (i.e. when a socket is sent to another process over itself,
1835  * and more complex situations).
1836  *
1837  * NOT MPSAFE - TODO socket flush code and maybe fdrop.  Rest is MPSAFE.
1838  */
1839 
1840 struct unp_gc_info {
1841 	struct file **extra_ref;
1842 	struct file *locked_fp;
1843 	int defer;
1844 	int index;
1845 	int maxindex;
1846 };
1847 
1848 static void
1849 unp_gc(void *arg __unused, int pending __unused)
1850 {
1851 	struct unp_gc_info info;
1852 	struct file **fpp;
1853 	int i;
1854 
1855 	lwkt_gettoken(&unp_rights_token);
1856 
1857 	/*
1858 	 * Before going through all this, set all FDs to be NOT defered
1859 	 * and NOT externally accessible (not marked).  During the scan
1860 	 * a fd can be marked externally accessible but we may or may not
1861 	 * be able to immediately process it (controlled by FDEFER).
1862 	 *
1863 	 * If we loop sleep a bit.  The complexity of the topology can cause
1864 	 * multiple loops.  Also failure to acquire the socket's so_rcv
1865 	 * token can cause us to loop.
1866 	 */
1867 	allfiles_scan_exclusive(unp_gc_clearmarks, NULL);
1868 	do {
1869 		info.defer = 0;
1870 		allfiles_scan_exclusive(unp_gc_checkmarks, &info);
1871 		if (info.defer)
1872 			tsleep(&info, 0, "gcagain", 1);
1873 	} while (info.defer);
1874 
1875 	/*
1876 	 * We grab an extra reference to each of the file table entries
1877 	 * that are not otherwise accessible and then free the rights
1878 	 * that are stored in messages on them.
1879 	 *
1880 	 * The bug in the orginal code is a little tricky, so I'll describe
1881 	 * what's wrong with it here.
1882 	 *
1883 	 * It is incorrect to simply unp_discard each entry for f_msgcount
1884 	 * times -- consider the case of sockets A and B that contain
1885 	 * references to each other.  On a last close of some other socket,
1886 	 * we trigger a gc since the number of outstanding rights (unp_rights)
1887 	 * is non-zero.  If during the sweep phase the gc code unp_discards,
1888 	 * we end up doing a (full) fdrop on the descriptor.  A fdrop on A
1889 	 * results in the following chain.  Closef calls soo_close, which
1890 	 * calls soclose.   Soclose calls first (through the switch
1891 	 * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
1892 	 * returns because the previous instance had set unp_gcing, and
1893 	 * we return all the way back to soclose, which marks the socket
1894 	 * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
1895 	 * to free up the rights that are queued in messages on the socket A,
1896 	 * i.e., the reference on B.  The sorflush calls via the dom_dispose
1897 	 * switch unp_dispose, which unp_scans with unp_discard.  This second
1898 	 * instance of unp_discard just calls fdrop on B.
1899 	 *
1900 	 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1901 	 * which results in another fdrop on A.  Unfortunately, A is already
1902 	 * being closed, and the descriptor has already been marked with
1903 	 * SS_NOFDREF, and soclose panics at this point.
1904 	 *
1905 	 * Here, we first take an extra reference to each inaccessible
1906 	 * descriptor.  Then, we call sorflush ourself, since we know
1907 	 * it is a Unix domain socket anyhow.  After we destroy all the
1908 	 * rights carried in messages, we do a last fdrop to get rid
1909 	 * of our extra reference.  This is the last close, and the
1910 	 * unp_detach etc will shut down the socket.
1911 	 *
1912 	 * 91/09/19, bsy@cs.cmu.edu
1913 	 */
1914 	info.extra_ref = kmalloc(256 * sizeof(struct file *), M_FILE, M_WAITOK);
1915 	info.maxindex = 256;
1916 
1917 	do {
1918 		/*
1919 		 * Look for matches
1920 		 */
1921 		info.index = 0;
1922 		allfiles_scan_exclusive(unp_gc_checkrefs, &info);
1923 
1924 		/*
1925 		 * For each FD on our hit list, do the following two things
1926 		 */
1927 		for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp) {
1928 			struct file *tfp = *fpp;
1929 			if (tfp->f_type == DTYPE_SOCKET && tfp->f_data != NULL)
1930 				sorflush((struct socket *)(tfp->f_data));
1931 		}
1932 		for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp)
1933 			fdrop(*fpp);
1934 	} while (info.index == info.maxindex);
1935 
1936 	kfree((caddr_t)info.extra_ref, M_FILE);
1937 
1938 	lwkt_reltoken(&unp_rights_token);
1939 }
1940 
1941 /*
1942  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1943  */
1944 static int
1945 unp_gc_checkrefs(struct file *fp, void *data)
1946 {
1947 	struct unp_gc_info *info = data;
1948 
1949 	if (fp->f_count == 0)
1950 		return(0);
1951 	if (info->index == info->maxindex)
1952 		return(-1);
1953 
1954 	/*
1955 	 * If all refs are from msgs, and it's not marked accessible
1956 	 * then it must be referenced from some unreachable cycle
1957 	 * of (shut-down) FDs, so include it in our
1958 	 * list of FDs to remove
1959 	 */
1960 	if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1961 		info->extra_ref[info->index++] = fp;
1962 		fhold(fp);
1963 	}
1964 	return(0);
1965 }
1966 
1967 /*
1968  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1969  */
1970 static int
1971 unp_gc_clearmarks(struct file *fp, void *data __unused)
1972 {
1973 	atomic_clear_int(&fp->f_flag, FMARK | FDEFER);
1974 	return(0);
1975 }
1976 
1977 /*
1978  * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1979  */
1980 static int
1981 unp_gc_checkmarks(struct file *fp, void *data)
1982 {
1983 	struct unp_gc_info *info = data;
1984 	struct socket *so;
1985 
1986 	/*
1987 	 * If the file is not open, skip it.  Make sure it isn't marked
1988 	 * defered or we could loop forever, in case we somehow race
1989 	 * something.
1990 	 */
1991 	if (fp->f_count == 0) {
1992 		if (fp->f_flag & FDEFER)
1993 			atomic_clear_int(&fp->f_flag, FDEFER);
1994 		return(0);
1995 	}
1996 	/*
1997 	 * If we already marked it as 'defer'  in a
1998 	 * previous pass, then try process it this time
1999 	 * and un-mark it
2000 	 */
2001 	if (fp->f_flag & FDEFER) {
2002 		atomic_clear_int(&fp->f_flag, FDEFER);
2003 	} else {
2004 		/*
2005 		 * if it's not defered, then check if it's
2006 		 * already marked.. if so skip it
2007 		 */
2008 		if (fp->f_flag & FMARK)
2009 			return(0);
2010 		/*
2011 		 * If all references are from messages
2012 		 * in transit, then skip it. it's not
2013 		 * externally accessible.
2014 		 */
2015 		if (fp->f_count == fp->f_msgcount)
2016 			return(0);
2017 		/*
2018 		 * If it got this far then it must be
2019 		 * externally accessible.
2020 		 */
2021 		atomic_set_int(&fp->f_flag, FMARK);
2022 	}
2023 
2024 	/*
2025 	 * either it was defered, or it is externally
2026 	 * accessible and not already marked so.
2027 	 * Now check if it is possibly one of OUR sockets.
2028 	 */
2029 	if (fp->f_type != DTYPE_SOCKET ||
2030 	    (so = (struct socket *)fp->f_data) == NULL) {
2031 		return(0);
2032 	}
2033 	if (so->so_proto->pr_domain != &localdomain ||
2034 	    !(so->so_proto->pr_flags & PR_RIGHTS)) {
2035 		return(0);
2036 	}
2037 
2038 	/*
2039 	 * So, Ok, it's one of our sockets and it IS externally accessible
2040 	 * (or was defered).  Now we look to see if we hold any file
2041 	 * descriptors in its message buffers.  Follow those links and mark
2042 	 * them as accessible too.
2043 	 *
2044 	 * We are holding multiple spinlocks here, if we cannot get the
2045 	 * token non-blocking defer until the next loop.
2046 	 */
2047 	info->locked_fp = fp;
2048 	if (lwkt_trytoken(&so->so_rcv.ssb_token)) {
2049 		unp_scan(so->so_rcv.ssb_mb, unp_mark, info);
2050 		lwkt_reltoken(&so->so_rcv.ssb_token);
2051 	} else {
2052 		atomic_set_int(&fp->f_flag, FDEFER);
2053 		++info->defer;
2054 	}
2055 	return (0);
2056 }
2057 
2058 /*
2059  * Mark visibility.  info->defer is recalculated on every pass.
2060  */
2061 static void
2062 unp_mark(struct file *fp, void *data)
2063 {
2064 	struct unp_gc_info *info = data;
2065 
2066 	if ((fp->f_flag & FMARK) == 0) {
2067 		++info->defer;
2068 		atomic_set_int(&fp->f_flag, FMARK | FDEFER);
2069 	} else if (fp->f_flag & FDEFER) {
2070 		++info->defer;
2071 	}
2072 }
2073 
2074 #else	/* !UNP_GC_ALLFILES */
2075 
2076 /*
2077  * They are thread local and do not require explicit synchronization.
2078  */
2079 static int	unp_marked;
2080 static int	unp_unreachable;
2081 
2082 static void
2083 unp_accessable(struct file *fp, void *data __unused)
2084 {
2085 	struct unpcb *unp;
2086 
2087 	if ((unp = unp_fp2unpcb(fp)) == NULL)
2088 		return;
2089 	if (unp->unp_gcflags & UNPGC_REF)
2090 		return;
2091 	unp->unp_gcflags &= ~UNPGC_DEAD;
2092 	unp->unp_gcflags |= UNPGC_REF;
2093 	unp_marked++;
2094 }
2095 
2096 static void
2097 unp_gc_process(struct unpcb *unp)
2098 {
2099 	struct file *fp;
2100 
2101 	/* Already processed. */
2102 	if (unp->unp_gcflags & UNPGC_SCANNED)
2103 		return;
2104 	fp = unp->unp_fp;
2105 
2106 	/*
2107 	 * Check for a socket potentially in a cycle.  It must be in a
2108 	 * queue as indicated by msgcount, and this must equal the file
2109 	 * reference count.  Note that when msgcount is 0 the file is NULL.
2110 	 */
2111 	if ((unp->unp_gcflags & UNPGC_REF) == 0 && fp &&
2112 	    unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2113 		unp->unp_gcflags |= UNPGC_DEAD;
2114 		unp_unreachable++;
2115 		return;
2116 	}
2117 
2118 	/*
2119 	 * Mark all sockets we reference with RIGHTS.
2120 	 */
2121 	if (UNP_ISATTACHED(unp)) {
2122 		struct signalsockbuf *ssb = &unp->unp_socket->so_rcv;
2123 
2124 		unp_reference(unp);
2125 		lwkt_gettoken(&ssb->ssb_token);
2126 		/*
2127 		 * unp_token would be temporarily dropped, if getting
2128 		 * so_rcv token blocks, so we need to check unp state
2129 		 * here again.
2130 		 */
2131 		if (UNP_ISATTACHED(unp))
2132 			unp_scan(ssb->ssb_mb, unp_accessable, NULL);
2133 		lwkt_reltoken(&ssb->ssb_token);
2134 		unp->unp_gcflags |= UNPGC_SCANNED;
2135 		unp_free(unp);
2136 	} else {
2137 		unp->unp_gcflags |= UNPGC_SCANNED;
2138 	}
2139 }
2140 
2141 static void
2142 unp_gc(void *arg __unused, int pending __unused)
2143 {
2144 	struct unp_global_head *head;
2145 	int h, filemax, fileidx, filetot;
2146 	struct file **unref;
2147 	struct unpcb *unp;
2148 
2149 	lwkt_gettoken(&unp_rights_token);
2150 	lwkt_gettoken(&unp_token);
2151 
2152 	/*
2153 	 * First clear all gc flags from previous runs.
2154 	 */
2155 	for (h = 0; unp_heads[h] != NULL; ++h) {
2156 		/*
2157 		 * NOTE: This loop does not block, so it is safe
2158 		 * to use TAILQ_FOREACH here.
2159 		 */
2160 		head = unp_heads[h];
2161 		TAILQ_FOREACH(unp, &head->list, unp_link)
2162 			unp->unp_gcflags = 0;
2163 	}
2164 
2165 	/*
2166 	 * Scan marking all reachable sockets with UNPGC_REF.  Once a socket
2167 	 * is reachable all of the sockets it references are reachable.
2168 	 * Stop the scan once we do a complete loop without discovering
2169 	 * a new reachable socket.
2170 	 */
2171 	do {
2172 		unp_unreachable = 0;
2173 		unp_marked = 0;
2174 		for (h = 0; unp_heads[h] != NULL; ++h) {
2175 			head = unp_heads[h];
2176 			TAILQ_INSERT_HEAD(&head->list, unp_gc_marker, unp_link);
2177 			while ((unp = TAILQ_NEXT(unp_gc_marker, unp_link))
2178 			    != NULL) {
2179 				TAILQ_REMOVE(&head->list, unp_gc_marker,
2180 				    unp_link);
2181 				TAILQ_INSERT_AFTER(&head->list, unp,
2182 				    unp_gc_marker, unp_link);
2183 
2184 				if (unp->unp_flags & UNP_MARKER)
2185 					continue;
2186 				unp_gc_process(unp);
2187 			}
2188 			TAILQ_REMOVE(&head->list, unp_gc_marker, unp_link);
2189 		}
2190 	} while (unp_marked);
2191 
2192 	if (unp_unreachable == 0)
2193 		goto done;
2194 
2195 	/*
2196 	 * We grab an extra reference to each of the file table entries
2197 	 * that are not otherwise accessible and then free the rights
2198 	 * that are stored in messages on them.
2199 	 *
2200 	 * The bug in the orginal code is a little tricky, so I'll describe
2201 	 * what's wrong with it here.
2202 	 *
2203 	 * It is incorrect to simply unp_discard each entry for f_msgcount
2204 	 * times -- consider the case of sockets A and B that contain
2205 	 * references to each other.  On a last close of some other socket,
2206 	 * we trigger a gc since the number of outstanding rights (unp_rights)
2207 	 * is non-zero.  If during the sweep phase the gc code unp_discards,
2208 	 * we end up doing a (full) fdrop on the descriptor.  A fdrop on A
2209 	 * results in the following chain.  Closef calls soo_close, which
2210 	 * calls soclose.   Soclose calls first (through the switch
2211 	 * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
2212 	 * returns because the previous instance had set unp_gcing, and
2213 	 * we return all the way back to soclose, which marks the socket
2214 	 * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
2215 	 * to free up the rights that are queued in messages on the socket A,
2216 	 * i.e., the reference on B.  The sorflush calls via the dom_dispose
2217 	 * switch unp_dispose, which unp_scans with unp_discard.  This second
2218 	 * instance of unp_discard just calls fdrop on B.
2219 	 *
2220 	 * Well, a similar chain occurs on B, resulting in a sorflush on B,
2221 	 * which results in another fdrop on A.  Unfortunately, A is already
2222 	 * being closed, and the descriptor has already been marked with
2223 	 * SS_NOFDREF, and soclose panics at this point.
2224 	 *
2225 	 * Here, we first take an extra reference to each inaccessible
2226 	 * descriptor.  Then, we call sorflush ourself, since we know
2227 	 * it is a Unix domain socket anyhow.  After we destroy all the
2228 	 * rights carried in messages, we do a last fdrop to get rid
2229 	 * of our extra reference.  This is the last close, and the
2230 	 * unp_detach etc will shut down the socket.
2231 	 *
2232 	 * 91/09/19, bsy@cs.cmu.edu
2233 	 */
2234 
2235 	filemax = unp_unreachable;
2236 	if (filemax > UNP_GCFILE_MAX)
2237 		filemax = UNP_GCFILE_MAX;
2238 	unref = kmalloc(filemax * sizeof(struct file *), M_TEMP, M_WAITOK);
2239 
2240 	filetot = 0;
2241 	do {
2242 		int i;
2243 
2244 		/*
2245 		 * Iterate looking for sockets which have been specifically
2246 		 * marked as as unreachable and store them locally.
2247 		 */
2248 		fileidx = 0;
2249 		for (h = 0; unp_heads[h] != NULL; ++h) {
2250 			/*
2251 			 * NOTE: This loop does not block, so it is safe
2252 			 * to use TAILQ_FOREACH here.
2253 			 */
2254 			head = unp_heads[h];
2255 			TAILQ_FOREACH(unp, &head->list, unp_link) {
2256 				struct file *fp;
2257 
2258 				if ((unp->unp_gcflags & UNPGC_DEAD) == 0)
2259 					continue;
2260 				unp->unp_gcflags &= ~UNPGC_DEAD;
2261 
2262 				fp = unp->unp_fp;
2263 				if (unp->unp_msgcount == 0 || fp == NULL ||
2264 				    fp->f_count != unp->unp_msgcount)
2265 					continue;
2266 				fhold(fp);
2267 
2268 				KASSERT(fileidx < filemax,
2269 				    ("invalid fileidx %d, filemax %d",
2270 				     fileidx, filemax));
2271 				unref[fileidx++] = fp;
2272 
2273 				KASSERT(filetot < unp_unreachable,
2274 				    ("invalid filetot %d and "
2275 				     "unp_unreachable %d",
2276 				     filetot, unp_unreachable));
2277 				++filetot;
2278 
2279 				if (fileidx == filemax ||
2280 				    filetot == unp_unreachable)
2281 					goto dogc;
2282 			}
2283 		}
2284 dogc:
2285 		/*
2286 		 * For each Unix domain socket on our hit list, do the
2287 		 * following two things.
2288 		 */
2289 		for (i = 0; i < fileidx; ++i)
2290 			sorflush(unref[i]->f_data);
2291 		for (i = 0; i < fileidx; ++i)
2292 			fdrop(unref[i]);
2293 	} while (fileidx == filemax && filetot < unp_unreachable);
2294 	kfree(unref, M_TEMP);
2295 done:
2296 	lwkt_reltoken(&unp_token);
2297 	lwkt_reltoken(&unp_rights_token);
2298 }
2299 
2300 #endif	/* UNP_GC_ALLFILES */
2301 
2302 /*
2303  * Dispose of the fp's stored in a mbuf.
2304  *
2305  * The dds loop can cause additional fps to be entered onto the
2306  * list while it is running, flattening out the operation and avoiding
2307  * a deep kernel stack recursion.
2308  */
2309 void
2310 unp_dispose(struct mbuf *m)
2311 {
2312 	lwkt_gettoken(&unp_rights_token);
2313 	if (m)
2314 		unp_scan(m, unp_discard, NULL);
2315 	lwkt_reltoken(&unp_rights_token);
2316 }
2317 
2318 static int
2319 unp_listen(struct unpcb *unp, struct thread *td)
2320 {
2321 	struct proc *p = td->td_proc;
2322 
2323 	ASSERT_LWKT_TOKEN_HELD(&unp_token);
2324 	UNP_ASSERT_TOKEN_HELD(unp);
2325 
2326 	KKASSERT(p);
2327 	cru2x(p->p_ucred, &unp->unp_peercred);
2328 	unp_setflags(unp, UNP_HAVEPCCACHED);
2329 	return (0);
2330 }
2331 
2332 static void
2333 unp_scan(struct mbuf *m0, void (*op)(struct file *, void *), void *data)
2334 {
2335 	struct mbuf *m;
2336 	struct file **rp;
2337 	struct cmsghdr *cm;
2338 	int i;
2339 	int qfds;
2340 
2341 	while (m0) {
2342 		for (m = m0; m; m = m->m_next) {
2343 			if (m->m_type == MT_CONTROL &&
2344 			    m->m_len >= sizeof(*cm)) {
2345 				cm = mtod(m, struct cmsghdr *);
2346 				if (cm->cmsg_level != SOL_SOCKET ||
2347 				    cm->cmsg_type != SCM_RIGHTS)
2348 					continue;
2349 				qfds = (cm->cmsg_len - CMSG_LEN(0)) /
2350 					sizeof(void *);
2351 				rp = (struct file **)CMSG_DATA(cm);
2352 				for (i = 0; i < qfds; i++)
2353 					(*op)(*rp++, data);
2354 				break;		/* XXX, but saves time */
2355 			}
2356 		}
2357 		m0 = m0->m_nextpkt;
2358 	}
2359 }
2360 
2361 /*
2362  * Discard a fp previously held in a unix domain socket mbuf.  To
2363  * avoid blowing out the kernel stack due to contrived chain-reactions
2364  * we may have to defer the operation to a dedicated taskqueue.
2365  *
2366  * Caller holds unp_rights_token.
2367  */
2368 static void
2369 unp_discard(struct file *fp, void *data __unused)
2370 {
2371 	unp_del_right(fp);
2372 	if (unp_fp2unpcb(fp) != NULL) {
2373 		struct unp_defdiscard *d;
2374 
2375 		/*
2376 		 * This fp is a Unix domain socket itself and fdrop()
2377 		 * it here directly may cause deep unp_discard()
2378 		 * recursion, so the fdrop() is defered to the
2379 		 * dedicated taskqueue.
2380 		 */
2381 		d = kmalloc(sizeof(*d), M_UNPCB, M_WAITOK);
2382 		d->fp = fp;
2383 
2384 		spin_lock(&unp_defdiscard_spin);
2385 		SLIST_INSERT_HEAD(&unp_defdiscard_head, d, next);
2386 		spin_unlock(&unp_defdiscard_spin);
2387 
2388 		taskqueue_enqueue(unp_taskqueue, &unp_defdiscard_task);
2389 	} else {
2390 		/* This fp is not a Unix domain socket */
2391 		fdrop(fp);
2392 	}
2393 }
2394 
2395 /*
2396  * NOTE:
2397  * unp_token must be held before calling this function to avoid name
2398  * resolution and v_socket accessing races, especially racing against
2399  * the unp_detach().
2400  *
2401  * NOTE:
2402  * For anyone caring about unconnected Unix domain socket sending
2403  * performance, other approach could be taken...
2404  */
2405 static int
2406 unp_find_lockref(struct sockaddr *nam, struct thread *td, short type,
2407     struct unpcb **unp_ret)
2408 {
2409 	struct proc *p = td->td_proc;
2410 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
2411 	struct vnode *vp = NULL;
2412 	struct socket *so;
2413 	struct unpcb *unp;
2414 	int error, len;
2415 	struct nlookupdata nd;
2416 	char buf[SOCK_MAXADDRLEN];
2417 
2418 	ASSERT_LWKT_TOKEN_HELD(&unp_token);
2419 
2420 	*unp_ret = NULL;
2421 
2422 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
2423 	if (len <= 0) {
2424 		error = EINVAL;
2425 		goto failed;
2426 	}
2427 	strncpy(buf, soun->sun_path, len);
2428 	buf[len] = 0;
2429 
2430 	error = nlookup_init(&nd, buf, UIO_SYSSPACE, NLC_FOLLOW);
2431 	if (error == 0)
2432 		error = nlookup(&nd);
2433 	if (error == 0)
2434 		error = cache_vget(&nd.nl_nch, nd.nl_cred, LK_EXCLUSIVE, &vp);
2435 	nlookup_done(&nd);
2436 	if (error) {
2437 		vp = NULL;
2438 		goto failed;
2439 	}
2440 
2441 	if (vp->v_type != VSOCK) {
2442 		error = ENOTSOCK;
2443 		goto failed;
2444 	}
2445 	error = VOP_EACCESS(vp, VWRITE, p->p_ucred);
2446 	if (error)
2447 		goto failed;
2448 	so = vp->v_socket;
2449 	if (so == NULL) {
2450 		error = ECONNREFUSED;
2451 		goto failed;
2452 	}
2453 	if (so->so_type != type) {
2454 		error = EPROTOTYPE;
2455 		goto failed;
2456 	}
2457 
2458 	/* Lock this unp. */
2459 	unp = unp_getsocktoken(so);
2460 	if (!UNP_ISATTACHED(unp)) {
2461 		unp_reltoken(unp);
2462 		error = ECONNREFUSED;
2463 		goto failed;
2464 	}
2465 	/* And keep this unp referenced. */
2466 	unp_reference(unp);
2467 
2468 	/* Done! */
2469 	*unp_ret = unp;
2470 	error = 0;
2471 failed:
2472 	if (vp != NULL)
2473 		vput(vp);
2474 	return error;
2475 }
2476 
2477 static int
2478 unp_connect_pair(struct unpcb *unp, struct unpcb *unp2)
2479 {
2480 	struct socket *so = unp->unp_socket;
2481 	struct socket *so2 = unp2->unp_socket;
2482 
2483 	ASSERT_LWKT_TOKEN_HELD(&unp_token);
2484 	UNP_ASSERT_TOKEN_HELD(unp);
2485 	UNP_ASSERT_TOKEN_HELD(unp2);
2486 
2487 	KASSERT(so->so_type == so2->so_type,
2488 	    ("socket type mismatch, so %d, so2 %d", so->so_type, so2->so_type));
2489 
2490 	if (!UNP_ISATTACHED(unp))
2491 		return EINVAL;
2492 	if (!UNP_ISATTACHED(unp2))
2493 		return ECONNREFUSED;
2494 
2495 	KASSERT(unp->unp_conn == NULL, ("unp is already connected"));
2496 	unp->unp_conn = unp2;
2497 
2498 	switch (so->so_type) {
2499 	case SOCK_DGRAM:
2500 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2501 		soisconnected(so);
2502 		break;
2503 
2504 	case SOCK_STREAM:
2505 	case SOCK_SEQPACKET:
2506 		KASSERT(unp2->unp_conn == NULL, ("unp2 is already connected"));
2507 		unp2->unp_conn = unp;
2508 		soisconnected(so);
2509 		soisconnected(so2);
2510 		break;
2511 
2512 	default:
2513 		panic("unp_connect_pair: unknown socket type %d", so->so_type);
2514 	}
2515 	return 0;
2516 }
2517 
2518 static void
2519 unp_drop(struct unpcb *unp, int error)
2520 {
2521 	struct unp_global_head *head;
2522 	struct unpcb *unp2;
2523 
2524 	ASSERT_LWKT_TOKEN_HELD(&unp_token);
2525 	UNP_ASSERT_TOKEN_HELD(unp);
2526 
2527 	KASSERT((unp->unp_flags & (UNP_DETACHED | UNP_DROPPED)) == 0,
2528 	    ("unp is dropped"));
2529 
2530 	/* Mark this unp as detached. */
2531 	unp_setflags(unp, UNP_DETACHED);
2532 
2533 	/* Remove this unp from the global unp list. */
2534 	head = unp_globalhead(unp->unp_socket->so_type);
2535 	KASSERT(head->count > 0, ("invalid unp count"));
2536 	TAILQ_REMOVE(&head->list, unp, unp_link);
2537 	head->count--;
2538 
2539 	/* Disconnect all. */
2540 	unp_disconnect(unp, error);
2541 	while ((unp2 = LIST_FIRST(&unp->unp_refs)) != NULL) {
2542 		lwkt_getpooltoken(unp2);
2543 		unp_disconnect(unp2, ECONNRESET);
2544 		lwkt_relpooltoken(unp2);
2545 	}
2546 	unp_setflags(unp, UNP_DROPPED);
2547 
2548 	/* Try freeing this unp. */
2549 	unp_free(unp);
2550 }
2551 
2552 static void
2553 unp_defdiscard_taskfunc(void *arg __unused, int pending __unused)
2554 {
2555 	struct unp_defdiscard *d;
2556 
2557 	spin_lock(&unp_defdiscard_spin);
2558 	while ((d = SLIST_FIRST(&unp_defdiscard_head)) != NULL) {
2559 		SLIST_REMOVE_HEAD(&unp_defdiscard_head, next);
2560 		spin_unlock(&unp_defdiscard_spin);
2561 
2562 		fdrop(d->fp);
2563 		kfree(d, M_UNPCB);
2564 
2565 		spin_lock(&unp_defdiscard_spin);
2566 	}
2567 	spin_unlock(&unp_defdiscard_spin);
2568 }
2569