Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / lwip / repo / lwip / src / core / tcp_out.c
1 /**
2  * @file
3  * Transmission Control Protocol, outgoing traffic
4  *
5  * The output functions of TCP.
6  *
7  */
8
9 /*
10  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
11  * All rights reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without modification,
14  * are permitted provided that the following conditions are met:
15  *
16  * 1. Redistributions of source code must retain the above copyright notice,
17  *    this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright notice,
19  *    this list of conditions and the following disclaimer in the documentation
20  *    and/or other materials provided with the distribution.
21  * 3. The name of the author may not be used to endorse or promote products
22  *    derived from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
25  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
27  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
29  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
33  * OF SUCH DAMAGE.
34  *
35  * This file is part of the lwIP TCP/IP stack.
36  *
37  * Author: Adam Dunkels <adam@sics.se>
38  *
39  */
40
41 #include "lwip/opt.h"
42
43 #if LWIP_TCP /* don't build if not configured for use in lwipopts.h */
44
45 #include "lwip/priv/tcp_priv.h"
46 #include "lwip/def.h"
47 #include "lwip/mem.h"
48 #include "lwip/memp.h"
49 #include "lwip/ip_addr.h"
50 #include "lwip/netif.h"
51 #include "lwip/inet_chksum.h"
52 #include "lwip/stats.h"
53 #include "lwip/ip6.h"
54 #include "lwip/ip6_addr.h"
55 #if LWIP_TCP_TIMESTAMPS
56 #include "lwip/sys.h"
57 #endif
58
59 #include <string.h>
60
61 /* Define some copy-macros for checksum-on-copy so that the code looks
62    nicer by preventing too many ifdef's. */
63 #if TCP_CHECKSUM_ON_COPY
64 #define TCP_DATA_COPY(dst, src, len, seg) do { \
65   tcp_seg_add_chksum(LWIP_CHKSUM_COPY(dst, src, len), \
66                      len, &seg->chksum, &seg->chksum_swapped); \
67   seg->flags |= TF_SEG_DATA_CHECKSUMMED; } while(0)
68 #define TCP_DATA_COPY2(dst, src, len, chksum, chksum_swapped)  \
69   tcp_seg_add_chksum(LWIP_CHKSUM_COPY(dst, src, len), len, chksum, chksum_swapped);
70 #else /* TCP_CHECKSUM_ON_COPY*/
71 #define TCP_DATA_COPY(dst, src, len, seg)                     MEMCPY(dst, src, len)
72 #define TCP_DATA_COPY2(dst, src, len, chksum, chksum_swapped) MEMCPY(dst, src, len)
73 #endif /* TCP_CHECKSUM_ON_COPY*/
74
75 /** Define this to 1 for an extra check that the output checksum is valid
76  * (usefule when the checksum is generated by the application, not the stack) */
77 #ifndef TCP_CHECKSUM_ON_COPY_SANITY_CHECK
78 #define TCP_CHECKSUM_ON_COPY_SANITY_CHECK   0
79 #endif
80 /* Allow to override the failure of sanity check from warning to e.g. hard failure */
81 #if TCP_CHECKSUM_ON_COPY_SANITY_CHECK
82 #ifndef TCP_CHECKSUM_ON_COPY_SANITY_CHECK_FAIL
83 #define TCP_CHECKSUM_ON_COPY_SANITY_CHECK_FAIL(msg) LWIP_DEBUGF(TCP_DEBUG | LWIP_DBG_LEVEL_WARNING, msg)
84 #endif
85 #endif
86
87 #if TCP_OVERSIZE
88 /** The size of segment pbufs created when TCP_OVERSIZE is enabled */
89 #ifndef TCP_OVERSIZE_CALC_LENGTH
90 #define TCP_OVERSIZE_CALC_LENGTH(length) ((length) + TCP_OVERSIZE)
91 #endif
92 #endif
93
94 /* Forward declarations.*/
95 static err_t tcp_output_segment(struct tcp_seg *seg, struct tcp_pcb *pcb, struct netif *netif);
96
97 /** Allocate a pbuf and create a tcphdr at p->payload, used for output
98  * functions other than the default tcp_output -> tcp_output_segment
99  * (e.g. tcp_send_empty_ack, etc.)
100  *
101  * @param pcb tcp pcb for which to send a packet (used to initialize tcp_hdr)
102  * @param optlen length of header-options
103  * @param datalen length of tcp data to reserve in pbuf
104  * @param seqno_be seqno in network byte order (big-endian)
105  * @return pbuf with p->payload being the tcp_hdr
106  */
107 static struct pbuf *
108 tcp_output_alloc_header(struct tcp_pcb *pcb, u16_t optlen, u16_t datalen,
109                       u32_t seqno_be /* already in network byte order */)
110 {
111   struct tcp_hdr *tcphdr;
112   struct pbuf *p = pbuf_alloc(PBUF_IP, TCP_HLEN + optlen + datalen, PBUF_RAM);
113   if (p != NULL) {
114     LWIP_ASSERT("check that first pbuf can hold struct tcp_hdr",
115                  (p->len >= TCP_HLEN + optlen));
116     tcphdr = (struct tcp_hdr *)p->payload;
117     tcphdr->src = lwip_htons(pcb->local_port);
118     tcphdr->dest = lwip_htons(pcb->remote_port);
119     tcphdr->seqno = seqno_be;
120     tcphdr->ackno = lwip_htonl(pcb->rcv_nxt);
121     TCPH_HDRLEN_FLAGS_SET(tcphdr, (5 + optlen / 4), TCP_ACK);
122     tcphdr->wnd = lwip_htons(TCPWND_MIN16(RCV_WND_SCALE(pcb, pcb->rcv_ann_wnd)));
123     tcphdr->chksum = 0;
124     tcphdr->urgp = 0;
125
126     /* If we're sending a packet, update the announced right window edge */
127     pcb->rcv_ann_right_edge = pcb->rcv_nxt + pcb->rcv_ann_wnd;
128   }
129   return p;
130 }
131
132 /**
133  * Called by tcp_close() to send a segment including FIN flag but not data.
134  *
135  * @param pcb the tcp_pcb over which to send a segment
136  * @return ERR_OK if sent, another err_t otherwise
137  */
138 err_t
139 tcp_send_fin(struct tcp_pcb *pcb)
140 {
141   /* first, try to add the fin to the last unsent segment */
142   if (pcb->unsent != NULL) {
143     struct tcp_seg *last_unsent;
144     for (last_unsent = pcb->unsent; last_unsent->next != NULL;
145          last_unsent = last_unsent->next);
146
147     if ((TCPH_FLAGS(last_unsent->tcphdr) & (TCP_SYN | TCP_FIN | TCP_RST)) == 0) {
148       /* no SYN/FIN/RST flag in the header, we can add the FIN flag */
149       TCPH_SET_FLAG(last_unsent->tcphdr, TCP_FIN);
150       pcb->flags |= TF_FIN;
151       return ERR_OK;
152     }
153   }
154   /* no data, no length, flags, copy=1, no optdata */
155   return tcp_enqueue_flags(pcb, TCP_FIN);
156 }
157
158 /**
159  * Create a TCP segment with prefilled header.
160  *
161  * Called by tcp_write and tcp_enqueue_flags.
162  *
163  * @param pcb Protocol control block for the TCP connection.
164  * @param p pbuf that is used to hold the TCP header.
165  * @param flags TCP flags for header.
166  * @param seqno TCP sequence number of this packet
167  * @param optflags options to include in TCP header
168  * @return a new tcp_seg pointing to p, or NULL.
169  * The TCP header is filled in except ackno and wnd.
170  * p is freed on failure.
171  */
172 static struct tcp_seg *
173 tcp_create_segment(struct tcp_pcb *pcb, struct pbuf *p, u8_t flags, u32_t seqno, u8_t optflags)
174 {
175   struct tcp_seg *seg;
176   u8_t optlen = LWIP_TCP_OPT_LENGTH(optflags);
177
178   if ((seg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG)) == NULL) {
179     LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("tcp_create_segment: no memory.\n"));
180     pbuf_free(p);
181     return NULL;
182   }
183   seg->flags = optflags;
184   seg->next = NULL;
185   seg->p = p;
186   LWIP_ASSERT("p->tot_len >= optlen", p->tot_len >= optlen);
187   seg->len = p->tot_len - optlen;
188 #if TCP_OVERSIZE_DBGCHECK
189   seg->oversize_left = 0;
190 #endif /* TCP_OVERSIZE_DBGCHECK */
191 #if TCP_CHECKSUM_ON_COPY
192   seg->chksum = 0;
193   seg->chksum_swapped = 0;
194   /* check optflags */
195   LWIP_ASSERT("invalid optflags passed: TF_SEG_DATA_CHECKSUMMED",
196               (optflags & TF_SEG_DATA_CHECKSUMMED) == 0);
197 #endif /* TCP_CHECKSUM_ON_COPY */
198
199   /* build TCP header */
200   if (pbuf_header(p, TCP_HLEN)) {
201     LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("tcp_create_segment: no room for TCP header in pbuf.\n"));
202     TCP_STATS_INC(tcp.err);
203     tcp_seg_free(seg);
204     return NULL;
205   }
206   seg->tcphdr = (struct tcp_hdr *)seg->p->payload;
207   seg->tcphdr->src = lwip_htons(pcb->local_port);
208   seg->tcphdr->dest = lwip_htons(pcb->remote_port);
209   seg->tcphdr->seqno = lwip_htonl(seqno);
210   /* ackno is set in tcp_output */
211   TCPH_HDRLEN_FLAGS_SET(seg->tcphdr, (5 + optlen / 4), flags);
212   /* wnd and chksum are set in tcp_output */
213   seg->tcphdr->urgp = 0;
214   return seg;
215 }
216
217 /**
218  * Allocate a PBUF_RAM pbuf, perhaps with extra space at the end.
219  *
220  * This function is like pbuf_alloc(layer, length, PBUF_RAM) except
221  * there may be extra bytes available at the end.
222  *
223  * @param layer flag to define header size.
224  * @param length size of the pbuf's payload.
225  * @param max_length maximum usable size of payload+oversize.
226  * @param oversize pointer to a u16_t that will receive the number of usable tail bytes.
227  * @param pcb The TCP connection that will enqueue the pbuf.
228  * @param apiflags API flags given to tcp_write.
229  * @param first_seg true when this pbuf will be used in the first enqueued segment.
230  */
231 #if TCP_OVERSIZE
232 static struct pbuf *
233 tcp_pbuf_prealloc(pbuf_layer layer, u16_t length, u16_t max_length,
234                   u16_t *oversize, struct tcp_pcb *pcb, u8_t apiflags,
235                   u8_t first_seg)
236 {
237   struct pbuf *p;
238   u16_t alloc = length;
239
240 #if LWIP_NETIF_TX_SINGLE_PBUF
241   LWIP_UNUSED_ARG(max_length);
242   LWIP_UNUSED_ARG(pcb);
243   LWIP_UNUSED_ARG(apiflags);
244   LWIP_UNUSED_ARG(first_seg);
245   alloc = max_length;
246 #else /* LWIP_NETIF_TX_SINGLE_PBUF */
247   if (length < max_length) {
248     /* Should we allocate an oversized pbuf, or just the minimum
249      * length required? If tcp_write is going to be called again
250      * before this segment is transmitted, we want the oversized
251      * buffer. If the segment will be transmitted immediately, we can
252      * save memory by allocating only length. We use a simple
253      * heuristic based on the following information:
254      *
255      * Did the user set TCP_WRITE_FLAG_MORE?
256      *
257      * Will the Nagle algorithm defer transmission of this segment?
258      */
259     if ((apiflags & TCP_WRITE_FLAG_MORE) ||
260         (!(pcb->flags & TF_NODELAY) &&
261          (!first_seg ||
262           pcb->unsent != NULL ||
263           pcb->unacked != NULL))) {
264       alloc = LWIP_MIN(max_length, LWIP_MEM_ALIGN_SIZE(TCP_OVERSIZE_CALC_LENGTH(length)));
265     }
266   }
267 #endif /* LWIP_NETIF_TX_SINGLE_PBUF */
268   p = pbuf_alloc(layer, alloc, PBUF_RAM);
269   if (p == NULL) {
270     return NULL;
271   }
272   LWIP_ASSERT("need unchained pbuf", p->next == NULL);
273   *oversize = p->len - length;
274   /* trim p->len to the currently used size */
275   p->len = p->tot_len = length;
276   return p;
277 }
278 #else /* TCP_OVERSIZE */
279 #define tcp_pbuf_prealloc(layer, length, mx, os, pcb, api, fst) pbuf_alloc((layer), (length), PBUF_RAM)
280 #endif /* TCP_OVERSIZE */
281
282 #if TCP_CHECKSUM_ON_COPY
283 /** Add a checksum of newly added data to the segment */
284 static void
285 tcp_seg_add_chksum(u16_t chksum, u16_t len, u16_t *seg_chksum,
286                    u8_t *seg_chksum_swapped)
287 {
288   u32_t helper;
289   /* add chksum to old chksum and fold to u16_t */
290   helper = chksum + *seg_chksum;
291   chksum = FOLD_U32T(helper);
292   if ((len & 1) != 0) {
293     *seg_chksum_swapped = 1 - *seg_chksum_swapped;
294     chksum = SWAP_BYTES_IN_WORD(chksum);
295   }
296   *seg_chksum = chksum;
297 }
298 #endif /* TCP_CHECKSUM_ON_COPY */
299
300 /** Checks if tcp_write is allowed or not (checks state, snd_buf and snd_queuelen).
301  *
302  * @param pcb the tcp pcb to check for
303  * @param len length of data to send (checked agains snd_buf)
304  * @return ERR_OK if tcp_write is allowed to proceed, another err_t otherwise
305  */
306 static err_t
307 tcp_write_checks(struct tcp_pcb *pcb, u16_t len)
308 {
309   /* connection is in invalid state for data transmission? */
310   if ((pcb->state != ESTABLISHED) &&
311       (pcb->state != CLOSE_WAIT) &&
312       (pcb->state != SYN_SENT) &&
313       (pcb->state != SYN_RCVD)) {
314     LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_STATE | LWIP_DBG_LEVEL_SEVERE, ("tcp_write() called in invalid state\n"));
315     return ERR_CONN;
316   } else if (len == 0) {
317     return ERR_OK;
318   }
319
320   /* fail on too much data */
321   if (len > pcb->snd_buf) {
322     LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("tcp_write: too much data (len=%"U16_F" > snd_buf=%"TCPWNDSIZE_F")\n",
323       len, pcb->snd_buf));
324     pcb->flags |= TF_NAGLEMEMERR;
325     return ERR_MEM;
326   }
327
328   LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_write: queuelen: %"TCPWNDSIZE_F"\n", (tcpwnd_size_t)pcb->snd_queuelen));
329
330   /* If total number of pbufs on the unsent/unacked queues exceeds the
331    * configured maximum, return an error */
332   /* check for configured max queuelen and possible overflow */
333   if ((pcb->snd_queuelen >= TCP_SND_QUEUELEN) || (pcb->snd_queuelen > TCP_SNDQUEUELEN_OVERFLOW)) {
334     LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("tcp_write: too long queue %"U16_F" (max %"U16_F")\n",
335       pcb->snd_queuelen, (u16_t)TCP_SND_QUEUELEN));
336     TCP_STATS_INC(tcp.memerr);
337     pcb->flags |= TF_NAGLEMEMERR;
338     return ERR_MEM;
339   }
340   if (pcb->snd_queuelen != 0) {
341     LWIP_ASSERT("tcp_write: pbufs on queue => at least one queue non-empty",
342       pcb->unacked != NULL || pcb->unsent != NULL);
343   } else {
344     LWIP_ASSERT("tcp_write: no pbufs on queue => both queues empty",
345       pcb->unacked == NULL && pcb->unsent == NULL);
346   }
347   return ERR_OK;
348 }
349
350 /**
351  * @ingroup tcp_raw
352  * Write data for sending (but does not send it immediately).
353  *
354  * It waits in the expectation of more data being sent soon (as
355  * it can send them more efficiently by combining them together).
356  * To prompt the system to send data now, call tcp_output() after
357  * calling tcp_write().
358  *
359  * @param pcb Protocol control block for the TCP connection to enqueue data for.
360  * @param arg Pointer to the data to be enqueued for sending.
361  * @param len Data length in bytes
362  * @param apiflags combination of following flags :
363  * - TCP_WRITE_FLAG_COPY (0x01) data will be copied into memory belonging to the stack
364  * - TCP_WRITE_FLAG_MORE (0x02) for TCP connection, PSH flag will not be set on last segment sent,
365  * @return ERR_OK if enqueued, another err_t on error
366  */
367 err_t
368 tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
369 {
370   struct pbuf *concat_p = NULL;
371   struct tcp_seg *last_unsent = NULL, *seg = NULL, *prev_seg = NULL, *queue = NULL;
372   u16_t pos = 0; /* position in 'arg' data */
373   u16_t queuelen;
374   u8_t optlen = 0;
375   u8_t optflags = 0;
376 #if TCP_OVERSIZE
377   u16_t oversize = 0;
378   u16_t oversize_used = 0;
379 #if TCP_OVERSIZE_DBGCHECK
380   u16_t oversize_add = 0;
381 #endif /* TCP_OVERSIZE_DBGCHECK*/
382 #endif /* TCP_OVERSIZE */
383   u16_t extendlen = 0;
384 #if TCP_CHECKSUM_ON_COPY
385   u16_t concat_chksum = 0;
386   u8_t concat_chksum_swapped = 0;
387   u16_t concat_chksummed = 0;
388 #endif /* TCP_CHECKSUM_ON_COPY */
389   err_t err;
390   /* don't allocate segments bigger than half the maximum window we ever received */
391   u16_t mss_local = LWIP_MIN(pcb->mss, TCPWND_MIN16(pcb->snd_wnd_max/2));
392   mss_local = mss_local ? mss_local : pcb->mss;
393
394   LWIP_ASSERT_CORE_LOCKED();
395
396 #if LWIP_NETIF_TX_SINGLE_PBUF
397   /* Always copy to try to create single pbufs for TX */
398   apiflags |= TCP_WRITE_FLAG_COPY;
399 #endif /* LWIP_NETIF_TX_SINGLE_PBUF */
400
401   LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_write(pcb=%p, data=%p, len=%"U16_F", apiflags=%"U16_F")\n",
402     (void *)pcb, arg, len, (u16_t)apiflags));
403   LWIP_ERROR("tcp_write: arg == NULL (programmer violates API)",
404              arg != NULL, return ERR_ARG;);
405
406   err = tcp_write_checks(pcb, len);
407   if (err != ERR_OK) {
408     return err;
409   }
410   queuelen = pcb->snd_queuelen;
411
412 #if LWIP_TCP_TIMESTAMPS
413   if ((pcb->flags & TF_TIMESTAMP)) {
414     /* Make sure the timestamp option is only included in data segments if we
415        agreed about it with the remote host. */
416     optflags = TF_SEG_OPTS_TS;
417     optlen = LWIP_TCP_OPT_LENGTH(TF_SEG_OPTS_TS);
418     /* ensure that segments can hold at least one data byte... */
419     mss_local = LWIP_MAX(mss_local, LWIP_TCP_OPT_LEN_TS + 1);
420   }
421 #endif /* LWIP_TCP_TIMESTAMPS */
422
423
424   /*
425    * TCP segmentation is done in three phases with increasing complexity:
426    *
427    * 1. Copy data directly into an oversized pbuf.
428    * 2. Chain a new pbuf to the end of pcb->unsent.
429    * 3. Create new segments.
430    *
431    * We may run out of memory at any point. In that case we must
432    * return ERR_MEM and not change anything in pcb. Therefore, all
433    * changes are recorded in local variables and committed at the end
434    * of the function. Some pcb fields are maintained in local copies:
435    *
436    * queuelen = pcb->snd_queuelen
437    * oversize = pcb->unsent_oversize
438    *
439    * These variables are set consistently by the phases:
440    *
441    * seg points to the last segment tampered with.
442    *
443    * pos records progress as data is segmented.
444    */
445
446   /* Find the tail of the unsent queue. */
447   if (pcb->unsent != NULL) {
448     u16_t space;
449     u16_t unsent_optlen;
450
451     /* @todo: this could be sped up by keeping last_unsent in the pcb */
452     for (last_unsent = pcb->unsent; last_unsent->next != NULL;
453          last_unsent = last_unsent->next);
454
455     /* Usable space at the end of the last unsent segment */
456     unsent_optlen = LWIP_TCP_OPT_LENGTH(last_unsent->flags);
457     LWIP_ASSERT("mss_local is too small", mss_local >= last_unsent->len + unsent_optlen);
458     space = mss_local - (last_unsent->len + unsent_optlen);
459
460     /*
461      * Phase 1: Copy data directly into an oversized pbuf.
462      *
463      * The number of bytes copied is recorded in the oversize_used
464      * variable. The actual copying is done at the bottom of the
465      * function.
466      */
467 #if TCP_OVERSIZE
468 #if TCP_OVERSIZE_DBGCHECK
469     /* check that pcb->unsent_oversize matches last_unsent->oversize_left */
470     LWIP_ASSERT("unsent_oversize mismatch (pcb vs. last_unsent)",
471                 pcb->unsent_oversize == last_unsent->oversize_left);
472 #endif /* TCP_OVERSIZE_DBGCHECK */
473     oversize = pcb->unsent_oversize;
474     if (oversize > 0) {
475       LWIP_ASSERT("inconsistent oversize vs. space", oversize <= space);
476       seg = last_unsent;
477       oversize_used = LWIP_MIN(space, LWIP_MIN(oversize, len));
478       pos += oversize_used;
479       oversize -= oversize_used;
480       space -= oversize_used;
481     }
482     /* now we are either finished or oversize is zero */
483     LWIP_ASSERT("inconsistent oversize vs. len", (oversize == 0) || (pos == len));
484 #endif /* TCP_OVERSIZE */
485
486     /*
487      * Phase 2: Chain a new pbuf to the end of pcb->unsent.
488      *
489      * As an exception when NOT copying the data, if the given data buffer
490      * directly follows the last unsent data buffer in memory, extend the last
491      * ROM pbuf reference to the buffer, thus saving a ROM pbuf allocation.
492      *
493      * We don't extend segments containing SYN/FIN flags or options
494      * (len==0). The new pbuf is kept in concat_p and pbuf_cat'ed at
495      * the end.
496      */
497     if ((pos < len) && (space > 0) && (last_unsent->len > 0)) {
498       u16_t seglen = LWIP_MIN(space, len - pos);
499       seg = last_unsent;
500
501       /* Create a pbuf with a copy or reference to seglen bytes. We
502        * can use PBUF_RAW here since the data appears in the middle of
503        * a segment. A header will never be prepended. */
504       if (apiflags & TCP_WRITE_FLAG_COPY) {
505         /* Data is copied */
506         if ((concat_p = tcp_pbuf_prealloc(PBUF_RAW, seglen, space, &oversize, pcb, apiflags, 1)) == NULL) {
507           LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
508                       ("tcp_write : could not allocate memory for pbuf copy size %"U16_F"\n",
509                        seglen));
510           goto memerr;
511         }
512 #if TCP_OVERSIZE_DBGCHECK
513         oversize_add = oversize;
514 #endif /* TCP_OVERSIZE_DBGCHECK */
515         TCP_DATA_COPY2(concat_p->payload, (const u8_t*)arg + pos, seglen, &concat_chksum, &concat_chksum_swapped);
516 #if TCP_CHECKSUM_ON_COPY
517         concat_chksummed += seglen;
518 #endif /* TCP_CHECKSUM_ON_COPY */
519         queuelen += pbuf_clen(concat_p);
520       } else {
521         /* Data is not copied */
522         /* If the last unsent pbuf is of type PBUF_ROM, try to extend it. */
523         struct pbuf *p;
524         for (p = last_unsent->p; p->next != NULL; p = p->next);
525         if (p->type == PBUF_ROM && (const u8_t *)p->payload + p->len == (const u8_t *)arg) {
526           LWIP_ASSERT("tcp_write: ROM pbufs cannot be oversized", pos == 0);
527           extendlen = seglen;
528         } else {
529           if ((concat_p = pbuf_alloc(PBUF_RAW, seglen, PBUF_ROM)) == NULL) {
530             LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
531                         ("tcp_write: could not allocate memory for zero-copy pbuf\n"));
532             goto memerr;
533           }
534           /* reference the non-volatile payload data */
535           ((struct pbuf_rom*)concat_p)->payload = (const u8_t*)arg + pos;
536           queuelen += pbuf_clen(concat_p);
537         }
538 #if TCP_CHECKSUM_ON_COPY
539         /* calculate the checksum of nocopy-data */
540         tcp_seg_add_chksum(~inet_chksum((const u8_t*)arg + pos, seglen), seglen,
541           &concat_chksum, &concat_chksum_swapped);
542         concat_chksummed += seglen;
543 #endif /* TCP_CHECKSUM_ON_COPY */
544       }
545
546       pos += seglen;
547     }
548   } else {
549 #if TCP_OVERSIZE
550     LWIP_ASSERT("unsent_oversize mismatch (pcb->unsent is NULL)",
551                 pcb->unsent_oversize == 0);
552 #endif /* TCP_OVERSIZE */
553   }
554
555   /*
556    * Phase 3: Create new segments.
557    *
558    * The new segments are chained together in the local 'queue'
559    * variable, ready to be appended to pcb->unsent.
560    */
561   while (pos < len) {
562     struct pbuf *p;
563     u16_t left = len - pos;
564     u16_t max_len = mss_local - optlen;
565     u16_t seglen = LWIP_MIN(left, max_len);
566 #if TCP_CHECKSUM_ON_COPY
567     u16_t chksum = 0;
568     u8_t chksum_swapped = 0;
569 #endif /* TCP_CHECKSUM_ON_COPY */
570
571     if (apiflags & TCP_WRITE_FLAG_COPY) {
572       /* If copy is set, memory should be allocated and data copied
573        * into pbuf */
574       if ((p = tcp_pbuf_prealloc(PBUF_TRANSPORT, seglen + optlen, mss_local, &oversize, pcb, apiflags, queue == NULL)) == NULL) {
575         LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("tcp_write : could not allocate memory for pbuf copy size %"U16_F"\n", seglen));
576         goto memerr;
577       }
578       LWIP_ASSERT("tcp_write: check that first pbuf can hold the complete seglen",
579                   (p->len >= seglen));
580       TCP_DATA_COPY2((char *)p->payload + optlen, (const u8_t*)arg + pos, seglen, &chksum, &chksum_swapped);
581     } else {
582       /* Copy is not set: First allocate a pbuf for holding the data.
583        * Since the referenced data is available at least until it is
584        * sent out on the link (as it has to be ACKed by the remote
585        * party) we can safely use PBUF_ROM instead of PBUF_REF here.
586        */
587       struct pbuf *p2;
588 #if TCP_OVERSIZE
589       LWIP_ASSERT("oversize == 0", oversize == 0);
590 #endif /* TCP_OVERSIZE */
591       if ((p2 = pbuf_alloc(PBUF_TRANSPORT, seglen, PBUF_ROM)) == NULL) {
592         LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("tcp_write: could not allocate memory for zero-copy pbuf\n"));
593         goto memerr;
594       }
595 #if TCP_CHECKSUM_ON_COPY
596       /* calculate the checksum of nocopy-data */
597       chksum = ~inet_chksum((const u8_t*)arg + pos, seglen);
598       if (seglen & 1) {
599         chksum_swapped = 1;
600         chksum = SWAP_BYTES_IN_WORD(chksum);
601       }
602 #endif /* TCP_CHECKSUM_ON_COPY */
603       /* reference the non-volatile payload data */
604       ((struct pbuf_rom*)p2)->payload = (const u8_t*)arg + pos;
605
606       /* Second, allocate a pbuf for the headers. */
607       if ((p = pbuf_alloc(PBUF_TRANSPORT, optlen, PBUF_RAM)) == NULL) {
608         /* If allocation fails, we have to deallocate the data pbuf as
609          * well. */
610         pbuf_free(p2);
611         LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("tcp_write: could not allocate memory for header pbuf\n"));
612         goto memerr;
613       }
614       /* Concatenate the headers and data pbufs together. */
615       pbuf_cat(p/*header*/, p2/*data*/);
616     }
617
618     queuelen += pbuf_clen(p);
619
620     /* Now that there are more segments queued, we check again if the
621      * length of the queue exceeds the configured maximum or
622      * overflows. */
623     if ((queuelen > TCP_SND_QUEUELEN) || (queuelen > TCP_SNDQUEUELEN_OVERFLOW)) {
624       LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("tcp_write: queue too long %"U16_F" (%d)\n",
625         queuelen, (int)TCP_SND_QUEUELEN));
626       pbuf_free(p);
627       goto memerr;
628     }
629
630     if ((seg = tcp_create_segment(pcb, p, 0, pcb->snd_lbb + pos, optflags)) == NULL) {
631       goto memerr;
632     }
633 #if TCP_OVERSIZE_DBGCHECK
634     seg->oversize_left = oversize;
635 #endif /* TCP_OVERSIZE_DBGCHECK */
636 #if TCP_CHECKSUM_ON_COPY
637     seg->chksum = chksum;
638     seg->chksum_swapped = chksum_swapped;
639     seg->flags |= TF_SEG_DATA_CHECKSUMMED;
640 #endif /* TCP_CHECKSUM_ON_COPY */
641
642     /* first segment of to-be-queued data? */
643     if (queue == NULL) {
644       queue = seg;
645     } else {
646       /* Attach the segment to the end of the queued segments */
647       LWIP_ASSERT("prev_seg != NULL", prev_seg != NULL);
648       prev_seg->next = seg;
649     }
650     /* remember last segment of to-be-queued data for next iteration */
651     prev_seg = seg;
652
653     LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_TRACE, ("tcp_write: queueing %"U32_F":%"U32_F"\n",
654       lwip_ntohl(seg->tcphdr->seqno),
655       lwip_ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg)));
656
657     pos += seglen;
658   }
659
660   /*
661    * All three segmentation phases were successful. We can commit the
662    * transaction.
663    */
664 #if TCP_OVERSIZE_DBGCHECK
665   if ((last_unsent != NULL) && (oversize_add != 0)) {
666     last_unsent->oversize_left += oversize_add;
667   }
668 #endif /* TCP_OVERSIZE_DBGCHECK */
669
670   /*
671    * Phase 1: If data has been added to the preallocated tail of
672    * last_unsent, we update the length fields of the pbuf chain.
673    */
674 #if TCP_OVERSIZE
675   if (oversize_used > 0) {
676     struct pbuf *p;
677     /* Bump tot_len of whole chain, len of tail */
678     for (p = last_unsent->p; p; p = p->next) {
679       p->tot_len += oversize_used;
680       if (p->next == NULL) {
681         TCP_DATA_COPY((char *)p->payload + p->len, arg, oversize_used, last_unsent);
682         p->len += oversize_used;
683       }
684     }
685     last_unsent->len += oversize_used;
686 #if TCP_OVERSIZE_DBGCHECK
687     LWIP_ASSERT("last_unsent->oversize_left >= oversize_used",
688                 last_unsent->oversize_left >= oversize_used);
689     last_unsent->oversize_left -= oversize_used;
690 #endif /* TCP_OVERSIZE_DBGCHECK */
691   }
692   pcb->unsent_oversize = oversize;
693 #endif /* TCP_OVERSIZE */
694
695   /*
696    * Phase 2: concat_p can be concatenated onto last_unsent->p, unless we
697    * determined that the last ROM pbuf can be extended to include the new data.
698    */
699   if (concat_p != NULL) {
700     LWIP_ASSERT("tcp_write: cannot concatenate when pcb->unsent is empty",
701       (last_unsent != NULL));
702     pbuf_cat(last_unsent->p, concat_p);
703     last_unsent->len += concat_p->tot_len;
704   } else if (extendlen > 0) {
705     struct pbuf *p;
706     LWIP_ASSERT("tcp_write: extension of reference requires reference",
707       last_unsent != NULL && last_unsent->p != NULL);
708     for (p = last_unsent->p; p->next != NULL; p = p->next) {
709       p->tot_len += extendlen;
710     }
711     p->tot_len += extendlen;
712     p->len += extendlen;
713     last_unsent->len += extendlen;
714   }
715
716 #if TCP_CHECKSUM_ON_COPY
717   if (concat_chksummed) {
718     LWIP_ASSERT("tcp_write: concat checksum needs concatenated data",
719         concat_p != NULL || extendlen > 0);
720     /*if concat checksumm swapped - swap it back */
721     if (concat_chksum_swapped) {
722       concat_chksum = SWAP_BYTES_IN_WORD(concat_chksum);
723     }
724     tcp_seg_add_chksum(concat_chksum, concat_chksummed, &last_unsent->chksum,
725       &last_unsent->chksum_swapped);
726     last_unsent->flags |= TF_SEG_DATA_CHECKSUMMED;
727   }
728 #endif /* TCP_CHECKSUM_ON_COPY */
729
730   /*
731    * Phase 3: Append queue to pcb->unsent. Queue may be NULL, but that
732    * is harmless
733    */
734   if (last_unsent == NULL) {
735     pcb->unsent = queue;
736   } else {
737     last_unsent->next = queue;
738   }
739
740   /*
741    * Finally update the pcb state.
742    */
743   pcb->snd_lbb += len;
744   pcb->snd_buf -= len;
745   pcb->snd_queuelen = queuelen;
746
747   LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_write: %"S16_F" (after enqueued)\n",
748     pcb->snd_queuelen));
749   if (pcb->snd_queuelen != 0) {
750     LWIP_ASSERT("tcp_write: valid queue length",
751                 pcb->unacked != NULL || pcb->unsent != NULL);
752   }
753
754   /* Set the PSH flag in the last segment that we enqueued. */
755   if (seg != NULL && seg->tcphdr != NULL && ((apiflags & TCP_WRITE_FLAG_MORE)==0)) {
756     TCPH_SET_FLAG(seg->tcphdr, TCP_PSH);
757   }
758
759   return ERR_OK;
760 memerr:
761   pcb->flags |= TF_NAGLEMEMERR;
762   TCP_STATS_INC(tcp.memerr);
763
764   if (concat_p != NULL) {
765     pbuf_free(concat_p);
766   }
767   if (queue != NULL) {
768     tcp_segs_free(queue);
769   }
770   if (pcb->snd_queuelen != 0) {
771     LWIP_ASSERT("tcp_write: valid queue length", pcb->unacked != NULL ||
772       pcb->unsent != NULL);
773   }
774   LWIP_DEBUGF(TCP_QLEN_DEBUG | LWIP_DBG_STATE, ("tcp_write: %"S16_F" (with mem err)\n", pcb->snd_queuelen));
775   return ERR_MEM;
776 }
777
778 /**
779  * Enqueue TCP options for transmission.
780  *
781  * Called by tcp_connect(), tcp_listen_input(), and tcp_send_ctrl().
782  *
783  * @param pcb Protocol control block for the TCP connection.
784  * @param flags TCP header flags to set in the outgoing segment.
785  */
786 err_t
787 tcp_enqueue_flags(struct tcp_pcb *pcb, u8_t flags)
788 {
789   struct pbuf *p;
790   struct tcp_seg *seg;
791   u8_t optflags = 0;
792   u8_t optlen = 0;
793
794   LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_enqueue_flags: queuelen: %"U16_F"\n", (u16_t)pcb->snd_queuelen));
795
796   LWIP_ASSERT("tcp_enqueue_flags: need either TCP_SYN or TCP_FIN in flags (programmer violates API)",
797               (flags & (TCP_SYN | TCP_FIN)) != 0);
798
799   /* check for configured max queuelen and possible overflow (FIN flag should always come through!) */
800   if (((pcb->snd_queuelen >= TCP_SND_QUEUELEN) || (pcb->snd_queuelen > TCP_SNDQUEUELEN_OVERFLOW)) &&
801       ((flags & TCP_FIN) == 0)) {
802     LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("tcp_enqueue_flags: too long queue %"U16_F" (max %"U16_F")\n",
803                                        pcb->snd_queuelen, (u16_t)TCP_SND_QUEUELEN));
804     TCP_STATS_INC(tcp.memerr);
805     pcb->flags |= TF_NAGLEMEMERR;
806     return ERR_MEM;
807   }
808
809   if (flags & TCP_SYN) {
810     optflags = TF_SEG_OPTS_MSS;
811 #if LWIP_WND_SCALE
812     if ((pcb->state != SYN_RCVD) || (pcb->flags & TF_WND_SCALE)) {
813       /* In a <SYN,ACK> (sent in state SYN_RCVD), the window scale option may only
814          be sent if we received a window scale option from the remote host. */
815       optflags |= TF_SEG_OPTS_WND_SCALE;
816     }
817 #endif /* LWIP_WND_SCALE */
818   }
819 #if LWIP_TCP_TIMESTAMPS
820   if ((pcb->flags & TF_TIMESTAMP)) {
821     /* Make sure the timestamp option is only included in data segments if we
822        agreed about it with the remote host. */
823     optflags |= TF_SEG_OPTS_TS;
824   }
825 #endif /* LWIP_TCP_TIMESTAMPS */
826   optlen = LWIP_TCP_OPT_LENGTH(optflags);
827
828   /* Allocate pbuf with room for TCP header + options */
829   if ((p = pbuf_alloc(PBUF_TRANSPORT, optlen, PBUF_RAM)) == NULL) {
830     pcb->flags |= TF_NAGLEMEMERR;
831     TCP_STATS_INC(tcp.memerr);
832     return ERR_MEM;
833   }
834   LWIP_ASSERT("tcp_enqueue_flags: check that first pbuf can hold optlen",
835               (p->len >= optlen));
836
837   /* Allocate memory for tcp_seg, and fill in fields. */
838   if ((seg = tcp_create_segment(pcb, p, flags, pcb->snd_lbb, optflags)) == NULL) {
839     pcb->flags |= TF_NAGLEMEMERR;
840     TCP_STATS_INC(tcp.memerr);
841     return ERR_MEM;
842   }
843   LWIP_ASSERT("seg->tcphdr not aligned", ((mem_ptr_t)seg->tcphdr % LWIP_MIN(MEM_ALIGNMENT, 4)) == 0);
844   LWIP_ASSERT("tcp_enqueue_flags: invalid segment length", seg->len == 0);
845
846   LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_TRACE,
847               ("tcp_enqueue_flags: queueing %"U32_F":%"U32_F" (0x%"X16_F")\n",
848                lwip_ntohl(seg->tcphdr->seqno),
849                lwip_ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg),
850                (u16_t)flags));
851
852   /* Now append seg to pcb->unsent queue */
853   if (pcb->unsent == NULL) {
854     pcb->unsent = seg;
855   } else {
856     struct tcp_seg *useg;
857     for (useg = pcb->unsent; useg->next != NULL; useg = useg->next);
858     useg->next = seg;
859   }
860 #if TCP_OVERSIZE
861   /* The new unsent tail has no space */
862   pcb->unsent_oversize = 0;
863 #endif /* TCP_OVERSIZE */
864
865   /* SYN and FIN bump the sequence number */
866   if ((flags & TCP_SYN) || (flags & TCP_FIN)) {
867     pcb->snd_lbb++;
868     /* optlen does not influence snd_buf */
869   }
870   if (flags & TCP_FIN) {
871     pcb->flags |= TF_FIN;
872   }
873
874   /* update number of segments on the queues */
875   pcb->snd_queuelen += pbuf_clen(seg->p);
876   LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_enqueue_flags: %"S16_F" (after enqueued)\n", pcb->snd_queuelen));
877   if (pcb->snd_queuelen != 0) {
878     LWIP_ASSERT("tcp_enqueue_flags: invalid queue length",
879       pcb->unacked != NULL || pcb->unsent != NULL);
880   }
881
882   return ERR_OK;
883 }
884
885 #if LWIP_TCP_TIMESTAMPS
886 /* Build a timestamp option (12 bytes long) at the specified options pointer)
887  *
888  * @param pcb tcp_pcb
889  * @param opts option pointer where to store the timestamp option
890  */
891 static void
892 tcp_build_timestamp_option(struct tcp_pcb *pcb, u32_t *opts)
893 {
894   /* Pad with two NOP options to make everything nicely aligned */
895   opts[0] = PP_HTONL(0x0101080A);
896   opts[1] = lwip_htonl(sys_now());
897   opts[2] = lwip_htonl(pcb->ts_recent);
898 }
899 #endif
900
901 #if LWIP_WND_SCALE
902 /** Build a window scale option (3 bytes long) at the specified options pointer)
903  *
904  * @param opts option pointer where to store the window scale option
905  */
906 static void
907 tcp_build_wnd_scale_option(u32_t *opts)
908 {
909   /* Pad with one NOP option to make everything nicely aligned */
910   opts[0] = PP_HTONL(0x01030300 | TCP_RCV_SCALE);
911 }
912 #endif
913
914 /**
915  * Send an ACK without data.
916  *
917  * @param pcb Protocol control block for the TCP connection to send the ACK
918  */
919 err_t
920 tcp_send_empty_ack(struct tcp_pcb *pcb)
921 {
922   err_t err;
923   struct pbuf *p;
924   u8_t optlen = 0;
925   struct netif *netif;
926 #if LWIP_TCP_TIMESTAMPS || CHECKSUM_GEN_TCP
927   struct tcp_hdr *tcphdr;
928 #endif /* LWIP_TCP_TIMESTAMPS || CHECKSUM_GEN_TCP */
929
930 #if LWIP_TCP_TIMESTAMPS
931   if (pcb->flags & TF_TIMESTAMP) {
932     optlen = LWIP_TCP_OPT_LENGTH(TF_SEG_OPTS_TS);
933   }
934 #endif
935
936   p = tcp_output_alloc_header(pcb, optlen, 0, lwip_htonl(pcb->snd_nxt));
937   if (p == NULL) {
938     /* let tcp_fasttmr retry sending this ACK */
939     pcb->flags |= (TF_ACK_DELAY | TF_ACK_NOW);
940     LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_output: (ACK) could not allocate pbuf\n"));
941     return ERR_BUF;
942   }
943 #if LWIP_TCP_TIMESTAMPS || CHECKSUM_GEN_TCP
944   tcphdr = (struct tcp_hdr *)p->payload;
945 #endif /* LWIP_TCP_TIMESTAMPS || CHECKSUM_GEN_TCP */
946   LWIP_DEBUGF(TCP_OUTPUT_DEBUG,
947               ("tcp_output: sending ACK for %"U32_F"\n", pcb->rcv_nxt));
948
949   /* NB. MSS and window scale options are only sent on SYNs, so ignore them here */
950 #if LWIP_TCP_TIMESTAMPS
951   pcb->ts_lastacksent = pcb->rcv_nxt;
952
953   if (pcb->flags & TF_TIMESTAMP) {
954     tcp_build_timestamp_option(pcb, (u32_t *)(tcphdr + 1));
955   }
956 #endif
957
958   netif = ip_route(&pcb->local_ip, &pcb->remote_ip);
959   if (netif == NULL) {
960     err = ERR_RTE;
961   } else {
962 #if CHECKSUM_GEN_TCP
963     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_TCP) {
964       tcphdr->chksum = ip_chksum_pseudo(p, IP_PROTO_TCP, p->tot_len,
965         &pcb->local_ip, &pcb->remote_ip);
966     }
967 #endif
968     netif_apply_pcb(netif, (struct ip_pcb *)pcb);
969     err = ip_output_if(p, &pcb->local_ip, &pcb->remote_ip,
970       pcb->ttl, pcb->tos, IP_PROTO_TCP, netif);
971     netif_apply_pcb(netif, NULL);
972   }
973   pbuf_free(p);
974
975   if (err != ERR_OK) {
976     /* let tcp_fasttmr retry sending this ACK */
977     pcb->flags |= (TF_ACK_DELAY | TF_ACK_NOW);
978   } else {
979     /* remove ACK flags from the PCB, as we sent an empty ACK now */
980     pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
981   }
982
983   return err;
984 }
985
986 /**
987  * @ingroup tcp_raw
988  * Find out what we can send and send it
989  *
990  * @param pcb Protocol control block for the TCP connection to send data
991  * @return ERR_OK if data has been sent or nothing to send
992  *         another err_t on error
993  */
994 err_t
995 tcp_output(struct tcp_pcb *pcb)
996 {
997   struct tcp_seg *seg, *useg;
998   u32_t wnd, snd_nxt;
999   err_t err;
1000   struct netif *netif;
1001 #if TCP_CWND_DEBUG
1002   s16_t i = 0;
1003 #endif /* TCP_CWND_DEBUG */
1004
1005   LWIP_ASSERT_CORE_LOCKED();
1006   /* pcb->state LISTEN not allowed here */
1007   LWIP_ASSERT("don't call tcp_output for listen-pcbs",
1008     pcb->state != LISTEN);
1009
1010   /* First, check if we are invoked by the TCP input processing
1011      code. If so, we do not output anything. Instead, we rely on the
1012      input processing code to call us when input processing is done
1013      with. */
1014   if (tcp_input_pcb == pcb) {
1015     return ERR_OK;
1016   }
1017
1018   wnd = LWIP_MIN(pcb->snd_wnd, pcb->cwnd);
1019
1020   seg = pcb->unsent;
1021
1022   /* If the TF_ACK_NOW flag is set and no data will be sent (either
1023    * because the ->unsent queue is empty or because the window does
1024    * not allow it), construct an empty ACK segment and send it.
1025    *
1026    * If data is to be sent, we will just piggyback the ACK (see below).
1027    */
1028   if (pcb->flags & TF_ACK_NOW &&
1029      (seg == NULL ||
1030       lwip_ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len > wnd)) {
1031      return tcp_send_empty_ack(pcb);
1032   }
1033
1034   /* useg should point to last segment on unacked queue */
1035   useg = pcb->unacked;
1036   if (useg != NULL) {
1037     for (; useg->next != NULL; useg = useg->next);
1038   }
1039
1040   netif = ip_route(&pcb->local_ip, &pcb->remote_ip);
1041   if (netif == NULL) {
1042     return ERR_RTE;
1043   }
1044
1045   /* If we don't have a local IP address, we get one from netif */
1046   if (ip_addr_isany(&pcb->local_ip)) {
1047     const ip_addr_t *local_ip = ip_netif_get_local_ip(netif, &pcb->remote_ip);
1048     if (local_ip == NULL) {
1049       return ERR_RTE;
1050     }
1051     ip_addr_copy(pcb->local_ip, *local_ip);
1052   }
1053
1054 #if TCP_OUTPUT_DEBUG
1055   if (seg == NULL) {
1056     LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_output: nothing to send (%p)\n",
1057                                    (void*)pcb->unsent));
1058   }
1059 #endif /* TCP_OUTPUT_DEBUG */
1060 #if TCP_CWND_DEBUG
1061   if (seg == NULL) {
1062     LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_output: snd_wnd %"TCPWNDSIZE_F
1063                                  ", cwnd %"TCPWNDSIZE_F", wnd %"U32_F
1064                                  ", seg == NULL, ack %"U32_F"\n",
1065                                  pcb->snd_wnd, pcb->cwnd, wnd, pcb->lastack));
1066   } else {
1067     LWIP_DEBUGF(TCP_CWND_DEBUG,
1068                 ("tcp_output: snd_wnd %"TCPWNDSIZE_F", cwnd %"TCPWNDSIZE_F", wnd %"U32_F
1069                  ", effwnd %"U32_F", seq %"U32_F", ack %"U32_F"\n",
1070                  pcb->snd_wnd, pcb->cwnd, wnd,
1071                  lwip_ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len,
1072                  lwip_ntohl(seg->tcphdr->seqno), pcb->lastack));
1073   }
1074 #endif /* TCP_CWND_DEBUG */
1075   /* Check if we need to start the persistent timer when the next unsent segment
1076    * does not fit within the remaining send window and RTO timer is not running (we
1077    * have no in-flight data). A traditional approach would fill the remaining window
1078    * with part of the unsent segment (which will engage zero-window probing upon
1079    * reception of the zero window update from the receiver). This ensures the
1080    * subsequent window update is reliably received. With the goal of being lightweight,
1081    * we avoid splitting the unsent segment and treat the window as already zero.
1082    */
1083   if (seg != NULL &&
1084       lwip_ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len > wnd &&
1085       wnd > 0 && wnd == pcb->snd_wnd && pcb->unacked == NULL) {
1086     /* Start the persist timer */
1087     if (pcb->persist_backoff == 0) {
1088       pcb->persist_cnt = 0;
1089       pcb->persist_backoff = 1;
1090     }
1091     goto output_done;
1092   }
1093   /* data available and window allows it to be sent? */
1094   while (seg != NULL &&
1095          lwip_ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len <= wnd) {
1096     LWIP_ASSERT("RST not expected here!",
1097                 (TCPH_FLAGS(seg->tcphdr) & TCP_RST) == 0);
1098     /* Stop sending if the nagle algorithm would prevent it
1099      * Don't stop:
1100      * - if tcp_write had a memory error before (prevent delayed ACK timeout) or
1101      * - if FIN was already enqueued for this PCB (SYN is always alone in a segment -
1102      *   either seg->next != NULL or pcb->unacked == NULL;
1103      *   RST is no sent using tcp_write/tcp_output.
1104      */
1105     if ((tcp_do_output_nagle(pcb) == 0) &&
1106       ((pcb->flags & (TF_NAGLEMEMERR | TF_FIN)) == 0)) {
1107       break;
1108     }
1109 #if TCP_CWND_DEBUG
1110     LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_output: snd_wnd %"TCPWNDSIZE_F", cwnd %"TCPWNDSIZE_F", wnd %"U32_F", effwnd %"U32_F", seq %"U32_F", ack %"U32_F", i %"S16_F"\n",
1111                             pcb->snd_wnd, pcb->cwnd, wnd,
1112                             lwip_ntohl(seg->tcphdr->seqno) + seg->len -
1113                             pcb->lastack,
1114                             lwip_ntohl(seg->tcphdr->seqno), pcb->lastack, i));
1115     ++i;
1116 #endif /* TCP_CWND_DEBUG */
1117
1118     if (pcb->state != SYN_SENT) {
1119       TCPH_SET_FLAG(seg->tcphdr, TCP_ACK);
1120     }
1121
1122 #if TCP_OVERSIZE_DBGCHECK
1123     seg->oversize_left = 0;
1124 #endif /* TCP_OVERSIZE_DBGCHECK */
1125     err = tcp_output_segment(seg, pcb, netif);
1126     if (err != ERR_OK) {
1127       /* segment could not be sent, for whatever reason */
1128       pcb->flags |= TF_NAGLEMEMERR;
1129       return err;
1130     }
1131     pcb->unsent = seg->next;
1132     if (pcb->state != SYN_SENT) {
1133       pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
1134     }
1135     snd_nxt = lwip_ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg);
1136     if (TCP_SEQ_LT(pcb->snd_nxt, snd_nxt)) {
1137       pcb->snd_nxt = snd_nxt;
1138     }
1139     /* put segment on unacknowledged list if length > 0 */
1140     if (TCP_TCPLEN(seg) > 0) {
1141       seg->next = NULL;
1142       /* unacked list is empty? */
1143       if (pcb->unacked == NULL) {
1144         pcb->unacked = seg;
1145         useg = seg;
1146       /* unacked list is not empty? */
1147       } else {
1148         /* In the case of fast retransmit, the packet should not go to the tail
1149          * of the unacked queue, but rather somewhere before it. We need to check for
1150          * this case. -STJ Jul 27, 2004 */
1151         if (TCP_SEQ_LT(lwip_ntohl(seg->tcphdr->seqno), lwip_ntohl(useg->tcphdr->seqno))) {
1152           /* add segment to before tail of unacked list, keeping the list sorted */
1153           struct tcp_seg **cur_seg = &(pcb->unacked);
1154           while (*cur_seg &&
1155             TCP_SEQ_LT(lwip_ntohl((*cur_seg)->tcphdr->seqno), lwip_ntohl(seg->tcphdr->seqno))) {
1156               cur_seg = &((*cur_seg)->next );
1157           }
1158           seg->next = (*cur_seg);
1159           (*cur_seg) = seg;
1160         } else {
1161           /* add segment to tail of unacked list */
1162           useg->next = seg;
1163           useg = useg->next;
1164         }
1165       }
1166     /* do not queue empty segments on the unacked list */
1167     } else {
1168       tcp_seg_free(seg);
1169     }
1170     seg = pcb->unsent;
1171   }
1172 output_done:
1173 #if TCP_OVERSIZE
1174   if (pcb->unsent == NULL) {
1175     /* last unsent has been removed, reset unsent_oversize */
1176     pcb->unsent_oversize = 0;
1177   }
1178 #endif /* TCP_OVERSIZE */
1179
1180   pcb->flags &= ~TF_NAGLEMEMERR;
1181   return ERR_OK;
1182 }
1183
1184 /**
1185  * Called by tcp_output() to actually send a TCP segment over IP.
1186  *
1187  * @param seg the tcp_seg to send
1188  * @param pcb the tcp_pcb for the TCP connection used to send the segment
1189  * @param netif the netif used to send the segment
1190  */
1191 static err_t
1192 tcp_output_segment(struct tcp_seg *seg, struct tcp_pcb *pcb, struct netif *netif)
1193 {
1194   err_t err;
1195   u16_t len;
1196   u32_t *opts;
1197
1198   if (seg->p->ref != 1) {
1199     /* This can happen if the pbuf of this segment is still referenced by the
1200        netif driver due to deferred transmission. Since this function modifies
1201        p->len, we must not continue in this case. */
1202     return ERR_OK;
1203   }
1204
1205   /* The TCP header has already been constructed, but the ackno and
1206    wnd fields remain. */
1207   seg->tcphdr->ackno = lwip_htonl(pcb->rcv_nxt);
1208
1209   /* advertise our receive window size in this TCP segment */
1210 #if LWIP_WND_SCALE
1211   if (seg->flags & TF_SEG_OPTS_WND_SCALE) {
1212     /* The Window field in a SYN segment itself (the only type where we send
1213        the window scale option) is never scaled. */
1214     seg->tcphdr->wnd = lwip_htons(TCPWND_MIN16(pcb->rcv_ann_wnd));
1215   } else
1216 #endif /* LWIP_WND_SCALE */
1217   {
1218     seg->tcphdr->wnd = lwip_htons(TCPWND_MIN16(RCV_WND_SCALE(pcb, pcb->rcv_ann_wnd)));
1219   }
1220
1221   pcb->rcv_ann_right_edge = pcb->rcv_nxt + pcb->rcv_ann_wnd;
1222
1223   /* Add any requested options.  NB MSS option is only set on SYN
1224      packets, so ignore it here */
1225   /* cast through void* to get rid of alignment warnings */
1226   opts = (u32_t *)(void *)(seg->tcphdr + 1);
1227   if (seg->flags & TF_SEG_OPTS_MSS) {
1228     u16_t mss;
1229 #if TCP_CALCULATE_EFF_SEND_MSS
1230     mss = tcp_eff_send_mss(TCP_MSS, &pcb->local_ip, &pcb->remote_ip);
1231 #else /* TCP_CALCULATE_EFF_SEND_MSS */
1232     mss = TCP_MSS;
1233 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1234     *opts = TCP_BUILD_MSS_OPTION(mss);
1235     opts += 1;
1236   }
1237 #if LWIP_TCP_TIMESTAMPS
1238   pcb->ts_lastacksent = pcb->rcv_nxt;
1239
1240   if (seg->flags & TF_SEG_OPTS_TS) {
1241     tcp_build_timestamp_option(pcb, opts);
1242     opts += 3;
1243   }
1244 #endif
1245 #if LWIP_WND_SCALE
1246   if (seg->flags & TF_SEG_OPTS_WND_SCALE) {
1247     tcp_build_wnd_scale_option(opts);
1248     opts += 1;
1249   }
1250 #endif
1251
1252   /* Set retransmission timer running if it is not currently enabled
1253      This must be set before checking the route. */
1254   if (pcb->rtime < 0) {
1255     pcb->rtime = 0;
1256   }
1257
1258   if (pcb->rttest == 0) {
1259     pcb->rttest = tcp_ticks;
1260     pcb->rtseq = lwip_ntohl(seg->tcphdr->seqno);
1261
1262     LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_output_segment: rtseq %"U32_F"\n", pcb->rtseq));
1263   }
1264   LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_output_segment: %"U32_F":%"U32_F"\n",
1265           lwip_htonl(seg->tcphdr->seqno), lwip_htonl(seg->tcphdr->seqno) +
1266           seg->len));
1267
1268   len = (u16_t)((u8_t *)seg->tcphdr - (u8_t *)seg->p->payload);
1269   if (len == 0) {
1270     /** Exclude retransmitted segments from this count. */
1271     MIB2_STATS_INC(mib2.tcpoutsegs);
1272   }
1273
1274   seg->p->len -= len;
1275   seg->p->tot_len -= len;
1276
1277   seg->p->payload = seg->tcphdr;
1278
1279   seg->tcphdr->chksum = 0;
1280 #if CHECKSUM_GEN_TCP
1281   IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_TCP) {
1282 #if TCP_CHECKSUM_ON_COPY
1283     u32_t acc;
1284 #if TCP_CHECKSUM_ON_COPY_SANITY_CHECK
1285     u16_t chksum_slow = ip_chksum_pseudo(seg->p, IP_PROTO_TCP,
1286       seg->p->tot_len, &pcb->local_ip, &pcb->remote_ip);
1287 #endif /* TCP_CHECKSUM_ON_COPY_SANITY_CHECK */
1288     if ((seg->flags & TF_SEG_DATA_CHECKSUMMED) == 0) {
1289       LWIP_ASSERT("data included but not checksummed",
1290         seg->p->tot_len == (TCPH_HDRLEN(seg->tcphdr) * 4));
1291     }
1292
1293     /* rebuild TCP header checksum (TCP header changes for retransmissions!) */
1294     acc = ip_chksum_pseudo_partial(seg->p, IP_PROTO_TCP,
1295       seg->p->tot_len, TCPH_HDRLEN(seg->tcphdr) * 4, &pcb->local_ip, &pcb->remote_ip);
1296     /* add payload checksum */
1297     if (seg->chksum_swapped) {
1298       seg->chksum = SWAP_BYTES_IN_WORD(seg->chksum);
1299       seg->chksum_swapped = 0;
1300     }
1301     acc += (u16_t)~(seg->chksum);
1302     seg->tcphdr->chksum = FOLD_U32T(acc);
1303 #if TCP_CHECKSUM_ON_COPY_SANITY_CHECK
1304     if (chksum_slow != seg->tcphdr->chksum) {
1305       TCP_CHECKSUM_ON_COPY_SANITY_CHECK_FAIL(
1306                   ("tcp_output_segment: calculated checksum is %"X16_F" instead of %"X16_F"\n",
1307                   seg->tcphdr->chksum, chksum_slow));
1308       seg->tcphdr->chksum = chksum_slow;
1309     }
1310 #endif /* TCP_CHECKSUM_ON_COPY_SANITY_CHECK */
1311 #else /* TCP_CHECKSUM_ON_COPY */
1312     seg->tcphdr->chksum = ip_chksum_pseudo(seg->p, IP_PROTO_TCP,
1313       seg->p->tot_len, &pcb->local_ip, &pcb->remote_ip);
1314 #endif /* TCP_CHECKSUM_ON_COPY */
1315   }
1316 #endif /* CHECKSUM_GEN_TCP */
1317   TCP_STATS_INC(tcp.xmit);
1318
1319 #if TCP_OUTPUT_DEBUG
1320 #if LWIP_IP_DEBUG_TARGET
1321   if (debug_target_match(PCB_ISIPV6(pcb), &pcb->local_ip, &pcb->remote_ip))
1322   {
1323 #endif
1324   tcp_debug_print(seg->tcphdr);
1325 #if LWIP_IP_DEBUG_TARGET
1326   }
1327 #endif
1328 #endif
1329
1330   netif_apply_pcb(netif, (struct ip_pcb *)pcb);
1331   err = ip_output_if(seg->p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl,
1332     pcb->tos, IP_PROTO_TCP, netif);
1333   netif_apply_pcb(netif, NULL);
1334   return err;
1335 }
1336
1337 /**
1338  * Send a TCP RESET packet (empty segment with RST flag set) either to
1339  * abort a connection or to show that there is no matching local connection
1340  * for a received segment.
1341  *
1342  * Called by tcp_abort() (to abort a local connection), tcp_input() (if no
1343  * matching local pcb was found), tcp_listen_input() (if incoming segment
1344  * has ACK flag set) and tcp_process() (received segment in the wrong state)
1345  *
1346  * Since a RST segment is in most cases not sent for an active connection,
1347  * tcp_rst() has a number of arguments that are taken from a tcp_pcb for
1348  * most other segment output functions.
1349  *
1350  * @param seqno the sequence number to use for the outgoing segment
1351  * @param ackno the acknowledge number to use for the outgoing segment
1352  * @param local_ip the local IP address to send the segment from
1353  * @param remote_ip the remote IP address to send the segment to
1354  * @param local_port the local TCP port to send the segment from
1355  * @param remote_port the remote TCP port to send the segment to
1356  */
1357 void
1358 tcp_rst(u32_t seqno, u32_t ackno,
1359   const ip_addr_t *local_ip, const ip_addr_t *remote_ip,
1360   u16_t local_port, u16_t remote_port)
1361 {
1362   struct pbuf *p;
1363   struct tcp_hdr *tcphdr;
1364   struct netif *netif;
1365   p = pbuf_alloc(PBUF_IP, TCP_HLEN, PBUF_RAM);
1366   if (p == NULL) {
1367     LWIP_DEBUGF(TCP_DEBUG, ("tcp_rst: could not allocate memory for pbuf\n"));
1368     return;
1369   }
1370   LWIP_ASSERT("check that first pbuf can hold struct tcp_hdr",
1371               (p->len >= sizeof(struct tcp_hdr)));
1372
1373   tcphdr = (struct tcp_hdr *)p->payload;
1374   tcphdr->src = lwip_htons(local_port);
1375   tcphdr->dest = lwip_htons(remote_port);
1376   tcphdr->seqno = lwip_htonl(seqno);
1377   tcphdr->ackno = lwip_htonl(ackno);
1378   TCPH_HDRLEN_FLAGS_SET(tcphdr, TCP_HLEN/4, TCP_RST | TCP_ACK);
1379 #if LWIP_WND_SCALE
1380   tcphdr->wnd = PP_HTONS(((TCP_WND >> TCP_RCV_SCALE) & 0xFFFF));
1381 #else
1382   tcphdr->wnd = PP_HTONS(TCP_WND);
1383 #endif
1384   tcphdr->chksum = 0;
1385   tcphdr->urgp = 0;
1386
1387   TCP_STATS_INC(tcp.xmit);
1388   MIB2_STATS_INC(mib2.tcpoutrsts);
1389
1390   netif = ip_route(local_ip, remote_ip);
1391   if (netif != NULL) {
1392 #if CHECKSUM_GEN_TCP
1393     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_TCP) {
1394       tcphdr->chksum = ip_chksum_pseudo(p, IP_PROTO_TCP, p->tot_len,
1395                                         local_ip, remote_ip);
1396     }
1397 #endif
1398     /* Send output with hardcoded TTL/HL since we have no access to the pcb */
1399     ip_output_if(p, local_ip, remote_ip, TCP_TTL, 0, IP_PROTO_TCP, netif);
1400   }
1401   pbuf_free(p);
1402   LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_rst: seqno %"U32_F" ackno %"U32_F".\n", seqno, ackno));
1403 }
1404
1405 /**
1406  * Requeue all unacked segments for retransmission
1407  *
1408  * Called by tcp_slowtmr() for slow retransmission.
1409  *
1410  * @param pcb the tcp_pcb for which to re-enqueue all unacked segments
1411  */
1412 void
1413 tcp_rexmit_rto(struct tcp_pcb *pcb)
1414 {
1415   struct tcp_seg *seg;
1416
1417   if (pcb->unacked == NULL) {
1418     return;
1419   }
1420
1421   /* Move all unacked segments to the head of the unsent queue */
1422   for (seg = pcb->unacked; seg->next != NULL; seg = seg->next);
1423   /* concatenate unsent queue after unacked queue */
1424   seg->next = pcb->unsent;
1425 #if TCP_OVERSIZE_DBGCHECK
1426   /* if last unsent changed, we need to update unsent_oversize */
1427   if (pcb->unsent == NULL) {
1428     pcb->unsent_oversize = seg->oversize_left;
1429   }
1430 #endif /* TCP_OVERSIZE_DBGCHECK */
1431   /* unsent queue is the concatenated queue (of unacked, unsent) */
1432   pcb->unsent = pcb->unacked;
1433   /* unacked queue is now empty */
1434   pcb->unacked = NULL;
1435
1436   /* increment number of retransmissions */
1437   if (pcb->nrtx < 0xFF) {
1438     ++pcb->nrtx;
1439   }
1440
1441   /* Don't take any RTT measurements after retransmitting. */
1442   pcb->rttest = 0;
1443
1444   /* Do the actual retransmission */
1445   tcp_output(pcb);
1446 }
1447
1448 /**
1449  * Requeue the first unacked segment for retransmission
1450  *
1451  * Called by tcp_receive() for fast retransmit.
1452  *
1453  * @param pcb the tcp_pcb for which to retransmit the first unacked segment
1454  */
1455 void
1456 tcp_rexmit(struct tcp_pcb *pcb)
1457 {
1458   struct tcp_seg *seg;
1459   struct tcp_seg **cur_seg;
1460
1461   if (pcb->unacked == NULL) {
1462     return;
1463   }
1464
1465   /* Move the first unacked segment to the unsent queue */
1466   /* Keep the unsent queue sorted. */
1467   seg = pcb->unacked;
1468   pcb->unacked = seg->next;
1469
1470   cur_seg = &(pcb->unsent);
1471   while (*cur_seg &&
1472     TCP_SEQ_LT(lwip_ntohl((*cur_seg)->tcphdr->seqno), lwip_ntohl(seg->tcphdr->seqno))) {
1473       cur_seg = &((*cur_seg)->next );
1474   }
1475   seg->next = *cur_seg;
1476   *cur_seg = seg;
1477 #if TCP_OVERSIZE
1478   if (seg->next == NULL) {
1479     /* the retransmitted segment is last in unsent, so reset unsent_oversize */
1480     pcb->unsent_oversize = 0;
1481   }
1482 #endif /* TCP_OVERSIZE */
1483
1484   if (pcb->nrtx < 0xFF) {
1485     ++pcb->nrtx;
1486   }
1487
1488   /* Don't take any rtt measurements after retransmitting. */
1489   pcb->rttest = 0;
1490
1491   /* Do the actual retransmission. */
1492   MIB2_STATS_INC(mib2.tcpretranssegs);
1493   /* No need to call tcp_output: we are always called from tcp_input()
1494      and thus tcp_output directly returns. */
1495 }
1496
1497
1498 /**
1499  * Handle retransmission after three dupacks received
1500  *
1501  * @param pcb the tcp_pcb for which to retransmit the first unacked segment
1502  */
1503 void
1504 tcp_rexmit_fast(struct tcp_pcb *pcb)
1505 {
1506   if (pcb->unacked != NULL && !(pcb->flags & TF_INFR)) {
1507     /* This is fast retransmit. Retransmit the first unacked segment. */
1508     LWIP_DEBUGF(TCP_FR_DEBUG,
1509                 ("tcp_receive: dupacks %"U16_F" (%"U32_F
1510                  "), fast retransmit %"U32_F"\n",
1511                  (u16_t)pcb->dupacks, pcb->lastack,
1512                  lwip_ntohl(pcb->unacked->tcphdr->seqno)));
1513     tcp_rexmit(pcb);
1514
1515     /* Set ssthresh to half of the minimum of the current
1516      * cwnd and the advertised window */
1517     pcb->ssthresh = LWIP_MIN(pcb->cwnd, pcb->snd_wnd) / 2;
1518
1519     /* The minimum value for ssthresh should be 2 MSS */
1520     if (pcb->ssthresh < (2U * pcb->mss)) {
1521       LWIP_DEBUGF(TCP_FR_DEBUG,
1522                   ("tcp_receive: The minimum value for ssthresh %"TCPWNDSIZE_F
1523                    " should be min 2 mss %"U16_F"...\n",
1524                    pcb->ssthresh, (u16_t)(2*pcb->mss)));
1525       pcb->ssthresh = 2*pcb->mss;
1526     }
1527
1528     pcb->cwnd = pcb->ssthresh + 3 * pcb->mss;
1529     pcb->flags |= TF_INFR;
1530
1531     /* Reset the retransmission timer to prevent immediate rto retransmissions */
1532     pcb->rtime = 0;
1533   }
1534 }
1535
1536
1537 /**
1538  * Send keepalive packets to keep a connection active although
1539  * no data is sent over it.
1540  *
1541  * Called by tcp_slowtmr()
1542  *
1543  * @param pcb the tcp_pcb for which to send a keepalive packet
1544  */
1545 err_t
1546 tcp_keepalive(struct tcp_pcb *pcb)
1547 {
1548   err_t err;
1549   struct pbuf *p;
1550   struct netif *netif;
1551
1552   LWIP_DEBUGF(TCP_DEBUG, ("tcp_keepalive: sending KEEPALIVE probe to "));
1553   ip_addr_debug_print(TCP_DEBUG, &pcb->remote_ip);
1554   LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1555
1556   LWIP_DEBUGF(TCP_DEBUG, ("tcp_keepalive: tcp_ticks %"U32_F"   pcb->tmr %"U32_F" pcb->keep_cnt_sent %"U16_F"\n",
1557                           tcp_ticks, pcb->tmr, (u16_t)pcb->keep_cnt_sent));
1558
1559   p = tcp_output_alloc_header(pcb, 0, 0, lwip_htonl(pcb->snd_nxt - 1));
1560   if (p == NULL) {
1561     LWIP_DEBUGF(TCP_DEBUG,
1562                 ("tcp_keepalive: could not allocate memory for pbuf\n"));
1563     return ERR_MEM;
1564   }
1565   netif = ip_route(&pcb->local_ip, &pcb->remote_ip);
1566   if (netif == NULL) {
1567     err = ERR_RTE;
1568   } else {
1569 #if CHECKSUM_GEN_TCP
1570     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_TCP) {
1571       struct tcp_hdr *tcphdr = (struct tcp_hdr *)p->payload;
1572       tcphdr->chksum = ip_chksum_pseudo(p, IP_PROTO_TCP, p->tot_len,
1573         &pcb->local_ip, &pcb->remote_ip);
1574     }
1575 #endif /* CHECKSUM_GEN_TCP */
1576     TCP_STATS_INC(tcp.xmit);
1577
1578     /* Send output to IP */
1579     netif_apply_pcb(netif, (struct ip_pcb *)pcb);
1580     err = ip_output_if(p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl, 0, IP_PROTO_TCP, netif);
1581     netif_apply_pcb(netif, NULL);
1582   }
1583   pbuf_free(p);
1584
1585   LWIP_DEBUGF(TCP_DEBUG, ("tcp_keepalive: seqno %"U32_F" ackno %"U32_F" err %d.\n",
1586                           pcb->snd_nxt - 1, pcb->rcv_nxt, (int)err));
1587   return err;
1588 }
1589
1590
1591 /**
1592  * Send persist timer zero-window probes to keep a connection active
1593  * when a window update is lost.
1594  *
1595  * Called by tcp_slowtmr()
1596  *
1597  * @param pcb the tcp_pcb for which to send a zero-window probe packet
1598  */
1599 err_t
1600 tcp_zero_window_probe(struct tcp_pcb *pcb)
1601 {
1602   err_t err;
1603   struct pbuf *p;
1604   struct tcp_hdr *tcphdr;
1605   struct tcp_seg *seg;
1606   u16_t len;
1607   u8_t is_fin;
1608   u32_t snd_nxt;
1609   struct netif *netif;
1610
1611   LWIP_DEBUGF(TCP_DEBUG, ("tcp_zero_window_probe: sending ZERO WINDOW probe to "));
1612   ip_addr_debug_print(TCP_DEBUG, &pcb->remote_ip);
1613   LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1614
1615   LWIP_DEBUGF(TCP_DEBUG,
1616               ("tcp_zero_window_probe: tcp_ticks %"U32_F
1617                "   pcb->tmr %"U32_F" pcb->keep_cnt_sent %"U16_F"\n",
1618                tcp_ticks, pcb->tmr, (u16_t)pcb->keep_cnt_sent));
1619
1620   seg = pcb->unacked;
1621
1622   if (seg == NULL) {
1623     seg = pcb->unsent;
1624   }
1625   if (seg == NULL) {
1626     /* nothing to send, zero window probe not needed */
1627     return ERR_OK;
1628   }
1629
1630   is_fin = ((TCPH_FLAGS(seg->tcphdr) & TCP_FIN) != 0) && (seg->len == 0);
1631   /* we want to send one seqno: either FIN or data (no options) */
1632   len = is_fin ? 0 : 1;
1633
1634   p = tcp_output_alloc_header(pcb, 0, len, seg->tcphdr->seqno);
1635   if (p == NULL) {
1636     LWIP_DEBUGF(TCP_DEBUG, ("tcp_zero_window_probe: no memory for pbuf\n"));
1637     return ERR_MEM;
1638   }
1639   tcphdr = (struct tcp_hdr *)p->payload;
1640
1641   if (is_fin) {
1642     /* FIN segment, no data */
1643     TCPH_FLAGS_SET(tcphdr, TCP_ACK | TCP_FIN);
1644   } else {
1645     /* Data segment, copy in one byte from the head of the unacked queue */
1646     char *d = ((char *)p->payload + TCP_HLEN);
1647     /* Depending on whether the segment has already been sent (unacked) or not
1648        (unsent), seg->p->payload points to the IP header or TCP header.
1649        Ensure we copy the first TCP data byte: */
1650     pbuf_copy_partial(seg->p, d, 1, seg->p->tot_len - seg->len);
1651   }
1652
1653   /* The byte may be acknowledged without the window being opened. */
1654   snd_nxt = lwip_ntohl(seg->tcphdr->seqno) + 1;
1655   if (TCP_SEQ_LT(pcb->snd_nxt, snd_nxt)) {
1656     pcb->snd_nxt = snd_nxt;
1657   }
1658
1659   netif = ip_route(&pcb->local_ip, &pcb->remote_ip);
1660   if (netif == NULL) {
1661     err = ERR_RTE;
1662   } else {
1663 #if CHECKSUM_GEN_TCP
1664     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_TCP) {
1665       tcphdr->chksum = ip_chksum_pseudo(p, IP_PROTO_TCP, p->tot_len,
1666         &pcb->local_ip, &pcb->remote_ip);
1667     }
1668 #endif
1669     TCP_STATS_INC(tcp.xmit);
1670
1671     /* Send output to IP */
1672     netif_apply_pcb(netif, (struct ip_pcb *)pcb);
1673     err = ip_output_if(p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl,
1674       0, IP_PROTO_TCP, netif);
1675     netif_apply_pcb(netif, NULL);
1676   }
1677
1678   pbuf_free(p);
1679
1680   LWIP_DEBUGF(TCP_DEBUG, ("tcp_zero_window_probe: seqno %"U32_F
1681                           " ackno %"U32_F" err %d.\n",
1682                           pcb->snd_nxt - 1, pcb->rcv_nxt, (int)err));
1683   return err;
1684 }
1685 #endif /* LWIP_TCP */