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