]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_usrreq.c
Add vnode_pager_clean_{a,}sync(9)
[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  * Copyright (c) 2022 Gleb Smirnoff <glebius@FreeBSD.org>
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * UNIX Domain (Local) Sockets
37  *
38  * This is an implementation of UNIX (local) domain sockets.  Each socket has
39  * an associated struct unpcb (UNIX protocol control block).  Stream sockets
40  * may be connected to 0 or 1 other socket.  Datagram sockets may be
41  * connected to 0, 1, or many other sockets.  Sockets may be created and
42  * connected in pairs (socketpair(2)), or bound/connected to using the file
43  * system name space.  For most purposes, only the receive socket buffer is
44  * used, as sending on one socket delivers directly to the receive socket
45  * buffer of a second socket.
46  *
47  * The implementation is substantially complicated by the fact that
48  * "ancillary data", such as file descriptors or credentials, may be passed
49  * across UNIX domain sockets.  The potential for passing UNIX domain sockets
50  * over other UNIX domain sockets requires the implementation of a simple
51  * garbage collector to find and tear down cycles of disconnected sockets.
52  *
53  * TODO:
54  *      RDM
55  *      rethink name space problems
56  *      need a proper out-of-band
57  */
58
59 #include <sys/cdefs.h>
60 #include "opt_ddb.h"
61
62 #include <sys/param.h>
63 #include <sys/capsicum.h>
64 #include <sys/domain.h>
65 #include <sys/eventhandler.h>
66 #include <sys/fcntl.h>
67 #include <sys/file.h>
68 #include <sys/filedesc.h>
69 #include <sys/kernel.h>
70 #include <sys/lock.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/mount.h>
74 #include <sys/mutex.h>
75 #include <sys/namei.h>
76 #include <sys/proc.h>
77 #include <sys/protosw.h>
78 #include <sys/queue.h>
79 #include <sys/resourcevar.h>
80 #include <sys/rwlock.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/signalvar.h>
84 #include <sys/stat.h>
85 #include <sys/sx.h>
86 #include <sys/sysctl.h>
87 #include <sys/systm.h>
88 #include <sys/taskqueue.h>
89 #include <sys/un.h>
90 #include <sys/unpcb.h>
91 #include <sys/vnode.h>
92
93 #include <net/vnet.h>
94
95 #ifdef DDB
96 #include <ddb/ddb.h>
97 #endif
98
99 #include <security/mac/mac_framework.h>
100
101 #include <vm/uma.h>
102
103 MALLOC_DECLARE(M_FILECAPS);
104
105 static struct domain localdomain;
106
107 static uma_zone_t       unp_zone;
108 static unp_gen_t        unp_gencnt;     /* (l) */
109 static u_int            unp_count;      /* (l) Count of local sockets. */
110 static ino_t            unp_ino;        /* Prototype for fake inode numbers. */
111 static int              unp_rights;     /* (g) File descriptors in flight. */
112 static struct unp_head  unp_shead;      /* (l) List of stream sockets. */
113 static struct unp_head  unp_dhead;      /* (l) List of datagram sockets. */
114 static struct unp_head  unp_sphead;     /* (l) List of seqpacket sockets. */
115
116 struct unp_defer {
117         SLIST_ENTRY(unp_defer) ud_link;
118         struct file *ud_fp;
119 };
120 static SLIST_HEAD(, unp_defer) unp_defers;
121 static int unp_defers_count;
122
123 static const struct sockaddr    sun_noname = {
124         .sa_len = sizeof(sun_noname),
125         .sa_family = AF_LOCAL,
126 };
127
128 /*
129  * Garbage collection of cyclic file descriptor/socket references occurs
130  * asynchronously in a taskqueue context in order to avoid recursion and
131  * reentrance in the UNIX domain socket, file descriptor, and socket layer
132  * code.  See unp_gc() for a full description.
133  */
134 static struct timeout_task unp_gc_task;
135
136 /*
137  * The close of unix domain sockets attached as SCM_RIGHTS is
138  * postponed to the taskqueue, to avoid arbitrary recursion depth.
139  * The attached sockets might have another sockets attached.
140  */
141 static struct task      unp_defer_task;
142
143 /*
144  * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
145  * stream sockets, although the total for sender and receiver is actually
146  * only PIPSIZ.
147  *
148  * Datagram sockets really use the sendspace as the maximum datagram size,
149  * and don't really want to reserve the sendspace.  Their recvspace should be
150  * large enough for at least one max-size datagram plus address.
151  */
152 #ifndef PIPSIZ
153 #define PIPSIZ  8192
154 #endif
155 static u_long   unpst_sendspace = PIPSIZ;
156 static u_long   unpst_recvspace = PIPSIZ;
157 static u_long   unpdg_maxdgram = 8*1024;        /* support 8KB syslog msgs */
158 static u_long   unpdg_recvspace = 16*1024;
159 static u_long   unpsp_sendspace = PIPSIZ;       /* really max datagram size */
160 static u_long   unpsp_recvspace = PIPSIZ;
161
162 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
163     "Local domain");
164 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
165     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
166     "SOCK_STREAM");
167 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
168     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
169     "SOCK_DGRAM");
170 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
171     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
172     "SOCK_SEQPACKET");
173
174 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
175            &unpst_sendspace, 0, "Default stream send space.");
176 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
177            &unpst_recvspace, 0, "Default stream receive space.");
178 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
179            &unpdg_maxdgram, 0, "Maximum datagram size.");
180 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
181            &unpdg_recvspace, 0, "Default datagram receive space.");
182 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
183            &unpsp_sendspace, 0, "Default seqpacket send space.");
184 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
185            &unpsp_recvspace, 0, "Default seqpacket receive space.");
186 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
187     "File descriptors in flight.");
188 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
189     &unp_defers_count, 0,
190     "File descriptors deferred to taskqueue for close.");
191
192 /*
193  * Locking and synchronization:
194  *
195  * Several types of locks exist in the local domain socket implementation:
196  * - a global linkage lock
197  * - a global connection list lock
198  * - the mtxpool lock
199  * - per-unpcb mutexes
200  *
201  * The linkage lock protects the global socket lists, the generation number
202  * counter and garbage collector state.
203  *
204  * The connection list lock protects the list of referring sockets in a datagram
205  * socket PCB.  This lock is also overloaded to protect a global list of
206  * sockets whose buffers contain socket references in the form of SCM_RIGHTS
207  * messages.  To avoid recursion, such references are released by a dedicated
208  * thread.
209  *
210  * The mtxpool lock protects the vnode from being modified while referenced.
211  * Lock ordering rules require that it be acquired before any PCB locks.
212  *
213  * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
214  * unpcb.  This includes the unp_conn field, which either links two connected
215  * PCBs together (for connected socket types) or points at the destination
216  * socket (for connectionless socket types).  The operations of creating or
217  * destroying a connection therefore involve locking multiple PCBs.  To avoid
218  * lock order reversals, in some cases this involves dropping a PCB lock and
219  * using a reference counter to maintain liveness.
220  *
221  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
222  * allocated in pr_attach() and freed in pr_detach().  The validity of that
223  * pointer is an invariant, so no lock is required to dereference the so_pcb
224  * pointer if a valid socket reference is held by the caller.  In practice,
225  * this is always true during operations performed on a socket.  Each unpcb
226  * has a back-pointer to its socket, unp_socket, which will be stable under
227  * the same circumstances.
228  *
229  * This pointer may only be safely dereferenced as long as a valid reference
230  * to the unpcb is held.  Typically, this reference will be from the socket,
231  * or from another unpcb when the referring unpcb's lock is held (in order
232  * that the reference not be invalidated during use).  For example, to follow
233  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
234  * that detach is not run clearing unp_socket.
235  *
236  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
237  * protocols, bind() is a non-atomic operation, and connect() requires
238  * potential sleeping in the protocol, due to potentially waiting on local or
239  * distributed file systems.  We try to separate "lookup" operations, which
240  * may sleep, and the IPC operations themselves, which typically can occur
241  * with relative atomicity as locks can be held over the entire operation.
242  *
243  * Another tricky issue is simultaneous multi-threaded or multi-process
244  * access to a single UNIX domain socket.  These are handled by the flags
245  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
246  * binding, both of which involve dropping UNIX domain socket locks in order
247  * to perform namei() and other file system operations.
248  */
249 static struct rwlock    unp_link_rwlock;
250 static struct mtx       unp_defers_lock;
251
252 #define UNP_LINK_LOCK_INIT()            rw_init(&unp_link_rwlock,       \
253                                             "unp_link_rwlock")
254
255 #define UNP_LINK_LOCK_ASSERT()          rw_assert(&unp_link_rwlock,     \
256                                             RA_LOCKED)
257 #define UNP_LINK_UNLOCK_ASSERT()        rw_assert(&unp_link_rwlock,     \
258                                             RA_UNLOCKED)
259
260 #define UNP_LINK_RLOCK()                rw_rlock(&unp_link_rwlock)
261 #define UNP_LINK_RUNLOCK()              rw_runlock(&unp_link_rwlock)
262 #define UNP_LINK_WLOCK()                rw_wlock(&unp_link_rwlock)
263 #define UNP_LINK_WUNLOCK()              rw_wunlock(&unp_link_rwlock)
264 #define UNP_LINK_WLOCK_ASSERT()         rw_assert(&unp_link_rwlock,     \
265                                             RA_WLOCKED)
266 #define UNP_LINK_WOWNED()               rw_wowned(&unp_link_rwlock)
267
268 #define UNP_DEFERRED_LOCK_INIT()        mtx_init(&unp_defers_lock, \
269                                             "unp_defer", NULL, MTX_DEF)
270 #define UNP_DEFERRED_LOCK()             mtx_lock(&unp_defers_lock)
271 #define UNP_DEFERRED_UNLOCK()           mtx_unlock(&unp_defers_lock)
272
273 #define UNP_REF_LIST_LOCK()             UNP_DEFERRED_LOCK();
274 #define UNP_REF_LIST_UNLOCK()           UNP_DEFERRED_UNLOCK();
275
276 #define UNP_PCB_LOCK_INIT(unp)          mtx_init(&(unp)->unp_mtx,       \
277                                             "unp", "unp",       \
278                                             MTX_DUPOK|MTX_DEF)
279 #define UNP_PCB_LOCK_DESTROY(unp)       mtx_destroy(&(unp)->unp_mtx)
280 #define UNP_PCB_LOCKPTR(unp)            (&(unp)->unp_mtx)
281 #define UNP_PCB_LOCK(unp)               mtx_lock(&(unp)->unp_mtx)
282 #define UNP_PCB_TRYLOCK(unp)            mtx_trylock(&(unp)->unp_mtx)
283 #define UNP_PCB_UNLOCK(unp)             mtx_unlock(&(unp)->unp_mtx)
284 #define UNP_PCB_OWNED(unp)              mtx_owned(&(unp)->unp_mtx)
285 #define UNP_PCB_LOCK_ASSERT(unp)        mtx_assert(&(unp)->unp_mtx, MA_OWNED)
286 #define UNP_PCB_UNLOCK_ASSERT(unp)      mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
287
288 static int      uipc_connect2(struct socket *, struct socket *);
289 static int      uipc_ctloutput(struct socket *, struct sockopt *);
290 static int      unp_connect(struct socket *, struct sockaddr *,
291                     struct thread *);
292 static int      unp_connectat(int, struct socket *, struct sockaddr *,
293                     struct thread *, bool);
294 typedef enum { PRU_CONNECT, PRU_CONNECT2 } conn2_how;
295 static void     unp_connect2(struct socket *so, struct socket *so2, conn2_how);
296 static void     unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
297 static void     unp_dispose(struct socket *so);
298 static void     unp_shutdown(struct unpcb *);
299 static void     unp_drop(struct unpcb *);
300 static void     unp_gc(__unused void *, int);
301 static void     unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
302 static void     unp_discard(struct file *);
303 static void     unp_freerights(struct filedescent **, int);
304 static int      unp_internalize(struct mbuf **, struct thread *,
305                     struct mbuf **, u_int *, u_int *);
306 static void     unp_internalize_fp(struct file *);
307 static int      unp_externalize(struct mbuf *, struct mbuf **, int);
308 static int      unp_externalize_fp(struct file *);
309 static struct mbuf      *unp_addsockcred(struct thread *, struct mbuf *,
310                     int, struct mbuf **, u_int *, u_int *);
311 static void     unp_process_defers(void * __unused, int);
312
313 static void
314 unp_pcb_hold(struct unpcb *unp)
315 {
316         u_int old __unused;
317
318         old = refcount_acquire(&unp->unp_refcount);
319         KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
320 }
321
322 static __result_use_check bool
323 unp_pcb_rele(struct unpcb *unp)
324 {
325         bool ret;
326
327         UNP_PCB_LOCK_ASSERT(unp);
328
329         if ((ret = refcount_release(&unp->unp_refcount))) {
330                 UNP_PCB_UNLOCK(unp);
331                 UNP_PCB_LOCK_DESTROY(unp);
332                 uma_zfree(unp_zone, unp);
333         }
334         return (ret);
335 }
336
337 static void
338 unp_pcb_rele_notlast(struct unpcb *unp)
339 {
340         bool ret __unused;
341
342         ret = refcount_release(&unp->unp_refcount);
343         KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
344 }
345
346 static void
347 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
348 {
349         UNP_PCB_UNLOCK_ASSERT(unp);
350         UNP_PCB_UNLOCK_ASSERT(unp2);
351
352         if (unp == unp2) {
353                 UNP_PCB_LOCK(unp);
354         } else 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 void
364 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
365 {
366         UNP_PCB_UNLOCK(unp);
367         if (unp != unp2)
368                 UNP_PCB_UNLOCK(unp2);
369 }
370
371 /*
372  * Try to lock the connected peer of an already locked socket.  In some cases
373  * this requires that we unlock the current socket.  The pairbusy counter is
374  * used to block concurrent connection attempts while the lock is dropped.  The
375  * caller must be careful to revalidate PCB state.
376  */
377 static struct unpcb *
378 unp_pcb_lock_peer(struct unpcb *unp)
379 {
380         struct unpcb *unp2;
381
382         UNP_PCB_LOCK_ASSERT(unp);
383         unp2 = unp->unp_conn;
384         if (unp2 == NULL)
385                 return (NULL);
386         if (__predict_false(unp == unp2))
387                 return (unp);
388
389         UNP_PCB_UNLOCK_ASSERT(unp2);
390
391         if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
392                 return (unp2);
393         if ((uintptr_t)unp2 > (uintptr_t)unp) {
394                 UNP_PCB_LOCK(unp2);
395                 return (unp2);
396         }
397         unp->unp_pairbusy++;
398         unp_pcb_hold(unp2);
399         UNP_PCB_UNLOCK(unp);
400
401         UNP_PCB_LOCK(unp2);
402         UNP_PCB_LOCK(unp);
403         KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
404             ("%s: socket %p was reconnected", __func__, unp));
405         if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
406                 unp->unp_flags &= ~UNP_WAITING;
407                 wakeup(unp);
408         }
409         if (unp_pcb_rele(unp2)) {
410                 /* unp2 is unlocked. */
411                 return (NULL);
412         }
413         if (unp->unp_conn == NULL) {
414                 UNP_PCB_UNLOCK(unp2);
415                 return (NULL);
416         }
417         return (unp2);
418 }
419
420 static void
421 uipc_abort(struct socket *so)
422 {
423         struct unpcb *unp, *unp2;
424
425         unp = sotounpcb(so);
426         KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
427         UNP_PCB_UNLOCK_ASSERT(unp);
428
429         UNP_PCB_LOCK(unp);
430         unp2 = unp->unp_conn;
431         if (unp2 != NULL) {
432                 unp_pcb_hold(unp2);
433                 UNP_PCB_UNLOCK(unp);
434                 unp_drop(unp2);
435         } else
436                 UNP_PCB_UNLOCK(unp);
437 }
438
439 static int
440 uipc_attach(struct socket *so, int proto, struct thread *td)
441 {
442         u_long sendspace, recvspace;
443         struct unpcb *unp;
444         int error;
445         bool locked;
446
447         KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
448         if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
449                 switch (so->so_type) {
450                 case SOCK_STREAM:
451                         sendspace = unpst_sendspace;
452                         recvspace = unpst_recvspace;
453                         break;
454
455                 case SOCK_DGRAM:
456                         STAILQ_INIT(&so->so_rcv.uxdg_mb);
457                         STAILQ_INIT(&so->so_snd.uxdg_mb);
458                         TAILQ_INIT(&so->so_rcv.uxdg_conns);
459                         /*
460                          * Since send buffer is either bypassed or is a part
461                          * of one-to-many receive buffer, we assign both space
462                          * limits to unpdg_recvspace.
463                          */
464                         sendspace = recvspace = unpdg_recvspace;
465                         break;
466
467                 case SOCK_SEQPACKET:
468                         sendspace = unpsp_sendspace;
469                         recvspace = unpsp_recvspace;
470                         break;
471
472                 default:
473                         panic("uipc_attach");
474                 }
475                 error = soreserve(so, sendspace, recvspace);
476                 if (error)
477                         return (error);
478         }
479         unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
480         if (unp == NULL)
481                 return (ENOBUFS);
482         LIST_INIT(&unp->unp_refs);
483         UNP_PCB_LOCK_INIT(unp);
484         unp->unp_socket = so;
485         so->so_pcb = unp;
486         refcount_init(&unp->unp_refcount, 1);
487
488         if ((locked = UNP_LINK_WOWNED()) == false)
489                 UNP_LINK_WLOCK();
490
491         unp->unp_gencnt = ++unp_gencnt;
492         unp->unp_ino = ++unp_ino;
493         unp_count++;
494         switch (so->so_type) {
495         case SOCK_STREAM:
496                 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
497                 break;
498
499         case SOCK_DGRAM:
500                 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
501                 break;
502
503         case SOCK_SEQPACKET:
504                 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
505                 break;
506
507         default:
508                 panic("uipc_attach");
509         }
510
511         if (locked == false)
512                 UNP_LINK_WUNLOCK();
513
514         return (0);
515 }
516
517 static int
518 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
519 {
520         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
521         struct vattr vattr;
522         int error, namelen;
523         struct nameidata nd;
524         struct unpcb *unp;
525         struct vnode *vp;
526         struct mount *mp;
527         cap_rights_t rights;
528         char *buf;
529
530         if (nam->sa_family != AF_UNIX)
531                 return (EAFNOSUPPORT);
532
533         unp = sotounpcb(so);
534         KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
535
536         if (soun->sun_len > sizeof(struct sockaddr_un))
537                 return (EINVAL);
538         namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
539         if (namelen <= 0)
540                 return (EINVAL);
541
542         /*
543          * We don't allow simultaneous bind() calls on a single UNIX domain
544          * socket, so flag in-progress operations, and return an error if an
545          * operation is already in progress.
546          *
547          * Historically, we have not allowed a socket to be rebound, so this
548          * also returns an error.  Not allowing re-binding simplifies the
549          * implementation and avoids a great many possible failure modes.
550          */
551         UNP_PCB_LOCK(unp);
552         if (unp->unp_vnode != NULL) {
553                 UNP_PCB_UNLOCK(unp);
554                 return (EINVAL);
555         }
556         if (unp->unp_flags & UNP_BINDING) {
557                 UNP_PCB_UNLOCK(unp);
558                 return (EALREADY);
559         }
560         unp->unp_flags |= UNP_BINDING;
561         UNP_PCB_UNLOCK(unp);
562
563         buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
564         bcopy(soun->sun_path, buf, namelen);
565         buf[namelen] = 0;
566
567 restart:
568         NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | NOCACHE,
569             UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
570 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
571         error = namei(&nd);
572         if (error)
573                 goto error;
574         vp = nd.ni_vp;
575         if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
576                 NDFREE_PNBUF(&nd);
577                 if (nd.ni_dvp == vp)
578                         vrele(nd.ni_dvp);
579                 else
580                         vput(nd.ni_dvp);
581                 if (vp != NULL) {
582                         vrele(vp);
583                         error = EADDRINUSE;
584                         goto error;
585                 }
586                 error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH);
587                 if (error)
588                         goto error;
589                 goto restart;
590         }
591         VATTR_NULL(&vattr);
592         vattr.va_type = VSOCK;
593         vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
594 #ifdef MAC
595         error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
596             &vattr);
597 #endif
598         if (error == 0)
599                 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
600         NDFREE_PNBUF(&nd);
601         if (error) {
602                 VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
603                 vn_finished_write(mp);
604                 if (error == ERELOOKUP)
605                         goto restart;
606                 goto error;
607         }
608         vp = nd.ni_vp;
609         ASSERT_VOP_ELOCKED(vp, "uipc_bind");
610         soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
611
612         UNP_PCB_LOCK(unp);
613         VOP_UNP_BIND(vp, unp);
614         unp->unp_vnode = vp;
615         unp->unp_addr = soun;
616         unp->unp_flags &= ~UNP_BINDING;
617         UNP_PCB_UNLOCK(unp);
618         vref(vp);
619         VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
620         vn_finished_write(mp);
621         free(buf, M_TEMP);
622         return (0);
623
624 error:
625         UNP_PCB_LOCK(unp);
626         unp->unp_flags &= ~UNP_BINDING;
627         UNP_PCB_UNLOCK(unp);
628         free(buf, M_TEMP);
629         return (error);
630 }
631
632 static int
633 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
634 {
635
636         return (uipc_bindat(AT_FDCWD, so, nam, td));
637 }
638
639 static int
640 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
641 {
642         int error;
643
644         KASSERT(td == curthread, ("uipc_connect: td != curthread"));
645         error = unp_connect(so, nam, td);
646         return (error);
647 }
648
649 static int
650 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
651     struct thread *td)
652 {
653         int error;
654
655         KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
656         error = unp_connectat(fd, so, nam, td, false);
657         return (error);
658 }
659
660 static void
661 uipc_close(struct socket *so)
662 {
663         struct unpcb *unp, *unp2;
664         struct vnode *vp = NULL;
665         struct mtx *vplock;
666
667         unp = sotounpcb(so);
668         KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
669
670         vplock = NULL;
671         if ((vp = unp->unp_vnode) != NULL) {
672                 vplock = mtx_pool_find(mtxpool_sleep, vp);
673                 mtx_lock(vplock);
674         }
675         UNP_PCB_LOCK(unp);
676         if (vp && unp->unp_vnode == NULL) {
677                 mtx_unlock(vplock);
678                 vp = NULL;
679         }
680         if (vp != NULL) {
681                 VOP_UNP_DETACH(vp);
682                 unp->unp_vnode = NULL;
683         }
684         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
685                 unp_disconnect(unp, unp2);
686         else
687                 UNP_PCB_UNLOCK(unp);
688         if (vp) {
689                 mtx_unlock(vplock);
690                 vrele(vp);
691         }
692 }
693
694 static int
695 uipc_connect2(struct socket *so1, struct socket *so2)
696 {
697         struct unpcb *unp, *unp2;
698
699         if (so1->so_type != so2->so_type)
700                 return (EPROTOTYPE);
701
702         unp = so1->so_pcb;
703         KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
704         unp2 = so2->so_pcb;
705         KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
706         unp_pcb_lock_pair(unp, unp2);
707         unp_connect2(so1, so2, PRU_CONNECT2);
708         unp_pcb_unlock_pair(unp, unp2);
709
710         return (0);
711 }
712
713 static void
714 uipc_detach(struct socket *so)
715 {
716         struct unpcb *unp, *unp2;
717         struct mtx *vplock;
718         struct vnode *vp;
719         int local_unp_rights;
720
721         unp = sotounpcb(so);
722         KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
723
724         vp = NULL;
725         vplock = NULL;
726
727         UNP_LINK_WLOCK();
728         LIST_REMOVE(unp, unp_link);
729         if (unp->unp_gcflag & UNPGC_DEAD)
730                 LIST_REMOVE(unp, unp_dead);
731         unp->unp_gencnt = ++unp_gencnt;
732         --unp_count;
733         UNP_LINK_WUNLOCK();
734
735         UNP_PCB_UNLOCK_ASSERT(unp);
736  restart:
737         if ((vp = unp->unp_vnode) != NULL) {
738                 vplock = mtx_pool_find(mtxpool_sleep, vp);
739                 mtx_lock(vplock);
740         }
741         UNP_PCB_LOCK(unp);
742         if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
743                 if (vplock)
744                         mtx_unlock(vplock);
745                 UNP_PCB_UNLOCK(unp);
746                 goto restart;
747         }
748         if ((vp = unp->unp_vnode) != NULL) {
749                 VOP_UNP_DETACH(vp);
750                 unp->unp_vnode = NULL;
751         }
752         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
753                 unp_disconnect(unp, unp2);
754         else
755                 UNP_PCB_UNLOCK(unp);
756
757         UNP_REF_LIST_LOCK();
758         while (!LIST_EMPTY(&unp->unp_refs)) {
759                 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
760
761                 unp_pcb_hold(ref);
762                 UNP_REF_LIST_UNLOCK();
763
764                 MPASS(ref != unp);
765                 UNP_PCB_UNLOCK_ASSERT(ref);
766                 unp_drop(ref);
767                 UNP_REF_LIST_LOCK();
768         }
769         UNP_REF_LIST_UNLOCK();
770
771         UNP_PCB_LOCK(unp);
772         local_unp_rights = unp_rights;
773         unp->unp_socket->so_pcb = NULL;
774         unp->unp_socket = NULL;
775         free(unp->unp_addr, M_SONAME);
776         unp->unp_addr = NULL;
777         if (!unp_pcb_rele(unp))
778                 UNP_PCB_UNLOCK(unp);
779         if (vp) {
780                 mtx_unlock(vplock);
781                 vrele(vp);
782         }
783         if (local_unp_rights)
784                 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
785
786         switch (so->so_type) {
787         case SOCK_DGRAM:
788                 /*
789                  * Everything should have been unlinked/freed by unp_dispose()
790                  * and/or unp_disconnect().
791                  */
792                 MPASS(so->so_rcv.uxdg_peeked == NULL);
793                 MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb));
794                 MPASS(TAILQ_EMPTY(&so->so_rcv.uxdg_conns));
795                 MPASS(STAILQ_EMPTY(&so->so_snd.uxdg_mb));
796         }
797 }
798
799 static int
800 uipc_disconnect(struct socket *so)
801 {
802         struct unpcb *unp, *unp2;
803
804         unp = sotounpcb(so);
805         KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
806
807         UNP_PCB_LOCK(unp);
808         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
809                 unp_disconnect(unp, unp2);
810         else
811                 UNP_PCB_UNLOCK(unp);
812         return (0);
813 }
814
815 static int
816 uipc_listen(struct socket *so, int backlog, struct thread *td)
817 {
818         struct unpcb *unp;
819         int error;
820
821         MPASS(so->so_type != SOCK_DGRAM);
822
823         /*
824          * Synchronize with concurrent connection attempts.
825          */
826         error = 0;
827         unp = sotounpcb(so);
828         UNP_PCB_LOCK(unp);
829         if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
830                 error = EINVAL;
831         else if (unp->unp_vnode == NULL)
832                 error = EDESTADDRREQ;
833         if (error != 0) {
834                 UNP_PCB_UNLOCK(unp);
835                 return (error);
836         }
837
838         SOCK_LOCK(so);
839         error = solisten_proto_check(so);
840         if (error == 0) {
841                 cru2xt(td, &unp->unp_peercred);
842                 solisten_proto(so, backlog);
843         }
844         SOCK_UNLOCK(so);
845         UNP_PCB_UNLOCK(unp);
846         return (error);
847 }
848
849 static int
850 uipc_peeraddr(struct socket *so, struct sockaddr *ret)
851 {
852         struct unpcb *unp, *unp2;
853         const struct sockaddr *sa;
854
855         unp = sotounpcb(so);
856         KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
857
858         UNP_PCB_LOCK(unp);
859         unp2 = unp_pcb_lock_peer(unp);
860         if (unp2 != NULL) {
861                 if (unp2->unp_addr != NULL)
862                         sa = (struct sockaddr *)unp2->unp_addr;
863                 else
864                         sa = &sun_noname;
865                 bcopy(sa, ret, sa->sa_len);
866                 unp_pcb_unlock_pair(unp, unp2);
867         } else {
868                 UNP_PCB_UNLOCK(unp);
869                 sa = &sun_noname;
870                 bcopy(sa, ret, sa->sa_len);
871         }
872         return (0);
873 }
874
875 static int
876 uipc_rcvd(struct socket *so, int flags)
877 {
878         struct unpcb *unp, *unp2;
879         struct socket *so2;
880         u_int mbcnt, sbcc;
881
882         unp = sotounpcb(so);
883         KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
884         KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
885             ("%s: socktype %d", __func__, so->so_type));
886
887         /*
888          * Adjust backpressure on sender and wakeup any waiting to write.
889          *
890          * The unp lock is acquired to maintain the validity of the unp_conn
891          * pointer; no lock on unp2 is required as unp2->unp_socket will be
892          * static as long as we don't permit unp2 to disconnect from unp,
893          * which is prevented by the lock on unp.  We cache values from
894          * so_rcv to avoid holding the so_rcv lock over the entire
895          * transaction on the remote so_snd.
896          */
897         SOCKBUF_LOCK(&so->so_rcv);
898         mbcnt = so->so_rcv.sb_mbcnt;
899         sbcc = sbavail(&so->so_rcv);
900         SOCKBUF_UNLOCK(&so->so_rcv);
901         /*
902          * There is a benign race condition at this point.  If we're planning to
903          * clear SB_STOP, but uipc_send is called on the connected socket at
904          * this instant, it might add data to the sockbuf and set SB_STOP.  Then
905          * we would erroneously clear SB_STOP below, even though the sockbuf is
906          * full.  The race is benign because the only ill effect is to allow the
907          * sockbuf to exceed its size limit, and the size limits are not
908          * strictly guaranteed anyway.
909          */
910         UNP_PCB_LOCK(unp);
911         unp2 = unp->unp_conn;
912         if (unp2 == NULL) {
913                 UNP_PCB_UNLOCK(unp);
914                 return (0);
915         }
916         so2 = unp2->unp_socket;
917         SOCKBUF_LOCK(&so2->so_snd);
918         if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
919                 so2->so_snd.sb_flags &= ~SB_STOP;
920         sowwakeup_locked(so2);
921         UNP_PCB_UNLOCK(unp);
922         return (0);
923 }
924
925 static int
926 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
927     struct mbuf *control, struct thread *td)
928 {
929         struct unpcb *unp, *unp2;
930         struct socket *so2;
931         u_int mbcnt, sbcc;
932         int error;
933
934         unp = sotounpcb(so);
935         KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
936         KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
937             ("%s: socktype %d", __func__, so->so_type));
938
939         error = 0;
940         if (flags & PRUS_OOB) {
941                 error = EOPNOTSUPP;
942                 goto release;
943         }
944         if (control != NULL &&
945             (error = unp_internalize(&control, td, NULL, NULL, NULL)))
946                 goto release;
947
948         unp2 = NULL;
949         if ((so->so_state & SS_ISCONNECTED) == 0) {
950                 if (nam != NULL) {
951                         if ((error = unp_connect(so, nam, td)) != 0)
952                                 goto out;
953                 } else {
954                         error = ENOTCONN;
955                         goto out;
956                 }
957         }
958
959         UNP_PCB_LOCK(unp);
960         if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
961                 UNP_PCB_UNLOCK(unp);
962                 error = ENOTCONN;
963                 goto out;
964         } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
965                 unp_pcb_unlock_pair(unp, unp2);
966                 error = EPIPE;
967                 goto out;
968         }
969         UNP_PCB_UNLOCK(unp);
970         if ((so2 = unp2->unp_socket) == NULL) {
971                 UNP_PCB_UNLOCK(unp2);
972                 error = ENOTCONN;
973                 goto out;
974         }
975         SOCKBUF_LOCK(&so2->so_rcv);
976         if (unp2->unp_flags & UNP_WANTCRED_MASK) {
977                 /*
978                  * Credentials are passed only once on SOCK_STREAM and
979                  * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
980                  * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
981                  */
982                 control = unp_addsockcred(td, control, unp2->unp_flags, NULL,
983                     NULL, NULL);
984                 unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
985         }
986
987         /*
988          * Send to paired receive port and wake up readers.  Don't
989          * check for space available in the receive buffer if we're
990          * attaching ancillary data; Unix domain sockets only check
991          * for space in the sending sockbuf, and that check is
992          * performed one level up the stack.  At that level we cannot
993          * precisely account for the amount of buffer space used
994          * (e.g., because control messages are not yet internalized).
995          */
996         switch (so->so_type) {
997         case SOCK_STREAM:
998                 if (control != NULL) {
999                         sbappendcontrol_locked(&so2->so_rcv, m,
1000                             control, flags);
1001                         control = NULL;
1002                 } else
1003                         sbappend_locked(&so2->so_rcv, m, flags);
1004                 break;
1005
1006         case SOCK_SEQPACKET:
1007                 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1008                     &sun_noname, m, control))
1009                         control = NULL;
1010                 break;
1011         }
1012
1013         mbcnt = so2->so_rcv.sb_mbcnt;
1014         sbcc = sbavail(&so2->so_rcv);
1015         if (sbcc)
1016                 sorwakeup_locked(so2);
1017         else
1018                 SOCKBUF_UNLOCK(&so2->so_rcv);
1019
1020         /*
1021          * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1022          * it would be possible for uipc_rcvd to be called at this
1023          * point, drain the receiving sockbuf, clear SB_STOP, and then
1024          * we would set SB_STOP below.  That could lead to an empty
1025          * sockbuf having SB_STOP set
1026          */
1027         SOCKBUF_LOCK(&so->so_snd);
1028         if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1029                 so->so_snd.sb_flags |= SB_STOP;
1030         SOCKBUF_UNLOCK(&so->so_snd);
1031         UNP_PCB_UNLOCK(unp2);
1032         m = NULL;
1033 out:
1034         /*
1035          * PRUS_EOF is equivalent to pr_send followed by pr_shutdown.
1036          */
1037         if (flags & PRUS_EOF) {
1038                 UNP_PCB_LOCK(unp);
1039                 socantsendmore(so);
1040                 unp_shutdown(unp);
1041                 UNP_PCB_UNLOCK(unp);
1042         }
1043         if (control != NULL && error != 0)
1044                 unp_scan(control, unp_freerights);
1045
1046 release:
1047         if (control != NULL)
1048                 m_freem(control);
1049         /*
1050          * In case of PRUS_NOTREADY, uipc_ready() is responsible
1051          * for freeing memory.
1052          */   
1053         if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1054                 m_freem(m);
1055         return (error);
1056 }
1057
1058 /* PF_UNIX/SOCK_DGRAM version of sbspace() */
1059 static inline bool
1060 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt)
1061 {
1062         u_int bleft, mleft;
1063
1064         /*
1065          * Negative space may happen if send(2) is followed by
1066          * setsockopt(SO_SNDBUF/SO_RCVBUF) that shrinks maximum.
1067          */
1068         if (__predict_false(sb->sb_hiwat < sb->uxdg_cc ||
1069             sb->sb_mbmax < sb->uxdg_mbcnt))
1070                 return (false);
1071
1072         if (__predict_false(sb->sb_state & SBS_CANTRCVMORE))
1073                 return (false);
1074
1075         bleft = sb->sb_hiwat - sb->uxdg_cc;
1076         mleft = sb->sb_mbmax - sb->uxdg_mbcnt;
1077
1078         return (bleft >= cc && mleft >= mbcnt);
1079 }
1080
1081 /*
1082  * PF_UNIX/SOCK_DGRAM send
1083  *
1084  * Allocate a record consisting of 3 mbufs in the sequence of
1085  * from -> control -> data and append it to the socket buffer.
1086  *
1087  * The first mbuf carries sender's name and is a pkthdr that stores
1088  * overall length of datagram, its memory consumption and control length.
1089  */
1090 #define ctllen  PH_loc.thirtytwo[1]
1091 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <=
1092     offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen");
1093 static int
1094 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1095     struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
1096 {
1097         struct unpcb *unp, *unp2;
1098         const struct sockaddr *from;
1099         struct socket *so2;
1100         struct sockbuf *sb;
1101         struct mbuf *f, *clast;
1102         u_int cc, ctl, mbcnt;
1103         u_int dcc __diagused, dctl __diagused, dmbcnt __diagused;
1104         int error;
1105
1106         MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
1107
1108         error = 0;
1109         f = NULL;
1110         ctl = 0;
1111
1112         if (__predict_false(flags & MSG_OOB)) {
1113                 error = EOPNOTSUPP;
1114                 goto out;
1115         }
1116         if (m == NULL) {
1117                 if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
1118                         error = EMSGSIZE;
1119                         goto out;
1120                 }
1121                 m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
1122                 if (__predict_false(m == NULL)) {
1123                         error = EFAULT;
1124                         goto out;
1125                 }
1126                 f = m_gethdr(M_WAITOK, MT_SONAME);
1127                 cc = m->m_pkthdr.len;
1128                 mbcnt = MSIZE + m->m_pkthdr.memlen;
1129                 if (c != NULL &&
1130                     (error = unp_internalize(&c, td, &clast, &ctl, &mbcnt)))
1131                         goto out;
1132         } else {
1133                 /* pr_sosend() with mbuf usually is a kernel thread. */
1134
1135                 M_ASSERTPKTHDR(m);
1136                 if (__predict_false(c != NULL))
1137                         panic("%s: control from a kernel thread", __func__);
1138
1139                 if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
1140                         error = EMSGSIZE;
1141                         goto out;
1142                 }
1143                 if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) {
1144                         error = ENOBUFS;
1145                         goto out;
1146                 }
1147                 /* Condition the foreign mbuf to our standards. */
1148                 m_clrprotoflags(m);
1149                 m_tag_delete_chain(m, NULL);
1150                 m->m_pkthdr.rcvif = NULL;
1151                 m->m_pkthdr.flowid = 0;
1152                 m->m_pkthdr.csum_flags = 0;
1153                 m->m_pkthdr.fibnum = 0;
1154                 m->m_pkthdr.rsstype = 0;
1155
1156                 cc = m->m_pkthdr.len;
1157                 mbcnt = MSIZE;
1158                 for (struct mbuf *mb = m; mb != NULL; mb = mb->m_next) {
1159                         mbcnt += MSIZE;
1160                         if (mb->m_flags & M_EXT)
1161                                 mbcnt += mb->m_ext.ext_size;
1162                 }
1163         }
1164
1165         unp = sotounpcb(so);
1166         MPASS(unp);
1167
1168         /*
1169          * XXXGL: would be cool to fully remove so_snd out of the equation
1170          * and avoid this lock, which is not only extraneous, but also being
1171          * released, thus still leaving possibility for a race.  We can easily
1172          * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
1173          * is more difficult to invent something to handle so_error.
1174          */
1175         error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1176         if (error)
1177                 goto out2;
1178         SOCK_SENDBUF_LOCK(so);
1179         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1180                 SOCK_SENDBUF_UNLOCK(so);
1181                 error = EPIPE;
1182                 goto out3;
1183         }
1184         if (so->so_error != 0) {
1185                 error = so->so_error;
1186                 so->so_error = 0;
1187                 SOCK_SENDBUF_UNLOCK(so);
1188                 goto out3;
1189         }
1190         if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
1191                 SOCK_SENDBUF_UNLOCK(so);
1192                 error = EDESTADDRREQ;
1193                 goto out3;
1194         }
1195         SOCK_SENDBUF_UNLOCK(so);
1196
1197         if (addr != NULL) {
1198                 if ((error = unp_connectat(AT_FDCWD, so, addr, td, true)))
1199                         goto out3;
1200                 UNP_PCB_LOCK_ASSERT(unp);
1201                 unp2 = unp->unp_conn;
1202                 UNP_PCB_LOCK_ASSERT(unp2);
1203         } else {
1204                 UNP_PCB_LOCK(unp);
1205                 unp2 = unp_pcb_lock_peer(unp);
1206                 if (unp2 == NULL) {
1207                         UNP_PCB_UNLOCK(unp);
1208                         error = ENOTCONN;
1209                         goto out3;
1210                 }
1211         }
1212
1213         if (unp2->unp_flags & UNP_WANTCRED_MASK)
1214                 c = unp_addsockcred(td, c, unp2->unp_flags, &clast, &ctl,
1215                     &mbcnt);
1216         if (unp->unp_addr != NULL)
1217                 from = (struct sockaddr *)unp->unp_addr;
1218         else
1219                 from = &sun_noname;
1220         f->m_len = from->sa_len;
1221         MPASS(from->sa_len <= MLEN);
1222         bcopy(from, mtod(f, void *), from->sa_len);
1223         ctl += f->m_len;
1224
1225         /*
1226          * Concatenate mbufs: from -> control -> data.
1227          * Save overall cc and mbcnt in "from" mbuf.
1228          */
1229         if (c != NULL) {
1230 #ifdef INVARIANTS
1231                 struct mbuf *mc;
1232
1233                 for (mc = c; mc->m_next != NULL; mc = mc->m_next);
1234                 MPASS(mc == clast);
1235 #endif
1236                 f->m_next = c;
1237                 clast->m_next = m;
1238                 c = NULL;
1239         } else
1240                 f->m_next = m;
1241         m = NULL;
1242 #ifdef INVARIANTS
1243         dcc = dctl = dmbcnt = 0;
1244         for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) {
1245                 if (mb->m_type == MT_DATA)
1246                         dcc += mb->m_len;
1247                 else
1248                         dctl += mb->m_len;
1249                 dmbcnt += MSIZE;
1250                 if (mb->m_flags & M_EXT)
1251                         dmbcnt += mb->m_ext.ext_size;
1252         }
1253         MPASS(dcc == cc);
1254         MPASS(dctl == ctl);
1255         MPASS(dmbcnt == mbcnt);
1256 #endif
1257         f->m_pkthdr.len = cc + ctl;
1258         f->m_pkthdr.memlen = mbcnt;
1259         f->m_pkthdr.ctllen = ctl;
1260
1261         /*
1262          * Destination socket buffer selection.
1263          *
1264          * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the
1265          * destination address is supplied, create a temporary connection for
1266          * the run time of the function (see call to unp_connectat() above and
1267          * to unp_disconnect() below).  We distinguish them by condition of
1268          * (addr != NULL).  We intentionally avoid adding 'bool connected' for
1269          * that condition, since, again, through the run time of this code we
1270          * are always connected.  For such "unconnected" sends, the destination
1271          * buffer would be the receive buffer of destination socket so2.
1272          *
1273          * For connected sends, data lands on the send buffer of the sender's
1274          * socket "so".  Then, if we just added the very first datagram
1275          * on this send buffer, we need to add the send buffer on to the
1276          * receiving socket's buffer list.  We put ourselves on top of the
1277          * list.  Such logic gives infrequent senders priority over frequent
1278          * senders.
1279          *
1280          * Note on byte count management. As long as event methods kevent(2),
1281          * select(2) are not protocol specific (yet), we need to maintain
1282          * meaningful values on the receive buffer.  So, the receive buffer
1283          * would accumulate counters from all connected buffers potentially
1284          * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax.
1285          */
1286         so2 = unp2->unp_socket;
1287         sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv;
1288         SOCK_RECVBUF_LOCK(so2);
1289         if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) {
1290                 if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb))
1291                         TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd,
1292                             uxdg_clist);
1293                 STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
1294                 sb->uxdg_cc += cc + ctl;
1295                 sb->uxdg_ctl += ctl;
1296                 sb->uxdg_mbcnt += mbcnt;
1297                 so2->so_rcv.sb_acc += cc + ctl;
1298                 so2->so_rcv.sb_ccc += cc + ctl;
1299                 so2->so_rcv.sb_ctl += ctl;
1300                 so2->so_rcv.sb_mbcnt += mbcnt;
1301                 sorwakeup_locked(so2);
1302                 f = NULL;
1303         } else {
1304                 soroverflow_locked(so2);
1305                 error = ENOBUFS;
1306                 if (f->m_next->m_type == MT_CONTROL) {
1307                         c = f->m_next;
1308                         f->m_next = NULL;
1309                 }
1310         }
1311
1312         if (addr != NULL)
1313                 unp_disconnect(unp, unp2);
1314         else
1315                 unp_pcb_unlock_pair(unp, unp2);
1316
1317         td->td_ru.ru_msgsnd++;
1318
1319 out3:
1320         SOCK_IO_SEND_UNLOCK(so);
1321 out2:
1322         if (c)
1323                 unp_scan(c, unp_freerights);
1324 out:
1325         if (f)
1326                 m_freem(f);
1327         if (c)
1328                 m_freem(c);
1329         if (m)
1330                 m_freem(m);
1331
1332         return (error);
1333 }
1334
1335 /*
1336  * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK.
1337  * The mbuf has already been unlinked from the uxdg_mb of socket buffer
1338  * and needs to be linked onto uxdg_peeked of receive socket buffer.
1339  */
1340 static int
1341 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa,
1342     struct uio *uio, struct mbuf **controlp, int *flagsp)
1343 {
1344         ssize_t len = 0;
1345         int error;
1346
1347         so->so_rcv.uxdg_peeked = m;
1348         so->so_rcv.uxdg_cc += m->m_pkthdr.len;
1349         so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen;
1350         so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen;
1351         SOCK_RECVBUF_UNLOCK(so);
1352
1353         KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1354         if (psa != NULL)
1355                 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1356
1357         m = m->m_next;
1358         KASSERT(m, ("%s: no data or control after soname", __func__));
1359
1360         /*
1361          * With MSG_PEEK the control isn't executed, just copied.
1362          */
1363         while (m != NULL && m->m_type == MT_CONTROL) {
1364                 if (controlp != NULL) {
1365                         *controlp = m_copym(m, 0, m->m_len, M_WAITOK);
1366                         controlp = &(*controlp)->m_next;
1367                 }
1368                 m = m->m_next;
1369         }
1370         KASSERT(m == NULL || m->m_type == MT_DATA,
1371             ("%s: not MT_DATA mbuf %p", __func__, m));
1372         while (m != NULL && uio->uio_resid > 0) {
1373                 len = uio->uio_resid;
1374                 if (len > m->m_len)
1375                         len = m->m_len;
1376                 error = uiomove(mtod(m, char *), (int)len, uio);
1377                 if (error) {
1378                         SOCK_IO_RECV_UNLOCK(so);
1379                         return (error);
1380                 }
1381                 if (len == m->m_len)
1382                         m = m->m_next;
1383         }
1384         SOCK_IO_RECV_UNLOCK(so);
1385
1386         if (flagsp != NULL) {
1387                 if (m != NULL) {
1388                         if (*flagsp & MSG_TRUNC) {
1389                                 /* Report real length of the packet */
1390                                 uio->uio_resid -= m_length(m, NULL) - len;
1391                         }
1392                         *flagsp |= MSG_TRUNC;
1393                 } else
1394                         *flagsp &= ~MSG_TRUNC;
1395         }
1396
1397         return (0);
1398 }
1399
1400 /*
1401  * PF_UNIX/SOCK_DGRAM receive
1402  */
1403 static int
1404 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1405     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1406 {
1407         struct sockbuf *sb = NULL;
1408         struct mbuf *m;
1409         int flags, error;
1410         ssize_t len = 0;
1411         bool nonblock;
1412
1413         MPASS(mp0 == NULL);
1414
1415         if (psa != NULL)
1416                 *psa = NULL;
1417         if (controlp != NULL)
1418                 *controlp = NULL;
1419
1420         flags = flagsp != NULL ? *flagsp : 0;
1421         nonblock = (so->so_state & SS_NBIO) ||
1422             (flags & (MSG_DONTWAIT | MSG_NBIO));
1423
1424         error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
1425         if (__predict_false(error))
1426                 return (error);
1427
1428         /*
1429          * Loop blocking while waiting for a datagram.  Prioritize connected
1430          * peers over unconnected sends.  Set sb to selected socket buffer
1431          * containing an mbuf on exit from the wait loop.  A datagram that
1432          * had already been peeked at has top priority.
1433          */
1434         SOCK_RECVBUF_LOCK(so);
1435         while ((m = so->so_rcv.uxdg_peeked) == NULL &&
1436             (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL &&
1437             (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
1438                 if (so->so_error) {
1439                         error = so->so_error;
1440                         so->so_error = 0;
1441                         SOCK_RECVBUF_UNLOCK(so);
1442                         SOCK_IO_RECV_UNLOCK(so);
1443                         return (error);
1444                 }
1445                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1446                     uio->uio_resid == 0) {
1447                         SOCK_RECVBUF_UNLOCK(so);
1448                         SOCK_IO_RECV_UNLOCK(so);
1449                         return (0);
1450                 }
1451                 if (nonblock) {
1452                         SOCK_RECVBUF_UNLOCK(so);
1453                         SOCK_IO_RECV_UNLOCK(so);
1454                         return (EWOULDBLOCK);
1455                 }
1456                 error = sbwait(so, SO_RCV);
1457                 if (error) {
1458                         SOCK_RECVBUF_UNLOCK(so);
1459                         SOCK_IO_RECV_UNLOCK(so);
1460                         return (error);
1461                 }
1462         }
1463
1464         if (sb == NULL)
1465                 sb = &so->so_rcv;
1466         else if (m == NULL)
1467                 m = STAILQ_FIRST(&sb->uxdg_mb);
1468         else
1469                 MPASS(m == so->so_rcv.uxdg_peeked);
1470
1471         MPASS(sb->uxdg_cc > 0);
1472         M_ASSERTPKTHDR(m);
1473         KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1474
1475         if (uio->uio_td)
1476                 uio->uio_td->td_ru.ru_msgrcv++;
1477
1478         if (__predict_true(m != so->so_rcv.uxdg_peeked)) {
1479                 STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt);
1480                 if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv)
1481                         TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
1482         } else
1483                 so->so_rcv.uxdg_peeked = NULL;
1484
1485         sb->uxdg_cc -= m->m_pkthdr.len;
1486         sb->uxdg_ctl -= m->m_pkthdr.ctllen;
1487         sb->uxdg_mbcnt -= m->m_pkthdr.memlen;
1488
1489         if (__predict_false(flags & MSG_PEEK))
1490                 return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp));
1491
1492         so->so_rcv.sb_acc -= m->m_pkthdr.len;
1493         so->so_rcv.sb_ccc -= m->m_pkthdr.len;
1494         so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen;
1495         so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen;
1496         SOCK_RECVBUF_UNLOCK(so);
1497
1498         if (psa != NULL)
1499                 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1500         m = m_free(m);
1501         KASSERT(m, ("%s: no data or control after soname", __func__));
1502
1503         /*
1504          * Packet to copyout() is now in 'm' and it is disconnected from the
1505          * queue.
1506          *
1507          * Process one or more MT_CONTROL mbufs present before any data mbufs
1508          * in the first mbuf chain on the socket buffer.  We call into the
1509          * unp_externalize() to perform externalization (or freeing if
1510          * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
1511          * without MT_DATA mbufs.
1512          */
1513         while (m != NULL && m->m_type == MT_CONTROL) {
1514                 struct mbuf *cm;
1515
1516                 /* XXXGL: unp_externalize() is also dom_externalize() KBI and
1517                  * it frees whole chain, so we must disconnect the mbuf.
1518                  */
1519                 cm = m; m = m->m_next; cm->m_next = NULL;
1520                 error = unp_externalize(cm, controlp, flags);
1521                 if (error != 0) {
1522                         SOCK_IO_RECV_UNLOCK(so);
1523                         unp_scan(m, unp_freerights);
1524                         m_freem(m);
1525                         return (error);
1526                 }
1527                 if (controlp != NULL) {
1528                         while (*controlp != NULL)
1529                                 controlp = &(*controlp)->m_next;
1530                 }
1531         }
1532         KASSERT(m == NULL || m->m_type == MT_DATA,
1533             ("%s: not MT_DATA mbuf %p", __func__, m));
1534         while (m != NULL && uio->uio_resid > 0) {
1535                 len = uio->uio_resid;
1536                 if (len > m->m_len)
1537                         len = m->m_len;
1538                 error = uiomove(mtod(m, char *), (int)len, uio);
1539                 if (error) {
1540                         SOCK_IO_RECV_UNLOCK(so);
1541                         m_freem(m);
1542                         return (error);
1543                 }
1544                 if (len == m->m_len)
1545                         m = m_free(m);
1546                 else {
1547                         m->m_data += len;
1548                         m->m_len -= len;
1549                 }
1550         }
1551         SOCK_IO_RECV_UNLOCK(so);
1552
1553         if (m != NULL) {
1554                 if (flagsp != NULL) {
1555                         if (flags & MSG_TRUNC) {
1556                                 /* Report real length of the packet */
1557                                 uio->uio_resid -= m_length(m, NULL);
1558                         }
1559                         *flagsp |= MSG_TRUNC;
1560                 }
1561                 m_freem(m);
1562         } else if (flagsp != NULL)
1563                 *flagsp &= ~MSG_TRUNC;
1564
1565         return (0);
1566 }
1567
1568 static bool
1569 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1570 {
1571         struct mbuf *mb, *n;
1572         struct sockbuf *sb;
1573
1574         SOCK_LOCK(so);
1575         if (SOLISTENING(so)) {
1576                 SOCK_UNLOCK(so);
1577                 return (false);
1578         }
1579         mb = NULL;
1580         sb = &so->so_rcv;
1581         SOCKBUF_LOCK(sb);
1582         if (sb->sb_fnrdy != NULL) {
1583                 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1584                         if (mb == m) {
1585                                 *errorp = sbready(sb, m, count);
1586                                 break;
1587                         }
1588                         mb = mb->m_next;
1589                         if (mb == NULL) {
1590                                 mb = n;
1591                                 if (mb != NULL)
1592                                         n = mb->m_nextpkt;
1593                         }
1594                 }
1595         }
1596         SOCKBUF_UNLOCK(sb);
1597         SOCK_UNLOCK(so);
1598         return (mb != NULL);
1599 }
1600
1601 static int
1602 uipc_ready(struct socket *so, struct mbuf *m, int count)
1603 {
1604         struct unpcb *unp, *unp2;
1605         struct socket *so2;
1606         int error, i;
1607
1608         unp = sotounpcb(so);
1609
1610         KASSERT(so->so_type == SOCK_STREAM,
1611             ("%s: unexpected socket type for %p", __func__, so));
1612
1613         UNP_PCB_LOCK(unp);
1614         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1615                 UNP_PCB_UNLOCK(unp);
1616                 so2 = unp2->unp_socket;
1617                 SOCKBUF_LOCK(&so2->so_rcv);
1618                 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1619                         sorwakeup_locked(so2);
1620                 else
1621                         SOCKBUF_UNLOCK(&so2->so_rcv);
1622                 UNP_PCB_UNLOCK(unp2);
1623                 return (error);
1624         }
1625         UNP_PCB_UNLOCK(unp);
1626
1627         /*
1628          * The receiving socket has been disconnected, but may still be valid.
1629          * In this case, the now-ready mbufs are still present in its socket
1630          * buffer, so perform an exhaustive search before giving up and freeing
1631          * the mbufs.
1632          */
1633         UNP_LINK_RLOCK();
1634         LIST_FOREACH(unp, &unp_shead, unp_link) {
1635                 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1636                         break;
1637         }
1638         UNP_LINK_RUNLOCK();
1639
1640         if (unp == NULL) {
1641                 for (i = 0; i < count; i++)
1642                         m = m_free(m);
1643                 error = ECONNRESET;
1644         }
1645         return (error);
1646 }
1647
1648 static int
1649 uipc_sense(struct socket *so, struct stat *sb)
1650 {
1651         struct unpcb *unp;
1652
1653         unp = sotounpcb(so);
1654         KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1655
1656         sb->st_blksize = so->so_snd.sb_hiwat;
1657         sb->st_dev = NODEV;
1658         sb->st_ino = unp->unp_ino;
1659         return (0);
1660 }
1661
1662 static int
1663 uipc_shutdown(struct socket *so)
1664 {
1665         struct unpcb *unp;
1666
1667         unp = sotounpcb(so);
1668         KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1669
1670         UNP_PCB_LOCK(unp);
1671         socantsendmore(so);
1672         unp_shutdown(unp);
1673         UNP_PCB_UNLOCK(unp);
1674         return (0);
1675 }
1676
1677 static int
1678 uipc_sockaddr(struct socket *so, struct sockaddr *ret)
1679 {
1680         struct unpcb *unp;
1681         const struct sockaddr *sa;
1682
1683         unp = sotounpcb(so);
1684         KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1685
1686         UNP_PCB_LOCK(unp);
1687         if (unp->unp_addr != NULL)
1688                 sa = (struct sockaddr *) unp->unp_addr;
1689         else
1690                 sa = &sun_noname;
1691         bcopy(sa, ret, sa->sa_len);
1692         UNP_PCB_UNLOCK(unp);
1693         return (0);
1694 }
1695
1696 static int
1697 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1698 {
1699         struct unpcb *unp;
1700         struct xucred xu;
1701         int error, optval;
1702
1703         if (sopt->sopt_level != SOL_LOCAL)
1704                 return (EINVAL);
1705
1706         unp = sotounpcb(so);
1707         KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1708         error = 0;
1709         switch (sopt->sopt_dir) {
1710         case SOPT_GET:
1711                 switch (sopt->sopt_name) {
1712                 case LOCAL_PEERCRED:
1713                         UNP_PCB_LOCK(unp);
1714                         if (unp->unp_flags & UNP_HAVEPC)
1715                                 xu = unp->unp_peercred;
1716                         else {
1717                                 if (so->so_type == SOCK_STREAM)
1718                                         error = ENOTCONN;
1719                                 else
1720                                         error = EINVAL;
1721                         }
1722                         UNP_PCB_UNLOCK(unp);
1723                         if (error == 0)
1724                                 error = sooptcopyout(sopt, &xu, sizeof(xu));
1725                         break;
1726
1727                 case LOCAL_CREDS:
1728                         /* Unlocked read. */
1729                         optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
1730                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1731                         break;
1732
1733                 case LOCAL_CREDS_PERSISTENT:
1734                         /* Unlocked read. */
1735                         optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
1736                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1737                         break;
1738
1739                 case LOCAL_CONNWAIT:
1740                         /* Unlocked read. */
1741                         optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1742                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1743                         break;
1744
1745                 default:
1746                         error = EOPNOTSUPP;
1747                         break;
1748                 }
1749                 break;
1750
1751         case SOPT_SET:
1752                 switch (sopt->sopt_name) {
1753                 case LOCAL_CREDS:
1754                 case LOCAL_CREDS_PERSISTENT:
1755                 case LOCAL_CONNWAIT:
1756                         error = sooptcopyin(sopt, &optval, sizeof(optval),
1757                                             sizeof(optval));
1758                         if (error)
1759                                 break;
1760
1761 #define OPTSET(bit, exclusive) do {                                     \
1762         UNP_PCB_LOCK(unp);                                              \
1763         if (optval) {                                                   \
1764                 if ((unp->unp_flags & (exclusive)) != 0) {              \
1765                         UNP_PCB_UNLOCK(unp);                            \
1766                         error = EINVAL;                                 \
1767                         break;                                          \
1768                 }                                                       \
1769                 unp->unp_flags |= (bit);                                \
1770         } else                                                          \
1771                 unp->unp_flags &= ~(bit);                               \
1772         UNP_PCB_UNLOCK(unp);                                            \
1773 } while (0)
1774
1775                         switch (sopt->sopt_name) {
1776                         case LOCAL_CREDS:
1777                                 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
1778                                 break;
1779
1780                         case LOCAL_CREDS_PERSISTENT:
1781                                 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
1782                                 break;
1783
1784                         case LOCAL_CONNWAIT:
1785                                 OPTSET(UNP_CONNWAIT, 0);
1786                                 break;
1787
1788                         default:
1789                                 break;
1790                         }
1791                         break;
1792 #undef  OPTSET
1793                 default:
1794                         error = ENOPROTOOPT;
1795                         break;
1796                 }
1797                 break;
1798
1799         default:
1800                 error = EOPNOTSUPP;
1801                 break;
1802         }
1803         return (error);
1804 }
1805
1806 static int
1807 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1808 {
1809
1810         return (unp_connectat(AT_FDCWD, so, nam, td, false));
1811 }
1812
1813 static int
1814 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1815     struct thread *td, bool return_locked)
1816 {
1817         struct mtx *vplock;
1818         struct sockaddr_un *soun;
1819         struct vnode *vp;
1820         struct socket *so2;
1821         struct unpcb *unp, *unp2, *unp3;
1822         struct nameidata nd;
1823         char buf[SOCK_MAXADDRLEN];
1824         struct sockaddr *sa;
1825         cap_rights_t rights;
1826         int error, len;
1827         bool connreq;
1828
1829         if (nam->sa_family != AF_UNIX)
1830                 return (EAFNOSUPPORT);
1831         if (nam->sa_len > sizeof(struct sockaddr_un))
1832                 return (EINVAL);
1833         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1834         if (len <= 0)
1835                 return (EINVAL);
1836         soun = (struct sockaddr_un *)nam;
1837         bcopy(soun->sun_path, buf, len);
1838         buf[len] = 0;
1839
1840         error = 0;
1841         unp = sotounpcb(so);
1842         UNP_PCB_LOCK(unp);
1843         for (;;) {
1844                 /*
1845                  * Wait for connection state to stabilize.  If a connection
1846                  * already exists, give up.  For datagram sockets, which permit
1847                  * multiple consecutive connect(2) calls, upper layers are
1848                  * responsible for disconnecting in advance of a subsequent
1849                  * connect(2), but this is not synchronized with PCB connection
1850                  * state.
1851                  *
1852                  * Also make sure that no threads are currently attempting to
1853                  * lock the peer socket, to ensure that unp_conn cannot
1854                  * transition between two valid sockets while locks are dropped.
1855                  */
1856                 if (SOLISTENING(so))
1857                         error = EOPNOTSUPP;
1858                 else if (unp->unp_conn != NULL)
1859                         error = EISCONN;
1860                 else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1861                         error = EALREADY;
1862                 }
1863                 if (error != 0) {
1864                         UNP_PCB_UNLOCK(unp);
1865                         return (error);
1866                 }
1867                 if (unp->unp_pairbusy > 0) {
1868                         unp->unp_flags |= UNP_WAITING;
1869                         mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1870                         continue;
1871                 }
1872                 break;
1873         }
1874         unp->unp_flags |= UNP_CONNECTING;
1875         UNP_PCB_UNLOCK(unp);
1876
1877         connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1878         if (connreq)
1879                 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1880         else
1881                 sa = NULL;
1882         NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1883             UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
1884         error = namei(&nd);
1885         if (error)
1886                 vp = NULL;
1887         else
1888                 vp = nd.ni_vp;
1889         ASSERT_VOP_LOCKED(vp, "unp_connect");
1890         if (error)
1891                 goto bad;
1892         NDFREE_PNBUF(&nd);
1893
1894         if (vp->v_type != VSOCK) {
1895                 error = ENOTSOCK;
1896                 goto bad;
1897         }
1898 #ifdef MAC
1899         error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1900         if (error)
1901                 goto bad;
1902 #endif
1903         error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1904         if (error)
1905                 goto bad;
1906
1907         unp = sotounpcb(so);
1908         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1909
1910         vplock = mtx_pool_find(mtxpool_sleep, vp);
1911         mtx_lock(vplock);
1912         VOP_UNP_CONNECT(vp, &unp2);
1913         if (unp2 == NULL) {
1914                 error = ECONNREFUSED;
1915                 goto bad2;
1916         }
1917         so2 = unp2->unp_socket;
1918         if (so->so_type != so2->so_type) {
1919                 error = EPROTOTYPE;
1920                 goto bad2;
1921         }
1922         if (connreq) {
1923                 if (SOLISTENING(so2)) {
1924                         CURVNET_SET(so2->so_vnet);
1925                         so2 = sonewconn(so2, 0);
1926                         CURVNET_RESTORE();
1927                 } else
1928                         so2 = NULL;
1929                 if (so2 == NULL) {
1930                         error = ECONNREFUSED;
1931                         goto bad2;
1932                 }
1933                 unp3 = sotounpcb(so2);
1934                 unp_pcb_lock_pair(unp2, unp3);
1935                 if (unp2->unp_addr != NULL) {
1936                         bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1937                         unp3->unp_addr = (struct sockaddr_un *) sa;
1938                         sa = NULL;
1939                 }
1940
1941                 unp_copy_peercred(td, unp3, unp, unp2);
1942
1943                 UNP_PCB_UNLOCK(unp2);
1944                 unp2 = unp3;
1945
1946                 /*
1947                  * It is safe to block on the PCB lock here since unp2 is
1948                  * nascent and cannot be connected to any other sockets.
1949                  */
1950                 UNP_PCB_LOCK(unp);
1951 #ifdef MAC
1952                 mac_socketpeer_set_from_socket(so, so2);
1953                 mac_socketpeer_set_from_socket(so2, so);
1954 #endif
1955         } else {
1956                 unp_pcb_lock_pair(unp, unp2);
1957         }
1958         KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1959             sotounpcb(so2) == unp2,
1960             ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1961         unp_connect2(so, so2, PRU_CONNECT);
1962         KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1963             ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1964         unp->unp_flags &= ~UNP_CONNECTING;
1965         if (!return_locked)
1966                 unp_pcb_unlock_pair(unp, unp2);
1967 bad2:
1968         mtx_unlock(vplock);
1969 bad:
1970         if (vp != NULL) {
1971                 /*
1972                  * If we are returning locked (called via uipc_sosend_dgram()),
1973                  * we need to be sure that vput() won't sleep.  This is
1974                  * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock.
1975                  * SOCK_STREAM/SEQPACKET can't request return_locked (yet).
1976                  */
1977                 MPASS(!(return_locked && connreq));
1978                 vput(vp);
1979         }
1980         free(sa, M_SONAME);
1981         if (__predict_false(error)) {
1982                 UNP_PCB_LOCK(unp);
1983                 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1984                     ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1985                 unp->unp_flags &= ~UNP_CONNECTING;
1986                 UNP_PCB_UNLOCK(unp);
1987         }
1988         return (error);
1989 }
1990
1991 /*
1992  * Set socket peer credentials at connection time.
1993  *
1994  * The client's PCB credentials are copied from its process structure.  The
1995  * server's PCB credentials are copied from the socket on which it called
1996  * listen(2).  uipc_listen cached that process's credentials at the time.
1997  */
1998 void
1999 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
2000     struct unpcb *server_unp, struct unpcb *listen_unp)
2001 {
2002         cru2xt(td, &client_unp->unp_peercred);
2003         client_unp->unp_flags |= UNP_HAVEPC;
2004
2005         memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
2006             sizeof(server_unp->unp_peercred));
2007         server_unp->unp_flags |= UNP_HAVEPC;
2008         client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
2009 }
2010
2011 static void
2012 unp_connect2(struct socket *so, struct socket *so2, conn2_how req)
2013 {
2014         struct unpcb *unp;
2015         struct unpcb *unp2;
2016
2017         MPASS(so2->so_type == so->so_type);
2018         unp = sotounpcb(so);
2019         KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
2020         unp2 = sotounpcb(so2);
2021         KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
2022
2023         UNP_PCB_LOCK_ASSERT(unp);
2024         UNP_PCB_LOCK_ASSERT(unp2);
2025         KASSERT(unp->unp_conn == NULL,
2026             ("%s: socket %p is already connected", __func__, unp));
2027
2028         unp->unp_conn = unp2;
2029         unp_pcb_hold(unp2);
2030         unp_pcb_hold(unp);
2031         switch (so->so_type) {
2032         case SOCK_DGRAM:
2033                 UNP_REF_LIST_LOCK();
2034                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2035                 UNP_REF_LIST_UNLOCK();
2036                 soisconnected(so);
2037                 break;
2038
2039         case SOCK_STREAM:
2040         case SOCK_SEQPACKET:
2041                 KASSERT(unp2->unp_conn == NULL,
2042                     ("%s: socket %p is already connected", __func__, unp2));
2043                 unp2->unp_conn = unp;
2044                 if (req == PRU_CONNECT &&
2045                     ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
2046                         soisconnecting(so);
2047                 else
2048                         soisconnected(so);
2049                 soisconnected(so2);
2050                 break;
2051
2052         default:
2053                 panic("unp_connect2");
2054         }
2055 }
2056
2057 static void
2058 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
2059 {
2060         struct socket *so, *so2;
2061         struct mbuf *m = NULL;
2062 #ifdef INVARIANTS
2063         struct unpcb *unptmp;
2064 #endif
2065
2066         UNP_PCB_LOCK_ASSERT(unp);
2067         UNP_PCB_LOCK_ASSERT(unp2);
2068         KASSERT(unp->unp_conn == unp2,
2069             ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
2070
2071         unp->unp_conn = NULL;
2072         so = unp->unp_socket;
2073         so2 = unp2->unp_socket;
2074         switch (unp->unp_socket->so_type) {
2075         case SOCK_DGRAM:
2076                 /*
2077                  * Remove our send socket buffer from the peer's receive buffer.
2078                  * Move the data to the receive buffer only if it is empty.
2079                  * This is a protection against a scenario where a peer
2080                  * connects, floods and disconnects, effectively blocking
2081                  * sendto() from unconnected sockets.
2082                  */
2083                 SOCK_RECVBUF_LOCK(so2);
2084                 if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) {
2085                         TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd,
2086                             uxdg_clist);
2087                         if (__predict_true((so2->so_rcv.sb_state &
2088                             SBS_CANTRCVMORE) == 0) &&
2089                             STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) {
2090                                 STAILQ_CONCAT(&so2->so_rcv.uxdg_mb,
2091                                     &so->so_snd.uxdg_mb);
2092                                 so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc;
2093                                 so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl;
2094                                 so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt;
2095                         } else {
2096                                 m = STAILQ_FIRST(&so->so_snd.uxdg_mb);
2097                                 STAILQ_INIT(&so->so_snd.uxdg_mb);
2098                                 so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc;
2099                                 so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc;
2100                                 so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl;
2101                                 so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt;
2102                         }
2103                         /* Note: so may reconnect. */
2104                         so->so_snd.uxdg_cc = 0;
2105                         so->so_snd.uxdg_ctl = 0;
2106                         so->so_snd.uxdg_mbcnt = 0;
2107                 }
2108                 SOCK_RECVBUF_UNLOCK(so2);
2109                 UNP_REF_LIST_LOCK();
2110 #ifdef INVARIANTS
2111                 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
2112                         if (unptmp == unp)
2113                                 break;
2114                 }
2115                 KASSERT(unptmp != NULL,
2116                     ("%s: %p not found in reflist of %p", __func__, unp, unp2));
2117 #endif
2118                 LIST_REMOVE(unp, unp_reflink);
2119                 UNP_REF_LIST_UNLOCK();
2120                 if (so) {
2121                         SOCK_LOCK(so);
2122                         so->so_state &= ~SS_ISCONNECTED;
2123                         SOCK_UNLOCK(so);
2124                 }
2125                 break;
2126
2127         case SOCK_STREAM:
2128         case SOCK_SEQPACKET:
2129                 if (so)
2130                         soisdisconnected(so);
2131                 MPASS(unp2->unp_conn == unp);
2132                 unp2->unp_conn = NULL;
2133                 if (so2)
2134                         soisdisconnected(so2);
2135                 break;
2136         }
2137
2138         if (unp == unp2) {
2139                 unp_pcb_rele_notlast(unp);
2140                 if (!unp_pcb_rele(unp))
2141                         UNP_PCB_UNLOCK(unp);
2142         } else {
2143                 if (!unp_pcb_rele(unp))
2144                         UNP_PCB_UNLOCK(unp);
2145                 if (!unp_pcb_rele(unp2))
2146                         UNP_PCB_UNLOCK(unp2);
2147         }
2148
2149         if (m != NULL) {
2150                 unp_scan(m, unp_freerights);
2151                 m_freem(m);
2152         }
2153 }
2154
2155 /*
2156  * unp_pcblist() walks the global list of struct unpcb's to generate a
2157  * pointer list, bumping the refcount on each unpcb.  It then copies them out
2158  * sequentially, validating the generation number on each to see if it has
2159  * been detached.  All of this is necessary because copyout() may sleep on
2160  * disk I/O.
2161  */
2162 static int
2163 unp_pcblist(SYSCTL_HANDLER_ARGS)
2164 {
2165         struct unpcb *unp, **unp_list;
2166         unp_gen_t gencnt;
2167         struct xunpgen *xug;
2168         struct unp_head *head;
2169         struct xunpcb *xu;
2170         u_int i;
2171         int error, n;
2172
2173         switch ((intptr_t)arg1) {
2174         case SOCK_STREAM:
2175                 head = &unp_shead;
2176                 break;
2177
2178         case SOCK_DGRAM:
2179                 head = &unp_dhead;
2180                 break;
2181
2182         case SOCK_SEQPACKET:
2183                 head = &unp_sphead;
2184                 break;
2185
2186         default:
2187                 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
2188         }
2189
2190         /*
2191          * The process of preparing the PCB list is too time-consuming and
2192          * resource-intensive to repeat twice on every request.
2193          */
2194         if (req->oldptr == NULL) {
2195                 n = unp_count;
2196                 req->oldidx = 2 * (sizeof *xug)
2197                         + (n + n/8) * sizeof(struct xunpcb);
2198                 return (0);
2199         }
2200
2201         if (req->newptr != NULL)
2202                 return (EPERM);
2203
2204         /*
2205          * OK, now we're committed to doing something.
2206          */
2207         xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
2208         UNP_LINK_RLOCK();
2209         gencnt = unp_gencnt;
2210         n = unp_count;
2211         UNP_LINK_RUNLOCK();
2212
2213         xug->xug_len = sizeof *xug;
2214         xug->xug_count = n;
2215         xug->xug_gen = gencnt;
2216         xug->xug_sogen = so_gencnt;
2217         error = SYSCTL_OUT(req, xug, sizeof *xug);
2218         if (error) {
2219                 free(xug, M_TEMP);
2220                 return (error);
2221         }
2222
2223         unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
2224
2225         UNP_LINK_RLOCK();
2226         for (unp = LIST_FIRST(head), i = 0; unp && i < n;
2227              unp = LIST_NEXT(unp, unp_link)) {
2228                 UNP_PCB_LOCK(unp);
2229                 if (unp->unp_gencnt <= gencnt) {
2230                         if (cr_cansee(req->td->td_ucred,
2231                             unp->unp_socket->so_cred)) {
2232                                 UNP_PCB_UNLOCK(unp);
2233                                 continue;
2234                         }
2235                         unp_list[i++] = unp;
2236                         unp_pcb_hold(unp);
2237                 }
2238                 UNP_PCB_UNLOCK(unp);
2239         }
2240         UNP_LINK_RUNLOCK();
2241         n = i;                  /* In case we lost some during malloc. */
2242
2243         error = 0;
2244         xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
2245         for (i = 0; i < n; i++) {
2246                 unp = unp_list[i];
2247                 UNP_PCB_LOCK(unp);
2248                 if (unp_pcb_rele(unp))
2249                         continue;
2250
2251                 if (unp->unp_gencnt <= gencnt) {
2252                         xu->xu_len = sizeof *xu;
2253                         xu->xu_unpp = (uintptr_t)unp;
2254                         /*
2255                          * XXX - need more locking here to protect against
2256                          * connect/disconnect races for SMP.
2257                          */
2258                         if (unp->unp_addr != NULL)
2259                                 bcopy(unp->unp_addr, &xu->xu_addr,
2260                                       unp->unp_addr->sun_len);
2261                         else
2262                                 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
2263                         if (unp->unp_conn != NULL &&
2264                             unp->unp_conn->unp_addr != NULL)
2265                                 bcopy(unp->unp_conn->unp_addr,
2266                                       &xu->xu_caddr,
2267                                       unp->unp_conn->unp_addr->sun_len);
2268                         else
2269                                 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
2270                         xu->unp_vnode = (uintptr_t)unp->unp_vnode;
2271                         xu->unp_conn = (uintptr_t)unp->unp_conn;
2272                         xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
2273                         xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
2274                         xu->unp_gencnt = unp->unp_gencnt;
2275                         sotoxsocket(unp->unp_socket, &xu->xu_socket);
2276                         UNP_PCB_UNLOCK(unp);
2277                         error = SYSCTL_OUT(req, xu, sizeof *xu);
2278                 } else {
2279                         UNP_PCB_UNLOCK(unp);
2280                 }
2281         }
2282         free(xu, M_TEMP);
2283         if (!error) {
2284                 /*
2285                  * Give the user an updated idea of our state.  If the
2286                  * generation differs from what we told her before, she knows
2287                  * that something happened while we were processing this
2288                  * request, and it might be necessary to retry.
2289                  */
2290                 xug->xug_gen = unp_gencnt;
2291                 xug->xug_sogen = so_gencnt;
2292                 xug->xug_count = unp_count;
2293                 error = SYSCTL_OUT(req, xug, sizeof *xug);
2294         }
2295         free(unp_list, M_TEMP);
2296         free(xug, M_TEMP);
2297         return (error);
2298 }
2299
2300 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
2301     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2302     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
2303     "List of active local datagram sockets");
2304 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
2305     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2306     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
2307     "List of active local stream sockets");
2308 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
2309     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2310     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
2311     "List of active local seqpacket sockets");
2312
2313 static void
2314 unp_shutdown(struct unpcb *unp)
2315 {
2316         struct unpcb *unp2;
2317         struct socket *so;
2318
2319         UNP_PCB_LOCK_ASSERT(unp);
2320
2321         unp2 = unp->unp_conn;
2322         if ((unp->unp_socket->so_type == SOCK_STREAM ||
2323             (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
2324                 so = unp2->unp_socket;
2325                 if (so != NULL)
2326                         socantrcvmore(so);
2327         }
2328 }
2329
2330 static void
2331 unp_drop(struct unpcb *unp)
2332 {
2333         struct socket *so;
2334         struct unpcb *unp2;
2335
2336         /*
2337          * Regardless of whether the socket's peer dropped the connection
2338          * with this socket by aborting or disconnecting, POSIX requires
2339          * that ECONNRESET is returned.
2340          */
2341
2342         UNP_PCB_LOCK(unp);
2343         so = unp->unp_socket;
2344         if (so)
2345                 so->so_error = ECONNRESET;
2346         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
2347                 /* Last reference dropped in unp_disconnect(). */
2348                 unp_pcb_rele_notlast(unp);
2349                 unp_disconnect(unp, unp2);
2350         } else if (!unp_pcb_rele(unp)) {
2351                 UNP_PCB_UNLOCK(unp);
2352         }
2353 }
2354
2355 static void
2356 unp_freerights(struct filedescent **fdep, int fdcount)
2357 {
2358         struct file *fp;
2359         int i;
2360
2361         KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
2362
2363         for (i = 0; i < fdcount; i++) {
2364                 fp = fdep[i]->fde_file;
2365                 filecaps_free(&fdep[i]->fde_caps);
2366                 unp_discard(fp);
2367         }
2368         free(fdep[0], M_FILECAPS);
2369 }
2370
2371 static int
2372 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2373 {
2374         struct thread *td = curthread;          /* XXX */
2375         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2376         int i;
2377         int *fdp;
2378         struct filedesc *fdesc = td->td_proc->p_fd;
2379         struct filedescent **fdep;
2380         void *data;
2381         socklen_t clen = control->m_len, datalen;
2382         int error, newfds;
2383         u_int newlen;
2384
2385         UNP_LINK_UNLOCK_ASSERT();
2386
2387         error = 0;
2388         if (controlp != NULL) /* controlp == NULL => free control messages */
2389                 *controlp = NULL;
2390         while (cm != NULL) {
2391                 MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
2392
2393                 data = CMSG_DATA(cm);
2394                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2395                 if (cm->cmsg_level == SOL_SOCKET
2396                     && cm->cmsg_type == SCM_RIGHTS) {
2397                         newfds = datalen / sizeof(*fdep);
2398                         if (newfds == 0)
2399                                 goto next;
2400                         fdep = data;
2401
2402                         /* If we're not outputting the descriptors free them. */
2403                         if (error || controlp == NULL) {
2404                                 unp_freerights(fdep, newfds);
2405                                 goto next;
2406                         }
2407                         FILEDESC_XLOCK(fdesc);
2408
2409                         /*
2410                          * Now change each pointer to an fd in the global
2411                          * table to an integer that is the index to the local
2412                          * fd table entry that we set up to point to the
2413                          * global one we are transferring.
2414                          */
2415                         newlen = newfds * sizeof(int);
2416                         *controlp = sbcreatecontrol(NULL, newlen,
2417                             SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2418
2419                         fdp = (int *)
2420                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2421                         if ((error = fdallocn(td, 0, fdp, newfds))) {
2422                                 FILEDESC_XUNLOCK(fdesc);
2423                                 unp_freerights(fdep, newfds);
2424                                 m_freem(*controlp);
2425                                 *controlp = NULL;
2426                                 goto next;
2427                         }
2428                         for (i = 0; i < newfds; i++, fdp++) {
2429                                 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2430                                     (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2431                                     &fdep[i]->fde_caps);
2432                                 unp_externalize_fp(fdep[i]->fde_file);
2433                         }
2434
2435                         /*
2436                          * The new type indicates that the mbuf data refers to
2437                          * kernel resources that may need to be released before
2438                          * the mbuf is freed.
2439                          */
2440                         m_chtype(*controlp, MT_EXTCONTROL);
2441                         FILEDESC_XUNLOCK(fdesc);
2442                         free(fdep[0], M_FILECAPS);
2443                 } else {
2444                         /* We can just copy anything else across. */
2445                         if (error || controlp == NULL)
2446                                 goto next;
2447                         *controlp = sbcreatecontrol(NULL, datalen,
2448                             cm->cmsg_type, cm->cmsg_level, M_WAITOK);
2449                         bcopy(data,
2450                             CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2451                             datalen);
2452                 }
2453                 controlp = &(*controlp)->m_next;
2454
2455 next:
2456                 if (CMSG_SPACE(datalen) < clen) {
2457                         clen -= CMSG_SPACE(datalen);
2458                         cm = (struct cmsghdr *)
2459                             ((caddr_t)cm + CMSG_SPACE(datalen));
2460                 } else {
2461                         clen = 0;
2462                         cm = NULL;
2463                 }
2464         }
2465
2466         m_freem(control);
2467         return (error);
2468 }
2469
2470 static void
2471 unp_zone_change(void *tag)
2472 {
2473
2474         uma_zone_set_max(unp_zone, maxsockets);
2475 }
2476
2477 #ifdef INVARIANTS
2478 static void
2479 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2480 {
2481         struct unpcb *unp;
2482
2483         unp = mem;
2484
2485         KASSERT(LIST_EMPTY(&unp->unp_refs),
2486             ("%s: unpcb %p has lingering refs", __func__, unp));
2487         KASSERT(unp->unp_socket == NULL,
2488             ("%s: unpcb %p has socket backpointer", __func__, unp));
2489         KASSERT(unp->unp_vnode == NULL,
2490             ("%s: unpcb %p has vnode references", __func__, unp));
2491         KASSERT(unp->unp_conn == NULL,
2492             ("%s: unpcb %p is still connected", __func__, unp));
2493         KASSERT(unp->unp_addr == NULL,
2494             ("%s: unpcb %p has leaked addr", __func__, unp));
2495 }
2496 #endif
2497
2498 static void
2499 unp_init(void *arg __unused)
2500 {
2501         uma_dtor dtor;
2502
2503 #ifdef INVARIANTS
2504         dtor = unp_zdtor;
2505 #else
2506         dtor = NULL;
2507 #endif
2508         unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2509             NULL, NULL, UMA_ALIGN_CACHE, 0);
2510         uma_zone_set_max(unp_zone, maxsockets);
2511         uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2512         EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2513             NULL, EVENTHANDLER_PRI_ANY);
2514         LIST_INIT(&unp_dhead);
2515         LIST_INIT(&unp_shead);
2516         LIST_INIT(&unp_sphead);
2517         SLIST_INIT(&unp_defers);
2518         TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2519         TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2520         UNP_LINK_LOCK_INIT();
2521         UNP_DEFERRED_LOCK_INIT();
2522 }
2523 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
2524
2525 static void
2526 unp_internalize_cleanup_rights(struct mbuf *control)
2527 {
2528         struct cmsghdr *cp;
2529         struct mbuf *m;
2530         void *data;
2531         socklen_t datalen;
2532
2533         for (m = control; m != NULL; m = m->m_next) {
2534                 cp = mtod(m, struct cmsghdr *);
2535                 if (cp->cmsg_level != SOL_SOCKET ||
2536                     cp->cmsg_type != SCM_RIGHTS)
2537                         continue;
2538                 data = CMSG_DATA(cp);
2539                 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2540                 unp_freerights(data, datalen / sizeof(struct filedesc *));
2541         }
2542 }
2543
2544 static int
2545 unp_internalize(struct mbuf **controlp, struct thread *td,
2546     struct mbuf **clast, u_int *space, u_int *mbcnt)
2547 {
2548         struct mbuf *control, **initial_controlp;
2549         struct proc *p;
2550         struct filedesc *fdesc;
2551         struct bintime *bt;
2552         struct cmsghdr *cm;
2553         struct cmsgcred *cmcred;
2554         struct filedescent *fde, **fdep, *fdev;
2555         struct file *fp;
2556         struct timeval *tv;
2557         struct timespec *ts;
2558         void *data;
2559         socklen_t clen, datalen;
2560         int i, j, error, *fdp, oldfds;
2561         u_int newlen;
2562
2563         MPASS((*controlp)->m_next == NULL); /* COMPAT_OLDSOCK may violate */
2564         UNP_LINK_UNLOCK_ASSERT();
2565
2566         p = td->td_proc;
2567         fdesc = p->p_fd;
2568         error = 0;
2569         control = *controlp;
2570         *controlp = NULL;
2571         initial_controlp = controlp;
2572         for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
2573             data = CMSG_DATA(cm);
2574
2575             clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
2576             clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
2577             (char *)cm + cm->cmsg_len >= (char *)data;
2578
2579             clen -= min(CMSG_SPACE(datalen), clen),
2580             cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
2581             data = CMSG_DATA(cm)) {
2582                 datalen = (char *)cm + cm->cmsg_len - (char *)data;
2583                 switch (cm->cmsg_type) {
2584                 case SCM_CREDS:
2585                         *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2586                             SCM_CREDS, SOL_SOCKET, M_WAITOK);
2587                         cmcred = (struct cmsgcred *)
2588                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2589                         cmcred->cmcred_pid = p->p_pid;
2590                         cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2591                         cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2592                         cmcred->cmcred_euid = td->td_ucred->cr_uid;
2593                         cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2594                             CMGROUP_MAX);
2595                         for (i = 0; i < cmcred->cmcred_ngroups; i++)
2596                                 cmcred->cmcred_groups[i] =
2597                                     td->td_ucred->cr_groups[i];
2598                         break;
2599
2600                 case SCM_RIGHTS:
2601                         oldfds = datalen / sizeof (int);
2602                         if (oldfds == 0)
2603                                 continue;
2604                         /* On some machines sizeof pointer is bigger than
2605                          * sizeof int, so we need to check if data fits into
2606                          * single mbuf.  We could allocate several mbufs, and
2607                          * unp_externalize() should even properly handle that.
2608                          * But it is not worth to complicate the code for an
2609                          * insane scenario of passing over 200 file descriptors
2610                          * at once.
2611                          */
2612                         newlen = oldfds * sizeof(fdep[0]);
2613                         if (CMSG_SPACE(newlen) > MCLBYTES) {
2614                                 error = EMSGSIZE;
2615                                 goto out;
2616                         }
2617                         /*
2618                          * Check that all the FDs passed in refer to legal
2619                          * files.  If not, reject the entire operation.
2620                          */
2621                         fdp = data;
2622                         FILEDESC_SLOCK(fdesc);
2623                         for (i = 0; i < oldfds; i++, fdp++) {
2624                                 fp = fget_noref(fdesc, *fdp);
2625                                 if (fp == NULL) {
2626                                         FILEDESC_SUNLOCK(fdesc);
2627                                         error = EBADF;
2628                                         goto out;
2629                                 }
2630                                 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2631                                         FILEDESC_SUNLOCK(fdesc);
2632                                         error = EOPNOTSUPP;
2633                                         goto out;
2634                                 }
2635                         }
2636
2637                         /*
2638                          * Now replace the integer FDs with pointers to the
2639                          * file structure and capability rights.
2640                          */
2641                         *controlp = sbcreatecontrol(NULL, newlen,
2642                             SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2643                         fdp = data;
2644                         for (i = 0; i < oldfds; i++, fdp++) {
2645                                 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2646                                         fdp = data;
2647                                         for (j = 0; j < i; j++, fdp++) {
2648                                                 fdrop(fdesc->fd_ofiles[*fdp].
2649                                                     fde_file, td);
2650                                         }
2651                                         FILEDESC_SUNLOCK(fdesc);
2652                                         error = EBADF;
2653                                         goto out;
2654                                 }
2655                         }
2656                         fdp = data;
2657                         fdep = (struct filedescent **)
2658                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2659                         fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2660                             M_WAITOK);
2661                         for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2662                                 fde = &fdesc->fd_ofiles[*fdp];
2663                                 fdep[i] = fdev;
2664                                 fdep[i]->fde_file = fde->fde_file;
2665                                 filecaps_copy(&fde->fde_caps,
2666                                     &fdep[i]->fde_caps, true);
2667                                 unp_internalize_fp(fdep[i]->fde_file);
2668                         }
2669                         FILEDESC_SUNLOCK(fdesc);
2670                         break;
2671
2672                 case SCM_TIMESTAMP:
2673                         *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2674                             SCM_TIMESTAMP, SOL_SOCKET, M_WAITOK);
2675                         tv = (struct timeval *)
2676                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2677                         microtime(tv);
2678                         break;
2679
2680                 case SCM_BINTIME:
2681                         *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2682                             SCM_BINTIME, SOL_SOCKET, M_WAITOK);
2683                         bt = (struct bintime *)
2684                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2685                         bintime(bt);
2686                         break;
2687
2688                 case SCM_REALTIME:
2689                         *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2690                             SCM_REALTIME, SOL_SOCKET, M_WAITOK);
2691                         ts = (struct timespec *)
2692                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2693                         nanotime(ts);
2694                         break;
2695
2696                 case SCM_MONOTONIC:
2697                         *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2698                             SCM_MONOTONIC, SOL_SOCKET, M_WAITOK);
2699                         ts = (struct timespec *)
2700                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2701                         nanouptime(ts);
2702                         break;
2703
2704                 default:
2705                         error = EINVAL;
2706                         goto out;
2707                 }
2708
2709                 if (space != NULL) {
2710                         *space += (*controlp)->m_len;
2711                         *mbcnt += MSIZE;
2712                         if ((*controlp)->m_flags & M_EXT)
2713                                 *mbcnt += (*controlp)->m_ext.ext_size;
2714                         *clast = *controlp;
2715                 }
2716                 controlp = &(*controlp)->m_next;
2717         }
2718         if (clen > 0)
2719                 error = EINVAL;
2720
2721 out:
2722         if (error != 0 && initial_controlp != NULL)
2723                 unp_internalize_cleanup_rights(*initial_controlp);
2724         m_freem(control);
2725         return (error);
2726 }
2727
2728 static struct mbuf *
2729 unp_addsockcred(struct thread *td, struct mbuf *control, int mode,
2730     struct mbuf **clast, u_int *space, u_int *mbcnt)
2731 {
2732         struct mbuf *m, *n, *n_prev;
2733         const struct cmsghdr *cm;
2734         int ngroups, i, cmsgtype;
2735         size_t ctrlsz;
2736
2737         ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2738         if (mode & UNP_WANTCRED_ALWAYS) {
2739                 ctrlsz = SOCKCRED2SIZE(ngroups);
2740                 cmsgtype = SCM_CREDS2;
2741         } else {
2742                 ctrlsz = SOCKCREDSIZE(ngroups);
2743                 cmsgtype = SCM_CREDS;
2744         }
2745
2746         m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
2747         if (m == NULL)
2748                 return (control);
2749         MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL);
2750
2751         if (mode & UNP_WANTCRED_ALWAYS) {
2752                 struct sockcred2 *sc;
2753
2754                 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2755                 sc->sc_version = 0;
2756                 sc->sc_pid = td->td_proc->p_pid;
2757                 sc->sc_uid = td->td_ucred->cr_ruid;
2758                 sc->sc_euid = td->td_ucred->cr_uid;
2759                 sc->sc_gid = td->td_ucred->cr_rgid;
2760                 sc->sc_egid = td->td_ucred->cr_gid;
2761                 sc->sc_ngroups = ngroups;
2762                 for (i = 0; i < sc->sc_ngroups; i++)
2763                         sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2764         } else {
2765                 struct sockcred *sc;
2766
2767                 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2768                 sc->sc_uid = td->td_ucred->cr_ruid;
2769                 sc->sc_euid = td->td_ucred->cr_uid;
2770                 sc->sc_gid = td->td_ucred->cr_rgid;
2771                 sc->sc_egid = td->td_ucred->cr_gid;
2772                 sc->sc_ngroups = ngroups;
2773                 for (i = 0; i < sc->sc_ngroups; i++)
2774                         sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2775         }
2776
2777         /*
2778          * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2779          * created SCM_CREDS control message (struct sockcred) has another
2780          * format.
2781          */
2782         if (control != NULL && cmsgtype == SCM_CREDS)
2783                 for (n = control, n_prev = NULL; n != NULL;) {
2784                         cm = mtod(n, struct cmsghdr *);
2785                         if (cm->cmsg_level == SOL_SOCKET &&
2786                             cm->cmsg_type == SCM_CREDS) {
2787                                 if (n_prev == NULL)
2788                                         control = n->m_next;
2789                                 else
2790                                         n_prev->m_next = n->m_next;
2791                                 if (space != NULL) {
2792                                         MPASS(*space >= n->m_len);
2793                                         *space -= n->m_len;
2794                                         MPASS(*mbcnt >= MSIZE);
2795                                         *mbcnt -= MSIZE;
2796                                         if (n->m_flags & M_EXT) {
2797                                                 MPASS(*mbcnt >=
2798                                                     n->m_ext.ext_size);
2799                                                 *mbcnt -= n->m_ext.ext_size;
2800                                         }
2801                                         MPASS(clast);
2802                                         if (*clast == n) {
2803                                                 MPASS(n->m_next == NULL);
2804                                                 if (n_prev == NULL)
2805                                                         *clast = m;
2806                                                 else
2807                                                         *clast = n_prev;
2808                                         }
2809                                 }
2810                                 n = m_free(n);
2811                         } else {
2812                                 n_prev = n;
2813                                 n = n->m_next;
2814                         }
2815                 }
2816
2817         /* Prepend it to the head. */
2818         m->m_next = control;
2819         if (space != NULL) {
2820                 *space += m->m_len;
2821                 *mbcnt += MSIZE;
2822                 if (control == NULL)
2823                         *clast = m;
2824         }
2825         return (m);
2826 }
2827
2828 static struct unpcb *
2829 fptounp(struct file *fp)
2830 {
2831         struct socket *so;
2832
2833         if (fp->f_type != DTYPE_SOCKET)
2834                 return (NULL);
2835         if ((so = fp->f_data) == NULL)
2836                 return (NULL);
2837         if (so->so_proto->pr_domain != &localdomain)
2838                 return (NULL);
2839         return sotounpcb(so);
2840 }
2841
2842 static void
2843 unp_discard(struct file *fp)
2844 {
2845         struct unp_defer *dr;
2846
2847         if (unp_externalize_fp(fp)) {
2848                 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2849                 dr->ud_fp = fp;
2850                 UNP_DEFERRED_LOCK();
2851                 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2852                 UNP_DEFERRED_UNLOCK();
2853                 atomic_add_int(&unp_defers_count, 1);
2854                 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2855         } else
2856                 closef_nothread(fp);
2857 }
2858
2859 static void
2860 unp_process_defers(void *arg __unused, int pending)
2861 {
2862         struct unp_defer *dr;
2863         SLIST_HEAD(, unp_defer) drl;
2864         int count;
2865
2866         SLIST_INIT(&drl);
2867         for (;;) {
2868                 UNP_DEFERRED_LOCK();
2869                 if (SLIST_FIRST(&unp_defers) == NULL) {
2870                         UNP_DEFERRED_UNLOCK();
2871                         break;
2872                 }
2873                 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2874                 UNP_DEFERRED_UNLOCK();
2875                 count = 0;
2876                 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2877                         SLIST_REMOVE_HEAD(&drl, ud_link);
2878                         closef_nothread(dr->ud_fp);
2879                         free(dr, M_TEMP);
2880                         count++;
2881                 }
2882                 atomic_add_int(&unp_defers_count, -count);
2883         }
2884 }
2885
2886 static void
2887 unp_internalize_fp(struct file *fp)
2888 {
2889         struct unpcb *unp;
2890
2891         UNP_LINK_WLOCK();
2892         if ((unp = fptounp(fp)) != NULL) {
2893                 unp->unp_file = fp;
2894                 unp->unp_msgcount++;
2895         }
2896         unp_rights++;
2897         UNP_LINK_WUNLOCK();
2898 }
2899
2900 static int
2901 unp_externalize_fp(struct file *fp)
2902 {
2903         struct unpcb *unp;
2904         int ret;
2905
2906         UNP_LINK_WLOCK();
2907         if ((unp = fptounp(fp)) != NULL) {
2908                 unp->unp_msgcount--;
2909                 ret = 1;
2910         } else
2911                 ret = 0;
2912         unp_rights--;
2913         UNP_LINK_WUNLOCK();
2914         return (ret);
2915 }
2916
2917 /*
2918  * unp_defer indicates whether additional work has been defered for a future
2919  * pass through unp_gc().  It is thread local and does not require explicit
2920  * synchronization.
2921  */
2922 static int      unp_marked;
2923
2924 static void
2925 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2926 {
2927         struct unpcb *unp;
2928         struct file *fp;
2929         int i;
2930
2931         /*
2932          * This function can only be called from the gc task.
2933          */
2934         KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2935             ("%s: not on gc callout", __func__));
2936         UNP_LINK_LOCK_ASSERT();
2937
2938         for (i = 0; i < fdcount; i++) {
2939                 fp = fdep[i]->fde_file;
2940                 if ((unp = fptounp(fp)) == NULL)
2941                         continue;
2942                 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2943                         continue;
2944                 unp->unp_gcrefs--;
2945         }
2946 }
2947
2948 static void
2949 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2950 {
2951         struct unpcb *unp;
2952         struct file *fp;
2953         int i;
2954
2955         /*
2956          * This function can only be called from the gc task.
2957          */
2958         KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2959             ("%s: not on gc callout", __func__));
2960         UNP_LINK_LOCK_ASSERT();
2961
2962         for (i = 0; i < fdcount; i++) {
2963                 fp = fdep[i]->fde_file;
2964                 if ((unp = fptounp(fp)) == NULL)
2965                         continue;
2966                 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2967                         continue;
2968                 unp->unp_gcrefs++;
2969                 unp_marked++;
2970         }
2971 }
2972
2973 static void
2974 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
2975 {
2976         struct sockbuf *sb;
2977
2978         SOCK_LOCK_ASSERT(so);
2979
2980         if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2981                 return;
2982
2983         SOCK_RECVBUF_LOCK(so);
2984         switch (so->so_type) {
2985         case SOCK_DGRAM:
2986                 unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
2987                 unp_scan(so->so_rcv.uxdg_peeked, op);
2988                 TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist)
2989                         unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op);
2990                 break;
2991         case SOCK_STREAM:
2992         case SOCK_SEQPACKET:
2993                 unp_scan(so->so_rcv.sb_mb, op);
2994                 break;
2995         }
2996         SOCK_RECVBUF_UNLOCK(so);
2997 }
2998
2999 static void
3000 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
3001 {
3002         struct socket *so, *soa;
3003
3004         so = unp->unp_socket;
3005         SOCK_LOCK(so);
3006         if (SOLISTENING(so)) {
3007                 /*
3008                  * Mark all sockets in our accept queue.
3009                  */
3010                 TAILQ_FOREACH(soa, &so->sol_comp, so_list)
3011                         unp_scan_socket(soa, op);
3012         } else {
3013                 /*
3014                  * Mark all sockets we reference with RIGHTS.
3015                  */
3016                 unp_scan_socket(so, op);
3017         }
3018         SOCK_UNLOCK(so);
3019 }
3020
3021 static int unp_recycled;
3022 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, 
3023     "Number of unreachable sockets claimed by the garbage collector.");
3024
3025 static int unp_taskcount;
3026 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, 
3027     "Number of times the garbage collector has run.");
3028
3029 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0, 
3030     "Number of active local sockets.");
3031
3032 static void
3033 unp_gc(__unused void *arg, int pending)
3034 {
3035         struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
3036                                     NULL };
3037         struct unp_head **head;
3038         struct unp_head unp_deadhead;   /* List of potentially-dead sockets. */
3039         struct file *f, **unref;
3040         struct unpcb *unp, *unptmp;
3041         int i, total, unp_unreachable;
3042
3043         LIST_INIT(&unp_deadhead);
3044         unp_taskcount++;
3045         UNP_LINK_RLOCK();
3046         /*
3047          * First determine which sockets may be in cycles.
3048          */
3049         unp_unreachable = 0;
3050
3051         for (head = heads; *head != NULL; head++)
3052                 LIST_FOREACH(unp, *head, unp_link) {
3053                         KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
3054                             ("%s: unp %p has unexpected gc flags 0x%x",
3055                             __func__, unp, (unsigned int)unp->unp_gcflag));
3056
3057                         f = unp->unp_file;
3058
3059                         /*
3060                          * Check for an unreachable socket potentially in a
3061                          * cycle.  It must be in a queue as indicated by
3062                          * msgcount, and this must equal the file reference
3063                          * count.  Note that when msgcount is 0 the file is
3064                          * NULL.
3065                          */
3066                         if (f != NULL && unp->unp_msgcount != 0 &&
3067                             refcount_load(&f->f_count) == unp->unp_msgcount) {
3068                                 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
3069                                 unp->unp_gcflag |= UNPGC_DEAD;
3070                                 unp->unp_gcrefs = unp->unp_msgcount;
3071                                 unp_unreachable++;
3072                         }
3073                 }
3074
3075         /*
3076          * Scan all sockets previously marked as potentially being in a cycle
3077          * and remove the references each socket holds on any UNPGC_DEAD
3078          * sockets in its queue.  After this step, all remaining references on
3079          * sockets marked UNPGC_DEAD should not be part of any cycle.
3080          */
3081         LIST_FOREACH(unp, &unp_deadhead, unp_dead)
3082                 unp_gc_scan(unp, unp_remove_dead_ref);
3083
3084         /*
3085          * If a socket still has a non-negative refcount, it cannot be in a
3086          * cycle.  In this case increment refcount of all children iteratively.
3087          * Stop the scan once we do a complete loop without discovering
3088          * a new reachable socket.
3089          */
3090         do {
3091                 unp_marked = 0;
3092                 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
3093                         if (unp->unp_gcrefs > 0) {
3094                                 unp->unp_gcflag &= ~UNPGC_DEAD;
3095                                 LIST_REMOVE(unp, unp_dead);
3096                                 KASSERT(unp_unreachable > 0,
3097                                     ("%s: unp_unreachable underflow.",
3098                                     __func__));
3099                                 unp_unreachable--;
3100                                 unp_gc_scan(unp, unp_restore_undead_ref);
3101                         }
3102         } while (unp_marked);
3103
3104         UNP_LINK_RUNLOCK();
3105
3106         if (unp_unreachable == 0)
3107                 return;
3108
3109         /*
3110          * Allocate space for a local array of dead unpcbs.
3111          * TODO: can this path be simplified by instead using the local
3112          * dead list at unp_deadhead, after taking out references
3113          * on the file object and/or unpcb and dropping the link lock?
3114          */
3115         unref = malloc(unp_unreachable * sizeof(struct file *),
3116             M_TEMP, M_WAITOK);
3117
3118         /*
3119          * Iterate looking for sockets which have been specifically marked
3120          * as unreachable and store them locally.
3121          */
3122         UNP_LINK_RLOCK();
3123         total = 0;
3124         LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
3125                 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
3126                     ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
3127                 unp->unp_gcflag &= ~UNPGC_DEAD;
3128                 f = unp->unp_file;
3129                 if (unp->unp_msgcount == 0 || f == NULL ||
3130                     refcount_load(&f->f_count) != unp->unp_msgcount ||
3131                     !fhold(f))
3132                         continue;
3133                 unref[total++] = f;
3134                 KASSERT(total <= unp_unreachable,
3135                     ("%s: incorrect unreachable count.", __func__));
3136         }
3137         UNP_LINK_RUNLOCK();
3138
3139         /*
3140          * Now flush all sockets, free'ing rights.  This will free the
3141          * struct files associated with these sockets but leave each socket
3142          * with one remaining ref.
3143          */
3144         for (i = 0; i < total; i++) {
3145                 struct socket *so;
3146
3147                 so = unref[i]->f_data;
3148                 CURVNET_SET(so->so_vnet);
3149                 sorflush(so);
3150                 CURVNET_RESTORE();
3151         }
3152
3153         /*
3154          * And finally release the sockets so they can be reclaimed.
3155          */
3156         for (i = 0; i < total; i++)
3157                 fdrop(unref[i], NULL);
3158         unp_recycled += total;
3159         free(unref, M_TEMP);
3160 }
3161
3162 /*
3163  * Synchronize against unp_gc, which can trip over data as we are freeing it.
3164  */
3165 static void
3166 unp_dispose(struct socket *so)
3167 {
3168         struct sockbuf *sb;
3169         struct unpcb *unp;
3170         struct mbuf *m;
3171
3172         MPASS(!SOLISTENING(so));
3173
3174         unp = sotounpcb(so);
3175         UNP_LINK_WLOCK();
3176         unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
3177         UNP_LINK_WUNLOCK();
3178
3179         /*
3180          * Grab our special mbufs before calling sbrelease().
3181          */
3182         SOCK_RECVBUF_LOCK(so);
3183         switch (so->so_type) {
3184         case SOCK_DGRAM:
3185                 while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) {
3186                         STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb);
3187                         TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
3188                         /* Note: socket of sb may reconnect. */
3189                         sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0;
3190                 }
3191                 sb = &so->so_rcv;
3192                 if (sb->uxdg_peeked != NULL) {
3193                         STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked,
3194                             m_stailqpkt);
3195                         sb->uxdg_peeked = NULL;
3196                 }
3197                 m = STAILQ_FIRST(&sb->uxdg_mb);
3198                 STAILQ_INIT(&sb->uxdg_mb);
3199                 /* XXX: our shortened sbrelease() */
3200                 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
3201                     RLIM_INFINITY);
3202                 /*
3203                  * XXXGL Mark sb with SBS_CANTRCVMORE.  This is needed to
3204                  * prevent uipc_sosend_dgram() or unp_disconnect() adding more
3205                  * data to the socket.
3206                  * We are now in dom_dispose and it could be a call from
3207                  * soshutdown() or from the final sofree().  The sofree() case
3208                  * is simple as it guarantees that no more sends will happen,
3209                  * however we can race with unp_disconnect() from our peer.
3210                  * The shutdown(2) case is more exotic.  It would call into
3211                  * dom_dispose() only if socket is SS_ISCONNECTED.  This is
3212                  * possible if we did connect(2) on this socket and we also
3213                  * had it bound with bind(2) and receive connections from other
3214                  * sockets.  Because soshutdown() violates POSIX (see comment
3215                  * there) we will end up here shutting down our receive side.
3216                  * Of course this will have affect not only on the peer we
3217                  * connect(2)ed to, but also on all of the peers who had
3218                  * connect(2)ed to us.  Their sends would end up with ENOBUFS.
3219                  */
3220                 sb->sb_state |= SBS_CANTRCVMORE;
3221                 break;
3222         case SOCK_STREAM:
3223         case SOCK_SEQPACKET:
3224                 sb = &so->so_rcv;
3225                 m = sbcut_locked(sb, sb->sb_ccc);
3226                 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
3227                     ("%s: ccc %u mb %p mbcnt %u", __func__,
3228                     sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
3229                 sbrelease_locked(so, SO_RCV);
3230                 break;
3231         }
3232         SOCK_RECVBUF_UNLOCK(so);
3233         if (SOCK_IO_RECV_OWNED(so))
3234                 SOCK_IO_RECV_UNLOCK(so);
3235
3236         if (m != NULL) {
3237                 unp_scan(m, unp_freerights);
3238                 m_freem(m);
3239         }
3240 }
3241
3242 static void
3243 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
3244 {
3245         struct mbuf *m;
3246         struct cmsghdr *cm;
3247         void *data;
3248         socklen_t clen, datalen;
3249
3250         while (m0 != NULL) {
3251                 for (m = m0; m; m = m->m_next) {
3252                         if (m->m_type != MT_CONTROL)
3253                                 continue;
3254
3255                         cm = mtod(m, struct cmsghdr *);
3256                         clen = m->m_len;
3257
3258                         while (cm != NULL) {
3259                                 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
3260                                         break;
3261
3262                                 data = CMSG_DATA(cm);
3263                                 datalen = (caddr_t)cm + cm->cmsg_len
3264                                     - (caddr_t)data;
3265
3266                                 if (cm->cmsg_level == SOL_SOCKET &&
3267                                     cm->cmsg_type == SCM_RIGHTS) {
3268                                         (*op)(data, datalen /
3269                                             sizeof(struct filedescent *));
3270                                 }
3271
3272                                 if (CMSG_SPACE(datalen) < clen) {
3273                                         clen -= CMSG_SPACE(datalen);
3274                                         cm = (struct cmsghdr *)
3275                                             ((caddr_t)cm + CMSG_SPACE(datalen));
3276                                 } else {
3277                                         clen = 0;
3278                                         cm = NULL;
3279                                 }
3280                         }
3281                 }
3282                 m0 = m0->m_nextpkt;
3283         }
3284 }
3285
3286 /*
3287  * Definitions of protocols supported in the LOCAL domain.
3288  */
3289 static struct protosw streamproto = {
3290         .pr_type =              SOCK_STREAM,
3291         .pr_flags =             PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|
3292                                     PR_CAPATTACH,
3293         .pr_ctloutput =         &uipc_ctloutput,
3294         .pr_abort =             uipc_abort,
3295         .pr_accept =            uipc_peeraddr,
3296         .pr_attach =            uipc_attach,
3297         .pr_bind =              uipc_bind,
3298         .pr_bindat =            uipc_bindat,
3299         .pr_connect =           uipc_connect,
3300         .pr_connectat =         uipc_connectat,
3301         .pr_connect2 =          uipc_connect2,
3302         .pr_detach =            uipc_detach,
3303         .pr_disconnect =        uipc_disconnect,
3304         .pr_listen =            uipc_listen,
3305         .pr_peeraddr =          uipc_peeraddr,
3306         .pr_rcvd =              uipc_rcvd,
3307         .pr_send =              uipc_send,
3308         .pr_ready =             uipc_ready,
3309         .pr_sense =             uipc_sense,
3310         .pr_shutdown =          uipc_shutdown,
3311         .pr_sockaddr =          uipc_sockaddr,
3312         .pr_soreceive =         soreceive_generic,
3313         .pr_close =             uipc_close,
3314 };
3315
3316 static struct protosw dgramproto = {
3317         .pr_type =              SOCK_DGRAM,
3318         .pr_flags =             PR_ATOMIC | PR_ADDR |PR_RIGHTS | PR_CAPATTACH |
3319                                     PR_SOCKBUF,
3320         .pr_ctloutput =         &uipc_ctloutput,
3321         .pr_abort =             uipc_abort,
3322         .pr_accept =            uipc_peeraddr,
3323         .pr_attach =            uipc_attach,
3324         .pr_bind =              uipc_bind,
3325         .pr_bindat =            uipc_bindat,
3326         .pr_connect =           uipc_connect,
3327         .pr_connectat =         uipc_connectat,
3328         .pr_connect2 =          uipc_connect2,
3329         .pr_detach =            uipc_detach,
3330         .pr_disconnect =        uipc_disconnect,
3331         .pr_peeraddr =          uipc_peeraddr,
3332         .pr_sosend =            uipc_sosend_dgram,
3333         .pr_sense =             uipc_sense,
3334         .pr_shutdown =          uipc_shutdown,
3335         .pr_sockaddr =          uipc_sockaddr,
3336         .pr_soreceive =         uipc_soreceive_dgram,
3337         .pr_close =             uipc_close,
3338 };
3339
3340 static struct protosw seqpacketproto = {
3341         .pr_type =              SOCK_SEQPACKET,
3342         /*
3343          * XXXRW: For now, PR_ADDR because soreceive will bump into them
3344          * due to our use of sbappendaddr.  A new sbappend variants is needed
3345          * that supports both atomic record writes and control data.
3346          */
3347         .pr_flags =             PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|
3348                                     PR_WANTRCVD|PR_RIGHTS|PR_CAPATTACH,
3349         .pr_ctloutput =         &uipc_ctloutput,
3350         .pr_abort =             uipc_abort,
3351         .pr_accept =            uipc_peeraddr,
3352         .pr_attach =            uipc_attach,
3353         .pr_bind =              uipc_bind,
3354         .pr_bindat =            uipc_bindat,
3355         .pr_connect =           uipc_connect,
3356         .pr_connectat =         uipc_connectat,
3357         .pr_connect2 =          uipc_connect2,
3358         .pr_detach =            uipc_detach,
3359         .pr_disconnect =        uipc_disconnect,
3360         .pr_listen =            uipc_listen,
3361         .pr_peeraddr =          uipc_peeraddr,
3362         .pr_rcvd =              uipc_rcvd,
3363         .pr_send =              uipc_send,
3364         .pr_sense =             uipc_sense,
3365         .pr_shutdown =          uipc_shutdown,
3366         .pr_sockaddr =          uipc_sockaddr,
3367         .pr_soreceive =         soreceive_generic,      /* XXX: or...? */
3368         .pr_close =             uipc_close,
3369 };
3370
3371 static struct domain localdomain = {
3372         .dom_family =           AF_LOCAL,
3373         .dom_name =             "local",
3374         .dom_externalize =      unp_externalize,
3375         .dom_dispose =          unp_dispose,
3376         .dom_nprotosw =         3,
3377         .dom_protosw =          {
3378                 &streamproto,
3379                 &dgramproto,
3380                 &seqpacketproto,
3381         }
3382 };
3383 DOMAIN_SET(local);
3384
3385 /*
3386  * A helper function called by VFS before socket-type vnode reclamation.
3387  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
3388  * use count.
3389  */
3390 void
3391 vfs_unp_reclaim(struct vnode *vp)
3392 {
3393         struct unpcb *unp;
3394         int active;
3395         struct mtx *vplock;
3396
3397         ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
3398         KASSERT(vp->v_type == VSOCK,
3399             ("vfs_unp_reclaim: vp->v_type != VSOCK"));
3400
3401         active = 0;
3402         vplock = mtx_pool_find(mtxpool_sleep, vp);
3403         mtx_lock(vplock);
3404         VOP_UNP_CONNECT(vp, &unp);
3405         if (unp == NULL)
3406                 goto done;
3407         UNP_PCB_LOCK(unp);
3408         if (unp->unp_vnode == vp) {
3409                 VOP_UNP_DETACH(vp);
3410                 unp->unp_vnode = NULL;
3411                 active = 1;
3412         }
3413         UNP_PCB_UNLOCK(unp);
3414  done:
3415         mtx_unlock(vplock);
3416         if (active)
3417                 vunref(vp);
3418 }
3419
3420 #ifdef DDB
3421 static void
3422 db_print_indent(int indent)
3423 {
3424         int i;
3425
3426         for (i = 0; i < indent; i++)
3427                 db_printf(" ");
3428 }
3429
3430 static void
3431 db_print_unpflags(int unp_flags)
3432 {
3433         int comma;
3434
3435         comma = 0;
3436         if (unp_flags & UNP_HAVEPC) {
3437                 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
3438                 comma = 1;
3439         }
3440         if (unp_flags & UNP_WANTCRED_ALWAYS) {
3441                 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
3442                 comma = 1;
3443         }
3444         if (unp_flags & UNP_WANTCRED_ONESHOT) {
3445                 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
3446                 comma = 1;
3447         }
3448         if (unp_flags & UNP_CONNWAIT) {
3449                 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
3450                 comma = 1;
3451         }
3452         if (unp_flags & UNP_CONNECTING) {
3453                 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
3454                 comma = 1;
3455         }
3456         if (unp_flags & UNP_BINDING) {
3457                 db_printf("%sUNP_BINDING", comma ? ", " : "");
3458                 comma = 1;
3459         }
3460 }
3461
3462 static void
3463 db_print_xucred(int indent, struct xucred *xu)
3464 {
3465         int comma, i;
3466
3467         db_print_indent(indent);
3468         db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
3469             xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
3470         db_print_indent(indent);
3471         db_printf("cr_groups: ");
3472         comma = 0;
3473         for (i = 0; i < xu->cr_ngroups; i++) {
3474                 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
3475                 comma = 1;
3476         }
3477         db_printf("\n");
3478 }
3479
3480 static void
3481 db_print_unprefs(int indent, struct unp_head *uh)
3482 {
3483         struct unpcb *unp;
3484         int counter;
3485
3486         counter = 0;
3487         LIST_FOREACH(unp, uh, unp_reflink) {
3488                 if (counter % 4 == 0)
3489                         db_print_indent(indent);
3490                 db_printf("%p  ", unp);
3491                 if (counter % 4 == 3)
3492                         db_printf("\n");
3493                 counter++;
3494         }
3495         if (counter != 0 && counter % 4 != 0)
3496                 db_printf("\n");
3497 }
3498
3499 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
3500 {
3501         struct unpcb *unp;
3502
3503         if (!have_addr) {
3504                 db_printf("usage: show unpcb <addr>\n");
3505                 return;
3506         }
3507         unp = (struct unpcb *)addr;
3508
3509         db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
3510             unp->unp_vnode);
3511
3512         db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
3513             unp->unp_conn);
3514
3515         db_printf("unp_refs:\n");
3516         db_print_unprefs(2, &unp->unp_refs);
3517
3518         /* XXXRW: Would be nice to print the full address, if any. */
3519         db_printf("unp_addr: %p\n", unp->unp_addr);
3520
3521         db_printf("unp_gencnt: %llu\n",
3522             (unsigned long long)unp->unp_gencnt);
3523
3524         db_printf("unp_flags: %x (", unp->unp_flags);
3525         db_print_unpflags(unp->unp_flags);
3526         db_printf(")\n");
3527
3528         db_printf("unp_peercred:\n");
3529         db_print_xucred(2, &unp->unp_peercred);
3530
3531         db_printf("unp_refcount: %u\n", unp->unp_refcount);
3532 }
3533 #endif