uipc_socket2.c revision 1.112.2.4 1 /* $NetBSD: uipc_socket2.c,v 1.112.2.4 2014/05/18 17:46:08 rmind Exp $ */
2
3 /*-
4 * Copyright (c) 2008 The NetBSD Foundation, Inc.
5 * 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 *
16 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29 /*
30 * Copyright (c) 1982, 1986, 1988, 1990, 1993
31 * The Regents of the University of California. All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. Neither the name of the University nor the names of its contributors
42 * may be used to endorse or promote products derived from this software
43 * without specific prior written permission.
44 *
45 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * SUCH DAMAGE.
56 *
57 * @(#)uipc_socket2.c 8.2 (Berkeley) 2/14/95
58 */
59
60 #include <sys/cdefs.h>
61 __KERNEL_RCSID(0, "$NetBSD: uipc_socket2.c,v 1.112.2.4 2014/05/18 17:46:08 rmind Exp $");
62
63 #include "opt_mbuftrace.h"
64 #include "opt_sb_max.h"
65
66 #include <sys/param.h>
67 #include <sys/systm.h>
68 #include <sys/proc.h>
69 #include <sys/file.h>
70 #include <sys/buf.h>
71 #include <sys/mbuf.h>
72 #include <sys/protosw.h>
73 #include <sys/domain.h>
74 #include <sys/poll.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/signalvar.h>
78 #include <sys/kauth.h>
79 #include <sys/pool.h>
80 #include <sys/uidinfo.h>
81
82 /*
83 * Primitive routines for operating on sockets and socket buffers.
84 *
85 * Connection life-cycle:
86 *
87 * Normal sequence from the active (originating) side:
88 *
89 * - soisconnecting() is called during processing of connect() call,
90 * - resulting in an eventual call to soisconnected() if/when the
91 * connection is established.
92 *
93 * When the connection is torn down during processing of disconnect():
94 *
95 * - soisdisconnecting() is called and,
96 * - soisdisconnected() is called when the connection to the peer
97 * is totally severed.
98 *
99 * The semantics of these routines are such that connectionless protocols
100 * can call soisconnected() and soisdisconnected() only, bypassing the
101 * in-progress calls when setting up a ``connection'' takes no time.
102 *
103 * From the passive side, a socket is created with two queues of sockets:
104 *
105 * - so_q0 (0) for partial connections (i.e. connections in progress)
106 * - so_q (1) for connections already made and awaiting user acceptance.
107 *
108 * As a protocol is preparing incoming connections, it creates a socket
109 * structure queued on so_q0 by calling sonewconn(). When the connection
110 * is established, soisconnected() is called, and transfers the
111 * socket structure to so_q, making it available to accept().
112 *
113 * If a socket is closed with sockets on either so_q0 or so_q, these
114 * sockets are dropped.
115 *
116 * Locking rules and assumptions:
117 *
118 * o socket::so_lock can change on the fly. The low level routines used
119 * to lock sockets are aware of this. When so_lock is acquired, the
120 * routine locking must check to see if so_lock still points to the
121 * lock that was acquired. If so_lock has changed in the meantime, the
122 * now irrelevant lock that was acquired must be dropped and the lock
123 * operation retried. Although not proven here, this is completely safe
124 * on a multiprocessor system, even with relaxed memory ordering, given
125 * the next two rules:
126 *
127 * o In order to mutate so_lock, the lock pointed to by the current value
128 * of so_lock must be held: i.e., the socket must be held locked by the
129 * changing thread. The thread must issue membar_exit() to prevent
130 * memory accesses being reordered, and can set so_lock to the desired
131 * value. If the lock pointed to by the new value of so_lock is not
132 * held by the changing thread, the socket must then be considered
133 * unlocked.
134 *
135 * o If so_lock is mutated, and the previous lock referred to by so_lock
136 * could still be visible to other threads in the system (e.g. via file
137 * descriptor or protocol-internal reference), then the old lock must
138 * remain valid until the socket and/or protocol control block has been
139 * torn down.
140 *
141 * o If a socket has a non-NULL so_head value (i.e. is in the process of
142 * connecting), then locking the socket must also lock the socket pointed
143 * to by so_head: their lock pointers must match.
144 *
145 * o If a socket has connections in progress (so_q, so_q0 not empty) then
146 * locking the socket must also lock the sockets attached to both queues.
147 * Again, their lock pointers must match.
148 *
149 * o Beyond the initial lock assignment in socreate(), assigning locks to
150 * sockets is the responsibility of the individual protocols / protocol
151 * domains.
152 */
153
154 static pool_cache_t socket_cache;
155 u_long sb_max = SB_MAX;/* maximum socket buffer size */
156 static u_long sb_max_adj; /* adjusted sb_max */
157
158 void
159 soisconnecting(struct socket *so)
160 {
161
162 KASSERT(solocked(so));
163
164 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
165 so->so_state |= SS_ISCONNECTING;
166 }
167
168 void
169 soisconnected(struct socket *so)
170 {
171 struct socket *head;
172
173 head = so->so_head;
174
175 KASSERT(solocked(so));
176 KASSERT(head == NULL || solocked2(so, head));
177
178 so->so_state &= ~(SS_ISCONNECTING | SS_ISDISCONNECTING);
179 so->so_state |= SS_ISCONNECTED;
180 if (head && so->so_onq == &head->so_q0) {
181 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
182 /*
183 * Re-enqueue and wake up any waiters, e.g.
184 * processes blocking on accept().
185 */
186 soqremque(so, 0);
187 soqinsque(head, so, 1);
188 sorwakeup(head);
189 cv_broadcast(&head->so_cv);
190 } else {
191 so->so_upcall =
192 head->so_accf->so_accept_filter->accf_callback;
193 so->so_upcallarg = head->so_accf->so_accept_filter_arg;
194 so->so_rcv.sb_flags |= SB_UPCALL;
195 so->so_options &= ~SO_ACCEPTFILTER;
196 (*so->so_upcall)(so, so->so_upcallarg,
197 POLLIN|POLLRDNORM, M_DONTWAIT);
198 }
199 } else {
200 cv_broadcast(&so->so_cv);
201 sorwakeup(so);
202 sowwakeup(so);
203 }
204 }
205
206 void
207 soisdisconnecting(struct socket *so)
208 {
209
210 KASSERT(solocked(so));
211
212 so->so_state &= ~SS_ISCONNECTING;
213 so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
214 cv_broadcast(&so->so_cv);
215 sowwakeup(so);
216 sorwakeup(so);
217 }
218
219 void
220 soisdisconnected(struct socket *so)
221 {
222
223 KASSERT(solocked(so));
224
225 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
226 so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
227 cv_broadcast(&so->so_cv);
228 sowwakeup(so);
229 sorwakeup(so);
230 }
231
232 void
233 soinit2(void)
234 {
235
236 socket_cache = pool_cache_init(sizeof(struct socket), 0, 0, 0,
237 "socket", NULL, IPL_SOFTNET, NULL, NULL, NULL);
238 }
239
240 /*
241 * sonewconn: accept a new connection.
242 *
243 * When an attempt at a new connection is noted on a socket which accepts
244 * connections, sonewconn(9) is called. If the connection is possible
245 * (subject to space constraints, etc) then we allocate a new structure,
246 * properly linked into the data structure of the original socket.
247 *
248 * => If 'soready' is true, then socket will become ready for accept() i.e.
249 * inserted into the so_q queue, SS_ISCONNECTED set and waiters awoken.
250 * => May be called from soft-interrupt context.
251 * => Listening socket should be locked.
252 * => Returns the new socket locked.
253 */
254 struct socket *
255 sonewconn(struct socket *head, bool soready)
256 {
257 struct socket *so;
258 int soqueue, error;
259
260 KASSERT(solocked(head));
261
262 if (head->so_qlen + head->so_q0len > 3 * head->so_qlimit / 2) {
263 /* Listen queue overflow. */
264 return NULL;
265 }
266 if ((head->so_options & SO_ACCEPTFILTER) != 0) {
267 soready = false;
268 }
269 soqueue = soready ? 1 : 0;
270
271 if ((so = soget(false)) == NULL) {
272 return NULL;
273 }
274 so->so_type = head->so_type;
275 so->so_options = head->so_options & ~SO_ACCEPTCONN;
276 so->so_linger = head->so_linger;
277 so->so_state = head->so_state | SS_NOFDREF;
278 so->so_proto = head->so_proto;
279 so->so_timeo = head->so_timeo;
280 so->so_pgid = head->so_pgid;
281 so->so_send = head->so_send;
282 so->so_receive = head->so_receive;
283 so->so_uidinfo = head->so_uidinfo;
284 so->so_cpid = head->so_cpid;
285 #ifdef MBUFTRACE
286 so->so_mowner = head->so_mowner;
287 so->so_rcv.sb_mowner = head->so_rcv.sb_mowner;
288 so->so_snd.sb_mowner = head->so_snd.sb_mowner;
289 #endif
290 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) != 0)
291 goto out;
292 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
293 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
294 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
295 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
296 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & (SB_AUTOSIZE | SB_ASYNC);
297 so->so_snd.sb_flags |= head->so_snd.sb_flags & (SB_AUTOSIZE | SB_ASYNC);
298
299 /*
300 * Share the lock with the listening-socket, it may get unshared
301 * once the connection is complete.
302 */
303 mutex_obj_hold(head->so_lock);
304 so->so_lock = head->so_lock;
305 sounlock(head);
306
307 /* Finally, perform the protocol attach and re-acquire the lock. */
308 error = (*so->so_proto->pr_usrreqs->pr_attach)(so, 0);
309 solock(head);
310
311 if (error) {
312 out:
313 KASSERT(so->so_accf == NULL);
314 soput(so);
315
316 /* Note: the listening socket shall stay locked. */
317 KASSERT(solocked(head));
318 return NULL;
319 }
320
321 /*
322 * Insert into the queue. If ready, update the connection status
323 * and wake up any waiters, e.g. processes blocking on accept().
324 */
325 soqinsque(head, so, soqueue);
326 if (soready) {
327 so->so_state |= SS_ISCONNECTED;
328 sorwakeup(head);
329 cv_broadcast(&head->so_cv);
330 }
331 KASSERT(solocked2(head, so));
332 return so;
333 }
334
335 struct socket *
336 soget(bool waitok)
337 {
338 struct socket *so;
339
340 so = pool_cache_get(socket_cache, (waitok ? PR_WAITOK : PR_NOWAIT));
341 if (__predict_false(so == NULL))
342 return (NULL);
343 memset(so, 0, sizeof(*so));
344 TAILQ_INIT(&so->so_q0);
345 TAILQ_INIT(&so->so_q);
346 cv_init(&so->so_cv, "socket");
347 cv_init(&so->so_rcv.sb_cv, "netio");
348 cv_init(&so->so_snd.sb_cv, "netio");
349 selinit(&so->so_rcv.sb_sel);
350 selinit(&so->so_snd.sb_sel);
351 so->so_rcv.sb_so = so;
352 so->so_snd.sb_so = so;
353 return so;
354 }
355
356 void
357 soput(struct socket *so)
358 {
359
360 KASSERT(!cv_has_waiters(&so->so_cv));
361 KASSERT(!cv_has_waiters(&so->so_rcv.sb_cv));
362 KASSERT(!cv_has_waiters(&so->so_snd.sb_cv));
363 seldestroy(&so->so_rcv.sb_sel);
364 seldestroy(&so->so_snd.sb_sel);
365 mutex_obj_free(so->so_lock);
366 cv_destroy(&so->so_cv);
367 cv_destroy(&so->so_rcv.sb_cv);
368 cv_destroy(&so->so_snd.sb_cv);
369 pool_cache_put(socket_cache, so);
370 }
371
372 /*
373 * soqinsque: insert socket of a new connection into the specified
374 * accept queue of the listening socket (head).
375 *
376 * q = 0: queue of partial connections
377 * q = 1: queue of incoming connections
378 */
379 void
380 soqinsque(struct socket *head, struct socket *so, int q)
381 {
382 KASSERT(q == 0 || q == 1);
383 KASSERT(solocked2(head, so));
384 KASSERT(so->so_onq == NULL);
385 KASSERT(so->so_head == NULL);
386
387 so->so_head = head;
388 if (q == 0) {
389 head->so_q0len++;
390 so->so_onq = &head->so_q0;
391 } else {
392 head->so_qlen++;
393 so->so_onq = &head->so_q;
394 }
395 TAILQ_INSERT_TAIL(so->so_onq, so, so_qe);
396 }
397
398 /*
399 * soqremque: remove socket from the specified queue.
400 *
401 * => Returns true if socket was removed from the specified queue.
402 * => False if socket was not removed (because it was in other queue).
403 */
404 bool
405 soqremque(struct socket *so, int q)
406 {
407 struct socket *head = so->so_head;
408
409 KASSERT(q == 0 || q == 1);
410 KASSERT(solocked(so));
411 KASSERT(so->so_onq != NULL);
412 KASSERT(head != NULL);
413
414 if (q == 0) {
415 if (so->so_onq != &head->so_q0)
416 return false;
417 head->so_q0len--;
418 } else {
419 if (so->so_onq != &head->so_q)
420 return false;
421 head->so_qlen--;
422 }
423 KASSERT(solocked2(so, head));
424 TAILQ_REMOVE(so->so_onq, so, so_qe);
425 so->so_onq = NULL;
426 so->so_head = NULL;
427 return true;
428 }
429
430 /*
431 * socantsendmore: indicates that no more data will be sent on the
432 * socket; it would normally be applied to a socket when the user
433 * informs the system that no more data is to be sent, by the protocol
434 * code (in case PRU_SHUTDOWN).
435 */
436 void
437 socantsendmore(struct socket *so)
438 {
439 KASSERT(solocked(so));
440
441 so->so_state |= SS_CANTSENDMORE;
442 sowwakeup(so);
443 }
444
445 /*
446 * socantrcvmore(): indicates that no more data will be received and
447 * will normally be applied to the socket by a protocol when it detects
448 * that the peer will send no more data. Data queued for reading in
449 * the socket may yet be read.
450 */
451 void
452 socantrcvmore(struct socket *so)
453 {
454 KASSERT(solocked(so));
455
456 so->so_state |= SS_CANTRCVMORE;
457 sorwakeup(so);
458 }
459
460 /*
461 * Wait for data to arrive at/drain from a socket buffer.
462 */
463 int
464 sbwait(struct sockbuf *sb)
465 {
466 struct socket *so;
467 kmutex_t *lock;
468 int error;
469
470 so = sb->sb_so;
471
472 KASSERT(solocked(so));
473
474 sb->sb_flags |= SB_NOTIFY;
475 lock = so->so_lock;
476 if ((sb->sb_flags & SB_NOINTR) != 0)
477 error = cv_timedwait(&sb->sb_cv, lock, sb->sb_timeo);
478 else
479 error = cv_timedwait_sig(&sb->sb_cv, lock, sb->sb_timeo);
480 if (__predict_false(lock != so->so_lock))
481 solockretry(so, lock);
482 return error;
483 }
484
485 /*
486 * Wakeup processes waiting on a socket buffer.
487 * Do asynchronous notification via SIGIO
488 * if the socket buffer has the SB_ASYNC flag set.
489 */
490 void
491 sowakeup(struct socket *so, struct sockbuf *sb, int code)
492 {
493 int band;
494
495 KASSERT(solocked(so));
496 KASSERT(sb->sb_so == so);
497
498 if (code == POLL_IN)
499 band = POLLIN|POLLRDNORM;
500 else
501 band = POLLOUT|POLLWRNORM;
502 sb->sb_flags &= ~SB_NOTIFY;
503 selnotify(&sb->sb_sel, band, NOTE_SUBMIT);
504 cv_broadcast(&sb->sb_cv);
505 if (sb->sb_flags & SB_ASYNC)
506 fownsignal(so->so_pgid, SIGIO, code, band, so);
507 if (sb->sb_flags & SB_UPCALL)
508 (*so->so_upcall)(so, so->so_upcallarg, band, M_DONTWAIT);
509 }
510
511 /*
512 * Reset a socket's lock pointer. Wake all threads waiting on the
513 * socket's condition variables so that they can restart their waits
514 * using the new lock. The existing lock must be held.
515 */
516 void
517 solockreset(struct socket *so, kmutex_t *lock)
518 {
519
520 KASSERT(solocked(so));
521
522 so->so_lock = lock;
523 cv_broadcast(&so->so_snd.sb_cv);
524 cv_broadcast(&so->so_rcv.sb_cv);
525 cv_broadcast(&so->so_cv);
526 }
527
528 /*
529 * Socket buffer (struct sockbuf) utility routines.
530 *
531 * Each socket contains two socket buffers: one for sending data and
532 * one for receiving data. Each buffer contains a queue of mbufs,
533 * information about the number of mbufs and amount of data in the
534 * queue, and other fields allowing poll() statements and notification
535 * on data availability to be implemented.
536 *
537 * Data stored in a socket buffer is maintained as a list of records.
538 * Each record is a list of mbufs chained together with the m_next
539 * field. Records are chained together with the m_nextpkt field. The upper
540 * level routine soreceive() expects the following conventions to be
541 * observed when placing information in the receive buffer:
542 *
543 * 1. If the protocol requires each message be preceded by the sender's
544 * name, then a record containing that name must be present before
545 * any associated data (mbuf's must be of type MT_SONAME).
546 * 2. If the protocol supports the exchange of ``access rights'' (really
547 * just additional data associated with the message), and there are
548 * ``rights'' to be received, then a record containing this data
549 * should be present (mbuf's must be of type MT_CONTROL).
550 * 3. If a name or rights record exists, then it must be followed by
551 * a data record, perhaps of zero length.
552 *
553 * Before using a new socket structure it is first necessary to reserve
554 * buffer space to the socket, by calling sbreserve(). This should commit
555 * some of the available buffer space in the system buffer pool for the
556 * socket (currently, it does nothing but enforce limits). The space
557 * should be released by calling sbrelease() when the socket is destroyed.
558 */
559
560 int
561 sb_max_set(u_long new_sbmax)
562 {
563 int s;
564
565 if (new_sbmax < (16 * 1024))
566 return (EINVAL);
567
568 s = splsoftnet();
569 sb_max = new_sbmax;
570 sb_max_adj = (u_quad_t)new_sbmax * MCLBYTES / (MSIZE + MCLBYTES);
571 splx(s);
572
573 return (0);
574 }
575
576 int
577 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
578 {
579 KASSERT(so->so_pcb == NULL || solocked(so));
580
581 /*
582 * there's at least one application (a configure script of screen)
583 * which expects a fifo is writable even if it has "some" bytes
584 * in its buffer.
585 * so we want to make sure (hiwat - lowat) >= (some bytes).
586 *
587 * PIPE_BUF here is an arbitrary value chosen as (some bytes) above.
588 * we expect it's large enough for such applications.
589 */
590 u_long lowat = MAX(sock_loan_thresh, MCLBYTES);
591 u_long hiwat = lowat + PIPE_BUF;
592
593 if (sndcc < hiwat)
594 sndcc = hiwat;
595 if (sbreserve(&so->so_snd, sndcc, so) == 0)
596 goto bad;
597 if (sbreserve(&so->so_rcv, rcvcc, so) == 0)
598 goto bad2;
599 if (so->so_rcv.sb_lowat == 0)
600 so->so_rcv.sb_lowat = 1;
601 if (so->so_snd.sb_lowat == 0)
602 so->so_snd.sb_lowat = lowat;
603 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
604 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
605 return (0);
606 bad2:
607 sbrelease(&so->so_snd, so);
608 bad:
609 return (ENOBUFS);
610 }
611
612 /*
613 * Allot mbufs to a sockbuf.
614 * Attempt to scale mbmax so that mbcnt doesn't become limiting
615 * if buffering efficiency is near the normal case.
616 */
617 int
618 sbreserve(struct sockbuf *sb, u_long cc, struct socket *so)
619 {
620 struct lwp *l = curlwp; /* XXX */
621 rlim_t maxcc;
622 struct uidinfo *uidinfo;
623
624 KASSERT(so->so_pcb == NULL || solocked(so));
625 KASSERT(sb->sb_so == so);
626 KASSERT(sb_max_adj != 0);
627
628 if (cc == 0 || cc > sb_max_adj)
629 return (0);
630
631 maxcc = l->l_proc->p_rlimit[RLIMIT_SBSIZE].rlim_cur;
632
633 uidinfo = so->so_uidinfo;
634 if (!chgsbsize(uidinfo, &sb->sb_hiwat, cc, maxcc))
635 return 0;
636 sb->sb_mbmax = min(cc * 2, sb_max);
637 if (sb->sb_lowat > sb->sb_hiwat)
638 sb->sb_lowat = sb->sb_hiwat;
639 return (1);
640 }
641
642 /*
643 * Free mbufs held by a socket, and reserved mbuf space. We do not assert
644 * that the socket is held locked here: see sorflush().
645 */
646 void
647 sbrelease(struct sockbuf *sb, struct socket *so)
648 {
649
650 KASSERT(sb->sb_so == so);
651
652 sbflush(sb);
653 (void)chgsbsize(so->so_uidinfo, &sb->sb_hiwat, 0, RLIM_INFINITY);
654 sb->sb_mbmax = 0;
655 }
656
657 /*
658 * Routines to add and remove
659 * data from an mbuf queue.
660 *
661 * The routines sbappend() or sbappendrecord() are normally called to
662 * append new mbufs to a socket buffer, after checking that adequate
663 * space is available, comparing the function sbspace() with the amount
664 * of data to be added. sbappendrecord() differs from sbappend() in
665 * that data supplied is treated as the beginning of a new record.
666 * To place a sender's address, optional access rights, and data in a
667 * socket receive buffer, sbappendaddr() should be used. To place
668 * access rights and data in a socket receive buffer, sbappendrights()
669 * should be used. In either case, the new data begins a new record.
670 * Note that unlike sbappend() and sbappendrecord(), these routines check
671 * for the caller that there will be enough space to store the data.
672 * Each fails if there is not enough space, or if it cannot find mbufs
673 * to store additional information in.
674 *
675 * Reliable protocols may use the socket send buffer to hold data
676 * awaiting acknowledgement. Data is normally copied from a socket
677 * send buffer in a protocol with m_copy for output to a peer,
678 * and then removing the data from the socket buffer with sbdrop()
679 * or sbdroprecord() when the data is acknowledged by the peer.
680 */
681
682 #ifdef SOCKBUF_DEBUG
683 void
684 sblastrecordchk(struct sockbuf *sb, const char *where)
685 {
686 struct mbuf *m = sb->sb_mb;
687
688 KASSERT(solocked(sb->sb_so));
689
690 while (m && m->m_nextpkt)
691 m = m->m_nextpkt;
692
693 if (m != sb->sb_lastrecord) {
694 printf("sblastrecordchk: sb_mb %p sb_lastrecord %p last %p\n",
695 sb->sb_mb, sb->sb_lastrecord, m);
696 printf("packet chain:\n");
697 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
698 printf("\t%p\n", m);
699 panic("sblastrecordchk from %s", where);
700 }
701 }
702
703 void
704 sblastmbufchk(struct sockbuf *sb, const char *where)
705 {
706 struct mbuf *m = sb->sb_mb;
707 struct mbuf *n;
708
709 KASSERT(solocked(sb->sb_so));
710
711 while (m && m->m_nextpkt)
712 m = m->m_nextpkt;
713
714 while (m && m->m_next)
715 m = m->m_next;
716
717 if (m != sb->sb_mbtail) {
718 printf("sblastmbufchk: sb_mb %p sb_mbtail %p last %p\n",
719 sb->sb_mb, sb->sb_mbtail, m);
720 printf("packet tree:\n");
721 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
722 printf("\t");
723 for (n = m; n != NULL; n = n->m_next)
724 printf("%p ", n);
725 printf("\n");
726 }
727 panic("sblastmbufchk from %s", where);
728 }
729 }
730 #endif /* SOCKBUF_DEBUG */
731
732 /*
733 * Link a chain of records onto a socket buffer
734 */
735 #define SBLINKRECORDCHAIN(sb, m0, mlast) \
736 do { \
737 if ((sb)->sb_lastrecord != NULL) \
738 (sb)->sb_lastrecord->m_nextpkt = (m0); \
739 else \
740 (sb)->sb_mb = (m0); \
741 (sb)->sb_lastrecord = (mlast); \
742 } while (/*CONSTCOND*/0)
743
744
745 #define SBLINKRECORD(sb, m0) \
746 SBLINKRECORDCHAIN(sb, m0, m0)
747
748 /*
749 * Append mbuf chain m to the last record in the
750 * socket buffer sb. The additional space associated
751 * the mbuf chain is recorded in sb. Empty mbufs are
752 * discarded and mbufs are compacted where possible.
753 */
754 void
755 sbappend(struct sockbuf *sb, struct mbuf *m)
756 {
757 struct mbuf *n;
758
759 KASSERT(solocked(sb->sb_so));
760
761 if (m == NULL)
762 return;
763
764 #ifdef MBUFTRACE
765 m_claimm(m, sb->sb_mowner);
766 #endif
767
768 SBLASTRECORDCHK(sb, "sbappend 1");
769
770 if ((n = sb->sb_lastrecord) != NULL) {
771 /*
772 * XXX Would like to simply use sb_mbtail here, but
773 * XXX I need to verify that I won't miss an EOR that
774 * XXX way.
775 */
776 do {
777 if (n->m_flags & M_EOR) {
778 sbappendrecord(sb, m); /* XXXXXX!!!! */
779 return;
780 }
781 } while (n->m_next && (n = n->m_next));
782 } else {
783 /*
784 * If this is the first record in the socket buffer, it's
785 * also the last record.
786 */
787 sb->sb_lastrecord = m;
788 }
789 sbcompress(sb, m, n);
790 SBLASTRECORDCHK(sb, "sbappend 2");
791 }
792
793 /*
794 * This version of sbappend() should only be used when the caller
795 * absolutely knows that there will never be more than one record
796 * in the socket buffer, that is, a stream protocol (such as TCP).
797 */
798 void
799 sbappendstream(struct sockbuf *sb, struct mbuf *m)
800 {
801
802 KASSERT(solocked(sb->sb_so));
803 KDASSERT(m->m_nextpkt == NULL);
804 KASSERT(sb->sb_mb == sb->sb_lastrecord);
805
806 SBLASTMBUFCHK(sb, __func__);
807
808 #ifdef MBUFTRACE
809 m_claimm(m, sb->sb_mowner);
810 #endif
811
812 sbcompress(sb, m, sb->sb_mbtail);
813
814 sb->sb_lastrecord = sb->sb_mb;
815 SBLASTRECORDCHK(sb, __func__);
816 }
817
818 #ifdef SOCKBUF_DEBUG
819 void
820 sbcheck(struct sockbuf *sb)
821 {
822 struct mbuf *m, *m2;
823 u_long len, mbcnt;
824
825 KASSERT(solocked(sb->sb_so));
826
827 len = 0;
828 mbcnt = 0;
829 for (m = sb->sb_mb; m; m = m->m_nextpkt) {
830 for (m2 = m; m2 != NULL; m2 = m2->m_next) {
831 len += m2->m_len;
832 mbcnt += MSIZE;
833 if (m2->m_flags & M_EXT)
834 mbcnt += m2->m_ext.ext_size;
835 if (m2->m_nextpkt != NULL)
836 panic("sbcheck nextpkt");
837 }
838 }
839 if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
840 printf("cc %lu != %lu || mbcnt %lu != %lu\n", len, sb->sb_cc,
841 mbcnt, sb->sb_mbcnt);
842 panic("sbcheck");
843 }
844 }
845 #endif
846
847 /*
848 * As above, except the mbuf chain
849 * begins a new record.
850 */
851 void
852 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
853 {
854 struct mbuf *m;
855
856 KASSERT(solocked(sb->sb_so));
857
858 if (m0 == NULL)
859 return;
860
861 #ifdef MBUFTRACE
862 m_claimm(m0, sb->sb_mowner);
863 #endif
864 /*
865 * Put the first mbuf on the queue.
866 * Note this permits zero length records.
867 */
868 sballoc(sb, m0);
869 SBLASTRECORDCHK(sb, "sbappendrecord 1");
870 SBLINKRECORD(sb, m0);
871 m = m0->m_next;
872 m0->m_next = 0;
873 if (m && (m0->m_flags & M_EOR)) {
874 m0->m_flags &= ~M_EOR;
875 m->m_flags |= M_EOR;
876 }
877 sbcompress(sb, m, m0);
878 SBLASTRECORDCHK(sb, "sbappendrecord 2");
879 }
880
881 /*
882 * As above except that OOB data
883 * is inserted at the beginning of the sockbuf,
884 * but after any other OOB data.
885 */
886 void
887 sbinsertoob(struct sockbuf *sb, struct mbuf *m0)
888 {
889 struct mbuf *m, **mp;
890
891 KASSERT(solocked(sb->sb_so));
892
893 if (m0 == NULL)
894 return;
895
896 SBLASTRECORDCHK(sb, "sbinsertoob 1");
897
898 for (mp = &sb->sb_mb; (m = *mp) != NULL; mp = &((*mp)->m_nextpkt)) {
899 again:
900 switch (m->m_type) {
901
902 case MT_OOBDATA:
903 continue; /* WANT next train */
904
905 case MT_CONTROL:
906 if ((m = m->m_next) != NULL)
907 goto again; /* inspect THIS train further */
908 }
909 break;
910 }
911 /*
912 * Put the first mbuf on the queue.
913 * Note this permits zero length records.
914 */
915 sballoc(sb, m0);
916 m0->m_nextpkt = *mp;
917 if (*mp == NULL) {
918 /* m0 is actually the new tail */
919 sb->sb_lastrecord = m0;
920 }
921 *mp = m0;
922 m = m0->m_next;
923 m0->m_next = 0;
924 if (m && (m0->m_flags & M_EOR)) {
925 m0->m_flags &= ~M_EOR;
926 m->m_flags |= M_EOR;
927 }
928 sbcompress(sb, m, m0);
929 SBLASTRECORDCHK(sb, "sbinsertoob 2");
930 }
931
932 /*
933 * Append address and data, and optionally, control (ancillary) data
934 * to the receive queue of a socket. If present,
935 * m0 must include a packet header with total length.
936 * Returns 0 if no space in sockbuf or insufficient mbufs.
937 */
938 int
939 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa, struct mbuf *m0,
940 struct mbuf *control)
941 {
942 struct mbuf *m, *n, *nlast;
943 int space, len;
944
945 KASSERT(solocked(sb->sb_so));
946
947 space = asa->sa_len;
948
949 if (m0 != NULL) {
950 if ((m0->m_flags & M_PKTHDR) == 0)
951 panic("sbappendaddr");
952 space += m0->m_pkthdr.len;
953 #ifdef MBUFTRACE
954 m_claimm(m0, sb->sb_mowner);
955 #endif
956 }
957 for (n = control; n; n = n->m_next) {
958 space += n->m_len;
959 MCLAIM(n, sb->sb_mowner);
960 if (n->m_next == NULL) /* keep pointer to last control buf */
961 break;
962 }
963 if (space > sbspace(sb))
964 return (0);
965 m = m_get(M_DONTWAIT, MT_SONAME);
966 if (m == NULL)
967 return (0);
968 MCLAIM(m, sb->sb_mowner);
969 /*
970 * XXX avoid 'comparison always true' warning which isn't easily
971 * avoided.
972 */
973 len = asa->sa_len;
974 if (len > MLEN) {
975 MEXTMALLOC(m, asa->sa_len, M_NOWAIT);
976 if ((m->m_flags & M_EXT) == 0) {
977 m_free(m);
978 return (0);
979 }
980 }
981 m->m_len = asa->sa_len;
982 memcpy(mtod(m, void *), asa, asa->sa_len);
983 if (n)
984 n->m_next = m0; /* concatenate data to control */
985 else
986 control = m0;
987 m->m_next = control;
988
989 SBLASTRECORDCHK(sb, "sbappendaddr 1");
990
991 for (n = m; n->m_next != NULL; n = n->m_next)
992 sballoc(sb, n);
993 sballoc(sb, n);
994 nlast = n;
995 SBLINKRECORD(sb, m);
996
997 sb->sb_mbtail = nlast;
998 SBLASTMBUFCHK(sb, "sbappendaddr");
999 SBLASTRECORDCHK(sb, "sbappendaddr 2");
1000
1001 return (1);
1002 }
1003
1004 /*
1005 * Helper for sbappendchainaddr: prepend a struct sockaddr* to
1006 * an mbuf chain.
1007 */
1008 static inline struct mbuf *
1009 m_prepend_sockaddr(struct sockbuf *sb, struct mbuf *m0,
1010 const struct sockaddr *asa)
1011 {
1012 struct mbuf *m;
1013 const int salen = asa->sa_len;
1014
1015 KASSERT(solocked(sb->sb_so));
1016
1017 /* only the first in each chain need be a pkthdr */
1018 m = m_gethdr(M_DONTWAIT, MT_SONAME);
1019 if (m == NULL)
1020 return NULL;
1021 MCLAIM(m, sb->sb_mowner);
1022 #ifdef notyet
1023 if (salen > MHLEN) {
1024 MEXTMALLOC(m, salen, M_NOWAIT);
1025 if ((m->m_flags & M_EXT) == 0) {
1026 m_free(m);
1027 return NULL;
1028 }
1029 }
1030 #else
1031 KASSERT(salen <= MHLEN);
1032 #endif
1033 m->m_len = salen;
1034 memcpy(mtod(m, void *), asa, salen);
1035 m->m_next = m0;
1036 m->m_pkthdr.len = salen + m0->m_pkthdr.len;
1037
1038 return m;
1039 }
1040
1041 int
1042 sbappendaddrchain(struct sockbuf *sb, const struct sockaddr *asa,
1043 struct mbuf *m0, int sbprio)
1044 {
1045 struct mbuf *m, *n, *n0, *nlast;
1046 int error;
1047
1048 KASSERT(solocked(sb->sb_so));
1049
1050 /*
1051 * XXX sbprio reserved for encoding priority of this* request:
1052 * SB_PRIO_NONE --> honour normal sb limits
1053 * SB_PRIO_ONESHOT_OVERFLOW --> if socket has any space,
1054 * take whole chain. Intended for large requests
1055 * that should be delivered atomically (all, or none).
1056 * SB_PRIO_OVERDRAFT -- allow a small (2*MLEN) overflow
1057 * over normal socket limits, for messages indicating
1058 * buffer overflow in earlier normal/lower-priority messages
1059 * SB_PRIO_BESTEFFORT --> ignore limits entirely.
1060 * Intended for kernel-generated messages only.
1061 * Up to generator to avoid total mbuf resource exhaustion.
1062 */
1063 (void)sbprio;
1064
1065 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1066 panic("sbappendaddrchain");
1067
1068 #ifdef notyet
1069 space = sbspace(sb);
1070
1071 /*
1072 * Enforce SB_PRIO_* limits as described above.
1073 */
1074 #endif
1075
1076 n0 = NULL;
1077 nlast = NULL;
1078 for (m = m0; m; m = m->m_nextpkt) {
1079 struct mbuf *np;
1080
1081 #ifdef MBUFTRACE
1082 m_claimm(m, sb->sb_mowner);
1083 #endif
1084
1085 /* Prepend sockaddr to this record (m) of input chain m0 */
1086 n = m_prepend_sockaddr(sb, m, asa);
1087 if (n == NULL) {
1088 error = ENOBUFS;
1089 goto bad;
1090 }
1091
1092 /* Append record (asa+m) to end of new chain n0 */
1093 if (n0 == NULL) {
1094 n0 = n;
1095 } else {
1096 nlast->m_nextpkt = n;
1097 }
1098 /* Keep track of last record on new chain */
1099 nlast = n;
1100
1101 for (np = n; np; np = np->m_next)
1102 sballoc(sb, np);
1103 }
1104
1105 SBLASTRECORDCHK(sb, "sbappendaddrchain 1");
1106
1107 /* Drop the entire chain of (asa+m) records onto the socket */
1108 SBLINKRECORDCHAIN(sb, n0, nlast);
1109
1110 SBLASTRECORDCHK(sb, "sbappendaddrchain 2");
1111
1112 for (m = nlast; m->m_next; m = m->m_next)
1113 ;
1114 sb->sb_mbtail = m;
1115 SBLASTMBUFCHK(sb, "sbappendaddrchain");
1116
1117 return (1);
1118
1119 bad:
1120 /*
1121 * On error, free the prepended addreseses. For consistency
1122 * with sbappendaddr(), leave it to our caller to free
1123 * the input record chain passed to us as m0.
1124 */
1125 while ((n = n0) != NULL) {
1126 struct mbuf *np;
1127
1128 /* Undo the sballoc() of this record */
1129 for (np = n; np; np = np->m_next)
1130 sbfree(sb, np);
1131
1132 n0 = n->m_nextpkt; /* iterate at next prepended address */
1133 MFREE(n, np); /* free prepended address (not data) */
1134 }
1135 return error;
1136 }
1137
1138
1139 int
1140 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control)
1141 {
1142 struct mbuf *m, *mlast, *n;
1143 int space;
1144
1145 KASSERT(solocked(sb->sb_so));
1146
1147 space = 0;
1148 if (control == NULL)
1149 panic("sbappendcontrol");
1150 for (m = control; ; m = m->m_next) {
1151 space += m->m_len;
1152 MCLAIM(m, sb->sb_mowner);
1153 if (m->m_next == NULL)
1154 break;
1155 }
1156 n = m; /* save pointer to last control buffer */
1157 for (m = m0; m; m = m->m_next) {
1158 MCLAIM(m, sb->sb_mowner);
1159 space += m->m_len;
1160 }
1161 if (space > sbspace(sb))
1162 return (0);
1163 n->m_next = m0; /* concatenate data to control */
1164
1165 SBLASTRECORDCHK(sb, "sbappendcontrol 1");
1166
1167 for (m = control; m->m_next != NULL; m = m->m_next)
1168 sballoc(sb, m);
1169 sballoc(sb, m);
1170 mlast = m;
1171 SBLINKRECORD(sb, control);
1172
1173 sb->sb_mbtail = mlast;
1174 SBLASTMBUFCHK(sb, "sbappendcontrol");
1175 SBLASTRECORDCHK(sb, "sbappendcontrol 2");
1176
1177 return (1);
1178 }
1179
1180 /*
1181 * Compress mbuf chain m into the socket
1182 * buffer sb following mbuf n. If n
1183 * is null, the buffer is presumed empty.
1184 */
1185 void
1186 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1187 {
1188 int eor;
1189 struct mbuf *o;
1190
1191 KASSERT(solocked(sb->sb_so));
1192
1193 eor = 0;
1194 while (m) {
1195 eor |= m->m_flags & M_EOR;
1196 if (m->m_len == 0 &&
1197 (eor == 0 ||
1198 (((o = m->m_next) || (o = n)) &&
1199 o->m_type == m->m_type))) {
1200 if (sb->sb_lastrecord == m)
1201 sb->sb_lastrecord = m->m_next;
1202 m = m_free(m);
1203 continue;
1204 }
1205 if (n && (n->m_flags & M_EOR) == 0 &&
1206 /* M_TRAILINGSPACE() checks buffer writeability */
1207 m->m_len <= MCLBYTES / 4 && /* XXX Don't copy too much */
1208 m->m_len <= M_TRAILINGSPACE(n) &&
1209 n->m_type == m->m_type) {
1210 memcpy(mtod(n, char *) + n->m_len, mtod(m, void *),
1211 (unsigned)m->m_len);
1212 n->m_len += m->m_len;
1213 sb->sb_cc += m->m_len;
1214 m = m_free(m);
1215 continue;
1216 }
1217 if (n)
1218 n->m_next = m;
1219 else
1220 sb->sb_mb = m;
1221 sb->sb_mbtail = m;
1222 sballoc(sb, m);
1223 n = m;
1224 m->m_flags &= ~M_EOR;
1225 m = m->m_next;
1226 n->m_next = 0;
1227 }
1228 if (eor) {
1229 if (n)
1230 n->m_flags |= eor;
1231 else
1232 printf("semi-panic: sbcompress\n");
1233 }
1234 SBLASTMBUFCHK(sb, __func__);
1235 }
1236
1237 /*
1238 * Free all mbufs in a sockbuf.
1239 * Check that all resources are reclaimed.
1240 */
1241 void
1242 sbflush(struct sockbuf *sb)
1243 {
1244
1245 KASSERT(solocked(sb->sb_so));
1246 KASSERT((sb->sb_flags & SB_LOCK) == 0);
1247
1248 while (sb->sb_mbcnt)
1249 sbdrop(sb, (int)sb->sb_cc);
1250
1251 KASSERT(sb->sb_cc == 0);
1252 KASSERT(sb->sb_mb == NULL);
1253 KASSERT(sb->sb_mbtail == NULL);
1254 KASSERT(sb->sb_lastrecord == NULL);
1255 }
1256
1257 /*
1258 * Drop data from (the front of) a sockbuf.
1259 */
1260 void
1261 sbdrop(struct sockbuf *sb, int len)
1262 {
1263 struct mbuf *m, *mn, *next;
1264
1265 KASSERT(solocked(sb->sb_so));
1266
1267 next = (m = sb->sb_mb) ? m->m_nextpkt : NULL;
1268 while (len > 0) {
1269 if (m == NULL) {
1270 if (next == NULL)
1271 panic("sbdrop(%p,%d): cc=%lu",
1272 sb, len, sb->sb_cc);
1273 m = next;
1274 next = m->m_nextpkt;
1275 continue;
1276 }
1277 if (m->m_len > len) {
1278 m->m_len -= len;
1279 m->m_data += len;
1280 sb->sb_cc -= len;
1281 break;
1282 }
1283 len -= m->m_len;
1284 sbfree(sb, m);
1285 MFREE(m, mn);
1286 m = mn;
1287 }
1288 while (m && m->m_len == 0) {
1289 sbfree(sb, m);
1290 MFREE(m, mn);
1291 m = mn;
1292 }
1293 if (m) {
1294 sb->sb_mb = m;
1295 m->m_nextpkt = next;
1296 } else
1297 sb->sb_mb = next;
1298 /*
1299 * First part is an inline SB_EMPTY_FIXUP(). Second part
1300 * makes sure sb_lastrecord is up-to-date if we dropped
1301 * part of the last record.
1302 */
1303 m = sb->sb_mb;
1304 if (m == NULL) {
1305 sb->sb_mbtail = NULL;
1306 sb->sb_lastrecord = NULL;
1307 } else if (m->m_nextpkt == NULL)
1308 sb->sb_lastrecord = m;
1309 }
1310
1311 /*
1312 * Drop a record off the front of a sockbuf
1313 * and move the next record to the front.
1314 */
1315 void
1316 sbdroprecord(struct sockbuf *sb)
1317 {
1318 struct mbuf *m, *mn;
1319
1320 KASSERT(solocked(sb->sb_so));
1321
1322 m = sb->sb_mb;
1323 if (m) {
1324 sb->sb_mb = m->m_nextpkt;
1325 do {
1326 sbfree(sb, m);
1327 MFREE(m, mn);
1328 } while ((m = mn) != NULL);
1329 }
1330 SB_EMPTY_FIXUP(sb);
1331 }
1332
1333 /*
1334 * Create a "control" mbuf containing the specified data
1335 * with the specified type for presentation on a socket buffer.
1336 */
1337 struct mbuf *
1338 sbcreatecontrol1(void **p, int size, int type, int level, int flags)
1339 {
1340 struct cmsghdr *cp;
1341 struct mbuf *m;
1342 int space = CMSG_SPACE(size);
1343
1344 if ((flags & M_DONTWAIT) && space > MCLBYTES) {
1345 printf("%s: message too large %d\n", __func__, space);
1346 return NULL;
1347 }
1348
1349 if ((m = m_get(flags, MT_CONTROL)) == NULL)
1350 return NULL;
1351 if (space > MLEN) {
1352 if (space > MCLBYTES)
1353 MEXTMALLOC(m, space, M_WAITOK);
1354 else
1355 MCLGET(m, flags);
1356 if ((m->m_flags & M_EXT) == 0) {
1357 m_free(m);
1358 return NULL;
1359 }
1360 }
1361 cp = mtod(m, struct cmsghdr *);
1362 *p = CMSG_DATA(cp);
1363 m->m_len = space;
1364 cp->cmsg_len = CMSG_LEN(size);
1365 cp->cmsg_level = level;
1366 cp->cmsg_type = type;
1367 return m;
1368 }
1369
1370 struct mbuf *
1371 sbcreatecontrol(void *p, int size, int type, int level)
1372 {
1373 struct mbuf *m;
1374 void *v;
1375
1376 m = sbcreatecontrol1(&v, size, type, level, M_DONTWAIT);
1377 if (m == NULL)
1378 return NULL;
1379 memcpy(v, p, size);
1380 return m;
1381 }
1382
1383 void
1384 solockretry(struct socket *so, kmutex_t *lock)
1385 {
1386
1387 while (lock != so->so_lock) {
1388 mutex_exit(lock);
1389 lock = so->so_lock;
1390 mutex_enter(lock);
1391 }
1392 }
1393
1394 bool
1395 solocked(struct socket *so)
1396 {
1397
1398 return mutex_owned(so->so_lock);
1399 }
1400
1401 bool
1402 solocked2(struct socket *so1, struct socket *so2)
1403 {
1404 kmutex_t *lock;
1405
1406 lock = so1->so_lock;
1407 if (lock != so2->so_lock)
1408 return false;
1409 return mutex_owned(lock);
1410 }
1411
1412 /*
1413 * sosetlock: assign a default lock to a new socket.
1414 */
1415 void
1416 sosetlock(struct socket *so)
1417 {
1418 if (so->so_lock == NULL) {
1419 kmutex_t *lock = softnet_lock;
1420
1421 so->so_lock = lock;
1422 mutex_obj_hold(lock);
1423 }
1424 }
1425
1426 /*
1427 * Set lock on sockbuf sb; sleep if lock is already held.
1428 * Unless SB_NOINTR is set on sockbuf, sleep is interruptible.
1429 * Returns error without lock if sleep is interrupted.
1430 */
1431 int
1432 sblock(struct sockbuf *sb, int wf)
1433 {
1434 struct socket *so;
1435 kmutex_t *lock;
1436 int error;
1437
1438 KASSERT(solocked(sb->sb_so));
1439
1440 for (;;) {
1441 if (__predict_true((sb->sb_flags & SB_LOCK) == 0)) {
1442 sb->sb_flags |= SB_LOCK;
1443 return 0;
1444 }
1445 if (wf != M_WAITOK)
1446 return EWOULDBLOCK;
1447 so = sb->sb_so;
1448 lock = so->so_lock;
1449 if ((sb->sb_flags & SB_NOINTR) != 0) {
1450 cv_wait(&so->so_cv, lock);
1451 error = 0;
1452 } else
1453 error = cv_wait_sig(&so->so_cv, lock);
1454 if (__predict_false(lock != so->so_lock))
1455 solockretry(so, lock);
1456 if (error != 0)
1457 return error;
1458 }
1459 }
1460
1461 void
1462 sbunlock(struct sockbuf *sb)
1463 {
1464 struct socket *so;
1465
1466 so = sb->sb_so;
1467
1468 KASSERT(solocked(so));
1469 KASSERT((sb->sb_flags & SB_LOCK) != 0);
1470
1471 sb->sb_flags &= ~SB_LOCK;
1472 cv_broadcast(&so->so_cv);
1473 }
1474
1475 int
1476 sowait(struct socket *so, bool catch, int timo)
1477 {
1478 kmutex_t *lock;
1479 int error;
1480
1481 KASSERT(solocked(so));
1482 KASSERT(catch || timo != 0);
1483
1484 lock = so->so_lock;
1485 if (catch)
1486 error = cv_timedwait_sig(&so->so_cv, lock, timo);
1487 else
1488 error = cv_timedwait(&so->so_cv, lock, timo);
1489 if (__predict_false(lock != so->so_lock))
1490 solockretry(so, lock);
1491 return error;
1492 }
1493