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