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