]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_sockbuf.c
Step 3: anonymize struct mbuf_ext_pgs and move all its fields into mbuf
[FreeBSD/FreeBSD.git] / sys / kern / uipc_sockbuf.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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.1 (Berkeley) 6/10/93
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_kern_tls.h"
38 #include "opt_param.h"
39
40 #include <sys/param.h>
41 #include <sys/aio.h> /* for aio_swake proto */
42 #include <sys/kernel.h>
43 #include <sys/ktls.h>
44 #include <sys/lock.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/mutex.h>
48 #include <sys/proc.h>
49 #include <sys/protosw.h>
50 #include <sys/resourcevar.h>
51 #include <sys/signalvar.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sx.h>
55 #include <sys/sysctl.h>
56
57 /*
58  * Function pointer set by the AIO routines so that the socket buffer code
59  * can call back into the AIO module if it is loaded.
60  */
61 void    (*aio_swake)(struct socket *, struct sockbuf *);
62
63 /*
64  * Primitive routines for operating on socket buffers
65  */
66
67 u_long  sb_max = SB_MAX;
68 u_long sb_max_adj =
69        (quad_t)SB_MAX * MCLBYTES / (MSIZE + MCLBYTES); /* adjusted sb_max */
70
71 static  u_long sb_efficiency = 8;       /* parameter for sbreserve() */
72
73 static struct mbuf      *sbcut_internal(struct sockbuf *sb, int len);
74 static void     sbflush_internal(struct sockbuf *sb);
75
76 /*
77  * Our own version of m_clrprotoflags(), that can preserve M_NOTREADY.
78  */
79 static void
80 sbm_clrprotoflags(struct mbuf *m, int flags)
81 {
82         int mask;
83
84         mask = ~M_PROTOFLAGS;
85         if (flags & PRUS_NOTREADY)
86                 mask |= M_NOTREADY;
87         while (m) {
88                 m->m_flags &= mask;
89                 m = m->m_next;
90         }
91 }
92
93 /*
94  * Compress M_NOTREADY mbufs after they have been readied by sbready().
95  *
96  * sbcompress() skips M_NOTREADY mbufs since the data is not available to
97  * be copied at the time of sbcompress().  This function combines small
98  * mbufs similar to sbcompress() once mbufs are ready.  'm0' is the first
99  * mbuf sbready() marked ready, and 'end' is the first mbuf still not
100  * ready.
101  */
102 static void
103 sbready_compress(struct sockbuf *sb, struct mbuf *m0, struct mbuf *end)
104 {
105         struct mbuf *m, *n;
106         int ext_size;
107
108         SOCKBUF_LOCK_ASSERT(sb);
109
110         if ((sb->sb_flags & SB_NOCOALESCE) != 0)
111                 return;
112
113         for (m = m0; m != end; m = m->m_next) {
114                 MPASS((m->m_flags & M_NOTREADY) == 0);
115                 /*
116                  * NB: In sbcompress(), 'n' is the last mbuf in the
117                  * socket buffer and 'm' is the new mbuf being copied
118                  * into the trailing space of 'n'.  Here, the roles
119                  * are reversed and 'n' is the next mbuf after 'm'
120                  * that is being copied into the trailing space of
121                  * 'm'.
122                  */
123                 n = m->m_next;
124 #ifdef KERN_TLS
125                 /* Try to coalesce adjacent ktls mbuf hdr/trailers. */
126                 if ((n != NULL) && (n != end) && (m->m_flags & M_EOR) == 0 &&
127                     (m->m_flags & M_NOMAP) &&
128                     (n->m_flags & M_NOMAP) &&
129                     !mbuf_has_tls_session(m) &&
130                     !mbuf_has_tls_session(n)) {
131                         int hdr_len, trail_len;
132
133                         hdr_len = n->m_epg_hdrlen;
134                         trail_len = m->m_epg_trllen;
135                         if (trail_len != 0 && hdr_len != 0 &&
136                             trail_len + hdr_len <= MBUF_PEXT_TRAIL_LEN) {
137                                 /* copy n's header to m's trailer */
138                                 memcpy(&m->m_epg_trail[trail_len],
139                                     n->m_epg_hdr, hdr_len);
140                                 m->m_epg_trllen += hdr_len;
141                                 m->m_len += hdr_len;
142                                 n->m_epg_hdrlen = 0;
143                                 n->m_len -= hdr_len;
144                         }
145                 }
146 #endif
147
148                 /* Compress small unmapped mbufs into plain mbufs. */
149                 if ((m->m_flags & M_NOMAP) && m->m_len <= MLEN &&
150                     !mbuf_has_tls_session(m)) {
151                         MPASS(m->m_flags & M_EXT);
152                         ext_size = m->m_ext.ext_size;
153                         if (mb_unmapped_compress(m) == 0) {
154                                 sb->sb_mbcnt -= ext_size;
155                                 sb->sb_ccnt -= 1;
156                         }
157                 }
158
159                 while ((n != NULL) && (n != end) && (m->m_flags & M_EOR) == 0 &&
160                     M_WRITABLE(m) &&
161                     (m->m_flags & M_NOMAP) == 0 &&
162                     !mbuf_has_tls_session(n) &&
163                     !mbuf_has_tls_session(m) &&
164                     n->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
165                     n->m_len <= M_TRAILINGSPACE(m) &&
166                     m->m_type == n->m_type) {
167                         KASSERT(sb->sb_lastrecord != n,
168                     ("%s: merging start of record (%p) into previous mbuf (%p)",
169                             __func__, n, m));
170                         m_copydata(n, 0, n->m_len, mtodo(m, m->m_len));
171                         m->m_len += n->m_len;
172                         m->m_next = n->m_next;
173                         m->m_flags |= n->m_flags & M_EOR;
174                         if (sb->sb_mbtail == n)
175                                 sb->sb_mbtail = m;
176
177                         sb->sb_mbcnt -= MSIZE;
178                         sb->sb_mcnt -= 1;
179                         if (n->m_flags & M_EXT) {
180                                 sb->sb_mbcnt -= n->m_ext.ext_size;
181                                 sb->sb_ccnt -= 1;
182                         }
183                         m_free(n);
184                         n = m->m_next;
185                 }
186         }
187         SBLASTRECORDCHK(sb);
188         SBLASTMBUFCHK(sb);
189 }
190
191 /*
192  * Mark ready "count" units of I/O starting with "m".  Most mbufs
193  * count as a single unit of I/O except for EXT_PGS-backed mbufs which
194  * can be backed by multiple pages.
195  */
196 int
197 sbready(struct sockbuf *sb, struct mbuf *m0, int count)
198 {
199         struct mbuf *m;
200         u_int blocker;
201
202         SOCKBUF_LOCK_ASSERT(sb);
203         KASSERT(sb->sb_fnrdy != NULL, ("%s: sb %p NULL fnrdy", __func__, sb));
204         KASSERT(count > 0, ("%s: invalid count %d", __func__, count));
205
206         m = m0;
207         blocker = (sb->sb_fnrdy == m) ? M_BLOCKED : 0;
208
209         while (count > 0) {
210                 KASSERT(m->m_flags & M_NOTREADY,
211                     ("%s: m %p !M_NOTREADY", __func__, m));
212                 if ((m->m_flags & M_EXT) != 0 &&
213                     m->m_ext.ext_type == EXT_PGS) {
214                         if (count < m->m_epg_nrdy) {
215                                 m->m_epg_nrdy -= count;
216                                 count = 0;
217                                 break;
218                         }
219                         count -= m->m_epg_nrdy;
220                         m->m_epg_nrdy = 0;
221                 } else
222                         count--;
223
224                 m->m_flags &= ~(M_NOTREADY | blocker);
225                 if (blocker)
226                         sb->sb_acc += m->m_len;
227                 m = m->m_next;
228         }
229
230         /*
231          * If the first mbuf is still not fully ready because only
232          * some of its backing pages were readied, no further progress
233          * can be made.
234          */
235         if (m0 == m) {
236                 MPASS(m->m_flags & M_NOTREADY);
237                 return (EINPROGRESS);
238         }
239
240         if (!blocker) {
241                 sbready_compress(sb, m0, m);
242                 return (EINPROGRESS);
243         }
244
245         /* This one was blocking all the queue. */
246         for (; m && (m->m_flags & M_NOTREADY) == 0; m = m->m_next) {
247                 KASSERT(m->m_flags & M_BLOCKED,
248                     ("%s: m %p !M_BLOCKED", __func__, m));
249                 m->m_flags &= ~M_BLOCKED;
250                 sb->sb_acc += m->m_len;
251         }
252
253         sb->sb_fnrdy = m;
254         sbready_compress(sb, m0, m);
255
256         return (0);
257 }
258
259 /*
260  * Adjust sockbuf state reflecting allocation of m.
261  */
262 void
263 sballoc(struct sockbuf *sb, struct mbuf *m)
264 {
265
266         SOCKBUF_LOCK_ASSERT(sb);
267
268         sb->sb_ccc += m->m_len;
269
270         if (sb->sb_fnrdy == NULL) {
271                 if (m->m_flags & M_NOTREADY)
272                         sb->sb_fnrdy = m;
273                 else
274                         sb->sb_acc += m->m_len;
275         } else
276                 m->m_flags |= M_BLOCKED;
277
278         if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
279                 sb->sb_ctl += m->m_len;
280
281         sb->sb_mbcnt += MSIZE;
282         sb->sb_mcnt += 1;
283
284         if (m->m_flags & M_EXT) {
285                 sb->sb_mbcnt += m->m_ext.ext_size;
286                 sb->sb_ccnt += 1;
287         }
288 }
289
290 /*
291  * Adjust sockbuf state reflecting freeing of m.
292  */
293 void
294 sbfree(struct sockbuf *sb, struct mbuf *m)
295 {
296
297 #if 0   /* XXX: not yet: soclose() call path comes here w/o lock. */
298         SOCKBUF_LOCK_ASSERT(sb);
299 #endif
300
301         sb->sb_ccc -= m->m_len;
302
303         if (!(m->m_flags & M_NOTAVAIL))
304                 sb->sb_acc -= m->m_len;
305
306         if (m == sb->sb_fnrdy) {
307                 struct mbuf *n;
308
309                 KASSERT(m->m_flags & M_NOTREADY,
310                     ("%s: m %p !M_NOTREADY", __func__, m));
311
312                 n = m->m_next;
313                 while (n != NULL && !(n->m_flags & M_NOTREADY)) {
314                         n->m_flags &= ~M_BLOCKED;
315                         sb->sb_acc += n->m_len;
316                         n = n->m_next;
317                 }
318                 sb->sb_fnrdy = n;
319         }
320
321         if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
322                 sb->sb_ctl -= m->m_len;
323
324         sb->sb_mbcnt -= MSIZE;
325         sb->sb_mcnt -= 1;
326         if (m->m_flags & M_EXT) {
327                 sb->sb_mbcnt -= m->m_ext.ext_size;
328                 sb->sb_ccnt -= 1;
329         }
330
331         if (sb->sb_sndptr == m) {
332                 sb->sb_sndptr = NULL;
333                 sb->sb_sndptroff = 0;
334         }
335         if (sb->sb_sndptroff != 0)
336                 sb->sb_sndptroff -= m->m_len;
337 }
338
339 /*
340  * Socantsendmore indicates that no more data will be sent on the socket; it
341  * would normally be applied to a socket when the user informs the system
342  * that no more data is to be sent, by the protocol code (in case
343  * PRU_SHUTDOWN).  Socantrcvmore indicates that no more data will be
344  * received, and will normally be applied to the socket by a protocol when it
345  * detects that the peer will send no more data.  Data queued for reading in
346  * the socket may yet be read.
347  */
348 void
349 socantsendmore_locked(struct socket *so)
350 {
351
352         SOCKBUF_LOCK_ASSERT(&so->so_snd);
353
354         so->so_snd.sb_state |= SBS_CANTSENDMORE;
355         sowwakeup_locked(so);
356         mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
357 }
358
359 void
360 socantsendmore(struct socket *so)
361 {
362
363         SOCKBUF_LOCK(&so->so_snd);
364         socantsendmore_locked(so);
365         mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
366 }
367
368 void
369 socantrcvmore_locked(struct socket *so)
370 {
371
372         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
373
374         so->so_rcv.sb_state |= SBS_CANTRCVMORE;
375         sorwakeup_locked(so);
376         mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
377 }
378
379 void
380 socantrcvmore(struct socket *so)
381 {
382
383         SOCKBUF_LOCK(&so->so_rcv);
384         socantrcvmore_locked(so);
385         mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
386 }
387
388 /*
389  * Wait for data to arrive at/drain from a socket buffer.
390  */
391 int
392 sbwait(struct sockbuf *sb)
393 {
394
395         SOCKBUF_LOCK_ASSERT(sb);
396
397         sb->sb_flags |= SB_WAIT;
398         return (msleep_sbt(&sb->sb_acc, &sb->sb_mtx,
399             (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
400             sb->sb_timeo, 0, 0));
401 }
402
403 int
404 sblock(struct sockbuf *sb, int flags)
405 {
406
407         KASSERT((flags & SBL_VALID) == flags,
408             ("sblock: flags invalid (0x%x)", flags));
409
410         if (flags & SBL_WAIT) {
411                 if ((sb->sb_flags & SB_NOINTR) ||
412                     (flags & SBL_NOINTR)) {
413                         sx_xlock(&sb->sb_sx);
414                         return (0);
415                 }
416                 return (sx_xlock_sig(&sb->sb_sx));
417         } else {
418                 if (sx_try_xlock(&sb->sb_sx) == 0)
419                         return (EWOULDBLOCK);
420                 return (0);
421         }
422 }
423
424 void
425 sbunlock(struct sockbuf *sb)
426 {
427
428         sx_xunlock(&sb->sb_sx);
429 }
430
431 /*
432  * Wakeup processes waiting on a socket buffer.  Do asynchronous notification
433  * via SIGIO if the socket has the SS_ASYNC flag set.
434  *
435  * Called with the socket buffer lock held; will release the lock by the end
436  * of the function.  This allows the caller to acquire the socket buffer lock
437  * while testing for the need for various sorts of wakeup and hold it through
438  * to the point where it's no longer required.  We currently hold the lock
439  * through calls out to other subsystems (with the exception of kqueue), and
440  * then release it to avoid lock order issues.  It's not clear that's
441  * correct.
442  */
443 void
444 sowakeup(struct socket *so, struct sockbuf *sb)
445 {
446         int ret;
447
448         SOCKBUF_LOCK_ASSERT(sb);
449
450         selwakeuppri(sb->sb_sel, PSOCK);
451         if (!SEL_WAITING(sb->sb_sel))
452                 sb->sb_flags &= ~SB_SEL;
453         if (sb->sb_flags & SB_WAIT) {
454                 sb->sb_flags &= ~SB_WAIT;
455                 wakeup(&sb->sb_acc);
456         }
457         KNOTE_LOCKED(&sb->sb_sel->si_note, 0);
458         if (sb->sb_upcall != NULL) {
459                 ret = sb->sb_upcall(so, sb->sb_upcallarg, M_NOWAIT);
460                 if (ret == SU_ISCONNECTED) {
461                         KASSERT(sb == &so->so_rcv,
462                             ("SO_SND upcall returned SU_ISCONNECTED"));
463                         soupcall_clear(so, SO_RCV);
464                 }
465         } else
466                 ret = SU_OK;
467         if (sb->sb_flags & SB_AIO)
468                 sowakeup_aio(so, sb);
469         SOCKBUF_UNLOCK(sb);
470         if (ret == SU_ISCONNECTED)
471                 soisconnected(so);
472         if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
473                 pgsigio(&so->so_sigio, SIGIO, 0);
474         mtx_assert(SOCKBUF_MTX(sb), MA_NOTOWNED);
475 }
476
477 /*
478  * Socket buffer (struct sockbuf) utility routines.
479  *
480  * Each socket contains two socket buffers: one for sending data and one for
481  * receiving data.  Each buffer contains a queue of mbufs, information about
482  * the number of mbufs and amount of data in the queue, and other fields
483  * allowing select() statements and notification on data availability to be
484  * implemented.
485  *
486  * Data stored in a socket buffer is maintained as a list of records.  Each
487  * record is a list of mbufs chained together with the m_next field.  Records
488  * are chained together with the m_nextpkt field. The upper level routine
489  * soreceive() expects the following conventions to be observed when placing
490  * information in the receive buffer:
491  *
492  * 1. If the protocol requires each message be preceded by the sender's name,
493  *    then a record containing that name must be present before any
494  *    associated data (mbuf's must be of type MT_SONAME).
495  * 2. If the protocol supports the exchange of ``access rights'' (really just
496  *    additional data associated with the message), and there are ``rights''
497  *    to be received, then a record containing this data should be present
498  *    (mbuf's must be of type MT_RIGHTS).
499  * 3. If a name or rights record exists, then it must be followed by a data
500  *    record, perhaps of zero length.
501  *
502  * Before using a new socket structure it is first necessary to reserve
503  * buffer space to the socket, by calling sbreserve().  This should commit
504  * some of the available buffer space in the system buffer pool for the
505  * socket (currently, it does nothing but enforce limits).  The space should
506  * be released by calling sbrelease() when the socket is destroyed.
507  */
508 int
509 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
510 {
511         struct thread *td = curthread;
512
513         SOCKBUF_LOCK(&so->so_snd);
514         SOCKBUF_LOCK(&so->so_rcv);
515         if (sbreserve_locked(&so->so_snd, sndcc, so, td) == 0)
516                 goto bad;
517         if (sbreserve_locked(&so->so_rcv, rcvcc, so, td) == 0)
518                 goto bad2;
519         if (so->so_rcv.sb_lowat == 0)
520                 so->so_rcv.sb_lowat = 1;
521         if (so->so_snd.sb_lowat == 0)
522                 so->so_snd.sb_lowat = MCLBYTES;
523         if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
524                 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
525         SOCKBUF_UNLOCK(&so->so_rcv);
526         SOCKBUF_UNLOCK(&so->so_snd);
527         return (0);
528 bad2:
529         sbrelease_locked(&so->so_snd, so);
530 bad:
531         SOCKBUF_UNLOCK(&so->so_rcv);
532         SOCKBUF_UNLOCK(&so->so_snd);
533         return (ENOBUFS);
534 }
535
536 static int
537 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
538 {
539         int error = 0;
540         u_long tmp_sb_max = sb_max;
541
542         error = sysctl_handle_long(oidp, &tmp_sb_max, arg2, req);
543         if (error || !req->newptr)
544                 return (error);
545         if (tmp_sb_max < MSIZE + MCLBYTES)
546                 return (EINVAL);
547         sb_max = tmp_sb_max;
548         sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
549         return (0);
550 }
551         
552 /*
553  * Allot mbufs to a sockbuf.  Attempt to scale mbmax so that mbcnt doesn't
554  * become limiting if buffering efficiency is near the normal case.
555  */
556 int
557 sbreserve_locked(struct sockbuf *sb, u_long cc, struct socket *so,
558     struct thread *td)
559 {
560         rlim_t sbsize_limit;
561
562         SOCKBUF_LOCK_ASSERT(sb);
563
564         /*
565          * When a thread is passed, we take into account the thread's socket
566          * buffer size limit.  The caller will generally pass curthread, but
567          * in the TCP input path, NULL will be passed to indicate that no
568          * appropriate thread resource limits are available.  In that case,
569          * we don't apply a process limit.
570          */
571         if (cc > sb_max_adj)
572                 return (0);
573         if (td != NULL) {
574                 sbsize_limit = lim_cur(td, RLIMIT_SBSIZE);
575         } else
576                 sbsize_limit = RLIM_INFINITY;
577         if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
578             sbsize_limit))
579                 return (0);
580         sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
581         if (sb->sb_lowat > sb->sb_hiwat)
582                 sb->sb_lowat = sb->sb_hiwat;
583         return (1);
584 }
585
586 int
587 sbsetopt(struct socket *so, int cmd, u_long cc)
588 {
589         struct sockbuf *sb;
590         short *flags;
591         u_int *hiwat, *lowat;
592         int error;
593
594         sb = NULL;
595         SOCK_LOCK(so);
596         if (SOLISTENING(so)) {
597                 switch (cmd) {
598                         case SO_SNDLOWAT:
599                         case SO_SNDBUF:
600                                 lowat = &so->sol_sbsnd_lowat;
601                                 hiwat = &so->sol_sbsnd_hiwat;
602                                 flags = &so->sol_sbsnd_flags;
603                                 break;
604                         case SO_RCVLOWAT:
605                         case SO_RCVBUF:
606                                 lowat = &so->sol_sbrcv_lowat;
607                                 hiwat = &so->sol_sbrcv_hiwat;
608                                 flags = &so->sol_sbrcv_flags;
609                                 break;
610                 }
611         } else {
612                 switch (cmd) {
613                         case SO_SNDLOWAT:
614                         case SO_SNDBUF:
615                                 sb = &so->so_snd;
616                                 break;
617                         case SO_RCVLOWAT:
618                         case SO_RCVBUF:
619                                 sb = &so->so_rcv;
620                                 break;
621                 }
622                 flags = &sb->sb_flags;
623                 hiwat = &sb->sb_hiwat;
624                 lowat = &sb->sb_lowat;
625                 SOCKBUF_LOCK(sb);
626         }
627
628         error = 0;
629         switch (cmd) {
630         case SO_SNDBUF:
631         case SO_RCVBUF:
632                 if (SOLISTENING(so)) {
633                         if (cc > sb_max_adj) {
634                                 error = ENOBUFS;
635                                 break;
636                         }
637                         *hiwat = cc;
638                         if (*lowat > *hiwat)
639                                 *lowat = *hiwat;
640                 } else {
641                         if (!sbreserve_locked(sb, cc, so, curthread))
642                                 error = ENOBUFS;
643                 }
644                 if (error == 0)
645                         *flags &= ~SB_AUTOSIZE;
646                 break;
647         case SO_SNDLOWAT:
648         case SO_RCVLOWAT:
649                 /*
650                  * Make sure the low-water is never greater than the
651                  * high-water.
652                  */
653                 *lowat = (cc > *hiwat) ? *hiwat : cc;
654                 break;
655         }
656
657         if (!SOLISTENING(so))
658                 SOCKBUF_UNLOCK(sb);
659         SOCK_UNLOCK(so);
660         return (error);
661 }
662
663 /*
664  * Free mbufs held by a socket, and reserved mbuf space.
665  */
666 void
667 sbrelease_internal(struct sockbuf *sb, struct socket *so)
668 {
669
670         sbflush_internal(sb);
671         (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
672             RLIM_INFINITY);
673         sb->sb_mbmax = 0;
674 }
675
676 void
677 sbrelease_locked(struct sockbuf *sb, struct socket *so)
678 {
679
680         SOCKBUF_LOCK_ASSERT(sb);
681
682         sbrelease_internal(sb, so);
683 }
684
685 void
686 sbrelease(struct sockbuf *sb, struct socket *so)
687 {
688
689         SOCKBUF_LOCK(sb);
690         sbrelease_locked(sb, so);
691         SOCKBUF_UNLOCK(sb);
692 }
693
694 void
695 sbdestroy(struct sockbuf *sb, struct socket *so)
696 {
697
698         sbrelease_internal(sb, so);
699 #ifdef KERN_TLS
700         if (sb->sb_tls_info != NULL)
701                 ktls_free(sb->sb_tls_info);
702         sb->sb_tls_info = NULL;
703 #endif
704 }
705
706 /*
707  * Routines to add and remove data from an mbuf queue.
708  *
709  * The routines sbappend() or sbappendrecord() are normally called to append
710  * new mbufs to a socket buffer, after checking that adequate space is
711  * available, comparing the function sbspace() with the amount of data to be
712  * added.  sbappendrecord() differs from sbappend() in that data supplied is
713  * treated as the beginning of a new record.  To place a sender's address,
714  * optional access rights, and data in a socket receive buffer,
715  * sbappendaddr() should be used.  To place access rights and data in a
716  * socket receive buffer, sbappendrights() should be used.  In either case,
717  * the new data begins a new record.  Note that unlike sbappend() and
718  * sbappendrecord(), these routines check for the caller that there will be
719  * enough space to store the data.  Each fails if there is not enough space,
720  * or if it cannot find mbufs to store additional information in.
721  *
722  * Reliable protocols may use the socket send buffer to hold data awaiting
723  * acknowledgement.  Data is normally copied from a socket send buffer in a
724  * protocol with m_copy for output to a peer, and then removing the data from
725  * the socket buffer with sbdrop() or sbdroprecord() when the data is
726  * acknowledged by the peer.
727  */
728 #ifdef SOCKBUF_DEBUG
729 void
730 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
731 {
732         struct mbuf *m = sb->sb_mb;
733
734         SOCKBUF_LOCK_ASSERT(sb);
735
736         while (m && m->m_nextpkt)
737                 m = m->m_nextpkt;
738
739         if (m != sb->sb_lastrecord) {
740                 printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
741                         __func__, sb->sb_mb, sb->sb_lastrecord, m);
742                 printf("packet chain:\n");
743                 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
744                         printf("\t%p\n", m);
745                 panic("%s from %s:%u", __func__, file, line);
746         }
747 }
748
749 void
750 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
751 {
752         struct mbuf *m = sb->sb_mb;
753         struct mbuf *n;
754
755         SOCKBUF_LOCK_ASSERT(sb);
756
757         while (m && m->m_nextpkt)
758                 m = m->m_nextpkt;
759
760         while (m && m->m_next)
761                 m = m->m_next;
762
763         if (m != sb->sb_mbtail) {
764                 printf("%s: sb_mb %p sb_mbtail %p last %p\n",
765                         __func__, sb->sb_mb, sb->sb_mbtail, m);
766                 printf("packet tree:\n");
767                 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
768                         printf("\t");
769                         for (n = m; n != NULL; n = n->m_next)
770                                 printf("%p ", n);
771                         printf("\n");
772                 }
773                 panic("%s from %s:%u", __func__, file, line);
774         }
775 }
776 #endif /* SOCKBUF_DEBUG */
777
778 #define SBLINKRECORD(sb, m0) do {                                       \
779         SOCKBUF_LOCK_ASSERT(sb);                                        \
780         if ((sb)->sb_lastrecord != NULL)                                \
781                 (sb)->sb_lastrecord->m_nextpkt = (m0);                  \
782         else                                                            \
783                 (sb)->sb_mb = (m0);                                     \
784         (sb)->sb_lastrecord = (m0);                                     \
785 } while (/*CONSTCOND*/0)
786
787 /*
788  * Append mbuf chain m to the last record in the socket buffer sb.  The
789  * additional space associated the mbuf chain is recorded in sb.  Empty mbufs
790  * are discarded and mbufs are compacted where possible.
791  */
792 void
793 sbappend_locked(struct sockbuf *sb, struct mbuf *m, int flags)
794 {
795         struct mbuf *n;
796
797         SOCKBUF_LOCK_ASSERT(sb);
798
799         if (m == NULL)
800                 return;
801         sbm_clrprotoflags(m, flags);
802         SBLASTRECORDCHK(sb);
803         n = sb->sb_mb;
804         if (n) {
805                 while (n->m_nextpkt)
806                         n = n->m_nextpkt;
807                 do {
808                         if (n->m_flags & M_EOR) {
809                                 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
810                                 return;
811                         }
812                 } while (n->m_next && (n = n->m_next));
813         } else {
814                 /*
815                  * XXX Would like to simply use sb_mbtail here, but
816                  * XXX I need to verify that I won't miss an EOR that
817                  * XXX way.
818                  */
819                 if ((n = sb->sb_lastrecord) != NULL) {
820                         do {
821                                 if (n->m_flags & M_EOR) {
822                                         sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
823                                         return;
824                                 }
825                         } while (n->m_next && (n = n->m_next));
826                 } else {
827                         /*
828                          * If this is the first record in the socket buffer,
829                          * it's also the last record.
830                          */
831                         sb->sb_lastrecord = m;
832                 }
833         }
834         sbcompress(sb, m, n);
835         SBLASTRECORDCHK(sb);
836 }
837
838 /*
839  * Append mbuf chain m to the last record in the socket buffer sb.  The
840  * additional space associated the mbuf chain is recorded in sb.  Empty mbufs
841  * are discarded and mbufs are compacted where possible.
842  */
843 void
844 sbappend(struct sockbuf *sb, struct mbuf *m, int flags)
845 {
846
847         SOCKBUF_LOCK(sb);
848         sbappend_locked(sb, m, flags);
849         SOCKBUF_UNLOCK(sb);
850 }
851
852 /*
853  * This version of sbappend() should only be used when the caller absolutely
854  * knows that there will never be more than one record in the socket buffer,
855  * that is, a stream protocol (such as TCP).
856  */
857 void
858 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m, int flags)
859 {
860         SOCKBUF_LOCK_ASSERT(sb);
861
862         KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
863         KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
864
865         SBLASTMBUFCHK(sb);
866
867 #ifdef KERN_TLS
868         if (sb->sb_tls_info != NULL)
869                 ktls_seq(sb, m);
870 #endif
871
872         /* Remove all packet headers and mbuf tags to get a pure data chain. */
873         m_demote(m, 1, flags & PRUS_NOTREADY ? M_NOTREADY : 0);
874
875         sbcompress(sb, m, sb->sb_mbtail);
876
877         sb->sb_lastrecord = sb->sb_mb;
878         SBLASTRECORDCHK(sb);
879 }
880
881 /*
882  * This version of sbappend() should only be used when the caller absolutely
883  * knows that there will never be more than one record in the socket buffer,
884  * that is, a stream protocol (such as TCP).
885  */
886 void
887 sbappendstream(struct sockbuf *sb, struct mbuf *m, int flags)
888 {
889
890         SOCKBUF_LOCK(sb);
891         sbappendstream_locked(sb, m, flags);
892         SOCKBUF_UNLOCK(sb);
893 }
894
895 #ifdef SOCKBUF_DEBUG
896 void
897 sbcheck(struct sockbuf *sb, const char *file, int line)
898 {
899         struct mbuf *m, *n, *fnrdy;
900         u_long acc, ccc, mbcnt;
901
902         SOCKBUF_LOCK_ASSERT(sb);
903
904         acc = ccc = mbcnt = 0;
905         fnrdy = NULL;
906
907         for (m = sb->sb_mb; m; m = n) {
908             n = m->m_nextpkt;
909             for (; m; m = m->m_next) {
910                 if (m->m_len == 0) {
911                         printf("sb %p empty mbuf %p\n", sb, m);
912                         goto fail;
913                 }
914                 if ((m->m_flags & M_NOTREADY) && fnrdy == NULL) {
915                         if (m != sb->sb_fnrdy) {
916                                 printf("sb %p: fnrdy %p != m %p\n",
917                                     sb, sb->sb_fnrdy, m);
918                                 goto fail;
919                         }
920                         fnrdy = m;
921                 }
922                 if (fnrdy) {
923                         if (!(m->m_flags & M_NOTAVAIL)) {
924                                 printf("sb %p: fnrdy %p, m %p is avail\n",
925                                     sb, sb->sb_fnrdy, m);
926                                 goto fail;
927                         }
928                 } else
929                         acc += m->m_len;
930                 ccc += m->m_len;
931                 mbcnt += MSIZE;
932                 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
933                         mbcnt += m->m_ext.ext_size;
934             }
935         }
936         if (acc != sb->sb_acc || ccc != sb->sb_ccc || mbcnt != sb->sb_mbcnt) {
937                 printf("acc %ld/%u ccc %ld/%u mbcnt %ld/%u\n",
938                     acc, sb->sb_acc, ccc, sb->sb_ccc, mbcnt, sb->sb_mbcnt);
939                 goto fail;
940         }
941         return;
942 fail:
943         panic("%s from %s:%u", __func__, file, line);
944 }
945 #endif
946
947 /*
948  * As above, except the mbuf chain begins a new record.
949  */
950 void
951 sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0)
952 {
953         struct mbuf *m;
954
955         SOCKBUF_LOCK_ASSERT(sb);
956
957         if (m0 == NULL)
958                 return;
959         m_clrprotoflags(m0);
960         /*
961          * Put the first mbuf on the queue.  Note this permits zero length
962          * records.
963          */
964         sballoc(sb, m0);
965         SBLASTRECORDCHK(sb);
966         SBLINKRECORD(sb, m0);
967         sb->sb_mbtail = m0;
968         m = m0->m_next;
969         m0->m_next = 0;
970         if (m && (m0->m_flags & M_EOR)) {
971                 m0->m_flags &= ~M_EOR;
972                 m->m_flags |= M_EOR;
973         }
974         /* always call sbcompress() so it can do SBLASTMBUFCHK() */
975         sbcompress(sb, m, m0);
976 }
977
978 /*
979  * As above, except the mbuf chain begins a new record.
980  */
981 void
982 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
983 {
984
985         SOCKBUF_LOCK(sb);
986         sbappendrecord_locked(sb, m0);
987         SOCKBUF_UNLOCK(sb);
988 }
989
990 /* Helper routine that appends data, control, and address to a sockbuf. */
991 static int
992 sbappendaddr_locked_internal(struct sockbuf *sb, const struct sockaddr *asa,
993     struct mbuf *m0, struct mbuf *control, struct mbuf *ctrl_last)
994 {
995         struct mbuf *m, *n, *nlast;
996 #if MSIZE <= 256
997         if (asa->sa_len > MLEN)
998                 return (0);
999 #endif
1000         m = m_get(M_NOWAIT, MT_SONAME);
1001         if (m == NULL)
1002                 return (0);
1003         m->m_len = asa->sa_len;
1004         bcopy(asa, mtod(m, caddr_t), asa->sa_len);
1005         if (m0) {
1006                 m_clrprotoflags(m0);
1007                 m_tag_delete_chain(m0, NULL);
1008                 /*
1009                  * Clear some persistent info from pkthdr.
1010                  * We don't use m_demote(), because some netgraph consumers
1011                  * expect M_PKTHDR presence.
1012                  */
1013                 m0->m_pkthdr.rcvif = NULL;
1014                 m0->m_pkthdr.flowid = 0;
1015                 m0->m_pkthdr.csum_flags = 0;
1016                 m0->m_pkthdr.fibnum = 0;
1017                 m0->m_pkthdr.rsstype = 0;
1018         }
1019         if (ctrl_last)
1020                 ctrl_last->m_next = m0; /* concatenate data to control */
1021         else
1022                 control = m0;
1023         m->m_next = control;
1024         for (n = m; n->m_next != NULL; n = n->m_next)
1025                 sballoc(sb, n);
1026         sballoc(sb, n);
1027         nlast = n;
1028         SBLINKRECORD(sb, m);
1029
1030         sb->sb_mbtail = nlast;
1031         SBLASTMBUFCHK(sb);
1032
1033         SBLASTRECORDCHK(sb);
1034         return (1);
1035 }
1036
1037 /*
1038  * Append address and data, and optionally, control (ancillary) data to the
1039  * receive queue of a socket.  If present, m0 must include a packet header
1040  * with total length.  Returns 0 if no space in sockbuf or insufficient
1041  * mbufs.
1042  */
1043 int
1044 sbappendaddr_locked(struct sockbuf *sb, const struct sockaddr *asa,
1045     struct mbuf *m0, struct mbuf *control)
1046 {
1047         struct mbuf *ctrl_last;
1048         int space = asa->sa_len;
1049
1050         SOCKBUF_LOCK_ASSERT(sb);
1051
1052         if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1053                 panic("sbappendaddr_locked");
1054         if (m0)
1055                 space += m0->m_pkthdr.len;
1056         space += m_length(control, &ctrl_last);
1057
1058         if (space > sbspace(sb))
1059                 return (0);
1060         return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1061 }
1062
1063 /*
1064  * Append address and data, and optionally, control (ancillary) data to the
1065  * receive queue of a socket.  If present, m0 must include a packet header
1066  * with total length.  Returns 0 if insufficient mbufs.  Does not validate space
1067  * on the receiving sockbuf.
1068  */
1069 int
1070 sbappendaddr_nospacecheck_locked(struct sockbuf *sb, const struct sockaddr *asa,
1071     struct mbuf *m0, struct mbuf *control)
1072 {
1073         struct mbuf *ctrl_last;
1074
1075         SOCKBUF_LOCK_ASSERT(sb);
1076
1077         ctrl_last = (control == NULL) ? NULL : m_last(control);
1078         return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1079 }
1080
1081 /*
1082  * Append address and data, and optionally, control (ancillary) data to the
1083  * receive queue of a socket.  If present, m0 must include a packet header
1084  * with total length.  Returns 0 if no space in sockbuf or insufficient
1085  * mbufs.
1086  */
1087 int
1088 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa,
1089     struct mbuf *m0, struct mbuf *control)
1090 {
1091         int retval;
1092
1093         SOCKBUF_LOCK(sb);
1094         retval = sbappendaddr_locked(sb, asa, m0, control);
1095         SOCKBUF_UNLOCK(sb);
1096         return (retval);
1097 }
1098
1099 void
1100 sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0,
1101     struct mbuf *control, int flags)
1102 {
1103         struct mbuf *m, *mlast;
1104
1105         sbm_clrprotoflags(m0, flags);
1106         m_last(control)->m_next = m0;
1107
1108         SBLASTRECORDCHK(sb);
1109
1110         for (m = control; m->m_next; m = m->m_next)
1111                 sballoc(sb, m);
1112         sballoc(sb, m);
1113         mlast = m;
1114         SBLINKRECORD(sb, control);
1115
1116         sb->sb_mbtail = mlast;
1117         SBLASTMBUFCHK(sb);
1118
1119         SBLASTRECORDCHK(sb);
1120 }
1121
1122 void
1123 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1124     int flags)
1125 {
1126
1127         SOCKBUF_LOCK(sb);
1128         sbappendcontrol_locked(sb, m0, control, flags);
1129         SOCKBUF_UNLOCK(sb);
1130 }
1131
1132 /*
1133  * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
1134  * (n).  If (n) is NULL, the buffer is presumed empty.
1135  *
1136  * When the data is compressed, mbufs in the chain may be handled in one of
1137  * three ways:
1138  *
1139  * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
1140  *     record boundary, and no change in data type).
1141  *
1142  * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
1143  *     an mbuf already in the socket buffer.  This can occur if an
1144  *     appropriate mbuf exists, there is room, both mbufs are not marked as
1145  *     not ready, and no merging of data types will occur.
1146  *
1147  * (3) The mbuf may be appended to the end of the existing mbuf chain.
1148  *
1149  * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
1150  * end-of-record.
1151  */
1152 void
1153 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1154 {
1155         int eor = 0;
1156         struct mbuf *o;
1157
1158         SOCKBUF_LOCK_ASSERT(sb);
1159
1160         while (m) {
1161                 eor |= m->m_flags & M_EOR;
1162                 if (m->m_len == 0 &&
1163                     (eor == 0 ||
1164                      (((o = m->m_next) || (o = n)) &&
1165                       o->m_type == m->m_type))) {
1166                         if (sb->sb_lastrecord == m)
1167                                 sb->sb_lastrecord = m->m_next;
1168                         m = m_free(m);
1169                         continue;
1170                 }
1171                 if (n && (n->m_flags & M_EOR) == 0 &&
1172                     M_WRITABLE(n) &&
1173                     ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1174                     !(m->m_flags & M_NOTREADY) &&
1175                     !(n->m_flags & (M_NOTREADY | M_NOMAP)) &&
1176                     !mbuf_has_tls_session(m) &&
1177                     !mbuf_has_tls_session(n) &&
1178                     m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1179                     m->m_len <= M_TRAILINGSPACE(n) &&
1180                     n->m_type == m->m_type) {
1181                         m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1182                         n->m_len += m->m_len;
1183                         sb->sb_ccc += m->m_len;
1184                         if (sb->sb_fnrdy == NULL)
1185                                 sb->sb_acc += m->m_len;
1186                         if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1187                                 /* XXX: Probably don't need.*/
1188                                 sb->sb_ctl += m->m_len;
1189                         m = m_free(m);
1190                         continue;
1191                 }
1192                 if (m->m_len <= MLEN && (m->m_flags & M_NOMAP) &&
1193                     (m->m_flags & M_NOTREADY) == 0 &&
1194                     !mbuf_has_tls_session(m))
1195                         (void)mb_unmapped_compress(m);
1196                 if (n)
1197                         n->m_next = m;
1198                 else
1199                         sb->sb_mb = m;
1200                 sb->sb_mbtail = m;
1201                 sballoc(sb, m);
1202                 n = m;
1203                 m->m_flags &= ~M_EOR;
1204                 m = m->m_next;
1205                 n->m_next = 0;
1206         }
1207         if (eor) {
1208                 KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
1209                 n->m_flags |= eor;
1210         }
1211         SBLASTMBUFCHK(sb);
1212 }
1213
1214 /*
1215  * Free all mbufs in a sockbuf.  Check that all resources are reclaimed.
1216  */
1217 static void
1218 sbflush_internal(struct sockbuf *sb)
1219 {
1220
1221         while (sb->sb_mbcnt) {
1222                 /*
1223                  * Don't call sbcut(sb, 0) if the leading mbuf is non-empty:
1224                  * we would loop forever. Panic instead.
1225                  */
1226                 if (sb->sb_ccc == 0 && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1227                         break;
1228                 m_freem(sbcut_internal(sb, (int)sb->sb_ccc));
1229         }
1230         KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
1231             ("%s: ccc %u mb %p mbcnt %u", __func__,
1232             sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
1233 }
1234
1235 void
1236 sbflush_locked(struct sockbuf *sb)
1237 {
1238
1239         SOCKBUF_LOCK_ASSERT(sb);
1240         sbflush_internal(sb);
1241 }
1242
1243 void
1244 sbflush(struct sockbuf *sb)
1245 {
1246
1247         SOCKBUF_LOCK(sb);
1248         sbflush_locked(sb);
1249         SOCKBUF_UNLOCK(sb);
1250 }
1251
1252 /*
1253  * Cut data from (the front of) a sockbuf.
1254  */
1255 static struct mbuf *
1256 sbcut_internal(struct sockbuf *sb, int len)
1257 {
1258         struct mbuf *m, *next, *mfree;
1259
1260         KASSERT(len >= 0, ("%s: len is %d but it is supposed to be >= 0",
1261             __func__, len));
1262         KASSERT(len <= sb->sb_ccc, ("%s: len: %d is > ccc: %u",
1263             __func__, len, sb->sb_ccc));
1264
1265         next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1266         mfree = NULL;
1267
1268         while (len > 0) {
1269                 if (m == NULL) {
1270                         KASSERT(next, ("%s: no next, len %d", __func__, len));
1271                         m = next;
1272                         next = m->m_nextpkt;
1273                 }
1274                 if (m->m_len > len) {
1275                         KASSERT(!(m->m_flags & M_NOTAVAIL),
1276                             ("%s: m %p M_NOTAVAIL", __func__, m));
1277                         m->m_len -= len;
1278                         m->m_data += len;
1279                         sb->sb_ccc -= len;
1280                         sb->sb_acc -= len;
1281                         if (sb->sb_sndptroff != 0)
1282                                 sb->sb_sndptroff -= len;
1283                         if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1284                                 sb->sb_ctl -= len;
1285                         break;
1286                 }
1287                 len -= m->m_len;
1288                 sbfree(sb, m);
1289                 /*
1290                  * Do not put M_NOTREADY buffers to the free list, they
1291                  * are referenced from outside.
1292                  */
1293                 if (m->m_flags & M_NOTREADY)
1294                         m = m->m_next;
1295                 else {
1296                         struct mbuf *n;
1297
1298                         n = m->m_next;
1299                         m->m_next = mfree;
1300                         mfree = m;
1301                         m = n;
1302                 }
1303         }
1304         /*
1305          * Free any zero-length mbufs from the buffer.
1306          * For SOCK_DGRAM sockets such mbufs represent empty records.
1307          * XXX: For SOCK_STREAM sockets such mbufs can appear in the buffer,
1308          * when sosend_generic() needs to send only control data.
1309          */
1310         while (m && m->m_len == 0) {
1311                 struct mbuf *n;
1312
1313                 sbfree(sb, m);
1314                 n = m->m_next;
1315                 m->m_next = mfree;
1316                 mfree = m;
1317                 m = n;
1318         }
1319         if (m) {
1320                 sb->sb_mb = m;
1321                 m->m_nextpkt = next;
1322         } else
1323                 sb->sb_mb = next;
1324         /*
1325          * First part is an inline SB_EMPTY_FIXUP().  Second part makes sure
1326          * sb_lastrecord is up-to-date if we dropped part of the last record.
1327          */
1328         m = sb->sb_mb;
1329         if (m == NULL) {
1330                 sb->sb_mbtail = NULL;
1331                 sb->sb_lastrecord = NULL;
1332         } else if (m->m_nextpkt == NULL) {
1333                 sb->sb_lastrecord = m;
1334         }
1335
1336         return (mfree);
1337 }
1338
1339 /*
1340  * Drop data from (the front of) a sockbuf.
1341  */
1342 void
1343 sbdrop_locked(struct sockbuf *sb, int len)
1344 {
1345
1346         SOCKBUF_LOCK_ASSERT(sb);
1347         m_freem(sbcut_internal(sb, len));
1348 }
1349
1350 /*
1351  * Drop data from (the front of) a sockbuf,
1352  * and return it to caller.
1353  */
1354 struct mbuf *
1355 sbcut_locked(struct sockbuf *sb, int len)
1356 {
1357
1358         SOCKBUF_LOCK_ASSERT(sb);
1359         return (sbcut_internal(sb, len));
1360 }
1361
1362 void
1363 sbdrop(struct sockbuf *sb, int len)
1364 {
1365         struct mbuf *mfree;
1366
1367         SOCKBUF_LOCK(sb);
1368         mfree = sbcut_internal(sb, len);
1369         SOCKBUF_UNLOCK(sb);
1370
1371         m_freem(mfree);
1372 }
1373
1374 struct mbuf *
1375 sbsndptr_noadv(struct sockbuf *sb, uint32_t off, uint32_t *moff)
1376 {
1377         struct mbuf *m;
1378
1379         KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1380         if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1381                 *moff = off;
1382                 if (sb->sb_sndptr == NULL) {
1383                         sb->sb_sndptr = sb->sb_mb;
1384                         sb->sb_sndptroff = 0;
1385                 }
1386                 return (sb->sb_mb);
1387         } else {
1388                 m = sb->sb_sndptr;
1389                 off -= sb->sb_sndptroff;
1390         }
1391         *moff = off;
1392         return (m);
1393 }
1394
1395 void
1396 sbsndptr_adv(struct sockbuf *sb, struct mbuf *mb, uint32_t len)
1397 {
1398         /*
1399          * A small copy was done, advance forward the sb_sbsndptr to cover
1400          * it.
1401          */
1402         struct mbuf *m;
1403
1404         if (mb != sb->sb_sndptr) {
1405                 /* Did not copyout at the same mbuf */
1406                 return;
1407         }
1408         m = mb;
1409         while (m && (len > 0)) {
1410                 if (len >= m->m_len) {
1411                         len -= m->m_len;
1412                         if (m->m_next) {
1413                                 sb->sb_sndptroff += m->m_len;
1414                                 sb->sb_sndptr = m->m_next;
1415                         }
1416                         m = m->m_next;
1417                 } else {
1418                         len = 0;
1419                 }
1420         }
1421 }
1422
1423 /*
1424  * Return the first mbuf and the mbuf data offset for the provided
1425  * send offset without changing the "sb_sndptroff" field.
1426  */
1427 struct mbuf *
1428 sbsndmbuf(struct sockbuf *sb, u_int off, u_int *moff)
1429 {
1430         struct mbuf *m;
1431
1432         KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1433
1434         /*
1435          * If the "off" is below the stored offset, which happens on
1436          * retransmits, just use "sb_mb":
1437          */
1438         if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1439                 m = sb->sb_mb;
1440         } else {
1441                 m = sb->sb_sndptr;
1442                 off -= sb->sb_sndptroff;
1443         }
1444         while (off > 0 && m != NULL) {
1445                 if (off < m->m_len)
1446                         break;
1447                 off -= m->m_len;
1448                 m = m->m_next;
1449         }
1450         *moff = off;
1451         return (m);
1452 }
1453
1454 /*
1455  * Drop a record off the front of a sockbuf and move the next record to the
1456  * front.
1457  */
1458 void
1459 sbdroprecord_locked(struct sockbuf *sb)
1460 {
1461         struct mbuf *m;
1462
1463         SOCKBUF_LOCK_ASSERT(sb);
1464
1465         m = sb->sb_mb;
1466         if (m) {
1467                 sb->sb_mb = m->m_nextpkt;
1468                 do {
1469                         sbfree(sb, m);
1470                         m = m_free(m);
1471                 } while (m);
1472         }
1473         SB_EMPTY_FIXUP(sb);
1474 }
1475
1476 /*
1477  * Drop a record off the front of a sockbuf and move the next record to the
1478  * front.
1479  */
1480 void
1481 sbdroprecord(struct sockbuf *sb)
1482 {
1483
1484         SOCKBUF_LOCK(sb);
1485         sbdroprecord_locked(sb);
1486         SOCKBUF_UNLOCK(sb);
1487 }
1488
1489 /*
1490  * Create a "control" mbuf containing the specified data with the specified
1491  * type for presentation on a socket buffer.
1492  */
1493 struct mbuf *
1494 sbcreatecontrol(caddr_t p, int size, int type, int level)
1495 {
1496         struct cmsghdr *cp;
1497         struct mbuf *m;
1498
1499         if (CMSG_SPACE((u_int)size) > MCLBYTES)
1500                 return ((struct mbuf *) NULL);
1501         if (CMSG_SPACE((u_int)size) > MLEN)
1502                 m = m_getcl(M_NOWAIT, MT_CONTROL, 0);
1503         else
1504                 m = m_get(M_NOWAIT, MT_CONTROL);
1505         if (m == NULL)
1506                 return ((struct mbuf *) NULL);
1507         cp = mtod(m, struct cmsghdr *);
1508         m->m_len = 0;
1509         KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
1510             ("sbcreatecontrol: short mbuf"));
1511         /*
1512          * Don't leave the padding between the msg header and the
1513          * cmsg data and the padding after the cmsg data un-initialized.
1514          */
1515         bzero(cp, CMSG_SPACE((u_int)size));
1516         if (p != NULL)
1517                 (void)memcpy(CMSG_DATA(cp), p, size);
1518         m->m_len = CMSG_SPACE(size);
1519         cp->cmsg_len = CMSG_LEN(size);
1520         cp->cmsg_level = level;
1521         cp->cmsg_type = type;
1522         return (m);
1523 }
1524
1525 /*
1526  * This does the same for socket buffers that sotoxsocket does for sockets:
1527  * generate an user-format data structure describing the socket buffer.  Note
1528  * that the xsockbuf structure, since it is always embedded in a socket, does
1529  * not include a self pointer nor a length.  We make this entry point public
1530  * in case some other mechanism needs it.
1531  */
1532 void
1533 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1534 {
1535
1536         xsb->sb_cc = sb->sb_ccc;
1537         xsb->sb_hiwat = sb->sb_hiwat;
1538         xsb->sb_mbcnt = sb->sb_mbcnt;
1539         xsb->sb_mcnt = sb->sb_mcnt;     
1540         xsb->sb_ccnt = sb->sb_ccnt;
1541         xsb->sb_mbmax = sb->sb_mbmax;
1542         xsb->sb_lowat = sb->sb_lowat;
1543         xsb->sb_flags = sb->sb_flags;
1544         xsb->sb_timeo = sb->sb_timeo;
1545 }
1546
1547 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1548 static int dummy;
1549 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW | CTLFLAG_SKIP, &dummy, 0, "");
1550 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf,
1551     CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &sb_max, 0,
1552     sysctl_handle_sb_max, "LU",
1553     "Maximum socket buffer size");
1554 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1555     &sb_efficiency, 0, "Socket buffer size waste factor");