]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_usrreq.c
Merge once more from ^/vendor/llvm-project/release-10.x, to get the
[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/fcntl.h>
69 #include <sys/malloc.h>         /* XXX must be before <sys/file.h> */
70 #include <sys/eventhandler.h>
71 #include <sys/file.h>
72 #include <sys/filedesc.h>
73 #include <sys/kernel.h>
74 #include <sys/lock.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  * Locking key:
110  * (l)  Locked using list lock
111  * (g)  Locked using linkage lock
112  */
113
114 static uma_zone_t       unp_zone;
115 static unp_gen_t        unp_gencnt;     /* (l) */
116 static u_int            unp_count;      /* (l) Count of local sockets. */
117 static ino_t            unp_ino;        /* Prototype for fake inode numbers. */
118 static int              unp_rights;     /* (g) File descriptors in flight. */
119 static struct unp_head  unp_shead;      /* (l) List of stream sockets. */
120 static struct unp_head  unp_dhead;      /* (l) List of datagram sockets. */
121 static struct unp_head  unp_sphead;     /* (l) List of seqpacket sockets. */
122
123 struct unp_defer {
124         SLIST_ENTRY(unp_defer) ud_link;
125         struct file *ud_fp;
126 };
127 static SLIST_HEAD(, unp_defer) unp_defers;
128 static int unp_defers_count;
129
130 static const struct sockaddr    sun_noname = { sizeof(sun_noname), AF_LOCAL };
131
132 /*
133  * Garbage collection of cyclic file descriptor/socket references occurs
134  * asynchronously in a taskqueue context in order to avoid recursion and
135  * reentrance in the UNIX domain socket, file descriptor, and socket layer
136  * code.  See unp_gc() for a full description.
137  */
138 static struct timeout_task unp_gc_task;
139
140 /*
141  * The close of unix domain sockets attached as SCM_RIGHTS is
142  * postponed to the taskqueue, to avoid arbitrary recursion depth.
143  * The attached sockets might have another sockets attached.
144  */
145 static struct task      unp_defer_task;
146
147 /*
148  * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
149  * stream sockets, although the total for sender and receiver is actually
150  * only PIPSIZ.
151  *
152  * Datagram sockets really use the sendspace as the maximum datagram size,
153  * and don't really want to reserve the sendspace.  Their recvspace should be
154  * large enough for at least one max-size datagram plus address.
155  */
156 #ifndef PIPSIZ
157 #define PIPSIZ  8192
158 #endif
159 static u_long   unpst_sendspace = PIPSIZ;
160 static u_long   unpst_recvspace = PIPSIZ;
161 static u_long   unpdg_sendspace = 2*1024;       /* really max datagram size */
162 static u_long   unpdg_recvspace = 4*1024;
163 static u_long   unpsp_sendspace = PIPSIZ;       /* really max datagram size */
164 static u_long   unpsp_recvspace = PIPSIZ;
165
166 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
167     "Local domain");
168 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
169     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
170     "SOCK_STREAM");
171 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
172     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
173     "SOCK_DGRAM");
174 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
175     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
176     "SOCK_SEQPACKET");
177
178 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
179            &unpst_sendspace, 0, "Default stream send space.");
180 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
181            &unpst_recvspace, 0, "Default stream receive space.");
182 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
183            &unpdg_sendspace, 0, "Default datagram send space.");
184 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
185            &unpdg_recvspace, 0, "Default datagram receive space.");
186 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
187            &unpsp_sendspace, 0, "Default seqpacket send space.");
188 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
189            &unpsp_recvspace, 0, "Default seqpacket receive space.");
190 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
191     "File descriptors in flight.");
192 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
193     &unp_defers_count, 0,
194     "File descriptors deferred to taskqueue for close.");
195
196 /*
197  * Locking and synchronization:
198  *
199  * Three types of locks exist in the local domain socket implementation: a
200  * a global linkage rwlock, the mtxpool lock, and per-unpcb mutexes.
201  * The linkage lock protects the socket count, global generation number,
202  * and stream/datagram global lists.
203  *
204  * The mtxpool lock protects the vnode from being modified while referenced.
205  * Lock ordering requires that it be acquired before any unpcb locks.
206  *
207  * The unpcb lock (unp_mtx) protects all fields in the unpcb. Of particular
208  * note is that this includes the unp_conn field. So long as the unpcb lock
209  * is held the reference to the unpcb pointed to by unp_conn is valid. If we
210  * require that the unpcb pointed to by unp_conn remain live in cases where
211  * we need to drop the unp_mtx as when we need to acquire the lock for a
212  * second unpcb the caller must first acquire an additional reference on the
213  * second unpcb and then revalidate any state (typically check that unp_conn
214  * is non-NULL) upon requiring the initial unpcb lock. The lock ordering
215  * between unpcbs is the conventional ascending address order. Two helper
216  * routines exist for this:
217  *
218  *   - unp_pcb_lock2(unp, unp2) - which just acquires the two locks in the
219  *     safe ordering.
220  *
221  *   - unp_pcb_owned_lock2(unp, unp2, freed) - the lock for unp is held
222  *     when called. If unp is unlocked and unp2 is subsequently freed
223  *     freed will be set to 1.
224  *
225  * The helper routines for references are:
226  *
227  *   - unp_pcb_hold(unp): Can be called any time we currently hold a valid
228  *     reference to unp.
229  *
230  *    - unp_pcb_rele(unp): The caller must hold the unp lock. If we are
231  *      releasing the last reference, detach must have been called thus
232  *      unp->unp_socket be NULL.
233  *
234  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
235  * allocated in pru_attach() and freed in pru_detach().  The validity of that
236  * pointer is an invariant, so no lock is required to dereference the so_pcb
237  * pointer if a valid socket reference is held by the caller.  In practice,
238  * this is always true during operations performed on a socket.  Each unpcb
239  * has a back-pointer to its socket, unp_socket, which will be stable under
240  * the same circumstances.
241  *
242  * This pointer may only be safely dereferenced as long as a valid reference
243  * to the unpcb is held.  Typically, this reference will be from the socket,
244  * or from another unpcb when the referring unpcb's lock is held (in order
245  * that the reference not be invalidated during use).  For example, to follow
246  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
247  * that detach is not run clearing unp_socket.
248  *
249  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
250  * protocols, bind() is a non-atomic operation, and connect() requires
251  * potential sleeping in the protocol, due to potentially waiting on local or
252  * distributed file systems.  We try to separate "lookup" operations, which
253  * may sleep, and the IPC operations themselves, which typically can occur
254  * with relative atomicity as locks can be held over the entire operation.
255  *
256  * Another tricky issue is simultaneous multi-threaded or multi-process
257  * access to a single UNIX domain socket.  These are handled by the flags
258  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
259  * binding, both of which involve dropping UNIX domain socket locks in order
260  * to perform namei() and other file system operations.
261  */
262 static struct rwlock    unp_link_rwlock;
263 static struct mtx       unp_defers_lock;
264
265 #define UNP_LINK_LOCK_INIT()            rw_init(&unp_link_rwlock,       \
266                                             "unp_link_rwlock")
267
268 #define UNP_LINK_LOCK_ASSERT()          rw_assert(&unp_link_rwlock,     \
269                                             RA_LOCKED)
270 #define UNP_LINK_UNLOCK_ASSERT()        rw_assert(&unp_link_rwlock,     \
271                                             RA_UNLOCKED)
272
273 #define UNP_LINK_RLOCK()                rw_rlock(&unp_link_rwlock)
274 #define UNP_LINK_RUNLOCK()              rw_runlock(&unp_link_rwlock)
275 #define UNP_LINK_WLOCK()                rw_wlock(&unp_link_rwlock)
276 #define UNP_LINK_WUNLOCK()              rw_wunlock(&unp_link_rwlock)
277 #define UNP_LINK_WLOCK_ASSERT()         rw_assert(&unp_link_rwlock,     \
278                                             RA_WLOCKED)
279 #define UNP_LINK_WOWNED()               rw_wowned(&unp_link_rwlock)
280
281 #define UNP_DEFERRED_LOCK_INIT()        mtx_init(&unp_defers_lock, \
282                                             "unp_defer", NULL, MTX_DEF)
283 #define UNP_DEFERRED_LOCK()             mtx_lock(&unp_defers_lock)
284 #define UNP_DEFERRED_UNLOCK()           mtx_unlock(&unp_defers_lock)
285
286 #define UNP_REF_LIST_LOCK()             UNP_DEFERRED_LOCK();
287 #define UNP_REF_LIST_UNLOCK()           UNP_DEFERRED_UNLOCK();
288
289 #define UNP_PCB_LOCK_INIT(unp)          mtx_init(&(unp)->unp_mtx,       \
290                                             "unp", "unp",       \
291                                             MTX_DUPOK|MTX_DEF)
292 #define UNP_PCB_LOCK_DESTROY(unp)       mtx_destroy(&(unp)->unp_mtx)
293 #define UNP_PCB_LOCK(unp)               mtx_lock(&(unp)->unp_mtx)
294 #define UNP_PCB_TRYLOCK(unp)            mtx_trylock(&(unp)->unp_mtx)
295 #define UNP_PCB_UNLOCK(unp)             mtx_unlock(&(unp)->unp_mtx)
296 #define UNP_PCB_OWNED(unp)              mtx_owned(&(unp)->unp_mtx)
297 #define UNP_PCB_LOCK_ASSERT(unp)        mtx_assert(&(unp)->unp_mtx, MA_OWNED)
298 #define UNP_PCB_UNLOCK_ASSERT(unp)      mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
299
300 static int      uipc_connect2(struct socket *, struct socket *);
301 static int      uipc_ctloutput(struct socket *, struct sockopt *);
302 static int      unp_connect(struct socket *, struct sockaddr *,
303                     struct thread *);
304 static int      unp_connectat(int, struct socket *, struct sockaddr *,
305                     struct thread *);
306 static int      unp_connect2(struct socket *so, struct socket *so2, int);
307 static void     unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
308 static void     unp_dispose(struct socket *so);
309 static void     unp_dispose_mbuf(struct mbuf *);
310 static void     unp_shutdown(struct unpcb *);
311 static void     unp_drop(struct unpcb *);
312 static void     unp_gc(__unused void *, int);
313 static void     unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
314 static void     unp_discard(struct file *);
315 static void     unp_freerights(struct filedescent **, int);
316 static void     unp_init(void);
317 static int      unp_internalize(struct mbuf **, struct thread *);
318 static void     unp_internalize_fp(struct file *);
319 static int      unp_externalize(struct mbuf *, struct mbuf **, int);
320 static int      unp_externalize_fp(struct file *);
321 static struct mbuf      *unp_addsockcred(struct thread *, struct mbuf *);
322 static void     unp_process_defers(void * __unused, int);
323
324 static void
325 unp_pcb_hold(struct unpcb *unp)
326 {
327         MPASS(unp->unp_refcount);
328         refcount_acquire(&unp->unp_refcount);
329 }
330
331 static int
332 unp_pcb_rele(struct unpcb *unp)
333 {
334         int freed;
335
336         UNP_PCB_LOCK_ASSERT(unp);
337         MPASS(unp->unp_refcount);
338         if ((freed = refcount_release(&unp->unp_refcount))) {
339                 /* we got here with having detached? */
340                 MPASS(unp->unp_socket == NULL);
341                 UNP_PCB_UNLOCK(unp);
342                 UNP_PCB_LOCK_DESTROY(unp);
343                 uma_zfree(unp_zone, unp);
344         }
345         return (freed);
346 }
347
348 static void
349 unp_pcb_lock2(struct unpcb *unp, struct unpcb *unp2)
350 {
351         MPASS(unp != unp2);
352         UNP_PCB_UNLOCK_ASSERT(unp);
353         UNP_PCB_UNLOCK_ASSERT(unp2);
354         if ((uintptr_t)unp2 > (uintptr_t)unp) {
355                 UNP_PCB_LOCK(unp);
356                 UNP_PCB_LOCK(unp2);
357         } else {
358                 UNP_PCB_LOCK(unp2);
359                 UNP_PCB_LOCK(unp);
360         }
361 }
362
363 static __noinline void
364 unp_pcb_owned_lock2_slowpath(struct unpcb *unp, struct unpcb **unp2p,
365     int *freed)
366 {
367         struct unpcb *unp2;
368
369         unp2 = *unp2p;
370         unp_pcb_hold(unp2);
371         UNP_PCB_UNLOCK(unp);
372         UNP_PCB_LOCK(unp2);
373         UNP_PCB_LOCK(unp);
374         *freed = unp_pcb_rele(unp2);
375         if (*freed)
376                 *unp2p = NULL;
377 }
378
379 #define unp_pcb_owned_lock2(unp, unp2, freed) do {                      \
380         freed = 0;                                                      \
381         UNP_PCB_LOCK_ASSERT(unp);                                       \
382         UNP_PCB_UNLOCK_ASSERT(unp2);                                    \
383         MPASS((unp) != (unp2));                                         \
384         if (__predict_true(UNP_PCB_TRYLOCK(unp2)))                      \
385                 break;                                                  \
386         else if ((uintptr_t)(unp2) > (uintptr_t)(unp))                  \
387                 UNP_PCB_LOCK(unp2);                                     \
388         else                                                            \
389                 unp_pcb_owned_lock2_slowpath((unp), &(unp2), &freed);   \
390 } while (0)
391
392 /*
393  * Definitions of protocols supported in the LOCAL domain.
394  */
395 static struct domain localdomain;
396 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
397 static struct pr_usrreqs uipc_usrreqs_seqpacket;
398 static struct protosw localsw[] = {
399 {
400         .pr_type =              SOCK_STREAM,
401         .pr_domain =            &localdomain,
402         .pr_flags =             PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
403         .pr_ctloutput =         &uipc_ctloutput,
404         .pr_usrreqs =           &uipc_usrreqs_stream
405 },
406 {
407         .pr_type =              SOCK_DGRAM,
408         .pr_domain =            &localdomain,
409         .pr_flags =             PR_ATOMIC|PR_ADDR|PR_RIGHTS,
410         .pr_ctloutput =         &uipc_ctloutput,
411         .pr_usrreqs =           &uipc_usrreqs_dgram
412 },
413 {
414         .pr_type =              SOCK_SEQPACKET,
415         .pr_domain =            &localdomain,
416
417         /*
418          * XXXRW: For now, PR_ADDR because soreceive will bump into them
419          * due to our use of sbappendaddr.  A new sbappend variants is needed
420          * that supports both atomic record writes and control data.
421          */
422         .pr_flags =             PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
423                                     PR_RIGHTS,
424         .pr_ctloutput =         &uipc_ctloutput,
425         .pr_usrreqs =           &uipc_usrreqs_seqpacket,
426 },
427 };
428
429 static struct domain localdomain = {
430         .dom_family =           AF_LOCAL,
431         .dom_name =             "local",
432         .dom_init =             unp_init,
433         .dom_externalize =      unp_externalize,
434         .dom_dispose =          unp_dispose,
435         .dom_protosw =          localsw,
436         .dom_protoswNPROTOSW =  &localsw[nitems(localsw)]
437 };
438 DOMAIN_SET(local);
439
440 static void
441 uipc_abort(struct socket *so)
442 {
443         struct unpcb *unp, *unp2;
444
445         unp = sotounpcb(so);
446         KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
447         UNP_PCB_UNLOCK_ASSERT(unp);
448
449         UNP_PCB_LOCK(unp);
450         unp2 = unp->unp_conn;
451         if (unp2 != NULL) {
452                 unp_pcb_hold(unp2);
453                 UNP_PCB_UNLOCK(unp);
454                 unp_drop(unp2);
455         } else
456                 UNP_PCB_UNLOCK(unp);
457 }
458
459 static int
460 uipc_accept(struct socket *so, struct sockaddr **nam)
461 {
462         struct unpcb *unp, *unp2;
463         const struct sockaddr *sa;
464
465         /*
466          * Pass back name of connected socket, if it was bound and we are
467          * still connected (our peer may have closed already!).
468          */
469         unp = sotounpcb(so);
470         KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
471
472         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
473         UNP_LINK_RLOCK();
474         unp2 = unp->unp_conn;
475         if (unp2 != NULL && unp2->unp_addr != NULL) {
476                 UNP_PCB_LOCK(unp2);
477                 sa = (struct sockaddr *) unp2->unp_addr;
478                 bcopy(sa, *nam, sa->sa_len);
479                 UNP_PCB_UNLOCK(unp2);
480         } else {
481                 sa = &sun_noname;
482                 bcopy(sa, *nam, sa->sa_len);
483         }
484         UNP_LINK_RUNLOCK();
485         return (0);
486 }
487
488 static int
489 uipc_attach(struct socket *so, int proto, struct thread *td)
490 {
491         u_long sendspace, recvspace;
492         struct unpcb *unp;
493         int error;
494         bool locked;
495
496         KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
497         if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
498                 switch (so->so_type) {
499                 case SOCK_STREAM:
500                         sendspace = unpst_sendspace;
501                         recvspace = unpst_recvspace;
502                         break;
503
504                 case SOCK_DGRAM:
505                         sendspace = unpdg_sendspace;
506                         recvspace = unpdg_recvspace;
507                         break;
508
509                 case SOCK_SEQPACKET:
510                         sendspace = unpsp_sendspace;
511                         recvspace = unpsp_recvspace;
512                         break;
513
514                 default:
515                         panic("uipc_attach");
516                 }
517                 error = soreserve(so, sendspace, recvspace);
518                 if (error)
519                         return (error);
520         }
521         unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
522         if (unp == NULL)
523                 return (ENOBUFS);
524         LIST_INIT(&unp->unp_refs);
525         UNP_PCB_LOCK_INIT(unp);
526         unp->unp_socket = so;
527         so->so_pcb = unp;
528         unp->unp_refcount = 1;
529
530         if ((locked = UNP_LINK_WOWNED()) == false)
531                 UNP_LINK_WLOCK();
532
533         unp->unp_gencnt = ++unp_gencnt;
534         unp->unp_ino = ++unp_ino;
535         unp_count++;
536         switch (so->so_type) {
537         case SOCK_STREAM:
538                 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
539                 break;
540
541         case SOCK_DGRAM:
542                 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
543                 break;
544
545         case SOCK_SEQPACKET:
546                 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
547                 break;
548
549         default:
550                 panic("uipc_attach");
551         }
552
553         if (locked == false)
554                 UNP_LINK_WUNLOCK();
555
556         return (0);
557 }
558
559 static int
560 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
561 {
562         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
563         struct vattr vattr;
564         int error, namelen;
565         struct nameidata nd;
566         struct unpcb *unp;
567         struct vnode *vp;
568         struct mount *mp;
569         cap_rights_t rights;
570         char *buf;
571
572         if (nam->sa_family != AF_UNIX)
573                 return (EAFNOSUPPORT);
574
575         unp = sotounpcb(so);
576         KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
577
578         if (soun->sun_len > sizeof(struct sockaddr_un))
579                 return (EINVAL);
580         namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
581         if (namelen <= 0)
582                 return (EINVAL);
583
584         /*
585          * We don't allow simultaneous bind() calls on a single UNIX domain
586          * socket, so flag in-progress operations, and return an error if an
587          * operation is already in progress.
588          *
589          * Historically, we have not allowed a socket to be rebound, so this
590          * also returns an error.  Not allowing re-binding simplifies the
591          * implementation and avoids a great many possible failure modes.
592          */
593         UNP_PCB_LOCK(unp);
594         if (unp->unp_vnode != NULL) {
595                 UNP_PCB_UNLOCK(unp);
596                 return (EINVAL);
597         }
598         if (unp->unp_flags & UNP_BINDING) {
599                 UNP_PCB_UNLOCK(unp);
600                 return (EALREADY);
601         }
602         unp->unp_flags |= UNP_BINDING;
603         UNP_PCB_UNLOCK(unp);
604
605         buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
606         bcopy(soun->sun_path, buf, namelen);
607         buf[namelen] = 0;
608
609 restart:
610         NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
611             UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
612 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
613         error = namei(&nd);
614         if (error)
615                 goto error;
616         vp = nd.ni_vp;
617         if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
618                 NDFREE(&nd, NDF_ONLY_PNBUF);
619                 if (nd.ni_dvp == vp)
620                         vrele(nd.ni_dvp);
621                 else
622                         vput(nd.ni_dvp);
623                 if (vp != NULL) {
624                         vrele(vp);
625                         error = EADDRINUSE;
626                         goto error;
627                 }
628                 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
629                 if (error)
630                         goto error;
631                 goto restart;
632         }
633         VATTR_NULL(&vattr);
634         vattr.va_type = VSOCK;
635         vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
636 #ifdef MAC
637         error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
638             &vattr);
639 #endif
640         if (error == 0)
641                 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
642         NDFREE(&nd, NDF_ONLY_PNBUF);
643         vput(nd.ni_dvp);
644         if (error) {
645                 vn_finished_write(mp);
646                 goto error;
647         }
648         vp = nd.ni_vp;
649         ASSERT_VOP_ELOCKED(vp, "uipc_bind");
650         soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
651
652         UNP_PCB_LOCK(unp);
653         VOP_UNP_BIND(vp, unp);
654         unp->unp_vnode = vp;
655         unp->unp_addr = soun;
656         unp->unp_flags &= ~UNP_BINDING;
657         UNP_PCB_UNLOCK(unp);
658         VOP_UNLOCK(vp);
659         vn_finished_write(mp);
660         free(buf, M_TEMP);
661         return (0);
662
663 error:
664         UNP_PCB_LOCK(unp);
665         unp->unp_flags &= ~UNP_BINDING;
666         UNP_PCB_UNLOCK(unp);
667         free(buf, M_TEMP);
668         return (error);
669 }
670
671 static int
672 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
673 {
674
675         return (uipc_bindat(AT_FDCWD, so, nam, td));
676 }
677
678 static int
679 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
680 {
681         int error;
682
683         KASSERT(td == curthread, ("uipc_connect: td != curthread"));
684         error = unp_connect(so, nam, td);
685         return (error);
686 }
687
688 static int
689 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
690     struct thread *td)
691 {
692         int error;
693
694         KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
695         error = unp_connectat(fd, so, nam, td);
696         return (error);
697 }
698
699 static void
700 uipc_close(struct socket *so)
701 {
702         struct unpcb *unp, *unp2;
703         struct vnode *vp = NULL;
704         struct mtx *vplock;
705         int freed;
706         unp = sotounpcb(so);
707         KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
708
709         vplock = NULL;
710         if ((vp = unp->unp_vnode) != NULL) {
711                 vplock = mtx_pool_find(mtxpool_sleep, vp);
712                 mtx_lock(vplock);
713         }
714         UNP_PCB_LOCK(unp);
715         if (vp && unp->unp_vnode == NULL) {
716                 mtx_unlock(vplock);
717                 vp = NULL;
718         }
719         if (vp != NULL) {
720                 VOP_UNP_DETACH(vp);
721                 unp->unp_vnode = NULL;
722         }
723         unp2 = unp->unp_conn;
724         unp_pcb_hold(unp);
725         if (__predict_false(unp == unp2)) {
726                 unp_disconnect(unp, unp2);
727         } else if (unp2 != NULL) {
728                 unp_pcb_hold(unp2);
729                 unp_pcb_owned_lock2(unp, unp2, freed);
730                 unp_disconnect(unp, unp2);
731                 if (unp_pcb_rele(unp2) == 0)
732                         UNP_PCB_UNLOCK(unp2);
733         }
734         if (unp_pcb_rele(unp) == 0)
735                 UNP_PCB_UNLOCK(unp);
736         if (vp) {
737                 mtx_unlock(vplock);
738                 vrele(vp);
739         }
740 }
741
742 static int
743 uipc_connect2(struct socket *so1, struct socket *so2)
744 {
745         struct unpcb *unp, *unp2;
746         int error;
747
748         unp = so1->so_pcb;
749         KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
750         unp2 = so2->so_pcb;
751         KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
752         if (unp != unp2)
753                 unp_pcb_lock2(unp, unp2);
754         else
755                 UNP_PCB_LOCK(unp);
756         error = unp_connect2(so1, so2, PRU_CONNECT2);
757         if (unp != unp2)
758                 UNP_PCB_UNLOCK(unp2);
759         UNP_PCB_UNLOCK(unp);
760         return (error);
761 }
762
763 static void
764 uipc_detach(struct socket *so)
765 {
766         struct unpcb *unp, *unp2;
767         struct mtx *vplock;
768         struct vnode *vp;
769         int freeunp, local_unp_rights;
770
771         unp = sotounpcb(so);
772         KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
773
774         vp = NULL;
775         vplock = NULL;
776         local_unp_rights = 0;
777
778         UNP_LINK_WLOCK();
779         LIST_REMOVE(unp, unp_link);
780         if (unp->unp_gcflag & UNPGC_DEAD)
781                 LIST_REMOVE(unp, unp_dead);
782         unp->unp_gencnt = ++unp_gencnt;
783         --unp_count;
784         UNP_LINK_WUNLOCK();
785
786         UNP_PCB_UNLOCK_ASSERT(unp);
787  restart:
788         if ((vp = unp->unp_vnode) != NULL) {
789                 vplock = mtx_pool_find(mtxpool_sleep, vp);
790                 mtx_lock(vplock);
791         }
792         UNP_PCB_LOCK(unp);
793         if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
794                 if (vplock)
795                         mtx_unlock(vplock);
796                 UNP_PCB_UNLOCK(unp);
797                 goto restart;
798         }
799         if ((vp = unp->unp_vnode) != NULL) {
800                 VOP_UNP_DETACH(vp);
801                 unp->unp_vnode = NULL;
802         }
803         if (__predict_false(unp == unp->unp_conn)) {
804                 unp_disconnect(unp, unp);
805                 unp2 = NULL;
806         } else {
807                 if ((unp2 = unp->unp_conn) != NULL) {
808                         unp_pcb_owned_lock2(unp, unp2, freeunp);
809                         if (freeunp)
810                                 unp2 = NULL;
811                 }
812                 unp_pcb_hold(unp);
813                 if (unp2 != NULL) {
814                         unp_pcb_hold(unp2);
815                         unp_disconnect(unp, unp2);
816                         if (unp_pcb_rele(unp2) == 0)
817                                 UNP_PCB_UNLOCK(unp2);
818                 }
819         }
820         UNP_PCB_UNLOCK(unp);
821         UNP_REF_LIST_LOCK();
822         while (!LIST_EMPTY(&unp->unp_refs)) {
823                 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
824
825                 unp_pcb_hold(ref);
826                 UNP_REF_LIST_UNLOCK();
827
828                 MPASS(ref != unp);
829                 UNP_PCB_UNLOCK_ASSERT(ref);
830                 unp_drop(ref);
831                 UNP_REF_LIST_LOCK();
832         }
833
834         UNP_REF_LIST_UNLOCK();
835         UNP_PCB_LOCK(unp);
836         freeunp = unp_pcb_rele(unp);
837         MPASS(freeunp == 0);
838         local_unp_rights = unp_rights;
839         unp->unp_socket->so_pcb = NULL;
840         unp->unp_socket = NULL;
841         free(unp->unp_addr, M_SONAME);
842         unp->unp_addr = NULL;
843         if (!unp_pcb_rele(unp))
844                 UNP_PCB_UNLOCK(unp);
845         if (vp) {
846                 mtx_unlock(vplock);
847                 vrele(vp);
848         }
849         if (local_unp_rights)
850                 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
851 }
852
853 static int
854 uipc_disconnect(struct socket *so)
855 {
856         struct unpcb *unp, *unp2;
857         int freed;
858
859         unp = sotounpcb(so);
860         KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
861
862         UNP_PCB_LOCK(unp);
863         if ((unp2 = unp->unp_conn) == NULL) {
864                 UNP_PCB_UNLOCK(unp);
865                 return (0);
866         }
867         if (__predict_true(unp != unp2)) {
868                 unp_pcb_owned_lock2(unp, unp2, freed);
869                 if (__predict_false(freed)) {
870                         UNP_PCB_UNLOCK(unp);
871                         return (0);
872                 }
873                 unp_pcb_hold(unp2);
874         }
875         unp_pcb_hold(unp);
876         unp_disconnect(unp, unp2);
877         if (unp_pcb_rele(unp) == 0)
878                 UNP_PCB_UNLOCK(unp);
879         if ((unp != unp2) && unp_pcb_rele(unp2) == 0)
880                 UNP_PCB_UNLOCK(unp2);
881         return (0);
882 }
883
884 static int
885 uipc_listen(struct socket *so, int backlog, struct thread *td)
886 {
887         struct unpcb *unp;
888         int error;
889
890         if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
891                 return (EOPNOTSUPP);
892
893         unp = sotounpcb(so);
894         KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
895
896         UNP_PCB_LOCK(unp);
897         if (unp->unp_vnode == NULL) {
898                 /* Already connected or not bound to an address. */
899                 error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
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 connect_internal(struct socket *so, struct sockaddr *nam, struct thread *td)
1000 {
1001         int error;
1002         struct unpcb *unp;
1003
1004         unp = so->so_pcb;
1005         if (unp->unp_conn != NULL)
1006                 return (EISCONN);
1007         error = unp_connect(so, nam, td);
1008         if (error)
1009                 return (error);
1010         UNP_PCB_LOCK(unp);
1011         if (unp->unp_conn == NULL) {
1012                 UNP_PCB_UNLOCK(unp);
1013                 if (error == 0)
1014                         error = ENOTCONN;
1015         }
1016         return (error);
1017 }
1018
1019 static int
1020 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1021     struct mbuf *control, struct thread *td)
1022 {
1023         struct unpcb *unp, *unp2;
1024         struct socket *so2;
1025         u_int mbcnt, sbcc;
1026         int freed, error;
1027
1028         unp = sotounpcb(so);
1029         KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
1030         KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
1031             so->so_type == SOCK_SEQPACKET,
1032             ("%s: socktype %d", __func__, so->so_type));
1033
1034         freed = error = 0;
1035         if (flags & PRUS_OOB) {
1036                 error = EOPNOTSUPP;
1037                 goto release;
1038         }
1039         if (control != NULL && (error = unp_internalize(&control, td)))
1040                 goto release;
1041
1042         unp2 = NULL;
1043         switch (so->so_type) {
1044         case SOCK_DGRAM:
1045         {
1046                 const struct sockaddr *from;
1047
1048                 if (nam != NULL) {
1049                         /*
1050                          * We return with UNP_PCB_LOCK_HELD so we know that
1051                          * the reference is live if the pointer is valid.
1052                          */
1053                         if ((error = connect_internal(so, nam, td)))
1054                                 break;
1055                         MPASS(unp->unp_conn != NULL);
1056                         unp2 = unp->unp_conn;
1057                 } else  {
1058                         UNP_PCB_LOCK(unp);
1059
1060                         /*
1061                          * Because connect() and send() are non-atomic in a sendto()
1062                          * with a target address, it's possible that the socket will
1063                          * have disconnected before the send() can run.  In that case
1064                          * return the slightly counter-intuitive but otherwise
1065                          * correct error that the socket is not connected.
1066                          */
1067                         if ((unp2 = unp->unp_conn)  == NULL) {
1068                                 UNP_PCB_UNLOCK(unp);
1069                                 error = ENOTCONN;
1070                                 break;
1071                         }
1072                 }
1073                 if (__predict_false(unp == unp2)) {
1074                         if (unp->unp_socket == NULL) {
1075                                 error = ENOTCONN;
1076                                 break;
1077                         }
1078                         goto connect_self;
1079                 }
1080                 unp_pcb_owned_lock2(unp, unp2, freed);
1081                 if (__predict_false(freed)) {
1082                         UNP_PCB_UNLOCK(unp);
1083                         error = ENOTCONN;
1084                         break;
1085                 }
1086                 /*
1087                  * The socket referencing unp2 may have been closed
1088                  * or unp may have been disconnected if the unp lock
1089                  * was dropped to acquire unp2.
1090                  */
1091                 if (__predict_false(unp->unp_conn == NULL) ||
1092                         unp2->unp_socket == NULL) {
1093                         UNP_PCB_UNLOCK(unp);
1094                         if (unp_pcb_rele(unp2) == 0)
1095                                 UNP_PCB_UNLOCK(unp2);
1096                         error = ENOTCONN;
1097                         break;
1098                 }
1099         connect_self:
1100                 if (unp2->unp_flags & UNP_WANTCRED)
1101                         control = unp_addsockcred(td, control);
1102                 if (unp->unp_addr != NULL)
1103                         from = (struct sockaddr *)unp->unp_addr;
1104                 else
1105                         from = &sun_noname;
1106                 so2 = unp2->unp_socket;
1107                 SOCKBUF_LOCK(&so2->so_rcv);
1108                 if (sbappendaddr_locked(&so2->so_rcv, from, m,
1109                     control)) {
1110                         sorwakeup_locked(so2);
1111                         m = NULL;
1112                         control = NULL;
1113                 } else {
1114                         SOCKBUF_UNLOCK(&so2->so_rcv);
1115                         error = ENOBUFS;
1116                 }
1117                 if (nam != NULL)
1118                         unp_disconnect(unp, unp2);
1119                 if (__predict_true(unp != unp2))
1120                         UNP_PCB_UNLOCK(unp2);
1121                 UNP_PCB_UNLOCK(unp);
1122                 break;
1123         }
1124
1125         case SOCK_SEQPACKET:
1126         case SOCK_STREAM:
1127                 if ((so->so_state & SS_ISCONNECTED) == 0) {
1128                         if (nam != NULL) {
1129                                 if ((error = connect_internal(so, nam, td)))
1130                                         break;
1131                         } else  {
1132                                 error = ENOTCONN;
1133                                 break;
1134                         }
1135                 } else if ((unp2 = unp->unp_conn) == NULL) {
1136                         error = ENOTCONN;
1137                         break;
1138                 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1139                         error = EPIPE;
1140                         break;
1141                 } else {
1142                         UNP_PCB_LOCK(unp);
1143                         if ((unp2 = unp->unp_conn) == NULL) {
1144                                 UNP_PCB_UNLOCK(unp);
1145                                 error = ENOTCONN;
1146                                 break;
1147                         }
1148                 }
1149                 unp_pcb_owned_lock2(unp, unp2, freed);
1150                 UNP_PCB_UNLOCK(unp);
1151                 if (__predict_false(freed)) {
1152                         error = ENOTCONN;
1153                         break;
1154                 }
1155                 if ((so2 = unp2->unp_socket) == NULL) {
1156                         UNP_PCB_UNLOCK(unp2);
1157                         error = ENOTCONN;
1158                         break;
1159                 }
1160                 SOCKBUF_LOCK(&so2->so_rcv);
1161                 if (unp2->unp_flags & UNP_WANTCRED) {
1162                         /*
1163                          * Credentials are passed only once on SOCK_STREAM
1164                          * and SOCK_SEQPACKET.
1165                          */
1166                         unp2->unp_flags &= ~UNP_WANTCRED;
1167                         control = unp_addsockcred(td, control);
1168                 }
1169
1170                 /*
1171                  * Send to paired receive port and wake up readers.  Don't
1172                  * check for space available in the receive buffer if we're
1173                  * attaching ancillary data; Unix domain sockets only check
1174                  * for space in the sending sockbuf, and that check is
1175                  * performed one level up the stack.  At that level we cannot
1176                  * precisely account for the amount of buffer space used
1177                  * (e.g., because control messages are not yet internalized).
1178                  */
1179                 switch (so->so_type) {
1180                 case SOCK_STREAM:
1181                         if (control != NULL) {
1182                                 sbappendcontrol_locked(&so2->so_rcv, m,
1183                                     control);
1184                                 control = NULL;
1185                         } else
1186                                 sbappend_locked(&so2->so_rcv, m, flags);
1187                         break;
1188
1189                 case SOCK_SEQPACKET: {
1190                         const struct sockaddr *from;
1191
1192                         from = &sun_noname;
1193                         if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1194                             from, m, control))
1195                                 control = NULL;
1196                         break;
1197                         }
1198                 }
1199
1200                 mbcnt = so2->so_rcv.sb_mbcnt;
1201                 sbcc = sbavail(&so2->so_rcv);
1202                 if (sbcc)
1203                         sorwakeup_locked(so2);
1204                 else
1205                         SOCKBUF_UNLOCK(&so2->so_rcv);
1206
1207                 /*
1208                  * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1209                  * it would be possible for uipc_rcvd to be called at this
1210                  * point, drain the receiving sockbuf, clear SB_STOP, and then
1211                  * we would set SB_STOP below.  That could lead to an empty
1212                  * sockbuf having SB_STOP set
1213                  */
1214                 SOCKBUF_LOCK(&so->so_snd);
1215                 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1216                         so->so_snd.sb_flags |= SB_STOP;
1217                 SOCKBUF_UNLOCK(&so->so_snd);
1218                 UNP_PCB_UNLOCK(unp2);
1219                 m = NULL;
1220                 break;
1221         }
1222
1223         /*
1224          * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1225          */
1226         if (flags & PRUS_EOF) {
1227                 UNP_PCB_LOCK(unp);
1228                 socantsendmore(so);
1229                 unp_shutdown(unp);
1230                 UNP_PCB_UNLOCK(unp);
1231         }
1232         if (control != NULL && error != 0)
1233                 unp_dispose_mbuf(control);
1234
1235 release:
1236         if (control != NULL)
1237                 m_freem(control);
1238         /*
1239          * In case of PRUS_NOTREADY, uipc_ready() is responsible
1240          * for freeing memory.
1241          */   
1242         if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1243                 m_freem(m);
1244         return (error);
1245 }
1246
1247 static int
1248 uipc_ready(struct socket *so, struct mbuf *m, int count)
1249 {
1250         struct unpcb *unp, *unp2;
1251         struct socket *so2;
1252         int error;
1253
1254         unp = sotounpcb(so);
1255
1256         UNP_PCB_LOCK(unp);
1257         if ((unp2 = unp->unp_conn) == NULL) {
1258                 UNP_PCB_UNLOCK(unp);
1259                 goto error;
1260         }
1261         if (unp != unp2) {
1262                 if (UNP_PCB_TRYLOCK(unp2) == 0) {
1263                         unp_pcb_hold(unp2);
1264                         UNP_PCB_UNLOCK(unp);
1265                         UNP_PCB_LOCK(unp2);
1266                         if (unp_pcb_rele(unp2))
1267                                 goto error;
1268                 } else
1269                         UNP_PCB_UNLOCK(unp);
1270         }
1271         so2 = unp2->unp_socket;
1272
1273         SOCKBUF_LOCK(&so2->so_rcv);
1274         if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1275                 sorwakeup_locked(so2);
1276         else
1277                 SOCKBUF_UNLOCK(&so2->so_rcv);
1278
1279         UNP_PCB_UNLOCK(unp2);
1280
1281         return (error);
1282  error:
1283         for (int i = 0; i < count; i++)
1284                 m = m_free(m);
1285         return (ECONNRESET);
1286 }
1287
1288 static int
1289 uipc_sense(struct socket *so, struct stat *sb)
1290 {
1291         struct unpcb *unp;
1292
1293         unp = sotounpcb(so);
1294         KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1295
1296         sb->st_blksize = so->so_snd.sb_hiwat;
1297         sb->st_dev = NODEV;
1298         sb->st_ino = unp->unp_ino;
1299         return (0);
1300 }
1301
1302 static int
1303 uipc_shutdown(struct socket *so)
1304 {
1305         struct unpcb *unp;
1306
1307         unp = sotounpcb(so);
1308         KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1309
1310         UNP_PCB_LOCK(unp);
1311         socantsendmore(so);
1312         unp_shutdown(unp);
1313         UNP_PCB_UNLOCK(unp);
1314         return (0);
1315 }
1316
1317 static int
1318 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1319 {
1320         struct unpcb *unp;
1321         const struct sockaddr *sa;
1322
1323         unp = sotounpcb(so);
1324         KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1325
1326         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1327         UNP_PCB_LOCK(unp);
1328         if (unp->unp_addr != NULL)
1329                 sa = (struct sockaddr *) unp->unp_addr;
1330         else
1331                 sa = &sun_noname;
1332         bcopy(sa, *nam, sa->sa_len);
1333         UNP_PCB_UNLOCK(unp);
1334         return (0);
1335 }
1336
1337 static struct pr_usrreqs uipc_usrreqs_dgram = {
1338         .pru_abort =            uipc_abort,
1339         .pru_accept =           uipc_accept,
1340         .pru_attach =           uipc_attach,
1341         .pru_bind =             uipc_bind,
1342         .pru_bindat =           uipc_bindat,
1343         .pru_connect =          uipc_connect,
1344         .pru_connectat =        uipc_connectat,
1345         .pru_connect2 =         uipc_connect2,
1346         .pru_detach =           uipc_detach,
1347         .pru_disconnect =       uipc_disconnect,
1348         .pru_listen =           uipc_listen,
1349         .pru_peeraddr =         uipc_peeraddr,
1350         .pru_rcvd =             uipc_rcvd,
1351         .pru_send =             uipc_send,
1352         .pru_sense =            uipc_sense,
1353         .pru_shutdown =         uipc_shutdown,
1354         .pru_sockaddr =         uipc_sockaddr,
1355         .pru_soreceive =        soreceive_dgram,
1356         .pru_close =            uipc_close,
1357 };
1358
1359 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1360         .pru_abort =            uipc_abort,
1361         .pru_accept =           uipc_accept,
1362         .pru_attach =           uipc_attach,
1363         .pru_bind =             uipc_bind,
1364         .pru_bindat =           uipc_bindat,
1365         .pru_connect =          uipc_connect,
1366         .pru_connectat =        uipc_connectat,
1367         .pru_connect2 =         uipc_connect2,
1368         .pru_detach =           uipc_detach,
1369         .pru_disconnect =       uipc_disconnect,
1370         .pru_listen =           uipc_listen,
1371         .pru_peeraddr =         uipc_peeraddr,
1372         .pru_rcvd =             uipc_rcvd,
1373         .pru_send =             uipc_send,
1374         .pru_sense =            uipc_sense,
1375         .pru_shutdown =         uipc_shutdown,
1376         .pru_sockaddr =         uipc_sockaddr,
1377         .pru_soreceive =        soreceive_generic,      /* XXX: or...? */
1378         .pru_close =            uipc_close,
1379 };
1380
1381 static struct pr_usrreqs uipc_usrreqs_stream = {
1382         .pru_abort =            uipc_abort,
1383         .pru_accept =           uipc_accept,
1384         .pru_attach =           uipc_attach,
1385         .pru_bind =             uipc_bind,
1386         .pru_bindat =           uipc_bindat,
1387         .pru_connect =          uipc_connect,
1388         .pru_connectat =        uipc_connectat,
1389         .pru_connect2 =         uipc_connect2,
1390         .pru_detach =           uipc_detach,
1391         .pru_disconnect =       uipc_disconnect,
1392         .pru_listen =           uipc_listen,
1393         .pru_peeraddr =         uipc_peeraddr,
1394         .pru_rcvd =             uipc_rcvd,
1395         .pru_send =             uipc_send,
1396         .pru_ready =            uipc_ready,
1397         .pru_sense =            uipc_sense,
1398         .pru_shutdown =         uipc_shutdown,
1399         .pru_sockaddr =         uipc_sockaddr,
1400         .pru_soreceive =        soreceive_generic,
1401         .pru_close =            uipc_close,
1402 };
1403
1404 static int
1405 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1406 {
1407         struct unpcb *unp;
1408         struct xucred xu;
1409         int error, optval;
1410
1411         if (sopt->sopt_level != 0)
1412                 return (EINVAL);
1413
1414         unp = sotounpcb(so);
1415         KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1416         error = 0;
1417         switch (sopt->sopt_dir) {
1418         case SOPT_GET:
1419                 switch (sopt->sopt_name) {
1420                 case LOCAL_PEERCRED:
1421                         UNP_PCB_LOCK(unp);
1422                         if (unp->unp_flags & UNP_HAVEPC)
1423                                 xu = unp->unp_peercred;
1424                         else {
1425                                 if (so->so_type == SOCK_STREAM)
1426                                         error = ENOTCONN;
1427                                 else
1428                                         error = EINVAL;
1429                         }
1430                         UNP_PCB_UNLOCK(unp);
1431                         if (error == 0)
1432                                 error = sooptcopyout(sopt, &xu, sizeof(xu));
1433                         break;
1434
1435                 case LOCAL_CREDS:
1436                         /* Unlocked read. */
1437                         optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1438                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1439                         break;
1440
1441                 case LOCAL_CONNWAIT:
1442                         /* Unlocked read. */
1443                         optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1444                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1445                         break;
1446
1447                 default:
1448                         error = EOPNOTSUPP;
1449                         break;
1450                 }
1451                 break;
1452
1453         case SOPT_SET:
1454                 switch (sopt->sopt_name) {
1455                 case LOCAL_CREDS:
1456                 case LOCAL_CONNWAIT:
1457                         error = sooptcopyin(sopt, &optval, sizeof(optval),
1458                                             sizeof(optval));
1459                         if (error)
1460                                 break;
1461
1462 #define OPTSET(bit) do {                                                \
1463         UNP_PCB_LOCK(unp);                                              \
1464         if (optval)                                                     \
1465                 unp->unp_flags |= bit;                                  \
1466         else                                                            \
1467                 unp->unp_flags &= ~bit;                                 \
1468         UNP_PCB_UNLOCK(unp);                                            \
1469 } while (0)
1470
1471                         switch (sopt->sopt_name) {
1472                         case LOCAL_CREDS:
1473                                 OPTSET(UNP_WANTCRED);
1474                                 break;
1475
1476                         case LOCAL_CONNWAIT:
1477                                 OPTSET(UNP_CONNWAIT);
1478                                 break;
1479
1480                         default:
1481                                 break;
1482                         }
1483                         break;
1484 #undef  OPTSET
1485                 default:
1486                         error = ENOPROTOOPT;
1487                         break;
1488                 }
1489                 break;
1490
1491         default:
1492                 error = EOPNOTSUPP;
1493                 break;
1494         }
1495         return (error);
1496 }
1497
1498 static int
1499 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1500 {
1501
1502         return (unp_connectat(AT_FDCWD, so, nam, td));
1503 }
1504
1505 static int
1506 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1507     struct thread *td)
1508 {
1509         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1510         struct vnode *vp;
1511         struct socket *so2;
1512         struct unpcb *unp, *unp2, *unp3;
1513         struct nameidata nd;
1514         char buf[SOCK_MAXADDRLEN];
1515         struct sockaddr *sa;
1516         cap_rights_t rights;
1517         int error, len, freed;
1518         struct mtx *vplock;
1519
1520         if (nam->sa_family != AF_UNIX)
1521                 return (EAFNOSUPPORT);
1522         if (nam->sa_len > sizeof(struct sockaddr_un))
1523                 return (EINVAL);
1524         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1525         if (len <= 0)
1526                 return (EINVAL);
1527         bcopy(soun->sun_path, buf, len);
1528         buf[len] = 0;
1529
1530         unp = sotounpcb(so);
1531         UNP_PCB_LOCK(unp);
1532         if (unp->unp_flags & UNP_CONNECTING) {
1533                 UNP_PCB_UNLOCK(unp);
1534                 return (EALREADY);
1535         }
1536         unp->unp_flags |= UNP_CONNECTING;
1537         UNP_PCB_UNLOCK(unp);
1538
1539         sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1540         NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1541             UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1542         error = namei(&nd);
1543         if (error)
1544                 vp = NULL;
1545         else
1546                 vp = nd.ni_vp;
1547         ASSERT_VOP_LOCKED(vp, "unp_connect");
1548         NDFREE(&nd, NDF_ONLY_PNBUF);
1549         if (error)
1550                 goto bad;
1551
1552         if (vp->v_type != VSOCK) {
1553                 error = ENOTSOCK;
1554                 goto bad;
1555         }
1556 #ifdef MAC
1557         error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1558         if (error)
1559                 goto bad;
1560 #endif
1561         error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1562         if (error)
1563                 goto bad;
1564
1565         unp = sotounpcb(so);
1566         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1567
1568         vplock = mtx_pool_find(mtxpool_sleep, vp);
1569         mtx_lock(vplock);
1570         VOP_UNP_CONNECT(vp, &unp2);
1571         if (unp2 == NULL) {
1572                 error = ECONNREFUSED;
1573                 goto bad2;
1574         }
1575         so2 = unp2->unp_socket;
1576         if (so->so_type != so2->so_type) {
1577                 error = EPROTOTYPE;
1578                 goto bad2;
1579         }
1580         if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1581                 if (so2->so_options & SO_ACCEPTCONN) {
1582                         CURVNET_SET(so2->so_vnet);
1583                         so2 = sonewconn(so2, 0);
1584                         CURVNET_RESTORE();
1585                 } else
1586                         so2 = NULL;
1587                 if (so2 == NULL) {
1588                         error = ECONNREFUSED;
1589                         goto bad2;
1590                 }
1591                 unp3 = sotounpcb(so2);
1592                 unp_pcb_lock2(unp2, unp3);
1593                 if (unp2->unp_addr != NULL) {
1594                         bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1595                         unp3->unp_addr = (struct sockaddr_un *) sa;
1596                         sa = NULL;
1597                 }
1598
1599                 unp_copy_peercred(td, unp3, unp, unp2);
1600
1601                 UNP_PCB_UNLOCK(unp2);
1602                 unp2 = unp3;
1603                 unp_pcb_owned_lock2(unp2, unp, freed);
1604                 if (__predict_false(freed)) {
1605                         UNP_PCB_UNLOCK(unp2);
1606                         error = ECONNREFUSED;
1607                         goto bad2;
1608                 }
1609 #ifdef MAC
1610                 mac_socketpeer_set_from_socket(so, so2);
1611                 mac_socketpeer_set_from_socket(so2, so);
1612 #endif
1613         } else {
1614                 if (unp == unp2)
1615                         UNP_PCB_LOCK(unp);
1616                 else
1617                         unp_pcb_lock2(unp, unp2);
1618         }
1619         KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1620             sotounpcb(so2) == unp2,
1621             ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1622         error = unp_connect2(so, so2, PRU_CONNECT);
1623         if (unp != unp2)
1624                 UNP_PCB_UNLOCK(unp2);
1625         UNP_PCB_UNLOCK(unp);
1626 bad2:
1627         mtx_unlock(vplock);
1628 bad:
1629         if (vp != NULL) {
1630                 vput(vp);
1631         }
1632         free(sa, M_SONAME);
1633         UNP_PCB_LOCK(unp);
1634         unp->unp_flags &= ~UNP_CONNECTING;
1635         UNP_PCB_UNLOCK(unp);
1636         return (error);
1637 }
1638
1639 /*
1640  * Set socket peer credentials at connection time.
1641  *
1642  * The client's PCB credentials are copied from its process structure.  The
1643  * server's PCB credentials are copied from the socket on which it called
1644  * listen(2).  uipc_listen cached that process's credentials at the time.
1645  */
1646 void
1647 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1648     struct unpcb *server_unp, struct unpcb *listen_unp)
1649 {
1650         cru2xt(td, &client_unp->unp_peercred);
1651         client_unp->unp_flags |= UNP_HAVEPC;
1652
1653         memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1654             sizeof(server_unp->unp_peercred));
1655         server_unp->unp_flags |= UNP_HAVEPC;
1656         if (listen_unp->unp_flags & UNP_WANTCRED)
1657                 client_unp->unp_flags |= UNP_WANTCRED;
1658 }
1659
1660 static int
1661 unp_connect2(struct socket *so, struct socket *so2, int req)
1662 {
1663         struct unpcb *unp;
1664         struct unpcb *unp2;
1665
1666         unp = sotounpcb(so);
1667         KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1668         unp2 = sotounpcb(so2);
1669         KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1670
1671         UNP_PCB_LOCK_ASSERT(unp);
1672         UNP_PCB_LOCK_ASSERT(unp2);
1673
1674         if (so2->so_type != so->so_type)
1675                 return (EPROTOTYPE);
1676         unp->unp_conn = unp2;
1677         unp_pcb_hold(unp2);
1678         unp_pcb_hold(unp);
1679         switch (so->so_type) {
1680         case SOCK_DGRAM:
1681                 UNP_REF_LIST_LOCK();
1682                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1683                 UNP_REF_LIST_UNLOCK();
1684                 soisconnected(so);
1685                 break;
1686
1687         case SOCK_STREAM:
1688         case SOCK_SEQPACKET:
1689                 unp2->unp_conn = unp;
1690                 if (req == PRU_CONNECT &&
1691                     ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1692                         soisconnecting(so);
1693                 else
1694                         soisconnected(so);
1695                 soisconnected(so2);
1696                 break;
1697
1698         default:
1699                 panic("unp_connect2");
1700         }
1701         return (0);
1702 }
1703
1704 static void
1705 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1706 {
1707         struct socket *so, *so2;
1708         int freed __unused;
1709
1710         KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1711
1712         UNP_PCB_LOCK_ASSERT(unp);
1713         UNP_PCB_LOCK_ASSERT(unp2);
1714
1715         if (unp->unp_conn == NULL && unp2->unp_conn == NULL)
1716                 return;
1717
1718         MPASS(unp->unp_conn == unp2);
1719         unp->unp_conn = NULL;
1720         so = unp->unp_socket;
1721         so2 = unp2->unp_socket;
1722         switch (unp->unp_socket->so_type) {
1723         case SOCK_DGRAM:
1724                 UNP_REF_LIST_LOCK();
1725                 LIST_REMOVE(unp, unp_reflink);
1726                 UNP_REF_LIST_UNLOCK();
1727                 if (so) {
1728                         SOCK_LOCK(so);
1729                         so->so_state &= ~SS_ISCONNECTED;
1730                         SOCK_UNLOCK(so);
1731                 }
1732                 break;
1733
1734         case SOCK_STREAM:
1735         case SOCK_SEQPACKET:
1736                 if (so)
1737                         soisdisconnected(so);
1738                 MPASS(unp2->unp_conn == unp);
1739                 unp2->unp_conn = NULL;
1740                 if (so2)
1741                         soisdisconnected(so2);
1742                 break;
1743         }
1744         freed = unp_pcb_rele(unp);
1745         MPASS(freed == 0);
1746         freed = unp_pcb_rele(unp2);
1747         MPASS(freed == 0);
1748 }
1749
1750 /*
1751  * unp_pcblist() walks the global list of struct unpcb's to generate a
1752  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1753  * sequentially, validating the generation number on each to see if it has
1754  * been detached.  All of this is necessary because copyout() may sleep on
1755  * disk I/O.
1756  */
1757 static int
1758 unp_pcblist(SYSCTL_HANDLER_ARGS)
1759 {
1760         struct unpcb *unp, **unp_list;
1761         unp_gen_t gencnt;
1762         struct xunpgen *xug;
1763         struct unp_head *head;
1764         struct xunpcb *xu;
1765         u_int i;
1766         int error, freeunp, n;
1767
1768         switch ((intptr_t)arg1) {
1769         case SOCK_STREAM:
1770                 head = &unp_shead;
1771                 break;
1772
1773         case SOCK_DGRAM:
1774                 head = &unp_dhead;
1775                 break;
1776
1777         case SOCK_SEQPACKET:
1778                 head = &unp_sphead;
1779                 break;
1780
1781         default:
1782                 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1783         }
1784
1785         /*
1786          * The process of preparing the PCB list is too time-consuming and
1787          * resource-intensive to repeat twice on every request.
1788          */
1789         if (req->oldptr == NULL) {
1790                 n = unp_count;
1791                 req->oldidx = 2 * (sizeof *xug)
1792                         + (n + n/8) * sizeof(struct xunpcb);
1793                 return (0);
1794         }
1795
1796         if (req->newptr != NULL)
1797                 return (EPERM);
1798
1799         /*
1800          * OK, now we're committed to doing something.
1801          */
1802         xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1803         UNP_LINK_RLOCK();
1804         gencnt = unp_gencnt;
1805         n = unp_count;
1806         UNP_LINK_RUNLOCK();
1807
1808         xug->xug_len = sizeof *xug;
1809         xug->xug_count = n;
1810         xug->xug_gen = gencnt;
1811         xug->xug_sogen = so_gencnt;
1812         error = SYSCTL_OUT(req, xug, sizeof *xug);
1813         if (error) {
1814                 free(xug, M_TEMP);
1815                 return (error);
1816         }
1817
1818         unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1819
1820         UNP_LINK_RLOCK();
1821         for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1822              unp = LIST_NEXT(unp, unp_link)) {
1823                 UNP_PCB_LOCK(unp);
1824                 if (unp->unp_gencnt <= gencnt) {
1825                         if (cr_cansee(req->td->td_ucred,
1826                             unp->unp_socket->so_cred)) {
1827                                 UNP_PCB_UNLOCK(unp);
1828                                 continue;
1829                         }
1830                         unp_list[i++] = unp;
1831                         unp_pcb_hold(unp);
1832                 }
1833                 UNP_PCB_UNLOCK(unp);
1834         }
1835         UNP_LINK_RUNLOCK();
1836         n = i;                  /* In case we lost some during malloc. */
1837
1838         error = 0;
1839         xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1840         for (i = 0; i < n; i++) {
1841                 unp = unp_list[i];
1842                 UNP_PCB_LOCK(unp);
1843                 freeunp = unp_pcb_rele(unp);
1844
1845                 if (freeunp == 0 && unp->unp_gencnt <= gencnt) {
1846                         xu->xu_len = sizeof *xu;
1847                         xu->xu_unpp = (uintptr_t)unp;
1848                         /*
1849                          * XXX - need more locking here to protect against
1850                          * connect/disconnect races for SMP.
1851                          */
1852                         if (unp->unp_addr != NULL)
1853                                 bcopy(unp->unp_addr, &xu->xu_addr,
1854                                       unp->unp_addr->sun_len);
1855                         else
1856                                 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1857                         if (unp->unp_conn != NULL &&
1858                             unp->unp_conn->unp_addr != NULL)
1859                                 bcopy(unp->unp_conn->unp_addr,
1860                                       &xu->xu_caddr,
1861                                       unp->unp_conn->unp_addr->sun_len);
1862                         else
1863                                 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
1864                         xu->unp_vnode = (uintptr_t)unp->unp_vnode;
1865                         xu->unp_conn = (uintptr_t)unp->unp_conn;
1866                         xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
1867                         xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
1868                         xu->unp_gencnt = unp->unp_gencnt;
1869                         sotoxsocket(unp->unp_socket, &xu->xu_socket);
1870                         UNP_PCB_UNLOCK(unp);
1871                         error = SYSCTL_OUT(req, xu, sizeof *xu);
1872                 } else  if (freeunp == 0)
1873                         UNP_PCB_UNLOCK(unp);
1874         }
1875         free(xu, M_TEMP);
1876         if (!error) {
1877                 /*
1878                  * Give the user an updated idea of our state.  If the
1879                  * generation differs from what we told her before, she knows
1880                  * that something happened while we were processing this
1881                  * request, and it might be necessary to retry.
1882                  */
1883                 xug->xug_gen = unp_gencnt;
1884                 xug->xug_sogen = so_gencnt;
1885                 xug->xug_count = unp_count;
1886                 error = SYSCTL_OUT(req, xug, sizeof *xug);
1887         }
1888         free(unp_list, M_TEMP);
1889         free(xug, M_TEMP);
1890         return (error);
1891 }
1892
1893 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
1894     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1895     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1896     "List of active local datagram sockets");
1897 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
1898     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1899     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1900     "List of active local stream sockets");
1901 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1902     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1903     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1904     "List of active local seqpacket sockets");
1905
1906 static void
1907 unp_shutdown(struct unpcb *unp)
1908 {
1909         struct unpcb *unp2;
1910         struct socket *so;
1911
1912         UNP_PCB_LOCK_ASSERT(unp);
1913
1914         unp2 = unp->unp_conn;
1915         if ((unp->unp_socket->so_type == SOCK_STREAM ||
1916             (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1917                 so = unp2->unp_socket;
1918                 if (so != NULL)
1919                         socantrcvmore(so);
1920         }
1921 }
1922
1923 static void
1924 unp_drop(struct unpcb *unp)
1925 {
1926         struct socket *so = unp->unp_socket;
1927         struct unpcb *unp2;
1928         int freed;
1929
1930         /*
1931          * Regardless of whether the socket's peer dropped the connection
1932          * with this socket by aborting or disconnecting, POSIX requires
1933          * that ECONNRESET is returned.
1934          */
1935         /* acquire a reference so that unp isn't freed from underneath us */
1936
1937         UNP_PCB_LOCK(unp);
1938         if (so)
1939                 so->so_error = ECONNRESET;
1940         unp2 = unp->unp_conn;
1941         if (unp2 == unp) {
1942                 unp_disconnect(unp, unp2);
1943         } else if (unp2 != NULL) {
1944                 unp_pcb_hold(unp2);
1945                 unp_pcb_owned_lock2(unp, unp2, freed);
1946                 unp_disconnect(unp, unp2);
1947                 if (unp_pcb_rele(unp2) == 0)
1948                         UNP_PCB_UNLOCK(unp2);
1949         }
1950         if (unp_pcb_rele(unp) == 0)
1951                 UNP_PCB_UNLOCK(unp);
1952 }
1953
1954 static void
1955 unp_freerights(struct filedescent **fdep, int fdcount)
1956 {
1957         struct file *fp;
1958         int i;
1959
1960         KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
1961
1962         for (i = 0; i < fdcount; i++) {
1963                 fp = fdep[i]->fde_file;
1964                 filecaps_free(&fdep[i]->fde_caps);
1965                 unp_discard(fp);
1966         }
1967         free(fdep[0], M_FILECAPS);
1968 }
1969
1970 static int
1971 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
1972 {
1973         struct thread *td = curthread;          /* XXX */
1974         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1975         int i;
1976         int *fdp;
1977         struct filedesc *fdesc = td->td_proc->p_fd;
1978         struct filedescent **fdep;
1979         void *data;
1980         socklen_t clen = control->m_len, datalen;
1981         int error, newfds;
1982         u_int newlen;
1983
1984         UNP_LINK_UNLOCK_ASSERT();
1985
1986         error = 0;
1987         if (controlp != NULL) /* controlp == NULL => free control messages */
1988                 *controlp = NULL;
1989         while (cm != NULL) {
1990                 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1991                         error = EINVAL;
1992                         break;
1993                 }
1994                 data = CMSG_DATA(cm);
1995                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1996                 if (cm->cmsg_level == SOL_SOCKET
1997                     && cm->cmsg_type == SCM_RIGHTS) {
1998                         newfds = datalen / sizeof(*fdep);
1999                         if (newfds == 0)
2000                                 goto next;
2001                         fdep = data;
2002
2003                         /* If we're not outputting the descriptors free them. */
2004                         if (error || controlp == NULL) {
2005                                 unp_freerights(fdep, newfds);
2006                                 goto next;
2007                         }
2008                         FILEDESC_XLOCK(fdesc);
2009
2010                         /*
2011                          * Now change each pointer to an fd in the global
2012                          * table to an integer that is the index to the local
2013                          * fd table entry that we set up to point to the
2014                          * global one we are transferring.
2015                          */
2016                         newlen = newfds * sizeof(int);
2017                         *controlp = sbcreatecontrol(NULL, newlen,
2018                             SCM_RIGHTS, SOL_SOCKET);
2019                         if (*controlp == NULL) {
2020                                 FILEDESC_XUNLOCK(fdesc);
2021                                 error = E2BIG;
2022                                 unp_freerights(fdep, newfds);
2023                                 goto next;
2024                         }
2025
2026                         fdp = (int *)
2027                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2028                         if (fdallocn(td, 0, fdp, newfds) != 0) {
2029                                 FILEDESC_XUNLOCK(fdesc);
2030                                 error = EMSGSIZE;
2031                                 unp_freerights(fdep, newfds);
2032                                 m_freem(*controlp);
2033                                 *controlp = NULL;
2034                                 goto next;
2035                         }
2036                         for (i = 0; i < newfds; i++, fdp++) {
2037                                 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2038                                     (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
2039                                     &fdep[i]->fde_caps);
2040                                 unp_externalize_fp(fdep[i]->fde_file);
2041                         }
2042
2043                         /*
2044                          * The new type indicates that the mbuf data refers to
2045                          * kernel resources that may need to be released before
2046                          * the mbuf is freed.
2047                          */
2048                         m_chtype(*controlp, MT_EXTCONTROL);
2049                         FILEDESC_XUNLOCK(fdesc);
2050                         free(fdep[0], M_FILECAPS);
2051                 } else {
2052                         /* We can just copy anything else across. */
2053                         if (error || controlp == NULL)
2054                                 goto next;
2055                         *controlp = sbcreatecontrol(NULL, datalen,
2056                             cm->cmsg_type, cm->cmsg_level);
2057                         if (*controlp == NULL) {
2058                                 error = ENOBUFS;
2059                                 goto next;
2060                         }
2061                         bcopy(data,
2062                             CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2063                             datalen);
2064                 }
2065                 controlp = &(*controlp)->m_next;
2066
2067 next:
2068                 if (CMSG_SPACE(datalen) < clen) {
2069                         clen -= CMSG_SPACE(datalen);
2070                         cm = (struct cmsghdr *)
2071                             ((caddr_t)cm + CMSG_SPACE(datalen));
2072                 } else {
2073                         clen = 0;
2074                         cm = NULL;
2075                 }
2076         }
2077
2078         m_freem(control);
2079         return (error);
2080 }
2081
2082 static void
2083 unp_zone_change(void *tag)
2084 {
2085
2086         uma_zone_set_max(unp_zone, maxsockets);
2087 }
2088
2089 static void
2090 unp_init(void)
2091 {
2092
2093 #ifdef VIMAGE
2094         if (!IS_DEFAULT_VNET(curvnet))
2095                 return;
2096 #endif
2097         unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
2098             NULL, NULL, UMA_ALIGN_CACHE, 0);
2099         if (unp_zone == NULL)
2100                 panic("unp_init");
2101         uma_zone_set_max(unp_zone, maxsockets);
2102         uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2103         EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2104             NULL, EVENTHANDLER_PRI_ANY);
2105         LIST_INIT(&unp_dhead);
2106         LIST_INIT(&unp_shead);
2107         LIST_INIT(&unp_sphead);
2108         SLIST_INIT(&unp_defers);
2109         TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2110         TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2111         UNP_LINK_LOCK_INIT();
2112         UNP_DEFERRED_LOCK_INIT();
2113 }
2114
2115 static void
2116 unp_internalize_cleanup_rights(struct mbuf *control)
2117 {
2118         struct cmsghdr *cp;
2119         struct mbuf *m;
2120         void *data;
2121         socklen_t datalen;
2122
2123         for (m = control; m != NULL; m = m->m_next) {
2124                 cp = mtod(m, struct cmsghdr *);
2125                 if (cp->cmsg_level != SOL_SOCKET ||
2126                     cp->cmsg_type != SCM_RIGHTS)
2127                         continue;
2128                 data = CMSG_DATA(cp);
2129                 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2130                 unp_freerights(data, datalen / sizeof(struct filedesc *));
2131         }
2132 }
2133
2134 static int
2135 unp_internalize(struct mbuf **controlp, struct thread *td)
2136 {
2137         struct mbuf *control, **initial_controlp;
2138         struct proc *p;
2139         struct filedesc *fdesc;
2140         struct bintime *bt;
2141         struct cmsghdr *cm;
2142         struct cmsgcred *cmcred;
2143         struct filedescent *fde, **fdep, *fdev;
2144         struct file *fp;
2145         struct timeval *tv;
2146         struct timespec *ts;
2147         void *data;
2148         socklen_t clen, datalen;
2149         int i, j, error, *fdp, oldfds;
2150         u_int newlen;
2151
2152         UNP_LINK_UNLOCK_ASSERT();
2153
2154         p = td->td_proc;
2155         fdesc = p->p_fd;
2156         error = 0;
2157         control = *controlp;
2158         clen = control->m_len;
2159         *controlp = NULL;
2160         initial_controlp = controlp;
2161         for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
2162                 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2163                     || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
2164                         error = EINVAL;
2165                         goto out;
2166                 }
2167                 data = CMSG_DATA(cm);
2168                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2169
2170                 switch (cm->cmsg_type) {
2171                 /*
2172                  * Fill in credential information.
2173                  */
2174                 case SCM_CREDS:
2175                         *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2176                             SCM_CREDS, SOL_SOCKET);
2177                         if (*controlp == NULL) {
2178                                 error = ENOBUFS;
2179                                 goto out;
2180                         }
2181                         cmcred = (struct cmsgcred *)
2182                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2183                         cmcred->cmcred_pid = p->p_pid;
2184                         cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2185                         cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2186                         cmcred->cmcred_euid = td->td_ucred->cr_uid;
2187                         cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2188                             CMGROUP_MAX);
2189                         for (i = 0; i < cmcred->cmcred_ngroups; i++)
2190                                 cmcred->cmcred_groups[i] =
2191                                     td->td_ucred->cr_groups[i];
2192                         break;
2193
2194                 case SCM_RIGHTS:
2195                         oldfds = datalen / sizeof (int);
2196                         if (oldfds == 0)
2197                                 break;
2198                         /*
2199                          * Check that all the FDs passed in refer to legal
2200                          * files.  If not, reject the entire operation.
2201                          */
2202                         fdp = data;
2203                         FILEDESC_SLOCK(fdesc);
2204                         for (i = 0; i < oldfds; i++, fdp++) {
2205                                 fp = fget_locked(fdesc, *fdp);
2206                                 if (fp == NULL) {
2207                                         FILEDESC_SUNLOCK(fdesc);
2208                                         error = EBADF;
2209                                         goto out;
2210                                 }
2211                                 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2212                                         FILEDESC_SUNLOCK(fdesc);
2213                                         error = EOPNOTSUPP;
2214                                         goto out;
2215                                 }
2216
2217                         }
2218
2219                         /*
2220                          * Now replace the integer FDs with pointers to the
2221                          * file structure and capability rights.
2222                          */
2223                         newlen = oldfds * sizeof(fdep[0]);
2224                         *controlp = sbcreatecontrol(NULL, newlen,
2225                             SCM_RIGHTS, SOL_SOCKET);
2226                         if (*controlp == NULL) {
2227                                 FILEDESC_SUNLOCK(fdesc);
2228                                 error = E2BIG;
2229                                 goto out;
2230                         }
2231                         fdp = data;
2232                         for (i = 0; i < oldfds; i++, fdp++) {
2233                                 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2234                                         fdp = data;
2235                                         for (j = 0; j < i; j++, fdp++) {
2236                                                 fdrop(fdesc->fd_ofiles[*fdp].
2237                                                     fde_file, td);
2238                                         }
2239                                         FILEDESC_SUNLOCK(fdesc);
2240                                         error = EBADF;
2241                                         goto out;
2242                                 }
2243                         }
2244                         fdp = data;
2245                         fdep = (struct filedescent **)
2246                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2247                         fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2248                             M_WAITOK);
2249                         for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2250                                 fde = &fdesc->fd_ofiles[*fdp];
2251                                 fdep[i] = fdev;
2252                                 fdep[i]->fde_file = fde->fde_file;
2253                                 filecaps_copy(&fde->fde_caps,
2254                                     &fdep[i]->fde_caps, true);
2255                                 unp_internalize_fp(fdep[i]->fde_file);
2256                         }
2257                         FILEDESC_SUNLOCK(fdesc);
2258                         break;
2259
2260                 case SCM_TIMESTAMP:
2261                         *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2262                             SCM_TIMESTAMP, SOL_SOCKET);
2263                         if (*controlp == NULL) {
2264                                 error = ENOBUFS;
2265                                 goto out;
2266                         }
2267                         tv = (struct timeval *)
2268                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2269                         microtime(tv);
2270                         break;
2271
2272                 case SCM_BINTIME:
2273                         *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2274                             SCM_BINTIME, SOL_SOCKET);
2275                         if (*controlp == NULL) {
2276                                 error = ENOBUFS;
2277                                 goto out;
2278                         }
2279                         bt = (struct bintime *)
2280                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2281                         bintime(bt);
2282                         break;
2283
2284                 case SCM_REALTIME:
2285                         *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2286                             SCM_REALTIME, SOL_SOCKET);
2287                         if (*controlp == NULL) {
2288                                 error = ENOBUFS;
2289                                 goto out;
2290                         }
2291                         ts = (struct timespec *)
2292                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2293                         nanotime(ts);
2294                         break;
2295
2296                 case SCM_MONOTONIC:
2297                         *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2298                             SCM_MONOTONIC, SOL_SOCKET);
2299                         if (*controlp == NULL) {
2300                                 error = ENOBUFS;
2301                                 goto out;
2302                         }
2303                         ts = (struct timespec *)
2304                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2305                         nanouptime(ts);
2306                         break;
2307
2308                 default:
2309                         error = EINVAL;
2310                         goto out;
2311                 }
2312
2313                 if (*controlp != NULL)
2314                         controlp = &(*controlp)->m_next;
2315                 if (CMSG_SPACE(datalen) < clen) {
2316                         clen -= CMSG_SPACE(datalen);
2317                         cm = (struct cmsghdr *)
2318                             ((caddr_t)cm + CMSG_SPACE(datalen));
2319                 } else {
2320                         clen = 0;
2321                         cm = NULL;
2322                 }
2323         }
2324
2325 out:
2326         if (error != 0 && initial_controlp != NULL)
2327                 unp_internalize_cleanup_rights(*initial_controlp);
2328         m_freem(control);
2329         return (error);
2330 }
2331
2332 static struct mbuf *
2333 unp_addsockcred(struct thread *td, struct mbuf *control)
2334 {
2335         struct mbuf *m, *n, *n_prev;
2336         struct sockcred *sc;
2337         const struct cmsghdr *cm;
2338         int ngroups;
2339         int i;
2340
2341         ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2342         m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2343         if (m == NULL)
2344                 return (control);
2345
2346         sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2347         sc->sc_uid = td->td_ucred->cr_ruid;
2348         sc->sc_euid = td->td_ucred->cr_uid;
2349         sc->sc_gid = td->td_ucred->cr_rgid;
2350         sc->sc_egid = td->td_ucred->cr_gid;
2351         sc->sc_ngroups = ngroups;
2352         for (i = 0; i < sc->sc_ngroups; i++)
2353                 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2354
2355         /*
2356          * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2357          * created SCM_CREDS control message (struct sockcred) has another
2358          * format.
2359          */
2360         if (control != NULL)
2361                 for (n = control, n_prev = NULL; n != NULL;) {
2362                         cm = mtod(n, struct cmsghdr *);
2363                         if (cm->cmsg_level == SOL_SOCKET &&
2364                             cm->cmsg_type == SCM_CREDS) {
2365                                 if (n_prev == NULL)
2366                                         control = n->m_next;
2367                                 else
2368                                         n_prev->m_next = n->m_next;
2369                                 n = m_free(n);
2370                         } else {
2371                                 n_prev = n;
2372                                 n = n->m_next;
2373                         }
2374                 }
2375
2376         /* Prepend it to the head. */
2377         m->m_next = control;
2378         return (m);
2379 }
2380
2381 static struct unpcb *
2382 fptounp(struct file *fp)
2383 {
2384         struct socket *so;
2385
2386         if (fp->f_type != DTYPE_SOCKET)
2387                 return (NULL);
2388         if ((so = fp->f_data) == NULL)
2389                 return (NULL);
2390         if (so->so_proto->pr_domain != &localdomain)
2391                 return (NULL);
2392         return sotounpcb(so);
2393 }
2394
2395 static void
2396 unp_discard(struct file *fp)
2397 {
2398         struct unp_defer *dr;
2399
2400         if (unp_externalize_fp(fp)) {
2401                 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2402                 dr->ud_fp = fp;
2403                 UNP_DEFERRED_LOCK();
2404                 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2405                 UNP_DEFERRED_UNLOCK();
2406                 atomic_add_int(&unp_defers_count, 1);
2407                 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2408         } else
2409                 (void) closef(fp, (struct thread *)NULL);
2410 }
2411
2412 static void
2413 unp_process_defers(void *arg __unused, int pending)
2414 {
2415         struct unp_defer *dr;
2416         SLIST_HEAD(, unp_defer) drl;
2417         int count;
2418
2419         SLIST_INIT(&drl);
2420         for (;;) {
2421                 UNP_DEFERRED_LOCK();
2422                 if (SLIST_FIRST(&unp_defers) == NULL) {
2423                         UNP_DEFERRED_UNLOCK();
2424                         break;
2425                 }
2426                 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2427                 UNP_DEFERRED_UNLOCK();
2428                 count = 0;
2429                 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2430                         SLIST_REMOVE_HEAD(&drl, ud_link);
2431                         closef(dr->ud_fp, NULL);
2432                         free(dr, M_TEMP);
2433                         count++;
2434                 }
2435                 atomic_add_int(&unp_defers_count, -count);
2436         }
2437 }
2438
2439 static void
2440 unp_internalize_fp(struct file *fp)
2441 {
2442         struct unpcb *unp;
2443
2444         UNP_LINK_WLOCK();
2445         if ((unp = fptounp(fp)) != NULL) {
2446                 unp->unp_file = fp;
2447                 unp->unp_msgcount++;
2448         }
2449         unp_rights++;
2450         UNP_LINK_WUNLOCK();
2451 }
2452
2453 static int
2454 unp_externalize_fp(struct file *fp)
2455 {
2456         struct unpcb *unp;
2457         int ret;
2458
2459         UNP_LINK_WLOCK();
2460         if ((unp = fptounp(fp)) != NULL) {
2461                 unp->unp_msgcount--;
2462                 ret = 1;
2463         } else
2464                 ret = 0;
2465         unp_rights--;
2466         UNP_LINK_WUNLOCK();
2467         return (ret);
2468 }
2469
2470 /*
2471  * unp_defer indicates whether additional work has been defered for a future
2472  * pass through unp_gc().  It is thread local and does not require explicit
2473  * synchronization.
2474  */
2475 static int      unp_marked;
2476
2477 static void
2478 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2479 {
2480         struct unpcb *unp;
2481         struct file *fp;
2482         int i;
2483
2484         /*
2485          * This function can only be called from the gc task.
2486          */
2487         KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2488             ("%s: not on gc callout", __func__));
2489         UNP_LINK_LOCK_ASSERT();
2490
2491         for (i = 0; i < fdcount; i++) {
2492                 fp = fdep[i]->fde_file;
2493                 if ((unp = fptounp(fp)) == NULL)
2494                         continue;
2495                 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2496                         continue;
2497                 unp->unp_gcrefs--;
2498         }
2499 }
2500
2501 static void
2502 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2503 {
2504         struct unpcb *unp;
2505         struct file *fp;
2506         int i;
2507
2508         /*
2509          * This function can only be called from the gc task.
2510          */
2511         KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2512             ("%s: not on gc callout", __func__));
2513         UNP_LINK_LOCK_ASSERT();
2514
2515         for (i = 0; i < fdcount; i++) {
2516                 fp = fdep[i]->fde_file;
2517                 if ((unp = fptounp(fp)) == NULL)
2518                         continue;
2519                 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2520                         continue;
2521                 unp->unp_gcrefs++;
2522                 unp_marked++;
2523         }
2524 }
2525
2526 static void
2527 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2528 {
2529         struct socket *so, *soa;
2530
2531         so = unp->unp_socket;
2532         SOCK_LOCK(so);
2533         if (SOLISTENING(so)) {
2534                 /*
2535                  * Mark all sockets in our accept queue.
2536                  */
2537                 TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2538                         if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2539                                 continue;
2540                         SOCKBUF_LOCK(&soa->so_rcv);
2541                         unp_scan(soa->so_rcv.sb_mb, op);
2542                         SOCKBUF_UNLOCK(&soa->so_rcv);
2543                 }
2544         } else {
2545                 /*
2546                  * Mark all sockets we reference with RIGHTS.
2547                  */
2548                 if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2549                         SOCKBUF_LOCK(&so->so_rcv);
2550                         unp_scan(so->so_rcv.sb_mb, op);
2551                         SOCKBUF_UNLOCK(&so->so_rcv);
2552                 }
2553         }
2554         SOCK_UNLOCK(so);
2555 }
2556
2557 static int unp_recycled;
2558 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, 
2559     "Number of unreachable sockets claimed by the garbage collector.");
2560
2561 static int unp_taskcount;
2562 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, 
2563     "Number of times the garbage collector has run.");
2564
2565 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0, 
2566     "Number of active local sockets.");
2567
2568 static void
2569 unp_gc(__unused void *arg, int pending)
2570 {
2571         struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2572                                     NULL };
2573         struct unp_head **head;
2574         struct unp_head unp_deadhead;   /* List of potentially-dead sockets. */
2575         struct file *f, **unref;
2576         struct unpcb *unp, *unptmp;
2577         int i, total, unp_unreachable;
2578
2579         LIST_INIT(&unp_deadhead);
2580         unp_taskcount++;
2581         UNP_LINK_RLOCK();
2582         /*
2583          * First determine which sockets may be in cycles.
2584          */
2585         unp_unreachable = 0;
2586
2587         for (head = heads; *head != NULL; head++)
2588                 LIST_FOREACH(unp, *head, unp_link) {
2589
2590                         KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2591                             ("%s: unp %p has unexpected gc flags 0x%x",
2592                             __func__, unp, (unsigned int)unp->unp_gcflag));
2593
2594                         f = unp->unp_file;
2595
2596                         /*
2597                          * Check for an unreachable socket potentially in a
2598                          * cycle.  It must be in a queue as indicated by
2599                          * msgcount, and this must equal the file reference
2600                          * count.  Note that when msgcount is 0 the file is
2601                          * NULL.
2602                          */
2603                         if (f != NULL && unp->unp_msgcount != 0 &&
2604                             f->f_count == unp->unp_msgcount) {
2605                                 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2606                                 unp->unp_gcflag |= UNPGC_DEAD;
2607                                 unp->unp_gcrefs = unp->unp_msgcount;
2608                                 unp_unreachable++;
2609                         }
2610                 }
2611
2612         /*
2613          * Scan all sockets previously marked as potentially being in a cycle
2614          * and remove the references each socket holds on any UNPGC_DEAD
2615          * sockets in its queue.  After this step, all remaining references on
2616          * sockets marked UNPGC_DEAD should not be part of any cycle.
2617          */
2618         LIST_FOREACH(unp, &unp_deadhead, unp_dead)
2619                 unp_gc_scan(unp, unp_remove_dead_ref);
2620
2621         /*
2622          * If a socket still has a non-negative refcount, it cannot be in a
2623          * cycle.  In this case increment refcount of all children iteratively.
2624          * Stop the scan once we do a complete loop without discovering
2625          * a new reachable socket.
2626          */
2627         do {
2628                 unp_marked = 0;
2629                 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
2630                         if (unp->unp_gcrefs > 0) {
2631                                 unp->unp_gcflag &= ~UNPGC_DEAD;
2632                                 LIST_REMOVE(unp, unp_dead);
2633                                 KASSERT(unp_unreachable > 0,
2634                                     ("%s: unp_unreachable underflow.",
2635                                     __func__));
2636                                 unp_unreachable--;
2637                                 unp_gc_scan(unp, unp_restore_undead_ref);
2638                         }
2639         } while (unp_marked);
2640
2641         UNP_LINK_RUNLOCK();
2642
2643         if (unp_unreachable == 0)
2644                 return;
2645
2646         /*
2647          * Allocate space for a local array of dead unpcbs.
2648          * TODO: can this path be simplified by instead using the local
2649          * dead list at unp_deadhead, after taking out references
2650          * on the file object and/or unpcb and dropping the link lock?
2651          */
2652         unref = malloc(unp_unreachable * sizeof(struct file *),
2653             M_TEMP, M_WAITOK);
2654
2655         /*
2656          * Iterate looking for sockets which have been specifically marked
2657          * as unreachable and store them locally.
2658          */
2659         UNP_LINK_RLOCK();
2660         total = 0;
2661         LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
2662                 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
2663                     ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
2664                 unp->unp_gcflag &= ~UNPGC_DEAD;
2665                 f = unp->unp_file;
2666                 if (unp->unp_msgcount == 0 || f == NULL ||
2667                     f->f_count != unp->unp_msgcount ||
2668                     !fhold(f))
2669                         continue;
2670                 unref[total++] = f;
2671                 KASSERT(total <= unp_unreachable,
2672                     ("%s: incorrect unreachable count.", __func__));
2673         }
2674         UNP_LINK_RUNLOCK();
2675
2676         /*
2677          * Now flush all sockets, free'ing rights.  This will free the
2678          * struct files associated with these sockets but leave each socket
2679          * with one remaining ref.
2680          */
2681         for (i = 0; i < total; i++) {
2682                 struct socket *so;
2683
2684                 so = unref[i]->f_data;
2685                 CURVNET_SET(so->so_vnet);
2686                 sorflush(so);
2687                 CURVNET_RESTORE();
2688         }
2689
2690         /*
2691          * And finally release the sockets so they can be reclaimed.
2692          */
2693         for (i = 0; i < total; i++)
2694                 fdrop(unref[i], NULL);
2695         unp_recycled += total;
2696         free(unref, M_TEMP);
2697 }
2698
2699 static void
2700 unp_dispose_mbuf(struct mbuf *m)
2701 {
2702
2703         if (m)
2704                 unp_scan(m, unp_freerights);
2705 }
2706
2707 /*
2708  * Synchronize against unp_gc, which can trip over data as we are freeing it.
2709  */
2710 static void
2711 unp_dispose(struct socket *so)
2712 {
2713         struct unpcb *unp;
2714
2715         unp = sotounpcb(so);
2716         UNP_LINK_WLOCK();
2717         unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2718         UNP_LINK_WUNLOCK();
2719         if (!SOLISTENING(so))
2720                 unp_dispose_mbuf(so->so_rcv.sb_mb);
2721 }
2722
2723 static void
2724 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2725 {
2726         struct mbuf *m;
2727         struct cmsghdr *cm;
2728         void *data;
2729         socklen_t clen, datalen;
2730
2731         while (m0 != NULL) {
2732                 for (m = m0; m; m = m->m_next) {
2733                         if (m->m_type != MT_CONTROL)
2734                                 continue;
2735
2736                         cm = mtod(m, struct cmsghdr *);
2737                         clen = m->m_len;
2738
2739                         while (cm != NULL) {
2740                                 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2741                                         break;
2742
2743                                 data = CMSG_DATA(cm);
2744                                 datalen = (caddr_t)cm + cm->cmsg_len
2745                                     - (caddr_t)data;
2746
2747                                 if (cm->cmsg_level == SOL_SOCKET &&
2748                                     cm->cmsg_type == SCM_RIGHTS) {
2749                                         (*op)(data, datalen /
2750                                             sizeof(struct filedescent *));
2751                                 }
2752
2753                                 if (CMSG_SPACE(datalen) < clen) {
2754                                         clen -= CMSG_SPACE(datalen);
2755                                         cm = (struct cmsghdr *)
2756                                             ((caddr_t)cm + CMSG_SPACE(datalen));
2757                                 } else {
2758                                         clen = 0;
2759                                         cm = NULL;
2760                                 }
2761                         }
2762                 }
2763                 m0 = m0->m_nextpkt;
2764         }
2765 }
2766
2767 /*
2768  * A helper function called by VFS before socket-type vnode reclamation.
2769  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2770  * use count.
2771  */
2772 void
2773 vfs_unp_reclaim(struct vnode *vp)
2774 {
2775         struct unpcb *unp;
2776         int active;
2777         struct mtx *vplock;
2778
2779         ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2780         KASSERT(vp->v_type == VSOCK,
2781             ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2782
2783         active = 0;
2784         vplock = mtx_pool_find(mtxpool_sleep, vp);
2785         mtx_lock(vplock);
2786         VOP_UNP_CONNECT(vp, &unp);
2787         if (unp == NULL)
2788                 goto done;
2789         UNP_PCB_LOCK(unp);
2790         if (unp->unp_vnode == vp) {
2791                 VOP_UNP_DETACH(vp);
2792                 unp->unp_vnode = NULL;
2793                 active = 1;
2794         }
2795         UNP_PCB_UNLOCK(unp);
2796  done:
2797         mtx_unlock(vplock);
2798         if (active)
2799                 vunref(vp);
2800 }
2801
2802 #ifdef DDB
2803 static void
2804 db_print_indent(int indent)
2805 {
2806         int i;
2807
2808         for (i = 0; i < indent; i++)
2809                 db_printf(" ");
2810 }
2811
2812 static void
2813 db_print_unpflags(int unp_flags)
2814 {
2815         int comma;
2816
2817         comma = 0;
2818         if (unp_flags & UNP_HAVEPC) {
2819                 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2820                 comma = 1;
2821         }
2822         if (unp_flags & UNP_WANTCRED) {
2823                 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2824                 comma = 1;
2825         }
2826         if (unp_flags & UNP_CONNWAIT) {
2827                 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2828                 comma = 1;
2829         }
2830         if (unp_flags & UNP_CONNECTING) {
2831                 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2832                 comma = 1;
2833         }
2834         if (unp_flags & UNP_BINDING) {
2835                 db_printf("%sUNP_BINDING", comma ? ", " : "");
2836                 comma = 1;
2837         }
2838 }
2839
2840 static void
2841 db_print_xucred(int indent, struct xucred *xu)
2842 {
2843         int comma, i;
2844
2845         db_print_indent(indent);
2846         db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
2847             xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
2848         db_print_indent(indent);
2849         db_printf("cr_groups: ");
2850         comma = 0;
2851         for (i = 0; i < xu->cr_ngroups; i++) {
2852                 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2853                 comma = 1;
2854         }
2855         db_printf("\n");
2856 }
2857
2858 static void
2859 db_print_unprefs(int indent, struct unp_head *uh)
2860 {
2861         struct unpcb *unp;
2862         int counter;
2863
2864         counter = 0;
2865         LIST_FOREACH(unp, uh, unp_reflink) {
2866                 if (counter % 4 == 0)
2867                         db_print_indent(indent);
2868                 db_printf("%p  ", unp);
2869                 if (counter % 4 == 3)
2870                         db_printf("\n");
2871                 counter++;
2872         }
2873         if (counter != 0 && counter % 4 != 0)
2874                 db_printf("\n");
2875 }
2876
2877 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2878 {
2879         struct unpcb *unp;
2880
2881         if (!have_addr) {
2882                 db_printf("usage: show unpcb <addr>\n");
2883                 return;
2884         }
2885         unp = (struct unpcb *)addr;
2886
2887         db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
2888             unp->unp_vnode);
2889
2890         db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2891             unp->unp_conn);
2892
2893         db_printf("unp_refs:\n");
2894         db_print_unprefs(2, &unp->unp_refs);
2895
2896         /* XXXRW: Would be nice to print the full address, if any. */
2897         db_printf("unp_addr: %p\n", unp->unp_addr);
2898
2899         db_printf("unp_gencnt: %llu\n",
2900             (unsigned long long)unp->unp_gencnt);
2901
2902         db_printf("unp_flags: %x (", unp->unp_flags);
2903         db_print_unpflags(unp->unp_flags);
2904         db_printf(")\n");
2905
2906         db_printf("unp_peercred:\n");
2907         db_print_xucred(2, &unp->unp_peercred);
2908
2909         db_printf("unp_refcount: %u\n", unp->unp_refcount);
2910 }
2911 #endif