1 //==========================================================================
3 // src/sys/kern/uipc_socket2.c
5 //==========================================================================
6 //####BSDCOPYRIGHTBEGIN####
8 // -------------------------------------------
10 // Portions of this software may have been derived from OpenBSD,
11 // FreeBSD or other sources, and are covered by the appropriate
12 // copyright disclaimers included herein.
14 // Portions created by Red Hat are
15 // Copyright (C) 2002 Red Hat, Inc. All Rights Reserved.
17 // -------------------------------------------
19 //####BSDCOPYRIGHTEND####
20 //==========================================================================
23 * Copyright (c) 1982, 1986, 1988, 1990, 1993
24 * The Regents of the University of California. All rights reserved.
26 * Redistribution and use in source and binary forms, with or without
27 * modification, are permitted provided that the following conditions
29 * 1. Redistributions of source code must retain the above copyright
30 * notice, this list of conditions and the following disclaimer.
31 * 2. Redistributions in binary form must reproduce the above copyright
32 * notice, this list of conditions and the following disclaimer in the
33 * documentation and/or other materials provided with the distribution.
34 * 3. All advertising materials mentioning features or use of this software
35 * must display the following acknowledgement:
36 * This product includes software developed by the University of
37 * California, Berkeley and its contributors.
38 * 4. Neither the name of the University nor the names of its contributors
39 * may be used to endorse or promote products derived from this software
40 * without specific prior written permission.
42 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54 * @(#)uipc_socket2.c 8.1 (Berkeley) 6/10/93
55 * $FreeBSD: src/sys/kern/uipc_socket2.c,v 1.55.2.9 2001/07/26 18:53:02 peter Exp $
58 #include <sys/param.h>
59 #include <sys/domain.h>
60 #include <sys/malloc.h>
62 #include <sys/protosw.h>
63 #include <sys/socket.h>
64 #include <sys/socketvar.h>
66 #include <cyg/io/file.h>
68 int maxsockets = CYGPKG_NET_MAXSOCKETS;
71 * Primitive routines for operating on sockets and socket buffers
74 u_long sb_max = SB_MAX; /* XXX should be static */
76 static u_long sb_efficiency = 8; /* parameter for sbreserve() */
79 * Procedures to manipulate state flags of socket
80 * and do appropriate wakeups. Normal sequence from the
81 * active (originating) side is that soisconnecting() is
82 * called during processing of connect() call,
83 * resulting in an eventual call to soisconnected() if/when the
84 * connection is established. When the connection is torn down
85 * soisdisconnecting() is called during processing of disconnect() call,
86 * and soisdisconnected() is called when the connection to the peer
87 * is totally severed. The semantics of these routines are such that
88 * connectionless protocols can call soisconnected() and soisdisconnected()
89 * only, bypassing the in-progress calls when setting up a ``connection''
92 * From the passive side, a socket is created with
93 * two queues of sockets: so_incomp for connections in progress
94 * and so_comp for connections already made and awaiting user acceptance.
95 * As a protocol is preparing incoming connections, it creates a socket
96 * structure queued on so_incomp by calling sonewconn(). When the connection
97 * is established, soisconnected() is called, and transfers the
98 * socket structure to so_comp, making it available to accept().
100 * If a socket is closed with sockets on either
101 * so_incomp or so_comp, these sockets are dropped.
103 * If higher level protocols are implemented in
104 * the kernel, the wakeups done here will sometimes
105 * cause software-interrupt process scheduling.
110 register struct socket *so;
113 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
114 so->so_state |= SS_ISCONNECTING;
121 struct socket *head = so->so_head;
123 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
124 so->so_state |= SS_ISCONNECTED;
125 if (head && (so->so_state & SS_INCOMP)) {
126 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
127 so->so_upcall = head->so_accf->so_accept_filter->accf_callback;
128 so->so_upcallarg = head->so_accf->so_accept_filter_arg;
129 so->so_rcv.sb_flags |= SB_UPCALL;
130 so->so_options &= ~SO_ACCEPTFILTER;
131 so->so_upcall(so, so->so_upcallarg, 0);
134 TAILQ_REMOVE(&head->so_incomp, so, so_list);
136 so->so_state &= ~SS_INCOMP;
137 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
138 so->so_state |= SS_COMP;
140 wakeup_one(&head->so_timeo);
142 wakeup(&so->so_timeo);
149 soisdisconnecting(so)
150 register struct socket *so;
153 so->so_state &= ~SS_ISCONNECTING;
154 so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
155 wakeup((caddr_t)&so->so_timeo);
162 register struct socket *so;
165 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
166 so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
167 wakeup((caddr_t)&so->so_timeo);
173 * Return a random connection that hasn't been serviced yet and
174 * is eligible for discard. There is a one in qlen chance that
175 * we will return a null, saying that there are no dropable
176 * requests. In this case, the protocol specific code should drop
177 * the new request. This insures fairness.
179 * This may be used in conjunction with protocol specific queue
180 * congestion routines.
184 register struct socket *head;
186 register struct socket *so;
187 unsigned int i, j, qlen;
189 static struct timeval old_runtime;
190 static unsigned int cur_cnt, old_cnt;
194 if ((i = (tv.tv_sec - old_runtime.tv_sec)) != 0) {
196 old_cnt = cur_cnt / i;
200 so = TAILQ_FIRST(&head->so_incomp);
204 qlen = head->so_incqlen;
205 if (++cur_cnt > qlen || old_cnt > qlen) {
206 rnd = (314159 * rnd + 66329) & 0xffff;
207 j = ((qlen + 1) * rnd) >> 16;
210 so = TAILQ_NEXT(so, so_list);
217 * When an attempt at a new connection is noted on a socket
218 * which accepts connections, sonewconn is called. If the
219 * connection is possible (subject to space constraints, etc.)
220 * then we allocate a new structure, propoerly linked into the
221 * data structure of the original socket, and return this.
222 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
225 sonewconn(head, connstatus)
226 register struct socket *head;
230 return (sonewconn3(head, connstatus, NULL));
234 sonewconn3(head, connstatus, p)
235 register struct socket *head;
239 register struct socket *so;
241 if (head->so_qlen > 3 * head->so_qlimit / 2)
242 return ((struct socket *)0);
245 return ((struct socket *)0);
247 so->so_type = head->so_type;
248 so->so_options = head->so_options &~ SO_ACCEPTCONN;
249 so->so_linger = head->so_linger;
250 so->so_state = head->so_state | SS_NOFDREF;
251 so->so_proto = head->so_proto;
252 so->so_timeo = head->so_timeo;
253 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
254 (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
256 return ((struct socket *)0);
260 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
261 so->so_state |= SS_COMP;
263 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
264 so->so_state |= SS_INCOMP;
270 wakeup((caddr_t)&head->so_timeo);
271 so->so_state |= connstatus;
277 * Socantsendmore indicates that no more data will be sent on the
278 * socket; it would normally be applied to a socket when the user
279 * informs the system that no more data is to be sent, by the protocol
280 * code (in case PRU_SHUTDOWN). Socantrcvmore indicates that no more data
281 * will be received, and will normally be applied to the socket by a
282 * protocol when it detects that the peer will send no more data.
283 * Data queued for reading in the socket may yet be read.
291 so->so_state |= SS_CANTSENDMORE;
300 so->so_state |= SS_CANTRCVMORE;
305 * Wait for data to arrive at/drain from a socket buffer.
312 sb->sb_flags |= SB_WAIT;
313 return (tsleep((caddr_t)&sb->sb_cc,
314 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
319 * Lock a sockbuf already known to be locked;
320 * return any error returned from sleep (EINTR).
324 register struct sockbuf *sb;
328 while (sb->sb_flags & SB_LOCK) {
329 sb->sb_flags |= SB_WANT;
330 error = tsleep((caddr_t)&sb->sb_flags,
331 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK|PCATCH,
336 sb->sb_flags |= SB_LOCK;
341 * Wakeup processes waiting on a socket buffer.
342 * Do asynchronous notification via SIGIO
343 * if the socket has the SS_ASYNC flag set.
347 register struct socket *so;
348 register struct sockbuf *sb;
350 selwakeup(&sb->sb_sel);
351 sb->sb_flags &= ~SB_SEL;
352 if (sb->sb_flags & SB_WAIT) {
353 sb->sb_flags &= ~SB_WAIT;
354 wakeup((caddr_t)&sb->sb_cc);
356 if (sb->sb_flags & SB_UPCALL)
357 (*so->so_upcall)(so, so->so_upcallarg, M_DONTWAIT);
361 * Socket buffer (struct sockbuf) utility routines.
363 * Each socket contains two socket buffers: one for sending data and
364 * one for receiving data. Each buffer contains a queue of mbufs,
365 * information about the number of mbufs and amount of data in the
366 * queue, and other fields allowing select() statements and notification
367 * on data availability to be implemented.
369 * Data stored in a socket buffer is maintained as a list of records.
370 * Each record is a list of mbufs chained together with the m_next
371 * field. Records are chained together with the m_nextpkt field. The upper
372 * level routine soreceive() expects the following conventions to be
373 * observed when placing information in the receive buffer:
375 * 1. If the protocol requires each message be preceded by the sender's
376 * name, then a record containing that name must be present before
377 * any associated data (mbuf's must be of type MT_SONAME).
378 * 2. If the protocol supports the exchange of ``access rights'' (really
379 * just additional data associated with the message), and there are
380 * ``rights'' to be received, then a record containing this data
381 * should be present (mbuf's must be of type MT_RIGHTS).
382 * 3. If a name or rights record exists, then it must be followed by
383 * a data record, perhaps of zero length.
385 * Before using a new socket structure it is first necessary to reserve
386 * buffer space to the socket, by calling sbreserve(). This should commit
387 * some of the available buffer space in the system buffer pool for the
388 * socket (currently, it does nothing but enforce limits). The space
389 * should be released by calling sbrelease() when the socket is destroyed.
393 soreserve(so, sndcc, rcvcc)
394 register struct socket *so;
397 struct proc *p = curproc;
399 if (sbreserve(&so->so_snd, sndcc, so, p) == 0)
401 if (sbreserve(&so->so_rcv, rcvcc, so, p) == 0)
403 if (so->so_rcv.sb_lowat == 0)
404 so->so_rcv.sb_lowat = 1;
405 if (so->so_snd.sb_lowat == 0)
406 so->so_snd.sb_lowat = MCLBYTES;
407 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
408 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
411 sbrelease(&so->so_snd, so);
417 * Allot mbufs to a sockbuf.
418 * Attempt to scale mbmax so that mbcnt doesn't become limiting
419 * if buffering efficiency is near the normal case.
422 sbreserve(sb, cc, so, p)
430 * p will only be NULL when we're in an interrupt
431 * (e.g. in tcp_input())
433 if ((u_quad_t)cc > (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES))
436 sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
437 if (sb->sb_lowat > sb->sb_hiwat)
438 sb->sb_lowat = sb->sb_hiwat;
443 * Free mbufs held by a socket, and reserved mbuf space.
456 * Routines to add and remove
457 * data from an mbuf queue.
459 * The routines sbappend() or sbappendrecord() are normally called to
460 * append new mbufs to a socket buffer, after checking that adequate
461 * space is available, comparing the function sbspace() with the amount
462 * of data to be added. sbappendrecord() differs from sbappend() in
463 * that data supplied is treated as the beginning of a new record.
464 * To place a sender's address, optional access rights, and data in a
465 * socket receive buffer, sbappendaddr() should be used. To place
466 * access rights and data in a socket receive buffer, sbappendrights()
467 * should be used. In either case, the new data begins a new record.
468 * Note that unlike sbappend() and sbappendrecord(), these routines check
469 * for the caller that there will be enough space to store the data.
470 * Each fails if there is not enough space, or if it cannot find mbufs
471 * to store additional information in.
473 * Reliable protocols may use the socket send buffer to hold data
474 * awaiting acknowledgement. Data is normally copied from a socket
475 * send buffer in a protocol with m_copy for output to a peer,
476 * and then removing the data from the socket buffer with sbdrop()
477 * or sbdroprecord() when the data is acknowledged by the peer.
481 * Append mbuf chain m to the last record in the
482 * socket buffer sb. The additional space associated
483 * the mbuf chain is recorded in sb. Empty mbufs are
484 * discarded and mbufs are compacted where possible.
491 register struct mbuf *n;
500 if (n->m_flags & M_EOR) {
501 sbappendrecord(sb, m); /* XXXXXX!!!! */
504 } while (n->m_next && (n = n->m_next));
506 sbcompress(sb, m, n);
512 register struct sockbuf *sb;
514 register struct mbuf *m;
515 register struct mbuf *n = 0;
516 register u_long len = 0, mbcnt = 0;
518 for (m = sb->sb_mb; m; m = n) {
520 for (; m; m = m->m_next) {
523 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
524 mbcnt += m->m_ext.ext_size;
527 if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
528 printf("cc %ld != %ld || mbcnt %ld != %ld\n", len, sb->sb_cc,
529 mbcnt, sb->sb_mbcnt);
536 * As above, except the mbuf chain
537 * begins a new record.
540 sbappendrecord(sb, m0)
541 register struct sockbuf *sb;
542 register struct mbuf *m0;
544 register struct mbuf *m;
553 * Put the first mbuf on the queue.
554 * Note this permits zero length records.
563 if (m && (m0->m_flags & M_EOR)) {
564 m0->m_flags &= ~M_EOR;
567 sbcompress(sb, m, m0);
571 * As above except that OOB data
572 * is inserted at the beginning of the sockbuf,
573 * but after any other OOB data.
577 register struct sockbuf *sb;
578 register struct mbuf *m0;
580 register struct mbuf *m;
581 register struct mbuf **mp;
585 for (mp = &sb->sb_mb; *mp ; mp = &((*mp)->m_nextpkt)) {
591 continue; /* WANT next train */
596 goto again; /* inspect THIS train further */
601 * Put the first mbuf on the queue.
602 * Note this permits zero length records.
609 if (m && (m0->m_flags & M_EOR)) {
610 m0->m_flags &= ~M_EOR;
613 sbcompress(sb, m, m0);
617 * Append address and data, and optionally, control (ancillary) data
618 * to the receive queue of a socket. If present,
619 * m0 must include a packet header with total length.
620 * Returns 0 if no space in sockbuf or insufficient mbufs.
623 sbappendaddr(sb, asa, m0, control)
624 register struct sockbuf *sb;
625 struct sockaddr *asa;
626 struct mbuf *m0, *control;
628 register struct mbuf *m, *n;
629 int space = asa->sa_len;
631 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
632 panic("sbappendaddr");
634 space += m0->m_pkthdr.len;
635 for (n = control; n; n = n->m_next) {
637 if (n->m_next == 0) /* keep pointer to last control buf */
640 if (space > sbspace(sb))
642 if (asa->sa_len > MLEN)
644 MGET(m, M_DONTWAIT, MT_SONAME);
647 m->m_len = asa->sa_len;
648 bcopy((caddr_t)asa, mtod(m, caddr_t), asa->sa_len);
650 n->m_next = m0; /* concatenate data to control */
654 for (n = m; n; n = n->m_next)
667 sbappendcontrol(sb, m0, control)
669 struct mbuf *control, *m0;
671 register struct mbuf *m, *n;
675 panic("sbappendcontrol");
676 for (m = control; ; m = m->m_next) {
681 n = m; /* save pointer to last control buffer */
682 for (m = m0; m; m = m->m_next)
684 if (space > sbspace(sb))
686 n->m_next = m0; /* concatenate data to control */
687 for (m = control; m; m = m->m_next)
693 n->m_nextpkt = control;
700 * Compress mbuf chain m into the socket
701 * buffer sb following mbuf n. If n
702 * is null, the buffer is presumed empty.
706 register struct sockbuf *sb;
707 register struct mbuf *m, *n;
709 register int eor = 0;
710 register struct mbuf *o;
713 eor |= m->m_flags & M_EOR;
716 (((o = m->m_next) || (o = n)) &&
717 o->m_type == m->m_type))) {
721 if (n && (n->m_flags & M_EOR) == 0 &&
723 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
724 m->m_len <= M_TRAILINGSPACE(n) &&
725 n->m_type == m->m_type) {
726 bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
728 n->m_len += m->m_len;
729 sb->sb_cc += m->m_len;
739 m->m_flags &= ~M_EOR;
747 printf("semi-panic: sbcompress\n");
752 * Free all mbufs in a sockbuf.
753 * Check that all resources are reclaimed.
757 register struct sockbuf *sb;
760 if (sb->sb_flags & SB_LOCK)
761 panic("sbflush: locked");
762 while (sb->sb_mbcnt) {
764 * Don't call sbdrop(sb, 0) if the leading mbuf is non-empty:
765 * we would loop forever. Panic instead.
767 if (!sb->sb_cc && (sb->sb_mb == NULL || sb->sb_mb->m_len))
769 sbdrop(sb, (int)sb->sb_cc);
771 if (sb->sb_cc || sb->sb_mb || sb->sb_mbcnt)
772 panic("sbflush: cc %ld || mb %p || mbcnt %ld", sb->sb_cc, (void *)sb->sb_mb, sb->sb_mbcnt);
776 * Drop data from (the front of) a sockbuf.
780 register struct sockbuf *sb;
783 register struct mbuf *m, *mn;
786 next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
795 if (m->m_len > len) {
806 while (m && m->m_len == 0) {
819 * Drop a record off the front of a sockbuf
820 * and move the next record to the front.
824 register struct sockbuf *sb;
826 register struct mbuf *m, *mn;
830 sb->sb_mb = m->m_nextpkt;
840 * Create a "control" mbuf containing the specified data
841 * with the specified type for presentation on a socket buffer.
844 sbcreatecontrol(p, size, type, level)
849 register struct cmsghdr *cp;
852 if (CMSG_SPACE((u_int)size) > MLEN)
853 return ((struct mbuf *) NULL);
854 if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
855 return ((struct mbuf *) NULL);
856 cp = mtod(m, struct cmsghdr *);
857 /* XXX check size? */
858 (void)memcpy(CMSG_DATA(cp), p, size);
859 m->m_len = CMSG_SPACE(size);
860 cp->cmsg_len = CMSG_LEN(size);
861 cp->cmsg_level = level;
862 cp->cmsg_type = type;
867 * Some routines that return EOPNOTSUPP for entry points that are not
868 * supported by a protocol. Fill in as needed.
871 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
877 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct proc *p)
883 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
889 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
890 struct ifnet *ifp, struct proc *p)
896 pru_listen_notsupp(struct socket *so, struct proc *p)
902 pru_rcvd_notsupp(struct socket *so, int flags)
908 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
914 * This isn't really a ``null'' operation, but it's the default one
915 * and doesn't do anything destructive.
918 pru_sense_null(struct socket *so, struct stat *sb)
924 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
927 dup_sockaddr(sa, canwait)
931 struct sockaddr *sa2;
933 MALLOC(sa2, struct sockaddr *, sa->sa_len, M_SONAME,
934 canwait ? M_WAITOK : M_NOWAIT);
936 bcopy(sa, sa2, sa->sa_len);
941 * Create an external-format (``xsocket'') structure using the information
942 * in the kernel-format socket structure pointed to by so. This is done
943 * to reduce the spew of irrelevant information over this interface,
944 * to isolate user code from changes in the kernel structure, and
945 * potentially to provide information-hiding if we decide that
946 * some of this information should be hidden from users.
949 sotoxsocket(struct socket *so, struct xsocket *xso)
951 xso->xso_len = sizeof *xso;
953 xso->so_type = so->so_type;
954 xso->so_options = so->so_options;
955 xso->so_linger = so->so_linger;
956 xso->so_state = so->so_state;
957 xso->so_pcb = so->so_pcb;
958 xso->xso_protocol = so->so_proto->pr_protocol;
959 xso->xso_family = so->so_proto->pr_domain->dom_family;
960 xso->so_qlen = so->so_qlen;
961 xso->so_incqlen = so->so_incqlen;
962 xso->so_qlimit = so->so_qlimit;
963 xso->so_timeo = so->so_timeo;
964 xso->so_error = so->so_error;
965 xso->so_oobmark = so->so_oobmark;
966 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
967 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
971 * This does the same for sockbufs. Note that the xsockbuf structure,
972 * since it is always embedded in a socket, does not include a self
973 * pointer nor a length. We make this entry point public in case
974 * some other mechanism needs it.
977 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
979 xsb->sb_cc = sb->sb_cc;
980 xsb->sb_hiwat = sb->sb_hiwat;
981 xsb->sb_mbcnt = sb->sb_mbcnt;
982 xsb->sb_mbmax = sb->sb_mbmax;
983 xsb->sb_lowat = sb->sb_lowat;
984 xsb->sb_flags = sb->sb_flags;
985 xsb->sb_timeo = sb->sb_timeo;