tcp: Let sosendtcp() call tcp_usrreq.pru_send asynchronous
[dragonfly.git] / sys / kern / uipc_socket.c
1 /*
2  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
4  * 
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
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  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  * 
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 1982, 1986, 1988, 1990, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed by the University of
49  *      California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *      @(#)uipc_socket.c       8.3 (Berkeley) 4/15/94
67  * $FreeBSD: src/sys/kern/uipc_socket.c,v 1.68.2.24 2003/11/11 17:18:18 silby Exp $
68  * $DragonFly: src/sys/kern/uipc_socket.c,v 1.55 2008/09/02 16:17:52 dillon Exp $
69  */
70
71 #include "opt_inet.h"
72 #include "opt_sctp.h"
73
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/fcntl.h>
77 #include <sys/malloc.h>
78 #include <sys/mbuf.h>
79 #include <sys/domain.h>
80 #include <sys/file.h>                   /* for struct knote */
81 #include <sys/kernel.h>
82 #include <sys/malloc.h>
83 #include <sys/event.h>
84 #include <sys/proc.h>
85 #include <sys/protosw.h>
86 #include <sys/socket.h>
87 #include <sys/socketvar.h>
88 #include <sys/socketops.h>
89 #include <sys/resourcevar.h>
90 #include <sys/signalvar.h>
91 #include <sys/sysctl.h>
92 #include <sys/uio.h>
93 #include <sys/jail.h>
94 #include <vm/vm_zone.h>
95 #include <vm/pmap.h>
96
97 #include <sys/thread2.h>
98 #include <sys/socketvar2.h>
99
100 #include <machine/limits.h>
101
102 #ifdef INET
103 static int       do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
104 #endif /* INET */
105
106 static void     filt_sordetach(struct knote *kn);
107 static int      filt_soread(struct knote *kn, long hint);
108 static void     filt_sowdetach(struct knote *kn);
109 static int      filt_sowrite(struct knote *kn, long hint);
110 static int      filt_solisten(struct knote *kn, long hint);
111
112 static struct filterops solisten_filtops = 
113         { FILTEROP_ISFD, NULL, filt_sordetach, filt_solisten };
114 static struct filterops soread_filtops =
115         { FILTEROP_ISFD, NULL, filt_sordetach, filt_soread };
116 static struct filterops sowrite_filtops = 
117         { FILTEROP_ISFD, NULL, filt_sowdetach, filt_sowrite };
118 static struct filterops soexcept_filtops =
119         { FILTEROP_ISFD, NULL, filt_sordetach, filt_soread };
120
121 MALLOC_DEFINE(M_SOCKET, "socket", "socket struct");
122 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
123 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
124
125
126 static int somaxconn = SOMAXCONN;
127 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
128     &somaxconn, 0, "Maximum pending socket connection queue size");
129
130 /*
131  * Socket operation routines.
132  * These routines are called by the routines in
133  * sys_socket.c or from a system process, and
134  * implement the semantics of socket operations by
135  * switching out to the protocol specific routines.
136  */
137
138 /*
139  * Get a socket structure, and initialize it.
140  * Note that it would probably be better to allocate socket
141  * and PCB at the same time, but I'm not convinced that all
142  * the protocols can be easily modified to do this.
143  */
144 struct socket *
145 soalloc(int waitok)
146 {
147         struct socket *so;
148         unsigned waitmask;
149
150         waitmask = waitok ? M_WAITOK : M_NOWAIT;
151         so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
152         if (so) {
153                 /* XXX race condition for reentrant kernel */
154                 TAILQ_INIT(&so->so_aiojobq);
155                 TAILQ_INIT(&so->so_rcv.ssb_kq.ki_mlist);
156                 TAILQ_INIT(&so->so_snd.ssb_kq.ki_mlist);
157                 lwkt_token_init(&so->so_rcv.ssb_token, "rcvtok");
158                 lwkt_token_init(&so->so_snd.ssb_token, "sndtok");
159                 so->so_state = SS_NOFDREF;
160                 so->so_refs = 1;
161         }
162         return so;
163 }
164
165 int
166 socreate(int dom, struct socket **aso, int type,
167         int proto, struct thread *td)
168 {
169         struct proc *p = td->td_proc;
170         struct protosw *prp;
171         struct socket *so;
172         struct pru_attach_info ai;
173         int error;
174
175         if (proto)
176                 prp = pffindproto(dom, proto, type);
177         else
178                 prp = pffindtype(dom, type);
179
180         if (prp == 0 || prp->pr_usrreqs->pru_attach == 0)
181                 return (EPROTONOSUPPORT);
182
183         if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
184             prp->pr_domain->dom_family != PF_LOCAL &&
185             prp->pr_domain->dom_family != PF_INET &&
186             prp->pr_domain->dom_family != PF_INET6 &&
187             prp->pr_domain->dom_family != PF_ROUTE) {
188                 return (EPROTONOSUPPORT);
189         }
190
191         if (prp->pr_type != type)
192                 return (EPROTOTYPE);
193         so = soalloc(p != 0);
194         if (so == NULL)
195                 return (ENOBUFS);
196
197         /*
198          * Callers of socreate() presumably will connect up a descriptor
199          * and call soclose() if they cannot.  This represents our so_refs
200          * (which should be 1) from soalloc().
201          */
202         soclrstate(so, SS_NOFDREF);
203
204         /*
205          * Set a default port for protocol processing.  No action will occur
206          * on the socket on this port until an inpcb is attached to it and
207          * is able to match incoming packets, or until the socket becomes
208          * available to userland.
209          *
210          * We normally default the socket to the protocol thread on cpu 0.
211          * If PR_SYNC_PORT is set (unix domain sockets) there is no protocol
212          * thread and all pr_*()/pru_*() calls are executed synchronously.
213          */
214         if (prp->pr_flags & PR_SYNC_PORT)
215                 so->so_port = &netisr_sync_port;
216         else
217                 so->so_port = cpu_portfn(0);
218
219         TAILQ_INIT(&so->so_incomp);
220         TAILQ_INIT(&so->so_comp);
221         so->so_type = type;
222         so->so_cred = crhold(p->p_ucred);
223         so->so_proto = prp;
224         ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
225         ai.p_ucred = p->p_ucred;
226         ai.fd_rdir = p->p_fd->fd_rdir;
227
228         /*
229          * Auto-sizing of socket buffers is managed by the protocols and
230          * the appropriate flags must be set in the pru_attach function.
231          */
232         error = so_pru_attach(so, proto, &ai);
233         if (error) {
234                 sosetstate(so, SS_NOFDREF);
235                 sofree(so);     /* from soalloc */
236                 return error;
237         }
238
239         /*
240          * NOTE: Returns referenced socket.
241          */
242         *aso = so;
243         return (0);
244 }
245
246 int
247 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
248 {
249         int error;
250
251         error = so_pru_bind(so, nam, td);
252         return (error);
253 }
254
255 static void
256 sodealloc(struct socket *so)
257 {
258         if (so->so_rcv.ssb_hiwat)
259                 (void)chgsbsize(so->so_cred->cr_uidinfo,
260                     &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
261         if (so->so_snd.ssb_hiwat)
262                 (void)chgsbsize(so->so_cred->cr_uidinfo,
263                     &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
264 #ifdef INET
265         /* remove accept filter if present */
266         if (so->so_accf != NULL)
267                 do_setopt_accept_filter(so, NULL);
268 #endif /* INET */
269         crfree(so->so_cred);
270         kfree(so, M_SOCKET);
271 }
272
273 int
274 solisten(struct socket *so, int backlog, struct thread *td)
275 {
276         int error;
277 #ifdef SCTP
278         short oldopt, oldqlimit;
279 #endif /* SCTP */
280
281         if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING))
282                 return (EINVAL);
283
284 #ifdef SCTP
285         oldopt = so->so_options;
286         oldqlimit = so->so_qlimit;
287 #endif /* SCTP */
288
289         lwkt_gettoken(&so->so_rcv.ssb_token);
290         if (TAILQ_EMPTY(&so->so_comp))
291                 so->so_options |= SO_ACCEPTCONN;
292         lwkt_reltoken(&so->so_rcv.ssb_token);
293         if (backlog < 0 || backlog > somaxconn)
294                 backlog = somaxconn;
295         so->so_qlimit = backlog;
296         /* SCTP needs to look at tweak both the inbound backlog parameter AND
297          * the so_options (UDP model both connect's and gets inbound
298          * connections .. implicitly).
299          */
300         error = so_pru_listen(so, td);
301         if (error) {
302 #ifdef SCTP
303                 /* Restore the params */
304                 so->so_options = oldopt;
305                 so->so_qlimit = oldqlimit;
306 #endif /* SCTP */
307                 return (error);
308         }
309         return (0);
310 }
311
312 /*
313  * Destroy a disconnected socket.  This routine is a NOP if entities
314  * still have a reference on the socket:
315  *
316  *      so_pcb -        The protocol stack still has a reference
317  *      SS_NOFDREF -    There is no longer a file pointer reference
318  */
319 void
320 sofree(struct socket *so)
321 {
322         struct socket *head;
323
324         /*
325          * This is a bit hackish at the moment.  We need to interlock
326          * any accept queue we are on before we potentially lose the
327          * last reference to avoid races against a re-reference from
328          * someone operating on the queue.
329          */
330         while ((head = so->so_head) != NULL) {
331                 lwkt_getpooltoken(head);
332                 if (so->so_head == head)
333                         break;
334                 lwkt_relpooltoken(head);
335         }
336
337         /*
338          * Arbitrage the last free.
339          */
340         KKASSERT(so->so_refs > 0);
341         if (atomic_fetchadd_int(&so->so_refs, -1) != 1) {
342                 if (head)
343                         lwkt_relpooltoken(head);
344                 return;
345         }
346
347         KKASSERT(so->so_pcb == NULL && (so->so_state & SS_NOFDREF));
348         KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
349
350         /*
351          * We're done, remove ourselves from the accept queue we are
352          * on, if we are on one.
353          */
354         if (head != NULL) {
355                 if (so->so_state & SS_INCOMP) {
356                         TAILQ_REMOVE(&head->so_incomp, so, so_list);
357                         head->so_incqlen--;
358                 } else if (so->so_state & SS_COMP) {
359                         /*
360                          * We must not decommission a socket that's
361                          * on the accept(2) queue.  If we do, then
362                          * accept(2) may hang after select(2) indicated
363                          * that the listening socket was ready.
364                          */
365                         lwkt_relpooltoken(head);
366                         return;
367                 } else {
368                         panic("sofree: not queued");
369                 }
370                 soclrstate(so, SS_INCOMP);
371                 so->so_head = NULL;
372                 lwkt_relpooltoken(head);
373         }
374         ssb_release(&so->so_snd, so);
375         sorflush(so);
376         sodealloc(so);
377 }
378
379 /*
380  * Close a socket on last file table reference removal.
381  * Initiate disconnect if connected.
382  * Free socket when disconnect complete.
383  */
384 int
385 soclose(struct socket *so, int fflag)
386 {
387         int error = 0;
388
389         funsetown(&so->so_sigio);
390         if (so->so_pcb == NULL)
391                 goto discard;
392         if (so->so_state & SS_ISCONNECTED) {
393                 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
394                         error = sodisconnect(so);
395                         if (error)
396                                 goto drop;
397                 }
398                 if (so->so_options & SO_LINGER) {
399                         if ((so->so_state & SS_ISDISCONNECTING) &&
400                             (fflag & FNONBLOCK))
401                                 goto drop;
402                         while (so->so_state & SS_ISCONNECTED) {
403                                 error = tsleep(&so->so_timeo, PCATCH,
404                                                "soclos", so->so_linger * hz);
405                                 if (error)
406                                         break;
407                         }
408                 }
409         }
410 drop:
411         if (so->so_pcb) {
412                 int error2;
413
414                 error2 = so_pru_detach(so);
415                 if (error == 0)
416                         error = error2;
417         }
418 discard:
419         lwkt_getpooltoken(so);
420         if (so->so_options & SO_ACCEPTCONN) {
421                 struct socket *sp;
422
423                 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
424                         TAILQ_REMOVE(&so->so_incomp, sp, so_list);
425                         soclrstate(sp, SS_INCOMP);
426                         sp->so_head = NULL;
427                         so->so_incqlen--;
428                         soaborta(sp);
429                 }
430                 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
431                         TAILQ_REMOVE(&so->so_comp, sp, so_list);
432                         soclrstate(sp, SS_COMP);
433                         sp->so_head = NULL;
434                         so->so_qlen--;
435                         soaborta(sp);
436                 }
437         }
438         lwkt_relpooltoken(so);
439         if (so->so_state & SS_NOFDREF)
440                 panic("soclose: NOFDREF");
441         sosetstate(so, SS_NOFDREF);     /* take ref */
442         sofree(so);                     /* dispose of ref */
443         return (error);
444 }
445
446 /*
447  * Abort and destroy a socket.  Only one abort can be in progress
448  * at any given moment.
449  */
450 void
451 soabort(struct socket *so)
452 {
453         soreference(so);
454         so_pru_abort(so);
455 }
456
457 void
458 soaborta(struct socket *so)
459 {
460         soreference(so);
461         so_pru_aborta(so);
462 }
463
464 void
465 soabort_oncpu(struct socket *so)
466 {
467         soreference(so);
468         so_pru_abort_oncpu(so);
469 }
470
471 /*
472  * so is passed in ref'd, which becomes owned by
473  * the cleared SS_NOFDREF flag.
474  */
475 int
476 soaccept(struct socket *so, struct sockaddr **nam)
477 {
478         int error;
479
480         if ((so->so_state & SS_NOFDREF) == 0)
481                 panic("soaccept: !NOFDREF");
482         soclrstate(so, SS_NOFDREF);     /* owned by lack of SS_NOFDREF */
483         error = so_pru_accept_direct(so, nam);
484         return (error);
485 }
486
487 int
488 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
489 {
490         int error;
491
492         if (so->so_options & SO_ACCEPTCONN)
493                 return (EOPNOTSUPP);
494         /*
495          * If protocol is connection-based, can only connect once.
496          * Otherwise, if connected, try to disconnect first.
497          * This allows user to disconnect by connecting to, e.g.,
498          * a null address.
499          */
500         if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
501             ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
502             (error = sodisconnect(so)))) {
503                 error = EISCONN;
504         } else {
505                 /*
506                  * Prevent accumulated error from previous connection
507                  * from biting us.
508                  */
509                 so->so_error = 0;
510                 error = so_pru_connect(so, nam, td);
511         }
512         return (error);
513 }
514
515 int
516 soconnect2(struct socket *so1, struct socket *so2)
517 {
518         int error;
519
520         error = so_pru_connect2(so1, so2);
521         return (error);
522 }
523
524 int
525 sodisconnect(struct socket *so)
526 {
527         int error;
528
529         if ((so->so_state & SS_ISCONNECTED) == 0) {
530                 error = ENOTCONN;
531                 goto bad;
532         }
533         if (so->so_state & SS_ISDISCONNECTING) {
534                 error = EALREADY;
535                 goto bad;
536         }
537         error = so_pru_disconnect(so);
538 bad:
539         return (error);
540 }
541
542 #define SBLOCKWAIT(f)   (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
543 /*
544  * Send on a socket.
545  * If send must go all at once and message is larger than
546  * send buffering, then hard error.
547  * Lock against other senders.
548  * If must go all at once and not enough room now, then
549  * inform user that this would block and do nothing.
550  * Otherwise, if nonblocking, send as much as possible.
551  * The data to be sent is described by "uio" if nonzero,
552  * otherwise by the mbuf chain "top" (which must be null
553  * if uio is not).  Data provided in mbuf chain must be small
554  * enough to send all at once.
555  *
556  * Returns nonzero on error, timeout or signal; callers
557  * must check for short counts if EINTR/ERESTART are returned.
558  * Data and control buffers are freed on return.
559  */
560 int
561 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
562         struct mbuf *top, struct mbuf *control, int flags,
563         struct thread *td)
564 {
565         struct mbuf **mp;
566         struct mbuf *m;
567         size_t resid;
568         int space, len;
569         int clen = 0, error, dontroute, mlen;
570         int atomic = sosendallatonce(so) || top;
571         int pru_flags;
572
573         if (uio) {
574                 resid = uio->uio_resid;
575         } else {
576                 resid = (size_t)top->m_pkthdr.len;
577 #ifdef INVARIANTS
578                 len = 0;
579                 for (m = top; m; m = m->m_next)
580                         len += m->m_len;
581                 KKASSERT(top->m_pkthdr.len == len);
582 #endif
583         }
584
585         /*
586          * WARNING!  resid is unsigned, space and len are signed.  space
587          *           can wind up negative if the sockbuf is overcommitted.
588          *
589          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
590          * type sockets since that's an error.
591          */
592         if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
593                 error = EINVAL;
594                 goto out;
595         }
596
597         dontroute =
598             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
599             (so->so_proto->pr_flags & PR_ATOMIC);
600         if (td->td_lwp != NULL)
601                 td->td_lwp->lwp_ru.ru_msgsnd++;
602         if (control)
603                 clen = control->m_len;
604 #define gotoerr(errcode)        { error = errcode; goto release; }
605
606 restart:
607         error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
608         if (error)
609                 goto out;
610
611         do {
612                 if (so->so_state & SS_CANTSENDMORE)
613                         gotoerr(EPIPE);
614                 if (so->so_error) {
615                         error = so->so_error;
616                         so->so_error = 0;
617                         goto release;
618                 }
619                 if ((so->so_state & SS_ISCONNECTED) == 0) {
620                         /*
621                          * `sendto' and `sendmsg' is allowed on a connection-
622                          * based socket if it supports implied connect.
623                          * Return ENOTCONN if not connected and no address is
624                          * supplied.
625                          */
626                         if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
627                             (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
628                                 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
629                                     !(resid == 0 && clen != 0))
630                                         gotoerr(ENOTCONN);
631                         } else if (addr == 0)
632                             gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
633                                    ENOTCONN : EDESTADDRREQ);
634                 }
635                 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
636                     clen > so->so_snd.ssb_hiwat) {
637                         gotoerr(EMSGSIZE);
638                 }
639                 space = ssb_space(&so->so_snd);
640                 if (flags & MSG_OOB)
641                         space += 1024;
642                 if ((space < 0 || (size_t)space < resid + clen) && uio &&
643                     (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
644                         if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
645                                 gotoerr(EWOULDBLOCK);
646                         ssb_unlock(&so->so_snd);
647                         error = ssb_wait(&so->so_snd);
648                         if (error)
649                                 goto out;
650                         goto restart;
651                 }
652                 mp = &top;
653                 space -= clen;
654                 do {
655                     if (uio == NULL) {
656                         /*
657                          * Data is prepackaged in "top".
658                          */
659                         resid = 0;
660                         if (flags & MSG_EOR)
661                                 top->m_flags |= M_EOR;
662                     } else do {
663                         if (resid > INT_MAX)
664                                 resid = INT_MAX;
665                         m = m_getl((int)resid, MB_WAIT, MT_DATA,
666                                    top == NULL ? M_PKTHDR : 0, &mlen);
667                         if (top == NULL) {
668                                 m->m_pkthdr.len = 0;
669                                 m->m_pkthdr.rcvif = NULL;
670                         }
671                         len = imin((int)szmin(mlen, resid), space);
672                         if (resid < MINCLSIZE) {
673                                 /*
674                                  * For datagram protocols, leave room
675                                  * for protocol headers in first mbuf.
676                                  */
677                                 if (atomic && top == 0 && len < mlen)
678                                         MH_ALIGN(m, len);
679                         }
680                         space -= len;
681                         error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
682                         resid = uio->uio_resid;
683                         m->m_len = len;
684                         *mp = m;
685                         top->m_pkthdr.len += len;
686                         if (error)
687                                 goto release;
688                         mp = &m->m_next;
689                         if (resid == 0) {
690                                 if (flags & MSG_EOR)
691                                         top->m_flags |= M_EOR;
692                                 break;
693                         }
694                     } while (space > 0 && atomic);
695                     if (dontroute)
696                             so->so_options |= SO_DONTROUTE;
697                     if (flags & MSG_OOB) {
698                             pru_flags = PRUS_OOB;
699                     } else if ((flags & MSG_EOF) &&
700                                (so->so_proto->pr_flags & PR_IMPLOPCL) &&
701                                (resid == 0)) {
702                             /*
703                              * If the user set MSG_EOF, the protocol
704                              * understands this flag and nothing left to
705                              * send then use PRU_SEND_EOF instead of PRU_SEND.
706                              */
707                             pru_flags = PRUS_EOF;
708                     } else if (resid > 0 && space > 0) {
709                             /* If there is more to send, set PRUS_MORETOCOME */
710                             pru_flags = PRUS_MORETOCOME;
711                     } else {
712                             pru_flags = 0;
713                     }
714                     /*
715                      * XXX all the SS_CANTSENDMORE checks previously
716                      * done could be out of date.  We could have recieved
717                      * a reset packet in an interrupt or maybe we slept
718                      * while doing page faults in uiomove() etc. We could
719                      * probably recheck again inside the splnet() protection
720                      * here, but there are probably other places that this
721                      * also happens.  We must rethink this.
722                      */
723                     error = so_pru_send(so, pru_flags, top, addr, control, td);
724                     if (dontroute)
725                             so->so_options &= ~SO_DONTROUTE;
726                     clen = 0;
727                     control = 0;
728                     top = NULL;
729                     mp = &top;
730                     if (error)
731                             goto release;
732                 } while (resid && space > 0);
733         } while (resid);
734
735 release:
736         ssb_unlock(&so->so_snd);
737 out:
738         if (top)
739                 m_freem(top);
740         if (control)
741                 m_freem(control);
742         return (error);
743 }
744
745 /*
746  * A specialization of sosend() for UDP based on protocol-specific knowledge:
747  *   so->so_proto->pr_flags has the PR_ATOMIC field set.  This means that
748  *      sosendallatonce() returns true,
749  *      the "atomic" variable is true,
750  *      and sosendudp() blocks until space is available for the entire send.
751  *   so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
752  *      PR_IMPLOPCL flags set.
753  *   UDP has no out-of-band data.
754  *   UDP has no control data.
755  *   UDP does not support MSG_EOR.
756  */
757 int
758 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
759           struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
760 {
761         boolean_t dontroute;            /* temporary SO_DONTROUTE setting */
762         size_t resid;
763         int error;
764         int space;
765
766         if (td->td_lwp != NULL)
767                 td->td_lwp->lwp_ru.ru_msgsnd++;
768         if (control)
769                 m_freem(control);
770
771         KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
772         resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
773
774 restart:
775         error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
776         if (error)
777                 goto out;
778
779         if (so->so_state & SS_CANTSENDMORE)
780                 gotoerr(EPIPE);
781         if (so->so_error) {
782                 error = so->so_error;
783                 so->so_error = 0;
784                 goto release;
785         }
786         if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
787                 gotoerr(EDESTADDRREQ);
788         if (resid > so->so_snd.ssb_hiwat)
789                 gotoerr(EMSGSIZE);
790         space = ssb_space(&so->so_snd);
791         if (uio && (space < 0 || (size_t)space < resid)) {
792                 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
793                         gotoerr(EWOULDBLOCK);
794                 ssb_unlock(&so->so_snd);
795                 error = ssb_wait(&so->so_snd);
796                 if (error)
797                         goto out;
798                 goto restart;
799         }
800
801         if (uio) {
802                 top = m_uiomove(uio);
803                 if (top == NULL)
804                         goto release;
805         }
806
807         dontroute = (flags & MSG_DONTROUTE) && !(so->so_options & SO_DONTROUTE);
808         if (dontroute)
809                 so->so_options |= SO_DONTROUTE;
810
811         error = so_pru_send(so, 0, top, addr, NULL, td);
812         top = NULL;             /* sent or freed in lower layer */
813
814         if (dontroute)
815                 so->so_options &= ~SO_DONTROUTE;
816
817 release:
818         ssb_unlock(&so->so_snd);
819 out:
820         if (top)
821                 m_freem(top);
822         return (error);
823 }
824
825 int
826 sosendtcp(struct socket *so, struct sockaddr *addr, struct uio *uio,
827         struct mbuf *top, struct mbuf *control, int flags,
828         struct thread *td)
829 {
830         struct mbuf **mp;
831         struct mbuf *m;
832         size_t resid;
833         int space, len;
834         int error, mlen;
835         int allatonce;
836         int pru_flags;
837
838         if (uio) {
839                 KKASSERT(top == NULL);
840                 allatonce = 0;
841                 resid = uio->uio_resid;
842         } else {
843                 allatonce = 1;
844                 resid = (size_t)top->m_pkthdr.len;
845 #ifdef INVARIANTS
846                 len = 0;
847                 for (m = top; m; m = m->m_next)
848                         len += m->m_len;
849                 KKASSERT(top->m_pkthdr.len == len);
850 #endif
851         }
852
853         /*
854          * WARNING!  resid is unsigned, space and len are signed.  space
855          *           can wind up negative if the sockbuf is overcommitted.
856          *
857          * Also check to make sure that MSG_EOR isn't used on TCP
858          */
859         if (flags & MSG_EOR) {
860                 error = EINVAL;
861                 goto out;
862         }
863
864         if (control) {
865                 /* TCP doesn't do control messages (rights, creds, etc) */
866                 if (control->m_len) {
867                         error = EINVAL;
868                         goto out;
869                 }
870                 m_freem(control);       /* empty control, just free it */
871                 control = NULL;
872         }
873
874         if (td->td_lwp != NULL)
875                 td->td_lwp->lwp_ru.ru_msgsnd++;
876
877 #define gotoerr(errcode)        { error = errcode; goto release; }
878
879 restart:
880         error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
881         if (error)
882                 goto out;
883
884         do {
885                 if (so->so_state & SS_CANTSENDMORE)
886                         gotoerr(EPIPE);
887                 if (so->so_error) {
888                         error = so->so_error;
889                         so->so_error = 0;
890                         goto release;
891                 }
892                 if ((so->so_state & SS_ISCONNECTED) == 0 &&
893                     (so->so_state & SS_ISCONFIRMING) == 0)
894                         gotoerr(ENOTCONN);
895                 if (allatonce && resid > so->so_snd.ssb_hiwat)
896                         gotoerr(EMSGSIZE);
897
898                 space = ssb_space(&so->so_snd);
899                 if (flags & MSG_OOB)
900                         space += 1024;
901                 if ((space < 0 || (size_t)space < resid) && !allatonce &&
902                     space < so->so_snd.ssb_lowat) {
903                         if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
904                                 gotoerr(EWOULDBLOCK);
905                         ssb_unlock(&so->so_snd);
906                         error = ssb_wait(&so->so_snd);
907                         if (error)
908                                 goto out;
909                         goto restart;
910                 }
911                 mp = &top;
912                 do {
913                     if (uio == NULL) {
914                         /*
915                          * Data is prepackaged in "top".
916                          */
917                         resid = 0;
918                     } else do {
919                         if (resid > INT_MAX)
920                                 resid = INT_MAX;
921                         m = m_getl((int)resid, MB_WAIT, MT_DATA,
922                                    top == NULL ? M_PKTHDR : 0, &mlen);
923                         if (top == NULL) {
924                                 m->m_pkthdr.len = 0;
925                                 m->m_pkthdr.rcvif = NULL;
926                         }
927                         len = imin((int)szmin(mlen, resid), space);
928                         space -= len;
929                         error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
930                         resid = uio->uio_resid;
931                         m->m_len = len;
932                         *mp = m;
933                         top->m_pkthdr.len += len;
934                         if (error)
935                                 goto release;
936                         mp = &m->m_next;
937                         if (resid == 0)
938                                 break;
939                     } while (space > 0 && 0 /* XXX */);
940
941                     if (flags & MSG_OOB) {
942                             pru_flags = PRUS_OOB;
943                     } else if (resid > 0 && space > 0) {
944                             /* If there is more to send, set PRUS_MORETOCOME */
945                             pru_flags = PRUS_MORETOCOME;
946                     } else {
947                             pru_flags = 0;
948                     }
949
950                     /*
951                      * XXX all the SS_CANTSENDMORE checks previously
952                      * done could be out of date.  We could have recieved
953                      * a reset packet in an interrupt or maybe we slept
954                      * while doing page faults in uiomove() etc. We could
955                      * probably recheck again inside the splnet() protection
956                      * here, but there are probably other places that this
957                      * also happens.  We must rethink this.
958                      */
959                     if ((pru_flags & PRUS_OOB) ||
960                         (pru_flags & PRUS_MORETOCOME) == 0) {
961                             error = so_pru_send(so, pru_flags, top,
962                                 NULL, NULL, td);
963                     } else {
964                             so_pru_send_async(so, pru_flags, top,
965                                 NULL, NULL, td);
966                             error = 0;
967                     }
968
969                     top = NULL;
970                     mp = &top;
971                     if (error)
972                             goto release;
973                 } while (resid && space > 0);
974         } while (resid);
975
976 release:
977         ssb_unlock(&so->so_snd);
978 out:
979         if (top)
980                 m_freem(top);
981         if (control)
982                 m_freem(control);
983         return (error);
984 }
985
986 /*
987  * Implement receive operations on a socket.
988  *
989  * We depend on the way that records are added to the signalsockbuf
990  * by sbappend*.  In particular, each record (mbufs linked through m_next)
991  * must begin with an address if the protocol so specifies,
992  * followed by an optional mbuf or mbufs containing ancillary data,
993  * and then zero or more mbufs of data.
994  *
995  * Although the signalsockbuf is locked, new data may still be appended.
996  * A token inside the ssb_lock deals with MP issues and still allows
997  * the network to access the socket if we block in a uio.
998  *
999  * The caller may receive the data as a single mbuf chain by supplying
1000  * an mbuf **mp0 for use in returning the chain.  The uio is then used
1001  * only for the count in uio_resid.
1002  */
1003 int
1004 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
1005           struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
1006 {
1007         struct mbuf *m, *n;
1008         struct mbuf *free_chain = NULL;
1009         int flags, len, error, offset;
1010         struct protosw *pr = so->so_proto;
1011         int moff, type = 0;
1012         size_t resid, orig_resid;
1013
1014         if (uio)
1015                 resid = uio->uio_resid;
1016         else
1017                 resid = (size_t)(sio->sb_climit - sio->sb_cc);
1018         orig_resid = resid;
1019
1020         if (psa)
1021                 *psa = NULL;
1022         if (controlp)
1023                 *controlp = NULL;
1024         if (flagsp)
1025                 flags = *flagsp &~ MSG_EOR;
1026         else
1027                 flags = 0;
1028         if (flags & MSG_OOB) {
1029                 m = m_get(MB_WAIT, MT_DATA);
1030                 if (m == NULL)
1031                         return (ENOBUFS);
1032                 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
1033                 if (error)
1034                         goto bad;
1035                 if (sio) {
1036                         do {
1037                                 sbappend(sio, m);
1038                                 KKASSERT(resid >= (size_t)m->m_len);
1039                                 resid -= (size_t)m->m_len;
1040                         } while (resid > 0 && m);
1041                 } else {
1042                         do {
1043                                 uio->uio_resid = resid;
1044                                 error = uiomove(mtod(m, caddr_t),
1045                                                 (int)szmin(resid, m->m_len),
1046                                                 uio);
1047                                 resid = uio->uio_resid;
1048                                 m = m_free(m);
1049                         } while (uio->uio_resid && error == 0 && m);
1050                 }
1051 bad:
1052                 if (m)
1053                         m_freem(m);
1054                 return (error);
1055         }
1056         if ((so->so_state & SS_ISCONFIRMING) && resid)
1057                 so_pru_rcvd(so, 0);
1058
1059         /*
1060          * The token interlocks against the protocol thread while
1061          * ssb_lock is a blocking lock against other userland entities.
1062          */
1063         lwkt_gettoken(&so->so_rcv.ssb_token);
1064 restart:
1065         error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
1066         if (error)
1067                 goto done;
1068
1069         m = so->so_rcv.ssb_mb;
1070         /*
1071          * If we have less data than requested, block awaiting more
1072          * (subject to any timeout) if:
1073          *   1. the current count is less than the low water mark, or
1074          *   2. MSG_WAITALL is set, and it is possible to do the entire
1075          *      receive operation at once if we block (resid <= hiwat).
1076          *   3. MSG_DONTWAIT is not set
1077          * If MSG_WAITALL is set but resid is larger than the receive buffer,
1078          * we have to do the receive in sections, and thus risk returning
1079          * a short count if a timeout or signal occurs after we start.
1080          */
1081         if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1082             (size_t)so->so_rcv.ssb_cc < resid) &&
1083             (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
1084             ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
1085             m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
1086                 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
1087                 if (so->so_error) {
1088                         if (m)
1089                                 goto dontblock;
1090                         error = so->so_error;
1091                         if ((flags & MSG_PEEK) == 0)
1092                                 so->so_error = 0;
1093                         goto release;
1094                 }
1095                 if (so->so_state & SS_CANTRCVMORE) {
1096                         if (m)
1097                                 goto dontblock;
1098                         else
1099                                 goto release;
1100                 }
1101                 for (; m; m = m->m_next) {
1102                         if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1103                                 m = so->so_rcv.ssb_mb;
1104                                 goto dontblock;
1105                         }
1106                 }
1107                 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1108                     (pr->pr_flags & PR_CONNREQUIRED)) {
1109                         error = ENOTCONN;
1110                         goto release;
1111                 }
1112                 if (resid == 0)
1113                         goto release;
1114                 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
1115                         error = EWOULDBLOCK;
1116                         goto release;
1117                 }
1118                 ssb_unlock(&so->so_rcv);
1119                 error = ssb_wait(&so->so_rcv);
1120                 if (error)
1121                         goto done;
1122                 goto restart;
1123         }
1124 dontblock:
1125         if (uio && uio->uio_td && uio->uio_td->td_proc)
1126                 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
1127
1128         /*
1129          * note: m should be == sb_mb here.  Cache the next record while
1130          * cleaning up.  Note that calling m_free*() will break out critical
1131          * section.
1132          */
1133         KKASSERT(m == so->so_rcv.ssb_mb);
1134
1135         /*
1136          * Skip any address mbufs prepending the record.
1137          */
1138         if (pr->pr_flags & PR_ADDR) {
1139                 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
1140                 orig_resid = 0;
1141                 if (psa)
1142                         *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1143                 if (flags & MSG_PEEK)
1144                         m = m->m_next;
1145                 else
1146                         m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1147         }
1148
1149         /*
1150          * Skip any control mbufs prepending the record.
1151          */
1152 #ifdef SCTP
1153         if (pr->pr_flags & PR_ADDR_OPT) {
1154                 /*
1155                  * For SCTP we may be getting a
1156                  * whole message OR a partial delivery.
1157                  */
1158                 if (m && m->m_type == MT_SONAME) {
1159                         orig_resid = 0;
1160                         if (psa)
1161                                 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
1162                         if (flags & MSG_PEEK)
1163                                 m = m->m_next;
1164                         else
1165                                 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1166                 }
1167         }
1168 #endif /* SCTP */
1169         while (m && m->m_type == MT_CONTROL && error == 0) {
1170                 if (flags & MSG_PEEK) {
1171                         if (controlp)
1172                                 *controlp = m_copy(m, 0, m->m_len);
1173                         m = m->m_next;  /* XXX race */
1174                 } else {
1175                         if (controlp) {
1176                                 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1177                                 if (pr->pr_domain->dom_externalize &&
1178                                     mtod(m, struct cmsghdr *)->cmsg_type ==
1179                                     SCM_RIGHTS)
1180                                    error = (*pr->pr_domain->dom_externalize)(m);
1181                                 *controlp = m;
1182                                 m = n;
1183                         } else {
1184                                 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1185                         }
1186                 }
1187                 if (controlp && *controlp) {
1188                         orig_resid = 0;
1189                         controlp = &(*controlp)->m_next;
1190                 }
1191         }
1192
1193         /*
1194          * flag OOB data.
1195          */
1196         if (m) {
1197                 type = m->m_type;
1198                 if (type == MT_OOBDATA)
1199                         flags |= MSG_OOB;
1200         }
1201
1202         /*
1203          * Copy to the UIO or mbuf return chain (*mp).
1204          */
1205         moff = 0;
1206         offset = 0;
1207         while (m && resid > 0 && error == 0) {
1208                 if (m->m_type == MT_OOBDATA) {
1209                         if (type != MT_OOBDATA)
1210                                 break;
1211                 } else if (type == MT_OOBDATA)
1212                         break;
1213                 else
1214                     KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1215                         ("receive 3"));
1216                 soclrstate(so, SS_RCVATMARK);
1217                 len = (resid > INT_MAX) ? INT_MAX : resid;
1218                 if (so->so_oobmark && len > so->so_oobmark - offset)
1219                         len = so->so_oobmark - offset;
1220                 if (len > m->m_len - moff)
1221                         len = m->m_len - moff;
1222
1223                 /*
1224                  * Copy out to the UIO or pass the mbufs back to the SIO.
1225                  * The SIO is dealt with when we eat the mbuf, but deal
1226                  * with the resid here either way.
1227                  */
1228                 if (uio) {
1229                         uio->uio_resid = resid;
1230                         error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1231                         resid = uio->uio_resid;
1232                         if (error)
1233                                 goto release;
1234                 } else {
1235                         resid -= (size_t)len;
1236                 }
1237
1238                 /*
1239                  * Eat the entire mbuf or just a piece of it
1240                  */
1241                 if (len == m->m_len - moff) {
1242                         if (m->m_flags & M_EOR)
1243                                 flags |= MSG_EOR;
1244 #ifdef SCTP
1245                         if (m->m_flags & M_NOTIFICATION)
1246                                 flags |= MSG_NOTIFICATION;
1247 #endif /* SCTP */
1248                         if (flags & MSG_PEEK) {
1249                                 m = m->m_next;
1250                                 moff = 0;
1251                         } else {
1252                                 if (sio) {
1253                                         n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1254                                         sbappend(sio, m);
1255                                         m = n;
1256                                 } else {
1257                                         m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1258                                 }
1259                         }
1260                 } else {
1261                         if (flags & MSG_PEEK) {
1262                                 moff += len;
1263                         } else {
1264                                 if (sio) {
1265                                         n = m_copym(m, 0, len, MB_WAIT);
1266                                         if (n)
1267                                                 sbappend(sio, n);
1268                                 }
1269                                 m->m_data += len;
1270                                 m->m_len -= len;
1271                                 so->so_rcv.ssb_cc -= len;
1272                         }
1273                 }
1274                 if (so->so_oobmark) {
1275                         if ((flags & MSG_PEEK) == 0) {
1276                                 so->so_oobmark -= len;
1277                                 if (so->so_oobmark == 0) {
1278                                         sosetstate(so, SS_RCVATMARK);
1279                                         break;
1280                                 }
1281                         } else {
1282                                 offset += len;
1283                                 if (offset == so->so_oobmark)
1284                                         break;
1285                         }
1286                 }
1287                 if (flags & MSG_EOR)
1288                         break;
1289                 /*
1290                  * If the MSG_WAITALL flag is set (for non-atomic socket),
1291                  * we must not quit until resid == 0 or an error
1292                  * termination.  If a signal/timeout occurs, return
1293                  * with a short count but without error.
1294                  * Keep signalsockbuf locked against other readers.
1295                  */
1296                 while ((flags & MSG_WAITALL) && m == NULL && 
1297                        resid > 0 && !sosendallatonce(so) && 
1298                        so->so_rcv.ssb_mb == NULL) {
1299                         if (so->so_error || so->so_state & SS_CANTRCVMORE)
1300                                 break;
1301                         /*
1302                          * The window might have closed to zero, make
1303                          * sure we send an ack now that we've drained
1304                          * the buffer or we might end up blocking until
1305                          * the idle takes over (5 seconds).
1306                          */
1307                         if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1308                                 so_pru_rcvd(so, flags);
1309                         error = ssb_wait(&so->so_rcv);
1310                         if (error) {
1311                                 ssb_unlock(&so->so_rcv);
1312                                 error = 0;
1313                                 goto done;
1314                         }
1315                         m = so->so_rcv.ssb_mb;
1316                 }
1317         }
1318
1319         /*
1320          * If an atomic read was requested but unread data still remains
1321          * in the record, set MSG_TRUNC.
1322          */
1323         if (m && pr->pr_flags & PR_ATOMIC)
1324                 flags |= MSG_TRUNC;
1325
1326         /*
1327          * Cleanup.  If an atomic read was requested drop any unread data.
1328          */
1329         if ((flags & MSG_PEEK) == 0) {
1330                 if (m && (pr->pr_flags & PR_ATOMIC))
1331                         sbdroprecord(&so->so_rcv.sb);
1332                 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1333                         so_pru_rcvd(so, flags);
1334         }
1335
1336         if (orig_resid == resid && orig_resid &&
1337             (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1338                 ssb_unlock(&so->so_rcv);
1339                 goto restart;
1340         }
1341
1342         if (flagsp)
1343                 *flagsp |= flags;
1344 release:
1345         ssb_unlock(&so->so_rcv);
1346 done:
1347         lwkt_reltoken(&so->so_rcv.ssb_token);
1348         if (free_chain)
1349                 m_freem(free_chain);
1350         return (error);
1351 }
1352
1353 /*
1354  * Shut a socket down.  Note that we do not get a frontend lock as we
1355  * want to be able to shut the socket down even if another thread is
1356  * blocked in a read(), thus waking it up.
1357  */
1358 int
1359 soshutdown(struct socket *so, int how)
1360 {
1361         if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1362                 return (EINVAL);
1363
1364         if (how != SHUT_WR) {
1365                 /*ssb_lock(&so->so_rcv, M_WAITOK);*/
1366                 sorflush(so);
1367                 /*ssb_unlock(&so->so_rcv);*/
1368         }
1369         if (how != SHUT_RD)
1370                 return (so_pru_shutdown(so));
1371         return (0);
1372 }
1373
1374 void
1375 sorflush(struct socket *so)
1376 {
1377         struct signalsockbuf *ssb = &so->so_rcv;
1378         struct protosw *pr = so->so_proto;
1379         struct signalsockbuf asb;
1380
1381         atomic_set_int(&ssb->ssb_flags, SSB_NOINTR);
1382
1383         lwkt_gettoken(&ssb->ssb_token);
1384         socantrcvmore(so);
1385         asb = *ssb;
1386
1387         /*
1388          * Can't just blow up the ssb structure here
1389          */
1390         bzero(&ssb->sb, sizeof(ssb->sb));
1391         ssb->ssb_timeo = 0;
1392         ssb->ssb_lowat = 0;
1393         ssb->ssb_hiwat = 0;
1394         ssb->ssb_mbmax = 0;
1395         atomic_clear_int(&ssb->ssb_flags, SSB_CLEAR_MASK);
1396
1397         if ((pr->pr_flags & PR_RIGHTS) && pr->pr_domain->dom_dispose)
1398                 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1399         ssb_release(&asb, so);
1400
1401         lwkt_reltoken(&ssb->ssb_token);
1402 }
1403
1404 #ifdef INET
1405 static int
1406 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1407 {
1408         struct accept_filter_arg        *afap = NULL;
1409         struct accept_filter    *afp;
1410         struct so_accf  *af = so->so_accf;
1411         int     error = 0;
1412
1413         /* do not set/remove accept filters on non listen sockets */
1414         if ((so->so_options & SO_ACCEPTCONN) == 0) {
1415                 error = EINVAL;
1416                 goto out;
1417         }
1418
1419         /* removing the filter */
1420         if (sopt == NULL) {
1421                 if (af != NULL) {
1422                         if (af->so_accept_filter != NULL && 
1423                                 af->so_accept_filter->accf_destroy != NULL) {
1424                                 af->so_accept_filter->accf_destroy(so);
1425                         }
1426                         if (af->so_accept_filter_str != NULL) {
1427                                 FREE(af->so_accept_filter_str, M_ACCF);
1428                         }
1429                         FREE(af, M_ACCF);
1430                         so->so_accf = NULL;
1431                 }
1432                 so->so_options &= ~SO_ACCEPTFILTER;
1433                 return (0);
1434         }
1435         /* adding a filter */
1436         /* must remove previous filter first */
1437         if (af != NULL) {
1438                 error = EINVAL;
1439                 goto out;
1440         }
1441         /* don't put large objects on the kernel stack */
1442         MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1443         error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1444         afap->af_name[sizeof(afap->af_name)-1] = '\0';
1445         afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1446         if (error)
1447                 goto out;
1448         afp = accept_filt_get(afap->af_name);
1449         if (afp == NULL) {
1450                 error = ENOENT;
1451                 goto out;
1452         }
1453         MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1454         if (afp->accf_create != NULL) {
1455                 if (afap->af_name[0] != '\0') {
1456                         int len = strlen(afap->af_name) + 1;
1457
1458                         MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1459                         strcpy(af->so_accept_filter_str, afap->af_name);
1460                 }
1461                 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1462                 if (af->so_accept_filter_arg == NULL) {
1463                         FREE(af->so_accept_filter_str, M_ACCF);
1464                         FREE(af, M_ACCF);
1465                         so->so_accf = NULL;
1466                         error = EINVAL;
1467                         goto out;
1468                 }
1469         }
1470         af->so_accept_filter = afp;
1471         so->so_accf = af;
1472         so->so_options |= SO_ACCEPTFILTER;
1473 out:
1474         if (afap != NULL)
1475                 FREE(afap, M_TEMP);
1476         return (error);
1477 }
1478 #endif /* INET */
1479
1480 /*
1481  * Perhaps this routine, and sooptcopyout(), below, ought to come in
1482  * an additional variant to handle the case where the option value needs
1483  * to be some kind of integer, but not a specific size.
1484  * In addition to their use here, these functions are also called by the
1485  * protocol-level pr_ctloutput() routines.
1486  */
1487 int
1488 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1489 {
1490         return soopt_to_kbuf(sopt, buf, len, minlen);
1491 }
1492
1493 int
1494 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1495 {
1496         size_t  valsize;
1497
1498         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1499         KKASSERT(kva_p(buf));
1500
1501         /*
1502          * If the user gives us more than we wanted, we ignore it,
1503          * but if we don't get the minimum length the caller
1504          * wants, we return EINVAL.  On success, sopt->sopt_valsize
1505          * is set to however much we actually retrieved.
1506          */
1507         if ((valsize = sopt->sopt_valsize) < minlen)
1508                 return EINVAL;
1509         if (valsize > len)
1510                 sopt->sopt_valsize = valsize = len;
1511
1512         bcopy(sopt->sopt_val, buf, valsize);
1513         return 0;
1514 }
1515
1516
1517 int
1518 sosetopt(struct socket *so, struct sockopt *sopt)
1519 {
1520         int     error, optval;
1521         struct  linger l;
1522         struct  timeval tv;
1523         u_long  val;
1524         struct signalsockbuf *sotmp;
1525
1526         error = 0;
1527         sopt->sopt_dir = SOPT_SET;
1528         if (sopt->sopt_level != SOL_SOCKET) {
1529                 if (so->so_proto && so->so_proto->pr_ctloutput) {
1530                         return (so_pr_ctloutput(so, sopt));
1531                 }
1532                 error = ENOPROTOOPT;
1533         } else {
1534                 switch (sopt->sopt_name) {
1535 #ifdef INET
1536                 case SO_ACCEPTFILTER:
1537                         error = do_setopt_accept_filter(so, sopt);
1538                         if (error)
1539                                 goto bad;
1540                         break;
1541 #endif /* INET */
1542                 case SO_LINGER:
1543                         error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1544                         if (error)
1545                                 goto bad;
1546
1547                         so->so_linger = l.l_linger;
1548                         if (l.l_onoff)
1549                                 so->so_options |= SO_LINGER;
1550                         else
1551                                 so->so_options &= ~SO_LINGER;
1552                         break;
1553
1554                 case SO_DEBUG:
1555                 case SO_KEEPALIVE:
1556                 case SO_DONTROUTE:
1557                 case SO_USELOOPBACK:
1558                 case SO_BROADCAST:
1559                 case SO_REUSEADDR:
1560                 case SO_REUSEPORT:
1561                 case SO_OOBINLINE:
1562                 case SO_TIMESTAMP:
1563                         error = sooptcopyin(sopt, &optval, sizeof optval,
1564                                             sizeof optval);
1565                         if (error)
1566                                 goto bad;
1567                         if (optval)
1568                                 so->so_options |= sopt->sopt_name;
1569                         else
1570                                 so->so_options &= ~sopt->sopt_name;
1571                         break;
1572
1573                 case SO_SNDBUF:
1574                 case SO_RCVBUF:
1575                 case SO_SNDLOWAT:
1576                 case SO_RCVLOWAT:
1577                         error = sooptcopyin(sopt, &optval, sizeof optval,
1578                                             sizeof optval);
1579                         if (error)
1580                                 goto bad;
1581
1582                         /*
1583                          * Values < 1 make no sense for any of these
1584                          * options, so disallow them.
1585                          */
1586                         if (optval < 1) {
1587                                 error = EINVAL;
1588                                 goto bad;
1589                         }
1590
1591                         switch (sopt->sopt_name) {
1592                         case SO_SNDBUF:
1593                         case SO_RCVBUF:
1594                                 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
1595                                     &so->so_snd : &so->so_rcv, (u_long)optval,
1596                                     so,
1597                                     &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
1598                                         error = ENOBUFS;
1599                                         goto bad;
1600                                 }
1601                                 sotmp = (sopt->sopt_name == SO_SNDBUF) ?
1602                                                 &so->so_snd : &so->so_rcv;
1603                                 atomic_clear_int(&sotmp->ssb_flags,
1604                                                  SSB_AUTOSIZE);
1605                                 break;
1606
1607                         /*
1608                          * Make sure the low-water is never greater than
1609                          * the high-water.
1610                          */
1611                         case SO_SNDLOWAT:
1612                                 so->so_snd.ssb_lowat =
1613                                     (optval > so->so_snd.ssb_hiwat) ?
1614                                     so->so_snd.ssb_hiwat : optval;
1615                                 atomic_clear_int(&so->so_snd.ssb_flags,
1616                                                  SSB_AUTOLOWAT);
1617                                 break;
1618                         case SO_RCVLOWAT:
1619                                 so->so_rcv.ssb_lowat =
1620                                     (optval > so->so_rcv.ssb_hiwat) ?
1621                                     so->so_rcv.ssb_hiwat : optval;
1622                                 atomic_clear_int(&so->so_rcv.ssb_flags,
1623                                                  SSB_AUTOLOWAT);
1624                                 break;
1625                         }
1626                         break;
1627
1628                 case SO_SNDTIMEO:
1629                 case SO_RCVTIMEO:
1630                         error = sooptcopyin(sopt, &tv, sizeof tv,
1631                                             sizeof tv);
1632                         if (error)
1633                                 goto bad;
1634
1635                         /* assert(hz > 0); */
1636                         if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
1637                             tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1638                                 error = EDOM;
1639                                 goto bad;
1640                         }
1641                         /* assert(tick > 0); */
1642                         /* assert(ULONG_MAX - INT_MAX >= 1000000); */
1643                         val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
1644                         if (val > INT_MAX) {
1645                                 error = EDOM;
1646                                 goto bad;
1647                         }
1648                         if (val == 0 && tv.tv_usec != 0)
1649                                 val = 1;
1650
1651                         switch (sopt->sopt_name) {
1652                         case SO_SNDTIMEO:
1653                                 so->so_snd.ssb_timeo = val;
1654                                 break;
1655                         case SO_RCVTIMEO:
1656                                 so->so_rcv.ssb_timeo = val;
1657                                 break;
1658                         }
1659                         break;
1660                 default:
1661                         error = ENOPROTOOPT;
1662                         break;
1663                 }
1664                 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1665                         (void) so_pr_ctloutput(so, sopt);
1666                 }
1667         }
1668 bad:
1669         return (error);
1670 }
1671
1672 /* Helper routine for getsockopt */
1673 int
1674 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1675 {
1676         soopt_from_kbuf(sopt, buf, len);
1677         return 0;
1678 }
1679
1680 void
1681 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
1682 {
1683         size_t  valsize;
1684
1685         if (len == 0) {
1686                 sopt->sopt_valsize = 0;
1687                 return;
1688         }
1689
1690         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1691         KKASSERT(kva_p(buf));
1692
1693         /*
1694          * Documented get behavior is that we always return a value,
1695          * possibly truncated to fit in the user's buffer.
1696          * Traditional behavior is that we always tell the user
1697          * precisely how much we copied, rather than something useful
1698          * like the total amount we had available for her.
1699          * Note that this interface is not idempotent; the entire answer must
1700          * generated ahead of time.
1701          */
1702         valsize = szmin(len, sopt->sopt_valsize);
1703         sopt->sopt_valsize = valsize;
1704         if (sopt->sopt_val != 0) {
1705                 bcopy(buf, sopt->sopt_val, valsize);
1706         }
1707 }
1708
1709 int
1710 sogetopt(struct socket *so, struct sockopt *sopt)
1711 {
1712         int     error, optval;
1713         long    optval_l;
1714         struct  linger l;
1715         struct  timeval tv;
1716 #ifdef INET
1717         struct accept_filter_arg *afap;
1718 #endif
1719
1720         error = 0;
1721         sopt->sopt_dir = SOPT_GET;
1722         if (sopt->sopt_level != SOL_SOCKET) {
1723                 if (so->so_proto && so->so_proto->pr_ctloutput) {
1724                         return (so_pr_ctloutput(so, sopt));
1725                 } else
1726                         return (ENOPROTOOPT);
1727         } else {
1728                 switch (sopt->sopt_name) {
1729 #ifdef INET
1730                 case SO_ACCEPTFILTER:
1731                         if ((so->so_options & SO_ACCEPTCONN) == 0)
1732                                 return (EINVAL);
1733                         MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1734                                 M_TEMP, M_WAITOK | M_ZERO);
1735                         if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1736                                 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1737                                 if (so->so_accf->so_accept_filter_str != NULL)
1738                                         strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1739                         }
1740                         error = sooptcopyout(sopt, afap, sizeof(*afap));
1741                         FREE(afap, M_TEMP);
1742                         break;
1743 #endif /* INET */
1744                         
1745                 case SO_LINGER:
1746                         l.l_onoff = so->so_options & SO_LINGER;
1747                         l.l_linger = so->so_linger;
1748                         error = sooptcopyout(sopt, &l, sizeof l);
1749                         break;
1750
1751                 case SO_USELOOPBACK:
1752                 case SO_DONTROUTE:
1753                 case SO_DEBUG:
1754                 case SO_KEEPALIVE:
1755                 case SO_REUSEADDR:
1756                 case SO_REUSEPORT:
1757                 case SO_BROADCAST:
1758                 case SO_OOBINLINE:
1759                 case SO_TIMESTAMP:
1760                         optval = so->so_options & sopt->sopt_name;
1761 integer:
1762                         error = sooptcopyout(sopt, &optval, sizeof optval);
1763                         break;
1764
1765                 case SO_TYPE:
1766                         optval = so->so_type;
1767                         goto integer;
1768
1769                 case SO_ERROR:
1770                         optval = so->so_error;
1771                         so->so_error = 0;
1772                         goto integer;
1773
1774                 case SO_SNDBUF:
1775                         optval = so->so_snd.ssb_hiwat;
1776                         goto integer;
1777
1778                 case SO_RCVBUF:
1779                         optval = so->so_rcv.ssb_hiwat;
1780                         goto integer;
1781
1782                 case SO_SNDLOWAT:
1783                         optval = so->so_snd.ssb_lowat;
1784                         goto integer;
1785
1786                 case SO_RCVLOWAT:
1787                         optval = so->so_rcv.ssb_lowat;
1788                         goto integer;
1789
1790                 case SO_SNDTIMEO:
1791                 case SO_RCVTIMEO:
1792                         optval = (sopt->sopt_name == SO_SNDTIMEO ?
1793                                   so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
1794
1795                         tv.tv_sec = optval / hz;
1796                         tv.tv_usec = (optval % hz) * ustick;
1797                         error = sooptcopyout(sopt, &tv, sizeof tv);
1798                         break;                  
1799
1800                 case SO_SNDSPACE:
1801                         optval_l = ssb_space(&so->so_snd);
1802                         error = sooptcopyout(sopt, &optval_l, sizeof(optval_l));
1803                         break;
1804
1805                 default:
1806                         error = ENOPROTOOPT;
1807                         break;
1808                 }
1809                 return (error);
1810         }
1811 }
1812
1813 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1814 int
1815 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1816 {
1817         struct mbuf *m, *m_prev;
1818         int sopt_size = sopt->sopt_valsize, msize;
1819
1820         m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
1821                    0, &msize);
1822         if (m == NULL)
1823                 return (ENOBUFS);
1824         m->m_len = min(msize, sopt_size);
1825         sopt_size -= m->m_len;
1826         *mp = m;
1827         m_prev = m;
1828
1829         while (sopt_size > 0) {
1830                 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
1831                            MT_DATA, 0, &msize);
1832                 if (m == NULL) {
1833                         m_freem(*mp);
1834                         return (ENOBUFS);
1835                 }
1836                 m->m_len = min(msize, sopt_size);
1837                 sopt_size -= m->m_len;
1838                 m_prev->m_next = m;
1839                 m_prev = m;
1840         }
1841         return (0);
1842 }
1843
1844 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1845 int
1846 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1847 {
1848         soopt_to_mbuf(sopt, m);
1849         return 0;
1850 }
1851
1852 void
1853 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
1854 {
1855         size_t valsize;
1856         void *val;
1857
1858         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1859         KKASSERT(kva_p(m));
1860         if (sopt->sopt_val == NULL)
1861                 return;
1862         val = sopt->sopt_val;
1863         valsize = sopt->sopt_valsize;
1864         while (m != NULL && valsize >= m->m_len) {
1865                 bcopy(val, mtod(m, char *), m->m_len);
1866                 valsize -= m->m_len;
1867                 val = (caddr_t)val + m->m_len;
1868                 m = m->m_next;
1869         }
1870         if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1871                 panic("ip6_sooptmcopyin");
1872 }
1873
1874 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1875 int
1876 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1877 {
1878         return soopt_from_mbuf(sopt, m);
1879 }
1880
1881 int
1882 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
1883 {
1884         struct mbuf *m0 = m;
1885         size_t valsize = 0;
1886         size_t maxsize;
1887         void *val;
1888
1889         KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1890         KKASSERT(kva_p(m));
1891         if (sopt->sopt_val == NULL)
1892                 return 0;
1893         val = sopt->sopt_val;
1894         maxsize = sopt->sopt_valsize;
1895         while (m != NULL && maxsize >= m->m_len) {
1896                 bcopy(mtod(m, char *), val, m->m_len);
1897                maxsize -= m->m_len;
1898                val = (caddr_t)val + m->m_len;
1899                valsize += m->m_len;
1900                m = m->m_next;
1901         }
1902         if (m != NULL) {
1903                 /* enough soopt buffer should be given from user-land */
1904                 m_freem(m0);
1905                 return (EINVAL);
1906         }
1907         sopt->sopt_valsize = valsize;
1908         return 0;
1909 }
1910
1911 void
1912 sohasoutofband(struct socket *so)
1913 {
1914         if (so->so_sigio != NULL)
1915                 pgsigio(so->so_sigio, SIGURG, 0);
1916         KNOTE(&so->so_rcv.ssb_kq.ki_note, NOTE_OOB);
1917 }
1918
1919 int
1920 sokqfilter(struct file *fp, struct knote *kn)
1921 {
1922         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1923         struct signalsockbuf *ssb;
1924
1925         switch (kn->kn_filter) {
1926         case EVFILT_READ:
1927                 if (so->so_options & SO_ACCEPTCONN)
1928                         kn->kn_fop = &solisten_filtops;
1929                 else
1930                         kn->kn_fop = &soread_filtops;
1931                 ssb = &so->so_rcv;
1932                 break;
1933         case EVFILT_WRITE:
1934                 kn->kn_fop = &sowrite_filtops;
1935                 ssb = &so->so_snd;
1936                 break;
1937         case EVFILT_EXCEPT:
1938                 kn->kn_fop = &soexcept_filtops;
1939                 ssb = &so->so_rcv;
1940                 break;
1941         default:
1942                 return (EOPNOTSUPP);
1943         }
1944
1945         knote_insert(&ssb->ssb_kq.ki_note, kn);
1946         atomic_set_int(&ssb->ssb_flags, SSB_KNOTE);
1947         return (0);
1948 }
1949
1950 static void
1951 filt_sordetach(struct knote *kn)
1952 {
1953         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1954
1955         knote_remove(&so->so_rcv.ssb_kq.ki_note, kn);
1956         if (SLIST_EMPTY(&so->so_rcv.ssb_kq.ki_note))
1957                 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_KNOTE);
1958 }
1959
1960 /*ARGSUSED*/
1961 static int
1962 filt_soread(struct knote *kn, long hint)
1963 {
1964         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1965
1966         if (kn->kn_sfflags & NOTE_OOB) {
1967                 if ((so->so_oobmark || (so->so_state & SS_RCVATMARK))) {
1968                         kn->kn_fflags |= NOTE_OOB;
1969                         return (1);
1970                 }
1971                 return (0);
1972         }
1973         kn->kn_data = so->so_rcv.ssb_cc;
1974
1975         if (so->so_state & SS_CANTRCVMORE) {
1976                 /*
1977                  * Only set NODATA if all data has been exhausted.
1978                  */
1979                 if (kn->kn_data == 0)
1980                         kn->kn_flags |= EV_NODATA;
1981                 kn->kn_flags |= EV_EOF; 
1982                 kn->kn_fflags = so->so_error;
1983                 return (1);
1984         }
1985         if (so->so_error)       /* temporary udp error */
1986                 return (1);
1987         if (kn->kn_sfflags & NOTE_LOWAT)
1988                 return (kn->kn_data >= kn->kn_sdata);
1989         return ((kn->kn_data >= so->so_rcv.ssb_lowat) ||
1990                 !TAILQ_EMPTY(&so->so_comp));
1991 }
1992
1993 static void
1994 filt_sowdetach(struct knote *kn)
1995 {
1996         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1997
1998         knote_remove(&so->so_snd.ssb_kq.ki_note, kn);
1999         if (SLIST_EMPTY(&so->so_snd.ssb_kq.ki_note))
2000                 atomic_clear_int(&so->so_snd.ssb_flags, SSB_KNOTE);
2001 }
2002
2003 /*ARGSUSED*/
2004 static int
2005 filt_sowrite(struct knote *kn, long hint)
2006 {
2007         struct socket *so = (struct socket *)kn->kn_fp->f_data;
2008
2009         kn->kn_data = ssb_space(&so->so_snd);
2010         if (so->so_state & SS_CANTSENDMORE) {
2011                 kn->kn_flags |= (EV_EOF | EV_NODATA);
2012                 kn->kn_fflags = so->so_error;
2013                 return (1);
2014         }
2015         if (so->so_error)       /* temporary udp error */
2016                 return (1);
2017         if (((so->so_state & SS_ISCONNECTED) == 0) &&
2018             (so->so_proto->pr_flags & PR_CONNREQUIRED))
2019                 return (0);
2020         if (kn->kn_sfflags & NOTE_LOWAT)
2021                 return (kn->kn_data >= kn->kn_sdata);
2022         return (kn->kn_data >= so->so_snd.ssb_lowat);
2023 }
2024
2025 /*ARGSUSED*/
2026 static int
2027 filt_solisten(struct knote *kn, long hint)
2028 {
2029         struct socket *so = (struct socket *)kn->kn_fp->f_data;
2030
2031         kn->kn_data = so->so_qlen;
2032         return (! TAILQ_EMPTY(&so->so_comp));
2033 }