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