]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_socket.c
callout: Move per-CPU callout state into the dpcpu region
[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() and KTLS. */
991         if (!SOLISTENING(so)) {
992                 bool ktls;
993
994 #ifdef KERN_TLS
995                 ktls = so->so_snd.sb_tls_info != NULL ||
996                     so->so_rcv.sb_tls_info != NULL;
997 #else
998                 ktls = false;
999 #endif
1000                 if (ktls ||
1001                     (so->so_snd.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0 ||
1002                     (so->so_rcv.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0) {
1003                         solisten_proto_abort(so);
1004                         return (EINVAL);
1005                 }
1006         }
1007
1008         return (0);
1009 }
1010
1011 /*
1012  * Undo the setup done by solisten_proto_check().
1013  */
1014 void
1015 solisten_proto_abort(struct socket *so)
1016 {
1017         mtx_unlock(&so->so_snd_mtx);
1018         mtx_unlock(&so->so_rcv_mtx);
1019         sx_xunlock(&so->so_snd_sx);
1020         sx_xunlock(&so->so_rcv_sx);
1021 }
1022
1023 void
1024 solisten_proto(struct socket *so, int backlog)
1025 {
1026         int sbrcv_lowat, sbsnd_lowat;
1027         u_int sbrcv_hiwat, sbsnd_hiwat;
1028         short sbrcv_flags, sbsnd_flags;
1029         sbintime_t sbrcv_timeo, sbsnd_timeo;
1030
1031         SOCK_LOCK_ASSERT(so);
1032         KASSERT((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
1033             SS_ISDISCONNECTING)) == 0,
1034             ("%s: bad socket state %p", __func__, so));
1035
1036         if (SOLISTENING(so))
1037                 goto listening;
1038
1039         /*
1040          * Change this socket to listening state.
1041          */
1042         sbrcv_lowat = so->so_rcv.sb_lowat;
1043         sbsnd_lowat = so->so_snd.sb_lowat;
1044         sbrcv_hiwat = so->so_rcv.sb_hiwat;
1045         sbsnd_hiwat = so->so_snd.sb_hiwat;
1046         sbrcv_flags = so->so_rcv.sb_flags;
1047         sbsnd_flags = so->so_snd.sb_flags;
1048         sbrcv_timeo = so->so_rcv.sb_timeo;
1049         sbsnd_timeo = so->so_snd.sb_timeo;
1050
1051         sbdestroy(so, SO_SND);
1052         sbdestroy(so, SO_RCV);
1053
1054 #ifdef INVARIANTS
1055         bzero(&so->so_rcv,
1056             sizeof(struct socket) - offsetof(struct socket, so_rcv));
1057 #endif
1058
1059         so->sol_sbrcv_lowat = sbrcv_lowat;
1060         so->sol_sbsnd_lowat = sbsnd_lowat;
1061         so->sol_sbrcv_hiwat = sbrcv_hiwat;
1062         so->sol_sbsnd_hiwat = sbsnd_hiwat;
1063         so->sol_sbrcv_flags = sbrcv_flags;
1064         so->sol_sbsnd_flags = sbsnd_flags;
1065         so->sol_sbrcv_timeo = sbrcv_timeo;
1066         so->sol_sbsnd_timeo = sbsnd_timeo;
1067
1068         so->sol_qlen = so->sol_incqlen = 0;
1069         TAILQ_INIT(&so->sol_incomp);
1070         TAILQ_INIT(&so->sol_comp);
1071
1072         so->sol_accept_filter = NULL;
1073         so->sol_accept_filter_arg = NULL;
1074         so->sol_accept_filter_str = NULL;
1075
1076         so->sol_upcall = NULL;
1077         so->sol_upcallarg = NULL;
1078
1079         so->so_options |= SO_ACCEPTCONN;
1080
1081 listening:
1082         if (backlog < 0 || backlog > somaxconn)
1083                 backlog = somaxconn;
1084         so->sol_qlimit = backlog;
1085
1086         mtx_unlock(&so->so_snd_mtx);
1087         mtx_unlock(&so->so_rcv_mtx);
1088         sx_xunlock(&so->so_snd_sx);
1089         sx_xunlock(&so->so_rcv_sx);
1090 }
1091
1092 /*
1093  * Wakeup listeners/subsystems once we have a complete connection.
1094  * Enters with lock, returns unlocked.
1095  */
1096 void
1097 solisten_wakeup(struct socket *sol)
1098 {
1099
1100         if (sol->sol_upcall != NULL)
1101                 (void )sol->sol_upcall(sol, sol->sol_upcallarg, M_NOWAIT);
1102         else {
1103                 selwakeuppri(&sol->so_rdsel, PSOCK);
1104                 KNOTE_LOCKED(&sol->so_rdsel.si_note, 0);
1105         }
1106         SOLISTEN_UNLOCK(sol);
1107         wakeup_one(&sol->sol_comp);
1108         if ((sol->so_state & SS_ASYNC) && sol->so_sigio != NULL)
1109                 pgsigio(&sol->so_sigio, SIGIO, 0);
1110 }
1111
1112 /*
1113  * Return single connection off a listening socket queue.  Main consumer of
1114  * the function is kern_accept4().  Some modules, that do their own accept
1115  * management also use the function.  The socket reference held by the
1116  * listen queue is handed to the caller.
1117  *
1118  * Listening socket must be locked on entry and is returned unlocked on
1119  * return.
1120  * The flags argument is set of accept4(2) flags and ACCEPT4_INHERIT.
1121  */
1122 int
1123 solisten_dequeue(struct socket *head, struct socket **ret, int flags)
1124 {
1125         struct socket *so;
1126         int error;
1127
1128         SOLISTEN_LOCK_ASSERT(head);
1129
1130         while (!(head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp) &&
1131             head->so_error == 0) {
1132                 error = msleep(&head->sol_comp, SOCK_MTX(head), PSOCK | PCATCH,
1133                     "accept", 0);
1134                 if (error != 0) {
1135                         SOLISTEN_UNLOCK(head);
1136                         return (error);
1137                 }
1138         }
1139         if (head->so_error) {
1140                 error = head->so_error;
1141                 head->so_error = 0;
1142         } else if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp))
1143                 error = EWOULDBLOCK;
1144         else
1145                 error = 0;
1146         if (error) {
1147                 SOLISTEN_UNLOCK(head);
1148                 return (error);
1149         }
1150         so = TAILQ_FIRST(&head->sol_comp);
1151         SOCK_LOCK(so);
1152         KASSERT(so->so_qstate == SQ_COMP,
1153             ("%s: so %p not SQ_COMP", __func__, so));
1154         head->sol_qlen--;
1155         so->so_qstate = SQ_NONE;
1156         so->so_listen = NULL;
1157         TAILQ_REMOVE(&head->sol_comp, so, so_list);
1158         if (flags & ACCEPT4_INHERIT)
1159                 so->so_state |= (head->so_state & SS_NBIO);
1160         else
1161                 so->so_state |= (flags & SOCK_NONBLOCK) ? SS_NBIO : 0;
1162         SOCK_UNLOCK(so);
1163         sorele_locked(head);
1164
1165         *ret = so;
1166         return (0);
1167 }
1168
1169 /*
1170  * Free socket upon release of the very last reference.
1171  */
1172 static void
1173 sofree(struct socket *so)
1174 {
1175         struct protosw *pr = so->so_proto;
1176
1177         SOCK_LOCK_ASSERT(so);
1178         KASSERT(refcount_load(&so->so_count) == 0,
1179             ("%s: so %p has references", __func__, so));
1180         KASSERT(SOLISTENING(so) || so->so_qstate == SQ_NONE,
1181             ("%s: so %p is on listen queue", __func__, so));
1182
1183         SOCK_UNLOCK(so);
1184
1185         if (so->so_dtor != NULL)
1186                 so->so_dtor(so);
1187
1188         VNET_SO_ASSERT(so);
1189         if ((pr->pr_flags & PR_RIGHTS) && !SOLISTENING(so)) {
1190                 MPASS(pr->pr_domain->dom_dispose != NULL);
1191                 (*pr->pr_domain->dom_dispose)(so);
1192         }
1193         if (pr->pr_detach != NULL)
1194                 pr->pr_detach(so);
1195
1196         /*
1197          * From this point on, we assume that no other references to this
1198          * socket exist anywhere else in the stack.  Therefore, no locks need
1199          * to be acquired or held.
1200          */
1201         if (!(pr->pr_flags & PR_SOCKBUF) && !SOLISTENING(so)) {
1202                 sbdestroy(so, SO_SND);
1203                 sbdestroy(so, SO_RCV);
1204         }
1205         seldrain(&so->so_rdsel);
1206         seldrain(&so->so_wrsel);
1207         knlist_destroy(&so->so_rdsel.si_note);
1208         knlist_destroy(&so->so_wrsel.si_note);
1209         sodealloc(so);
1210 }
1211
1212 /*
1213  * Release a reference on a socket while holding the socket lock.
1214  * Unlocks the socket lock before returning.
1215  */
1216 void
1217 sorele_locked(struct socket *so)
1218 {
1219         SOCK_LOCK_ASSERT(so);
1220         if (refcount_release(&so->so_count))
1221                 sofree(so);
1222         else
1223                 SOCK_UNLOCK(so);
1224 }
1225
1226 /*
1227  * Close a socket on last file table reference removal.  Initiate disconnect
1228  * if connected.  Free socket when disconnect complete.
1229  *
1230  * This function will sorele() the socket.  Note that soclose() may be called
1231  * prior to the ref count reaching zero.  The actual socket structure will
1232  * not be freed until the ref count reaches zero.
1233  */
1234 int
1235 soclose(struct socket *so)
1236 {
1237         struct accept_queue lqueue;
1238         int error = 0;
1239         bool listening, last __diagused;
1240
1241         CURVNET_SET(so->so_vnet);
1242         funsetown(&so->so_sigio);
1243         if (so->so_state & SS_ISCONNECTED) {
1244                 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
1245                         error = sodisconnect(so);
1246                         if (error) {
1247                                 if (error == ENOTCONN)
1248                                         error = 0;
1249                                 goto drop;
1250                         }
1251                 }
1252
1253                 if ((so->so_options & SO_LINGER) != 0 && so->so_linger != 0) {
1254                         if ((so->so_state & SS_ISDISCONNECTING) &&
1255                             (so->so_state & SS_NBIO))
1256                                 goto drop;
1257                         while (so->so_state & SS_ISCONNECTED) {
1258                                 error = tsleep(&so->so_timeo,
1259                                     PSOCK | PCATCH, "soclos",
1260                                     so->so_linger * hz);
1261                                 if (error)
1262                                         break;
1263                         }
1264                 }
1265         }
1266
1267 drop:
1268         if (so->so_proto->pr_close != NULL)
1269                 so->so_proto->pr_close(so);
1270
1271         SOCK_LOCK(so);
1272         if ((listening = SOLISTENING(so))) {
1273                 struct socket *sp;
1274
1275                 TAILQ_INIT(&lqueue);
1276                 TAILQ_SWAP(&lqueue, &so->sol_incomp, socket, so_list);
1277                 TAILQ_CONCAT(&lqueue, &so->sol_comp, so_list);
1278
1279                 so->sol_qlen = so->sol_incqlen = 0;
1280
1281                 TAILQ_FOREACH(sp, &lqueue, so_list) {
1282                         SOCK_LOCK(sp);
1283                         sp->so_qstate = SQ_NONE;
1284                         sp->so_listen = NULL;
1285                         SOCK_UNLOCK(sp);
1286                         last = refcount_release(&so->so_count);
1287                         KASSERT(!last, ("%s: released last reference for %p",
1288                             __func__, so));
1289                 }
1290         }
1291         sorele_locked(so);
1292         if (listening) {
1293                 struct socket *sp, *tsp;
1294
1295                 TAILQ_FOREACH_SAFE(sp, &lqueue, so_list, tsp)
1296                         soabort(sp);
1297         }
1298         CURVNET_RESTORE();
1299         return (error);
1300 }
1301
1302 /*
1303  * soabort() is used to abruptly tear down a connection, such as when a
1304  * resource limit is reached (listen queue depth exceeded), or if a listen
1305  * socket is closed while there are sockets waiting to be accepted.
1306  *
1307  * This interface is tricky, because it is called on an unreferenced socket,
1308  * and must be called only by a thread that has actually removed the socket
1309  * from the listen queue it was on.  Likely this thread holds the last
1310  * reference on the socket and soabort() will proceed with sofree().  But
1311  * it might be not the last, as the sockets on the listen queues are seen
1312  * from the protocol side.
1313  *
1314  * This interface will call into the protocol code, so must not be called
1315  * with any socket locks held.  Protocols do call it while holding their own
1316  * recursible protocol mutexes, but this is something that should be subject
1317  * to review in the future.
1318  *
1319  * Usually socket should have a single reference left, but this is not a
1320  * requirement.  In the past, when we have had named references for file
1321  * descriptor and protocol, we asserted that none of them are being held.
1322  */
1323 void
1324 soabort(struct socket *so)
1325 {
1326
1327         VNET_SO_ASSERT(so);
1328
1329         if (so->so_proto->pr_abort != NULL)
1330                 so->so_proto->pr_abort(so);
1331         SOCK_LOCK(so);
1332         sorele_locked(so);
1333 }
1334
1335 int
1336 soaccept(struct socket *so, struct sockaddr **nam)
1337 {
1338         int error;
1339
1340         CURVNET_SET(so->so_vnet);
1341         error = so->so_proto->pr_accept(so, nam);
1342         CURVNET_RESTORE();
1343         return (error);
1344 }
1345
1346 int
1347 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
1348 {
1349
1350         return (soconnectat(AT_FDCWD, so, nam, td));
1351 }
1352
1353 int
1354 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
1355 {
1356         int error;
1357
1358         CURVNET_SET(so->so_vnet);
1359
1360         /*
1361          * If protocol is connection-based, can only connect once.
1362          * Otherwise, if connected, try to disconnect first.  This allows
1363          * user to disconnect by connecting to, e.g., a null address.
1364          *
1365          * Note, this check is racy and may need to be re-evaluated at the
1366          * protocol layer.
1367          */
1368         if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
1369             ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
1370             (error = sodisconnect(so)))) {
1371                 error = EISCONN;
1372         } else {
1373                 /*
1374                  * Prevent accumulated error from previous connection from
1375                  * biting us.
1376                  */
1377                 so->so_error = 0;
1378                 if (fd == AT_FDCWD) {
1379                         error = so->so_proto->pr_connect(so, nam, td);
1380                 } else {
1381                         error = so->so_proto->pr_connectat(fd, so, nam, td);
1382                 }
1383         }
1384         CURVNET_RESTORE();
1385
1386         return (error);
1387 }
1388
1389 int
1390 soconnect2(struct socket *so1, struct socket *so2)
1391 {
1392         int error;
1393
1394         CURVNET_SET(so1->so_vnet);
1395         error = so1->so_proto->pr_connect2(so1, so2);
1396         CURVNET_RESTORE();
1397         return (error);
1398 }
1399
1400 int
1401 sodisconnect(struct socket *so)
1402 {
1403         int error;
1404
1405         if ((so->so_state & SS_ISCONNECTED) == 0)
1406                 return (ENOTCONN);
1407         if (so->so_state & SS_ISDISCONNECTING)
1408                 return (EALREADY);
1409         VNET_SO_ASSERT(so);
1410         error = so->so_proto->pr_disconnect(so);
1411         return (error);
1412 }
1413
1414 int
1415 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1416     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1417 {
1418         long space;
1419         ssize_t resid;
1420         int clen = 0, error, dontroute;
1421
1422         KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
1423         KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1424             ("sosend_dgram: !PR_ATOMIC"));
1425
1426         if (uio != NULL)
1427                 resid = uio->uio_resid;
1428         else
1429                 resid = top->m_pkthdr.len;
1430         /*
1431          * In theory resid should be unsigned.  However, space must be
1432          * signed, as it might be less than 0 if we over-committed, and we
1433          * must use a signed comparison of space and resid.  On the other
1434          * hand, a negative resid causes us to loop sending 0-length
1435          * segments to the protocol.
1436          */
1437         if (resid < 0) {
1438                 error = EINVAL;
1439                 goto out;
1440         }
1441
1442         dontroute =
1443             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1444         if (td != NULL)
1445                 td->td_ru.ru_msgsnd++;
1446         if (control != NULL)
1447                 clen = control->m_len;
1448
1449         SOCKBUF_LOCK(&so->so_snd);
1450         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1451                 SOCKBUF_UNLOCK(&so->so_snd);
1452                 error = EPIPE;
1453                 goto out;
1454         }
1455         if (so->so_error) {
1456                 error = so->so_error;
1457                 so->so_error = 0;
1458                 SOCKBUF_UNLOCK(&so->so_snd);
1459                 goto out;
1460         }
1461         if ((so->so_state & SS_ISCONNECTED) == 0) {
1462                 /*
1463                  * `sendto' and `sendmsg' is allowed on a connection-based
1464                  * socket if it supports implied connect.  Return ENOTCONN if
1465                  * not connected and no address is supplied.
1466                  */
1467                 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1468                     (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1469                         if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1470                             !(resid == 0 && clen != 0)) {
1471                                 SOCKBUF_UNLOCK(&so->so_snd);
1472                                 error = ENOTCONN;
1473                                 goto out;
1474                         }
1475                 } else if (addr == NULL) {
1476                         if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1477                                 error = ENOTCONN;
1478                         else
1479                                 error = EDESTADDRREQ;
1480                         SOCKBUF_UNLOCK(&so->so_snd);
1481                         goto out;
1482                 }
1483         }
1484
1485         /*
1486          * Do we need MSG_OOB support in SOCK_DGRAM?  Signs here may be a
1487          * problem and need fixing.
1488          */
1489         space = sbspace(&so->so_snd);
1490         if (flags & MSG_OOB)
1491                 space += 1024;
1492         space -= clen;
1493         SOCKBUF_UNLOCK(&so->so_snd);
1494         if (resid > space) {
1495                 error = EMSGSIZE;
1496                 goto out;
1497         }
1498         if (uio == NULL) {
1499                 resid = 0;
1500                 if (flags & MSG_EOR)
1501                         top->m_flags |= M_EOR;
1502         } else {
1503                 /*
1504                  * Copy the data from userland into a mbuf chain.
1505                  * If no data is to be copied in, a single empty mbuf
1506                  * is returned.
1507                  */
1508                 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1509                     (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1510                 if (top == NULL) {
1511                         error = EFAULT; /* only possible error */
1512                         goto out;
1513                 }
1514                 space -= resid - uio->uio_resid;
1515                 resid = uio->uio_resid;
1516         }
1517         KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1518         /*
1519          * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1520          * than with.
1521          */
1522         if (dontroute) {
1523                 SOCK_LOCK(so);
1524                 so->so_options |= SO_DONTROUTE;
1525                 SOCK_UNLOCK(so);
1526         }
1527         /*
1528          * XXX all the SBS_CANTSENDMORE checks previously done could be out
1529          * of date.  We could have received a reset packet in an interrupt or
1530          * maybe we slept while doing page faults in uiomove() etc.  We could
1531          * probably recheck again inside the locking protection here, but
1532          * there are probably other places that this also happens.  We must
1533          * rethink this.
1534          */
1535         VNET_SO_ASSERT(so);
1536         error = so->so_proto->pr_send(so, (flags & MSG_OOB) ? PRUS_OOB :
1537         /*
1538          * If the user set MSG_EOF, the protocol understands this flag and
1539          * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1540          */
1541             ((flags & MSG_EOF) &&
1542              (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1543              (resid <= 0)) ?
1544                 PRUS_EOF :
1545                 /* If there is more to send set PRUS_MORETOCOME */
1546                 (flags & MSG_MORETOCOME) ||
1547                 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1548                 top, addr, control, td);
1549         if (dontroute) {
1550                 SOCK_LOCK(so);
1551                 so->so_options &= ~SO_DONTROUTE;
1552                 SOCK_UNLOCK(so);
1553         }
1554         clen = 0;
1555         control = NULL;
1556         top = NULL;
1557 out:
1558         if (top != NULL)
1559                 m_freem(top);
1560         if (control != NULL)
1561                 m_freem(control);
1562         return (error);
1563 }
1564
1565 /*
1566  * Send on a socket.  If send must go all at once and message is larger than
1567  * send buffering, then hard error.  Lock against other senders.  If must go
1568  * all at once and not enough room now, then inform user that this would
1569  * block and do nothing.  Otherwise, if nonblocking, send as much as
1570  * possible.  The data to be sent is described by "uio" if nonzero, otherwise
1571  * by the mbuf chain "top" (which must be null if uio is not).  Data provided
1572  * in mbuf chain must be small enough to send all at once.
1573  *
1574  * Returns nonzero on error, timeout or signal; callers must check for short
1575  * counts if EINTR/ERESTART are returned.  Data and control buffers are freed
1576  * on return.
1577  */
1578 int
1579 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1580     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1581 {
1582         long space;
1583         ssize_t resid;
1584         int clen = 0, error, dontroute;
1585         int atomic = sosendallatonce(so) || top;
1586         int pr_send_flag;
1587 #ifdef KERN_TLS
1588         struct ktls_session *tls;
1589         int tls_enq_cnt, tls_send_flag;
1590         uint8_t tls_rtype;
1591
1592         tls = NULL;
1593         tls_rtype = TLS_RLTYPE_APP;
1594 #endif
1595         if (uio != NULL)
1596                 resid = uio->uio_resid;
1597         else if ((top->m_flags & M_PKTHDR) != 0)
1598                 resid = top->m_pkthdr.len;
1599         else
1600                 resid = m_length(top, NULL);
1601         /*
1602          * In theory resid should be unsigned.  However, space must be
1603          * signed, as it might be less than 0 if we over-committed, and we
1604          * must use a signed comparison of space and resid.  On the other
1605          * hand, a negative resid causes us to loop sending 0-length
1606          * segments to the protocol.
1607          *
1608          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1609          * type sockets since that's an error.
1610          */
1611         if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1612                 error = EINVAL;
1613                 goto out;
1614         }
1615
1616         dontroute =
1617             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1618             (so->so_proto->pr_flags & PR_ATOMIC);
1619         if (td != NULL)
1620                 td->td_ru.ru_msgsnd++;
1621         if (control != NULL)
1622                 clen = control->m_len;
1623
1624         error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1625         if (error)
1626                 goto out;
1627
1628 #ifdef KERN_TLS
1629         tls_send_flag = 0;
1630         tls = ktls_hold(so->so_snd.sb_tls_info);
1631         if (tls != NULL) {
1632                 if (tls->mode == TCP_TLS_MODE_SW)
1633                         tls_send_flag = PRUS_NOTREADY;
1634
1635                 if (control != NULL) {
1636                         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1637
1638                         if (clen >= sizeof(*cm) &&
1639                             cm->cmsg_type == TLS_SET_RECORD_TYPE) {
1640                                 tls_rtype = *((uint8_t *)CMSG_DATA(cm));
1641                                 clen = 0;
1642                                 m_freem(control);
1643                                 control = NULL;
1644                                 atomic = 1;
1645                         }
1646                 }
1647
1648                 if (resid == 0 && !ktls_permit_empty_frames(tls)) {
1649                         error = EINVAL;
1650                         goto release;
1651                 }
1652         }
1653 #endif
1654
1655 restart:
1656         do {
1657                 SOCKBUF_LOCK(&so->so_snd);
1658                 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1659                         SOCKBUF_UNLOCK(&so->so_snd);
1660                         error = EPIPE;
1661                         goto release;
1662                 }
1663                 if (so->so_error) {
1664                         error = so->so_error;
1665                         so->so_error = 0;
1666                         SOCKBUF_UNLOCK(&so->so_snd);
1667                         goto release;
1668                 }
1669                 if ((so->so_state & SS_ISCONNECTED) == 0) {
1670                         /*
1671                          * `sendto' and `sendmsg' is allowed on a connection-
1672                          * based socket if it supports implied connect.
1673                          * Return ENOTCONN if not connected and no address is
1674                          * supplied.
1675                          */
1676                         if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1677                             (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1678                                 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1679                                     !(resid == 0 && clen != 0)) {
1680                                         SOCKBUF_UNLOCK(&so->so_snd);
1681                                         error = ENOTCONN;
1682                                         goto release;
1683                                 }
1684                         } else if (addr == NULL) {
1685                                 SOCKBUF_UNLOCK(&so->so_snd);
1686                                 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1687                                         error = ENOTCONN;
1688                                 else
1689                                         error = EDESTADDRREQ;
1690                                 goto release;
1691                         }
1692                 }
1693                 space = sbspace(&so->so_snd);
1694                 if (flags & MSG_OOB)
1695                         space += 1024;
1696                 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1697                     clen > so->so_snd.sb_hiwat) {
1698                         SOCKBUF_UNLOCK(&so->so_snd);
1699                         error = EMSGSIZE;
1700                         goto release;
1701                 }
1702                 if (space < resid + clen &&
1703                     (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1704                         if ((so->so_state & SS_NBIO) ||
1705                             (flags & (MSG_NBIO | MSG_DONTWAIT)) != 0) {
1706                                 SOCKBUF_UNLOCK(&so->so_snd);
1707                                 error = EWOULDBLOCK;
1708                                 goto release;
1709                         }
1710                         error = sbwait(so, SO_SND);
1711                         SOCKBUF_UNLOCK(&so->so_snd);
1712                         if (error)
1713                                 goto release;
1714                         goto restart;
1715                 }
1716                 SOCKBUF_UNLOCK(&so->so_snd);
1717                 space -= clen;
1718                 do {
1719                         if (uio == NULL) {
1720                                 resid = 0;
1721                                 if (flags & MSG_EOR)
1722                                         top->m_flags |= M_EOR;
1723 #ifdef KERN_TLS
1724                                 if (tls != NULL) {
1725                                         ktls_frame(top, tls, &tls_enq_cnt,
1726                                             tls_rtype);
1727                                         tls_rtype = TLS_RLTYPE_APP;
1728                                 }
1729 #endif
1730                         } else {
1731                                 /*
1732                                  * Copy the data from userland into a mbuf
1733                                  * chain.  If resid is 0, which can happen
1734                                  * only if we have control to send, then
1735                                  * a single empty mbuf is returned.  This
1736                                  * is a workaround to prevent protocol send
1737                                  * methods to panic.
1738                                  */
1739 #ifdef KERN_TLS
1740                                 if (tls != NULL) {
1741                                         top = m_uiotombuf(uio, M_WAITOK, space,
1742                                             tls->params.max_frame_len,
1743                                             M_EXTPG |
1744                                             ((flags & MSG_EOR) ? M_EOR : 0));
1745                                         if (top != NULL) {
1746                                                 ktls_frame(top, tls,
1747                                                     &tls_enq_cnt, tls_rtype);
1748                                         }
1749                                         tls_rtype = TLS_RLTYPE_APP;
1750                                 } else
1751 #endif
1752                                         top = m_uiotombuf(uio, M_WAITOK, space,
1753                                             (atomic ? max_hdr : 0),
1754                                             (atomic ? M_PKTHDR : 0) |
1755                                             ((flags & MSG_EOR) ? M_EOR : 0));
1756                                 if (top == NULL) {
1757                                         error = EFAULT; /* only possible error */
1758                                         goto release;
1759                                 }
1760                                 space -= resid - uio->uio_resid;
1761                                 resid = uio->uio_resid;
1762                         }
1763                         if (dontroute) {
1764                                 SOCK_LOCK(so);
1765                                 so->so_options |= SO_DONTROUTE;
1766                                 SOCK_UNLOCK(so);
1767                         }
1768                         /*
1769                          * XXX all the SBS_CANTSENDMORE checks previously
1770                          * done could be out of date.  We could have received
1771                          * a reset packet in an interrupt or maybe we slept
1772                          * while doing page faults in uiomove() etc.  We
1773                          * could probably recheck again inside the locking
1774                          * protection here, but there are probably other
1775                          * places that this also happens.  We must rethink
1776                          * this.
1777                          */
1778                         VNET_SO_ASSERT(so);
1779
1780                         pr_send_flag = (flags & MSG_OOB) ? PRUS_OOB :
1781                         /*
1782                          * If the user set MSG_EOF, the protocol understands
1783                          * this flag and nothing left to send then use
1784                          * PRU_SEND_EOF instead of PRU_SEND.
1785                          */
1786                             ((flags & MSG_EOF) &&
1787                              (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1788                              (resid <= 0)) ?
1789                                 PRUS_EOF :
1790                         /* If there is more to send set PRUS_MORETOCOME. */
1791                             (flags & MSG_MORETOCOME) ||
1792                             (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0;
1793
1794 #ifdef KERN_TLS
1795                         pr_send_flag |= tls_send_flag;
1796 #endif
1797
1798                         error = so->so_proto->pr_send(so, pr_send_flag, top,
1799                             addr, control, td);
1800
1801                         if (dontroute) {
1802                                 SOCK_LOCK(so);
1803                                 so->so_options &= ~SO_DONTROUTE;
1804                                 SOCK_UNLOCK(so);
1805                         }
1806
1807 #ifdef KERN_TLS
1808                         if (tls != NULL && tls->mode == TCP_TLS_MODE_SW) {
1809                                 if (error != 0) {
1810                                         m_freem(top);
1811                                         top = NULL;
1812                                 } else {
1813                                         soref(so);
1814                                         ktls_enqueue(top, so, tls_enq_cnt);
1815                                 }
1816                         }
1817 #endif
1818                         clen = 0;
1819                         control = NULL;
1820                         top = NULL;
1821                         if (error)
1822                                 goto release;
1823                 } while (resid && space > 0);
1824         } while (resid);
1825
1826 release:
1827         SOCK_IO_SEND_UNLOCK(so);
1828 out:
1829 #ifdef KERN_TLS
1830         if (tls != NULL)
1831                 ktls_free(tls);
1832 #endif
1833         if (top != NULL)
1834                 m_freem(top);
1835         if (control != NULL)
1836                 m_freem(control);
1837         return (error);
1838 }
1839
1840 /*
1841  * Send to a socket from a kernel thread.
1842  *
1843  * XXXGL: in almost all cases uio is NULL and the mbuf is supplied.
1844  * Exception is nfs/bootp_subr.c.  It is arguable that the VNET context needs
1845  * to be set at all.  This function should just boil down to a static inline
1846  * calling the protocol method.
1847  */
1848 int
1849 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1850     struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1851 {
1852         int error;
1853
1854         CURVNET_SET(so->so_vnet);
1855         error = so->so_proto->pr_sosend(so, addr, uio,
1856             top, control, flags, td);
1857         CURVNET_RESTORE();
1858         return (error);
1859 }
1860
1861 /*
1862  * send(2), write(2) or aio_write(2) on a socket.
1863  */
1864 int
1865 sousrsend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1866     struct mbuf *control, int flags, struct proc *userproc)
1867 {
1868         struct thread *td;
1869         ssize_t len;
1870         int error;
1871
1872         td = uio->uio_td;
1873         len = uio->uio_resid;
1874         CURVNET_SET(so->so_vnet);
1875         error = so->so_proto->pr_sosend(so, addr, uio, NULL, control, flags,
1876             td);
1877         CURVNET_RESTORE();
1878         if (error != 0) {
1879                 /*
1880                  * Clear transient errors for stream protocols if they made
1881                  * some progress.  Make exclusion for aio(4) that would
1882                  * schedule a new write in case of EWOULDBLOCK and clear
1883                  * error itself.  See soaio_process_job().
1884                  */
1885                 if (uio->uio_resid != len &&
1886                     (so->so_proto->pr_flags & PR_ATOMIC) == 0 &&
1887                     userproc == NULL &&
1888                     (error == ERESTART || error == EINTR ||
1889                     error == EWOULDBLOCK))
1890                         error = 0;
1891                 /* Generation of SIGPIPE can be controlled per socket. */
1892                 if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0 &&
1893                     (flags & MSG_NOSIGNAL) == 0) {
1894                         if (userproc != NULL) {
1895                                 /* aio(4) job */
1896                                 PROC_LOCK(userproc);
1897                                 kern_psignal(userproc, SIGPIPE);
1898                                 PROC_UNLOCK(userproc);
1899                         } else {
1900                                 PROC_LOCK(td->td_proc);
1901                                 tdsignal(td, SIGPIPE);
1902                                 PROC_UNLOCK(td->td_proc);
1903                         }
1904                 }
1905         }
1906         return (error);
1907 }
1908
1909 /*
1910  * The part of soreceive() that implements reading non-inline out-of-band
1911  * data from a socket.  For more complete comments, see soreceive(), from
1912  * which this code originated.
1913  *
1914  * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1915  * unable to return an mbuf chain to the caller.
1916  */
1917 static int
1918 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1919 {
1920         struct protosw *pr = so->so_proto;
1921         struct mbuf *m;
1922         int error;
1923
1924         KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1925         VNET_SO_ASSERT(so);
1926
1927         m = m_get(M_WAITOK, MT_DATA);
1928         error = pr->pr_rcvoob(so, m, flags & MSG_PEEK);
1929         if (error)
1930                 goto bad;
1931         do {
1932                 error = uiomove(mtod(m, void *),
1933                     (int) min(uio->uio_resid, m->m_len), uio);
1934                 m = m_free(m);
1935         } while (uio->uio_resid && error == 0 && m);
1936 bad:
1937         if (m != NULL)
1938                 m_freem(m);
1939         return (error);
1940 }
1941
1942 /*
1943  * Following replacement or removal of the first mbuf on the first mbuf chain
1944  * of a socket buffer, push necessary state changes back into the socket
1945  * buffer so that other consumers see the values consistently.  'nextrecord'
1946  * is the callers locally stored value of the original value of
1947  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1948  * NOTE: 'nextrecord' may be NULL.
1949  */
1950 static __inline void
1951 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1952 {
1953
1954         SOCKBUF_LOCK_ASSERT(sb);
1955         /*
1956          * First, update for the new value of nextrecord.  If necessary, make
1957          * it the first record.
1958          */
1959         if (sb->sb_mb != NULL)
1960                 sb->sb_mb->m_nextpkt = nextrecord;
1961         else
1962                 sb->sb_mb = nextrecord;
1963
1964         /*
1965          * Now update any dependent socket buffer fields to reflect the new
1966          * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
1967          * addition of a second clause that takes care of the case where
1968          * sb_mb has been updated, but remains the last record.
1969          */
1970         if (sb->sb_mb == NULL) {
1971                 sb->sb_mbtail = NULL;
1972                 sb->sb_lastrecord = NULL;
1973         } else if (sb->sb_mb->m_nextpkt == NULL)
1974                 sb->sb_lastrecord = sb->sb_mb;
1975 }
1976
1977 /*
1978  * Implement receive operations on a socket.  We depend on the way that
1979  * records are added to the sockbuf by sbappend.  In particular, each record
1980  * (mbufs linked through m_next) must begin with an address if the protocol
1981  * so specifies, followed by an optional mbuf or mbufs containing ancillary
1982  * data, and then zero or more mbufs of data.  In order to allow parallelism
1983  * between network receive and copying to user space, as well as avoid
1984  * sleeping with a mutex held, we release the socket buffer mutex during the
1985  * user space copy.  Although the sockbuf is locked, new data may still be
1986  * appended, and thus we must maintain consistency of the sockbuf during that
1987  * time.
1988  *
1989  * The caller may receive the data as a single mbuf chain by supplying an
1990  * mbuf **mp0 for use in returning the chain.  The uio is then used only for
1991  * the count in uio_resid.
1992  */
1993 int
1994 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1995     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1996 {
1997         struct mbuf *m, **mp;
1998         int flags, error, offset;
1999         ssize_t len;
2000         struct protosw *pr = so->so_proto;
2001         struct mbuf *nextrecord;
2002         int moff, type = 0;
2003         ssize_t orig_resid = uio->uio_resid;
2004         bool report_real_len = false;
2005
2006         mp = mp0;
2007         if (psa != NULL)
2008                 *psa = NULL;
2009         if (controlp != NULL)
2010                 *controlp = NULL;
2011         if (flagsp != NULL) {
2012                 report_real_len = *flagsp & MSG_TRUNC;
2013                 *flagsp &= ~MSG_TRUNC;
2014                 flags = *flagsp &~ MSG_EOR;
2015         } else
2016                 flags = 0;
2017         if (flags & MSG_OOB)
2018                 return (soreceive_rcvoob(so, uio, flags));
2019         if (mp != NULL)
2020                 *mp = NULL;
2021         if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
2022             && uio->uio_resid) {
2023                 VNET_SO_ASSERT(so);
2024                 pr->pr_rcvd(so, 0);
2025         }
2026
2027         error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
2028         if (error)
2029                 return (error);
2030
2031 restart:
2032         SOCKBUF_LOCK(&so->so_rcv);
2033         m = so->so_rcv.sb_mb;
2034         /*
2035          * If we have less data than requested, block awaiting more (subject
2036          * to any timeout) if:
2037          *   1. the current count is less than the low water mark, or
2038          *   2. MSG_DONTWAIT is not set
2039          */
2040         if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
2041             sbavail(&so->so_rcv) < uio->uio_resid) &&
2042             sbavail(&so->so_rcv) < so->so_rcv.sb_lowat &&
2043             m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
2044                 KASSERT(m != NULL || !sbavail(&so->so_rcv),
2045                     ("receive: m == %p sbavail == %u",
2046                     m, sbavail(&so->so_rcv)));
2047                 if (so->so_error || so->so_rerror) {
2048                         if (m != NULL)
2049                                 goto dontblock;
2050                         if (so->so_error)
2051                                 error = so->so_error;
2052                         else
2053                                 error = so->so_rerror;
2054                         if ((flags & MSG_PEEK) == 0) {
2055                                 if (so->so_error)
2056                                         so->so_error = 0;
2057                                 else
2058                                         so->so_rerror = 0;
2059                         }
2060                         SOCKBUF_UNLOCK(&so->so_rcv);
2061                         goto release;
2062                 }
2063                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2064                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2065                         if (m != NULL)
2066                                 goto dontblock;
2067 #ifdef KERN_TLS
2068                         else if (so->so_rcv.sb_tlsdcc == 0 &&
2069                             so->so_rcv.sb_tlscc == 0) {
2070 #else
2071                         else {
2072 #endif
2073                                 SOCKBUF_UNLOCK(&so->so_rcv);
2074                                 goto release;
2075                         }
2076                 }
2077                 for (; m != NULL; m = m->m_next)
2078                         if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
2079                                 m = so->so_rcv.sb_mb;
2080                                 goto dontblock;
2081                         }
2082                 if ((so->so_state & (SS_ISCONNECTING | SS_ISCONNECTED |
2083                     SS_ISDISCONNECTING | SS_ISDISCONNECTED)) == 0 &&
2084                     (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
2085                         SOCKBUF_UNLOCK(&so->so_rcv);
2086                         error = ENOTCONN;
2087                         goto release;
2088                 }
2089                 if (uio->uio_resid == 0 && !report_real_len) {
2090                         SOCKBUF_UNLOCK(&so->so_rcv);
2091                         goto release;
2092                 }
2093                 if ((so->so_state & SS_NBIO) ||
2094                     (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2095                         SOCKBUF_UNLOCK(&so->so_rcv);
2096                         error = EWOULDBLOCK;
2097                         goto release;
2098                 }
2099                 SBLASTRECORDCHK(&so->so_rcv);
2100                 SBLASTMBUFCHK(&so->so_rcv);
2101                 error = sbwait(so, SO_RCV);
2102                 SOCKBUF_UNLOCK(&so->so_rcv);
2103                 if (error)
2104                         goto release;
2105                 goto restart;
2106         }
2107 dontblock:
2108         /*
2109          * From this point onward, we maintain 'nextrecord' as a cache of the
2110          * pointer to the next record in the socket buffer.  We must keep the
2111          * various socket buffer pointers and local stack versions of the
2112          * pointers in sync, pushing out modifications before dropping the
2113          * socket buffer mutex, and re-reading them when picking it up.
2114          *
2115          * Otherwise, we will race with the network stack appending new data
2116          * or records onto the socket buffer by using inconsistent/stale
2117          * versions of the field, possibly resulting in socket buffer
2118          * corruption.
2119          *
2120          * By holding the high-level sblock(), we prevent simultaneous
2121          * readers from pulling off the front of the socket buffer.
2122          */
2123         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2124         if (uio->uio_td)
2125                 uio->uio_td->td_ru.ru_msgrcv++;
2126         KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
2127         SBLASTRECORDCHK(&so->so_rcv);
2128         SBLASTMBUFCHK(&so->so_rcv);
2129         nextrecord = m->m_nextpkt;
2130         if (pr->pr_flags & PR_ADDR) {
2131                 KASSERT(m->m_type == MT_SONAME,
2132                     ("m->m_type == %d", m->m_type));
2133                 orig_resid = 0;
2134                 if (psa != NULL)
2135                         *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2136                             M_NOWAIT);
2137                 if (flags & MSG_PEEK) {
2138                         m = m->m_next;
2139                 } else {
2140                         sbfree(&so->so_rcv, m);
2141                         so->so_rcv.sb_mb = m_free(m);
2142                         m = so->so_rcv.sb_mb;
2143                         sockbuf_pushsync(&so->so_rcv, nextrecord);
2144                 }
2145         }
2146
2147         /*
2148          * Process one or more MT_CONTROL mbufs present before any data mbufs
2149          * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
2150          * just copy the data; if !MSG_PEEK, we call into the protocol to
2151          * perform externalization (or freeing if controlp == NULL).
2152          */
2153         if (m != NULL && m->m_type == MT_CONTROL) {
2154                 struct mbuf *cm = NULL, *cmn;
2155                 struct mbuf **cme = &cm;
2156 #ifdef KERN_TLS
2157                 struct cmsghdr *cmsg;
2158                 struct tls_get_record tgr;
2159
2160                 /*
2161                  * For MSG_TLSAPPDATA, check for an alert record.
2162                  * If found, return ENXIO without removing
2163                  * it from the receive queue.  This allows a subsequent
2164                  * call without MSG_TLSAPPDATA to receive it.
2165                  * Note that, for TLS, there should only be a single
2166                  * control mbuf with the TLS_GET_RECORD message in it.
2167                  */
2168                 if (flags & MSG_TLSAPPDATA) {
2169                         cmsg = mtod(m, struct cmsghdr *);
2170                         if (cmsg->cmsg_type == TLS_GET_RECORD &&
2171                             cmsg->cmsg_len == CMSG_LEN(sizeof(tgr))) {
2172                                 memcpy(&tgr, CMSG_DATA(cmsg), sizeof(tgr));
2173                                 if (__predict_false(tgr.tls_type ==
2174                                     TLS_RLTYPE_ALERT)) {
2175                                         SOCKBUF_UNLOCK(&so->so_rcv);
2176                                         error = ENXIO;
2177                                         goto release;
2178                                 }
2179                         }
2180                 }
2181 #endif
2182
2183                 do {
2184                         if (flags & MSG_PEEK) {
2185                                 if (controlp != NULL) {
2186                                         *controlp = m_copym(m, 0, m->m_len,
2187                                             M_NOWAIT);
2188                                         controlp = &(*controlp)->m_next;
2189                                 }
2190                                 m = m->m_next;
2191                         } else {
2192                                 sbfree(&so->so_rcv, m);
2193                                 so->so_rcv.sb_mb = m->m_next;
2194                                 m->m_next = NULL;
2195                                 *cme = m;
2196                                 cme = &(*cme)->m_next;
2197                                 m = so->so_rcv.sb_mb;
2198                         }
2199                 } while (m != NULL && m->m_type == MT_CONTROL);
2200                 if ((flags & MSG_PEEK) == 0)
2201                         sockbuf_pushsync(&so->so_rcv, nextrecord);
2202                 while (cm != NULL) {
2203                         cmn = cm->m_next;
2204                         cm->m_next = NULL;
2205                         if (pr->pr_domain->dom_externalize != NULL) {
2206                                 SOCKBUF_UNLOCK(&so->so_rcv);
2207                                 VNET_SO_ASSERT(so);
2208                                 error = (*pr->pr_domain->dom_externalize)
2209                                     (cm, controlp, flags);
2210                                 SOCKBUF_LOCK(&so->so_rcv);
2211                         } else if (controlp != NULL)
2212                                 *controlp = cm;
2213                         else
2214                                 m_freem(cm);
2215                         if (controlp != NULL) {
2216                                 while (*controlp != NULL)
2217                                         controlp = &(*controlp)->m_next;
2218                         }
2219                         cm = cmn;
2220                 }
2221                 if (m != NULL)
2222                         nextrecord = so->so_rcv.sb_mb->m_nextpkt;
2223                 else
2224                         nextrecord = so->so_rcv.sb_mb;
2225                 orig_resid = 0;
2226         }
2227         if (m != NULL) {
2228                 if ((flags & MSG_PEEK) == 0) {
2229                         KASSERT(m->m_nextpkt == nextrecord,
2230                             ("soreceive: post-control, nextrecord !sync"));
2231                         if (nextrecord == NULL) {
2232                                 KASSERT(so->so_rcv.sb_mb == m,
2233                                     ("soreceive: post-control, sb_mb!=m"));
2234                                 KASSERT(so->so_rcv.sb_lastrecord == m,
2235                                     ("soreceive: post-control, lastrecord!=m"));
2236                         }
2237                 }
2238                 type = m->m_type;
2239                 if (type == MT_OOBDATA)
2240                         flags |= MSG_OOB;
2241         } else {
2242                 if ((flags & MSG_PEEK) == 0) {
2243                         KASSERT(so->so_rcv.sb_mb == nextrecord,
2244                             ("soreceive: sb_mb != nextrecord"));
2245                         if (so->so_rcv.sb_mb == NULL) {
2246                                 KASSERT(so->so_rcv.sb_lastrecord == NULL,
2247                                     ("soreceive: sb_lastercord != NULL"));
2248                         }
2249                 }
2250         }
2251         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2252         SBLASTRECORDCHK(&so->so_rcv);
2253         SBLASTMBUFCHK(&so->so_rcv);
2254
2255         /*
2256          * Now continue to read any data mbufs off of the head of the socket
2257          * buffer until the read request is satisfied.  Note that 'type' is
2258          * used to store the type of any mbuf reads that have happened so far
2259          * such that soreceive() can stop reading if the type changes, which
2260          * causes soreceive() to return only one of regular data and inline
2261          * out-of-band data in a single socket receive operation.
2262          */
2263         moff = 0;
2264         offset = 0;
2265         while (m != NULL && !(m->m_flags & M_NOTAVAIL) && uio->uio_resid > 0
2266             && error == 0) {
2267                 /*
2268                  * If the type of mbuf has changed since the last mbuf
2269                  * examined ('type'), end the receive operation.
2270                  */
2271                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2272                 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
2273                         if (type != m->m_type)
2274                                 break;
2275                 } else if (type == MT_OOBDATA)
2276                         break;
2277                 else
2278                     KASSERT(m->m_type == MT_DATA,
2279                         ("m->m_type == %d", m->m_type));
2280                 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
2281                 len = uio->uio_resid;
2282                 if (so->so_oobmark && len > so->so_oobmark - offset)
2283                         len = so->so_oobmark - offset;
2284                 if (len > m->m_len - moff)
2285                         len = m->m_len - moff;
2286                 /*
2287                  * If mp is set, just pass back the mbufs.  Otherwise copy
2288                  * them out via the uio, then free.  Sockbuf must be
2289                  * consistent here (points to current mbuf, it points to next
2290                  * record) when we drop priority; we must note any additions
2291                  * to the sockbuf when we block interrupts again.
2292                  */
2293                 if (mp == NULL) {
2294                         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2295                         SBLASTRECORDCHK(&so->so_rcv);
2296                         SBLASTMBUFCHK(&so->so_rcv);
2297                         SOCKBUF_UNLOCK(&so->so_rcv);
2298                         if ((m->m_flags & M_EXTPG) != 0)
2299                                 error = m_unmapped_uiomove(m, moff, uio,
2300                                     (int)len);
2301                         else
2302                                 error = uiomove(mtod(m, char *) + moff,
2303                                     (int)len, uio);
2304                         SOCKBUF_LOCK(&so->so_rcv);
2305                         if (error) {
2306                                 /*
2307                                  * The MT_SONAME mbuf has already been removed
2308                                  * from the record, so it is necessary to
2309                                  * remove the data mbufs, if any, to preserve
2310                                  * the invariant in the case of PR_ADDR that
2311                                  * requires MT_SONAME mbufs at the head of
2312                                  * each record.
2313                                  */
2314                                 if (pr->pr_flags & PR_ATOMIC &&
2315                                     ((flags & MSG_PEEK) == 0))
2316                                         (void)sbdroprecord_locked(&so->so_rcv);
2317                                 SOCKBUF_UNLOCK(&so->so_rcv);
2318                                 goto release;
2319                         }
2320                 } else
2321                         uio->uio_resid -= len;
2322                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2323                 if (len == m->m_len - moff) {
2324                         if (m->m_flags & M_EOR)
2325                                 flags |= MSG_EOR;
2326                         if (flags & MSG_PEEK) {
2327                                 m = m->m_next;
2328                                 moff = 0;
2329                         } else {
2330                                 nextrecord = m->m_nextpkt;
2331                                 sbfree(&so->so_rcv, m);
2332                                 if (mp != NULL) {
2333                                         m->m_nextpkt = NULL;
2334                                         *mp = m;
2335                                         mp = &m->m_next;
2336                                         so->so_rcv.sb_mb = m = m->m_next;
2337                                         *mp = NULL;
2338                                 } else {
2339                                         so->so_rcv.sb_mb = m_free(m);
2340                                         m = so->so_rcv.sb_mb;
2341                                 }
2342                                 sockbuf_pushsync(&so->so_rcv, nextrecord);
2343                                 SBLASTRECORDCHK(&so->so_rcv);
2344                                 SBLASTMBUFCHK(&so->so_rcv);
2345                         }
2346                 } else {
2347                         if (flags & MSG_PEEK)
2348                                 moff += len;
2349                         else {
2350                                 if (mp != NULL) {
2351                                         if (flags & MSG_DONTWAIT) {
2352                                                 *mp = m_copym(m, 0, len,
2353                                                     M_NOWAIT);
2354                                                 if (*mp == NULL) {
2355                                                         /*
2356                                                          * m_copym() couldn't
2357                                                          * allocate an mbuf.
2358                                                          * Adjust uio_resid back
2359                                                          * (it was adjusted
2360                                                          * down by len bytes,
2361                                                          * which we didn't end
2362                                                          * up "copying" over).
2363                                                          */
2364                                                         uio->uio_resid += len;
2365                                                         break;
2366                                                 }
2367                                         } else {
2368                                                 SOCKBUF_UNLOCK(&so->so_rcv);
2369                                                 *mp = m_copym(m, 0, len,
2370                                                     M_WAITOK);
2371                                                 SOCKBUF_LOCK(&so->so_rcv);
2372                                         }
2373                                 }
2374                                 sbcut_locked(&so->so_rcv, len);
2375                         }
2376                 }
2377                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2378                 if (so->so_oobmark) {
2379                         if ((flags & MSG_PEEK) == 0) {
2380                                 so->so_oobmark -= len;
2381                                 if (so->so_oobmark == 0) {
2382                                         so->so_rcv.sb_state |= SBS_RCVATMARK;
2383                                         break;
2384                                 }
2385                         } else {
2386                                 offset += len;
2387                                 if (offset == so->so_oobmark)
2388                                         break;
2389                         }
2390                 }
2391                 if (flags & MSG_EOR)
2392                         break;
2393                 /*
2394                  * If the MSG_WAITALL flag is set (for non-atomic socket), we
2395                  * must not quit until "uio->uio_resid == 0" or an error
2396                  * termination.  If a signal/timeout occurs, return with a
2397                  * short count but without error.  Keep sockbuf locked
2398                  * against other readers.
2399                  */
2400                 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
2401                     !sosendallatonce(so) && nextrecord == NULL) {
2402                         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2403                         if (so->so_error || so->so_rerror ||
2404                             so->so_rcv.sb_state & SBS_CANTRCVMORE)
2405                                 break;
2406                         /*
2407                          * Notify the protocol that some data has been
2408                          * drained before blocking.
2409                          */
2410                         if (pr->pr_flags & PR_WANTRCVD) {
2411                                 SOCKBUF_UNLOCK(&so->so_rcv);
2412                                 VNET_SO_ASSERT(so);
2413                                 pr->pr_rcvd(so, flags);
2414                                 SOCKBUF_LOCK(&so->so_rcv);
2415                         }
2416                         SBLASTRECORDCHK(&so->so_rcv);
2417                         SBLASTMBUFCHK(&so->so_rcv);
2418                         /*
2419                          * We could receive some data while was notifying
2420                          * the protocol. Skip blocking in this case.
2421                          */
2422                         if (so->so_rcv.sb_mb == NULL) {
2423                                 error = sbwait(so, SO_RCV);
2424                                 if (error) {
2425                                         SOCKBUF_UNLOCK(&so->so_rcv);
2426                                         goto release;
2427                                 }
2428                         }
2429                         m = so->so_rcv.sb_mb;
2430                         if (m != NULL)
2431                                 nextrecord = m->m_nextpkt;
2432                 }
2433         }
2434
2435         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2436         if (m != NULL && pr->pr_flags & PR_ATOMIC) {
2437                 if (report_real_len)
2438                         uio->uio_resid -= m_length(m, NULL) - moff;
2439                 flags |= MSG_TRUNC;
2440                 if ((flags & MSG_PEEK) == 0)
2441                         (void) sbdroprecord_locked(&so->so_rcv);
2442         }
2443         if ((flags & MSG_PEEK) == 0) {
2444                 if (m == NULL) {
2445                         /*
2446                          * First part is an inline SB_EMPTY_FIXUP().  Second
2447                          * part makes sure sb_lastrecord is up-to-date if
2448                          * there is still data in the socket buffer.
2449                          */
2450                         so->so_rcv.sb_mb = nextrecord;
2451                         if (so->so_rcv.sb_mb == NULL) {
2452                                 so->so_rcv.sb_mbtail = NULL;
2453                                 so->so_rcv.sb_lastrecord = NULL;
2454                         } else if (nextrecord->m_nextpkt == NULL)
2455                                 so->so_rcv.sb_lastrecord = nextrecord;
2456                 }
2457                 SBLASTRECORDCHK(&so->so_rcv);
2458                 SBLASTMBUFCHK(&so->so_rcv);
2459                 /*
2460                  * If soreceive() is being done from the socket callback,
2461                  * then don't need to generate ACK to peer to update window,
2462                  * since ACK will be generated on return to TCP.
2463                  */
2464                 if (!(flags & MSG_SOCALLBCK) &&
2465                     (pr->pr_flags & PR_WANTRCVD)) {
2466                         SOCKBUF_UNLOCK(&so->so_rcv);
2467                         VNET_SO_ASSERT(so);
2468                         pr->pr_rcvd(so, flags);
2469                         SOCKBUF_LOCK(&so->so_rcv);
2470                 }
2471         }
2472         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2473         if (orig_resid == uio->uio_resid && orig_resid &&
2474             (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
2475                 SOCKBUF_UNLOCK(&so->so_rcv);
2476                 goto restart;
2477         }
2478         SOCKBUF_UNLOCK(&so->so_rcv);
2479
2480         if (flagsp != NULL)
2481                 *flagsp |= flags;
2482 release:
2483         SOCK_IO_RECV_UNLOCK(so);
2484         return (error);
2485 }
2486
2487 /*
2488  * Optimized version of soreceive() for stream (TCP) sockets.
2489  */
2490 int
2491 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
2492     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2493 {
2494         int len = 0, error = 0, flags, oresid;
2495         struct sockbuf *sb;
2496         struct mbuf *m, *n = NULL;
2497
2498         /* We only do stream sockets. */
2499         if (so->so_type != SOCK_STREAM)
2500                 return (EINVAL);
2501         if (psa != NULL)
2502                 *psa = NULL;
2503         if (flagsp != NULL)
2504                 flags = *flagsp &~ MSG_EOR;
2505         else
2506                 flags = 0;
2507         if (controlp != NULL)
2508                 *controlp = NULL;
2509         if (flags & MSG_OOB)
2510                 return (soreceive_rcvoob(so, uio, flags));
2511         if (mp0 != NULL)
2512                 *mp0 = NULL;
2513
2514         sb = &so->so_rcv;
2515
2516 #ifdef KERN_TLS
2517         /*
2518          * KTLS store TLS records as records with a control message to
2519          * describe the framing.
2520          *
2521          * We check once here before acquiring locks to optimize the
2522          * common case.
2523          */
2524         if (sb->sb_tls_info != NULL)
2525                 return (soreceive_generic(so, psa, uio, mp0, controlp,
2526                     flagsp));
2527 #endif
2528
2529         /* Prevent other readers from entering the socket. */
2530         error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
2531         if (error)
2532                 return (error);
2533         SOCKBUF_LOCK(sb);
2534
2535 #ifdef KERN_TLS
2536         if (sb->sb_tls_info != NULL) {
2537                 SOCKBUF_UNLOCK(sb);
2538                 SOCK_IO_RECV_UNLOCK(so);
2539                 return (soreceive_generic(so, psa, uio, mp0, controlp,
2540                     flagsp));
2541         }
2542 #endif
2543
2544         /* Easy one, no space to copyout anything. */
2545         if (uio->uio_resid == 0) {
2546                 error = EINVAL;
2547                 goto out;
2548         }
2549         oresid = uio->uio_resid;
2550
2551         /* We will never ever get anything unless we are or were connected. */
2552         if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
2553                 error = ENOTCONN;
2554                 goto out;
2555         }
2556
2557 restart:
2558         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2559
2560         /* Abort if socket has reported problems. */
2561         if (so->so_error) {
2562                 if (sbavail(sb) > 0)
2563                         goto deliver;
2564                 if (oresid > uio->uio_resid)
2565                         goto out;
2566                 error = so->so_error;
2567                 if (!(flags & MSG_PEEK))
2568                         so->so_error = 0;
2569                 goto out;
2570         }
2571
2572         /* Door is closed.  Deliver what is left, if any. */
2573         if (sb->sb_state & SBS_CANTRCVMORE) {
2574                 if (sbavail(sb) > 0)
2575                         goto deliver;
2576                 else
2577                         goto out;
2578         }
2579
2580         /* Socket buffer is empty and we shall not block. */
2581         if (sbavail(sb) == 0 &&
2582             ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2583                 error = EAGAIN;
2584                 goto out;
2585         }
2586
2587         /* Socket buffer got some data that we shall deliver now. */
2588         if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
2589             ((so->so_state & SS_NBIO) ||
2590              (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2591              sbavail(sb) >= sb->sb_lowat ||
2592              sbavail(sb) >= uio->uio_resid ||
2593              sbavail(sb) >= sb->sb_hiwat) ) {
2594                 goto deliver;
2595         }
2596
2597         /* On MSG_WAITALL we must wait until all data or error arrives. */
2598         if ((flags & MSG_WAITALL) &&
2599             (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
2600                 goto deliver;
2601
2602         /*
2603          * Wait and block until (more) data comes in.
2604          * NB: Drops the sockbuf lock during wait.
2605          */
2606         error = sbwait(so, SO_RCV);
2607         if (error)
2608                 goto out;
2609         goto restart;
2610
2611 deliver:
2612         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2613         KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
2614         KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2615
2616         /* Statistics. */
2617         if (uio->uio_td)
2618                 uio->uio_td->td_ru.ru_msgrcv++;
2619
2620         /* Fill uio until full or current end of socket buffer is reached. */
2621         len = min(uio->uio_resid, sbavail(sb));
2622         if (mp0 != NULL) {
2623                 /* Dequeue as many mbufs as possible. */
2624                 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2625                         if (*mp0 == NULL)
2626                                 *mp0 = sb->sb_mb;
2627                         else
2628                                 m_cat(*mp0, sb->sb_mb);
2629                         for (m = sb->sb_mb;
2630                              m != NULL && m->m_len <= len;
2631                              m = m->m_next) {
2632                                 KASSERT(!(m->m_flags & M_NOTAVAIL),
2633                                     ("%s: m %p not available", __func__, m));
2634                                 len -= m->m_len;
2635                                 uio->uio_resid -= m->m_len;
2636                                 sbfree(sb, m);
2637                                 n = m;
2638                         }
2639                         n->m_next = NULL;
2640                         sb->sb_mb = m;
2641                         sb->sb_lastrecord = sb->sb_mb;
2642                         if (sb->sb_mb == NULL)
2643                                 SB_EMPTY_FIXUP(sb);
2644                 }
2645                 /* Copy the remainder. */
2646                 if (len > 0) {
2647                         KASSERT(sb->sb_mb != NULL,
2648                             ("%s: len > 0 && sb->sb_mb empty", __func__));
2649
2650                         m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
2651                         if (m == NULL)
2652                                 len = 0;        /* Don't flush data from sockbuf. */
2653                         else
2654                                 uio->uio_resid -= len;
2655                         if (*mp0 != NULL)
2656                                 m_cat(*mp0, m);
2657                         else
2658                                 *mp0 = m;
2659                         if (*mp0 == NULL) {
2660                                 error = ENOBUFS;
2661                                 goto out;
2662                         }
2663                 }
2664         } else {
2665                 /* NB: Must unlock socket buffer as uiomove may sleep. */
2666                 SOCKBUF_UNLOCK(sb);
2667                 error = m_mbuftouio(uio, sb->sb_mb, len);
2668                 SOCKBUF_LOCK(sb);
2669                 if (error)
2670                         goto out;
2671         }
2672         SBLASTRECORDCHK(sb);
2673         SBLASTMBUFCHK(sb);
2674
2675         /*
2676          * Remove the delivered data from the socket buffer unless we
2677          * were only peeking.
2678          */
2679         if (!(flags & MSG_PEEK)) {
2680                 if (len > 0)
2681                         sbdrop_locked(sb, len);
2682
2683                 /* Notify protocol that we drained some data. */
2684                 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2685                     (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2686                      !(flags & MSG_SOCALLBCK))) {
2687                         SOCKBUF_UNLOCK(sb);
2688                         VNET_SO_ASSERT(so);
2689                         so->so_proto->pr_rcvd(so, flags);
2690                         SOCKBUF_LOCK(sb);
2691                 }
2692         }
2693
2694         /*
2695          * For MSG_WAITALL we may have to loop again and wait for
2696          * more data to come in.
2697          */
2698         if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2699                 goto restart;
2700 out:
2701         SBLASTRECORDCHK(sb);
2702         SBLASTMBUFCHK(sb);
2703         SOCKBUF_UNLOCK(sb);
2704         SOCK_IO_RECV_UNLOCK(so);
2705         return (error);
2706 }
2707
2708 /*
2709  * Optimized version of soreceive() for simple datagram cases from userspace.
2710  * Unlike in the stream case, we're able to drop a datagram if copyout()
2711  * fails, and because we handle datagrams atomically, we don't need to use a
2712  * sleep lock to prevent I/O interlacing.
2713  */
2714 int
2715 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2716     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2717 {
2718         struct mbuf *m, *m2;
2719         int flags, error;
2720         ssize_t len;
2721         struct protosw *pr = so->so_proto;
2722         struct mbuf *nextrecord;
2723
2724         if (psa != NULL)
2725                 *psa = NULL;
2726         if (controlp != NULL)
2727                 *controlp = NULL;
2728         if (flagsp != NULL)
2729                 flags = *flagsp &~ MSG_EOR;
2730         else
2731                 flags = 0;
2732
2733         /*
2734          * For any complicated cases, fall back to the full
2735          * soreceive_generic().
2736          */
2737         if (mp0 != NULL || (flags & (MSG_PEEK | MSG_OOB | MSG_TRUNC)))
2738                 return (soreceive_generic(so, psa, uio, mp0, controlp,
2739                     flagsp));
2740
2741         /*
2742          * Enforce restrictions on use.
2743          */
2744         KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2745             ("soreceive_dgram: wantrcvd"));
2746         KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2747         KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2748             ("soreceive_dgram: SBS_RCVATMARK"));
2749         KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2750             ("soreceive_dgram: P_CONNREQUIRED"));
2751
2752         /*
2753          * Loop blocking while waiting for a datagram.
2754          */
2755         SOCKBUF_LOCK(&so->so_rcv);
2756         while ((m = so->so_rcv.sb_mb) == NULL) {
2757                 KASSERT(sbavail(&so->so_rcv) == 0,
2758                     ("soreceive_dgram: sb_mb NULL but sbavail %u",
2759                     sbavail(&so->so_rcv)));
2760                 if (so->so_error) {
2761                         error = so->so_error;
2762                         so->so_error = 0;
2763                         SOCKBUF_UNLOCK(&so->so_rcv);
2764                         return (error);
2765                 }
2766                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2767                     uio->uio_resid == 0) {
2768                         SOCKBUF_UNLOCK(&so->so_rcv);
2769                         return (0);
2770                 }
2771                 if ((so->so_state & SS_NBIO) ||
2772                     (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2773                         SOCKBUF_UNLOCK(&so->so_rcv);
2774                         return (EWOULDBLOCK);
2775                 }
2776                 SBLASTRECORDCHK(&so->so_rcv);
2777                 SBLASTMBUFCHK(&so->so_rcv);
2778                 error = sbwait(so, SO_RCV);
2779                 if (error) {
2780                         SOCKBUF_UNLOCK(&so->so_rcv);
2781                         return (error);
2782                 }
2783         }
2784         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2785
2786         if (uio->uio_td)
2787                 uio->uio_td->td_ru.ru_msgrcv++;
2788         SBLASTRECORDCHK(&so->so_rcv);
2789         SBLASTMBUFCHK(&so->so_rcv);
2790         nextrecord = m->m_nextpkt;
2791         if (nextrecord == NULL) {
2792                 KASSERT(so->so_rcv.sb_lastrecord == m,
2793                     ("soreceive_dgram: lastrecord != m"));
2794         }
2795
2796         KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2797             ("soreceive_dgram: m_nextpkt != nextrecord"));
2798
2799         /*
2800          * Pull 'm' and its chain off the front of the packet queue.
2801          */
2802         so->so_rcv.sb_mb = NULL;
2803         sockbuf_pushsync(&so->so_rcv, nextrecord);
2804
2805         /*
2806          * Walk 'm's chain and free that many bytes from the socket buffer.
2807          */
2808         for (m2 = m; m2 != NULL; m2 = m2->m_next)
2809                 sbfree(&so->so_rcv, m2);
2810
2811         /*
2812          * Do a few last checks before we let go of the lock.
2813          */
2814         SBLASTRECORDCHK(&so->so_rcv);
2815         SBLASTMBUFCHK(&so->so_rcv);
2816         SOCKBUF_UNLOCK(&so->so_rcv);
2817
2818         if (pr->pr_flags & PR_ADDR) {
2819                 KASSERT(m->m_type == MT_SONAME,
2820                     ("m->m_type == %d", m->m_type));
2821                 if (psa != NULL)
2822                         *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2823                             M_NOWAIT);
2824                 m = m_free(m);
2825         }
2826         if (m == NULL) {
2827                 /* XXXRW: Can this happen? */
2828                 return (0);
2829         }
2830
2831         /*
2832          * Packet to copyout() is now in 'm' and it is disconnected from the
2833          * queue.
2834          *
2835          * Process one or more MT_CONTROL mbufs present before any data mbufs
2836          * in the first mbuf chain on the socket buffer.  We call into the
2837          * protocol to perform externalization (or freeing if controlp ==
2838          * NULL). In some cases there can be only MT_CONTROL mbufs without
2839          * MT_DATA mbufs.
2840          */
2841         if (m->m_type == MT_CONTROL) {
2842                 struct mbuf *cm = NULL, *cmn;
2843                 struct mbuf **cme = &cm;
2844
2845                 do {
2846                         m2 = m->m_next;
2847                         m->m_next = NULL;
2848                         *cme = m;
2849                         cme = &(*cme)->m_next;
2850                         m = m2;
2851                 } while (m != NULL && m->m_type == MT_CONTROL);
2852                 while (cm != NULL) {
2853                         cmn = cm->m_next;
2854                         cm->m_next = NULL;
2855                         if (pr->pr_domain->dom_externalize != NULL) {
2856                                 error = (*pr->pr_domain->dom_externalize)
2857                                     (cm, controlp, flags);
2858                         } else if (controlp != NULL)
2859                                 *controlp = cm;
2860                         else
2861                                 m_freem(cm);
2862                         if (controlp != NULL) {
2863                                 while (*controlp != NULL)
2864                                         controlp = &(*controlp)->m_next;
2865                         }
2866                         cm = cmn;
2867                 }
2868         }
2869         KASSERT(m == NULL || m->m_type == MT_DATA,
2870             ("soreceive_dgram: !data"));
2871         while (m != NULL && uio->uio_resid > 0) {
2872                 len = uio->uio_resid;
2873                 if (len > m->m_len)
2874                         len = m->m_len;
2875                 error = uiomove(mtod(m, char *), (int)len, uio);
2876                 if (error) {
2877                         m_freem(m);
2878                         return (error);
2879                 }
2880                 if (len == m->m_len)
2881                         m = m_free(m);
2882                 else {
2883                         m->m_data += len;
2884                         m->m_len -= len;
2885                 }
2886         }
2887         if (m != NULL) {
2888                 flags |= MSG_TRUNC;
2889                 m_freem(m);
2890         }
2891         if (flagsp != NULL)
2892                 *flagsp |= flags;
2893         return (0);
2894 }
2895
2896 int
2897 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2898     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2899 {
2900         int error;
2901
2902         CURVNET_SET(so->so_vnet);
2903         error = so->so_proto->pr_soreceive(so, psa, uio, mp0, controlp, flagsp);
2904         CURVNET_RESTORE();
2905         return (error);
2906 }
2907
2908 int
2909 soshutdown(struct socket *so, int how)
2910 {
2911         struct protosw *pr;
2912         int error, soerror_enotconn;
2913
2914         if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2915                 return (EINVAL);
2916
2917         soerror_enotconn = 0;
2918         SOCK_LOCK(so);
2919         if ((so->so_state &
2920             (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
2921                 /*
2922                  * POSIX mandates us to return ENOTCONN when shutdown(2) is
2923                  * invoked on a datagram sockets, however historically we would
2924                  * actually tear socket down. This is known to be leveraged by
2925                  * some applications to unblock process waiting in recvXXX(2)
2926                  * by other process that it shares that socket with. Try to meet
2927                  * both backward-compatibility and POSIX requirements by forcing
2928                  * ENOTCONN but still asking protocol to perform pru_shutdown().
2929                  */
2930                 if (so->so_type != SOCK_DGRAM && !SOLISTENING(so)) {
2931                         SOCK_UNLOCK(so);
2932                         return (ENOTCONN);
2933                 }
2934                 soerror_enotconn = 1;
2935         }
2936
2937         if (SOLISTENING(so)) {
2938                 if (how != SHUT_WR) {
2939                         so->so_error = ECONNABORTED;
2940                         solisten_wakeup(so);    /* unlocks so */
2941                 } else {
2942                         SOCK_UNLOCK(so);
2943                 }
2944                 goto done;
2945         }
2946         SOCK_UNLOCK(so);
2947
2948         CURVNET_SET(so->so_vnet);
2949         pr = so->so_proto;
2950         if (pr->pr_flush != NULL)
2951                 pr->pr_flush(so, how);
2952         if (how != SHUT_WR)
2953                 sorflush(so);
2954         if (how != SHUT_RD) {
2955                 error = pr->pr_shutdown(so);
2956                 wakeup(&so->so_timeo);
2957                 CURVNET_RESTORE();
2958                 return ((error == 0 && soerror_enotconn) ? ENOTCONN : error);
2959         }
2960         wakeup(&so->so_timeo);
2961         CURVNET_RESTORE();
2962
2963 done:
2964         return (soerror_enotconn ? ENOTCONN : 0);
2965 }
2966
2967 void
2968 sorflush(struct socket *so)
2969 {
2970         struct protosw *pr;
2971         int error;
2972
2973         VNET_SO_ASSERT(so);
2974
2975         /*
2976          * Dislodge threads currently blocked in receive and wait to acquire
2977          * a lock against other simultaneous readers before clearing the
2978          * socket buffer.  Don't let our acquire be interrupted by a signal
2979          * despite any existing socket disposition on interruptable waiting.
2980          */
2981         socantrcvmore(so);
2982
2983         error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR);
2984         if (error != 0) {
2985                 KASSERT(SOLISTENING(so),
2986                     ("%s: soiolock(%p) failed", __func__, so));
2987                 return;
2988         }
2989
2990         pr = so->so_proto;
2991         if (pr->pr_flags & PR_RIGHTS) {
2992                 MPASS(pr->pr_domain->dom_dispose != NULL);
2993                 (*pr->pr_domain->dom_dispose)(so);
2994         } else {
2995                 sbrelease(so, SO_RCV);
2996                 SOCK_IO_RECV_UNLOCK(so);
2997         }
2998
2999 }
3000
3001 /*
3002  * Wrapper for Socket established helper hook.
3003  * Parameters: socket, context of the hook point, hook id.
3004  */
3005 static int inline
3006 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
3007 {
3008         struct socket_hhook_data hhook_data = {
3009                 .so = so,
3010                 .hctx = hctx,
3011                 .m = NULL,
3012                 .status = 0
3013         };
3014
3015         CURVNET_SET(so->so_vnet);
3016         HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
3017         CURVNET_RESTORE();
3018
3019         /* Ugly but needed, since hhooks return void for now */
3020         return (hhook_data.status);
3021 }
3022
3023 /*
3024  * Perhaps this routine, and sooptcopyout(), below, ought to come in an
3025  * additional variant to handle the case where the option value needs to be
3026  * some kind of integer, but not a specific size.  In addition to their use
3027  * here, these functions are also called by the protocol-level pr_ctloutput()
3028  * routines.
3029  */
3030 int
3031 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
3032 {
3033         size_t  valsize;
3034
3035         /*
3036          * If the user gives us more than we wanted, we ignore it, but if we
3037          * don't get the minimum length the caller wants, we return EINVAL.
3038          * On success, sopt->sopt_valsize is set to however much we actually
3039          * retrieved.
3040          */
3041         if ((valsize = sopt->sopt_valsize) < minlen)
3042                 return EINVAL;
3043         if (valsize > len)
3044                 sopt->sopt_valsize = valsize = len;
3045
3046         if (sopt->sopt_td != NULL)
3047                 return (copyin(sopt->sopt_val, buf, valsize));
3048
3049         bcopy(sopt->sopt_val, buf, valsize);
3050         return (0);
3051 }
3052
3053 /*
3054  * Kernel version of setsockopt(2).
3055  *
3056  * XXX: optlen is size_t, not socklen_t
3057  */
3058 int
3059 so_setsockopt(struct socket *so, int level, int optname, void *optval,
3060     size_t optlen)
3061 {
3062         struct sockopt sopt;
3063
3064         sopt.sopt_level = level;
3065         sopt.sopt_name = optname;
3066         sopt.sopt_dir = SOPT_SET;
3067         sopt.sopt_val = optval;
3068         sopt.sopt_valsize = optlen;
3069         sopt.sopt_td = NULL;
3070         return (sosetopt(so, &sopt));
3071 }
3072
3073 int
3074 sosetopt(struct socket *so, struct sockopt *sopt)
3075 {
3076         int     error, optval;
3077         struct  linger l;
3078         struct  timeval tv;
3079         sbintime_t val, *valp;
3080         uint32_t val32;
3081 #ifdef MAC
3082         struct mac extmac;
3083 #endif
3084
3085         CURVNET_SET(so->so_vnet);
3086         error = 0;
3087         if (sopt->sopt_level != SOL_SOCKET) {
3088                 if (so->so_proto->pr_ctloutput != NULL)
3089                         error = (*so->so_proto->pr_ctloutput)(so, sopt);
3090                 else
3091                         error = ENOPROTOOPT;
3092         } else {
3093                 switch (sopt->sopt_name) {
3094                 case SO_ACCEPTFILTER:
3095                         error = accept_filt_setopt(so, sopt);
3096                         if (error)
3097                                 goto bad;
3098                         break;
3099
3100                 case SO_LINGER:
3101                         error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
3102                         if (error)
3103                                 goto bad;
3104                         if (l.l_linger < 0 ||
3105                             l.l_linger > USHRT_MAX ||
3106                             l.l_linger > (INT_MAX / hz)) {
3107                                 error = EDOM;
3108                                 goto bad;
3109                         }
3110                         SOCK_LOCK(so);
3111                         so->so_linger = l.l_linger;
3112                         if (l.l_onoff)
3113                                 so->so_options |= SO_LINGER;
3114                         else
3115                                 so->so_options &= ~SO_LINGER;
3116                         SOCK_UNLOCK(so);
3117                         break;
3118
3119                 case SO_DEBUG:
3120                 case SO_KEEPALIVE:
3121                 case SO_DONTROUTE:
3122                 case SO_USELOOPBACK:
3123                 case SO_BROADCAST:
3124                 case SO_REUSEADDR:
3125                 case SO_REUSEPORT:
3126                 case SO_REUSEPORT_LB:
3127                 case SO_OOBINLINE:
3128                 case SO_TIMESTAMP:
3129                 case SO_BINTIME:
3130                 case SO_NOSIGPIPE:
3131                 case SO_NO_DDP:
3132                 case SO_NO_OFFLOAD:
3133                 case SO_RERROR:
3134                         error = sooptcopyin(sopt, &optval, sizeof optval,
3135                             sizeof optval);
3136                         if (error)
3137                                 goto bad;
3138                         SOCK_LOCK(so);
3139                         if (optval)
3140                                 so->so_options |= sopt->sopt_name;
3141                         else
3142                                 so->so_options &= ~sopt->sopt_name;
3143                         SOCK_UNLOCK(so);
3144                         break;
3145
3146                 case SO_SETFIB:
3147                         error = sooptcopyin(sopt, &optval, sizeof optval,
3148                             sizeof optval);
3149                         if (error)
3150                                 goto bad;
3151
3152                         if (optval < 0 || optval >= rt_numfibs) {
3153                                 error = EINVAL;
3154                                 goto bad;
3155                         }
3156                         if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
3157                            (so->so_proto->pr_domain->dom_family == PF_INET6) ||
3158                            (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
3159                                 so->so_fibnum = optval;
3160                         else
3161                                 so->so_fibnum = 0;
3162                         break;
3163
3164                 case SO_USER_COOKIE:
3165                         error = sooptcopyin(sopt, &val32, sizeof val32,
3166                             sizeof val32);
3167                         if (error)
3168                                 goto bad;
3169                         so->so_user_cookie = val32;
3170                         break;
3171
3172                 case SO_SNDBUF:
3173                 case SO_RCVBUF:
3174                 case SO_SNDLOWAT:
3175                 case SO_RCVLOWAT:
3176                         error = so->so_proto->pr_setsbopt(so, sopt);
3177                         if (error)
3178                                 goto bad;
3179                         break;
3180
3181                 case SO_SNDTIMEO:
3182                 case SO_RCVTIMEO:
3183 #ifdef COMPAT_FREEBSD32
3184                         if (SV_CURPROC_FLAG(SV_ILP32)) {
3185                                 struct timeval32 tv32;
3186
3187                                 error = sooptcopyin(sopt, &tv32, sizeof tv32,
3188                                     sizeof tv32);
3189                                 CP(tv32, tv, tv_sec);
3190                                 CP(tv32, tv, tv_usec);
3191                         } else
3192 #endif
3193                                 error = sooptcopyin(sopt, &tv, sizeof tv,
3194                                     sizeof tv);
3195                         if (error)
3196                                 goto bad;
3197                         if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
3198                             tv.tv_usec >= 1000000) {
3199                                 error = EDOM;
3200                                 goto bad;
3201                         }
3202                         if (tv.tv_sec > INT32_MAX)
3203                                 val = SBT_MAX;
3204                         else
3205                                 val = tvtosbt(tv);
3206                         SOCK_LOCK(so);
3207                         valp = sopt->sopt_name == SO_SNDTIMEO ?
3208                             (SOLISTENING(so) ? &so->sol_sbsnd_timeo :
3209                             &so->so_snd.sb_timeo) :
3210                             (SOLISTENING(so) ? &so->sol_sbrcv_timeo :
3211                             &so->so_rcv.sb_timeo);
3212                         *valp = val;
3213                         SOCK_UNLOCK(so);
3214                         break;
3215
3216                 case SO_LABEL:
3217 #ifdef MAC
3218                         error = sooptcopyin(sopt, &extmac, sizeof extmac,
3219                             sizeof extmac);
3220                         if (error)
3221                                 goto bad;
3222                         error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
3223                             so, &extmac);
3224 #else
3225                         error = EOPNOTSUPP;
3226 #endif
3227                         break;
3228
3229                 case SO_TS_CLOCK:
3230                         error = sooptcopyin(sopt, &optval, sizeof optval,
3231                             sizeof optval);
3232                         if (error)
3233                                 goto bad;
3234                         if (optval < 0 || optval > SO_TS_CLOCK_MAX) {
3235                                 error = EINVAL;
3236                                 goto bad;
3237                         }
3238                         so->so_ts_clock = optval;
3239                         break;
3240
3241                 case SO_MAX_PACING_RATE:
3242                         error = sooptcopyin(sopt, &val32, sizeof(val32),
3243                             sizeof(val32));
3244                         if (error)
3245                                 goto bad;
3246                         so->so_max_pacing_rate = val32;
3247                         break;
3248
3249                 default:
3250                         if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3251                                 error = hhook_run_socket(so, sopt,
3252                                     HHOOK_SOCKET_OPT);
3253                         else
3254                                 error = ENOPROTOOPT;
3255                         break;
3256                 }
3257                 if (error == 0 && so->so_proto->pr_ctloutput != NULL)
3258                         (void)(*so->so_proto->pr_ctloutput)(so, sopt);
3259         }
3260 bad:
3261         CURVNET_RESTORE();
3262         return (error);
3263 }
3264
3265 /*
3266  * Helper routine for getsockopt.
3267  */
3268 int
3269 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
3270 {
3271         int     error;
3272         size_t  valsize;
3273
3274         error = 0;
3275
3276         /*
3277          * Documented get behavior is that we always return a value, possibly
3278          * truncated to fit in the user's buffer.  Traditional behavior is
3279          * that we always tell the user precisely how much we copied, rather
3280          * than something useful like the total amount we had available for
3281          * her.  Note that this interface is not idempotent; the entire
3282          * answer must be generated ahead of time.
3283          */
3284         valsize = min(len, sopt->sopt_valsize);
3285         sopt->sopt_valsize = valsize;
3286         if (sopt->sopt_val != NULL) {
3287                 if (sopt->sopt_td != NULL)
3288                         error = copyout(buf, sopt->sopt_val, valsize);
3289                 else
3290                         bcopy(buf, sopt->sopt_val, valsize);
3291         }
3292         return (error);
3293 }
3294
3295 int
3296 sogetopt(struct socket *so, struct sockopt *sopt)
3297 {
3298         int     error, optval;
3299         struct  linger l;
3300         struct  timeval tv;
3301 #ifdef MAC
3302         struct mac extmac;
3303 #endif
3304
3305         CURVNET_SET(so->so_vnet);
3306         error = 0;
3307         if (sopt->sopt_level != SOL_SOCKET) {
3308                 if (so->so_proto->pr_ctloutput != NULL)
3309                         error = (*so->so_proto->pr_ctloutput)(so, sopt);
3310                 else
3311                         error = ENOPROTOOPT;
3312                 CURVNET_RESTORE();
3313                 return (error);
3314         } else {
3315                 switch (sopt->sopt_name) {
3316                 case SO_ACCEPTFILTER:
3317                         error = accept_filt_getopt(so, sopt);
3318                         break;
3319
3320                 case SO_LINGER:
3321                         SOCK_LOCK(so);
3322                         l.l_onoff = so->so_options & SO_LINGER;
3323                         l.l_linger = so->so_linger;
3324                         SOCK_UNLOCK(so);
3325                         error = sooptcopyout(sopt, &l, sizeof l);
3326                         break;
3327
3328                 case SO_USELOOPBACK:
3329                 case SO_DONTROUTE:
3330                 case SO_DEBUG:
3331                 case SO_KEEPALIVE:
3332                 case SO_REUSEADDR:
3333                 case SO_REUSEPORT:
3334                 case SO_REUSEPORT_LB:
3335                 case SO_BROADCAST:
3336                 case SO_OOBINLINE:
3337                 case SO_ACCEPTCONN:
3338                 case SO_TIMESTAMP:
3339                 case SO_BINTIME:
3340                 case SO_NOSIGPIPE:
3341                 case SO_NO_DDP:
3342                 case SO_NO_OFFLOAD:
3343                 case SO_RERROR:
3344                         optval = so->so_options & sopt->sopt_name;
3345 integer:
3346                         error = sooptcopyout(sopt, &optval, sizeof optval);
3347                         break;
3348
3349                 case SO_DOMAIN:
3350                         optval = so->so_proto->pr_domain->dom_family;
3351                         goto integer;
3352
3353                 case SO_TYPE:
3354                         optval = so->so_type;
3355                         goto integer;
3356
3357                 case SO_PROTOCOL:
3358                         optval = so->so_proto->pr_protocol;
3359                         goto integer;
3360
3361                 case SO_ERROR:
3362                         SOCK_LOCK(so);
3363                         if (so->so_error) {
3364                                 optval = so->so_error;
3365                                 so->so_error = 0;
3366                         } else {
3367                                 optval = so->so_rerror;
3368                                 so->so_rerror = 0;
3369                         }
3370                         SOCK_UNLOCK(so);
3371                         goto integer;
3372
3373                 case SO_SNDBUF:
3374                         optval = SOLISTENING(so) ? so->sol_sbsnd_hiwat :
3375                             so->so_snd.sb_hiwat;
3376                         goto integer;
3377
3378                 case SO_RCVBUF:
3379                         optval = SOLISTENING(so) ? so->sol_sbrcv_hiwat :
3380                             so->so_rcv.sb_hiwat;
3381                         goto integer;
3382
3383                 case SO_SNDLOWAT:
3384                         optval = SOLISTENING(so) ? so->sol_sbsnd_lowat :
3385                             so->so_snd.sb_lowat;
3386                         goto integer;
3387
3388                 case SO_RCVLOWAT:
3389                         optval = SOLISTENING(so) ? so->sol_sbrcv_lowat :
3390                             so->so_rcv.sb_lowat;
3391                         goto integer;
3392
3393                 case SO_SNDTIMEO:
3394                 case SO_RCVTIMEO:
3395                         SOCK_LOCK(so);
3396                         tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
3397                             (SOLISTENING(so) ? so->sol_sbsnd_timeo :
3398                             so->so_snd.sb_timeo) :
3399                             (SOLISTENING(so) ? so->sol_sbrcv_timeo :
3400                             so->so_rcv.sb_timeo));
3401                         SOCK_UNLOCK(so);
3402 #ifdef COMPAT_FREEBSD32
3403                         if (SV_CURPROC_FLAG(SV_ILP32)) {
3404                                 struct timeval32 tv32;
3405
3406                                 CP(tv, tv32, tv_sec);
3407                                 CP(tv, tv32, tv_usec);
3408                                 error = sooptcopyout(sopt, &tv32, sizeof tv32);
3409                         } else
3410 #endif
3411                                 error = sooptcopyout(sopt, &tv, sizeof tv);
3412                         break;
3413
3414                 case SO_LABEL:
3415 #ifdef MAC
3416                         error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3417                             sizeof(extmac));
3418                         if (error)
3419                                 goto bad;
3420                         error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
3421                             so, &extmac);
3422                         if (error)
3423                                 goto bad;
3424                         error = sooptcopyout(sopt, &extmac, sizeof extmac);
3425 #else
3426                         error = EOPNOTSUPP;
3427 #endif
3428                         break;
3429
3430                 case SO_PEERLABEL:
3431 #ifdef MAC
3432                         error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3433                             sizeof(extmac));
3434                         if (error)
3435                                 goto bad;
3436                         error = mac_getsockopt_peerlabel(
3437                             sopt->sopt_td->td_ucred, so, &extmac);
3438                         if (error)
3439                                 goto bad;
3440                         error = sooptcopyout(sopt, &extmac, sizeof extmac);
3441 #else
3442                         error = EOPNOTSUPP;
3443 #endif
3444                         break;
3445
3446                 case SO_LISTENQLIMIT:
3447                         optval = SOLISTENING(so) ? so->sol_qlimit : 0;
3448                         goto integer;
3449
3450                 case SO_LISTENQLEN:
3451                         optval = SOLISTENING(so) ? so->sol_qlen : 0;
3452                         goto integer;
3453
3454                 case SO_LISTENINCQLEN:
3455                         optval = SOLISTENING(so) ? so->sol_incqlen : 0;
3456                         goto integer;
3457
3458                 case SO_TS_CLOCK:
3459                         optval = so->so_ts_clock;
3460                         goto integer;
3461
3462                 case SO_MAX_PACING_RATE:
3463                         optval = so->so_max_pacing_rate;
3464                         goto integer;
3465
3466                 default:
3467                         if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3468                                 error = hhook_run_socket(so, sopt,
3469                                     HHOOK_SOCKET_OPT);
3470                         else
3471                                 error = ENOPROTOOPT;
3472                         break;
3473                 }
3474         }
3475 #ifdef MAC
3476 bad:
3477 #endif
3478         CURVNET_RESTORE();
3479         return (error);
3480 }
3481
3482 int
3483 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
3484 {
3485         struct mbuf *m, *m_prev;
3486         int sopt_size = sopt->sopt_valsize;
3487
3488         MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3489         if (m == NULL)
3490                 return ENOBUFS;
3491         if (sopt_size > MLEN) {
3492                 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
3493                 if ((m->m_flags & M_EXT) == 0) {
3494                         m_free(m);
3495                         return ENOBUFS;
3496                 }
3497                 m->m_len = min(MCLBYTES, sopt_size);
3498         } else {
3499                 m->m_len = min(MLEN, sopt_size);
3500         }
3501         sopt_size -= m->m_len;
3502         *mp = m;
3503         m_prev = m;
3504
3505         while (sopt_size) {
3506                 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3507                 if (m == NULL) {
3508                         m_freem(*mp);
3509                         return ENOBUFS;
3510                 }
3511                 if (sopt_size > MLEN) {
3512                         MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
3513                             M_NOWAIT);
3514                         if ((m->m_flags & M_EXT) == 0) {
3515                                 m_freem(m);
3516                                 m_freem(*mp);
3517                                 return ENOBUFS;
3518                         }
3519                         m->m_len = min(MCLBYTES, sopt_size);
3520                 } else {
3521                         m->m_len = min(MLEN, sopt_size);
3522                 }
3523                 sopt_size -= m->m_len;
3524                 m_prev->m_next = m;
3525                 m_prev = m;
3526         }
3527         return (0);
3528 }
3529
3530 int
3531 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
3532 {
3533         struct mbuf *m0 = m;
3534
3535         if (sopt->sopt_val == NULL)
3536                 return (0);
3537         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3538                 if (sopt->sopt_td != NULL) {
3539                         int error;
3540
3541                         error = copyin(sopt->sopt_val, mtod(m, char *),
3542                             m->m_len);
3543                         if (error != 0) {
3544                                 m_freem(m0);
3545                                 return(error);
3546                         }
3547                 } else
3548                         bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
3549                 sopt->sopt_valsize -= m->m_len;
3550                 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3551                 m = m->m_next;
3552         }
3553         if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
3554                 panic("ip6_sooptmcopyin");
3555         return (0);
3556 }
3557
3558 int
3559 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
3560 {
3561         struct mbuf *m0 = m;
3562         size_t valsize = 0;
3563
3564         if (sopt->sopt_val == NULL)
3565                 return (0);
3566         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3567                 if (sopt->sopt_td != NULL) {
3568                         int error;
3569
3570                         error = copyout(mtod(m, char *), sopt->sopt_val,
3571                             m->m_len);
3572                         if (error != 0) {
3573                                 m_freem(m0);
3574                                 return(error);
3575                         }
3576                 } else
3577                         bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
3578                 sopt->sopt_valsize -= m->m_len;
3579                 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3580                 valsize += m->m_len;
3581                 m = m->m_next;
3582         }
3583         if (m != NULL) {
3584                 /* enough soopt buffer should be given from user-land */
3585                 m_freem(m0);
3586                 return(EINVAL);
3587         }
3588         sopt->sopt_valsize = valsize;
3589         return (0);
3590 }
3591
3592 /*
3593  * sohasoutofband(): protocol notifies socket layer of the arrival of new
3594  * out-of-band data, which will then notify socket consumers.
3595  */
3596 void
3597 sohasoutofband(struct socket *so)
3598 {
3599
3600         if (so->so_sigio != NULL)
3601                 pgsigio(&so->so_sigio, SIGURG, 0);
3602         selwakeuppri(&so->so_rdsel, PSOCK);
3603 }
3604
3605 int
3606 sopoll(struct socket *so, int events, struct ucred *active_cred,
3607     struct thread *td)
3608 {
3609
3610         /*
3611          * We do not need to set or assert curvnet as long as everyone uses
3612          * sopoll_generic().
3613          */
3614         return (so->so_proto->pr_sopoll(so, events, active_cred, td));
3615 }
3616
3617 int
3618 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3619     struct thread *td)
3620 {
3621         int revents;
3622
3623         SOCK_LOCK(so);
3624         if (SOLISTENING(so)) {
3625                 if (!(events & (POLLIN | POLLRDNORM)))
3626                         revents = 0;
3627                 else if (!TAILQ_EMPTY(&so->sol_comp))
3628                         revents = events & (POLLIN | POLLRDNORM);
3629                 else if ((events & POLLINIGNEOF) == 0 && so->so_error)
3630                         revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP;
3631                 else {
3632                         selrecord(td, &so->so_rdsel);
3633                         revents = 0;
3634                 }
3635         } else {
3636                 revents = 0;
3637                 SOCK_SENDBUF_LOCK(so);
3638                 SOCK_RECVBUF_LOCK(so);
3639                 if (events & (POLLIN | POLLRDNORM))
3640                         if (soreadabledata(so))
3641                                 revents |= events & (POLLIN | POLLRDNORM);
3642                 if (events & (POLLOUT | POLLWRNORM))
3643                         if (sowriteable(so))
3644                                 revents |= events & (POLLOUT | POLLWRNORM);
3645                 if (events & (POLLPRI | POLLRDBAND))
3646                         if (so->so_oobmark ||
3647                             (so->so_rcv.sb_state & SBS_RCVATMARK))
3648                                 revents |= events & (POLLPRI | POLLRDBAND);
3649                 if ((events & POLLINIGNEOF) == 0) {
3650                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3651                                 revents |= events & (POLLIN | POLLRDNORM);
3652                                 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3653                                         revents |= POLLHUP;
3654                         }
3655                 }
3656                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3657                         revents |= events & POLLRDHUP;
3658                 if (revents == 0) {
3659                         if (events &
3660                             (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND | POLLRDHUP)) {
3661                                 selrecord(td, &so->so_rdsel);
3662                                 so->so_rcv.sb_flags |= SB_SEL;
3663                         }
3664                         if (events & (POLLOUT | POLLWRNORM)) {
3665                                 selrecord(td, &so->so_wrsel);
3666                                 so->so_snd.sb_flags |= SB_SEL;
3667                         }
3668                 }
3669                 SOCK_RECVBUF_UNLOCK(so);
3670                 SOCK_SENDBUF_UNLOCK(so);
3671         }
3672         SOCK_UNLOCK(so);
3673         return (revents);
3674 }
3675
3676 int
3677 soo_kqfilter(struct file *fp, struct knote *kn)
3678 {
3679         struct socket *so = kn->kn_fp->f_data;
3680         struct sockbuf *sb;
3681         sb_which which;
3682         struct knlist *knl;
3683
3684         switch (kn->kn_filter) {
3685         case EVFILT_READ:
3686                 kn->kn_fop = &soread_filtops;
3687                 knl = &so->so_rdsel.si_note;
3688                 sb = &so->so_rcv;
3689                 which = SO_RCV;
3690                 break;
3691         case EVFILT_WRITE:
3692                 kn->kn_fop = &sowrite_filtops;
3693                 knl = &so->so_wrsel.si_note;
3694                 sb = &so->so_snd;
3695                 which = SO_SND;
3696                 break;
3697         case EVFILT_EMPTY:
3698                 kn->kn_fop = &soempty_filtops;
3699                 knl = &so->so_wrsel.si_note;
3700                 sb = &so->so_snd;
3701                 which = SO_SND;
3702                 break;
3703         default:
3704                 return (EINVAL);
3705         }
3706
3707         SOCK_LOCK(so);
3708         if (SOLISTENING(so)) {
3709                 knlist_add(knl, kn, 1);
3710         } else {
3711                 SOCK_BUF_LOCK(so, which);
3712                 knlist_add(knl, kn, 1);
3713                 sb->sb_flags |= SB_KNOTE;
3714                 SOCK_BUF_UNLOCK(so, which);
3715         }
3716         SOCK_UNLOCK(so);
3717         return (0);
3718 }
3719
3720 static void
3721 filt_sordetach(struct knote *kn)
3722 {
3723         struct socket *so = kn->kn_fp->f_data;
3724
3725         so_rdknl_lock(so);
3726         knlist_remove(&so->so_rdsel.si_note, kn, 1);
3727         if (!SOLISTENING(so) && knlist_empty(&so->so_rdsel.si_note))
3728                 so->so_rcv.sb_flags &= ~SB_KNOTE;
3729         so_rdknl_unlock(so);
3730 }
3731
3732 /*ARGSUSED*/
3733 static int
3734 filt_soread(struct knote *kn, long hint)
3735 {
3736         struct socket *so;
3737
3738         so = kn->kn_fp->f_data;
3739
3740         if (SOLISTENING(so)) {
3741                 SOCK_LOCK_ASSERT(so);
3742                 kn->kn_data = so->sol_qlen;
3743                 if (so->so_error) {
3744                         kn->kn_flags |= EV_EOF;
3745                         kn->kn_fflags = so->so_error;
3746                         return (1);
3747                 }
3748                 return (!TAILQ_EMPTY(&so->sol_comp));
3749         }
3750
3751         SOCK_RECVBUF_LOCK_ASSERT(so);
3752
3753         kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
3754         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3755                 kn->kn_flags |= EV_EOF;
3756                 kn->kn_fflags = so->so_error;
3757                 return (1);
3758         } else if (so->so_error || so->so_rerror)
3759                 return (1);
3760
3761         if (kn->kn_sfflags & NOTE_LOWAT) {
3762                 if (kn->kn_data >= kn->kn_sdata)
3763                         return (1);
3764         } else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
3765                 return (1);
3766
3767         /* This hook returning non-zero indicates an event, not error */
3768         return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
3769 }
3770
3771 static void
3772 filt_sowdetach(struct knote *kn)
3773 {
3774         struct socket *so = kn->kn_fp->f_data;
3775
3776         so_wrknl_lock(so);
3777         knlist_remove(&so->so_wrsel.si_note, kn, 1);
3778         if (!SOLISTENING(so) && knlist_empty(&so->so_wrsel.si_note))
3779                 so->so_snd.sb_flags &= ~SB_KNOTE;
3780         so_wrknl_unlock(so);
3781 }
3782
3783 /*ARGSUSED*/
3784 static int
3785 filt_sowrite(struct knote *kn, long hint)
3786 {
3787         struct socket *so;
3788
3789         so = kn->kn_fp->f_data;
3790
3791         if (SOLISTENING(so))
3792                 return (0);
3793
3794         SOCK_SENDBUF_LOCK_ASSERT(so);
3795         kn->kn_data = sbspace(&so->so_snd);
3796
3797         hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
3798
3799         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3800                 kn->kn_flags |= EV_EOF;
3801                 kn->kn_fflags = so->so_error;
3802                 return (1);
3803         } else if (so->so_error)        /* temporary udp error */
3804                 return (1);
3805         else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3806             (so->so_proto->pr_flags & PR_CONNREQUIRED))
3807                 return (0);
3808         else if (kn->kn_sfflags & NOTE_LOWAT)
3809                 return (kn->kn_data >= kn->kn_sdata);
3810         else
3811                 return (kn->kn_data >= so->so_snd.sb_lowat);
3812 }
3813
3814 static int
3815 filt_soempty(struct knote *kn, long hint)
3816 {
3817         struct socket *so;
3818
3819         so = kn->kn_fp->f_data;
3820
3821         if (SOLISTENING(so))
3822                 return (1);
3823
3824         SOCK_SENDBUF_LOCK_ASSERT(so);
3825         kn->kn_data = sbused(&so->so_snd);
3826
3827         if (kn->kn_data == 0)
3828                 return (1);
3829         else
3830                 return (0);
3831 }
3832
3833 int
3834 socheckuid(struct socket *so, uid_t uid)
3835 {
3836
3837         if (so == NULL)
3838                 return (EPERM);
3839         if (so->so_cred->cr_uid != uid)
3840                 return (EPERM);
3841         return (0);
3842 }
3843
3844 /*
3845  * These functions are used by protocols to notify the socket layer (and its
3846  * consumers) of state changes in the sockets driven by protocol-side events.
3847  */
3848
3849 /*
3850  * Procedures to manipulate state flags of socket and do appropriate wakeups.
3851  *
3852  * Normal sequence from the active (originating) side is that
3853  * soisconnecting() is called during processing of connect() call, resulting
3854  * in an eventual call to soisconnected() if/when the connection is
3855  * established.  When the connection is torn down soisdisconnecting() is
3856  * called during processing of disconnect() call, and soisdisconnected() is
3857  * called when the connection to the peer is totally severed.  The semantics
3858  * of these routines are such that connectionless protocols can call
3859  * soisconnected() and soisdisconnected() only, bypassing the in-progress
3860  * calls when setting up a ``connection'' takes no time.
3861  *
3862  * From the passive side, a socket is created with two queues of sockets:
3863  * so_incomp for connections in progress and so_comp for connections already
3864  * made and awaiting user acceptance.  As a protocol is preparing incoming
3865  * connections, it creates a socket structure queued on so_incomp by calling
3866  * sonewconn().  When the connection is established, soisconnected() is
3867  * called, and transfers the socket structure to so_comp, making it available
3868  * to accept().
3869  *
3870  * If a socket is closed with sockets on either so_incomp or so_comp, these
3871  * sockets are dropped.
3872  *
3873  * If higher-level protocols are implemented in the kernel, the wakeups done
3874  * here will sometimes cause software-interrupt process scheduling.
3875  */
3876 void
3877 soisconnecting(struct socket *so)
3878 {
3879
3880         SOCK_LOCK(so);
3881         so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3882         so->so_state |= SS_ISCONNECTING;
3883         SOCK_UNLOCK(so);
3884 }
3885
3886 void
3887 soisconnected(struct socket *so)
3888 {
3889         bool last __diagused;
3890
3891         SOCK_LOCK(so);
3892         so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3893         so->so_state |= SS_ISCONNECTED;
3894
3895         if (so->so_qstate == SQ_INCOMP) {
3896                 struct socket *head = so->so_listen;
3897                 int ret;
3898
3899                 KASSERT(head, ("%s: so %p on incomp of NULL", __func__, so));
3900                 /*
3901                  * Promoting a socket from incomplete queue to complete, we
3902                  * need to go through reverse order of locking.  We first do
3903                  * trylock, and if that doesn't succeed, we go the hard way
3904                  * leaving a reference and rechecking consistency after proper
3905                  * locking.
3906                  */
3907                 if (__predict_false(SOLISTEN_TRYLOCK(head) == 0)) {
3908                         soref(head);
3909                         SOCK_UNLOCK(so);
3910                         SOLISTEN_LOCK(head);
3911                         SOCK_LOCK(so);
3912                         if (__predict_false(head != so->so_listen)) {
3913                                 /*
3914                                  * The socket went off the listen queue,
3915                                  * should be lost race to close(2) of sol.
3916                                  * The socket is about to soabort().
3917                                  */
3918                                 SOCK_UNLOCK(so);
3919                                 sorele_locked(head);
3920                                 return;
3921                         }
3922                         last = refcount_release(&head->so_count);
3923                         KASSERT(!last, ("%s: released last reference for %p",
3924                             __func__, head));
3925                 }
3926 again:
3927                 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3928                         TAILQ_REMOVE(&head->sol_incomp, so, so_list);
3929                         head->sol_incqlen--;
3930                         TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
3931                         head->sol_qlen++;
3932                         so->so_qstate = SQ_COMP;
3933                         SOCK_UNLOCK(so);
3934                         solisten_wakeup(head);  /* unlocks */
3935                 } else {
3936                         SOCK_RECVBUF_LOCK(so);
3937                         soupcall_set(so, SO_RCV,
3938                             head->sol_accept_filter->accf_callback,
3939                             head->sol_accept_filter_arg);
3940                         so->so_options &= ~SO_ACCEPTFILTER;
3941                         ret = head->sol_accept_filter->accf_callback(so,
3942                             head->sol_accept_filter_arg, M_NOWAIT);
3943                         if (ret == SU_ISCONNECTED) {
3944                                 soupcall_clear(so, SO_RCV);
3945                                 SOCK_RECVBUF_UNLOCK(so);
3946                                 goto again;
3947                         }
3948                         SOCK_RECVBUF_UNLOCK(so);
3949                         SOCK_UNLOCK(so);
3950                         SOLISTEN_UNLOCK(head);
3951                 }
3952                 return;
3953         }
3954         SOCK_UNLOCK(so);
3955         wakeup(&so->so_timeo);
3956         sorwakeup(so);
3957         sowwakeup(so);
3958 }
3959
3960 void
3961 soisdisconnecting(struct socket *so)
3962 {
3963
3964         SOCK_LOCK(so);
3965         so->so_state &= ~SS_ISCONNECTING;
3966         so->so_state |= SS_ISDISCONNECTING;
3967
3968         if (!SOLISTENING(so)) {
3969                 SOCK_RECVBUF_LOCK(so);
3970                 socantrcvmore_locked(so);
3971                 SOCK_SENDBUF_LOCK(so);
3972                 socantsendmore_locked(so);
3973         }
3974         SOCK_UNLOCK(so);
3975         wakeup(&so->so_timeo);
3976 }
3977
3978 void
3979 soisdisconnected(struct socket *so)
3980 {
3981
3982         SOCK_LOCK(so);
3983
3984         /*
3985          * There is at least one reader of so_state that does not
3986          * acquire socket lock, namely soreceive_generic().  Ensure
3987          * that it never sees all flags that track connection status
3988          * cleared, by ordering the update with a barrier semantic of
3989          * our release thread fence.
3990          */
3991         so->so_state |= SS_ISDISCONNECTED;
3992         atomic_thread_fence_rel();
3993         so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3994
3995         if (!SOLISTENING(so)) {
3996                 SOCK_UNLOCK(so);
3997                 SOCK_RECVBUF_LOCK(so);
3998                 socantrcvmore_locked(so);
3999                 SOCK_SENDBUF_LOCK(so);
4000                 sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
4001                 socantsendmore_locked(so);
4002         } else
4003                 SOCK_UNLOCK(so);
4004         wakeup(&so->so_timeo);
4005 }
4006
4007 int
4008 soiolock(struct socket *so, struct sx *sx, int flags)
4009 {
4010         int error;
4011
4012         KASSERT((flags & SBL_VALID) == flags,
4013             ("soiolock: invalid flags %#x", flags));
4014
4015         if ((flags & SBL_WAIT) != 0) {
4016                 if ((flags & SBL_NOINTR) != 0) {
4017                         sx_xlock(sx);
4018                 } else {
4019                         error = sx_xlock_sig(sx);
4020                         if (error != 0)
4021                                 return (error);
4022                 }
4023         } else if (!sx_try_xlock(sx)) {
4024                 return (EWOULDBLOCK);
4025         }
4026
4027         if (__predict_false(SOLISTENING(so))) {
4028                 sx_xunlock(sx);
4029                 return (ENOTCONN);
4030         }
4031         return (0);
4032 }
4033
4034 void
4035 soiounlock(struct sx *sx)
4036 {
4037         sx_xunlock(sx);
4038 }
4039
4040 /*
4041  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
4042  */
4043 struct sockaddr *
4044 sodupsockaddr(const struct sockaddr *sa, int mflags)
4045 {
4046         struct sockaddr *sa2;
4047
4048         sa2 = malloc(sa->sa_len, M_SONAME, mflags);
4049         if (sa2)
4050                 bcopy(sa, sa2, sa->sa_len);
4051         return sa2;
4052 }
4053
4054 /*
4055  * Register per-socket destructor.
4056  */
4057 void
4058 sodtor_set(struct socket *so, so_dtor_t *func)
4059 {
4060
4061         SOCK_LOCK_ASSERT(so);
4062         so->so_dtor = func;
4063 }
4064
4065 /*
4066  * Register per-socket buffer upcalls.
4067  */
4068 void
4069 soupcall_set(struct socket *so, sb_which which, so_upcall_t func, void *arg)
4070 {
4071         struct sockbuf *sb;
4072
4073         KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4074
4075         switch (which) {
4076         case SO_RCV:
4077                 sb = &so->so_rcv;
4078                 break;
4079         case SO_SND:
4080                 sb = &so->so_snd;
4081                 break;
4082         }
4083         SOCK_BUF_LOCK_ASSERT(so, which);
4084         sb->sb_upcall = func;
4085         sb->sb_upcallarg = arg;
4086         sb->sb_flags |= SB_UPCALL;
4087 }
4088
4089 void
4090 soupcall_clear(struct socket *so, sb_which which)
4091 {
4092         struct sockbuf *sb;
4093
4094         KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4095
4096         switch (which) {
4097         case SO_RCV:
4098                 sb = &so->so_rcv;
4099                 break;
4100         case SO_SND:
4101                 sb = &so->so_snd;
4102                 break;
4103         }
4104         SOCK_BUF_LOCK_ASSERT(so, which);
4105         KASSERT(sb->sb_upcall != NULL,
4106             ("%s: so %p no upcall to clear", __func__, so));
4107         sb->sb_upcall = NULL;
4108         sb->sb_upcallarg = NULL;
4109         sb->sb_flags &= ~SB_UPCALL;
4110 }
4111
4112 void
4113 solisten_upcall_set(struct socket *so, so_upcall_t func, void *arg)
4114 {
4115
4116         SOLISTEN_LOCK_ASSERT(so);
4117         so->sol_upcall = func;
4118         so->sol_upcallarg = arg;
4119 }
4120
4121 static void
4122 so_rdknl_lock(void *arg)
4123 {
4124         struct socket *so = arg;
4125
4126 retry:
4127         if (SOLISTENING(so)) {
4128                 SOLISTEN_LOCK(so);
4129         } else {
4130                 SOCK_RECVBUF_LOCK(so);
4131                 if (__predict_false(SOLISTENING(so))) {
4132                         SOCK_RECVBUF_UNLOCK(so);
4133                         goto retry;
4134                 }
4135         }
4136 }
4137
4138 static void
4139 so_rdknl_unlock(void *arg)
4140 {
4141         struct socket *so = arg;
4142
4143         if (SOLISTENING(so))
4144                 SOLISTEN_UNLOCK(so);
4145         else
4146                 SOCK_RECVBUF_UNLOCK(so);
4147 }
4148
4149 static void
4150 so_rdknl_assert_lock(void *arg, int what)
4151 {
4152         struct socket *so = arg;
4153
4154         if (what == LA_LOCKED) {
4155                 if (SOLISTENING(so))
4156                         SOLISTEN_LOCK_ASSERT(so);
4157                 else
4158                         SOCK_RECVBUF_LOCK_ASSERT(so);
4159         } else {
4160                 if (SOLISTENING(so))
4161                         SOLISTEN_UNLOCK_ASSERT(so);
4162                 else
4163                         SOCK_RECVBUF_UNLOCK_ASSERT(so);
4164         }
4165 }
4166
4167 static void
4168 so_wrknl_lock(void *arg)
4169 {
4170         struct socket *so = arg;
4171
4172 retry:
4173         if (SOLISTENING(so)) {
4174                 SOLISTEN_LOCK(so);
4175         } else {
4176                 SOCK_SENDBUF_LOCK(so);
4177                 if (__predict_false(SOLISTENING(so))) {
4178                         SOCK_SENDBUF_UNLOCK(so);
4179                         goto retry;
4180                 }
4181         }
4182 }
4183
4184 static void
4185 so_wrknl_unlock(void *arg)
4186 {
4187         struct socket *so = arg;
4188
4189         if (SOLISTENING(so))
4190                 SOLISTEN_UNLOCK(so);
4191         else
4192                 SOCK_SENDBUF_UNLOCK(so);
4193 }
4194
4195 static void
4196 so_wrknl_assert_lock(void *arg, int what)
4197 {
4198         struct socket *so = arg;
4199
4200         if (what == LA_LOCKED) {
4201                 if (SOLISTENING(so))
4202                         SOLISTEN_LOCK_ASSERT(so);
4203                 else
4204                         SOCK_SENDBUF_LOCK_ASSERT(so);
4205         } else {
4206                 if (SOLISTENING(so))
4207                         SOLISTEN_UNLOCK_ASSERT(so);
4208                 else
4209                         SOCK_SENDBUF_UNLOCK_ASSERT(so);
4210         }
4211 }
4212
4213 /*
4214  * Create an external-format (``xsocket'') structure using the information in
4215  * the kernel-format socket structure pointed to by so.  This is done to
4216  * reduce the spew of irrelevant information over this interface, to isolate
4217  * user code from changes in the kernel structure, and potentially to provide
4218  * information-hiding if we decide that some of this information should be
4219  * hidden from users.
4220  */
4221 void
4222 sotoxsocket(struct socket *so, struct xsocket *xso)
4223 {
4224
4225         bzero(xso, sizeof(*xso));
4226         xso->xso_len = sizeof *xso;
4227         xso->xso_so = (uintptr_t)so;
4228         xso->so_type = so->so_type;
4229         xso->so_options = so->so_options;
4230         xso->so_linger = so->so_linger;
4231         xso->so_state = so->so_state;
4232         xso->so_pcb = (uintptr_t)so->so_pcb;
4233         xso->xso_protocol = so->so_proto->pr_protocol;
4234         xso->xso_family = so->so_proto->pr_domain->dom_family;
4235         xso->so_timeo = so->so_timeo;
4236         xso->so_error = so->so_error;
4237         xso->so_uid = so->so_cred->cr_uid;
4238         xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
4239         if (SOLISTENING(so)) {
4240                 xso->so_qlen = so->sol_qlen;
4241                 xso->so_incqlen = so->sol_incqlen;
4242                 xso->so_qlimit = so->sol_qlimit;
4243                 xso->so_oobmark = 0;
4244         } else {
4245                 xso->so_state |= so->so_qstate;
4246                 xso->so_qlen = xso->so_incqlen = xso->so_qlimit = 0;
4247                 xso->so_oobmark = so->so_oobmark;
4248                 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
4249                 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
4250         }
4251 }
4252
4253 struct sockbuf *
4254 so_sockbuf_rcv(struct socket *so)
4255 {
4256
4257         return (&so->so_rcv);
4258 }
4259
4260 struct sockbuf *
4261 so_sockbuf_snd(struct socket *so)
4262 {
4263
4264         return (&so->so_snd);
4265 }
4266
4267 int
4268 so_state_get(const struct socket *so)
4269 {
4270
4271         return (so->so_state);
4272 }
4273
4274 void
4275 so_state_set(struct socket *so, int val)
4276 {
4277
4278         so->so_state = val;
4279 }
4280
4281 int
4282 so_options_get(const struct socket *so)
4283 {
4284
4285         return (so->so_options);
4286 }
4287
4288 void
4289 so_options_set(struct socket *so, int val)
4290 {
4291
4292         so->so_options = val;
4293 }
4294
4295 int
4296 so_error_get(const struct socket *so)
4297 {
4298
4299         return (so->so_error);
4300 }
4301
4302 void
4303 so_error_set(struct socket *so, int val)
4304 {
4305
4306         so->so_error = val;
4307 }
4308
4309 int
4310 so_linger_get(const struct socket *so)
4311 {
4312
4313         return (so->so_linger);
4314 }
4315
4316 void
4317 so_linger_set(struct socket *so, int val)
4318 {
4319
4320         KASSERT(val >= 0 && val <= USHRT_MAX && val <= (INT_MAX / hz),
4321             ("%s: val %d out of range", __func__, val));
4322
4323         so->so_linger = val;
4324 }
4325
4326 struct protosw *
4327 so_protosw_get(const struct socket *so)
4328 {
4329
4330         return (so->so_proto);
4331 }
4332
4333 void
4334 so_protosw_set(struct socket *so, struct protosw *val)
4335 {
4336
4337         so->so_proto = val;
4338 }
4339
4340 void
4341 so_sorwakeup(struct socket *so)
4342 {
4343
4344         sorwakeup(so);
4345 }
4346
4347 void
4348 so_sowwakeup(struct socket *so)
4349 {
4350
4351         sowwakeup(so);
4352 }
4353
4354 void
4355 so_sorwakeup_locked(struct socket *so)
4356 {
4357
4358         sorwakeup_locked(so);
4359 }
4360
4361 void
4362 so_sowwakeup_locked(struct socket *so)
4363 {
4364
4365         sowwakeup_locked(so);
4366 }
4367
4368 void
4369 so_lock(struct socket *so)
4370 {
4371
4372         SOCK_LOCK(so);
4373 }
4374
4375 void
4376 so_unlock(struct socket *so)
4377 {
4378
4379         SOCK_UNLOCK(so);
4380 }