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