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