]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_usrreq.c
unix/dgram: use minimal possible socket buffer for PF_UNIX/SOCK_DGRAM
[FreeBSD/FreeBSD.git] / sys / kern / uipc_usrreq.c
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  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
34  */
35
36 /*
37  * UNIX Domain (Local) Sockets
38  *
39  * This is an implementation of UNIX (local) domain sockets.  Each socket has
40  * an associated struct unpcb (UNIX protocol control block).  Stream sockets
41  * may be connected to 0 or 1 other socket.  Datagram sockets may be
42  * connected to 0, 1, or many other sockets.  Sockets may be created and
43  * connected in pairs (socketpair(2)), or bound/connected to using the file
44  * system name space.  For most purposes, only the receive socket buffer is
45  * used, as sending on one socket delivers directly to the receive socket
46  * buffer of a second socket.
47  *
48  * The implementation is substantially complicated by the fact that
49  * "ancillary data", such as file descriptors or credentials, may be passed
50  * across UNIX domain sockets.  The potential for passing UNIX domain sockets
51  * over other UNIX domain sockets requires the implementation of a simple
52  * garbage collector to find and tear down cycles of disconnected sockets.
53  *
54  * TODO:
55  *      RDM
56  *      rethink name space problems
57  *      need a proper out-of-band
58  */
59
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
62
63 #include "opt_ddb.h"
64
65 #include <sys/param.h>
66 #include <sys/capsicum.h>
67 #include <sys/domain.h>
68 #include <sys/eventhandler.h>
69 #include <sys/fcntl.h>
70 #include <sys/file.h>
71 #include <sys/filedesc.h>
72 #include <sys/kernel.h>
73 #include <sys/lock.h>
74 #include <sys/malloc.h>
75 #include <sys/mbuf.h>
76 #include <sys/mount.h>
77 #include <sys/mutex.h>
78 #include <sys/namei.h>
79 #include <sys/proc.h>
80 #include <sys/protosw.h>
81 #include <sys/queue.h>
82 #include <sys/resourcevar.h>
83 #include <sys/rwlock.h>
84 #include <sys/socket.h>
85 #include <sys/socketvar.h>
86 #include <sys/signalvar.h>
87 #include <sys/stat.h>
88 #include <sys/sx.h>
89 #include <sys/sysctl.h>
90 #include <sys/systm.h>
91 #include <sys/taskqueue.h>
92 #include <sys/un.h>
93 #include <sys/unpcb.h>
94 #include <sys/vnode.h>
95
96 #include <net/vnet.h>
97
98 #ifdef DDB
99 #include <ddb/ddb.h>
100 #endif
101
102 #include <security/mac/mac_framework.h>
103
104 #include <vm/uma.h>
105
106 MALLOC_DECLARE(M_FILECAPS);
107
108 /*
109  * See unpcb.h for the locking key.
110  */
111
112 static uma_zone_t       unp_zone;
113 static unp_gen_t        unp_gencnt;     /* (l) */
114 static u_int            unp_count;      /* (l) Count of local sockets. */
115 static ino_t            unp_ino;        /* Prototype for fake inode numbers. */
116 static int              unp_rights;     /* (g) File descriptors in flight. */
117 static struct unp_head  unp_shead;      /* (l) List of stream sockets. */
118 static struct unp_head  unp_dhead;      /* (l) List of datagram sockets. */
119 static struct unp_head  unp_sphead;     /* (l) List of seqpacket sockets. */
120
121 struct unp_defer {
122         SLIST_ENTRY(unp_defer) ud_link;
123         struct file *ud_fp;
124 };
125 static SLIST_HEAD(, unp_defer) unp_defers;
126 static int unp_defers_count;
127
128 static const struct sockaddr    sun_noname = { sizeof(sun_noname), AF_LOCAL };
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  * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
147  * stream sockets, although the total for sender and receiver is actually
148  * only PIPSIZ.
149  *
150  * Datagram sockets really use the sendspace as the maximum datagram size,
151  * and don't really want to reserve the sendspace.  Their recvspace should be
152  * large enough for at least one max-size datagram plus address.
153  */
154 #ifndef PIPSIZ
155 #define PIPSIZ  8192
156 #endif
157 static u_long   unpst_sendspace = PIPSIZ;
158 static u_long   unpst_recvspace = PIPSIZ;
159 static u_long   unpdg_maxdgram = 2*1024;
160 static u_long   unpdg_recvspace = 16*1024;      /* support 8KB syslog msgs */
161 static u_long   unpsp_sendspace = PIPSIZ;       /* really max datagram size */
162 static u_long   unpsp_recvspace = PIPSIZ;
163
164 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
165     "Local domain");
166 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
167     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
168     "SOCK_STREAM");
169 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
170     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
171     "SOCK_DGRAM");
172 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
173     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
174     "SOCK_SEQPACKET");
175
176 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
177            &unpst_sendspace, 0, "Default stream send space.");
178 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
179            &unpst_recvspace, 0, "Default stream receive space.");
180 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
181            &unpdg_maxdgram, 0, "Maximum datagram size.");
182 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
183            &unpdg_recvspace, 0, "Default datagram receive space.");
184 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
185            &unpsp_sendspace, 0, "Default seqpacket send space.");
186 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
187            &unpsp_recvspace, 0, "Default seqpacket receive space.");
188 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
189     "File descriptors in flight.");
190 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
191     &unp_defers_count, 0,
192     "File descriptors deferred to taskqueue for close.");
193
194 /*
195  * Locking and synchronization:
196  *
197  * Several types of locks exist in the local domain socket implementation:
198  * - a global linkage lock
199  * - a global connection list lock
200  * - the mtxpool lock
201  * - per-unpcb mutexes
202  *
203  * The linkage lock protects the global socket lists, the generation number
204  * counter and garbage collector state.
205  *
206  * The connection list lock protects the list of referring sockets in a datagram
207  * socket PCB.  This lock is also overloaded to protect a global list of
208  * sockets whose buffers contain socket references in the form of SCM_RIGHTS
209  * messages.  To avoid recursion, such references are released by a dedicated
210  * thread.
211  *
212  * The mtxpool lock protects the vnode from being modified while referenced.
213  * Lock ordering rules require that it be acquired before any PCB locks.
214  *
215  * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
216  * unpcb.  This includes the unp_conn field, which either links two connected
217  * PCBs together (for connected socket types) or points at the destination
218  * socket (for connectionless socket types).  The operations of creating or
219  * destroying a connection therefore involve locking multiple PCBs.  To avoid
220  * lock order reversals, in some cases this involves dropping a PCB lock and
221  * using a reference counter to maintain liveness.
222  *
223  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
224  * allocated in pru_attach() and freed in pru_detach().  The validity of that
225  * pointer is an invariant, so no lock is required to dereference the so_pcb
226  * pointer if a valid socket reference is held by the caller.  In practice,
227  * this is always true during operations performed on a socket.  Each unpcb
228  * has a back-pointer to its socket, unp_socket, which will be stable under
229  * the same circumstances.
230  *
231  * This pointer may only be safely dereferenced as long as a valid reference
232  * to the unpcb is held.  Typically, this reference will be from the socket,
233  * or from another unpcb when the referring unpcb's lock is held (in order
234  * that the reference not be invalidated during use).  For example, to follow
235  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
236  * that detach is not run clearing unp_socket.
237  *
238  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
239  * protocols, bind() is a non-atomic operation, and connect() requires
240  * potential sleeping in the protocol, due to potentially waiting on local or
241  * distributed file systems.  We try to separate "lookup" operations, which
242  * may sleep, and the IPC operations themselves, which typically can occur
243  * with relative atomicity as locks can be held over the entire operation.
244  *
245  * Another tricky issue is simultaneous multi-threaded or multi-process
246  * access to a single UNIX domain socket.  These are handled by the flags
247  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
248  * binding, both of which involve dropping UNIX domain socket locks in order
249  * to perform namei() and other file system operations.
250  */
251 static struct rwlock    unp_link_rwlock;
252 static struct mtx       unp_defers_lock;
253
254 #define UNP_LINK_LOCK_INIT()            rw_init(&unp_link_rwlock,       \
255                                             "unp_link_rwlock")
256
257 #define UNP_LINK_LOCK_ASSERT()          rw_assert(&unp_link_rwlock,     \
258                                             RA_LOCKED)
259 #define UNP_LINK_UNLOCK_ASSERT()        rw_assert(&unp_link_rwlock,     \
260                                             RA_UNLOCKED)
261
262 #define UNP_LINK_RLOCK()                rw_rlock(&unp_link_rwlock)
263 #define UNP_LINK_RUNLOCK()              rw_runlock(&unp_link_rwlock)
264 #define UNP_LINK_WLOCK()                rw_wlock(&unp_link_rwlock)
265 #define UNP_LINK_WUNLOCK()              rw_wunlock(&unp_link_rwlock)
266 #define UNP_LINK_WLOCK_ASSERT()         rw_assert(&unp_link_rwlock,     \
267                                             RA_WLOCKED)
268 #define UNP_LINK_WOWNED()               rw_wowned(&unp_link_rwlock)
269
270 #define UNP_DEFERRED_LOCK_INIT()        mtx_init(&unp_defers_lock, \
271                                             "unp_defer", NULL, MTX_DEF)
272 #define UNP_DEFERRED_LOCK()             mtx_lock(&unp_defers_lock)
273 #define UNP_DEFERRED_UNLOCK()           mtx_unlock(&unp_defers_lock)
274
275 #define UNP_REF_LIST_LOCK()             UNP_DEFERRED_LOCK();
276 #define UNP_REF_LIST_UNLOCK()           UNP_DEFERRED_UNLOCK();
277
278 #define UNP_PCB_LOCK_INIT(unp)          mtx_init(&(unp)->unp_mtx,       \
279                                             "unp", "unp",       \
280                                             MTX_DUPOK|MTX_DEF)
281 #define UNP_PCB_LOCK_DESTROY(unp)       mtx_destroy(&(unp)->unp_mtx)
282 #define UNP_PCB_LOCKPTR(unp)            (&(unp)->unp_mtx)
283 #define UNP_PCB_LOCK(unp)               mtx_lock(&(unp)->unp_mtx)
284 #define UNP_PCB_TRYLOCK(unp)            mtx_trylock(&(unp)->unp_mtx)
285 #define UNP_PCB_UNLOCK(unp)             mtx_unlock(&(unp)->unp_mtx)
286 #define UNP_PCB_OWNED(unp)              mtx_owned(&(unp)->unp_mtx)
287 #define UNP_PCB_LOCK_ASSERT(unp)        mtx_assert(&(unp)->unp_mtx, MA_OWNED)
288 #define UNP_PCB_UNLOCK_ASSERT(unp)      mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
289
290 static int      uipc_connect2(struct socket *, struct socket *);
291 static int      uipc_ctloutput(struct socket *, struct sockopt *);
292 static int      unp_connect(struct socket *, struct sockaddr *,
293                     struct thread *);
294 static int      unp_connectat(int, struct socket *, struct sockaddr *,
295                     struct thread *, bool);
296 static void     unp_connect2(struct socket *so, struct socket *so2, int);
297 static void     unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
298 static void     unp_dispose(struct socket *so);
299 static void     unp_shutdown(struct unpcb *);
300 static void     unp_drop(struct unpcb *);
301 static void     unp_gc(__unused void *, int);
302 static void     unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
303 static void     unp_discard(struct file *);
304 static void     unp_freerights(struct filedescent **, int);
305 static int      unp_internalize(struct mbuf **, struct thread *);
306 static void     unp_internalize_fp(struct file *);
307 static int      unp_externalize(struct mbuf *, struct mbuf **, int);
308 static int      unp_externalize_fp(struct file *);
309 static struct mbuf      *unp_addsockcred(struct thread *, struct mbuf *, int);
310 static void     unp_process_defers(void * __unused, int);
311
312 static void
313 unp_pcb_hold(struct unpcb *unp)
314 {
315         u_int old __unused;
316
317         old = refcount_acquire(&unp->unp_refcount);
318         KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
319 }
320
321 static __result_use_check bool
322 unp_pcb_rele(struct unpcb *unp)
323 {
324         bool ret;
325
326         UNP_PCB_LOCK_ASSERT(unp);
327
328         if ((ret = refcount_release(&unp->unp_refcount))) {
329                 UNP_PCB_UNLOCK(unp);
330                 UNP_PCB_LOCK_DESTROY(unp);
331                 uma_zfree(unp_zone, unp);
332         }
333         return (ret);
334 }
335
336 static void
337 unp_pcb_rele_notlast(struct unpcb *unp)
338 {
339         bool ret __unused;
340
341         ret = refcount_release(&unp->unp_refcount);
342         KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
343 }
344
345 static void
346 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
347 {
348         UNP_PCB_UNLOCK_ASSERT(unp);
349         UNP_PCB_UNLOCK_ASSERT(unp2);
350
351         if (unp == unp2) {
352                 UNP_PCB_LOCK(unp);
353         } else if ((uintptr_t)unp2 > (uintptr_t)unp) {
354                 UNP_PCB_LOCK(unp);
355                 UNP_PCB_LOCK(unp2);
356         } else {
357                 UNP_PCB_LOCK(unp2);
358                 UNP_PCB_LOCK(unp);
359         }
360 }
361
362 static void
363 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
364 {
365         UNP_PCB_UNLOCK(unp);
366         if (unp != unp2)
367                 UNP_PCB_UNLOCK(unp2);
368 }
369
370 /*
371  * Try to lock the connected peer of an already locked socket.  In some cases
372  * this requires that we unlock the current socket.  The pairbusy counter is
373  * used to block concurrent connection attempts while the lock is dropped.  The
374  * caller must be careful to revalidate PCB state.
375  */
376 static struct unpcb *
377 unp_pcb_lock_peer(struct unpcb *unp)
378 {
379         struct unpcb *unp2;
380
381         UNP_PCB_LOCK_ASSERT(unp);
382         unp2 = unp->unp_conn;
383         if (unp2 == NULL)
384                 return (NULL);
385         if (__predict_false(unp == unp2))
386                 return (unp);
387
388         UNP_PCB_UNLOCK_ASSERT(unp2);
389
390         if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
391                 return (unp2);
392         if ((uintptr_t)unp2 > (uintptr_t)unp) {
393                 UNP_PCB_LOCK(unp2);
394                 return (unp2);
395         }
396         unp->unp_pairbusy++;
397         unp_pcb_hold(unp2);
398         UNP_PCB_UNLOCK(unp);
399
400         UNP_PCB_LOCK(unp2);
401         UNP_PCB_LOCK(unp);
402         KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
403             ("%s: socket %p was reconnected", __func__, unp));
404         if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
405                 unp->unp_flags &= ~UNP_WAITING;
406                 wakeup(unp);
407         }
408         if (unp_pcb_rele(unp2)) {
409                 /* unp2 is unlocked. */
410                 return (NULL);
411         }
412         if (unp->unp_conn == NULL) {
413                 UNP_PCB_UNLOCK(unp2);
414                 return (NULL);
415         }
416         return (unp2);
417 }
418
419 /*
420  * Definitions of protocols supported in the LOCAL domain.
421  */
422 static struct domain localdomain;
423 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
424 static struct pr_usrreqs uipc_usrreqs_seqpacket;
425 static struct protosw localsw[] = {
426 {
427         .pr_type =              SOCK_STREAM,
428         .pr_domain =            &localdomain,
429         .pr_flags =             PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|
430                                     PR_CAPATTACH,
431         .pr_ctloutput =         &uipc_ctloutput,
432         .pr_usrreqs =           &uipc_usrreqs_stream
433 },
434 {
435         .pr_type =              SOCK_DGRAM,
436         .pr_domain =            &localdomain,
437         .pr_flags =             PR_ATOMIC | PR_ADDR |PR_RIGHTS | PR_CAPATTACH |
438                                     PR_SOCKBUF,
439         .pr_ctloutput =         &uipc_ctloutput,
440         .pr_usrreqs =           &uipc_usrreqs_dgram
441 },
442 {
443         .pr_type =              SOCK_SEQPACKET,
444         .pr_domain =            &localdomain,
445
446         /*
447          * XXXRW: For now, PR_ADDR because soreceive will bump into them
448          * due to our use of sbappendaddr.  A new sbappend variants is needed
449          * that supports both atomic record writes and control data.
450          */
451         .pr_flags =             PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|
452                                     PR_WANTRCVD|PR_RIGHTS|PR_CAPATTACH,
453         .pr_ctloutput =         &uipc_ctloutput,
454         .pr_usrreqs =           &uipc_usrreqs_seqpacket,
455 },
456 };
457
458 static struct domain localdomain = {
459         .dom_family =           AF_LOCAL,
460         .dom_name =             "local",
461         .dom_externalize =      unp_externalize,
462         .dom_dispose =          unp_dispose,
463         .dom_protosw =          localsw,
464         .dom_protoswNPROTOSW =  &localsw[nitems(localsw)]
465 };
466 DOMAIN_SET(local);
467
468 static void
469 uipc_abort(struct socket *so)
470 {
471         struct unpcb *unp, *unp2;
472
473         unp = sotounpcb(so);
474         KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
475         UNP_PCB_UNLOCK_ASSERT(unp);
476
477         UNP_PCB_LOCK(unp);
478         unp2 = unp->unp_conn;
479         if (unp2 != NULL) {
480                 unp_pcb_hold(unp2);
481                 UNP_PCB_UNLOCK(unp);
482                 unp_drop(unp2);
483         } else
484                 UNP_PCB_UNLOCK(unp);
485 }
486
487 static int
488 uipc_accept(struct socket *so, struct sockaddr **nam)
489 {
490         struct unpcb *unp, *unp2;
491         const struct sockaddr *sa;
492
493         /*
494          * Pass back name of connected socket, if it was bound and we are
495          * still connected (our peer may have closed already!).
496          */
497         unp = sotounpcb(so);
498         KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
499
500         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
501         UNP_PCB_LOCK(unp);
502         unp2 = unp_pcb_lock_peer(unp);
503         if (unp2 != NULL && unp2->unp_addr != NULL)
504                 sa = (struct sockaddr *)unp2->unp_addr;
505         else
506                 sa = &sun_noname;
507         bcopy(sa, *nam, sa->sa_len);
508         if (unp2 != NULL)
509                 unp_pcb_unlock_pair(unp, unp2);
510         else
511                 UNP_PCB_UNLOCK(unp);
512         return (0);
513 }
514
515 static int
516 uipc_attach(struct socket *so, int proto, struct thread *td)
517 {
518         u_long sendspace, recvspace;
519         struct unpcb *unp;
520         int error;
521         bool locked;
522
523         KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
524         if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
525                 switch (so->so_type) {
526                 case SOCK_STREAM:
527                         sendspace = unpst_sendspace;
528                         recvspace = unpst_recvspace;
529                         break;
530
531                 case SOCK_DGRAM:
532                         STAILQ_INIT(&so->so_rcv.uxdg_mb);
533                         sendspace = unpdg_maxdgram;
534                         recvspace = unpdg_recvspace;
535                         break;
536
537                 case SOCK_SEQPACKET:
538                         sendspace = unpsp_sendspace;
539                         recvspace = unpsp_recvspace;
540                         break;
541
542                 default:
543                         panic("uipc_attach");
544                 }
545                 error = soreserve(so, sendspace, recvspace);
546                 if (error)
547                         return (error);
548         }
549         unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
550         if (unp == NULL)
551                 return (ENOBUFS);
552         LIST_INIT(&unp->unp_refs);
553         UNP_PCB_LOCK_INIT(unp);
554         unp->unp_socket = so;
555         so->so_pcb = unp;
556         refcount_init(&unp->unp_refcount, 1);
557
558         if ((locked = UNP_LINK_WOWNED()) == false)
559                 UNP_LINK_WLOCK();
560
561         unp->unp_gencnt = ++unp_gencnt;
562         unp->unp_ino = ++unp_ino;
563         unp_count++;
564         switch (so->so_type) {
565         case SOCK_STREAM:
566                 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
567                 break;
568
569         case SOCK_DGRAM:
570                 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
571                 break;
572
573         case SOCK_SEQPACKET:
574                 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
575                 break;
576
577         default:
578                 panic("uipc_attach");
579         }
580
581         if (locked == false)
582                 UNP_LINK_WUNLOCK();
583
584         return (0);
585 }
586
587 static int
588 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
589 {
590         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
591         struct vattr vattr;
592         int error, namelen;
593         struct nameidata nd;
594         struct unpcb *unp;
595         struct vnode *vp;
596         struct mount *mp;
597         cap_rights_t rights;
598         char *buf;
599
600         if (nam->sa_family != AF_UNIX)
601                 return (EAFNOSUPPORT);
602
603         unp = sotounpcb(so);
604         KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
605
606         if (soun->sun_len > sizeof(struct sockaddr_un))
607                 return (EINVAL);
608         namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
609         if (namelen <= 0)
610                 return (EINVAL);
611
612         /*
613          * We don't allow simultaneous bind() calls on a single UNIX domain
614          * socket, so flag in-progress operations, and return an error if an
615          * operation is already in progress.
616          *
617          * Historically, we have not allowed a socket to be rebound, so this
618          * also returns an error.  Not allowing re-binding simplifies the
619          * implementation and avoids a great many possible failure modes.
620          */
621         UNP_PCB_LOCK(unp);
622         if (unp->unp_vnode != NULL) {
623                 UNP_PCB_UNLOCK(unp);
624                 return (EINVAL);
625         }
626         if (unp->unp_flags & UNP_BINDING) {
627                 UNP_PCB_UNLOCK(unp);
628                 return (EALREADY);
629         }
630         unp->unp_flags |= UNP_BINDING;
631         UNP_PCB_UNLOCK(unp);
632
633         buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
634         bcopy(soun->sun_path, buf, namelen);
635         buf[namelen] = 0;
636
637 restart:
638         NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
639             UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
640 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
641         error = namei(&nd);
642         if (error)
643                 goto error;
644         vp = nd.ni_vp;
645         if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
646                 NDFREE_PNBUF(&nd);
647                 if (nd.ni_dvp == vp)
648                         vrele(nd.ni_dvp);
649                 else
650                         vput(nd.ni_dvp);
651                 if (vp != NULL) {
652                         vrele(vp);
653                         error = EADDRINUSE;
654                         goto error;
655                 }
656                 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
657                 if (error)
658                         goto error;
659                 goto restart;
660         }
661         VATTR_NULL(&vattr);
662         vattr.va_type = VSOCK;
663         vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
664 #ifdef MAC
665         error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
666             &vattr);
667 #endif
668         if (error == 0)
669                 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
670         NDFREE_PNBUF(&nd);
671         if (error) {
672                 VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
673                 vn_finished_write(mp);
674                 if (error == ERELOOKUP)
675                         goto restart;
676                 goto error;
677         }
678         vp = nd.ni_vp;
679         ASSERT_VOP_ELOCKED(vp, "uipc_bind");
680         soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
681
682         UNP_PCB_LOCK(unp);
683         VOP_UNP_BIND(vp, unp);
684         unp->unp_vnode = vp;
685         unp->unp_addr = soun;
686         unp->unp_flags &= ~UNP_BINDING;
687         UNP_PCB_UNLOCK(unp);
688         vref(vp);
689         VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
690         vn_finished_write(mp);
691         free(buf, M_TEMP);
692         return (0);
693
694 error:
695         UNP_PCB_LOCK(unp);
696         unp->unp_flags &= ~UNP_BINDING;
697         UNP_PCB_UNLOCK(unp);
698         free(buf, M_TEMP);
699         return (error);
700 }
701
702 static int
703 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
704 {
705
706         return (uipc_bindat(AT_FDCWD, so, nam, td));
707 }
708
709 static int
710 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
711 {
712         int error;
713
714         KASSERT(td == curthread, ("uipc_connect: td != curthread"));
715         error = unp_connect(so, nam, td);
716         return (error);
717 }
718
719 static int
720 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
721     struct thread *td)
722 {
723         int error;
724
725         KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
726         error = unp_connectat(fd, so, nam, td, false);
727         return (error);
728 }
729
730 static void
731 uipc_close(struct socket *so)
732 {
733         struct unpcb *unp, *unp2;
734         struct vnode *vp = NULL;
735         struct mtx *vplock;
736
737         unp = sotounpcb(so);
738         KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
739
740         vplock = NULL;
741         if ((vp = unp->unp_vnode) != NULL) {
742                 vplock = mtx_pool_find(mtxpool_sleep, vp);
743                 mtx_lock(vplock);
744         }
745         UNP_PCB_LOCK(unp);
746         if (vp && unp->unp_vnode == NULL) {
747                 mtx_unlock(vplock);
748                 vp = NULL;
749         }
750         if (vp != NULL) {
751                 VOP_UNP_DETACH(vp);
752                 unp->unp_vnode = NULL;
753         }
754         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
755                 unp_disconnect(unp, unp2);
756         else
757                 UNP_PCB_UNLOCK(unp);
758         if (vp) {
759                 mtx_unlock(vplock);
760                 vrele(vp);
761         }
762 }
763
764 static int
765 uipc_connect2(struct socket *so1, struct socket *so2)
766 {
767         struct unpcb *unp, *unp2;
768
769         if (so1->so_type != so2->so_type)
770                 return (EPROTOTYPE);
771
772         unp = so1->so_pcb;
773         KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
774         unp2 = so2->so_pcb;
775         KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
776         unp_pcb_lock_pair(unp, unp2);
777         unp_connect2(so1, so2, PRU_CONNECT2);
778         unp_pcb_unlock_pair(unp, unp2);
779
780         return (0);
781 }
782
783 static void
784 uipc_detach(struct socket *so)
785 {
786         struct unpcb *unp, *unp2;
787         struct mtx *vplock;
788         struct vnode *vp;
789         int local_unp_rights;
790
791         unp = sotounpcb(so);
792         KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
793
794         vp = NULL;
795         vplock = NULL;
796
797         UNP_LINK_WLOCK();
798         LIST_REMOVE(unp, unp_link);
799         if (unp->unp_gcflag & UNPGC_DEAD)
800                 LIST_REMOVE(unp, unp_dead);
801         unp->unp_gencnt = ++unp_gencnt;
802         --unp_count;
803         UNP_LINK_WUNLOCK();
804
805         UNP_PCB_UNLOCK_ASSERT(unp);
806  restart:
807         if ((vp = unp->unp_vnode) != NULL) {
808                 vplock = mtx_pool_find(mtxpool_sleep, vp);
809                 mtx_lock(vplock);
810         }
811         UNP_PCB_LOCK(unp);
812         if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
813                 if (vplock)
814                         mtx_unlock(vplock);
815                 UNP_PCB_UNLOCK(unp);
816                 goto restart;
817         }
818         if ((vp = unp->unp_vnode) != NULL) {
819                 VOP_UNP_DETACH(vp);
820                 unp->unp_vnode = NULL;
821         }
822         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
823                 unp_disconnect(unp, unp2);
824         else
825                 UNP_PCB_UNLOCK(unp);
826
827         UNP_REF_LIST_LOCK();
828         while (!LIST_EMPTY(&unp->unp_refs)) {
829                 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
830
831                 unp_pcb_hold(ref);
832                 UNP_REF_LIST_UNLOCK();
833
834                 MPASS(ref != unp);
835                 UNP_PCB_UNLOCK_ASSERT(ref);
836                 unp_drop(ref);
837                 UNP_REF_LIST_LOCK();
838         }
839         UNP_REF_LIST_UNLOCK();
840
841         UNP_PCB_LOCK(unp);
842         local_unp_rights = unp_rights;
843         unp->unp_socket->so_pcb = NULL;
844         unp->unp_socket = NULL;
845         free(unp->unp_addr, M_SONAME);
846         unp->unp_addr = NULL;
847         if (!unp_pcb_rele(unp))
848                 UNP_PCB_UNLOCK(unp);
849         if (vp) {
850                 mtx_unlock(vplock);
851                 vrele(vp);
852         }
853         if (local_unp_rights)
854                 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
855
856         switch (so->so_type) {
857         case SOCK_DGRAM:
858                 /*
859                  * Everything should have been unlinked/freed by unp_dispose().
860                  */
861                 MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb));
862         }
863 }
864
865 static int
866 uipc_disconnect(struct socket *so)
867 {
868         struct unpcb *unp, *unp2;
869
870         unp = sotounpcb(so);
871         KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
872
873         UNP_PCB_LOCK(unp);
874         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
875                 unp_disconnect(unp, unp2);
876         else
877                 UNP_PCB_UNLOCK(unp);
878         return (0);
879 }
880
881 static int
882 uipc_listen(struct socket *so, int backlog, struct thread *td)
883 {
884         struct unpcb *unp;
885         int error;
886
887         MPASS(so->so_type != SOCK_DGRAM);
888
889         /*
890          * Synchronize with concurrent connection attempts.
891          */
892         error = 0;
893         unp = sotounpcb(so);
894         UNP_PCB_LOCK(unp);
895         if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
896                 error = EINVAL;
897         else if (unp->unp_vnode == NULL)
898                 error = EDESTADDRREQ;
899         if (error != 0) {
900                 UNP_PCB_UNLOCK(unp);
901                 return (error);
902         }
903
904         SOCK_LOCK(so);
905         error = solisten_proto_check(so);
906         if (error == 0) {
907                 cru2xt(td, &unp->unp_peercred);
908                 solisten_proto(so, backlog);
909         }
910         SOCK_UNLOCK(so);
911         UNP_PCB_UNLOCK(unp);
912         return (error);
913 }
914
915 static int
916 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
917 {
918         struct unpcb *unp, *unp2;
919         const struct sockaddr *sa;
920
921         unp = sotounpcb(so);
922         KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
923
924         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
925         UNP_LINK_RLOCK();
926         /*
927          * XXX: It seems that this test always fails even when connection is
928          * established.  So, this else clause is added as workaround to
929          * return PF_LOCAL sockaddr.
930          */
931         unp2 = unp->unp_conn;
932         if (unp2 != NULL) {
933                 UNP_PCB_LOCK(unp2);
934                 if (unp2->unp_addr != NULL)
935                         sa = (struct sockaddr *) unp2->unp_addr;
936                 else
937                         sa = &sun_noname;
938                 bcopy(sa, *nam, sa->sa_len);
939                 UNP_PCB_UNLOCK(unp2);
940         } else {
941                 sa = &sun_noname;
942                 bcopy(sa, *nam, sa->sa_len);
943         }
944         UNP_LINK_RUNLOCK();
945         return (0);
946 }
947
948 static int
949 uipc_rcvd(struct socket *so, int flags)
950 {
951         struct unpcb *unp, *unp2;
952         struct socket *so2;
953         u_int mbcnt, sbcc;
954
955         unp = sotounpcb(so);
956         KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
957         KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
958             ("%s: socktype %d", __func__, so->so_type));
959
960         /*
961          * Adjust backpressure on sender and wakeup any waiting to write.
962          *
963          * The unp lock is acquired to maintain the validity of the unp_conn
964          * pointer; no lock on unp2 is required as unp2->unp_socket will be
965          * static as long as we don't permit unp2 to disconnect from unp,
966          * which is prevented by the lock on unp.  We cache values from
967          * so_rcv to avoid holding the so_rcv lock over the entire
968          * transaction on the remote so_snd.
969          */
970         SOCKBUF_LOCK(&so->so_rcv);
971         mbcnt = so->so_rcv.sb_mbcnt;
972         sbcc = sbavail(&so->so_rcv);
973         SOCKBUF_UNLOCK(&so->so_rcv);
974         /*
975          * There is a benign race condition at this point.  If we're planning to
976          * clear SB_STOP, but uipc_send is called on the connected socket at
977          * this instant, it might add data to the sockbuf and set SB_STOP.  Then
978          * we would erroneously clear SB_STOP below, even though the sockbuf is
979          * full.  The race is benign because the only ill effect is to allow the
980          * sockbuf to exceed its size limit, and the size limits are not
981          * strictly guaranteed anyway.
982          */
983         UNP_PCB_LOCK(unp);
984         unp2 = unp->unp_conn;
985         if (unp2 == NULL) {
986                 UNP_PCB_UNLOCK(unp);
987                 return (0);
988         }
989         so2 = unp2->unp_socket;
990         SOCKBUF_LOCK(&so2->so_snd);
991         if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
992                 so2->so_snd.sb_flags &= ~SB_STOP;
993         sowwakeup_locked(so2);
994         UNP_PCB_UNLOCK(unp);
995         return (0);
996 }
997
998 static int
999 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1000     struct mbuf *control, struct thread *td)
1001 {
1002         struct unpcb *unp, *unp2;
1003         struct socket *so2;
1004         u_int mbcnt, sbcc;
1005         int error;
1006
1007         unp = sotounpcb(so);
1008         KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
1009         KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
1010             ("%s: socktype %d", __func__, so->so_type));
1011
1012         error = 0;
1013         if (flags & PRUS_OOB) {
1014                 error = EOPNOTSUPP;
1015                 goto release;
1016         }
1017         if (control != NULL && (error = unp_internalize(&control, td)))
1018                 goto release;
1019
1020         unp2 = NULL;
1021         if ((so->so_state & SS_ISCONNECTED) == 0) {
1022                 if (nam != NULL) {
1023                         if ((error = unp_connect(so, nam, td)) != 0)
1024                                 goto out;
1025                 } else {
1026                         error = ENOTCONN;
1027                         goto out;
1028                 }
1029         }
1030
1031         UNP_PCB_LOCK(unp);
1032         if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
1033                 UNP_PCB_UNLOCK(unp);
1034                 error = ENOTCONN;
1035                 goto out;
1036         } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1037                 unp_pcb_unlock_pair(unp, unp2);
1038                 error = EPIPE;
1039                 goto out;
1040         }
1041         UNP_PCB_UNLOCK(unp);
1042         if ((so2 = unp2->unp_socket) == NULL) {
1043                 UNP_PCB_UNLOCK(unp2);
1044                 error = ENOTCONN;
1045                 goto out;
1046         }
1047         SOCKBUF_LOCK(&so2->so_rcv);
1048         if (unp2->unp_flags & UNP_WANTCRED_MASK) {
1049                 /*
1050                  * Credentials are passed only once on SOCK_STREAM and
1051                  * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
1052                  * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
1053                  */
1054                 control = unp_addsockcred(td, control, unp2->unp_flags);
1055                 unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
1056         }
1057
1058         /*
1059          * Send to paired receive port and wake up readers.  Don't
1060          * check for space available in the receive buffer if we're
1061          * attaching ancillary data; Unix domain sockets only check
1062          * for space in the sending sockbuf, and that check is
1063          * performed one level up the stack.  At that level we cannot
1064          * precisely account for the amount of buffer space used
1065          * (e.g., because control messages are not yet internalized).
1066          */
1067         switch (so->so_type) {
1068         case SOCK_STREAM:
1069                 if (control != NULL) {
1070                         sbappendcontrol_locked(&so2->so_rcv, m,
1071                             control, flags);
1072                         control = NULL;
1073                 } else
1074                         sbappend_locked(&so2->so_rcv, m, flags);
1075                 break;
1076
1077         case SOCK_SEQPACKET:
1078                 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1079                     &sun_noname, m, control))
1080                         control = NULL;
1081                 break;
1082         }
1083
1084         mbcnt = so2->so_rcv.sb_mbcnt;
1085         sbcc = sbavail(&so2->so_rcv);
1086         if (sbcc)
1087                 sorwakeup_locked(so2);
1088         else
1089                 SOCKBUF_UNLOCK(&so2->so_rcv);
1090
1091         /*
1092          * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1093          * it would be possible for uipc_rcvd to be called at this
1094          * point, drain the receiving sockbuf, clear SB_STOP, and then
1095          * we would set SB_STOP below.  That could lead to an empty
1096          * sockbuf having SB_STOP set
1097          */
1098         SOCKBUF_LOCK(&so->so_snd);
1099         if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1100                 so->so_snd.sb_flags |= SB_STOP;
1101         SOCKBUF_UNLOCK(&so->so_snd);
1102         UNP_PCB_UNLOCK(unp2);
1103         m = NULL;
1104 out:
1105         /*
1106          * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1107          */
1108         if (flags & PRUS_EOF) {
1109                 UNP_PCB_LOCK(unp);
1110                 socantsendmore(so);
1111                 unp_shutdown(unp);
1112                 UNP_PCB_UNLOCK(unp);
1113         }
1114         if (control != NULL && error != 0)
1115                 unp_scan(control, unp_freerights);
1116
1117 release:
1118         if (control != NULL)
1119                 m_freem(control);
1120         /*
1121          * In case of PRUS_NOTREADY, uipc_ready() is responsible
1122          * for freeing memory.
1123          */   
1124         if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1125                 m_freem(m);
1126         return (error);
1127 }
1128
1129 /*
1130  * PF_UNIX/SOCK_DGRAM send
1131  *
1132  * Allocate a record consisting of 3 mbufs in the sequence of
1133  * from -> control -> data and append it to the socket buffer.
1134  */
1135 static int
1136 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1137     struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
1138 {
1139         struct unpcb *unp, *unp2;
1140         const struct sockaddr *from;
1141         struct socket *so2;
1142         struct sockbuf *sb;
1143         struct mbuf *f;
1144         u_int cc;
1145         int error;
1146
1147         MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
1148
1149         error = 0;
1150         f = NULL;
1151
1152         if (__predict_false(flags & MSG_OOB)) {
1153                 error = EOPNOTSUPP;
1154                 goto out;
1155         }
1156         if (m == NULL) {
1157                 if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
1158                         error = EMSGSIZE;
1159                         goto out;
1160                 }
1161                 m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
1162                 if (__predict_false(m == NULL)) {
1163                         error = EFAULT;
1164                         goto out;
1165                 }
1166                 f = m_get(M_WAITOK, MT_SONAME);
1167                 if (c != NULL && (error = unp_internalize(&c, td)))
1168                         goto out;
1169         } else {
1170                 /* pru_sosend() with mbuf usually is a kernel thread. */
1171
1172                 M_ASSERTPKTHDR(m);
1173                 if (__predict_false(c != NULL))
1174                         panic("%s: control from a kernel thread", __func__);
1175
1176                 if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
1177                         error = EMSGSIZE;
1178                         goto out;
1179                 }
1180                 if ((f = m_get(M_NOWAIT, MT_SONAME)) == NULL) {
1181                         error = ENOBUFS;
1182                         goto out;
1183                 }
1184                 /* Condition the foreign mbuf to our standards. */
1185                 m_clrprotoflags(m);
1186                 m_tag_delete_chain(m, NULL);
1187                 m->m_pkthdr.rcvif = NULL;
1188                 m->m_pkthdr.flowid = 0;
1189                 m->m_pkthdr.csum_flags = 0;
1190                 m->m_pkthdr.fibnum = 0;
1191                 m->m_pkthdr.rsstype = 0;
1192         }
1193
1194         unp = sotounpcb(so);
1195         MPASS(unp);
1196
1197         /*
1198          * XXXGL: would be cool to fully remove so_snd out of the equation
1199          * and avoid this lock, which is not only extraneous, but also being
1200          * released, thus still leaving possibility for a race.  We can easily
1201          * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
1202          * is more difficult to invent something to handle so_error.
1203          */
1204         error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1205         if (error)
1206                 goto out2;
1207         SOCK_SENDBUF_LOCK(so);
1208         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1209                 SOCK_SENDBUF_UNLOCK(so);
1210                 error = EPIPE;
1211                 goto out3;
1212         }
1213         if (so->so_error != 0) {
1214                 error = so->so_error;
1215                 so->so_error = 0;
1216                 SOCK_SENDBUF_UNLOCK(so);
1217                 goto out3;
1218         }
1219         if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
1220                 SOCK_SENDBUF_UNLOCK(so);
1221                 error = EDESTADDRREQ;
1222                 goto out3;
1223         }
1224         SOCK_SENDBUF_UNLOCK(so);
1225
1226         if (addr != NULL) {
1227                 if ((error = unp_connectat(AT_FDCWD, so, addr, td, true)))
1228                         goto out3;
1229                 UNP_PCB_LOCK_ASSERT(unp);
1230                 unp2 = unp->unp_conn;
1231                 UNP_PCB_LOCK_ASSERT(unp2);
1232         } else {
1233                 UNP_PCB_LOCK(unp);
1234                 unp2 = unp_pcb_lock_peer(unp);
1235                 if (unp2 == NULL) {
1236                         UNP_PCB_UNLOCK(unp);
1237                         error = ENOTCONN;
1238                         goto out3;
1239                 }
1240         }
1241
1242         if (unp2->unp_flags & UNP_WANTCRED_MASK)
1243                 c = unp_addsockcred(td, c, unp2->unp_flags);
1244         if (unp->unp_addr != NULL)
1245                 from = (struct sockaddr *)unp->unp_addr;
1246         else
1247                 from = &sun_noname;
1248         f->m_len = from->sa_len;
1249         MPASS(from->sa_len <= MLEN);
1250         bcopy(from, mtod(f, void *), from->sa_len);
1251         cc = f->m_len + m->m_pkthdr.len;
1252
1253         /* Concatenate: from -> control -> data. */
1254         if (c != NULL) {
1255                 struct mbuf *clast;
1256
1257                 cc += m_length(c, &clast);
1258                 f->m_next = c;
1259                 clast->m_next = m;
1260                 c = NULL;
1261         } else
1262                 f->m_next = m;
1263         m = NULL;
1264
1265         so2 = unp2->unp_socket;
1266         sb = &so2->so_rcv;
1267         SOCK_RECVBUF_LOCK(so2);
1268         if (cc <= sbspace(sb)) {
1269                 STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
1270                 /* XXX: would be nice if m_uiotombuf() returns count. */
1271                 for (; f != NULL ; f = f->m_next) {
1272                         if (f->m_type != MT_DATA)
1273                                 sb->sb_ctl += f->m_len;
1274                         sb->sb_mbcnt += MSIZE;
1275                         if (f->m_flags & M_EXT)
1276                                 sb->sb_mbcnt += f->m_ext.ext_size;
1277                 }
1278                 sb->sb_acc += cc;
1279                 sb->sb_ccc += cc;
1280                 sorwakeup_locked(so2);
1281         } else {
1282                 soroverflow_locked(so2);
1283                 error = (so->so_state & SS_NBIO) ? EAGAIN : ENOBUFS;
1284         }
1285
1286         if (addr != NULL)
1287                 unp_disconnect(unp, unp2);
1288         else
1289                 unp_pcb_unlock_pair(unp, unp2);
1290
1291         td->td_ru.ru_msgsnd++;
1292
1293 out3:
1294         SOCK_IO_SEND_UNLOCK(so);
1295 out2:
1296         if (c)
1297                 unp_scan(c, unp_freerights);
1298 out:
1299         if (f)
1300                 m_freem(f);
1301         if (c)
1302                 m_freem(c);
1303         if (m)
1304                 m_freem(m);
1305
1306         return (error);
1307 }
1308
1309 /*
1310  * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK
1311  */
1312 static int
1313 uipc_peek_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1314     struct mbuf **controlp, int *flagsp)
1315 {
1316         struct mbuf *m;
1317         ssize_t len;
1318         int error;
1319
1320         SOCK_RECVBUF_UNLOCK(so);
1321
1322         m = STAILQ_FIRST(&so->so_rcv.uxdg_mb);
1323         KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1324         if (psa != NULL)
1325                 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1326
1327         m = m->m_next;
1328         KASSERT(m, ("%s: no data or control after soname", __func__));
1329
1330         /*
1331          * With MSG_PEEK the control isn't executed, just copied.
1332          */
1333         while (m != NULL && m->m_type == MT_CONTROL) {
1334                 if (controlp != NULL) {
1335                         *controlp = m_copym(m, 0, m->m_len, M_WAITOK);
1336                         controlp = &(*controlp)->m_next;
1337                 }
1338                 m = m->m_next;
1339         }
1340         KASSERT(m == NULL || m->m_type == MT_DATA,
1341             ("%s: not MT_DATA mbuf %p", __func__, m));
1342         while (m != NULL && uio->uio_resid > 0) {
1343                 len = uio->uio_resid;
1344                 if (len > m->m_len)
1345                         len = m->m_len;
1346                 error = uiomove(mtod(m, char *), (int)len, uio);
1347                 if (error) {
1348                         SOCK_IO_RECV_UNLOCK(so);
1349                         return (error);
1350                 }
1351                 if (len == m->m_len)
1352                         m = m->m_next;
1353         }
1354         SOCK_IO_RECV_UNLOCK(so);
1355
1356         if (m != NULL && flagsp != NULL)
1357                 *flagsp |= MSG_TRUNC;
1358
1359         return (0);
1360 }
1361
1362 /*
1363  * PF_UNIX/SOCK_DGRAM receive
1364  */
1365 static int
1366 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1367     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1368 {
1369         struct mbuf *m, *m2;
1370         int flags, error;
1371         ssize_t len;
1372         bool nonblock;
1373
1374         MPASS(mp0 == NULL);
1375
1376         if (psa != NULL)
1377                 *psa = NULL;
1378         if (controlp != NULL)
1379                 *controlp = NULL;
1380
1381         flags = flagsp != NULL ? *flagsp : 0;
1382         nonblock = (so->so_state & SS_NBIO) ||
1383             (flags & (MSG_DONTWAIT | MSG_NBIO));
1384
1385         error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
1386         if (__predict_false(error))
1387                 return (error);
1388
1389         /*
1390          * Loop blocking while waiting for a datagram.
1391          */
1392         SOCK_RECVBUF_LOCK(so);
1393         while ((m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
1394                 KASSERT(sbavail(&so->so_rcv) == 0,
1395                     ("soreceive_dgram: sb_mb NULL but sbavail %u",
1396                     sbavail(&so->so_rcv)));
1397                 if (so->so_error) {
1398                         error = so->so_error;
1399                         so->so_error = 0;
1400                         SOCK_RECVBUF_UNLOCK(so);
1401                         SOCK_IO_RECV_UNLOCK(so);
1402                         return (error);
1403                 }
1404                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1405                     uio->uio_resid == 0) {
1406                         SOCK_RECVBUF_UNLOCK(so);
1407                         SOCK_IO_RECV_UNLOCK(so);
1408                         return (0);
1409                 }
1410                 if (nonblock) {
1411                         SOCK_RECVBUF_UNLOCK(so);
1412                         SOCK_IO_RECV_UNLOCK(so);
1413                         return (EWOULDBLOCK);
1414                 }
1415                 error = sbwait(so, SO_RCV);
1416                 if (error) {
1417                         SOCK_RECVBUF_UNLOCK(so);
1418                         SOCK_IO_RECV_UNLOCK(so);
1419                         return (error);
1420                 }
1421         }
1422         SOCK_RECVBUF_LOCK_ASSERT(so);
1423
1424         if (uio->uio_td)
1425                 uio->uio_td->td_ru.ru_msgrcv++;
1426
1427         if (__predict_false(flags & MSG_PEEK))
1428                 return (uipc_peek_dgram(so, psa, uio, controlp, flagsp));
1429
1430         STAILQ_REMOVE_HEAD(&so->so_rcv.uxdg_mb, m_stailqpkt);
1431         for (m2 = m; m2 != NULL; m2 = m2->m_next) {
1432                 if (m2->m_type != MT_DATA)
1433                         so->so_rcv.sb_ctl -= m2->m_len;
1434                 so->so_rcv.sb_acc -= m2->m_len;
1435                 so->so_rcv.sb_ccc -= m2->m_len;
1436                 so->so_rcv.sb_mbcnt -= MSIZE;
1437                 if (m2->m_flags & M_EXT)
1438                         so->so_rcv.sb_mbcnt -= m2->m_ext.ext_size;
1439         }
1440         SOCK_RECVBUF_UNLOCK(so);
1441
1442         KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1443         if (psa != NULL)
1444                 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1445         m = m_free(m);
1446         KASSERT(m, ("%s: no data or control after soname", __func__));
1447
1448         /*
1449          * Packet to copyout() is now in 'm' and it is disconnected from the
1450          * queue.
1451          *
1452          * Process one or more MT_CONTROL mbufs present before any data mbufs
1453          * in the first mbuf chain on the socket buffer.  We call into the
1454          * unp_externalize() to perform externalization (or freeing if
1455          * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
1456          * without MT_DATA mbufs.
1457          */
1458         while (m != NULL && m->m_type == MT_CONTROL) {
1459                 struct mbuf *cm;
1460
1461                 /* XXXGL: unp_externalize() is also dom_externalize() KBI and
1462                  * it frees whole chain, so we must disconnect the mbuf.
1463                  */
1464                 cm = m; m = m->m_next; cm->m_next = NULL;
1465                 error = unp_externalize(cm, controlp, flags);
1466                 if (error != 0) {
1467                         SOCK_IO_RECV_UNLOCK(so);
1468                         unp_scan(m, unp_freerights);
1469                         m_freem(m);
1470                         return (error);
1471                 }
1472                 if (controlp != NULL) {
1473                         while (*controlp != NULL)
1474                                 controlp = &(*controlp)->m_next;
1475                 }
1476         }
1477         KASSERT(m == NULL || m->m_type == MT_DATA,
1478             ("%s: not MT_DATA mbuf %p", __func__, m));
1479         while (m != NULL && uio->uio_resid > 0) {
1480                 len = uio->uio_resid;
1481                 if (len > m->m_len)
1482                         len = m->m_len;
1483                 error = uiomove(mtod(m, char *), (int)len, uio);
1484                 if (error) {
1485                         SOCK_IO_RECV_UNLOCK(so);
1486                         m_freem(m);
1487                         return (error);
1488                 }
1489                 if (len == m->m_len)
1490                         m = m_free(m);
1491                 else {
1492                         m->m_data += len;
1493                         m->m_len -= len;
1494                 }
1495         }
1496         SOCK_IO_RECV_UNLOCK(so);
1497
1498         if (m != NULL) {
1499                 flags |= MSG_TRUNC;
1500                 m_freem(m);
1501         }
1502         if (flagsp != NULL)
1503                 *flagsp |= flags;
1504
1505         return (0);
1506 }
1507
1508 static bool
1509 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1510 {
1511         struct mbuf *mb, *n;
1512         struct sockbuf *sb;
1513
1514         SOCK_LOCK(so);
1515         if (SOLISTENING(so)) {
1516                 SOCK_UNLOCK(so);
1517                 return (false);
1518         }
1519         mb = NULL;
1520         sb = &so->so_rcv;
1521         SOCKBUF_LOCK(sb);
1522         if (sb->sb_fnrdy != NULL) {
1523                 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1524                         if (mb == m) {
1525                                 *errorp = sbready(sb, m, count);
1526                                 break;
1527                         }
1528                         mb = mb->m_next;
1529                         if (mb == NULL) {
1530                                 mb = n;
1531                                 if (mb != NULL)
1532                                         n = mb->m_nextpkt;
1533                         }
1534                 }
1535         }
1536         SOCKBUF_UNLOCK(sb);
1537         SOCK_UNLOCK(so);
1538         return (mb != NULL);
1539 }
1540
1541 static int
1542 uipc_ready(struct socket *so, struct mbuf *m, int count)
1543 {
1544         struct unpcb *unp, *unp2;
1545         struct socket *so2;
1546         int error, i;
1547
1548         unp = sotounpcb(so);
1549
1550         KASSERT(so->so_type == SOCK_STREAM,
1551             ("%s: unexpected socket type for %p", __func__, so));
1552
1553         UNP_PCB_LOCK(unp);
1554         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1555                 UNP_PCB_UNLOCK(unp);
1556                 so2 = unp2->unp_socket;
1557                 SOCKBUF_LOCK(&so2->so_rcv);
1558                 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1559                         sorwakeup_locked(so2);
1560                 else
1561                         SOCKBUF_UNLOCK(&so2->so_rcv);
1562                 UNP_PCB_UNLOCK(unp2);
1563                 return (error);
1564         }
1565         UNP_PCB_UNLOCK(unp);
1566
1567         /*
1568          * The receiving socket has been disconnected, but may still be valid.
1569          * In this case, the now-ready mbufs are still present in its socket
1570          * buffer, so perform an exhaustive search before giving up and freeing
1571          * the mbufs.
1572          */
1573         UNP_LINK_RLOCK();
1574         LIST_FOREACH(unp, &unp_shead, unp_link) {
1575                 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1576                         break;
1577         }
1578         UNP_LINK_RUNLOCK();
1579
1580         if (unp == NULL) {
1581                 for (i = 0; i < count; i++)
1582                         m = m_free(m);
1583                 error = ECONNRESET;
1584         }
1585         return (error);
1586 }
1587
1588 static int
1589 uipc_sense(struct socket *so, struct stat *sb)
1590 {
1591         struct unpcb *unp;
1592
1593         unp = sotounpcb(so);
1594         KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1595
1596         sb->st_blksize = so->so_snd.sb_hiwat;
1597         sb->st_dev = NODEV;
1598         sb->st_ino = unp->unp_ino;
1599         return (0);
1600 }
1601
1602 static int
1603 uipc_shutdown(struct socket *so)
1604 {
1605         struct unpcb *unp;
1606
1607         unp = sotounpcb(so);
1608         KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1609
1610         UNP_PCB_LOCK(unp);
1611         socantsendmore(so);
1612         unp_shutdown(unp);
1613         UNP_PCB_UNLOCK(unp);
1614         return (0);
1615 }
1616
1617 static int
1618 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1619 {
1620         struct unpcb *unp;
1621         const struct sockaddr *sa;
1622
1623         unp = sotounpcb(so);
1624         KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1625
1626         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1627         UNP_PCB_LOCK(unp);
1628         if (unp->unp_addr != NULL)
1629                 sa = (struct sockaddr *) unp->unp_addr;
1630         else
1631                 sa = &sun_noname;
1632         bcopy(sa, *nam, sa->sa_len);
1633         UNP_PCB_UNLOCK(unp);
1634         return (0);
1635 }
1636
1637 static struct pr_usrreqs uipc_usrreqs_dgram = {
1638         .pru_abort =            uipc_abort,
1639         .pru_accept =           uipc_accept,
1640         .pru_attach =           uipc_attach,
1641         .pru_bind =             uipc_bind,
1642         .pru_bindat =           uipc_bindat,
1643         .pru_connect =          uipc_connect,
1644         .pru_connectat =        uipc_connectat,
1645         .pru_connect2 =         uipc_connect2,
1646         .pru_detach =           uipc_detach,
1647         .pru_disconnect =       uipc_disconnect,
1648         .pru_peeraddr =         uipc_peeraddr,
1649         .pru_sosend =           uipc_sosend_dgram,
1650         .pru_sense =            uipc_sense,
1651         .pru_shutdown =         uipc_shutdown,
1652         .pru_sockaddr =         uipc_sockaddr,
1653         .pru_soreceive =        uipc_soreceive_dgram,
1654         .pru_close =            uipc_close,
1655 };
1656
1657 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1658         .pru_abort =            uipc_abort,
1659         .pru_accept =           uipc_accept,
1660         .pru_attach =           uipc_attach,
1661         .pru_bind =             uipc_bind,
1662         .pru_bindat =           uipc_bindat,
1663         .pru_connect =          uipc_connect,
1664         .pru_connectat =        uipc_connectat,
1665         .pru_connect2 =         uipc_connect2,
1666         .pru_detach =           uipc_detach,
1667         .pru_disconnect =       uipc_disconnect,
1668         .pru_listen =           uipc_listen,
1669         .pru_peeraddr =         uipc_peeraddr,
1670         .pru_rcvd =             uipc_rcvd,
1671         .pru_send =             uipc_send,
1672         .pru_sense =            uipc_sense,
1673         .pru_shutdown =         uipc_shutdown,
1674         .pru_sockaddr =         uipc_sockaddr,
1675         .pru_soreceive =        soreceive_generic,      /* XXX: or...? */
1676         .pru_close =            uipc_close,
1677 };
1678
1679 static struct pr_usrreqs uipc_usrreqs_stream = {
1680         .pru_abort =            uipc_abort,
1681         .pru_accept =           uipc_accept,
1682         .pru_attach =           uipc_attach,
1683         .pru_bind =             uipc_bind,
1684         .pru_bindat =           uipc_bindat,
1685         .pru_connect =          uipc_connect,
1686         .pru_connectat =        uipc_connectat,
1687         .pru_connect2 =         uipc_connect2,
1688         .pru_detach =           uipc_detach,
1689         .pru_disconnect =       uipc_disconnect,
1690         .pru_listen =           uipc_listen,
1691         .pru_peeraddr =         uipc_peeraddr,
1692         .pru_rcvd =             uipc_rcvd,
1693         .pru_send =             uipc_send,
1694         .pru_ready =            uipc_ready,
1695         .pru_sense =            uipc_sense,
1696         .pru_shutdown =         uipc_shutdown,
1697         .pru_sockaddr =         uipc_sockaddr,
1698         .pru_soreceive =        soreceive_generic,
1699         .pru_close =            uipc_close,
1700 };
1701
1702 static int
1703 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1704 {
1705         struct unpcb *unp;
1706         struct xucred xu;
1707         int error, optval;
1708
1709         if (sopt->sopt_level != SOL_LOCAL)
1710                 return (EINVAL);
1711
1712         unp = sotounpcb(so);
1713         KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1714         error = 0;
1715         switch (sopt->sopt_dir) {
1716         case SOPT_GET:
1717                 switch (sopt->sopt_name) {
1718                 case LOCAL_PEERCRED:
1719                         UNP_PCB_LOCK(unp);
1720                         if (unp->unp_flags & UNP_HAVEPC)
1721                                 xu = unp->unp_peercred;
1722                         else {
1723                                 if (so->so_type == SOCK_STREAM)
1724                                         error = ENOTCONN;
1725                                 else
1726                                         error = EINVAL;
1727                         }
1728                         UNP_PCB_UNLOCK(unp);
1729                         if (error == 0)
1730                                 error = sooptcopyout(sopt, &xu, sizeof(xu));
1731                         break;
1732
1733                 case LOCAL_CREDS:
1734                         /* Unlocked read. */
1735                         optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
1736                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1737                         break;
1738
1739                 case LOCAL_CREDS_PERSISTENT:
1740                         /* Unlocked read. */
1741                         optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
1742                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1743                         break;
1744
1745                 case LOCAL_CONNWAIT:
1746                         /* Unlocked read. */
1747                         optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1748                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1749                         break;
1750
1751                 default:
1752                         error = EOPNOTSUPP;
1753                         break;
1754                 }
1755                 break;
1756
1757         case SOPT_SET:
1758                 switch (sopt->sopt_name) {
1759                 case LOCAL_CREDS:
1760                 case LOCAL_CREDS_PERSISTENT:
1761                 case LOCAL_CONNWAIT:
1762                         error = sooptcopyin(sopt, &optval, sizeof(optval),
1763                                             sizeof(optval));
1764                         if (error)
1765                                 break;
1766
1767 #define OPTSET(bit, exclusive) do {                                     \
1768         UNP_PCB_LOCK(unp);                                              \
1769         if (optval) {                                                   \
1770                 if ((unp->unp_flags & (exclusive)) != 0) {              \
1771                         UNP_PCB_UNLOCK(unp);                            \
1772                         error = EINVAL;                                 \
1773                         break;                                          \
1774                 }                                                       \
1775                 unp->unp_flags |= (bit);                                \
1776         } else                                                          \
1777                 unp->unp_flags &= ~(bit);                               \
1778         UNP_PCB_UNLOCK(unp);                                            \
1779 } while (0)
1780
1781                         switch (sopt->sopt_name) {
1782                         case LOCAL_CREDS:
1783                                 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
1784                                 break;
1785
1786                         case LOCAL_CREDS_PERSISTENT:
1787                                 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
1788                                 break;
1789
1790                         case LOCAL_CONNWAIT:
1791                                 OPTSET(UNP_CONNWAIT, 0);
1792                                 break;
1793
1794                         default:
1795                                 break;
1796                         }
1797                         break;
1798 #undef  OPTSET
1799                 default:
1800                         error = ENOPROTOOPT;
1801                         break;
1802                 }
1803                 break;
1804
1805         default:
1806                 error = EOPNOTSUPP;
1807                 break;
1808         }
1809         return (error);
1810 }
1811
1812 static int
1813 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1814 {
1815
1816         return (unp_connectat(AT_FDCWD, so, nam, td, false));
1817 }
1818
1819 static int
1820 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1821     struct thread *td, bool return_locked)
1822 {
1823         struct mtx *vplock;
1824         struct sockaddr_un *soun;
1825         struct vnode *vp;
1826         struct socket *so2;
1827         struct unpcb *unp, *unp2, *unp3;
1828         struct nameidata nd;
1829         char buf[SOCK_MAXADDRLEN];
1830         struct sockaddr *sa;
1831         cap_rights_t rights;
1832         int error, len;
1833         bool connreq;
1834
1835         if (nam->sa_family != AF_UNIX)
1836                 return (EAFNOSUPPORT);
1837         if (nam->sa_len > sizeof(struct sockaddr_un))
1838                 return (EINVAL);
1839         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1840         if (len <= 0)
1841                 return (EINVAL);
1842         soun = (struct sockaddr_un *)nam;
1843         bcopy(soun->sun_path, buf, len);
1844         buf[len] = 0;
1845
1846         error = 0;
1847         unp = sotounpcb(so);
1848         UNP_PCB_LOCK(unp);
1849         for (;;) {
1850                 /*
1851                  * Wait for connection state to stabilize.  If a connection
1852                  * already exists, give up.  For datagram sockets, which permit
1853                  * multiple consecutive connect(2) calls, upper layers are
1854                  * responsible for disconnecting in advance of a subsequent
1855                  * connect(2), but this is not synchronized with PCB connection
1856                  * state.
1857                  *
1858                  * Also make sure that no threads are currently attempting to
1859                  * lock the peer socket, to ensure that unp_conn cannot
1860                  * transition between two valid sockets while locks are dropped.
1861                  */
1862                 if (SOLISTENING(so))
1863                         error = EOPNOTSUPP;
1864                 else if (unp->unp_conn != NULL)
1865                         error = EISCONN;
1866                 else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1867                         error = EALREADY;
1868                 }
1869                 if (error != 0) {
1870                         UNP_PCB_UNLOCK(unp);
1871                         return (error);
1872                 }
1873                 if (unp->unp_pairbusy > 0) {
1874                         unp->unp_flags |= UNP_WAITING;
1875                         mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1876                         continue;
1877                 }
1878                 break;
1879         }
1880         unp->unp_flags |= UNP_CONNECTING;
1881         UNP_PCB_UNLOCK(unp);
1882
1883         connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1884         if (connreq)
1885                 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1886         else
1887                 sa = NULL;
1888         NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1889             UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
1890         error = namei(&nd);
1891         if (error)
1892                 vp = NULL;
1893         else
1894                 vp = nd.ni_vp;
1895         ASSERT_VOP_LOCKED(vp, "unp_connect");
1896         NDFREE_NOTHING(&nd);
1897         if (error)
1898                 goto bad;
1899
1900         if (vp->v_type != VSOCK) {
1901                 error = ENOTSOCK;
1902                 goto bad;
1903         }
1904 #ifdef MAC
1905         error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1906         if (error)
1907                 goto bad;
1908 #endif
1909         error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1910         if (error)
1911                 goto bad;
1912
1913         unp = sotounpcb(so);
1914         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1915
1916         vplock = mtx_pool_find(mtxpool_sleep, vp);
1917         mtx_lock(vplock);
1918         VOP_UNP_CONNECT(vp, &unp2);
1919         if (unp2 == NULL) {
1920                 error = ECONNREFUSED;
1921                 goto bad2;
1922         }
1923         so2 = unp2->unp_socket;
1924         if (so->so_type != so2->so_type) {
1925                 error = EPROTOTYPE;
1926                 goto bad2;
1927         }
1928         if (connreq) {
1929                 if (SOLISTENING(so2)) {
1930                         CURVNET_SET(so2->so_vnet);
1931                         so2 = sonewconn(so2, 0);
1932                         CURVNET_RESTORE();
1933                 } else
1934                         so2 = NULL;
1935                 if (so2 == NULL) {
1936                         error = ECONNREFUSED;
1937                         goto bad2;
1938                 }
1939                 unp3 = sotounpcb(so2);
1940                 unp_pcb_lock_pair(unp2, unp3);
1941                 if (unp2->unp_addr != NULL) {
1942                         bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1943                         unp3->unp_addr = (struct sockaddr_un *) sa;
1944                         sa = NULL;
1945                 }
1946
1947                 unp_copy_peercred(td, unp3, unp, unp2);
1948
1949                 UNP_PCB_UNLOCK(unp2);
1950                 unp2 = unp3;
1951
1952                 /*
1953                  * It is safe to block on the PCB lock here since unp2 is
1954                  * nascent and cannot be connected to any other sockets.
1955                  */
1956                 UNP_PCB_LOCK(unp);
1957 #ifdef MAC
1958                 mac_socketpeer_set_from_socket(so, so2);
1959                 mac_socketpeer_set_from_socket(so2, so);
1960 #endif
1961         } else {
1962                 unp_pcb_lock_pair(unp, unp2);
1963         }
1964         KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1965             sotounpcb(so2) == unp2,
1966             ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1967         unp_connect2(so, so2, PRU_CONNECT);
1968         KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1969             ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1970         unp->unp_flags &= ~UNP_CONNECTING;
1971         if (!return_locked)
1972                 unp_pcb_unlock_pair(unp, unp2);
1973 bad2:
1974         mtx_unlock(vplock);
1975 bad:
1976         if (vp != NULL) {
1977                 /*
1978                  * If we are returning locked (called via uipc_sosend_dgram()),
1979                  * we need to be sure that vput() won't sleep.  This is
1980                  * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock.
1981                  * SOCK_STREAM/SEQPACKET can't request return_locked (yet).
1982                  */
1983                 MPASS(!(return_locked && connreq));
1984                 vput(vp);
1985         }
1986         free(sa, M_SONAME);
1987         if (__predict_false(error)) {
1988                 UNP_PCB_LOCK(unp);
1989                 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1990                     ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1991                 unp->unp_flags &= ~UNP_CONNECTING;
1992                 UNP_PCB_UNLOCK(unp);
1993         }
1994         return (error);
1995 }
1996
1997 /*
1998  * Set socket peer credentials at connection time.
1999  *
2000  * The client's PCB credentials are copied from its process structure.  The
2001  * server's PCB credentials are copied from the socket on which it called
2002  * listen(2).  uipc_listen cached that process's credentials at the time.
2003  */
2004 void
2005 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
2006     struct unpcb *server_unp, struct unpcb *listen_unp)
2007 {
2008         cru2xt(td, &client_unp->unp_peercred);
2009         client_unp->unp_flags |= UNP_HAVEPC;
2010
2011         memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
2012             sizeof(server_unp->unp_peercred));
2013         server_unp->unp_flags |= UNP_HAVEPC;
2014         client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
2015 }
2016
2017 static void
2018 unp_connect2(struct socket *so, struct socket *so2, int req)
2019 {
2020         struct unpcb *unp;
2021         struct unpcb *unp2;
2022
2023         MPASS(so2->so_type == so->so_type);
2024         unp = sotounpcb(so);
2025         KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
2026         unp2 = sotounpcb(so2);
2027         KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
2028
2029         UNP_PCB_LOCK_ASSERT(unp);
2030         UNP_PCB_LOCK_ASSERT(unp2);
2031         KASSERT(unp->unp_conn == NULL,
2032             ("%s: socket %p is already connected", __func__, unp));
2033
2034         unp->unp_conn = unp2;
2035         unp_pcb_hold(unp2);
2036         unp_pcb_hold(unp);
2037         switch (so->so_type) {
2038         case SOCK_DGRAM:
2039                 UNP_REF_LIST_LOCK();
2040                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2041                 UNP_REF_LIST_UNLOCK();
2042                 soisconnected(so);
2043                 break;
2044
2045         case SOCK_STREAM:
2046         case SOCK_SEQPACKET:
2047                 KASSERT(unp2->unp_conn == NULL,
2048                     ("%s: socket %p is already connected", __func__, unp2));
2049                 unp2->unp_conn = unp;
2050                 if (req == PRU_CONNECT &&
2051                     ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
2052                         soisconnecting(so);
2053                 else
2054                         soisconnected(so);
2055                 soisconnected(so2);
2056                 break;
2057
2058         default:
2059                 panic("unp_connect2");
2060         }
2061 }
2062
2063 static void
2064 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
2065 {
2066         struct socket *so, *so2;
2067 #ifdef INVARIANTS
2068         struct unpcb *unptmp;
2069 #endif
2070
2071         UNP_PCB_LOCK_ASSERT(unp);
2072         UNP_PCB_LOCK_ASSERT(unp2);
2073         KASSERT(unp->unp_conn == unp2,
2074             ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
2075
2076         unp->unp_conn = NULL;
2077         so = unp->unp_socket;
2078         so2 = unp2->unp_socket;
2079         switch (unp->unp_socket->so_type) {
2080         case SOCK_DGRAM:
2081                 UNP_REF_LIST_LOCK();
2082 #ifdef INVARIANTS
2083                 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
2084                         if (unptmp == unp)
2085                                 break;
2086                 }
2087                 KASSERT(unptmp != NULL,
2088                     ("%s: %p not found in reflist of %p", __func__, unp, unp2));
2089 #endif
2090                 LIST_REMOVE(unp, unp_reflink);
2091                 UNP_REF_LIST_UNLOCK();
2092                 if (so) {
2093                         SOCK_LOCK(so);
2094                         so->so_state &= ~SS_ISCONNECTED;
2095                         SOCK_UNLOCK(so);
2096                 }
2097                 break;
2098
2099         case SOCK_STREAM:
2100         case SOCK_SEQPACKET:
2101                 if (so)
2102                         soisdisconnected(so);
2103                 MPASS(unp2->unp_conn == unp);
2104                 unp2->unp_conn = NULL;
2105                 if (so2)
2106                         soisdisconnected(so2);
2107                 break;
2108         }
2109
2110         if (unp == unp2) {
2111                 unp_pcb_rele_notlast(unp);
2112                 if (!unp_pcb_rele(unp))
2113                         UNP_PCB_UNLOCK(unp);
2114         } else {
2115                 if (!unp_pcb_rele(unp))
2116                         UNP_PCB_UNLOCK(unp);
2117                 if (!unp_pcb_rele(unp2))
2118                         UNP_PCB_UNLOCK(unp2);
2119         }
2120 }
2121
2122 /*
2123  * unp_pcblist() walks the global list of struct unpcb's to generate a
2124  * pointer list, bumping the refcount on each unpcb.  It then copies them out
2125  * sequentially, validating the generation number on each to see if it has
2126  * been detached.  All of this is necessary because copyout() may sleep on
2127  * disk I/O.
2128  */
2129 static int
2130 unp_pcblist(SYSCTL_HANDLER_ARGS)
2131 {
2132         struct unpcb *unp, **unp_list;
2133         unp_gen_t gencnt;
2134         struct xunpgen *xug;
2135         struct unp_head *head;
2136         struct xunpcb *xu;
2137         u_int i;
2138         int error, n;
2139
2140         switch ((intptr_t)arg1) {
2141         case SOCK_STREAM:
2142                 head = &unp_shead;
2143                 break;
2144
2145         case SOCK_DGRAM:
2146                 head = &unp_dhead;
2147                 break;
2148
2149         case SOCK_SEQPACKET:
2150                 head = &unp_sphead;
2151                 break;
2152
2153         default:
2154                 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
2155         }
2156
2157         /*
2158          * The process of preparing the PCB list is too time-consuming and
2159          * resource-intensive to repeat twice on every request.
2160          */
2161         if (req->oldptr == NULL) {
2162                 n = unp_count;
2163                 req->oldidx = 2 * (sizeof *xug)
2164                         + (n + n/8) * sizeof(struct xunpcb);
2165                 return (0);
2166         }
2167
2168         if (req->newptr != NULL)
2169                 return (EPERM);
2170
2171         /*
2172          * OK, now we're committed to doing something.
2173          */
2174         xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
2175         UNP_LINK_RLOCK();
2176         gencnt = unp_gencnt;
2177         n = unp_count;
2178         UNP_LINK_RUNLOCK();
2179
2180         xug->xug_len = sizeof *xug;
2181         xug->xug_count = n;
2182         xug->xug_gen = gencnt;
2183         xug->xug_sogen = so_gencnt;
2184         error = SYSCTL_OUT(req, xug, sizeof *xug);
2185         if (error) {
2186                 free(xug, M_TEMP);
2187                 return (error);
2188         }
2189
2190         unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
2191
2192         UNP_LINK_RLOCK();
2193         for (unp = LIST_FIRST(head), i = 0; unp && i < n;
2194              unp = LIST_NEXT(unp, unp_link)) {
2195                 UNP_PCB_LOCK(unp);
2196                 if (unp->unp_gencnt <= gencnt) {
2197                         if (cr_cansee(req->td->td_ucred,
2198                             unp->unp_socket->so_cred)) {
2199                                 UNP_PCB_UNLOCK(unp);
2200                                 continue;
2201                         }
2202                         unp_list[i++] = unp;
2203                         unp_pcb_hold(unp);
2204                 }
2205                 UNP_PCB_UNLOCK(unp);
2206         }
2207         UNP_LINK_RUNLOCK();
2208         n = i;                  /* In case we lost some during malloc. */
2209
2210         error = 0;
2211         xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
2212         for (i = 0; i < n; i++) {
2213                 unp = unp_list[i];
2214                 UNP_PCB_LOCK(unp);
2215                 if (unp_pcb_rele(unp))
2216                         continue;
2217
2218                 if (unp->unp_gencnt <= gencnt) {
2219                         xu->xu_len = sizeof *xu;
2220                         xu->xu_unpp = (uintptr_t)unp;
2221                         /*
2222                          * XXX - need more locking here to protect against
2223                          * connect/disconnect races for SMP.
2224                          */
2225                         if (unp->unp_addr != NULL)
2226                                 bcopy(unp->unp_addr, &xu->xu_addr,
2227                                       unp->unp_addr->sun_len);
2228                         else
2229                                 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
2230                         if (unp->unp_conn != NULL &&
2231                             unp->unp_conn->unp_addr != NULL)
2232                                 bcopy(unp->unp_conn->unp_addr,
2233                                       &xu->xu_caddr,
2234                                       unp->unp_conn->unp_addr->sun_len);
2235                         else
2236                                 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
2237                         xu->unp_vnode = (uintptr_t)unp->unp_vnode;
2238                         xu->unp_conn = (uintptr_t)unp->unp_conn;
2239                         xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
2240                         xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
2241                         xu->unp_gencnt = unp->unp_gencnt;
2242                         sotoxsocket(unp->unp_socket, &xu->xu_socket);
2243                         UNP_PCB_UNLOCK(unp);
2244                         error = SYSCTL_OUT(req, xu, sizeof *xu);
2245                 } else {
2246                         UNP_PCB_UNLOCK(unp);
2247                 }
2248         }
2249         free(xu, M_TEMP);
2250         if (!error) {
2251                 /*
2252                  * Give the user an updated idea of our state.  If the
2253                  * generation differs from what we told her before, she knows
2254                  * that something happened while we were processing this
2255                  * request, and it might be necessary to retry.
2256                  */
2257                 xug->xug_gen = unp_gencnt;
2258                 xug->xug_sogen = so_gencnt;
2259                 xug->xug_count = unp_count;
2260                 error = SYSCTL_OUT(req, xug, sizeof *xug);
2261         }
2262         free(unp_list, M_TEMP);
2263         free(xug, M_TEMP);
2264         return (error);
2265 }
2266
2267 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
2268     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2269     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
2270     "List of active local datagram sockets");
2271 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
2272     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2273     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
2274     "List of active local stream sockets");
2275 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
2276     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2277     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
2278     "List of active local seqpacket sockets");
2279
2280 static void
2281 unp_shutdown(struct unpcb *unp)
2282 {
2283         struct unpcb *unp2;
2284         struct socket *so;
2285
2286         UNP_PCB_LOCK_ASSERT(unp);
2287
2288         unp2 = unp->unp_conn;
2289         if ((unp->unp_socket->so_type == SOCK_STREAM ||
2290             (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
2291                 so = unp2->unp_socket;
2292                 if (so != NULL)
2293                         socantrcvmore(so);
2294         }
2295 }
2296
2297 static void
2298 unp_drop(struct unpcb *unp)
2299 {
2300         struct socket *so;
2301         struct unpcb *unp2;
2302
2303         /*
2304          * Regardless of whether the socket's peer dropped the connection
2305          * with this socket by aborting or disconnecting, POSIX requires
2306          * that ECONNRESET is returned.
2307          */
2308
2309         UNP_PCB_LOCK(unp);
2310         so = unp->unp_socket;
2311         if (so)
2312                 so->so_error = ECONNRESET;
2313         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
2314                 /* Last reference dropped in unp_disconnect(). */
2315                 unp_pcb_rele_notlast(unp);
2316                 unp_disconnect(unp, unp2);
2317         } else if (!unp_pcb_rele(unp)) {
2318                 UNP_PCB_UNLOCK(unp);
2319         }
2320 }
2321
2322 static void
2323 unp_freerights(struct filedescent **fdep, int fdcount)
2324 {
2325         struct file *fp;
2326         int i;
2327
2328         KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
2329
2330         for (i = 0; i < fdcount; i++) {
2331                 fp = fdep[i]->fde_file;
2332                 filecaps_free(&fdep[i]->fde_caps);
2333                 unp_discard(fp);
2334         }
2335         free(fdep[0], M_FILECAPS);
2336 }
2337
2338 static int
2339 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2340 {
2341         struct thread *td = curthread;          /* XXX */
2342         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2343         int i;
2344         int *fdp;
2345         struct filedesc *fdesc = td->td_proc->p_fd;
2346         struct filedescent **fdep;
2347         void *data;
2348         socklen_t clen = control->m_len, datalen;
2349         int error, newfds;
2350         u_int newlen;
2351
2352         UNP_LINK_UNLOCK_ASSERT();
2353
2354         error = 0;
2355         if (controlp != NULL) /* controlp == NULL => free control messages */
2356                 *controlp = NULL;
2357         while (cm != NULL) {
2358                 MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
2359
2360                 data = CMSG_DATA(cm);
2361                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2362                 if (cm->cmsg_level == SOL_SOCKET
2363                     && cm->cmsg_type == SCM_RIGHTS) {
2364                         newfds = datalen / sizeof(*fdep);
2365                         if (newfds == 0)
2366                                 goto next;
2367                         fdep = data;
2368
2369                         /* If we're not outputting the descriptors free them. */
2370                         if (error || controlp == NULL) {
2371                                 unp_freerights(fdep, newfds);
2372                                 goto next;
2373                         }
2374                         FILEDESC_XLOCK(fdesc);
2375
2376                         /*
2377                          * Now change each pointer to an fd in the global
2378                          * table to an integer that is the index to the local
2379                          * fd table entry that we set up to point to the
2380                          * global one we are transferring.
2381                          */
2382                         newlen = newfds * sizeof(int);
2383                         *controlp = sbcreatecontrol(NULL, newlen,
2384                             SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2385
2386                         fdp = (int *)
2387                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2388                         if (fdallocn(td, 0, fdp, newfds) != 0) {
2389                                 FILEDESC_XUNLOCK(fdesc);
2390                                 error = EMSGSIZE;
2391                                 unp_freerights(fdep, newfds);
2392                                 m_freem(*controlp);
2393                                 *controlp = NULL;
2394                                 goto next;
2395                         }
2396                         for (i = 0; i < newfds; i++, fdp++) {
2397                                 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2398                                     (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2399                                     &fdep[i]->fde_caps);
2400                                 unp_externalize_fp(fdep[i]->fde_file);
2401                         }
2402
2403                         /*
2404                          * The new type indicates that the mbuf data refers to
2405                          * kernel resources that may need to be released before
2406                          * the mbuf is freed.
2407                          */
2408                         m_chtype(*controlp, MT_EXTCONTROL);
2409                         FILEDESC_XUNLOCK(fdesc);
2410                         free(fdep[0], M_FILECAPS);
2411                 } else {
2412                         /* We can just copy anything else across. */
2413                         if (error || controlp == NULL)
2414                                 goto next;
2415                         *controlp = sbcreatecontrol(NULL, datalen,
2416                             cm->cmsg_type, cm->cmsg_level, M_WAITOK);
2417                         bcopy(data,
2418                             CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2419                             datalen);
2420                 }
2421                 controlp = &(*controlp)->m_next;
2422
2423 next:
2424                 if (CMSG_SPACE(datalen) < clen) {
2425                         clen -= CMSG_SPACE(datalen);
2426                         cm = (struct cmsghdr *)
2427                             ((caddr_t)cm + CMSG_SPACE(datalen));
2428                 } else {
2429                         clen = 0;
2430                         cm = NULL;
2431                 }
2432         }
2433
2434         m_freem(control);
2435         return (error);
2436 }
2437
2438 static void
2439 unp_zone_change(void *tag)
2440 {
2441
2442         uma_zone_set_max(unp_zone, maxsockets);
2443 }
2444
2445 #ifdef INVARIANTS
2446 static void
2447 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2448 {
2449         struct unpcb *unp;
2450
2451         unp = mem;
2452
2453         KASSERT(LIST_EMPTY(&unp->unp_refs),
2454             ("%s: unpcb %p has lingering refs", __func__, unp));
2455         KASSERT(unp->unp_socket == NULL,
2456             ("%s: unpcb %p has socket backpointer", __func__, unp));
2457         KASSERT(unp->unp_vnode == NULL,
2458             ("%s: unpcb %p has vnode references", __func__, unp));
2459         KASSERT(unp->unp_conn == NULL,
2460             ("%s: unpcb %p is still connected", __func__, unp));
2461         KASSERT(unp->unp_addr == NULL,
2462             ("%s: unpcb %p has leaked addr", __func__, unp));
2463 }
2464 #endif
2465
2466 static void
2467 unp_init(void *arg __unused)
2468 {
2469         uma_dtor dtor;
2470
2471 #ifdef INVARIANTS
2472         dtor = unp_zdtor;
2473 #else
2474         dtor = NULL;
2475 #endif
2476         unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2477             NULL, NULL, UMA_ALIGN_CACHE, 0);
2478         uma_zone_set_max(unp_zone, maxsockets);
2479         uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2480         EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2481             NULL, EVENTHANDLER_PRI_ANY);
2482         LIST_INIT(&unp_dhead);
2483         LIST_INIT(&unp_shead);
2484         LIST_INIT(&unp_sphead);
2485         SLIST_INIT(&unp_defers);
2486         TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2487         TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2488         UNP_LINK_LOCK_INIT();
2489         UNP_DEFERRED_LOCK_INIT();
2490 }
2491 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
2492
2493 static void
2494 unp_internalize_cleanup_rights(struct mbuf *control)
2495 {
2496         struct cmsghdr *cp;
2497         struct mbuf *m;
2498         void *data;
2499         socklen_t datalen;
2500
2501         for (m = control; m != NULL; m = m->m_next) {
2502                 cp = mtod(m, struct cmsghdr *);
2503                 if (cp->cmsg_level != SOL_SOCKET ||
2504                     cp->cmsg_type != SCM_RIGHTS)
2505                         continue;
2506                 data = CMSG_DATA(cp);
2507                 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2508                 unp_freerights(data, datalen / sizeof(struct filedesc *));
2509         }
2510 }
2511
2512 static int
2513 unp_internalize(struct mbuf **controlp, struct thread *td)
2514 {
2515         struct mbuf *control, **initial_controlp;
2516         struct proc *p;
2517         struct filedesc *fdesc;
2518         struct bintime *bt;
2519         struct cmsghdr *cm;
2520         struct cmsgcred *cmcred;
2521         struct filedescent *fde, **fdep, *fdev;
2522         struct file *fp;
2523         struct timeval *tv;
2524         struct timespec *ts;
2525         void *data;
2526         socklen_t clen, datalen;
2527         int i, j, error, *fdp, oldfds;
2528         u_int newlen;
2529
2530         UNP_LINK_UNLOCK_ASSERT();
2531
2532         p = td->td_proc;
2533         fdesc = p->p_fd;
2534         error = 0;
2535         control = *controlp;
2536         *controlp = NULL;
2537         initial_controlp = controlp;
2538         for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
2539             data = CMSG_DATA(cm);
2540
2541             clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
2542             clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
2543             (char *)cm + cm->cmsg_len >= (char *)data;
2544
2545             clen -= min(CMSG_SPACE(datalen), clen),
2546             cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
2547             data = CMSG_DATA(cm)) {
2548                 datalen = (char *)cm + cm->cmsg_len - (char *)data;
2549                 switch (cm->cmsg_type) {
2550                 case SCM_CREDS:
2551                         *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2552                             SCM_CREDS, SOL_SOCKET, M_WAITOK);
2553                         cmcred = (struct cmsgcred *)
2554                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2555                         cmcred->cmcred_pid = p->p_pid;
2556                         cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2557                         cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2558                         cmcred->cmcred_euid = td->td_ucred->cr_uid;
2559                         cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2560                             CMGROUP_MAX);
2561                         for (i = 0; i < cmcred->cmcred_ngroups; i++)
2562                                 cmcred->cmcred_groups[i] =
2563                                     td->td_ucred->cr_groups[i];
2564                         break;
2565
2566                 case SCM_RIGHTS:
2567                         oldfds = datalen / sizeof (int);
2568                         if (oldfds == 0)
2569                                 continue;
2570                         /* On some machines sizeof pointer is bigger than
2571                          * sizeof int, so we need to check if data fits into
2572                          * single mbuf.  We could allocate several mbufs, and
2573                          * unp_externalize() should even properly handle that.
2574                          * But it is not worth to complicate the code for an
2575                          * insane scenario of passing over 200 file descriptors
2576                          * at once.
2577                          */
2578                         newlen = oldfds * sizeof(fdep[0]);
2579                         if (CMSG_SPACE(newlen) > MCLBYTES) {
2580                                 error = EMSGSIZE;
2581                                 goto out;
2582                         }
2583                         /*
2584                          * Check that all the FDs passed in refer to legal
2585                          * files.  If not, reject the entire operation.
2586                          */
2587                         fdp = data;
2588                         FILEDESC_SLOCK(fdesc);
2589                         for (i = 0; i < oldfds; i++, fdp++) {
2590                                 fp = fget_noref(fdesc, *fdp);
2591                                 if (fp == NULL) {
2592                                         FILEDESC_SUNLOCK(fdesc);
2593                                         error = EBADF;
2594                                         goto out;
2595                                 }
2596                                 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2597                                         FILEDESC_SUNLOCK(fdesc);
2598                                         error = EOPNOTSUPP;
2599                                         goto out;
2600                                 }
2601                         }
2602
2603                         /*
2604                          * Now replace the integer FDs with pointers to the
2605                          * file structure and capability rights.
2606                          */
2607                         *controlp = sbcreatecontrol(NULL, newlen,
2608                             SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2609                         fdp = data;
2610                         for (i = 0; i < oldfds; i++, fdp++) {
2611                                 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2612                                         fdp = data;
2613                                         for (j = 0; j < i; j++, fdp++) {
2614                                                 fdrop(fdesc->fd_ofiles[*fdp].
2615                                                     fde_file, td);
2616                                         }
2617                                         FILEDESC_SUNLOCK(fdesc);
2618                                         error = EBADF;
2619                                         goto out;
2620                                 }
2621                         }
2622                         fdp = data;
2623                         fdep = (struct filedescent **)
2624                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2625                         fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2626                             M_WAITOK);
2627                         for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2628                                 fde = &fdesc->fd_ofiles[*fdp];
2629                                 fdep[i] = fdev;
2630                                 fdep[i]->fde_file = fde->fde_file;
2631                                 filecaps_copy(&fde->fde_caps,
2632                                     &fdep[i]->fde_caps, true);
2633                                 unp_internalize_fp(fdep[i]->fde_file);
2634                         }
2635                         FILEDESC_SUNLOCK(fdesc);
2636                         break;
2637
2638                 case SCM_TIMESTAMP:
2639                         *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2640                             SCM_TIMESTAMP, SOL_SOCKET, M_WAITOK);
2641                         tv = (struct timeval *)
2642                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2643                         microtime(tv);
2644                         break;
2645
2646                 case SCM_BINTIME:
2647                         *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2648                             SCM_BINTIME, SOL_SOCKET, M_WAITOK);
2649                         bt = (struct bintime *)
2650                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2651                         bintime(bt);
2652                         break;
2653
2654                 case SCM_REALTIME:
2655                         *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2656                             SCM_REALTIME, SOL_SOCKET, M_WAITOK);
2657                         ts = (struct timespec *)
2658                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2659                         nanotime(ts);
2660                         break;
2661
2662                 case SCM_MONOTONIC:
2663                         *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2664                             SCM_MONOTONIC, SOL_SOCKET, M_WAITOK);
2665                         ts = (struct timespec *)
2666                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2667                         nanouptime(ts);
2668                         break;
2669
2670                 default:
2671                         error = EINVAL;
2672                         goto out;
2673                 }
2674
2675                 controlp = &(*controlp)->m_next;
2676         }
2677         if (clen > 0)
2678                 error = EINVAL;
2679
2680 out:
2681         if (error != 0 && initial_controlp != NULL)
2682                 unp_internalize_cleanup_rights(*initial_controlp);
2683         m_freem(control);
2684         return (error);
2685 }
2686
2687 static struct mbuf *
2688 unp_addsockcred(struct thread *td, struct mbuf *control, int mode)
2689 {
2690         struct mbuf *m, *n, *n_prev;
2691         const struct cmsghdr *cm;
2692         int ngroups, i, cmsgtype;
2693         size_t ctrlsz;
2694
2695         ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2696         if (mode & UNP_WANTCRED_ALWAYS) {
2697                 ctrlsz = SOCKCRED2SIZE(ngroups);
2698                 cmsgtype = SCM_CREDS2;
2699         } else {
2700                 ctrlsz = SOCKCREDSIZE(ngroups);
2701                 cmsgtype = SCM_CREDS;
2702         }
2703
2704         m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
2705         if (m == NULL)
2706                 return (control);
2707
2708         if (mode & UNP_WANTCRED_ALWAYS) {
2709                 struct sockcred2 *sc;
2710
2711                 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2712                 sc->sc_version = 0;
2713                 sc->sc_pid = td->td_proc->p_pid;
2714                 sc->sc_uid = td->td_ucred->cr_ruid;
2715                 sc->sc_euid = td->td_ucred->cr_uid;
2716                 sc->sc_gid = td->td_ucred->cr_rgid;
2717                 sc->sc_egid = td->td_ucred->cr_gid;
2718                 sc->sc_ngroups = ngroups;
2719                 for (i = 0; i < sc->sc_ngroups; i++)
2720                         sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2721         } else {
2722                 struct sockcred *sc;
2723
2724                 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2725                 sc->sc_uid = td->td_ucred->cr_ruid;
2726                 sc->sc_euid = td->td_ucred->cr_uid;
2727                 sc->sc_gid = td->td_ucred->cr_rgid;
2728                 sc->sc_egid = td->td_ucred->cr_gid;
2729                 sc->sc_ngroups = ngroups;
2730                 for (i = 0; i < sc->sc_ngroups; i++)
2731                         sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2732         }
2733
2734         /*
2735          * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2736          * created SCM_CREDS control message (struct sockcred) has another
2737          * format.
2738          */
2739         if (control != NULL && cmsgtype == SCM_CREDS)
2740                 for (n = control, n_prev = NULL; n != NULL;) {
2741                         cm = mtod(n, struct cmsghdr *);
2742                         if (cm->cmsg_level == SOL_SOCKET &&
2743                             cm->cmsg_type == SCM_CREDS) {
2744                                 if (n_prev == NULL)
2745                                         control = n->m_next;
2746                                 else
2747                                         n_prev->m_next = n->m_next;
2748                                 n = m_free(n);
2749                         } else {
2750                                 n_prev = n;
2751                                 n = n->m_next;
2752                         }
2753                 }
2754
2755         /* Prepend it to the head. */
2756         m->m_next = control;
2757         return (m);
2758 }
2759
2760 static struct unpcb *
2761 fptounp(struct file *fp)
2762 {
2763         struct socket *so;
2764
2765         if (fp->f_type != DTYPE_SOCKET)
2766                 return (NULL);
2767         if ((so = fp->f_data) == NULL)
2768                 return (NULL);
2769         if (so->so_proto->pr_domain != &localdomain)
2770                 return (NULL);
2771         return sotounpcb(so);
2772 }
2773
2774 static void
2775 unp_discard(struct file *fp)
2776 {
2777         struct unp_defer *dr;
2778
2779         if (unp_externalize_fp(fp)) {
2780                 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2781                 dr->ud_fp = fp;
2782                 UNP_DEFERRED_LOCK();
2783                 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2784                 UNP_DEFERRED_UNLOCK();
2785                 atomic_add_int(&unp_defers_count, 1);
2786                 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2787         } else
2788                 closef_nothread(fp);
2789 }
2790
2791 static void
2792 unp_process_defers(void *arg __unused, int pending)
2793 {
2794         struct unp_defer *dr;
2795         SLIST_HEAD(, unp_defer) drl;
2796         int count;
2797
2798         SLIST_INIT(&drl);
2799         for (;;) {
2800                 UNP_DEFERRED_LOCK();
2801                 if (SLIST_FIRST(&unp_defers) == NULL) {
2802                         UNP_DEFERRED_UNLOCK();
2803                         break;
2804                 }
2805                 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2806                 UNP_DEFERRED_UNLOCK();
2807                 count = 0;
2808                 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2809                         SLIST_REMOVE_HEAD(&drl, ud_link);
2810                         closef_nothread(dr->ud_fp);
2811                         free(dr, M_TEMP);
2812                         count++;
2813                 }
2814                 atomic_add_int(&unp_defers_count, -count);
2815         }
2816 }
2817
2818 static void
2819 unp_internalize_fp(struct file *fp)
2820 {
2821         struct unpcb *unp;
2822
2823         UNP_LINK_WLOCK();
2824         if ((unp = fptounp(fp)) != NULL) {
2825                 unp->unp_file = fp;
2826                 unp->unp_msgcount++;
2827         }
2828         unp_rights++;
2829         UNP_LINK_WUNLOCK();
2830 }
2831
2832 static int
2833 unp_externalize_fp(struct file *fp)
2834 {
2835         struct unpcb *unp;
2836         int ret;
2837
2838         UNP_LINK_WLOCK();
2839         if ((unp = fptounp(fp)) != NULL) {
2840                 unp->unp_msgcount--;
2841                 ret = 1;
2842         } else
2843                 ret = 0;
2844         unp_rights--;
2845         UNP_LINK_WUNLOCK();
2846         return (ret);
2847 }
2848
2849 /*
2850  * unp_defer indicates whether additional work has been defered for a future
2851  * pass through unp_gc().  It is thread local and does not require explicit
2852  * synchronization.
2853  */
2854 static int      unp_marked;
2855
2856 static void
2857 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2858 {
2859         struct unpcb *unp;
2860         struct file *fp;
2861         int i;
2862
2863         /*
2864          * This function can only be called from the gc task.
2865          */
2866         KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2867             ("%s: not on gc callout", __func__));
2868         UNP_LINK_LOCK_ASSERT();
2869
2870         for (i = 0; i < fdcount; i++) {
2871                 fp = fdep[i]->fde_file;
2872                 if ((unp = fptounp(fp)) == NULL)
2873                         continue;
2874                 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2875                         continue;
2876                 unp->unp_gcrefs--;
2877         }
2878 }
2879
2880 static void
2881 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2882 {
2883         struct unpcb *unp;
2884         struct file *fp;
2885         int i;
2886
2887         /*
2888          * This function can only be called from the gc task.
2889          */
2890         KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2891             ("%s: not on gc callout", __func__));
2892         UNP_LINK_LOCK_ASSERT();
2893
2894         for (i = 0; i < fdcount; i++) {
2895                 fp = fdep[i]->fde_file;
2896                 if ((unp = fptounp(fp)) == NULL)
2897                         continue;
2898                 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2899                         continue;
2900                 unp->unp_gcrefs++;
2901                 unp_marked++;
2902         }
2903 }
2904
2905 static void
2906 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
2907 {
2908
2909         SOCK_LOCK_ASSERT(so);
2910
2911         if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2912                 return;
2913
2914         SOCK_RECVBUF_LOCK(so);
2915         switch (so->so_type) {
2916         case SOCK_DGRAM:
2917                 unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
2918                 break;
2919         case SOCK_STREAM:
2920         case SOCK_SEQPACKET:
2921                 unp_scan(so->so_rcv.sb_mb, op);
2922                 break;
2923         }
2924         SOCK_RECVBUF_UNLOCK(so);
2925 }
2926
2927 static void
2928 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2929 {
2930         struct socket *so, *soa;
2931
2932         so = unp->unp_socket;
2933         SOCK_LOCK(so);
2934         if (SOLISTENING(so)) {
2935                 /*
2936                  * Mark all sockets in our accept queue.
2937                  */
2938                 TAILQ_FOREACH(soa, &so->sol_comp, so_list)
2939                         unp_scan_socket(soa, op);
2940         } else {
2941                 /*
2942                  * Mark all sockets we reference with RIGHTS.
2943                  */
2944                 unp_scan_socket(so, op);
2945         }
2946         SOCK_UNLOCK(so);
2947 }
2948
2949 static int unp_recycled;
2950 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, 
2951     "Number of unreachable sockets claimed by the garbage collector.");
2952
2953 static int unp_taskcount;
2954 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, 
2955     "Number of times the garbage collector has run.");
2956
2957 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0, 
2958     "Number of active local sockets.");
2959
2960 static void
2961 unp_gc(__unused void *arg, int pending)
2962 {
2963         struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2964                                     NULL };
2965         struct unp_head **head;
2966         struct unp_head unp_deadhead;   /* List of potentially-dead sockets. */
2967         struct file *f, **unref;
2968         struct unpcb *unp, *unptmp;
2969         int i, total, unp_unreachable;
2970
2971         LIST_INIT(&unp_deadhead);
2972         unp_taskcount++;
2973         UNP_LINK_RLOCK();
2974         /*
2975          * First determine which sockets may be in cycles.
2976          */
2977         unp_unreachable = 0;
2978
2979         for (head = heads; *head != NULL; head++)
2980                 LIST_FOREACH(unp, *head, unp_link) {
2981                         KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2982                             ("%s: unp %p has unexpected gc flags 0x%x",
2983                             __func__, unp, (unsigned int)unp->unp_gcflag));
2984
2985                         f = unp->unp_file;
2986
2987                         /*
2988                          * Check for an unreachable socket potentially in a
2989                          * cycle.  It must be in a queue as indicated by
2990                          * msgcount, and this must equal the file reference
2991                          * count.  Note that when msgcount is 0 the file is
2992                          * NULL.
2993                          */
2994                         if (f != NULL && unp->unp_msgcount != 0 &&
2995                             refcount_load(&f->f_count) == unp->unp_msgcount) {
2996                                 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2997                                 unp->unp_gcflag |= UNPGC_DEAD;
2998                                 unp->unp_gcrefs = unp->unp_msgcount;
2999                                 unp_unreachable++;
3000                         }
3001                 }
3002
3003         /*
3004          * Scan all sockets previously marked as potentially being in a cycle
3005          * and remove the references each socket holds on any UNPGC_DEAD
3006          * sockets in its queue.  After this step, all remaining references on
3007          * sockets marked UNPGC_DEAD should not be part of any cycle.
3008          */
3009         LIST_FOREACH(unp, &unp_deadhead, unp_dead)
3010                 unp_gc_scan(unp, unp_remove_dead_ref);
3011
3012         /*
3013          * If a socket still has a non-negative refcount, it cannot be in a
3014          * cycle.  In this case increment refcount of all children iteratively.
3015          * Stop the scan once we do a complete loop without discovering
3016          * a new reachable socket.
3017          */
3018         do {
3019                 unp_marked = 0;
3020                 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
3021                         if (unp->unp_gcrefs > 0) {
3022                                 unp->unp_gcflag &= ~UNPGC_DEAD;
3023                                 LIST_REMOVE(unp, unp_dead);
3024                                 KASSERT(unp_unreachable > 0,
3025                                     ("%s: unp_unreachable underflow.",
3026                                     __func__));
3027                                 unp_unreachable--;
3028                                 unp_gc_scan(unp, unp_restore_undead_ref);
3029                         }
3030         } while (unp_marked);
3031
3032         UNP_LINK_RUNLOCK();
3033
3034         if (unp_unreachable == 0)
3035                 return;
3036
3037         /*
3038          * Allocate space for a local array of dead unpcbs.
3039          * TODO: can this path be simplified by instead using the local
3040          * dead list at unp_deadhead, after taking out references
3041          * on the file object and/or unpcb and dropping the link lock?
3042          */
3043         unref = malloc(unp_unreachable * sizeof(struct file *),
3044             M_TEMP, M_WAITOK);
3045
3046         /*
3047          * Iterate looking for sockets which have been specifically marked
3048          * as unreachable and store them locally.
3049          */
3050         UNP_LINK_RLOCK();
3051         total = 0;
3052         LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
3053                 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
3054                     ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
3055                 unp->unp_gcflag &= ~UNPGC_DEAD;
3056                 f = unp->unp_file;
3057                 if (unp->unp_msgcount == 0 || f == NULL ||
3058                     refcount_load(&f->f_count) != unp->unp_msgcount ||
3059                     !fhold(f))
3060                         continue;
3061                 unref[total++] = f;
3062                 KASSERT(total <= unp_unreachable,
3063                     ("%s: incorrect unreachable count.", __func__));
3064         }
3065         UNP_LINK_RUNLOCK();
3066
3067         /*
3068          * Now flush all sockets, free'ing rights.  This will free the
3069          * struct files associated with these sockets but leave each socket
3070          * with one remaining ref.
3071          */
3072         for (i = 0; i < total; i++) {
3073                 struct socket *so;
3074
3075                 so = unref[i]->f_data;
3076                 CURVNET_SET(so->so_vnet);
3077                 sorflush(so);
3078                 CURVNET_RESTORE();
3079         }
3080
3081         /*
3082          * And finally release the sockets so they can be reclaimed.
3083          */
3084         for (i = 0; i < total; i++)
3085                 fdrop(unref[i], NULL);
3086         unp_recycled += total;
3087         free(unref, M_TEMP);
3088 }
3089
3090 /*
3091  * Synchronize against unp_gc, which can trip over data as we are freeing it.
3092  */
3093 static void
3094 unp_dispose(struct socket *so)
3095 {
3096         struct sockbuf *sb = &so->so_rcv;
3097         struct unpcb *unp;
3098         struct mbuf *m;
3099
3100         MPASS(!SOLISTENING(so));
3101
3102         unp = sotounpcb(so);
3103         UNP_LINK_WLOCK();
3104         unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
3105         UNP_LINK_WUNLOCK();
3106
3107         /*
3108          * Grab our special mbufs before calling sbrelease().
3109          */
3110         SOCK_RECVBUF_LOCK(so);
3111         switch (so->so_type) {
3112         case SOCK_DGRAM:
3113                 m = STAILQ_FIRST(&sb->uxdg_mb);
3114                 STAILQ_INIT(&sb->uxdg_mb);
3115                 /* XXX: our shortened sbrelease() */
3116                 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
3117                     RLIM_INFINITY);
3118                 break;
3119         case SOCK_STREAM:
3120         case SOCK_SEQPACKET:
3121                 m = sbcut_locked(sb, sb->sb_ccc);
3122                 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
3123                     ("%s: ccc %u mb %p mbcnt %u", __func__,
3124                     sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
3125                 sbrelease_locked(so, SO_RCV);
3126                 break;
3127         }
3128         SOCK_RECVBUF_UNLOCK(so);
3129         if (SOCK_IO_RECV_OWNED(so))
3130                 SOCK_IO_RECV_UNLOCK(so);
3131
3132         if (m != NULL) {
3133                 unp_scan(m, unp_freerights);
3134                 m_freem(m);
3135         }
3136 }
3137
3138 static void
3139 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
3140 {
3141         struct mbuf *m;
3142         struct cmsghdr *cm;
3143         void *data;
3144         socklen_t clen, datalen;
3145
3146         while (m0 != NULL) {
3147                 for (m = m0; m; m = m->m_next) {
3148                         if (m->m_type != MT_CONTROL)
3149                                 continue;
3150
3151                         cm = mtod(m, struct cmsghdr *);
3152                         clen = m->m_len;
3153
3154                         while (cm != NULL) {
3155                                 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
3156                                         break;
3157
3158                                 data = CMSG_DATA(cm);
3159                                 datalen = (caddr_t)cm + cm->cmsg_len
3160                                     - (caddr_t)data;
3161
3162                                 if (cm->cmsg_level == SOL_SOCKET &&
3163                                     cm->cmsg_type == SCM_RIGHTS) {
3164                                         (*op)(data, datalen /
3165                                             sizeof(struct filedescent *));
3166                                 }
3167
3168                                 if (CMSG_SPACE(datalen) < clen) {
3169                                         clen -= CMSG_SPACE(datalen);
3170                                         cm = (struct cmsghdr *)
3171                                             ((caddr_t)cm + CMSG_SPACE(datalen));
3172                                 } else {
3173                                         clen = 0;
3174                                         cm = NULL;
3175                                 }
3176                         }
3177                 }
3178                 m0 = m0->m_nextpkt;
3179         }
3180 }
3181
3182 /*
3183  * A helper function called by VFS before socket-type vnode reclamation.
3184  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
3185  * use count.
3186  */
3187 void
3188 vfs_unp_reclaim(struct vnode *vp)
3189 {
3190         struct unpcb *unp;
3191         int active;
3192         struct mtx *vplock;
3193
3194         ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
3195         KASSERT(vp->v_type == VSOCK,
3196             ("vfs_unp_reclaim: vp->v_type != VSOCK"));
3197
3198         active = 0;
3199         vplock = mtx_pool_find(mtxpool_sleep, vp);
3200         mtx_lock(vplock);
3201         VOP_UNP_CONNECT(vp, &unp);
3202         if (unp == NULL)
3203                 goto done;
3204         UNP_PCB_LOCK(unp);
3205         if (unp->unp_vnode == vp) {
3206                 VOP_UNP_DETACH(vp);
3207                 unp->unp_vnode = NULL;
3208                 active = 1;
3209         }
3210         UNP_PCB_UNLOCK(unp);
3211  done:
3212         mtx_unlock(vplock);
3213         if (active)
3214                 vunref(vp);
3215 }
3216
3217 #ifdef DDB
3218 static void
3219 db_print_indent(int indent)
3220 {
3221         int i;
3222
3223         for (i = 0; i < indent; i++)
3224                 db_printf(" ");
3225 }
3226
3227 static void
3228 db_print_unpflags(int unp_flags)
3229 {
3230         int comma;
3231
3232         comma = 0;
3233         if (unp_flags & UNP_HAVEPC) {
3234                 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
3235                 comma = 1;
3236         }
3237         if (unp_flags & UNP_WANTCRED_ALWAYS) {
3238                 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
3239                 comma = 1;
3240         }
3241         if (unp_flags & UNP_WANTCRED_ONESHOT) {
3242                 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
3243                 comma = 1;
3244         }
3245         if (unp_flags & UNP_CONNWAIT) {
3246                 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
3247                 comma = 1;
3248         }
3249         if (unp_flags & UNP_CONNECTING) {
3250                 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
3251                 comma = 1;
3252         }
3253         if (unp_flags & UNP_BINDING) {
3254                 db_printf("%sUNP_BINDING", comma ? ", " : "");
3255                 comma = 1;
3256         }
3257 }
3258
3259 static void
3260 db_print_xucred(int indent, struct xucred *xu)
3261 {
3262         int comma, i;
3263
3264         db_print_indent(indent);
3265         db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
3266             xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
3267         db_print_indent(indent);
3268         db_printf("cr_groups: ");
3269         comma = 0;
3270         for (i = 0; i < xu->cr_ngroups; i++) {
3271                 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
3272                 comma = 1;
3273         }
3274         db_printf("\n");
3275 }
3276
3277 static void
3278 db_print_unprefs(int indent, struct unp_head *uh)
3279 {
3280         struct unpcb *unp;
3281         int counter;
3282
3283         counter = 0;
3284         LIST_FOREACH(unp, uh, unp_reflink) {
3285                 if (counter % 4 == 0)
3286                         db_print_indent(indent);
3287                 db_printf("%p  ", unp);
3288                 if (counter % 4 == 3)
3289                         db_printf("\n");
3290                 counter++;
3291         }
3292         if (counter != 0 && counter % 4 != 0)
3293                 db_printf("\n");
3294 }
3295
3296 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
3297 {
3298         struct unpcb *unp;
3299
3300         if (!have_addr) {
3301                 db_printf("usage: show unpcb <addr>\n");
3302                 return;
3303         }
3304         unp = (struct unpcb *)addr;
3305
3306         db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
3307             unp->unp_vnode);
3308
3309         db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
3310             unp->unp_conn);
3311
3312         db_printf("unp_refs:\n");
3313         db_print_unprefs(2, &unp->unp_refs);
3314
3315         /* XXXRW: Would be nice to print the full address, if any. */
3316         db_printf("unp_addr: %p\n", unp->unp_addr);
3317
3318         db_printf("unp_gencnt: %llu\n",
3319             (unsigned long long)unp->unp_gencnt);
3320
3321         db_printf("unp_flags: %x (", unp->unp_flags);
3322         db_print_unpflags(unp->unp_flags);
3323         db_printf(")\n");
3324
3325         db_printf("unp_peercred:\n");
3326         db_print_xucred(2, &unp->unp_peercred);
3327
3328         db_printf("unp_refcount: %u\n", unp->unp_refcount);
3329 }
3330 #endif