xref: /haiku/src/add-ons/kernel/network/protocols/tcp/TCPEndpoint.cpp (revision 445d4fd926c569e7b9ae28017da86280aaecbae2)
1 /*
2  * Copyright 2006-2010, Haiku, Inc. All Rights Reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Andrew Galante, haiku.galante@gmail.com
7  *		Axel Dörfler, axeld@pinc-software.de
8  *		Hugo Santos, hugosantos@gmail.com
9  */
10 
11 
12 #include "TCPEndpoint.h"
13 
14 #include <netinet/in.h>
15 #include <netinet/ip.h>
16 #include <netinet/tcp.h>
17 #include <new>
18 #include <signal.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <stdint.h>
22 
23 #include <KernelExport.h>
24 #include <Select.h>
25 
26 #include <net_buffer.h>
27 #include <net_datalink.h>
28 #include <net_stat.h>
29 #include <NetBufferUtilities.h>
30 #include <NetUtilities.h>
31 
32 #include <lock.h>
33 #include <tracing.h>
34 #include <util/AutoLock.h>
35 #include <util/list.h>
36 
37 #include "EndpointManager.h"
38 
39 
40 // References:
41 //	- RFC 793 - Transmission Control Protocol
42 //	- RFC 813 - Window and Acknowledgement Strategy in TCP
43 //	- RFC 1337 - TIME_WAIT Assassination Hazards in TCP
44 //
45 // Things this implementation currently doesn't implement:
46 //	- TCP Slow Start, Congestion Avoidance, Fast Retransmit, and Fast Recovery,
47 //	  RFC 2001, RFC 2581, RFC 3042
48 //	- NewReno Modification to TCP's Fast Recovery, RFC 2582
49 //	- Explicit Congestion Notification (ECN), RFC 3168
50 //	- SYN-Cache
51 //	- SACK, Selective Acknowledgment - RFC 2018, RFC 2883, RFC 3517
52 //	- Forward RTO-Recovery, RFC 4138
53 //	- Time-Wait hash instead of keeping sockets alive
54 //
55 // Things incomplete in this implementation:
56 //	- TCP Extensions for High Performance, RFC 1323 - RTTM, PAWS
57 
58 #define PrintAddress(address) \
59 	AddressString(Domain(), address, true).Data()
60 
61 //#define TRACE_TCP
62 //#define PROBE_TCP
63 
64 #ifdef TRACE_TCP
65 // the space before ', ##args' is important in order for this to work with cpp 2.95
66 #	define TRACE(format, args...)	dprintf("%" B_PRId32 ": TCP [%" \
67 		B_PRIdBIGTIME "] %p (%12s) " format "\n", find_thread(NULL), \
68 		system_time(), this, name_for_state(fState) , ##args)
69 #else
70 #	define TRACE(args...)			do { } while (0)
71 #endif
72 
73 #ifdef PROBE_TCP
74 #	define PROBE(buffer, window) \
75 	dprintf("TCP PROBE %" B_PRIdBIGTIME " %s %s %" B_PRIu32 " snxt %" B_PRIu32 \
76 		" suna %" B_PRIu32 " cw %" B_PRIu32 " sst %" B_PRIu32 " win %" \
77 		B_PRIu32 " swin %" B_PRIu32 " smax-suna %" B_PRIu32 " savail %" \
78 		B_PRIuSIZE " sqused %" B_PRIuSIZE " rto %" B_PRIdBIGTIME "\n", \
79 		system_time(), PrintAddress(buffer->source), \
80 		PrintAddress(buffer->destination), buffer->size, fSendNext.Number(), \
81 		fSendUnacknowledged.Number(), fCongestionWindow, fSlowStartThreshold, \
82 		window, fSendWindow, (fSendMax - fSendUnacknowledged).Number(), \
83 		fSendQueue.Available(fSendNext), fSendQueue.Used(), fRetransmitTimeout)
84 #else
85 #	define PROBE(buffer, window)	do { } while (0)
86 #endif
87 
88 #if TCP_TRACING
89 namespace TCPTracing {
90 
91 class Receive : public AbstractTraceEntry {
92 public:
93 	Receive(TCPEndpoint* endpoint, tcp_segment_header& segment, uint32 window,
94 			net_buffer* buffer)
95 		:
96 		fEndpoint(endpoint),
97 		fBuffer(buffer),
98 		fBufferSize(buffer->size),
99 		fSequence(segment.sequence),
100 		fAcknowledge(segment.acknowledge),
101 		fWindow(window),
102 		fState(endpoint->State()),
103 		fFlags(segment.flags)
104 	{
105 		Initialized();
106 	}
107 
108 	virtual void AddDump(TraceOutput& out)
109 	{
110 		out.Print("tcp:%p (%12s) receive buffer %p (%" B_PRIu32 " bytes), "
111 			"flags %#" B_PRIx8 ", seq %" B_PRIu32 ", ack %" B_PRIu32
112 			", wnd %" B_PRIu32, fEndpoint, name_for_state(fState), fBuffer,
113 			fBufferSize, fFlags, fSequence, fAcknowledge, fWindow);
114 	}
115 
116 protected:
117 	TCPEndpoint*	fEndpoint;
118 	net_buffer*		fBuffer;
119 	uint32			fBufferSize;
120 	uint32			fSequence;
121 	uint32			fAcknowledge;
122 	uint32			fWindow;
123 	tcp_state		fState;
124 	uint8			fFlags;
125 };
126 
127 class Send : public AbstractTraceEntry {
128 public:
129 	Send(TCPEndpoint* endpoint, tcp_segment_header& segment, net_buffer* buffer,
130 			tcp_sequence firstSequence, tcp_sequence lastSequence)
131 		:
132 		fEndpoint(endpoint),
133 		fBuffer(buffer),
134 		fBufferSize(buffer->size),
135 		fSequence(segment.sequence),
136 		fAcknowledge(segment.acknowledge),
137 		fFirstSequence(firstSequence.Number()),
138 		fLastSequence(lastSequence.Number()),
139 		fState(endpoint->State()),
140 		fFlags(segment.flags)
141 	{
142 		Initialized();
143 	}
144 
145 	virtual void AddDump(TraceOutput& out)
146 	{
147 		out.Print("tcp:%p (%12s) send buffer %p (%" B_PRIu32 " bytes), "
148 			"flags %#" B_PRIx8 ", seq %" B_PRIu32 ", ack %" B_PRIu32
149 			", first %" B_PRIu32 ", last %" B_PRIu32, fEndpoint,
150 			name_for_state(fState), fBuffer, fBufferSize, fFlags, fSequence,
151 			fAcknowledge, fFirstSequence, fLastSequence);
152 	}
153 
154 protected:
155 	TCPEndpoint*	fEndpoint;
156 	net_buffer*		fBuffer;
157 	uint32			fBufferSize;
158 	uint32			fSequence;
159 	uint32			fAcknowledge;
160 	uint32			fFirstSequence;
161 	uint32			fLastSequence;
162 	tcp_state		fState;
163 	uint8			fFlags;
164 };
165 
166 class State : public AbstractTraceEntry {
167 public:
168 	State(TCPEndpoint* endpoint)
169 		:
170 		fEndpoint(endpoint),
171 		fState(endpoint->State())
172 	{
173 		Initialized();
174 	}
175 
176 	virtual void AddDump(TraceOutput& out)
177 	{
178 		out.Print("tcp:%p (%12s) state change", fEndpoint,
179 			name_for_state(fState));
180 	}
181 
182 protected:
183 	TCPEndpoint*	fEndpoint;
184 	tcp_state		fState;
185 };
186 
187 class Spawn : public AbstractTraceEntry {
188 public:
189 	Spawn(TCPEndpoint* listeningEndpoint, TCPEndpoint* spawnedEndpoint)
190 		:
191 		fListeningEndpoint(listeningEndpoint),
192 		fSpawnedEndpoint(spawnedEndpoint)
193 	{
194 		Initialized();
195 	}
196 
197 	virtual void AddDump(TraceOutput& out)
198 	{
199 		out.Print("tcp:%p spawns %p", fListeningEndpoint, fSpawnedEndpoint);
200 	}
201 
202 protected:
203 	TCPEndpoint*	fListeningEndpoint;
204 	TCPEndpoint*	fSpawnedEndpoint;
205 };
206 
207 class Error : public AbstractTraceEntry {
208 public:
209 	Error(TCPEndpoint* endpoint, const char* error, int32 line)
210 		:
211 		fEndpoint(endpoint),
212 		fLine(line),
213 		fError(error),
214 		fState(endpoint->State())
215 	{
216 		Initialized();
217 	}
218 
219 	virtual void AddDump(TraceOutput& out)
220 	{
221 		out.Print("tcp:%p (%12s) error at line %" B_PRId32 ": %s", fEndpoint,
222 			name_for_state(fState), fLine, fError);
223 	}
224 
225 protected:
226 	TCPEndpoint*	fEndpoint;
227 	int32			fLine;
228 	const char*		fError;
229 	tcp_state		fState;
230 };
231 
232 class TimerSet : public AbstractTraceEntry {
233 public:
234 	TimerSet(TCPEndpoint* endpoint, const char* which, bigtime_t timeout)
235 		:
236 		fEndpoint(endpoint),
237 		fWhich(which),
238 		fTimeout(timeout),
239 		fState(endpoint->State())
240 	{
241 		Initialized();
242 	}
243 
244 	virtual void AddDump(TraceOutput& out)
245 	{
246 		out.Print("tcp:%p (%12s) %s timer set to %" B_PRIdBIGTIME, fEndpoint,
247 			name_for_state(fState), fWhich, fTimeout);
248 	}
249 
250 protected:
251 	TCPEndpoint*	fEndpoint;
252 	const char*		fWhich;
253 	bigtime_t		fTimeout;
254 	tcp_state		fState;
255 };
256 
257 class TimerTriggered : public AbstractTraceEntry {
258 public:
259 	TimerTriggered(TCPEndpoint* endpoint, const char* which)
260 		:
261 		fEndpoint(endpoint),
262 		fWhich(which),
263 		fState(endpoint->State())
264 	{
265 		Initialized();
266 	}
267 
268 	virtual void AddDump(TraceOutput& out)
269 	{
270 		out.Print("tcp:%p (%12s) %s timer triggered", fEndpoint,
271 			name_for_state(fState), fWhich);
272 	}
273 
274 protected:
275 	TCPEndpoint*	fEndpoint;
276 	const char*		fWhich;
277 	tcp_state		fState;
278 };
279 
280 class APICall : public AbstractTraceEntry {
281 public:
282 	APICall(TCPEndpoint* endpoint, const char* which)
283 		:
284 		fEndpoint(endpoint),
285 		fWhich(which),
286 		fState(endpoint->State())
287 	{
288 		Initialized();
289 	}
290 
291 	virtual void AddDump(TraceOutput& out)
292 	{
293 		out.Print("tcp:%p (%12s) api call: %s", fEndpoint,
294 			name_for_state(fState), fWhich);
295 	}
296 
297 protected:
298 	TCPEndpoint*	fEndpoint;
299 	const char*		fWhich;
300 	tcp_state		fState;
301 };
302 
303 }	// namespace TCPTracing
304 
305 #	define T(x)	new(std::nothrow) TCPTracing::x
306 #else
307 #	define T(x)
308 #endif	// TCP_TRACING
309 
310 
311 // constants for the fFlags field
312 enum {
313 	FLAG_OPTION_WINDOW_SCALE	= 0x01,
314 	FLAG_OPTION_TIMESTAMP		= 0x02,
315 	// TODO: Should FLAG_NO_RECEIVE apply as well to received connections?
316 	//       That is, what is expected from accept() after a shutdown()
317 	//       is performed on a listen()ing socket.
318 	FLAG_NO_RECEIVE				= 0x04,
319 	FLAG_CLOSED					= 0x08,
320 	FLAG_DELETE_ON_CLOSE		= 0x10,
321 	FLAG_LOCAL					= 0x20,
322 	FLAG_RECOVERY				= 0x40,
323 	FLAG_OPTION_SACK_PERMITTED	= 0x80,
324 };
325 
326 
327 static const int kTimestampFactor = 1000;
328 	// conversion factor between usec system time and msec tcp time
329 
330 
331 static inline bigtime_t
332 absolute_timeout(bigtime_t timeout)
333 {
334 	if (timeout == 0 || timeout == B_INFINITE_TIMEOUT)
335 		return timeout;
336 
337 	return timeout + system_time();
338 }
339 
340 
341 static inline status_t
342 posix_error(status_t error)
343 {
344 	if (error == B_TIMED_OUT)
345 		return B_WOULD_BLOCK;
346 
347 	return error;
348 }
349 
350 
351 static inline bool
352 in_window(const tcp_sequence& sequence, const tcp_sequence& receiveNext,
353 	uint32 receiveWindow)
354 {
355 	return sequence >= receiveNext && sequence < (receiveNext + receiveWindow);
356 }
357 
358 
359 static inline bool
360 segment_in_sequence(const tcp_segment_header& segment, int size,
361 	const tcp_sequence& receiveNext, uint32 receiveWindow)
362 {
363 	tcp_sequence sequence(segment.sequence);
364 	if (size == 0) {
365 		if (receiveWindow == 0)
366 			return sequence == receiveNext;
367 		return in_window(sequence, receiveNext, receiveWindow);
368 	} else {
369 		if (receiveWindow == 0)
370 			return false;
371 		return in_window(sequence, receiveNext, receiveWindow)
372 			|| in_window(sequence + size - 1, receiveNext, receiveWindow);
373 	}
374 }
375 
376 
377 static inline bool
378 is_writable(tcp_state state)
379 {
380 	return state == ESTABLISHED || state == FINISH_RECEIVED;
381 }
382 
383 
384 static inline bool
385 is_establishing(tcp_state state)
386 {
387 	return state == SYNCHRONIZE_SENT || state == SYNCHRONIZE_RECEIVED;
388 }
389 
390 
391 static inline uint32 tcp_now()
392 {
393 	return system_time() / kTimestampFactor;
394 }
395 
396 
397 static inline uint32 tcp_diff_timestamp(uint32 base)
398 {
399 	uint32 now = tcp_now();
400 
401 	if (now > base)
402 		return now - base;
403 
404 	return now + UINT_MAX - base;
405 }
406 
407 
408 static inline bool
409 state_needs_finish(int32 state)
410 {
411 	return state == WAIT_FOR_FINISH_ACKNOWLEDGE
412 		|| state == FINISH_SENT || state == CLOSING;
413 }
414 
415 
416 //	#pragma mark -
417 
418 
419 TCPEndpoint::TCPEndpoint(net_socket* socket)
420 	:
421 	ProtocolSocket(socket),
422 	fManager(NULL),
423 	fOptions(0),
424 	fSendWindowShift(0),
425 	fReceiveWindowShift(0),
426 	fSendUnacknowledged(0),
427 	fSendNext(0),
428 	fSendMax(0),
429 	fSendUrgentOffset(0),
430 	fSendWindow(0),
431 	fSendMaxWindow(0),
432 	fSendMaxSegmentSize(TCP_DEFAULT_MAX_SEGMENT_SIZE),
433 	fSendMaxSegments(0),
434 	fSendQueue(socket->send.buffer_size),
435 	fInitialSendSequence(0),
436 	fPreviousHighestAcknowledge(0),
437 	fDuplicateAcknowledgeCount(0),
438 	fPreviousFlightSize(0),
439 	fRecover(0),
440 	fRoute(NULL),
441 	fReceiveNext(0),
442 	fReceiveMaxAdvertised(0),
443 	fReceiveWindow(socket->receive.buffer_size),
444 	fReceiveMaxSegmentSize(TCP_DEFAULT_MAX_SEGMENT_SIZE),
445 	fReceiveQueue(socket->receive.buffer_size),
446 	fSmoothedRoundTripTime(0),
447 	fRoundTripVariation(0),
448 	fSendTime(0),
449 	fRoundTripStartSequence(0),
450 	fRetransmitTimeout(TCP_INITIAL_RTT),
451 	fReceivedTimestamp(0),
452 	fCongestionWindow(0),
453 	fSlowStartThreshold(0),
454 	fState(CLOSED),
455 	fFlags(FLAG_OPTION_WINDOW_SCALE | FLAG_OPTION_TIMESTAMP | FLAG_OPTION_SACK_PERMITTED)
456 {
457 	// TODO: to be replaced with a real read/write locking strategy!
458 	mutex_init(&fLock, "tcp lock");
459 
460 	fReceiveCondition.Init(this, "tcp receive");
461 	fSendCondition.Init(this, "tcp send");
462 
463 	gStackModule->init_timer(&fPersistTimer, TCPEndpoint::_PersistTimer, this);
464 	gStackModule->init_timer(&fRetransmitTimer, TCPEndpoint::_RetransmitTimer,
465 		this);
466 	gStackModule->init_timer(&fDelayedAcknowledgeTimer,
467 		TCPEndpoint::_DelayedAcknowledgeTimer, this);
468 	gStackModule->init_timer(&fTimeWaitTimer, TCPEndpoint::_TimeWaitTimer,
469 		this);
470 
471 	T(APICall(this, "constructor"));
472 }
473 
474 
475 TCPEndpoint::~TCPEndpoint()
476 {
477 	mutex_lock(&fLock);
478 
479 	T(APICall(this, "destructor"));
480 
481 	_CancelConnectionTimers();
482 	gStackModule->cancel_timer(&fTimeWaitTimer);
483 	T(TimerSet(this, "time-wait", -1));
484 
485 	if (fManager != NULL) {
486 		fManager->Unbind(this);
487 		put_endpoint_manager(fManager);
488 	}
489 
490 	mutex_destroy(&fLock);
491 
492 	// we need to wait for all timers to return
493 	gStackModule->wait_for_timer(&fRetransmitTimer);
494 	gStackModule->wait_for_timer(&fPersistTimer);
495 	gStackModule->wait_for_timer(&fDelayedAcknowledgeTimer);
496 	gStackModule->wait_for_timer(&fTimeWaitTimer);
497 
498 	gDatalinkModule->put_route(Domain(), fRoute);
499 }
500 
501 
502 status_t
503 TCPEndpoint::InitCheck() const
504 {
505 	return B_OK;
506 }
507 
508 
509 //	#pragma mark - protocol API
510 
511 
512 status_t
513 TCPEndpoint::Open()
514 {
515 	TRACE("Open()");
516 	T(APICall(this, "open"));
517 
518 	status_t status = ProtocolSocket::Open();
519 	if (status < B_OK)
520 		return status;
521 
522 	fManager = get_endpoint_manager(Domain());
523 	if (fManager == NULL)
524 		return EAFNOSUPPORT;
525 
526 	return B_OK;
527 }
528 
529 
530 status_t
531 TCPEndpoint::Close()
532 {
533 	MutexLocker locker(fLock);
534 
535 	TRACE("Close()");
536 	T(APICall(this, "close"));
537 
538 	if (fState == LISTEN)
539 		delete_sem(fAcceptSemaphore);
540 
541 	if (fState == SYNCHRONIZE_SENT || fState == LISTEN) {
542 		// TODO: what about linger in case of SYNCHRONIZE_SENT?
543 		fState = CLOSED;
544 		T(State(this));
545 		return B_OK;
546 	}
547 
548 	// handle linger with zero timeout
549 	if ((socket->options & SO_LINGER) != 0 && socket->linger == 0) {
550 		fState = CLOSED;
551 		T(State(this));
552 		return _SendQueued(true);
553 	}
554 
555 	status_t status = _Disconnect(true);
556 	if (status != B_OK)
557 		return status;
558 
559 	if ((socket->options & SO_LINGER) != 0) {
560 		TRACE("Close(): Lingering for %i secs", socket->linger);
561 
562 		bigtime_t maximum = absolute_timeout(socket->linger * 1000000LL);
563 
564 		while (fSendQueue.Used() > 0) {
565 			status = _WaitForCondition(fSendCondition, locker, maximum);
566 			if (status == B_TIMED_OUT || status == B_WOULD_BLOCK)
567 				break;
568 			else if (status < B_OK)
569 				return status;
570 		}
571 
572 		TRACE("Close(): after waiting, the SendQ was left with %" B_PRIuSIZE
573 			" bytes.", fSendQueue.Used());
574 	}
575 	return B_OK;
576 }
577 
578 
579 void
580 TCPEndpoint::Free()
581 {
582 	MutexLocker _(fLock);
583 
584 	TRACE("Free()");
585 	T(APICall(this, "free"));
586 
587 	if (fState <= SYNCHRONIZE_SENT)
588 		return;
589 
590 	// we are only interested in the timer, not in changing state
591 	_EnterTimeWait();
592 
593 	fFlags |= FLAG_CLOSED;
594 	if ((fFlags & FLAG_DELETE_ON_CLOSE) == 0) {
595 		// we'll be freed later when the 2MSL timer expires
596 		gSocketModule->acquire_socket(socket);
597 	}
598 }
599 
600 
601 /*!	Creates and sends a synchronize packet to /a address, and then waits
602 	until the connection has been established or refused.
603 */
604 status_t
605 TCPEndpoint::Connect(const sockaddr* address)
606 {
607 	if (!AddressModule()->is_same_family(address))
608 		return EAFNOSUPPORT;
609 
610 	MutexLocker locker(fLock);
611 
612 	TRACE("Connect() on address %s", PrintAddress(address));
613 	T(APICall(this, "connect"));
614 
615 	if (gStackModule->is_restarted_syscall()) {
616 		bigtime_t timeout = gStackModule->restore_syscall_restart_timeout();
617 		status_t status = _WaitForEstablished(locker, timeout);
618 		TRACE("  Connect(): Connection complete: %s (timeout was %"
619 			B_PRIdBIGTIME ")", strerror(status), timeout);
620 		return posix_error(status);
621 	}
622 
623 	// Can only call connect() from CLOSED or LISTEN states
624 	// otherwise endpoint is considered already connected
625 	if (fState == LISTEN) {
626 		// this socket is about to connect; remove pending connections in the backlog
627 		gSocketModule->set_max_backlog(socket, 0);
628 	} else if (fState == ESTABLISHED) {
629 		return EISCONN;
630 	} else if (fState != CLOSED)
631 		return EALREADY;
632 
633 	// consider destination address INADDR_ANY as INADDR_LOOPBACK
634 	sockaddr_storage _address;
635 	if (AddressModule()->is_empty_address(address, false)) {
636 		AddressModule()->get_loopback_address((sockaddr *)&_address);
637 		// for IPv4 and IPv6 the port is at the same offset
638 		((sockaddr_in &)_address).sin_port = ((sockaddr_in *)address)->sin_port;
639 		address = (sockaddr *)&_address;
640 	}
641 
642 	status_t status = _PrepareSendPath(address);
643 	if (status < B_OK)
644 		return status;
645 
646 	TRACE("  Connect(): starting 3-way handshake...");
647 
648 	fState = SYNCHRONIZE_SENT;
649 	T(State(this));
650 
651 	// send SYN
652 	status = _SendQueued();
653 	if (status != B_OK) {
654 		_Close();
655 		return status;
656 	}
657 
658 	// If we are running over Loopback, after _SendQueued() returns we
659 	// may be in ESTABLISHED already.
660 	if (fState == ESTABLISHED) {
661 		TRACE("  Connect() completed after _SendQueued()");
662 		return B_OK;
663 	}
664 
665 	// wait until 3-way handshake is complete (if needed)
666 	bigtime_t timeout = min_c(socket->send.timeout, TCP_CONNECTION_TIMEOUT);
667 	if (timeout == 0) {
668 		// we're a non-blocking socket
669 		TRACE("  Connect() delayed, return EINPROGRESS");
670 		return EINPROGRESS;
671 	}
672 
673 	bigtime_t absoluteTimeout = absolute_timeout(timeout);
674 	gStackModule->store_syscall_restart_timeout(absoluteTimeout);
675 
676 	status = _WaitForEstablished(locker, absoluteTimeout);
677 	TRACE("  Connect(): Connection complete: %s (timeout was %" B_PRIdBIGTIME
678 		")", strerror(status), timeout);
679 	return posix_error(status);
680 }
681 
682 
683 status_t
684 TCPEndpoint::Accept(struct net_socket** _acceptedSocket)
685 {
686 	MutexLocker locker(fLock);
687 
688 	TRACE("Accept()");
689 	T(APICall(this, "accept"));
690 
691 	status_t status;
692 	bigtime_t timeout = absolute_timeout(socket->receive.timeout);
693 	if (gStackModule->is_restarted_syscall())
694 		timeout = gStackModule->restore_syscall_restart_timeout();
695 	else
696 		gStackModule->store_syscall_restart_timeout(timeout);
697 
698 	do {
699 		locker.Unlock();
700 
701 		status = acquire_sem_etc(fAcceptSemaphore, 1, B_ABSOLUTE_TIMEOUT
702 			| B_CAN_INTERRUPT, timeout);
703 		if (status != B_OK) {
704 			if (status == B_TIMED_OUT && socket->receive.timeout == 0)
705 				return B_WOULD_BLOCK;
706 
707 			return status;
708 		}
709 
710 		locker.Lock();
711 		status = gSocketModule->dequeue_connected(socket, _acceptedSocket);
712 #ifdef TRACE_TCP
713 		if (status == B_OK)
714 			TRACE("  Accept() returning %p", (*_acceptedSocket)->first_protocol);
715 #endif
716 	} while (status != B_OK);
717 
718 	return status;
719 }
720 
721 
722 status_t
723 TCPEndpoint::Bind(const sockaddr *address)
724 {
725 	if (address == NULL)
726 		return B_BAD_VALUE;
727 
728 	MutexLocker lock(fLock);
729 
730 	TRACE("Bind() on address %s", PrintAddress(address));
731 	T(APICall(this, "bind"));
732 
733 	if (fState != CLOSED)
734 		return EISCONN;
735 
736 	return fManager->Bind(this, address);
737 }
738 
739 
740 status_t
741 TCPEndpoint::Unbind(struct sockaddr *address)
742 {
743 	MutexLocker _(fLock);
744 
745 	TRACE("Unbind()");
746 	T(APICall(this, "unbind"));
747 
748 	return fManager->Unbind(this);
749 }
750 
751 
752 status_t
753 TCPEndpoint::Listen(int count)
754 {
755 	MutexLocker _(fLock);
756 
757 	TRACE("Listen()");
758 	T(APICall(this, "listen"));
759 
760 	if (fState != CLOSED && fState != LISTEN)
761 		return B_BAD_VALUE;
762 
763 	if (fState == CLOSED) {
764 		fAcceptSemaphore = create_sem(0, "tcp accept");
765 		if (fAcceptSemaphore < B_OK)
766 			return ENOBUFS;
767 
768 		status_t status = fManager->SetPassive(this);
769 		if (status != B_OK) {
770 			delete_sem(fAcceptSemaphore);
771 			fAcceptSemaphore = -1;
772 			return status;
773 		}
774 	}
775 
776 	gSocketModule->set_max_backlog(socket, count);
777 
778 	fState = LISTEN;
779 	T(State(this));
780 	return B_OK;
781 }
782 
783 
784 status_t
785 TCPEndpoint::Shutdown(int direction)
786 {
787 	MutexLocker lock(fLock);
788 
789 	TRACE("Shutdown(%i)", direction);
790 	T(APICall(this, "shutdown"));
791 
792 	if (direction == SHUT_RD || direction == SHUT_RDWR)
793 		fFlags |= FLAG_NO_RECEIVE;
794 
795 	if (direction == SHUT_WR || direction == SHUT_RDWR) {
796 		// TODO: That's not correct. After read/write shutting down the socket
797 		// one should still be able to read previously arrived data.
798 		_Disconnect(false);
799 	}
800 
801 	return B_OK;
802 }
803 
804 
805 /*!	Puts data contained in \a buffer into send buffer */
806 status_t
807 TCPEndpoint::SendData(net_buffer *buffer)
808 {
809 	MutexLocker lock(fLock);
810 
811 	TRACE("SendData(buffer %p, size %" B_PRIu32 ", flags %#" B_PRIx32
812 		") [total %" B_PRIuSIZE " bytes, has %" B_PRIuSIZE "]", buffer,
813 		buffer->size, buffer->flags, fSendQueue.Size(), fSendQueue.Free());
814 	T(APICall(this, "senddata"));
815 
816 	uint32 flags = buffer->flags;
817 
818 	if (fState == CLOSED)
819 		return ENOTCONN;
820 	if (fState == LISTEN)
821 		return EDESTADDRREQ;
822 	if (!is_writable(fState) && !is_establishing(fState)) {
823 		// we only send signals when called from userland
824 		if (gStackModule->is_syscall() && (flags & MSG_NOSIGNAL) == 0)
825 			send_signal(find_thread(NULL), SIGPIPE);
826 		return EPIPE;
827 	}
828 
829 	size_t left = buffer->size;
830 
831 	bigtime_t timeout = absolute_timeout(socket->send.timeout);
832 	if (gStackModule->is_restarted_syscall())
833 		timeout = gStackModule->restore_syscall_restart_timeout();
834 	else
835 		gStackModule->store_syscall_restart_timeout(timeout);
836 
837 	while (left > 0) {
838 		while (fSendQueue.Free() < socket->send.low_water_mark) {
839 			// wait until enough space is available
840 			status_t status = _WaitForCondition(fSendCondition, lock, timeout);
841 			if (status < B_OK) {
842 				TRACE("  SendData() returning %s (%d)",
843 					strerror(posix_error(status)), (int)posix_error(status));
844 				return posix_error(status);
845 			}
846 
847 			if (!is_writable(fState) && !is_establishing(fState)) {
848 				// we only send signals when called from userland
849 				if (gStackModule->is_syscall())
850 					send_signal(find_thread(NULL), SIGPIPE);
851 				return EPIPE;
852 			}
853 		}
854 
855 		size_t size = fSendQueue.Free();
856 		if (size < left) {
857 			// we need to split the original buffer
858 			net_buffer* clone = gBufferModule->clone(buffer, false);
859 				// TODO: add offset/size parameter to net_buffer::clone() or
860 				// even a move_data() function, as this is a bit inefficient
861 			if (clone == NULL)
862 				return ENOBUFS;
863 
864 			status_t status = gBufferModule->trim(clone, size);
865 			if (status != B_OK) {
866 				gBufferModule->free(clone);
867 				return status;
868 			}
869 
870 			gBufferModule->remove_header(buffer, size);
871 			left -= size;
872 			fSendQueue.Add(clone);
873 		} else {
874 			left -= buffer->size;
875 			fSendQueue.Add(buffer);
876 		}
877 	}
878 
879 	TRACE("  SendData(): %" B_PRIuSIZE " bytes used.", fSendQueue.Used());
880 
881 	bool force = false;
882 	if ((flags & MSG_OOB) != 0) {
883 		fSendUrgentOffset = fSendQueue.LastSequence();
884 			// RFC 961 specifies that the urgent offset points to the last
885 			// byte of urgent data. However, this is commonly implemented as
886 			// here, ie. it points to the first byte after the urgent data.
887 		force = true;
888 	}
889 	if ((flags & MSG_EOF) != 0)
890 		_Disconnect(false);
891 
892 	if (fState == ESTABLISHED || fState == FINISH_RECEIVED)
893 		_SendQueued(force);
894 
895 	return B_OK;
896 }
897 
898 
899 ssize_t
900 TCPEndpoint::SendAvailable()
901 {
902 	MutexLocker locker(fLock);
903 
904 	ssize_t available;
905 
906 	if (is_writable(fState))
907 		available = fSendQueue.Free();
908 	else if (is_establishing(fState))
909 		available = 0;
910 	else
911 		available = EPIPE;
912 
913 	TRACE("SendAvailable(): %" B_PRIdSSIZE, available);
914 	T(APICall(this, "sendavailable"));
915 	return available;
916 }
917 
918 
919 status_t
920 TCPEndpoint::FillStat(net_stat *stat)
921 {
922 	MutexLocker _(fLock);
923 
924 	strlcpy(stat->state, name_for_state(fState), sizeof(stat->state));
925 	stat->receive_queue_size = fReceiveQueue.Available();
926 	stat->send_queue_size = fSendQueue.Used();
927 
928 	return B_OK;
929 }
930 
931 
932 status_t
933 TCPEndpoint::ReadData(size_t numBytes, uint32 flags, net_buffer** _buffer)
934 {
935 	MutexLocker locker(fLock);
936 
937 	TRACE("ReadData(%" B_PRIuSIZE " bytes, flags %#" B_PRIx32 ")", numBytes,
938 		flags);
939 	T(APICall(this, "readdata"));
940 
941 	*_buffer = NULL;
942 
943 	if (fState == CLOSED) {
944 		if (socket->error != B_OK)
945 			return socket->error;
946 		return ENOTCONN;
947 	}
948 
949 	bigtime_t timeout = absolute_timeout(socket->receive.timeout);
950 	if (gStackModule->is_restarted_syscall())
951 		timeout = gStackModule->restore_syscall_restart_timeout();
952 	else
953 		gStackModule->store_syscall_restart_timeout(timeout);
954 
955 	if (fState == SYNCHRONIZE_SENT || fState == SYNCHRONIZE_RECEIVED) {
956 		if (flags & MSG_DONTWAIT)
957 			return B_WOULD_BLOCK;
958 
959 		status_t status = _WaitForEstablished(locker, timeout);
960 		if (status < B_OK)
961 			return posix_error(status);
962 	}
963 
964 	size_t dataNeeded = socket->receive.low_water_mark;
965 
966 	// When MSG_WAITALL is set then the function should block
967 	// until the full amount of data can be returned.
968 	if (flags & MSG_WAITALL)
969 		dataNeeded = numBytes;
970 
971 	// TODO: add support for urgent data (MSG_OOB)
972 
973 	while (true) {
974 		if (fState == CLOSING || fState == WAIT_FOR_FINISH_ACKNOWLEDGE
975 			|| fState == TIME_WAIT) {
976 			// ``Connection closing''.
977 			if (fReceiveQueue.Available() > 0)
978 				break;
979 			return B_OK;
980 		}
981 
982 		if (fReceiveQueue.Available() > 0) {
983 			if (fReceiveQueue.Available() >= dataNeeded
984 				|| (fReceiveQueue.PushedData() > 0
985 					&& fReceiveQueue.PushedData() >= fReceiveQueue.Available()))
986 				break;
987 		} else if (fState == FINISH_RECEIVED) {
988 			// ``If no text is awaiting delivery, the RECEIVE will
989 			//   get a Connection closing''.
990 			return B_OK;
991 		}
992 
993 		if ((flags & MSG_DONTWAIT) != 0 || socket->receive.timeout == 0)
994 			return B_WOULD_BLOCK;
995 
996 		if ((fFlags & FLAG_NO_RECEIVE) != 0)
997 			return B_OK;
998 
999 		status_t status = _WaitForCondition(fReceiveCondition, locker, timeout);
1000 		if (status < B_OK) {
1001 			// The Open Group base specification mentions that EINTR should be
1002 			// returned if the recv() is interrupted before _any data_ is
1003 			// available. So we actually check if there is data, and if so,
1004 			// push it to the user.
1005 			if ((status == B_TIMED_OUT || status == B_INTERRUPTED)
1006 				&& fReceiveQueue.Available() > 0)
1007 				break;
1008 
1009 			return posix_error(status);
1010 		}
1011 	}
1012 
1013 	TRACE("  ReadData(): %" B_PRIuSIZE " are available.",
1014 		fReceiveQueue.Available());
1015 
1016 	if (numBytes < fReceiveQueue.Available())
1017 		fReceiveCondition.NotifyAll();
1018 
1019 	bool clone = (flags & MSG_PEEK) != 0;
1020 
1021 	ssize_t receivedBytes = fReceiveQueue.Get(numBytes, !clone, _buffer);
1022 
1023 	TRACE("  ReadData(): %" B_PRIuSIZE " bytes kept.",
1024 		fReceiveQueue.Available());
1025 
1026 	if (fReceiveQueue.Available() == 0 && fState == FINISH_RECEIVED)
1027 		socket->receive.low_water_mark = 0;
1028 
1029 	// if we are opening the window, check if we should send an ACK
1030 	if (!clone)
1031 		SendAcknowledge(false);
1032 
1033 	return receivedBytes;
1034 }
1035 
1036 
1037 ssize_t
1038 TCPEndpoint::ReadAvailable()
1039 {
1040 	MutexLocker locker(fLock);
1041 
1042 	TRACE("ReadAvailable(): %" B_PRIdSSIZE, _AvailableData());
1043 	T(APICall(this, "readavailable"));
1044 
1045 	return _AvailableData();
1046 }
1047 
1048 
1049 status_t
1050 TCPEndpoint::SetSendBufferSize(size_t length)
1051 {
1052 	MutexLocker _(fLock);
1053 	fSendQueue.SetMaxBytes(length);
1054 	return B_OK;
1055 }
1056 
1057 
1058 status_t
1059 TCPEndpoint::SetReceiveBufferSize(size_t length)
1060 {
1061 	MutexLocker _(fLock);
1062 	fReceiveQueue.SetMaxBytes(length);
1063 	return B_OK;
1064 }
1065 
1066 
1067 status_t
1068 TCPEndpoint::GetOption(int option, void* _value, int* _length)
1069 {
1070 	if (*_length != sizeof(int))
1071 		return B_BAD_VALUE;
1072 
1073 	int* value = (int*)_value;
1074 
1075 	switch (option) {
1076 		case TCP_NODELAY:
1077 			if ((fOptions & TCP_NODELAY) != 0)
1078 				*value = 1;
1079 			else
1080 				*value = 0;
1081 			return B_OK;
1082 
1083 		case TCP_MAXSEG:
1084 			*value = fReceiveMaxSegmentSize;
1085 			return B_OK;
1086 
1087 		default:
1088 			return B_BAD_VALUE;
1089 	}
1090 }
1091 
1092 
1093 status_t
1094 TCPEndpoint::SetOption(int option, const void* _value, int length)
1095 {
1096 	if (option != TCP_NODELAY)
1097 		return B_BAD_VALUE;
1098 
1099 	if (length != sizeof(int))
1100 		return B_BAD_VALUE;
1101 
1102 	const int* value = (const int*)_value;
1103 
1104 	MutexLocker _(fLock);
1105 	if (*value)
1106 		fOptions |= TCP_NODELAY;
1107 	else
1108 		fOptions &= ~TCP_NODELAY;
1109 
1110 	return B_OK;
1111 }
1112 
1113 
1114 //	#pragma mark - misc
1115 
1116 
1117 bool
1118 TCPEndpoint::IsBound() const
1119 {
1120 	return !LocalAddress().IsEmpty(true);
1121 }
1122 
1123 
1124 bool
1125 TCPEndpoint::IsLocal() const
1126 {
1127 	return (fFlags & FLAG_LOCAL) != 0;
1128 }
1129 
1130 
1131 status_t
1132 TCPEndpoint::DelayedAcknowledge()
1133 {
1134 	if (gStackModule->cancel_timer(&fDelayedAcknowledgeTimer)) {
1135 		// timer was active, send an ACK now (with the exception above,
1136 		// we send every other ACK)
1137 		T(TimerSet(this, "delayed ack", -1));
1138 		return SendAcknowledge(true);
1139 	}
1140 
1141 	gStackModule->set_timer(&fDelayedAcknowledgeTimer,
1142 		TCP_DELAYED_ACKNOWLEDGE_TIMEOUT);
1143 	T(TimerSet(this, "delayed ack", TCP_DELAYED_ACKNOWLEDGE_TIMEOUT));
1144 	return B_OK;
1145 }
1146 
1147 
1148 status_t
1149 TCPEndpoint::SendAcknowledge(bool force)
1150 {
1151 	return _SendQueued(force, 0);
1152 }
1153 
1154 
1155 void
1156 TCPEndpoint::_StartPersistTimer()
1157 {
1158 	gStackModule->set_timer(&fPersistTimer, TCP_PERSIST_TIMEOUT);
1159 	T(TimerSet(this, "persist", TCP_PERSIST_TIMEOUT));
1160 }
1161 
1162 
1163 void
1164 TCPEndpoint::_EnterTimeWait()
1165 {
1166 	TRACE("_EnterTimeWait()");
1167 
1168 	if (fState == TIME_WAIT) {
1169 		_CancelConnectionTimers();
1170 	}
1171 
1172 	_UpdateTimeWait();
1173 }
1174 
1175 
1176 void
1177 TCPEndpoint::_UpdateTimeWait()
1178 {
1179 	gStackModule->set_timer(&fTimeWaitTimer, TCP_MAX_SEGMENT_LIFETIME << 1);
1180 	T(TimerSet(this, "time-wait", TCP_MAX_SEGMENT_LIFETIME << 1));
1181 }
1182 
1183 
1184 void
1185 TCPEndpoint::_CancelConnectionTimers()
1186 {
1187 	gStackModule->cancel_timer(&fRetransmitTimer);
1188 	T(TimerSet(this, "retransmit", -1));
1189 	gStackModule->cancel_timer(&fPersistTimer);
1190 	T(TimerSet(this, "persist", -1));
1191 	gStackModule->cancel_timer(&fDelayedAcknowledgeTimer);
1192 	T(TimerSet(this, "delayed ack", -1));
1193 }
1194 
1195 
1196 /*!	Sends the FIN flag to the peer when the connection is still open.
1197 	Moves the endpoint to the next state depending on where it was.
1198 */
1199 status_t
1200 TCPEndpoint::_Disconnect(bool closing)
1201 {
1202 	tcp_state previousState = fState;
1203 
1204 	if (fState == SYNCHRONIZE_RECEIVED || fState == ESTABLISHED)
1205 		fState = FINISH_SENT;
1206 	else if (fState == FINISH_RECEIVED)
1207 		fState = WAIT_FOR_FINISH_ACKNOWLEDGE;
1208 	else
1209 		return B_OK;
1210 
1211 	T(State(this));
1212 
1213 	status_t status = _SendQueued();
1214 	if (status != B_OK) {
1215 		fState = previousState;
1216 		T(State(this));
1217 		return status;
1218 	}
1219 
1220 	return B_OK;
1221 }
1222 
1223 
1224 void
1225 TCPEndpoint::_MarkEstablished()
1226 {
1227 	fState = ESTABLISHED;
1228 	T(State(this));
1229 
1230 	gSocketModule->set_connected(socket);
1231 	if (gSocketModule->has_parent(socket))
1232 		release_sem_etc(fAcceptSemaphore, 1, B_DO_NOT_RESCHEDULE);
1233 
1234 	fSendCondition.NotifyAll();
1235 	gSocketModule->notify(socket, B_SELECT_WRITE, fSendQueue.Free());
1236 }
1237 
1238 
1239 status_t
1240 TCPEndpoint::_WaitForEstablished(MutexLocker &locker, bigtime_t timeout)
1241 {
1242 	// TODO: Checking for CLOSED seems correct, but breaks several neon tests.
1243 	// When investigating this, also have a look at _Close() and _HandleReset().
1244 	while (fState < ESTABLISHED/* && fState != CLOSED*/) {
1245 		if (socket->error != B_OK)
1246 			return socket->error;
1247 
1248 		status_t status = _WaitForCondition(fSendCondition, locker, timeout);
1249 		if (status < B_OK)
1250 			return status;
1251 	}
1252 
1253 	return B_OK;
1254 }
1255 
1256 
1257 //	#pragma mark - receive
1258 
1259 
1260 void
1261 TCPEndpoint::_Close()
1262 {
1263 	_CancelConnectionTimers();
1264 	fState = CLOSED;
1265 	T(State(this));
1266 
1267 	fFlags |= FLAG_DELETE_ON_CLOSE;
1268 
1269 	fSendCondition.NotifyAll();
1270 	_NotifyReader();
1271 
1272 	if (gSocketModule->has_parent(socket)) {
1273 		// We still have a parent - obviously, we haven't been accepted yet,
1274 		// so no one could ever close us.
1275 		_CancelConnectionTimers();
1276 		gSocketModule->set_aborted(socket);
1277 	}
1278 }
1279 
1280 
1281 void
1282 TCPEndpoint::_HandleReset(status_t error)
1283 {
1284 	socket->error = error;
1285 	_Close();
1286 
1287 	gSocketModule->notify(socket, B_SELECT_WRITE, error);
1288 	gSocketModule->notify(socket, B_SELECT_ERROR, error);
1289 }
1290 
1291 
1292 void
1293 TCPEndpoint::_DuplicateAcknowledge(tcp_segment_header &segment)
1294 {
1295 	if (fDuplicateAcknowledgeCount == 0)
1296 		fPreviousFlightSize = (fSendMax - fSendUnacknowledged).Number();
1297 
1298 	if (++fDuplicateAcknowledgeCount < 3) {
1299 		if (fSendQueue.Available(fSendMax) != 0  && fSendWindow != 0) {
1300 			fSendNext = fSendMax;
1301 			fCongestionWindow += fDuplicateAcknowledgeCount * fSendMaxSegmentSize;
1302 			_SendQueued();
1303 			TRACE("_DuplicateAcknowledge(): packet sent under limited transmit on receipt of dup ack");
1304 			fCongestionWindow -= fDuplicateAcknowledgeCount * fSendMaxSegmentSize;
1305 		}
1306 	}
1307 
1308 	if (fDuplicateAcknowledgeCount == 3) {
1309 		if ((segment.acknowledge - 1) > fRecover || (fCongestionWindow > fSendMaxSegmentSize &&
1310 			(fSendUnacknowledged - fPreviousHighestAcknowledge) <= 4 * fSendMaxSegmentSize)) {
1311 			fFlags |= FLAG_RECOVERY;
1312 			fRecover = fSendMax.Number() - 1;
1313 			fSlowStartThreshold = max_c(fPreviousFlightSize / 2, 2 * fSendMaxSegmentSize);
1314 			fCongestionWindow = fSlowStartThreshold + 3 * fSendMaxSegmentSize;
1315 			fSendNext = segment.acknowledge;
1316 			_SendQueued();
1317 			TRACE("_DuplicateAcknowledge(): packet sent under fast restransmit on the receipt of 3rd dup ack");
1318 		}
1319 	} else if (fDuplicateAcknowledgeCount > 3) {
1320 		uint32 flightSize = (fSendMax - fSendUnacknowledged).Number();
1321 		if ((fDuplicateAcknowledgeCount - 3) * fSendMaxSegmentSize <= flightSize)
1322 			fCongestionWindow += fSendMaxSegmentSize;
1323 		if (fSendQueue.Available(fSendMax) != 0) {
1324 			fSendNext = fSendMax;
1325 			_SendQueued();
1326 		}
1327 	}
1328 }
1329 
1330 
1331 void
1332 TCPEndpoint::_UpdateTimestamps(tcp_segment_header& segment,
1333 	size_t segmentLength)
1334 {
1335 	if (fFlags & FLAG_OPTION_TIMESTAMP) {
1336 		tcp_sequence sequence(segment.sequence);
1337 
1338 		if (fLastAcknowledgeSent >= sequence
1339 			&& fLastAcknowledgeSent < (sequence + segmentLength))
1340 			fReceivedTimestamp = segment.timestamp_value;
1341 	}
1342 }
1343 
1344 
1345 ssize_t
1346 TCPEndpoint::_AvailableData() const
1347 {
1348 	// TODO: Refer to the FLAG_NO_RECEIVE comment above regarding
1349 	//       the application of FLAG_NO_RECEIVE in listen()ing
1350 	//       sockets.
1351 	if (fState == LISTEN)
1352 		return gSocketModule->count_connected(socket);
1353 	if (fState == SYNCHRONIZE_SENT)
1354 		return 0;
1355 
1356 	ssize_t availableData = fReceiveQueue.Available();
1357 
1358 	if (availableData == 0 && !_ShouldReceive())
1359 		return ENOTCONN;
1360 	if (availableData == 0 && (fState == FINISH_RECEIVED || fState == WAIT_FOR_FINISH_ACKNOWLEDGE))
1361 		return ESHUTDOWN;
1362 	return availableData;
1363 }
1364 
1365 
1366 void
1367 TCPEndpoint::_NotifyReader()
1368 {
1369 	fReceiveCondition.NotifyAll();
1370 	gSocketModule->notify(socket, B_SELECT_READ, _AvailableData());
1371 }
1372 
1373 
1374 bool
1375 TCPEndpoint::_AddData(tcp_segment_header& segment, net_buffer* buffer)
1376 {
1377 	if ((segment.flags & TCP_FLAG_FINISH) != 0) {
1378 		// Remember the position of the finish received flag
1379 		fFinishReceived = true;
1380 		fFinishReceivedAt = segment.sequence + buffer->size;
1381 	}
1382 
1383 	fReceiveQueue.Add(buffer, segment.sequence);
1384 	fReceiveNext = fReceiveQueue.NextSequence();
1385 
1386 	if (fFinishReceived) {
1387 		// Set or reset the finish flag on the current segment
1388 		if (fReceiveNext < fFinishReceivedAt)
1389 			segment.flags &= ~TCP_FLAG_FINISH;
1390 		else
1391 			segment.flags |= TCP_FLAG_FINISH;
1392 	}
1393 
1394 	TRACE("  _AddData(): adding data, receive next = %" B_PRIu32 ". Now have %"
1395 		B_PRIuSIZE " bytes.", fReceiveNext.Number(), fReceiveQueue.Available());
1396 
1397 	if ((segment.flags & TCP_FLAG_PUSH) != 0)
1398 		fReceiveQueue.SetPushPointer();
1399 
1400 	return fReceiveQueue.Available() > 0;
1401 }
1402 
1403 
1404 void
1405 TCPEndpoint::_PrepareReceivePath(tcp_segment_header& segment)
1406 {
1407 	fInitialReceiveSequence = segment.sequence;
1408 	fFinishReceived = false;
1409 
1410 	// count the received SYN
1411 	segment.sequence++;
1412 
1413 	fReceiveNext = segment.sequence;
1414 	fReceiveQueue.SetInitialSequence(segment.sequence);
1415 
1416 	if ((fOptions & TCP_NOOPT) == 0) {
1417 		if (segment.max_segment_size > 0) {
1418 			// The maximum size of a segment that a TCP endpoint really sends,
1419 			// the "effective send MSS", MUST be the smaller of the send MSS and
1420 			// the largest transmission size permitted by the IP layer:
1421 			fSendMaxSegmentSize = min_c(segment.max_segment_size,
1422 				_MaxSegmentSize(*PeerAddress()));
1423 		}
1424 
1425 		if (segment.options & TCP_HAS_WINDOW_SCALE) {
1426 			fFlags |= FLAG_OPTION_WINDOW_SCALE;
1427 			fSendWindowShift = segment.window_shift;
1428 		} else {
1429 			fFlags &= ~FLAG_OPTION_WINDOW_SCALE;
1430 			fReceiveWindowShift = 0;
1431 		}
1432 
1433 		if (segment.options & TCP_HAS_TIMESTAMPS) {
1434 			fFlags |= FLAG_OPTION_TIMESTAMP;
1435 			fReceivedTimestamp = segment.timestamp_value;
1436 		} else
1437 			fFlags &= ~FLAG_OPTION_TIMESTAMP;
1438 
1439 		if ((segment.options & TCP_SACK_PERMITTED) == 0)
1440 			fFlags &= ~FLAG_OPTION_SACK_PERMITTED;
1441 	}
1442 
1443 	if (fSendMaxSegmentSize > 2190)
1444 		fCongestionWindow = 2 * fSendMaxSegmentSize;
1445 	else if (fSendMaxSegmentSize > 1095)
1446 		fCongestionWindow = 3 * fSendMaxSegmentSize;
1447 	else
1448 		fCongestionWindow = 4 * fSendMaxSegmentSize;
1449 
1450 	fSendMaxSegments = fCongestionWindow / fSendMaxSegmentSize;
1451 	fSlowStartThreshold = (uint32)segment.advertised_window << fSendWindowShift;
1452 }
1453 
1454 
1455 bool
1456 TCPEndpoint::_ShouldReceive() const
1457 {
1458 	if ((fFlags & FLAG_NO_RECEIVE) != 0)
1459 		return false;
1460 
1461 	return fState == ESTABLISHED || fState == FINISH_SENT
1462 		|| fState == FINISH_ACKNOWLEDGED || fState == FINISH_RECEIVED;
1463 }
1464 
1465 
1466 int32
1467 TCPEndpoint::_Spawn(TCPEndpoint* parent, tcp_segment_header& segment,
1468 	net_buffer* buffer)
1469 {
1470 	MutexLocker _(fLock);
1471 
1472 	// TODO error checking
1473 	ProtocolSocket::Open();
1474 
1475 	fState = SYNCHRONIZE_RECEIVED;
1476 	T(Spawn(parent, this));
1477 
1478 	fManager = parent->fManager;
1479 
1480 	LocalAddress().SetTo(buffer->destination);
1481 	PeerAddress().SetTo(buffer->source);
1482 
1483 	TRACE("Spawn()");
1484 
1485 	// TODO: proper error handling!
1486 	if (fManager->BindChild(this) != B_OK) {
1487 		T(Error(this, "binding failed", __LINE__));
1488 		return DROP;
1489 	}
1490 	if (_PrepareSendPath(*PeerAddress()) != B_OK) {
1491 		T(Error(this, "prepare send faild", __LINE__));
1492 		return DROP;
1493 	}
1494 
1495 	fOptions = parent->fOptions;
1496 	fAcceptSemaphore = parent->fAcceptSemaphore;
1497 
1498 	_PrepareReceivePath(segment);
1499 
1500 	// send SYN+ACK
1501 	if (_SendQueued() != B_OK) {
1502 		T(Error(this, "sending failed", __LINE__));
1503 		return DROP;
1504 	}
1505 
1506 	segment.flags &= ~TCP_FLAG_SYNCHRONIZE;
1507 		// we handled this flag now, it must not be set for further processing
1508 
1509 	return _Receive(segment, buffer);
1510 }
1511 
1512 
1513 int32
1514 TCPEndpoint::_ListenReceive(tcp_segment_header& segment, net_buffer* buffer)
1515 {
1516 	TRACE("ListenReceive()");
1517 
1518 	// Essentially, we accept only TCP_FLAG_SYNCHRONIZE in this state,
1519 	// but the error behaviour differs
1520 	if (segment.flags & TCP_FLAG_RESET)
1521 		return DROP;
1522 	if (segment.flags & TCP_FLAG_ACKNOWLEDGE)
1523 		return DROP | RESET;
1524 	if ((segment.flags & TCP_FLAG_SYNCHRONIZE) == 0)
1525 		return DROP;
1526 
1527 	// TODO: drop broadcast/multicast
1528 
1529 	// spawn new endpoint for accept()
1530 	net_socket* newSocket;
1531 	if (gSocketModule->spawn_pending_socket(socket, &newSocket) < B_OK) {
1532 		T(Error(this, "spawning failed", __LINE__));
1533 		return DROP;
1534 	}
1535 
1536 	return ((TCPEndpoint *)newSocket->first_protocol)->_Spawn(this,
1537 		segment, buffer);
1538 }
1539 
1540 
1541 int32
1542 TCPEndpoint::_SynchronizeSentReceive(tcp_segment_header &segment,
1543 	net_buffer *buffer)
1544 {
1545 	TRACE("_SynchronizeSentReceive()");
1546 
1547 	if ((segment.flags & TCP_FLAG_ACKNOWLEDGE) != 0
1548 		&& (fInitialSendSequence >= segment.acknowledge
1549 			|| fSendMax < segment.acknowledge))
1550 		return DROP | RESET;
1551 
1552 	if (segment.flags & TCP_FLAG_RESET) {
1553 		_HandleReset(ECONNREFUSED);
1554 		return DROP;
1555 	}
1556 
1557 	if ((segment.flags & TCP_FLAG_SYNCHRONIZE) == 0)
1558 		return DROP;
1559 
1560 	fSendUnacknowledged = segment.acknowledge;
1561 	_PrepareReceivePath(segment);
1562 
1563 	if (segment.flags & TCP_FLAG_ACKNOWLEDGE) {
1564 		_MarkEstablished();
1565 	} else {
1566 		// simultaneous open
1567 		fState = SYNCHRONIZE_RECEIVED;
1568 		T(State(this));
1569 	}
1570 
1571 	segment.flags &= ~TCP_FLAG_SYNCHRONIZE;
1572 		// we handled this flag now, it must not be set for further processing
1573 
1574 	return _Receive(segment, buffer) | IMMEDIATE_ACKNOWLEDGE;
1575 }
1576 
1577 
1578 int32
1579 TCPEndpoint::_Receive(tcp_segment_header& segment, net_buffer* buffer)
1580 {
1581 	// PAWS processing takes precedence over regular TCP acceptability check
1582 	if ((fFlags & FLAG_OPTION_TIMESTAMP) != 0 && (segment.flags & TCP_FLAG_RESET) == 0) {
1583 		if ((segment.options & TCP_HAS_TIMESTAMPS) == 0)
1584 			return DROP;
1585 		if ((int32)(fReceivedTimestamp - segment.timestamp_value) > 0
1586 			&& (fReceivedTimestamp - segment.timestamp_value) <= INT32_MAX)
1587 			return DROP | IMMEDIATE_ACKNOWLEDGE;
1588 	}
1589 
1590 	uint32 advertisedWindow = (uint32)segment.advertised_window
1591 		<< fSendWindowShift;
1592 	size_t segmentLength = buffer->size;
1593 
1594 	// First, handle the most common case for uni-directional data transfer
1595 	// (known as header prediction - the segment must not change the window,
1596 	// and must be the expected sequence, and contain no control flags)
1597 
1598 	if (fState == ESTABLISHED
1599 		&& segment.AcknowledgeOnly()
1600 		&& fReceiveNext == segment.sequence
1601 		&& advertisedWindow > 0 && advertisedWindow == fSendWindow
1602 		&& fSendNext == fSendMax) {
1603 		_UpdateTimestamps(segment, segmentLength);
1604 
1605 		if (segmentLength == 0) {
1606 			// this is a pure acknowledge segment - we're on the sending end
1607 			if (fSendUnacknowledged < segment.acknowledge
1608 				&& fSendMax >= segment.acknowledge) {
1609 				_Acknowledged(segment);
1610 				return DROP;
1611 			}
1612 		} else if (segment.acknowledge == fSendUnacknowledged
1613 			&& fReceiveQueue.IsContiguous()
1614 			&& fReceiveQueue.Free() >= segmentLength
1615 			&& (fFlags & FLAG_NO_RECEIVE) == 0) {
1616 			if (_AddData(segment, buffer))
1617 				_NotifyReader();
1618 
1619 			return KEEP | ((segment.flags & TCP_FLAG_PUSH) != 0
1620 				? IMMEDIATE_ACKNOWLEDGE : ACKNOWLEDGE);
1621 		}
1622 	}
1623 
1624 	// The fast path was not applicable, so we continue with the standard
1625 	// processing of the incoming segment
1626 
1627 	ASSERT(fState != SYNCHRONIZE_SENT && fState != LISTEN);
1628 
1629 	if (fState != CLOSED && fState != TIME_WAIT) {
1630 		// Check sequence number
1631 		if (!segment_in_sequence(segment, segmentLength, fReceiveNext,
1632 				fReceiveWindow)) {
1633 			TRACE("  Receive(): segment out of window, next: %" B_PRIu32
1634 				" wnd: %" B_PRIu32, fReceiveNext.Number(), fReceiveWindow);
1635 			if ((segment.flags & TCP_FLAG_RESET) != 0) {
1636 				// TODO: this doesn't look right - review!
1637 				return DROP;
1638 			}
1639 			return DROP | IMMEDIATE_ACKNOWLEDGE;
1640 		}
1641 	}
1642 
1643 	if ((segment.flags & TCP_FLAG_RESET) != 0) {
1644 		// Is this a valid reset?
1645 		// We generally ignore resets in time wait state (see RFC 1337)
1646 		if (fLastAcknowledgeSent <= segment.sequence
1647 			&& tcp_sequence(segment.sequence) < (fLastAcknowledgeSent
1648 				+ fReceiveWindow)
1649 			&& fState != TIME_WAIT) {
1650 			status_t error;
1651 			if (fState == SYNCHRONIZE_RECEIVED)
1652 				error = ECONNREFUSED;
1653 			else if (fState == CLOSING || fState == WAIT_FOR_FINISH_ACKNOWLEDGE)
1654 				error = ENOTCONN;
1655 			else
1656 				error = ECONNRESET;
1657 
1658 			_HandleReset(error);
1659 		}
1660 
1661 		return DROP;
1662 	}
1663 
1664 	if ((segment.flags & TCP_FLAG_SYNCHRONIZE) != 0
1665 		|| (fState == SYNCHRONIZE_RECEIVED
1666 			&& (fInitialReceiveSequence > segment.sequence
1667 				|| ((segment.flags & TCP_FLAG_ACKNOWLEDGE) != 0
1668 					&& (fSendUnacknowledged > segment.acknowledge
1669 						|| fSendMax < segment.acknowledge))))) {
1670 		// reset the connection - either the initial SYN was faulty, or we
1671 		// received a SYN within the data stream
1672 		return DROP | RESET;
1673 	}
1674 
1675 	// TODO: Check this! Why do we advertize a window outside of what we should
1676 	// buffer?
1677 	fReceiveWindow = max_c(fReceiveQueue.Free(), fReceiveWindow);
1678 		// the window must not shrink
1679 
1680 	// trim buffer to be within the receive window
1681 	int32 drop = (int32)(fReceiveNext - segment.sequence).Number();
1682 	if (drop > 0) {
1683 		if ((uint32)drop > buffer->size
1684 			|| ((uint32)drop == buffer->size
1685 				&& (segment.flags & TCP_FLAG_FINISH) == 0)) {
1686 			// don't accidently remove a FIN we shouldn't remove
1687 			segment.flags &= ~TCP_FLAG_FINISH;
1688 			drop = buffer->size;
1689 		}
1690 
1691 		// remove duplicate data at the start
1692 		TRACE("* remove %" B_PRId32 " bytes from the start", drop);
1693 		gBufferModule->remove_header(buffer, drop);
1694 		segment.sequence += drop;
1695 	}
1696 
1697 	int32 action = KEEP;
1698 
1699 	// immediately acknowledge out-of-order segment to trigger fast-retransmit at the sender
1700 	if (drop != 0)
1701 		action |= IMMEDIATE_ACKNOWLEDGE;
1702 
1703 	drop = (int32)(segment.sequence + buffer->size
1704 		- (fReceiveNext + fReceiveWindow)).Number();
1705 	if (drop > 0) {
1706 		// remove data exceeding our window
1707 		if ((uint32)drop >= buffer->size) {
1708 			// if we can accept data, or the segment is not what we'd expect,
1709 			// drop the segment (an immediate acknowledge is always triggered)
1710 			if (fReceiveWindow != 0 || segment.sequence != fReceiveNext)
1711 				return DROP | IMMEDIATE_ACKNOWLEDGE;
1712 
1713 			action |= IMMEDIATE_ACKNOWLEDGE;
1714 		}
1715 
1716 		if ((segment.flags & TCP_FLAG_FINISH) != 0) {
1717 			// we need to remove the finish, too, as part of the data
1718 			drop--;
1719 		}
1720 
1721 		segment.flags &= ~(TCP_FLAG_FINISH | TCP_FLAG_PUSH);
1722 		TRACE("* remove %" B_PRId32 " bytes from the end", drop);
1723 		gBufferModule->remove_trailer(buffer, drop);
1724 	}
1725 
1726 #ifdef TRACE_TCP
1727 	if (advertisedWindow > fSendWindow) {
1728 		TRACE("  Receive(): Window update %" B_PRIu32 " -> %" B_PRIu32,
1729 			fSendWindow, advertisedWindow);
1730 	}
1731 #endif
1732 
1733 	if (advertisedWindow > fSendWindow)
1734 		action |= IMMEDIATE_ACKNOWLEDGE;
1735 
1736 	fSendWindow = advertisedWindow;
1737 	if (advertisedWindow > fSendMaxWindow)
1738 		fSendMaxWindow = advertisedWindow;
1739 
1740 	// Then look at the acknowledgement for any updates
1741 
1742 	if ((segment.flags & TCP_FLAG_ACKNOWLEDGE) != 0) {
1743 		// process acknowledged data
1744 		if (fState == SYNCHRONIZE_RECEIVED)
1745 			_MarkEstablished();
1746 
1747 		if (fSendMax < segment.acknowledge)
1748 			return DROP | IMMEDIATE_ACKNOWLEDGE;
1749 
1750 		if (segment.acknowledge == fSendUnacknowledged) {
1751 			if (buffer->size == 0 && advertisedWindow == fSendWindow
1752 				&& (segment.flags & TCP_FLAG_FINISH) == 0 && fSendUnacknowledged != fSendMax) {
1753 				TRACE("Receive(): duplicate ack!");
1754 				_DuplicateAcknowledge(segment);
1755 			}
1756 		} else if (segment.acknowledge < fSendUnacknowledged) {
1757 			return DROP;
1758 		} else {
1759 			// this segment acknowledges in flight data
1760 
1761 			if (fDuplicateAcknowledgeCount >= 3) {
1762 				// deflate the window.
1763 				if (segment.acknowledge > fRecover) {
1764 					uint32 flightSize = (fSendMax - fSendUnacknowledged).Number();
1765 					fCongestionWindow = min_c(fSlowStartThreshold,
1766 						max_c(flightSize, fSendMaxSegmentSize) + fSendMaxSegmentSize);
1767 					fFlags &= ~FLAG_RECOVERY;
1768 				}
1769 			}
1770 
1771 			if (fSendMax == segment.acknowledge)
1772 				TRACE("Receive(): all inflight data ack'd!");
1773 
1774 			if (segment.acknowledge > fSendQueue.LastSequence()
1775 					&& fState > ESTABLISHED) {
1776 				TRACE("Receive(): FIN has been acknowledged!");
1777 
1778 				switch (fState) {
1779 					case FINISH_SENT:
1780 						fState = FINISH_ACKNOWLEDGED;
1781 						T(State(this));
1782 						break;
1783 					case CLOSING:
1784 						fState = TIME_WAIT;
1785 						T(State(this));
1786 						_EnterTimeWait();
1787 						return DROP;
1788 					case WAIT_FOR_FINISH_ACKNOWLEDGE:
1789 						_Close();
1790 						break;
1791 
1792 					default:
1793 						break;
1794 				}
1795 			}
1796 
1797 			if (fState != CLOSED) {
1798 				tcp_sequence last = fLastAcknowledgeSent;
1799 				_Acknowledged(segment);
1800 				// we just sent an acknowledge, remove from action
1801 				if (last < fLastAcknowledgeSent)
1802 					action &= ~IMMEDIATE_ACKNOWLEDGE;
1803 			}
1804 		}
1805 	}
1806 
1807 	if (segment.flags & TCP_FLAG_URGENT) {
1808 		if (fState == ESTABLISHED || fState == FINISH_SENT
1809 			|| fState == FINISH_ACKNOWLEDGED) {
1810 			// TODO: Handle urgent data:
1811 			//  - RCV.UP <- max(RCV.UP, SEG.UP)
1812 			//  - signal the user that urgent data is available (SIGURG)
1813 		}
1814 	}
1815 
1816 	bool notify = false;
1817 
1818 	// The buffer may be freed if its data is added to the queue, so cache
1819 	// the size as we still need it later.
1820 	uint32 bufferSize = buffer->size;
1821 
1822 	if ((bufferSize > 0 || (segment.flags & TCP_FLAG_FINISH) != 0)
1823 		&& _ShouldReceive())
1824 		notify = _AddData(segment, buffer);
1825 	else {
1826 		if ((fFlags & FLAG_NO_RECEIVE) != 0)
1827 			fReceiveNext += buffer->size;
1828 
1829 		action = (action & ~KEEP) | DROP;
1830 	}
1831 
1832 	if ((segment.flags & TCP_FLAG_FINISH) != 0) {
1833 		segmentLength++;
1834 		if (fState != CLOSED && fState != LISTEN && fState != SYNCHRONIZE_SENT) {
1835 			TRACE("Receive(): peer is finishing connection!");
1836 			fReceiveNext++;
1837 			notify = true;
1838 
1839 			// FIN implies PUSH
1840 			fReceiveQueue.SetPushPointer();
1841 
1842 			// we'll reply immediately to the FIN if we are not
1843 			// transitioning to TIME WAIT so we immediatly ACK it.
1844 			action |= IMMEDIATE_ACKNOWLEDGE;
1845 
1846 			// other side is closing connection; change states
1847 			switch (fState) {
1848 				case ESTABLISHED:
1849 				case SYNCHRONIZE_RECEIVED:
1850 					fState = FINISH_RECEIVED;
1851 					T(State(this));
1852 					break;
1853 				case FINISH_SENT:
1854 					// simultaneous close
1855 					fState = CLOSING;
1856 					T(State(this));
1857 					break;
1858 				case FINISH_ACKNOWLEDGED:
1859 					fState = TIME_WAIT;
1860 					T(State(this));
1861 					_EnterTimeWait();
1862 					break;
1863 				case TIME_WAIT:
1864 					_UpdateTimeWait();
1865 					break;
1866 
1867 				default:
1868 					break;
1869 			}
1870 		}
1871 	}
1872 
1873 	if (notify)
1874 		_NotifyReader();
1875 
1876 	if (bufferSize > 0 || (segment.flags & TCP_FLAG_SYNCHRONIZE) != 0)
1877 		action |= ACKNOWLEDGE;
1878 
1879 	_UpdateTimestamps(segment, segmentLength);
1880 
1881 	TRACE("Receive() Action %" B_PRId32, action);
1882 
1883 	return action;
1884 }
1885 
1886 
1887 int32
1888 TCPEndpoint::SegmentReceived(tcp_segment_header& segment, net_buffer* buffer)
1889 {
1890 	MutexLocker locker(fLock);
1891 
1892 	TRACE("SegmentReceived(): buffer %p (%" B_PRIu32 " bytes) address %s "
1893 		"to %s flags %#" B_PRIx8 ", seq %" B_PRIu32 ", ack %" B_PRIu32
1894 		", wnd %" B_PRIu32, buffer, buffer->size, PrintAddress(buffer->source),
1895 		PrintAddress(buffer->destination), segment.flags, segment.sequence,
1896 		segment.acknowledge,
1897 		(uint32)segment.advertised_window << fSendWindowShift);
1898 	T(Receive(this, segment,
1899 		(uint32)segment.advertised_window << fSendWindowShift, buffer));
1900 	int32 segmentAction = DROP;
1901 
1902 	switch (fState) {
1903 		case LISTEN:
1904 			segmentAction = _ListenReceive(segment, buffer);
1905 			break;
1906 
1907 		case SYNCHRONIZE_SENT:
1908 			segmentAction = _SynchronizeSentReceive(segment, buffer);
1909 			break;
1910 
1911 		case SYNCHRONIZE_RECEIVED:
1912 		case ESTABLISHED:
1913 		case FINISH_RECEIVED:
1914 		case WAIT_FOR_FINISH_ACKNOWLEDGE:
1915 		case FINISH_SENT:
1916 		case FINISH_ACKNOWLEDGED:
1917 		case CLOSING:
1918 		case TIME_WAIT:
1919 		case CLOSED:
1920 			segmentAction = _Receive(segment, buffer);
1921 			break;
1922 	}
1923 
1924 	// process acknowledge action as asked for by the *Receive() method
1925 	if (segmentAction & IMMEDIATE_ACKNOWLEDGE)
1926 		SendAcknowledge(true);
1927 	else if (segmentAction & ACKNOWLEDGE)
1928 		DelayedAcknowledge();
1929 
1930 	if ((fFlags & (FLAG_CLOSED | FLAG_DELETE_ON_CLOSE))
1931 			== (FLAG_CLOSED | FLAG_DELETE_ON_CLOSE)) {
1932 
1933 		locker.Unlock();
1934 		if (gSocketModule->release_socket(socket))
1935 			segmentAction |= DELETED_ENDPOINT;
1936 	}
1937 
1938 	return segmentAction;
1939 }
1940 
1941 
1942 //	#pragma mark - send
1943 
1944 
1945 inline uint8
1946 TCPEndpoint::_CurrentFlags()
1947 {
1948 	// we don't set FLAG_FINISH here, instead we do it
1949 	// conditionally below depending if we are sending
1950 	// the last bytes of the send queue.
1951 
1952 	switch (fState) {
1953 		case CLOSED:
1954 			return TCP_FLAG_RESET | TCP_FLAG_ACKNOWLEDGE;
1955 
1956 		case SYNCHRONIZE_SENT:
1957 			return TCP_FLAG_SYNCHRONIZE;
1958 		case SYNCHRONIZE_RECEIVED:
1959 			return TCP_FLAG_SYNCHRONIZE | TCP_FLAG_ACKNOWLEDGE;
1960 
1961 		case ESTABLISHED:
1962 		case FINISH_RECEIVED:
1963 		case FINISH_ACKNOWLEDGED:
1964 		case TIME_WAIT:
1965 		case WAIT_FOR_FINISH_ACKNOWLEDGE:
1966 		case FINISH_SENT:
1967 		case CLOSING:
1968 			return TCP_FLAG_ACKNOWLEDGE;
1969 
1970 		default:
1971 			return 0;
1972 	}
1973 }
1974 
1975 
1976 inline bool
1977 TCPEndpoint::_ShouldSendSegment(tcp_segment_header& segment, uint32 length,
1978 	uint32 segmentMaxSize, uint32 flightSize)
1979 {
1980 	if (fState == ESTABLISHED && fSendMaxSegments == 0)
1981 		return false;
1982 
1983 	if (length > 0) {
1984 		// Avoid the silly window syndrome - we only send a segment in case:
1985 		// - we have a full segment to send, or
1986 		// - we're at the end of our buffer queue, or
1987 		// - the buffer is at least larger than half of the maximum send window,
1988 		//   or
1989 		// - we're retransmitting data
1990 		if (length == segmentMaxSize
1991 			|| (fOptions & TCP_NODELAY) != 0
1992 			|| tcp_sequence(fSendNext + length) == fSendQueue.LastSequence()
1993 			|| (fSendMaxWindow > 0 && length >= fSendMaxWindow / 2))
1994 			return true;
1995 	}
1996 
1997 	// check if we need to send a window update to the peer
1998 	if (segment.advertised_window > 0) {
1999 		// correct the window to take into account what already has been advertised
2000 		uint32 window = (segment.advertised_window << fReceiveWindowShift)
2001 			- (fReceiveMaxAdvertised - fReceiveNext).Number();
2002 
2003 		// if we can advertise a window larger than twice the maximum segment
2004 		// size, or half the maximum buffer size we send a window update
2005 		if (window >= (fReceiveMaxSegmentSize << 1)
2006 			|| window >= (socket->receive.buffer_size >> 1))
2007 			return true;
2008 	}
2009 
2010 	if ((segment.flags & (TCP_FLAG_SYNCHRONIZE | TCP_FLAG_FINISH
2011 			| TCP_FLAG_RESET)) != 0)
2012 		return true;
2013 
2014 	// We do have urgent data pending
2015 	if (fSendUrgentOffset > fSendNext)
2016 		return true;
2017 
2018 	// there is no reason to send a segment just now
2019 	return false;
2020 }
2021 
2022 
2023 status_t
2024 TCPEndpoint::_SendQueued(bool force)
2025 {
2026 	return _SendQueued(force, fSendWindow);
2027 }
2028 
2029 
2030 /*!	Sends one or more TCP segments with the data waiting in the queue, or some
2031 	specific flags that need to be sent.
2032 */
2033 status_t
2034 TCPEndpoint::_SendQueued(bool force, uint32 sendWindow)
2035 {
2036 	if (fRoute == NULL)
2037 		return B_ERROR;
2038 
2039 	// in passive state?
2040 	if (fState == LISTEN)
2041 		return B_ERROR;
2042 
2043 	tcp_segment_header segment(_CurrentFlags());
2044 
2045 	if ((fOptions & TCP_NOOPT) == 0) {
2046 		if ((fFlags & FLAG_OPTION_TIMESTAMP) != 0) {
2047 			segment.options |= TCP_HAS_TIMESTAMPS;
2048 			segment.timestamp_reply = fReceivedTimestamp;
2049 			segment.timestamp_value = tcp_now();
2050 		}
2051 
2052 		// SACK information is embedded with duplicate acknowledgements
2053 		if (!fReceiveQueue.IsContiguous()
2054 			&& fLastAcknowledgeSent <= fReceiveNext
2055 			&& (fFlags & FLAG_OPTION_SACK_PERMITTED) != 0) {
2056 			segment.options |= TCP_HAS_SACK;
2057 			int maxSackCount = MAX_SACK_BLKS
2058 				- ((fFlags & FLAG_OPTION_TIMESTAMP) != 0);
2059 			memset(segment.sacks, 0, sizeof(segment.sacks));
2060 			segment.sackCount = fReceiveQueue.PopulateSackInfo(fReceiveNext,
2061 				maxSackCount, segment.sacks);
2062 		}
2063 
2064 		if ((segment.flags & TCP_FLAG_SYNCHRONIZE) != 0
2065 			&& fSendNext == fInitialSendSequence) {
2066 			// add connection establishment options
2067 			segment.max_segment_size = fReceiveMaxSegmentSize;
2068 			if (fFlags & FLAG_OPTION_WINDOW_SCALE) {
2069 				segment.options |= TCP_HAS_WINDOW_SCALE;
2070 				segment.window_shift = fReceiveWindowShift;
2071 			}
2072 			if ((fFlags & FLAG_OPTION_SACK_PERMITTED) != 0)
2073 				segment.options |= TCP_SACK_PERMITTED;
2074 		}
2075 	}
2076 
2077 	size_t availableBytes = fReceiveQueue.Free();
2078 	// window size must remain same for duplicate acknowledgements
2079 	if (!fReceiveQueue.IsContiguous())
2080 		availableBytes = (fReceiveMaxAdvertised - fReceiveNext).Number();
2081 
2082 	if (fFlags & FLAG_OPTION_WINDOW_SCALE)
2083 		availableBytes >>= fReceiveWindowShift;
2084 	segment.advertised_window = min_c(TCP_MAX_WINDOW, availableBytes);
2085 
2086 	segment.acknowledge = fReceiveNext.Number();
2087 
2088 	// Process urgent data
2089 	if (fSendUrgentOffset > fSendNext) {
2090 		segment.flags |= TCP_FLAG_URGENT;
2091 		segment.urgent_offset = (fSendUrgentOffset - fSendNext).Number();
2092 	} else {
2093 		fSendUrgentOffset = fSendUnacknowledged.Number();
2094 			// Keep urgent offset updated, so that it doesn't reach into our
2095 			// send window on overlap
2096 		segment.urgent_offset = 0;
2097 	}
2098 
2099 	if (fCongestionWindow > 0 && fCongestionWindow < sendWindow)
2100 		sendWindow = fCongestionWindow;
2101 
2102 	// fSendUnacknowledged
2103 	//  |    fSendNext      fSendMax
2104 	//  |        |              |
2105 	//  v        v              v
2106 	//  -----------------------------------
2107 	//  | effective window           |
2108 	//  -----------------------------------
2109 
2110 	// Flight size represents the window of data which is currently in the
2111 	// ether. We should never send data such as the flight size becomes larger
2112 	// than the effective window. Note however that the effective window may be
2113 	// reduced (by congestion for instance), so at some point in time flight
2114 	// size may be larger than the currently calculated window.
2115 
2116 	uint32 flightSize = (fSendMax - fSendUnacknowledged).Number();
2117 	uint32 consumedWindow = (fSendNext - fSendUnacknowledged).Number();
2118 
2119 	if (consumedWindow > sendWindow) {
2120 		sendWindow = 0;
2121 		// TODO: enter persist state? try to get a window update.
2122 	} else
2123 		sendWindow -= consumedWindow;
2124 
2125 	uint32 length = min_c(fSendQueue.Available(fSendNext), sendWindow);
2126 	bool shouldStartRetransmitTimer = fSendNext == fSendUnacknowledged;
2127 	bool retransmit = fSendNext < fSendMax;
2128 
2129 	if (fDuplicateAcknowledgeCount != 0) {
2130 		// send at most 1 SMSS of data when under limited transmit, fast transmit/recovery
2131 		length = min_c(length, fSendMaxSegmentSize);
2132 	}
2133 
2134 	do {
2135 		uint32 segmentMaxSize = fSendMaxSegmentSize
2136 			- tcp_options_length(segment);
2137 		uint32 segmentLength = min_c(length, segmentMaxSize);
2138 
2139 		if (fSendNext + segmentLength == fSendQueue.LastSequence() && !force) {
2140 			if (state_needs_finish(fState))
2141 				segment.flags |= TCP_FLAG_FINISH;
2142 			if (length > 0)
2143 				segment.flags |= TCP_FLAG_PUSH;
2144 		}
2145 
2146 		// Determine if we should really send this segment
2147 		if (!force && !retransmit && !_ShouldSendSegment(segment, segmentLength,
2148 				segmentMaxSize, flightSize)) {
2149 			if (fSendQueue.Available()
2150 				&& !gStackModule->is_timer_active(&fPersistTimer)
2151 				&& !gStackModule->is_timer_active(&fRetransmitTimer))
2152 				_StartPersistTimer();
2153 			break;
2154 		}
2155 
2156 		net_buffer *buffer = gBufferModule->create(256);
2157 		if (buffer == NULL)
2158 			return B_NO_MEMORY;
2159 
2160 		status_t status = B_OK;
2161 		if (segmentLength > 0)
2162 			status = fSendQueue.Get(buffer, fSendNext, segmentLength);
2163 		if (status < B_OK) {
2164 			gBufferModule->free(buffer);
2165 			return status;
2166 		}
2167 
2168 		LocalAddress().CopyTo(buffer->source);
2169 		PeerAddress().CopyTo(buffer->destination);
2170 
2171 		uint32 size = buffer->size;
2172 		segment.sequence = fSendNext.Number();
2173 
2174 		TRACE("SendQueued(): buffer %p (%" B_PRIu32 " bytes) address %s to "
2175 			"%s flags %#" B_PRIx8 ", seq %" B_PRIu32 ", ack %" B_PRIu32
2176 			", rwnd %" B_PRIu16 ", cwnd %" B_PRIu32 ", ssthresh %" B_PRIu32
2177 			", len %" B_PRIu32 ", first %" B_PRIu32 ", last %" B_PRIu32,
2178 			buffer, buffer->size, PrintAddress(buffer->source),
2179 			PrintAddress(buffer->destination), segment.flags, segment.sequence,
2180 			segment.acknowledge, segment.advertised_window,
2181 			fCongestionWindow, fSlowStartThreshold, segmentLength,
2182 			fSendQueue.FirstSequence().Number(),
2183 			fSendQueue.LastSequence().Number());
2184 		T(Send(this, segment, buffer, fSendQueue.FirstSequence(),
2185 			fSendQueue.LastSequence()));
2186 
2187 		PROBE(buffer, sendWindow);
2188 		sendWindow -= buffer->size;
2189 
2190 		status = add_tcp_header(AddressModule(), segment, buffer);
2191 		if (status != B_OK) {
2192 			gBufferModule->free(buffer);
2193 			return status;
2194 		}
2195 
2196 		// Update send status - we need to do this before we send the data
2197 		// for local connections as the answer is directly handled
2198 
2199 		if (segment.flags & TCP_FLAG_SYNCHRONIZE) {
2200 			segment.options &= ~TCP_HAS_WINDOW_SCALE;
2201 			segment.max_segment_size = 0;
2202 			size++;
2203 		}
2204 
2205 		if (segment.flags & TCP_FLAG_FINISH)
2206 			size++;
2207 
2208 		uint32 sendMax = fSendMax.Number();
2209 		fSendNext += size;
2210 		if (fSendMax < fSendNext)
2211 			fSendMax = fSendNext;
2212 
2213 		fReceiveMaxAdvertised = fReceiveNext
2214 			+ ((uint32)segment.advertised_window << fReceiveWindowShift);
2215 
2216 		if (segmentLength != 0 && fState == ESTABLISHED)
2217 			--fSendMaxSegments;
2218 
2219 		status = next->module->send_routed_data(next, fRoute, buffer);
2220 		if (status < B_OK) {
2221 			gBufferModule->free(buffer);
2222 
2223 			fSendNext = segment.sequence;
2224 			fSendMax = sendMax;
2225 				// restore send status
2226 			return status;
2227 		}
2228 
2229 		if (fSendTime == 0 && !retransmit
2230 			&& (segmentLength != 0 || (segment.flags & TCP_FLAG_SYNCHRONIZE) !=0)) {
2231 			fSendTime = tcp_now();
2232 			fRoundTripStartSequence = segment.sequence;
2233 		}
2234 
2235 		if (shouldStartRetransmitTimer && size > 0) {
2236 			TRACE("starting initial retransmit timer of: %" B_PRIdBIGTIME,
2237 				fRetransmitTimeout);
2238 			gStackModule->set_timer(&fRetransmitTimer, fRetransmitTimeout);
2239 			T(TimerSet(this, "retransmit", fRetransmitTimeout));
2240 			shouldStartRetransmitTimer = false;
2241 		}
2242 
2243 		if (segment.flags & TCP_FLAG_ACKNOWLEDGE) {
2244 			fLastAcknowledgeSent = segment.acknowledge;
2245 			gStackModule->cancel_timer(&fDelayedAcknowledgeTimer);
2246 		}
2247 
2248 		length -= segmentLength;
2249 		segment.flags &= ~(TCP_FLAG_SYNCHRONIZE | TCP_FLAG_RESET
2250 			| TCP_FLAG_FINISH);
2251 
2252 		if (retransmit)
2253 			break;
2254 
2255 	} while (length > 0);
2256 
2257 	return B_OK;
2258 }
2259 
2260 
2261 int
2262 TCPEndpoint::_MaxSegmentSize(const sockaddr* address) const
2263 {
2264 	return next->module->get_mtu(next, address) - sizeof(tcp_header);
2265 }
2266 
2267 
2268 status_t
2269 TCPEndpoint::_PrepareSendPath(const sockaddr* peer)
2270 {
2271 	if (fRoute == NULL) {
2272 		fRoute = gDatalinkModule->get_route(Domain(), peer);
2273 		if (fRoute == NULL)
2274 			return ENETUNREACH;
2275 
2276 		if ((fRoute->flags & RTF_LOCAL) != 0)
2277 			fFlags |= FLAG_LOCAL;
2278 	}
2279 
2280 	// make sure connection does not already exist
2281 	status_t status = fManager->SetConnection(this, *LocalAddress(), peer,
2282 		fRoute->interface_address->local);
2283 	if (status < B_OK)
2284 		return status;
2285 
2286 	fInitialSendSequence = system_time() >> 4;
2287 	fSendNext = fInitialSendSequence;
2288 	fSendUnacknowledged = fInitialSendSequence;
2289 	fSendMax = fInitialSendSequence;
2290 	fSendUrgentOffset = fInitialSendSequence;
2291 	fRecover = fInitialSendSequence.Number();
2292 
2293 	// we are counting the SYN here
2294 	fSendQueue.SetInitialSequence(fSendNext + 1);
2295 
2296 	fReceiveMaxSegmentSize = _MaxSegmentSize(peer);
2297 
2298 	// Compute the window shift we advertise to our peer - if it doesn't support
2299 	// this option, this will be reset to 0 (when its SYN is received)
2300 	fReceiveWindowShift = 0;
2301 	while (fReceiveWindowShift < TCP_MAX_WINDOW_SHIFT
2302 		&& (0xffffUL << fReceiveWindowShift) < socket->receive.buffer_size) {
2303 		fReceiveWindowShift++;
2304 	}
2305 
2306 	return B_OK;
2307 }
2308 
2309 
2310 void
2311 TCPEndpoint::_Acknowledged(tcp_segment_header& segment)
2312 {
2313 	TRACE("_Acknowledged(): ack %" B_PRIu32 "; uack %" B_PRIu32 "; next %"
2314 		B_PRIu32 "; max %" B_PRIu32, segment.acknowledge,
2315 		fSendUnacknowledged.Number(), fSendNext.Number(), fSendMax.Number());
2316 
2317 	ASSERT(fSendUnacknowledged <= segment.acknowledge);
2318 
2319 	if (fSendUnacknowledged < segment.acknowledge) {
2320 		fSendQueue.RemoveUntil(segment.acknowledge);
2321 
2322 		uint32 bytesAcknowledged = segment.acknowledge - fSendUnacknowledged.Number();
2323 		fPreviousHighestAcknowledge = fSendUnacknowledged;
2324 		fSendUnacknowledged = segment.acknowledge;
2325 		uint32 flightSize = (fSendMax - fSendUnacknowledged).Number();
2326 		int32 expectedSamples = flightSize / (fSendMaxSegmentSize << 1);
2327 
2328 		if (fPreviousHighestAcknowledge > fSendUnacknowledged) {
2329 			// need to update the recover variable upon a sequence wraparound
2330 			fRecover = segment.acknowledge - 1;
2331 		}
2332 
2333 		// the acknowledgment of the SYN/ACK MUST NOT increase the size of the congestion window
2334 		if (fSendUnacknowledged != fInitialSendSequence) {
2335 			if (fCongestionWindow < fSlowStartThreshold)
2336 				fCongestionWindow += min_c(bytesAcknowledged, fSendMaxSegmentSize);
2337 			else {
2338 				uint32 increment = fSendMaxSegmentSize * fSendMaxSegmentSize;
2339 
2340 				if (increment < fCongestionWindow)
2341 					increment = 1;
2342 				else
2343 					increment /= fCongestionWindow;
2344 
2345 				fCongestionWindow += increment;
2346 			}
2347 
2348 			fSendMaxSegments = UINT32_MAX;
2349 		}
2350 
2351 		if ((fFlags & FLAG_RECOVERY) != 0) {
2352 			fSendNext = fSendUnacknowledged;
2353 			_SendQueued();
2354 			fCongestionWindow -= bytesAcknowledged;
2355 
2356 			if (bytesAcknowledged > fSendMaxSegmentSize)
2357 				fCongestionWindow += fSendMaxSegmentSize;
2358 
2359 			fSendNext = fSendMax;
2360 		} else
2361 			fDuplicateAcknowledgeCount = 0;
2362 
2363 		if (fSendNext < fSendUnacknowledged)
2364 			fSendNext = fSendUnacknowledged;
2365 
2366 		if (fFlags & FLAG_OPTION_TIMESTAMP) {
2367 			_UpdateRoundTripTime(tcp_diff_timestamp(segment.timestamp_reply),
2368 				expectedSamples > 0 ? expectedSamples : 1);
2369 		} else if (fSendTime != 0 && fRoundTripStartSequence < segment.acknowledge) {
2370 			_UpdateRoundTripTime(tcp_diff_timestamp(fSendTime), 1);
2371 			fSendTime = 0;
2372 		}
2373 
2374 		if (fSendUnacknowledged == fSendMax) {
2375 			TRACE("all acknowledged, cancelling retransmission timer.");
2376 			gStackModule->cancel_timer(&fRetransmitTimer);
2377 			T(TimerSet(this, "retransmit", -1));
2378 		} else {
2379 			TRACE("data acknowledged, resetting retransmission timer to: %"
2380 				B_PRIdBIGTIME, fRetransmitTimeout);
2381 			gStackModule->set_timer(&fRetransmitTimer, fRetransmitTimeout);
2382 			T(TimerSet(this, "retransmit", fRetransmitTimeout));
2383 		}
2384 
2385 		if (is_writable(fState)) {
2386 			// notify threads waiting on the socket to become writable again
2387 			fSendCondition.NotifyAll();
2388 			gSocketModule->notify(socket, B_SELECT_WRITE, fSendQueue.Free());
2389 		}
2390 	}
2391 
2392 	// if there is data left to be sent, send it now
2393 	if (fSendQueue.Used() > 0)
2394 		_SendQueued();
2395 }
2396 
2397 
2398 void
2399 TCPEndpoint::_Retransmit()
2400 {
2401 	TRACE("Retransmit()");
2402 
2403 	if (fState < ESTABLISHED) {
2404 		fRetransmitTimeout = TCP_SYN_RETRANSMIT_TIMEOUT;
2405 		fCongestionWindow = fSendMaxSegmentSize;
2406 	} else {
2407 		_ResetSlowStart();
2408 		fDuplicateAcknowledgeCount = 0;
2409 		// Do exponential back off of the retransmit timeout
2410 		fRetransmitTimeout *= 2;
2411 		if (fRetransmitTimeout > TCP_MAX_RETRANSMIT_TIMEOUT)
2412 			fRetransmitTimeout = TCP_MAX_RETRANSMIT_TIMEOUT;
2413 	}
2414 
2415 	fSendNext = fSendUnacknowledged;
2416 	_SendQueued();
2417 
2418 	fRecover = fSendNext.Number() - 1;
2419 	if ((fFlags & FLAG_RECOVERY) != 0)
2420 		fFlags &= ~FLAG_RECOVERY;
2421 }
2422 
2423 
2424 void
2425 TCPEndpoint::_UpdateRoundTripTime(int32 roundTripTime, int32 expectedSamples)
2426 {
2427 	if (fSmoothedRoundTripTime == 0) {
2428 		fSmoothedRoundTripTime = roundTripTime;
2429 		fRoundTripVariation = roundTripTime / 2;
2430 		fRetransmitTimeout = (fSmoothedRoundTripTime + max_c(100, fRoundTripVariation * 4))
2431 				* kTimestampFactor;
2432 	} else {
2433 		int32 delta = fSmoothedRoundTripTime - roundTripTime;
2434 		if (delta < 0)
2435 			delta = -delta;
2436 		fRoundTripVariation += (delta - fRoundTripVariation) / (expectedSamples * 4);
2437 		fSmoothedRoundTripTime += (roundTripTime - fSmoothedRoundTripTime) / (expectedSamples * 8);
2438 		fRetransmitTimeout = (fSmoothedRoundTripTime + max_c(100, fRoundTripVariation * 4))
2439 			* kTimestampFactor;
2440 	}
2441 
2442 	if (fRetransmitTimeout > TCP_MAX_RETRANSMIT_TIMEOUT)
2443 		fRetransmitTimeout = TCP_MAX_RETRANSMIT_TIMEOUT;
2444 
2445 	if (fRetransmitTimeout < TCP_MIN_RETRANSMIT_TIMEOUT)
2446 		fRetransmitTimeout = TCP_MIN_RETRANSMIT_TIMEOUT;
2447 
2448 	TRACE("  RTO is now %" B_PRIdBIGTIME " (after rtt %" B_PRId32 "ms)",
2449 		fRetransmitTimeout, roundTripTime);
2450 }
2451 
2452 
2453 void
2454 TCPEndpoint::_ResetSlowStart()
2455 {
2456 	fSlowStartThreshold = max_c((fSendMax - fSendUnacknowledged).Number() / 2,
2457 		2 * fSendMaxSegmentSize);
2458 	fCongestionWindow = fSendMaxSegmentSize;
2459 }
2460 
2461 
2462 //	#pragma mark - timer
2463 
2464 
2465 /*static*/ void
2466 TCPEndpoint::_RetransmitTimer(net_timer* timer, void* _endpoint)
2467 {
2468 	TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint;
2469 	T(TimerTriggered(endpoint, "retransmit"));
2470 
2471 	MutexLocker locker(endpoint->fLock);
2472 	if (!locker.IsLocked() || gStackModule->is_timer_active(timer))
2473 		return;
2474 
2475 	endpoint->_Retransmit();
2476 }
2477 
2478 
2479 /*static*/ void
2480 TCPEndpoint::_PersistTimer(net_timer* timer, void* _endpoint)
2481 {
2482 	TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint;
2483 	T(TimerTriggered(endpoint, "persist"));
2484 
2485 	MutexLocker locker(endpoint->fLock);
2486 	if (!locker.IsLocked())
2487 		return;
2488 
2489 	// the timer might not have been canceled early enough
2490 	if (endpoint->State() == CLOSED)
2491 		return;
2492 
2493 	endpoint->_SendQueued(true);
2494 }
2495 
2496 
2497 /*static*/ void
2498 TCPEndpoint::_DelayedAcknowledgeTimer(net_timer* timer, void* _endpoint)
2499 {
2500 	TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint;
2501 	T(TimerTriggered(endpoint, "delayed ack"));
2502 
2503 	MutexLocker locker(endpoint->fLock);
2504 	if (!locker.IsLocked())
2505 		return;
2506 
2507 	// the timer might not have been canceled early enough
2508 	if (endpoint->State() == CLOSED)
2509 		return;
2510 
2511 	endpoint->SendAcknowledge(true);
2512 }
2513 
2514 
2515 /*static*/ void
2516 TCPEndpoint::_TimeWaitTimer(net_timer* timer, void* _endpoint)
2517 {
2518 	TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint;
2519 	T(TimerTriggered(endpoint, "time-wait"));
2520 
2521 	MutexLocker locker(endpoint->fLock);
2522 	if (!locker.IsLocked())
2523 		return;
2524 
2525 	if ((endpoint->fFlags & FLAG_CLOSED) == 0) {
2526 		endpoint->fFlags |= FLAG_DELETE_ON_CLOSE;
2527 		return;
2528 	}
2529 
2530 	locker.Unlock();
2531 
2532 	gSocketModule->release_socket(endpoint->socket);
2533 }
2534 
2535 
2536 /*static*/ status_t
2537 TCPEndpoint::_WaitForCondition(ConditionVariable& condition,
2538 	MutexLocker& locker, bigtime_t timeout)
2539 {
2540 	ConditionVariableEntry entry;
2541 	condition.Add(&entry);
2542 
2543 	locker.Unlock();
2544 	status_t result = entry.Wait(B_ABSOLUTE_TIMEOUT | B_CAN_INTERRUPT, timeout);
2545 	locker.Lock();
2546 
2547 	return result;
2548 }
2549 
2550 
2551 //	#pragma mark -
2552 
2553 
2554 void
2555 TCPEndpoint::Dump() const
2556 {
2557 	kprintf("TCP endpoint %p\n", this);
2558 	kprintf("  state: %s\n", name_for_state(fState));
2559 	kprintf("  flags: 0x%" B_PRIx32 "\n", fFlags);
2560 #if KDEBUG
2561 	kprintf("  lock: { %p, holder: %" B_PRId32 " }\n", &fLock, fLock.holder);
2562 #endif
2563 	kprintf("  accept sem: %" B_PRId32 "\n", fAcceptSemaphore);
2564 	kprintf("  options: 0x%" B_PRIx32 "\n", (uint32)fOptions);
2565 	kprintf("  send\n");
2566 	kprintf("    window shift: %" B_PRIu8 "\n", fSendWindowShift);
2567 	kprintf("    unacknowledged: %" B_PRIu32 "\n",
2568 		fSendUnacknowledged.Number());
2569 	kprintf("    next: %" B_PRIu32 "\n", fSendNext.Number());
2570 	kprintf("    max: %" B_PRIu32 "\n", fSendMax.Number());
2571 	kprintf("    urgent offset: %" B_PRIu32 "\n", fSendUrgentOffset.Number());
2572 	kprintf("    window: %" B_PRIu32 "\n", fSendWindow);
2573 	kprintf("    max window: %" B_PRIu32 "\n", fSendMaxWindow);
2574 	kprintf("    max segment size: %" B_PRIu32 "\n", fSendMaxSegmentSize);
2575 	kprintf("    queue: %" B_PRIuSIZE " / %" B_PRIuSIZE "\n", fSendQueue.Used(),
2576 		fSendQueue.Size());
2577 #if DEBUG_TCP_BUFFER_QUEUE
2578 	fSendQueue.Dump();
2579 #endif
2580 	kprintf("    last acknowledge sent: %" B_PRIu32 "\n",
2581 		fLastAcknowledgeSent.Number());
2582 	kprintf("    initial sequence: %" B_PRIu32 "\n",
2583 		fInitialSendSequence.Number());
2584 	kprintf("  receive\n");
2585 	kprintf("    window shift: %" B_PRIu8 "\n", fReceiveWindowShift);
2586 	kprintf("    next: %" B_PRIu32 "\n", fReceiveNext.Number());
2587 	kprintf("    max advertised: %" B_PRIu32 "\n",
2588 		fReceiveMaxAdvertised.Number());
2589 	kprintf("    window: %" B_PRIu32 "\n", fReceiveWindow);
2590 	kprintf("    max segment size: %" B_PRIu32 "\n", fReceiveMaxSegmentSize);
2591 	kprintf("    queue: %" B_PRIuSIZE " / %" B_PRIuSIZE "\n",
2592 		fReceiveQueue.Available(), fReceiveQueue.Size());
2593 #if DEBUG_TCP_BUFFER_QUEUE
2594 	fReceiveQueue.Dump();
2595 #endif
2596 	kprintf("    initial sequence: %" B_PRIu32 "\n",
2597 		fInitialReceiveSequence.Number());
2598 	kprintf("    duplicate acknowledge count: %" B_PRIu32 "\n",
2599 		fDuplicateAcknowledgeCount);
2600 	kprintf("  smoothed round trip time: %" B_PRId32 " (deviation %" B_PRId32 ")\n",
2601 		fSmoothedRoundTripTime, fRoundTripVariation);
2602 	kprintf("  retransmit timeout: %" B_PRId64 "\n", fRetransmitTimeout);
2603 	kprintf("  congestion window: %" B_PRIu32 "\n", fCongestionWindow);
2604 	kprintf("  slow start threshold: %" B_PRIu32 "\n", fSlowStartThreshold);
2605 }
2606 
2607