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