]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_socket.c
This commit was generated by cvs2svn to compensate for changes in r147078,
[FreeBSD/FreeBSD.git] / sys / kern / uipc_socket.c
1 /*-
2  * Copyright (c) 2004 The FreeBSD Foundation
3  * Copyright (c) 2004-2005 Robert N. M. Watson
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      @(#)uipc_socket.c       8.3 (Berkeley) 4/15/94
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_inet.h"
38 #include "opt_mac.h"
39 #include "opt_zero.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/fcntl.h>
44 #include <sys/limits.h>
45 #include <sys/lock.h>
46 #include <sys/mac.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/mutex.h>
50 #include <sys/domain.h>
51 #include <sys/file.h>                   /* for struct knote */
52 #include <sys/kernel.h>
53 #include <sys/event.h>
54 #include <sys/poll.h>
55 #include <sys/proc.h>
56 #include <sys/protosw.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/resourcevar.h>
60 #include <sys/signalvar.h>
61 #include <sys/sysctl.h>
62 #include <sys/uio.h>
63 #include <sys/jail.h>
64
65 #include <vm/uma.h>
66
67
68 static int      soreceive_rcvoob(struct socket *so, struct uio *uio,
69                     int flags);
70
71 static void     filt_sordetach(struct knote *kn);
72 static int      filt_soread(struct knote *kn, long hint);
73 static void     filt_sowdetach(struct knote *kn);
74 static int      filt_sowrite(struct knote *kn, long hint);
75 static int      filt_solisten(struct knote *kn, long hint);
76
77 static struct filterops solisten_filtops =
78         { 1, NULL, filt_sordetach, filt_solisten };
79 static struct filterops soread_filtops =
80         { 1, NULL, filt_sordetach, filt_soread };
81 static struct filterops sowrite_filtops =
82         { 1, NULL, filt_sowdetach, filt_sowrite };
83
84 uma_zone_t socket_zone;
85 so_gen_t        so_gencnt;      /* generation count for sockets */
86
87 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
88 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
89
90 SYSCTL_DECL(_kern_ipc);
91
92 static int somaxconn = SOMAXCONN;
93 static int somaxconn_sysctl(SYSCTL_HANDLER_ARGS);
94 /* XXX: we dont have SYSCTL_USHORT */
95 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
96     0, sizeof(int), somaxconn_sysctl, "I", "Maximum pending socket connection "
97     "queue size");
98 static int numopensockets;
99 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
100     &numopensockets, 0, "Number of open sockets");
101 #ifdef ZERO_COPY_SOCKETS
102 /* These aren't static because they're used in other files. */
103 int so_zero_copy_send = 1;
104 int so_zero_copy_receive = 1;
105 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
106     "Zero copy controls");
107 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
108     &so_zero_copy_receive, 0, "Enable zero copy receive");
109 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
110     &so_zero_copy_send, 0, "Enable zero copy send");
111 #endif /* ZERO_COPY_SOCKETS */
112
113 /*
114  * accept_mtx locks down per-socket fields relating to accept queues.  See
115  * socketvar.h for an annotation of the protected fields of struct socket.
116  */
117 struct mtx accept_mtx;
118 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
119
120 /*
121  * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
122  * so_gencnt field.
123  */
124 static struct mtx so_global_mtx;
125 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
126
127 /*
128  * Socket operation routines.
129  * These routines are called by the routines in
130  * sys_socket.c or from a system process, and
131  * implement the semantics of socket operations by
132  * switching out to the protocol specific routines.
133  */
134
135 /*
136  * Get a socket structure from our zone, and initialize it.
137  * Note that it would probably be better to allocate socket
138  * and PCB at the same time, but I'm not convinced that all
139  * the protocols can be easily modified to do this.
140  *
141  * soalloc() returns a socket with a ref count of 0.
142  */
143 struct socket *
144 soalloc(int mflags)
145 {
146         struct socket *so;
147
148         so = uma_zalloc(socket_zone, mflags | M_ZERO);
149         if (so != NULL) {
150 #ifdef MAC
151                 if (mac_init_socket(so, mflags) != 0) {
152                         uma_zfree(socket_zone, so);
153                         return (NULL);
154                 }
155 #endif
156                 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
157                 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
158                 TAILQ_INIT(&so->so_aiojobq);
159                 mtx_lock(&so_global_mtx);
160                 so->so_gencnt = ++so_gencnt;
161                 ++numopensockets;
162                 mtx_unlock(&so_global_mtx);
163         }
164         return (so);
165 }
166
167 /*
168  * socreate returns a socket with a ref count of 1.  The socket should be
169  * closed with soclose().
170  */
171 int
172 socreate(dom, aso, type, proto, cred, td)
173         int dom;
174         struct socket **aso;
175         int type;
176         int proto;
177         struct ucred *cred;
178         struct thread *td;
179 {
180         struct protosw *prp;
181         struct socket *so;
182         int error;
183
184         if (proto)
185                 prp = pffindproto(dom, proto, type);
186         else
187                 prp = pffindtype(dom, type);
188
189         if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
190             prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
191                 return (EPROTONOSUPPORT);
192
193         if (jailed(cred) && jail_socket_unixiproute_only &&
194             prp->pr_domain->dom_family != PF_LOCAL &&
195             prp->pr_domain->dom_family != PF_INET &&
196             prp->pr_domain->dom_family != PF_ROUTE) {
197                 return (EPROTONOSUPPORT);
198         }
199
200         if (prp->pr_type != type)
201                 return (EPROTOTYPE);
202         so = soalloc(M_WAITOK);
203         if (so == NULL)
204                 return (ENOBUFS);
205
206         TAILQ_INIT(&so->so_incomp);
207         TAILQ_INIT(&so->so_comp);
208         so->so_type = type;
209         so->so_cred = crhold(cred);
210         so->so_proto = prp;
211 #ifdef MAC
212         mac_create_socket(cred, so);
213 #endif
214         knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
215         knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
216         so->so_count = 1;
217         error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
218         if (error) {
219                 ACCEPT_LOCK();
220                 SOCK_LOCK(so);
221                 so->so_state |= SS_NOFDREF;
222                 sorele(so);
223                 return (error);
224         }
225         *aso = so;
226         return (0);
227 }
228
229 int
230 sobind(so, nam, td)
231         struct socket *so;
232         struct sockaddr *nam;
233         struct thread *td;
234 {
235
236         return ((*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td));
237 }
238
239 void
240 sodealloc(struct socket *so)
241 {
242
243         KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
244         mtx_lock(&so_global_mtx);
245         so->so_gencnt = ++so_gencnt;
246         mtx_unlock(&so_global_mtx);
247         if (so->so_rcv.sb_hiwat)
248                 (void)chgsbsize(so->so_cred->cr_uidinfo,
249                     &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
250         if (so->so_snd.sb_hiwat)
251                 (void)chgsbsize(so->so_cred->cr_uidinfo,
252                     &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
253 #ifdef INET
254         /* remove acccept filter if one is present. */
255         if (so->so_accf != NULL)
256                 do_setopt_accept_filter(so, NULL);
257 #endif
258 #ifdef MAC
259         mac_destroy_socket(so);
260 #endif
261         crfree(so->so_cred);
262         SOCKBUF_LOCK_DESTROY(&so->so_snd);
263         SOCKBUF_LOCK_DESTROY(&so->so_rcv);
264         uma_zfree(socket_zone, so);
265         mtx_lock(&so_global_mtx);
266         --numopensockets;
267         mtx_unlock(&so_global_mtx);
268 }
269
270 /*
271  * solisten() transitions a socket from a non-listening state to a listening
272  * state, but can also be used to update the listen queue depth on an
273  * existing listen socket.  The protocol will call back into the sockets
274  * layer using solisten_proto_check() and solisten_proto() to check and set
275  * socket-layer listen state.  Call backs are used so that the protocol can
276  * acquire both protocol and socket layer locks in whatever order is reuiqred
277  * by the protocol.
278  *
279  * Protocol implementors are advised to hold the socket lock across the
280  * socket-layer test and set to avoid races at the socket layer.
281  */
282 int
283 solisten(so, backlog, td)
284         struct socket *so;
285         int backlog;
286         struct thread *td;
287 {
288         int error;
289
290         error = (*so->so_proto->pr_usrreqs->pru_listen)(so, td);
291         if (error)
292                 return (error);
293
294         /*
295          * XXXRW: The following state adjustment should occur in
296          * solisten_proto(), but we don't currently pass the backlog request
297          * to the protocol via pru_listen().
298          */
299         if (backlog < 0 || backlog > somaxconn)
300                 backlog = somaxconn;
301         so->so_qlimit = backlog;
302         return (0);
303 }
304
305 int
306 solisten_proto_check(so)
307         struct socket *so;
308 {
309
310         SOCK_LOCK_ASSERT(so);
311
312         if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
313             SS_ISDISCONNECTING))
314                 return (EINVAL);
315         return (0);
316 }
317
318 void
319 solisten_proto(so)
320         struct socket *so;
321 {
322
323         SOCK_LOCK_ASSERT(so);
324
325         so->so_options |= SO_ACCEPTCONN;
326 }
327
328 /*
329  * Attempt to free a socket.  This should really be sotryfree().
330  *
331  * We free the socket if the protocol is no longer interested in the socket,
332  * there's no file descriptor reference, and the refcount is 0.  While the
333  * calling macro sotryfree() tests the refcount, sofree() has to test it
334  * again as it's possible to race with an accept()ing thread if the socket is
335  * in an listen queue of a listen socket, as being in the listen queue
336  * doesn't elevate the reference count.  sofree() acquires the accept mutex
337  * early for this test in order to avoid that race.
338  */
339 void
340 sofree(so)
341         struct socket *so;
342 {
343         struct socket *head;
344
345         ACCEPT_LOCK_ASSERT();
346         SOCK_LOCK_ASSERT(so);
347
348         if (so->so_pcb != NULL || (so->so_state & SS_NOFDREF) == 0 ||
349             so->so_count != 0) {
350                 SOCK_UNLOCK(so);
351                 ACCEPT_UNLOCK();
352                 return;
353         }
354
355         head = so->so_head;
356         if (head != NULL) {
357                 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
358                     (so->so_qstate & SQ_INCOMP) != 0,
359                     ("sofree: so_head != NULL, but neither SQ_COMP nor "
360                     "SQ_INCOMP"));
361                 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
362                     (so->so_qstate & SQ_INCOMP) == 0,
363                     ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
364                 /*
365                  * accept(2) is responsible draining the completed
366                  * connection queue and freeing those sockets, so
367                  * we just return here if this socket is currently
368                  * on the completed connection queue.  Otherwise,
369                  * accept(2) may hang after select(2) has indicating
370                  * that a listening socket was ready.  If it's an
371                  * incomplete connection, we remove it from the queue
372                  * and free it; otherwise, it won't be released until
373                  * the listening socket is closed.
374                  */
375                 if ((so->so_qstate & SQ_COMP) != 0) {
376                         SOCK_UNLOCK(so);
377                         ACCEPT_UNLOCK();
378                         return;
379                 }
380                 TAILQ_REMOVE(&head->so_incomp, so, so_list);
381                 head->so_incqlen--;
382                 so->so_qstate &= ~SQ_INCOMP;
383                 so->so_head = NULL;
384         }
385         KASSERT((so->so_qstate & SQ_COMP) == 0 &&
386             (so->so_qstate & SQ_INCOMP) == 0,
387             ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
388             so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
389         SOCK_UNLOCK(so);
390         ACCEPT_UNLOCK();
391         SOCKBUF_LOCK(&so->so_snd);
392         so->so_snd.sb_flags |= SB_NOINTR;
393         (void)sblock(&so->so_snd, M_WAITOK);
394         /*
395          * socantsendmore_locked() drops the socket buffer mutex so that it
396          * can safely perform wakeups.  Re-acquire the mutex before
397          * continuing.
398          */
399         socantsendmore_locked(so);
400         SOCKBUF_LOCK(&so->so_snd);
401         sbunlock(&so->so_snd);
402         sbrelease_locked(&so->so_snd, so);
403         SOCKBUF_UNLOCK(&so->so_snd);
404         sorflush(so);
405         knlist_destroy(&so->so_rcv.sb_sel.si_note);
406         knlist_destroy(&so->so_snd.sb_sel.si_note);
407         sodealloc(so);
408 }
409
410 /*
411  * Close a socket on last file table reference removal.
412  * Initiate disconnect if connected.
413  * Free socket when disconnect complete.
414  *
415  * This function will sorele() the socket.  Note that soclose() may be
416  * called prior to the ref count reaching zero.  The actual socket
417  * structure will not be freed until the ref count reaches zero.
418  */
419 int
420 soclose(so)
421         struct socket *so;
422 {
423         int error = 0;
424
425         KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
426
427         funsetown(&so->so_sigio);
428         if (so->so_options & SO_ACCEPTCONN) {
429                 struct socket *sp;
430                 ACCEPT_LOCK();
431                 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
432                         TAILQ_REMOVE(&so->so_incomp, sp, so_list);
433                         so->so_incqlen--;
434                         sp->so_qstate &= ~SQ_INCOMP;
435                         sp->so_head = NULL;
436                         ACCEPT_UNLOCK();
437                         (void) soabort(sp);
438                         ACCEPT_LOCK();
439                 }
440                 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
441                         TAILQ_REMOVE(&so->so_comp, sp, so_list);
442                         so->so_qlen--;
443                         sp->so_qstate &= ~SQ_COMP;
444                         sp->so_head = NULL;
445                         ACCEPT_UNLOCK();
446                         (void) soabort(sp);
447                         ACCEPT_LOCK();
448                 }
449                 ACCEPT_UNLOCK();
450         }
451         if (so->so_pcb == NULL)
452                 goto discard;
453         if (so->so_state & SS_ISCONNECTED) {
454                 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
455                         error = sodisconnect(so);
456                         if (error)
457                                 goto drop;
458                 }
459                 if (so->so_options & SO_LINGER) {
460                         if ((so->so_state & SS_ISDISCONNECTING) &&
461                             (so->so_state & SS_NBIO))
462                                 goto drop;
463                         while (so->so_state & SS_ISCONNECTED) {
464                                 error = tsleep(&so->so_timeo,
465                                     PSOCK | PCATCH, "soclos", so->so_linger * hz);
466                                 if (error)
467                                         break;
468                         }
469                 }
470         }
471 drop:
472         if (so->so_pcb != NULL) {
473                 int error2 = (*so->so_proto->pr_usrreqs->pru_detach)(so);
474                 if (error == 0)
475                         error = error2;
476         }
477 discard:
478         ACCEPT_LOCK();
479         SOCK_LOCK(so);
480         KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
481         so->so_state |= SS_NOFDREF;
482         sorele(so);
483         return (error);
484 }
485
486 /*
487  * soabort() must not be called with any socket locks held, as it calls
488  * into the protocol, which will call back into the socket code causing
489  * it to acquire additional socket locks that may cause recursion or lock
490  * order reversals.
491  */
492 int
493 soabort(so)
494         struct socket *so;
495 {
496         int error;
497
498         error = (*so->so_proto->pr_usrreqs->pru_abort)(so);
499         if (error) {
500                 ACCEPT_LOCK();
501                 SOCK_LOCK(so);
502                 sotryfree(so);  /* note: does not decrement the ref count */
503                 return error;
504         }
505         return (0);
506 }
507
508 int
509 soaccept(so, nam)
510         struct socket *so;
511         struct sockaddr **nam;
512 {
513         int error;
514
515         SOCK_LOCK(so);
516         KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
517         so->so_state &= ~SS_NOFDREF;
518         SOCK_UNLOCK(so);
519         error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
520         return (error);
521 }
522
523 int
524 soconnect(so, nam, td)
525         struct socket *so;
526         struct sockaddr *nam;
527         struct thread *td;
528 {
529         int error;
530
531         if (so->so_options & SO_ACCEPTCONN)
532                 return (EOPNOTSUPP);
533         /*
534          * If protocol is connection-based, can only connect once.
535          * Otherwise, if connected, try to disconnect first.
536          * This allows user to disconnect by connecting to, e.g.,
537          * a null address.
538          */
539         if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
540             ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
541             (error = sodisconnect(so)))) {
542                 error = EISCONN;
543         } else {
544                 /*
545                  * Prevent accumulated error from previous connection
546                  * from biting us.
547                  */
548                 so->so_error = 0;
549                 error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
550         }
551
552         return (error);
553 }
554
555 int
556 soconnect2(so1, so2)
557         struct socket *so1;
558         struct socket *so2;
559 {
560
561         return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
562 }
563
564 int
565 sodisconnect(so)
566         struct socket *so;
567 {
568         int error;
569
570         if ((so->so_state & SS_ISCONNECTED) == 0)
571                 return (ENOTCONN);
572         if (so->so_state & SS_ISDISCONNECTING)
573                 return (EALREADY);
574         error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
575         return (error);
576 }
577
578 #define SBLOCKWAIT(f)   (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
579 /*
580  * Send on a socket.
581  * If send must go all at once and message is larger than
582  * send buffering, then hard error.
583  * Lock against other senders.
584  * If must go all at once and not enough room now, then
585  * inform user that this would block and do nothing.
586  * Otherwise, if nonblocking, send as much as possible.
587  * The data to be sent is described by "uio" if nonzero,
588  * otherwise by the mbuf chain "top" (which must be null
589  * if uio is not).  Data provided in mbuf chain must be small
590  * enough to send all at once.
591  *
592  * Returns nonzero on error, timeout or signal; callers
593  * must check for short counts if EINTR/ERESTART are returned.
594  * Data and control buffers are freed on return.
595  */
596
597 #ifdef ZERO_COPY_SOCKETS
598 struct so_zerocopy_stats{
599         int size_ok;
600         int align_ok;
601         int found_ifp;
602 };
603 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
604 #include <netinet/in.h>
605 #include <net/route.h>
606 #include <netinet/in_pcb.h>
607 #include <vm/vm.h>
608 #include <vm/vm_page.h>
609 #include <vm/vm_object.h>
610 #endif /*ZERO_COPY_SOCKETS*/
611
612 int
613 sosend(so, addr, uio, top, control, flags, td)
614         struct socket *so;
615         struct sockaddr *addr;
616         struct uio *uio;
617         struct mbuf *top;
618         struct mbuf *control;
619         int flags;
620         struct thread *td;
621 {
622         struct mbuf **mp;
623         struct mbuf *m;
624         long space, len = 0, resid;
625         int clen = 0, error, dontroute;
626         int atomic = sosendallatonce(so) || top;
627 #ifdef ZERO_COPY_SOCKETS
628         int cow_send;
629 #endif /* ZERO_COPY_SOCKETS */
630
631         if (uio != NULL)
632                 resid = uio->uio_resid;
633         else
634                 resid = top->m_pkthdr.len;
635         /*
636          * In theory resid should be unsigned.
637          * However, space must be signed, as it might be less than 0
638          * if we over-committed, and we must use a signed comparison
639          * of space and resid.  On the other hand, a negative resid
640          * causes us to loop sending 0-length segments to the protocol.
641          *
642          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
643          * type sockets since that's an error.
644          */
645         if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
646                 error = EINVAL;
647                 goto out;
648         }
649
650         dontroute =
651             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
652             (so->so_proto->pr_flags & PR_ATOMIC);
653         if (td != NULL)
654                 td->td_proc->p_stats->p_ru.ru_msgsnd++;
655         if (control != NULL)
656                 clen = control->m_len;
657 #define snderr(errno)   { error = (errno); goto release; }
658
659         SOCKBUF_LOCK(&so->so_snd);
660 restart:
661         SOCKBUF_LOCK_ASSERT(&so->so_snd);
662         error = sblock(&so->so_snd, SBLOCKWAIT(flags));
663         if (error)
664                 goto out_locked;
665         do {
666                 SOCKBUF_LOCK_ASSERT(&so->so_snd);
667                 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
668                         snderr(EPIPE);
669                 if (so->so_error) {
670                         error = so->so_error;
671                         so->so_error = 0;
672                         goto release;
673                 }
674                 if ((so->so_state & SS_ISCONNECTED) == 0) {
675                         /*
676                          * `sendto' and `sendmsg' is allowed on a connection-
677                          * based socket if it supports implied connect.
678                          * Return ENOTCONN if not connected and no address is
679                          * supplied.
680                          */
681                         if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
682                             (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
683                                 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
684                                     !(resid == 0 && clen != 0))
685                                         snderr(ENOTCONN);
686                         } else if (addr == NULL)
687                             snderr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
688                                    ENOTCONN : EDESTADDRREQ);
689                 }
690                 space = sbspace(&so->so_snd);
691                 if (flags & MSG_OOB)
692                         space += 1024;
693                 if ((atomic && resid > so->so_snd.sb_hiwat) ||
694                     clen > so->so_snd.sb_hiwat)
695                         snderr(EMSGSIZE);
696                 if (space < resid + clen &&
697                     (atomic || space < so->so_snd.sb_lowat || space < clen)) {
698                         if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO))
699                                 snderr(EWOULDBLOCK);
700                         sbunlock(&so->so_snd);
701                         error = sbwait(&so->so_snd);
702                         if (error)
703                                 goto out_locked;
704                         goto restart;
705                 }
706                 SOCKBUF_UNLOCK(&so->so_snd);
707                 mp = &top;
708                 space -= clen;
709                 do {
710                     if (uio == NULL) {
711                         /*
712                          * Data is prepackaged in "top".
713                          */
714                         resid = 0;
715                         if (flags & MSG_EOR)
716                                 top->m_flags |= M_EOR;
717                     } else do {
718 #ifdef ZERO_COPY_SOCKETS
719                         cow_send = 0;
720 #endif /* ZERO_COPY_SOCKETS */
721                         if (resid >= MINCLSIZE) {
722 #ifdef ZERO_COPY_SOCKETS
723                                 if (top == NULL) {
724                                         MGETHDR(m, M_TRYWAIT, MT_DATA);
725                                         if (m == NULL) {
726                                                 error = ENOBUFS;
727                                                 SOCKBUF_LOCK(&so->so_snd);
728                                                 goto release;
729                                         }
730                                         m->m_pkthdr.len = 0;
731                                         m->m_pkthdr.rcvif = (struct ifnet *)0;
732                                 } else {
733                                         MGET(m, M_TRYWAIT, MT_DATA);
734                                         if (m == NULL) {
735                                                 error = ENOBUFS;
736                                                 SOCKBUF_LOCK(&so->so_snd);
737                                                 goto release;
738                                         }
739                                 }
740                                 if (so_zero_copy_send &&
741                                     resid>=PAGE_SIZE &&
742                                     space>=PAGE_SIZE &&
743                                     uio->uio_iov->iov_len>=PAGE_SIZE) {
744                                         so_zerocp_stats.size_ok++;
745                                         so_zerocp_stats.align_ok++;
746                                         cow_send = socow_setup(m, uio);
747                                         len = cow_send;
748                                 }
749                                 if (!cow_send) {
750                                         MCLGET(m, M_TRYWAIT);
751                                         if ((m->m_flags & M_EXT) == 0) {
752                                                 m_free(m);
753                                                 m = NULL;
754                                         } else {
755                                                 len = min(min(MCLBYTES, resid), space);
756                                         }
757                                 }
758 #else /* ZERO_COPY_SOCKETS */
759                                 if (top == NULL) {
760                                         m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
761                                         m->m_pkthdr.len = 0;
762                                         m->m_pkthdr.rcvif = (struct ifnet *)0;
763                                 } else
764                                         m = m_getcl(M_TRYWAIT, MT_DATA, 0);
765                                 len = min(min(MCLBYTES, resid), space);
766 #endif /* ZERO_COPY_SOCKETS */
767                         } else {
768                                 if (top == NULL) {
769                                         m = m_gethdr(M_TRYWAIT, MT_DATA);
770                                         m->m_pkthdr.len = 0;
771                                         m->m_pkthdr.rcvif = (struct ifnet *)0;
772
773                                         len = min(min(MHLEN, resid), space);
774                                         /*
775                                          * For datagram protocols, leave room
776                                          * for protocol headers in first mbuf.
777                                          */
778                                         if (atomic && m && len < MHLEN)
779                                                 MH_ALIGN(m, len);
780                                 } else {
781                                         m = m_get(M_TRYWAIT, MT_DATA);
782                                         len = min(min(MLEN, resid), space);
783                                 }
784                         }
785                         if (m == NULL) {
786                                 error = ENOBUFS;
787                                 SOCKBUF_LOCK(&so->so_snd);
788                                 goto release;
789                         }
790
791                         space -= len;
792 #ifdef ZERO_COPY_SOCKETS
793                         if (cow_send)
794                                 error = 0;
795                         else
796 #endif /* ZERO_COPY_SOCKETS */
797                         error = uiomove(mtod(m, void *), (int)len, uio);
798                         resid = uio->uio_resid;
799                         m->m_len = len;
800                         *mp = m;
801                         top->m_pkthdr.len += len;
802                         if (error) {
803                                 SOCKBUF_LOCK(&so->so_snd);
804                                 goto release;
805                         }
806                         mp = &m->m_next;
807                         if (resid <= 0) {
808                                 if (flags & MSG_EOR)
809                                         top->m_flags |= M_EOR;
810                                 break;
811                         }
812                     } while (space > 0 && atomic);
813                     if (dontroute) {
814                             SOCK_LOCK(so);
815                             so->so_options |= SO_DONTROUTE;
816                             SOCK_UNLOCK(so);
817                     }
818                     /*
819                      * XXX all the SBS_CANTSENDMORE checks previously
820                      * done could be out of date.  We could have recieved
821                      * a reset packet in an interrupt or maybe we slept
822                      * while doing page faults in uiomove() etc. We could
823                      * probably recheck again inside the locking protection
824                      * here, but there are probably other places that this
825                      * also happens.  We must rethink this.
826                      */
827                     error = (*so->so_proto->pr_usrreqs->pru_send)(so,
828                         (flags & MSG_OOB) ? PRUS_OOB :
829                         /*
830                          * If the user set MSG_EOF, the protocol
831                          * understands this flag and nothing left to
832                          * send then use PRU_SEND_EOF instead of PRU_SEND.
833                          */
834                         ((flags & MSG_EOF) &&
835                          (so->so_proto->pr_flags & PR_IMPLOPCL) &&
836                          (resid <= 0)) ?
837                                 PRUS_EOF :
838                         /* If there is more to send set PRUS_MORETOCOME */
839                         (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
840                         top, addr, control, td);
841                     if (dontroute) {
842                             SOCK_LOCK(so);
843                             so->so_options &= ~SO_DONTROUTE;
844                             SOCK_UNLOCK(so);
845                     }
846                     clen = 0;
847                     control = NULL;
848                     top = NULL;
849                     mp = &top;
850                     if (error) {
851                         SOCKBUF_LOCK(&so->so_snd);
852                         goto release;
853                     }
854                 } while (resid && space > 0);
855                 SOCKBUF_LOCK(&so->so_snd);
856         } while (resid);
857
858 release:
859         SOCKBUF_LOCK_ASSERT(&so->so_snd);
860         sbunlock(&so->so_snd);
861 out_locked:
862         SOCKBUF_LOCK_ASSERT(&so->so_snd);
863         SOCKBUF_UNLOCK(&so->so_snd);
864 out:
865         if (top != NULL)
866                 m_freem(top);
867         if (control != NULL)
868                 m_freem(control);
869         return (error);
870 }
871
872 /*
873  * The part of soreceive() that implements reading non-inline out-of-band
874  * data from a socket.  For more complete comments, see soreceive(), from
875  * which this code originated.
876  *
877  * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
878  * unable to return an mbuf chain to the caller.
879  */
880 static int
881 soreceive_rcvoob(so, uio, flags)
882         struct socket *so;
883         struct uio *uio;
884         int flags;
885 {
886         struct protosw *pr = so->so_proto;
887         struct mbuf *m;
888         int error;
889
890         KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
891
892         m = m_get(M_TRYWAIT, MT_DATA);
893         if (m == NULL)
894                 return (ENOBUFS);
895         error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
896         if (error)
897                 goto bad;
898         do {
899 #ifdef ZERO_COPY_SOCKETS
900                 if (so_zero_copy_receive) {
901                         int disposable;
902
903                         if ((m->m_flags & M_EXT)
904                          && (m->m_ext.ext_type == EXT_DISPOSABLE))
905                                 disposable = 1;
906                         else
907                                 disposable = 0;
908
909                         error = uiomoveco(mtod(m, void *),
910                                           min(uio->uio_resid, m->m_len),
911                                           uio, disposable);
912                 } else
913 #endif /* ZERO_COPY_SOCKETS */
914                 error = uiomove(mtod(m, void *),
915                     (int) min(uio->uio_resid, m->m_len), uio);
916                 m = m_free(m);
917         } while (uio->uio_resid && error == 0 && m);
918 bad:
919         if (m != NULL)
920                 m_freem(m);
921         return (error);
922 }
923
924 /*
925  * Following replacement or removal of the first mbuf on the first mbuf chain
926  * of a socket buffer, push necessary state changes back into the socket
927  * buffer so that other consumers see the values consistently.  'nextrecord'
928  * is the callers locally stored value of the original value of
929  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
930  * NOTE: 'nextrecord' may be NULL.
931  */
932 static __inline void
933 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
934 {
935
936         SOCKBUF_LOCK_ASSERT(sb);
937         /*
938          * First, update for the new value of nextrecord.  If necessary, make
939          * it the first record.
940          */
941         if (sb->sb_mb != NULL)
942                 sb->sb_mb->m_nextpkt = nextrecord;
943         else
944                 sb->sb_mb = nextrecord;
945
946         /*
947          * Now update any dependent socket buffer fields to reflect the new
948          * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
949          * addition of a second clause that takes care of the case where
950          * sb_mb has been updated, but remains the last record.
951          */
952         if (sb->sb_mb == NULL) {
953                 sb->sb_mbtail = NULL;
954                 sb->sb_lastrecord = NULL;
955         } else if (sb->sb_mb->m_nextpkt == NULL)
956                 sb->sb_lastrecord = sb->sb_mb;
957 }
958
959
960 /*
961  * Implement receive operations on a socket.
962  * We depend on the way that records are added to the sockbuf
963  * by sbappend*.  In particular, each record (mbufs linked through m_next)
964  * must begin with an address if the protocol so specifies,
965  * followed by an optional mbuf or mbufs containing ancillary data,
966  * and then zero or more mbufs of data.
967  * In order to avoid blocking network interrupts for the entire time here,
968  * we splx() while doing the actual copy to user space.
969  * Although the sockbuf is locked, new data may still be appended,
970  * and thus we must maintain consistency of the sockbuf during that time.
971  *
972  * The caller may receive the data as a single mbuf chain by supplying
973  * an mbuf **mp0 for use in returning the chain.  The uio is then used
974  * only for the count in uio_resid.
975  */
976 int
977 soreceive(so, psa, uio, mp0, controlp, flagsp)
978         struct socket *so;
979         struct sockaddr **psa;
980         struct uio *uio;
981         struct mbuf **mp0;
982         struct mbuf **controlp;
983         int *flagsp;
984 {
985         struct mbuf *m, **mp;
986         int flags, len, error, offset;
987         struct protosw *pr = so->so_proto;
988         struct mbuf *nextrecord;
989         int moff, type = 0;
990         int orig_resid = uio->uio_resid;
991
992         mp = mp0;
993         if (psa != NULL)
994                 *psa = NULL;
995         if (controlp != NULL)
996                 *controlp = NULL;
997         if (flagsp != NULL)
998                 flags = *flagsp &~ MSG_EOR;
999         else
1000                 flags = 0;
1001         if (flags & MSG_OOB)
1002                 return (soreceive_rcvoob(so, uio, flags));
1003         if (mp != NULL)
1004                 *mp = NULL;
1005         if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1006             && uio->uio_resid)
1007                 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1008
1009         SOCKBUF_LOCK(&so->so_rcv);
1010 restart:
1011         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1012         error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1013         if (error)
1014                 goto out;
1015
1016         m = so->so_rcv.sb_mb;
1017         /*
1018          * If we have less data than requested, block awaiting more
1019          * (subject to any timeout) if:
1020          *   1. the current count is less than the low water mark, or
1021          *   2. MSG_WAITALL is set, and it is possible to do the entire
1022          *      receive operation at once if we block (resid <= hiwat).
1023          *   3. MSG_DONTWAIT is not set
1024          * If MSG_WAITALL is set but resid is larger than the receive buffer,
1025          * we have to do the receive in sections, and thus risk returning
1026          * a short count if a timeout or signal occurs after we start.
1027          */
1028         if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1029             so->so_rcv.sb_cc < uio->uio_resid) &&
1030             (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1031             ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1032             m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1033                 KASSERT(m != NULL || !so->so_rcv.sb_cc,
1034                     ("receive: m == %p so->so_rcv.sb_cc == %u",
1035                     m, so->so_rcv.sb_cc));
1036                 if (so->so_error) {
1037                         if (m != NULL)
1038                                 goto dontblock;
1039                         error = so->so_error;
1040                         if ((flags & MSG_PEEK) == 0)
1041                                 so->so_error = 0;
1042                         goto release;
1043                 }
1044                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1045                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1046                         if (m)
1047                                 goto dontblock;
1048                         else
1049                                 goto release;
1050                 }
1051                 for (; m != NULL; m = m->m_next)
1052                         if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1053                                 m = so->so_rcv.sb_mb;
1054                                 goto dontblock;
1055                         }
1056                 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1057                     (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1058                         error = ENOTCONN;
1059                         goto release;
1060                 }
1061                 if (uio->uio_resid == 0)
1062                         goto release;
1063                 if ((so->so_state & SS_NBIO) ||
1064                     (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1065                         error = EWOULDBLOCK;
1066                         goto release;
1067                 }
1068                 SBLASTRECORDCHK(&so->so_rcv);
1069                 SBLASTMBUFCHK(&so->so_rcv);
1070                 sbunlock(&so->so_rcv);
1071                 error = sbwait(&so->so_rcv);
1072                 if (error)
1073                         goto out;
1074                 goto restart;
1075         }
1076 dontblock:
1077         /*
1078          * From this point onward, we maintain 'nextrecord' as a cache of the
1079          * pointer to the next record in the socket buffer.  We must keep the
1080          * various socket buffer pointers and local stack versions of the
1081          * pointers in sync, pushing out modifications before dropping the
1082          * socket buffer mutex, and re-reading them when picking it up.
1083          *
1084          * Otherwise, we will race with the network stack appending new data
1085          * or records onto the socket buffer by using inconsistent/stale
1086          * versions of the field, possibly resulting in socket buffer
1087          * corruption.
1088          *
1089          * By holding the high-level sblock(), we prevent simultaneous
1090          * readers from pulling off the front of the socket buffer.
1091          */
1092         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1093         if (uio->uio_td)
1094                 uio->uio_td->td_proc->p_stats->p_ru.ru_msgrcv++;
1095         KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1096         SBLASTRECORDCHK(&so->so_rcv);
1097         SBLASTMBUFCHK(&so->so_rcv);
1098         nextrecord = m->m_nextpkt;
1099         if (pr->pr_flags & PR_ADDR) {
1100                 KASSERT(m->m_type == MT_SONAME,
1101                     ("m->m_type == %d", m->m_type));
1102                 orig_resid = 0;
1103                 if (psa != NULL)
1104                         *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1105                             M_NOWAIT);
1106                 if (flags & MSG_PEEK) {
1107                         m = m->m_next;
1108                 } else {
1109                         sbfree(&so->so_rcv, m);
1110                         so->so_rcv.sb_mb = m_free(m);
1111                         m = so->so_rcv.sb_mb;
1112                         sockbuf_pushsync(&so->so_rcv, nextrecord);
1113                 }
1114         }
1115
1116         /*
1117          * Process one or more MT_CONTROL mbufs present before any data mbufs
1118          * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1119          * just copy the data; if !MSG_PEEK, we call into the protocol to
1120          * perform externalization (or freeing if controlp == NULL).
1121          */
1122         if (m != NULL && m->m_type == MT_CONTROL) {
1123                 struct mbuf *cm = NULL, *cmn;
1124                 struct mbuf **cme = &cm;
1125
1126                 do {
1127                         if (flags & MSG_PEEK) {
1128                                 if (controlp != NULL) {
1129                                         *controlp = m_copy(m, 0, m->m_len);
1130                                         controlp = &(*controlp)->m_next;
1131                                 }
1132                                 m = m->m_next;
1133                         } else {
1134                                 sbfree(&so->so_rcv, m);
1135                                 so->so_rcv.sb_mb = m->m_next;
1136                                 m->m_next = NULL;
1137                                 *cme = m;
1138                                 cme = &(*cme)->m_next;
1139                                 m = so->so_rcv.sb_mb;
1140                         }
1141                 } while (m != NULL && m->m_type == MT_CONTROL);
1142                 if ((flags & MSG_PEEK) == 0)
1143                         sockbuf_pushsync(&so->so_rcv, nextrecord);
1144                 while (cm != NULL) {
1145                         cmn = cm->m_next;
1146                         cm->m_next = NULL;
1147                         if (pr->pr_domain->dom_externalize != NULL) {
1148                                 SOCKBUF_UNLOCK(&so->so_rcv);
1149                                 error = (*pr->pr_domain->dom_externalize)
1150                                     (cm, controlp);
1151                                 SOCKBUF_LOCK(&so->so_rcv);
1152                         } else if (controlp != NULL)
1153                                 *controlp = cm;
1154                         else
1155                                 m_freem(cm);
1156                         if (controlp != NULL) {
1157                                 orig_resid = 0;
1158                                 while (*controlp != NULL)
1159                                         controlp = &(*controlp)->m_next;
1160                         }
1161                         cm = cmn;
1162                 }
1163                 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1164                 orig_resid = 0;
1165         }
1166         if (m != NULL) {
1167                 if ((flags & MSG_PEEK) == 0) {
1168                         KASSERT(m->m_nextpkt == nextrecord,
1169                             ("soreceive: post-control, nextrecord !sync"));
1170                         if (nextrecord == NULL) {
1171                                 KASSERT(so->so_rcv.sb_mb == m,
1172                                     ("soreceive: post-control, sb_mb!=m"));
1173                                 KASSERT(so->so_rcv.sb_lastrecord == m,
1174                                     ("soreceive: post-control, lastrecord!=m"));
1175                         }
1176                 }
1177                 type = m->m_type;
1178                 if (type == MT_OOBDATA)
1179                         flags |= MSG_OOB;
1180         } else {
1181                 if ((flags & MSG_PEEK) == 0) {
1182                         KASSERT(so->so_rcv.sb_mb == nextrecord,
1183                             ("soreceive: sb_mb != nextrecord"));
1184                         if (so->so_rcv.sb_mb == NULL) {
1185                                 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1186                                     ("soreceive: sb_lastercord != NULL"));
1187                         }
1188                 }
1189         }
1190         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1191         SBLASTRECORDCHK(&so->so_rcv);
1192         SBLASTMBUFCHK(&so->so_rcv);
1193
1194         /*
1195          * Now continue to read any data mbufs off of the head of the socket
1196          * buffer until the read request is satisfied.  Note that 'type' is
1197          * used to store the type of any mbuf reads that have happened so far
1198          * such that soreceive() can stop reading if the type changes, which
1199          * causes soreceive() to return only one of regular data and inline
1200          * out-of-band data in a single socket receive operation.
1201          */
1202         moff = 0;
1203         offset = 0;
1204         while (m != NULL && uio->uio_resid > 0 && error == 0) {
1205                 /*
1206                  * If the type of mbuf has changed since the last mbuf
1207                  * examined ('type'), end the receive operation.
1208                  */
1209                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1210                 if (m->m_type == MT_OOBDATA) {
1211                         if (type != MT_OOBDATA)
1212                                 break;
1213                 } else if (type == MT_OOBDATA)
1214                         break;
1215                 else
1216                     KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1217                         ("m->m_type == %d", m->m_type));
1218                 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1219                 len = uio->uio_resid;
1220                 if (so->so_oobmark && len > so->so_oobmark - offset)
1221                         len = so->so_oobmark - offset;
1222                 if (len > m->m_len - moff)
1223                         len = m->m_len - moff;
1224                 /*
1225                  * If mp is set, just pass back the mbufs.
1226                  * Otherwise copy them out via the uio, then free.
1227                  * Sockbuf must be consistent here (points to current mbuf,
1228                  * it points to next record) when we drop priority;
1229                  * we must note any additions to the sockbuf when we
1230                  * block interrupts again.
1231                  */
1232                 if (mp == NULL) {
1233                         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1234                         SBLASTRECORDCHK(&so->so_rcv);
1235                         SBLASTMBUFCHK(&so->so_rcv);
1236                         SOCKBUF_UNLOCK(&so->so_rcv);
1237 #ifdef ZERO_COPY_SOCKETS
1238                         if (so_zero_copy_receive) {
1239                                 int disposable;
1240
1241                                 if ((m->m_flags & M_EXT)
1242                                  && (m->m_ext.ext_type == EXT_DISPOSABLE))
1243                                         disposable = 1;
1244                                 else
1245                                         disposable = 0;
1246
1247                                 error = uiomoveco(mtod(m, char *) + moff,
1248                                                   (int)len, uio,
1249                                                   disposable);
1250                         } else
1251 #endif /* ZERO_COPY_SOCKETS */
1252                         error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1253                         SOCKBUF_LOCK(&so->so_rcv);
1254                         if (error)
1255                                 goto release;
1256                 } else
1257                         uio->uio_resid -= len;
1258                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1259                 if (len == m->m_len - moff) {
1260                         if (m->m_flags & M_EOR)
1261                                 flags |= MSG_EOR;
1262                         if (flags & MSG_PEEK) {
1263                                 m = m->m_next;
1264                                 moff = 0;
1265                         } else {
1266                                 nextrecord = m->m_nextpkt;
1267                                 sbfree(&so->so_rcv, m);
1268                                 if (mp != NULL) {
1269                                         *mp = m;
1270                                         mp = &m->m_next;
1271                                         so->so_rcv.sb_mb = m = m->m_next;
1272                                         *mp = NULL;
1273                                 } else {
1274                                         so->so_rcv.sb_mb = m_free(m);
1275                                         m = so->so_rcv.sb_mb;
1276                                 }
1277                                 if (m != NULL) {
1278                                         m->m_nextpkt = nextrecord;
1279                                         if (nextrecord == NULL)
1280                                                 so->so_rcv.sb_lastrecord = m;
1281                                 } else {
1282                                         so->so_rcv.sb_mb = nextrecord;
1283                                         SB_EMPTY_FIXUP(&so->so_rcv);
1284                                 }
1285                                 SBLASTRECORDCHK(&so->so_rcv);
1286                                 SBLASTMBUFCHK(&so->so_rcv);
1287                         }
1288                 } else {
1289                         if (flags & MSG_PEEK)
1290                                 moff += len;
1291                         else {
1292                                 if (mp != NULL) {
1293                                         int copy_flag;
1294
1295                                         if (flags & MSG_DONTWAIT)
1296                                                 copy_flag = M_DONTWAIT;
1297                                         else
1298                                                 copy_flag = M_TRYWAIT;
1299                                         if (copy_flag == M_TRYWAIT)
1300                                                 SOCKBUF_UNLOCK(&so->so_rcv);
1301                                         *mp = m_copym(m, 0, len, copy_flag);
1302                                         if (copy_flag == M_TRYWAIT)
1303                                                 SOCKBUF_LOCK(&so->so_rcv);
1304                                         if (*mp == NULL) {
1305                                                 /*
1306                                                  * m_copym() couldn't allocate an mbuf. 
1307                                                  * Adjust uio_resid back (it was adjusted 
1308                                                  * down by len bytes, which we didn't end 
1309                                                  * up "copying" over).
1310                                                  */
1311                                                 uio->uio_resid += len;
1312                                                 break;
1313                                         }
1314                                 }
1315                                 m->m_data += len;
1316                                 m->m_len -= len;
1317                                 so->so_rcv.sb_cc -= len;
1318                         }
1319                 }
1320                 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1321                 if (so->so_oobmark) {
1322                         if ((flags & MSG_PEEK) == 0) {
1323                                 so->so_oobmark -= len;
1324                                 if (so->so_oobmark == 0) {
1325                                         so->so_rcv.sb_state |= SBS_RCVATMARK;
1326                                         break;
1327                                 }
1328                         } else {
1329                                 offset += len;
1330                                 if (offset == so->so_oobmark)
1331                                         break;
1332                         }
1333                 }
1334                 if (flags & MSG_EOR)
1335                         break;
1336                 /*
1337                  * If the MSG_WAITALL flag is set (for non-atomic socket),
1338                  * we must not quit until "uio->uio_resid == 0" or an error
1339                  * termination.  If a signal/timeout occurs, return
1340                  * with a short count but without error.
1341                  * Keep sockbuf locked against other readers.
1342                  */
1343                 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1344                     !sosendallatonce(so) && nextrecord == NULL) {
1345                         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1346                         if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1347                                 break;
1348                         /*
1349                          * Notify the protocol that some data has been
1350                          * drained before blocking.
1351                          */
1352                         if (pr->pr_flags & PR_WANTRCVD && so->so_pcb != NULL) {
1353                                 SOCKBUF_UNLOCK(&so->so_rcv);
1354                                 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1355                                 SOCKBUF_LOCK(&so->so_rcv);
1356                         }
1357                         SBLASTRECORDCHK(&so->so_rcv);
1358                         SBLASTMBUFCHK(&so->so_rcv);
1359                         error = sbwait(&so->so_rcv);
1360                         if (error)
1361                                 goto release;
1362                         m = so->so_rcv.sb_mb;
1363                         if (m != NULL)
1364                                 nextrecord = m->m_nextpkt;
1365                 }
1366         }
1367
1368         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1369         if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1370                 flags |= MSG_TRUNC;
1371                 if ((flags & MSG_PEEK) == 0)
1372                         (void) sbdroprecord_locked(&so->so_rcv);
1373         }
1374         if ((flags & MSG_PEEK) == 0) {
1375                 if (m == NULL) {
1376                         /*
1377                          * First part is an inline SB_EMPTY_FIXUP().  Second
1378                          * part makes sure sb_lastrecord is up-to-date if
1379                          * there is still data in the socket buffer.
1380                          */
1381                         so->so_rcv.sb_mb = nextrecord;
1382                         if (so->so_rcv.sb_mb == NULL) {
1383                                 so->so_rcv.sb_mbtail = NULL;
1384                                 so->so_rcv.sb_lastrecord = NULL;
1385                         } else if (nextrecord->m_nextpkt == NULL)
1386                                 so->so_rcv.sb_lastrecord = nextrecord;
1387                 }
1388                 SBLASTRECORDCHK(&so->so_rcv);
1389                 SBLASTMBUFCHK(&so->so_rcv);
1390                 /*
1391                  * If soreceive() is being done from the socket callback, then 
1392                  * don't need to generate ACK to peer to update window, since 
1393                  * ACK will be generated on return to TCP.
1394                  */
1395                 if (!(flags & MSG_SOCALLBCK) && 
1396                     (pr->pr_flags & PR_WANTRCVD) && so->so_pcb) {
1397                         SOCKBUF_UNLOCK(&so->so_rcv);
1398                         (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1399                         SOCKBUF_LOCK(&so->so_rcv);
1400                 }
1401         }
1402         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1403         if (orig_resid == uio->uio_resid && orig_resid &&
1404             (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1405                 sbunlock(&so->so_rcv);
1406                 goto restart;
1407         }
1408
1409         if (flagsp != NULL)
1410                 *flagsp |= flags;
1411 release:
1412         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1413         sbunlock(&so->so_rcv);
1414 out:
1415         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1416         SOCKBUF_UNLOCK(&so->so_rcv);
1417         return (error);
1418 }
1419
1420 int
1421 soshutdown(so, how)
1422         struct socket *so;
1423         int how;
1424 {
1425         struct protosw *pr = so->so_proto;
1426
1427         if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1428                 return (EINVAL);
1429
1430         if (how != SHUT_WR)
1431                 sorflush(so);
1432         if (how != SHUT_RD)
1433                 return ((*pr->pr_usrreqs->pru_shutdown)(so));
1434         return (0);
1435 }
1436
1437 void
1438 sorflush(so)
1439         struct socket *so;
1440 {
1441         struct sockbuf *sb = &so->so_rcv;
1442         struct protosw *pr = so->so_proto;
1443         struct sockbuf asb;
1444
1445         /*
1446          * XXXRW: This is quite ugly.  Previously, this code made a copy of
1447          * the socket buffer, then zero'd the original to clear the buffer
1448          * fields.  However, with mutexes in the socket buffer, this causes
1449          * problems.  We only clear the zeroable bits of the original;
1450          * however, we have to initialize and destroy the mutex in the copy
1451          * so that dom_dispose() and sbrelease() can lock t as needed.
1452          */
1453         SOCKBUF_LOCK(sb);
1454         sb->sb_flags |= SB_NOINTR;
1455         (void) sblock(sb, M_WAITOK);
1456         /*
1457          * socantrcvmore_locked() drops the socket buffer mutex so that it
1458          * can safely perform wakeups.  Re-acquire the mutex before
1459          * continuing.
1460          */
1461         socantrcvmore_locked(so);
1462         SOCKBUF_LOCK(sb);
1463         sbunlock(sb);
1464         /*
1465          * Invalidate/clear most of the sockbuf structure, but leave
1466          * selinfo and mutex data unchanged.
1467          */
1468         bzero(&asb, offsetof(struct sockbuf, sb_startzero));
1469         bcopy(&sb->sb_startzero, &asb.sb_startzero,
1470             sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1471         bzero(&sb->sb_startzero,
1472             sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1473         SOCKBUF_UNLOCK(sb);
1474
1475         SOCKBUF_LOCK_INIT(&asb, "so_rcv");
1476         if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
1477                 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
1478         sbrelease(&asb, so);
1479         SOCKBUF_LOCK_DESTROY(&asb);
1480 }
1481
1482 /*
1483  * Perhaps this routine, and sooptcopyout(), below, ought to come in
1484  * an additional variant to handle the case where the option value needs
1485  * to be some kind of integer, but not a specific size.
1486  * In addition to their use here, these functions are also called by the
1487  * protocol-level pr_ctloutput() routines.
1488  */
1489 int
1490 sooptcopyin(sopt, buf, len, minlen)
1491         struct  sockopt *sopt;
1492         void    *buf;
1493         size_t  len;
1494         size_t  minlen;
1495 {
1496         size_t  valsize;
1497
1498         /*
1499          * If the user gives us more than we wanted, we ignore it,
1500          * but if we don't get the minimum length the caller
1501          * wants, we return EINVAL.  On success, sopt->sopt_valsize
1502          * is set to however much we actually retrieved.
1503          */
1504         if ((valsize = sopt->sopt_valsize) < minlen)
1505                 return EINVAL;
1506         if (valsize > len)
1507                 sopt->sopt_valsize = valsize = len;
1508
1509         if (sopt->sopt_td != NULL)
1510                 return (copyin(sopt->sopt_val, buf, valsize));
1511
1512         bcopy(sopt->sopt_val, buf, valsize);
1513         return 0;
1514 }
1515
1516 /*
1517  * Kernel version of setsockopt(2)/
1518  * XXX: optlen is size_t, not socklen_t
1519  */
1520 int
1521 so_setsockopt(struct socket *so, int level, int optname, void *optval,
1522     size_t optlen)
1523 {
1524         struct sockopt sopt;
1525
1526         sopt.sopt_level = level;
1527         sopt.sopt_name = optname;
1528         sopt.sopt_dir = SOPT_SET;
1529         sopt.sopt_val = optval;
1530         sopt.sopt_valsize = optlen;
1531         sopt.sopt_td = NULL;
1532         return (sosetopt(so, &sopt));
1533 }
1534
1535 int
1536 sosetopt(so, sopt)
1537         struct socket *so;
1538         struct sockopt *sopt;
1539 {
1540         int     error, optval;
1541         struct  linger l;
1542         struct  timeval tv;
1543         u_long  val;
1544 #ifdef MAC
1545         struct mac extmac;
1546 #endif
1547
1548         error = 0;
1549         if (sopt->sopt_level != SOL_SOCKET) {
1550                 if (so->so_proto && so->so_proto->pr_ctloutput)
1551                         return ((*so->so_proto->pr_ctloutput)
1552                                   (so, sopt));
1553                 error = ENOPROTOOPT;
1554         } else {
1555                 switch (sopt->sopt_name) {
1556 #ifdef INET
1557                 case SO_ACCEPTFILTER:
1558                         error = do_setopt_accept_filter(so, sopt);
1559                         if (error)
1560                                 goto bad;
1561                         break;
1562 #endif
1563                 case SO_LINGER:
1564                         error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1565                         if (error)
1566                                 goto bad;
1567
1568                         SOCK_LOCK(so);
1569                         so->so_linger = l.l_linger;
1570                         if (l.l_onoff)
1571                                 so->so_options |= SO_LINGER;
1572                         else
1573                                 so->so_options &= ~SO_LINGER;
1574                         SOCK_UNLOCK(so);
1575                         break;
1576
1577                 case SO_DEBUG:
1578                 case SO_KEEPALIVE:
1579                 case SO_DONTROUTE:
1580                 case SO_USELOOPBACK:
1581                 case SO_BROADCAST:
1582                 case SO_REUSEADDR:
1583                 case SO_REUSEPORT:
1584                 case SO_OOBINLINE:
1585                 case SO_TIMESTAMP:
1586                 case SO_BINTIME:
1587                 case SO_NOSIGPIPE:
1588                         error = sooptcopyin(sopt, &optval, sizeof optval,
1589                                             sizeof optval);
1590                         if (error)
1591                                 goto bad;
1592                         SOCK_LOCK(so);
1593                         if (optval)
1594                                 so->so_options |= sopt->sopt_name;
1595                         else
1596                                 so->so_options &= ~sopt->sopt_name;
1597                         SOCK_UNLOCK(so);
1598                         break;
1599
1600                 case SO_SNDBUF:
1601                 case SO_RCVBUF:
1602                 case SO_SNDLOWAT:
1603                 case SO_RCVLOWAT:
1604                         error = sooptcopyin(sopt, &optval, sizeof optval,
1605                                             sizeof optval);
1606                         if (error)
1607                                 goto bad;
1608
1609                         /*
1610                          * Values < 1 make no sense for any of these
1611                          * options, so disallow them.
1612                          */
1613                         if (optval < 1) {
1614                                 error = EINVAL;
1615                                 goto bad;
1616                         }
1617
1618                         switch (sopt->sopt_name) {
1619                         case SO_SNDBUF:
1620                         case SO_RCVBUF:
1621                                 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1622                                     &so->so_snd : &so->so_rcv, (u_long)optval,
1623                                     so, curthread) == 0) {
1624                                         error = ENOBUFS;
1625                                         goto bad;
1626                                 }
1627                                 break;
1628
1629                         /*
1630                          * Make sure the low-water is never greater than
1631                          * the high-water.
1632                          */
1633                         case SO_SNDLOWAT:
1634                                 SOCKBUF_LOCK(&so->so_snd);
1635                                 so->so_snd.sb_lowat =
1636                                     (optval > so->so_snd.sb_hiwat) ?
1637                                     so->so_snd.sb_hiwat : optval;
1638                                 SOCKBUF_UNLOCK(&so->so_snd);
1639                                 break;
1640                         case SO_RCVLOWAT:
1641                                 SOCKBUF_LOCK(&so->so_rcv);
1642                                 so->so_rcv.sb_lowat =
1643                                     (optval > so->so_rcv.sb_hiwat) ?
1644                                     so->so_rcv.sb_hiwat : optval;
1645                                 SOCKBUF_UNLOCK(&so->so_rcv);
1646                                 break;
1647                         }
1648                         break;
1649
1650                 case SO_SNDTIMEO:
1651                 case SO_RCVTIMEO:
1652                         error = sooptcopyin(sopt, &tv, sizeof tv,
1653                                             sizeof tv);
1654                         if (error)
1655                                 goto bad;
1656
1657                         /* assert(hz > 0); */
1658                         if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
1659                             tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1660                                 error = EDOM;
1661                                 goto bad;
1662                         }
1663                         /* assert(tick > 0); */
1664                         /* assert(ULONG_MAX - INT_MAX >= 1000000); */
1665                         val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1666                         if (val > INT_MAX) {
1667                                 error = EDOM;
1668                                 goto bad;
1669                         }
1670                         if (val == 0 && tv.tv_usec != 0)
1671                                 val = 1;
1672
1673                         switch (sopt->sopt_name) {
1674                         case SO_SNDTIMEO:
1675                                 so->so_snd.sb_timeo = val;
1676                                 break;
1677                         case SO_RCVTIMEO:
1678                                 so->so_rcv.sb_timeo = val;
1679                                 break;
1680                         }
1681                         break;
1682                 case SO_LABEL:
1683 #ifdef MAC
1684                         error = sooptcopyin(sopt, &extmac, sizeof extmac,
1685                             sizeof extmac);
1686                         if (error)
1687                                 goto bad;
1688                         error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
1689                             so, &extmac);
1690 #else
1691                         error = EOPNOTSUPP;
1692 #endif
1693                         break;
1694                 default:
1695                         error = ENOPROTOOPT;
1696                         break;
1697                 }
1698                 if (error == 0 && so->so_proto != NULL &&
1699                     so->so_proto->pr_ctloutput != NULL) {
1700                         (void) ((*so->so_proto->pr_ctloutput)
1701                                   (so, sopt));
1702                 }
1703         }
1704 bad:
1705         return (error);
1706 }
1707
1708 /* Helper routine for getsockopt */
1709 int
1710 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1711 {
1712         int     error;
1713         size_t  valsize;
1714
1715         error = 0;
1716
1717         /*
1718          * Documented get behavior is that we always return a value,
1719          * possibly truncated to fit in the user's buffer.
1720          * Traditional behavior is that we always tell the user
1721          * precisely how much we copied, rather than something useful
1722          * like the total amount we had available for her.
1723          * Note that this interface is not idempotent; the entire answer must
1724          * generated ahead of time.
1725          */
1726         valsize = min(len, sopt->sopt_valsize);
1727         sopt->sopt_valsize = valsize;
1728         if (sopt->sopt_val != NULL) {
1729                 if (sopt->sopt_td != NULL)
1730                         error = copyout(buf, sopt->sopt_val, valsize);
1731                 else
1732                         bcopy(buf, sopt->sopt_val, valsize);
1733         }
1734         return error;
1735 }
1736
1737 int
1738 sogetopt(so, sopt)
1739         struct socket *so;
1740         struct sockopt *sopt;
1741 {
1742         int     error, optval;
1743         struct  linger l;
1744         struct  timeval tv;
1745 #ifdef MAC
1746         struct mac extmac;
1747 #endif
1748
1749         error = 0;
1750         if (sopt->sopt_level != SOL_SOCKET) {
1751                 if (so->so_proto && so->so_proto->pr_ctloutput) {
1752                         return ((*so->so_proto->pr_ctloutput)
1753                                   (so, sopt));
1754                 } else
1755                         return (ENOPROTOOPT);
1756         } else {
1757                 switch (sopt->sopt_name) {
1758 #ifdef INET
1759                 case SO_ACCEPTFILTER:
1760                         error = do_getopt_accept_filter(so, sopt);
1761                         break;
1762 #endif
1763                 case SO_LINGER:
1764                         SOCK_LOCK(so);
1765                         l.l_onoff = so->so_options & SO_LINGER;
1766                         l.l_linger = so->so_linger;
1767                         SOCK_UNLOCK(so);
1768                         error = sooptcopyout(sopt, &l, sizeof l);
1769                         break;
1770
1771                 case SO_USELOOPBACK:
1772                 case SO_DONTROUTE:
1773                 case SO_DEBUG:
1774                 case SO_KEEPALIVE:
1775                 case SO_REUSEADDR:
1776                 case SO_REUSEPORT:
1777                 case SO_BROADCAST:
1778                 case SO_OOBINLINE:
1779                 case SO_TIMESTAMP:
1780                 case SO_BINTIME:
1781                 case SO_NOSIGPIPE:
1782                         optval = so->so_options & sopt->sopt_name;
1783 integer:
1784                         error = sooptcopyout(sopt, &optval, sizeof optval);
1785                         break;
1786
1787                 case SO_TYPE:
1788                         optval = so->so_type;
1789                         goto integer;
1790
1791                 case SO_ERROR:
1792                         optval = so->so_error;
1793                         so->so_error = 0;
1794                         goto integer;
1795
1796                 case SO_SNDBUF:
1797                         optval = so->so_snd.sb_hiwat;
1798                         goto integer;
1799
1800                 case SO_RCVBUF:
1801                         optval = so->so_rcv.sb_hiwat;
1802                         goto integer;
1803
1804                 case SO_SNDLOWAT:
1805                         optval = so->so_snd.sb_lowat;
1806                         goto integer;
1807
1808                 case SO_RCVLOWAT:
1809                         optval = so->so_rcv.sb_lowat;
1810                         goto integer;
1811
1812                 case SO_SNDTIMEO:
1813                 case SO_RCVTIMEO:
1814                         optval = (sopt->sopt_name == SO_SNDTIMEO ?
1815                                   so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1816
1817                         tv.tv_sec = optval / hz;
1818                         tv.tv_usec = (optval % hz) * tick;
1819                         error = sooptcopyout(sopt, &tv, sizeof tv);
1820                         break;
1821                 case SO_LABEL:
1822 #ifdef MAC
1823                         error = sooptcopyin(sopt, &extmac, sizeof(extmac),
1824                             sizeof(extmac));
1825                         if (error)
1826                                 return (error);
1827                         error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
1828                             so, &extmac);
1829                         if (error)
1830                                 return (error);
1831                         error = sooptcopyout(sopt, &extmac, sizeof extmac);
1832 #else
1833                         error = EOPNOTSUPP;
1834 #endif
1835                         break;
1836                 case SO_PEERLABEL:
1837 #ifdef MAC
1838                         error = sooptcopyin(sopt, &extmac, sizeof(extmac),
1839                             sizeof(extmac));
1840                         if (error)
1841                                 return (error);
1842                         error = mac_getsockopt_peerlabel(
1843                             sopt->sopt_td->td_ucred, so, &extmac);
1844                         if (error)
1845                                 return (error);
1846                         error = sooptcopyout(sopt, &extmac, sizeof extmac);
1847 #else
1848                         error = EOPNOTSUPP;
1849 #endif
1850                         break;
1851                 default:
1852                         error = ENOPROTOOPT;
1853                         break;
1854                 }
1855                 return (error);
1856         }
1857 }
1858
1859 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1860 int
1861 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1862 {
1863         struct mbuf *m, *m_prev;
1864         int sopt_size = sopt->sopt_valsize;
1865
1866         MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1867         if (m == NULL)
1868                 return ENOBUFS;
1869         if (sopt_size > MLEN) {
1870                 MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
1871                 if ((m->m_flags & M_EXT) == 0) {
1872                         m_free(m);
1873                         return ENOBUFS;
1874                 }
1875                 m->m_len = min(MCLBYTES, sopt_size);
1876         } else {
1877                 m->m_len = min(MLEN, sopt_size);
1878         }
1879         sopt_size -= m->m_len;
1880         *mp = m;
1881         m_prev = m;
1882
1883         while (sopt_size) {
1884                 MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1885                 if (m == NULL) {
1886                         m_freem(*mp);
1887                         return ENOBUFS;
1888                 }
1889                 if (sopt_size > MLEN) {
1890                         MCLGET(m, sopt->sopt_td != NULL ? M_TRYWAIT :
1891                             M_DONTWAIT);
1892                         if ((m->m_flags & M_EXT) == 0) {
1893                                 m_freem(m);
1894                                 m_freem(*mp);
1895                                 return ENOBUFS;
1896                         }
1897                         m->m_len = min(MCLBYTES, sopt_size);
1898                 } else {
1899                         m->m_len = min(MLEN, sopt_size);
1900                 }
1901                 sopt_size -= m->m_len;
1902                 m_prev->m_next = m;
1903                 m_prev = m;
1904         }
1905         return 0;
1906 }
1907
1908 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1909 int
1910 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1911 {
1912         struct mbuf *m0 = m;
1913
1914         if (sopt->sopt_val == NULL)
1915                 return 0;
1916         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1917                 if (sopt->sopt_td != NULL) {
1918                         int error;
1919
1920                         error = copyin(sopt->sopt_val, mtod(m, char *),
1921                                        m->m_len);
1922                         if (error != 0) {
1923                                 m_freem(m0);
1924                                 return(error);
1925                         }
1926                 } else
1927                         bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
1928                 sopt->sopt_valsize -= m->m_len;
1929                 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
1930                 m = m->m_next;
1931         }
1932         if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1933                 panic("ip6_sooptmcopyin");
1934         return 0;
1935 }
1936
1937 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1938 int
1939 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1940 {
1941         struct mbuf *m0 = m;
1942         size_t valsize = 0;
1943
1944         if (sopt->sopt_val == NULL)
1945                 return 0;
1946         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1947                 if (sopt->sopt_td != NULL) {
1948                         int error;
1949
1950                         error = copyout(mtod(m, char *), sopt->sopt_val,
1951                                        m->m_len);
1952                         if (error != 0) {
1953                                 m_freem(m0);
1954                                 return(error);
1955                         }
1956                 } else
1957                         bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
1958                sopt->sopt_valsize -= m->m_len;
1959                sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
1960                valsize += m->m_len;
1961                m = m->m_next;
1962         }
1963         if (m != NULL) {
1964                 /* enough soopt buffer should be given from user-land */
1965                 m_freem(m0);
1966                 return(EINVAL);
1967         }
1968         sopt->sopt_valsize = valsize;
1969         return 0;
1970 }
1971
1972 void
1973 sohasoutofband(so)
1974         struct socket *so;
1975 {
1976         if (so->so_sigio != NULL)
1977                 pgsigio(&so->so_sigio, SIGURG, 0);
1978         selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
1979 }
1980
1981 int
1982 sopoll(struct socket *so, int events, struct ucred *active_cred,
1983     struct thread *td)
1984 {
1985         int revents = 0;
1986
1987         SOCKBUF_LOCK(&so->so_snd);
1988         SOCKBUF_LOCK(&so->so_rcv);
1989         if (events & (POLLIN | POLLRDNORM))
1990                 if (soreadable(so))
1991                         revents |= events & (POLLIN | POLLRDNORM);
1992
1993         if (events & POLLINIGNEOF)
1994                 if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
1995                     !TAILQ_EMPTY(&so->so_comp) || so->so_error)
1996                         revents |= POLLINIGNEOF;
1997
1998         if (events & (POLLOUT | POLLWRNORM))
1999                 if (sowriteable(so))
2000                         revents |= events & (POLLOUT | POLLWRNORM);
2001
2002         if (events & (POLLPRI | POLLRDBAND))
2003                 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2004                         revents |= events & (POLLPRI | POLLRDBAND);
2005
2006         if (revents == 0) {
2007                 if (events &
2008                     (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2009                      POLLRDBAND)) {
2010                         selrecord(td, &so->so_rcv.sb_sel);
2011                         so->so_rcv.sb_flags |= SB_SEL;
2012                 }
2013
2014                 if (events & (POLLOUT | POLLWRNORM)) {
2015                         selrecord(td, &so->so_snd.sb_sel);
2016                         so->so_snd.sb_flags |= SB_SEL;
2017                 }
2018         }
2019
2020         SOCKBUF_UNLOCK(&so->so_rcv);
2021         SOCKBUF_UNLOCK(&so->so_snd);
2022         return (revents);
2023 }
2024
2025 int
2026 soo_kqfilter(struct file *fp, struct knote *kn)
2027 {
2028         struct socket *so = kn->kn_fp->f_data;
2029         struct sockbuf *sb;
2030
2031         switch (kn->kn_filter) {
2032         case EVFILT_READ:
2033                 if (so->so_options & SO_ACCEPTCONN)
2034                         kn->kn_fop = &solisten_filtops;
2035                 else
2036                         kn->kn_fop = &soread_filtops;
2037                 sb = &so->so_rcv;
2038                 break;
2039         case EVFILT_WRITE:
2040                 kn->kn_fop = &sowrite_filtops;
2041                 sb = &so->so_snd;
2042                 break;
2043         default:
2044                 return (EINVAL);
2045         }
2046
2047         SOCKBUF_LOCK(sb);
2048         knlist_add(&sb->sb_sel.si_note, kn, 1);
2049         sb->sb_flags |= SB_KNOTE;
2050         SOCKBUF_UNLOCK(sb);
2051         return (0);
2052 }
2053
2054 static void
2055 filt_sordetach(struct knote *kn)
2056 {
2057         struct socket *so = kn->kn_fp->f_data;
2058
2059         SOCKBUF_LOCK(&so->so_rcv);
2060         knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2061         if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2062                 so->so_rcv.sb_flags &= ~SB_KNOTE;
2063         SOCKBUF_UNLOCK(&so->so_rcv);
2064 }
2065
2066 /*ARGSUSED*/
2067 static int
2068 filt_soread(struct knote *kn, long hint)
2069 {
2070         struct socket *so;
2071
2072         so = kn->kn_fp->f_data;
2073         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2074
2075         kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2076         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2077                 kn->kn_flags |= EV_EOF;
2078                 kn->kn_fflags = so->so_error;
2079                 return (1);
2080         } else if (so->so_error)        /* temporary udp error */
2081                 return (1);
2082         else if (kn->kn_sfflags & NOTE_LOWAT)
2083                 return (kn->kn_data >= kn->kn_sdata);
2084         else
2085                 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2086 }
2087
2088 static void
2089 filt_sowdetach(struct knote *kn)
2090 {
2091         struct socket *so = kn->kn_fp->f_data;
2092
2093         SOCKBUF_LOCK(&so->so_snd);
2094         knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2095         if (knlist_empty(&so->so_snd.sb_sel.si_note))
2096                 so->so_snd.sb_flags &= ~SB_KNOTE;
2097         SOCKBUF_UNLOCK(&so->so_snd);
2098 }
2099
2100 /*ARGSUSED*/
2101 static int
2102 filt_sowrite(struct knote *kn, long hint)
2103 {
2104         struct socket *so;
2105
2106         so = kn->kn_fp->f_data;
2107         SOCKBUF_LOCK_ASSERT(&so->so_snd);
2108         kn->kn_data = sbspace(&so->so_snd);
2109         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2110                 kn->kn_flags |= EV_EOF;
2111                 kn->kn_fflags = so->so_error;
2112                 return (1);
2113         } else if (so->so_error)        /* temporary udp error */
2114                 return (1);
2115         else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2116             (so->so_proto->pr_flags & PR_CONNREQUIRED))
2117                 return (0);
2118         else if (kn->kn_sfflags & NOTE_LOWAT)
2119                 return (kn->kn_data >= kn->kn_sdata);
2120         else
2121                 return (kn->kn_data >= so->so_snd.sb_lowat);
2122 }
2123
2124 /*ARGSUSED*/
2125 static int
2126 filt_solisten(struct knote *kn, long hint)
2127 {
2128         struct socket *so = kn->kn_fp->f_data;
2129
2130         kn->kn_data = so->so_qlen;
2131         return (! TAILQ_EMPTY(&so->so_comp));
2132 }
2133
2134 int
2135 socheckuid(struct socket *so, uid_t uid)
2136 {
2137
2138         if (so == NULL)
2139                 return (EPERM);
2140         if (so->so_cred->cr_uid != uid)
2141                 return (EPERM);
2142         return (0);
2143 }
2144
2145 static int
2146 somaxconn_sysctl(SYSCTL_HANDLER_ARGS)
2147 {
2148         int error;
2149         int val;
2150
2151         val = somaxconn;
2152         error = sysctl_handle_int(oidp, &val, sizeof(int), req);
2153         if (error || !req->newptr )
2154                 return (error);
2155
2156         if (val < 1 || val > USHRT_MAX)
2157                 return (EINVAL);
2158
2159         somaxconn = val;
2160         return (0);
2161 }