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