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