xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp_fusion.c (revision 4fceebdf03eeac0d7c58a4f70cc19b00a8c40a73)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/debug.h>
33 #include <sys/sdt.h>
34 #include <sys/cmn_err.h>
35 #include <sys/tihdr.h>
36 
37 #include <inet/common.h>
38 #include <inet/ip.h>
39 #include <inet/ip_impl.h>
40 #include <inet/tcp.h>
41 #include <inet/tcp_impl.h>
42 #include <inet/ipsec_impl.h>
43 #include <inet/ipclassifier.h>
44 #include <inet/ipp_common.h>
45 
46 /*
47  * This file implements TCP fusion - a protocol-less data path for TCP
48  * loopback connections.  The fusion of two local TCP endpoints occurs
49  * at connection establishment time.  Various conditions (see details
50  * in tcp_fuse()) need to be met for fusion to be successful.  If it
51  * fails, we fall back to the regular TCP data path; if it succeeds,
52  * both endpoints proceed to use tcp_fuse_output() as the transmit path.
53  * tcp_fuse_output() enqueues application data directly onto the peer's
54  * receive queue; no protocol processing is involved.  After enqueueing
55  * the data, the sender can either push (putnext) data up the receiver's
56  * read queue; or the sender can simply return and let the receiver
57  * retrieve the enqueued data via the synchronous streams entry point
58  * tcp_fuse_rrw().  The latter path is taken if synchronous streams is
59  * enabled (the default).  It is disabled if sockfs no longer resides
60  * directly on top of tcp module due to a module insertion or removal.
61  * It also needs to be temporarily disabled when sending urgent data
62  * because the tcp_fuse_rrw() path bypasses the M_PROTO processing done
63  * by strsock_proto() hook.
64  *
65  * Sychronization is handled by squeue and the mutex tcp_non_sq_lock.
66  * One of the requirements for fusion to succeed is that both endpoints
67  * need to be using the same squeue.  This ensures that neither side
68  * can disappear while the other side is still sending data.  By itself,
69  * squeue is not sufficient for guaranteeing safety when synchronous
70  * streams is enabled.  The reason is that tcp_fuse_rrw() doesn't enter
71  * the squeue and its access to tcp_rcv_list and other fusion-related
72  * fields needs to be sychronized with the sender.  tcp_non_sq_lock is
73  * used for this purpose.  When there is urgent data, the sender needs
74  * to push the data up the receiver's streams read queue.  In order to
75  * avoid holding the tcp_non_sq_lock across putnext(), the sender sets
76  * the peer tcp's tcp_fuse_syncstr_plugged bit and releases tcp_non_sq_lock
77  * (see macro TCP_FUSE_SYNCSTR_PLUG_DRAIN()).  If tcp_fuse_rrw() enters
78  * after this point, it will see that synchronous streams is plugged and
79  * will wait on tcp_fuse_plugcv.  After the sender has finished pushing up
80  * all urgent data, it will clear the tcp_fuse_syncstr_plugged bit using
81  * TCP_FUSE_SYNCSTR_UNPLUG_DRAIN().  This will cause any threads waiting
82  * on tcp_fuse_plugcv to return EBUSY, and in turn cause strget() to call
83  * getq_noenab() to dequeue data from the stream head instead.  Once the
84  * data on the stream head has been consumed, tcp_fuse_rrw() may again
85  * be used to process tcp_rcv_list.  However, if TCP_FUSE_SYNCSTR_STOP()
86  * has been called, all future calls to tcp_fuse_rrw() will return EBUSY,
87  * effectively disabling synchronous streams.
88  *
89  * The following note applies only to the synchronous streams mode.
90  *
91  * Flow control is done by checking the size of receive buffer and
92  * the number of data blocks, both set to different limits.  This is
93  * different than regular streams flow control where cumulative size
94  * check dominates block count check -- streams queue high water mark
95  * typically represents bytes.  Each enqueue triggers notifications
96  * to the receiving process; a build up of data blocks indicates a
97  * slow receiver and the sender should be blocked or informed at the
98  * earliest moment instead of further wasting system resources.  In
99  * effect, this is equivalent to limiting the number of outstanding
100  * segments in flight.
101  */
102 
103 /*
104  * Macros that determine whether or not IP processing is needed for TCP.
105  */
106 #define	TCP_IPOPT_POLICY_V4(tcp)					\
107 	((tcp)->tcp_ipversion == IPV4_VERSION &&			\
108 	((tcp)->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH ||		\
109 	CONN_OUTBOUND_POLICY_PRESENT((tcp)->tcp_connp) ||		\
110 	CONN_INBOUND_POLICY_PRESENT((tcp)->tcp_connp)))
111 
112 #define	TCP_IPOPT_POLICY_V6(tcp)					\
113 	((tcp)->tcp_ipversion == IPV6_VERSION &&			\
114 	((tcp)->tcp_ip_hdr_len != IPV6_HDR_LEN ||			\
115 	CONN_OUTBOUND_POLICY_PRESENT_V6((tcp)->tcp_connp) ||		\
116 	CONN_INBOUND_POLICY_PRESENT_V6((tcp)->tcp_connp)))
117 
118 #define	TCP_LOOPBACK_IP(tcp)						\
119 	(TCP_IPOPT_POLICY_V4(tcp) || TCP_IPOPT_POLICY_V6(tcp) ||	\
120 	!CONN_IS_LSO_MD_FASTPATH((tcp)->tcp_connp))
121 
122 /*
123  * Setting this to false means we disable fusion altogether and
124  * loopback connections would go through the protocol paths.
125  */
126 boolean_t do_tcp_fusion = B_TRUE;
127 
128 /*
129  * Enabling this flag allows sockfs to retrieve data directly
130  * from a fused tcp endpoint using synchronous streams interface.
131  */
132 boolean_t do_tcp_direct_sockfs = B_TRUE;
133 
134 /*
135  * This is the minimum amount of outstanding writes allowed on
136  * a synchronous streams-enabled receiving endpoint before the
137  * sender gets flow-controlled.  Setting this value to 0 means
138  * that the data block limit is equivalent to the byte count
139  * limit, which essentially disables the check.
140  */
141 #define	TCP_FUSION_RCV_UNREAD_MIN	8
142 uint_t tcp_fusion_rcv_unread_min = TCP_FUSION_RCV_UNREAD_MIN;
143 
144 static void	tcp_fuse_syncstr_enable(tcp_t *);
145 static void	tcp_fuse_syncstr_disable(tcp_t *);
146 static void	strrput_sig(queue_t *, boolean_t);
147 
148 /*
149  * This routine gets called by the eager tcp upon changing state from
150  * SYN_RCVD to ESTABLISHED.  It fuses a direct path between itself
151  * and the active connect tcp such that the regular tcp processings
152  * may be bypassed under allowable circumstances.  Because the fusion
153  * requires both endpoints to be in the same squeue, it does not work
154  * for simultaneous active connects because there is no easy way to
155  * switch from one squeue to another once the connection is created.
156  * This is different from the eager tcp case where we assign it the
157  * same squeue as the one given to the active connect tcp during open.
158  */
159 void
160 tcp_fuse(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph)
161 {
162 	conn_t *peer_connp, *connp = tcp->tcp_connp;
163 	tcp_t *peer_tcp;
164 
165 	ASSERT(!tcp->tcp_fused);
166 	ASSERT(tcp->tcp_loopback);
167 	ASSERT(tcp->tcp_loopback_peer == NULL);
168 	/*
169 	 * We need to inherit q_hiwat of the listener tcp, but we can't
170 	 * really use tcp_listener since we get here after sending up
171 	 * T_CONN_IND and tcp_wput_accept() may be called independently,
172 	 * at which point tcp_listener is cleared; this is why we use
173 	 * tcp_saved_listener.  The listener itself is guaranteed to be
174 	 * around until tcp_accept_finish() is called on this eager --
175 	 * this won't happen until we're done since we're inside the
176 	 * eager's perimeter now.
177 	 */
178 	ASSERT(tcp->tcp_saved_listener != NULL);
179 
180 	/*
181 	 * Lookup peer endpoint; search for the remote endpoint having
182 	 * the reversed address-port quadruplet in ESTABLISHED state,
183 	 * which is guaranteed to be unique in the system.  Zone check
184 	 * is applied accordingly for loopback address, but not for
185 	 * local address since we want fusion to happen across Zones.
186 	 */
187 	if (tcp->tcp_ipversion == IPV4_VERSION) {
188 		peer_connp = ipcl_conn_tcp_lookup_reversed_ipv4(connp,
189 		    (ipha_t *)iphdr, tcph);
190 	} else {
191 		peer_connp = ipcl_conn_tcp_lookup_reversed_ipv6(connp,
192 		    (ip6_t *)iphdr, tcph);
193 	}
194 
195 	/*
196 	 * We can only proceed if peer exists, resides in the same squeue
197 	 * as our conn and is not raw-socket.  The squeue assignment of
198 	 * this eager tcp was done earlier at the time of SYN processing
199 	 * in ip_fanout_tcp{_v6}.  Note that similar squeues by itself
200 	 * doesn't guarantee a safe condition to fuse, hence we perform
201 	 * additional tests below.
202 	 */
203 	ASSERT(peer_connp == NULL || peer_connp != connp);
204 	if (peer_connp == NULL || peer_connp->conn_sqp != connp->conn_sqp ||
205 	    !IPCL_IS_TCP(peer_connp)) {
206 		if (peer_connp != NULL) {
207 			TCP_STAT(tcp_fusion_unqualified);
208 			CONN_DEC_REF(peer_connp);
209 		}
210 		return;
211 	}
212 	peer_tcp = peer_connp->conn_tcp;	/* active connect tcp */
213 
214 	ASSERT(peer_tcp != NULL && peer_tcp != tcp && !peer_tcp->tcp_fused);
215 	ASSERT(peer_tcp->tcp_loopback && peer_tcp->tcp_loopback_peer == NULL);
216 	ASSERT(peer_connp->conn_sqp == connp->conn_sqp);
217 
218 	/*
219 	 * Fuse the endpoints; we perform further checks against both
220 	 * tcp endpoints to ensure that a fusion is allowed to happen.
221 	 * In particular we bail out for non-simple TCP/IP or if IPsec/
222 	 * IPQoS policy/kernel SSL exists.
223 	 */
224 	if (!tcp->tcp_unfusable && !peer_tcp->tcp_unfusable &&
225 	    !TCP_LOOPBACK_IP(tcp) && !TCP_LOOPBACK_IP(peer_tcp) &&
226 	    tcp->tcp_kssl_ent == NULL &&
227 	    !IPP_ENABLED(IPP_LOCAL_OUT|IPP_LOCAL_IN)) {
228 		mblk_t *mp;
229 		struct stroptions *stropt;
230 		queue_t *peer_rq = peer_tcp->tcp_rq;
231 
232 		ASSERT(!TCP_IS_DETACHED(peer_tcp) && peer_rq != NULL);
233 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
234 		ASSERT(peer_tcp->tcp_fused_sigurg_mp == NULL);
235 		ASSERT(tcp->tcp_kssl_ctx == NULL);
236 
237 		/*
238 		 * We need to drain data on both endpoints during unfuse.
239 		 * If we need to send up SIGURG at the time of draining,
240 		 * we want to be sure that an mblk is readily available.
241 		 * This is why we pre-allocate the M_PCSIG mblks for both
242 		 * endpoints which will only be used during/after unfuse.
243 		 */
244 		if ((mp = allocb(1, BPRI_HI)) == NULL)
245 			goto failed;
246 
247 		tcp->tcp_fused_sigurg_mp = mp;
248 
249 		if ((mp = allocb(1, BPRI_HI)) == NULL)
250 			goto failed;
251 
252 		peer_tcp->tcp_fused_sigurg_mp = mp;
253 
254 		/* Allocate M_SETOPTS mblk */
255 		if ((mp = allocb(sizeof (*stropt), BPRI_HI)) == NULL)
256 			goto failed;
257 
258 		/* Fuse both endpoints */
259 		peer_tcp->tcp_loopback_peer = tcp;
260 		tcp->tcp_loopback_peer = peer_tcp;
261 		peer_tcp->tcp_fused = tcp->tcp_fused = B_TRUE;
262 
263 		/*
264 		 * We never use regular tcp paths in fusion and should
265 		 * therefore clear tcp_unsent on both endpoints.  Having
266 		 * them set to non-zero values means asking for trouble
267 		 * especially after unfuse, where we may end up sending
268 		 * through regular tcp paths which expect xmit_list and
269 		 * friends to be correctly setup.
270 		 */
271 		peer_tcp->tcp_unsent = tcp->tcp_unsent = 0;
272 
273 		tcp_timers_stop(tcp);
274 		tcp_timers_stop(peer_tcp);
275 
276 		/*
277 		 * At this point we are a detached eager tcp and therefore
278 		 * don't have a queue assigned to us until accept happens.
279 		 * In the mean time the peer endpoint may immediately send
280 		 * us data as soon as fusion is finished, and we need to be
281 		 * able to flow control it in case it sends down huge amount
282 		 * of data while we're still detached.  To prevent that we
283 		 * inherit the listener's q_hiwat value; this is temporary
284 		 * since we'll repeat the process in tcp_accept_finish().
285 		 */
286 		(void) tcp_fuse_set_rcv_hiwat(tcp,
287 		    tcp->tcp_saved_listener->tcp_rq->q_hiwat);
288 
289 		/*
290 		 * Set the stream head's write offset value to zero since we
291 		 * won't be needing any room for TCP/IP headers; tell it to
292 		 * not break up the writes (this would reduce the amount of
293 		 * work done by kmem); and configure our receive buffer.
294 		 * Note that we can only do this for the active connect tcp
295 		 * since our eager is still detached; it will be dealt with
296 		 * later in tcp_accept_finish().
297 		 */
298 		DB_TYPE(mp) = M_SETOPTS;
299 		mp->b_wptr += sizeof (*stropt);
300 
301 		stropt = (struct stroptions *)mp->b_rptr;
302 		stropt->so_flags = SO_MAXBLK | SO_WROFF | SO_HIWAT;
303 		stropt->so_maxblk = tcp_maxpsz_set(peer_tcp, B_FALSE);
304 		stropt->so_wroff = 0;
305 
306 		/*
307 		 * Record the stream head's high water mark for
308 		 * peer endpoint; this is used for flow-control
309 		 * purposes in tcp_fuse_output().
310 		 */
311 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(peer_tcp,
312 		    peer_rq->q_hiwat);
313 
314 		/* Send the options up */
315 		putnext(peer_rq, mp);
316 	} else {
317 		TCP_STAT(tcp_fusion_unqualified);
318 	}
319 	CONN_DEC_REF(peer_connp);
320 	return;
321 
322 failed:
323 	if (tcp->tcp_fused_sigurg_mp != NULL) {
324 		freeb(tcp->tcp_fused_sigurg_mp);
325 		tcp->tcp_fused_sigurg_mp = NULL;
326 	}
327 	if (peer_tcp->tcp_fused_sigurg_mp != NULL) {
328 		freeb(peer_tcp->tcp_fused_sigurg_mp);
329 		peer_tcp->tcp_fused_sigurg_mp = NULL;
330 	}
331 	CONN_DEC_REF(peer_connp);
332 }
333 
334 /*
335  * Unfuse a previously-fused pair of tcp loopback endpoints.
336  */
337 void
338 tcp_unfuse(tcp_t *tcp)
339 {
340 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
341 
342 	ASSERT(tcp->tcp_fused && peer_tcp != NULL);
343 	ASSERT(peer_tcp->tcp_fused && peer_tcp->tcp_loopback_peer == tcp);
344 	ASSERT(tcp->tcp_connp->conn_sqp == peer_tcp->tcp_connp->conn_sqp);
345 	ASSERT(tcp->tcp_unsent == 0 && peer_tcp->tcp_unsent == 0);
346 	ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
347 	ASSERT(peer_tcp->tcp_fused_sigurg_mp != NULL);
348 
349 	/*
350 	 * We disable synchronous streams, drain any queued data and
351 	 * clear tcp_direct_sockfs.  The synchronous streams entry
352 	 * points will become no-ops after this point.
353 	 */
354 	tcp_fuse_disable_pair(tcp, B_TRUE);
355 
356 	/*
357 	 * Update th_seq and th_ack in the header template
358 	 */
359 	U32_TO_ABE32(tcp->tcp_snxt, tcp->tcp_tcph->th_seq);
360 	U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
361 	U32_TO_ABE32(peer_tcp->tcp_snxt, peer_tcp->tcp_tcph->th_seq);
362 	U32_TO_ABE32(peer_tcp->tcp_rnxt, peer_tcp->tcp_tcph->th_ack);
363 
364 	/* Unfuse the endpoints */
365 	peer_tcp->tcp_fused = tcp->tcp_fused = B_FALSE;
366 	peer_tcp->tcp_loopback_peer = tcp->tcp_loopback_peer = NULL;
367 }
368 
369 /*
370  * Fusion output routine for urgent data.  This routine is called by
371  * tcp_fuse_output() for handling non-M_DATA mblks.
372  */
373 void
374 tcp_fuse_output_urg(tcp_t *tcp, mblk_t *mp)
375 {
376 	mblk_t *mp1;
377 	struct T_exdata_ind *tei;
378 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
379 	mblk_t *head, *prev_head = NULL;
380 
381 	ASSERT(tcp->tcp_fused);
382 	ASSERT(peer_tcp != NULL && peer_tcp->tcp_loopback_peer == tcp);
383 	ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
384 	ASSERT(mp->b_cont != NULL && DB_TYPE(mp->b_cont) == M_DATA);
385 	ASSERT(MBLKL(mp) >= sizeof (*tei) && MBLKL(mp->b_cont) > 0);
386 
387 	/*
388 	 * Urgent data arrives in the form of T_EXDATA_REQ from above.
389 	 * Each occurence denotes a new urgent pointer.  For each new
390 	 * urgent pointer we signal (SIGURG) the receiving app to indicate
391 	 * that it needs to go into urgent mode.  This is similar to the
392 	 * urgent data handling in the regular tcp.  We don't need to keep
393 	 * track of where the urgent pointer is, because each T_EXDATA_REQ
394 	 * "advances" the urgent pointer for us.
395 	 *
396 	 * The actual urgent data carried by T_EXDATA_REQ is then prepended
397 	 * by a T_EXDATA_IND before being enqueued behind any existing data
398 	 * destined for the receiving app.  There is only a single urgent
399 	 * pointer (out-of-band mark) for a given tcp.  If the new urgent
400 	 * data arrives before the receiving app reads some existing urgent
401 	 * data, the previous marker is lost.  This behavior is emulated
402 	 * accordingly below, by removing any existing T_EXDATA_IND messages
403 	 * and essentially converting old urgent data into non-urgent.
404 	 */
405 	ASSERT(tcp->tcp_valid_bits & TCP_URG_VALID);
406 	/* Let sender get out of urgent mode */
407 	tcp->tcp_valid_bits &= ~TCP_URG_VALID;
408 
409 	/*
410 	 * This flag indicates that a signal needs to be sent up.
411 	 * This flag will only get cleared once SIGURG is delivered and
412 	 * is not affected by the tcp_fused flag -- delivery will still
413 	 * happen even after an endpoint is unfused, to handle the case
414 	 * where the sending endpoint immediately closes/unfuses after
415 	 * sending urgent data and the accept is not yet finished.
416 	 */
417 	peer_tcp->tcp_fused_sigurg = B_TRUE;
418 
419 	/* Reuse T_EXDATA_REQ mblk for T_EXDATA_IND */
420 	DB_TYPE(mp) = M_PROTO;
421 	tei = (struct T_exdata_ind *)mp->b_rptr;
422 	tei->PRIM_type = T_EXDATA_IND;
423 	tei->MORE_flag = 0;
424 	mp->b_wptr = (uchar_t *)&tei[1];
425 
426 	TCP_STAT(tcp_fusion_urg);
427 	BUMP_MIB(&tcp_mib, tcpOutUrg);
428 
429 	head = peer_tcp->tcp_rcv_list;
430 	while (head != NULL) {
431 		/*
432 		 * Remove existing T_EXDATA_IND, keep the data which follows
433 		 * it and relink our list.  Note that we don't modify the
434 		 * tcp_rcv_last_tail since it never points to T_EXDATA_IND.
435 		 */
436 		if (DB_TYPE(head) != M_DATA) {
437 			mp1 = head;
438 
439 			ASSERT(DB_TYPE(mp1->b_cont) == M_DATA);
440 			head = mp1->b_cont;
441 			mp1->b_cont = NULL;
442 			head->b_next = mp1->b_next;
443 			mp1->b_next = NULL;
444 			if (prev_head != NULL)
445 				prev_head->b_next = head;
446 			if (peer_tcp->tcp_rcv_list == mp1)
447 				peer_tcp->tcp_rcv_list = head;
448 			if (peer_tcp->tcp_rcv_last_head == mp1)
449 				peer_tcp->tcp_rcv_last_head = head;
450 			freeb(mp1);
451 		}
452 		prev_head = head;
453 		head = head->b_next;
454 	}
455 }
456 
457 /*
458  * Fusion output routine, called by tcp_output() and tcp_wput_proto().
459  * If we are modifying any member that can be changed outside the squeue,
460  * like tcp_flow_stopped, we need to take tcp_non_sq_lock.
461  */
462 boolean_t
463 tcp_fuse_output(tcp_t *tcp, mblk_t *mp, uint32_t send_size)
464 {
465 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
466 	uint_t max_unread;
467 	boolean_t flow_stopped;
468 	boolean_t urgent = (DB_TYPE(mp) != M_DATA);
469 	mblk_t *mp1 = mp;
470 	ill_t *ilp, *olp;
471 	ipha_t *ipha;
472 	ip6_t *ip6h;
473 	tcph_t *tcph;
474 	uint_t ip_hdr_len;
475 	uint32_t seq;
476 	uint32_t recv_size = send_size;
477 
478 	ASSERT(tcp->tcp_fused);
479 	ASSERT(peer_tcp != NULL && peer_tcp->tcp_loopback_peer == tcp);
480 	ASSERT(tcp->tcp_connp->conn_sqp == peer_tcp->tcp_connp->conn_sqp);
481 	ASSERT(DB_TYPE(mp) == M_DATA || DB_TYPE(mp) == M_PROTO ||
482 	    DB_TYPE(mp) == M_PCPROTO);
483 
484 	max_unread = peer_tcp->tcp_fuse_rcv_unread_hiwater;
485 
486 	/* If this connection requires IP, unfuse and use regular path */
487 	if (TCP_LOOPBACK_IP(tcp) || TCP_LOOPBACK_IP(peer_tcp) ||
488 	    IPP_ENABLED(IPP_LOCAL_OUT|IPP_LOCAL_IN)) {
489 		TCP_STAT(tcp_fusion_aborted);
490 		goto unfuse;
491 	}
492 
493 	if (send_size == 0) {
494 		freemsg(mp);
495 		return (B_TRUE);
496 	}
497 
498 	/*
499 	 * Handle urgent data; we either send up SIGURG to the peer now
500 	 * or do it later when we drain, in case the peer is detached
501 	 * or if we're short of memory for M_PCSIG mblk.
502 	 */
503 	if (urgent) {
504 		/*
505 		 * We stop synchronous streams when we have urgent data
506 		 * queued to prevent tcp_fuse_rrw() from pulling it.  If
507 		 * for some reasons the urgent data can't be delivered
508 		 * below, synchronous streams will remain stopped until
509 		 * someone drains the tcp_rcv_list.
510 		 */
511 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(peer_tcp);
512 		tcp_fuse_output_urg(tcp, mp);
513 
514 		mp1 = mp->b_cont;
515 	}
516 
517 	if (tcp->tcp_ipversion == IPV4_VERSION &&
518 	    (HOOKS4_INTERESTED_LOOPBACK_IN ||
519 	    HOOKS4_INTERESTED_LOOPBACK_OUT) ||
520 	    tcp->tcp_ipversion == IPV6_VERSION &&
521 	    (HOOKS6_INTERESTED_LOOPBACK_IN ||
522 	    HOOKS6_INTERESTED_LOOPBACK_OUT)) {
523 		/*
524 		 * Build ip and tcp header to satisfy FW_HOOKS.
525 		 * We only build it when any hook is present.
526 		 */
527 		if ((mp1 = tcp_xmit_mp(tcp, mp1, tcp->tcp_mss, NULL, NULL,
528 		    tcp->tcp_snxt, B_TRUE, NULL, B_FALSE)) == NULL)
529 			/* If tcp_xmit_mp fails, use regular path */
530 			goto unfuse;
531 
532 		ASSERT(peer_tcp->tcp_connp->conn_ire_cache->ire_ipif != NULL);
533 		olp = peer_tcp->tcp_connp->conn_ire_cache->ire_ipif->ipif_ill;
534 		/* PFHooks: LOOPBACK_OUT */
535 		if (tcp->tcp_ipversion == IPV4_VERSION) {
536 			ipha = (ipha_t *)mp1->b_rptr;
537 
538 			DTRACE_PROBE4(ip4__loopback__out__start,
539 			    ill_t *, NULL, ill_t *, olp,
540 			    ipha_t *, ipha, mblk_t *, mp1);
541 			FW_HOOKS(ip4_loopback_out_event,
542 			    ipv4firewall_loopback_out,
543 			    NULL, olp, ipha, mp1, mp1);
544 			DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, mp1);
545 		} else {
546 			ip6h = (ip6_t *)mp1->b_rptr;
547 
548 			DTRACE_PROBE4(ip6__loopback__out__start,
549 			    ill_t *, NULL, ill_t *, olp,
550 			    ip6_t *, ip6h, mblk_t *, mp1);
551 			FW_HOOKS6(ip6_loopback_out_event,
552 			    ipv6firewall_loopback_out,
553 			    NULL, olp, ip6h, mp1, mp1);
554 			DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, mp1);
555 		}
556 		if (mp1 == NULL)
557 			goto unfuse;
558 
559 
560 		/* PFHooks: LOOPBACK_IN */
561 		ASSERT(tcp->tcp_connp->conn_ire_cache->ire_ipif != NULL);
562 		ilp = tcp->tcp_connp->conn_ire_cache->ire_ipif->ipif_ill;
563 
564 		if (tcp->tcp_ipversion == IPV4_VERSION) {
565 			DTRACE_PROBE4(ip4__loopback__in__start,
566 			    ill_t *, ilp, ill_t *, NULL,
567 			    ipha_t *, ipha, mblk_t *, mp1);
568 			FW_HOOKS(ip4_loopback_in_event,
569 			    ipv4firewall_loopback_in,
570 			    ilp, NULL, ipha, mp1, mp1);
571 			DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, mp1);
572 			if (mp1 == NULL)
573 				goto unfuse;
574 
575 			ip_hdr_len = IPH_HDR_LENGTH(ipha);
576 		} else {
577 			DTRACE_PROBE4(ip6__loopback__in__start,
578 			    ill_t *, ilp, ill_t *, NULL,
579 			    ip6_t *, ip6h, mblk_t *, mp1);
580 			FW_HOOKS6(ip6_loopback_in_event,
581 			    ipv6firewall_loopback_in,
582 			    ilp, NULL, ip6h, mp1, mp1);
583 			DTRACE_PROBE1(ip6__loopback__in__end, mblk_t *, mp1);
584 			if (mp1 == NULL)
585 				goto unfuse;
586 
587 			ip_hdr_len = ip_hdr_length_v6(mp1, ip6h);
588 		}
589 
590 		/* Data length might be changed by FW_HOOKS */
591 		tcph = (tcph_t *)&mp1->b_rptr[ip_hdr_len];
592 		seq = ABE32_TO_U32(tcph->th_seq);
593 		recv_size += seq - tcp->tcp_snxt;
594 
595 		/*
596 		 * The message duplicated by tcp_xmit_mp is freed.
597 		 * Note: the original message passed in remains unchanged.
598 		 */
599 		freemsg(mp1);
600 	}
601 
602 	mutex_enter(&peer_tcp->tcp_non_sq_lock);
603 	/*
604 	 * Wake up and signal the peer; it is okay to do this before
605 	 * enqueueing because we are holding the lock.  One of the
606 	 * advantages of synchronous streams is the ability for us to
607 	 * find out when the application performs a read on the socket,
608 	 * by way of tcp_fuse_rrw() entry point being called.  Every
609 	 * data that gets enqueued onto the receiver is treated as if
610 	 * it has arrived at the receiving endpoint, thus generating
611 	 * SIGPOLL/SIGIO for asynchronous socket just as in the strrput()
612 	 * case.  However, we only wake up the application when necessary,
613 	 * i.e. during the first enqueue.  When tcp_fuse_rrw() is called
614 	 * it will send everything upstream.
615 	 */
616 	if (peer_tcp->tcp_direct_sockfs && !urgent &&
617 	    !TCP_IS_DETACHED(peer_tcp)) {
618 		if (peer_tcp->tcp_rcv_list == NULL)
619 			STR_WAKEUP_SET(STREAM(peer_tcp->tcp_rq));
620 		/* Update poll events and send SIGPOLL/SIGIO if necessary */
621 		STR_SENDSIG(STREAM(peer_tcp->tcp_rq));
622 	}
623 
624 	/*
625 	 * Enqueue data into the peer's receive list; we may or may not
626 	 * drain the contents depending on the conditions below.
627 	 */
628 	tcp_rcv_enqueue(peer_tcp, mp, recv_size);
629 
630 	/* In case it wrapped around and also to keep it constant */
631 	peer_tcp->tcp_rwnd += recv_size;
632 
633 	/*
634 	 * Exercise flow-control when needed; we will get back-enabled
635 	 * in either tcp_accept_finish(), tcp_unfuse(), or tcp_fuse_rrw().
636 	 * If tcp_direct_sockfs is on or if the peer endpoint is detached,
637 	 * we emulate streams flow control by checking the peer's queue
638 	 * size and high water mark; otherwise we simply use canputnext()
639 	 * to decide if we need to stop our flow.
640 	 *
641 	 * The outstanding unread data block check does not apply for a
642 	 * detached receiver; this is to avoid unnecessary blocking of the
643 	 * sender while the accept is currently in progress and is quite
644 	 * similar to the regular tcp.
645 	 */
646 	if (TCP_IS_DETACHED(peer_tcp) || max_unread == 0)
647 		max_unread = UINT_MAX;
648 
649 	/*
650 	 * Since we are accessing our tcp_flow_stopped and might modify it,
651 	 * we need to take tcp->tcp_non_sq_lock. The lock for the highest
652 	 * address is held first. Dropping peer_tcp->tcp_non_sq_lock should
653 	 * not be an issue here since we are within the squeue and the peer
654 	 * won't disappear.
655 	 */
656 	if (tcp > peer_tcp) {
657 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
658 		mutex_enter(&tcp->tcp_non_sq_lock);
659 		mutex_enter(&peer_tcp->tcp_non_sq_lock);
660 	} else {
661 		mutex_enter(&tcp->tcp_non_sq_lock);
662 	}
663 	flow_stopped = tcp->tcp_flow_stopped;
664 	if (!flow_stopped &&
665 	    (((peer_tcp->tcp_direct_sockfs || TCP_IS_DETACHED(peer_tcp)) &&
666 	    (peer_tcp->tcp_rcv_cnt >= peer_tcp->tcp_fuse_rcv_hiwater ||
667 	    ++peer_tcp->tcp_fuse_rcv_unread_cnt >= max_unread)) ||
668 	    (!peer_tcp->tcp_direct_sockfs &&
669 	    !TCP_IS_DETACHED(peer_tcp) && !canputnext(peer_tcp->tcp_rq)))) {
670 		tcp_setqfull(tcp);
671 		flow_stopped = B_TRUE;
672 		TCP_STAT(tcp_fusion_flowctl);
673 		DTRACE_PROBE4(tcp__fuse__output__flowctl, tcp_t *, tcp,
674 		    uint_t, send_size, uint_t, peer_tcp->tcp_rcv_cnt,
675 		    uint_t, peer_tcp->tcp_fuse_rcv_unread_cnt);
676 	} else if (flow_stopped &&
677 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
678 		tcp_clrqfull(tcp);
679 		flow_stopped = B_FALSE;
680 	}
681 	mutex_exit(&tcp->tcp_non_sq_lock);
682 	loopback_packets++;
683 	tcp->tcp_last_sent_len = send_size;
684 
685 	/* Need to adjust the following SNMP MIB-related variables */
686 	tcp->tcp_snxt += send_size;
687 	tcp->tcp_suna = tcp->tcp_snxt;
688 	peer_tcp->tcp_rnxt += recv_size;
689 	peer_tcp->tcp_rack = peer_tcp->tcp_rnxt;
690 
691 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
692 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, send_size);
693 
694 	BUMP_MIB(&tcp_mib, tcpInSegs);
695 	BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
696 	UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, send_size);
697 
698 	BUMP_LOCAL(tcp->tcp_obsegs);
699 	BUMP_LOCAL(peer_tcp->tcp_ibsegs);
700 
701 	mutex_exit(&peer_tcp->tcp_non_sq_lock);
702 
703 	DTRACE_PROBE2(tcp__fuse__output, tcp_t *, tcp, uint_t, send_size);
704 
705 	if (!TCP_IS_DETACHED(peer_tcp)) {
706 		/*
707 		 * Drain the peer's receive queue it has urgent data or if
708 		 * we're not flow-controlled.  There is no need for draining
709 		 * normal data when tcp_direct_sockfs is on because the peer
710 		 * will pull the data via tcp_fuse_rrw().
711 		 */
712 		if (urgent || (!flow_stopped && !peer_tcp->tcp_direct_sockfs)) {
713 			ASSERT(peer_tcp->tcp_rcv_list != NULL);
714 			/*
715 			 * For TLI-based streams, a thread in tcp_accept_swap()
716 			 * can race with us.  That thread will ensure that the
717 			 * correct peer_tcp->tcp_rq is globally visible before
718 			 * peer_tcp->tcp_detached is visible as clear, but we
719 			 * must also ensure that the load of tcp_rq cannot be
720 			 * reordered to be before the tcp_detached check.
721 			 */
722 			membar_consumer();
723 			(void) tcp_fuse_rcv_drain(peer_tcp->tcp_rq, peer_tcp,
724 			    NULL);
725 			/*
726 			 * If synchronous streams was stopped above due
727 			 * to the presence of urgent data, re-enable it.
728 			 */
729 			if (urgent)
730 				TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(peer_tcp);
731 		}
732 	}
733 	return (B_TRUE);
734 unfuse:
735 	tcp_unfuse(tcp);
736 	return (B_FALSE);
737 }
738 
739 /*
740  * This routine gets called to deliver data upstream on a fused or
741  * previously fused tcp loopback endpoint; the latter happens only
742  * when there is a pending SIGURG signal plus urgent data that can't
743  * be sent upstream in the past.
744  */
745 boolean_t
746 tcp_fuse_rcv_drain(queue_t *q, tcp_t *tcp, mblk_t **sigurg_mpp)
747 {
748 	mblk_t *mp;
749 #ifdef DEBUG
750 	uint_t cnt = 0;
751 #endif
752 
753 	ASSERT(tcp->tcp_loopback);
754 	ASSERT(tcp->tcp_fused || tcp->tcp_fused_sigurg);
755 	ASSERT(!tcp->tcp_fused || tcp->tcp_loopback_peer != NULL);
756 	ASSERT(sigurg_mpp != NULL || tcp->tcp_fused);
757 
758 	/* No need for the push timer now, in case it was scheduled */
759 	if (tcp->tcp_push_tid != 0) {
760 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
761 		tcp->tcp_push_tid = 0;
762 	}
763 	/*
764 	 * If there's urgent data sitting in receive list and we didn't
765 	 * get a chance to send up a SIGURG signal, make sure we send
766 	 * it first before draining in order to ensure that SIOCATMARK
767 	 * works properly.
768 	 */
769 	if (tcp->tcp_fused_sigurg) {
770 		/*
771 		 * sigurg_mpp is normally NULL, i.e. when we're still
772 		 * fused and didn't get here because of tcp_unfuse().
773 		 * In this case try hard to allocate the M_PCSIG mblk.
774 		 */
775 		if (sigurg_mpp == NULL &&
776 		    (mp = allocb(1, BPRI_HI)) == NULL &&
777 		    (mp = allocb_tryhard(1)) == NULL) {
778 			/* Alloc failed; try again next time */
779 			tcp->tcp_push_tid = TCP_TIMER(tcp, tcp_push_timer,
780 			    MSEC_TO_TICK(tcp_push_timer_interval));
781 			return (B_TRUE);
782 		} else if (sigurg_mpp != NULL) {
783 			/*
784 			 * Use the supplied M_PCSIG mblk; it means we're
785 			 * either unfused or in the process of unfusing,
786 			 * and the drain must happen now.
787 			 */
788 			mp = *sigurg_mpp;
789 			*sigurg_mpp = NULL;
790 		}
791 		ASSERT(mp != NULL);
792 
793 		tcp->tcp_fused_sigurg = B_FALSE;
794 		/* Send up the signal */
795 		DB_TYPE(mp) = M_PCSIG;
796 		*mp->b_wptr++ = (uchar_t)SIGURG;
797 		putnext(q, mp);
798 		/*
799 		 * Let the regular tcp_rcv_drain() path handle
800 		 * draining the data if we're no longer fused.
801 		 */
802 		if (!tcp->tcp_fused)
803 			return (B_FALSE);
804 	}
805 
806 	/*
807 	 * In the synchronous streams case, we generate SIGPOLL/SIGIO for
808 	 * each M_DATA that gets enqueued onto the receiver.  At this point
809 	 * we are about to drain any queued data via putnext().  In order
810 	 * to avoid extraneous signal generation from strrput(), we set
811 	 * STRGETINPROG flag at the stream head prior to the draining and
812 	 * restore it afterwards.  This masks out signal generation only
813 	 * for M_DATA messages and does not affect urgent data.
814 	 */
815 	if (tcp->tcp_direct_sockfs)
816 		strrput_sig(q, B_FALSE);
817 
818 	/* Drain the data */
819 	while ((mp = tcp->tcp_rcv_list) != NULL) {
820 		tcp->tcp_rcv_list = mp->b_next;
821 		mp->b_next = NULL;
822 #ifdef DEBUG
823 		cnt += msgdsize(mp);
824 #endif
825 		putnext(q, mp);
826 		TCP_STAT(tcp_fusion_putnext);
827 	}
828 
829 	if (tcp->tcp_direct_sockfs)
830 		strrput_sig(q, B_TRUE);
831 
832 	ASSERT(cnt == tcp->tcp_rcv_cnt);
833 	tcp->tcp_rcv_last_head = NULL;
834 	tcp->tcp_rcv_last_tail = NULL;
835 	tcp->tcp_rcv_cnt = 0;
836 	tcp->tcp_fuse_rcv_unread_cnt = 0;
837 	tcp->tcp_rwnd = q->q_hiwat;
838 
839 	return (B_TRUE);
840 }
841 
842 /*
843  * Synchronous stream entry point for sockfs to retrieve
844  * data directly from tcp_rcv_list.
845  * tcp_fuse_rrw() might end up modifying the peer's tcp_flow_stopped,
846  * for which it  must take the tcp_non_sq_lock of the peer as well
847  * making any change. The order of taking the locks is based on
848  * the TCP pointer itself. Before we get the peer we need to take
849  * our tcp_non_sq_lock so that the peer doesn't disappear. However,
850  * we cannot drop the lock if we have to grab the peer's lock (because
851  * of ordering), since the peer might disappear in the interim. So,
852  * we take our tcp_non_sq_lock, get the peer, increment the ref on the
853  * peer's conn, drop all the locks and then take the tcp_non_sq_lock in the
854  * desired order. Incrementing the conn ref on the peer means that the
855  * peer won't disappear when we drop our tcp_non_sq_lock.
856  */
857 int
858 tcp_fuse_rrw(queue_t *q, struiod_t *dp)
859 {
860 	tcp_t *tcp = Q_TO_CONN(q)->conn_tcp;
861 	mblk_t *mp;
862 	tcp_t *peer_tcp;
863 
864 	mutex_enter(&tcp->tcp_non_sq_lock);
865 
866 	/*
867 	 * If tcp_fuse_syncstr_plugged is set, then another thread is moving
868 	 * the underlying data to the stream head.  We need to wait until it's
869 	 * done, then return EBUSY so that strget() will dequeue data from the
870 	 * stream head to ensure data is drained in-order.
871 	 */
872 plugged:
873 	if (tcp->tcp_fuse_syncstr_plugged) {
874 		do {
875 			cv_wait(&tcp->tcp_fuse_plugcv, &tcp->tcp_non_sq_lock);
876 		} while (tcp->tcp_fuse_syncstr_plugged);
877 
878 		mutex_exit(&tcp->tcp_non_sq_lock);
879 		TCP_STAT(tcp_fusion_rrw_plugged);
880 		TCP_STAT(tcp_fusion_rrw_busy);
881 		return (EBUSY);
882 	}
883 
884 	peer_tcp = tcp->tcp_loopback_peer;
885 
886 	/*
887 	 * If someone had turned off tcp_direct_sockfs or if synchronous
888 	 * streams is stopped, we return EBUSY.  This causes strget() to
889 	 * dequeue data from the stream head instead.
890 	 */
891 	if (!tcp->tcp_direct_sockfs || tcp->tcp_fuse_syncstr_stopped) {
892 		mutex_exit(&tcp->tcp_non_sq_lock);
893 		TCP_STAT(tcp_fusion_rrw_busy);
894 		return (EBUSY);
895 	}
896 
897 	/*
898 	 * Grab lock in order. The highest addressed tcp is locked first.
899 	 * We don't do this within the tcp_rcv_list check since if we
900 	 * have to drop the lock, for ordering, then the tcp_rcv_list
901 	 * could change.
902 	 */
903 	if (peer_tcp > tcp) {
904 		CONN_INC_REF(peer_tcp->tcp_connp);
905 		mutex_exit(&tcp->tcp_non_sq_lock);
906 		mutex_enter(&peer_tcp->tcp_non_sq_lock);
907 		mutex_enter(&tcp->tcp_non_sq_lock);
908 		CONN_DEC_REF(peer_tcp->tcp_connp);
909 		/* This might have changed in the interim */
910 		if (tcp->tcp_fuse_syncstr_plugged) {
911 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
912 			goto plugged;
913 		}
914 	} else {
915 		mutex_enter(&peer_tcp->tcp_non_sq_lock);
916 	}
917 
918 	if ((mp = tcp->tcp_rcv_list) != NULL) {
919 
920 		DTRACE_PROBE3(tcp__fuse__rrw, tcp_t *, tcp,
921 		    uint32_t, tcp->tcp_rcv_cnt, ssize_t, dp->d_uio.uio_resid);
922 
923 		tcp->tcp_rcv_list = NULL;
924 		TCP_STAT(tcp_fusion_rrw_msgcnt);
925 
926 		/*
927 		 * At this point nothing should be left in tcp_rcv_list.
928 		 * The only possible case where we would have a chain of
929 		 * b_next-linked messages is urgent data, but we wouldn't
930 		 * be here if that's true since urgent data is delivered
931 		 * via putnext() and synchronous streams is stopped until
932 		 * tcp_fuse_rcv_drain() is finished.
933 		 */
934 		ASSERT(DB_TYPE(mp) == M_DATA && mp->b_next == NULL);
935 
936 		tcp->tcp_rcv_last_head = NULL;
937 		tcp->tcp_rcv_last_tail = NULL;
938 		tcp->tcp_rcv_cnt = 0;
939 		tcp->tcp_fuse_rcv_unread_cnt = 0;
940 
941 		if (peer_tcp->tcp_flow_stopped) {
942 			tcp_clrqfull(peer_tcp);
943 			TCP_STAT(tcp_fusion_backenabled);
944 		}
945 	}
946 	mutex_exit(&peer_tcp->tcp_non_sq_lock);
947 	/*
948 	 * Either we just dequeued everything or we get here from sockfs
949 	 * and have nothing to return; in this case clear RSLEEP.
950 	 */
951 	ASSERT(tcp->tcp_rcv_last_head == NULL);
952 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
953 	ASSERT(tcp->tcp_rcv_cnt == 0);
954 	ASSERT(tcp->tcp_fuse_rcv_unread_cnt == 0);
955 	STR_WAKEUP_CLEAR(STREAM(q));
956 
957 	mutex_exit(&tcp->tcp_non_sq_lock);
958 	dp->d_mp = mp;
959 	return (0);
960 }
961 
962 /*
963  * Synchronous stream entry point used by certain ioctls to retrieve
964  * information about or peek into the tcp_rcv_list.
965  */
966 int
967 tcp_fuse_rinfop(queue_t *q, infod_t *dp)
968 {
969 	tcp_t	*tcp = Q_TO_CONN(q)->conn_tcp;
970 	mblk_t	*mp;
971 	uint_t	cmd = dp->d_cmd;
972 	int	res = 0;
973 	int	error = 0;
974 	struct stdata *stp = STREAM(q);
975 
976 	mutex_enter(&tcp->tcp_non_sq_lock);
977 	/* If shutdown on read has happened, return nothing */
978 	mutex_enter(&stp->sd_lock);
979 	if (stp->sd_flag & STREOF) {
980 		mutex_exit(&stp->sd_lock);
981 		goto done;
982 	}
983 	mutex_exit(&stp->sd_lock);
984 
985 	/*
986 	 * It is OK not to return an answer if tcp_rcv_list is
987 	 * currently not accessible.
988 	 */
989 	if (!tcp->tcp_direct_sockfs || tcp->tcp_fuse_syncstr_stopped ||
990 	    tcp->tcp_fuse_syncstr_plugged || (mp = tcp->tcp_rcv_list) == NULL)
991 		goto done;
992 
993 	if (cmd & INFOD_COUNT) {
994 		/*
995 		 * We have at least one message and
996 		 * could return only one at a time.
997 		 */
998 		dp->d_count++;
999 		res |= INFOD_COUNT;
1000 	}
1001 	if (cmd & INFOD_BYTES) {
1002 		/*
1003 		 * Return size of all data messages.
1004 		 */
1005 		dp->d_bytes += tcp->tcp_rcv_cnt;
1006 		res |= INFOD_BYTES;
1007 	}
1008 	if (cmd & INFOD_FIRSTBYTES) {
1009 		/*
1010 		 * Return size of first data message.
1011 		 */
1012 		dp->d_bytes = msgdsize(mp);
1013 		res |= INFOD_FIRSTBYTES;
1014 		dp->d_cmd &= ~INFOD_FIRSTBYTES;
1015 	}
1016 	if (cmd & INFOD_COPYOUT) {
1017 		mblk_t *mp1;
1018 		int n;
1019 
1020 		if (DB_TYPE(mp) == M_DATA) {
1021 			mp1 = mp;
1022 		} else {
1023 			mp1 = mp->b_cont;
1024 			ASSERT(mp1 != NULL);
1025 		}
1026 
1027 		/*
1028 		 * Return data contents of first message.
1029 		 */
1030 		ASSERT(DB_TYPE(mp1) == M_DATA);
1031 		while (mp1 != NULL && dp->d_uiop->uio_resid > 0) {
1032 			n = MIN(dp->d_uiop->uio_resid, MBLKL(mp1));
1033 			if (n != 0 && (error = uiomove((char *)mp1->b_rptr, n,
1034 			    UIO_READ, dp->d_uiop)) != 0) {
1035 				goto done;
1036 			}
1037 			mp1 = mp1->b_cont;
1038 		}
1039 		res |= INFOD_COPYOUT;
1040 		dp->d_cmd &= ~INFOD_COPYOUT;
1041 	}
1042 done:
1043 	mutex_exit(&tcp->tcp_non_sq_lock);
1044 
1045 	dp->d_res |= res;
1046 
1047 	return (error);
1048 }
1049 
1050 /*
1051  * Enable synchronous streams on a fused tcp loopback endpoint.
1052  */
1053 static void
1054 tcp_fuse_syncstr_enable(tcp_t *tcp)
1055 {
1056 	queue_t *rq = tcp->tcp_rq;
1057 	struct stdata *stp = STREAM(rq);
1058 
1059 	/* We can only enable synchronous streams for sockfs mode */
1060 	tcp->tcp_direct_sockfs = tcp->tcp_issocket && do_tcp_direct_sockfs;
1061 
1062 	if (!tcp->tcp_direct_sockfs)
1063 		return;
1064 
1065 	mutex_enter(&stp->sd_lock);
1066 	mutex_enter(QLOCK(rq));
1067 
1068 	/*
1069 	 * We replace our q_qinfo with one that has the qi_rwp entry point.
1070 	 * Clear SR_SIGALLDATA because we generate the equivalent signal(s)
1071 	 * for every enqueued data in tcp_fuse_output().
1072 	 */
1073 	rq->q_qinfo = &tcp_loopback_rinit;
1074 	rq->q_struiot = tcp_loopback_rinit.qi_struiot;
1075 	stp->sd_struiordq = rq;
1076 	stp->sd_rput_opt &= ~SR_SIGALLDATA;
1077 
1078 	mutex_exit(QLOCK(rq));
1079 	mutex_exit(&stp->sd_lock);
1080 }
1081 
1082 /*
1083  * Disable synchronous streams on a fused tcp loopback endpoint.
1084  */
1085 static void
1086 tcp_fuse_syncstr_disable(tcp_t *tcp)
1087 {
1088 	queue_t *rq = tcp->tcp_rq;
1089 	struct stdata *stp = STREAM(rq);
1090 
1091 	if (!tcp->tcp_direct_sockfs)
1092 		return;
1093 
1094 	mutex_enter(&stp->sd_lock);
1095 	mutex_enter(QLOCK(rq));
1096 
1097 	/*
1098 	 * Reset q_qinfo to point to the default tcp entry points.
1099 	 * Also restore SR_SIGALLDATA so that strrput() can generate
1100 	 * the signals again for future M_DATA messages.
1101 	 */
1102 	rq->q_qinfo = &tcp_rinit;
1103 	rq->q_struiot = tcp_rinit.qi_struiot;
1104 	stp->sd_struiordq = NULL;
1105 	stp->sd_rput_opt |= SR_SIGALLDATA;
1106 	tcp->tcp_direct_sockfs = B_FALSE;
1107 
1108 	mutex_exit(QLOCK(rq));
1109 	mutex_exit(&stp->sd_lock);
1110 }
1111 
1112 /*
1113  * Enable synchronous streams on a pair of fused tcp endpoints.
1114  */
1115 void
1116 tcp_fuse_syncstr_enable_pair(tcp_t *tcp)
1117 {
1118 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
1119 
1120 	ASSERT(tcp->tcp_fused);
1121 	ASSERT(peer_tcp != NULL);
1122 
1123 	tcp_fuse_syncstr_enable(tcp);
1124 	tcp_fuse_syncstr_enable(peer_tcp);
1125 }
1126 
1127 /*
1128  * Allow or disallow signals to be generated by strrput().
1129  */
1130 static void
1131 strrput_sig(queue_t *q, boolean_t on)
1132 {
1133 	struct stdata *stp = STREAM(q);
1134 
1135 	mutex_enter(&stp->sd_lock);
1136 	if (on)
1137 		stp->sd_flag &= ~STRGETINPROG;
1138 	else
1139 		stp->sd_flag |= STRGETINPROG;
1140 	mutex_exit(&stp->sd_lock);
1141 }
1142 
1143 /*
1144  * Disable synchronous streams on a pair of fused tcp endpoints and drain
1145  * any queued data; called either during unfuse or upon transitioning from
1146  * a socket to a stream endpoint due to _SIOCSOCKFALLBACK.
1147  */
1148 void
1149 tcp_fuse_disable_pair(tcp_t *tcp, boolean_t unfusing)
1150 {
1151 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
1152 
1153 	ASSERT(tcp->tcp_fused);
1154 	ASSERT(peer_tcp != NULL);
1155 
1156 	/*
1157 	 * Force any tcp_fuse_rrw() calls to block until we've moved the data
1158 	 * onto the stream head.
1159 	 */
1160 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
1161 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(peer_tcp);
1162 
1163 	/*
1164 	 * Drain any pending data; the detached check is needed because
1165 	 * we may be called as a result of a tcp_unfuse() triggered by
1166 	 * tcp_fuse_output().  Note that in case of a detached tcp, the
1167 	 * draining will happen later after the tcp is unfused.  For non-
1168 	 * urgent data, this can be handled by the regular tcp_rcv_drain().
1169 	 * If we have urgent data sitting in the receive list, we will
1170 	 * need to send up a SIGURG signal first before draining the data.
1171 	 * All of these will be handled by the code in tcp_fuse_rcv_drain()
1172 	 * when called from tcp_rcv_drain().
1173 	 */
1174 	if (!TCP_IS_DETACHED(tcp)) {
1175 		(void) tcp_fuse_rcv_drain(tcp->tcp_rq, tcp,
1176 		    (unfusing ? &tcp->tcp_fused_sigurg_mp : NULL));
1177 	}
1178 	if (!TCP_IS_DETACHED(peer_tcp)) {
1179 		(void) tcp_fuse_rcv_drain(peer_tcp->tcp_rq, peer_tcp,
1180 		    (unfusing ? &peer_tcp->tcp_fused_sigurg_mp : NULL));
1181 	}
1182 
1183 	/*
1184 	 * Make all current and future tcp_fuse_rrw() calls fail with EBUSY.
1185 	 * To ensure threads don't sneak past the checks in tcp_fuse_rrw(),
1186 	 * a given stream must be stopped prior to being unplugged (but the
1187 	 * ordering of operations between the streams is unimportant).
1188 	 */
1189 	TCP_FUSE_SYNCSTR_STOP(tcp);
1190 	TCP_FUSE_SYNCSTR_STOP(peer_tcp);
1191 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
1192 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(peer_tcp);
1193 
1194 	/* Lift up any flow-control conditions */
1195 	if (tcp->tcp_flow_stopped) {
1196 		tcp_clrqfull(tcp);
1197 		TCP_STAT(tcp_fusion_backenabled);
1198 	}
1199 	if (peer_tcp->tcp_flow_stopped) {
1200 		tcp_clrqfull(peer_tcp);
1201 		TCP_STAT(tcp_fusion_backenabled);
1202 	}
1203 
1204 	/* Disable synchronous streams */
1205 	tcp_fuse_syncstr_disable(tcp);
1206 	tcp_fuse_syncstr_disable(peer_tcp);
1207 }
1208 
1209 /*
1210  * Calculate the size of receive buffer for a fused tcp endpoint.
1211  */
1212 size_t
1213 tcp_fuse_set_rcv_hiwat(tcp_t *tcp, size_t rwnd)
1214 {
1215 	ASSERT(tcp->tcp_fused);
1216 
1217 	/* Ensure that value is within the maximum upper bound */
1218 	if (rwnd > tcp_max_buf)
1219 		rwnd = tcp_max_buf;
1220 
1221 	/* Obey the absolute minimum tcp receive high water mark */
1222 	if (rwnd < tcp_sth_rcv_hiwat)
1223 		rwnd = tcp_sth_rcv_hiwat;
1224 
1225 	/*
1226 	 * Round up to system page size in case SO_RCVBUF is modified
1227 	 * after SO_SNDBUF; the latter is also similarly rounded up.
1228 	 */
1229 	rwnd = P2ROUNDUP_TYPED(rwnd, PAGESIZE, size_t);
1230 	tcp->tcp_fuse_rcv_hiwater = rwnd;
1231 	return (rwnd);
1232 }
1233 
1234 /*
1235  * Calculate the maximum outstanding unread data block for a fused tcp endpoint.
1236  */
1237 int
1238 tcp_fuse_maxpsz_set(tcp_t *tcp)
1239 {
1240 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
1241 	uint_t sndbuf = tcp->tcp_xmit_hiwater;
1242 	uint_t maxpsz = sndbuf;
1243 
1244 	ASSERT(tcp->tcp_fused);
1245 	ASSERT(peer_tcp != NULL);
1246 	ASSERT(peer_tcp->tcp_fuse_rcv_hiwater != 0);
1247 	/*
1248 	 * In the fused loopback case, we want the stream head to split
1249 	 * up larger writes into smaller chunks for a more accurate flow-
1250 	 * control accounting.  Our maxpsz is half of the sender's send
1251 	 * buffer or the receiver's receive buffer, whichever is smaller.
1252 	 * We round up the buffer to system page size due to the lack of
1253 	 * TCP MSS concept in Fusion.
1254 	 */
1255 	if (maxpsz > peer_tcp->tcp_fuse_rcv_hiwater)
1256 		maxpsz = peer_tcp->tcp_fuse_rcv_hiwater;
1257 	maxpsz = P2ROUNDUP_TYPED(maxpsz, PAGESIZE, uint_t) >> 1;
1258 
1259 	/*
1260 	 * Calculate the peer's limit for the number of outstanding unread
1261 	 * data block.  This is the amount of data blocks that are allowed
1262 	 * to reside in the receiver's queue before the sender gets flow
1263 	 * controlled.  It is used only in the synchronous streams mode as
1264 	 * a way to throttle the sender when it performs consecutive writes
1265 	 * faster than can be read.  The value is derived from SO_SNDBUF in
1266 	 * order to give the sender some control; we divide it with a large
1267 	 * value (16KB) to produce a fairly low initial limit.
1268 	 */
1269 	if (tcp_fusion_rcv_unread_min == 0) {
1270 		/* A value of 0 means that we disable the check */
1271 		peer_tcp->tcp_fuse_rcv_unread_hiwater = 0;
1272 	} else {
1273 		peer_tcp->tcp_fuse_rcv_unread_hiwater =
1274 		    MAX(sndbuf >> 14, tcp_fusion_rcv_unread_min);
1275 	}
1276 	return (maxpsz);
1277 }
1278