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