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