]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_sockbuf.c
zfs: merge openzfs/zfs@e25f9131d (zfs-2.1-release) into stable/13
[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                         u_long limit = sogetmaxbuf(so);
697                         if (!sbreserve_locked_limit(sb, cc, so, limit, curthread))
698                                 error = ENOBUFS;
699                 }
700                 if (error == 0)
701                         *flags &= ~SB_AUTOSIZE;
702                 break;
703         case SO_SNDLOWAT:
704         case SO_RCVLOWAT:
705                 /*
706                  * Make sure the low-water is never greater than the
707                  * high-water.
708                  */
709                 *lowat = (cc > *hiwat) ? *hiwat : cc;
710                 break;
711         }
712
713         if (!SOLISTENING(so))
714                 SOCKBUF_UNLOCK(sb);
715         SOCK_UNLOCK(so);
716         return (error);
717 }
718
719 /*
720  * Free mbufs held by a socket, and reserved mbuf space.
721  */
722 void
723 sbrelease_internal(struct sockbuf *sb, struct socket *so)
724 {
725
726         sbflush_internal(sb);
727         (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
728             RLIM_INFINITY);
729         sb->sb_mbmax = 0;
730 }
731
732 void
733 sbrelease_locked(struct sockbuf *sb, struct socket *so)
734 {
735
736         SOCKBUF_LOCK_ASSERT(sb);
737
738         sbrelease_internal(sb, so);
739 }
740
741 void
742 sbrelease(struct sockbuf *sb, struct socket *so)
743 {
744
745         SOCKBUF_LOCK(sb);
746         sbrelease_locked(sb, so);
747         SOCKBUF_UNLOCK(sb);
748 }
749
750 void
751 sbdestroy(struct sockbuf *sb, struct socket *so)
752 {
753
754         sbrelease_internal(sb, so);
755 #ifdef KERN_TLS
756         if (sb->sb_tls_info != NULL)
757                 ktls_free(sb->sb_tls_info);
758         sb->sb_tls_info = NULL;
759 #endif
760 }
761
762 /*
763  * Routines to add and remove data from an mbuf queue.
764  *
765  * The routines sbappend() or sbappendrecord() are normally called to append
766  * new mbufs to a socket buffer, after checking that adequate space is
767  * available, comparing the function sbspace() with the amount of data to be
768  * added.  sbappendrecord() differs from sbappend() in that data supplied is
769  * treated as the beginning of a new record.  To place a sender's address,
770  * optional access rights, and data in a socket receive buffer,
771  * sbappendaddr() should be used.  To place access rights and data in a
772  * socket receive buffer, sbappendrights() should be used.  In either case,
773  * the new data begins a new record.  Note that unlike sbappend() and
774  * sbappendrecord(), these routines check for the caller that there will be
775  * enough space to store the data.  Each fails if there is not enough space,
776  * or if it cannot find mbufs to store additional information in.
777  *
778  * Reliable protocols may use the socket send buffer to hold data awaiting
779  * acknowledgement.  Data is normally copied from a socket send buffer in a
780  * protocol with m_copy for output to a peer, and then removing the data from
781  * the socket buffer with sbdrop() or sbdroprecord() when the data is
782  * acknowledged by the peer.
783  */
784 #ifdef SOCKBUF_DEBUG
785 void
786 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
787 {
788         struct mbuf *m = sb->sb_mb;
789
790         SOCKBUF_LOCK_ASSERT(sb);
791
792         while (m && m->m_nextpkt)
793                 m = m->m_nextpkt;
794
795         if (m != sb->sb_lastrecord) {
796                 printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
797                         __func__, sb->sb_mb, sb->sb_lastrecord, m);
798                 printf("packet chain:\n");
799                 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
800                         printf("\t%p\n", m);
801                 panic("%s from %s:%u", __func__, file, line);
802         }
803 }
804
805 void
806 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
807 {
808         struct mbuf *m = sb->sb_mb;
809         struct mbuf *n;
810
811         SOCKBUF_LOCK_ASSERT(sb);
812
813         while (m && m->m_nextpkt)
814                 m = m->m_nextpkt;
815
816         while (m && m->m_next)
817                 m = m->m_next;
818
819         if (m != sb->sb_mbtail) {
820                 printf("%s: sb_mb %p sb_mbtail %p last %p\n",
821                         __func__, sb->sb_mb, sb->sb_mbtail, m);
822                 printf("packet tree:\n");
823                 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
824                         printf("\t");
825                         for (n = m; n != NULL; n = n->m_next)
826                                 printf("%p ", n);
827                         printf("\n");
828                 }
829                 panic("%s from %s:%u", __func__, file, line);
830         }
831
832 #ifdef KERN_TLS
833         m = sb->sb_mtls;
834         while (m && m->m_next)
835                 m = m->m_next;
836
837         if (m != sb->sb_mtlstail) {
838                 printf("%s: sb_mtls %p sb_mtlstail %p last %p\n",
839                         __func__, sb->sb_mtls, sb->sb_mtlstail, m);
840                 printf("TLS packet tree:\n");
841                 printf("\t");
842                 for (m = sb->sb_mtls; m != NULL; m = m->m_next) {
843                         printf("%p ", m);
844                 }
845                 printf("\n");
846                 panic("%s from %s:%u", __func__, file, line);
847         }
848 #endif
849 }
850 #endif /* SOCKBUF_DEBUG */
851
852 #define SBLINKRECORD(sb, m0) do {                                       \
853         SOCKBUF_LOCK_ASSERT(sb);                                        \
854         if ((sb)->sb_lastrecord != NULL)                                \
855                 (sb)->sb_lastrecord->m_nextpkt = (m0);                  \
856         else                                                            \
857                 (sb)->sb_mb = (m0);                                     \
858         (sb)->sb_lastrecord = (m0);                                     \
859 } while (/*CONSTCOND*/0)
860
861 /*
862  * Append mbuf chain m to the last record in the socket buffer sb.  The
863  * additional space associated the mbuf chain is recorded in sb.  Empty mbufs
864  * are discarded and mbufs are compacted where possible.
865  */
866 void
867 sbappend_locked(struct sockbuf *sb, struct mbuf *m, int flags)
868 {
869         struct mbuf *n;
870
871         SOCKBUF_LOCK_ASSERT(sb);
872
873         if (m == NULL)
874                 return;
875         sbm_clrprotoflags(m, flags);
876         SBLASTRECORDCHK(sb);
877         n = sb->sb_mb;
878         if (n) {
879                 while (n->m_nextpkt)
880                         n = n->m_nextpkt;
881                 do {
882                         if (n->m_flags & M_EOR) {
883                                 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
884                                 return;
885                         }
886                 } while (n->m_next && (n = n->m_next));
887         } else {
888                 /*
889                  * XXX Would like to simply use sb_mbtail here, but
890                  * XXX I need to verify that I won't miss an EOR that
891                  * XXX way.
892                  */
893                 if ((n = sb->sb_lastrecord) != NULL) {
894                         do {
895                                 if (n->m_flags & M_EOR) {
896                                         sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
897                                         return;
898                                 }
899                         } while (n->m_next && (n = n->m_next));
900                 } else {
901                         /*
902                          * If this is the first record in the socket buffer,
903                          * it's also the last record.
904                          */
905                         sb->sb_lastrecord = m;
906                 }
907         }
908         sbcompress(sb, m, n);
909         SBLASTRECORDCHK(sb);
910 }
911
912 /*
913  * Append mbuf chain m to the last record in the socket buffer sb.  The
914  * additional space associated the mbuf chain is recorded in sb.  Empty mbufs
915  * are discarded and mbufs are compacted where possible.
916  */
917 void
918 sbappend(struct sockbuf *sb, struct mbuf *m, int flags)
919 {
920
921         SOCKBUF_LOCK(sb);
922         sbappend_locked(sb, m, flags);
923         SOCKBUF_UNLOCK(sb);
924 }
925
926 #ifdef KERN_TLS
927 /*
928  * Append an mbuf containing encrypted TLS data.  The data
929  * is marked M_NOTREADY until it has been decrypted and
930  * stored as a TLS record.
931  */
932 static void
933 sbappend_ktls_rx(struct sockbuf *sb, struct mbuf *m)
934 {
935         struct mbuf *n;
936
937         SBLASTMBUFCHK(sb);
938
939         /* Remove all packet headers and mbuf tags to get a pure data chain. */
940         m_demote(m, 1, 0);
941
942         for (n = m; n != NULL; n = n->m_next)
943                 n->m_flags |= M_NOTREADY;
944         sbcompress_ktls_rx(sb, m, sb->sb_mtlstail);
945         ktls_check_rx(sb);
946 }
947 #endif
948
949 /*
950  * This version of sbappend() should only be used when the caller absolutely
951  * knows that there will never be more than one record in the socket buffer,
952  * that is, a stream protocol (such as TCP).
953  */
954 void
955 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m, int flags)
956 {
957         SOCKBUF_LOCK_ASSERT(sb);
958
959         KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
960
961 #ifdef KERN_TLS
962         /*
963          * Decrypted TLS records are appended as records via
964          * sbappendrecord().  TCP passes encrypted TLS records to this
965          * function which must be scheduled for decryption.
966          */
967         if (sb->sb_flags & SB_TLS_RX) {
968                 sbappend_ktls_rx(sb, m);
969                 return;
970         }
971 #endif
972
973         KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
974
975         SBLASTMBUFCHK(sb);
976
977 #ifdef KERN_TLS
978         if (sb->sb_tls_info != NULL)
979                 ktls_seq(sb, m);
980 #endif
981
982         /* Remove all packet headers and mbuf tags to get a pure data chain. */
983         m_demote(m, 1, flags & PRUS_NOTREADY ? M_NOTREADY : 0);
984
985         sbcompress(sb, m, sb->sb_mbtail);
986
987         sb->sb_lastrecord = sb->sb_mb;
988         SBLASTRECORDCHK(sb);
989 }
990
991 /*
992  * This version of sbappend() should only be used when the caller absolutely
993  * knows that there will never be more than one record in the socket buffer,
994  * that is, a stream protocol (such as TCP).
995  */
996 void
997 sbappendstream(struct sockbuf *sb, struct mbuf *m, int flags)
998 {
999
1000         SOCKBUF_LOCK(sb);
1001         sbappendstream_locked(sb, m, flags);
1002         SOCKBUF_UNLOCK(sb);
1003 }
1004
1005 #ifdef SOCKBUF_DEBUG
1006 void
1007 sbcheck(struct sockbuf *sb, const char *file, int line)
1008 {
1009         struct mbuf *m, *n, *fnrdy;
1010         u_long acc, ccc, mbcnt;
1011 #ifdef KERN_TLS
1012         u_long tlscc;
1013 #endif
1014
1015         SOCKBUF_LOCK_ASSERT(sb);
1016
1017         acc = ccc = mbcnt = 0;
1018         fnrdy = NULL;
1019
1020         for (m = sb->sb_mb; m; m = n) {
1021             n = m->m_nextpkt;
1022             for (; m; m = m->m_next) {
1023                 if (m->m_len == 0) {
1024                         printf("sb %p empty mbuf %p\n", sb, m);
1025                         goto fail;
1026                 }
1027                 if ((m->m_flags & M_NOTREADY) && fnrdy == NULL) {
1028                         if (m != sb->sb_fnrdy) {
1029                                 printf("sb %p: fnrdy %p != m %p\n",
1030                                     sb, sb->sb_fnrdy, m);
1031                                 goto fail;
1032                         }
1033                         fnrdy = m;
1034                 }
1035                 if (fnrdy) {
1036                         if (!(m->m_flags & M_NOTAVAIL)) {
1037                                 printf("sb %p: fnrdy %p, m %p is avail\n",
1038                                     sb, sb->sb_fnrdy, m);
1039                                 goto fail;
1040                         }
1041                 } else
1042                         acc += m->m_len;
1043                 ccc += m->m_len;
1044                 mbcnt += MSIZE;
1045                 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
1046                         mbcnt += m->m_ext.ext_size;
1047             }
1048         }
1049 #ifdef KERN_TLS
1050         /*
1051          * Account for mbufs "detached" by ktls_detach_record() while
1052          * they are decrypted by ktls_decrypt().  tlsdcc gives a count
1053          * of the detached bytes that are included in ccc.  The mbufs
1054          * and clusters are not included in the socket buffer
1055          * accounting.
1056          */
1057         ccc += sb->sb_tlsdcc;
1058
1059         tlscc = 0;
1060         for (m = sb->sb_mtls; m; m = m->m_next) {
1061                 if (m->m_nextpkt != NULL) {
1062                         printf("sb %p TLS mbuf %p with nextpkt\n", sb, m);
1063                         goto fail;
1064                 }
1065                 if ((m->m_flags & M_NOTREADY) == 0) {
1066                         printf("sb %p TLS mbuf %p ready\n", sb, m);
1067                         goto fail;
1068                 }
1069                 tlscc += m->m_len;
1070                 ccc += m->m_len;
1071                 mbcnt += MSIZE;
1072                 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
1073                         mbcnt += m->m_ext.ext_size;
1074         }
1075
1076         if (sb->sb_tlscc != tlscc) {
1077                 printf("tlscc %ld/%u dcc %u\n", tlscc, sb->sb_tlscc,
1078                     sb->sb_tlsdcc);
1079                 goto fail;
1080         }
1081 #endif
1082         if (acc != sb->sb_acc || ccc != sb->sb_ccc || mbcnt != sb->sb_mbcnt) {
1083                 printf("acc %ld/%u ccc %ld/%u mbcnt %ld/%u\n",
1084                     acc, sb->sb_acc, ccc, sb->sb_ccc, mbcnt, sb->sb_mbcnt);
1085 #ifdef KERN_TLS
1086                 printf("tlscc %ld/%u dcc %u\n", tlscc, sb->sb_tlscc,
1087                     sb->sb_tlsdcc);
1088 #endif
1089                 goto fail;
1090         }
1091         return;
1092 fail:
1093         panic("%s from %s:%u", __func__, file, line);
1094 }
1095 #endif
1096
1097 /*
1098  * As above, except the mbuf chain begins a new record.
1099  */
1100 void
1101 sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0)
1102 {
1103         struct mbuf *m;
1104
1105         SOCKBUF_LOCK_ASSERT(sb);
1106
1107         if (m0 == NULL)
1108                 return;
1109         m_clrprotoflags(m0);
1110         /*
1111          * Put the first mbuf on the queue.  Note this permits zero length
1112          * records.
1113          */
1114         sballoc(sb, m0);
1115         SBLASTRECORDCHK(sb);
1116         SBLINKRECORD(sb, m0);
1117         sb->sb_mbtail = m0;
1118         m = m0->m_next;
1119         m0->m_next = 0;
1120         if (m && (m0->m_flags & M_EOR)) {
1121                 m0->m_flags &= ~M_EOR;
1122                 m->m_flags |= M_EOR;
1123         }
1124         /* always call sbcompress() so it can do SBLASTMBUFCHK() */
1125         sbcompress(sb, m, m0);
1126 }
1127
1128 /*
1129  * As above, except the mbuf chain begins a new record.
1130  */
1131 void
1132 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
1133 {
1134
1135         SOCKBUF_LOCK(sb);
1136         sbappendrecord_locked(sb, m0);
1137         SOCKBUF_UNLOCK(sb);
1138 }
1139
1140 /* Helper routine that appends data, control, and address to a sockbuf. */
1141 static int
1142 sbappendaddr_locked_internal(struct sockbuf *sb, const struct sockaddr *asa,
1143     struct mbuf *m0, struct mbuf *control, struct mbuf *ctrl_last)
1144 {
1145         struct mbuf *m, *n, *nlast;
1146 #if MSIZE <= 256
1147         if (asa->sa_len > MLEN)
1148                 return (0);
1149 #endif
1150         m = m_get(M_NOWAIT, MT_SONAME);
1151         if (m == NULL)
1152                 return (0);
1153         m->m_len = asa->sa_len;
1154         bcopy(asa, mtod(m, caddr_t), asa->sa_len);
1155         if (m0) {
1156                 M_ASSERT_NO_SND_TAG(m0);
1157                 m_clrprotoflags(m0);
1158                 m_tag_delete_chain(m0, NULL);
1159                 /*
1160                  * Clear some persistent info from pkthdr.
1161                  * We don't use m_demote(), because some netgraph consumers
1162                  * expect M_PKTHDR presence.
1163                  */
1164                 m0->m_pkthdr.rcvif = NULL;
1165                 m0->m_pkthdr.flowid = 0;
1166                 m0->m_pkthdr.csum_flags = 0;
1167                 m0->m_pkthdr.fibnum = 0;
1168                 m0->m_pkthdr.rsstype = 0;
1169         }
1170         if (ctrl_last)
1171                 ctrl_last->m_next = m0; /* concatenate data to control */
1172         else
1173                 control = m0;
1174         m->m_next = control;
1175         for (n = m; n->m_next != NULL; n = n->m_next)
1176                 sballoc(sb, n);
1177         sballoc(sb, n);
1178         nlast = n;
1179         SBLINKRECORD(sb, m);
1180
1181         sb->sb_mbtail = nlast;
1182         SBLASTMBUFCHK(sb);
1183
1184         SBLASTRECORDCHK(sb);
1185         return (1);
1186 }
1187
1188 /*
1189  * Append address and data, and optionally, control (ancillary) data to the
1190  * receive queue of a socket.  If present, m0 must include a packet header
1191  * with total length.  Returns 0 if no space in sockbuf or insufficient
1192  * mbufs.
1193  */
1194 int
1195 sbappendaddr_locked(struct sockbuf *sb, const struct sockaddr *asa,
1196     struct mbuf *m0, struct mbuf *control)
1197 {
1198         struct mbuf *ctrl_last;
1199         int space = asa->sa_len;
1200
1201         SOCKBUF_LOCK_ASSERT(sb);
1202
1203         if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1204                 panic("sbappendaddr_locked");
1205         if (m0)
1206                 space += m0->m_pkthdr.len;
1207         space += m_length(control, &ctrl_last);
1208
1209         if (space > sbspace(sb))
1210                 return (0);
1211         return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1212 }
1213
1214 /*
1215  * Append address and data, and optionally, control (ancillary) data to the
1216  * receive queue of a socket.  If present, m0 must include a packet header
1217  * with total length.  Returns 0 if insufficient mbufs.  Does not validate space
1218  * on the receiving sockbuf.
1219  */
1220 int
1221 sbappendaddr_nospacecheck_locked(struct sockbuf *sb, const struct sockaddr *asa,
1222     struct mbuf *m0, struct mbuf *control)
1223 {
1224         struct mbuf *ctrl_last;
1225
1226         SOCKBUF_LOCK_ASSERT(sb);
1227
1228         ctrl_last = (control == NULL) ? NULL : m_last(control);
1229         return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1230 }
1231
1232 /*
1233  * Append address and data, and optionally, control (ancillary) data to the
1234  * receive queue of a socket.  If present, m0 must include a packet header
1235  * with total length.  Returns 0 if no space in sockbuf or insufficient
1236  * mbufs.
1237  */
1238 int
1239 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa,
1240     struct mbuf *m0, struct mbuf *control)
1241 {
1242         int retval;
1243
1244         SOCKBUF_LOCK(sb);
1245         retval = sbappendaddr_locked(sb, asa, m0, control);
1246         SOCKBUF_UNLOCK(sb);
1247         return (retval);
1248 }
1249
1250 void
1251 sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0,
1252     struct mbuf *control, int flags)
1253 {
1254         struct mbuf *m, *mlast;
1255
1256         sbm_clrprotoflags(m0, flags);
1257         m_last(control)->m_next = m0;
1258
1259         SBLASTRECORDCHK(sb);
1260
1261         for (m = control; m->m_next; m = m->m_next)
1262                 sballoc(sb, m);
1263         sballoc(sb, m);
1264         mlast = m;
1265         SBLINKRECORD(sb, control);
1266
1267         sb->sb_mbtail = mlast;
1268         SBLASTMBUFCHK(sb);
1269
1270         SBLASTRECORDCHK(sb);
1271 }
1272
1273 void
1274 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1275     int flags)
1276 {
1277
1278         SOCKBUF_LOCK(sb);
1279         sbappendcontrol_locked(sb, m0, control, flags);
1280         SOCKBUF_UNLOCK(sb);
1281 }
1282
1283 /*
1284  * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
1285  * (n).  If (n) is NULL, the buffer is presumed empty.
1286  *
1287  * When the data is compressed, mbufs in the chain may be handled in one of
1288  * three ways:
1289  *
1290  * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
1291  *     record boundary, and no change in data type).
1292  *
1293  * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
1294  *     an mbuf already in the socket buffer.  This can occur if an
1295  *     appropriate mbuf exists, there is room, both mbufs are not marked as
1296  *     not ready, and no merging of data types will occur.
1297  *
1298  * (3) The mbuf may be appended to the end of the existing mbuf chain.
1299  *
1300  * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
1301  * end-of-record.
1302  */
1303 void
1304 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1305 {
1306         int eor = 0;
1307         struct mbuf *o;
1308
1309         SOCKBUF_LOCK_ASSERT(sb);
1310
1311         while (m) {
1312                 eor |= m->m_flags & M_EOR;
1313                 if (m->m_len == 0 &&
1314                     (eor == 0 ||
1315                      (((o = m->m_next) || (o = n)) &&
1316                       o->m_type == m->m_type))) {
1317                         if (sb->sb_lastrecord == m)
1318                                 sb->sb_lastrecord = m->m_next;
1319                         m = m_free(m);
1320                         continue;
1321                 }
1322                 if (n && (n->m_flags & M_EOR) == 0 &&
1323                     M_WRITABLE(n) &&
1324                     ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1325                     !(m->m_flags & M_NOTREADY) &&
1326                     !(n->m_flags & (M_NOTREADY | M_EXTPG)) &&
1327                     !mbuf_has_tls_session(m) &&
1328                     !mbuf_has_tls_session(n) &&
1329                     m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1330                     m->m_len <= M_TRAILINGSPACE(n) &&
1331                     n->m_type == m->m_type) {
1332                         m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1333                         n->m_len += m->m_len;
1334                         sb->sb_ccc += m->m_len;
1335                         if (sb->sb_fnrdy == NULL)
1336                                 sb->sb_acc += m->m_len;
1337                         if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1338                                 /* XXX: Probably don't need.*/
1339                                 sb->sb_ctl += m->m_len;
1340                         m = m_free(m);
1341                         continue;
1342                 }
1343                 if (m->m_len <= MLEN && (m->m_flags & M_EXTPG) &&
1344                     (m->m_flags & M_NOTREADY) == 0 &&
1345                     !mbuf_has_tls_session(m))
1346                         (void)mb_unmapped_compress(m);
1347                 if (n)
1348                         n->m_next = m;
1349                 else
1350                         sb->sb_mb = m;
1351                 sb->sb_mbtail = m;
1352                 sballoc(sb, m);
1353                 n = m;
1354                 m->m_flags &= ~M_EOR;
1355                 m = m->m_next;
1356                 n->m_next = 0;
1357         }
1358         if (eor) {
1359                 KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
1360                 n->m_flags |= eor;
1361         }
1362         SBLASTMBUFCHK(sb);
1363 }
1364
1365 #ifdef KERN_TLS
1366 /*
1367  * A version of sbcompress() for encrypted TLS RX mbufs.  These mbufs
1368  * are appended to the 'sb_mtls' chain instead of 'sb_mb' and are also
1369  * a bit simpler (no EOR markers, always MT_DATA, etc.).
1370  */
1371 static void
1372 sbcompress_ktls_rx(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1373 {
1374
1375         SOCKBUF_LOCK_ASSERT(sb);
1376
1377         while (m) {
1378                 KASSERT((m->m_flags & M_EOR) == 0,
1379                     ("TLS RX mbuf %p with EOR", m));
1380                 KASSERT(m->m_type == MT_DATA,
1381                     ("TLS RX mbuf %p is not MT_DATA", m));
1382                 KASSERT((m->m_flags & M_NOTREADY) != 0,
1383                     ("TLS RX mbuf %p ready", m));
1384                 KASSERT((m->m_flags & M_EXTPG) == 0,
1385                     ("TLS RX mbuf %p unmapped", m));
1386
1387                 if (m->m_len == 0) {
1388                         m = m_free(m);
1389                         continue;
1390                 }
1391
1392                 /*
1393                  * Even though both 'n' and 'm' are NOTREADY, it's ok
1394                  * to coalesce the data.
1395                  */
1396                 if (n &&
1397                     M_WRITABLE(n) &&
1398                     ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1399                     !(n->m_flags & (M_EXTPG)) &&
1400                     m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1401                     m->m_len <= M_TRAILINGSPACE(n)) {
1402                         m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1403                         n->m_len += m->m_len;
1404                         sb->sb_ccc += m->m_len;
1405                         sb->sb_tlscc += m->m_len;
1406                         m = m_free(m);
1407                         continue;
1408                 }
1409                 if (n)
1410                         n->m_next = m;
1411                 else
1412                         sb->sb_mtls = m;
1413                 sb->sb_mtlstail = m;
1414                 sballoc_ktls_rx(sb, m);
1415                 n = m;
1416                 m = m->m_next;
1417                 n->m_next = NULL;
1418         }
1419         SBLASTMBUFCHK(sb);
1420 }
1421 #endif
1422
1423 /*
1424  * Free all mbufs in a sockbuf.  Check that all resources are reclaimed.
1425  */
1426 static void
1427 sbflush_internal(struct sockbuf *sb)
1428 {
1429
1430         while (sb->sb_mbcnt || sb->sb_tlsdcc) {
1431                 /*
1432                  * Don't call sbcut(sb, 0) if the leading mbuf is non-empty:
1433                  * we would loop forever. Panic instead.
1434                  */
1435                 if (sb->sb_ccc == 0 && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1436                         break;
1437                 m_freem(sbcut_internal(sb, (int)sb->sb_ccc));
1438         }
1439         KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
1440             ("%s: ccc %u mb %p mbcnt %u", __func__,
1441             sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
1442 }
1443
1444 void
1445 sbflush_locked(struct sockbuf *sb)
1446 {
1447
1448         SOCKBUF_LOCK_ASSERT(sb);
1449         sbflush_internal(sb);
1450 }
1451
1452 void
1453 sbflush(struct sockbuf *sb)
1454 {
1455
1456         SOCKBUF_LOCK(sb);
1457         sbflush_locked(sb);
1458         SOCKBUF_UNLOCK(sb);
1459 }
1460
1461 /*
1462  * Cut data from (the front of) a sockbuf.
1463  */
1464 static struct mbuf *
1465 sbcut_internal(struct sockbuf *sb, int len)
1466 {
1467         struct mbuf *m, *next, *mfree;
1468         bool is_tls;
1469
1470         KASSERT(len >= 0, ("%s: len is %d but it is supposed to be >= 0",
1471             __func__, len));
1472         KASSERT(len <= sb->sb_ccc, ("%s: len: %d is > ccc: %u",
1473             __func__, len, sb->sb_ccc));
1474
1475         next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1476         is_tls = false;
1477         mfree = NULL;
1478
1479         while (len > 0) {
1480                 if (m == NULL) {
1481 #ifdef KERN_TLS
1482                         if (next == NULL && !is_tls) {
1483                                 if (sb->sb_tlsdcc != 0) {
1484                                         MPASS(len >= sb->sb_tlsdcc);
1485                                         len -= sb->sb_tlsdcc;
1486                                         sb->sb_ccc -= sb->sb_tlsdcc;
1487                                         sb->sb_tlsdcc = 0;
1488                                         if (len == 0)
1489                                                 break;
1490                                 }
1491                                 next = sb->sb_mtls;
1492                                 is_tls = true;
1493                         }
1494 #endif
1495                         KASSERT(next, ("%s: no next, len %d", __func__, len));
1496                         m = next;
1497                         next = m->m_nextpkt;
1498                 }
1499                 if (m->m_len > len) {
1500                         KASSERT(!(m->m_flags & M_NOTAVAIL),
1501                             ("%s: m %p M_NOTAVAIL", __func__, m));
1502                         m->m_len -= len;
1503                         m->m_data += len;
1504                         sb->sb_ccc -= len;
1505                         sb->sb_acc -= len;
1506                         if (sb->sb_sndptroff != 0)
1507                                 sb->sb_sndptroff -= len;
1508                         if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1509                                 sb->sb_ctl -= len;
1510                         break;
1511                 }
1512                 len -= m->m_len;
1513 #ifdef KERN_TLS
1514                 if (is_tls)
1515                         sbfree_ktls_rx(sb, m);
1516                 else
1517 #endif
1518                         sbfree(sb, m);
1519                 /*
1520                  * Do not put M_NOTREADY buffers to the free list, they
1521                  * are referenced from outside.
1522                  */
1523                 if (m->m_flags & M_NOTREADY && !is_tls)
1524                         m = m->m_next;
1525                 else {
1526                         struct mbuf *n;
1527
1528                         n = m->m_next;
1529                         m->m_next = mfree;
1530                         mfree = m;
1531                         m = n;
1532                 }
1533         }
1534         /*
1535          * Free any zero-length mbufs from the buffer.
1536          * For SOCK_DGRAM sockets such mbufs represent empty records.
1537          * XXX: For SOCK_STREAM sockets such mbufs can appear in the buffer,
1538          * when sosend_generic() needs to send only control data.
1539          */
1540         while (m && m->m_len == 0) {
1541                 struct mbuf *n;
1542
1543                 sbfree(sb, m);
1544                 n = m->m_next;
1545                 m->m_next = mfree;
1546                 mfree = m;
1547                 m = n;
1548         }
1549 #ifdef KERN_TLS
1550         if (is_tls) {
1551                 sb->sb_mb = NULL;
1552                 sb->sb_mtls = m;
1553                 if (m == NULL)
1554                         sb->sb_mtlstail = NULL;
1555         } else
1556 #endif
1557         if (m) {
1558                 sb->sb_mb = m;
1559                 m->m_nextpkt = next;
1560         } else
1561                 sb->sb_mb = next;
1562         /*
1563          * First part is an inline SB_EMPTY_FIXUP().  Second part makes sure
1564          * sb_lastrecord is up-to-date if we dropped part of the last record.
1565          */
1566         m = sb->sb_mb;
1567         if (m == NULL) {
1568                 sb->sb_mbtail = NULL;
1569                 sb->sb_lastrecord = NULL;
1570         } else if (m->m_nextpkt == NULL) {
1571                 sb->sb_lastrecord = m;
1572         }
1573
1574         return (mfree);
1575 }
1576
1577 /*
1578  * Drop data from (the front of) a sockbuf.
1579  */
1580 void
1581 sbdrop_locked(struct sockbuf *sb, int len)
1582 {
1583
1584         SOCKBUF_LOCK_ASSERT(sb);
1585         m_freem(sbcut_internal(sb, len));
1586 }
1587
1588 /*
1589  * Drop data from (the front of) a sockbuf,
1590  * and return it to caller.
1591  */
1592 struct mbuf *
1593 sbcut_locked(struct sockbuf *sb, int len)
1594 {
1595
1596         SOCKBUF_LOCK_ASSERT(sb);
1597         return (sbcut_internal(sb, len));
1598 }
1599
1600 void
1601 sbdrop(struct sockbuf *sb, int len)
1602 {
1603         struct mbuf *mfree;
1604
1605         SOCKBUF_LOCK(sb);
1606         mfree = sbcut_internal(sb, len);
1607         SOCKBUF_UNLOCK(sb);
1608
1609         m_freem(mfree);
1610 }
1611
1612 struct mbuf *
1613 sbsndptr_noadv(struct sockbuf *sb, uint32_t off, uint32_t *moff)
1614 {
1615         struct mbuf *m;
1616
1617         KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1618         if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1619                 *moff = off;
1620                 if (sb->sb_sndptr == NULL) {
1621                         sb->sb_sndptr = sb->sb_mb;
1622                         sb->sb_sndptroff = 0;
1623                 }
1624                 return (sb->sb_mb);
1625         } else {
1626                 m = sb->sb_sndptr;
1627                 off -= sb->sb_sndptroff;
1628         }
1629         *moff = off;
1630         return (m);
1631 }
1632
1633 void
1634 sbsndptr_adv(struct sockbuf *sb, struct mbuf *mb, uint32_t len)
1635 {
1636         /*
1637          * A small copy was done, advance forward the sb_sbsndptr to cover
1638          * it.
1639          */
1640         struct mbuf *m;
1641
1642         if (mb != sb->sb_sndptr) {
1643                 /* Did not copyout at the same mbuf */
1644                 return;
1645         }
1646         m = mb;
1647         while (m && (len > 0)) {
1648                 if (len >= m->m_len) {
1649                         len -= m->m_len;
1650                         if (m->m_next) {
1651                                 sb->sb_sndptroff += m->m_len;
1652                                 sb->sb_sndptr = m->m_next;
1653                         }
1654                         m = m->m_next;
1655                 } else {
1656                         len = 0;
1657                 }
1658         }
1659 }
1660
1661 /*
1662  * Return the first mbuf and the mbuf data offset for the provided
1663  * send offset without changing the "sb_sndptroff" field.
1664  */
1665 struct mbuf *
1666 sbsndmbuf(struct sockbuf *sb, u_int off, u_int *moff)
1667 {
1668         struct mbuf *m;
1669
1670         KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1671
1672         /*
1673          * If the "off" is below the stored offset, which happens on
1674          * retransmits, just use "sb_mb":
1675          */
1676         if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1677                 m = sb->sb_mb;
1678         } else {
1679                 m = sb->sb_sndptr;
1680                 off -= sb->sb_sndptroff;
1681         }
1682         while (off > 0 && m != NULL) {
1683                 if (off < m->m_len)
1684                         break;
1685                 off -= m->m_len;
1686                 m = m->m_next;
1687         }
1688         *moff = off;
1689         return (m);
1690 }
1691
1692 /*
1693  * Drop a record off the front of a sockbuf and move the next record to the
1694  * front.
1695  */
1696 void
1697 sbdroprecord_locked(struct sockbuf *sb)
1698 {
1699         struct mbuf *m;
1700
1701         SOCKBUF_LOCK_ASSERT(sb);
1702
1703         m = sb->sb_mb;
1704         if (m) {
1705                 sb->sb_mb = m->m_nextpkt;
1706                 do {
1707                         sbfree(sb, m);
1708                         m = m_free(m);
1709                 } while (m);
1710         }
1711         SB_EMPTY_FIXUP(sb);
1712 }
1713
1714 /*
1715  * Drop a record off the front of a sockbuf and move the next record to the
1716  * front.
1717  */
1718 void
1719 sbdroprecord(struct sockbuf *sb)
1720 {
1721
1722         SOCKBUF_LOCK(sb);
1723         sbdroprecord_locked(sb);
1724         SOCKBUF_UNLOCK(sb);
1725 }
1726
1727 /*
1728  * Create a "control" mbuf containing the specified data with the specified
1729  * type for presentation on a socket buffer.
1730  */
1731 struct mbuf *
1732 sbcreatecontrol_how(void *p, int size, int type, int level, int wait)
1733 {
1734         struct cmsghdr *cp;
1735         struct mbuf *m;
1736
1737         MBUF_CHECKSLEEP(wait);
1738         if (CMSG_SPACE((u_int)size) > MCLBYTES)
1739                 return ((struct mbuf *) NULL);
1740         if (CMSG_SPACE((u_int)size) > MLEN)
1741                 m = m_getcl(wait, MT_CONTROL, 0);
1742         else
1743                 m = m_get(wait, MT_CONTROL);
1744         if (m == NULL)
1745                 return ((struct mbuf *) NULL);
1746         cp = mtod(m, struct cmsghdr *);
1747         m->m_len = 0;
1748         KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
1749             ("sbcreatecontrol: short mbuf"));
1750         /*
1751          * Don't leave the padding between the msg header and the
1752          * cmsg data and the padding after the cmsg data un-initialized.
1753          */
1754         bzero(cp, CMSG_SPACE((u_int)size));
1755         if (p != NULL)
1756                 (void)memcpy(CMSG_DATA(cp), p, size);
1757         m->m_len = CMSG_SPACE(size);
1758         cp->cmsg_len = CMSG_LEN(size);
1759         cp->cmsg_level = level;
1760         cp->cmsg_type = type;
1761         return (m);
1762 }
1763
1764 struct mbuf *
1765 sbcreatecontrol(caddr_t p, int size, int type, int level)
1766 {
1767
1768         return (sbcreatecontrol_how(p, size, type, level, M_NOWAIT));
1769 }
1770
1771 /*
1772  * This does the same for socket buffers that sotoxsocket does for sockets:
1773  * generate an user-format data structure describing the socket buffer.  Note
1774  * that the xsockbuf structure, since it is always embedded in a socket, does
1775  * not include a self pointer nor a length.  We make this entry point public
1776  * in case some other mechanism needs it.
1777  */
1778 void
1779 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1780 {
1781
1782         xsb->sb_cc = sb->sb_ccc;
1783         xsb->sb_hiwat = sb->sb_hiwat;
1784         xsb->sb_mbcnt = sb->sb_mbcnt;
1785         xsb->sb_mcnt = sb->sb_mcnt;     
1786         xsb->sb_ccnt = sb->sb_ccnt;
1787         xsb->sb_mbmax = sb->sb_mbmax;
1788         xsb->sb_lowat = sb->sb_lowat;
1789         xsb->sb_flags = sb->sb_flags;
1790         xsb->sb_timeo = sb->sb_timeo;
1791 }
1792
1793 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1794 static int dummy;
1795 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW | CTLFLAG_SKIP, &dummy, 0, "");
1796 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf,
1797     CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, &sb_max, 0,
1798     sysctl_handle_sb_max, "LU",
1799     "Maximum socket buffer size");
1800 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1801     &sb_efficiency, 0, "Socket buffer size waste factor");