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