Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[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.2 2003/06/17 04:28:41 dillon 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         register 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         register 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         register 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(head, connstatus)
175         register struct socket *head;
176         int connstatus;
177 {
178
179         return (sonewconn3(head, connstatus, NULL));
180 }
181
182 struct socket *
183 sonewconn3(head, connstatus, p)
184         register struct socket *head;
185         int connstatus;
186         struct proc *p;
187 {
188         register struct socket *so;
189
190         if (head->so_qlen > 3 * head->so_qlimit / 2)
191                 return ((struct socket *)0);
192         so = soalloc(0);
193         if (so == NULL)
194                 return ((struct socket *)0);
195         if ((head->so_options & SO_ACCEPTFILTER) != 0)
196                 connstatus = 0;
197         so->so_head = head;
198         so->so_type = head->so_type;
199         so->so_options = head->so_options &~ SO_ACCEPTCONN;
200         so->so_linger = head->so_linger;
201         so->so_state = head->so_state | SS_NOFDREF;
202         so->so_proto = head->so_proto;
203         so->so_timeo = head->so_timeo;
204         so->so_cred = p ? p->p_ucred : head->so_cred;
205         crhold(so->so_cred);
206         if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
207             (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
208                 sodealloc(so);
209                 return ((struct socket *)0);
210         }
211
212         if (connstatus) {
213                 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
214                 so->so_state |= SS_COMP;
215                 head->so_qlen++;
216         } else {
217                 if (head->so_incqlen > head->so_qlimit) {
218                         struct socket *sp;
219                         sp = TAILQ_FIRST(&head->so_incomp);
220                         (void) soabort(sp);
221                 }
222                 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
223                 so->so_state |= SS_INCOMP;
224                 head->so_incqlen++;
225         }
226         if (connstatus) {
227                 sorwakeup(head);
228                 wakeup((caddr_t)&head->so_timeo);
229                 so->so_state |= connstatus;
230         }
231         return (so);
232 }
233
234 /*
235  * Socantsendmore indicates that no more data will be sent on the
236  * socket; it would normally be applied to a socket when the user
237  * informs the system that no more data is to be sent, by the protocol
238  * code (in case PRU_SHUTDOWN).  Socantrcvmore indicates that no more data
239  * will be received, and will normally be applied to the socket by a
240  * protocol when it detects that the peer will send no more data.
241  * Data queued for reading in the socket may yet be read.
242  */
243
244 void
245 socantsendmore(so)
246         struct socket *so;
247 {
248
249         so->so_state |= SS_CANTSENDMORE;
250         sowwakeup(so);
251 }
252
253 void
254 socantrcvmore(so)
255         struct socket *so;
256 {
257
258         so->so_state |= SS_CANTRCVMORE;
259         sorwakeup(so);
260 }
261
262 /*
263  * Wait for data to arrive at/drain from a socket buffer.
264  */
265 int
266 sbwait(sb)
267         struct sockbuf *sb;
268 {
269
270         sb->sb_flags |= SB_WAIT;
271         return (tsleep((caddr_t)&sb->sb_cc,
272             (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
273             sb->sb_timeo));
274 }
275
276 /*
277  * Lock a sockbuf already known to be locked;
278  * return any error returned from sleep (EINTR).
279  */
280 int
281 sb_lock(sb)
282         register struct sockbuf *sb;
283 {
284         int error;
285
286         while (sb->sb_flags & SB_LOCK) {
287                 sb->sb_flags |= SB_WANT;
288                 error = tsleep((caddr_t)&sb->sb_flags,
289                     (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK|PCATCH,
290                     "sblock", 0);
291                 if (error)
292                         return (error);
293         }
294         sb->sb_flags |= SB_LOCK;
295         return (0);
296 }
297
298 /*
299  * Wakeup processes waiting on a socket buffer.
300  * Do asynchronous notification via SIGIO
301  * if the socket has the SS_ASYNC flag set.
302  */
303 void
304 sowakeup(so, sb)
305         register struct socket *so;
306         register struct sockbuf *sb;
307 {
308         selwakeup(&sb->sb_sel);
309         sb->sb_flags &= ~SB_SEL;
310         if (sb->sb_flags & SB_WAIT) {
311                 sb->sb_flags &= ~SB_WAIT;
312                 wakeup((caddr_t)&sb->sb_cc);
313         }
314         if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
315                 pgsigio(so->so_sigio, SIGIO, 0);
316         if (sb->sb_flags & SB_UPCALL)
317                 (*so->so_upcall)(so, so->so_upcallarg, M_DONTWAIT);
318         if (sb->sb_flags & SB_AIO)
319                 aio_swake(so, sb);
320         KNOTE(&sb->sb_sel.si_note, 0);
321 }
322
323 /*
324  * Socket buffer (struct sockbuf) utility routines.
325  *
326  * Each socket contains two socket buffers: one for sending data and
327  * one for receiving data.  Each buffer contains a queue of mbufs,
328  * information about the number of mbufs and amount of data in the
329  * queue, and other fields allowing select() statements and notification
330  * on data availability to be implemented.
331  *
332  * Data stored in a socket buffer is maintained as a list of records.
333  * Each record is a list of mbufs chained together with the m_next
334  * field.  Records are chained together with the m_nextpkt field. The upper
335  * level routine soreceive() expects the following conventions to be
336  * observed when placing information in the receive buffer:
337  *
338  * 1. If the protocol requires each message be preceded by the sender's
339  *    name, then a record containing that name must be present before
340  *    any associated data (mbuf's must be of type MT_SONAME).
341  * 2. If the protocol supports the exchange of ``access rights'' (really
342  *    just additional data associated with the message), and there are
343  *    ``rights'' to be received, then a record containing this data
344  *    should be present (mbuf's must be of type MT_RIGHTS).
345  * 3. If a name or rights record exists, then it must be followed by
346  *    a data record, perhaps of zero length.
347  *
348  * Before using a new socket structure it is first necessary to reserve
349  * buffer space to the socket, by calling sbreserve().  This should commit
350  * some of the available buffer space in the system buffer pool for the
351  * socket (currently, it does nothing but enforce limits).  The space
352  * should be released by calling sbrelease() when the socket is destroyed.
353  */
354
355 int
356 soreserve(so, sndcc, rcvcc)
357         register struct socket *so;
358         u_long sndcc, rcvcc;
359 {
360         struct proc *p = curproc;
361
362         if (sbreserve(&so->so_snd, sndcc, so, p) == 0)
363                 goto bad;
364         if (sbreserve(&so->so_rcv, rcvcc, so, p) == 0)
365                 goto bad2;
366         if (so->so_rcv.sb_lowat == 0)
367                 so->so_rcv.sb_lowat = 1;
368         if (so->so_snd.sb_lowat == 0)
369                 so->so_snd.sb_lowat = MCLBYTES;
370         if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
371                 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
372         return (0);
373 bad2:
374         sbrelease(&so->so_snd, so);
375 bad:
376         return (ENOBUFS);
377 }
378
379 static int
380 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
381 {
382         int error = 0;
383         u_long old_sb_max = sb_max;
384
385         error = SYSCTL_OUT(req, arg1, sizeof(int));
386         if (error || !req->newptr)
387                 return (error);
388         error = SYSCTL_IN(req, arg1, sizeof(int));
389         if (error)
390                 return (error);
391         if (sb_max < MSIZE + MCLBYTES) {
392                 sb_max = old_sb_max;
393                 return (EINVAL);
394         }
395         sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
396         return (0);
397 }
398         
399 /*
400  * Allot mbufs to a sockbuf.
401  * Attempt to scale mbmax so that mbcnt doesn't become limiting
402  * if buffering efficiency is near the normal case.
403  */
404 int
405 sbreserve(sb, cc, so, p)
406         struct sockbuf *sb;
407         u_long cc;
408         struct socket *so;
409         struct proc *p;
410 {
411
412         /*
413          * p will only be NULL when we're in an interrupt
414          * (e.g. in tcp_input())
415          */
416         if (cc > sb_max_adj)
417                 return (0);
418         if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
419             p ? p->p_rlimit[RLIMIT_SBSIZE].rlim_cur : RLIM_INFINITY)) {
420                 return (0);
421         }
422         sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
423         if (sb->sb_lowat > sb->sb_hiwat)
424                 sb->sb_lowat = sb->sb_hiwat;
425         return (1);
426 }
427
428 /*
429  * Free mbufs held by a socket, and reserved mbuf space.
430  */
431 void
432 sbrelease(sb, so)
433         struct sockbuf *sb;
434         struct socket *so;
435 {
436
437         sbflush(sb);
438         (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
439             RLIM_INFINITY);
440         sb->sb_mbmax = 0;
441 }
442
443 /*
444  * Routines to add and remove
445  * data from an mbuf queue.
446  *
447  * The routines sbappend() or sbappendrecord() are normally called to
448  * append new mbufs to a socket buffer, after checking that adequate
449  * space is available, comparing the function sbspace() with the amount
450  * of data to be added.  sbappendrecord() differs from sbappend() in
451  * that data supplied is treated as the beginning of a new record.
452  * To place a sender's address, optional access rights, and data in a
453  * socket receive buffer, sbappendaddr() should be used.  To place
454  * access rights and data in a socket receive buffer, sbappendrights()
455  * should be used.  In either case, the new data begins a new record.
456  * Note that unlike sbappend() and sbappendrecord(), these routines check
457  * for the caller that there will be enough space to store the data.
458  * Each fails if there is not enough space, or if it cannot find mbufs
459  * to store additional information in.
460  *
461  * Reliable protocols may use the socket send buffer to hold data
462  * awaiting acknowledgement.  Data is normally copied from a socket
463  * send buffer in a protocol with m_copy for output to a peer,
464  * and then removing the data from the socket buffer with sbdrop()
465  * or sbdroprecord() when the data is acknowledged by the peer.
466  */
467
468 /*
469  * Append mbuf chain m to the last record in the
470  * socket buffer sb.  The additional space associated
471  * the mbuf chain is recorded in sb.  Empty mbufs are
472  * discarded and mbufs are compacted where possible.
473  */
474 void
475 sbappend(sb, m)
476         struct sockbuf *sb;
477         struct mbuf *m;
478 {
479         register struct mbuf *n;
480
481         if (m == 0)
482                 return;
483         n = sb->sb_mb;
484         if (n) {
485                 while (n->m_nextpkt)
486                         n = n->m_nextpkt;
487                 do {
488                         if (n->m_flags & M_EOR) {
489                                 sbappendrecord(sb, m); /* XXXXXX!!!! */
490                                 return;
491                         }
492                 } while (n->m_next && (n = n->m_next));
493         }
494         sbcompress(sb, m, n);
495 }
496
497 #ifdef SOCKBUF_DEBUG
498 void
499 sbcheck(sb)
500         register struct sockbuf *sb;
501 {
502         register struct mbuf *m;
503         register struct mbuf *n = 0;
504         register u_long len = 0, mbcnt = 0;
505
506         for (m = sb->sb_mb; m; m = n) {
507             n = m->m_nextpkt;
508             for (; m; m = m->m_next) {
509                 len += m->m_len;
510                 mbcnt += MSIZE;
511                 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
512                         mbcnt += m->m_ext.ext_size;
513             }
514         }
515         if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
516                 printf("cc %ld != %ld || mbcnt %ld != %ld\n", len, sb->sb_cc,
517                     mbcnt, sb->sb_mbcnt);
518                 panic("sbcheck");
519         }
520 }
521 #endif
522
523 /*
524  * As above, except the mbuf chain
525  * begins a new record.
526  */
527 void
528 sbappendrecord(sb, m0)
529         register struct sockbuf *sb;
530         register struct mbuf *m0;
531 {
532         register struct mbuf *m;
533
534         if (m0 == 0)
535                 return;
536         m = sb->sb_mb;
537         if (m)
538                 while (m->m_nextpkt)
539                         m = m->m_nextpkt;
540         /*
541          * Put the first mbuf on the queue.
542          * Note this permits zero length records.
543          */
544         sballoc(sb, m0);
545         if (m)
546                 m->m_nextpkt = m0;
547         else
548                 sb->sb_mb = m0;
549         m = m0->m_next;
550         m0->m_next = 0;
551         if (m && (m0->m_flags & M_EOR)) {
552                 m0->m_flags &= ~M_EOR;
553                 m->m_flags |= M_EOR;
554         }
555         sbcompress(sb, m, m0);
556 }
557
558 /*
559  * As above except that OOB data
560  * is inserted at the beginning of the sockbuf,
561  * but after any other OOB data.
562  */
563 void
564 sbinsertoob(sb, m0)
565         register struct sockbuf *sb;
566         register struct mbuf *m0;
567 {
568         register struct mbuf *m;
569         register struct mbuf **mp;
570
571         if (m0 == 0)
572                 return;
573         for (mp = &sb->sb_mb; *mp ; mp = &((*mp)->m_nextpkt)) {
574             m = *mp;
575             again:
576                 switch (m->m_type) {
577
578                 case MT_OOBDATA:
579                         continue;               /* WANT next train */
580
581                 case MT_CONTROL:
582                         m = m->m_next;
583                         if (m)
584                                 goto again;     /* inspect THIS train further */
585                 }
586                 break;
587         }
588         /*
589          * Put the first mbuf on the queue.
590          * Note this permits zero length records.
591          */
592         sballoc(sb, m0);
593         m0->m_nextpkt = *mp;
594         *mp = m0;
595         m = m0->m_next;
596         m0->m_next = 0;
597         if (m && (m0->m_flags & M_EOR)) {
598                 m0->m_flags &= ~M_EOR;
599                 m->m_flags |= M_EOR;
600         }
601         sbcompress(sb, m, m0);
602 }
603
604 /*
605  * Append address and data, and optionally, control (ancillary) data
606  * to the receive queue of a socket.  If present,
607  * m0 must include a packet header with total length.
608  * Returns 0 if no space in sockbuf or insufficient mbufs.
609  */
610 int
611 sbappendaddr(sb, asa, m0, control)
612         register struct sockbuf *sb;
613         struct sockaddr *asa;
614         struct mbuf *m0, *control;
615 {
616         register struct mbuf *m, *n;
617         int space = asa->sa_len;
618
619 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
620 panic("sbappendaddr");
621         if (m0)
622                 space += m0->m_pkthdr.len;
623         for (n = control; n; n = n->m_next) {
624                 space += n->m_len;
625                 if (n->m_next == 0)     /* keep pointer to last control buf */
626                         break;
627         }
628         if (space > sbspace(sb))
629                 return (0);
630         if (asa->sa_len > MLEN)
631                 return (0);
632         MGET(m, M_DONTWAIT, MT_SONAME);
633         if (m == 0)
634                 return (0);
635         m->m_len = asa->sa_len;
636         bcopy((caddr_t)asa, mtod(m, caddr_t), asa->sa_len);
637         if (n)
638                 n->m_next = m0;         /* concatenate data to control */
639         else
640                 control = m0;
641         m->m_next = control;
642         for (n = m; n; n = n->m_next)
643                 sballoc(sb, n);
644         n = sb->sb_mb;
645         if (n) {
646                 while (n->m_nextpkt)
647                         n = n->m_nextpkt;
648                 n->m_nextpkt = m;
649         } else
650                 sb->sb_mb = m;
651         return (1);
652 }
653
654 int
655 sbappendcontrol(sb, m0, control)
656         struct sockbuf *sb;
657         struct mbuf *control, *m0;
658 {
659         register struct mbuf *m, *n;
660         int space = 0;
661
662         if (control == 0)
663                 panic("sbappendcontrol");
664         for (m = control; ; m = m->m_next) {
665                 space += m->m_len;
666                 if (m->m_next == 0)
667                         break;
668         }
669         n = m;                  /* save pointer to last control buffer */
670         for (m = m0; m; m = m->m_next)
671                 space += m->m_len;
672         if (space > sbspace(sb))
673                 return (0);
674         n->m_next = m0;                 /* concatenate data to control */
675         for (m = control; m; m = m->m_next)
676                 sballoc(sb, m);
677         n = sb->sb_mb;
678         if (n) {
679                 while (n->m_nextpkt)
680                         n = n->m_nextpkt;
681                 n->m_nextpkt = control;
682         } else
683                 sb->sb_mb = control;
684         return (1);
685 }
686
687 /*
688  * Compress mbuf chain m into the socket
689  * buffer sb following mbuf n.  If n
690  * is null, the buffer is presumed empty.
691  */
692 void
693 sbcompress(sb, m, n)
694         register struct sockbuf *sb;
695         register struct mbuf *m, *n;
696 {
697         register int eor = 0;
698         register struct mbuf *o;
699
700         while (m) {
701                 eor |= m->m_flags & M_EOR;
702                 if (m->m_len == 0 &&
703                     (eor == 0 ||
704                      (((o = m->m_next) || (o = n)) &&
705                       o->m_type == m->m_type))) {
706                         m = m_free(m);
707                         continue;
708                 }
709                 if (n && (n->m_flags & M_EOR) == 0 &&
710                     M_WRITABLE(n) &&
711                     m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
712                     m->m_len <= M_TRAILINGSPACE(n) &&
713                     n->m_type == m->m_type) {
714                         bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
715                             (unsigned)m->m_len);
716                         n->m_len += m->m_len;
717                         sb->sb_cc += m->m_len;
718                         m = m_free(m);
719                         continue;
720                 }
721                 if (n)
722                         n->m_next = m;
723                 else
724                         sb->sb_mb = m;
725                 sballoc(sb, m);
726                 n = m;
727                 m->m_flags &= ~M_EOR;
728                 m = m->m_next;
729                 n->m_next = 0;
730         }
731         if (eor) {
732                 if (n)
733                         n->m_flags |= eor;
734                 else
735                         printf("semi-panic: sbcompress\n");
736         }
737 }
738
739 /*
740  * Free all mbufs in a sockbuf.
741  * Check that all resources are reclaimed.
742  */
743 void
744 sbflush(sb)
745         register struct sockbuf *sb;
746 {
747
748         if (sb->sb_flags & SB_LOCK)
749                 panic("sbflush: locked");
750         while (sb->sb_mbcnt) {
751                 /*
752                  * Don't call sbdrop(sb, 0) if the leading mbuf is non-empty:
753                  * we would loop forever. Panic instead.
754                  */
755                 if (!sb->sb_cc && (sb->sb_mb == NULL || sb->sb_mb->m_len))
756                         break;
757                 sbdrop(sb, (int)sb->sb_cc);
758         }
759         if (sb->sb_cc || sb->sb_mb || sb->sb_mbcnt)
760                 panic("sbflush: cc %ld || mb %p || mbcnt %ld", sb->sb_cc, (void *)sb->sb_mb, sb->sb_mbcnt);
761 }
762
763 /*
764  * Drop data from (the front of) a sockbuf.
765  */
766 void
767 sbdrop(sb, len)
768         register struct sockbuf *sb;
769         register int len;
770 {
771         register struct mbuf *m;
772         struct mbuf *next;
773
774         next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
775         while (len > 0) {
776                 if (m == 0) {
777                         if (next == 0)
778                                 panic("sbdrop");
779                         m = next;
780                         next = m->m_nextpkt;
781                         continue;
782                 }
783                 if (m->m_len > len) {
784                         m->m_len -= len;
785                         m->m_data += len;
786                         sb->sb_cc -= len;
787                         break;
788                 }
789                 len -= m->m_len;
790                 sbfree(sb, m);
791                 m = m_free(m);
792         }
793         while (m && m->m_len == 0) {
794                 sbfree(sb, m);
795                 m = m_free(m);
796         }
797         if (m) {
798                 sb->sb_mb = m;
799                 m->m_nextpkt = next;
800         } else
801                 sb->sb_mb = next;
802 }
803
804 /*
805  * Drop a record off the front of a sockbuf
806  * and move the next record to the front.
807  */
808 void
809 sbdroprecord(sb)
810         register struct sockbuf *sb;
811 {
812         register struct mbuf *m;
813
814         m = sb->sb_mb;
815         if (m) {
816                 sb->sb_mb = m->m_nextpkt;
817                 do {
818                         sbfree(sb, m);
819                         m = m_free(m);
820                 } while (m);
821         }
822 }
823
824 /*
825  * Create a "control" mbuf containing the specified data
826  * with the specified type for presentation on a socket buffer.
827  */
828 struct mbuf *
829 sbcreatecontrol(p, size, type, level)
830         caddr_t p;
831         register int size;
832         int type, level;
833 {
834         register struct cmsghdr *cp;
835         struct mbuf *m;
836
837         if (CMSG_SPACE((u_int)size) > MCLBYTES)
838                 return ((struct mbuf *) NULL);
839         if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
840                 return ((struct mbuf *) NULL);
841         if (CMSG_SPACE((u_int)size) > MLEN) {
842                 MCLGET(m, M_DONTWAIT);
843                 if ((m->m_flags & M_EXT) == 0) {
844                         m_free(m);
845                         return ((struct mbuf *) NULL);
846                 }
847         }
848         cp = mtod(m, struct cmsghdr *);
849         m->m_len = 0;
850         KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
851             ("sbcreatecontrol: short mbuf"));
852         if (p != NULL)
853                 (void)memcpy(CMSG_DATA(cp), p, size);
854         m->m_len = CMSG_SPACE(size);
855         cp->cmsg_len = CMSG_LEN(size);
856         cp->cmsg_level = level;
857         cp->cmsg_type = type;
858         return (m);
859 }
860
861 /*
862  * Some routines that return EOPNOTSUPP for entry points that are not
863  * supported by a protocol.  Fill in as needed.
864  */
865 int
866 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
867 {
868         return EOPNOTSUPP;
869 }
870
871 int
872 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct proc *p)
873 {
874         return EOPNOTSUPP;
875 }
876
877 int
878 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
879 {
880         return EOPNOTSUPP;
881 }
882
883 int
884 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
885                     struct ifnet *ifp, struct proc *p)
886 {
887         return EOPNOTSUPP;
888 }
889
890 int
891 pru_listen_notsupp(struct socket *so, struct proc *p)
892 {
893         return EOPNOTSUPP;
894 }
895
896 int
897 pru_rcvd_notsupp(struct socket *so, int flags)
898 {
899         return EOPNOTSUPP;
900 }
901
902 int
903 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
904 {
905         return EOPNOTSUPP;
906 }
907
908 /*
909  * This isn't really a ``null'' operation, but it's the default one
910  * and doesn't do anything destructive.
911  */
912 int
913 pru_sense_null(struct socket *so, struct stat *sb)
914 {
915         sb->st_blksize = so->so_snd.sb_hiwat;
916         return 0;
917 }
918
919 /*
920  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
921  */
922 struct sockaddr *
923 dup_sockaddr(sa, canwait)
924         struct sockaddr *sa;
925         int canwait;
926 {
927         struct sockaddr *sa2;
928
929         MALLOC(sa2, struct sockaddr *, sa->sa_len, M_SONAME, 
930                canwait ? M_WAITOK : M_NOWAIT);
931         if (sa2)
932                 bcopy(sa, sa2, sa->sa_len);
933         return sa2;
934 }
935
936 /*
937  * Create an external-format (``xsocket'') structure using the information
938  * in the kernel-format socket structure pointed to by so.  This is done
939  * to reduce the spew of irrelevant information over this interface,
940  * to isolate user code from changes in the kernel structure, and
941  * potentially to provide information-hiding if we decide that
942  * some of this information should be hidden from users.
943  */
944 void
945 sotoxsocket(struct socket *so, struct xsocket *xso)
946 {
947         xso->xso_len = sizeof *xso;
948         xso->xso_so = so;
949         xso->so_type = so->so_type;
950         xso->so_options = so->so_options;
951         xso->so_linger = so->so_linger;
952         xso->so_state = so->so_state;
953         xso->so_pcb = so->so_pcb;
954         xso->xso_protocol = so->so_proto->pr_protocol;
955         xso->xso_family = so->so_proto->pr_domain->dom_family;
956         xso->so_qlen = so->so_qlen;
957         xso->so_incqlen = so->so_incqlen;
958         xso->so_qlimit = so->so_qlimit;
959         xso->so_timeo = so->so_timeo;
960         xso->so_error = so->so_error;
961         xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
962         xso->so_oobmark = so->so_oobmark;
963         sbtoxsockbuf(&so->so_snd, &xso->so_snd);
964         sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
965         xso->so_uid = so->so_cred->cr_uid;
966 }
967
968 /*
969  * This does the same for sockbufs.  Note that the xsockbuf structure,
970  * since it is always embedded in a socket, does not include a self
971  * pointer nor a length.  We make this entry point public in case
972  * some other mechanism needs it.
973  */
974 void
975 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
976 {
977         xsb->sb_cc = sb->sb_cc;
978         xsb->sb_hiwat = sb->sb_hiwat;
979         xsb->sb_mbcnt = sb->sb_mbcnt;
980         xsb->sb_mbmax = sb->sb_mbmax;
981         xsb->sb_lowat = sb->sb_lowat;
982         xsb->sb_flags = sb->sb_flags;
983         xsb->sb_timeo = sb->sb_timeo;
984 }
985
986 /*
987  * Here is the definition of some of the basic objects in the kern.ipc
988  * branch of the MIB.
989  */
990 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
991
992 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
993 static int dummy;
994 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW, &dummy, 0, "");
995 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf, CTLTYPE_INT|CTLFLAG_RW, 
996     &sb_max, 0, sysctl_handle_sb_max, "I", "Maximum socket buffer size");
997 SYSCTL_INT(_kern_ipc, OID_AUTO, maxsockets, CTLFLAG_RD, 
998     &maxsockets, 0, "Maximum number of sockets avaliable");
999 SYSCTL_INT(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1000     &sb_efficiency, 0, "");
1001
1002 /*
1003  * Initialise maxsockets 
1004  */
1005 static void init_maxsockets(void *ignored)
1006 {
1007     TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
1008     maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
1009 }
1010 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);