]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_usrreq.c
Import mandoc 1.14.4
[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, 0, "Local domain");
167 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0,
168     "SOCK_STREAM");
169 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
170 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, CTLFLAG_RW, 0,
171     "SOCK_SEQPACKET");
172
173 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
174            &unpst_sendspace, 0, "Default stream send space.");
175 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
176            &unpst_recvspace, 0, "Default stream receive space.");
177 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
178            &unpdg_sendspace, 0, "Default datagram send space.");
179 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
180            &unpdg_recvspace, 0, "Default datagram receive space.");
181 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
182            &unpsp_sendspace, 0, "Default seqpacket send space.");
183 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
184            &unpsp_recvspace, 0, "Default seqpacket receive space.");
185 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
186     "File descriptors in flight.");
187 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
188     &unp_defers_count, 0,
189     "File descriptors deferred to taskqueue for close.");
190
191 /*
192  * Locking and synchronization:
193  *
194  * Three types of locks exist in the local domain socket implementation: a
195  * a global linkage rwlock, the mtxpool lock, and per-unpcb mutexes.
196  * The linkage lock protects the socket count, global generation number,
197  * and stream/datagram global lists.
198  *
199  * The mtxpool lock protects the vnode from being modified while referenced.
200  * Lock ordering requires that it be acquired before any unpcb locks.
201  *
202  * The unpcb lock (unp_mtx) protects all fields in the unpcb. Of particular
203  * note is that this includes the unp_conn field. So long as the unpcb lock
204  * is held the reference to the unpcb pointed to by unp_conn is valid. If we
205  * require that the unpcb pointed to by unp_conn remain live in cases where
206  * we need to drop the unp_mtx as when we need to acquire the lock for a
207  * second unpcb the caller must first acquire an additional reference on the
208  * second unpcb and then revalidate any state (typically check that unp_conn
209  * is non-NULL) upon requiring the initial unpcb lock. The lock ordering
210  * between unpcbs is the conventional ascending address order. Two helper
211  * routines exist for this:
212  *
213  *   - unp_pcb_lock2(unp, unp2) - which just acquires the two locks in the
214  *     safe ordering.
215  *
216  *   - unp_pcb_owned_lock2(unp, unp2, freed) - the lock for unp is held
217  *     when called. If unp is unlocked and unp2 is subsequently freed
218  *     freed will be set to 1.
219  *
220  * The helper routines for references are:
221  *
222  *   - unp_pcb_hold(unp): Can be called any time we currently hold a valid
223  *     reference to unp.
224  *
225  *    - unp_pcb_rele(unp): The caller must hold the unp lock. If we are
226  *      releasing the last reference, detach must have been called thus
227  *      unp->unp_socket be NULL.
228  *
229  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
230  * allocated in pru_attach() and freed in pru_detach().  The validity of that
231  * pointer is an invariant, so no lock is required to dereference the so_pcb
232  * pointer if a valid socket reference is held by the caller.  In practice,
233  * this is always true during operations performed on a socket.  Each unpcb
234  * has a back-pointer to its socket, unp_socket, which will be stable under
235  * the same circumstances.
236  *
237  * This pointer may only be safely dereferenced as long as a valid reference
238  * to the unpcb is held.  Typically, this reference will be from the socket,
239  * or from another unpcb when the referring unpcb's lock is held (in order
240  * that the reference not be invalidated during use).  For example, to follow
241  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
242  * that detach is not run clearing unp_socket.
243  *
244  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
245  * protocols, bind() is a non-atomic operation, and connect() requires
246  * potential sleeping in the protocol, due to potentially waiting on local or
247  * distributed file systems.  We try to separate "lookup" operations, which
248  * may sleep, and the IPC operations themselves, which typically can occur
249  * with relative atomicity as locks can be held over the entire operation.
250  *
251  * Another tricky issue is simultaneous multi-threaded or multi-process
252  * access to a single UNIX domain socket.  These are handled by the flags
253  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
254  * binding, both of which involve dropping UNIX domain socket locks in order
255  * to perform namei() and other file system operations.
256  */
257 static struct rwlock    unp_link_rwlock;
258 static struct mtx       unp_defers_lock;
259
260 #define UNP_LINK_LOCK_INIT()            rw_init(&unp_link_rwlock,       \
261                                             "unp_link_rwlock")
262
263 #define UNP_LINK_LOCK_ASSERT()  rw_assert(&unp_link_rwlock,     \
264                                             RA_LOCKED)
265 #define UNP_LINK_UNLOCK_ASSERT()        rw_assert(&unp_link_rwlock,     \
266                                             RA_UNLOCKED)
267
268 #define UNP_LINK_RLOCK()                rw_rlock(&unp_link_rwlock)
269 #define UNP_LINK_RUNLOCK()              rw_runlock(&unp_link_rwlock)
270 #define UNP_LINK_WLOCK()                rw_wlock(&unp_link_rwlock)
271 #define UNP_LINK_WUNLOCK()              rw_wunlock(&unp_link_rwlock)
272 #define UNP_LINK_WLOCK_ASSERT()         rw_assert(&unp_link_rwlock,     \
273                                             RA_WLOCKED)
274 #define UNP_LINK_WOWNED()               rw_wowned(&unp_link_rwlock)
275
276 #define UNP_DEFERRED_LOCK_INIT()        mtx_init(&unp_defers_lock, \
277                                             "unp_defer", NULL, MTX_DEF)
278 #define UNP_DEFERRED_LOCK()             mtx_lock(&unp_defers_lock)
279 #define UNP_DEFERRED_UNLOCK()           mtx_unlock(&unp_defers_lock)
280
281 #define UNP_REF_LIST_LOCK()             UNP_DEFERRED_LOCK();
282 #define UNP_REF_LIST_UNLOCK()           UNP_DEFERRED_UNLOCK();
283
284 #define UNP_PCB_LOCK_INIT(unp)          mtx_init(&(unp)->unp_mtx,       \
285                                             "unp", "unp",       \
286                                             MTX_DUPOK|MTX_DEF)
287 #define UNP_PCB_LOCK_DESTROY(unp)       mtx_destroy(&(unp)->unp_mtx)
288 #define UNP_PCB_LOCK(unp)               mtx_lock(&(unp)->unp_mtx)
289 #define UNP_PCB_TRYLOCK(unp)            mtx_trylock(&(unp)->unp_mtx)
290 #define UNP_PCB_UNLOCK(unp)             mtx_unlock(&(unp)->unp_mtx)
291 #define UNP_PCB_OWNED(unp)              mtx_owned(&(unp)->unp_mtx)
292 #define UNP_PCB_LOCK_ASSERT(unp)        mtx_assert(&(unp)->unp_mtx, MA_OWNED)
293 #define UNP_PCB_UNLOCK_ASSERT(unp)      mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
294
295 static int      uipc_connect2(struct socket *, struct socket *);
296 static int      uipc_ctloutput(struct socket *, struct sockopt *);
297 static int      unp_connect(struct socket *, struct sockaddr *,
298                     struct thread *);
299 static int      unp_connectat(int, struct socket *, struct sockaddr *,
300                     struct thread *);
301 static int      unp_connect2(struct socket *so, struct socket *so2, int);
302 static void     unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
303 static void     unp_dispose(struct socket *so);
304 static void     unp_dispose_mbuf(struct mbuf *);
305 static void     unp_shutdown(struct unpcb *);
306 static void     unp_drop(struct unpcb *);
307 static void     unp_gc(__unused void *, int);
308 static void     unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
309 static void     unp_discard(struct file *);
310 static void     unp_freerights(struct filedescent **, int);
311 static void     unp_init(void);
312 static int      unp_internalize(struct mbuf **, struct thread *);
313 static void     unp_internalize_fp(struct file *);
314 static int      unp_externalize(struct mbuf *, struct mbuf **, int);
315 static int      unp_externalize_fp(struct file *);
316 static struct mbuf      *unp_addsockcred(struct thread *, struct mbuf *);
317 static void     unp_process_defers(void * __unused, int);
318
319
320 static void
321 unp_pcb_hold(struct unpcb *unp)
322 {
323         MPASS(unp->unp_refcount);
324         refcount_acquire(&unp->unp_refcount);
325 }
326
327 static int
328 unp_pcb_rele(struct unpcb *unp)
329 {
330         int freed;
331
332         UNP_PCB_LOCK_ASSERT(unp);
333         MPASS(unp->unp_refcount);
334         if ((freed = refcount_release(&unp->unp_refcount))) {
335                 /* we got here with having detached? */
336                 MPASS(unp->unp_socket == NULL);
337                 UNP_PCB_UNLOCK(unp);
338                 UNP_PCB_LOCK_DESTROY(unp);
339                 uma_zfree(unp_zone, unp);
340         }
341         return (freed);
342 }
343
344 static void
345 unp_pcb_lock2(struct unpcb *unp, struct unpcb *unp2)
346 {
347         MPASS(unp != unp2);
348         UNP_PCB_UNLOCK_ASSERT(unp);
349         UNP_PCB_UNLOCK_ASSERT(unp2);
350         if ((uintptr_t)unp2 > (uintptr_t)unp) {
351                 UNP_PCB_LOCK(unp);
352                 UNP_PCB_LOCK(unp2);
353         } else {
354                 UNP_PCB_LOCK(unp2);
355                 UNP_PCB_LOCK(unp);
356         }
357 }
358
359 static __noinline void
360 unp_pcb_owned_lock2_slowpath(struct unpcb *unp, struct unpcb **unp2p,
361     int *freed)
362 {
363         struct unpcb *unp2;
364
365         unp2 = *unp2p;
366         unp_pcb_hold(unp2);
367         UNP_PCB_UNLOCK(unp);
368         UNP_PCB_LOCK(unp2);
369         UNP_PCB_LOCK(unp);
370         *freed = unp_pcb_rele(unp2);
371         if (*freed)
372                 *unp2p = NULL;
373 }
374
375 #define unp_pcb_owned_lock2(unp, unp2, freed) do {                      \
376         freed = 0;                                                      \
377         UNP_PCB_LOCK_ASSERT(unp);                                       \
378         UNP_PCB_UNLOCK_ASSERT(unp2);                                    \
379         MPASS((unp) != (unp2));                                         \
380         if (__predict_true(UNP_PCB_TRYLOCK(unp2)))                      \
381                 break;                                                  \
382         else if ((uintptr_t)(unp2) > (uintptr_t)(unp))                  \
383                 UNP_PCB_LOCK(unp2);                                     \
384         else                                                            \
385                 unp_pcb_owned_lock2_slowpath((unp), &(unp2), &freed);   \
386 } while (0)
387
388
389 /*
390  * Definitions of protocols supported in the LOCAL domain.
391  */
392 static struct domain localdomain;
393 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
394 static struct pr_usrreqs uipc_usrreqs_seqpacket;
395 static struct protosw localsw[] = {
396 {
397         .pr_type =              SOCK_STREAM,
398         .pr_domain =            &localdomain,
399         .pr_flags =             PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
400         .pr_ctloutput =         &uipc_ctloutput,
401         .pr_usrreqs =           &uipc_usrreqs_stream
402 },
403 {
404         .pr_type =              SOCK_DGRAM,
405         .pr_domain =            &localdomain,
406         .pr_flags =             PR_ATOMIC|PR_ADDR|PR_RIGHTS,
407         .pr_ctloutput =         &uipc_ctloutput,
408         .pr_usrreqs =           &uipc_usrreqs_dgram
409 },
410 {
411         .pr_type =              SOCK_SEQPACKET,
412         .pr_domain =            &localdomain,
413
414         /*
415          * XXXRW: For now, PR_ADDR because soreceive will bump into them
416          * due to our use of sbappendaddr.  A new sbappend variants is needed
417          * that supports both atomic record writes and control data.
418          */
419         .pr_flags =             PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
420                                     PR_RIGHTS,
421         .pr_ctloutput =         &uipc_ctloutput,
422         .pr_usrreqs =           &uipc_usrreqs_seqpacket,
423 },
424 };
425
426 static struct domain localdomain = {
427         .dom_family =           AF_LOCAL,
428         .dom_name =             "local",
429         .dom_init =             unp_init,
430         .dom_externalize =      unp_externalize,
431         .dom_dispose =          unp_dispose,
432         .dom_protosw =          localsw,
433         .dom_protoswNPROTOSW =  &localsw[nitems(localsw)]
434 };
435 DOMAIN_SET(local);
436
437 static void
438 uipc_abort(struct socket *so)
439 {
440         struct unpcb *unp, *unp2;
441
442         unp = sotounpcb(so);
443         KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
444         UNP_PCB_UNLOCK_ASSERT(unp);
445
446         UNP_PCB_LOCK(unp);
447         unp2 = unp->unp_conn;
448         if (unp2 != NULL) {
449                 unp_pcb_hold(unp2);
450                 UNP_PCB_UNLOCK(unp);
451                 unp_drop(unp2);
452         } else
453                 UNP_PCB_UNLOCK(unp);
454 }
455
456 static int
457 uipc_accept(struct socket *so, struct sockaddr **nam)
458 {
459         struct unpcb *unp, *unp2;
460         const struct sockaddr *sa;
461
462         /*
463          * Pass back name of connected socket, if it was bound and we are
464          * still connected (our peer may have closed already!).
465          */
466         unp = sotounpcb(so);
467         KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
468
469         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
470         UNP_LINK_RLOCK();
471         unp2 = unp->unp_conn;
472         if (unp2 != NULL && unp2->unp_addr != NULL) {
473                 UNP_PCB_LOCK(unp2);
474                 sa = (struct sockaddr *) unp2->unp_addr;
475                 bcopy(sa, *nam, sa->sa_len);
476                 UNP_PCB_UNLOCK(unp2);
477         } else {
478                 sa = &sun_noname;
479                 bcopy(sa, *nam, sa->sa_len);
480         }
481         UNP_LINK_RUNLOCK();
482         return (0);
483 }
484
485 static int
486 uipc_attach(struct socket *so, int proto, struct thread *td)
487 {
488         u_long sendspace, recvspace;
489         struct unpcb *unp;
490         int error;
491         bool locked;
492
493         KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
494         if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
495                 switch (so->so_type) {
496                 case SOCK_STREAM:
497                         sendspace = unpst_sendspace;
498                         recvspace = unpst_recvspace;
499                         break;
500
501                 case SOCK_DGRAM:
502                         sendspace = unpdg_sendspace;
503                         recvspace = unpdg_recvspace;
504                         break;
505
506                 case SOCK_SEQPACKET:
507                         sendspace = unpsp_sendspace;
508                         recvspace = unpsp_recvspace;
509                         break;
510
511                 default:
512                         panic("uipc_attach");
513                 }
514                 error = soreserve(so, sendspace, recvspace);
515                 if (error)
516                         return (error);
517         }
518         unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
519         if (unp == NULL)
520                 return (ENOBUFS);
521         LIST_INIT(&unp->unp_refs);
522         UNP_PCB_LOCK_INIT(unp);
523         unp->unp_socket = so;
524         so->so_pcb = unp;
525         unp->unp_refcount = 1;
526         if (so->so_listen != NULL)
527                 unp->unp_flags |= UNP_NASCENT;
528
529         if ((locked = UNP_LINK_WOWNED()) == false)
530                 UNP_LINK_WLOCK();
531
532         unp->unp_gencnt = ++unp_gencnt;
533         unp_count++;
534         switch (so->so_type) {
535         case SOCK_STREAM:
536                 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
537                 break;
538
539         case SOCK_DGRAM:
540                 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
541                 break;
542
543         case SOCK_SEQPACKET:
544                 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
545                 break;
546
547         default:
548                 panic("uipc_attach");
549         }
550
551         if (locked == false)
552                 UNP_LINK_WUNLOCK();
553
554         return (0);
555 }
556
557 static int
558 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
559 {
560         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
561         struct vattr vattr;
562         int error, namelen;
563         struct nameidata nd;
564         struct unpcb *unp;
565         struct vnode *vp;
566         struct mount *mp;
567         cap_rights_t rights;
568         char *buf;
569
570         if (nam->sa_family != AF_UNIX)
571                 return (EAFNOSUPPORT);
572
573         unp = sotounpcb(so);
574         KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
575
576         if (soun->sun_len > sizeof(struct sockaddr_un))
577                 return (EINVAL);
578         namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
579         if (namelen <= 0)
580                 return (EINVAL);
581
582         /*
583          * We don't allow simultaneous bind() calls on a single UNIX domain
584          * socket, so flag in-progress operations, and return an error if an
585          * operation is already in progress.
586          *
587          * Historically, we have not allowed a socket to be rebound, so this
588          * also returns an error.  Not allowing re-binding simplifies the
589          * implementation and avoids a great many possible failure modes.
590          */
591         UNP_PCB_LOCK(unp);
592         if (unp->unp_vnode != NULL) {
593                 UNP_PCB_UNLOCK(unp);
594                 return (EINVAL);
595         }
596         if (unp->unp_flags & UNP_BINDING) {
597                 UNP_PCB_UNLOCK(unp);
598                 return (EALREADY);
599         }
600         unp->unp_flags |= UNP_BINDING;
601         UNP_PCB_UNLOCK(unp);
602
603         buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
604         bcopy(soun->sun_path, buf, namelen);
605         buf[namelen] = 0;
606
607 restart:
608         NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
609             UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
610 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
611         error = namei(&nd);
612         if (error)
613                 goto error;
614         vp = nd.ni_vp;
615         if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
616                 NDFREE(&nd, NDF_ONLY_PNBUF);
617                 if (nd.ni_dvp == vp)
618                         vrele(nd.ni_dvp);
619                 else
620                         vput(nd.ni_dvp);
621                 if (vp != NULL) {
622                         vrele(vp);
623                         error = EADDRINUSE;
624                         goto error;
625                 }
626                 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
627                 if (error)
628                         goto error;
629                 goto restart;
630         }
631         VATTR_NULL(&vattr);
632         vattr.va_type = VSOCK;
633         vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
634 #ifdef MAC
635         error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
636             &vattr);
637 #endif
638         if (error == 0)
639                 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
640         NDFREE(&nd, NDF_ONLY_PNBUF);
641         vput(nd.ni_dvp);
642         if (error) {
643                 vn_finished_write(mp);
644                 goto error;
645         }
646         vp = nd.ni_vp;
647         ASSERT_VOP_ELOCKED(vp, "uipc_bind");
648         soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
649
650         UNP_PCB_LOCK(unp);
651         VOP_UNP_BIND(vp, unp);
652         unp->unp_vnode = vp;
653         unp->unp_addr = soun;
654         unp->unp_flags &= ~UNP_BINDING;
655         UNP_PCB_UNLOCK(unp);
656         VOP_UNLOCK(vp, 0);
657         vn_finished_write(mp);
658         free(buf, M_TEMP);
659         return (0);
660
661 error:
662         UNP_PCB_LOCK(unp);
663         unp->unp_flags &= ~UNP_BINDING;
664         UNP_PCB_UNLOCK(unp);
665         free(buf, M_TEMP);
666         return (error);
667 }
668
669 static int
670 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
671 {
672
673         return (uipc_bindat(AT_FDCWD, so, nam, td));
674 }
675
676 static int
677 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
678 {
679         int error;
680
681         KASSERT(td == curthread, ("uipc_connect: td != curthread"));
682         error = unp_connect(so, nam, td);
683         return (error);
684 }
685
686 static int
687 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
688     struct thread *td)
689 {
690         int error;
691
692         KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
693         error = unp_connectat(fd, so, nam, td);
694         return (error);
695 }
696
697 static void
698 uipc_close(struct socket *so)
699 {
700         struct unpcb *unp, *unp2;
701         struct vnode *vp = NULL;
702         struct mtx *vplock;
703         int freed;
704         unp = sotounpcb(so);
705         KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
706
707
708         vplock = NULL;
709         if ((vp = unp->unp_vnode) != NULL) {
710                 vplock = mtx_pool_find(mtxpool_sleep, vp);
711                 mtx_lock(vplock);
712         }
713         UNP_PCB_LOCK(unp);
714         if (vp && unp->unp_vnode == NULL) {
715                 mtx_unlock(vplock);
716                 vp = NULL;
717         }
718         if (vp != NULL) {
719                 VOP_UNP_DETACH(vp);
720                 unp->unp_vnode = NULL;
721         }
722         unp2 = unp->unp_conn;
723         unp_pcb_hold(unp);
724         if (__predict_false(unp == unp2)) {
725                 unp_disconnect(unp, unp2);
726         } else if (unp2 != NULL) {
727                 unp_pcb_hold(unp2);
728                 unp_pcb_owned_lock2(unp, unp2, freed);
729                 unp_disconnect(unp, unp2);
730                 if (unp_pcb_rele(unp2) == 0)
731                         UNP_PCB_UNLOCK(unp2);
732         }
733         if (unp_pcb_rele(unp) == 0)
734                 UNP_PCB_UNLOCK(unp);
735         if (vp) {
736                 mtx_unlock(vplock);
737                 vrele(vp);
738         }
739 }
740
741 static int
742 uipc_connect2(struct socket *so1, struct socket *so2)
743 {
744         struct unpcb *unp, *unp2;
745         int error;
746
747         unp = so1->so_pcb;
748         KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
749         unp2 = so2->so_pcb;
750         KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
751         if (unp != unp2)
752                 unp_pcb_lock2(unp, unp2);
753         else
754                 UNP_PCB_LOCK(unp);
755         error = unp_connect2(so1, so2, PRU_CONNECT2);
756         if (unp != unp2)
757                 UNP_PCB_UNLOCK(unp2);
758         UNP_PCB_UNLOCK(unp);
759         return (error);
760 }
761
762 static void
763 uipc_detach(struct socket *so)
764 {
765         struct unpcb *unp, *unp2;
766         struct mtx *vplock;
767         struct sockaddr_un *saved_unp_addr;
768         struct vnode *vp;
769         int freeunp, local_unp_rights;
770
771         unp = sotounpcb(so);
772         KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
773
774         vp = NULL;
775         vplock = NULL;
776         local_unp_rights = 0;
777
778         UNP_LINK_WLOCK();
779         LIST_REMOVE(unp, unp_link);
780         unp->unp_gencnt = ++unp_gencnt;
781         --unp_count;
782         UNP_LINK_WUNLOCK();
783
784         UNP_PCB_UNLOCK_ASSERT(unp);
785  restart:
786         if ((vp = unp->unp_vnode) != NULL) {
787                 vplock = mtx_pool_find(mtxpool_sleep, vp);
788                 mtx_lock(vplock);
789         }
790         UNP_PCB_LOCK(unp);
791         if (unp->unp_vnode != vp &&
792                 unp->unp_vnode != NULL) {
793                 if (vplock)
794                         mtx_unlock(vplock);
795                 UNP_PCB_UNLOCK(unp);
796                 goto restart;
797         }
798         if ((unp->unp_flags & UNP_NASCENT) != 0) {
799                 goto teardown;
800         }
801         if ((vp = unp->unp_vnode) != NULL) {
802                 VOP_UNP_DETACH(vp);
803                 unp->unp_vnode = NULL;
804         }
805         if (__predict_false(unp == unp->unp_conn)) {
806                 unp_disconnect(unp, unp);
807                 unp2 = NULL;
808                 goto connect_self;
809         }
810         if ((unp2 = unp->unp_conn) != NULL) {
811                 unp_pcb_owned_lock2(unp, unp2, freeunp);
812                 if (freeunp)
813                         unp2 = NULL;
814         }
815         unp_pcb_hold(unp);
816         if (unp2 != NULL) {
817                 unp_pcb_hold(unp2);
818                 unp_disconnect(unp, unp2);
819                 if (unp_pcb_rele(unp2) == 0)
820                         UNP_PCB_UNLOCK(unp2);
821         }
822  connect_self:
823         UNP_PCB_UNLOCK(unp);
824         UNP_REF_LIST_LOCK();
825         while (!LIST_EMPTY(&unp->unp_refs)) {
826                 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
827
828                 unp_pcb_hold(ref);
829                 UNP_REF_LIST_UNLOCK();
830
831                 MPASS(ref != unp);
832                 UNP_PCB_UNLOCK_ASSERT(ref);
833                 unp_drop(ref);
834                 UNP_REF_LIST_LOCK();
835         }
836
837         UNP_REF_LIST_UNLOCK();
838         UNP_PCB_LOCK(unp);
839         freeunp = unp_pcb_rele(unp);
840         MPASS(freeunp == 0);
841         local_unp_rights = unp_rights;
842 teardown:
843         unp->unp_socket->so_pcb = NULL;
844         saved_unp_addr = unp->unp_addr;
845         unp->unp_addr = NULL;
846         unp->unp_socket = NULL;
847         freeunp = unp_pcb_rele(unp);
848         if (saved_unp_addr != NULL)
849                 free(saved_unp_addr, M_SONAME);
850         if (!freeunp)
851                 UNP_PCB_UNLOCK(unp);
852         if (vp) {
853                 mtx_unlock(vplock);
854                 vrele(vp);
855         }
856         if (local_unp_rights)
857                 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
858 }
859
860 static int
861 uipc_disconnect(struct socket *so)
862 {
863         struct unpcb *unp, *unp2;
864         int freed;
865
866         unp = sotounpcb(so);
867         KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
868
869         UNP_PCB_LOCK(unp);
870         if ((unp2 = unp->unp_conn) == NULL) {
871                 UNP_PCB_UNLOCK(unp);
872                 return (0);
873         }
874         if (__predict_true(unp != unp2)) {
875                 unp_pcb_owned_lock2(unp, unp2, freed);
876                 if (__predict_false(freed)) {
877                         UNP_PCB_UNLOCK(unp);
878                         return (0);
879                 }
880                 unp_pcb_hold(unp2);
881         }
882         unp_pcb_hold(unp);
883         unp_disconnect(unp, unp2);
884         if (unp_pcb_rele(unp) == 0)
885                 UNP_PCB_UNLOCK(unp);
886         if ((unp != unp2) && unp_pcb_rele(unp2) == 0)
887                 UNP_PCB_UNLOCK(unp2);
888         return (0);
889 }
890
891 static int
892 uipc_listen(struct socket *so, int backlog, struct thread *td)
893 {
894         struct unpcb *unp;
895         int error;
896
897         if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
898                 return (EOPNOTSUPP);
899
900         unp = sotounpcb(so);
901         KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
902
903         UNP_PCB_LOCK(unp);
904         if (unp->unp_vnode == NULL) {
905                 /* Already connected or not bound to an address. */
906                 error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
907                 UNP_PCB_UNLOCK(unp);
908                 return (error);
909         }
910
911         SOCK_LOCK(so);
912         error = solisten_proto_check(so);
913         if (error == 0) {
914                 cru2x(td->td_ucred, &unp->unp_peercred);
915                 solisten_proto(so, backlog);
916         }
917         SOCK_UNLOCK(so);
918         UNP_PCB_UNLOCK(unp);
919         return (error);
920 }
921
922 static int
923 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
924 {
925         struct unpcb *unp, *unp2;
926         const struct sockaddr *sa;
927
928         unp = sotounpcb(so);
929         KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
930
931         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
932         UNP_LINK_RLOCK();
933         /*
934          * XXX: It seems that this test always fails even when connection is
935          * established.  So, this else clause is added as workaround to
936          * return PF_LOCAL sockaddr.
937          */
938         unp2 = unp->unp_conn;
939         if (unp2 != NULL) {
940                 UNP_PCB_LOCK(unp2);
941                 if (unp2->unp_addr != NULL)
942                         sa = (struct sockaddr *) unp2->unp_addr;
943                 else
944                         sa = &sun_noname;
945                 bcopy(sa, *nam, sa->sa_len);
946                 UNP_PCB_UNLOCK(unp2);
947         } else {
948                 sa = &sun_noname;
949                 bcopy(sa, *nam, sa->sa_len);
950         }
951         UNP_LINK_RUNLOCK();
952         return (0);
953 }
954
955 static int
956 uipc_rcvd(struct socket *so, int flags)
957 {
958         struct unpcb *unp, *unp2;
959         struct socket *so2;
960         u_int mbcnt, sbcc;
961
962         unp = sotounpcb(so);
963         KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
964         KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
965             ("%s: socktype %d", __func__, so->so_type));
966
967         /*
968          * Adjust backpressure on sender and wakeup any waiting to write.
969          *
970          * The unp lock is acquired to maintain the validity of the unp_conn
971          * pointer; no lock on unp2 is required as unp2->unp_socket will be
972          * static as long as we don't permit unp2 to disconnect from unp,
973          * which is prevented by the lock on unp.  We cache values from
974          * so_rcv to avoid holding the so_rcv lock over the entire
975          * transaction on the remote so_snd.
976          */
977         SOCKBUF_LOCK(&so->so_rcv);
978         mbcnt = so->so_rcv.sb_mbcnt;
979         sbcc = sbavail(&so->so_rcv);
980         SOCKBUF_UNLOCK(&so->so_rcv);
981         /*
982          * There is a benign race condition at this point.  If we're planning to
983          * clear SB_STOP, but uipc_send is called on the connected socket at
984          * this instant, it might add data to the sockbuf and set SB_STOP.  Then
985          * we would erroneously clear SB_STOP below, even though the sockbuf is
986          * full.  The race is benign because the only ill effect is to allow the
987          * sockbuf to exceed its size limit, and the size limits are not
988          * strictly guaranteed anyway.
989          */
990         UNP_PCB_LOCK(unp);
991         unp2 = unp->unp_conn;
992         if (unp2 == NULL) {
993                 UNP_PCB_UNLOCK(unp);
994                 return (0);
995         }
996         so2 = unp2->unp_socket;
997         SOCKBUF_LOCK(&so2->so_snd);
998         if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
999                 so2->so_snd.sb_flags &= ~SB_STOP;
1000         sowwakeup_locked(so2);
1001         UNP_PCB_UNLOCK(unp);
1002         return (0);
1003 }
1004
1005 static int
1006 connect_internal(struct socket *so, struct sockaddr *nam, struct thread *td)
1007 {
1008         int error;
1009         struct unpcb *unp;
1010
1011         unp = so->so_pcb;
1012         if (unp->unp_conn != NULL)
1013                 return (EISCONN);
1014         error = unp_connect(so, nam, td);
1015         if (error)
1016                 return (error);
1017         UNP_PCB_LOCK(unp);
1018         if (unp->unp_conn == NULL) {
1019                 UNP_PCB_UNLOCK(unp);
1020                 if (error == 0)
1021                         error = ENOTCONN;
1022         }
1023         return (error);
1024 }
1025
1026
1027 static int
1028 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1029     struct mbuf *control, struct thread *td)
1030 {
1031         struct unpcb *unp, *unp2;
1032         struct socket *so2;
1033         u_int mbcnt, sbcc;
1034         int freed, error;
1035
1036         unp = sotounpcb(so);
1037         KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
1038         KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
1039             so->so_type == SOCK_SEQPACKET,
1040             ("%s: socktype %d", __func__, so->so_type));
1041
1042         freed = error = 0;
1043         if (flags & PRUS_OOB) {
1044                 error = EOPNOTSUPP;
1045                 goto release;
1046         }
1047         if (control != NULL && (error = unp_internalize(&control, td)))
1048                 goto release;
1049
1050         unp2 = NULL;
1051         switch (so->so_type) {
1052         case SOCK_DGRAM:
1053         {
1054                 const struct sockaddr *from;
1055
1056                 if (nam != NULL) {
1057                         /*
1058                          * We return with UNP_PCB_LOCK_HELD so we know that
1059                          * the reference is live if the pointer is valid.
1060                          */
1061                         if ((error = connect_internal(so, nam, td)))
1062                                 break;
1063                         MPASS(unp->unp_conn != NULL);
1064                         unp2 = unp->unp_conn;
1065                 } else  {
1066                         UNP_PCB_LOCK(unp);
1067
1068                         /*
1069                          * Because connect() and send() are non-atomic in a sendto()
1070                          * with a target address, it's possible that the socket will
1071                          * have disconnected before the send() can run.  In that case
1072                          * return the slightly counter-intuitive but otherwise
1073                          * correct error that the socket is not connected.
1074                          */
1075                         if ((unp2 = unp->unp_conn)  == NULL) {
1076                                 UNP_PCB_UNLOCK(unp);
1077                                 error = ENOTCONN;
1078                                 break;
1079                         }
1080                 }
1081                 if (__predict_false(unp == unp2)) {
1082                         if (unp->unp_socket == NULL) {
1083                                 error = ENOTCONN;
1084                                 break;
1085                         }
1086                         goto connect_self;
1087                 }
1088                 unp_pcb_owned_lock2(unp, unp2, freed);
1089                 if (__predict_false(freed)) {
1090                         UNP_PCB_UNLOCK(unp);
1091                         error = ENOTCONN;
1092                         break;
1093                 }
1094                 /*
1095                  * The socket referencing unp2 may have been closed
1096                  * or unp may have been disconnected if the unp lock
1097                  * was dropped to acquire unp2.
1098                  */
1099                 if (__predict_false(unp->unp_conn == NULL) ||
1100                         unp2->unp_socket == NULL) {
1101                         UNP_PCB_UNLOCK(unp);
1102                         if (unp_pcb_rele(unp2) == 0)
1103                                 UNP_PCB_UNLOCK(unp2);
1104                         error = ENOTCONN;
1105                         break;
1106                 }
1107         connect_self:
1108                 if (unp2->unp_flags & UNP_WANTCRED)
1109                         control = unp_addsockcred(td, control);
1110                 if (unp->unp_addr != NULL)
1111                         from = (struct sockaddr *)unp->unp_addr;
1112                 else
1113                         from = &sun_noname;
1114                 so2 = unp2->unp_socket;
1115                 SOCKBUF_LOCK(&so2->so_rcv);
1116                 if (sbappendaddr_locked(&so2->so_rcv, from, m,
1117                     control)) {
1118                         sorwakeup_locked(so2);
1119                         m = NULL;
1120                         control = NULL;
1121                 } else {
1122                         SOCKBUF_UNLOCK(&so2->so_rcv);
1123                         error = ENOBUFS;
1124                 }
1125                 if (nam != NULL)
1126                         unp_disconnect(unp, unp2);
1127                 if (__predict_true(unp != unp2))
1128                         UNP_PCB_UNLOCK(unp2);
1129                 UNP_PCB_UNLOCK(unp);
1130                 break;
1131         }
1132
1133         case SOCK_SEQPACKET:
1134         case SOCK_STREAM:
1135                 if ((so->so_state & SS_ISCONNECTED) == 0) {
1136                         if (nam != NULL) {
1137                                 if ((error = connect_internal(so, nam, td)))
1138                                         break;
1139                         } else  {
1140                                 error = ENOTCONN;
1141                                 break;
1142                         }
1143                 } else if ((unp2 = unp->unp_conn) == NULL) {
1144                         error = ENOTCONN;
1145                         break;
1146                 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1147                         error = EPIPE;
1148                         break;
1149                 } else {
1150                         UNP_PCB_LOCK(unp);
1151                         if ((unp2 = unp->unp_conn) == NULL) {
1152                                 UNP_PCB_UNLOCK(unp);
1153                                 error = ENOTCONN;
1154                                 break;
1155                         }
1156                 }
1157                 unp_pcb_owned_lock2(unp, unp2, freed);
1158                 UNP_PCB_UNLOCK(unp);
1159                 if (__predict_false(freed)) {
1160                         error = ENOTCONN;
1161                         break;
1162                 }
1163                 if ((so2 = unp2->unp_socket) == NULL) {
1164                         UNP_PCB_UNLOCK(unp2);
1165                         error = ENOTCONN;
1166                         break;
1167                 }
1168                 SOCKBUF_LOCK(&so2->so_rcv);
1169                 if (unp2->unp_flags & UNP_WANTCRED) {
1170                         /*
1171                          * Credentials are passed only once on SOCK_STREAM
1172                          * and SOCK_SEQPACKET.
1173                          */
1174                         unp2->unp_flags &= ~UNP_WANTCRED;
1175                         control = unp_addsockcred(td, control);
1176                 }
1177
1178                 /*
1179                  * Send to paired receive port and wake up readers.  Don't
1180                  * check for space available in the receive buffer if we're
1181                  * attaching ancillary data; Unix domain sockets only check
1182                  * for space in the sending sockbuf, and that check is
1183                  * performed one level up the stack.  At that level we cannot
1184                  * precisely account for the amount of buffer space used
1185                  * (e.g., because control messages are not yet internalized).
1186                  */
1187                 switch (so->so_type) {
1188                 case SOCK_STREAM:
1189                         if (control != NULL) {
1190                                 sbappendcontrol_locked(&so2->so_rcv, m,
1191                                     control);
1192                                 control = NULL;
1193                         } else
1194                                 sbappend_locked(&so2->so_rcv, m, flags);
1195                         break;
1196
1197                 case SOCK_SEQPACKET: {
1198                         const struct sockaddr *from;
1199
1200                         from = &sun_noname;
1201                         if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1202                             from, m, control))
1203                                 control = NULL;
1204                         break;
1205                         }
1206                 }
1207
1208                 mbcnt = so2->so_rcv.sb_mbcnt;
1209                 sbcc = sbavail(&so2->so_rcv);
1210                 if (sbcc)
1211                         sorwakeup_locked(so2);
1212                 else
1213                         SOCKBUF_UNLOCK(&so2->so_rcv);
1214
1215                 /*
1216                  * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1217                  * it would be possible for uipc_rcvd to be called at this
1218                  * point, drain the receiving sockbuf, clear SB_STOP, and then
1219                  * we would set SB_STOP below.  That could lead to an empty
1220                  * sockbuf having SB_STOP set
1221                  */
1222                 SOCKBUF_LOCK(&so->so_snd);
1223                 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1224                         so->so_snd.sb_flags |= SB_STOP;
1225                 SOCKBUF_UNLOCK(&so->so_snd);
1226                 UNP_PCB_UNLOCK(unp2);
1227                 m = NULL;
1228                 break;
1229         }
1230
1231         /*
1232          * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1233          */
1234         if (flags & PRUS_EOF) {
1235                 UNP_PCB_LOCK(unp);
1236                 socantsendmore(so);
1237                 unp_shutdown(unp);
1238                 UNP_PCB_UNLOCK(unp);
1239         }
1240         if (control != NULL && error != 0)
1241                 unp_dispose_mbuf(control);
1242
1243 release:
1244         if (control != NULL)
1245                 m_freem(control);
1246         /*
1247          * In case of PRUS_NOTREADY, uipc_ready() is responsible
1248          * for freeing memory.
1249          */   
1250         if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1251                 m_freem(m);
1252         return (error);
1253 }
1254
1255 static int
1256 uipc_ready(struct socket *so, struct mbuf *m, int count)
1257 {
1258         struct unpcb *unp, *unp2;
1259         struct socket *so2;
1260         int error;
1261
1262         unp = sotounpcb(so);
1263
1264         UNP_PCB_LOCK(unp);
1265         if ((unp2 = unp->unp_conn) == NULL) {
1266                 UNP_PCB_UNLOCK(unp);
1267                 goto error;
1268         }
1269         if (unp != unp2) {
1270                 if (UNP_PCB_TRYLOCK(unp2) == 0) {
1271                         unp_pcb_hold(unp2);
1272                         UNP_PCB_UNLOCK(unp);
1273                         UNP_PCB_LOCK(unp2);
1274                         if (unp_pcb_rele(unp2))
1275                                 goto error;
1276                 } else
1277                         UNP_PCB_UNLOCK(unp);
1278         }
1279         so2 = unp2->unp_socket;
1280
1281         SOCKBUF_LOCK(&so2->so_rcv);
1282         if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1283                 sorwakeup_locked(so2);
1284         else
1285                 SOCKBUF_UNLOCK(&so2->so_rcv);
1286
1287         UNP_PCB_UNLOCK(unp2);
1288
1289         return (error);
1290  error:
1291         for (int i = 0; i < count; i++)
1292                 m = m_free(m);
1293         return (ECONNRESET);
1294 }
1295
1296 static int
1297 uipc_sense(struct socket *so, struct stat *sb)
1298 {
1299         struct unpcb *unp;
1300
1301         unp = sotounpcb(so);
1302         KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1303
1304         sb->st_blksize = so->so_snd.sb_hiwat;
1305         UNP_PCB_LOCK(unp);
1306         sb->st_dev = NODEV;
1307         if (unp->unp_ino == 0)
1308                 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
1309         sb->st_ino = unp->unp_ino;
1310         UNP_PCB_UNLOCK(unp);
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         cru2x(td->td_ucred, &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);
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, CTLTYPE_OPAQUE | CTLFLAG_RD,
1907     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1908     "List of active local datagram sockets");
1909 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1910     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1911     "List of active local stream sockets");
1912 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1913     CTLTYPE_OPAQUE | CTLFLAG_RD,
1914     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1915     "List of active local seqpacket sockets");
1916
1917 static void
1918 unp_shutdown(struct unpcb *unp)
1919 {
1920         struct unpcb *unp2;
1921         struct socket *so;
1922
1923         UNP_PCB_LOCK_ASSERT(unp);
1924
1925         unp2 = unp->unp_conn;
1926         if ((unp->unp_socket->so_type == SOCK_STREAM ||
1927             (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1928                 so = unp2->unp_socket;
1929                 if (so != NULL)
1930                         socantrcvmore(so);
1931         }
1932 }
1933
1934 static void
1935 unp_drop(struct unpcb *unp)
1936 {
1937         struct socket *so = unp->unp_socket;
1938         struct unpcb *unp2;
1939         int freed;
1940
1941         /*
1942          * Regardless of whether the socket's peer dropped the connection
1943          * with this socket by aborting or disconnecting, POSIX requires
1944          * that ECONNRESET is returned.
1945          */
1946         /* acquire a reference so that unp isn't freed from underneath us */
1947
1948         UNP_PCB_LOCK(unp);
1949         if (so)
1950                 so->so_error = ECONNRESET;
1951         unp2 = unp->unp_conn;
1952         if (unp2 == unp) {
1953                 unp_disconnect(unp, unp2);
1954         } else if (unp2 != NULL) {
1955                 unp_pcb_hold(unp2);
1956                 unp_pcb_owned_lock2(unp, unp2, freed);
1957                 unp_disconnect(unp, unp2);
1958                 if (unp_pcb_rele(unp2) == 0)
1959                         UNP_PCB_UNLOCK(unp2);
1960         }
1961         if (unp_pcb_rele(unp) == 0)
1962                 UNP_PCB_UNLOCK(unp);
1963 }
1964
1965 static void
1966 unp_freerights(struct filedescent **fdep, int fdcount)
1967 {
1968         struct file *fp;
1969         int i;
1970
1971         KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
1972
1973         for (i = 0; i < fdcount; i++) {
1974                 fp = fdep[i]->fde_file;
1975                 filecaps_free(&fdep[i]->fde_caps);
1976                 unp_discard(fp);
1977         }
1978         free(fdep[0], M_FILECAPS);
1979 }
1980
1981 static int
1982 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
1983 {
1984         struct thread *td = curthread;          /* XXX */
1985         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1986         int i;
1987         int *fdp;
1988         struct filedesc *fdesc = td->td_proc->p_fd;
1989         struct filedescent **fdep;
1990         void *data;
1991         socklen_t clen = control->m_len, datalen;
1992         int error, newfds;
1993         u_int newlen;
1994
1995         UNP_LINK_UNLOCK_ASSERT();
1996
1997         error = 0;
1998         if (controlp != NULL) /* controlp == NULL => free control messages */
1999                 *controlp = NULL;
2000         while (cm != NULL) {
2001                 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
2002                         error = EINVAL;
2003                         break;
2004                 }
2005                 data = CMSG_DATA(cm);
2006                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2007                 if (cm->cmsg_level == SOL_SOCKET
2008                     && cm->cmsg_type == SCM_RIGHTS) {
2009                         newfds = datalen / sizeof(*fdep);
2010                         if (newfds == 0)
2011                                 goto next;
2012                         fdep = data;
2013
2014                         /* If we're not outputting the descriptors free them. */
2015                         if (error || controlp == NULL) {
2016                                 unp_freerights(fdep, newfds);
2017                                 goto next;
2018                         }
2019                         FILEDESC_XLOCK(fdesc);
2020
2021                         /*
2022                          * Now change each pointer to an fd in the global
2023                          * table to an integer that is the index to the local
2024                          * fd table entry that we set up to point to the
2025                          * global one we are transferring.
2026                          */
2027                         newlen = newfds * sizeof(int);
2028                         *controlp = sbcreatecontrol(NULL, newlen,
2029                             SCM_RIGHTS, SOL_SOCKET);
2030                         if (*controlp == NULL) {
2031                                 FILEDESC_XUNLOCK(fdesc);
2032                                 error = E2BIG;
2033                                 unp_freerights(fdep, newfds);
2034                                 goto next;
2035                         }
2036
2037                         fdp = (int *)
2038                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2039                         if (fdallocn(td, 0, fdp, newfds) != 0) {
2040                                 FILEDESC_XUNLOCK(fdesc);
2041                                 error = EMSGSIZE;
2042                                 unp_freerights(fdep, newfds);
2043                                 m_freem(*controlp);
2044                                 *controlp = NULL;
2045                                 goto next;
2046                         }
2047                         for (i = 0; i < newfds; i++, fdp++) {
2048                                 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2049                                     (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
2050                                     &fdep[i]->fde_caps);
2051                                 unp_externalize_fp(fdep[i]->fde_file);
2052                         }
2053
2054                         /*
2055                          * The new type indicates that the mbuf data refers to
2056                          * kernel resources that may need to be released before
2057                          * the mbuf is freed.
2058                          */
2059                         m_chtype(*controlp, MT_EXTCONTROL);
2060                         FILEDESC_XUNLOCK(fdesc);
2061                         free(fdep[0], M_FILECAPS);
2062                 } else {
2063                         /* We can just copy anything else across. */
2064                         if (error || controlp == NULL)
2065                                 goto next;
2066                         *controlp = sbcreatecontrol(NULL, datalen,
2067                             cm->cmsg_type, cm->cmsg_level);
2068                         if (*controlp == NULL) {
2069                                 error = ENOBUFS;
2070                                 goto next;
2071                         }
2072                         bcopy(data,
2073                             CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2074                             datalen);
2075                 }
2076                 controlp = &(*controlp)->m_next;
2077
2078 next:
2079                 if (CMSG_SPACE(datalen) < clen) {
2080                         clen -= CMSG_SPACE(datalen);
2081                         cm = (struct cmsghdr *)
2082                             ((caddr_t)cm + CMSG_SPACE(datalen));
2083                 } else {
2084                         clen = 0;
2085                         cm = NULL;
2086                 }
2087         }
2088
2089         m_freem(control);
2090         return (error);
2091 }
2092
2093 static void
2094 unp_zone_change(void *tag)
2095 {
2096
2097         uma_zone_set_max(unp_zone, maxsockets);
2098 }
2099
2100 static void
2101 unp_init(void)
2102 {
2103
2104 #ifdef VIMAGE
2105         if (!IS_DEFAULT_VNET(curvnet))
2106                 return;
2107 #endif
2108         unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
2109             NULL, NULL, UMA_ALIGN_CACHE, 0);
2110         if (unp_zone == NULL)
2111                 panic("unp_init");
2112         uma_zone_set_max(unp_zone, maxsockets);
2113         uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2114         EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2115             NULL, EVENTHANDLER_PRI_ANY);
2116         LIST_INIT(&unp_dhead);
2117         LIST_INIT(&unp_shead);
2118         LIST_INIT(&unp_sphead);
2119         SLIST_INIT(&unp_defers);
2120         TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2121         TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2122         UNP_LINK_LOCK_INIT();
2123         UNP_DEFERRED_LOCK_INIT();
2124 }
2125
2126 static int
2127 unp_internalize(struct mbuf **controlp, struct thread *td)
2128 {
2129         struct mbuf *control = *controlp;
2130         struct proc *p = td->td_proc;
2131         struct filedesc *fdesc = p->p_fd;
2132         struct bintime *bt;
2133         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2134         struct cmsgcred *cmcred;
2135         struct filedescent *fde, **fdep, *fdev;
2136         struct file *fp;
2137         struct timeval *tv;
2138         struct timespec *ts;
2139         int i, *fdp;
2140         void *data;
2141         socklen_t clen = control->m_len, datalen;
2142         int error, oldfds;
2143         u_int newlen;
2144
2145         UNP_LINK_UNLOCK_ASSERT();
2146
2147         error = 0;
2148         *controlp = NULL;
2149         while (cm != NULL) {
2150                 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2151                     || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
2152                         error = EINVAL;
2153                         goto out;
2154                 }
2155                 data = CMSG_DATA(cm);
2156                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2157
2158                 switch (cm->cmsg_type) {
2159                 /*
2160                  * Fill in credential information.
2161                  */
2162                 case SCM_CREDS:
2163                         *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2164                             SCM_CREDS, SOL_SOCKET);
2165                         if (*controlp == NULL) {
2166                                 error = ENOBUFS;
2167                                 goto out;
2168                         }
2169                         cmcred = (struct cmsgcred *)
2170                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2171                         cmcred->cmcred_pid = p->p_pid;
2172                         cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2173                         cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2174                         cmcred->cmcred_euid = td->td_ucred->cr_uid;
2175                         cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2176                             CMGROUP_MAX);
2177                         for (i = 0; i < cmcred->cmcred_ngroups; i++)
2178                                 cmcred->cmcred_groups[i] =
2179                                     td->td_ucred->cr_groups[i];
2180                         break;
2181
2182                 case SCM_RIGHTS:
2183                         oldfds = datalen / sizeof (int);
2184                         if (oldfds == 0)
2185                                 break;
2186                         /*
2187                          * Check that all the FDs passed in refer to legal
2188                          * files.  If not, reject the entire operation.
2189                          */
2190                         fdp = data;
2191                         FILEDESC_SLOCK(fdesc);
2192                         for (i = 0; i < oldfds; i++, fdp++) {
2193                                 fp = fget_locked(fdesc, *fdp);
2194                                 if (fp == NULL) {
2195                                         FILEDESC_SUNLOCK(fdesc);
2196                                         error = EBADF;
2197                                         goto out;
2198                                 }
2199                                 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2200                                         FILEDESC_SUNLOCK(fdesc);
2201                                         error = EOPNOTSUPP;
2202                                         goto out;
2203                                 }
2204
2205                         }
2206
2207                         /*
2208                          * Now replace the integer FDs with pointers to the
2209                          * file structure and capability rights.
2210                          */
2211                         newlen = oldfds * sizeof(fdep[0]);
2212                         *controlp = sbcreatecontrol(NULL, newlen,
2213                             SCM_RIGHTS, SOL_SOCKET);
2214                         if (*controlp == NULL) {
2215                                 FILEDESC_SUNLOCK(fdesc);
2216                                 error = E2BIG;
2217                                 goto out;
2218                         }
2219                         fdp = data;
2220                         fdep = (struct filedescent **)
2221                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2222                         fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2223                             M_WAITOK);
2224                         for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2225                                 fde = &fdesc->fd_ofiles[*fdp];
2226                                 fdep[i] = fdev;
2227                                 fdep[i]->fde_file = fde->fde_file;
2228                                 filecaps_copy(&fde->fde_caps,
2229                                     &fdep[i]->fde_caps, true);
2230                                 unp_internalize_fp(fdep[i]->fde_file);
2231                         }
2232                         FILEDESC_SUNLOCK(fdesc);
2233                         break;
2234
2235                 case SCM_TIMESTAMP:
2236                         *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2237                             SCM_TIMESTAMP, SOL_SOCKET);
2238                         if (*controlp == NULL) {
2239                                 error = ENOBUFS;
2240                                 goto out;
2241                         }
2242                         tv = (struct timeval *)
2243                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2244                         microtime(tv);
2245                         break;
2246
2247                 case SCM_BINTIME:
2248                         *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2249                             SCM_BINTIME, SOL_SOCKET);
2250                         if (*controlp == NULL) {
2251                                 error = ENOBUFS;
2252                                 goto out;
2253                         }
2254                         bt = (struct bintime *)
2255                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2256                         bintime(bt);
2257                         break;
2258
2259                 case SCM_REALTIME:
2260                         *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2261                             SCM_REALTIME, SOL_SOCKET);
2262                         if (*controlp == NULL) {
2263                                 error = ENOBUFS;
2264                                 goto out;
2265                         }
2266                         ts = (struct timespec *)
2267                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2268                         nanotime(ts);
2269                         break;
2270
2271                 case SCM_MONOTONIC:
2272                         *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2273                             SCM_MONOTONIC, SOL_SOCKET);
2274                         if (*controlp == NULL) {
2275                                 error = ENOBUFS;
2276                                 goto out;
2277                         }
2278                         ts = (struct timespec *)
2279                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2280                         nanouptime(ts);
2281                         break;
2282
2283                 default:
2284                         error = EINVAL;
2285                         goto out;
2286                 }
2287
2288                 controlp = &(*controlp)->m_next;
2289                 if (CMSG_SPACE(datalen) < clen) {
2290                         clen -= CMSG_SPACE(datalen);
2291                         cm = (struct cmsghdr *)
2292                             ((caddr_t)cm + CMSG_SPACE(datalen));
2293                 } else {
2294                         clen = 0;
2295                         cm = NULL;
2296                 }
2297         }
2298
2299 out:
2300         m_freem(control);
2301         return (error);
2302 }
2303
2304 static struct mbuf *
2305 unp_addsockcred(struct thread *td, struct mbuf *control)
2306 {
2307         struct mbuf *m, *n, *n_prev;
2308         struct sockcred *sc;
2309         const struct cmsghdr *cm;
2310         int ngroups;
2311         int i;
2312
2313         ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2314         m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2315         if (m == NULL)
2316                 return (control);
2317
2318         sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2319         sc->sc_uid = td->td_ucred->cr_ruid;
2320         sc->sc_euid = td->td_ucred->cr_uid;
2321         sc->sc_gid = td->td_ucred->cr_rgid;
2322         sc->sc_egid = td->td_ucred->cr_gid;
2323         sc->sc_ngroups = ngroups;
2324         for (i = 0; i < sc->sc_ngroups; i++)
2325                 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2326
2327         /*
2328          * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2329          * created SCM_CREDS control message (struct sockcred) has another
2330          * format.
2331          */
2332         if (control != NULL)
2333                 for (n = control, n_prev = NULL; n != NULL;) {
2334                         cm = mtod(n, struct cmsghdr *);
2335                         if (cm->cmsg_level == SOL_SOCKET &&
2336                             cm->cmsg_type == SCM_CREDS) {
2337                                 if (n_prev == NULL)
2338                                         control = n->m_next;
2339                                 else
2340                                         n_prev->m_next = n->m_next;
2341                                 n = m_free(n);
2342                         } else {
2343                                 n_prev = n;
2344                                 n = n->m_next;
2345                         }
2346                 }
2347
2348         /* Prepend it to the head. */
2349         m->m_next = control;
2350         return (m);
2351 }
2352
2353 static struct unpcb *
2354 fptounp(struct file *fp)
2355 {
2356         struct socket *so;
2357
2358         if (fp->f_type != DTYPE_SOCKET)
2359                 return (NULL);
2360         if ((so = fp->f_data) == NULL)
2361                 return (NULL);
2362         if (so->so_proto->pr_domain != &localdomain)
2363                 return (NULL);
2364         return sotounpcb(so);
2365 }
2366
2367 static void
2368 unp_discard(struct file *fp)
2369 {
2370         struct unp_defer *dr;
2371
2372         if (unp_externalize_fp(fp)) {
2373                 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2374                 dr->ud_fp = fp;
2375                 UNP_DEFERRED_LOCK();
2376                 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2377                 UNP_DEFERRED_UNLOCK();
2378                 atomic_add_int(&unp_defers_count, 1);
2379                 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2380         } else
2381                 (void) closef(fp, (struct thread *)NULL);
2382 }
2383
2384 static void
2385 unp_process_defers(void *arg __unused, int pending)
2386 {
2387         struct unp_defer *dr;
2388         SLIST_HEAD(, unp_defer) drl;
2389         int count;
2390
2391         SLIST_INIT(&drl);
2392         for (;;) {
2393                 UNP_DEFERRED_LOCK();
2394                 if (SLIST_FIRST(&unp_defers) == NULL) {
2395                         UNP_DEFERRED_UNLOCK();
2396                         break;
2397                 }
2398                 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2399                 UNP_DEFERRED_UNLOCK();
2400                 count = 0;
2401                 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2402                         SLIST_REMOVE_HEAD(&drl, ud_link);
2403                         closef(dr->ud_fp, NULL);
2404                         free(dr, M_TEMP);
2405                         count++;
2406                 }
2407                 atomic_add_int(&unp_defers_count, -count);
2408         }
2409 }
2410
2411 static void
2412 unp_internalize_fp(struct file *fp)
2413 {
2414         struct unpcb *unp;
2415
2416         UNP_LINK_WLOCK();
2417         if ((unp = fptounp(fp)) != NULL) {
2418                 unp->unp_file = fp;
2419                 unp->unp_msgcount++;
2420         }
2421         fhold(fp);
2422         unp_rights++;
2423         UNP_LINK_WUNLOCK();
2424 }
2425
2426 static int
2427 unp_externalize_fp(struct file *fp)
2428 {
2429         struct unpcb *unp;
2430         int ret;
2431
2432         UNP_LINK_WLOCK();
2433         if ((unp = fptounp(fp)) != NULL) {
2434                 unp->unp_msgcount--;
2435                 ret = 1;
2436         } else
2437                 ret = 0;
2438         unp_rights--;
2439         UNP_LINK_WUNLOCK();
2440         return (ret);
2441 }
2442
2443 /*
2444  * unp_defer indicates whether additional work has been defered for a future
2445  * pass through unp_gc().  It is thread local and does not require explicit
2446  * synchronization.
2447  */
2448 static int      unp_marked;
2449 static int      unp_unreachable;
2450
2451 static void
2452 unp_accessable(struct filedescent **fdep, int fdcount)
2453 {
2454         struct unpcb *unp;
2455         struct file *fp;
2456         int i;
2457
2458         for (i = 0; i < fdcount; i++) {
2459                 fp = fdep[i]->fde_file;
2460                 if ((unp = fptounp(fp)) == NULL)
2461                         continue;
2462                 if (unp->unp_gcflag & UNPGC_REF)
2463                         continue;
2464                 unp->unp_gcflag &= ~UNPGC_DEAD;
2465                 unp->unp_gcflag |= UNPGC_REF;
2466                 unp_marked++;
2467         }
2468 }
2469
2470 static void
2471 unp_gc_process(struct unpcb *unp)
2472 {
2473         struct socket *so, *soa;
2474         struct file *fp;
2475
2476         /* Already processed. */
2477         if (unp->unp_gcflag & UNPGC_SCANNED)
2478                 return;
2479         fp = unp->unp_file;
2480
2481         /*
2482          * Check for a socket potentially in a cycle.  It must be in a
2483          * queue as indicated by msgcount, and this must equal the file
2484          * reference count.  Note that when msgcount is 0 the file is NULL.
2485          */
2486         if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2487             unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2488                 unp->unp_gcflag |= UNPGC_DEAD;
2489                 unp_unreachable++;
2490                 return;
2491         }
2492
2493         so = unp->unp_socket;
2494         SOCK_LOCK(so);
2495         if (SOLISTENING(so)) {
2496                 /*
2497                  * Mark all sockets in our accept queue.
2498                  */
2499                 TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2500                         if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2501                                 continue;
2502                         SOCKBUF_LOCK(&soa->so_rcv);
2503                         unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2504                         SOCKBUF_UNLOCK(&soa->so_rcv);
2505                 }
2506         } else {
2507                 /*
2508                  * Mark all sockets we reference with RIGHTS.
2509                  */
2510                 if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2511                         SOCKBUF_LOCK(&so->so_rcv);
2512                         unp_scan(so->so_rcv.sb_mb, unp_accessable);
2513                         SOCKBUF_UNLOCK(&so->so_rcv);
2514                 }
2515         }
2516         SOCK_UNLOCK(so);
2517         unp->unp_gcflag |= UNPGC_SCANNED;
2518 }
2519
2520 static int unp_recycled;
2521 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, 
2522     "Number of unreachable sockets claimed by the garbage collector.");
2523
2524 static int unp_taskcount;
2525 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, 
2526     "Number of times the garbage collector has run.");
2527
2528 static void
2529 unp_gc(__unused void *arg, int pending)
2530 {
2531         struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2532                                     NULL };
2533         struct unp_head **head;
2534         struct file *f, **unref;
2535         struct unpcb *unp;
2536         int i, total;
2537
2538         unp_taskcount++;
2539         UNP_LINK_RLOCK();
2540         /*
2541          * First clear all gc flags from previous runs, apart from
2542          * UNPGC_IGNORE_RIGHTS.
2543          */
2544         for (head = heads; *head != NULL; head++)
2545                 LIST_FOREACH(unp, *head, unp_link)
2546                         unp->unp_gcflag =
2547                             (unp->unp_gcflag & UNPGC_IGNORE_RIGHTS);
2548
2549         /*
2550          * Scan marking all reachable sockets with UNPGC_REF.  Once a socket
2551          * is reachable all of the sockets it references are reachable.
2552          * Stop the scan once we do a complete loop without discovering
2553          * a new reachable socket.
2554          */
2555         do {
2556                 unp_unreachable = 0;
2557                 unp_marked = 0;
2558                 for (head = heads; *head != NULL; head++)
2559                         LIST_FOREACH(unp, *head, unp_link)
2560                                 unp_gc_process(unp);
2561         } while (unp_marked);
2562         UNP_LINK_RUNLOCK();
2563         if (unp_unreachable == 0)
2564                 return;
2565
2566         /*
2567          * Allocate space for a local list of dead unpcbs.
2568          */
2569         unref = malloc(unp_unreachable * sizeof(struct file *),
2570             M_TEMP, M_WAITOK);
2571
2572         /*
2573          * Iterate looking for sockets which have been specifically marked
2574          * as as unreachable and store them locally.
2575          */
2576         UNP_LINK_RLOCK();
2577         for (total = 0, head = heads; *head != NULL; head++)
2578                 LIST_FOREACH(unp, *head, unp_link)
2579                         if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
2580                                 f = unp->unp_file;
2581                                 if (unp->unp_msgcount == 0 || f == NULL ||
2582                                     f->f_count != unp->unp_msgcount)
2583                                         continue;
2584                                 unref[total++] = f;
2585                                 fhold(f);
2586                                 KASSERT(total <= unp_unreachable,
2587                                     ("unp_gc: incorrect unreachable count."));
2588                         }
2589         UNP_LINK_RUNLOCK();
2590
2591         /*
2592          * Now flush all sockets, free'ing rights.  This will free the
2593          * struct files associated with these sockets but leave each socket
2594          * with one remaining ref.
2595          */
2596         for (i = 0; i < total; i++) {
2597                 struct socket *so;
2598
2599                 so = unref[i]->f_data;
2600                 CURVNET_SET(so->so_vnet);
2601                 sorflush(so);
2602                 CURVNET_RESTORE();
2603         }
2604
2605         /*
2606          * And finally release the sockets so they can be reclaimed.
2607          */
2608         for (i = 0; i < total; i++)
2609                 fdrop(unref[i], NULL);
2610         unp_recycled += total;
2611         free(unref, M_TEMP);
2612 }
2613
2614 static void
2615 unp_dispose_mbuf(struct mbuf *m)
2616 {
2617
2618         if (m)
2619                 unp_scan(m, unp_freerights);
2620 }
2621
2622 /*
2623  * Synchronize against unp_gc, which can trip over data as we are freeing it.
2624  */
2625 static void
2626 unp_dispose(struct socket *so)
2627 {
2628         struct unpcb *unp;
2629
2630         unp = sotounpcb(so);
2631         UNP_LINK_WLOCK();
2632         unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2633         UNP_LINK_WUNLOCK();
2634         if (!SOLISTENING(so))
2635                 unp_dispose_mbuf(so->so_rcv.sb_mb);
2636 }
2637
2638 static void
2639 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2640 {
2641         struct mbuf *m;
2642         struct cmsghdr *cm;
2643         void *data;
2644         socklen_t clen, datalen;
2645
2646         while (m0 != NULL) {
2647                 for (m = m0; m; m = m->m_next) {
2648                         if (m->m_type != MT_CONTROL)
2649                                 continue;
2650
2651                         cm = mtod(m, struct cmsghdr *);
2652                         clen = m->m_len;
2653
2654                         while (cm != NULL) {
2655                                 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2656                                         break;
2657
2658                                 data = CMSG_DATA(cm);
2659                                 datalen = (caddr_t)cm + cm->cmsg_len
2660                                     - (caddr_t)data;
2661
2662                                 if (cm->cmsg_level == SOL_SOCKET &&
2663                                     cm->cmsg_type == SCM_RIGHTS) {
2664                                         (*op)(data, datalen /
2665                                             sizeof(struct filedescent *));
2666                                 }
2667
2668                                 if (CMSG_SPACE(datalen) < clen) {
2669                                         clen -= CMSG_SPACE(datalen);
2670                                         cm = (struct cmsghdr *)
2671                                             ((caddr_t)cm + CMSG_SPACE(datalen));
2672                                 } else {
2673                                         clen = 0;
2674                                         cm = NULL;
2675                                 }
2676                         }
2677                 }
2678                 m0 = m0->m_nextpkt;
2679         }
2680 }
2681
2682 /*
2683  * A helper function called by VFS before socket-type vnode reclamation.
2684  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2685  * use count.
2686  */
2687 void
2688 vfs_unp_reclaim(struct vnode *vp)
2689 {
2690         struct unpcb *unp;
2691         int active;
2692         struct mtx *vplock;
2693
2694         ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2695         KASSERT(vp->v_type == VSOCK,
2696             ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2697
2698         active = 0;
2699         vplock = mtx_pool_find(mtxpool_sleep, vp);
2700         mtx_lock(vplock);
2701         VOP_UNP_CONNECT(vp, &unp);
2702         if (unp == NULL)
2703                 goto done;
2704         UNP_PCB_LOCK(unp);
2705         if (unp->unp_vnode == vp) {
2706                 VOP_UNP_DETACH(vp);
2707                 unp->unp_vnode = NULL;
2708                 active = 1;
2709         }
2710         UNP_PCB_UNLOCK(unp);
2711  done:
2712         mtx_unlock(vplock);
2713         if (active)
2714                 vunref(vp);
2715 }
2716
2717 #ifdef DDB
2718 static void
2719 db_print_indent(int indent)
2720 {
2721         int i;
2722
2723         for (i = 0; i < indent; i++)
2724                 db_printf(" ");
2725 }
2726
2727 static void
2728 db_print_unpflags(int unp_flags)
2729 {
2730         int comma;
2731
2732         comma = 0;
2733         if (unp_flags & UNP_HAVEPC) {
2734                 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2735                 comma = 1;
2736         }
2737         if (unp_flags & UNP_WANTCRED) {
2738                 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2739                 comma = 1;
2740         }
2741         if (unp_flags & UNP_CONNWAIT) {
2742                 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2743                 comma = 1;
2744         }
2745         if (unp_flags & UNP_CONNECTING) {
2746                 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2747                 comma = 1;
2748         }
2749         if (unp_flags & UNP_BINDING) {
2750                 db_printf("%sUNP_BINDING", comma ? ", " : "");
2751                 comma = 1;
2752         }
2753 }
2754
2755 static void
2756 db_print_xucred(int indent, struct xucred *xu)
2757 {
2758         int comma, i;
2759
2760         db_print_indent(indent);
2761         db_printf("cr_version: %u   cr_uid: %u   cr_ngroups: %d\n",
2762             xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2763         db_print_indent(indent);
2764         db_printf("cr_groups: ");
2765         comma = 0;
2766         for (i = 0; i < xu->cr_ngroups; i++) {
2767                 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2768                 comma = 1;
2769         }
2770         db_printf("\n");
2771 }
2772
2773 static void
2774 db_print_unprefs(int indent, struct unp_head *uh)
2775 {
2776         struct unpcb *unp;
2777         int counter;
2778
2779         counter = 0;
2780         LIST_FOREACH(unp, uh, unp_reflink) {
2781                 if (counter % 4 == 0)
2782                         db_print_indent(indent);
2783                 db_printf("%p  ", unp);
2784                 if (counter % 4 == 3)
2785                         db_printf("\n");
2786                 counter++;
2787         }
2788         if (counter != 0 && counter % 4 != 0)
2789                 db_printf("\n");
2790 }
2791
2792 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2793 {
2794         struct unpcb *unp;
2795
2796         if (!have_addr) {
2797                 db_printf("usage: show unpcb <addr>\n");
2798                 return;
2799         }
2800         unp = (struct unpcb *)addr;
2801
2802         db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
2803             unp->unp_vnode);
2804
2805         db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2806             unp->unp_conn);
2807
2808         db_printf("unp_refs:\n");
2809         db_print_unprefs(2, &unp->unp_refs);
2810
2811         /* XXXRW: Would be nice to print the full address, if any. */
2812         db_printf("unp_addr: %p\n", unp->unp_addr);
2813
2814         db_printf("unp_gencnt: %llu\n",
2815             (unsigned long long)unp->unp_gencnt);
2816
2817         db_printf("unp_flags: %x (", unp->unp_flags);
2818         db_print_unpflags(unp->unp_flags);
2819         db_printf(")\n");
2820
2821         db_printf("unp_peercred:\n");
2822         db_print_xucred(2, &unp->unp_peercred);
2823
2824         db_printf("unp_refcount: %u\n", unp->unp_refcount);
2825 }
2826 #endif