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