network - Major netmsg retooling, part 1
[dragonfly.git] / sys / kern / uipc_socket2.c
1 /*
2  * Copyright (c) 2005 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 1982, 1986, 1988, 1990, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *      This product includes software developed by the University of
17  *      California, Berkeley and its contributors.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)uipc_socket2.c      8.1 (Berkeley) 6/10/93
35  * $FreeBSD: src/sys/kern/uipc_socket2.c,v 1.55.2.17 2002/08/31 19:04:55 dwmalone Exp $
36  * $DragonFly: src/sys/kern/uipc_socket2.c,v 1.33 2008/09/02 16:17:52 dillon Exp $
37  */
38
39 #include "opt_param.h"
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/domain.h>
43 #include <sys/file.h>   /* for maxfiles */
44 #include <sys/kernel.h>
45 #include <sys/proc.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/protosw.h>
49 #include <sys/resourcevar.h>
50 #include <sys/stat.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/socketops.h>
54 #include <sys/signalvar.h>
55 #include <sys/sysctl.h>
56 #include <sys/aio.h> /* for aio_swake proto */
57 #include <sys/event.h>
58
59 #include <sys/thread2.h>
60 #include <sys/msgport2.h>
61 #include <sys/socketvar2.h>
62
63 int     maxsockets;
64
65 /*
66  * Primitive routines for operating on sockets and socket buffers
67  */
68
69 u_long  sb_max = SB_MAX;
70 u_long  sb_max_adj =
71     SB_MAX * MCLBYTES / (MSIZE + MCLBYTES); /* adjusted sb_max */
72
73 static  u_long sb_efficiency = 8;       /* parameter for sbreserve() */
74
75 /************************************************************************
76  * signalsockbuf procedures                                             *
77  ************************************************************************/
78
79 /*
80  * Wait for data to arrive at/drain from a socket buffer.
81  *
82  * NOTE: Caller must generally hold the ssb_lock (client side lock) since
83  *       WAIT/WAKEUP only works for one client at a time.
84  *
85  * NOTE: Caller always retries whatever operation it was waiting on.
86  */
87 int
88 ssb_wait(struct signalsockbuf *ssb)
89 {
90         uint32_t flags;
91         int pflags;
92         int error;
93
94         pflags = (ssb->ssb_flags & SSB_NOINTR) ? 0 : PCATCH;
95
96         for (;;) {
97                 flags = ssb->ssb_flags;
98                 cpu_ccfence();
99
100                 /*
101                  * WAKEUP and WAIT interlock eachother.  We can catch the
102                  * race by checking to see if WAKEUP has already been set,
103                  * and only setting WAIT if WAKEUP is clear.
104                  */
105                 if (flags & SSB_WAKEUP) {
106                         if (atomic_cmpset_int(&ssb->ssb_flags, flags,
107                                               flags & ~SSB_WAKEUP)) {
108                                 error = 0;
109                                 break;
110                         }
111                         continue;
112                 }
113
114                 /*
115                  * Only set WAIT if WAKEUP is clear.
116                  */
117                 tsleep_interlock(&ssb->ssb_cc, pflags);
118                 if (atomic_cmpset_int(&ssb->ssb_flags, flags,
119                                       flags | SSB_WAIT)) {
120                         error = tsleep(&ssb->ssb_cc, pflags | PINTERLOCKED,
121                                        "sbwait", ssb->ssb_timeo);
122                         break;
123                 }
124         }
125         return (error);
126 }
127
128 /*
129  * Lock a sockbuf already known to be locked;
130  * return any error returned from sleep (EINTR).
131  */
132 int
133 _ssb_lock(struct signalsockbuf *ssb)
134 {
135         uint32_t flags;
136         int pflags;
137         int error;
138
139         pflags = (ssb->ssb_flags & SSB_NOINTR) ? 0 : PCATCH;
140
141         for (;;) {
142                 flags = ssb->ssb_flags;
143                 cpu_ccfence();
144                 if (flags & SSB_LOCK) {
145                         tsleep_interlock(&ssb->ssb_flags, pflags);
146                         if (atomic_cmpset_int(&ssb->ssb_flags, flags,
147                                               flags | SSB_WANT)) {
148                                 error = tsleep(&ssb->ssb_flags,
149                                                pflags | PINTERLOCKED,
150                                                "sblock", 0);
151                                 if (error)
152                                         break;
153                         }
154                 } else {
155                         if (atomic_cmpset_int(&ssb->ssb_flags, flags,
156                                               flags | SSB_LOCK)) {
157                                 lwkt_gettoken(&ssb->ssb_token);
158                                 error = 0;
159                                 break;
160                         }
161                 }
162         }
163         return (error);
164 }
165
166 /*
167  * This does the same for sockbufs.  Note that the xsockbuf structure,
168  * since it is always embedded in a socket, does not include a self
169  * pointer nor a length.  We make this entry point public in case
170  * some other mechanism needs it.
171  */
172 void
173 ssbtoxsockbuf(struct signalsockbuf *ssb, struct xsockbuf *xsb)
174 {
175         xsb->sb_cc = ssb->ssb_cc;
176         xsb->sb_hiwat = ssb->ssb_hiwat;
177         xsb->sb_mbcnt = ssb->ssb_mbcnt;
178         xsb->sb_mbmax = ssb->ssb_mbmax;
179         xsb->sb_lowat = ssb->ssb_lowat;
180         xsb->sb_flags = ssb->ssb_flags;
181         xsb->sb_timeo = ssb->ssb_timeo;
182 }
183
184
185 /************************************************************************
186  * Procedures which manipulate socket state flags, wakeups, etc.        *
187  ************************************************************************
188  *
189  * Normal sequence from the active (originating) side is that
190  * soisconnecting() is called during processing of connect() call, resulting
191  * in an eventual call to soisconnected() if/when the connection is
192  * established.  When the connection is torn down soisdisconnecting() is
193  * called during processing of disconnect() call, and soisdisconnected() is
194  * called when the connection to the peer is totally severed.
195  *
196  * The semantics of these routines are such that connectionless protocols
197  * can call soisconnected() and soisdisconnected() only, bypassing the
198  * in-progress calls when setting up a ``connection'' takes no time.
199  *
200  * From the passive side, a socket is created with two queues of sockets:
201  * so_incomp for connections in progress and so_comp for connections
202  * already made and awaiting user acceptance.  As a protocol is preparing
203  * incoming connections, it creates a socket structure queued on so_incomp
204  * by calling sonewconn().  When the connection is established,
205  * soisconnected() is called, and transfers the socket structure to so_comp,
206  * making it available to accept().
207  *
208  * If a socket is closed with sockets on either so_incomp or so_comp, these
209  * sockets are dropped.
210  *
211  * If higher level protocols are implemented in the kernel, the wakeups
212  * done here will sometimes cause software-interrupt process scheduling.
213  */
214
215 void
216 soisconnecting(struct socket *so)
217 {
218         soclrstate(so, SS_ISCONNECTED | SS_ISDISCONNECTING);
219         sosetstate(so, SS_ISCONNECTING);
220 }
221
222 void
223 soisconnected(struct socket *so)
224 {
225         struct socket *head = so->so_head;
226
227         soclrstate(so, SS_ISCONNECTING | SS_ISDISCONNECTING | SS_ISCONFIRMING);
228         sosetstate(so, SS_ISCONNECTED);
229         if (head && (so->so_state & SS_INCOMP)) {
230                 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
231                         so->so_upcall = head->so_accf->so_accept_filter->accf_callback;
232                         so->so_upcallarg = head->so_accf->so_accept_filter_arg;
233                         atomic_set_int(&so->so_rcv.ssb_flags, SSB_UPCALL);
234                         so->so_options &= ~SO_ACCEPTFILTER;
235                         so->so_upcall(so, so->so_upcallarg, 0);
236                         return;
237                 }
238
239                 /*
240                  * Listen socket are not per-cpu.
241                  */
242                 lwkt_gettoken(&head->so_rcv.ssb_token);
243                 TAILQ_REMOVE(&head->so_incomp, so, so_list);
244                 head->so_incqlen--;
245                 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
246                 head->so_qlen++;
247                 sosetstate(so, SS_COMP);
248                 soclrstate(so, SS_INCOMP);
249                 lwkt_reltoken(&head->so_rcv.ssb_token);
250
251                 /*
252                  * XXX head may be on a different protocol thread.
253                  *     sorwakeup()->sowakeup() is hacked atm.
254                  */
255                 sorwakeup(head);
256                 wakeup_one(&head->so_timeo);
257         } else {
258                 wakeup(&so->so_timeo);
259                 sorwakeup(so);
260                 sowwakeup(so);
261         }
262 }
263
264 void
265 soisdisconnecting(struct socket *so)
266 {
267         soclrstate(so, SS_ISCONNECTING);
268         sosetstate(so, SS_ISDISCONNECTING | SS_CANTRCVMORE | SS_CANTSENDMORE);
269         wakeup((caddr_t)&so->so_timeo);
270         sowwakeup(so);
271         sorwakeup(so);
272 }
273
274 void
275 soisdisconnected(struct socket *so)
276 {
277         soclrstate(so, SS_ISCONNECTING | SS_ISCONNECTED | SS_ISDISCONNECTING);
278         sosetstate(so, SS_CANTRCVMORE | SS_CANTSENDMORE | SS_ISDISCONNECTED);
279         wakeup((caddr_t)&so->so_timeo);
280         sbdrop(&so->so_snd.sb, so->so_snd.ssb_cc);
281         sowwakeup(so);
282         sorwakeup(so);
283 }
284
285 void
286 soisreconnecting(struct socket *so)
287 {
288         soclrstate(so, SS_ISDISCONNECTING | SS_ISDISCONNECTED |
289                        SS_CANTRCVMORE | SS_CANTSENDMORE);
290         sosetstate(so, SS_ISCONNECTING);
291 }
292
293 void
294 soisreconnected(struct socket *so)
295 {
296         soclrstate(so, SS_ISDISCONNECTED | SS_CANTRCVMORE | SS_CANTSENDMORE);
297         soisconnected(so);
298 }
299
300 /*
301  * Set or change the message port a socket receives commands on.
302  *
303  * XXX
304  */
305 void
306 sosetport(struct socket *so, lwkt_port_t port)
307 {
308         so->so_port = port;
309 }
310
311 /*
312  * When an attempt at a new connection is noted on a socket
313  * which accepts connections, sonewconn is called.  If the
314  * connection is possible (subject to space constraints, etc.)
315  * then we allocate a new structure, propoerly linked into the
316  * data structure of the original socket, and return this.
317  * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
318  *
319  * The new socket is returned with one ref and so_pcb assigned.
320  * The reference is implied by so_pcb.
321  */
322 struct socket *
323 sonewconn(struct socket *head, int connstatus)
324 {
325         struct socket *so;
326         struct socket *sp;
327         struct pru_attach_info ai;
328
329         if (head->so_qlen > 3 * head->so_qlimit / 2)
330                 return (NULL);
331         so = soalloc(1);
332         if (so == NULL)
333                 return (NULL);
334
335         /*
336          * Set the port prior to attaching the inpcb to the current
337          * cpu's protocol thread (which should be the current thread
338          * but might not be in all cases).  This serializes any pcb ops
339          * which occur to our cpu allowing us to complete the attachment
340          * without racing anything.
341          */
342         sosetport(so, cpu_portfn(mycpu->gd_cpuid));
343         if ((head->so_options & SO_ACCEPTFILTER) != 0)
344                 connstatus = 0;
345         so->so_head = head;
346         so->so_type = head->so_type;
347         so->so_options = head->so_options &~ SO_ACCEPTCONN;
348         so->so_linger = head->so_linger;
349
350         /*
351          * NOTE: Clearing NOFDREF implies referencing the so with
352          *       soreference().
353          */
354         so->so_state = head->so_state | SS_NOFDREF | SS_ASSERTINPROG;
355         so->so_proto = head->so_proto;
356         so->so_cred = crhold(head->so_cred);
357         ai.sb_rlimit = NULL;
358         ai.p_ucred = NULL;
359         ai.fd_rdir = NULL;              /* jail code cruft XXX JH */
360
361         /*
362          * Reserve space and call pru_attach.  We can direct-call the
363          * function since we're already in the protocol thread.
364          */
365         if (soreserve(so, head->so_snd.ssb_hiwat,
366                       head->so_rcv.ssb_hiwat, NULL) ||
367             so_pru_attach_direct(so, 0, &ai)) {
368                 so->so_head = NULL;
369                 soclrstate(so, SS_ASSERTINPROG);
370                 sofree(so);             /* remove implied pcb ref */
371                 return (NULL);
372         }
373         KKASSERT(so->so_refs == 2);     /* attach + our base ref */
374         sofree(so);
375         KKASSERT(so->so_port != NULL);
376         so->so_rcv.ssb_lowat = head->so_rcv.ssb_lowat;
377         so->so_snd.ssb_lowat = head->so_snd.ssb_lowat;
378         so->so_rcv.ssb_timeo = head->so_rcv.ssb_timeo;
379         so->so_snd.ssb_timeo = head->so_snd.ssb_timeo;
380         so->so_rcv.ssb_flags |= head->so_rcv.ssb_flags &
381                                 (SSB_AUTOSIZE | SSB_AUTOLOWAT);
382         so->so_snd.ssb_flags |= head->so_snd.ssb_flags &
383                                 (SSB_AUTOSIZE | SSB_AUTOLOWAT);
384         lwkt_gettoken(&head->so_rcv.ssb_token);
385         if (connstatus) {
386                 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
387                 sosetstate(so, SS_COMP);
388                 head->so_qlen++;
389         } else {
390                 if (head->so_incqlen > head->so_qlimit) {
391                         sp = TAILQ_FIRST(&head->so_incomp);
392                         TAILQ_REMOVE(&head->so_incomp, sp, so_list);
393                         head->so_incqlen--;
394                         soclrstate(sp, SS_INCOMP);
395                         sp->so_head = NULL;
396                         soaborta(sp);
397                 }
398                 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
399                 sosetstate(so, SS_INCOMP);
400                 head->so_incqlen++;
401         }
402         lwkt_reltoken(&head->so_rcv.ssb_token);
403         if (connstatus) {
404                 /*
405                  * XXX head may be on a different protocol thread.
406                  *     sorwakeup()->sowakeup() is hacked atm.
407                  */
408                 sorwakeup(head);
409                 wakeup((caddr_t)&head->so_timeo);
410                 sosetstate(so, connstatus);
411         }
412         soclrstate(so, SS_ASSERTINPROG);
413         return (so);
414 }
415
416 /*
417  * Socantsendmore indicates that no more data will be sent on the
418  * socket; it would normally be applied to a socket when the user
419  * informs the system that no more data is to be sent, by the protocol
420  * code (in case PRU_SHUTDOWN).  Socantrcvmore indicates that no more data
421  * will be received, and will normally be applied to the socket by a
422  * protocol when it detects that the peer will send no more data.
423  * Data queued for reading in the socket may yet be read.
424  */
425 void
426 socantsendmore(struct socket *so)
427 {
428         sosetstate(so, SS_CANTSENDMORE);
429         sowwakeup(so);
430 }
431
432 void
433 socantrcvmore(struct socket *so)
434 {
435         sosetstate(so, SS_CANTRCVMORE);
436         sorwakeup(so);
437 }
438
439 /*
440  * Wakeup processes waiting on a socket buffer.  Do asynchronous notification
441  * via SIGIO if the socket has the SS_ASYNC flag set.
442  *
443  * For users waiting on send/recv try to avoid unnecessary context switch
444  * thrashing.  Particularly for senders of large buffers (needs to be
445  * extended to sel and aio? XXX)
446  *
447  * WARNING!  Can be called on a foreign socket from the wrong protocol
448  *           thread.  aka is called on the 'head' listen socket when
449  *           a new connection comes in.
450  */
451 void
452 sowakeup(struct socket *so, struct signalsockbuf *ssb)
453 {
454         struct kqinfo *kqinfo = &ssb->ssb_kq;
455         uint32_t flags;
456
457         /*
458          * Check conditions, set the WAKEUP flag, and clear and signal if
459          * the WAIT flag is found to be set.  This interlocks against the
460          * client side.
461          */
462         for (;;) {
463                 flags = ssb->ssb_flags;
464                 cpu_ccfence();
465
466                 if ((ssb == &so->so_snd && ssb_space(ssb) >= ssb->ssb_lowat) ||
467                     (ssb == &so->so_rcv && ssb->ssb_cc >= ssb->ssb_lowat) ||
468                     (ssb == &so->so_snd && (so->so_state & SS_CANTSENDMORE)) ||
469                     (ssb == &so->so_rcv && (so->so_state & SS_CANTRCVMORE))
470                 ) {
471                         if (atomic_cmpset_int(&ssb->ssb_flags, flags,
472                                           (flags | SSB_WAKEUP) & ~SSB_WAIT)) {
473                                 if (flags & SSB_WAIT)
474                                         wakeup(&ssb->ssb_cc);
475                                 break;
476                         }
477                 } else {
478                         break;
479                 }
480         }
481
482         /*
483          * Misc other events
484          */
485         if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
486                 pgsigio(so->so_sigio, SIGIO, 0);
487         if (ssb->ssb_flags & SSB_UPCALL)
488                 (*so->so_upcall)(so, so->so_upcallarg, MB_DONTWAIT);
489         if (ssb->ssb_flags & SSB_AIO)
490                 aio_swake(so, ssb);
491         KNOTE(&kqinfo->ki_note, 0);
492
493         /*
494          * This is a bit of a hack.  Multiple threads can wind up scanning
495          * ki_mlist concurrently due to the fact that this function can be
496          * called on a foreign socket, so we can't afford to block here.
497          */
498         if (ssb->ssb_flags & SSB_MEVENT) {
499                 struct netmsg_so_notify *msg, *nmsg;
500
501                 lwkt_gettoken(&kq_token);
502                 lwkt_gettoken_hard(&ssb->ssb_token);
503                 TAILQ_FOREACH_MUTABLE(msg, &kqinfo->ki_mlist, nm_list, nmsg) {
504                         if (msg->nm_predicate(msg)) {
505                                 TAILQ_REMOVE(&kqinfo->ki_mlist, msg, nm_list);
506                                 lwkt_replymsg(&msg->base.lmsg,
507                                               msg->base.lmsg.ms_error);
508                         }
509                 }
510                 if (TAILQ_EMPTY(&ssb->ssb_kq.ki_mlist))
511                         atomic_clear_int(&ssb->ssb_flags, SSB_MEVENT);
512                 lwkt_reltoken_hard(&ssb->ssb_token);
513                 lwkt_reltoken(&kq_token);
514         }
515 }
516
517 /*
518  * Socket buffer (struct signalsockbuf) utility routines.
519  *
520  * Each socket contains two socket buffers: one for sending data and
521  * one for receiving data.  Each buffer contains a queue of mbufs,
522  * information about the number of mbufs and amount of data in the
523  * queue, and other fields allowing kevent()/select()/poll() statements
524  * and notification on data availability to be implemented.
525  *
526  * Data stored in a socket buffer is maintained as a list of records.
527  * Each record is a list of mbufs chained together with the m_next
528  * field.  Records are chained together with the m_nextpkt field. The upper
529  * level routine soreceive() expects the following conventions to be
530  * observed when placing information in the receive buffer:
531  *
532  * 1. If the protocol requires each message be preceded by the sender's
533  *    name, then a record containing that name must be present before
534  *    any associated data (mbuf's must be of type MT_SONAME).
535  * 2. If the protocol supports the exchange of ``access rights'' (really
536  *    just additional data associated with the message), and there are
537  *    ``rights'' to be received, then a record containing this data
538  *    should be present (mbuf's must be of type MT_RIGHTS).
539  * 3. If a name or rights record exists, then it must be followed by
540  *    a data record, perhaps of zero length.
541  *
542  * Before using a new socket structure it is first necessary to reserve
543  * buffer space to the socket, by calling sbreserve().  This should commit
544  * some of the available buffer space in the system buffer pool for the
545  * socket (currently, it does nothing but enforce limits).  The space
546  * should be released by calling ssb_release() when the socket is destroyed.
547  */
548 int
549 soreserve(struct socket *so, u_long sndcc, u_long rcvcc, struct rlimit *rl)
550 {
551         if (so->so_snd.ssb_lowat == 0)
552                 atomic_set_int(&so->so_snd.ssb_flags, SSB_AUTOLOWAT);
553         if (ssb_reserve(&so->so_snd, sndcc, so, rl) == 0)
554                 goto bad;
555         if (ssb_reserve(&so->so_rcv, rcvcc, so, rl) == 0)
556                 goto bad2;
557         if (so->so_rcv.ssb_lowat == 0)
558                 so->so_rcv.ssb_lowat = 1;
559         if (so->so_snd.ssb_lowat == 0)
560                 so->so_snd.ssb_lowat = MCLBYTES;
561         if (so->so_snd.ssb_lowat > so->so_snd.ssb_hiwat)
562                 so->so_snd.ssb_lowat = so->so_snd.ssb_hiwat;
563         return (0);
564 bad2:
565         ssb_release(&so->so_snd, so);
566 bad:
567         return (ENOBUFS);
568 }
569
570 static int
571 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
572 {
573         int error = 0;
574         u_long old_sb_max = sb_max;
575
576         error = SYSCTL_OUT(req, arg1, sizeof(int));
577         if (error || !req->newptr)
578                 return (error);
579         error = SYSCTL_IN(req, arg1, sizeof(int));
580         if (error)
581                 return (error);
582         if (sb_max < MSIZE + MCLBYTES) {
583                 sb_max = old_sb_max;
584                 return (EINVAL);
585         }
586         sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
587         return (0);
588 }
589         
590 /*
591  * Allot mbufs to a signalsockbuf.
592  *
593  * Attempt to scale mbmax so that mbcnt doesn't become limiting
594  * if buffering efficiency is near the normal case.
595  *
596  * sb_max only applies to user-sockets (where rl != NULL).  It does
597  * not apply to kernel sockets or kernel-controlled sockets.  Note
598  * that NFS overrides the sockbuf limits created when nfsd creates
599  * a socket.
600  */
601 int
602 ssb_reserve(struct signalsockbuf *ssb, u_long cc, struct socket *so,
603             struct rlimit *rl)
604 {
605         /*
606          * rl will only be NULL when we're in an interrupt (eg, in tcp_input)
607          * or when called from netgraph (ie, ngd_attach)
608          */
609         if (rl && cc > sb_max_adj)
610                 cc = sb_max_adj;
611         if (!chgsbsize(so->so_cred->cr_uidinfo, &ssb->ssb_hiwat, cc,
612                        rl ? rl->rlim_cur : RLIM_INFINITY)) {
613                 return (0);
614         }
615         if (rl)
616                 ssb->ssb_mbmax = min(cc * sb_efficiency, sb_max);
617         else
618                 ssb->ssb_mbmax = cc * sb_efficiency;
619
620         /*
621          * AUTOLOWAT is set on send buffers and prevents large writes
622          * from generating a huge number of context switches.
623          */
624         if (ssb->ssb_flags & SSB_AUTOLOWAT) {
625                 ssb->ssb_lowat = ssb->ssb_hiwat / 2;
626                 if (ssb->ssb_lowat < MCLBYTES)
627                         ssb->ssb_lowat = MCLBYTES;
628         }
629         if (ssb->ssb_lowat > ssb->ssb_hiwat)
630                 ssb->ssb_lowat = ssb->ssb_hiwat;
631         return (1);
632 }
633
634 /*
635  * Free mbufs held by a socket, and reserved mbuf space.
636  */
637 void
638 ssb_release(struct signalsockbuf *ssb, struct socket *so)
639 {
640         sbflush(&ssb->sb);
641         (void)chgsbsize(so->so_cred->cr_uidinfo, &ssb->ssb_hiwat, 0,
642             RLIM_INFINITY);
643         ssb->ssb_mbmax = 0;
644 }
645
646 /*
647  * Some routines that return EOPNOTSUPP for entry points that are not
648  * supported by a protocol.  Fill in as needed.
649  */
650 void
651 pr_generic_notsupp(netmsg_t msg)
652 {
653         lwkt_replymsg(&msg->lmsg, EOPNOTSUPP);
654 }
655
656 int
657 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
658            struct mbuf *top, struct mbuf *control, int flags,
659            struct thread *td)
660 {
661         if (top)
662                 m_freem(top);
663         if (control)
664                 m_freem(control);
665         return (EOPNOTSUPP);
666 }
667
668 int
669 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
670                       struct uio *uio, struct sockbuf *sio,
671                       struct mbuf **controlp, int *flagsp)
672 {
673         return (EOPNOTSUPP);
674 }
675
676 /*
677  * This isn't really a ``null'' operation, but it's the default one
678  * and doesn't do anything destructive.
679  */
680 void
681 pru_sense_null(netmsg_t msg)
682 {
683         msg->sense.nm_stat->st_blksize = msg->base.nm_so->so_snd.ssb_hiwat;
684         lwkt_replymsg(&msg->lmsg, 0);
685 }
686
687 /*
688  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.  Callers
689  * of this routine assume that it always succeeds, so we have to use a 
690  * blockable allocation even though we might be called from a critical thread.
691  */
692 struct sockaddr *
693 dup_sockaddr(const struct sockaddr *sa)
694 {
695         struct sockaddr *sa2;
696
697         sa2 = kmalloc(sa->sa_len, M_SONAME, M_INTWAIT);
698         bcopy(sa, sa2, sa->sa_len);
699         return (sa2);
700 }
701
702 /*
703  * Create an external-format (``xsocket'') structure using the information
704  * in the kernel-format socket structure pointed to by so.  This is done
705  * to reduce the spew of irrelevant information over this interface,
706  * to isolate user code from changes in the kernel structure, and
707  * potentially to provide information-hiding if we decide that
708  * some of this information should be hidden from users.
709  */
710 void
711 sotoxsocket(struct socket *so, struct xsocket *xso)
712 {
713         xso->xso_len = sizeof *xso;
714         xso->xso_so = so;
715         xso->so_type = so->so_type;
716         xso->so_options = so->so_options;
717         xso->so_linger = so->so_linger;
718         xso->so_state = so->so_state;
719         xso->so_pcb = so->so_pcb;
720         xso->xso_protocol = so->so_proto->pr_protocol;
721         xso->xso_family = so->so_proto->pr_domain->dom_family;
722         xso->so_qlen = so->so_qlen;
723         xso->so_incqlen = so->so_incqlen;
724         xso->so_qlimit = so->so_qlimit;
725         xso->so_timeo = so->so_timeo;
726         xso->so_error = so->so_error;
727         xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
728         xso->so_oobmark = so->so_oobmark;
729         ssbtoxsockbuf(&so->so_snd, &xso->so_snd);
730         ssbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
731         xso->so_uid = so->so_cred->cr_uid;
732 }
733
734 /*
735  * Here is the definition of some of the basic objects in the kern.ipc
736  * branch of the MIB.
737  */
738 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
739
740 /*
741  * This takes the place of kern.maxsockbuf, which moved to kern.ipc.
742  *
743  * NOTE! sb_max only applies to user-created socket buffers.
744  */
745 static int dummy;
746 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW, &dummy, 0, "");
747 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf, CTLTYPE_INT|CTLFLAG_RW, 
748     &sb_max, 0, sysctl_handle_sb_max, "I", "Maximum socket buffer size");
749 SYSCTL_INT(_kern_ipc, OID_AUTO, maxsockets, CTLFLAG_RD, 
750     &maxsockets, 0, "Maximum number of sockets available");
751 SYSCTL_INT(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
752     &sb_efficiency, 0, "");
753
754 /*
755  * Initialize maxsockets 
756  */
757 static void
758 init_maxsockets(void *ignored)
759 {
760     TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
761     maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
762 }
763 SYSINIT(param, SI_BOOT1_TUNABLES, SI_ORDER_ANY,
764         init_maxsockets, NULL);
765