uipc_socket2.c revision 1.83 1 /* $NetBSD: uipc_socket2.c,v 1.83 2007/07/04 07:13:13 tls Exp $ */
2
3 /*
4 * Copyright (c) 1982, 1986, 1988, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 * @(#)uipc_socket2.c 8.2 (Berkeley) 2/14/95
32 */
33
34 #include <sys/cdefs.h>
35 __KERNEL_RCSID(0, "$NetBSD: uipc_socket2.c,v 1.83 2007/07/04 07:13:13 tls Exp $");
36
37 #include "opt_mbuftrace.h"
38 #include "opt_sb_max.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/proc.h>
43 #include <sys/file.h>
44 #include <sys/buf.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/protosw.h>
48 #include <sys/poll.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/signalvar.h>
52 #include <sys/kauth.h>
53
54 /*
55 * Primitive routines for operating on sockets and socket buffers
56 */
57
58 /* strings for sleep message: */
59 const char netcon[] = "netcon";
60 const char netcls[] = "netcls";
61 const char netio[] = "netio";
62 const char netlck[] = "netlck";
63
64 u_long sb_max = SB_MAX; /* maximum socket buffer size */
65 static u_long sb_max_adj; /* adjusted sb_max */
66
67 /*
68 * Procedures to manipulate state flags of socket
69 * and do appropriate wakeups. Normal sequence from the
70 * active (originating) side is that soisconnecting() is
71 * called during processing of connect() call,
72 * resulting in an eventual call to soisconnected() if/when the
73 * connection is established. When the connection is torn down
74 * soisdisconnecting() is called during processing of disconnect() call,
75 * and soisdisconnected() is called when the connection to the peer
76 * is totally severed. The semantics of these routines are such that
77 * connectionless protocols can call soisconnected() and soisdisconnected()
78 * only, bypassing the in-progress calls when setting up a ``connection''
79 * takes no time.
80 *
81 * From the passive side, a socket is created with
82 * two queues of sockets: so_q0 for connections in progress
83 * and so_q for connections already made and awaiting user acceptance.
84 * As a protocol is preparing incoming connections, it creates a socket
85 * structure queued on so_q0 by calling sonewconn(). When the connection
86 * is established, soisconnected() is called, and transfers the
87 * socket structure to so_q, making it available to accept().
88 *
89 * If a socket is closed with sockets on either
90 * so_q0 or so_q, these sockets are dropped.
91 *
92 * If higher level protocols are implemented in
93 * the kernel, the wakeups done here will sometimes
94 * cause software-interrupt process scheduling.
95 */
96
97 void
98 soisconnecting(struct socket *so)
99 {
100
101 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
102 so->so_state |= SS_ISCONNECTING;
103 }
104
105 void
106 soisconnected(struct socket *so)
107 {
108 struct socket *head;
109
110 head = so->so_head;
111 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
112 so->so_state |= SS_ISCONNECTED;
113 if (head && soqremque(so, 0)) {
114 soqinsque(head, so, 1);
115 sorwakeup(head);
116 wakeup((void *)&head->so_timeo);
117 } else {
118 wakeup((void *)&so->so_timeo);
119 sorwakeup(so);
120 sowwakeup(so);
121 }
122 }
123
124 void
125 soisdisconnecting(struct socket *so)
126 {
127
128 so->so_state &= ~SS_ISCONNECTING;
129 so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
130 wakeup((void *)&so->so_timeo);
131 sowwakeup(so);
132 sorwakeup(so);
133 }
134
135 void
136 soisdisconnected(struct socket *so)
137 {
138
139 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
140 so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
141 wakeup((void *)&so->so_timeo);
142 sowwakeup(so);
143 sorwakeup(so);
144 }
145
146 /*
147 * When an attempt at a new connection is noted on a socket
148 * which accepts connections, sonewconn is called. If the
149 * connection is possible (subject to space constraints, etc.)
150 * then we allocate a new structure, propoerly linked into the
151 * data structure of the original socket, and return this.
152 * Connstatus may be 0, SS_ISCONFIRMING, or SS_ISCONNECTED.
153 */
154 struct socket *
155 sonewconn(struct socket *head, int connstatus)
156 {
157 struct socket *so;
158 int soqueue;
159
160 soqueue = connstatus ? 1 : 0;
161 if (head->so_qlen + head->so_q0len > 3 * head->so_qlimit / 2)
162 return ((struct socket *)0);
163 so = pool_get(&socket_pool, PR_NOWAIT);
164 if (so == NULL)
165 return (NULL);
166 memset((void *)so, 0, sizeof(*so));
167 so->so_type = head->so_type;
168 so->so_options = head->so_options &~ SO_ACCEPTCONN;
169 so->so_linger = head->so_linger;
170 so->so_state = head->so_state | SS_NOFDREF;
171 so->so_proto = head->so_proto;
172 so->so_timeo = head->so_timeo;
173 so->so_pgid = head->so_pgid;
174 so->so_send = head->so_send;
175 so->so_receive = head->so_receive;
176 so->so_uidinfo = head->so_uidinfo;
177 #ifdef MBUFTRACE
178 so->so_mowner = head->so_mowner;
179 so->so_rcv.sb_mowner = head->so_rcv.sb_mowner;
180 so->so_snd.sb_mowner = head->so_snd.sb_mowner;
181 #endif
182 (void) soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat);
183 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
184 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
185 soqinsque(head, so, soqueue);
186 if ((*so->so_proto->pr_usrreq)(so, PRU_ATTACH,
187 (struct mbuf *)0, (struct mbuf *)0, (struct mbuf *)0,
188 (struct lwp *)0)) {
189 (void) soqremque(so, soqueue);
190 pool_put(&socket_pool, so);
191 return (NULL);
192 }
193 if (connstatus) {
194 sorwakeup(head);
195 wakeup((void *)&head->so_timeo);
196 so->so_state |= connstatus;
197 }
198 return (so);
199 }
200
201 void
202 soqinsque(struct socket *head, struct socket *so, int q)
203 {
204
205 #ifdef DIAGNOSTIC
206 if (so->so_onq != NULL)
207 panic("soqinsque");
208 #endif
209
210 so->so_head = head;
211 if (q == 0) {
212 head->so_q0len++;
213 so->so_onq = &head->so_q0;
214 } else {
215 head->so_qlen++;
216 so->so_onq = &head->so_q;
217 }
218 TAILQ_INSERT_TAIL(so->so_onq, so, so_qe);
219 }
220
221 int
222 soqremque(struct socket *so, int q)
223 {
224 struct socket *head;
225
226 head = so->so_head;
227 if (q == 0) {
228 if (so->so_onq != &head->so_q0)
229 return (0);
230 head->so_q0len--;
231 } else {
232 if (so->so_onq != &head->so_q)
233 return (0);
234 head->so_qlen--;
235 }
236 TAILQ_REMOVE(so->so_onq, so, so_qe);
237 so->so_onq = NULL;
238 so->so_head = NULL;
239 return (1);
240 }
241
242 /*
243 * Socantsendmore indicates that no more data will be sent on the
244 * socket; it would normally be applied to a socket when the user
245 * informs the system that no more data is to be sent, by the protocol
246 * code (in case PRU_SHUTDOWN). Socantrcvmore indicates that no more data
247 * will be received, and will normally be applied to the socket by a
248 * protocol when it detects that the peer will send no more data.
249 * Data queued for reading in the socket may yet be read.
250 */
251
252 void
253 socantsendmore(struct socket *so)
254 {
255
256 so->so_state |= SS_CANTSENDMORE;
257 sowwakeup(so);
258 }
259
260 void
261 socantrcvmore(struct socket *so)
262 {
263
264 so->so_state |= SS_CANTRCVMORE;
265 sorwakeup(so);
266 }
267
268 /*
269 * Wait for data to arrive at/drain from a socket buffer.
270 */
271 int
272 sbwait(struct sockbuf *sb)
273 {
274
275 sb->sb_flags |= SB_WAIT;
276 return (tsleep((void *)&sb->sb_cc,
277 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, netio,
278 sb->sb_timeo));
279 }
280
281 /*
282 * Lock a sockbuf already known to be locked;
283 * return any error returned from sleep (EINTR).
284 */
285 int
286 sb_lock(struct sockbuf *sb)
287 {
288 int error;
289
290 while (sb->sb_flags & SB_LOCK) {
291 sb->sb_flags |= SB_WANT;
292 error = tsleep((void *)&sb->sb_flags,
293 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK|PCATCH,
294 netlck, 0);
295 if (error)
296 return (error);
297 }
298 sb->sb_flags |= SB_LOCK;
299 return (0);
300 }
301
302 /*
303 * Wakeup processes waiting on a socket buffer.
304 * Do asynchronous notification via SIGIO
305 * if the socket buffer has the SB_ASYNC flag set.
306 */
307 void
308 sowakeup(struct socket *so, struct sockbuf *sb, int code)
309 {
310 selnotify(&sb->sb_sel, 0);
311 sb->sb_flags &= ~SB_SEL;
312 if (sb->sb_flags & SB_WAIT) {
313 sb->sb_flags &= ~SB_WAIT;
314 wakeup((void *)&sb->sb_cc);
315 }
316 if (sb->sb_flags & SB_ASYNC) {
317 int band;
318 if (code == POLL_IN)
319 band = POLLIN|POLLRDNORM;
320 else
321 band = POLLOUT|POLLWRNORM;
322 fownsignal(so->so_pgid, SIGIO, code, band, so);
323 }
324 if (sb->sb_flags & SB_UPCALL)
325 (*so->so_upcall)(so, so->so_upcallarg, M_DONTWAIT);
326 }
327
328 /*
329 * Socket buffer (struct sockbuf) utility routines.
330 *
331 * Each socket contains two socket buffers: one for sending data and
332 * one for receiving data. Each buffer contains a queue of mbufs,
333 * information about the number of mbufs and amount of data in the
334 * queue, and other fields allowing poll() statements and notification
335 * on data availability to be implemented.
336 *
337 * Data stored in a socket buffer is maintained as a list of records.
338 * Each record is a list of mbufs chained together with the m_next
339 * field. Records are chained together with the m_nextpkt field. The upper
340 * level routine soreceive() expects the following conventions to be
341 * observed when placing information in the receive buffer:
342 *
343 * 1. If the protocol requires each message be preceded by the sender's
344 * name, then a record containing that name must be present before
345 * any associated data (mbuf's must be of type MT_SONAME).
346 * 2. If the protocol supports the exchange of ``access rights'' (really
347 * just additional data associated with the message), and there are
348 * ``rights'' to be received, then a record containing this data
349 * should be present (mbuf's must be of type MT_CONTROL).
350 * 3. If a name or rights record exists, then it must be followed by
351 * a data record, perhaps of zero length.
352 *
353 * Before using a new socket structure it is first necessary to reserve
354 * buffer space to the socket, by calling sbreserve(). This should commit
355 * some of the available buffer space in the system buffer pool for the
356 * socket (currently, it does nothing but enforce limits). The space
357 * should be released by calling sbrelease() when the socket is destroyed.
358 */
359
360 int
361 sb_max_set(u_long new_sbmax)
362 {
363 int s;
364
365 if (new_sbmax < (16 * 1024))
366 return (EINVAL);
367
368 s = splsoftnet();
369 sb_max = new_sbmax;
370 sb_max_adj = (u_quad_t)new_sbmax * MCLBYTES / (MSIZE + MCLBYTES);
371 splx(s);
372
373 return (0);
374 }
375
376 int
377 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
378 {
379 /*
380 * there's at least one application (a configure script of screen)
381 * which expects a fifo is writable even if it has "some" bytes
382 * in its buffer.
383 * so we want to make sure (hiwat - lowat) >= (some bytes).
384 *
385 * PIPE_BUF here is an arbitrary value chosen as (some bytes) above.
386 * we expect it's large enough for such applications.
387 */
388 u_long lowat = MAX(sock_loan_thresh, MCLBYTES);
389 u_long hiwat = lowat + PIPE_BUF;
390
391 if (sndcc < hiwat)
392 sndcc = hiwat;
393 if (sbreserve(&so->so_snd, sndcc, so) == 0)
394 goto bad;
395 if (sbreserve(&so->so_rcv, rcvcc, so) == 0)
396 goto bad2;
397 if (so->so_rcv.sb_lowat == 0)
398 so->so_rcv.sb_lowat = 1;
399 if (so->so_snd.sb_lowat == 0)
400 so->so_snd.sb_lowat = lowat;
401 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
402 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
403 return (0);
404 bad2:
405 sbrelease(&so->so_snd, so);
406 bad:
407 return (ENOBUFS);
408 }
409
410 /*
411 * Allot mbufs to a sockbuf.
412 * Attempt to scale mbmax so that mbcnt doesn't become limiting
413 * if buffering efficiency is near the normal case.
414 */
415 int
416 sbreserve(struct sockbuf *sb, u_long cc, struct socket *so)
417 {
418 struct lwp *l = curlwp; /* XXX */
419 rlim_t maxcc;
420 struct uidinfo *uidinfo;
421
422 KDASSERT(sb_max_adj != 0);
423 if (cc == 0 || cc > sb_max_adj)
424 return (0);
425 if (so) {
426 if (l && kauth_cred_geteuid(l->l_cred) == so->so_uidinfo->ui_uid)
427 maxcc = l->l_proc->p_rlimit[RLIMIT_SBSIZE].rlim_cur;
428 else
429 maxcc = RLIM_INFINITY;
430 uidinfo = so->so_uidinfo;
431 } else {
432 uidinfo = uid_find(0); /* XXX: nothing better */
433 maxcc = RLIM_INFINITY;
434 }
435 if (!chgsbsize(uidinfo, &sb->sb_hiwat, cc, maxcc))
436 return 0;
437 sb->sb_mbmax = min(cc * 2, sb_max);
438 if (sb->sb_lowat > sb->sb_hiwat)
439 sb->sb_lowat = sb->sb_hiwat;
440 return (1);
441 }
442
443 /*
444 * Free mbufs held by a socket, and reserved mbuf space.
445 */
446 void
447 sbrelease(struct sockbuf *sb, struct socket *so)
448 {
449
450 sbflush(sb);
451 (void)chgsbsize(so->so_uidinfo, &sb->sb_hiwat, 0,
452 RLIM_INFINITY);
453 sb->sb_mbmax = 0;
454 }
455
456 /*
457 * Routines to add and remove
458 * data from an mbuf queue.
459 *
460 * The routines sbappend() or sbappendrecord() are normally called to
461 * append new mbufs to a socket buffer, after checking that adequate
462 * space is available, comparing the function sbspace() with the amount
463 * of data to be added. sbappendrecord() differs from sbappend() in
464 * that data supplied is treated as the beginning of a new record.
465 * To place a sender's address, optional access rights, and data in a
466 * socket receive buffer, sbappendaddr() should be used. To place
467 * access rights and data in a socket receive buffer, sbappendrights()
468 * should be used. In either case, the new data begins a new record.
469 * Note that unlike sbappend() and sbappendrecord(), these routines check
470 * for the caller that there will be enough space to store the data.
471 * Each fails if there is not enough space, or if it cannot find mbufs
472 * to store additional information in.
473 *
474 * Reliable protocols may use the socket send buffer to hold data
475 * awaiting acknowledgement. Data is normally copied from a socket
476 * send buffer in a protocol with m_copy for output to a peer,
477 * and then removing the data from the socket buffer with sbdrop()
478 * or sbdroprecord() when the data is acknowledged by the peer.
479 */
480
481 #ifdef SOCKBUF_DEBUG
482 void
483 sblastrecordchk(struct sockbuf *sb, const char *where)
484 {
485 struct mbuf *m = sb->sb_mb;
486
487 while (m && m->m_nextpkt)
488 m = m->m_nextpkt;
489
490 if (m != sb->sb_lastrecord) {
491 printf("sblastrecordchk: sb_mb %p sb_lastrecord %p last %p\n",
492 sb->sb_mb, sb->sb_lastrecord, m);
493 printf("packet chain:\n");
494 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
495 printf("\t%p\n", m);
496 panic("sblastrecordchk from %s", where);
497 }
498 }
499
500 void
501 sblastmbufchk(struct sockbuf *sb, const char *where)
502 {
503 struct mbuf *m = sb->sb_mb;
504 struct mbuf *n;
505
506 while (m && m->m_nextpkt)
507 m = m->m_nextpkt;
508
509 while (m && m->m_next)
510 m = m->m_next;
511
512 if (m != sb->sb_mbtail) {
513 printf("sblastmbufchk: sb_mb %p sb_mbtail %p last %p\n",
514 sb->sb_mb, sb->sb_mbtail, m);
515 printf("packet tree:\n");
516 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
517 printf("\t");
518 for (n = m; n != NULL; n = n->m_next)
519 printf("%p ", n);
520 printf("\n");
521 }
522 panic("sblastmbufchk from %s", where);
523 }
524 }
525 #endif /* SOCKBUF_DEBUG */
526
527 /*
528 * Link a chain of records onto a socket buffer
529 */
530 #define SBLINKRECORDCHAIN(sb, m0, mlast) \
531 do { \
532 if ((sb)->sb_lastrecord != NULL) \
533 (sb)->sb_lastrecord->m_nextpkt = (m0); \
534 else \
535 (sb)->sb_mb = (m0); \
536 (sb)->sb_lastrecord = (mlast); \
537 } while (/*CONSTCOND*/0)
538
539
540 #define SBLINKRECORD(sb, m0) \
541 SBLINKRECORDCHAIN(sb, m0, m0)
542
543 /*
544 * Append mbuf chain m to the last record in the
545 * socket buffer sb. The additional space associated
546 * the mbuf chain is recorded in sb. Empty mbufs are
547 * discarded and mbufs are compacted where possible.
548 */
549 void
550 sbappend(struct sockbuf *sb, struct mbuf *m)
551 {
552 struct mbuf *n;
553
554 if (m == 0)
555 return;
556
557 #ifdef MBUFTRACE
558 m_claimm(m, sb->sb_mowner);
559 #endif
560
561 SBLASTRECORDCHK(sb, "sbappend 1");
562
563 if ((n = sb->sb_lastrecord) != NULL) {
564 /*
565 * XXX Would like to simply use sb_mbtail here, but
566 * XXX I need to verify that I won't miss an EOR that
567 * XXX way.
568 */
569 do {
570 if (n->m_flags & M_EOR) {
571 sbappendrecord(sb, m); /* XXXXXX!!!! */
572 return;
573 }
574 } while (n->m_next && (n = n->m_next));
575 } else {
576 /*
577 * If this is the first record in the socket buffer, it's
578 * also the last record.
579 */
580 sb->sb_lastrecord = m;
581 }
582 sbcompress(sb, m, n);
583 SBLASTRECORDCHK(sb, "sbappend 2");
584 }
585
586 /*
587 * This version of sbappend() should only be used when the caller
588 * absolutely knows that there will never be more than one record
589 * in the socket buffer, that is, a stream protocol (such as TCP).
590 */
591 void
592 sbappendstream(struct sockbuf *sb, struct mbuf *m)
593 {
594
595 KDASSERT(m->m_nextpkt == NULL);
596 KASSERT(sb->sb_mb == sb->sb_lastrecord);
597
598 SBLASTMBUFCHK(sb, __func__);
599
600 #ifdef MBUFTRACE
601 m_claimm(m, sb->sb_mowner);
602 #endif
603
604 sbcompress(sb, m, sb->sb_mbtail);
605
606 sb->sb_lastrecord = sb->sb_mb;
607 SBLASTRECORDCHK(sb, __func__);
608 }
609
610 #ifdef SOCKBUF_DEBUG
611 void
612 sbcheck(struct sockbuf *sb)
613 {
614 struct mbuf *m;
615 u_long len, mbcnt;
616
617 len = 0;
618 mbcnt = 0;
619 for (m = sb->sb_mb; m; m = m->m_next) {
620 len += m->m_len;
621 mbcnt += MSIZE;
622 if (m->m_flags & M_EXT)
623 mbcnt += m->m_ext.ext_size;
624 if (m->m_nextpkt)
625 panic("sbcheck nextpkt");
626 }
627 if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
628 printf("cc %lu != %lu || mbcnt %lu != %lu\n", len, sb->sb_cc,
629 mbcnt, sb->sb_mbcnt);
630 panic("sbcheck");
631 }
632 }
633 #endif
634
635 /*
636 * As above, except the mbuf chain
637 * begins a new record.
638 */
639 void
640 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
641 {
642 struct mbuf *m;
643
644 if (m0 == 0)
645 return;
646
647 #ifdef MBUFTRACE
648 m_claimm(m0, sb->sb_mowner);
649 #endif
650 /*
651 * Put the first mbuf on the queue.
652 * Note this permits zero length records.
653 */
654 sballoc(sb, m0);
655 SBLASTRECORDCHK(sb, "sbappendrecord 1");
656 SBLINKRECORD(sb, m0);
657 m = m0->m_next;
658 m0->m_next = 0;
659 if (m && (m0->m_flags & M_EOR)) {
660 m0->m_flags &= ~M_EOR;
661 m->m_flags |= M_EOR;
662 }
663 sbcompress(sb, m, m0);
664 SBLASTRECORDCHK(sb, "sbappendrecord 2");
665 }
666
667 /*
668 * As above except that OOB data
669 * is inserted at the beginning of the sockbuf,
670 * but after any other OOB data.
671 */
672 void
673 sbinsertoob(struct sockbuf *sb, struct mbuf *m0)
674 {
675 struct mbuf *m, **mp;
676
677 if (m0 == 0)
678 return;
679
680 SBLASTRECORDCHK(sb, "sbinsertoob 1");
681
682 for (mp = &sb->sb_mb; (m = *mp) != NULL; mp = &((*mp)->m_nextpkt)) {
683 again:
684 switch (m->m_type) {
685
686 case MT_OOBDATA:
687 continue; /* WANT next train */
688
689 case MT_CONTROL:
690 if ((m = m->m_next) != NULL)
691 goto again; /* inspect THIS train further */
692 }
693 break;
694 }
695 /*
696 * Put the first mbuf on the queue.
697 * Note this permits zero length records.
698 */
699 sballoc(sb, m0);
700 m0->m_nextpkt = *mp;
701 if (*mp == NULL) {
702 /* m0 is actually the new tail */
703 sb->sb_lastrecord = m0;
704 }
705 *mp = m0;
706 m = m0->m_next;
707 m0->m_next = 0;
708 if (m && (m0->m_flags & M_EOR)) {
709 m0->m_flags &= ~M_EOR;
710 m->m_flags |= M_EOR;
711 }
712 sbcompress(sb, m, m0);
713 SBLASTRECORDCHK(sb, "sbinsertoob 2");
714 }
715
716 /*
717 * Append address and data, and optionally, control (ancillary) data
718 * to the receive queue of a socket. If present,
719 * m0 must include a packet header with total length.
720 * Returns 0 if no space in sockbuf or insufficient mbufs.
721 */
722 int
723 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa, struct mbuf *m0,
724 struct mbuf *control)
725 {
726 struct mbuf *m, *n, *nlast;
727 int space, len;
728
729 space = asa->sa_len;
730
731 if (m0 != NULL) {
732 if ((m0->m_flags & M_PKTHDR) == 0)
733 panic("sbappendaddr");
734 space += m0->m_pkthdr.len;
735 #ifdef MBUFTRACE
736 m_claimm(m0, sb->sb_mowner);
737 #endif
738 }
739 for (n = control; n; n = n->m_next) {
740 space += n->m_len;
741 MCLAIM(n, sb->sb_mowner);
742 if (n->m_next == 0) /* keep pointer to last control buf */
743 break;
744 }
745 if (space > sbspace(sb))
746 return (0);
747 MGET(m, M_DONTWAIT, MT_SONAME);
748 if (m == 0)
749 return (0);
750 MCLAIM(m, sb->sb_mowner);
751 /*
752 * XXX avoid 'comparison always true' warning which isn't easily
753 * avoided.
754 */
755 len = asa->sa_len;
756 if (len > MLEN) {
757 MEXTMALLOC(m, asa->sa_len, M_NOWAIT);
758 if ((m->m_flags & M_EXT) == 0) {
759 m_free(m);
760 return (0);
761 }
762 }
763 m->m_len = asa->sa_len;
764 memcpy(mtod(m, void *), asa, asa->sa_len);
765 if (n)
766 n->m_next = m0; /* concatenate data to control */
767 else
768 control = m0;
769 m->m_next = control;
770
771 SBLASTRECORDCHK(sb, "sbappendaddr 1");
772
773 for (n = m; n->m_next != NULL; n = n->m_next)
774 sballoc(sb, n);
775 sballoc(sb, n);
776 nlast = n;
777 SBLINKRECORD(sb, m);
778
779 sb->sb_mbtail = nlast;
780 SBLASTMBUFCHK(sb, "sbappendaddr");
781
782 SBLASTRECORDCHK(sb, "sbappendaddr 2");
783
784 return (1);
785 }
786
787 /*
788 * Helper for sbappendchainaddr: prepend a struct sockaddr* to
789 * an mbuf chain.
790 */
791 static inline struct mbuf *
792 m_prepend_sockaddr(struct sockbuf *sb, struct mbuf *m0,
793 const struct sockaddr *asa)
794 {
795 struct mbuf *m;
796 const int salen = asa->sa_len;
797
798 /* only the first in each chain need be a pkthdr */
799 MGETHDR(m, M_DONTWAIT, MT_SONAME);
800 if (m == 0)
801 return (0);
802 MCLAIM(m, sb->sb_mowner);
803 #ifdef notyet
804 if (salen > MHLEN) {
805 MEXTMALLOC(m, salen, M_NOWAIT);
806 if ((m->m_flags & M_EXT) == 0) {
807 m_free(m);
808 return (0);
809 }
810 }
811 #else
812 KASSERT(salen <= MHLEN);
813 #endif
814 m->m_len = salen;
815 memcpy(mtod(m, void *), asa, salen);
816 m->m_next = m0;
817 m->m_pkthdr.len = salen + m0->m_pkthdr.len;
818
819 return m;
820 }
821
822 int
823 sbappendaddrchain(struct sockbuf *sb, const struct sockaddr *asa,
824 struct mbuf *m0, int sbprio)
825 {
826 int space;
827 struct mbuf *m, *n, *n0, *nlast;
828 int error;
829
830 /*
831 * XXX sbprio reserved for encoding priority of this* request:
832 * SB_PRIO_NONE --> honour normal sb limits
833 * SB_PRIO_ONESHOT_OVERFLOW --> if socket has any space,
834 * take whole chain. Intended for large requests
835 * that should be delivered atomically (all, or none).
836 * SB_PRIO_OVERDRAFT -- allow a small (2*MLEN) overflow
837 * over normal socket limits, for messages indicating
838 * buffer overflow in earlier normal/lower-priority messages
839 * SB_PRIO_BESTEFFORT --> ignore limits entirely.
840 * Intended for kernel-generated messages only.
841 * Up to generator to avoid total mbuf resource exhaustion.
842 */
843 (void)sbprio;
844
845 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
846 panic("sbappendaddrchain");
847
848 space = sbspace(sb);
849
850 #ifdef notyet
851 /*
852 * Enforce SB_PRIO_* limits as described above.
853 */
854 #endif
855
856 n0 = NULL;
857 nlast = NULL;
858 for (m = m0; m; m = m->m_nextpkt) {
859 struct mbuf *np;
860
861 #ifdef MBUFTRACE
862 m_claimm(m, sb->sb_mowner);
863 #endif
864
865 /* Prepend sockaddr to this record (m) of input chain m0 */
866 n = m_prepend_sockaddr(sb, m, asa);
867 if (n == NULL) {
868 error = ENOBUFS;
869 goto bad;
870 }
871
872 /* Append record (asa+m) to end of new chain n0 */
873 if (n0 == NULL) {
874 n0 = n;
875 } else {
876 nlast->m_nextpkt = n;
877 }
878 /* Keep track of last record on new chain */
879 nlast = n;
880
881 for (np = n; np; np = np->m_next)
882 sballoc(sb, np);
883 }
884
885 SBLASTRECORDCHK(sb, "sbappendaddrchain 1");
886
887 /* Drop the entire chain of (asa+m) records onto the socket */
888 SBLINKRECORDCHAIN(sb, n0, nlast);
889
890 SBLASTRECORDCHK(sb, "sbappendaddrchain 2");
891
892 for (m = nlast; m->m_next; m = m->m_next)
893 ;
894 sb->sb_mbtail = m;
895 SBLASTMBUFCHK(sb, "sbappendaddrchain");
896
897 return (1);
898
899 bad:
900 /*
901 * On error, free the prepended addreseses. For consistency
902 * with sbappendaddr(), leave it to our caller to free
903 * the input record chain passed to us as m0.
904 */
905 while ((n = n0) != NULL) {
906 struct mbuf *np;
907
908 /* Undo the sballoc() of this record */
909 for (np = n; np; np = np->m_next)
910 sbfree(sb, np);
911
912 n0 = n->m_nextpkt; /* iterate at next prepended address */
913 MFREE(n, np); /* free prepended address (not data) */
914 }
915 return 0;
916 }
917
918
919 int
920 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control)
921 {
922 struct mbuf *m, *mlast, *n;
923 int space;
924
925 space = 0;
926 if (control == 0)
927 panic("sbappendcontrol");
928 for (m = control; ; m = m->m_next) {
929 space += m->m_len;
930 MCLAIM(m, sb->sb_mowner);
931 if (m->m_next == 0)
932 break;
933 }
934 n = m; /* save pointer to last control buffer */
935 for (m = m0; m; m = m->m_next) {
936 MCLAIM(m, sb->sb_mowner);
937 space += m->m_len;
938 }
939 if (space > sbspace(sb))
940 return (0);
941 n->m_next = m0; /* concatenate data to control */
942
943 SBLASTRECORDCHK(sb, "sbappendcontrol 1");
944
945 for (m = control; m->m_next != NULL; m = m->m_next)
946 sballoc(sb, m);
947 sballoc(sb, m);
948 mlast = m;
949 SBLINKRECORD(sb, control);
950
951 sb->sb_mbtail = mlast;
952 SBLASTMBUFCHK(sb, "sbappendcontrol");
953
954 SBLASTRECORDCHK(sb, "sbappendcontrol 2");
955
956 return (1);
957 }
958
959 /*
960 * Compress mbuf chain m into the socket
961 * buffer sb following mbuf n. If n
962 * is null, the buffer is presumed empty.
963 */
964 void
965 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
966 {
967 int eor;
968 struct mbuf *o;
969
970 eor = 0;
971 while (m) {
972 eor |= m->m_flags & M_EOR;
973 if (m->m_len == 0 &&
974 (eor == 0 ||
975 (((o = m->m_next) || (o = n)) &&
976 o->m_type == m->m_type))) {
977 if (sb->sb_lastrecord == m)
978 sb->sb_lastrecord = m->m_next;
979 m = m_free(m);
980 continue;
981 }
982 if (n && (n->m_flags & M_EOR) == 0 &&
983 /* M_TRAILINGSPACE() checks buffer writeability */
984 m->m_len <= MCLBYTES / 4 && /* XXX Don't copy too much */
985 m->m_len <= M_TRAILINGSPACE(n) &&
986 n->m_type == m->m_type) {
987 memcpy(mtod(n, char *) + n->m_len, mtod(m, void *),
988 (unsigned)m->m_len);
989 n->m_len += m->m_len;
990 sb->sb_cc += m->m_len;
991 m = m_free(m);
992 continue;
993 }
994 if (n)
995 n->m_next = m;
996 else
997 sb->sb_mb = m;
998 sb->sb_mbtail = m;
999 sballoc(sb, m);
1000 n = m;
1001 m->m_flags &= ~M_EOR;
1002 m = m->m_next;
1003 n->m_next = 0;
1004 }
1005 if (eor) {
1006 if (n)
1007 n->m_flags |= eor;
1008 else
1009 printf("semi-panic: sbcompress\n");
1010 }
1011 SBLASTMBUFCHK(sb, __func__);
1012 }
1013
1014 /*
1015 * Free all mbufs in a sockbuf.
1016 * Check that all resources are reclaimed.
1017 */
1018 void
1019 sbflush(struct sockbuf *sb)
1020 {
1021
1022 KASSERT((sb->sb_flags & SB_LOCK) == 0);
1023
1024 while (sb->sb_mbcnt)
1025 sbdrop(sb, (int)sb->sb_cc);
1026
1027 KASSERT(sb->sb_cc == 0);
1028 KASSERT(sb->sb_mb == NULL);
1029 KASSERT(sb->sb_mbtail == NULL);
1030 KASSERT(sb->sb_lastrecord == NULL);
1031 }
1032
1033 /*
1034 * Drop data from (the front of) a sockbuf.
1035 */
1036 void
1037 sbdrop(struct sockbuf *sb, int len)
1038 {
1039 struct mbuf *m, *mn, *next;
1040
1041 next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1042 while (len > 0) {
1043 if (m == 0) {
1044 if (next == 0)
1045 panic("sbdrop");
1046 m = next;
1047 next = m->m_nextpkt;
1048 continue;
1049 }
1050 if (m->m_len > len) {
1051 m->m_len -= len;
1052 m->m_data += len;
1053 sb->sb_cc -= len;
1054 break;
1055 }
1056 len -= m->m_len;
1057 sbfree(sb, m);
1058 MFREE(m, mn);
1059 m = mn;
1060 }
1061 while (m && m->m_len == 0) {
1062 sbfree(sb, m);
1063 MFREE(m, mn);
1064 m = mn;
1065 }
1066 if (m) {
1067 sb->sb_mb = m;
1068 m->m_nextpkt = next;
1069 } else
1070 sb->sb_mb = next;
1071 /*
1072 * First part is an inline SB_EMPTY_FIXUP(). Second part
1073 * makes sure sb_lastrecord is up-to-date if we dropped
1074 * part of the last record.
1075 */
1076 m = sb->sb_mb;
1077 if (m == NULL) {
1078 sb->sb_mbtail = NULL;
1079 sb->sb_lastrecord = NULL;
1080 } else if (m->m_nextpkt == NULL)
1081 sb->sb_lastrecord = m;
1082 }
1083
1084 /*
1085 * Drop a record off the front of a sockbuf
1086 * and move the next record to the front.
1087 */
1088 void
1089 sbdroprecord(struct sockbuf *sb)
1090 {
1091 struct mbuf *m, *mn;
1092
1093 m = sb->sb_mb;
1094 if (m) {
1095 sb->sb_mb = m->m_nextpkt;
1096 do {
1097 sbfree(sb, m);
1098 MFREE(m, mn);
1099 } while ((m = mn) != NULL);
1100 }
1101 SB_EMPTY_FIXUP(sb);
1102 }
1103
1104 /*
1105 * Create a "control" mbuf containing the specified data
1106 * with the specified type for presentation on a socket buffer.
1107 */
1108 struct mbuf *
1109 sbcreatecontrol(void *p, int size, int type, int level)
1110 {
1111 struct cmsghdr *cp;
1112 struct mbuf *m;
1113
1114 if (CMSG_SPACE(size) > MCLBYTES) {
1115 printf("sbcreatecontrol: message too large %d\n", size);
1116 return NULL;
1117 }
1118
1119 if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
1120 return ((struct mbuf *) NULL);
1121 if (CMSG_SPACE(size) > MLEN) {
1122 MCLGET(m, M_DONTWAIT);
1123 if ((m->m_flags & M_EXT) == 0) {
1124 m_free(m);
1125 return NULL;
1126 }
1127 }
1128 cp = mtod(m, struct cmsghdr *);
1129 memcpy(CMSG_DATA(cp), p, size);
1130 m->m_len = CMSG_SPACE(size);
1131 cp->cmsg_len = CMSG_LEN(size);
1132 cp->cmsg_level = level;
1133 cp->cmsg_type = type;
1134 return (m);
1135 }
1136