]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_socket.c
After r319722 two fields were left uninitialized when transforming a
[FreeBSD/FreeBSD.git] / sys / kern / uipc_socket.c
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993
3  *      The Regents of the University of California.
4  * Copyright (c) 2004 The FreeBSD Foundation
5  * Copyright (c) 2004-2008 Robert N. M. Watson
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      @(#)uipc_socket.c       8.3 (Berkeley) 4/15/94
33  */
34
35 /*
36  * Comments on the socket life cycle:
37  *
38  * soalloc() sets of socket layer state for a socket, called only by
39  * socreate() and sonewconn().  Socket layer private.
40  *
41  * sodealloc() tears down socket layer state for a socket, called only by
42  * sofree() and sonewconn().  Socket layer private.
43  *
44  * pru_attach() associates protocol layer state with an allocated socket;
45  * called only once, may fail, aborting socket allocation.  This is called
46  * from socreate() and sonewconn().  Socket layer private.
47  *
48  * pru_detach() disassociates protocol layer state from an attached socket,
49  * and will be called exactly once for sockets in which pru_attach() has
50  * been successfully called.  If pru_attach() returned an error,
51  * pru_detach() will not be called.  Socket layer private.
52  *
53  * pru_abort() and pru_close() notify the protocol layer that the last
54  * consumer of a socket is starting to tear down the socket, and that the
55  * protocol should terminate the connection.  Historically, pru_abort() also
56  * detached protocol state from the socket state, but this is no longer the
57  * case.
58  *
59  * socreate() creates a socket and attaches protocol state.  This is a public
60  * interface that may be used by socket layer consumers to create new
61  * sockets.
62  *
63  * sonewconn() creates a socket and attaches protocol state.  This is a
64  * public interface  that may be used by protocols to create new sockets when
65  * a new connection is received and will be available for accept() on a
66  * listen socket.
67  *
68  * soclose() destroys a socket after possibly waiting for it to disconnect.
69  * This is a public interface that socket consumers should use to close and
70  * release a socket when done with it.
71  *
72  * soabort() destroys a socket without waiting for it to disconnect (used
73  * only for incoming connections that are already partially or fully
74  * connected).  This is used internally by the socket layer when clearing
75  * listen socket queues (due to overflow or close on the listen socket), but
76  * is also a public interface protocols may use to abort connections in
77  * their incomplete listen queues should they no longer be required.  Sockets
78  * placed in completed connection listen queues should not be aborted for
79  * reasons described in the comment above the soclose() implementation.  This
80  * is not a general purpose close routine, and except in the specific
81  * circumstances described here, should not be used.
82  *
83  * sofree() will free a socket and its protocol state if all references on
84  * the socket have been released, and is the public interface to attempt to
85  * free a socket when a reference is removed.  This is a socket layer private
86  * interface.
87  *
88  * NOTE: In addition to socreate() and soclose(), which provide a single
89  * socket reference to the consumer to be managed as required, there are two
90  * calls to explicitly manage socket references, soref(), and sorele().
91  * Currently, these are generally required only when transitioning a socket
92  * from a listen queue to a file descriptor, in order to prevent garbage
93  * collection of the socket at an untimely moment.  For a number of reasons,
94  * these interfaces are not preferred, and should be avoided.
95  *
96  * NOTE: With regard to VNETs the general rule is that callers do not set
97  * curvnet. Exceptions to this rule include soabort(), sodisconnect(),
98  * sofree() (and with that sorele(), sotryfree()), as well as sonewconn()
99  * and sorflush(), which are usually called from a pre-set VNET context.
100  * sopoll() currently does not need a VNET context to be set.
101  */
102
103 #include <sys/cdefs.h>
104 __FBSDID("$FreeBSD$");
105
106 #include "opt_inet.h"
107 #include "opt_inet6.h"
108 #include "opt_compat.h"
109 #include "opt_sctp.h"
110
111 #include <sys/param.h>
112 #include <sys/systm.h>
113 #include <sys/fcntl.h>
114 #include <sys/limits.h>
115 #include <sys/lock.h>
116 #include <sys/mac.h>
117 #include <sys/malloc.h>
118 #include <sys/mbuf.h>
119 #include <sys/mutex.h>
120 #include <sys/domain.h>
121 #include <sys/file.h>                   /* for struct knote */
122 #include <sys/hhook.h>
123 #include <sys/kernel.h>
124 #include <sys/khelp.h>
125 #include <sys/event.h>
126 #include <sys/eventhandler.h>
127 #include <sys/poll.h>
128 #include <sys/proc.h>
129 #include <sys/protosw.h>
130 #include <sys/socket.h>
131 #include <sys/socketvar.h>
132 #include <sys/resourcevar.h>
133 #include <net/route.h>
134 #include <sys/signalvar.h>
135 #include <sys/stat.h>
136 #include <sys/sx.h>
137 #include <sys/sysctl.h>
138 #include <sys/taskqueue.h>
139 #include <sys/uio.h>
140 #include <sys/jail.h>
141 #include <sys/syslog.h>
142 #include <netinet/in.h>
143
144 #include <net/vnet.h>
145
146 #include <security/mac/mac_framework.h>
147
148 #include <vm/uma.h>
149
150 #ifdef COMPAT_FREEBSD32
151 #include <sys/mount.h>
152 #include <sys/sysent.h>
153 #include <compat/freebsd32/freebsd32.h>
154 #endif
155
156 static int      soreceive_rcvoob(struct socket *so, struct uio *uio,
157                     int flags);
158 static void     so_rdknl_lock(void *);
159 static void     so_rdknl_unlock(void *);
160 static void     so_rdknl_assert_locked(void *);
161 static void     so_rdknl_assert_unlocked(void *);
162 static void     so_wrknl_lock(void *);
163 static void     so_wrknl_unlock(void *);
164 static void     so_wrknl_assert_locked(void *);
165 static void     so_wrknl_assert_unlocked(void *);
166
167 static void     filt_sordetach(struct knote *kn);
168 static int      filt_soread(struct knote *kn, long hint);
169 static void     filt_sowdetach(struct knote *kn);
170 static int      filt_sowrite(struct knote *kn, long hint);
171 static int      filt_soempty(struct knote *kn, long hint);
172 static int inline hhook_run_socket(struct socket *so, void *hctx, int32_t h_id);
173 fo_kqfilter_t   soo_kqfilter;
174
175 static struct filterops soread_filtops = {
176         .f_isfd = 1,
177         .f_detach = filt_sordetach,
178         .f_event = filt_soread,
179 };
180 static struct filterops sowrite_filtops = {
181         .f_isfd = 1,
182         .f_detach = filt_sowdetach,
183         .f_event = filt_sowrite,
184 };
185 static struct filterops soempty_filtops = {
186         .f_isfd = 1,
187         .f_detach = filt_sowdetach,
188         .f_event = filt_soempty,
189 };
190
191 so_gen_t        so_gencnt;      /* generation count for sockets */
192
193 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
194 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
195
196 #define VNET_SO_ASSERT(so)                                              \
197         VNET_ASSERT(curvnet != NULL,                                    \
198             ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
199
200 VNET_DEFINE(struct hhook_head *, socket_hhh[HHOOK_SOCKET_LAST + 1]);
201 #define V_socket_hhh            VNET(socket_hhh)
202
203 /*
204  * Limit on the number of connections in the listen queue waiting
205  * for accept(2).
206  * NB: The original sysctl somaxconn is still available but hidden
207  * to prevent confusion about the actual purpose of this number.
208  */
209 static u_int somaxconn = SOMAXCONN;
210
211 static int
212 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
213 {
214         int error;
215         int val;
216
217         val = somaxconn;
218         error = sysctl_handle_int(oidp, &val, 0, req);
219         if (error || !req->newptr )
220                 return (error);
221
222         /*
223          * The purpose of the UINT_MAX / 3 limit, is so that the formula
224          *   3 * so_qlimit / 2
225          * below, will not overflow.
226          */
227
228         if (val < 1 || val > UINT_MAX / 3)
229                 return (EINVAL);
230
231         somaxconn = val;
232         return (0);
233 }
234 SYSCTL_PROC(_kern_ipc, OID_AUTO, soacceptqueue, CTLTYPE_UINT | CTLFLAG_RW,
235     0, sizeof(int), sysctl_somaxconn, "I",
236     "Maximum listen socket pending connection accept queue size");
237 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn,
238     CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_SKIP,
239     0, sizeof(int), sysctl_somaxconn, "I",
240     "Maximum listen socket pending connection accept queue size (compat)");
241
242 static int numopensockets;
243 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
244     &numopensockets, 0, "Number of open sockets");
245
246 /*
247  * accept_mtx locks down per-socket fields relating to accept queues.  See
248  * socketvar.h for an annotation of the protected fields of struct socket.
249  */
250 struct mtx accept_mtx;
251 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
252
253 /*
254  * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
255  * so_gencnt field.
256  */
257 static struct mtx so_global_mtx;
258 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
259
260 /*
261  * General IPC sysctl name space, used by sockets and a variety of other IPC
262  * types.
263  */
264 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
265
266 /*
267  * Initialize the socket subsystem and set up the socket
268  * memory allocator.
269  */
270 static uma_zone_t socket_zone;
271 int     maxsockets;
272
273 static void
274 socket_zone_change(void *tag)
275 {
276
277         maxsockets = uma_zone_set_max(socket_zone, maxsockets);
278 }
279
280 static void
281 socket_hhook_register(int subtype)
282 {
283         
284         if (hhook_head_register(HHOOK_TYPE_SOCKET, subtype,
285             &V_socket_hhh[subtype],
286             HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
287                 printf("%s: WARNING: unable to register hook\n", __func__);
288 }
289
290 static void
291 socket_hhook_deregister(int subtype)
292 {
293         
294         if (hhook_head_deregister(V_socket_hhh[subtype]) != 0)
295                 printf("%s: WARNING: unable to deregister hook\n", __func__);
296 }
297
298 static void
299 socket_init(void *tag)
300 {
301
302         socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL,
303             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
304         maxsockets = uma_zone_set_max(socket_zone, maxsockets);
305         uma_zone_set_warning(socket_zone, "kern.ipc.maxsockets limit reached");
306         EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL,
307             EVENTHANDLER_PRI_FIRST);
308 }
309 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL);
310
311 static void
312 socket_vnet_init(const void *unused __unused)
313 {
314         int i;
315
316         /* We expect a contiguous range */
317         for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
318                 socket_hhook_register(i);
319 }
320 VNET_SYSINIT(socket_vnet_init, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
321     socket_vnet_init, NULL);
322
323 static void
324 socket_vnet_uninit(const void *unused __unused)
325 {
326         int i;
327
328         for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
329                 socket_hhook_deregister(i);
330 }
331 VNET_SYSUNINIT(socket_vnet_uninit, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
332     socket_vnet_uninit, NULL);
333
334 /*
335  * Initialise maxsockets.  This SYSINIT must be run after
336  * tunable_mbinit().
337  */
338 static void
339 init_maxsockets(void *ignored)
340 {
341
342         TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
343         maxsockets = imax(maxsockets, maxfiles);
344 }
345 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
346
347 /*
348  * Sysctl to get and set the maximum global sockets limit.  Notify protocols
349  * of the change so that they can update their dependent limits as required.
350  */
351 static int
352 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
353 {
354         int error, newmaxsockets;
355
356         newmaxsockets = maxsockets;
357         error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
358         if (error == 0 && req->newptr) {
359                 if (newmaxsockets > maxsockets &&
360                     newmaxsockets <= maxfiles) {
361                         maxsockets = newmaxsockets;
362                         EVENTHANDLER_INVOKE(maxsockets_change);
363                 } else
364                         error = EINVAL;
365         }
366         return (error);
367 }
368 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
369     &maxsockets, 0, sysctl_maxsockets, "IU",
370     "Maximum number of sockets available");
371
372 /*
373  * Socket operation routines.  These routines are called by the routines in
374  * sys_socket.c or from a system process, and implement the semantics of
375  * socket operations by switching out to the protocol specific routines.
376  */
377
378 /*
379  * Get a socket structure from our zone, and initialize it.  Note that it
380  * would probably be better to allocate socket and PCB at the same time, but
381  * I'm not convinced that all the protocols can be easily modified to do
382  * this.
383  *
384  * soalloc() returns a socket with a ref count of 0.
385  */
386 static struct socket *
387 soalloc(struct vnet *vnet)
388 {
389         struct socket *so;
390
391         so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
392         if (so == NULL)
393                 return (NULL);
394 #ifdef MAC
395         if (mac_socket_init(so, M_NOWAIT) != 0) {
396                 uma_zfree(socket_zone, so);
397                 return (NULL);
398         }
399 #endif
400         if (khelp_init_osd(HELPER_CLASS_SOCKET, &so->osd)) {
401                 uma_zfree(socket_zone, so);
402                 return (NULL);
403         }
404
405         /*
406          * The socket locking protocol allows to lock 2 sockets at a time,
407          * however, the first one must be a listening socket.  WITNESS lacks
408          * a feature to change class of an existing lock, so we use DUPOK.
409          */
410         mtx_init(&so->so_lock, "socket", NULL, MTX_DEF | MTX_DUPOK);
411         SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
412         SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
413         so->so_rcv.sb_sel = &so->so_rdsel;
414         so->so_snd.sb_sel = &so->so_wrsel;
415         sx_init(&so->so_snd.sb_sx, "so_snd_sx");
416         sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
417         TAILQ_INIT(&so->so_snd.sb_aiojobq);
418         TAILQ_INIT(&so->so_rcv.sb_aiojobq);
419         TASK_INIT(&so->so_snd.sb_aiotask, 0, soaio_snd, so);
420         TASK_INIT(&so->so_rcv.sb_aiotask, 0, soaio_rcv, so);
421 #ifdef VIMAGE
422         VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
423             __func__, __LINE__, so));
424         so->so_vnet = vnet;
425 #endif
426         /* We shouldn't need the so_global_mtx */
427         if (hhook_run_socket(so, NULL, HHOOK_SOCKET_CREATE)) {
428                 /* Do we need more comprehensive error returns? */
429                 uma_zfree(socket_zone, so);
430                 return (NULL);
431         }
432         mtx_lock(&so_global_mtx);
433         so->so_gencnt = ++so_gencnt;
434         ++numopensockets;
435 #ifdef VIMAGE
436         vnet->vnet_sockcnt++;
437 #endif
438         mtx_unlock(&so_global_mtx);
439
440         return (so);
441 }
442
443 /*
444  * Free the storage associated with a socket at the socket layer, tear down
445  * locks, labels, etc.  All protocol state is assumed already to have been
446  * torn down (and possibly never set up) by the caller.
447  */
448 static void
449 sodealloc(struct socket *so)
450 {
451
452         KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
453         KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
454
455         mtx_lock(&so_global_mtx);
456         so->so_gencnt = ++so_gencnt;
457         --numopensockets;       /* Could be below, but faster here. */
458 #ifdef VIMAGE
459         VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
460             __func__, __LINE__, so));
461         so->so_vnet->vnet_sockcnt--;
462 #endif
463         mtx_unlock(&so_global_mtx);
464 #ifdef MAC
465         mac_socket_destroy(so);
466 #endif
467         hhook_run_socket(so, NULL, HHOOK_SOCKET_CLOSE);
468
469         crfree(so->so_cred);
470         khelp_destroy_osd(&so->osd);
471         if (SOLISTENING(so)) {
472                 if (so->sol_accept_filter != NULL)
473                         accept_filt_setopt(so, NULL);
474         } else {
475                 if (so->so_rcv.sb_hiwat)
476                         (void)chgsbsize(so->so_cred->cr_uidinfo,
477                             &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
478                 if (so->so_snd.sb_hiwat)
479                         (void)chgsbsize(so->so_cred->cr_uidinfo,
480                             &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
481                 sx_destroy(&so->so_snd.sb_sx);
482                 sx_destroy(&so->so_rcv.sb_sx);
483                 SOCKBUF_LOCK_DESTROY(&so->so_snd);
484                 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
485         }
486         mtx_destroy(&so->so_lock);
487         uma_zfree(socket_zone, so);
488 }
489
490 /*
491  * socreate returns a socket with a ref count of 1.  The socket should be
492  * closed with soclose().
493  */
494 int
495 socreate(int dom, struct socket **aso, int type, int proto,
496     struct ucred *cred, struct thread *td)
497 {
498         struct protosw *prp;
499         struct socket *so;
500         int error;
501
502         if (proto)
503                 prp = pffindproto(dom, proto, type);
504         else
505                 prp = pffindtype(dom, type);
506
507         if (prp == NULL) {
508                 /* No support for domain. */
509                 if (pffinddomain(dom) == NULL)
510                         return (EAFNOSUPPORT);
511                 /* No support for socket type. */
512                 if (proto == 0 && type != 0)
513                         return (EPROTOTYPE);
514                 return (EPROTONOSUPPORT);
515         }
516         if (prp->pr_usrreqs->pru_attach == NULL ||
517             prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
518                 return (EPROTONOSUPPORT);
519
520         if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
521                 return (EPROTONOSUPPORT);
522
523         if (prp->pr_type != type)
524                 return (EPROTOTYPE);
525         so = soalloc(CRED_TO_VNET(cred));
526         if (so == NULL)
527                 return (ENOBUFS);
528
529         so->so_type = type;
530         so->so_cred = crhold(cred);
531         if ((prp->pr_domain->dom_family == PF_INET) ||
532             (prp->pr_domain->dom_family == PF_INET6) ||
533             (prp->pr_domain->dom_family == PF_ROUTE))
534                 so->so_fibnum = td->td_proc->p_fibnum;
535         else
536                 so->so_fibnum = 0;
537         so->so_proto = prp;
538 #ifdef MAC
539         mac_socket_create(cred, so);
540 #endif
541         knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
542             so_rdknl_assert_locked, so_rdknl_assert_unlocked);
543         knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
544             so_wrknl_assert_locked, so_wrknl_assert_unlocked);
545         /*
546          * Auto-sizing of socket buffers is managed by the protocols and
547          * the appropriate flags must be set in the pru_attach function.
548          */
549         CURVNET_SET(so->so_vnet);
550         error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
551         CURVNET_RESTORE();
552         if (error) {
553                 sodealloc(so);
554                 return (error);
555         }
556         soref(so);
557         *aso = so;
558         return (0);
559 }
560
561 #ifdef REGRESSION
562 static int regression_sonewconn_earlytest = 1;
563 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
564     &regression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
565 #endif
566
567 /*
568  * When an attempt at a new connection is noted on a socket which accepts
569  * connections, sonewconn is called.  If the connection is possible (subject
570  * to space constraints, etc.) then we allocate a new structure, properly
571  * linked into the data structure of the original socket, and return this.
572  * Connstatus may be 0, or SS_ISCONFIRMING, or SS_ISCONNECTED.
573  *
574  * Note: the ref count on the socket is 0 on return.
575  */
576 struct socket *
577 sonewconn(struct socket *head, int connstatus)
578 {
579         static struct timeval lastover;
580         static struct timeval overinterval = { 60, 0 };
581         static int overcount;
582
583         struct socket *so;
584         u_int over;
585
586         SOLISTEN_LOCK(head);
587         over = (head->sol_qlen > 3 * head->sol_qlimit / 2);
588         SOLISTEN_UNLOCK(head);
589 #ifdef REGRESSION
590         if (regression_sonewconn_earlytest && over) {
591 #else
592         if (over) {
593 #endif
594                 overcount++;
595
596                 if (ratecheck(&lastover, &overinterval)) {
597                         log(LOG_DEBUG, "%s: pcb %p: Listen queue overflow: "
598                             "%i already in queue awaiting acceptance "
599                             "(%d occurrences)\n",
600                             __func__, head->so_pcb, head->sol_qlen, overcount);
601
602                         overcount = 0;
603                 }
604
605                 return (NULL);
606         }
607         VNET_ASSERT(head->so_vnet != NULL, ("%s: so %p vnet is NULL",
608             __func__, head));
609         so = soalloc(head->so_vnet);
610         if (so == NULL) {
611                 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
612                     "limit reached or out of memory\n",
613                     __func__, head->so_pcb);
614                 return (NULL);
615         }
616         so->so_listen = head;
617         so->so_type = head->so_type;
618         so->so_linger = head->so_linger;
619         so->so_state = head->so_state | SS_NOFDREF;
620         so->so_fibnum = head->so_fibnum;
621         so->so_proto = head->so_proto;
622         so->so_cred = crhold(head->so_cred);
623 #ifdef MAC
624         mac_socket_newconn(head, so);
625 #endif
626         knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
627             so_rdknl_assert_locked, so_rdknl_assert_unlocked);
628         knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
629             so_wrknl_assert_locked, so_wrknl_assert_unlocked);
630         VNET_SO_ASSERT(head);
631         if (soreserve(so, head->sol_sbsnd_hiwat, head->sol_sbrcv_hiwat)) {
632                 sodealloc(so);
633                 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
634                     __func__, head->so_pcb);
635                 return (NULL);
636         }
637         if ((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
638                 sodealloc(so);
639                 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
640                     __func__, head->so_pcb);
641                 return (NULL);
642         }
643         so->so_rcv.sb_lowat = head->sol_sbrcv_lowat;
644         so->so_snd.sb_lowat = head->sol_sbsnd_lowat;
645         so->so_rcv.sb_timeo = head->sol_sbrcv_timeo;
646         so->so_snd.sb_timeo = head->sol_sbsnd_timeo;
647         so->so_rcv.sb_flags |= head->sol_sbrcv_flags & SB_AUTOSIZE;
648         so->so_snd.sb_flags |= head->sol_sbsnd_flags & SB_AUTOSIZE;
649
650         SOLISTEN_LOCK(head);
651         if (head->sol_accept_filter != NULL)
652                 connstatus = 0;
653         so->so_state |= connstatus;
654         so->so_options = head->so_options & ~SO_ACCEPTCONN;
655         soref(head); /* A socket on (in)complete queue refs head. */
656         if (connstatus) {
657                 TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
658                 so->so_qstate = SQ_COMP;
659                 head->sol_qlen++;
660                 solisten_wakeup(head);  /* unlocks */
661         } else {
662                 /*
663                  * Keep removing sockets from the head until there's room for
664                  * us to insert on the tail.  In pre-locking revisions, this
665                  * was a simple if(), but as we could be racing with other
666                  * threads and soabort() requires dropping locks, we must
667                  * loop waiting for the condition to be true.
668                  */
669                 while (head->sol_incqlen > head->sol_qlimit) {
670                         struct socket *sp;
671
672                         sp = TAILQ_FIRST(&head->sol_incomp);
673                         TAILQ_REMOVE(&head->sol_incomp, sp, so_list);
674                         head->sol_incqlen--;
675                         SOCK_LOCK(sp);
676                         sp->so_qstate = SQ_NONE;
677                         sp->so_listen = NULL;
678                         SOCK_UNLOCK(sp);
679                         sorele(head);   /* does SOLISTEN_UNLOCK, head stays */
680                         soabort(sp);
681                         SOLISTEN_LOCK(head);
682                 }
683                 TAILQ_INSERT_TAIL(&head->sol_incomp, so, so_list);
684                 so->so_qstate = SQ_INCOMP;
685                 head->sol_incqlen++;
686                 SOLISTEN_UNLOCK(head);
687         }
688         return (so);
689 }
690
691 #ifdef SCTP
692 /*
693  * Socket part of sctp_peeloff().  Detach a new socket from an
694  * association.  The new socket is returned with a reference.
695  */
696 struct socket *
697 sopeeloff(struct socket *head)
698 {
699         struct socket *so;
700
701         VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
702             __func__, __LINE__, head));
703         so = soalloc(head->so_vnet);
704         if (so == NULL) {
705                 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
706                     "limit reached or out of memory\n",
707                     __func__, head->so_pcb);
708                 return (NULL);
709         }
710         so->so_type = head->so_type;
711         so->so_options = head->so_options;
712         so->so_linger = head->so_linger;
713         so->so_state = (head->so_state & SS_NBIO) | SS_ISCONNECTED;
714         so->so_fibnum = head->so_fibnum;
715         so->so_proto = head->so_proto;
716         so->so_cred = crhold(head->so_cred);
717 #ifdef MAC
718         mac_socket_newconn(head, so);
719 #endif
720         knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
721             so_rdknl_assert_locked, so_rdknl_assert_unlocked);
722         knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
723             so_wrknl_assert_locked, so_wrknl_assert_unlocked);
724         VNET_SO_ASSERT(head);
725         if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
726                 sodealloc(so);
727                 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
728                     __func__, head->so_pcb);
729                 return (NULL);
730         }
731         if ((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
732                 sodealloc(so);
733                 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
734                     __func__, head->so_pcb);
735                 return (NULL);
736         }
737         so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
738         so->so_snd.sb_lowat = head->so_snd.sb_lowat;
739         so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
740         so->so_snd.sb_timeo = head->so_snd.sb_timeo;
741         so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
742         so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
743
744         soref(so);
745
746         return (so);
747 }
748 #endif  /* SCTP */
749
750 int
751 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
752 {
753         int error;
754
755         CURVNET_SET(so->so_vnet);
756         error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
757         CURVNET_RESTORE();
758         return (error);
759 }
760
761 int
762 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
763 {
764         int error;
765
766         CURVNET_SET(so->so_vnet);
767         error = (*so->so_proto->pr_usrreqs->pru_bindat)(fd, so, nam, td);
768         CURVNET_RESTORE();
769         return (error);
770 }
771
772 /*
773  * solisten() transitions a socket from a non-listening state to a listening
774  * state, but can also be used to update the listen queue depth on an
775  * existing listen socket.  The protocol will call back into the sockets
776  * layer using solisten_proto_check() and solisten_proto() to check and set
777  * socket-layer listen state.  Call backs are used so that the protocol can
778  * acquire both protocol and socket layer locks in whatever order is required
779  * by the protocol.
780  *
781  * Protocol implementors are advised to hold the socket lock across the
782  * socket-layer test and set to avoid races at the socket layer.
783  */
784 int
785 solisten(struct socket *so, int backlog, struct thread *td)
786 {
787         int error;
788
789         CURVNET_SET(so->so_vnet);
790         error = (*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td);
791         CURVNET_RESTORE();
792         return (error);
793 }
794
795 int
796 solisten_proto_check(struct socket *so)
797 {
798
799         SOCK_LOCK_ASSERT(so);
800
801         if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
802             SS_ISDISCONNECTING))
803                 return (EINVAL);
804         return (0);
805 }
806
807 void
808 solisten_proto(struct socket *so, int backlog)
809 {
810         int sbrcv_lowat, sbsnd_lowat;
811         u_int sbrcv_hiwat, sbsnd_hiwat;
812         short sbrcv_flags, sbsnd_flags;
813         sbintime_t sbrcv_timeo, sbsnd_timeo;
814
815         SOCK_LOCK_ASSERT(so);
816
817         if (SOLISTENING(so))
818                 goto listening;
819
820         /*
821          * Change this socket to listening state.
822          */
823         sbrcv_lowat = so->so_rcv.sb_lowat;
824         sbsnd_lowat = so->so_snd.sb_lowat;
825         sbrcv_hiwat = so->so_rcv.sb_hiwat;
826         sbsnd_hiwat = so->so_snd.sb_hiwat;
827         sbrcv_flags = so->so_rcv.sb_flags;
828         sbsnd_flags = so->so_snd.sb_flags;
829         sbrcv_timeo = so->so_rcv.sb_timeo;
830         sbsnd_timeo = so->so_snd.sb_timeo;
831
832         sbdestroy(&so->so_snd, so);
833         sbdestroy(&so->so_rcv, so);
834         sx_destroy(&so->so_snd.sb_sx);
835         sx_destroy(&so->so_rcv.sb_sx);
836         SOCKBUF_LOCK_DESTROY(&so->so_snd);
837         SOCKBUF_LOCK_DESTROY(&so->so_rcv);
838
839 #ifdef INVARIANTS
840         bzero(&so->so_rcv,
841             sizeof(struct socket) - offsetof(struct socket, so_rcv));
842 #endif
843
844         so->sol_sbrcv_lowat = sbrcv_lowat;
845         so->sol_sbsnd_lowat = sbsnd_lowat;
846         so->sol_sbrcv_hiwat = sbrcv_hiwat;
847         so->sol_sbsnd_hiwat = sbsnd_hiwat;
848         so->sol_sbrcv_flags = sbrcv_flags;
849         so->sol_sbsnd_flags = sbsnd_flags;
850         so->sol_sbrcv_timeo = sbrcv_timeo;
851         so->sol_sbsnd_timeo = sbsnd_timeo;
852
853         so->sol_qlen = so->sol_incqlen = 0;
854         TAILQ_INIT(&so->sol_incomp);
855         TAILQ_INIT(&so->sol_comp);
856
857         so->sol_accept_filter = NULL;
858         so->sol_accept_filter_arg = NULL;
859         so->sol_accept_filter_str = NULL;
860
861         so->sol_upcall = NULL;
862         so->sol_upcallarg = NULL;
863
864         so->so_options |= SO_ACCEPTCONN;
865
866 listening:
867         if (backlog < 0 || backlog > somaxconn)
868                 backlog = somaxconn;
869         so->sol_qlimit = backlog;
870 }
871
872 /*
873  * Wakeup listeners/subsystems once we have a complete connection.
874  * Enters with lock, returns unlocked.
875  */
876 void
877 solisten_wakeup(struct socket *sol)
878 {
879
880         if (sol->sol_upcall != NULL)
881                 (void )sol->sol_upcall(sol, sol->sol_upcallarg, M_NOWAIT);
882         else {
883                 selwakeuppri(&sol->so_rdsel, PSOCK);
884                 KNOTE_LOCKED(&sol->so_rdsel.si_note, 0);
885         }
886         SOLISTEN_UNLOCK(sol);
887         wakeup_one(&sol->sol_comp);
888 }
889
890 /*
891  * Return single connection off a listening socket queue.  Main consumer of
892  * the function is kern_accept4().  Some modules, that do their own accept
893  * management also use the function.
894  *
895  * Listening socket must be locked on entry and is returned unlocked on
896  * return.
897  * The flags argument is set of accept4(2) flags and ACCEPT4_INHERIT.
898  */
899 int
900 solisten_dequeue(struct socket *head, struct socket **ret, int flags)
901 {
902         struct socket *so;
903         int error;
904
905         SOLISTEN_LOCK_ASSERT(head);
906
907         while (!(head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp) &&
908             head->so_error == 0) {
909                 error = msleep(&head->sol_comp, &head->so_lock, PSOCK | PCATCH,
910                     "accept", 0);
911                 if (error != 0) {
912                         SOLISTEN_UNLOCK(head);
913                         return (error);
914                 }
915         }
916         if (head->so_error) {
917                 error = head->so_error;
918                 head->so_error = 0;
919                 SOLISTEN_UNLOCK(head);
920                 return (error);
921         }
922         if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp)) {
923                 SOLISTEN_UNLOCK(head);
924                 return (EWOULDBLOCK);
925         }
926         so = TAILQ_FIRST(&head->sol_comp);
927         SOCK_LOCK(so);
928         KASSERT(so->so_qstate == SQ_COMP,
929             ("%s: so %p not SQ_COMP", __func__, so));
930         soref(so);
931         head->sol_qlen--;
932         so->so_qstate = SQ_NONE;
933         so->so_listen = NULL;
934         TAILQ_REMOVE(&head->sol_comp, so, so_list);
935         if (flags & ACCEPT4_INHERIT)
936                 so->so_state |= (head->so_state & SS_NBIO);
937         else
938                 so->so_state |= (flags & SOCK_NONBLOCK) ? SS_NBIO : 0;
939         SOCK_UNLOCK(so);
940         sorele(head);
941
942         *ret = so;
943         return (0);
944 }
945
946 /*
947  * Evaluate the reference count and named references on a socket; if no
948  * references remain, free it.  This should be called whenever a reference is
949  * released, such as in sorele(), but also when named reference flags are
950  * cleared in socket or protocol code.
951  *
952  * sofree() will free the socket if:
953  *
954  * - There are no outstanding file descriptor references or related consumers
955  *   (so_count == 0).
956  *
957  * - The socket has been closed by user space, if ever open (SS_NOFDREF).
958  *
959  * - The protocol does not have an outstanding strong reference on the socket
960  *   (SS_PROTOREF).
961  *
962  * - The socket is not in a completed connection queue, so a process has been
963  *   notified that it is present.  If it is removed, the user process may
964  *   block in accept() despite select() saying the socket was ready.
965  */
966 void
967 sofree(struct socket *so)
968 {
969         struct protosw *pr = so->so_proto;
970
971         SOCK_LOCK_ASSERT(so);
972
973         if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
974             (so->so_state & SS_PROTOREF) || (so->so_qstate == SQ_COMP)) {
975                 SOCK_UNLOCK(so);
976                 return;
977         }
978
979         if (!SOLISTENING(so) && so->so_qstate == SQ_INCOMP) {
980                 struct socket *sol;
981
982                 sol = so->so_listen;
983                 KASSERT(sol, ("%s: so %p on incomp of NULL", __func__, so));
984
985                 /*
986                  * To solve race between close of a listening socket and
987                  * a socket on its incomplete queue, we need to lock both.
988                  * The order is first listening socket, then regular.
989                  * Since we don't have SS_NOFDREF neither SS_PROTOREF, this
990                  * function and the listening socket are the only pointers
991                  * to so.  To preserve so and sol, we reference both and then
992                  * relock.
993                  * After relock the socket may not move to so_comp since it
994                  * doesn't have PCB already, but it may be removed from
995                  * so_incomp. If that happens, we share responsiblity on
996                  * freeing the socket, but soclose() has already removed
997                  * it from queue.
998                  */
999                 soref(sol);
1000                 soref(so);
1001                 SOCK_UNLOCK(so);
1002                 SOLISTEN_LOCK(sol);
1003                 SOCK_LOCK(so);
1004                 if (so->so_qstate == SQ_INCOMP) {
1005                         KASSERT(so->so_listen == sol,
1006                             ("%s: so %p migrated out of sol %p",
1007                             __func__, so, sol));
1008                         TAILQ_REMOVE(&sol->sol_incomp, so, so_list);
1009                         sol->sol_incqlen--;
1010                         /* This is guarenteed not to be the last. */
1011                         refcount_release(&sol->so_count);
1012                         so->so_qstate = SQ_NONE;
1013                         so->so_listen = NULL;
1014                 } else
1015                         KASSERT(so->so_listen == NULL,
1016                             ("%s: so %p not on (in)comp with so_listen",
1017                             __func__, so));
1018                 sorele(sol);
1019                 KASSERT(so->so_count == 1,
1020                     ("%s: so %p count %u", __func__, so, so->so_count));
1021                 so->so_count = 0;
1022         }
1023         if (SOLISTENING(so))
1024                 so->so_error = ECONNABORTED;
1025         SOCK_UNLOCK(so);
1026
1027         VNET_SO_ASSERT(so);
1028         if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
1029                 (*pr->pr_domain->dom_dispose)(so);
1030         if (pr->pr_usrreqs->pru_detach != NULL)
1031                 (*pr->pr_usrreqs->pru_detach)(so);
1032
1033         /*
1034          * From this point on, we assume that no other references to this
1035          * socket exist anywhere else in the stack.  Therefore, no locks need
1036          * to be acquired or held.
1037          *
1038          * We used to do a lot of socket buffer and socket locking here, as
1039          * well as invoke sorflush() and perform wakeups.  The direct call to
1040          * dom_dispose() and sbrelease_internal() are an inlining of what was
1041          * necessary from sorflush().
1042          *
1043          * Notice that the socket buffer and kqueue state are torn down
1044          * before calling pru_detach.  This means that protocols shold not
1045          * assume they can perform socket wakeups, etc, in their detach code.
1046          */
1047         if (!SOLISTENING(so)) {
1048                 sbdestroy(&so->so_snd, so);
1049                 sbdestroy(&so->so_rcv, so);
1050         }
1051         seldrain(&so->so_rdsel);
1052         seldrain(&so->so_wrsel);
1053         knlist_destroy(&so->so_rdsel.si_note);
1054         knlist_destroy(&so->so_wrsel.si_note);
1055         sodealloc(so);
1056 }
1057
1058 /*
1059  * Close a socket on last file table reference removal.  Initiate disconnect
1060  * if connected.  Free socket when disconnect complete.
1061  *
1062  * This function will sorele() the socket.  Note that soclose() may be called
1063  * prior to the ref count reaching zero.  The actual socket structure will
1064  * not be freed until the ref count reaches zero.
1065  */
1066 int
1067 soclose(struct socket *so)
1068 {
1069         struct accept_queue lqueue;
1070         bool listening;
1071         int error = 0;
1072
1073         KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
1074
1075         CURVNET_SET(so->so_vnet);
1076         funsetown(&so->so_sigio);
1077         if (so->so_state & SS_ISCONNECTED) {
1078                 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
1079                         error = sodisconnect(so);
1080                         if (error) {
1081                                 if (error == ENOTCONN)
1082                                         error = 0;
1083                                 goto drop;
1084                         }
1085                 }
1086                 if (so->so_options & SO_LINGER) {
1087                         if ((so->so_state & SS_ISDISCONNECTING) &&
1088                             (so->so_state & SS_NBIO))
1089                                 goto drop;
1090                         while (so->so_state & SS_ISCONNECTED) {
1091                                 error = tsleep(&so->so_timeo,
1092                                     PSOCK | PCATCH, "soclos",
1093                                     so->so_linger * hz);
1094                                 if (error)
1095                                         break;
1096                         }
1097                 }
1098         }
1099
1100 drop:
1101         if (so->so_proto->pr_usrreqs->pru_close != NULL)
1102                 (*so->so_proto->pr_usrreqs->pru_close)(so);
1103
1104         SOCK_LOCK(so);
1105         if ((listening = (so->so_options & SO_ACCEPTCONN))) {
1106                 struct socket *sp;
1107
1108                 TAILQ_INIT(&lqueue);
1109                 TAILQ_SWAP(&lqueue, &so->sol_incomp, socket, so_list);
1110                 TAILQ_CONCAT(&lqueue, &so->sol_comp, so_list);
1111
1112                 so->sol_qlen = so->sol_incqlen = 0;
1113
1114                 TAILQ_FOREACH(sp, &lqueue, so_list) {
1115                         SOCK_LOCK(sp);
1116                         sp->so_qstate = SQ_NONE;
1117                         sp->so_listen = NULL;
1118                         SOCK_UNLOCK(sp);
1119                         /* Guaranteed not to be the last. */
1120                         refcount_release(&so->so_count);
1121                 }
1122         }
1123         KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
1124         so->so_state |= SS_NOFDREF;
1125         sorele(so);
1126         if (listening) {
1127                 struct socket *sp;
1128
1129                 TAILQ_FOREACH(sp, &lqueue, so_list) {
1130                         SOCK_LOCK(sp);
1131                         if (sp->so_count == 0) {
1132                                 SOCK_UNLOCK(sp);
1133                                 soabort(sp);
1134                         } else
1135                                 /* sp is now in sofree() */
1136                                 SOCK_UNLOCK(sp);
1137                 }
1138         }
1139         CURVNET_RESTORE();
1140         return (error);
1141 }
1142
1143 /*
1144  * soabort() is used to abruptly tear down a connection, such as when a
1145  * resource limit is reached (listen queue depth exceeded), or if a listen
1146  * socket is closed while there are sockets waiting to be accepted.
1147  *
1148  * This interface is tricky, because it is called on an unreferenced socket,
1149  * and must be called only by a thread that has actually removed the socket
1150  * from the listen queue it was on, or races with other threads are risked.
1151  *
1152  * This interface will call into the protocol code, so must not be called
1153  * with any socket locks held.  Protocols do call it while holding their own
1154  * recursible protocol mutexes, but this is something that should be subject
1155  * to review in the future.
1156  */
1157 void
1158 soabort(struct socket *so)
1159 {
1160
1161         /*
1162          * In as much as is possible, assert that no references to this
1163          * socket are held.  This is not quite the same as asserting that the
1164          * current thread is responsible for arranging for no references, but
1165          * is as close as we can get for now.
1166          */
1167         KASSERT(so->so_count == 0, ("soabort: so_count"));
1168         KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
1169         KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
1170         KASSERT(so->so_qstate == SQ_NONE, ("soabort: !SQ_NONE"));
1171         VNET_SO_ASSERT(so);
1172
1173         if (so->so_proto->pr_usrreqs->pru_abort != NULL)
1174                 (*so->so_proto->pr_usrreqs->pru_abort)(so);
1175         SOCK_LOCK(so);
1176         sofree(so);
1177 }
1178
1179 int
1180 soaccept(struct socket *so, struct sockaddr **nam)
1181 {
1182         int error;
1183
1184         SOCK_LOCK(so);
1185         KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
1186         so->so_state &= ~SS_NOFDREF;
1187         SOCK_UNLOCK(so);
1188
1189         CURVNET_SET(so->so_vnet);
1190         error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
1191         CURVNET_RESTORE();
1192         return (error);
1193 }
1194
1195 int
1196 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
1197 {
1198
1199         return (soconnectat(AT_FDCWD, so, nam, td));
1200 }
1201
1202 int
1203 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
1204 {
1205         int error;
1206
1207         if (so->so_options & SO_ACCEPTCONN)
1208                 return (EOPNOTSUPP);
1209
1210         CURVNET_SET(so->so_vnet);
1211         /*
1212          * If protocol is connection-based, can only connect once.
1213          * Otherwise, if connected, try to disconnect first.  This allows
1214          * user to disconnect by connecting to, e.g., a null address.
1215          */
1216         if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
1217             ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
1218             (error = sodisconnect(so)))) {
1219                 error = EISCONN;
1220         } else {
1221                 /*
1222                  * Prevent accumulated error from previous connection from
1223                  * biting us.
1224                  */
1225                 so->so_error = 0;
1226                 if (fd == AT_FDCWD) {
1227                         error = (*so->so_proto->pr_usrreqs->pru_connect)(so,
1228                             nam, td);
1229                 } else {
1230                         error = (*so->so_proto->pr_usrreqs->pru_connectat)(fd,
1231                             so, nam, td);
1232                 }
1233         }
1234         CURVNET_RESTORE();
1235
1236         return (error);
1237 }
1238
1239 int
1240 soconnect2(struct socket *so1, struct socket *so2)
1241 {
1242         int error;
1243
1244         CURVNET_SET(so1->so_vnet);
1245         error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
1246         CURVNET_RESTORE();
1247         return (error);
1248 }
1249
1250 int
1251 sodisconnect(struct socket *so)
1252 {
1253         int error;
1254
1255         if ((so->so_state & SS_ISCONNECTED) == 0)
1256                 return (ENOTCONN);
1257         if (so->so_state & SS_ISDISCONNECTING)
1258                 return (EALREADY);
1259         VNET_SO_ASSERT(so);
1260         error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
1261         return (error);
1262 }
1263
1264 #define SBLOCKWAIT(f)   (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1265
1266 int
1267 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1268     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1269 {
1270         long space;
1271         ssize_t resid;
1272         int clen = 0, error, dontroute;
1273
1274         KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
1275         KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1276             ("sosend_dgram: !PR_ATOMIC"));
1277
1278         if (uio != NULL)
1279                 resid = uio->uio_resid;
1280         else
1281                 resid = top->m_pkthdr.len;
1282         /*
1283          * In theory resid should be unsigned.  However, space must be
1284          * signed, as it might be less than 0 if we over-committed, and we
1285          * must use a signed comparison of space and resid.  On the other
1286          * hand, a negative resid causes us to loop sending 0-length
1287          * segments to the protocol.
1288          */
1289         if (resid < 0) {
1290                 error = EINVAL;
1291                 goto out;
1292         }
1293
1294         dontroute =
1295             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1296         if (td != NULL)
1297                 td->td_ru.ru_msgsnd++;
1298         if (control != NULL)
1299                 clen = control->m_len;
1300
1301         SOCKBUF_LOCK(&so->so_snd);
1302         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1303                 SOCKBUF_UNLOCK(&so->so_snd);
1304                 error = EPIPE;
1305                 goto out;
1306         }
1307         if (so->so_error) {
1308                 error = so->so_error;
1309                 so->so_error = 0;
1310                 SOCKBUF_UNLOCK(&so->so_snd);
1311                 goto out;
1312         }
1313         if ((so->so_state & SS_ISCONNECTED) == 0) {
1314                 /*
1315                  * `sendto' and `sendmsg' is allowed on a connection-based
1316                  * socket if it supports implied connect.  Return ENOTCONN if
1317                  * not connected and no address is supplied.
1318                  */
1319                 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1320                     (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1321                         if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1322                             !(resid == 0 && clen != 0)) {
1323                                 SOCKBUF_UNLOCK(&so->so_snd);
1324                                 error = ENOTCONN;
1325                                 goto out;
1326                         }
1327                 } else if (addr == NULL) {
1328                         if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1329                                 error = ENOTCONN;
1330                         else
1331                                 error = EDESTADDRREQ;
1332                         SOCKBUF_UNLOCK(&so->so_snd);
1333                         goto out;
1334                 }
1335         }
1336
1337         /*
1338          * Do we need MSG_OOB support in SOCK_DGRAM?  Signs here may be a
1339          * problem and need fixing.
1340          */
1341         space = sbspace(&so->so_snd);
1342         if (flags & MSG_OOB)
1343                 space += 1024;
1344         space -= clen;
1345         SOCKBUF_UNLOCK(&so->so_snd);
1346         if (resid > space) {
1347                 error = EMSGSIZE;
1348                 goto out;
1349         }
1350         if (uio == NULL) {
1351                 resid = 0;
1352                 if (flags & MSG_EOR)
1353                         top->m_flags |= M_EOR;
1354         } else {
1355                 /*
1356                  * Copy the data from userland into a mbuf chain.
1357                  * If no data is to be copied in, a single empty mbuf
1358                  * is returned.
1359                  */
1360                 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1361                     (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1362                 if (top == NULL) {
1363                         error = EFAULT; /* only possible error */
1364                         goto out;
1365                 }
1366                 space -= resid - uio->uio_resid;
1367                 resid = uio->uio_resid;
1368         }
1369         KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1370         /*
1371          * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1372          * than with.
1373          */
1374         if (dontroute) {
1375                 SOCK_LOCK(so);
1376                 so->so_options |= SO_DONTROUTE;
1377                 SOCK_UNLOCK(so);
1378         }
1379         /*
1380          * XXX all the SBS_CANTSENDMORE checks previously done could be out
1381          * of date.  We could have received a reset packet in an interrupt or
1382          * maybe we slept while doing page faults in uiomove() etc.  We could
1383          * probably recheck again inside the locking protection here, but
1384          * there are probably other places that this also happens.  We must
1385          * rethink this.
1386          */
1387         VNET_SO_ASSERT(so);
1388         error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1389             (flags & MSG_OOB) ? PRUS_OOB :
1390         /*
1391          * If the user set MSG_EOF, the protocol understands this flag and
1392          * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1393          */
1394             ((flags & MSG_EOF) &&
1395              (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1396              (resid <= 0)) ?
1397                 PRUS_EOF :
1398                 /* If there is more to send set PRUS_MORETOCOME */
1399                 (flags & MSG_MORETOCOME) ||
1400                 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1401                 top, addr, control, td);
1402         if (dontroute) {
1403                 SOCK_LOCK(so);
1404                 so->so_options &= ~SO_DONTROUTE;
1405                 SOCK_UNLOCK(so);
1406         }
1407         clen = 0;
1408         control = NULL;
1409         top = NULL;
1410 out:
1411         if (top != NULL)
1412                 m_freem(top);
1413         if (control != NULL)
1414                 m_freem(control);
1415         return (error);
1416 }
1417
1418 /*
1419  * Send on a socket.  If send must go all at once and message is larger than
1420  * send buffering, then hard error.  Lock against other senders.  If must go
1421  * all at once and not enough room now, then inform user that this would
1422  * block and do nothing.  Otherwise, if nonblocking, send as much as
1423  * possible.  The data to be sent is described by "uio" if nonzero, otherwise
1424  * by the mbuf chain "top" (which must be null if uio is not).  Data provided
1425  * in mbuf chain must be small enough to send all at once.
1426  *
1427  * Returns nonzero on error, timeout or signal; callers must check for short
1428  * counts if EINTR/ERESTART are returned.  Data and control buffers are freed
1429  * on return.
1430  */
1431 int
1432 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1433     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1434 {
1435         long space;
1436         ssize_t resid;
1437         int clen = 0, error, dontroute;
1438         int atomic = sosendallatonce(so) || top;
1439
1440         if (uio != NULL)
1441                 resid = uio->uio_resid;
1442         else
1443                 resid = top->m_pkthdr.len;
1444         /*
1445          * In theory resid should be unsigned.  However, space must be
1446          * signed, as it might be less than 0 if we over-committed, and we
1447          * must use a signed comparison of space and resid.  On the other
1448          * hand, a negative resid causes us to loop sending 0-length
1449          * segments to the protocol.
1450          *
1451          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1452          * type sockets since that's an error.
1453          */
1454         if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1455                 error = EINVAL;
1456                 goto out;
1457         }
1458
1459         dontroute =
1460             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1461             (so->so_proto->pr_flags & PR_ATOMIC);
1462         if (td != NULL)
1463                 td->td_ru.ru_msgsnd++;
1464         if (control != NULL)
1465                 clen = control->m_len;
1466
1467         error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1468         if (error)
1469                 goto out;
1470
1471 restart:
1472         do {
1473                 SOCKBUF_LOCK(&so->so_snd);
1474                 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1475                         SOCKBUF_UNLOCK(&so->so_snd);
1476                         error = EPIPE;
1477                         goto release;
1478                 }
1479                 if (so->so_error) {
1480                         error = so->so_error;
1481                         so->so_error = 0;
1482                         SOCKBUF_UNLOCK(&so->so_snd);
1483                         goto release;
1484                 }
1485                 if ((so->so_state & SS_ISCONNECTED) == 0) {
1486                         /*
1487                          * `sendto' and `sendmsg' is allowed on a connection-
1488                          * based socket if it supports implied connect.
1489                          * Return ENOTCONN if not connected and no address is
1490                          * supplied.
1491                          */
1492                         if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1493                             (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1494                                 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1495                                     !(resid == 0 && clen != 0)) {
1496                                         SOCKBUF_UNLOCK(&so->so_snd);
1497                                         error = ENOTCONN;
1498                                         goto release;
1499                                 }
1500                         } else if (addr == NULL) {
1501                                 SOCKBUF_UNLOCK(&so->so_snd);
1502                                 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1503                                         error = ENOTCONN;
1504                                 else
1505                                         error = EDESTADDRREQ;
1506                                 goto release;
1507                         }
1508                 }
1509                 space = sbspace(&so->so_snd);
1510                 if (flags & MSG_OOB)
1511                         space += 1024;
1512                 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1513                     clen > so->so_snd.sb_hiwat) {
1514                         SOCKBUF_UNLOCK(&so->so_snd);
1515                         error = EMSGSIZE;
1516                         goto release;
1517                 }
1518                 if (space < resid + clen &&
1519                     (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1520                         if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1521                                 SOCKBUF_UNLOCK(&so->so_snd);
1522                                 error = EWOULDBLOCK;
1523                                 goto release;
1524                         }
1525                         error = sbwait(&so->so_snd);
1526                         SOCKBUF_UNLOCK(&so->so_snd);
1527                         if (error)
1528                                 goto release;
1529                         goto restart;
1530                 }
1531                 SOCKBUF_UNLOCK(&so->so_snd);
1532                 space -= clen;
1533                 do {
1534                         if (uio == NULL) {
1535                                 resid = 0;
1536                                 if (flags & MSG_EOR)
1537                                         top->m_flags |= M_EOR;
1538                         } else {
1539                                 /*
1540                                  * Copy the data from userland into a mbuf
1541                                  * chain.  If resid is 0, which can happen
1542                                  * only if we have control to send, then
1543                                  * a single empty mbuf is returned.  This
1544                                  * is a workaround to prevent protocol send
1545                                  * methods to panic.
1546                                  */
1547                                 top = m_uiotombuf(uio, M_WAITOK, space,
1548                                     (atomic ? max_hdr : 0),
1549                                     (atomic ? M_PKTHDR : 0) |
1550                                     ((flags & MSG_EOR) ? M_EOR : 0));
1551                                 if (top == NULL) {
1552                                         error = EFAULT; /* only possible error */
1553                                         goto release;
1554                                 }
1555                                 space -= resid - uio->uio_resid;
1556                                 resid = uio->uio_resid;
1557                         }
1558                         if (dontroute) {
1559                                 SOCK_LOCK(so);
1560                                 so->so_options |= SO_DONTROUTE;
1561                                 SOCK_UNLOCK(so);
1562                         }
1563                         /*
1564                          * XXX all the SBS_CANTSENDMORE checks previously
1565                          * done could be out of date.  We could have received
1566                          * a reset packet in an interrupt or maybe we slept
1567                          * while doing page faults in uiomove() etc.  We
1568                          * could probably recheck again inside the locking
1569                          * protection here, but there are probably other
1570                          * places that this also happens.  We must rethink
1571                          * this.
1572                          */
1573                         VNET_SO_ASSERT(so);
1574                         error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1575                             (flags & MSG_OOB) ? PRUS_OOB :
1576                         /*
1577                          * If the user set MSG_EOF, the protocol understands
1578                          * this flag and nothing left to send then use
1579                          * PRU_SEND_EOF instead of PRU_SEND.
1580                          */
1581                             ((flags & MSG_EOF) &&
1582                              (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1583                              (resid <= 0)) ?
1584                                 PRUS_EOF :
1585                         /* If there is more to send set PRUS_MORETOCOME. */
1586                             (flags & MSG_MORETOCOME) ||
1587                             (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1588                             top, addr, control, td);
1589                         if (dontroute) {
1590                                 SOCK_LOCK(so);
1591                                 so->so_options &= ~SO_DONTROUTE;
1592                                 SOCK_UNLOCK(so);
1593                         }
1594                         clen = 0;
1595                         control = NULL;
1596                         top = NULL;
1597                         if (error)
1598                                 goto release;
1599                 } while (resid && space > 0);
1600         } while (resid);
1601
1602 release:
1603         sbunlock(&so->so_snd);
1604 out:
1605         if (top != NULL)
1606                 m_freem(top);
1607         if (control != NULL)
1608                 m_freem(control);
1609         return (error);
1610 }
1611
1612 int
1613 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1614     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1615 {
1616         int error;
1617
1618         CURVNET_SET(so->so_vnet);
1619         if (!SOLISTENING(so))
1620                 error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio,
1621                     top, control, flags, td);
1622         else {
1623                 m_freem(top);
1624                 m_freem(control);
1625                 error = ENOTCONN;
1626         }
1627         CURVNET_RESTORE();
1628         return (error);
1629 }
1630
1631 /*
1632  * The part of soreceive() that implements reading non-inline out-of-band
1633  * data from a socket.  For more complete comments, see soreceive(), from
1634  * which this code originated.
1635  *
1636  * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1637  * unable to return an mbuf chain to the caller.
1638  */
1639 static int
1640 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1641 {
1642         struct protosw *pr = so->so_proto;
1643         struct mbuf *m;
1644         int error;
1645
1646         KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1647         VNET_SO_ASSERT(so);
1648
1649         m = m_get(M_WAITOK, MT_DATA);
1650         error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1651         if (error)
1652                 goto bad;
1653         do {
1654                 error = uiomove(mtod(m, void *),
1655                     (int) min(uio->uio_resid, m->m_len), uio);
1656                 m = m_free(m);
1657         } while (uio->uio_resid && error == 0 && m);
1658 bad:
1659         if (m != NULL)
1660                 m_freem(m);
1661         return (error);
1662 }
1663
1664 /*
1665  * Following replacement or removal of the first mbuf on the first mbuf chain
1666  * of a socket buffer, push necessary state changes back into the socket
1667  * buffer so that other consumers see the values consistently.  'nextrecord'
1668  * is the callers locally stored value of the original value of
1669  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1670  * NOTE: 'nextrecord' may be NULL.
1671  */
1672 static __inline void
1673 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1674 {
1675
1676         SOCKBUF_LOCK_ASSERT(sb);
1677         /*
1678          * First, update for the new value of nextrecord.  If necessary, make
1679          * it the first record.
1680          */
1681         if (sb->sb_mb != NULL)
1682                 sb->sb_mb->m_nextpkt = nextrecord;
1683         else
1684                 sb->sb_mb = nextrecord;
1685
1686         /*
1687          * Now update any dependent socket buffer fields to reflect the new
1688          * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
1689          * addition of a second clause that takes care of the case where
1690          * sb_mb has been updated, but remains the last record.
1691          */
1692         if (sb->sb_mb == NULL) {
1693                 sb->sb_mbtail = NULL;
1694                 sb->sb_lastrecord = NULL;
1695         } else if (sb->sb_mb->m_nextpkt == NULL)
1696                 sb->sb_lastrecord = sb->sb_mb;
1697 }
1698
1699 /*
1700  * Implement receive operations on a socket.  We depend on the way that
1701  * records are added to the sockbuf by sbappend.  In particular, each record
1702  * (mbufs linked through m_next) must begin with an address if the protocol
1703  * so specifies, followed by an optional mbuf or mbufs containing ancillary
1704  * data, and then zero or more mbufs of data.  In order to allow parallelism
1705  * between network receive and copying to user space, as well as avoid
1706  * sleeping with a mutex held, we release the socket buffer mutex during the
1707  * user space copy.  Although the sockbuf is locked, new data may still be
1708  * appended, and thus we must maintain consistency of the sockbuf during that
1709  * time.
1710  *
1711  * The caller may receive the data as a single mbuf chain by supplying an
1712  * mbuf **mp0 for use in returning the chain.  The uio is then used only for
1713  * the count in uio_resid.
1714  */
1715 int
1716 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1717     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1718 {
1719         struct mbuf *m, **mp;
1720         int flags, error, offset;
1721         ssize_t len;
1722         struct protosw *pr = so->so_proto;
1723         struct mbuf *nextrecord;
1724         int moff, type = 0;
1725         ssize_t orig_resid = uio->uio_resid;
1726
1727         mp = mp0;
1728         if (psa != NULL)
1729                 *psa = NULL;
1730         if (controlp != NULL)
1731                 *controlp = NULL;
1732         if (flagsp != NULL)
1733                 flags = *flagsp &~ MSG_EOR;
1734         else
1735                 flags = 0;
1736         if (flags & MSG_OOB)
1737                 return (soreceive_rcvoob(so, uio, flags));
1738         if (mp != NULL)
1739                 *mp = NULL;
1740         if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1741             && uio->uio_resid) {
1742                 VNET_SO_ASSERT(so);
1743                 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1744         }
1745
1746         error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1747         if (error)
1748                 return (error);
1749
1750 restart:
1751         SOCKBUF_LOCK(&so->so_rcv);
1752         m = so->so_rcv.sb_mb;
1753         /*
1754          * If we have less data than requested, block awaiting more (subject
1755          * to any timeout) if:
1756          *   1. the current count is less than the low water mark, or
1757          *   2. MSG_DONTWAIT is not set
1758          */
1759         if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1760             sbavail(&so->so_rcv) < uio->uio_resid) &&
1761             sbavail(&so->so_rcv) < so->so_rcv.sb_lowat &&
1762             m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1763                 KASSERT(m != NULL || !sbavail(&so->so_rcv),
1764                     ("receive: m == %p sbavail == %u",
1765                     m, sbavail(&so->so_rcv)));
1766                 if (so->so_error) {
1767                         if (m != NULL)
1768                                 goto dontblock;
1769                         error = so->so_error;
1770                         if ((flags & MSG_PEEK) == 0)
1771                                 so->so_error = 0;
1772                         SOCKBUF_UNLOCK(&so->so_rcv);
1773                         goto release;
1774                 }
1775                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1776                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1777                         if (m == NULL) {
1778                                 SOCKBUF_UNLOCK(&so->so_rcv);
1779                                 goto release;
1780                         } else
1781                                 goto dontblock;
1782                 }
1783                 for (; m != NULL; m = m->m_next)
1784                         if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1785                                 m = so->so_rcv.sb_mb;
1786                                 goto dontblock;
1787                         }
1788                 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1789                     (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1790                         SOCKBUF_UNLOCK(&so->so_rcv);
1791                         error = ENOTCONN;
1792                         goto release;
1793                 }
1794                 if (uio->uio_resid == 0) {
1795                         SOCKBUF_UNLOCK(&so->so_rcv);
1796                         goto release;
1797                 }
1798                 if ((so->so_state & SS_NBIO) ||
1799                     (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1800                         SOCKBUF_UNLOCK(&so->so_rcv);
1801                         error = EWOULDBLOCK;
1802                         goto release;
1803                 }
1804                 SBLASTRECORDCHK(&so->so_rcv);
1805                 SBLASTMBUFCHK(&so->so_rcv);
1806                 error = sbwait(&so->so_rcv);
1807                 SOCKBUF_UNLOCK(&so->so_rcv);
1808                 if (error)
1809                         goto release;
1810                 goto restart;
1811         }
1812 dontblock:
1813         /*
1814          * From this point onward, we maintain 'nextrecord' as a cache of the
1815          * pointer to the next record in the socket buffer.  We must keep the
1816          * various socket buffer pointers and local stack versions of the
1817          * pointers in sync, pushing out modifications before dropping the
1818          * socket buffer mutex, and re-reading them when picking it up.
1819          *
1820          * Otherwise, we will race with the network stack appending new data
1821          * or records onto the socket buffer by using inconsistent/stale
1822          * versions of the field, possibly resulting in socket buffer
1823          * corruption.
1824          *
1825          * By holding the high-level sblock(), we prevent simultaneous
1826          * readers from pulling off the front of the socket buffer.
1827          */
1828         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1829         if (uio->uio_td)
1830                 uio->uio_td->td_ru.ru_msgrcv++;
1831         KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1832         SBLASTRECORDCHK(&so->so_rcv);
1833         SBLASTMBUFCHK(&so->so_rcv);
1834         nextrecord = m->m_nextpkt;
1835         if (pr->pr_flags & PR_ADDR) {
1836                 KASSERT(m->m_type == MT_SONAME,
1837                     ("m->m_type == %d", m->m_type));
1838                 orig_resid = 0;
1839                 if (psa != NULL)
1840                         *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1841                             M_NOWAIT);
1842                 if (flags & MSG_PEEK) {
1843                         m = m->m_next;
1844                 } else {
1845                         sbfree(&so->so_rcv, m);
1846                         so->so_rcv.sb_mb = m_free(m);
1847                         m = so->so_rcv.sb_mb;
1848                         sockbuf_pushsync(&so->so_rcv, nextrecord);
1849                 }
1850         }
1851
1852         /*
1853          * Process one or more MT_CONTROL mbufs present before any data mbufs
1854          * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1855          * just copy the data; if !MSG_PEEK, we call into the protocol to
1856          * perform externalization (or freeing if controlp == NULL).
1857          */
1858         if (m != NULL && m->m_type == MT_CONTROL) {
1859                 struct mbuf *cm = NULL, *cmn;
1860                 struct mbuf **cme = &cm;
1861
1862                 do {
1863                         if (flags & MSG_PEEK) {
1864                                 if (controlp != NULL) {
1865                                         *controlp = m_copym(m, 0, m->m_len,
1866                                             M_NOWAIT);
1867                                         controlp = &(*controlp)->m_next;
1868                                 }
1869                                 m = m->m_next;
1870                         } else {
1871                                 sbfree(&so->so_rcv, m);
1872                                 so->so_rcv.sb_mb = m->m_next;
1873                                 m->m_next = NULL;
1874                                 *cme = m;
1875                                 cme = &(*cme)->m_next;
1876                                 m = so->so_rcv.sb_mb;
1877                         }
1878                 } while (m != NULL && m->m_type == MT_CONTROL);
1879                 if ((flags & MSG_PEEK) == 0)
1880                         sockbuf_pushsync(&so->so_rcv, nextrecord);
1881                 while (cm != NULL) {
1882                         cmn = cm->m_next;
1883                         cm->m_next = NULL;
1884                         if (pr->pr_domain->dom_externalize != NULL) {
1885                                 SOCKBUF_UNLOCK(&so->so_rcv);
1886                                 VNET_SO_ASSERT(so);
1887                                 error = (*pr->pr_domain->dom_externalize)
1888                                     (cm, controlp, flags);
1889                                 SOCKBUF_LOCK(&so->so_rcv);
1890                         } else if (controlp != NULL)
1891                                 *controlp = cm;
1892                         else
1893                                 m_freem(cm);
1894                         if (controlp != NULL) {
1895                                 orig_resid = 0;
1896                                 while (*controlp != NULL)
1897                                         controlp = &(*controlp)->m_next;
1898                         }
1899                         cm = cmn;
1900                 }
1901                 if (m != NULL)
1902                         nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1903                 else
1904                         nextrecord = so->so_rcv.sb_mb;
1905                 orig_resid = 0;
1906         }
1907         if (m != NULL) {
1908                 if ((flags & MSG_PEEK) == 0) {
1909                         KASSERT(m->m_nextpkt == nextrecord,
1910                             ("soreceive: post-control, nextrecord !sync"));
1911                         if (nextrecord == NULL) {
1912                                 KASSERT(so->so_rcv.sb_mb == m,
1913                                     ("soreceive: post-control, sb_mb!=m"));
1914                                 KASSERT(so->so_rcv.sb_lastrecord == m,
1915                                     ("soreceive: post-control, lastrecord!=m"));
1916                         }
1917                 }
1918                 type = m->m_type;
1919                 if (type == MT_OOBDATA)
1920                         flags |= MSG_OOB;
1921         } else {
1922                 if ((flags & MSG_PEEK) == 0) {
1923                         KASSERT(so->so_rcv.sb_mb == nextrecord,
1924                             ("soreceive: sb_mb != nextrecord"));
1925                         if (so->so_rcv.sb_mb == NULL) {
1926                                 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1927                                     ("soreceive: sb_lastercord != NULL"));
1928                         }
1929                 }
1930         }
1931         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1932         SBLASTRECORDCHK(&so->so_rcv);
1933         SBLASTMBUFCHK(&so->so_rcv);
1934
1935         /*
1936          * Now continue to read any data mbufs off of the head of the socket
1937          * buffer until the read request is satisfied.  Note that 'type' is
1938          * used to store the type of any mbuf reads that have happened so far
1939          * such that soreceive() can stop reading if the type changes, which
1940          * causes soreceive() to return only one of regular data and inline
1941          * out-of-band data in a single socket receive operation.
1942          */
1943         moff = 0;
1944         offset = 0;
1945         while (m != NULL && !(m->m_flags & M_NOTAVAIL) && uio->uio_resid > 0
1946             && error == 0) {
1947                 /*
1948                  * If the type of mbuf has changed since the last mbuf
1949                  * examined ('type'), end the receive operation.
1950                  */
1951                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1952                 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
1953                         if (type != m->m_type)
1954                                 break;
1955                 } else if (type == MT_OOBDATA)
1956                         break;
1957                 else
1958                     KASSERT(m->m_type == MT_DATA,
1959                         ("m->m_type == %d", m->m_type));
1960                 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1961                 len = uio->uio_resid;
1962                 if (so->so_oobmark && len > so->so_oobmark - offset)
1963                         len = so->so_oobmark - offset;
1964                 if (len > m->m_len - moff)
1965                         len = m->m_len - moff;
1966                 /*
1967                  * If mp is set, just pass back the mbufs.  Otherwise copy
1968                  * them out via the uio, then free.  Sockbuf must be
1969                  * consistent here (points to current mbuf, it points to next
1970                  * record) when we drop priority; we must note any additions
1971                  * to the sockbuf when we block interrupts again.
1972                  */
1973                 if (mp == NULL) {
1974                         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1975                         SBLASTRECORDCHK(&so->so_rcv);
1976                         SBLASTMBUFCHK(&so->so_rcv);
1977                         SOCKBUF_UNLOCK(&so->so_rcv);
1978                         error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1979                         SOCKBUF_LOCK(&so->so_rcv);
1980                         if (error) {
1981                                 /*
1982                                  * The MT_SONAME mbuf has already been removed
1983                                  * from the record, so it is necessary to
1984                                  * remove the data mbufs, if any, to preserve
1985                                  * the invariant in the case of PR_ADDR that
1986                                  * requires MT_SONAME mbufs at the head of
1987                                  * each record.
1988                                  */
1989                                 if (pr->pr_flags & PR_ATOMIC &&
1990                                     ((flags & MSG_PEEK) == 0))
1991                                         (void)sbdroprecord_locked(&so->so_rcv);
1992                                 SOCKBUF_UNLOCK(&so->so_rcv);
1993                                 goto release;
1994                         }
1995                 } else
1996                         uio->uio_resid -= len;
1997                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1998                 if (len == m->m_len - moff) {
1999                         if (m->m_flags & M_EOR)
2000                                 flags |= MSG_EOR;
2001                         if (flags & MSG_PEEK) {
2002                                 m = m->m_next;
2003                                 moff = 0;
2004                         } else {
2005                                 nextrecord = m->m_nextpkt;
2006                                 sbfree(&so->so_rcv, m);
2007                                 if (mp != NULL) {
2008                                         m->m_nextpkt = NULL;
2009                                         *mp = m;
2010                                         mp = &m->m_next;
2011                                         so->so_rcv.sb_mb = m = m->m_next;
2012                                         *mp = NULL;
2013                                 } else {
2014                                         so->so_rcv.sb_mb = m_free(m);
2015                                         m = so->so_rcv.sb_mb;
2016                                 }
2017                                 sockbuf_pushsync(&so->so_rcv, nextrecord);
2018                                 SBLASTRECORDCHK(&so->so_rcv);
2019                                 SBLASTMBUFCHK(&so->so_rcv);
2020                         }
2021                 } else {
2022                         if (flags & MSG_PEEK)
2023                                 moff += len;
2024                         else {
2025                                 if (mp != NULL) {
2026                                         if (flags & MSG_DONTWAIT) {
2027                                                 *mp = m_copym(m, 0, len,
2028                                                     M_NOWAIT);
2029                                                 if (*mp == NULL) {
2030                                                         /*
2031                                                          * m_copym() couldn't
2032                                                          * allocate an mbuf.
2033                                                          * Adjust uio_resid back
2034                                                          * (it was adjusted
2035                                                          * down by len bytes,
2036                                                          * which we didn't end
2037                                                          * up "copying" over).
2038                                                          */
2039                                                         uio->uio_resid += len;
2040                                                         break;
2041                                                 }
2042                                         } else {
2043                                                 SOCKBUF_UNLOCK(&so->so_rcv);
2044                                                 *mp = m_copym(m, 0, len,
2045                                                     M_WAITOK);
2046                                                 SOCKBUF_LOCK(&so->so_rcv);
2047                                         }
2048                                 }
2049                                 sbcut_locked(&so->so_rcv, len);
2050                         }
2051                 }
2052                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2053                 if (so->so_oobmark) {
2054                         if ((flags & MSG_PEEK) == 0) {
2055                                 so->so_oobmark -= len;
2056                                 if (so->so_oobmark == 0) {
2057                                         so->so_rcv.sb_state |= SBS_RCVATMARK;
2058                                         break;
2059                                 }
2060                         } else {
2061                                 offset += len;
2062                                 if (offset == so->so_oobmark)
2063                                         break;
2064                         }
2065                 }
2066                 if (flags & MSG_EOR)
2067                         break;
2068                 /*
2069                  * If the MSG_WAITALL flag is set (for non-atomic socket), we
2070                  * must not quit until "uio->uio_resid == 0" or an error
2071                  * termination.  If a signal/timeout occurs, return with a
2072                  * short count but without error.  Keep sockbuf locked
2073                  * against other readers.
2074                  */
2075                 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
2076                     !sosendallatonce(so) && nextrecord == NULL) {
2077                         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2078                         if (so->so_error ||
2079                             so->so_rcv.sb_state & SBS_CANTRCVMORE)
2080                                 break;
2081                         /*
2082                          * Notify the protocol that some data has been
2083                          * drained before blocking.
2084                          */
2085                         if (pr->pr_flags & PR_WANTRCVD) {
2086                                 SOCKBUF_UNLOCK(&so->so_rcv);
2087                                 VNET_SO_ASSERT(so);
2088                                 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
2089                                 SOCKBUF_LOCK(&so->so_rcv);
2090                         }
2091                         SBLASTRECORDCHK(&so->so_rcv);
2092                         SBLASTMBUFCHK(&so->so_rcv);
2093                         /*
2094                          * We could receive some data while was notifying
2095                          * the protocol. Skip blocking in this case.
2096                          */
2097                         if (so->so_rcv.sb_mb == NULL) {
2098                                 error = sbwait(&so->so_rcv);
2099                                 if (error) {
2100                                         SOCKBUF_UNLOCK(&so->so_rcv);
2101                                         goto release;
2102                                 }
2103                         }
2104                         m = so->so_rcv.sb_mb;
2105                         if (m != NULL)
2106                                 nextrecord = m->m_nextpkt;
2107                 }
2108         }
2109
2110         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2111         if (m != NULL && pr->pr_flags & PR_ATOMIC) {
2112                 flags |= MSG_TRUNC;
2113                 if ((flags & MSG_PEEK) == 0)
2114                         (void) sbdroprecord_locked(&so->so_rcv);
2115         }
2116         if ((flags & MSG_PEEK) == 0) {
2117                 if (m == NULL) {
2118                         /*
2119                          * First part is an inline SB_EMPTY_FIXUP().  Second
2120                          * part makes sure sb_lastrecord is up-to-date if
2121                          * there is still data in the socket buffer.
2122                          */
2123                         so->so_rcv.sb_mb = nextrecord;
2124                         if (so->so_rcv.sb_mb == NULL) {
2125                                 so->so_rcv.sb_mbtail = NULL;
2126                                 so->so_rcv.sb_lastrecord = NULL;
2127                         } else if (nextrecord->m_nextpkt == NULL)
2128                                 so->so_rcv.sb_lastrecord = nextrecord;
2129                 }
2130                 SBLASTRECORDCHK(&so->so_rcv);
2131                 SBLASTMBUFCHK(&so->so_rcv);
2132                 /*
2133                  * If soreceive() is being done from the socket callback,
2134                  * then don't need to generate ACK to peer to update window,
2135                  * since ACK will be generated on return to TCP.
2136                  */
2137                 if (!(flags & MSG_SOCALLBCK) &&
2138                     (pr->pr_flags & PR_WANTRCVD)) {
2139                         SOCKBUF_UNLOCK(&so->so_rcv);
2140                         VNET_SO_ASSERT(so);
2141                         (*pr->pr_usrreqs->pru_rcvd)(so, flags);
2142                         SOCKBUF_LOCK(&so->so_rcv);
2143                 }
2144         }
2145         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2146         if (orig_resid == uio->uio_resid && orig_resid &&
2147             (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
2148                 SOCKBUF_UNLOCK(&so->so_rcv);
2149                 goto restart;
2150         }
2151         SOCKBUF_UNLOCK(&so->so_rcv);
2152
2153         if (flagsp != NULL)
2154                 *flagsp |= flags;
2155 release:
2156         sbunlock(&so->so_rcv);
2157         return (error);
2158 }
2159
2160 /*
2161  * Optimized version of soreceive() for stream (TCP) sockets.
2162  * XXXAO: (MSG_WAITALL | MSG_PEEK) isn't properly handled.
2163  */
2164 int
2165 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
2166     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2167 {
2168         int len = 0, error = 0, flags, oresid;
2169         struct sockbuf *sb;
2170         struct mbuf *m, *n = NULL;
2171
2172         /* We only do stream sockets. */
2173         if (so->so_type != SOCK_STREAM)
2174                 return (EINVAL);
2175         if (psa != NULL)
2176                 *psa = NULL;
2177         if (controlp != NULL)
2178                 return (EINVAL);
2179         if (flagsp != NULL)
2180                 flags = *flagsp &~ MSG_EOR;
2181         else
2182                 flags = 0;
2183         if (flags & MSG_OOB)
2184                 return (soreceive_rcvoob(so, uio, flags));
2185         if (mp0 != NULL)
2186                 *mp0 = NULL;
2187
2188         sb = &so->so_rcv;
2189
2190         /* Prevent other readers from entering the socket. */
2191         error = sblock(sb, SBLOCKWAIT(flags));
2192         if (error)
2193                 goto out;
2194         SOCKBUF_LOCK(sb);
2195
2196         /* Easy one, no space to copyout anything. */
2197         if (uio->uio_resid == 0) {
2198                 error = EINVAL;
2199                 goto out;
2200         }
2201         oresid = uio->uio_resid;
2202
2203         /* We will never ever get anything unless we are or were connected. */
2204         if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
2205                 error = ENOTCONN;
2206                 goto out;
2207         }
2208
2209 restart:
2210         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2211
2212         /* Abort if socket has reported problems. */
2213         if (so->so_error) {
2214                 if (sbavail(sb) > 0)
2215                         goto deliver;
2216                 if (oresid > uio->uio_resid)
2217                         goto out;
2218                 error = so->so_error;
2219                 if (!(flags & MSG_PEEK))
2220                         so->so_error = 0;
2221                 goto out;
2222         }
2223
2224         /* Door is closed.  Deliver what is left, if any. */
2225         if (sb->sb_state & SBS_CANTRCVMORE) {
2226                 if (sbavail(sb) > 0)
2227                         goto deliver;
2228                 else
2229                         goto out;
2230         }
2231
2232         /* Socket buffer is empty and we shall not block. */
2233         if (sbavail(sb) == 0 &&
2234             ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2235                 error = EAGAIN;
2236                 goto out;
2237         }
2238
2239         /* Socket buffer got some data that we shall deliver now. */
2240         if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
2241             ((so->so_state & SS_NBIO) ||
2242              (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2243              sbavail(sb) >= sb->sb_lowat ||
2244              sbavail(sb) >= uio->uio_resid ||
2245              sbavail(sb) >= sb->sb_hiwat) ) {
2246                 goto deliver;
2247         }
2248
2249         /* On MSG_WAITALL we must wait until all data or error arrives. */
2250         if ((flags & MSG_WAITALL) &&
2251             (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
2252                 goto deliver;
2253
2254         /*
2255          * Wait and block until (more) data comes in.
2256          * NB: Drops the sockbuf lock during wait.
2257          */
2258         error = sbwait(sb);
2259         if (error)
2260                 goto out;
2261         goto restart;
2262
2263 deliver:
2264         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2265         KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
2266         KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2267
2268         /* Statistics. */
2269         if (uio->uio_td)
2270                 uio->uio_td->td_ru.ru_msgrcv++;
2271
2272         /* Fill uio until full or current end of socket buffer is reached. */
2273         len = min(uio->uio_resid, sbavail(sb));
2274         if (mp0 != NULL) {
2275                 /* Dequeue as many mbufs as possible. */
2276                 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2277                         if (*mp0 == NULL)
2278                                 *mp0 = sb->sb_mb;
2279                         else
2280                                 m_cat(*mp0, sb->sb_mb);
2281                         for (m = sb->sb_mb;
2282                              m != NULL && m->m_len <= len;
2283                              m = m->m_next) {
2284                                 KASSERT(!(m->m_flags & M_NOTAVAIL),
2285                                     ("%s: m %p not available", __func__, m));
2286                                 len -= m->m_len;
2287                                 uio->uio_resid -= m->m_len;
2288                                 sbfree(sb, m);
2289                                 n = m;
2290                         }
2291                         n->m_next = NULL;
2292                         sb->sb_mb = m;
2293                         sb->sb_lastrecord = sb->sb_mb;
2294                         if (sb->sb_mb == NULL)
2295                                 SB_EMPTY_FIXUP(sb);
2296                 }
2297                 /* Copy the remainder. */
2298                 if (len > 0) {
2299                         KASSERT(sb->sb_mb != NULL,
2300                             ("%s: len > 0 && sb->sb_mb empty", __func__));
2301
2302                         m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
2303                         if (m == NULL)
2304                                 len = 0;        /* Don't flush data from sockbuf. */
2305                         else
2306                                 uio->uio_resid -= len;
2307                         if (*mp0 != NULL)
2308                                 m_cat(*mp0, m);
2309                         else
2310                                 *mp0 = m;
2311                         if (*mp0 == NULL) {
2312                                 error = ENOBUFS;
2313                                 goto out;
2314                         }
2315                 }
2316         } else {
2317                 /* NB: Must unlock socket buffer as uiomove may sleep. */
2318                 SOCKBUF_UNLOCK(sb);
2319                 error = m_mbuftouio(uio, sb->sb_mb, len);
2320                 SOCKBUF_LOCK(sb);
2321                 if (error)
2322                         goto out;
2323         }
2324         SBLASTRECORDCHK(sb);
2325         SBLASTMBUFCHK(sb);
2326
2327         /*
2328          * Remove the delivered data from the socket buffer unless we
2329          * were only peeking.
2330          */
2331         if (!(flags & MSG_PEEK)) {
2332                 if (len > 0)
2333                         sbdrop_locked(sb, len);
2334
2335                 /* Notify protocol that we drained some data. */
2336                 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2337                     (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2338                      !(flags & MSG_SOCALLBCK))) {
2339                         SOCKBUF_UNLOCK(sb);
2340                         VNET_SO_ASSERT(so);
2341                         (*so->so_proto->pr_usrreqs->pru_rcvd)(so, flags);
2342                         SOCKBUF_LOCK(sb);
2343                 }
2344         }
2345
2346         /*
2347          * For MSG_WAITALL we may have to loop again and wait for
2348          * more data to come in.
2349          */
2350         if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2351                 goto restart;
2352 out:
2353         SOCKBUF_LOCK_ASSERT(sb);
2354         SBLASTRECORDCHK(sb);
2355         SBLASTMBUFCHK(sb);
2356         SOCKBUF_UNLOCK(sb);
2357         sbunlock(sb);
2358         return (error);
2359 }
2360
2361 /*
2362  * Optimized version of soreceive() for simple datagram cases from userspace.
2363  * Unlike in the stream case, we're able to drop a datagram if copyout()
2364  * fails, and because we handle datagrams atomically, we don't need to use a
2365  * sleep lock to prevent I/O interlacing.
2366  */
2367 int
2368 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2369     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2370 {
2371         struct mbuf *m, *m2;
2372         int flags, error;
2373         ssize_t len;
2374         struct protosw *pr = so->so_proto;
2375         struct mbuf *nextrecord;
2376
2377         if (psa != NULL)
2378                 *psa = NULL;
2379         if (controlp != NULL)
2380                 *controlp = NULL;
2381         if (flagsp != NULL)
2382                 flags = *flagsp &~ MSG_EOR;
2383         else
2384                 flags = 0;
2385
2386         /*
2387          * For any complicated cases, fall back to the full
2388          * soreceive_generic().
2389          */
2390         if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
2391                 return (soreceive_generic(so, psa, uio, mp0, controlp,
2392                     flagsp));
2393
2394         /*
2395          * Enforce restrictions on use.
2396          */
2397         KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2398             ("soreceive_dgram: wantrcvd"));
2399         KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2400         KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2401             ("soreceive_dgram: SBS_RCVATMARK"));
2402         KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2403             ("soreceive_dgram: P_CONNREQUIRED"));
2404
2405         /*
2406          * Loop blocking while waiting for a datagram.
2407          */
2408         SOCKBUF_LOCK(&so->so_rcv);
2409         while ((m = so->so_rcv.sb_mb) == NULL) {
2410                 KASSERT(sbavail(&so->so_rcv) == 0,
2411                     ("soreceive_dgram: sb_mb NULL but sbavail %u",
2412                     sbavail(&so->so_rcv)));
2413                 if (so->so_error) {
2414                         error = so->so_error;
2415                         so->so_error = 0;
2416                         SOCKBUF_UNLOCK(&so->so_rcv);
2417                         return (error);
2418                 }
2419                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2420                     uio->uio_resid == 0) {
2421                         SOCKBUF_UNLOCK(&so->so_rcv);
2422                         return (0);
2423                 }
2424                 if ((so->so_state & SS_NBIO) ||
2425                     (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2426                         SOCKBUF_UNLOCK(&so->so_rcv);
2427                         return (EWOULDBLOCK);
2428                 }
2429                 SBLASTRECORDCHK(&so->so_rcv);
2430                 SBLASTMBUFCHK(&so->so_rcv);
2431                 error = sbwait(&so->so_rcv);
2432                 if (error) {
2433                         SOCKBUF_UNLOCK(&so->so_rcv);
2434                         return (error);
2435                 }
2436         }
2437         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2438
2439         if (uio->uio_td)
2440                 uio->uio_td->td_ru.ru_msgrcv++;
2441         SBLASTRECORDCHK(&so->so_rcv);
2442         SBLASTMBUFCHK(&so->so_rcv);
2443         nextrecord = m->m_nextpkt;
2444         if (nextrecord == NULL) {
2445                 KASSERT(so->so_rcv.sb_lastrecord == m,
2446                     ("soreceive_dgram: lastrecord != m"));
2447         }
2448
2449         KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2450             ("soreceive_dgram: m_nextpkt != nextrecord"));
2451
2452         /*
2453          * Pull 'm' and its chain off the front of the packet queue.
2454          */
2455         so->so_rcv.sb_mb = NULL;
2456         sockbuf_pushsync(&so->so_rcv, nextrecord);
2457
2458         /*
2459          * Walk 'm's chain and free that many bytes from the socket buffer.
2460          */
2461         for (m2 = m; m2 != NULL; m2 = m2->m_next)
2462                 sbfree(&so->so_rcv, m2);
2463
2464         /*
2465          * Do a few last checks before we let go of the lock.
2466          */
2467         SBLASTRECORDCHK(&so->so_rcv);
2468         SBLASTMBUFCHK(&so->so_rcv);
2469         SOCKBUF_UNLOCK(&so->so_rcv);
2470
2471         if (pr->pr_flags & PR_ADDR) {
2472                 KASSERT(m->m_type == MT_SONAME,
2473                     ("m->m_type == %d", m->m_type));
2474                 if (psa != NULL)
2475                         *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2476                             M_NOWAIT);
2477                 m = m_free(m);
2478         }
2479         if (m == NULL) {
2480                 /* XXXRW: Can this happen? */
2481                 return (0);
2482         }
2483
2484         /*
2485          * Packet to copyout() is now in 'm' and it is disconnected from the
2486          * queue.
2487          *
2488          * Process one or more MT_CONTROL mbufs present before any data mbufs
2489          * in the first mbuf chain on the socket buffer.  We call into the
2490          * protocol to perform externalization (or freeing if controlp ==
2491          * NULL). In some cases there can be only MT_CONTROL mbufs without
2492          * MT_DATA mbufs.
2493          */
2494         if (m->m_type == MT_CONTROL) {
2495                 struct mbuf *cm = NULL, *cmn;
2496                 struct mbuf **cme = &cm;
2497
2498                 do {
2499                         m2 = m->m_next;
2500                         m->m_next = NULL;
2501                         *cme = m;
2502                         cme = &(*cme)->m_next;
2503                         m = m2;
2504                 } while (m != NULL && m->m_type == MT_CONTROL);
2505                 while (cm != NULL) {
2506                         cmn = cm->m_next;
2507                         cm->m_next = NULL;
2508                         if (pr->pr_domain->dom_externalize != NULL) {
2509                                 error = (*pr->pr_domain->dom_externalize)
2510                                     (cm, controlp, flags);
2511                         } else if (controlp != NULL)
2512                                 *controlp = cm;
2513                         else
2514                                 m_freem(cm);
2515                         if (controlp != NULL) {
2516                                 while (*controlp != NULL)
2517                                         controlp = &(*controlp)->m_next;
2518                         }
2519                         cm = cmn;
2520                 }
2521         }
2522         KASSERT(m == NULL || m->m_type == MT_DATA,
2523             ("soreceive_dgram: !data"));
2524         while (m != NULL && uio->uio_resid > 0) {
2525                 len = uio->uio_resid;
2526                 if (len > m->m_len)
2527                         len = m->m_len;
2528                 error = uiomove(mtod(m, char *), (int)len, uio);
2529                 if (error) {
2530                         m_freem(m);
2531                         return (error);
2532                 }
2533                 if (len == m->m_len)
2534                         m = m_free(m);
2535                 else {
2536                         m->m_data += len;
2537                         m->m_len -= len;
2538                 }
2539         }
2540         if (m != NULL) {
2541                 flags |= MSG_TRUNC;
2542                 m_freem(m);
2543         }
2544         if (flagsp != NULL)
2545                 *flagsp |= flags;
2546         return (0);
2547 }
2548
2549 int
2550 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2551     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2552 {
2553         int error;
2554
2555         CURVNET_SET(so->so_vnet);
2556         if (!SOLISTENING(so))
2557                 error = (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio,
2558                     mp0, controlp, flagsp));
2559         else
2560                 error = ENOTCONN;
2561         CURVNET_RESTORE();
2562         return (error);
2563 }
2564
2565 int
2566 soshutdown(struct socket *so, int how)
2567 {
2568         struct protosw *pr = so->so_proto;
2569         int error, soerror_enotconn;
2570
2571         if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2572                 return (EINVAL);
2573
2574         soerror_enotconn = 0;
2575         if ((so->so_state &
2576             (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
2577                 /*
2578                  * POSIX mandates us to return ENOTCONN when shutdown(2) is
2579                  * invoked on a datagram sockets, however historically we would
2580                  * actually tear socket down. This is known to be leveraged by
2581                  * some applications to unblock process waiting in recvXXX(2)
2582                  * by other process that it shares that socket with. Try to meet
2583                  * both backward-compatibility and POSIX requirements by forcing
2584                  * ENOTCONN but still asking protocol to perform pru_shutdown().
2585                  */
2586                 if (so->so_type != SOCK_DGRAM)
2587                         return (ENOTCONN);
2588                 soerror_enotconn = 1;
2589         }
2590
2591         CURVNET_SET(so->so_vnet);
2592         if (pr->pr_usrreqs->pru_flush != NULL)
2593                 (*pr->pr_usrreqs->pru_flush)(so, how);
2594         if (how != SHUT_WR)
2595                 sorflush(so);
2596         if (how != SHUT_RD) {
2597                 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2598                 wakeup(&so->so_timeo);
2599                 CURVNET_RESTORE();
2600                 return ((error == 0 && soerror_enotconn) ? ENOTCONN : error);
2601         }
2602         wakeup(&so->so_timeo);
2603         CURVNET_RESTORE();
2604
2605         return (soerror_enotconn ? ENOTCONN : 0);
2606 }
2607
2608 void
2609 sorflush(struct socket *so)
2610 {
2611         struct sockbuf *sb = &so->so_rcv;
2612         struct protosw *pr = so->so_proto;
2613         struct socket aso;
2614
2615         VNET_SO_ASSERT(so);
2616
2617         /*
2618          * In order to avoid calling dom_dispose with the socket buffer mutex
2619          * held, and in order to generally avoid holding the lock for a long
2620          * time, we make a copy of the socket buffer and clear the original
2621          * (except locks, state).  The new socket buffer copy won't have
2622          * initialized locks so we can only call routines that won't use or
2623          * assert those locks.
2624          *
2625          * Dislodge threads currently blocked in receive and wait to acquire
2626          * a lock against other simultaneous readers before clearing the
2627          * socket buffer.  Don't let our acquire be interrupted by a signal
2628          * despite any existing socket disposition on interruptable waiting.
2629          */
2630         socantrcvmore(so);
2631         (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2632
2633         /*
2634          * Invalidate/clear most of the sockbuf structure, but leave selinfo
2635          * and mutex data unchanged.
2636          */
2637         SOCKBUF_LOCK(sb);
2638         bzero(&aso, sizeof(aso));
2639         aso.so_pcb = so->so_pcb;
2640         bcopy(&sb->sb_startzero, &aso.so_rcv.sb_startzero,
2641             sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2642         bzero(&sb->sb_startzero,
2643             sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2644         SOCKBUF_UNLOCK(sb);
2645         sbunlock(sb);
2646
2647         /*
2648          * Dispose of special rights and flush the copied socket.  Don't call
2649          * any unsafe routines (that rely on locks being initialized) on aso.
2650          */
2651         if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2652                 (*pr->pr_domain->dom_dispose)(&aso);
2653         sbrelease_internal(&aso.so_rcv, so);
2654 }
2655
2656 /*
2657  * Wrapper for Socket established helper hook.
2658  * Parameters: socket, context of the hook point, hook id.
2659  */
2660 static int inline
2661 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
2662 {
2663         struct socket_hhook_data hhook_data = {
2664                 .so = so,
2665                 .hctx = hctx,
2666                 .m = NULL,
2667                 .status = 0
2668         };
2669
2670         CURVNET_SET(so->so_vnet);
2671         HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
2672         CURVNET_RESTORE();
2673
2674         /* Ugly but needed, since hhooks return void for now */
2675         return (hhook_data.status);
2676 }
2677
2678 /*
2679  * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2680  * additional variant to handle the case where the option value needs to be
2681  * some kind of integer, but not a specific size.  In addition to their use
2682  * here, these functions are also called by the protocol-level pr_ctloutput()
2683  * routines.
2684  */
2685 int
2686 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2687 {
2688         size_t  valsize;
2689
2690         /*
2691          * If the user gives us more than we wanted, we ignore it, but if we
2692          * don't get the minimum length the caller wants, we return EINVAL.
2693          * On success, sopt->sopt_valsize is set to however much we actually
2694          * retrieved.
2695          */
2696         if ((valsize = sopt->sopt_valsize) < minlen)
2697                 return EINVAL;
2698         if (valsize > len)
2699                 sopt->sopt_valsize = valsize = len;
2700
2701         if (sopt->sopt_td != NULL)
2702                 return (copyin(sopt->sopt_val, buf, valsize));
2703
2704         bcopy(sopt->sopt_val, buf, valsize);
2705         return (0);
2706 }
2707
2708 /*
2709  * Kernel version of setsockopt(2).
2710  *
2711  * XXX: optlen is size_t, not socklen_t
2712  */
2713 int
2714 so_setsockopt(struct socket *so, int level, int optname, void *optval,
2715     size_t optlen)
2716 {
2717         struct sockopt sopt;
2718
2719         sopt.sopt_level = level;
2720         sopt.sopt_name = optname;
2721         sopt.sopt_dir = SOPT_SET;
2722         sopt.sopt_val = optval;
2723         sopt.sopt_valsize = optlen;
2724         sopt.sopt_td = NULL;
2725         return (sosetopt(so, &sopt));
2726 }
2727
2728 int
2729 sosetopt(struct socket *so, struct sockopt *sopt)
2730 {
2731         int     error, optval;
2732         struct  linger l;
2733         struct  timeval tv;
2734         sbintime_t val;
2735         uint32_t val32;
2736 #ifdef MAC
2737         struct mac extmac;
2738 #endif
2739
2740         CURVNET_SET(so->so_vnet);
2741         error = 0;
2742         if (sopt->sopt_level != SOL_SOCKET) {
2743                 if (so->so_proto->pr_ctloutput != NULL) {
2744                         error = (*so->so_proto->pr_ctloutput)(so, sopt);
2745                         CURVNET_RESTORE();
2746                         return (error);
2747                 }
2748                 error = ENOPROTOOPT;
2749         } else {
2750                 switch (sopt->sopt_name) {
2751                 case SO_ACCEPTFILTER:
2752                         error = accept_filt_setopt(so, sopt);
2753                         if (error)
2754                                 goto bad;
2755                         break;
2756
2757                 case SO_LINGER:
2758                         error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2759                         if (error)
2760                                 goto bad;
2761
2762                         SOCK_LOCK(so);
2763                         so->so_linger = l.l_linger;
2764                         if (l.l_onoff)
2765                                 so->so_options |= SO_LINGER;
2766                         else
2767                                 so->so_options &= ~SO_LINGER;
2768                         SOCK_UNLOCK(so);
2769                         break;
2770
2771                 case SO_DEBUG:
2772                 case SO_KEEPALIVE:
2773                 case SO_DONTROUTE:
2774                 case SO_USELOOPBACK:
2775                 case SO_BROADCAST:
2776                 case SO_REUSEADDR:
2777                 case SO_REUSEPORT:
2778                 case SO_OOBINLINE:
2779                 case SO_TIMESTAMP:
2780                 case SO_BINTIME:
2781                 case SO_NOSIGPIPE:
2782                 case SO_NO_DDP:
2783                 case SO_NO_OFFLOAD:
2784                         error = sooptcopyin(sopt, &optval, sizeof optval,
2785                             sizeof optval);
2786                         if (error)
2787                                 goto bad;
2788                         SOCK_LOCK(so);
2789                         if (optval)
2790                                 so->so_options |= sopt->sopt_name;
2791                         else
2792                                 so->so_options &= ~sopt->sopt_name;
2793                         SOCK_UNLOCK(so);
2794                         break;
2795
2796                 case SO_SETFIB:
2797                         error = sooptcopyin(sopt, &optval, sizeof optval,
2798                             sizeof optval);
2799                         if (error)
2800                                 goto bad;
2801
2802                         if (optval < 0 || optval >= rt_numfibs) {
2803                                 error = EINVAL;
2804                                 goto bad;
2805                         }
2806                         if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
2807                            (so->so_proto->pr_domain->dom_family == PF_INET6) ||
2808                            (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
2809                                 so->so_fibnum = optval;
2810                         else
2811                                 so->so_fibnum = 0;
2812                         break;
2813
2814                 case SO_USER_COOKIE:
2815                         error = sooptcopyin(sopt, &val32, sizeof val32,
2816                             sizeof val32);
2817                         if (error)
2818                                 goto bad;
2819                         so->so_user_cookie = val32;
2820                         break;
2821
2822                 case SO_SNDBUF:
2823                 case SO_RCVBUF:
2824                 case SO_SNDLOWAT:
2825                 case SO_RCVLOWAT:
2826                         error = sooptcopyin(sopt, &optval, sizeof optval,
2827                             sizeof optval);
2828                         if (error)
2829                                 goto bad;
2830
2831                         /*
2832                          * Values < 1 make no sense for any of these options,
2833                          * so disallow them.
2834                          */
2835                         if (optval < 1) {
2836                                 error = EINVAL;
2837                                 goto bad;
2838                         }
2839
2840                         error = sbsetopt(so, sopt->sopt_name, optval);
2841                         break;
2842
2843                 case SO_SNDTIMEO:
2844                 case SO_RCVTIMEO:
2845 #ifdef COMPAT_FREEBSD32
2846                         if (SV_CURPROC_FLAG(SV_ILP32)) {
2847                                 struct timeval32 tv32;
2848
2849                                 error = sooptcopyin(sopt, &tv32, sizeof tv32,
2850                                     sizeof tv32);
2851                                 CP(tv32, tv, tv_sec);
2852                                 CP(tv32, tv, tv_usec);
2853                         } else
2854 #endif
2855                                 error = sooptcopyin(sopt, &tv, sizeof tv,
2856                                     sizeof tv);
2857                         if (error)
2858                                 goto bad;
2859                         if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
2860                             tv.tv_usec >= 1000000) {
2861                                 error = EDOM;
2862                                 goto bad;
2863                         }
2864                         if (tv.tv_sec > INT32_MAX)
2865                                 val = SBT_MAX;
2866                         else
2867                                 val = tvtosbt(tv);
2868                         switch (sopt->sopt_name) {
2869                         case SO_SNDTIMEO:
2870                                 so->so_snd.sb_timeo = val;
2871                                 break;
2872                         case SO_RCVTIMEO:
2873                                 so->so_rcv.sb_timeo = val;
2874                                 break;
2875                         }
2876                         break;
2877
2878                 case SO_LABEL:
2879 #ifdef MAC
2880                         error = sooptcopyin(sopt, &extmac, sizeof extmac,
2881                             sizeof extmac);
2882                         if (error)
2883                                 goto bad;
2884                         error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2885                             so, &extmac);
2886 #else
2887                         error = EOPNOTSUPP;
2888 #endif
2889                         break;
2890
2891                 case SO_TS_CLOCK:
2892                         error = sooptcopyin(sopt, &optval, sizeof optval,
2893                             sizeof optval);
2894                         if (error)
2895                                 goto bad;
2896                         if (optval < 0 || optval > SO_TS_CLOCK_MAX) {
2897                                 error = EINVAL;
2898                                 goto bad;
2899                         }
2900                         so->so_ts_clock = optval;
2901                         break;
2902
2903                 case SO_MAX_PACING_RATE:
2904                         error = sooptcopyin(sopt, &val32, sizeof(val32),
2905                             sizeof(val32));
2906                         if (error)
2907                                 goto bad;
2908                         so->so_max_pacing_rate = val32;
2909                         break;
2910
2911                 default:
2912                         if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
2913                                 error = hhook_run_socket(so, sopt,
2914                                     HHOOK_SOCKET_OPT);
2915                         else
2916                                 error = ENOPROTOOPT;
2917                         break;
2918                 }
2919                 if (error == 0 && so->so_proto->pr_ctloutput != NULL)
2920                         (void)(*so->so_proto->pr_ctloutput)(so, sopt);
2921         }
2922 bad:
2923         CURVNET_RESTORE();
2924         return (error);
2925 }
2926
2927 /*
2928  * Helper routine for getsockopt.
2929  */
2930 int
2931 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2932 {
2933         int     error;
2934         size_t  valsize;
2935
2936         error = 0;
2937
2938         /*
2939          * Documented get behavior is that we always return a value, possibly
2940          * truncated to fit in the user's buffer.  Traditional behavior is
2941          * that we always tell the user precisely how much we copied, rather
2942          * than something useful like the total amount we had available for
2943          * her.  Note that this interface is not idempotent; the entire
2944          * answer must be generated ahead of time.
2945          */
2946         valsize = min(len, sopt->sopt_valsize);
2947         sopt->sopt_valsize = valsize;
2948         if (sopt->sopt_val != NULL) {
2949                 if (sopt->sopt_td != NULL)
2950                         error = copyout(buf, sopt->sopt_val, valsize);
2951                 else
2952                         bcopy(buf, sopt->sopt_val, valsize);
2953         }
2954         return (error);
2955 }
2956
2957 int
2958 sogetopt(struct socket *so, struct sockopt *sopt)
2959 {
2960         int     error, optval;
2961         struct  linger l;
2962         struct  timeval tv;
2963 #ifdef MAC
2964         struct mac extmac;
2965 #endif
2966
2967         CURVNET_SET(so->so_vnet);
2968         error = 0;
2969         if (sopt->sopt_level != SOL_SOCKET) {
2970                 if (so->so_proto->pr_ctloutput != NULL)
2971                         error = (*so->so_proto->pr_ctloutput)(so, sopt);
2972                 else
2973                         error = ENOPROTOOPT;
2974                 CURVNET_RESTORE();
2975                 return (error);
2976         } else {
2977                 switch (sopt->sopt_name) {
2978                 case SO_ACCEPTFILTER:
2979                         error = accept_filt_getopt(so, sopt);
2980                         break;
2981
2982                 case SO_LINGER:
2983                         SOCK_LOCK(so);
2984                         l.l_onoff = so->so_options & SO_LINGER;
2985                         l.l_linger = so->so_linger;
2986                         SOCK_UNLOCK(so);
2987                         error = sooptcopyout(sopt, &l, sizeof l);
2988                         break;
2989
2990                 case SO_USELOOPBACK:
2991                 case SO_DONTROUTE:
2992                 case SO_DEBUG:
2993                 case SO_KEEPALIVE:
2994                 case SO_REUSEADDR:
2995                 case SO_REUSEPORT:
2996                 case SO_BROADCAST:
2997                 case SO_OOBINLINE:
2998                 case SO_ACCEPTCONN:
2999                 case SO_TIMESTAMP:
3000                 case SO_BINTIME:
3001                 case SO_NOSIGPIPE:
3002                         optval = so->so_options & sopt->sopt_name;
3003 integer:
3004                         error = sooptcopyout(sopt, &optval, sizeof optval);
3005                         break;
3006
3007                 case SO_TYPE:
3008                         optval = so->so_type;
3009                         goto integer;
3010
3011                 case SO_PROTOCOL:
3012                         optval = so->so_proto->pr_protocol;
3013                         goto integer;
3014
3015                 case SO_ERROR:
3016                         SOCK_LOCK(so);
3017                         optval = so->so_error;
3018                         so->so_error = 0;
3019                         SOCK_UNLOCK(so);
3020                         goto integer;
3021
3022                 case SO_SNDBUF:
3023                         optval = so->so_snd.sb_hiwat;
3024                         goto integer;
3025
3026                 case SO_RCVBUF:
3027                         optval = so->so_rcv.sb_hiwat;
3028                         goto integer;
3029
3030                 case SO_SNDLOWAT:
3031                         optval = so->so_snd.sb_lowat;
3032                         goto integer;
3033
3034                 case SO_RCVLOWAT:
3035                         optval = so->so_rcv.sb_lowat;
3036                         goto integer;
3037
3038                 case SO_SNDTIMEO:
3039                 case SO_RCVTIMEO:
3040                         tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
3041                             so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
3042 #ifdef COMPAT_FREEBSD32
3043                         if (SV_CURPROC_FLAG(SV_ILP32)) {
3044                                 struct timeval32 tv32;
3045
3046                                 CP(tv, tv32, tv_sec);
3047                                 CP(tv, tv32, tv_usec);
3048                                 error = sooptcopyout(sopt, &tv32, sizeof tv32);
3049                         } else
3050 #endif
3051                                 error = sooptcopyout(sopt, &tv, sizeof tv);
3052                         break;
3053
3054                 case SO_LABEL:
3055 #ifdef MAC
3056                         error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3057                             sizeof(extmac));
3058                         if (error)
3059                                 goto bad;
3060                         error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
3061                             so, &extmac);
3062                         if (error)
3063                                 goto bad;
3064                         error = sooptcopyout(sopt, &extmac, sizeof extmac);
3065 #else
3066                         error = EOPNOTSUPP;
3067 #endif
3068                         break;
3069
3070                 case SO_PEERLABEL:
3071 #ifdef MAC
3072                         error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3073                             sizeof(extmac));
3074                         if (error)
3075                                 goto bad;
3076                         error = mac_getsockopt_peerlabel(
3077                             sopt->sopt_td->td_ucred, so, &extmac);
3078                         if (error)
3079                                 goto bad;
3080                         error = sooptcopyout(sopt, &extmac, sizeof extmac);
3081 #else
3082                         error = EOPNOTSUPP;
3083 #endif
3084                         break;
3085
3086                 case SO_LISTENQLIMIT:
3087                         optval = SOLISTENING(so) ? so->sol_qlimit : 0;
3088                         goto integer;
3089
3090                 case SO_LISTENQLEN:
3091                         optval = SOLISTENING(so) ? so->sol_qlen : 0;
3092                         goto integer;
3093
3094                 case SO_LISTENINCQLEN:
3095                         optval = SOLISTENING(so) ? so->sol_incqlen : 0;
3096                         goto integer;
3097
3098                 case SO_TS_CLOCK:
3099                         optval = so->so_ts_clock;
3100                         goto integer;
3101
3102                 case SO_MAX_PACING_RATE:
3103                         optval = so->so_max_pacing_rate;
3104                         goto integer;
3105
3106                 default:
3107                         if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3108                                 error = hhook_run_socket(so, sopt,
3109                                     HHOOK_SOCKET_OPT);
3110                         else
3111                                 error = ENOPROTOOPT;
3112                         break;
3113                 }
3114         }
3115 #ifdef MAC
3116 bad:
3117 #endif
3118         CURVNET_RESTORE();
3119         return (error);
3120 }
3121
3122 int
3123 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
3124 {
3125         struct mbuf *m, *m_prev;
3126         int sopt_size = sopt->sopt_valsize;
3127
3128         MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3129         if (m == NULL)
3130                 return ENOBUFS;
3131         if (sopt_size > MLEN) {
3132                 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
3133                 if ((m->m_flags & M_EXT) == 0) {
3134                         m_free(m);
3135                         return ENOBUFS;
3136                 }
3137                 m->m_len = min(MCLBYTES, sopt_size);
3138         } else {
3139                 m->m_len = min(MLEN, sopt_size);
3140         }
3141         sopt_size -= m->m_len;
3142         *mp = m;
3143         m_prev = m;
3144
3145         while (sopt_size) {
3146                 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3147                 if (m == NULL) {
3148                         m_freem(*mp);
3149                         return ENOBUFS;
3150                 }
3151                 if (sopt_size > MLEN) {
3152                         MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
3153                             M_NOWAIT);
3154                         if ((m->m_flags & M_EXT) == 0) {
3155                                 m_freem(m);
3156                                 m_freem(*mp);
3157                                 return ENOBUFS;
3158                         }
3159                         m->m_len = min(MCLBYTES, sopt_size);
3160                 } else {
3161                         m->m_len = min(MLEN, sopt_size);
3162                 }
3163                 sopt_size -= m->m_len;
3164                 m_prev->m_next = m;
3165                 m_prev = m;
3166         }
3167         return (0);
3168 }
3169
3170 int
3171 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
3172 {
3173         struct mbuf *m0 = m;
3174
3175         if (sopt->sopt_val == NULL)
3176                 return (0);
3177         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3178                 if (sopt->sopt_td != NULL) {
3179                         int error;
3180
3181                         error = copyin(sopt->sopt_val, mtod(m, char *),
3182                             m->m_len);
3183                         if (error != 0) {
3184                                 m_freem(m0);
3185                                 return(error);
3186                         }
3187                 } else
3188                         bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
3189                 sopt->sopt_valsize -= m->m_len;
3190                 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3191                 m = m->m_next;
3192         }
3193         if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
3194                 panic("ip6_sooptmcopyin");
3195         return (0);
3196 }
3197
3198 int
3199 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
3200 {
3201         struct mbuf *m0 = m;
3202         size_t valsize = 0;
3203
3204         if (sopt->sopt_val == NULL)
3205                 return (0);
3206         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3207                 if (sopt->sopt_td != NULL) {
3208                         int error;
3209
3210                         error = copyout(mtod(m, char *), sopt->sopt_val,
3211                             m->m_len);
3212                         if (error != 0) {
3213                                 m_freem(m0);
3214                                 return(error);
3215                         }
3216                 } else
3217                         bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
3218                 sopt->sopt_valsize -= m->m_len;
3219                 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3220                 valsize += m->m_len;
3221                 m = m->m_next;
3222         }
3223         if (m != NULL) {
3224                 /* enough soopt buffer should be given from user-land */
3225                 m_freem(m0);
3226                 return(EINVAL);
3227         }
3228         sopt->sopt_valsize = valsize;
3229         return (0);
3230 }
3231
3232 /*
3233  * sohasoutofband(): protocol notifies socket layer of the arrival of new
3234  * out-of-band data, which will then notify socket consumers.
3235  */
3236 void
3237 sohasoutofband(struct socket *so)
3238 {
3239
3240         if (so->so_sigio != NULL)
3241                 pgsigio(&so->so_sigio, SIGURG, 0);
3242         selwakeuppri(&so->so_rdsel, PSOCK);
3243 }
3244
3245 int
3246 sopoll(struct socket *so, int events, struct ucred *active_cred,
3247     struct thread *td)
3248 {
3249
3250         /*
3251          * We do not need to set or assert curvnet as long as everyone uses
3252          * sopoll_generic().
3253          */
3254         return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
3255             td));
3256 }
3257
3258 int
3259 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3260     struct thread *td)
3261 {
3262         int revents;
3263
3264         SOCK_LOCK(so);
3265         if (SOLISTENING(so)) {
3266                 if (!(events & (POLLIN | POLLRDNORM)))
3267                         revents = 0;
3268                 else if (!TAILQ_EMPTY(&so->sol_comp))
3269                         revents = events & (POLLIN | POLLRDNORM);
3270                 else {
3271                         selrecord(td, &so->so_rdsel);
3272                         revents = 0;
3273                 }
3274         } else {
3275                 revents = 0;
3276                 SOCKBUF_LOCK(&so->so_snd);
3277                 SOCKBUF_LOCK(&so->so_rcv);
3278                 if (events & (POLLIN | POLLRDNORM))
3279                         if (soreadabledata(so))
3280                                 revents |= events & (POLLIN | POLLRDNORM);
3281                 if (events & (POLLOUT | POLLWRNORM))
3282                         if (sowriteable(so))
3283                                 revents |= events & (POLLOUT | POLLWRNORM);
3284                 if (events & (POLLPRI | POLLRDBAND))
3285                         if (so->so_oobmark ||
3286                             (so->so_rcv.sb_state & SBS_RCVATMARK))
3287                                 revents |= events & (POLLPRI | POLLRDBAND);
3288                 if ((events & POLLINIGNEOF) == 0) {
3289                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3290                                 revents |= events & (POLLIN | POLLRDNORM);
3291                                 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3292                                         revents |= POLLHUP;
3293                         }
3294                 }
3295                 if (revents == 0) {
3296                         if (events &
3297                             (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
3298                                 selrecord(td, &so->so_rdsel);
3299                                 so->so_rcv.sb_flags |= SB_SEL;
3300                         }
3301                         if (events & (POLLOUT | POLLWRNORM)) {
3302                                 selrecord(td, &so->so_wrsel);
3303                                 so->so_snd.sb_flags |= SB_SEL;
3304                         }
3305                 }
3306                 SOCKBUF_UNLOCK(&so->so_rcv);
3307                 SOCKBUF_UNLOCK(&so->so_snd);
3308         }
3309         SOCK_UNLOCK(so);
3310         return (revents);
3311 }
3312
3313 int
3314 soo_kqfilter(struct file *fp, struct knote *kn)
3315 {
3316         struct socket *so = kn->kn_fp->f_data;
3317         struct sockbuf *sb;
3318         struct knlist *knl;
3319
3320         switch (kn->kn_filter) {
3321         case EVFILT_READ:
3322                 kn->kn_fop = &soread_filtops;
3323                 knl = &so->so_rdsel.si_note;
3324                 sb = &so->so_rcv;
3325                 break;
3326         case EVFILT_WRITE:
3327                 kn->kn_fop = &sowrite_filtops;
3328                 knl = &so->so_wrsel.si_note;
3329                 sb = &so->so_snd;
3330                 break;
3331         case EVFILT_EMPTY:
3332                 kn->kn_fop = &soempty_filtops;
3333                 knl = &so->so_wrsel.si_note;
3334                 sb = &so->so_snd;
3335                 break;
3336         default:
3337                 return (EINVAL);
3338         }
3339
3340         SOCK_LOCK(so);
3341         if (SOLISTENING(so)) {
3342                 knlist_add(knl, kn, 1);
3343         } else {
3344                 SOCKBUF_LOCK(sb);
3345                 knlist_add(knl, kn, 1);
3346                 sb->sb_flags |= SB_KNOTE;
3347                 SOCKBUF_UNLOCK(sb);
3348         }
3349         SOCK_UNLOCK(so);
3350         return (0);
3351 }
3352
3353 /*
3354  * Some routines that return EOPNOTSUPP for entry points that are not
3355  * supported by a protocol.  Fill in as needed.
3356  */
3357 int
3358 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
3359 {
3360
3361         return EOPNOTSUPP;
3362 }
3363
3364 int
3365 pru_aio_queue_notsupp(struct socket *so, struct kaiocb *job)
3366 {
3367
3368         return EOPNOTSUPP;
3369 }
3370
3371 int
3372 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
3373 {
3374
3375         return EOPNOTSUPP;
3376 }
3377
3378 int
3379 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3380 {
3381
3382         return EOPNOTSUPP;
3383 }
3384
3385 int
3386 pru_bindat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3387     struct thread *td)
3388 {
3389
3390         return EOPNOTSUPP;
3391 }
3392
3393 int
3394 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3395 {
3396
3397         return EOPNOTSUPP;
3398 }
3399
3400 int
3401 pru_connectat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3402     struct thread *td)
3403 {
3404
3405         return EOPNOTSUPP;
3406 }
3407
3408 int
3409 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
3410 {
3411
3412         return EOPNOTSUPP;
3413 }
3414
3415 int
3416 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
3417     struct ifnet *ifp, struct thread *td)
3418 {
3419
3420         return EOPNOTSUPP;
3421 }
3422
3423 int
3424 pru_disconnect_notsupp(struct socket *so)
3425 {
3426
3427         return EOPNOTSUPP;
3428 }
3429
3430 int
3431 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
3432 {
3433
3434         return EOPNOTSUPP;
3435 }
3436
3437 int
3438 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
3439 {
3440
3441         return EOPNOTSUPP;
3442 }
3443
3444 int
3445 pru_rcvd_notsupp(struct socket *so, int flags)
3446 {
3447
3448         return EOPNOTSUPP;
3449 }
3450
3451 int
3452 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
3453 {
3454
3455         return EOPNOTSUPP;
3456 }
3457
3458 int
3459 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
3460     struct sockaddr *addr, struct mbuf *control, struct thread *td)
3461 {
3462
3463         return EOPNOTSUPP;
3464 }
3465
3466 int
3467 pru_ready_notsupp(struct socket *so, struct mbuf *m, int count)
3468 {
3469
3470         return (EOPNOTSUPP);
3471 }
3472
3473 /*
3474  * This isn't really a ``null'' operation, but it's the default one and
3475  * doesn't do anything destructive.
3476  */
3477 int
3478 pru_sense_null(struct socket *so, struct stat *sb)
3479 {
3480
3481         sb->st_blksize = so->so_snd.sb_hiwat;
3482         return 0;
3483 }
3484
3485 int
3486 pru_shutdown_notsupp(struct socket *so)
3487 {
3488
3489         return EOPNOTSUPP;
3490 }
3491
3492 int
3493 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
3494 {
3495
3496         return EOPNOTSUPP;
3497 }
3498
3499 int
3500 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
3501     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
3502 {
3503
3504         return EOPNOTSUPP;
3505 }
3506
3507 int
3508 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
3509     struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3510 {
3511
3512         return EOPNOTSUPP;
3513 }
3514
3515 int
3516 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
3517     struct thread *td)
3518 {
3519
3520         return EOPNOTSUPP;
3521 }
3522
3523 static void
3524 filt_sordetach(struct knote *kn)
3525 {
3526         struct socket *so = kn->kn_fp->f_data;
3527
3528         so_rdknl_lock(so);
3529         knlist_remove(&so->so_rdsel.si_note, kn, 1);
3530         if (!SOLISTENING(so) && knlist_empty(&so->so_rdsel.si_note))
3531                 so->so_rcv.sb_flags &= ~SB_KNOTE;
3532         so_rdknl_unlock(so);
3533 }
3534
3535 /*ARGSUSED*/
3536 static int
3537 filt_soread(struct knote *kn, long hint)
3538 {
3539         struct socket *so;
3540
3541         so = kn->kn_fp->f_data;
3542
3543         if (SOLISTENING(so)) {
3544                 SOCK_LOCK_ASSERT(so);
3545                 kn->kn_data = so->sol_qlen;
3546                 return (!TAILQ_EMPTY(&so->sol_comp));
3547         }
3548
3549         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3550
3551         kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
3552         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3553                 kn->kn_flags |= EV_EOF;
3554                 kn->kn_fflags = so->so_error;
3555                 return (1);
3556         } else if (so->so_error)        /* temporary udp error */
3557                 return (1);
3558
3559         if (kn->kn_sfflags & NOTE_LOWAT) {
3560                 if (kn->kn_data >= kn->kn_sdata)
3561                         return (1);
3562         } else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
3563                 return (1);
3564
3565         /* This hook returning non-zero indicates an event, not error */
3566         return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
3567 }
3568
3569 static void
3570 filt_sowdetach(struct knote *kn)
3571 {
3572         struct socket *so = kn->kn_fp->f_data;
3573
3574         so_wrknl_lock(so);
3575         knlist_remove(&so->so_wrsel.si_note, kn, 1);
3576         if (!SOLISTENING(so) && knlist_empty(&so->so_wrsel.si_note))
3577                 so->so_snd.sb_flags &= ~SB_KNOTE;
3578         so_wrknl_unlock(so);
3579 }
3580
3581 /*ARGSUSED*/
3582 static int
3583 filt_sowrite(struct knote *kn, long hint)
3584 {
3585         struct socket *so;
3586
3587         so = kn->kn_fp->f_data;
3588
3589         if (SOLISTENING(so))
3590                 return (0);
3591
3592         SOCKBUF_LOCK_ASSERT(&so->so_snd);
3593         kn->kn_data = sbspace(&so->so_snd);
3594
3595         hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
3596
3597         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3598                 kn->kn_flags |= EV_EOF;
3599                 kn->kn_fflags = so->so_error;
3600                 return (1);
3601         } else if (so->so_error)        /* temporary udp error */
3602                 return (1);
3603         else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3604             (so->so_proto->pr_flags & PR_CONNREQUIRED))
3605                 return (0);
3606         else if (kn->kn_sfflags & NOTE_LOWAT)
3607                 return (kn->kn_data >= kn->kn_sdata);
3608         else
3609                 return (kn->kn_data >= so->so_snd.sb_lowat);
3610 }
3611
3612 static int
3613 filt_soempty(struct knote *kn, long hint)
3614 {
3615         struct socket *so;
3616
3617         so = kn->kn_fp->f_data;
3618
3619         if (SOLISTENING(so))
3620                 return (1);
3621
3622         SOCKBUF_LOCK_ASSERT(&so->so_snd);
3623         kn->kn_data = sbused(&so->so_snd);
3624
3625         if (kn->kn_data == 0)
3626                 return (1);
3627         else
3628                 return (0);
3629 }
3630
3631 int
3632 socheckuid(struct socket *so, uid_t uid)
3633 {
3634
3635         if (so == NULL)
3636                 return (EPERM);
3637         if (so->so_cred->cr_uid != uid)
3638                 return (EPERM);
3639         return (0);
3640 }
3641
3642 /*
3643  * These functions are used by protocols to notify the socket layer (and its
3644  * consumers) of state changes in the sockets driven by protocol-side events.
3645  */
3646
3647 /*
3648  * Procedures to manipulate state flags of socket and do appropriate wakeups.
3649  *
3650  * Normal sequence from the active (originating) side is that
3651  * soisconnecting() is called during processing of connect() call, resulting
3652  * in an eventual call to soisconnected() if/when the connection is
3653  * established.  When the connection is torn down soisdisconnecting() is
3654  * called during processing of disconnect() call, and soisdisconnected() is
3655  * called when the connection to the peer is totally severed.  The semantics
3656  * of these routines are such that connectionless protocols can call
3657  * soisconnected() and soisdisconnected() only, bypassing the in-progress
3658  * calls when setting up a ``connection'' takes no time.
3659  *
3660  * From the passive side, a socket is created with two queues of sockets:
3661  * so_incomp for connections in progress and so_comp for connections already
3662  * made and awaiting user acceptance.  As a protocol is preparing incoming
3663  * connections, it creates a socket structure queued on so_incomp by calling
3664  * sonewconn().  When the connection is established, soisconnected() is
3665  * called, and transfers the socket structure to so_comp, making it available
3666  * to accept().
3667  *
3668  * If a socket is closed with sockets on either so_incomp or so_comp, these
3669  * sockets are dropped.
3670  *
3671  * If higher-level protocols are implemented in the kernel, the wakeups done
3672  * here will sometimes cause software-interrupt process scheduling.
3673  */
3674 void
3675 soisconnecting(struct socket *so)
3676 {
3677
3678         SOCK_LOCK(so);
3679         so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3680         so->so_state |= SS_ISCONNECTING;
3681         SOCK_UNLOCK(so);
3682 }
3683
3684 void
3685 soisconnected(struct socket *so)
3686 {
3687         struct socket *head;
3688         int ret;
3689
3690         /*
3691          * XXXGL: this is the only place where we acquire socket locks
3692          * in reverse order: first child, then listening socket.  To
3693          * avoid possible LOR, use try semantics.
3694          */
3695 restart:
3696         SOCK_LOCK(so);
3697         if ((head = so->so_listen) != NULL &&
3698             __predict_false(SOLISTEN_TRYLOCK(head) == 0)) {
3699                 SOCK_UNLOCK(so);
3700                 goto restart;
3701         }
3702         so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3703         so->so_state |= SS_ISCONNECTED;
3704         if (head != NULL && (so->so_qstate == SQ_INCOMP)) {
3705 again:
3706                 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3707                         TAILQ_REMOVE(&head->sol_incomp, so, so_list);
3708                         head->sol_incqlen--;
3709                         TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
3710                         head->sol_qlen++;
3711                         so->so_qstate = SQ_COMP;
3712                         SOCK_UNLOCK(so);
3713                         solisten_wakeup(head);  /* unlocks */
3714                 } else {
3715                         SOCKBUF_LOCK(&so->so_rcv);
3716                         soupcall_set(so, SO_RCV,
3717                             head->sol_accept_filter->accf_callback,
3718                             head->sol_accept_filter_arg);
3719                         so->so_options &= ~SO_ACCEPTFILTER;
3720                         ret = head->sol_accept_filter->accf_callback(so,
3721                             head->sol_accept_filter_arg, M_NOWAIT);
3722                         if (ret == SU_ISCONNECTED) {
3723                                 soupcall_clear(so, SO_RCV);
3724                                 SOCKBUF_UNLOCK(&so->so_rcv);
3725                                 goto again;
3726                         }
3727                         SOCKBUF_UNLOCK(&so->so_rcv);
3728                         SOCK_UNLOCK(so);
3729                         SOLISTEN_UNLOCK(head);
3730                 }
3731                 return;
3732         }
3733         if (head != NULL)
3734                 SOLISTEN_UNLOCK(head);
3735         SOCK_UNLOCK(so);
3736         wakeup(&so->so_timeo);
3737         sorwakeup(so);
3738         sowwakeup(so);
3739 }
3740
3741 void
3742 soisdisconnecting(struct socket *so)
3743 {
3744
3745         SOCK_LOCK(so);
3746         so->so_state &= ~SS_ISCONNECTING;
3747         so->so_state |= SS_ISDISCONNECTING;
3748
3749         if (!SOLISTENING(so)) {
3750                 SOCKBUF_LOCK(&so->so_rcv);
3751                 socantrcvmore_locked(so);
3752                 SOCKBUF_LOCK(&so->so_snd);
3753                 socantsendmore_locked(so);
3754         }
3755         SOCK_UNLOCK(so);
3756         wakeup(&so->so_timeo);
3757 }
3758
3759 void
3760 soisdisconnected(struct socket *so)
3761 {
3762
3763         SOCK_LOCK(so);
3764         so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3765         so->so_state |= SS_ISDISCONNECTED;
3766
3767         if (!SOLISTENING(so)) {
3768                 SOCKBUF_LOCK(&so->so_rcv);
3769                 socantrcvmore_locked(so);
3770                 SOCKBUF_LOCK(&so->so_snd);
3771                 sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
3772                 socantsendmore_locked(so);
3773         }
3774         SOCK_UNLOCK(so);
3775         wakeup(&so->so_timeo);
3776 }
3777
3778 /*
3779  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3780  */
3781 struct sockaddr *
3782 sodupsockaddr(const struct sockaddr *sa, int mflags)
3783 {
3784         struct sockaddr *sa2;
3785
3786         sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3787         if (sa2)
3788                 bcopy(sa, sa2, sa->sa_len);
3789         return sa2;
3790 }
3791
3792 /*
3793  * Register per-socket buffer upcalls.
3794  */
3795 void
3796 soupcall_set(struct socket *so, int which, so_upcall_t func, void *arg)
3797 {
3798         struct sockbuf *sb;
3799
3800         KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
3801
3802         switch (which) {
3803         case SO_RCV:
3804                 sb = &so->so_rcv;
3805                 break;
3806         case SO_SND:
3807                 sb = &so->so_snd;
3808                 break;
3809         default:
3810                 panic("soupcall_set: bad which");
3811         }
3812         SOCKBUF_LOCK_ASSERT(sb);
3813         sb->sb_upcall = func;
3814         sb->sb_upcallarg = arg;
3815         sb->sb_flags |= SB_UPCALL;
3816 }
3817
3818 void
3819 soupcall_clear(struct socket *so, int which)
3820 {
3821         struct sockbuf *sb;
3822
3823         KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
3824
3825         switch (which) {
3826         case SO_RCV:
3827                 sb = &so->so_rcv;
3828                 break;
3829         case SO_SND:
3830                 sb = &so->so_snd;
3831                 break;
3832         default:
3833                 panic("soupcall_clear: bad which");
3834         }
3835         SOCKBUF_LOCK_ASSERT(sb);
3836         KASSERT(sb->sb_upcall != NULL,
3837             ("%s: so %p no upcall to clear", __func__, so));
3838         sb->sb_upcall = NULL;
3839         sb->sb_upcallarg = NULL;
3840         sb->sb_flags &= ~SB_UPCALL;
3841 }
3842
3843 void
3844 solisten_upcall_set(struct socket *so, so_upcall_t func, void *arg)
3845 {
3846
3847         SOLISTEN_LOCK_ASSERT(so);
3848         so->sol_upcall = func;
3849         so->sol_upcallarg = arg;
3850 }
3851
3852 static void
3853 so_rdknl_lock(void *arg)
3854 {
3855         struct socket *so = arg;
3856
3857         if (SOLISTENING(so))
3858                 SOCK_LOCK(so);
3859         else
3860                 SOCKBUF_LOCK(&so->so_rcv);
3861 }
3862
3863 static void
3864 so_rdknl_unlock(void *arg)
3865 {
3866         struct socket *so = arg;
3867
3868         if (SOLISTENING(so))
3869                 SOCK_UNLOCK(so);
3870         else
3871                 SOCKBUF_UNLOCK(&so->so_rcv);
3872 }
3873
3874 static void
3875 so_rdknl_assert_locked(void *arg)
3876 {
3877         struct socket *so = arg;
3878
3879         if (SOLISTENING(so))
3880                 SOCK_LOCK_ASSERT(so);
3881         else
3882                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3883 }
3884
3885 static void
3886 so_rdknl_assert_unlocked(void *arg)
3887 {
3888         struct socket *so = arg;
3889
3890         if (SOLISTENING(so))
3891                 SOCK_UNLOCK_ASSERT(so);
3892         else
3893                 SOCKBUF_UNLOCK_ASSERT(&so->so_rcv);
3894 }
3895
3896 static void
3897 so_wrknl_lock(void *arg)
3898 {
3899         struct socket *so = arg;
3900
3901         if (SOLISTENING(so))
3902                 SOCK_LOCK(so);
3903         else
3904                 SOCKBUF_LOCK(&so->so_snd);
3905 }
3906
3907 static void
3908 so_wrknl_unlock(void *arg)
3909 {
3910         struct socket *so = arg;
3911
3912         if (SOLISTENING(so))
3913                 SOCK_UNLOCK(so);
3914         else
3915                 SOCKBUF_UNLOCK(&so->so_snd);
3916 }
3917
3918 static void
3919 so_wrknl_assert_locked(void *arg)
3920 {
3921         struct socket *so = arg;
3922
3923         if (SOLISTENING(so))
3924                 SOCK_LOCK_ASSERT(so);
3925         else
3926                 SOCKBUF_LOCK_ASSERT(&so->so_snd);
3927 }
3928
3929 static void
3930 so_wrknl_assert_unlocked(void *arg)
3931 {
3932         struct socket *so = arg;
3933
3934         if (SOLISTENING(so))
3935                 SOCK_UNLOCK_ASSERT(so);
3936         else
3937                 SOCKBUF_UNLOCK_ASSERT(&so->so_snd);
3938 }
3939
3940 /*
3941  * Create an external-format (``xsocket'') structure using the information in
3942  * the kernel-format socket structure pointed to by so.  This is done to
3943  * reduce the spew of irrelevant information over this interface, to isolate
3944  * user code from changes in the kernel structure, and potentially to provide
3945  * information-hiding if we decide that some of this information should be
3946  * hidden from users.
3947  */
3948 void
3949 sotoxsocket(struct socket *so, struct xsocket *xso)
3950 {
3951
3952         xso->xso_len = sizeof *xso;
3953         xso->xso_so = so;
3954         xso->so_type = so->so_type;
3955         xso->so_options = so->so_options;
3956         xso->so_linger = so->so_linger;
3957         xso->so_state = so->so_state;
3958         xso->so_pcb = so->so_pcb;
3959         xso->xso_protocol = so->so_proto->pr_protocol;
3960         xso->xso_family = so->so_proto->pr_domain->dom_family;
3961         xso->so_timeo = so->so_timeo;
3962         xso->so_error = so->so_error;
3963         xso->so_uid = so->so_cred->cr_uid;
3964         xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
3965         if (SOLISTENING(so)) {
3966                 xso->so_qlen = so->sol_qlen;
3967                 xso->so_incqlen = so->sol_incqlen;
3968                 xso->so_qlimit = so->sol_qlimit;
3969                 xso->so_oobmark = 0;
3970                 bzero(&xso->so_snd, sizeof(xso->so_snd));
3971                 bzero(&xso->so_rcv, sizeof(xso->so_rcv));
3972         } else {
3973                 xso->so_state |= so->so_qstate;
3974                 xso->so_qlen = xso->so_incqlen = xso->so_qlimit = 0;
3975                 xso->so_oobmark = so->so_oobmark;
3976                 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
3977                 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
3978         }
3979 }
3980
3981 struct sockbuf *
3982 so_sockbuf_rcv(struct socket *so)
3983 {
3984
3985         return (&so->so_rcv);
3986 }
3987
3988 struct sockbuf *
3989 so_sockbuf_snd(struct socket *so)
3990 {
3991
3992         return (&so->so_snd);
3993 }
3994
3995 int
3996 so_state_get(const struct socket *so)
3997 {
3998
3999         return (so->so_state);
4000 }
4001
4002 void
4003 so_state_set(struct socket *so, int val)
4004 {
4005
4006         so->so_state = val;
4007 }
4008
4009 int
4010 so_options_get(const struct socket *so)
4011 {
4012
4013         return (so->so_options);
4014 }
4015
4016 void
4017 so_options_set(struct socket *so, int val)
4018 {
4019
4020         so->so_options = val;
4021 }
4022
4023 int
4024 so_error_get(const struct socket *so)
4025 {
4026
4027         return (so->so_error);
4028 }
4029
4030 void
4031 so_error_set(struct socket *so, int val)
4032 {
4033
4034         so->so_error = val;
4035 }
4036
4037 int
4038 so_linger_get(const struct socket *so)
4039 {
4040
4041         return (so->so_linger);
4042 }
4043
4044 void
4045 so_linger_set(struct socket *so, int val)
4046 {
4047
4048         so->so_linger = val;
4049 }
4050
4051 struct protosw *
4052 so_protosw_get(const struct socket *so)
4053 {
4054
4055         return (so->so_proto);
4056 }
4057
4058 void
4059 so_protosw_set(struct socket *so, struct protosw *val)
4060 {
4061
4062         so->so_proto = val;
4063 }
4064
4065 void
4066 so_sorwakeup(struct socket *so)
4067 {
4068
4069         sorwakeup(so);
4070 }
4071
4072 void
4073 so_sowwakeup(struct socket *so)
4074 {
4075
4076         sowwakeup(so);
4077 }
4078
4079 void
4080 so_sorwakeup_locked(struct socket *so)
4081 {
4082
4083         sorwakeup_locked(so);
4084 }
4085
4086 void
4087 so_sowwakeup_locked(struct socket *so)
4088 {
4089
4090         sowwakeup_locked(so);
4091 }
4092
4093 void
4094 so_lock(struct socket *so)
4095 {
4096
4097         SOCK_LOCK(so);
4098 }
4099
4100 void
4101 so_unlock(struct socket *so)
4102 {
4103
4104         SOCK_UNLOCK(so);
4105 }