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