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