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