xref: /freebsd/sys/kern/uipc_usrreq.c (revision 4dbe268d2e7ad4f1172a174a3c55f0fdff3aaa99)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California. All Rights Reserved.
6  * Copyright (c) 2004-2009 Robert N. M. Watson All Rights Reserved.
7  * Copyright (c) 2018 Matthew Macy
8  * Copyright (c) 2022-2025 Gleb Smirnoff <glebius@FreeBSD.org>
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * UNIX Domain (Local) Sockets
37  *
38  * This is an implementation of UNIX (local) domain sockets.  Each socket has
39  * an associated struct unpcb (UNIX protocol control block).  Stream sockets
40  * may be connected to 0 or 1 other socket.  Datagram sockets may be
41  * connected to 0, 1, or many other sockets.  Sockets may be created and
42  * connected in pairs (socketpair(2)), or bound/connected to using the file
43  * system name space.  For most purposes, only the receive socket buffer is
44  * used, as sending on one socket delivers directly to the receive socket
45  * buffer of a second socket.
46  *
47  * The implementation is substantially complicated by the fact that
48  * "ancillary data", such as file descriptors or credentials, may be passed
49  * across UNIX domain sockets.  The potential for passing UNIX domain sockets
50  * over other UNIX domain sockets requires the implementation of a simple
51  * garbage collector to find and tear down cycles of disconnected sockets.
52  *
53  * TODO:
54  *	RDM
55  *	rethink name space problems
56  *	need a proper out-of-band
57  */
58 
59 #include <sys/cdefs.h>
60 #include "opt_ddb.h"
61 
62 #include <sys/param.h>
63 #include <sys/capsicum.h>
64 #include <sys/domain.h>
65 #include <sys/eventhandler.h>
66 #include <sys/fcntl.h>
67 #include <sys/file.h>
68 #include <sys/filedesc.h>
69 #include <sys/kernel.h>
70 #include <sys/lock.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/mount.h>
74 #include <sys/mutex.h>
75 #include <sys/namei.h>
76 #include <sys/poll.h>
77 #include <sys/proc.h>
78 #include <sys/protosw.h>
79 #include <sys/queue.h>
80 #include <sys/resourcevar.h>
81 #include <sys/rwlock.h>
82 #include <sys/socket.h>
83 #include <sys/socketvar.h>
84 #include <sys/signalvar.h>
85 #include <sys/stat.h>
86 #include <sys/sx.h>
87 #include <sys/sysctl.h>
88 #include <sys/systm.h>
89 #include <sys/taskqueue.h>
90 #include <sys/un.h>
91 #include <sys/unpcb.h>
92 #include <sys/vnode.h>
93 
94 #include <net/vnet.h>
95 
96 #ifdef DDB
97 #include <ddb/ddb.h>
98 #endif
99 
100 #include <security/mac/mac_framework.h>
101 
102 #include <vm/uma.h>
103 
104 MALLOC_DECLARE(M_FILECAPS);
105 
106 static struct domain localdomain;
107 
108 static uma_zone_t	unp_zone;
109 static unp_gen_t	unp_gencnt;	/* (l) */
110 static u_int		unp_count;	/* (l) Count of local sockets. */
111 static ino_t		unp_ino;	/* Prototype for fake inode numbers. */
112 static int		unp_rights;	/* (g) File descriptors in flight. */
113 static struct unp_head	unp_shead;	/* (l) List of stream sockets. */
114 static struct unp_head	unp_dhead;	/* (l) List of datagram sockets. */
115 static struct unp_head	unp_sphead;	/* (l) List of seqpacket sockets. */
116 static struct mtx_pool	*unp_vp_mtxpool;
117 
118 struct unp_defer {
119 	SLIST_ENTRY(unp_defer) ud_link;
120 	struct file *ud_fp;
121 };
122 static SLIST_HEAD(, unp_defer) unp_defers;
123 static int unp_defers_count;
124 
125 static const struct sockaddr	sun_noname = {
126 	.sa_len = sizeof(sun_noname),
127 	.sa_family = AF_LOCAL,
128 };
129 
130 /*
131  * Garbage collection of cyclic file descriptor/socket references occurs
132  * asynchronously in a taskqueue context in order to avoid recursion and
133  * reentrance in the UNIX domain socket, file descriptor, and socket layer
134  * code.  See unp_gc() for a full description.
135  */
136 static struct timeout_task unp_gc_task;
137 
138 /*
139  * The close of unix domain sockets attached as SCM_RIGHTS is
140  * postponed to the taskqueue, to avoid arbitrary recursion depth.
141  * The attached sockets might have another sockets attached.
142  */
143 static struct task	unp_defer_task;
144 
145 /*
146  * SOCK_STREAM and SOCK_SEQPACKET unix(4) sockets fully bypass the send buffer,
147  * however the notion of send buffer still makes sense with them.  Its size is
148  * the amount of space that a send(2) syscall may copyin(9) before checking
149  * with the receive buffer of a peer.  Although not linked anywhere yet,
150  * pointed to by a stack variable, effectively it is a buffer that needs to be
151  * sized.
152  *
153  * SOCK_DGRAM sockets really use the sendspace as the maximum datagram size,
154  * and don't really want to reserve the sendspace.  Their recvspace should be
155  * large enough for at least one max-size datagram plus address.
156  */
157 #ifndef PIPSIZ
158 #define	PIPSIZ	8192
159 #endif
160 static u_long	unpst_sendspace = PIPSIZ;
161 static u_long	unpst_recvspace = PIPSIZ;
162 static u_long	unpdg_maxdgram = 8*1024;	/* support 8KB syslog msgs */
163 static u_long	unpdg_recvspace = 16*1024;
164 static u_long	unpsp_sendspace = PIPSIZ;
165 static u_long	unpsp_recvspace = PIPSIZ;
166 
167 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
168     "Local domain");
169 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
170     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
171     "SOCK_STREAM");
172 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
173     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
174     "SOCK_DGRAM");
175 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
176     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
177     "SOCK_SEQPACKET");
178 
179 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
180 	   &unpst_sendspace, 0, "Default stream send space.");
181 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
182 	   &unpst_recvspace, 0, "Default stream receive space.");
183 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
184 	   &unpdg_maxdgram, 0, "Maximum datagram size.");
185 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
186 	   &unpdg_recvspace, 0, "Default datagram receive space.");
187 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
188 	   &unpsp_sendspace, 0, "Default seqpacket send space.");
189 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
190 	   &unpsp_recvspace, 0, "Default seqpacket receive space.");
191 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
192     "File descriptors in flight.");
193 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
194     &unp_defers_count, 0,
195     "File descriptors deferred to taskqueue for close.");
196 
197 /*
198  * Locking and synchronization:
199  *
200  * Several types of locks exist in the local domain socket implementation:
201  * - a global linkage lock
202  * - a global connection list lock
203  * - the mtxpool lock
204  * - per-unpcb mutexes
205  *
206  * The linkage lock protects the global socket lists, the generation number
207  * counter and garbage collector state.
208  *
209  * The connection list lock protects the list of referring sockets in a datagram
210  * socket PCB.  This lock is also overloaded to protect a global list of
211  * sockets whose buffers contain socket references in the form of SCM_RIGHTS
212  * messages.  To avoid recursion, such references are released by a dedicated
213  * thread.
214  *
215  * The mtxpool lock protects the vnode from being modified while referenced.
216  * Lock ordering rules require that it be acquired before any PCB locks.
217  *
218  * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
219  * unpcb.  This includes the unp_conn field, which either links two connected
220  * PCBs together (for connected socket types) or points at the destination
221  * socket (for connectionless socket types).  The operations of creating or
222  * destroying a connection therefore involve locking multiple PCBs.  To avoid
223  * lock order reversals, in some cases this involves dropping a PCB lock and
224  * using a reference counter to maintain liveness.
225  *
226  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
227  * allocated in pr_attach() and freed in pr_detach().  The validity of that
228  * pointer is an invariant, so no lock is required to dereference the so_pcb
229  * pointer if a valid socket reference is held by the caller.  In practice,
230  * this is always true during operations performed on a socket.  Each unpcb
231  * has a back-pointer to its socket, unp_socket, which will be stable under
232  * the same circumstances.
233  *
234  * This pointer may only be safely dereferenced as long as a valid reference
235  * to the unpcb is held.  Typically, this reference will be from the socket,
236  * or from another unpcb when the referring unpcb's lock is held (in order
237  * that the reference not be invalidated during use).  For example, to follow
238  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
239  * that detach is not run clearing unp_socket.
240  *
241  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
242  * protocols, bind() is a non-atomic operation, and connect() requires
243  * potential sleeping in the protocol, due to potentially waiting on local or
244  * distributed file systems.  We try to separate "lookup" operations, which
245  * may sleep, and the IPC operations themselves, which typically can occur
246  * with relative atomicity as locks can be held over the entire operation.
247  *
248  * Another tricky issue is simultaneous multi-threaded or multi-process
249  * access to a single UNIX domain socket.  These are handled by the flags
250  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
251  * binding, both of which involve dropping UNIX domain socket locks in order
252  * to perform namei() and other file system operations.
253  */
254 static struct rwlock	unp_link_rwlock;
255 static struct mtx	unp_defers_lock;
256 
257 #define	UNP_LINK_LOCK_INIT()		rw_init(&unp_link_rwlock,	\
258 					    "unp_link_rwlock")
259 
260 #define	UNP_LINK_LOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
261 					    RA_LOCKED)
262 #define	UNP_LINK_UNLOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
263 					    RA_UNLOCKED)
264 
265 #define	UNP_LINK_RLOCK()		rw_rlock(&unp_link_rwlock)
266 #define	UNP_LINK_RUNLOCK()		rw_runlock(&unp_link_rwlock)
267 #define	UNP_LINK_WLOCK()		rw_wlock(&unp_link_rwlock)
268 #define	UNP_LINK_WUNLOCK()		rw_wunlock(&unp_link_rwlock)
269 #define	UNP_LINK_WLOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
270 					    RA_WLOCKED)
271 #define	UNP_LINK_WOWNED()		rw_wowned(&unp_link_rwlock)
272 
273 #define	UNP_DEFERRED_LOCK_INIT()	mtx_init(&unp_defers_lock, \
274 					    "unp_defer", NULL, MTX_DEF)
275 #define	UNP_DEFERRED_LOCK()		mtx_lock(&unp_defers_lock)
276 #define	UNP_DEFERRED_UNLOCK()		mtx_unlock(&unp_defers_lock)
277 
278 #define UNP_REF_LIST_LOCK()		UNP_DEFERRED_LOCK();
279 #define UNP_REF_LIST_UNLOCK()		UNP_DEFERRED_UNLOCK();
280 
281 #define UNP_PCB_LOCK_INIT(unp)		mtx_init(&(unp)->unp_mtx,	\
282 					    "unp", "unp",	\
283 					    MTX_DUPOK|MTX_DEF)
284 #define	UNP_PCB_LOCK_DESTROY(unp)	mtx_destroy(&(unp)->unp_mtx)
285 #define	UNP_PCB_LOCKPTR(unp)		(&(unp)->unp_mtx)
286 #define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
287 #define	UNP_PCB_TRYLOCK(unp)		mtx_trylock(&(unp)->unp_mtx)
288 #define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
289 #define	UNP_PCB_OWNED(unp)		mtx_owned(&(unp)->unp_mtx)
290 #define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
291 #define	UNP_PCB_UNLOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
292 
293 static int	uipc_connect2(struct socket *, struct socket *);
294 static int	uipc_ctloutput(struct socket *, struct sockopt *);
295 static int	unp_connect(struct socket *, struct sockaddr *,
296 		    struct thread *);
297 static int	unp_connectat(int, struct socket *, struct sockaddr *,
298 		    struct thread *, bool);
299 static void	unp_connect2(struct socket *, struct socket *, bool);
300 static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
301 static void	unp_dispose(struct socket *so);
302 static void	unp_shutdown(struct unpcb *);
303 static void	unp_drop(struct unpcb *);
304 static void	unp_gc(__unused void *, int);
305 static void	unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
306 static void	unp_discard(struct file *);
307 static void	unp_freerights(struct filedescent **, int);
308 static int	unp_internalize(struct mbuf *, struct mchain *,
309 		    struct thread *);
310 static void	unp_internalize_fp(struct file *);
311 static int	unp_externalize(struct mbuf *, struct mbuf **, int);
312 static int	unp_externalize_fp(struct file *);
313 static void	unp_addsockcred(struct thread *, struct mchain *, int);
314 static void	unp_process_defers(void * __unused, int);
315 
316 static void	uipc_wrknl_lock(void *);
317 static void	uipc_wrknl_unlock(void *);
318 static void	uipc_wrknl_assert_lock(void *, int);
319 
320 static void
321 unp_pcb_hold(struct unpcb *unp)
322 {
323 	u_int old __unused;
324 
325 	old = refcount_acquire(&unp->unp_refcount);
326 	KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
327 }
328 
329 static __result_use_check bool
330 unp_pcb_rele(struct unpcb *unp)
331 {
332 	bool ret;
333 
334 	UNP_PCB_LOCK_ASSERT(unp);
335 
336 	if ((ret = refcount_release(&unp->unp_refcount))) {
337 		UNP_PCB_UNLOCK(unp);
338 		UNP_PCB_LOCK_DESTROY(unp);
339 		uma_zfree(unp_zone, unp);
340 	}
341 	return (ret);
342 }
343 
344 static void
345 unp_pcb_rele_notlast(struct unpcb *unp)
346 {
347 	bool ret __unused;
348 
349 	ret = refcount_release(&unp->unp_refcount);
350 	KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
351 }
352 
353 static void
354 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
355 {
356 	UNP_PCB_UNLOCK_ASSERT(unp);
357 	UNP_PCB_UNLOCK_ASSERT(unp2);
358 
359 	if (unp == unp2) {
360 		UNP_PCB_LOCK(unp);
361 	} else if ((uintptr_t)unp2 > (uintptr_t)unp) {
362 		UNP_PCB_LOCK(unp);
363 		UNP_PCB_LOCK(unp2);
364 	} else {
365 		UNP_PCB_LOCK(unp2);
366 		UNP_PCB_LOCK(unp);
367 	}
368 }
369 
370 static void
371 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
372 {
373 	UNP_PCB_UNLOCK(unp);
374 	if (unp != unp2)
375 		UNP_PCB_UNLOCK(unp2);
376 }
377 
378 /*
379  * Try to lock the connected peer of an already locked socket.  In some cases
380  * this requires that we unlock the current socket.  The pairbusy counter is
381  * used to block concurrent connection attempts while the lock is dropped.  The
382  * caller must be careful to revalidate PCB state.
383  */
384 static struct unpcb *
385 unp_pcb_lock_peer(struct unpcb *unp)
386 {
387 	struct unpcb *unp2;
388 
389 	UNP_PCB_LOCK_ASSERT(unp);
390 	unp2 = unp->unp_conn;
391 	if (unp2 == NULL)
392 		return (NULL);
393 	if (__predict_false(unp == unp2))
394 		return (unp);
395 
396 	UNP_PCB_UNLOCK_ASSERT(unp2);
397 
398 	if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
399 		return (unp2);
400 	if ((uintptr_t)unp2 > (uintptr_t)unp) {
401 		UNP_PCB_LOCK(unp2);
402 		return (unp2);
403 	}
404 	unp->unp_pairbusy++;
405 	unp_pcb_hold(unp2);
406 	UNP_PCB_UNLOCK(unp);
407 
408 	UNP_PCB_LOCK(unp2);
409 	UNP_PCB_LOCK(unp);
410 	KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
411 	    ("%s: socket %p was reconnected", __func__, unp));
412 	if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
413 		unp->unp_flags &= ~UNP_WAITING;
414 		wakeup(unp);
415 	}
416 	if (unp_pcb_rele(unp2)) {
417 		/* unp2 is unlocked. */
418 		return (NULL);
419 	}
420 	if (unp->unp_conn == NULL) {
421 		UNP_PCB_UNLOCK(unp2);
422 		return (NULL);
423 	}
424 	return (unp2);
425 }
426 
427 /*
428  * Try to lock peer of our socket for purposes of sending data to it.
429  */
430 static int
431 uipc_lock_peer(struct socket *so, struct unpcb **unp2)
432 {
433 	struct unpcb *unp;
434 	int error;
435 
436 	unp = sotounpcb(so);
437 	UNP_PCB_LOCK(unp);
438 	*unp2 = unp_pcb_lock_peer(unp);
439 	if (__predict_false(so->so_error != 0)) {
440 		error = so->so_error;
441 		so->so_error = 0;
442 		UNP_PCB_UNLOCK(unp);
443 		if (*unp2 != NULL)
444 			UNP_PCB_UNLOCK(*unp2);
445 		return (error);
446 	}
447 	if (__predict_false(*unp2 == NULL)) {
448 		/*
449 		 * Different error code for a previously connected socket and
450 		 * a never connected one.  The SS_ISDISCONNECTED is set in the
451 		 * unp_soisdisconnected() and is synchronized by the pcb lock.
452 		 */
453 		error = so->so_state & SS_ISDISCONNECTED ? EPIPE : ENOTCONN;
454 		UNP_PCB_UNLOCK(unp);
455 		return (error);
456 	}
457 	UNP_PCB_UNLOCK(unp);
458 
459 	return (0);
460 }
461 
462 static void
463 uipc_abort(struct socket *so)
464 {
465 	struct unpcb *unp, *unp2;
466 
467 	unp = sotounpcb(so);
468 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
469 	UNP_PCB_UNLOCK_ASSERT(unp);
470 
471 	UNP_PCB_LOCK(unp);
472 	unp2 = unp->unp_conn;
473 	if (unp2 != NULL) {
474 		unp_pcb_hold(unp2);
475 		UNP_PCB_UNLOCK(unp);
476 		unp_drop(unp2);
477 	} else
478 		UNP_PCB_UNLOCK(unp);
479 }
480 
481 static int
482 uipc_attach(struct socket *so, int proto, struct thread *td)
483 {
484 	u_long sendspace, recvspace;
485 	struct unpcb *unp;
486 	int error;
487 	bool locked;
488 
489 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
490 	switch (so->so_type) {
491 	case SOCK_DGRAM:
492 		STAILQ_INIT(&so->so_rcv.uxdg_mb);
493 		STAILQ_INIT(&so->so_snd.uxdg_mb);
494 		TAILQ_INIT(&so->so_rcv.uxdg_conns);
495 		/*
496 		 * Since send buffer is either bypassed or is a part
497 		 * of one-to-many receive buffer, we assign both space
498 		 * limits to unpdg_recvspace.
499 		 */
500 		sendspace = recvspace = unpdg_recvspace;
501 		break;
502 
503 	case SOCK_STREAM:
504 		sendspace = unpst_sendspace;
505 		recvspace = unpst_recvspace;
506 		goto common;
507 
508 	case SOCK_SEQPACKET:
509 		sendspace = unpsp_sendspace;
510 		recvspace = unpsp_recvspace;
511 common:
512 		/*
513 		 * XXXGL: we need to initialize the mutex with MTX_DUPOK.
514 		 * Ideally, protocols that have PR_SOCKBUF should be
515 		 * responsible for mutex initialization officially, and then
516 		 * this uglyness with mtx_destroy(); mtx_init(); would go away.
517 		 */
518 		mtx_destroy(&so->so_rcv_mtx);
519 		mtx_init(&so->so_rcv_mtx, "so_rcv", NULL, MTX_DEF | MTX_DUPOK);
520 		knlist_init(&so->so_wrsel.si_note, so, uipc_wrknl_lock,
521 		    uipc_wrknl_unlock, uipc_wrknl_assert_lock);
522 		STAILQ_INIT(&so->so_rcv.uxst_mbq);
523 		break;
524 	default:
525 		panic("uipc_attach");
526 	}
527 	error = soreserve(so, sendspace, recvspace);
528 	if (error)
529 		return (error);
530 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
531 	if (unp == NULL)
532 		return (ENOBUFS);
533 	LIST_INIT(&unp->unp_refs);
534 	UNP_PCB_LOCK_INIT(unp);
535 	unp->unp_socket = so;
536 	so->so_pcb = unp;
537 	refcount_init(&unp->unp_refcount, 1);
538 	unp->unp_mode = ACCESSPERMS;
539 
540 	if ((locked = UNP_LINK_WOWNED()) == false)
541 		UNP_LINK_WLOCK();
542 
543 	unp->unp_gencnt = ++unp_gencnt;
544 	unp->unp_ino = ++unp_ino;
545 	unp_count++;
546 	switch (so->so_type) {
547 	case SOCK_STREAM:
548 		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
549 		break;
550 
551 	case SOCK_DGRAM:
552 		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
553 		break;
554 
555 	case SOCK_SEQPACKET:
556 		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
557 		break;
558 
559 	default:
560 		panic("uipc_attach");
561 	}
562 
563 	if (locked == false)
564 		UNP_LINK_WUNLOCK();
565 
566 	return (0);
567 }
568 
569 static int
570 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
571 {
572 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
573 	struct vattr vattr;
574 	int error, namelen;
575 	struct nameidata nd;
576 	struct unpcb *unp;
577 	struct vnode *vp;
578 	struct mount *mp;
579 	cap_rights_t rights;
580 	char *buf;
581 	mode_t mode;
582 
583 	if (nam->sa_family != AF_UNIX)
584 		return (EAFNOSUPPORT);
585 
586 	unp = sotounpcb(so);
587 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
588 
589 	if (soun->sun_len > sizeof(struct sockaddr_un))
590 		return (EINVAL);
591 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
592 	if (namelen <= 0)
593 		return (EINVAL);
594 
595 	/*
596 	 * We don't allow simultaneous bind() calls on a single UNIX domain
597 	 * socket, so flag in-progress operations, and return an error if an
598 	 * operation is already in progress.
599 	 *
600 	 * Historically, we have not allowed a socket to be rebound, so this
601 	 * also returns an error.  Not allowing re-binding simplifies the
602 	 * implementation and avoids a great many possible failure modes.
603 	 */
604 	UNP_PCB_LOCK(unp);
605 	if (unp->unp_vnode != NULL) {
606 		UNP_PCB_UNLOCK(unp);
607 		return (EINVAL);
608 	}
609 	if (unp->unp_flags & UNP_BINDING) {
610 		UNP_PCB_UNLOCK(unp);
611 		return (EALREADY);
612 	}
613 	unp->unp_flags |= UNP_BINDING;
614 	mode = unp->unp_mode & ~td->td_proc->p_pd->pd_cmask;
615 	UNP_PCB_UNLOCK(unp);
616 
617 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
618 	bcopy(soun->sun_path, buf, namelen);
619 	buf[namelen] = 0;
620 
621 restart:
622 	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | NOCACHE,
623 	    UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
624 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
625 	error = namei(&nd);
626 	if (error)
627 		goto error;
628 	vp = nd.ni_vp;
629 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
630 		NDFREE_PNBUF(&nd);
631 		if (nd.ni_dvp == vp)
632 			vrele(nd.ni_dvp);
633 		else
634 			vput(nd.ni_dvp);
635 		if (vp != NULL) {
636 			vrele(vp);
637 			error = EADDRINUSE;
638 			goto error;
639 		}
640 		error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH);
641 		if (error)
642 			goto error;
643 		goto restart;
644 	}
645 	VATTR_NULL(&vattr);
646 	vattr.va_type = VSOCK;
647 	vattr.va_mode = mode;
648 #ifdef MAC
649 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
650 	    &vattr);
651 #endif
652 	if (error == 0) {
653 		/*
654 		 * The prior lookup may have left LK_SHARED in cn_lkflags,
655 		 * and VOP_CREATE technically only requires the new vnode to
656 		 * be locked shared. Most filesystems will return the new vnode
657 		 * locked exclusive regardless, but we should explicitly
658 		 * specify that here since we require it and assert to that
659 		 * effect below.
660 		 */
661 		nd.ni_cnd.cn_lkflags = (nd.ni_cnd.cn_lkflags & ~LK_SHARED) |
662 		    LK_EXCLUSIVE;
663 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
664 	}
665 	NDFREE_PNBUF(&nd);
666 	if (error) {
667 		VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
668 		vn_finished_write(mp);
669 		if (error == ERELOOKUP)
670 			goto restart;
671 		goto error;
672 	}
673 	vp = nd.ni_vp;
674 	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
675 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
676 
677 	UNP_PCB_LOCK(unp);
678 	VOP_UNP_BIND(vp, unp);
679 	unp->unp_vnode = vp;
680 	unp->unp_addr = soun;
681 	unp->unp_flags &= ~UNP_BINDING;
682 	UNP_PCB_UNLOCK(unp);
683 	vref(vp);
684 	VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
685 	vn_finished_write(mp);
686 	free(buf, M_TEMP);
687 	return (0);
688 
689 error:
690 	UNP_PCB_LOCK(unp);
691 	unp->unp_flags &= ~UNP_BINDING;
692 	UNP_PCB_UNLOCK(unp);
693 	free(buf, M_TEMP);
694 	return (error);
695 }
696 
697 static int
698 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
699 {
700 
701 	return (uipc_bindat(AT_FDCWD, so, nam, td));
702 }
703 
704 static int
705 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
706 {
707 	int error;
708 
709 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
710 	error = unp_connect(so, nam, td);
711 	return (error);
712 }
713 
714 static int
715 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
716     struct thread *td)
717 {
718 	int error;
719 
720 	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
721 	error = unp_connectat(fd, so, nam, td, false);
722 	return (error);
723 }
724 
725 static void
726 uipc_close(struct socket *so)
727 {
728 	struct unpcb *unp, *unp2;
729 	struct vnode *vp = NULL;
730 	struct mtx *vplock;
731 
732 	unp = sotounpcb(so);
733 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
734 
735 	vplock = NULL;
736 	if ((vp = unp->unp_vnode) != NULL) {
737 		vplock = mtx_pool_find(unp_vp_mtxpool, vp);
738 		mtx_lock(vplock);
739 	}
740 	UNP_PCB_LOCK(unp);
741 	if (vp && unp->unp_vnode == NULL) {
742 		mtx_unlock(vplock);
743 		vp = NULL;
744 	}
745 	if (vp != NULL) {
746 		VOP_UNP_DETACH(vp);
747 		unp->unp_vnode = NULL;
748 	}
749 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
750 		unp_disconnect(unp, unp2);
751 	else
752 		UNP_PCB_UNLOCK(unp);
753 	if (vp) {
754 		mtx_unlock(vplock);
755 		vrele(vp);
756 	}
757 }
758 
759 static int
760 uipc_chmod(struct socket *so, mode_t mode, struct ucred *cred __unused,
761     struct thread *td __unused)
762 {
763 	struct unpcb *unp;
764 	int error;
765 
766 	if ((mode & ~ACCESSPERMS) != 0)
767 		return (EINVAL);
768 
769 	error = 0;
770 	unp = sotounpcb(so);
771 	UNP_PCB_LOCK(unp);
772 	if (unp->unp_vnode != NULL || (unp->unp_flags & UNP_BINDING) != 0)
773 		error = EINVAL;
774 	else
775 		unp->unp_mode = mode;
776 	UNP_PCB_UNLOCK(unp);
777 	return (error);
778 }
779 
780 static int
781 uipc_connect2(struct socket *so1, struct socket *so2)
782 {
783 	struct unpcb *unp, *unp2;
784 
785 	if (so1->so_type != so2->so_type)
786 		return (EPROTOTYPE);
787 
788 	unp = so1->so_pcb;
789 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
790 	unp2 = so2->so_pcb;
791 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
792 	unp_pcb_lock_pair(unp, unp2);
793 	unp_connect2(so1, so2, false);
794 	unp_pcb_unlock_pair(unp, unp2);
795 
796 	return (0);
797 }
798 
799 static void
800 uipc_detach(struct socket *so)
801 {
802 	struct unpcb *unp, *unp2;
803 	struct mtx *vplock;
804 	struct vnode *vp;
805 	int local_unp_rights;
806 
807 	unp = sotounpcb(so);
808 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
809 
810 	vp = NULL;
811 	vplock = NULL;
812 
813 	if (!SOLISTENING(so))
814 		unp_dispose(so);
815 
816 	UNP_LINK_WLOCK();
817 	LIST_REMOVE(unp, unp_link);
818 	if (unp->unp_gcflag & UNPGC_DEAD)
819 		LIST_REMOVE(unp, unp_dead);
820 	unp->unp_gencnt = ++unp_gencnt;
821 	--unp_count;
822 	UNP_LINK_WUNLOCK();
823 
824 	UNP_PCB_UNLOCK_ASSERT(unp);
825  restart:
826 	if ((vp = unp->unp_vnode) != NULL) {
827 		vplock = mtx_pool_find(unp_vp_mtxpool, vp);
828 		mtx_lock(vplock);
829 	}
830 	UNP_PCB_LOCK(unp);
831 	if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
832 		if (vplock)
833 			mtx_unlock(vplock);
834 		UNP_PCB_UNLOCK(unp);
835 		goto restart;
836 	}
837 	if ((vp = unp->unp_vnode) != NULL) {
838 		VOP_UNP_DETACH(vp);
839 		unp->unp_vnode = NULL;
840 	}
841 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
842 		unp_disconnect(unp, unp2);
843 	else
844 		UNP_PCB_UNLOCK(unp);
845 
846 	UNP_REF_LIST_LOCK();
847 	while (!LIST_EMPTY(&unp->unp_refs)) {
848 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
849 
850 		unp_pcb_hold(ref);
851 		UNP_REF_LIST_UNLOCK();
852 
853 		MPASS(ref != unp);
854 		UNP_PCB_UNLOCK_ASSERT(ref);
855 		unp_drop(ref);
856 		UNP_REF_LIST_LOCK();
857 	}
858 	UNP_REF_LIST_UNLOCK();
859 
860 	UNP_PCB_LOCK(unp);
861 	local_unp_rights = unp_rights;
862 	unp->unp_socket->so_pcb = NULL;
863 	unp->unp_socket = NULL;
864 	free(unp->unp_addr, M_SONAME);
865 	unp->unp_addr = NULL;
866 	if (!unp_pcb_rele(unp))
867 		UNP_PCB_UNLOCK(unp);
868 	if (vp) {
869 		mtx_unlock(vplock);
870 		vrele(vp);
871 	}
872 	if (local_unp_rights)
873 		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
874 
875 	switch (so->so_type) {
876 	case SOCK_STREAM:
877 	case SOCK_SEQPACKET:
878 		MPASS(SOLISTENING(so) || (STAILQ_EMPTY(&so->so_rcv.uxst_mbq) &&
879 		    so->so_rcv.uxst_peer == NULL));
880 		break;
881 	case SOCK_DGRAM:
882 		/*
883 		 * Everything should have been unlinked/freed by unp_dispose()
884 		 * and/or unp_disconnect().
885 		 */
886 		MPASS(so->so_rcv.uxdg_peeked == NULL);
887 		MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb));
888 		MPASS(TAILQ_EMPTY(&so->so_rcv.uxdg_conns));
889 		MPASS(STAILQ_EMPTY(&so->so_snd.uxdg_mb));
890 	}
891 }
892 
893 static int
894 uipc_disconnect(struct socket *so)
895 {
896 	struct unpcb *unp, *unp2;
897 
898 	unp = sotounpcb(so);
899 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
900 
901 	UNP_PCB_LOCK(unp);
902 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
903 		unp_disconnect(unp, unp2);
904 	else
905 		UNP_PCB_UNLOCK(unp);
906 	return (0);
907 }
908 
909 static int
910 uipc_listen(struct socket *so, int backlog, struct thread *td)
911 {
912 	struct unpcb *unp;
913 	int error;
914 
915 	MPASS(so->so_type != SOCK_DGRAM);
916 
917 	/*
918 	 * Synchronize with concurrent connection attempts.
919 	 */
920 	error = 0;
921 	unp = sotounpcb(so);
922 	UNP_PCB_LOCK(unp);
923 	if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
924 		error = EINVAL;
925 	else if (unp->unp_vnode == NULL)
926 		error = EDESTADDRREQ;
927 	if (error != 0) {
928 		UNP_PCB_UNLOCK(unp);
929 		return (error);
930 	}
931 
932 	SOCK_LOCK(so);
933 	error = solisten_proto_check(so);
934 	if (error == 0) {
935 		cru2xt(td, &unp->unp_peercred);
936 		if (!SOLISTENING(so)) {
937 			(void)chgsbsize(so->so_cred->cr_uidinfo,
938 			    &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
939 			(void)chgsbsize(so->so_cred->cr_uidinfo,
940 			    &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
941 		}
942 		solisten_proto(so, backlog);
943 	}
944 	SOCK_UNLOCK(so);
945 	UNP_PCB_UNLOCK(unp);
946 	return (error);
947 }
948 
949 static int
950 uipc_peeraddr(struct socket *so, struct sockaddr *ret)
951 {
952 	struct unpcb *unp, *unp2;
953 	const struct sockaddr *sa;
954 
955 	unp = sotounpcb(so);
956 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
957 
958 	UNP_PCB_LOCK(unp);
959 	unp2 = unp_pcb_lock_peer(unp);
960 	if (unp2 != NULL) {
961 		if (unp2->unp_addr != NULL)
962 			sa = (struct sockaddr *)unp2->unp_addr;
963 		else
964 			sa = &sun_noname;
965 		bcopy(sa, ret, sa->sa_len);
966 		unp_pcb_unlock_pair(unp, unp2);
967 	} else {
968 		UNP_PCB_UNLOCK(unp);
969 		sa = &sun_noname;
970 		bcopy(sa, ret, sa->sa_len);
971 	}
972 	return (0);
973 }
974 
975 /*
976  * pr_sosend() called with mbuf instead of uio is a kernel thread.  NFS,
977  * netgraph(4) and other subsystems can call into socket code.  The
978  * function will condition the mbuf so that it can be safely put onto socket
979  * buffer and calculate its char count and mbuf count.
980  *
981  * Note: we don't support receiving control data from a kernel thread.  Our
982  * pr_sosend methods have MPASS() to check that.  This may change.
983  */
984 static void
985 uipc_reset_kernel_mbuf(struct mbuf *m, struct mchain *mc)
986 {
987 
988 	M_ASSERTPKTHDR(m);
989 
990 	m_clrprotoflags(m);
991 	m_tag_delete_chain(m, NULL);
992 	m->m_pkthdr.rcvif = NULL;
993 	m->m_pkthdr.flowid = 0;
994 	m->m_pkthdr.csum_flags = 0;
995 	m->m_pkthdr.fibnum = 0;
996 	m->m_pkthdr.rsstype = 0;
997 
998 	mc_init_m(mc, m);
999 	MPASS(m->m_pkthdr.len == mc->mc_len);
1000 }
1001 
1002 #ifdef SOCKBUF_DEBUG
1003 static inline void
1004 uipc_stream_sbcheck(struct sockbuf *sb)
1005 {
1006 	struct mbuf *d;
1007 	u_int dacc, dccc, dctl, dmbcnt;
1008 	bool notready = false;
1009 
1010 	dacc = dccc = dctl = dmbcnt = 0;
1011 	STAILQ_FOREACH(d, &sb->uxst_mbq, m_stailq) {
1012 		if (d == sb->uxst_fnrdy)
1013 			notready = true;
1014 		if (notready)
1015 			MPASS(d->m_flags & M_NOTREADY);
1016 		if (d->m_type == MT_CONTROL)
1017 			dctl += d->m_len;
1018 		else if (d->m_type == MT_DATA) {
1019 			dccc +=  d->m_len;
1020 			if (!notready)
1021 				dacc += d->m_len;
1022 		} else
1023 			MPASS(0);
1024 		dmbcnt += MSIZE;
1025 		if (d->m_flags & M_EXT)
1026 			dmbcnt += d->m_ext.ext_size;
1027 		if (d->m_stailq.stqe_next == NULL)
1028 			MPASS(sb->uxst_mbq.stqh_last == &d->m_stailq.stqe_next);
1029 	}
1030 	MPASS(sb->uxst_fnrdy == NULL || notready);
1031 	MPASS(dacc == sb->sb_acc);
1032 	MPASS(dccc == sb->sb_ccc);
1033 	MPASS(dctl == sb->sb_ctl);
1034 	MPASS(dmbcnt == sb->sb_mbcnt);
1035 	(void)STAILQ_EMPTY(&sb->uxst_mbq);
1036 }
1037 #define	UIPC_STREAM_SBCHECK(sb)	uipc_stream_sbcheck(sb)
1038 #else
1039 #define	UIPC_STREAM_SBCHECK(sb)	do {} while (0)
1040 #endif
1041 
1042 /*
1043  * uipc_stream_sbspace() returns how much a writer can send, limited by char
1044  * count or mbuf memory use, whatever ends first.
1045  *
1046  * An obvious and legitimate reason for a socket having more data than allowed,
1047  * is lowering the limit with setsockopt(SO_RCVBUF) on already full buffer.
1048  * Also, sb_mbcnt may overcommit sb_mbmax in case if previous write observed
1049  * 'space < mbspace', but mchain allocated to hold 'space' bytes of data ended
1050  * up with 'mc_mlen > mbspace'.  A typical scenario would be a full buffer with
1051  * writer trying to push in a large write, and a slow reader, that reads just
1052  * a few bytes at a time.  In that case writer will keep creating new mbufs
1053  * with mc_split().  These mbufs will carry little chars, but will all point at
1054  * the same cluster, thus each adding cluster size to sb_mbcnt.  This means we
1055  * will count same cluster many times potentially underutilizing socket buffer.
1056  * We aren't optimizing towards ineffective readers.  Classic socket buffer had
1057  * the same "feature".
1058  */
1059 static inline u_int
1060 uipc_stream_sbspace(struct sockbuf *sb)
1061 {
1062 	u_int space, mbspace;
1063 
1064 	if (__predict_true(sb->sb_hiwat >= sb->sb_ccc + sb->sb_ctl))
1065 		space = sb->sb_hiwat - sb->sb_ccc - sb->sb_ctl;
1066 	else
1067 		return (0);
1068 	if (__predict_true(sb->sb_mbmax >= sb->sb_mbcnt))
1069 		mbspace = sb->sb_mbmax - sb->sb_mbcnt;
1070 	else
1071 		return (0);
1072 
1073 	return (min(space, mbspace));
1074 }
1075 
1076 static int
1077 uipc_sosend_stream_or_seqpacket(struct socket *so, struct sockaddr *addr,
1078     struct uio *uio0, struct mbuf *m, struct mbuf *c, int flags,
1079     struct thread *td)
1080 {
1081 	struct unpcb *unp2;
1082 	struct socket *so2;
1083 	struct sockbuf *sb;
1084 	struct uio *uio;
1085 	struct mchain mc, cmc;
1086 	size_t resid, sent;
1087 	bool nonblock, eor, aio;
1088 	int error;
1089 
1090 	MPASS((uio0 != NULL && m == NULL) || (m != NULL && uio0 == NULL));
1091 	MPASS(m == NULL || c == NULL);
1092 
1093 	if (__predict_false(flags & MSG_OOB))
1094 		return (EOPNOTSUPP);
1095 
1096 	nonblock = (so->so_state & SS_NBIO) ||
1097 	    (flags & (MSG_DONTWAIT | MSG_NBIO));
1098 	eor = flags & MSG_EOR;
1099 
1100 	mc = MCHAIN_INITIALIZER(&mc);
1101 	cmc = MCHAIN_INITIALIZER(&cmc);
1102 	sent = 0;
1103 	aio = false;
1104 
1105 	if (m == NULL) {
1106 		if (c != NULL && (error = unp_internalize(c, &cmc, td)))
1107 			goto out;
1108 		/*
1109 		 * This function may read more data from the uio than it would
1110 		 * then place on socket.  That would leave uio inconsistent
1111 		 * upon return.  Normally uio is allocated on the stack of the
1112 		 * syscall thread and we don't care about leaving it consistent.
1113 		 * However, aio(9) will allocate a uio as part of job and will
1114 		 * use it to track progress.  We detect aio(9) checking the
1115 		 * SB_AIO_RUNNING flag.  It is safe to check it without lock
1116 		 * cause it is set and cleared in the same taskqueue thread.
1117 		 *
1118 		 * This check can also produce a false positive: there is
1119 		 * aio(9) job and also there is a syscall we are serving now.
1120 		 * No sane software does that, it would leave to a mess in
1121 		 * the socket buffer, as aio(9) doesn't grab the I/O sx(9).
1122 		 * But syzkaller can create this mess.  For such false positive
1123 		 * our goal is just don't panic or leak memory.
1124 		 */
1125 		if (__predict_false(so->so_snd.sb_flags & SB_AIO_RUNNING)) {
1126 			uio = cloneuio(uio0);
1127 			aio = true;
1128 		} else {
1129 			uio = uio0;
1130 			resid = uio->uio_resid;
1131 		}
1132 		/*
1133 		 * Optimization for a case when our send fits into the receive
1134 		 * buffer - do the copyin before taking any locks, sized to our
1135 		 * send buffer.  Later copyins will also take into account
1136 		 * space in the peer's receive buffer.
1137 		 */
1138 		error = mc_uiotomc(&mc, uio, so->so_snd.sb_hiwat, 0, M_WAITOK,
1139 		    eor ? M_EOR : 0);
1140 		if (__predict_false(error))
1141 			goto out2;
1142 	} else
1143 		uipc_reset_kernel_mbuf(m, &mc);
1144 
1145 	error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1146 	if (error)
1147 		goto out2;
1148 
1149 	if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0))
1150 		goto out3;
1151 
1152 	if (unp2->unp_flags & UNP_WANTCRED_MASK) {
1153 		/*
1154 		 * Credentials are passed only once on SOCK_STREAM and
1155 		 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
1156 		 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
1157 		 */
1158 		unp_addsockcred(td, &cmc, unp2->unp_flags);
1159 		unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
1160 	}
1161 
1162 	/*
1163 	 * Cycle through the data to send and available space in the peer's
1164 	 * receive buffer.  Put a reference on the peer socket, so that it
1165 	 * doesn't get freed while we sbwait().  If peer goes away, we will
1166 	 * observe the SBS_CANTRCVMORE and our sorele() will finalize peer's
1167 	 * socket destruction.
1168 	 */
1169 	so2 = unp2->unp_socket;
1170 	soref(so2);
1171 	UNP_PCB_UNLOCK(unp2);
1172 	sb = &so2->so_rcv;
1173 	while (mc.mc_len + cmc.mc_len > 0) {
1174 		struct mchain mcnext = MCHAIN_INITIALIZER(&mcnext);
1175 		u_int space;
1176 
1177 		SOCK_RECVBUF_LOCK(so2);
1178 restart:
1179 		UIPC_STREAM_SBCHECK(sb);
1180 		if (__predict_false(cmc.mc_len > sb->sb_hiwat)) {
1181 			SOCK_RECVBUF_UNLOCK(so2);
1182 			error = EMSGSIZE;
1183 			goto out4;
1184 		}
1185 		if (__predict_false(sb->sb_state & SBS_CANTRCVMORE)) {
1186 			SOCK_RECVBUF_UNLOCK(so2);
1187 			error = EPIPE;
1188 			goto out4;
1189 		}
1190 		/*
1191 		 * Wait on the peer socket receive buffer until we have enough
1192 		 * space to put at least control.  The data is a stream and can
1193 		 * be put partially, but control is really a datagram.
1194 		 */
1195 		space = uipc_stream_sbspace(sb);
1196 		if (space < sb->sb_lowat || space < cmc.mc_len) {
1197 			if (nonblock) {
1198 				if (aio)
1199 					sb->uxst_flags |= UXST_PEER_AIO;
1200 				SOCK_RECVBUF_UNLOCK(so2);
1201 				if (aio) {
1202 					SOCK_SENDBUF_LOCK(so);
1203 					so->so_snd.sb_ccc =
1204 					    so->so_snd.sb_hiwat - space;
1205 					SOCK_SENDBUF_UNLOCK(so);
1206 				}
1207 				error = EWOULDBLOCK;
1208 				goto out4;
1209 			}
1210 			if ((error = sbwait(so2, SO_RCV)) != 0) {
1211 				SOCK_RECVBUF_UNLOCK(so2);
1212 				goto out4;
1213 			} else
1214 				goto restart;
1215 		}
1216 		MPASS(space >= cmc.mc_len);
1217 		space -= cmc.mc_len;
1218 		if (space == 0) {
1219 			/* There is space only to send control. */
1220 			MPASS(!STAILQ_EMPTY(&cmc.mc_q));
1221 			mcnext = mc;
1222 			mc = MCHAIN_INITIALIZER(&mc);
1223 		} else if (space < mc.mc_len) {
1224 			/* Not enough space. */
1225 			if (__predict_false(mc_split(&mc, &mcnext, space,
1226 			    M_NOWAIT) == ENOMEM)) {
1227 				/*
1228 				 * If allocation failed use M_WAITOK and merge
1229 				 * the chain back.  Next time mc_split() will
1230 				 * easily split at the same place.  Only if we
1231 				 * race with setsockopt(SO_RCVBUF) shrinking
1232 				 * sb_hiwat can this happen more than once.
1233 				 */
1234 				SOCK_RECVBUF_UNLOCK(so2);
1235 				(void)mc_split(&mc, &mcnext, space, M_WAITOK);
1236 				mc_concat(&mc, &mcnext);
1237 				SOCK_RECVBUF_LOCK(so2);
1238 				goto restart;
1239 			}
1240 			MPASS(mc.mc_len == space);
1241 		}
1242 		if (!STAILQ_EMPTY(&cmc.mc_q)) {
1243 			STAILQ_CONCAT(&sb->uxst_mbq, &cmc.mc_q);
1244 			sb->sb_ctl += cmc.mc_len;
1245 			sb->sb_mbcnt += cmc.mc_mlen;
1246 			cmc.mc_len = 0;
1247 		}
1248 		sent += mc.mc_len;
1249 		sb->sb_acc += mc.mc_len;
1250 		sb->sb_ccc += mc.mc_len;
1251 		sb->sb_mbcnt += mc.mc_mlen;
1252 		STAILQ_CONCAT(&sb->uxst_mbq, &mc.mc_q);
1253 		UIPC_STREAM_SBCHECK(sb);
1254 		space = uipc_stream_sbspace(sb);
1255 		sorwakeup_locked(so2);
1256 		if (!STAILQ_EMPTY(&mcnext.mc_q)) {
1257 			/*
1258 			 * Such assignment is unsafe in general, but it is
1259 			 * safe with !STAILQ_EMPTY(&mcnext.mc_q).  In C++ we
1260 			 * could reload = for STAILQs :)
1261 			 */
1262 			mc = mcnext;
1263 		} else if (uio != NULL && uio->uio_resid > 0) {
1264 			/*
1265 			 * Copyin sum of peer's receive buffer space and our
1266 			 * sb_hiwat, which is our virtual send buffer size.
1267 			 * See comment above unpst_sendspace declaration.
1268 			 * We are reading sb_hiwat locklessly, cause a) we
1269 			 * don't care about an application that does send(2)
1270 			 * and setsockopt(2) racing internally, and for an
1271 			 * application that does this in sequence we will see
1272 			 * the correct value cause sbsetopt() uses buffer lock
1273 			 * and we also have already acquired it at least once.
1274 			 */
1275 			error = mc_uiotomc(&mc, uio, space +
1276 			    atomic_load_int(&so->so_snd.sb_hiwat), 0, M_WAITOK,
1277 			    eor ? M_EOR : 0);
1278 			if (__predict_false(error))
1279 				goto out4;
1280 		} else
1281 			mc = MCHAIN_INITIALIZER(&mc);
1282 	}
1283 
1284 	MPASS(STAILQ_EMPTY(&mc.mc_q));
1285 
1286 	td->td_ru.ru_msgsnd++;
1287 out4:
1288 	sorele(so2);
1289 out3:
1290 	SOCK_IO_SEND_UNLOCK(so);
1291 out2:
1292 	if (aio) {
1293 		freeuio(uio);
1294 		uioadvance(uio0, sent);
1295 	} else if (uio != NULL)
1296 		uio->uio_resid = resid - sent;
1297 	if (!mc_empty(&cmc))
1298 		unp_scan(mc_first(&cmc), unp_freerights);
1299 out:
1300 	mc_freem(&mc);
1301 	mc_freem(&cmc);
1302 
1303 	return (error);
1304 }
1305 
1306 static int
1307 uipc_soreceive_stream_or_seqpacket(struct socket *so, struct sockaddr **psa,
1308     struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1309 {
1310 	struct sockbuf *sb = &so->so_rcv;
1311 	struct mbuf *control, *m, *first, *last, *next;
1312 	u_int ctl, space, datalen, mbcnt, lastlen;
1313 	int error, flags;
1314 	bool nonblock, waitall, peek;
1315 
1316 	MPASS(mp0 == NULL);
1317 
1318 	if (psa != NULL)
1319 		*psa = NULL;
1320 	if (controlp != NULL)
1321 		*controlp = NULL;
1322 
1323 	flags = flagsp != NULL ? *flagsp : 0;
1324 	nonblock = (so->so_state & SS_NBIO) ||
1325 	    (flags & (MSG_DONTWAIT | MSG_NBIO));
1326 	peek = flags & MSG_PEEK;
1327 	waitall = (flags & MSG_WAITALL) && !peek;
1328 
1329 	/*
1330 	 * This check may fail only on a socket that never went through
1331 	 * connect(2).  We can check this locklessly, cause: a) for a new born
1332 	 * socket we don't care about applications that may race internally
1333 	 * between connect(2) and recv(2), and b) for a dying socket if we
1334 	 * miss update by unp_sosidisconnected(), we would still get the check
1335 	 * correct.  For dying socket we would observe SBS_CANTRCVMORE later.
1336 	 */
1337 	if (__predict_false((atomic_load_short(&so->so_state) &
1338 	    (SS_ISCONNECTED|SS_ISDISCONNECTED)) == 0))
1339 		return (ENOTCONN);
1340 
1341 	error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
1342 	if (__predict_false(error))
1343 		return (error);
1344 
1345 restart:
1346 	SOCK_RECVBUF_LOCK(so);
1347 	UIPC_STREAM_SBCHECK(sb);
1348 	while (sb->sb_acc < sb->sb_lowat &&
1349 	    (sb->sb_ctl == 0 || controlp == NULL)) {
1350 		if (so->so_error) {
1351 			error = so->so_error;
1352 			if (!peek)
1353 				so->so_error = 0;
1354 			SOCK_RECVBUF_UNLOCK(so);
1355 			SOCK_IO_RECV_UNLOCK(so);
1356 			return (error);
1357 		}
1358 		if (sb->sb_state & SBS_CANTRCVMORE) {
1359 			SOCK_RECVBUF_UNLOCK(so);
1360 			SOCK_IO_RECV_UNLOCK(so);
1361 			return (0);
1362 		}
1363 		if (nonblock) {
1364 			SOCK_RECVBUF_UNLOCK(so);
1365 			SOCK_IO_RECV_UNLOCK(so);
1366 			return (EWOULDBLOCK);
1367 		}
1368 		error = sbwait(so, SO_RCV);
1369 		if (error) {
1370 			SOCK_RECVBUF_UNLOCK(so);
1371 			SOCK_IO_RECV_UNLOCK(so);
1372 			return (error);
1373 		}
1374 	}
1375 
1376 	MPASS(STAILQ_FIRST(&sb->uxst_mbq));
1377 	MPASS(sb->sb_acc > 0 || sb->sb_ctl > 0);
1378 
1379 	mbcnt = 0;
1380 	ctl = 0;
1381 	first = STAILQ_FIRST(&sb->uxst_mbq);
1382 	if (first->m_type == MT_CONTROL) {
1383 		control = first;
1384 		STAILQ_FOREACH_FROM(first, &sb->uxst_mbq, m_stailq) {
1385 			if (first->m_type != MT_CONTROL)
1386 				break;
1387 			ctl += first->m_len;
1388 			mbcnt += MSIZE;
1389 			if (first->m_flags & M_EXT)
1390 				mbcnt += first->m_ext.ext_size;
1391 		}
1392 	} else
1393 		control = NULL;
1394 
1395 	/*
1396 	 * Find split point for the next copyout.  On exit from the loop:
1397 	 * last == NULL - socket to be flushed
1398 	 * last != NULL
1399 	 *   lastlen > last->m_len - uio to be filled, last to be adjusted
1400 	 *   lastlen == 0          - MT_CONTROL or M_EOR encountered
1401 	 */
1402 	space = uio->uio_resid;
1403 	datalen = 0;
1404 	for (m = first, last = NULL; m != NULL; m = STAILQ_NEXT(m, m_stailq)) {
1405 		if (m->m_type != MT_DATA) {
1406 			last = m;
1407 			lastlen = 0;
1408 			break;
1409 		}
1410 		if (space >= m->m_len) {
1411 			space -= m->m_len;
1412 			datalen += m->m_len;
1413 			mbcnt += MSIZE;
1414 			if (m->m_flags & M_EXT)
1415 				mbcnt += m->m_ext.ext_size;
1416 			if (m->m_flags & M_EOR) {
1417 				last = STAILQ_NEXT(m, m_stailq);
1418 				lastlen = 0;
1419 				flags |= MSG_EOR;
1420 				break;
1421 			}
1422 		} else {
1423 			datalen += space;
1424 			last = m;
1425 			lastlen = space;
1426 			break;
1427 		}
1428 	}
1429 
1430 	UIPC_STREAM_SBCHECK(sb);
1431 	if (!peek) {
1432 		if (last == NULL)
1433 			STAILQ_INIT(&sb->uxst_mbq);
1434 		else {
1435 			STAILQ_FIRST(&sb->uxst_mbq) = last;
1436 			MPASS(last->m_len > lastlen);
1437 			last->m_len -= lastlen;
1438 			last->m_data += lastlen;
1439 		}
1440 		MPASS(sb->sb_acc >= datalen);
1441 		sb->sb_acc -= datalen;
1442 		sb->sb_ccc -= datalen;
1443 		MPASS(sb->sb_ctl >= ctl);
1444 		sb->sb_ctl -= ctl;
1445 		MPASS(sb->sb_mbcnt >= mbcnt);
1446 		sb->sb_mbcnt -= mbcnt;
1447 		UIPC_STREAM_SBCHECK(sb);
1448 		/*
1449 		 * In a blocking mode peer is sleeping on our receive buffer,
1450 		 * and we need just wakeup(9) on it.  But to wake up various
1451 		 * event engines, we need to reach over to peer's selinfo.
1452 		 * This can be safely done as the socket buffer receive lock
1453 		 * is protecting us from the peer going away.
1454 		 */
1455 		if (__predict_true(sb->uxst_peer != NULL)) {
1456 			struct selinfo *sel = &sb->uxst_peer->so_wrsel;
1457 			struct unpcb *unp2;
1458 			bool aio;
1459 
1460 			if ((aio = sb->uxst_flags & UXST_PEER_AIO))
1461 				sb->uxst_flags &= ~UXST_PEER_AIO;
1462 			if (sb->uxst_flags & UXST_PEER_SEL) {
1463 				selwakeuppri(sel, PSOCK);
1464 				/*
1465 				 * XXXGL: sowakeup() does SEL_WAITING() without
1466 				 * locks.
1467 				 */
1468 				if (!SEL_WAITING(sel))
1469 					sb->uxst_flags &= ~UXST_PEER_SEL;
1470 			}
1471 			if (sb->sb_flags & SB_WAIT) {
1472 				sb->sb_flags &= ~SB_WAIT;
1473 				wakeup(&sb->sb_acc);
1474 			}
1475 			KNOTE_LOCKED(&sel->si_note, 0);
1476 			SOCK_RECVBUF_UNLOCK(so);
1477 			/*
1478 			 * XXXGL: need to go through uipc_lock_peer() after
1479 			 * the receive buffer lock dropped, it was protecting
1480 			 * us from unp_soisdisconnected().  The aio workarounds
1481 			 * should be refactored to the aio(4) side.
1482 			 */
1483 			if (aio && uipc_lock_peer(so, &unp2) == 0) {
1484 				struct socket *so2 = unp2->unp_socket;
1485 
1486 				SOCK_SENDBUF_LOCK(so2);
1487 				so2->so_snd.sb_ccc -= datalen;
1488 				sowakeup_aio(so2, SO_SND);
1489 				SOCK_SENDBUF_UNLOCK(so2);
1490 				UNP_PCB_UNLOCK(unp2);
1491 			}
1492 		} else
1493 			SOCK_RECVBUF_UNLOCK(so);
1494 	} else
1495 		SOCK_RECVBUF_UNLOCK(so);
1496 
1497 	while (control != NULL && control->m_type == MT_CONTROL) {
1498 		if (!peek) {
1499 			struct mbuf *c;
1500 
1501 			/*
1502 			 * unp_externalize() failure must abort entire read(2).
1503 			 * Such failure should also free the problematic
1504 			 * control, but link back the remaining data to the head
1505 			 * of the buffer, so that socket is not left in a state
1506 			 * where it can't progress forward with reading.
1507 			 * Probability of such a failure is really low, so it
1508 			 * is fine that we need to perform pretty complex
1509 			 * operation here to reconstruct the buffer.
1510 			 * XXXGL: unp_externalize() used to be
1511 			 * dom_externalize() KBI and it frees whole chain, so
1512 			 * we need to feed it with mbufs one by one.
1513 			 */
1514 			c = control;
1515 			control = STAILQ_NEXT(c, m_stailq);
1516 			STAILQ_NEXT(c, m_stailq) = NULL;
1517 			error = unp_externalize(c, controlp, flags);
1518 			if (__predict_false(error && control != NULL)) {
1519 				struct mchain cmc;
1520 
1521 				mc_init_m(&cmc, control);
1522 
1523 				SOCK_RECVBUF_LOCK(so);
1524 				MPASS(!(sb->sb_state & SBS_CANTRCVMORE));
1525 
1526 				if (__predict_false(cmc.mc_len + sb->sb_ccc +
1527 				    sb->sb_ctl > sb->sb_hiwat)) {
1528 					/*
1529 					 * Too bad, while unp_externalize() was
1530 					 * failing, the other side had filled
1531 					 * the buffer and we can't prepend data
1532 					 * back. Losing data!
1533 					 */
1534 					SOCK_RECVBUF_UNLOCK(so);
1535 					SOCK_IO_RECV_UNLOCK(so);
1536 					unp_scan(mc_first(&cmc),
1537 					    unp_freerights);
1538 					mc_freem(&cmc);
1539 					return (error);
1540 				}
1541 
1542 				UIPC_STREAM_SBCHECK(sb);
1543 				/* XXXGL: STAILQ_PREPEND */
1544 				STAILQ_CONCAT(&cmc.mc_q, &sb->uxst_mbq);
1545 				STAILQ_SWAP(&cmc.mc_q, &sb->uxst_mbq, mbuf);
1546 
1547 				sb->sb_ctl = sb->sb_acc = sb->sb_ccc =
1548 				    sb->sb_mbcnt = 0;
1549 				STAILQ_FOREACH(m, &sb->uxst_mbq, m_stailq) {
1550 					if (m->m_type == MT_DATA) {
1551 						sb->sb_acc += m->m_len;
1552 						sb->sb_ccc += m->m_len;
1553 					} else {
1554 						sb->sb_ctl += m->m_len;
1555 					}
1556 					sb->sb_mbcnt += MSIZE;
1557 					if (m->m_flags & M_EXT)
1558 						sb->sb_mbcnt +=
1559 						    m->m_ext.ext_size;
1560 				}
1561 				UIPC_STREAM_SBCHECK(sb);
1562 				SOCK_RECVBUF_UNLOCK(so);
1563 				SOCK_IO_RECV_UNLOCK(so);
1564 				return (error);
1565 			}
1566 			if (controlp != NULL) {
1567 				while (*controlp != NULL)
1568 					controlp = &(*controlp)->m_next;
1569 			}
1570 		} else {
1571 			/*
1572 			 * XXXGL
1573 			 *
1574 			 * In MSG_PEEK case control is not externalized.  This
1575 			 * means we are leaking some kernel pointers to the
1576 			 * userland.  They are useless to a law-abiding
1577 			 * application, but may be useful to a malware.  This
1578 			 * is what the historical implementation in the
1579 			 * soreceive_generic() did. To be improved?
1580 			 */
1581 			if (controlp != NULL) {
1582 				*controlp = m_copym(control, 0, control->m_len,
1583 				    M_WAITOK);
1584 				controlp = &(*controlp)->m_next;
1585 			}
1586 			control = STAILQ_NEXT(control, m_stailq);
1587 		}
1588 	}
1589 
1590 	for (m = first; m != last; m = next) {
1591 		next = STAILQ_NEXT(m, m_stailq);
1592 		error = uiomove(mtod(m, char *), m->m_len, uio);
1593 		if (__predict_false(error)) {
1594 			SOCK_IO_RECV_UNLOCK(so);
1595 			if (!peek)
1596 				for (; m != last; m = next) {
1597 					next = STAILQ_NEXT(m, m_stailq);
1598 					m_free(m);
1599 				}
1600 			return (error);
1601 		}
1602 		if (!peek)
1603 			m_free(m);
1604 	}
1605 	if (last != NULL && lastlen > 0) {
1606 		if (!peek) {
1607 			MPASS(!(m->m_flags & M_PKTHDR));
1608 			MPASS(last->m_data - M_START(last) >= lastlen);
1609 			error = uiomove(mtod(last, char *) - lastlen,
1610 			    lastlen, uio);
1611 		} else
1612 			error = uiomove(mtod(last, char *), lastlen, uio);
1613 		if (__predict_false(error)) {
1614 			SOCK_IO_RECV_UNLOCK(so);
1615 			return (error);
1616 		}
1617 	}
1618 	if (waitall && !(flags & MSG_EOR) && uio->uio_resid > 0)
1619 		goto restart;
1620 	SOCK_IO_RECV_UNLOCK(so);
1621 
1622 	if (flagsp != NULL)
1623 		*flagsp |= flags;
1624 
1625 	uio->uio_td->td_ru.ru_msgrcv++;
1626 
1627 	return (0);
1628 }
1629 
1630 static int
1631 uipc_sopoll_stream_or_seqpacket(struct socket *so, int events,
1632     struct thread *td)
1633 {
1634 	struct unpcb *unp = sotounpcb(so);
1635 	int revents;
1636 
1637 	UNP_PCB_LOCK(unp);
1638 	if (SOLISTENING(so)) {
1639 		/* The above check is safe, since conversion to listening uses
1640 		 * both protocol and socket lock.
1641 		 */
1642 		SOCK_LOCK(so);
1643 		if (!(events & (POLLIN | POLLRDNORM)))
1644 			revents = 0;
1645 		else if (!TAILQ_EMPTY(&so->sol_comp))
1646 			revents = events & (POLLIN | POLLRDNORM);
1647 		else if (so->so_error)
1648 			revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP;
1649 		else {
1650 			selrecord(td, &so->so_rdsel);
1651 			revents = 0;
1652 		}
1653 		SOCK_UNLOCK(so);
1654 	} else {
1655 		if (so->so_state & SS_ISDISCONNECTED)
1656 			revents = POLLHUP;
1657 		else
1658 			revents = 0;
1659 		if (events & (POLLIN | POLLRDNORM | POLLRDHUP)) {
1660 			SOCK_RECVBUF_LOCK(so);
1661 			if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat ||
1662 			    so->so_error || so->so_rerror)
1663 				revents |= events & (POLLIN | POLLRDNORM);
1664 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
1665 				revents |= events & POLLRDHUP;
1666 			if (!(revents & (POLLIN | POLLRDNORM | POLLRDHUP))) {
1667 				selrecord(td, &so->so_rdsel);
1668 				so->so_rcv.sb_flags |= SB_SEL;
1669 			}
1670 			SOCK_RECVBUF_UNLOCK(so);
1671 		}
1672 		if (events & (POLLOUT | POLLWRNORM)) {
1673 			struct socket *so2 = so->so_rcv.uxst_peer;
1674 
1675 			if (so2 != NULL) {
1676 				struct sockbuf *sb = &so2->so_rcv;
1677 
1678 				SOCK_RECVBUF_LOCK(so2);
1679 				if (uipc_stream_sbspace(sb) >= sb->sb_lowat)
1680 					revents |= events &
1681 					    (POLLOUT | POLLWRNORM);
1682 				if (sb->sb_state & SBS_CANTRCVMORE)
1683 					revents |= POLLHUP;
1684 				if (!(revents & (POLLOUT | POLLWRNORM))) {
1685 					so2->so_rcv.uxst_flags |= UXST_PEER_SEL;
1686 					selrecord(td, &so->so_wrsel);
1687 				}
1688 				SOCK_RECVBUF_UNLOCK(so2);
1689 			} else
1690 				selrecord(td, &so->so_wrsel);
1691 		}
1692 	}
1693 	UNP_PCB_UNLOCK(unp);
1694 	return (revents);
1695 }
1696 
1697 static void
1698 uipc_wrknl_lock(void *arg)
1699 {
1700 	struct socket *so = arg;
1701 	struct unpcb *unp = sotounpcb(so);
1702 
1703 retry:
1704 	if (SOLISTENING(so)) {
1705 		SOLISTEN_LOCK(so);
1706 	} else {
1707 		UNP_PCB_LOCK(unp);
1708 		if (__predict_false(SOLISTENING(so))) {
1709 			UNP_PCB_UNLOCK(unp);
1710 			goto retry;
1711 		}
1712 		if (so->so_rcv.uxst_peer != NULL)
1713 			SOCK_RECVBUF_LOCK(so->so_rcv.uxst_peer);
1714 	}
1715 }
1716 
1717 static void
1718 uipc_wrknl_unlock(void *arg)
1719 {
1720 	struct socket *so = arg;
1721 	struct unpcb *unp = sotounpcb(so);
1722 
1723 	if (SOLISTENING(so))
1724 		SOLISTEN_UNLOCK(so);
1725 	else {
1726 		if (so->so_rcv.uxst_peer != NULL)
1727 			SOCK_RECVBUF_UNLOCK(so->so_rcv.uxst_peer);
1728 		UNP_PCB_UNLOCK(unp);
1729 	}
1730 }
1731 
1732 static void
1733 uipc_wrknl_assert_lock(void *arg, int what)
1734 {
1735 	struct socket *so = arg;
1736 
1737 	if (SOLISTENING(so)) {
1738 		if (what == LA_LOCKED)
1739 			SOLISTEN_LOCK_ASSERT(so);
1740 		else
1741 			SOLISTEN_UNLOCK_ASSERT(so);
1742 	} else {
1743 		/*
1744 		 * The pr_soreceive method will put a note without owning the
1745 		 * unp lock, so we can't assert it here.  But we can safely
1746 		 * dereference uxst_peer pointer, since receive buffer lock
1747 		 * is assumed to be held here.
1748 		 */
1749 		if (what == LA_LOCKED && so->so_rcv.uxst_peer != NULL)
1750 			SOCK_RECVBUF_LOCK_ASSERT(so->so_rcv.uxst_peer);
1751 	}
1752 }
1753 
1754 static void
1755 uipc_filt_sowdetach(struct knote *kn)
1756 {
1757 	struct socket *so = kn->kn_fp->f_data;
1758 
1759 	uipc_wrknl_lock(so);
1760 	knlist_remove(&so->so_wrsel.si_note, kn, 1);
1761 	uipc_wrknl_unlock(so);
1762 }
1763 
1764 static int
1765 uipc_filt_sowrite(struct knote *kn, long hint)
1766 {
1767 	struct socket *so = kn->kn_fp->f_data, *so2;
1768 	struct unpcb *unp = sotounpcb(so), *unp2 = unp->unp_conn;
1769 
1770 	if (SOLISTENING(so) || unp2 == NULL)
1771 		return (0);
1772 
1773 	so2 = unp2->unp_socket;
1774 	SOCK_RECVBUF_LOCK_ASSERT(so2);
1775 	kn->kn_data = uipc_stream_sbspace(&so2->so_rcv);
1776 
1777 	if (so2->so_rcv.sb_state & SBS_CANTRCVMORE) {
1778 		kn->kn_flags |= EV_EOF;
1779 		kn->kn_fflags = so->so_error;
1780 		return (1);
1781 	} else if (kn->kn_sfflags & NOTE_LOWAT)
1782 		return (kn->kn_data >= kn->kn_sdata);
1783 	else
1784 		return (kn->kn_data >= so2->so_rcv.sb_lowat);
1785 }
1786 
1787 static int
1788 uipc_filt_soempty(struct knote *kn, long hint)
1789 {
1790 	struct socket *so = kn->kn_fp->f_data, *so2;
1791 	struct unpcb *unp = sotounpcb(so), *unp2 = unp->unp_conn;
1792 
1793 	if (SOLISTENING(so) || unp2 == NULL)
1794 		return (1);
1795 
1796 	so2 = unp2->unp_socket;
1797 	SOCK_RECVBUF_LOCK_ASSERT(so2);
1798 	kn->kn_data = uipc_stream_sbspace(&so2->so_rcv);
1799 
1800 	return (kn->kn_data == 0 ? 1 : 0);
1801 }
1802 
1803 static const struct filterops uipc_write_filtops = {
1804 	.f_isfd = 1,
1805 	.f_detach = uipc_filt_sowdetach,
1806 	.f_event = uipc_filt_sowrite,
1807 };
1808 static const struct filterops uipc_empty_filtops = {
1809 	.f_isfd = 1,
1810 	.f_detach = uipc_filt_sowdetach,
1811 	.f_event = uipc_filt_soempty,
1812 };
1813 
1814 static int
1815 uipc_kqfilter_stream_or_seqpacket(struct socket *so, struct knote *kn)
1816 {
1817 	struct unpcb *unp = sotounpcb(so);
1818 	struct knlist *knl;
1819 
1820 	switch (kn->kn_filter) {
1821 	case EVFILT_READ:
1822 		return (sokqfilter_generic(so, kn));
1823 	case EVFILT_WRITE:
1824 		kn->kn_fop = &uipc_write_filtops;
1825 		break;
1826 	case EVFILT_EMPTY:
1827 		kn->kn_fop = &uipc_empty_filtops;
1828 		break;
1829 	default:
1830 		return (EINVAL);
1831 	}
1832 
1833 	knl = &so->so_wrsel.si_note;
1834 	UNP_PCB_LOCK(unp);
1835 	if (SOLISTENING(so)) {
1836 		SOLISTEN_LOCK(so);
1837 		knlist_add(knl, kn, 1);
1838 		SOLISTEN_UNLOCK(so);
1839 	} else {
1840 		struct socket *so2 = so->so_rcv.uxst_peer;
1841 
1842 		if (so2 != NULL)
1843 			SOCK_RECVBUF_LOCK(so2);
1844 		knlist_add(knl, kn, 1);
1845 		if (so2 != NULL)
1846 			SOCK_RECVBUF_UNLOCK(so2);
1847 	}
1848 	UNP_PCB_UNLOCK(unp);
1849 	return (0);
1850 }
1851 
1852 /* PF_UNIX/SOCK_DGRAM version of sbspace() */
1853 static inline bool
1854 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt)
1855 {
1856 	u_int bleft, mleft;
1857 
1858 	/*
1859 	 * Negative space may happen if send(2) is followed by
1860 	 * setsockopt(SO_SNDBUF/SO_RCVBUF) that shrinks maximum.
1861 	 */
1862 	if (__predict_false(sb->sb_hiwat < sb->uxdg_cc ||
1863 	    sb->sb_mbmax < sb->uxdg_mbcnt))
1864 		return (false);
1865 
1866 	if (__predict_false(sb->sb_state & SBS_CANTRCVMORE))
1867 		return (false);
1868 
1869 	bleft = sb->sb_hiwat - sb->uxdg_cc;
1870 	mleft = sb->sb_mbmax - sb->uxdg_mbcnt;
1871 
1872 	return (bleft >= cc && mleft >= mbcnt);
1873 }
1874 
1875 /*
1876  * PF_UNIX/SOCK_DGRAM send
1877  *
1878  * Allocate a record consisting of 3 mbufs in the sequence of
1879  * from -> control -> data and append it to the socket buffer.
1880  *
1881  * The first mbuf carries sender's name and is a pkthdr that stores
1882  * overall length of datagram, its memory consumption and control length.
1883  */
1884 #define	ctllen	PH_loc.thirtytwo[1]
1885 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <=
1886     offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen");
1887 static int
1888 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1889     struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
1890 {
1891 	struct unpcb *unp, *unp2;
1892 	const struct sockaddr *from;
1893 	struct socket *so2;
1894 	struct sockbuf *sb;
1895 	struct mchain cmc = MCHAIN_INITIALIZER(&cmc);
1896 	struct mbuf *f;
1897 	u_int cc, ctl, mbcnt;
1898 	u_int dcc __diagused, dctl __diagused, dmbcnt __diagused;
1899 	int error;
1900 
1901 	MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
1902 
1903 	error = 0;
1904 	f = NULL;
1905 
1906 	if (__predict_false(flags & MSG_OOB)) {
1907 		error = EOPNOTSUPP;
1908 		goto out;
1909 	}
1910 	if (m == NULL) {
1911 		if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
1912 			error = EMSGSIZE;
1913 			goto out;
1914 		}
1915 		m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
1916 		if (__predict_false(m == NULL)) {
1917 			error = EFAULT;
1918 			goto out;
1919 		}
1920 		f = m_gethdr(M_WAITOK, MT_SONAME);
1921 		cc = m->m_pkthdr.len;
1922 		mbcnt = MSIZE + m->m_pkthdr.memlen;
1923 		if (c != NULL && (error = unp_internalize(c, &cmc, td)))
1924 			goto out;
1925 	} else {
1926 		struct mchain mc;
1927 
1928 		uipc_reset_kernel_mbuf(m, &mc);
1929 		cc = mc.mc_len;
1930 		mbcnt = mc.mc_mlen;
1931 		if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
1932 			error = EMSGSIZE;
1933 			goto out;
1934 		}
1935 		if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) {
1936 			error = ENOBUFS;
1937 			goto out;
1938 		}
1939 	}
1940 
1941 	unp = sotounpcb(so);
1942 	MPASS(unp);
1943 
1944 	/*
1945 	 * XXXGL: would be cool to fully remove so_snd out of the equation
1946 	 * and avoid this lock, which is not only extraneous, but also being
1947 	 * released, thus still leaving possibility for a race.  We can easily
1948 	 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
1949 	 * is more difficult to invent something to handle so_error.
1950 	 */
1951 	error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1952 	if (error)
1953 		goto out2;
1954 	SOCK_SENDBUF_LOCK(so);
1955 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1956 		SOCK_SENDBUF_UNLOCK(so);
1957 		error = EPIPE;
1958 		goto out3;
1959 	}
1960 	if (so->so_error != 0) {
1961 		error = so->so_error;
1962 		so->so_error = 0;
1963 		SOCK_SENDBUF_UNLOCK(so);
1964 		goto out3;
1965 	}
1966 	if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
1967 		SOCK_SENDBUF_UNLOCK(so);
1968 		error = EDESTADDRREQ;
1969 		goto out3;
1970 	}
1971 	SOCK_SENDBUF_UNLOCK(so);
1972 
1973 	if (addr != NULL) {
1974 		if ((error = unp_connectat(AT_FDCWD, so, addr, td, true)))
1975 			goto out3;
1976 		UNP_PCB_LOCK_ASSERT(unp);
1977 		unp2 = unp->unp_conn;
1978 		UNP_PCB_LOCK_ASSERT(unp2);
1979 	} else {
1980 		UNP_PCB_LOCK(unp);
1981 		unp2 = unp_pcb_lock_peer(unp);
1982 		if (unp2 == NULL) {
1983 			UNP_PCB_UNLOCK(unp);
1984 			error = ENOTCONN;
1985 			goto out3;
1986 		}
1987 	}
1988 
1989 	if (unp2->unp_flags & UNP_WANTCRED_MASK)
1990 		unp_addsockcred(td, &cmc, unp2->unp_flags);
1991 	if (unp->unp_addr != NULL)
1992 		from = (struct sockaddr *)unp->unp_addr;
1993 	else
1994 		from = &sun_noname;
1995 	f->m_len = from->sa_len;
1996 	MPASS(from->sa_len <= MLEN);
1997 	bcopy(from, mtod(f, void *), from->sa_len);
1998 
1999 	/*
2000 	 * Concatenate mbufs: from -> control -> data.
2001 	 * Save overall cc and mbcnt in "from" mbuf.
2002 	 */
2003 	if (!STAILQ_EMPTY(&cmc.mc_q)) {
2004 		f->m_next = mc_first(&cmc);
2005 		mc_last(&cmc)->m_next = m;
2006 		/* XXXGL: This is dirty as well as rollback after ENOBUFS. */
2007 		STAILQ_INIT(&cmc.mc_q);
2008 	} else
2009 		f->m_next = m;
2010 	m = NULL;
2011 	ctl = f->m_len + cmc.mc_len;
2012 	mbcnt += cmc.mc_mlen;
2013 #ifdef INVARIANTS
2014 	dcc = dctl = dmbcnt = 0;
2015 	for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) {
2016 		if (mb->m_type == MT_DATA)
2017 			dcc += mb->m_len;
2018 		else
2019 			dctl += mb->m_len;
2020 		dmbcnt += MSIZE;
2021 		if (mb->m_flags & M_EXT)
2022 			dmbcnt += mb->m_ext.ext_size;
2023 	}
2024 	MPASS(dcc == cc);
2025 	MPASS(dctl == ctl);
2026 	MPASS(dmbcnt == mbcnt);
2027 #endif
2028 	f->m_pkthdr.len = cc + ctl;
2029 	f->m_pkthdr.memlen = mbcnt;
2030 	f->m_pkthdr.ctllen = ctl;
2031 
2032 	/*
2033 	 * Destination socket buffer selection.
2034 	 *
2035 	 * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the
2036 	 * destination address is supplied, create a temporary connection for
2037 	 * the run time of the function (see call to unp_connectat() above and
2038 	 * to unp_disconnect() below).  We distinguish them by condition of
2039 	 * (addr != NULL).  We intentionally avoid adding 'bool connected' for
2040 	 * that condition, since, again, through the run time of this code we
2041 	 * are always connected.  For such "unconnected" sends, the destination
2042 	 * buffer would be the receive buffer of destination socket so2.
2043 	 *
2044 	 * For connected sends, data lands on the send buffer of the sender's
2045 	 * socket "so".  Then, if we just added the very first datagram
2046 	 * on this send buffer, we need to add the send buffer on to the
2047 	 * receiving socket's buffer list.  We put ourselves on top of the
2048 	 * list.  Such logic gives infrequent senders priority over frequent
2049 	 * senders.
2050 	 *
2051 	 * Note on byte count management. As long as event methods kevent(2),
2052 	 * select(2) are not protocol specific (yet), we need to maintain
2053 	 * meaningful values on the receive buffer.  So, the receive buffer
2054 	 * would accumulate counters from all connected buffers potentially
2055 	 * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax.
2056 	 */
2057 	so2 = unp2->unp_socket;
2058 	sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv;
2059 	SOCK_RECVBUF_LOCK(so2);
2060 	if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) {
2061 		if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb))
2062 			TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd,
2063 			    uxdg_clist);
2064 		STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
2065 		sb->uxdg_cc += cc + ctl;
2066 		sb->uxdg_ctl += ctl;
2067 		sb->uxdg_mbcnt += mbcnt;
2068 		so2->so_rcv.sb_acc += cc + ctl;
2069 		so2->so_rcv.sb_ccc += cc + ctl;
2070 		so2->so_rcv.sb_ctl += ctl;
2071 		so2->so_rcv.sb_mbcnt += mbcnt;
2072 		sorwakeup_locked(so2);
2073 		f = NULL;
2074 	} else {
2075 		soroverflow_locked(so2);
2076 		error = ENOBUFS;
2077 		if (f->m_next->m_type == MT_CONTROL) {
2078 			STAILQ_FIRST(&cmc.mc_q) = f->m_next;
2079 			f->m_next = NULL;
2080 		}
2081 	}
2082 
2083 	if (addr != NULL)
2084 		unp_disconnect(unp, unp2);
2085 	else
2086 		unp_pcb_unlock_pair(unp, unp2);
2087 
2088 	td->td_ru.ru_msgsnd++;
2089 
2090 out3:
2091 	SOCK_IO_SEND_UNLOCK(so);
2092 out2:
2093 	if (!mc_empty(&cmc))
2094 		unp_scan(mc_first(&cmc), unp_freerights);
2095 out:
2096 	if (f)
2097 		m_freem(f);
2098 	mc_freem(&cmc);
2099 	if (m)
2100 		m_freem(m);
2101 
2102 	return (error);
2103 }
2104 
2105 /*
2106  * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK.
2107  * The mbuf has already been unlinked from the uxdg_mb of socket buffer
2108  * and needs to be linked onto uxdg_peeked of receive socket buffer.
2109  */
2110 static int
2111 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa,
2112     struct uio *uio, struct mbuf **controlp, int *flagsp)
2113 {
2114 	ssize_t len = 0;
2115 	int error;
2116 
2117 	so->so_rcv.uxdg_peeked = m;
2118 	so->so_rcv.uxdg_cc += m->m_pkthdr.len;
2119 	so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen;
2120 	so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen;
2121 	SOCK_RECVBUF_UNLOCK(so);
2122 
2123 	KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
2124 	if (psa != NULL)
2125 		*psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
2126 
2127 	m = m->m_next;
2128 	KASSERT(m, ("%s: no data or control after soname", __func__));
2129 
2130 	/*
2131 	 * With MSG_PEEK the control isn't executed, just copied.
2132 	 */
2133 	while (m != NULL && m->m_type == MT_CONTROL) {
2134 		if (controlp != NULL) {
2135 			*controlp = m_copym(m, 0, m->m_len, M_WAITOK);
2136 			controlp = &(*controlp)->m_next;
2137 		}
2138 		m = m->m_next;
2139 	}
2140 	KASSERT(m == NULL || m->m_type == MT_DATA,
2141 	    ("%s: not MT_DATA mbuf %p", __func__, m));
2142 	while (m != NULL && uio->uio_resid > 0) {
2143 		len = uio->uio_resid;
2144 		if (len > m->m_len)
2145 			len = m->m_len;
2146 		error = uiomove(mtod(m, char *), (int)len, uio);
2147 		if (error) {
2148 			SOCK_IO_RECV_UNLOCK(so);
2149 			return (error);
2150 		}
2151 		if (len == m->m_len)
2152 			m = m->m_next;
2153 	}
2154 	SOCK_IO_RECV_UNLOCK(so);
2155 
2156 	if (flagsp != NULL) {
2157 		if (m != NULL) {
2158 			if (*flagsp & MSG_TRUNC) {
2159 				/* Report real length of the packet */
2160 				uio->uio_resid -= m_length(m, NULL) - len;
2161 			}
2162 			*flagsp |= MSG_TRUNC;
2163 		} else
2164 			*flagsp &= ~MSG_TRUNC;
2165 	}
2166 
2167 	return (0);
2168 }
2169 
2170 /*
2171  * PF_UNIX/SOCK_DGRAM receive
2172  */
2173 static int
2174 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2175     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2176 {
2177 	struct sockbuf *sb = NULL;
2178 	struct mbuf *m;
2179 	int flags, error;
2180 	ssize_t len = 0;
2181 	bool nonblock;
2182 
2183 	MPASS(mp0 == NULL);
2184 
2185 	if (psa != NULL)
2186 		*psa = NULL;
2187 	if (controlp != NULL)
2188 		*controlp = NULL;
2189 
2190 	flags = flagsp != NULL ? *flagsp : 0;
2191 	nonblock = (so->so_state & SS_NBIO) ||
2192 	    (flags & (MSG_DONTWAIT | MSG_NBIO));
2193 
2194 	error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
2195 	if (__predict_false(error))
2196 		return (error);
2197 
2198 	/*
2199 	 * Loop blocking while waiting for a datagram.  Prioritize connected
2200 	 * peers over unconnected sends.  Set sb to selected socket buffer
2201 	 * containing an mbuf on exit from the wait loop.  A datagram that
2202 	 * had already been peeked at has top priority.
2203 	 */
2204 	SOCK_RECVBUF_LOCK(so);
2205 	while ((m = so->so_rcv.uxdg_peeked) == NULL &&
2206 	    (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL &&
2207 	    (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
2208 		if (so->so_error) {
2209 			error = so->so_error;
2210 			if (!(flags & MSG_PEEK))
2211 				so->so_error = 0;
2212 			SOCK_RECVBUF_UNLOCK(so);
2213 			SOCK_IO_RECV_UNLOCK(so);
2214 			return (error);
2215 		}
2216 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2217 		    uio->uio_resid == 0) {
2218 			SOCK_RECVBUF_UNLOCK(so);
2219 			SOCK_IO_RECV_UNLOCK(so);
2220 			return (0);
2221 		}
2222 		if (nonblock) {
2223 			SOCK_RECVBUF_UNLOCK(so);
2224 			SOCK_IO_RECV_UNLOCK(so);
2225 			return (EWOULDBLOCK);
2226 		}
2227 		error = sbwait(so, SO_RCV);
2228 		if (error) {
2229 			SOCK_RECVBUF_UNLOCK(so);
2230 			SOCK_IO_RECV_UNLOCK(so);
2231 			return (error);
2232 		}
2233 	}
2234 
2235 	if (sb == NULL)
2236 		sb = &so->so_rcv;
2237 	else if (m == NULL)
2238 		m = STAILQ_FIRST(&sb->uxdg_mb);
2239 	else
2240 		MPASS(m == so->so_rcv.uxdg_peeked);
2241 
2242 	MPASS(sb->uxdg_cc > 0);
2243 	M_ASSERTPKTHDR(m);
2244 	KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
2245 
2246 	if (uio->uio_td)
2247 		uio->uio_td->td_ru.ru_msgrcv++;
2248 
2249 	if (__predict_true(m != so->so_rcv.uxdg_peeked)) {
2250 		STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt);
2251 		if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv)
2252 			TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
2253 	} else
2254 		so->so_rcv.uxdg_peeked = NULL;
2255 
2256 	sb->uxdg_cc -= m->m_pkthdr.len;
2257 	sb->uxdg_ctl -= m->m_pkthdr.ctllen;
2258 	sb->uxdg_mbcnt -= m->m_pkthdr.memlen;
2259 
2260 	if (__predict_false(flags & MSG_PEEK))
2261 		return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp));
2262 
2263 	so->so_rcv.sb_acc -= m->m_pkthdr.len;
2264 	so->so_rcv.sb_ccc -= m->m_pkthdr.len;
2265 	so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen;
2266 	so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen;
2267 	SOCK_RECVBUF_UNLOCK(so);
2268 
2269 	if (psa != NULL)
2270 		*psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
2271 	m = m_free(m);
2272 	KASSERT(m, ("%s: no data or control after soname", __func__));
2273 
2274 	/*
2275 	 * Packet to copyout() is now in 'm' and it is disconnected from the
2276 	 * queue.
2277 	 *
2278 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
2279 	 * in the first mbuf chain on the socket buffer.  We call into the
2280 	 * unp_externalize() to perform externalization (or freeing if
2281 	 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
2282 	 * without MT_DATA mbufs.
2283 	 */
2284 	while (m != NULL && m->m_type == MT_CONTROL) {
2285 		struct mbuf *cm;
2286 
2287 		/* XXXGL: unp_externalize() is also dom_externalize() KBI and
2288 		 * it frees whole chain, so we must disconnect the mbuf.
2289 		 */
2290 		cm = m; m = m->m_next; cm->m_next = NULL;
2291 		error = unp_externalize(cm, controlp, flags);
2292 		if (error != 0) {
2293 			SOCK_IO_RECV_UNLOCK(so);
2294 			unp_scan(m, unp_freerights);
2295 			m_freem(m);
2296 			return (error);
2297 		}
2298 		if (controlp != NULL) {
2299 			while (*controlp != NULL)
2300 				controlp = &(*controlp)->m_next;
2301 		}
2302 	}
2303 	KASSERT(m == NULL || m->m_type == MT_DATA,
2304 	    ("%s: not MT_DATA mbuf %p", __func__, m));
2305 	while (m != NULL && uio->uio_resid > 0) {
2306 		len = uio->uio_resid;
2307 		if (len > m->m_len)
2308 			len = m->m_len;
2309 		error = uiomove(mtod(m, char *), (int)len, uio);
2310 		if (error) {
2311 			SOCK_IO_RECV_UNLOCK(so);
2312 			m_freem(m);
2313 			return (error);
2314 		}
2315 		if (len == m->m_len)
2316 			m = m_free(m);
2317 		else {
2318 			m->m_data += len;
2319 			m->m_len -= len;
2320 		}
2321 	}
2322 	SOCK_IO_RECV_UNLOCK(so);
2323 
2324 	if (m != NULL) {
2325 		if (flagsp != NULL) {
2326 			if (flags & MSG_TRUNC) {
2327 				/* Report real length of the packet */
2328 				uio->uio_resid -= m_length(m, NULL);
2329 			}
2330 			*flagsp |= MSG_TRUNC;
2331 		}
2332 		m_freem(m);
2333 	} else if (flagsp != NULL)
2334 		*flagsp &= ~MSG_TRUNC;
2335 
2336 	return (0);
2337 }
2338 
2339 static int
2340 uipc_sendfile_wait(struct socket *so, off_t need, int *space)
2341 {
2342 	struct unpcb *unp2;
2343 	struct socket *so2;
2344 	struct sockbuf *sb;
2345 	bool nonblock, sockref;
2346 	int error;
2347 
2348 	MPASS(so->so_type == SOCK_STREAM);
2349 	MPASS(need > 0);
2350 	MPASS(space != NULL);
2351 
2352 	nonblock = so->so_state & SS_NBIO;
2353 	sockref = false;
2354 
2355 	if (__predict_false((so->so_state & SS_ISCONNECTED) == 0))
2356 		return (ENOTCONN);
2357 
2358 	if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0))
2359 		return (error);
2360 
2361 	so2 = unp2->unp_socket;
2362 	sb = &so2->so_rcv;
2363 	SOCK_RECVBUF_LOCK(so2);
2364 	UNP_PCB_UNLOCK(unp2);
2365 	while ((*space = uipc_stream_sbspace(sb)) < need &&
2366 	    (*space < so->so_snd.sb_hiwat / 2)) {
2367 		UIPC_STREAM_SBCHECK(sb);
2368 		if (nonblock) {
2369 			SOCK_RECVBUF_UNLOCK(so2);
2370 			return (EAGAIN);
2371 		}
2372 		if (!sockref)
2373 			soref(so2);
2374 		error = sbwait(so2, SO_RCV);
2375 		if (error == 0 &&
2376 		    __predict_false(sb->sb_state & SBS_CANTRCVMORE))
2377 			error = EPIPE;
2378 		if (error) {
2379 			SOCK_RECVBUF_UNLOCK(so2);
2380 			sorele(so2);
2381 			return (error);
2382 		}
2383 	}
2384 	UIPC_STREAM_SBCHECK(sb);
2385 	SOCK_RECVBUF_UNLOCK(so2);
2386 	if (sockref)
2387 		sorele(so2);
2388 
2389 	return (0);
2390 }
2391 
2392 /*
2393  * Although this is a pr_send method, for unix(4) it is called only via
2394  * sendfile(2) path.  This means we can be sure that mbufs are clear of
2395  * any extra flags and don't require any conditioning.
2396  */
2397 static int
2398 uipc_sendfile(struct socket *so, int flags, struct mbuf *m,
2399     struct sockaddr *from, struct mbuf *control, struct thread *td)
2400 {
2401 	struct mchain mc;
2402 	struct unpcb *unp2;
2403 	struct socket *so2;
2404 	struct sockbuf *sb;
2405 	bool notready, wakeup;
2406 	int error;
2407 
2408 	MPASS(so->so_type == SOCK_STREAM);
2409 	MPASS(from == NULL && control == NULL);
2410 	KASSERT(!(m->m_flags & M_EXTPG),
2411 	    ("unix(4): TLS sendfile(2) not supported"));
2412 
2413 	notready = flags & PRUS_NOTREADY;
2414 
2415 	if (__predict_false((so->so_state & SS_ISCONNECTED) == 0)) {
2416 		error = ENOTCONN;
2417 		goto out;
2418 	}
2419 
2420 	if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0))
2421 		goto out;
2422 
2423 	mc_init_m(&mc, m);
2424 
2425 	so2 = unp2->unp_socket;
2426 	sb = &so2->so_rcv;
2427 	SOCK_RECVBUF_LOCK(so2);
2428 	UNP_PCB_UNLOCK(unp2);
2429 	UIPC_STREAM_SBCHECK(sb);
2430 	sb->sb_ccc += mc.mc_len;
2431 	sb->sb_mbcnt += mc.mc_mlen;
2432 	if (sb->uxst_fnrdy == NULL) {
2433 		if (notready) {
2434 			sb->uxst_fnrdy = STAILQ_FIRST(&mc.mc_q);
2435 			wakeup = false;
2436 		} else {
2437 			sb->sb_acc += mc.mc_len;
2438 			wakeup = true;
2439 		}
2440 	} else {
2441 		STAILQ_FOREACH(m, &mc.mc_q, m_stailq)
2442 			m->m_flags |= M_BLOCKED;
2443 		wakeup = false;
2444 	}
2445 	STAILQ_CONCAT(&sb->uxst_mbq, &mc.mc_q);
2446 	UIPC_STREAM_SBCHECK(sb);
2447 	if (wakeup)
2448 		sorwakeup_locked(so2);
2449 	else
2450 		SOCK_RECVBUF_UNLOCK(so2);
2451 
2452 	return (0);
2453 out:
2454 	/*
2455 	 * In case of not ready data, uipc_ready() is responsible
2456 	 * for freeing memory.
2457 	 */
2458 	if (m != NULL && !notready)
2459 		m_freem(m);
2460 
2461 	return (error);
2462 }
2463 
2464 static int
2465 uipc_sbready(struct sockbuf *sb, struct mbuf *m, int count)
2466 {
2467 	u_int blocker;
2468 
2469 	/* assert locked */
2470 
2471 	blocker = (sb->uxst_fnrdy == m) ? M_BLOCKED : 0;
2472 	STAILQ_FOREACH_FROM(m, &sb->uxst_mbq, m_stailq) {
2473 		if (count > 0) {
2474 			MPASS(m->m_flags & M_NOTREADY);
2475 			m->m_flags &= ~(M_NOTREADY | blocker);
2476 			if (blocker)
2477 				sb->sb_acc += m->m_len;
2478 			count--;
2479 		} else if (blocker && !(m->m_flags & M_NOTREADY)) {
2480 			MPASS(m->m_flags & M_BLOCKED);
2481 			m->m_flags &= ~M_BLOCKED;
2482 			sb->sb_acc += m->m_len;
2483 		} else
2484 			break;
2485 	}
2486 	if (blocker) {
2487 		sb->uxst_fnrdy = m;
2488 		return (0);
2489 	} else
2490 		return (EINPROGRESS);
2491 }
2492 
2493 static bool
2494 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
2495 {
2496 	struct mbuf *mb;
2497 	struct sockbuf *sb;
2498 
2499 	SOCK_LOCK(so);
2500 	if (SOLISTENING(so)) {
2501 		SOCK_UNLOCK(so);
2502 		return (false);
2503 	}
2504 	mb = NULL;
2505 	sb = &so->so_rcv;
2506 	SOCK_RECVBUF_LOCK(so);
2507 	if (sb->uxst_fnrdy != NULL) {
2508 		STAILQ_FOREACH(mb, &sb->uxst_mbq, m_stailq) {
2509 			if (mb == m) {
2510 				*errorp = uipc_sbready(sb, m, count);
2511 				break;
2512 			}
2513 		}
2514 	}
2515 	SOCK_RECVBUF_UNLOCK(so);
2516 	SOCK_UNLOCK(so);
2517 	return (mb != NULL);
2518 }
2519 
2520 static int
2521 uipc_ready(struct socket *so, struct mbuf *m, int count)
2522 {
2523 	struct unpcb *unp, *unp2;
2524 	int error;
2525 
2526 	MPASS(so->so_type == SOCK_STREAM);
2527 
2528 	if (__predict_true(uipc_lock_peer(so, &unp2) == 0)) {
2529 		struct socket *so2;
2530 		struct sockbuf *sb;
2531 
2532 		so2 = unp2->unp_socket;
2533 		sb = &so2->so_rcv;
2534 		SOCK_RECVBUF_LOCK(so2);
2535 		UNP_PCB_UNLOCK(unp2);
2536 		UIPC_STREAM_SBCHECK(sb);
2537 		error = uipc_sbready(sb, m, count);
2538 		UIPC_STREAM_SBCHECK(sb);
2539 		if (error == 0)
2540 			sorwakeup_locked(so2);
2541 		else
2542 			SOCK_RECVBUF_UNLOCK(so2);
2543 	} else {
2544 		/*
2545 		 * The receiving socket has been disconnected, but may still
2546 		 * be valid.  In this case, the not-ready mbufs are still
2547 		 * present in its socket buffer, so perform an exhaustive
2548 		 * search before giving up and freeing the mbufs.
2549 		 */
2550 		UNP_LINK_RLOCK();
2551 		LIST_FOREACH(unp, &unp_shead, unp_link) {
2552 			if (uipc_ready_scan(unp->unp_socket, m, count, &error))
2553 				break;
2554 		}
2555 		UNP_LINK_RUNLOCK();
2556 
2557 		if (unp == NULL) {
2558 			for (int i = 0; i < count; i++)
2559 				m = m_free(m);
2560 			return (ECONNRESET);
2561 		}
2562 	}
2563 	return (error);
2564 }
2565 
2566 static int
2567 uipc_sense(struct socket *so, struct stat *sb)
2568 {
2569 	struct unpcb *unp;
2570 
2571 	unp = sotounpcb(so);
2572 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
2573 
2574 	sb->st_blksize = so->so_snd.sb_hiwat;
2575 	sb->st_dev = NODEV;
2576 	sb->st_ino = unp->unp_ino;
2577 	return (0);
2578 }
2579 
2580 static int
2581 uipc_shutdown(struct socket *so, enum shutdown_how how)
2582 {
2583 	struct unpcb *unp = sotounpcb(so);
2584 	int error;
2585 
2586 	SOCK_LOCK(so);
2587 	if (SOLISTENING(so)) {
2588 		if (how != SHUT_WR) {
2589 			so->so_error = ECONNABORTED;
2590 			solisten_wakeup(so);    /* unlocks so */
2591 		} else
2592 			SOCK_UNLOCK(so);
2593 		return (ENOTCONN);
2594 	} else if ((so->so_state &
2595 	    (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
2596 		/*
2597 		 * POSIX mandates us to just return ENOTCONN when shutdown(2) is
2598 		 * invoked on a datagram sockets, however historically we would
2599 		 * actually tear socket down.  This is known to be leveraged by
2600 		 * some applications to unblock process waiting in recv(2) by
2601 		 * other process that it shares that socket with.  Try to meet
2602 		 * both backward-compatibility and POSIX requirements by forcing
2603 		 * ENOTCONN but still flushing buffers and performing wakeup(9).
2604 		 *
2605 		 * XXXGL: it remains unknown what applications expect this
2606 		 * behavior and is this isolated to unix/dgram or inet/dgram or
2607 		 * both.  See: D10351, D3039.
2608 		 */
2609 		error = ENOTCONN;
2610 		if (so->so_type != SOCK_DGRAM) {
2611 			SOCK_UNLOCK(so);
2612 			return (error);
2613 		}
2614 	} else
2615 		error = 0;
2616 	SOCK_UNLOCK(so);
2617 
2618 	switch (how) {
2619 	case SHUT_RD:
2620 		socantrcvmore(so);
2621 		unp_dispose(so);
2622 		break;
2623 	case SHUT_RDWR:
2624 		socantrcvmore(so);
2625 		unp_dispose(so);
2626 		/* FALLTHROUGH */
2627 	case SHUT_WR:
2628 		UNP_PCB_LOCK(unp);
2629 		socantsendmore(so);
2630 		unp_shutdown(unp);
2631 		UNP_PCB_UNLOCK(unp);
2632 	}
2633 	wakeup(&so->so_timeo);
2634 
2635 	return (error);
2636 }
2637 
2638 static int
2639 uipc_sockaddr(struct socket *so, struct sockaddr *ret)
2640 {
2641 	struct unpcb *unp;
2642 	const struct sockaddr *sa;
2643 
2644 	unp = sotounpcb(so);
2645 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
2646 
2647 	UNP_PCB_LOCK(unp);
2648 	if (unp->unp_addr != NULL)
2649 		sa = (struct sockaddr *) unp->unp_addr;
2650 	else
2651 		sa = &sun_noname;
2652 	bcopy(sa, ret, sa->sa_len);
2653 	UNP_PCB_UNLOCK(unp);
2654 	return (0);
2655 }
2656 
2657 static int
2658 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
2659 {
2660 	struct unpcb *unp;
2661 	struct xucred xu;
2662 	int error, optval;
2663 
2664 	if (sopt->sopt_level != SOL_LOCAL)
2665 		return (EINVAL);
2666 
2667 	unp = sotounpcb(so);
2668 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
2669 	error = 0;
2670 	switch (sopt->sopt_dir) {
2671 	case SOPT_GET:
2672 		switch (sopt->sopt_name) {
2673 		case LOCAL_PEERCRED:
2674 			UNP_PCB_LOCK(unp);
2675 			if (unp->unp_flags & UNP_HAVEPC)
2676 				xu = unp->unp_peercred;
2677 			else {
2678 				if (so->so_proto->pr_flags & PR_CONNREQUIRED)
2679 					error = ENOTCONN;
2680 				else
2681 					error = EINVAL;
2682 			}
2683 			UNP_PCB_UNLOCK(unp);
2684 			if (error == 0)
2685 				error = sooptcopyout(sopt, &xu, sizeof(xu));
2686 			break;
2687 
2688 		case LOCAL_CREDS:
2689 			/* Unlocked read. */
2690 			optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
2691 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2692 			break;
2693 
2694 		case LOCAL_CREDS_PERSISTENT:
2695 			/* Unlocked read. */
2696 			optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
2697 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2698 			break;
2699 
2700 		default:
2701 			error = EOPNOTSUPP;
2702 			break;
2703 		}
2704 		break;
2705 
2706 	case SOPT_SET:
2707 		switch (sopt->sopt_name) {
2708 		case LOCAL_CREDS:
2709 		case LOCAL_CREDS_PERSISTENT:
2710 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2711 					    sizeof(optval));
2712 			if (error)
2713 				break;
2714 
2715 #define	OPTSET(bit, exclusive) do {					\
2716 	UNP_PCB_LOCK(unp);						\
2717 	if (optval) {							\
2718 		if ((unp->unp_flags & (exclusive)) != 0) {		\
2719 			UNP_PCB_UNLOCK(unp);				\
2720 			error = EINVAL;					\
2721 			break;						\
2722 		}							\
2723 		unp->unp_flags |= (bit);				\
2724 	} else								\
2725 		unp->unp_flags &= ~(bit);				\
2726 	UNP_PCB_UNLOCK(unp);						\
2727 } while (0)
2728 
2729 			switch (sopt->sopt_name) {
2730 			case LOCAL_CREDS:
2731 				OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
2732 				break;
2733 
2734 			case LOCAL_CREDS_PERSISTENT:
2735 				OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
2736 				break;
2737 
2738 			default:
2739 				break;
2740 			}
2741 			break;
2742 #undef	OPTSET
2743 		default:
2744 			error = ENOPROTOOPT;
2745 			break;
2746 		}
2747 		break;
2748 
2749 	default:
2750 		error = EOPNOTSUPP;
2751 		break;
2752 	}
2753 	return (error);
2754 }
2755 
2756 static int
2757 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
2758 {
2759 
2760 	return (unp_connectat(AT_FDCWD, so, nam, td, false));
2761 }
2762 
2763 static int
2764 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
2765     struct thread *td, bool return_locked)
2766 {
2767 	struct mtx *vplock;
2768 	struct sockaddr_un *soun;
2769 	struct vnode *vp;
2770 	struct socket *so2;
2771 	struct unpcb *unp, *unp2, *unp3;
2772 	struct nameidata nd;
2773 	char buf[SOCK_MAXADDRLEN];
2774 	struct sockaddr *sa;
2775 	cap_rights_t rights;
2776 	int error, len;
2777 	bool connreq;
2778 
2779 	CURVNET_ASSERT_SET();
2780 
2781 	if (nam->sa_family != AF_UNIX)
2782 		return (EAFNOSUPPORT);
2783 	if (nam->sa_len > sizeof(struct sockaddr_un))
2784 		return (EINVAL);
2785 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
2786 	if (len <= 0)
2787 		return (EINVAL);
2788 	soun = (struct sockaddr_un *)nam;
2789 	bcopy(soun->sun_path, buf, len);
2790 	buf[len] = 0;
2791 
2792 	error = 0;
2793 	unp = sotounpcb(so);
2794 	UNP_PCB_LOCK(unp);
2795 	for (;;) {
2796 		/*
2797 		 * Wait for connection state to stabilize.  If a connection
2798 		 * already exists, give up.  For datagram sockets, which permit
2799 		 * multiple consecutive connect(2) calls, upper layers are
2800 		 * responsible for disconnecting in advance of a subsequent
2801 		 * connect(2), but this is not synchronized with PCB connection
2802 		 * state.
2803 		 *
2804 		 * Also make sure that no threads are currently attempting to
2805 		 * lock the peer socket, to ensure that unp_conn cannot
2806 		 * transition between two valid sockets while locks are dropped.
2807 		 */
2808 		if (SOLISTENING(so))
2809 			error = EOPNOTSUPP;
2810 		else if (unp->unp_conn != NULL)
2811 			error = EISCONN;
2812 		else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
2813 			error = EALREADY;
2814 		}
2815 		if (error != 0) {
2816 			UNP_PCB_UNLOCK(unp);
2817 			return (error);
2818 		}
2819 		if (unp->unp_pairbusy > 0) {
2820 			unp->unp_flags |= UNP_WAITING;
2821 			mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
2822 			continue;
2823 		}
2824 		break;
2825 	}
2826 	unp->unp_flags |= UNP_CONNECTING;
2827 	UNP_PCB_UNLOCK(unp);
2828 
2829 	connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
2830 	if (connreq)
2831 		sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
2832 	else
2833 		sa = NULL;
2834 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
2835 	    UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
2836 	error = namei(&nd);
2837 	if (error)
2838 		vp = NULL;
2839 	else
2840 		vp = nd.ni_vp;
2841 	ASSERT_VOP_LOCKED(vp, "unp_connect");
2842 	if (error)
2843 		goto bad;
2844 	NDFREE_PNBUF(&nd);
2845 
2846 	if (vp->v_type != VSOCK) {
2847 		error = ENOTSOCK;
2848 		goto bad;
2849 	}
2850 #ifdef MAC
2851 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
2852 	if (error)
2853 		goto bad;
2854 #endif
2855 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
2856 	if (error)
2857 		goto bad;
2858 
2859 	unp = sotounpcb(so);
2860 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
2861 
2862 	vplock = mtx_pool_find(unp_vp_mtxpool, vp);
2863 	mtx_lock(vplock);
2864 	VOP_UNP_CONNECT(vp, &unp2);
2865 	if (unp2 == NULL) {
2866 		error = ECONNREFUSED;
2867 		goto bad2;
2868 	}
2869 	so2 = unp2->unp_socket;
2870 	if (so->so_type != so2->so_type) {
2871 		error = EPROTOTYPE;
2872 		goto bad2;
2873 	}
2874 	if (connreq) {
2875 		if (SOLISTENING(so2))
2876 			so2 = solisten_clone(so2);
2877 		else
2878 			so2 = NULL;
2879 		if (so2 == NULL) {
2880 			error = ECONNREFUSED;
2881 			goto bad2;
2882 		}
2883 		if ((error = uipc_attach(so2, 0, NULL)) != 0) {
2884 			sodealloc(so2);
2885 			goto bad2;
2886 		}
2887 		unp3 = sotounpcb(so2);
2888 		unp_pcb_lock_pair(unp2, unp3);
2889 		if (unp2->unp_addr != NULL) {
2890 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
2891 			unp3->unp_addr = (struct sockaddr_un *) sa;
2892 			sa = NULL;
2893 		}
2894 
2895 		unp_copy_peercred(td, unp3, unp, unp2);
2896 
2897 		UNP_PCB_UNLOCK(unp2);
2898 		unp2 = unp3;
2899 
2900 		/*
2901 		 * It is safe to block on the PCB lock here since unp2 is
2902 		 * nascent and cannot be connected to any other sockets.
2903 		 */
2904 		UNP_PCB_LOCK(unp);
2905 #ifdef MAC
2906 		mac_socketpeer_set_from_socket(so, so2);
2907 		mac_socketpeer_set_from_socket(so2, so);
2908 #endif
2909 	} else {
2910 		unp_pcb_lock_pair(unp, unp2);
2911 	}
2912 	KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
2913 	    sotounpcb(so2) == unp2,
2914 	    ("%s: unp2 %p so2 %p", __func__, unp2, so2));
2915 	unp_connect2(so, so2, connreq);
2916 	if (connreq)
2917 		(void)solisten_enqueue(so2, SS_ISCONNECTED);
2918 	KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
2919 	    ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
2920 	unp->unp_flags &= ~UNP_CONNECTING;
2921 	if (!return_locked)
2922 		unp_pcb_unlock_pair(unp, unp2);
2923 bad2:
2924 	mtx_unlock(vplock);
2925 bad:
2926 	if (vp != NULL) {
2927 		/*
2928 		 * If we are returning locked (called via uipc_sosend_dgram()),
2929 		 * we need to be sure that vput() won't sleep.  This is
2930 		 * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock.
2931 		 * SOCK_STREAM/SEQPACKET can't request return_locked (yet).
2932 		 */
2933 		MPASS(!(return_locked && connreq));
2934 		vput(vp);
2935 	}
2936 	free(sa, M_SONAME);
2937 	if (__predict_false(error)) {
2938 		UNP_PCB_LOCK(unp);
2939 		KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
2940 		    ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
2941 		unp->unp_flags &= ~UNP_CONNECTING;
2942 		UNP_PCB_UNLOCK(unp);
2943 	}
2944 	return (error);
2945 }
2946 
2947 /*
2948  * Set socket peer credentials at connection time.
2949  *
2950  * The client's PCB credentials are copied from its process structure.  The
2951  * server's PCB credentials are copied from the socket on which it called
2952  * listen(2).  uipc_listen cached that process's credentials at the time.
2953  */
2954 void
2955 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
2956     struct unpcb *server_unp, struct unpcb *listen_unp)
2957 {
2958 	cru2xt(td, &client_unp->unp_peercred);
2959 	client_unp->unp_flags |= UNP_HAVEPC;
2960 
2961 	memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
2962 	    sizeof(server_unp->unp_peercred));
2963 	server_unp->unp_flags |= UNP_HAVEPC;
2964 	client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
2965 }
2966 
2967 /*
2968  * unix/stream & unix/seqpacket version of soisconnected().
2969  *
2970  * The crucial thing we are doing here is setting up the uxst_peer linkage,
2971  * holding unp and receive buffer locks of the both sockets.  The disconnect
2972  * procedure does the same.  This gives as a safe way to access the peer in the
2973  * send(2) and recv(2) during the socket lifetime.
2974  *
2975  * The less important thing is event notification of the fact that a socket is
2976  * now connected.  It is unusual for a software to put a socket into event
2977  * mechanism before connect(2), but is supposed to be supported.  Note that
2978  * there can not be any sleeping I/O on the socket, yet, only presence in the
2979  * select/poll/kevent.
2980  *
2981  * This function can be called via two call paths:
2982  * 1) socketpair(2) - in this case socket has not been yet reported to userland
2983  *    and just can't have any event notifications mechanisms set up.  The
2984  *    'wakeup' boolean is always false.
2985  * 2) connect(2) of existing socket to a recent clone of a listener:
2986  *   2.1) Socket that connect(2)s will have 'wakeup' true.  An application
2987  *        could have already put it into event mechanism, is it shall be
2988  *        reported as readable and as writable.
2989  *   2.2) Socket that was just cloned with solisten_clone().  Same as 1).
2990  */
2991 static void
2992 unp_soisconnected(struct socket *so, bool wakeup)
2993 {
2994 	struct socket *so2 = sotounpcb(so)->unp_conn->unp_socket;
2995 	struct sockbuf *sb;
2996 
2997 	SOCK_LOCK_ASSERT(so);
2998 	UNP_PCB_LOCK_ASSERT(sotounpcb(so));
2999 	UNP_PCB_LOCK_ASSERT(sotounpcb(so2));
3000 	SOCK_RECVBUF_LOCK_ASSERT(so);
3001 	SOCK_RECVBUF_LOCK_ASSERT(so2);
3002 
3003 	MPASS(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET);
3004 	MPASS((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
3005 	    SS_ISDISCONNECTING)) == 0);
3006 	MPASS(so->so_qstate == SQ_NONE);
3007 
3008 	so->so_state &= ~SS_ISDISCONNECTED;
3009 	so->so_state |= SS_ISCONNECTED;
3010 
3011 	sb = &so2->so_rcv;
3012 	sb->uxst_peer = so;
3013 
3014 	if (wakeup) {
3015 		KNOTE_LOCKED(&sb->sb_sel->si_note, 0);
3016 		sb = &so->so_rcv;
3017 		selwakeuppri(sb->sb_sel, PSOCK);
3018 		SOCK_SENDBUF_LOCK_ASSERT(so);
3019 		sb = &so->so_snd;
3020 		selwakeuppri(sb->sb_sel, PSOCK);
3021 		SOCK_SENDBUF_UNLOCK(so);
3022 	}
3023 }
3024 
3025 static void
3026 unp_connect2(struct socket *so, struct socket *so2, bool wakeup)
3027 {
3028 	struct unpcb *unp;
3029 	struct unpcb *unp2;
3030 
3031 	MPASS(so2->so_type == so->so_type);
3032 	unp = sotounpcb(so);
3033 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
3034 	unp2 = sotounpcb(so2);
3035 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
3036 
3037 	UNP_PCB_LOCK_ASSERT(unp);
3038 	UNP_PCB_LOCK_ASSERT(unp2);
3039 	KASSERT(unp->unp_conn == NULL,
3040 	    ("%s: socket %p is already connected", __func__, unp));
3041 
3042 	unp->unp_conn = unp2;
3043 	unp_pcb_hold(unp2);
3044 	unp_pcb_hold(unp);
3045 	switch (so->so_type) {
3046 	case SOCK_DGRAM:
3047 		UNP_REF_LIST_LOCK();
3048 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
3049 		UNP_REF_LIST_UNLOCK();
3050 		soisconnected(so);
3051 		break;
3052 
3053 	case SOCK_STREAM:
3054 	case SOCK_SEQPACKET:
3055 		KASSERT(unp2->unp_conn == NULL,
3056 		    ("%s: socket %p is already connected", __func__, unp2));
3057 		unp2->unp_conn = unp;
3058 		SOCK_LOCK(so);
3059 		SOCK_LOCK(so2);
3060 		if (wakeup)	/* Avoid LOR with receive buffer lock. */
3061 			SOCK_SENDBUF_LOCK(so);
3062 		SOCK_RECVBUF_LOCK(so);
3063 		SOCK_RECVBUF_LOCK(so2);
3064 		unp_soisconnected(so, wakeup);	/* Will unlock send buffer. */
3065 		unp_soisconnected(so2, false);
3066 		SOCK_RECVBUF_UNLOCK(so);
3067 		SOCK_RECVBUF_UNLOCK(so2);
3068 		SOCK_UNLOCK(so);
3069 		SOCK_UNLOCK(so2);
3070 		break;
3071 
3072 	default:
3073 		panic("unp_connect2");
3074 	}
3075 }
3076 
3077 static void
3078 unp_soisdisconnected(struct socket *so)
3079 {
3080 	SOCK_LOCK_ASSERT(so);
3081 	SOCK_RECVBUF_LOCK_ASSERT(so);
3082 	MPASS(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET);
3083 	MPASS(!SOLISTENING(so));
3084 	MPASS((so->so_state & (SS_ISCONNECTING | SS_ISDISCONNECTING |
3085 	    SS_ISDISCONNECTED)) == 0);
3086 	MPASS(so->so_state & SS_ISCONNECTED);
3087 
3088 	so->so_state |= SS_ISDISCONNECTED;
3089 	so->so_state &= ~SS_ISCONNECTED;
3090 	so->so_rcv.uxst_peer = NULL;
3091 	socantrcvmore_locked(so);
3092 }
3093 
3094 static void
3095 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
3096 {
3097 	struct socket *so, *so2;
3098 	struct mbuf *m = NULL;
3099 #ifdef INVARIANTS
3100 	struct unpcb *unptmp;
3101 #endif
3102 
3103 	UNP_PCB_LOCK_ASSERT(unp);
3104 	UNP_PCB_LOCK_ASSERT(unp2);
3105 	KASSERT(unp->unp_conn == unp2,
3106 	    ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
3107 
3108 	unp->unp_conn = NULL;
3109 	so = unp->unp_socket;
3110 	so2 = unp2->unp_socket;
3111 	switch (unp->unp_socket->so_type) {
3112 	case SOCK_DGRAM:
3113 		/*
3114 		 * Remove our send socket buffer from the peer's receive buffer.
3115 		 * Move the data to the receive buffer only if it is empty.
3116 		 * This is a protection against a scenario where a peer
3117 		 * connects, floods and disconnects, effectively blocking
3118 		 * sendto() from unconnected sockets.
3119 		 */
3120 		SOCK_RECVBUF_LOCK(so2);
3121 		if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) {
3122 			TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd,
3123 			    uxdg_clist);
3124 			if (__predict_true((so2->so_rcv.sb_state &
3125 			    SBS_CANTRCVMORE) == 0) &&
3126 			    STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) {
3127 				STAILQ_CONCAT(&so2->so_rcv.uxdg_mb,
3128 				    &so->so_snd.uxdg_mb);
3129 				so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc;
3130 				so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl;
3131 				so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt;
3132 			} else {
3133 				m = STAILQ_FIRST(&so->so_snd.uxdg_mb);
3134 				STAILQ_INIT(&so->so_snd.uxdg_mb);
3135 				so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc;
3136 				so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc;
3137 				so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl;
3138 				so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt;
3139 			}
3140 			/* Note: so may reconnect. */
3141 			so->so_snd.uxdg_cc = 0;
3142 			so->so_snd.uxdg_ctl = 0;
3143 			so->so_snd.uxdg_mbcnt = 0;
3144 		}
3145 		SOCK_RECVBUF_UNLOCK(so2);
3146 		UNP_REF_LIST_LOCK();
3147 #ifdef INVARIANTS
3148 		LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
3149 			if (unptmp == unp)
3150 				break;
3151 		}
3152 		KASSERT(unptmp != NULL,
3153 		    ("%s: %p not found in reflist of %p", __func__, unp, unp2));
3154 #endif
3155 		LIST_REMOVE(unp, unp_reflink);
3156 		UNP_REF_LIST_UNLOCK();
3157 		if (so) {
3158 			SOCK_LOCK(so);
3159 			so->so_state &= ~SS_ISCONNECTED;
3160 			SOCK_UNLOCK(so);
3161 		}
3162 		break;
3163 
3164 	case SOCK_STREAM:
3165 	case SOCK_SEQPACKET:
3166 		SOCK_LOCK(so);
3167 		SOCK_LOCK(so2);
3168 		SOCK_RECVBUF_LOCK(so);
3169 		SOCK_RECVBUF_LOCK(so2);
3170 		unp_soisdisconnected(so);
3171 		MPASS(unp2->unp_conn == unp);
3172 		unp2->unp_conn = NULL;
3173 		unp_soisdisconnected(so2);
3174 		SOCK_UNLOCK(so);
3175 		SOCK_UNLOCK(so2);
3176 		break;
3177 	}
3178 
3179 	if (unp == unp2) {
3180 		unp_pcb_rele_notlast(unp);
3181 		if (!unp_pcb_rele(unp))
3182 			UNP_PCB_UNLOCK(unp);
3183 	} else {
3184 		if (!unp_pcb_rele(unp))
3185 			UNP_PCB_UNLOCK(unp);
3186 		if (!unp_pcb_rele(unp2))
3187 			UNP_PCB_UNLOCK(unp2);
3188 	}
3189 
3190 	if (m != NULL) {
3191 		unp_scan(m, unp_freerights);
3192 		m_freemp(m);
3193 	}
3194 }
3195 
3196 /*
3197  * unp_pcblist() walks the global list of struct unpcb's to generate a
3198  * pointer list, bumping the refcount on each unpcb.  It then copies them out
3199  * sequentially, validating the generation number on each to see if it has
3200  * been detached.  All of this is necessary because copyout() may sleep on
3201  * disk I/O.
3202  */
3203 static int
3204 unp_pcblist(SYSCTL_HANDLER_ARGS)
3205 {
3206 	struct unpcb *unp, **unp_list;
3207 	unp_gen_t gencnt;
3208 	struct xunpgen *xug;
3209 	struct unp_head *head;
3210 	struct xunpcb *xu;
3211 	u_int i;
3212 	int error, n;
3213 
3214 	switch ((intptr_t)arg1) {
3215 	case SOCK_STREAM:
3216 		head = &unp_shead;
3217 		break;
3218 
3219 	case SOCK_DGRAM:
3220 		head = &unp_dhead;
3221 		break;
3222 
3223 	case SOCK_SEQPACKET:
3224 		head = &unp_sphead;
3225 		break;
3226 
3227 	default:
3228 		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
3229 	}
3230 
3231 	/*
3232 	 * The process of preparing the PCB list is too time-consuming and
3233 	 * resource-intensive to repeat twice on every request.
3234 	 */
3235 	if (req->oldptr == NULL) {
3236 		n = unp_count;
3237 		req->oldidx = 2 * (sizeof *xug)
3238 			+ (n + n/8) * sizeof(struct xunpcb);
3239 		return (0);
3240 	}
3241 
3242 	if (req->newptr != NULL)
3243 		return (EPERM);
3244 
3245 	/*
3246 	 * OK, now we're committed to doing something.
3247 	 */
3248 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
3249 	UNP_LINK_RLOCK();
3250 	gencnt = unp_gencnt;
3251 	n = unp_count;
3252 	UNP_LINK_RUNLOCK();
3253 
3254 	xug->xug_len = sizeof *xug;
3255 	xug->xug_count = n;
3256 	xug->xug_gen = gencnt;
3257 	xug->xug_sogen = so_gencnt;
3258 	error = SYSCTL_OUT(req, xug, sizeof *xug);
3259 	if (error) {
3260 		free(xug, M_TEMP);
3261 		return (error);
3262 	}
3263 
3264 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
3265 
3266 	UNP_LINK_RLOCK();
3267 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
3268 	     unp = LIST_NEXT(unp, unp_link)) {
3269 		UNP_PCB_LOCK(unp);
3270 		if (unp->unp_gencnt <= gencnt) {
3271 			if (cr_cansee(req->td->td_ucred,
3272 			    unp->unp_socket->so_cred)) {
3273 				UNP_PCB_UNLOCK(unp);
3274 				continue;
3275 			}
3276 			unp_list[i++] = unp;
3277 			unp_pcb_hold(unp);
3278 		}
3279 		UNP_PCB_UNLOCK(unp);
3280 	}
3281 	UNP_LINK_RUNLOCK();
3282 	n = i;			/* In case we lost some during malloc. */
3283 
3284 	error = 0;
3285 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
3286 	for (i = 0; i < n; i++) {
3287 		unp = unp_list[i];
3288 		UNP_PCB_LOCK(unp);
3289 		if (unp_pcb_rele(unp))
3290 			continue;
3291 
3292 		if (unp->unp_gencnt <= gencnt) {
3293 			xu->xu_len = sizeof *xu;
3294 			xu->xu_unpp = (uintptr_t)unp;
3295 			/*
3296 			 * XXX - need more locking here to protect against
3297 			 * connect/disconnect races for SMP.
3298 			 */
3299 			if (unp->unp_addr != NULL)
3300 				bcopy(unp->unp_addr, &xu->xu_addr,
3301 				      unp->unp_addr->sun_len);
3302 			else
3303 				bzero(&xu->xu_addr, sizeof(xu->xu_addr));
3304 			if (unp->unp_conn != NULL &&
3305 			    unp->unp_conn->unp_addr != NULL)
3306 				bcopy(unp->unp_conn->unp_addr,
3307 				      &xu->xu_caddr,
3308 				      unp->unp_conn->unp_addr->sun_len);
3309 			else
3310 				bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
3311 			xu->unp_vnode = (uintptr_t)unp->unp_vnode;
3312 			xu->unp_conn = (uintptr_t)unp->unp_conn;
3313 			xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
3314 			xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
3315 			xu->unp_gencnt = unp->unp_gencnt;
3316 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
3317 			UNP_PCB_UNLOCK(unp);
3318 			error = SYSCTL_OUT(req, xu, sizeof *xu);
3319 		} else {
3320 			UNP_PCB_UNLOCK(unp);
3321 		}
3322 	}
3323 	free(xu, M_TEMP);
3324 	if (!error) {
3325 		/*
3326 		 * Give the user an updated idea of our state.  If the
3327 		 * generation differs from what we told her before, she knows
3328 		 * that something happened while we were processing this
3329 		 * request, and it might be necessary to retry.
3330 		 */
3331 		xug->xug_gen = unp_gencnt;
3332 		xug->xug_sogen = so_gencnt;
3333 		xug->xug_count = unp_count;
3334 		error = SYSCTL_OUT(req, xug, sizeof *xug);
3335 	}
3336 	free(unp_list, M_TEMP);
3337 	free(xug, M_TEMP);
3338 	return (error);
3339 }
3340 
3341 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
3342     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
3343     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
3344     "List of active local datagram sockets");
3345 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
3346     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
3347     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
3348     "List of active local stream sockets");
3349 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
3350     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
3351     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
3352     "List of active local seqpacket sockets");
3353 
3354 static void
3355 unp_shutdown(struct unpcb *unp)
3356 {
3357 	struct unpcb *unp2;
3358 	struct socket *so;
3359 
3360 	UNP_PCB_LOCK_ASSERT(unp);
3361 
3362 	unp2 = unp->unp_conn;
3363 	if ((unp->unp_socket->so_type == SOCK_STREAM ||
3364 	    (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
3365 		so = unp2->unp_socket;
3366 		if (so != NULL)
3367 			socantrcvmore(so);
3368 	}
3369 }
3370 
3371 static void
3372 unp_drop(struct unpcb *unp)
3373 {
3374 	struct socket *so;
3375 	struct unpcb *unp2;
3376 
3377 	/*
3378 	 * Regardless of whether the socket's peer dropped the connection
3379 	 * with this socket by aborting or disconnecting, POSIX requires
3380 	 * that ECONNRESET is returned on next connected send(2) in case of
3381 	 * a SOCK_DGRAM socket and EPIPE for SOCK_STREAM.
3382 	 */
3383 	UNP_PCB_LOCK(unp);
3384 	if ((so = unp->unp_socket) != NULL)
3385 		so->so_error =
3386 		    so->so_proto->pr_type == SOCK_DGRAM ? ECONNRESET : EPIPE;
3387 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
3388 		/* Last reference dropped in unp_disconnect(). */
3389 		unp_pcb_rele_notlast(unp);
3390 		unp_disconnect(unp, unp2);
3391 	} else if (!unp_pcb_rele(unp)) {
3392 		UNP_PCB_UNLOCK(unp);
3393 	}
3394 }
3395 
3396 static void
3397 unp_freerights(struct filedescent **fdep, int fdcount)
3398 {
3399 	struct file *fp;
3400 	int i;
3401 
3402 	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
3403 
3404 	for (i = 0; i < fdcount; i++) {
3405 		fp = fdep[i]->fde_file;
3406 		filecaps_free(&fdep[i]->fde_caps);
3407 		unp_discard(fp);
3408 	}
3409 	free(fdep[0], M_FILECAPS);
3410 }
3411 
3412 static int
3413 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
3414 {
3415 	struct thread *td = curthread;		/* XXX */
3416 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
3417 	int i;
3418 	int *fdp;
3419 	struct filedesc *fdesc = td->td_proc->p_fd;
3420 	struct filedescent **fdep;
3421 	void *data;
3422 	socklen_t clen = control->m_len, datalen;
3423 	int error, newfds;
3424 	u_int newlen;
3425 
3426 	UNP_LINK_UNLOCK_ASSERT();
3427 
3428 	error = 0;
3429 	if (controlp != NULL) /* controlp == NULL => free control messages */
3430 		*controlp = NULL;
3431 	while (cm != NULL) {
3432 		MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
3433 
3434 		data = CMSG_DATA(cm);
3435 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
3436 		if (cm->cmsg_level == SOL_SOCKET
3437 		    && cm->cmsg_type == SCM_RIGHTS) {
3438 			newfds = datalen / sizeof(*fdep);
3439 			if (newfds == 0)
3440 				goto next;
3441 			fdep = data;
3442 
3443 			/* If we're not outputting the descriptors free them. */
3444 			if (error || controlp == NULL) {
3445 				unp_freerights(fdep, newfds);
3446 				goto next;
3447 			}
3448 			FILEDESC_XLOCK(fdesc);
3449 
3450 			/*
3451 			 * Now change each pointer to an fd in the global
3452 			 * table to an integer that is the index to the local
3453 			 * fd table entry that we set up to point to the
3454 			 * global one we are transferring.
3455 			 */
3456 			newlen = newfds * sizeof(int);
3457 			*controlp = sbcreatecontrol(NULL, newlen,
3458 			    SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
3459 
3460 			fdp = (int *)
3461 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
3462 			if ((error = fdallocn(td, 0, fdp, newfds))) {
3463 				FILEDESC_XUNLOCK(fdesc);
3464 				unp_freerights(fdep, newfds);
3465 				m_freem(*controlp);
3466 				*controlp = NULL;
3467 				goto next;
3468 			}
3469 			for (i = 0; i < newfds; i++, fdp++) {
3470 				_finstall(fdesc, fdep[i]->fde_file, *fdp,
3471 				    (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
3472 				    &fdep[i]->fde_caps);
3473 				unp_externalize_fp(fdep[i]->fde_file);
3474 			}
3475 
3476 			/*
3477 			 * The new type indicates that the mbuf data refers to
3478 			 * kernel resources that may need to be released before
3479 			 * the mbuf is freed.
3480 			 */
3481 			m_chtype(*controlp, MT_EXTCONTROL);
3482 			FILEDESC_XUNLOCK(fdesc);
3483 			free(fdep[0], M_FILECAPS);
3484 		} else {
3485 			/* We can just copy anything else across. */
3486 			if (error || controlp == NULL)
3487 				goto next;
3488 			*controlp = sbcreatecontrol(NULL, datalen,
3489 			    cm->cmsg_type, cm->cmsg_level, M_WAITOK);
3490 			bcopy(data,
3491 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
3492 			    datalen);
3493 		}
3494 		controlp = &(*controlp)->m_next;
3495 
3496 next:
3497 		if (CMSG_SPACE(datalen) < clen) {
3498 			clen -= CMSG_SPACE(datalen);
3499 			cm = (struct cmsghdr *)
3500 			    ((caddr_t)cm + CMSG_SPACE(datalen));
3501 		} else {
3502 			clen = 0;
3503 			cm = NULL;
3504 		}
3505 	}
3506 
3507 	m_freem(control);
3508 	return (error);
3509 }
3510 
3511 static void
3512 unp_zone_change(void *tag)
3513 {
3514 
3515 	uma_zone_set_max(unp_zone, maxsockets);
3516 }
3517 
3518 #ifdef INVARIANTS
3519 static void
3520 unp_zdtor(void *mem, int size __unused, void *arg __unused)
3521 {
3522 	struct unpcb *unp;
3523 
3524 	unp = mem;
3525 
3526 	KASSERT(LIST_EMPTY(&unp->unp_refs),
3527 	    ("%s: unpcb %p has lingering refs", __func__, unp));
3528 	KASSERT(unp->unp_socket == NULL,
3529 	    ("%s: unpcb %p has socket backpointer", __func__, unp));
3530 	KASSERT(unp->unp_vnode == NULL,
3531 	    ("%s: unpcb %p has vnode references", __func__, unp));
3532 	KASSERT(unp->unp_conn == NULL,
3533 	    ("%s: unpcb %p is still connected", __func__, unp));
3534 	KASSERT(unp->unp_addr == NULL,
3535 	    ("%s: unpcb %p has leaked addr", __func__, unp));
3536 }
3537 #endif
3538 
3539 static void
3540 unp_init(void *arg __unused)
3541 {
3542 	uma_dtor dtor;
3543 
3544 #ifdef INVARIANTS
3545 	dtor = unp_zdtor;
3546 #else
3547 	dtor = NULL;
3548 #endif
3549 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
3550 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
3551 	uma_zone_set_max(unp_zone, maxsockets);
3552 	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
3553 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
3554 	    NULL, EVENTHANDLER_PRI_ANY);
3555 	LIST_INIT(&unp_dhead);
3556 	LIST_INIT(&unp_shead);
3557 	LIST_INIT(&unp_sphead);
3558 	SLIST_INIT(&unp_defers);
3559 	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
3560 	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
3561 	UNP_LINK_LOCK_INIT();
3562 	UNP_DEFERRED_LOCK_INIT();
3563 	unp_vp_mtxpool = mtx_pool_create("unp vp mtxpool", 32, MTX_DEF);
3564 }
3565 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
3566 
3567 static void
3568 unp_internalize_cleanup_rights(struct mbuf *control)
3569 {
3570 	struct cmsghdr *cp;
3571 	struct mbuf *m;
3572 	void *data;
3573 	socklen_t datalen;
3574 
3575 	for (m = control; m != NULL; m = m->m_next) {
3576 		cp = mtod(m, struct cmsghdr *);
3577 		if (cp->cmsg_level != SOL_SOCKET ||
3578 		    cp->cmsg_type != SCM_RIGHTS)
3579 			continue;
3580 		data = CMSG_DATA(cp);
3581 		datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
3582 		unp_freerights(data, datalen / sizeof(struct filedesc *));
3583 	}
3584 }
3585 
3586 static int
3587 unp_internalize(struct mbuf *control, struct mchain *mc, struct thread *td)
3588 {
3589 	struct proc *p;
3590 	struct filedesc *fdesc;
3591 	struct bintime *bt;
3592 	struct cmsghdr *cm;
3593 	struct cmsgcred *cmcred;
3594 	struct mbuf *m;
3595 	struct filedescent *fde, **fdep, *fdev;
3596 	struct file *fp;
3597 	struct timeval *tv;
3598 	struct timespec *ts;
3599 	void *data;
3600 	socklen_t clen, datalen;
3601 	int i, j, error, *fdp, oldfds;
3602 	u_int newlen;
3603 
3604 	MPASS(control->m_next == NULL); /* COMPAT_OLDSOCK may violate */
3605 	UNP_LINK_UNLOCK_ASSERT();
3606 
3607 	p = td->td_proc;
3608 	fdesc = p->p_fd;
3609 	error = 0;
3610 	*mc = MCHAIN_INITIALIZER(mc);
3611 	for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
3612 	    data = CMSG_DATA(cm);
3613 
3614 	    clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
3615 	    clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
3616 	    (char *)cm + cm->cmsg_len >= (char *)data;
3617 
3618 	    clen -= min(CMSG_SPACE(datalen), clen),
3619 	    cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
3620 	    data = CMSG_DATA(cm)) {
3621 		datalen = (char *)cm + cm->cmsg_len - (char *)data;
3622 		switch (cm->cmsg_type) {
3623 		case SCM_CREDS:
3624 			m = sbcreatecontrol(NULL, sizeof(*cmcred), SCM_CREDS,
3625 			    SOL_SOCKET, M_WAITOK);
3626 			cmcred = (struct cmsgcred *)
3627 			    CMSG_DATA(mtod(m, struct cmsghdr *));
3628 			cmcred->cmcred_pid = p->p_pid;
3629 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
3630 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
3631 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
3632 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
3633 			    CMGROUP_MAX);
3634 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
3635 				cmcred->cmcred_groups[i] =
3636 				    td->td_ucred->cr_groups[i];
3637 			break;
3638 
3639 		case SCM_RIGHTS:
3640 			oldfds = datalen / sizeof (int);
3641 			if (oldfds == 0)
3642 				continue;
3643 			/* On some machines sizeof pointer is bigger than
3644 			 * sizeof int, so we need to check if data fits into
3645 			 * single mbuf.  We could allocate several mbufs, and
3646 			 * unp_externalize() should even properly handle that.
3647 			 * But it is not worth to complicate the code for an
3648 			 * insane scenario of passing over 200 file descriptors
3649 			 * at once.
3650 			 */
3651 			newlen = oldfds * sizeof(fdep[0]);
3652 			if (CMSG_SPACE(newlen) > MCLBYTES) {
3653 				error = EMSGSIZE;
3654 				goto out;
3655 			}
3656 			/*
3657 			 * Check that all the FDs passed in refer to legal
3658 			 * files.  If not, reject the entire operation.
3659 			 */
3660 			fdp = data;
3661 			FILEDESC_SLOCK(fdesc);
3662 			for (i = 0; i < oldfds; i++, fdp++) {
3663 				fp = fget_noref(fdesc, *fdp);
3664 				if (fp == NULL) {
3665 					FILEDESC_SUNLOCK(fdesc);
3666 					error = EBADF;
3667 					goto out;
3668 				}
3669 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
3670 					FILEDESC_SUNLOCK(fdesc);
3671 					error = EOPNOTSUPP;
3672 					goto out;
3673 				}
3674 			}
3675 
3676 			/*
3677 			 * Now replace the integer FDs with pointers to the
3678 			 * file structure and capability rights.
3679 			 */
3680 			m = sbcreatecontrol(NULL, newlen, SCM_RIGHTS,
3681 			    SOL_SOCKET, M_WAITOK);
3682 			fdp = data;
3683 			for (i = 0; i < oldfds; i++, fdp++) {
3684 				if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
3685 					fdp = data;
3686 					for (j = 0; j < i; j++, fdp++) {
3687 						fdrop(fdesc->fd_ofiles[*fdp].
3688 						    fde_file, td);
3689 					}
3690 					FILEDESC_SUNLOCK(fdesc);
3691 					error = EBADF;
3692 					goto out;
3693 				}
3694 			}
3695 			fdp = data;
3696 			fdep = (struct filedescent **)
3697 			    CMSG_DATA(mtod(m, struct cmsghdr *));
3698 			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
3699 			    M_WAITOK);
3700 			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
3701 				fde = &fdesc->fd_ofiles[*fdp];
3702 				fdep[i] = fdev;
3703 				fdep[i]->fde_file = fde->fde_file;
3704 				filecaps_copy(&fde->fde_caps,
3705 				    &fdep[i]->fde_caps, true);
3706 				unp_internalize_fp(fdep[i]->fde_file);
3707 			}
3708 			FILEDESC_SUNLOCK(fdesc);
3709 			break;
3710 
3711 		case SCM_TIMESTAMP:
3712 			m = sbcreatecontrol(NULL, sizeof(*tv), SCM_TIMESTAMP,
3713 			    SOL_SOCKET, M_WAITOK);
3714 			tv = (struct timeval *)
3715 			    CMSG_DATA(mtod(m, struct cmsghdr *));
3716 			microtime(tv);
3717 			break;
3718 
3719 		case SCM_BINTIME:
3720 			m = sbcreatecontrol(NULL, sizeof(*bt), SCM_BINTIME,
3721 			    SOL_SOCKET, M_WAITOK);
3722 			bt = (struct bintime *)
3723 			    CMSG_DATA(mtod(m, struct cmsghdr *));
3724 			bintime(bt);
3725 			break;
3726 
3727 		case SCM_REALTIME:
3728 			m = sbcreatecontrol(NULL, sizeof(*ts), SCM_REALTIME,
3729 			    SOL_SOCKET, M_WAITOK);
3730 			ts = (struct timespec *)
3731 			    CMSG_DATA(mtod(m, struct cmsghdr *));
3732 			nanotime(ts);
3733 			break;
3734 
3735 		case SCM_MONOTONIC:
3736 			m = sbcreatecontrol(NULL, sizeof(*ts), SCM_MONOTONIC,
3737 			    SOL_SOCKET, M_WAITOK);
3738 			ts = (struct timespec *)
3739 			    CMSG_DATA(mtod(m, struct cmsghdr *));
3740 			nanouptime(ts);
3741 			break;
3742 
3743 		default:
3744 			error = EINVAL;
3745 			goto out;
3746 		}
3747 
3748 		mc_append(mc, m);
3749 	}
3750 	if (clen > 0)
3751 		error = EINVAL;
3752 
3753 out:
3754 	if (error != 0)
3755 		unp_internalize_cleanup_rights(mc_first(mc));
3756 	m_freem(control);
3757 	return (error);
3758 }
3759 
3760 static void
3761 unp_addsockcred(struct thread *td, struct mchain *mc, int mode)
3762 {
3763 	struct mbuf *m, *n, *n_prev;
3764 	const struct cmsghdr *cm;
3765 	int ngroups, i, cmsgtype;
3766 	size_t ctrlsz;
3767 
3768 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
3769 	if (mode & UNP_WANTCRED_ALWAYS) {
3770 		ctrlsz = SOCKCRED2SIZE(ngroups);
3771 		cmsgtype = SCM_CREDS2;
3772 	} else {
3773 		ctrlsz = SOCKCREDSIZE(ngroups);
3774 		cmsgtype = SCM_CREDS;
3775 	}
3776 
3777 	/* XXXGL: uipc_sosend_*() need to be improved so that we can M_WAITOK */
3778 	m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
3779 	if (m == NULL)
3780 		return;
3781 	MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL);
3782 
3783 	if (mode & UNP_WANTCRED_ALWAYS) {
3784 		struct sockcred2 *sc;
3785 
3786 		sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
3787 		sc->sc_version = 0;
3788 		sc->sc_pid = td->td_proc->p_pid;
3789 		sc->sc_uid = td->td_ucred->cr_ruid;
3790 		sc->sc_euid = td->td_ucred->cr_uid;
3791 		sc->sc_gid = td->td_ucred->cr_rgid;
3792 		sc->sc_egid = td->td_ucred->cr_gid;
3793 		sc->sc_ngroups = ngroups;
3794 		for (i = 0; i < sc->sc_ngroups; i++)
3795 			sc->sc_groups[i] = td->td_ucred->cr_groups[i];
3796 	} else {
3797 		struct sockcred *sc;
3798 
3799 		sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
3800 		sc->sc_uid = td->td_ucred->cr_ruid;
3801 		sc->sc_euid = td->td_ucred->cr_uid;
3802 		sc->sc_gid = td->td_ucred->cr_rgid;
3803 		sc->sc_egid = td->td_ucred->cr_gid;
3804 		sc->sc_ngroups = ngroups;
3805 		for (i = 0; i < sc->sc_ngroups; i++)
3806 			sc->sc_groups[i] = td->td_ucred->cr_groups[i];
3807 	}
3808 
3809 	/*
3810 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
3811 	 * created SCM_CREDS control message (struct sockcred) has another
3812 	 * format.
3813 	 */
3814 	if (!STAILQ_EMPTY(&mc->mc_q) && cmsgtype == SCM_CREDS)
3815 		STAILQ_FOREACH_SAFE(n, &mc->mc_q, m_stailq, n_prev) {
3816 			cm = mtod(n, struct cmsghdr *);
3817     			if (cm->cmsg_level == SOL_SOCKET &&
3818 			    cm->cmsg_type == SCM_CREDS) {
3819 				mc_remove(mc, n);
3820 				m_free(n);
3821 			}
3822 		}
3823 
3824 	/* Prepend it to the head. */
3825 	mc_prepend(mc, m);
3826 }
3827 
3828 static struct unpcb *
3829 fptounp(struct file *fp)
3830 {
3831 	struct socket *so;
3832 
3833 	if (fp->f_type != DTYPE_SOCKET)
3834 		return (NULL);
3835 	if ((so = fp->f_data) == NULL)
3836 		return (NULL);
3837 	if (so->so_proto->pr_domain != &localdomain)
3838 		return (NULL);
3839 	return sotounpcb(so);
3840 }
3841 
3842 static void
3843 unp_discard(struct file *fp)
3844 {
3845 	struct unp_defer *dr;
3846 
3847 	if (unp_externalize_fp(fp)) {
3848 		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
3849 		dr->ud_fp = fp;
3850 		UNP_DEFERRED_LOCK();
3851 		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
3852 		UNP_DEFERRED_UNLOCK();
3853 		atomic_add_int(&unp_defers_count, 1);
3854 		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
3855 	} else
3856 		closef_nothread(fp);
3857 }
3858 
3859 static void
3860 unp_process_defers(void *arg __unused, int pending)
3861 {
3862 	struct unp_defer *dr;
3863 	SLIST_HEAD(, unp_defer) drl;
3864 	int count;
3865 
3866 	SLIST_INIT(&drl);
3867 	for (;;) {
3868 		UNP_DEFERRED_LOCK();
3869 		if (SLIST_FIRST(&unp_defers) == NULL) {
3870 			UNP_DEFERRED_UNLOCK();
3871 			break;
3872 		}
3873 		SLIST_SWAP(&unp_defers, &drl, unp_defer);
3874 		UNP_DEFERRED_UNLOCK();
3875 		count = 0;
3876 		while ((dr = SLIST_FIRST(&drl)) != NULL) {
3877 			SLIST_REMOVE_HEAD(&drl, ud_link);
3878 			closef_nothread(dr->ud_fp);
3879 			free(dr, M_TEMP);
3880 			count++;
3881 		}
3882 		atomic_add_int(&unp_defers_count, -count);
3883 	}
3884 }
3885 
3886 static void
3887 unp_internalize_fp(struct file *fp)
3888 {
3889 	struct unpcb *unp;
3890 
3891 	UNP_LINK_WLOCK();
3892 	if ((unp = fptounp(fp)) != NULL) {
3893 		unp->unp_file = fp;
3894 		unp->unp_msgcount++;
3895 	}
3896 	unp_rights++;
3897 	UNP_LINK_WUNLOCK();
3898 }
3899 
3900 static int
3901 unp_externalize_fp(struct file *fp)
3902 {
3903 	struct unpcb *unp;
3904 	int ret;
3905 
3906 	UNP_LINK_WLOCK();
3907 	if ((unp = fptounp(fp)) != NULL) {
3908 		unp->unp_msgcount--;
3909 		ret = 1;
3910 	} else
3911 		ret = 0;
3912 	unp_rights--;
3913 	UNP_LINK_WUNLOCK();
3914 	return (ret);
3915 }
3916 
3917 /*
3918  * unp_defer indicates whether additional work has been defered for a future
3919  * pass through unp_gc().  It is thread local and does not require explicit
3920  * synchronization.
3921  */
3922 static int	unp_marked;
3923 
3924 static void
3925 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
3926 {
3927 	struct unpcb *unp;
3928 	struct file *fp;
3929 	int i;
3930 
3931 	/*
3932 	 * This function can only be called from the gc task.
3933 	 */
3934 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
3935 	    ("%s: not on gc callout", __func__));
3936 	UNP_LINK_LOCK_ASSERT();
3937 
3938 	for (i = 0; i < fdcount; i++) {
3939 		fp = fdep[i]->fde_file;
3940 		if ((unp = fptounp(fp)) == NULL)
3941 			continue;
3942 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
3943 			continue;
3944 		unp->unp_gcrefs--;
3945 	}
3946 }
3947 
3948 static void
3949 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
3950 {
3951 	struct unpcb *unp;
3952 	struct file *fp;
3953 	int i;
3954 
3955 	/*
3956 	 * This function can only be called from the gc task.
3957 	 */
3958 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
3959 	    ("%s: not on gc callout", __func__));
3960 	UNP_LINK_LOCK_ASSERT();
3961 
3962 	for (i = 0; i < fdcount; i++) {
3963 		fp = fdep[i]->fde_file;
3964 		if ((unp = fptounp(fp)) == NULL)
3965 			continue;
3966 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
3967 			continue;
3968 		unp->unp_gcrefs++;
3969 		unp_marked++;
3970 	}
3971 }
3972 
3973 static void
3974 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
3975 {
3976 	struct sockbuf *sb;
3977 
3978 	SOCK_LOCK_ASSERT(so);
3979 
3980 	if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
3981 		return;
3982 
3983 	SOCK_RECVBUF_LOCK(so);
3984 	switch (so->so_type) {
3985 	case SOCK_DGRAM:
3986 		unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
3987 		unp_scan(so->so_rcv.uxdg_peeked, op);
3988 		TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist)
3989 			unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op);
3990 		break;
3991 	case SOCK_STREAM:
3992 	case SOCK_SEQPACKET:
3993 		unp_scan(STAILQ_FIRST(&so->so_rcv.uxst_mbq), op);
3994 		break;
3995 	}
3996 	SOCK_RECVBUF_UNLOCK(so);
3997 }
3998 
3999 static void
4000 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
4001 {
4002 	struct socket *so, *soa;
4003 
4004 	so = unp->unp_socket;
4005 	SOCK_LOCK(so);
4006 	if (SOLISTENING(so)) {
4007 		/*
4008 		 * Mark all sockets in our accept queue.
4009 		 */
4010 		TAILQ_FOREACH(soa, &so->sol_comp, so_list)
4011 			unp_scan_socket(soa, op);
4012 	} else {
4013 		/*
4014 		 * Mark all sockets we reference with RIGHTS.
4015 		 */
4016 		unp_scan_socket(so, op);
4017 	}
4018 	SOCK_UNLOCK(so);
4019 }
4020 
4021 static int unp_recycled;
4022 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
4023     "Number of unreachable sockets claimed by the garbage collector.");
4024 
4025 static int unp_taskcount;
4026 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
4027     "Number of times the garbage collector has run.");
4028 
4029 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
4030     "Number of active local sockets.");
4031 
4032 static void
4033 unp_gc(__unused void *arg, int pending)
4034 {
4035 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
4036 				    NULL };
4037 	struct unp_head **head;
4038 	struct unp_head unp_deadhead;	/* List of potentially-dead sockets. */
4039 	struct file *f, **unref;
4040 	struct unpcb *unp, *unptmp;
4041 	int i, total, unp_unreachable;
4042 
4043 	LIST_INIT(&unp_deadhead);
4044 	unp_taskcount++;
4045 	UNP_LINK_RLOCK();
4046 	/*
4047 	 * First determine which sockets may be in cycles.
4048 	 */
4049 	unp_unreachable = 0;
4050 
4051 	for (head = heads; *head != NULL; head++)
4052 		LIST_FOREACH(unp, *head, unp_link) {
4053 			KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
4054 			    ("%s: unp %p has unexpected gc flags 0x%x",
4055 			    __func__, unp, (unsigned int)unp->unp_gcflag));
4056 
4057 			f = unp->unp_file;
4058 
4059 			/*
4060 			 * Check for an unreachable socket potentially in a
4061 			 * cycle.  It must be in a queue as indicated by
4062 			 * msgcount, and this must equal the file reference
4063 			 * count.  Note that when msgcount is 0 the file is
4064 			 * NULL.
4065 			 */
4066 			if (f != NULL && unp->unp_msgcount != 0 &&
4067 			    refcount_load(&f->f_count) == unp->unp_msgcount) {
4068 				LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
4069 				unp->unp_gcflag |= UNPGC_DEAD;
4070 				unp->unp_gcrefs = unp->unp_msgcount;
4071 				unp_unreachable++;
4072 			}
4073 		}
4074 
4075 	/*
4076 	 * Scan all sockets previously marked as potentially being in a cycle
4077 	 * and remove the references each socket holds on any UNPGC_DEAD
4078 	 * sockets in its queue.  After this step, all remaining references on
4079 	 * sockets marked UNPGC_DEAD should not be part of any cycle.
4080 	 */
4081 	LIST_FOREACH(unp, &unp_deadhead, unp_dead)
4082 		unp_gc_scan(unp, unp_remove_dead_ref);
4083 
4084 	/*
4085 	 * If a socket still has a non-negative refcount, it cannot be in a
4086 	 * cycle.  In this case increment refcount of all children iteratively.
4087 	 * Stop the scan once we do a complete loop without discovering
4088 	 * a new reachable socket.
4089 	 */
4090 	do {
4091 		unp_marked = 0;
4092 		LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
4093 			if (unp->unp_gcrefs > 0) {
4094 				unp->unp_gcflag &= ~UNPGC_DEAD;
4095 				LIST_REMOVE(unp, unp_dead);
4096 				KASSERT(unp_unreachable > 0,
4097 				    ("%s: unp_unreachable underflow.",
4098 				    __func__));
4099 				unp_unreachable--;
4100 				unp_gc_scan(unp, unp_restore_undead_ref);
4101 			}
4102 	} while (unp_marked);
4103 
4104 	UNP_LINK_RUNLOCK();
4105 
4106 	if (unp_unreachable == 0)
4107 		return;
4108 
4109 	/*
4110 	 * Allocate space for a local array of dead unpcbs.
4111 	 * TODO: can this path be simplified by instead using the local
4112 	 * dead list at unp_deadhead, after taking out references
4113 	 * on the file object and/or unpcb and dropping the link lock?
4114 	 */
4115 	unref = malloc(unp_unreachable * sizeof(struct file *),
4116 	    M_TEMP, M_WAITOK);
4117 
4118 	/*
4119 	 * Iterate looking for sockets which have been specifically marked
4120 	 * as unreachable and store them locally.
4121 	 */
4122 	UNP_LINK_RLOCK();
4123 	total = 0;
4124 	LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
4125 		KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
4126 		    ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
4127 		unp->unp_gcflag &= ~UNPGC_DEAD;
4128 		f = unp->unp_file;
4129 		if (unp->unp_msgcount == 0 || f == NULL ||
4130 		    refcount_load(&f->f_count) != unp->unp_msgcount ||
4131 		    !fhold(f))
4132 			continue;
4133 		unref[total++] = f;
4134 		KASSERT(total <= unp_unreachable,
4135 		    ("%s: incorrect unreachable count.", __func__));
4136 	}
4137 	UNP_LINK_RUNLOCK();
4138 
4139 	/*
4140 	 * Now flush all sockets, free'ing rights.  This will free the
4141 	 * struct files associated with these sockets but leave each socket
4142 	 * with one remaining ref.
4143 	 */
4144 	for (i = 0; i < total; i++) {
4145 		struct socket *so;
4146 
4147 		so = unref[i]->f_data;
4148 		CURVNET_SET(so->so_vnet);
4149 		socantrcvmore(so);
4150 		unp_dispose(so);
4151 		CURVNET_RESTORE();
4152 	}
4153 
4154 	/*
4155 	 * And finally release the sockets so they can be reclaimed.
4156 	 */
4157 	for (i = 0; i < total; i++)
4158 		fdrop(unref[i], NULL);
4159 	unp_recycled += total;
4160 	free(unref, M_TEMP);
4161 }
4162 
4163 /*
4164  * Synchronize against unp_gc, which can trip over data as we are freeing it.
4165  */
4166 static void
4167 unp_dispose(struct socket *so)
4168 {
4169 	struct sockbuf *sb;
4170 	struct unpcb *unp;
4171 	struct mbuf *m;
4172 	int error __diagused;
4173 
4174 	MPASS(!SOLISTENING(so));
4175 
4176 	unp = sotounpcb(so);
4177 	UNP_LINK_WLOCK();
4178 	unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
4179 	UNP_LINK_WUNLOCK();
4180 
4181 	/*
4182 	 * Grab our special mbufs before calling sbrelease().
4183 	 */
4184 	error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR);
4185 	MPASS(!error);
4186 	SOCK_RECVBUF_LOCK(so);
4187 	switch (so->so_type) {
4188 	case SOCK_DGRAM:
4189 		while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) {
4190 			STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb);
4191 			TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
4192 			/* Note: socket of sb may reconnect. */
4193 			sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0;
4194 		}
4195 		sb = &so->so_rcv;
4196 		if (sb->uxdg_peeked != NULL) {
4197 			STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked,
4198 			    m_stailqpkt);
4199 			sb->uxdg_peeked = NULL;
4200 		}
4201 		m = STAILQ_FIRST(&sb->uxdg_mb);
4202 		STAILQ_INIT(&sb->uxdg_mb);
4203 		break;
4204 	case SOCK_STREAM:
4205 	case SOCK_SEQPACKET:
4206 		sb = &so->so_rcv;
4207 		m = STAILQ_FIRST(&sb->uxst_mbq);
4208 		STAILQ_INIT(&sb->uxst_mbq);
4209 		sb->sb_acc = sb->sb_ccc = sb->sb_ctl = sb->sb_mbcnt = 0;
4210 		/*
4211 		 * Trim M_NOTREADY buffers from the free list.  They are
4212 		 * referenced by the I/O thread.
4213 		 */
4214 		if (sb->uxst_fnrdy != NULL) {
4215 			struct mbuf *n, *prev;
4216 
4217 			while (m != NULL && m->m_flags & M_NOTREADY)
4218 				m = m->m_next;
4219 			for (prev = n = m; n != NULL; n = n->m_next) {
4220 				if (n->m_flags & M_NOTREADY)
4221 					prev->m_next = n->m_next;
4222 				else
4223 					prev = n;
4224 			}
4225 			sb->uxst_fnrdy = NULL;
4226 		}
4227 		break;
4228 	}
4229 	/*
4230 	 * Mark sb with SBS_CANTRCVMORE.  This is needed to prevent
4231 	 * uipc_sosend_*() or unp_disconnect() adding more data to the socket.
4232 	 * We came here either through shutdown(2) or from the final sofree().
4233 	 * The sofree() case is simple as it guarantees that no more sends will
4234 	 * happen, however we can race with unp_disconnect() from our peer.
4235 	 * The shutdown(2) case is more exotic.  It would call into
4236 	 * unp_dispose() only if socket is SS_ISCONNECTED.  This is possible if
4237 	 * we did connect(2) on this socket and we also had it bound with
4238 	 * bind(2) and receive connections from other sockets.  Because
4239 	 * uipc_shutdown() violates POSIX (see comment there) this applies to
4240 	 * SOCK_DGRAM as well.  For SOCK_DGRAM this SBS_CANTRCVMORE will have
4241 	 * affect not only on the peer we connect(2)ed to, but also on all of
4242 	 * the peers who had connect(2)ed to us.  Their sends would end up
4243 	 * with ENOBUFS.
4244 	 */
4245 	sb->sb_state |= SBS_CANTRCVMORE;
4246 	(void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
4247 	    RLIM_INFINITY);
4248 	SOCK_RECVBUF_UNLOCK(so);
4249 	SOCK_IO_RECV_UNLOCK(so);
4250 
4251 	if (m != NULL) {
4252 		unp_scan(m, unp_freerights);
4253 		m_freemp(m);
4254 	}
4255 }
4256 
4257 static void
4258 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
4259 {
4260 	struct mbuf *m;
4261 	struct cmsghdr *cm;
4262 	void *data;
4263 	socklen_t clen, datalen;
4264 
4265 	while (m0 != NULL) {
4266 		for (m = m0; m; m = m->m_next) {
4267 			if (m->m_type != MT_CONTROL)
4268 				continue;
4269 
4270 			cm = mtod(m, struct cmsghdr *);
4271 			clen = m->m_len;
4272 
4273 			while (cm != NULL) {
4274 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
4275 					break;
4276 
4277 				data = CMSG_DATA(cm);
4278 				datalen = (caddr_t)cm + cm->cmsg_len
4279 				    - (caddr_t)data;
4280 
4281 				if (cm->cmsg_level == SOL_SOCKET &&
4282 				    cm->cmsg_type == SCM_RIGHTS) {
4283 					(*op)(data, datalen /
4284 					    sizeof(struct filedescent *));
4285 				}
4286 
4287 				if (CMSG_SPACE(datalen) < clen) {
4288 					clen -= CMSG_SPACE(datalen);
4289 					cm = (struct cmsghdr *)
4290 					    ((caddr_t)cm + CMSG_SPACE(datalen));
4291 				} else {
4292 					clen = 0;
4293 					cm = NULL;
4294 				}
4295 			}
4296 		}
4297 		m0 = m0->m_nextpkt;
4298 	}
4299 }
4300 
4301 /*
4302  * Definitions of protocols supported in the LOCAL domain.
4303  */
4304 static struct protosw streamproto = {
4305 	.pr_type =		SOCK_STREAM,
4306 	.pr_flags =		PR_CONNREQUIRED | PR_CAPATTACH | PR_SOCKBUF,
4307 	.pr_ctloutput =		&uipc_ctloutput,
4308 	.pr_abort = 		uipc_abort,
4309 	.pr_accept =		uipc_peeraddr,
4310 	.pr_attach =		uipc_attach,
4311 	.pr_bind =		uipc_bind,
4312 	.pr_bindat =		uipc_bindat,
4313 	.pr_connect =		uipc_connect,
4314 	.pr_connectat =		uipc_connectat,
4315 	.pr_connect2 =		uipc_connect2,
4316 	.pr_detach =		uipc_detach,
4317 	.pr_disconnect =	uipc_disconnect,
4318 	.pr_listen =		uipc_listen,
4319 	.pr_peeraddr =		uipc_peeraddr,
4320 	.pr_send =		uipc_sendfile,
4321 	.pr_sendfile_wait =	uipc_sendfile_wait,
4322 	.pr_ready =		uipc_ready,
4323 	.pr_sense =		uipc_sense,
4324 	.pr_shutdown =		uipc_shutdown,
4325 	.pr_sockaddr =		uipc_sockaddr,
4326 	.pr_sosend = 		uipc_sosend_stream_or_seqpacket,
4327 	.pr_soreceive =		uipc_soreceive_stream_or_seqpacket,
4328 	.pr_sopoll =		uipc_sopoll_stream_or_seqpacket,
4329 	.pr_kqfilter =		uipc_kqfilter_stream_or_seqpacket,
4330 	.pr_close =		uipc_close,
4331 	.pr_chmod =		uipc_chmod,
4332 };
4333 
4334 static struct protosw dgramproto = {
4335 	.pr_type =		SOCK_DGRAM,
4336 	.pr_flags =		PR_ATOMIC | PR_ADDR | PR_CAPATTACH | PR_SOCKBUF,
4337 	.pr_ctloutput =		&uipc_ctloutput,
4338 	.pr_abort = 		uipc_abort,
4339 	.pr_accept =		uipc_peeraddr,
4340 	.pr_attach =		uipc_attach,
4341 	.pr_bind =		uipc_bind,
4342 	.pr_bindat =		uipc_bindat,
4343 	.pr_connect =		uipc_connect,
4344 	.pr_connectat =		uipc_connectat,
4345 	.pr_connect2 =		uipc_connect2,
4346 	.pr_detach =		uipc_detach,
4347 	.pr_disconnect =	uipc_disconnect,
4348 	.pr_peeraddr =		uipc_peeraddr,
4349 	.pr_sosend =		uipc_sosend_dgram,
4350 	.pr_sense =		uipc_sense,
4351 	.pr_shutdown =		uipc_shutdown,
4352 	.pr_sockaddr =		uipc_sockaddr,
4353 	.pr_soreceive =		uipc_soreceive_dgram,
4354 	.pr_close =		uipc_close,
4355 	.pr_chmod =		uipc_chmod,
4356 };
4357 
4358 static struct protosw seqpacketproto = {
4359 	.pr_type =		SOCK_SEQPACKET,
4360 	.pr_flags =		PR_CONNREQUIRED | PR_CAPATTACH | PR_SOCKBUF,
4361 	.pr_ctloutput =		&uipc_ctloutput,
4362 	.pr_abort =		uipc_abort,
4363 	.pr_accept =		uipc_peeraddr,
4364 	.pr_attach =		uipc_attach,
4365 	.pr_bind =		uipc_bind,
4366 	.pr_bindat =		uipc_bindat,
4367 	.pr_connect =		uipc_connect,
4368 	.pr_connectat =		uipc_connectat,
4369 	.pr_connect2 =		uipc_connect2,
4370 	.pr_detach =		uipc_detach,
4371 	.pr_disconnect =	uipc_disconnect,
4372 	.pr_listen =		uipc_listen,
4373 	.pr_peeraddr =		uipc_peeraddr,
4374 	.pr_sense =		uipc_sense,
4375 	.pr_shutdown =		uipc_shutdown,
4376 	.pr_sockaddr =		uipc_sockaddr,
4377 	.pr_sosend = 		uipc_sosend_stream_or_seqpacket,
4378 	.pr_soreceive =		uipc_soreceive_stream_or_seqpacket,
4379 	.pr_sopoll =		uipc_sopoll_stream_or_seqpacket,
4380 	.pr_kqfilter =		uipc_kqfilter_stream_or_seqpacket,
4381 	.pr_close =		uipc_close,
4382 	.pr_chmod =		uipc_chmod,
4383 };
4384 
4385 static struct domain localdomain = {
4386 	.dom_family =		AF_LOCAL,
4387 	.dom_name =		"local",
4388 	.dom_externalize =	unp_externalize,
4389 	.dom_nprotosw =		3,
4390 	.dom_protosw =		{
4391 		&streamproto,
4392 		&dgramproto,
4393 		&seqpacketproto,
4394 	}
4395 };
4396 DOMAIN_SET(local);
4397 
4398 /*
4399  * A helper function called by VFS before socket-type vnode reclamation.
4400  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
4401  * use count.
4402  */
4403 void
4404 vfs_unp_reclaim(struct vnode *vp)
4405 {
4406 	struct unpcb *unp;
4407 	int active;
4408 	struct mtx *vplock;
4409 
4410 	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
4411 	KASSERT(vp->v_type == VSOCK,
4412 	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
4413 
4414 	active = 0;
4415 	vplock = mtx_pool_find(unp_vp_mtxpool, vp);
4416 	mtx_lock(vplock);
4417 	VOP_UNP_CONNECT(vp, &unp);
4418 	if (unp == NULL)
4419 		goto done;
4420 	UNP_PCB_LOCK(unp);
4421 	if (unp->unp_vnode == vp) {
4422 		VOP_UNP_DETACH(vp);
4423 		unp->unp_vnode = NULL;
4424 		active = 1;
4425 	}
4426 	UNP_PCB_UNLOCK(unp);
4427  done:
4428 	mtx_unlock(vplock);
4429 	if (active)
4430 		vunref(vp);
4431 }
4432 
4433 #ifdef DDB
4434 static void
4435 db_print_indent(int indent)
4436 {
4437 	int i;
4438 
4439 	for (i = 0; i < indent; i++)
4440 		db_printf(" ");
4441 }
4442 
4443 static void
4444 db_print_unpflags(int unp_flags)
4445 {
4446 	int comma;
4447 
4448 	comma = 0;
4449 	if (unp_flags & UNP_HAVEPC) {
4450 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
4451 		comma = 1;
4452 	}
4453 	if (unp_flags & UNP_WANTCRED_ALWAYS) {
4454 		db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
4455 		comma = 1;
4456 	}
4457 	if (unp_flags & UNP_WANTCRED_ONESHOT) {
4458 		db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
4459 		comma = 1;
4460 	}
4461 	if (unp_flags & UNP_CONNECTING) {
4462 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
4463 		comma = 1;
4464 	}
4465 	if (unp_flags & UNP_BINDING) {
4466 		db_printf("%sUNP_BINDING", comma ? ", " : "");
4467 		comma = 1;
4468 	}
4469 }
4470 
4471 static void
4472 db_print_xucred(int indent, struct xucred *xu)
4473 {
4474 	int comma, i;
4475 
4476 	db_print_indent(indent);
4477 	db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
4478 	    xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
4479 	db_print_indent(indent);
4480 	db_printf("cr_groups: ");
4481 	comma = 0;
4482 	for (i = 0; i < xu->cr_ngroups; i++) {
4483 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
4484 		comma = 1;
4485 	}
4486 	db_printf("\n");
4487 }
4488 
4489 static void
4490 db_print_unprefs(int indent, struct unp_head *uh)
4491 {
4492 	struct unpcb *unp;
4493 	int counter;
4494 
4495 	counter = 0;
4496 	LIST_FOREACH(unp, uh, unp_reflink) {
4497 		if (counter % 4 == 0)
4498 			db_print_indent(indent);
4499 		db_printf("%p  ", unp);
4500 		if (counter % 4 == 3)
4501 			db_printf("\n");
4502 		counter++;
4503 	}
4504 	if (counter != 0 && counter % 4 != 0)
4505 		db_printf("\n");
4506 }
4507 
4508 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
4509 {
4510 	struct unpcb *unp;
4511 
4512         if (!have_addr) {
4513                 db_printf("usage: show unpcb <addr>\n");
4514                 return;
4515         }
4516         unp = (struct unpcb *)addr;
4517 
4518 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
4519 	    unp->unp_vnode);
4520 
4521 	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
4522 	    unp->unp_conn);
4523 
4524 	db_printf("unp_refs:\n");
4525 	db_print_unprefs(2, &unp->unp_refs);
4526 
4527 	/* XXXRW: Would be nice to print the full address, if any. */
4528 	db_printf("unp_addr: %p\n", unp->unp_addr);
4529 
4530 	db_printf("unp_gencnt: %llu\n",
4531 	    (unsigned long long)unp->unp_gencnt);
4532 
4533 	db_printf("unp_flags: %x (", unp->unp_flags);
4534 	db_print_unpflags(unp->unp_flags);
4535 	db_printf(")\n");
4536 
4537 	db_printf("unp_peercred:\n");
4538 	db_print_xucred(2, &unp->unp_peercred);
4539 
4540 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
4541 }
4542 #endif
4543