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