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