kernel tree reorganization stage 1: Major cvs repository work (not logged as
[dragonfly.git] / sys / kern / uipc_socket2.c
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)uipc_socket2.c      8.1 (Berkeley) 6/10/93
34  * $FreeBSD: src/sys/kern/uipc_socket2.c,v 1.55.2.17 2002/08/31 19:04:55 dwmalone Exp $
35  * $DragonFly: src/sys/kern/uipc_socket2.c,v 1.5 2003/07/26 19:42:11 rob Exp $
36  */
37
38 #include "opt_param.h"
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/domain.h>
42 #include <sys/file.h>   /* for maxfiles */
43 #include <sys/kernel.h>
44 #include <sys/proc.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/protosw.h>
48 #include <sys/resourcevar.h>
49 #include <sys/stat.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/signalvar.h>
53 #include <sys/sysctl.h>
54 #include <sys/aio.h> /* for aio_swake proto */
55 #include <sys/event.h>
56
57 int     maxsockets;
58
59 /*
60  * Primitive routines for operating on sockets and socket buffers
61  */
62
63 u_long  sb_max = SB_MAX;
64 u_long  sb_max_adj =
65     SB_MAX * MCLBYTES / (MSIZE + MCLBYTES); /* adjusted sb_max */
66
67 static  u_long sb_efficiency = 8;       /* parameter for sbreserve() */
68
69 /*
70  * Procedures to manipulate state flags of socket
71  * and do appropriate wakeups.  Normal sequence from the
72  * active (originating) side is that soisconnecting() is
73  * called during processing of connect() call,
74  * resulting in an eventual call to soisconnected() if/when the
75  * connection is established.  When the connection is torn down
76  * soisdisconnecting() is called during processing of disconnect() call,
77  * and soisdisconnected() is called when the connection to the peer
78  * is totally severed.  The semantics of these routines are such that
79  * connectionless protocols can call soisconnected() and soisdisconnected()
80  * only, bypassing the in-progress calls when setting up a ``connection''
81  * takes no time.
82  *
83  * From the passive side, a socket is created with
84  * two queues of sockets: so_incomp for connections in progress
85  * and so_comp for connections already made and awaiting user acceptance.
86  * As a protocol is preparing incoming connections, it creates a socket
87  * structure queued on so_incomp by calling sonewconn().  When the connection
88  * is established, soisconnected() is called, and transfers the
89  * socket structure to so_comp, making it available to accept().
90  *
91  * If a socket is closed with sockets on either
92  * so_incomp or so_comp, these sockets are dropped.
93  *
94  * If higher level protocols are implemented in
95  * the kernel, the wakeups done here will sometimes
96  * cause software-interrupt process scheduling.
97  */
98
99 void
100 soisconnecting(so)
101         struct socket *so;
102 {
103
104         so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
105         so->so_state |= SS_ISCONNECTING;
106 }
107
108 void
109 soisconnected(so)
110         struct socket *so;
111 {
112         struct socket *head = so->so_head;
113
114         so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
115         so->so_state |= SS_ISCONNECTED;
116         if (head && (so->so_state & SS_INCOMP)) {
117                 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
118                         so->so_upcall = head->so_accf->so_accept_filter->accf_callback;
119                         so->so_upcallarg = head->so_accf->so_accept_filter_arg;
120                         so->so_rcv.sb_flags |= SB_UPCALL;
121                         so->so_options &= ~SO_ACCEPTFILTER;
122                         so->so_upcall(so, so->so_upcallarg, 0);
123                         return;
124                 }
125                 TAILQ_REMOVE(&head->so_incomp, so, so_list);
126                 head->so_incqlen--;
127                 so->so_state &= ~SS_INCOMP;
128                 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
129                 head->so_qlen++;
130                 so->so_state |= SS_COMP;
131                 sorwakeup(head);
132                 wakeup_one(&head->so_timeo);
133         } else {
134                 wakeup(&so->so_timeo);
135                 sorwakeup(so);
136                 sowwakeup(so);
137         }
138 }
139
140 void
141 soisdisconnecting(so)
142         struct socket *so;
143 {
144
145         so->so_state &= ~SS_ISCONNECTING;
146         so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
147         wakeup((caddr_t)&so->so_timeo);
148         sowwakeup(so);
149         sorwakeup(so);
150 }
151
152 void
153 soisdisconnected(so)
154         struct socket *so;
155 {
156
157         so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
158         so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
159         wakeup((caddr_t)&so->so_timeo);
160         sbdrop(&so->so_snd, so->so_snd.sb_cc);
161         sowwakeup(so);
162         sorwakeup(so);
163 }
164
165 /*
166  * When an attempt at a new connection is noted on a socket
167  * which accepts connections, sonewconn is called.  If the
168  * connection is possible (subject to space constraints, etc.)
169  * then we allocate a new structure, propoerly linked into the
170  * data structure of the original socket, and return this.
171  * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
172  */
173 struct socket *
174 sonewconn(struct socket *head, int connstatus)
175 {
176         struct socket *so;
177
178         if (head->so_qlen > 3 * head->so_qlimit / 2)
179                 return ((struct socket *)0);
180         so = soalloc(0);
181         if (so == NULL)
182                 return ((struct socket *)0);
183         if ((head->so_options & SO_ACCEPTFILTER) != 0)
184                 connstatus = 0;
185         so->so_head = head;
186         so->so_type = head->so_type;
187         so->so_options = head->so_options &~ SO_ACCEPTCONN;
188         so->so_linger = head->so_linger;
189         so->so_state = head->so_state | SS_NOFDREF;
190         so->so_proto = head->so_proto;
191         so->so_timeo = head->so_timeo;
192         so->so_cred = crhold(head->so_cred);
193         if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
194             (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
195                 sodealloc(so);
196                 return ((struct socket *)0);
197         }
198
199         if (connstatus) {
200                 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
201                 so->so_state |= SS_COMP;
202                 head->so_qlen++;
203         } else {
204                 if (head->so_incqlen > head->so_qlimit) {
205                         struct socket *sp;
206                         sp = TAILQ_FIRST(&head->so_incomp);
207                         (void) soabort(sp);
208                 }
209                 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
210                 so->so_state |= SS_INCOMP;
211                 head->so_incqlen++;
212         }
213         if (connstatus) {
214                 sorwakeup(head);
215                 wakeup((caddr_t)&head->so_timeo);
216                 so->so_state |= connstatus;
217         }
218         return (so);
219 }
220
221 /*
222  * Socantsendmore indicates that no more data will be sent on the
223  * socket; it would normally be applied to a socket when the user
224  * informs the system that no more data is to be sent, by the protocol
225  * code (in case PRU_SHUTDOWN).  Socantrcvmore indicates that no more data
226  * will be received, and will normally be applied to the socket by a
227  * protocol when it detects that the peer will send no more data.
228  * Data queued for reading in the socket may yet be read.
229  */
230
231 void
232 socantsendmore(so)
233         struct socket *so;
234 {
235
236         so->so_state |= SS_CANTSENDMORE;
237         sowwakeup(so);
238 }
239
240 void
241 socantrcvmore(so)
242         struct socket *so;
243 {
244
245         so->so_state |= SS_CANTRCVMORE;
246         sorwakeup(so);
247 }
248
249 /*
250  * Wait for data to arrive at/drain from a socket buffer.
251  */
252 int
253 sbwait(sb)
254         struct sockbuf *sb;
255 {
256
257         sb->sb_flags |= SB_WAIT;
258         return (tsleep((caddr_t)&sb->sb_cc,
259                         ((sb->sb_flags & SB_NOINTR) ? 0 : PCATCH),
260                         "sbwait",
261                         sb->sb_timeo));
262 }
263
264 /*
265  * Lock a sockbuf already known to be locked;
266  * return any error returned from sleep (EINTR).
267  */
268 int
269 sb_lock(sb)
270         struct sockbuf *sb;
271 {
272         int error;
273
274         while (sb->sb_flags & SB_LOCK) {
275                 sb->sb_flags |= SB_WANT;
276                 error = tsleep((caddr_t)&sb->sb_flags,
277                             ((sb->sb_flags & SB_NOINTR) ? 0 : PCATCH),
278                             "sblock", 0);
279                 if (error)
280                         return (error);
281         }
282         sb->sb_flags |= SB_LOCK;
283         return (0);
284 }
285
286 /*
287  * Wakeup processes waiting on a socket buffer.
288  * Do asynchronous notification via SIGIO
289  * if the socket has the SS_ASYNC flag set.
290  */
291 void
292 sowakeup(so, sb)
293         struct socket *so;
294         struct sockbuf *sb;
295 {
296         selwakeup(&sb->sb_sel);
297         sb->sb_flags &= ~SB_SEL;
298         if (sb->sb_flags & SB_WAIT) {
299                 sb->sb_flags &= ~SB_WAIT;
300                 wakeup((caddr_t)&sb->sb_cc);
301         }
302         if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
303                 pgsigio(so->so_sigio, SIGIO, 0);
304         if (sb->sb_flags & SB_UPCALL)
305                 (*so->so_upcall)(so, so->so_upcallarg, M_DONTWAIT);
306         if (sb->sb_flags & SB_AIO)
307                 aio_swake(so, sb);
308         KNOTE(&sb->sb_sel.si_note, 0);
309 }
310
311 /*
312  * Socket buffer (struct sockbuf) utility routines.
313  *
314  * Each socket contains two socket buffers: one for sending data and
315  * one for receiving data.  Each buffer contains a queue of mbufs,
316  * information about the number of mbufs and amount of data in the
317  * queue, and other fields allowing select() statements and notification
318  * on data availability to be implemented.
319  *
320  * Data stored in a socket buffer is maintained as a list of records.
321  * Each record is a list of mbufs chained together with the m_next
322  * field.  Records are chained together with the m_nextpkt field. The upper
323  * level routine soreceive() expects the following conventions to be
324  * observed when placing information in the receive buffer:
325  *
326  * 1. If the protocol requires each message be preceded by the sender's
327  *    name, then a record containing that name must be present before
328  *    any associated data (mbuf's must be of type MT_SONAME).
329  * 2. If the protocol supports the exchange of ``access rights'' (really
330  *    just additional data associated with the message), and there are
331  *    ``rights'' to be received, then a record containing this data
332  *    should be present (mbuf's must be of type MT_RIGHTS).
333  * 3. If a name or rights record exists, then it must be followed by
334  *    a data record, perhaps of zero length.
335  *
336  * Before using a new socket structure it is first necessary to reserve
337  * buffer space to the socket, by calling sbreserve().  This should commit
338  * some of the available buffer space in the system buffer pool for the
339  * socket (currently, it does nothing but enforce limits).  The space
340  * should be released by calling sbrelease() when the socket is destroyed.
341  */
342
343 int
344 soreserve(so, sndcc, rcvcc)
345         struct socket *so;
346         u_long sndcc, rcvcc;
347 {
348         struct proc *p = curproc;
349
350         if (sbreserve(&so->so_snd, sndcc, so, p) == 0)
351                 goto bad;
352         if (sbreserve(&so->so_rcv, rcvcc, so, p) == 0)
353                 goto bad2;
354         if (so->so_rcv.sb_lowat == 0)
355                 so->so_rcv.sb_lowat = 1;
356         if (so->so_snd.sb_lowat == 0)
357                 so->so_snd.sb_lowat = MCLBYTES;
358         if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
359                 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
360         return (0);
361 bad2:
362         sbrelease(&so->so_snd, so);
363 bad:
364         return (ENOBUFS);
365 }
366
367 static int
368 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
369 {
370         int error = 0;
371         u_long old_sb_max = sb_max;
372
373         error = SYSCTL_OUT(req, arg1, sizeof(int));
374         if (error || !req->newptr)
375                 return (error);
376         error = SYSCTL_IN(req, arg1, sizeof(int));
377         if (error)
378                 return (error);
379         if (sb_max < MSIZE + MCLBYTES) {
380                 sb_max = old_sb_max;
381                 return (EINVAL);
382         }
383         sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
384         return (0);
385 }
386         
387 /*
388  * Allot mbufs to a sockbuf.
389  * Attempt to scale mbmax so that mbcnt doesn't become limiting
390  * if buffering efficiency is near the normal case.
391  */
392 int
393 sbreserve(sb, cc, so, p)
394         struct sockbuf *sb;
395         u_long cc;
396         struct socket *so;
397         struct proc *p;
398 {
399
400         /*
401          * p will only be NULL when we're in an interrupt
402          * (e.g. in tcp_input())
403          */
404         if (cc > sb_max_adj)
405                 return (0);
406         if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
407             p ? p->p_rlimit[RLIMIT_SBSIZE].rlim_cur : RLIM_INFINITY)) {
408                 return (0);
409         }
410         sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
411         if (sb->sb_lowat > sb->sb_hiwat)
412                 sb->sb_lowat = sb->sb_hiwat;
413         return (1);
414 }
415
416 /*
417  * Free mbufs held by a socket, and reserved mbuf space.
418  */
419 void
420 sbrelease(sb, so)
421         struct sockbuf *sb;
422         struct socket *so;
423 {
424
425         sbflush(sb);
426         (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
427             RLIM_INFINITY);
428         sb->sb_mbmax = 0;
429 }
430
431 /*
432  * Routines to add and remove
433  * data from an mbuf queue.
434  *
435  * The routines sbappend() or sbappendrecord() are normally called to
436  * append new mbufs to a socket buffer, after checking that adequate
437  * space is available, comparing the function sbspace() with the amount
438  * of data to be added.  sbappendrecord() differs from sbappend() in
439  * that data supplied is treated as the beginning of a new record.
440  * To place a sender's address, optional access rights, and data in a
441  * socket receive buffer, sbappendaddr() should be used.  To place
442  * access rights and data in a socket receive buffer, sbappendrights()
443  * should be used.  In either case, the new data begins a new record.
444  * Note that unlike sbappend() and sbappendrecord(), these routines check
445  * for the caller that there will be enough space to store the data.
446  * Each fails if there is not enough space, or if it cannot find mbufs
447  * to store additional information in.
448  *
449  * Reliable protocols may use the socket send buffer to hold data
450  * awaiting acknowledgement.  Data is normally copied from a socket
451  * send buffer in a protocol with m_copy for output to a peer,
452  * and then removing the data from the socket buffer with sbdrop()
453  * or sbdroprecord() when the data is acknowledged by the peer.
454  */
455
456 /*
457  * Append mbuf chain m to the last record in the
458  * socket buffer sb.  The additional space associated
459  * the mbuf chain is recorded in sb.  Empty mbufs are
460  * discarded and mbufs are compacted where possible.
461  */
462 void
463 sbappend(sb, m)
464         struct sockbuf *sb;
465         struct mbuf *m;
466 {
467         struct mbuf *n;
468
469         if (m == 0)
470                 return;
471         n = sb->sb_mb;
472         if (n) {
473                 while (n->m_nextpkt)
474                         n = n->m_nextpkt;
475                 do {
476                         if (n->m_flags & M_EOR) {
477                                 sbappendrecord(sb, m); /* XXXXXX!!!! */
478                                 return;
479                         }
480                 } while (n->m_next && (n = n->m_next));
481         }
482         sbcompress(sb, m, n);
483 }
484
485 #ifdef SOCKBUF_DEBUG
486 void
487 sbcheck(sb)
488         struct sockbuf *sb;
489 {
490         struct mbuf *m;
491         struct mbuf *n = 0;
492         u_long len = 0, mbcnt = 0;
493
494         for (m = sb->sb_mb; m; m = n) {
495             n = m->m_nextpkt;
496             for (; m; m = m->m_next) {
497                 len += m->m_len;
498                 mbcnt += MSIZE;
499                 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
500                         mbcnt += m->m_ext.ext_size;
501             }
502         }
503         if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
504                 printf("cc %ld != %ld || mbcnt %ld != %ld\n", len, sb->sb_cc,
505                     mbcnt, sb->sb_mbcnt);
506                 panic("sbcheck");
507         }
508 }
509 #endif
510
511 /*
512  * As above, except the mbuf chain
513  * begins a new record.
514  */
515 void
516 sbappendrecord(sb, m0)
517         struct sockbuf *sb;
518         struct mbuf *m0;
519 {
520         struct mbuf *m;
521
522         if (m0 == 0)
523                 return;
524         m = sb->sb_mb;
525         if (m)
526                 while (m->m_nextpkt)
527                         m = m->m_nextpkt;
528         /*
529          * Put the first mbuf on the queue.
530          * Note this permits zero length records.
531          */
532         sballoc(sb, m0);
533         if (m)
534                 m->m_nextpkt = m0;
535         else
536                 sb->sb_mb = m0;
537         m = m0->m_next;
538         m0->m_next = 0;
539         if (m && (m0->m_flags & M_EOR)) {
540                 m0->m_flags &= ~M_EOR;
541                 m->m_flags |= M_EOR;
542         }
543         sbcompress(sb, m, m0);
544 }
545
546 /*
547  * As above except that OOB data
548  * is inserted at the beginning of the sockbuf,
549  * but after any other OOB data.
550  */
551 void
552 sbinsertoob(sb, m0)
553         struct sockbuf *sb;
554         struct mbuf *m0;
555 {
556         struct mbuf *m;
557         struct mbuf **mp;
558
559         if (m0 == 0)
560                 return;
561         for (mp = &sb->sb_mb; *mp ; mp = &((*mp)->m_nextpkt)) {
562             m = *mp;
563             again:
564                 switch (m->m_type) {
565
566                 case MT_OOBDATA:
567                         continue;               /* WANT next train */
568
569                 case MT_CONTROL:
570                         m = m->m_next;
571                         if (m)
572                                 goto again;     /* inspect THIS train further */
573                 }
574                 break;
575         }
576         /*
577          * Put the first mbuf on the queue.
578          * Note this permits zero length records.
579          */
580         sballoc(sb, m0);
581         m0->m_nextpkt = *mp;
582         *mp = m0;
583         m = m0->m_next;
584         m0->m_next = 0;
585         if (m && (m0->m_flags & M_EOR)) {
586                 m0->m_flags &= ~M_EOR;
587                 m->m_flags |= M_EOR;
588         }
589         sbcompress(sb, m, m0);
590 }
591
592 /*
593  * Append address and data, and optionally, control (ancillary) data
594  * to the receive queue of a socket.  If present,
595  * m0 must include a packet header with total length.
596  * Returns 0 if no space in sockbuf or insufficient mbufs.
597  */
598 int
599 sbappendaddr(sb, asa, m0, control)
600         struct sockbuf *sb;
601         struct sockaddr *asa;
602         struct mbuf *m0, *control;
603 {
604         struct mbuf *m, *n;
605         int space = asa->sa_len;
606
607 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
608 panic("sbappendaddr");
609         if (m0)
610                 space += m0->m_pkthdr.len;
611         for (n = control; n; n = n->m_next) {
612                 space += n->m_len;
613                 if (n->m_next == 0)     /* keep pointer to last control buf */
614                         break;
615         }
616         if (space > sbspace(sb))
617                 return (0);
618         if (asa->sa_len > MLEN)
619                 return (0);
620         MGET(m, M_DONTWAIT, MT_SONAME);
621         if (m == 0)
622                 return (0);
623         m->m_len = asa->sa_len;
624         bcopy((caddr_t)asa, mtod(m, caddr_t), asa->sa_len);
625         if (n)
626                 n->m_next = m0;         /* concatenate data to control */
627         else
628                 control = m0;
629         m->m_next = control;
630         for (n = m; n; n = n->m_next)
631                 sballoc(sb, n);
632         n = sb->sb_mb;
633         if (n) {
634                 while (n->m_nextpkt)
635                         n = n->m_nextpkt;
636                 n->m_nextpkt = m;
637         } else
638                 sb->sb_mb = m;
639         return (1);
640 }
641
642 int
643 sbappendcontrol(sb, m0, control)
644         struct sockbuf *sb;
645         struct mbuf *control, *m0;
646 {
647         struct mbuf *m, *n;
648         int space = 0;
649
650         if (control == 0)
651                 panic("sbappendcontrol");
652         for (m = control; ; m = m->m_next) {
653                 space += m->m_len;
654                 if (m->m_next == 0)
655                         break;
656         }
657         n = m;                  /* save pointer to last control buffer */
658         for (m = m0; m; m = m->m_next)
659                 space += m->m_len;
660         if (space > sbspace(sb))
661                 return (0);
662         n->m_next = m0;                 /* concatenate data to control */
663         for (m = control; m; m = m->m_next)
664                 sballoc(sb, m);
665         n = sb->sb_mb;
666         if (n) {
667                 while (n->m_nextpkt)
668                         n = n->m_nextpkt;
669                 n->m_nextpkt = control;
670         } else
671                 sb->sb_mb = control;
672         return (1);
673 }
674
675 /*
676  * Compress mbuf chain m into the socket
677  * buffer sb following mbuf n.  If n
678  * is null, the buffer is presumed empty.
679  */
680 void
681 sbcompress(sb, m, n)
682         struct sockbuf *sb;
683         struct mbuf *m, *n;
684 {
685         int eor = 0;
686         struct mbuf *o;
687
688         while (m) {
689                 eor |= m->m_flags & M_EOR;
690                 if (m->m_len == 0 &&
691                     (eor == 0 ||
692                      (((o = m->m_next) || (o = n)) &&
693                       o->m_type == m->m_type))) {
694                         m = m_free(m);
695                         continue;
696                 }
697                 if (n && (n->m_flags & M_EOR) == 0 &&
698                     M_WRITABLE(n) &&
699                     m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
700                     m->m_len <= M_TRAILINGSPACE(n) &&
701                     n->m_type == m->m_type) {
702                         bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
703                             (unsigned)m->m_len);
704                         n->m_len += m->m_len;
705                         sb->sb_cc += m->m_len;
706                         m = m_free(m);
707                         continue;
708                 }
709                 if (n)
710                         n->m_next = m;
711                 else
712                         sb->sb_mb = m;
713                 sballoc(sb, m);
714                 n = m;
715                 m->m_flags &= ~M_EOR;
716                 m = m->m_next;
717                 n->m_next = 0;
718         }
719         if (eor) {
720                 if (n)
721                         n->m_flags |= eor;
722                 else
723                         printf("semi-panic: sbcompress\n");
724         }
725 }
726
727 /*
728  * Free all mbufs in a sockbuf.
729  * Check that all resources are reclaimed.
730  */
731 void
732 sbflush(sb)
733         struct sockbuf *sb;
734 {
735
736         if (sb->sb_flags & SB_LOCK)
737                 panic("sbflush: locked");
738         while (sb->sb_mbcnt) {
739                 /*
740                  * Don't call sbdrop(sb, 0) if the leading mbuf is non-empty:
741                  * we would loop forever. Panic instead.
742                  */
743                 if (!sb->sb_cc && (sb->sb_mb == NULL || sb->sb_mb->m_len))
744                         break;
745                 sbdrop(sb, (int)sb->sb_cc);
746         }
747         if (sb->sb_cc || sb->sb_mb || sb->sb_mbcnt)
748                 panic("sbflush: cc %ld || mb %p || mbcnt %ld", sb->sb_cc, (void *)sb->sb_mb, sb->sb_mbcnt);
749 }
750
751 /*
752  * Drop data from (the front of) a sockbuf.
753  */
754 void
755 sbdrop(sb, len)
756         struct sockbuf *sb;
757         int len;
758 {
759         struct mbuf *m;
760         struct mbuf *next;
761
762         next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
763         while (len > 0) {
764                 if (m == 0) {
765                         if (next == 0)
766                                 panic("sbdrop");
767                         m = next;
768                         next = m->m_nextpkt;
769                         continue;
770                 }
771                 if (m->m_len > len) {
772                         m->m_len -= len;
773                         m->m_data += len;
774                         sb->sb_cc -= len;
775                         break;
776                 }
777                 len -= m->m_len;
778                 sbfree(sb, m);
779                 m = m_free(m);
780         }
781         while (m && m->m_len == 0) {
782                 sbfree(sb, m);
783                 m = m_free(m);
784         }
785         if (m) {
786                 sb->sb_mb = m;
787                 m->m_nextpkt = next;
788         } else
789                 sb->sb_mb = next;
790 }
791
792 /*
793  * Drop a record off the front of a sockbuf
794  * and move the next record to the front.
795  */
796 void
797 sbdroprecord(sb)
798         struct sockbuf *sb;
799 {
800         struct mbuf *m;
801
802         m = sb->sb_mb;
803         if (m) {
804                 sb->sb_mb = m->m_nextpkt;
805                 do {
806                         sbfree(sb, m);
807                         m = m_free(m);
808                 } while (m);
809         }
810 }
811
812 /*
813  * Create a "control" mbuf containing the specified data
814  * with the specified type for presentation on a socket buffer.
815  */
816 struct mbuf *
817 sbcreatecontrol(p, size, type, level)
818         caddr_t p;
819         int size;
820         int type, level;
821 {
822         struct cmsghdr *cp;
823         struct mbuf *m;
824
825         if (CMSG_SPACE((u_int)size) > MCLBYTES)
826                 return ((struct mbuf *) NULL);
827         if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
828                 return ((struct mbuf *) NULL);
829         if (CMSG_SPACE((u_int)size) > MLEN) {
830                 MCLGET(m, M_DONTWAIT);
831                 if ((m->m_flags & M_EXT) == 0) {
832                         m_free(m);
833                         return ((struct mbuf *) NULL);
834                 }
835         }
836         cp = mtod(m, struct cmsghdr *);
837         m->m_len = 0;
838         KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
839             ("sbcreatecontrol: short mbuf"));
840         if (p != NULL)
841                 (void)memcpy(CMSG_DATA(cp), p, size);
842         m->m_len = CMSG_SPACE(size);
843         cp->cmsg_len = CMSG_LEN(size);
844         cp->cmsg_level = level;
845         cp->cmsg_type = type;
846         return (m);
847 }
848
849 /*
850  * Some routines that return EOPNOTSUPP for entry points that are not
851  * supported by a protocol.  Fill in as needed.
852  */
853 int
854 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
855 {
856         return EOPNOTSUPP;
857 }
858
859 int
860 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
861 {
862         return EOPNOTSUPP;
863 }
864
865 int
866 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
867 {
868         return EOPNOTSUPP;
869 }
870
871 int
872 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
873                     struct ifnet *ifp, struct thread *td)
874 {
875         return EOPNOTSUPP;
876 }
877
878 int
879 pru_listen_notsupp(struct socket *so, struct thread *td)
880 {
881         return EOPNOTSUPP;
882 }
883
884 int
885 pru_rcvd_notsupp(struct socket *so, int flags)
886 {
887         return EOPNOTSUPP;
888 }
889
890 int
891 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
892 {
893         return EOPNOTSUPP;
894 }
895
896 /*
897  * This isn't really a ``null'' operation, but it's the default one
898  * and doesn't do anything destructive.
899  */
900 int
901 pru_sense_null(struct socket *so, struct stat *sb)
902 {
903         sb->st_blksize = so->so_snd.sb_hiwat;
904         return 0;
905 }
906
907 /*
908  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
909  */
910 struct sockaddr *
911 dup_sockaddr(sa, canwait)
912         struct sockaddr *sa;
913         int canwait;
914 {
915         struct sockaddr *sa2;
916
917         MALLOC(sa2, struct sockaddr *, sa->sa_len, M_SONAME, 
918                canwait ? M_WAITOK : M_NOWAIT);
919         if (sa2)
920                 bcopy(sa, sa2, sa->sa_len);
921         return sa2;
922 }
923
924 /*
925  * Create an external-format (``xsocket'') structure using the information
926  * in the kernel-format socket structure pointed to by so.  This is done
927  * to reduce the spew of irrelevant information over this interface,
928  * to isolate user code from changes in the kernel structure, and
929  * potentially to provide information-hiding if we decide that
930  * some of this information should be hidden from users.
931  */
932 void
933 sotoxsocket(struct socket *so, struct xsocket *xso)
934 {
935         xso->xso_len = sizeof *xso;
936         xso->xso_so = so;
937         xso->so_type = so->so_type;
938         xso->so_options = so->so_options;
939         xso->so_linger = so->so_linger;
940         xso->so_state = so->so_state;
941         xso->so_pcb = so->so_pcb;
942         xso->xso_protocol = so->so_proto->pr_protocol;
943         xso->xso_family = so->so_proto->pr_domain->dom_family;
944         xso->so_qlen = so->so_qlen;
945         xso->so_incqlen = so->so_incqlen;
946         xso->so_qlimit = so->so_qlimit;
947         xso->so_timeo = so->so_timeo;
948         xso->so_error = so->so_error;
949         xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
950         xso->so_oobmark = so->so_oobmark;
951         sbtoxsockbuf(&so->so_snd, &xso->so_snd);
952         sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
953         xso->so_uid = so->so_cred->cr_uid;
954 }
955
956 /*
957  * This does the same for sockbufs.  Note that the xsockbuf structure,
958  * since it is always embedded in a socket, does not include a self
959  * pointer nor a length.  We make this entry point public in case
960  * some other mechanism needs it.
961  */
962 void
963 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
964 {
965         xsb->sb_cc = sb->sb_cc;
966         xsb->sb_hiwat = sb->sb_hiwat;
967         xsb->sb_mbcnt = sb->sb_mbcnt;
968         xsb->sb_mbmax = sb->sb_mbmax;
969         xsb->sb_lowat = sb->sb_lowat;
970         xsb->sb_flags = sb->sb_flags;
971         xsb->sb_timeo = sb->sb_timeo;
972 }
973
974 /*
975  * Here is the definition of some of the basic objects in the kern.ipc
976  * branch of the MIB.
977  */
978 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
979
980 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
981 static int dummy;
982 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW, &dummy, 0, "");
983 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf, CTLTYPE_INT|CTLFLAG_RW, 
984     &sb_max, 0, sysctl_handle_sb_max, "I", "Maximum socket buffer size");
985 SYSCTL_INT(_kern_ipc, OID_AUTO, maxsockets, CTLFLAG_RD, 
986     &maxsockets, 0, "Maximum number of sockets avaliable");
987 SYSCTL_INT(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
988     &sb_efficiency, 0, "");
989
990 /*
991  * Initialise maxsockets 
992  */
993 static void init_maxsockets(void *ignored)
994 {
995     TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
996     maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
997 }
998 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);