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