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