]> git.sur5r.net Git - freertos/blob - Demo/Common/ethernet/lwIP/core/tcp.c
89dfd2413336c794b1dfecee898c66f950501173
[freertos] / Demo / Common / ethernet / lwIP / core / tcp.c
1 /**
2  * @file
3  *
4  * Transmission Control Protocol for IP
5  *
6  * This file contains common functions for the TCP implementation, such as functinos
7  * for manipulating the data structures and the TCP timer functions. TCP functions
8  * related to input and output is found in tcp_in.c and tcp_out.c respectively.
9  *
10  */
11
12 /*
13  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
14  * All rights reserved. 
15  * 
16  * Redistribution and use in source and binary forms, with or without modification, 
17  * are permitted provided that the following conditions are met:
18  *
19  * 1. Redistributions of source code must retain the above copyright notice,
20  *    this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright notice,
22  *    this list of conditions and the following disclaimer in the documentation
23  *    and/or other materials provided with the distribution.
24  * 3. The name of the author may not be used to endorse or promote products
25  *    derived from this software without specific prior written permission. 
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
28  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
29  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
30  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
31  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
32  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
35  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
36  * OF SUCH DAMAGE.
37  *
38  * This file is part of the lwIP TCP/IP stack.
39  * 
40  * Author: Adam Dunkels <adam@sics.se>
41  *
42  */
43
44 #include <string.h>
45
46 #include "lwip/opt.h"
47 #include "lwip/def.h"
48 #include "lwip/mem.h"
49 #include "lwip/memp.h"
50 #include "lwip/snmp.h"
51
52 #include "lwip/tcp.h"
53 #if LWIP_TCP
54
55 /* Incremented every coarse grained timer shot (typically every 500 ms). */
56 u32_t tcp_ticks;
57 const u8_t tcp_backoff[13] =
58     { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7};
59
60 /* The TCP PCB lists. */
61
62 /** List of all TCP PCBs in LISTEN state */
63 union tcp_listen_pcbs_t tcp_listen_pcbs;
64 /** List of all TCP PCBs that are in a state in which
65  * they accept or send data. */
66 struct tcp_pcb *tcp_active_pcbs;  
67 /** List of all TCP PCBs in TIME-WAIT state */
68 struct tcp_pcb *tcp_tw_pcbs;
69
70 struct tcp_pcb *tcp_tmp_pcb;
71
72 static u8_t tcp_timer;
73 static u16_t tcp_new_port(void);
74
75 /**
76  * Initializes the TCP layer.
77  */
78 void
79 tcp_init(void)
80 {
81   /* Clear globals. */
82   tcp_listen_pcbs.listen_pcbs = NULL;
83   tcp_active_pcbs = NULL;
84   tcp_tw_pcbs = NULL;
85   tcp_tmp_pcb = NULL;
86   
87   /* initialize timer */
88   tcp_ticks = 0;
89   tcp_timer = 0;
90   
91 }
92
93 /**
94  * Called periodically to dispatch TCP timers.
95  *
96  */
97 void
98 tcp_tmr(void)
99 {
100   /* Call tcp_fasttmr() every 250 ms */
101   tcp_fasttmr();
102
103   if (++tcp_timer & 1) {
104     /* Call tcp_tmr() every 500 ms, i.e., every other timer
105        tcp_tmr() is called. */
106     tcp_slowtmr();
107   }
108 }
109
110 /**
111  * Closes the connection held by the PCB.
112  *
113  */
114 err_t
115 tcp_close(struct tcp_pcb *pcb)
116 {
117   err_t err;
118
119 #if TCP_DEBUG
120   LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in "));
121   tcp_debug_print_state(pcb->state);
122 #endif /* TCP_DEBUG */
123
124   switch (pcb->state) {
125   case CLOSED:
126     /* Closing a pcb in the CLOSED state might seem erroneous,
127      * however, it is in this state once allocated and as yet unused
128      * and the user needs some way to free it should the need arise.
129      * Calling tcp_close() with a pcb that has already been closed, (i.e. twice)
130      * or for a pcb that has been used and then entered the CLOSED state 
131      * is erroneous, but this should never happen as the pcb has in those cases
132      * been freed, and so any remaining handles are bogus. */
133     err = ERR_OK;
134     memp_free(MEMP_TCP_PCB, pcb);
135     pcb = NULL;
136     break;
137   case LISTEN:
138     err = ERR_OK;
139     tcp_pcb_remove((struct tcp_pcb **)&tcp_listen_pcbs.pcbs, pcb);
140     memp_free(MEMP_TCP_PCB_LISTEN, pcb);
141     pcb = NULL;
142     break;
143   case SYN_SENT:
144     err = ERR_OK;
145     tcp_pcb_remove(&tcp_active_pcbs, pcb);
146     memp_free(MEMP_TCP_PCB, pcb);
147     pcb = NULL;
148     snmp_inc_tcpattemptfails();
149     break;
150   case SYN_RCVD:
151     err = tcp_send_ctrl(pcb, TCP_FIN);
152     if (err == ERR_OK) {
153       snmp_inc_tcpattemptfails();
154       pcb->state = FIN_WAIT_1;
155     }
156     break;
157   case ESTABLISHED:
158     err = tcp_send_ctrl(pcb, TCP_FIN);
159     if (err == ERR_OK) {
160       snmp_inc_tcpestabresets();
161       pcb->state = FIN_WAIT_1;
162     }
163     break;
164   case CLOSE_WAIT:
165     err = tcp_send_ctrl(pcb, TCP_FIN);
166     if (err == ERR_OK) {
167       snmp_inc_tcpestabresets();
168       pcb->state = LAST_ACK;
169     }
170     break;
171   default:
172     /* Has already been closed, do nothing. */
173     err = ERR_OK;
174     pcb = NULL;
175     break;
176   }
177
178   if (pcb != NULL && err == ERR_OK) {
179     err = tcp_output(pcb);
180   }
181   return err;
182 }
183
184 /**
185  * Aborts a connection by sending a RST to the remote host and deletes
186  * the local protocol control block. This is done when a connection is
187  * killed because of shortage of memory.
188  *
189  */
190 void
191 tcp_abort(struct tcp_pcb *pcb)
192 {
193   u32_t seqno, ackno;
194   u16_t remote_port, local_port;
195   struct ip_addr remote_ip, local_ip;
196 #if LWIP_CALLBACK_API  
197   void (* errf)(void *arg, err_t err);
198 #endif /* LWIP_CALLBACK_API */
199   void *errf_arg;
200
201   
202   /* Figure out on which TCP PCB list we are, and remove us. If we
203      are in an active state, call the receive function associated with
204      the PCB with a NULL argument, and send an RST to the remote end. */
205   if (pcb->state == TIME_WAIT) {
206     tcp_pcb_remove(&tcp_tw_pcbs, pcb);
207     memp_free(MEMP_TCP_PCB, pcb);
208   } else {
209     seqno = pcb->snd_nxt;
210     ackno = pcb->rcv_nxt;
211     ip_addr_set(&local_ip, &(pcb->local_ip));
212     ip_addr_set(&remote_ip, &(pcb->remote_ip));
213     local_port = pcb->local_port;
214     remote_port = pcb->remote_port;
215 #if LWIP_CALLBACK_API
216     errf = pcb->errf;
217 #endif /* LWIP_CALLBACK_API */
218     errf_arg = pcb->callback_arg;
219     tcp_pcb_remove(&tcp_active_pcbs, pcb);
220     if (pcb->unacked != NULL) {
221       tcp_segs_free(pcb->unacked);
222     }
223     if (pcb->unsent != NULL) {
224       tcp_segs_free(pcb->unsent);
225     }
226 #if TCP_QUEUE_OOSEQ    
227     if (pcb->ooseq != NULL) {
228       tcp_segs_free(pcb->ooseq);
229     }
230 #endif /* TCP_QUEUE_OOSEQ */
231     memp_free(MEMP_TCP_PCB, pcb);
232     TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT);
233     LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abort: sending RST\n"));
234     tcp_rst(seqno, ackno, &local_ip, &remote_ip, local_port, remote_port);
235   }
236 }
237
238 /**
239  * Binds the connection to a local portnumber and IP address. If the
240  * IP address is not given (i.e., ipaddr == NULL), the IP address of
241  * the outgoing network interface is used instead.
242  *
243  */
244
245 err_t
246 tcp_bind(struct tcp_pcb *pcb, struct ip_addr *ipaddr, u16_t port)
247 {
248   struct tcp_pcb *cpcb;
249
250   if (port == 0) {
251     port = tcp_new_port();
252   }
253   /* Check if the address already is in use. */
254   for(cpcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs;
255       cpcb != NULL; cpcb = cpcb->next) {
256     if (cpcb->local_port == port) {
257       if (ip_addr_isany(&(cpcb->local_ip)) ||
258         ip_addr_isany(ipaddr) ||
259         ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
260           return ERR_USE;
261       }
262     }
263   }
264   for(cpcb = tcp_active_pcbs;
265       cpcb != NULL; cpcb = cpcb->next) {
266     if (cpcb->local_port == port) {
267       if (ip_addr_isany(&(cpcb->local_ip)) ||
268    ip_addr_isany(ipaddr) ||
269    ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
270   return ERR_USE;
271       }
272     }
273   }
274
275   if (!ip_addr_isany(ipaddr)) {
276     pcb->local_ip = *ipaddr;
277   }
278   pcb->local_port = port;
279   LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
280   return ERR_OK;
281 }
282 #if LWIP_CALLBACK_API
283 static err_t
284 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
285 {
286   (void)arg;
287   (void)pcb;
288   (void)err;
289
290   return ERR_ABRT;
291 }
292 #endif /* LWIP_CALLBACK_API */
293
294 /**
295  * Set the state of the connection to be LISTEN, which means that it
296  * is able to accept incoming connections. The protocol control block
297  * is reallocated in order to consume less memory. Setting the
298  * connection to LISTEN is an irreversible process.
299  *
300  */
301 struct tcp_pcb *
302 tcp_listen(struct tcp_pcb *pcb)
303 {
304   struct tcp_pcb_listen *lpcb;
305
306   /* already listening? */
307   if (pcb->state == LISTEN) {
308     return pcb;
309   }
310   lpcb = memp_malloc(MEMP_TCP_PCB_LISTEN);
311   if (lpcb == NULL) {
312     return NULL;
313   }
314   lpcb->callback_arg = pcb->callback_arg;
315   lpcb->local_port = pcb->local_port;
316   lpcb->state = LISTEN;
317   lpcb->so_options = pcb->so_options;
318   lpcb->so_options |= SOF_ACCEPTCONN;
319   lpcb->ttl = pcb->ttl;
320   lpcb->tos = pcb->tos;
321   ip_addr_set(&lpcb->local_ip, &pcb->local_ip);
322   memp_free(MEMP_TCP_PCB, pcb);
323 #if LWIP_CALLBACK_API
324   lpcb->accept = tcp_accept_null;
325 #endif /* LWIP_CALLBACK_API */
326   TCP_REG(&tcp_listen_pcbs.listen_pcbs, lpcb);
327   return (struct tcp_pcb *)lpcb;
328 }
329
330 /**
331  * This function should be called by the application when it has
332  * processed the data. The purpose is to advertise a larger window
333  * when the data has been processed.
334  *
335  */
336 void
337 tcp_recved(struct tcp_pcb *pcb, u16_t len)
338 {
339   if ((u32_t)pcb->rcv_wnd + len > TCP_WND) {
340     pcb->rcv_wnd = TCP_WND;
341   } else {
342     pcb->rcv_wnd += len;
343   }
344   if (!(pcb->flags & TF_ACK_DELAY) &&
345      !(pcb->flags & TF_ACK_NOW)) {
346     /*
347      * We send an ACK here (if one is not already pending, hence
348      * the above tests) as tcp_recved() implies that the application
349      * has processed some data, and so we can open the receiver's
350      * window to allow more to be transmitted.  This could result in
351      * two ACKs being sent for each received packet in some limited cases
352      * (where the application is only receiving data, and is slow to
353      * process it) but it is necessary to guarantee that the sender can
354      * continue to transmit.
355      */
356     tcp_ack(pcb);
357   } 
358   else if (pcb->flags & TF_ACK_DELAY && pcb->rcv_wnd >= TCP_WND/2) {
359     /* If we can send a window update such that there is a full
360      * segment available in the window, do so now.  This is sort of
361      * nagle-like in its goals, and tries to hit a compromise between
362      * sending acks each time the window is updated, and only sending
363      * window updates when a timer expires.  The "threshold" used
364      * above (currently TCP_WND/2) can be tuned to be more or less
365      * aggressive  */
366     tcp_ack_now(pcb);
367   }
368
369   LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: recveived %"U16_F" bytes, wnd %"U16_F" (%"U16_F").\n",
370          len, pcb->rcv_wnd, TCP_WND - pcb->rcv_wnd));
371 }
372
373 /**
374  * A nastly hack featuring 'goto' statements that allocates a
375  * new TCP local port.
376  */
377 static u16_t
378 tcp_new_port(void)
379 {
380   struct tcp_pcb *pcb;
381 #ifndef TCP_LOCAL_PORT_RANGE_START
382 #define TCP_LOCAL_PORT_RANGE_START 4096
383 #define TCP_LOCAL_PORT_RANGE_END   0x7fff
384 #endif
385   static u16_t port = TCP_LOCAL_PORT_RANGE_START;
386   
387  again:
388   if (++port > TCP_LOCAL_PORT_RANGE_END) {
389     port = TCP_LOCAL_PORT_RANGE_START;
390   }
391   
392   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
393     if (pcb->local_port == port) {
394       goto again;
395     }
396   }
397   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
398     if (pcb->local_port == port) {
399       goto again;
400     }
401   }
402   for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
403     if (pcb->local_port == port) {
404       goto again;
405     }
406   }
407   return port;
408 }
409
410 /**
411  * Connects to another host. The function given as the "connected"
412  * argument will be called when the connection has been established.
413  *
414  */
415 err_t
416 tcp_connect(struct tcp_pcb *pcb, struct ip_addr *ipaddr, u16_t port,
417       err_t (* connected)(void *arg, struct tcp_pcb *tpcb, err_t err))
418 {
419   u32_t optdata;
420   err_t ret;
421   u32_t iss;
422
423   LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
424   if (ipaddr != NULL) {
425     pcb->remote_ip = *ipaddr;
426   } else {
427     return ERR_VAL;
428   }
429   pcb->remote_port = port;
430   if (pcb->local_port == 0) {
431     pcb->local_port = tcp_new_port();
432   }
433   iss = tcp_next_iss();
434   pcb->rcv_nxt = 0;
435   pcb->snd_nxt = iss;
436   pcb->lastack = iss - 1;
437   pcb->snd_lbb = iss - 1;
438   pcb->rcv_wnd = TCP_WND;
439   pcb->snd_wnd = TCP_WND;
440   pcb->mss = TCP_MSS;
441   pcb->cwnd = 1;
442   pcb->ssthresh = pcb->mss * 10;
443   pcb->state = SYN_SENT;
444 #if LWIP_CALLBACK_API  
445   pcb->connected = connected;
446 #endif /* LWIP_CALLBACK_API */  
447   TCP_REG(&tcp_active_pcbs, pcb);
448
449   snmp_inc_tcpactiveopens();
450   
451   /* Build an MSS option */
452   optdata = htonl(((u32_t)2 << 24) | 
453       ((u32_t)4 << 16) | 
454       (((u32_t)pcb->mss / 256) << 8) |
455       (pcb->mss & 255));
456
457   ret = tcp_enqueue(pcb, NULL, 0, TCP_SYN, 0, (u8_t *)&optdata, 4);
458   if (ret == ERR_OK) { 
459     tcp_output(pcb);
460   }
461   return ret;
462
463
464 /**
465  * Called every 500 ms and implements the retransmission timer and the timer that
466  * removes PCBs that have been in TIME-WAIT for enough time. It also increments
467  * various timers such as the inactivity timer in each PCB.
468  */
469 void
470 tcp_slowtmr(void)
471 {
472   struct tcp_pcb *pcb, *pcb2, *prev;
473   u32_t eff_wnd;
474   u8_t pcb_remove;      /* flag if a PCB should be removed */
475   err_t err;
476
477   err = ERR_OK;
478
479   ++tcp_ticks;
480
481   /* Steps through all of the active PCBs. */
482   prev = NULL;
483   pcb = tcp_active_pcbs;
484   if (pcb == NULL) {
485     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
486   }
487   while (pcb != NULL) {
488     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
489     LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
490     LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
491     LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
492
493     pcb_remove = 0;
494
495     if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX) {
496       ++pcb_remove;
497       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
498     }
499     else if (pcb->nrtx == TCP_MAXRTX) {
500       ++pcb_remove;
501       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
502     } else {
503       ++pcb->rtime;
504       if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) {
505
506         /* Time for a retransmission. */
507         LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"U16_F" pcb->rto %"U16_F"\n",
508           pcb->rtime, pcb->rto));
509
510         /* Double retransmission time-out unless we are trying to
511          * connect to somebody (i.e., we are in SYN_SENT). */
512         if (pcb->state != SYN_SENT) {
513           pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx];
514         }
515         /* Reduce congestion window and ssthresh. */
516         eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
517         pcb->ssthresh = eff_wnd >> 1;
518         if (pcb->ssthresh < pcb->mss) {
519           pcb->ssthresh = pcb->mss * 2;
520         }
521         pcb->cwnd = pcb->mss;
522         LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"U16_F" ssthresh %"U16_F"\n",
523                                 pcb->cwnd, pcb->ssthresh));
524  
525         /* The following needs to be called AFTER cwnd is set to one mss - STJ */
526         tcp_rexmit_rto(pcb);
527      }
528     }
529     /* Check if this PCB has stayed too long in FIN-WAIT-2 */
530     if (pcb->state == FIN_WAIT_2) {
531       if ((u32_t)(tcp_ticks - pcb->tmr) >
532         TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
533         ++pcb_remove;
534         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
535       }
536     }
537
538    /* Check if KEEPALIVE should be sent */
539    if((pcb->so_options & SOF_KEEPALIVE) && ((pcb->state == ESTABLISHED) || (pcb->state == CLOSE_WAIT))) {
540       if((u32_t)(tcp_ticks - pcb->tmr) > (pcb->keepalive + TCP_MAXIDLE) / TCP_SLOW_INTERVAL)  {
541          LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to %"U16_F".%"U16_F".%"U16_F".%"U16_F".\n",
542                                  ip4_addr1(&pcb->remote_ip), ip4_addr2(&pcb->remote_ip),
543                                  ip4_addr3(&pcb->remote_ip), ip4_addr4(&pcb->remote_ip)));
544
545          tcp_abort(pcb);
546       }
547       else if((u32_t)(tcp_ticks - pcb->tmr) > (pcb->keepalive + pcb->keep_cnt * TCP_KEEPINTVL) / TCP_SLOW_INTERVAL) {
548          tcp_keepalive(pcb);
549          pcb->keep_cnt++;
550       }
551    }
552
553     /* If this PCB has queued out of sequence data, but has been
554        inactive for too long, will drop the data (it will eventually
555        be retransmitted). */
556 #if TCP_QUEUE_OOSEQ    
557     if (pcb->ooseq != NULL &&
558        (u32_t)tcp_ticks - pcb->tmr >=
559        pcb->rto * TCP_OOSEQ_TIMEOUT) {
560       tcp_segs_free(pcb->ooseq);
561       pcb->ooseq = NULL;
562       LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
563     }
564 #endif /* TCP_QUEUE_OOSEQ */
565
566     /* Check if this PCB has stayed too long in SYN-RCVD */
567     if (pcb->state == SYN_RCVD) {
568       if ((u32_t)(tcp_ticks - pcb->tmr) >
569         TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
570         ++pcb_remove;
571         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
572       }
573     }
574
575     /* Check if this PCB has stayed too long in LAST-ACK */
576     if (pcb->state == LAST_ACK) {
577       if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
578         ++pcb_remove;
579         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
580       }
581     }
582
583     /* If the PCB should be removed, do it. */
584     if (pcb_remove) {
585       tcp_pcb_purge(pcb);      
586       /* Remove PCB from tcp_active_pcbs list. */
587       if (prev != NULL) {
588   LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
589         prev->next = pcb->next;
590       } else {
591         /* This PCB was the first. */
592         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
593         tcp_active_pcbs = pcb->next;
594       }
595
596       TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_ABRT);
597
598       pcb2 = pcb->next;
599       memp_free(MEMP_TCP_PCB, pcb);
600       pcb = pcb2;
601     } else {
602
603       /* We check if we should poll the connection. */
604       ++pcb->polltmr;
605       if (pcb->polltmr >= pcb->pollinterval) {
606         pcb->polltmr = 0;
607         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
608         TCP_EVENT_POLL(pcb, err);
609         if (err == ERR_OK) {
610           tcp_output(pcb);
611         }
612       }
613       
614       prev = pcb;
615       pcb = pcb->next;
616     }
617   }
618
619   
620   /* Steps through all of the TIME-WAIT PCBs. */
621   prev = NULL;    
622   pcb = tcp_tw_pcbs;
623   while (pcb != NULL) {
624     LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
625     pcb_remove = 0;
626
627     /* Check if this PCB has stayed long enough in TIME-WAIT */
628     if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
629       ++pcb_remove;
630     }
631     
632
633
634     /* If the PCB should be removed, do it. */
635     if (pcb_remove) {
636       tcp_pcb_purge(pcb);      
637       /* Remove PCB from tcp_tw_pcbs list. */
638       if (prev != NULL) {
639   LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
640         prev->next = pcb->next;
641       } else {
642         /* This PCB was the first. */
643         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
644         tcp_tw_pcbs = pcb->next;
645       }
646       pcb2 = pcb->next;
647       memp_free(MEMP_TCP_PCB, pcb);
648       pcb = pcb2;
649     } else {
650       prev = pcb;
651       pcb = pcb->next;
652     }
653   }
654 }
655
656 /**
657  * Is called every TCP_FAST_INTERVAL (250 ms) and sends delayed ACKs.
658  */
659 void
660 tcp_fasttmr(void)
661 {
662   struct tcp_pcb *pcb;
663
664   /* send delayed ACKs */  
665   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
666     if (pcb->flags & TF_ACK_DELAY) {
667       LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
668       tcp_ack_now(pcb);
669       pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
670     }
671   }
672 }
673
674 /**
675  * Deallocates a list of TCP segments (tcp_seg structures).
676  *
677  */
678 u8_t
679 tcp_segs_free(struct tcp_seg *seg)
680 {
681   u8_t count = 0;
682   struct tcp_seg *next;
683   while (seg != NULL) {
684     next = seg->next;
685     count += tcp_seg_free(seg);
686     seg = next;
687   }
688   return count;
689 }
690
691 /**
692  * Frees a TCP segment.
693  *
694  */
695 u8_t
696 tcp_seg_free(struct tcp_seg *seg)
697 {
698   u8_t count = 0;
699   
700   if (seg != NULL) {
701     if (seg->p != NULL) {
702       count = pbuf_free(seg->p);
703 #if TCP_DEBUG
704       seg->p = NULL;
705 #endif /* TCP_DEBUG */
706     }
707     memp_free(MEMP_TCP_SEG, seg);
708   }
709   return count;
710 }
711
712 /**
713  * Sets the priority of a connection.
714  *
715  */
716 void
717 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
718 {
719   pcb->prio = prio;
720 }
721 #if TCP_QUEUE_OOSEQ
722
723 /**
724  * Returns a copy of the given TCP segment.
725  *
726  */ 
727 struct tcp_seg *
728 tcp_seg_copy(struct tcp_seg *seg)
729 {
730   struct tcp_seg *cseg;
731
732   cseg = memp_malloc(MEMP_TCP_SEG);
733   if (cseg == NULL) {
734     return NULL;
735   }
736   memcpy((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg)); 
737   pbuf_ref(cseg->p);
738   return cseg;
739 }
740 #endif
741
742 #if LWIP_CALLBACK_API
743 static err_t
744 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
745 {
746   arg = arg;
747   if (p != NULL) {
748     pbuf_free(p);
749   } else if (err == ERR_OK) {
750     return tcp_close(pcb);
751   }
752   return ERR_OK;
753 }
754 #endif /* LWIP_CALLBACK_API */
755
756 static void
757 tcp_kill_prio(u8_t prio)
758 {
759   struct tcp_pcb *pcb, *inactive;
760   u32_t inactivity;
761   u8_t mprio;
762
763
764   mprio = TCP_PRIO_MAX;
765   
766   /* We kill the oldest active connection that has lower priority than
767      prio. */
768   inactivity = 0;
769   inactive = NULL;
770   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
771     if (pcb->prio <= prio &&
772        pcb->prio <= mprio &&
773        (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
774       inactivity = tcp_ticks - pcb->tmr;
775       inactive = pcb;
776       mprio = pcb->prio;
777     }
778   }
779   if (inactive != NULL) {
780     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
781            (void *)inactive, inactivity));
782     tcp_abort(inactive);
783   }      
784 }
785
786
787 static void
788 tcp_kill_timewait(void)
789 {
790   struct tcp_pcb *pcb, *inactive;
791   u32_t inactivity;
792
793   inactivity = 0;
794   inactive = NULL;
795   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
796     if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
797       inactivity = tcp_ticks - pcb->tmr;
798       inactive = pcb;
799     }
800   }
801   if (inactive != NULL) {
802     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
803            (void *)inactive, inactivity));
804     tcp_abort(inactive);
805   }      
806 }
807
808
809
810 struct tcp_pcb *
811 tcp_alloc(u8_t prio)
812 {
813   struct tcp_pcb *pcb;
814   u32_t iss;
815   
816   pcb = memp_malloc(MEMP_TCP_PCB);
817   if (pcb == NULL) {
818     /* Try killing oldest connection in TIME-WAIT. */
819     LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
820     tcp_kill_timewait();
821     pcb = memp_malloc(MEMP_TCP_PCB);
822     if (pcb == NULL) {
823       tcp_kill_prio(prio);    
824       pcb = memp_malloc(MEMP_TCP_PCB);
825     }
826   }
827   if (pcb != NULL) {
828     memset(pcb, 0, sizeof(struct tcp_pcb));
829     pcb->prio = TCP_PRIO_NORMAL;
830     pcb->snd_buf = TCP_SND_BUF;
831     pcb->snd_queuelen = 0;
832     pcb->rcv_wnd = TCP_WND;
833     pcb->tos = 0;
834     pcb->ttl = TCP_TTL;
835     pcb->mss = TCP_MSS;
836     pcb->rto = 3000 / TCP_SLOW_INTERVAL;
837     pcb->sa = 0;
838     pcb->sv = 3000 / TCP_SLOW_INTERVAL;
839     pcb->rtime = 0;
840     pcb->cwnd = 1;
841     iss = tcp_next_iss();
842     pcb->snd_wl2 = iss;
843     pcb->snd_nxt = iss;
844     pcb->snd_max = iss;
845     pcb->lastack = iss;
846     pcb->snd_lbb = iss;   
847     pcb->tmr = tcp_ticks;
848
849     pcb->polltmr = 0;
850
851 #if LWIP_CALLBACK_API
852     pcb->recv = tcp_recv_null;
853 #endif /* LWIP_CALLBACK_API */  
854     
855     /* Init KEEPALIVE timer */
856     pcb->keepalive = TCP_KEEPDEFAULT;
857     pcb->keep_cnt = 0;
858   }
859   return pcb;
860 }
861
862 /**
863  * Creates a new TCP protocol control block but doesn't place it on
864  * any of the TCP PCB lists.
865  *
866  * @internal: Maybe there should be a idle TCP PCB list where these
867  * PCBs are put on. We can then implement port reservation using
868  * tcp_bind(). Currently, we lack this (BSD socket type of) feature.
869  */
870
871 struct tcp_pcb *
872 tcp_new(void)
873 {
874   return tcp_alloc(TCP_PRIO_NORMAL);
875 }
876
877 /*
878  * tcp_arg():
879  *
880  * Used to specify the argument that should be passed callback
881  * functions.
882  *
883  */ 
884
885 void
886 tcp_arg(struct tcp_pcb *pcb, void *arg)
887 {  
888   pcb->callback_arg = arg;
889 }
890 #if LWIP_CALLBACK_API
891
892 /**
893  * Used to specify the function that should be called when a TCP
894  * connection receives data.
895  *
896  */ 
897 void
898 tcp_recv(struct tcp_pcb *pcb,
899    err_t (* recv)(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err))
900 {
901   pcb->recv = recv;
902 }
903
904 /**
905  * Used to specify the function that should be called when TCP data
906  * has been successfully delivered to the remote host.
907  *
908  */ 
909
910 void
911 tcp_sent(struct tcp_pcb *pcb,
912    err_t (* sent)(void *arg, struct tcp_pcb *tpcb, u16_t len))
913 {
914   pcb->sent = sent;
915 }
916
917 /**
918  * Used to specify the function that should be called when a fatal error
919  * has occured on the connection.
920  *
921  */ 
922 void
923 tcp_err(struct tcp_pcb *pcb,
924    void (* errf)(void *arg, err_t err))
925 {
926   pcb->errf = errf;
927 }
928
929 /**
930  * Used for specifying the function that should be called when a
931  * LISTENing connection has been connected to another host.
932  *
933  */ 
934 void
935 tcp_accept(struct tcp_pcb *pcb,
936      err_t (* accept)(void *arg, struct tcp_pcb *newpcb, err_t err))
937 {
938   ((struct tcp_pcb_listen *)pcb)->accept = accept;
939 }
940 #endif /* LWIP_CALLBACK_API */
941
942
943 /**
944  * Used to specify the function that should be called periodically
945  * from TCP. The interval is specified in terms of the TCP coarse
946  * timer interval, which is called twice a second.
947  *
948  */ 
949 void
950 tcp_poll(struct tcp_pcb *pcb,
951    err_t (* poll)(void *arg, struct tcp_pcb *tpcb), u8_t interval)
952 {
953 #if LWIP_CALLBACK_API
954   pcb->poll = poll;
955 #endif /* LWIP_CALLBACK_API */  
956   pcb->pollinterval = interval;
957 }
958
959 /**
960  * Purges a TCP PCB. Removes any buffered data and frees the buffer memory.
961  *
962  */
963 void
964 tcp_pcb_purge(struct tcp_pcb *pcb)
965 {
966   if (pcb->state != CLOSED &&
967      pcb->state != TIME_WAIT &&
968      pcb->state != LISTEN) {
969
970     LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
971     
972     if (pcb->unsent != NULL) {    
973       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
974     }
975     if (pcb->unacked != NULL) {    
976       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
977     }
978 #if TCP_QUEUE_OOSEQ /* LW */
979     if (pcb->ooseq != NULL) {    
980       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
981     }
982     
983     tcp_segs_free(pcb->ooseq);
984     pcb->ooseq = NULL;
985 #endif /* TCP_QUEUE_OOSEQ */
986     tcp_segs_free(pcb->unsent);
987     tcp_segs_free(pcb->unacked);
988     pcb->unacked = pcb->unsent = NULL;
989   }
990 }
991
992 /**
993  * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
994  *
995  */
996 void
997 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
998 {
999   TCP_RMV(pcblist, pcb);
1000
1001   tcp_pcb_purge(pcb);
1002   
1003   /* if there is an outstanding delayed ACKs, send it */
1004   if (pcb->state != TIME_WAIT &&
1005      pcb->state != LISTEN &&
1006      pcb->flags & TF_ACK_DELAY) {
1007     pcb->flags |= TF_ACK_NOW;
1008     tcp_output(pcb);
1009   }  
1010   pcb->state = CLOSED;
1011
1012   LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
1013 }
1014
1015 /**
1016  * Calculates a new initial sequence number for new connections.
1017  *
1018  */
1019 u32_t
1020 tcp_next_iss(void)
1021 {
1022   static u32_t iss = 6510;
1023   
1024   iss += tcp_ticks;       /* XXX */
1025   return iss;
1026 }
1027
1028 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
1029 void
1030 tcp_debug_print(struct tcp_hdr *tcphdr)
1031 {
1032   LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
1033   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1034   LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
1035          ntohs(tcphdr->src), ntohs(tcphdr->dest)));
1036   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1037   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
1038           ntohl(tcphdr->seqno)));
1039   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1040   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
1041          ntohl(tcphdr->ackno)));
1042   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1043   LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
1044        TCPH_HDRLEN(tcphdr),
1045          TCPH_FLAGS(tcphdr) >> 5 & 1,
1046          TCPH_FLAGS(tcphdr) >> 4 & 1,
1047          TCPH_FLAGS(tcphdr) >> 3 & 1,
1048          TCPH_FLAGS(tcphdr) >> 2 & 1,
1049          TCPH_FLAGS(tcphdr) >> 1 & 1,
1050          TCPH_FLAGS(tcphdr) & 1,
1051          ntohs(tcphdr->wnd)));
1052   tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
1053   LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
1054   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1055   LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
1056          ntohs(tcphdr->chksum), ntohs(tcphdr->urgp)));
1057   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1058 }
1059
1060 void
1061 tcp_debug_print_state(enum tcp_state s)
1062 {
1063   LWIP_DEBUGF(TCP_DEBUG, ("State: "));
1064   switch (s) {
1065   case CLOSED:
1066     LWIP_DEBUGF(TCP_DEBUG, ("CLOSED\n"));
1067     break;
1068  case LISTEN:
1069    LWIP_DEBUGF(TCP_DEBUG, ("LISTEN\n"));
1070    break;
1071   case SYN_SENT:
1072     LWIP_DEBUGF(TCP_DEBUG, ("SYN_SENT\n"));
1073     break;
1074   case SYN_RCVD:
1075     LWIP_DEBUGF(TCP_DEBUG, ("SYN_RCVD\n"));
1076     break;
1077   case ESTABLISHED:
1078     LWIP_DEBUGF(TCP_DEBUG, ("ESTABLISHED\n"));
1079     break;
1080   case FIN_WAIT_1:
1081     LWIP_DEBUGF(TCP_DEBUG, ("FIN_WAIT_1\n"));
1082     break;
1083   case FIN_WAIT_2:
1084     LWIP_DEBUGF(TCP_DEBUG, ("FIN_WAIT_2\n"));
1085     break;
1086   case CLOSE_WAIT:
1087     LWIP_DEBUGF(TCP_DEBUG, ("CLOSE_WAIT\n"));
1088     break;
1089   case CLOSING:
1090     LWIP_DEBUGF(TCP_DEBUG, ("CLOSING\n"));
1091     break;
1092   case LAST_ACK:
1093     LWIP_DEBUGF(TCP_DEBUG, ("LAST_ACK\n"));
1094     break;
1095   case TIME_WAIT:
1096     LWIP_DEBUGF(TCP_DEBUG, ("TIME_WAIT\n"));
1097    break;
1098   }
1099 }
1100
1101 void
1102 tcp_debug_print_flags(u8_t flags)
1103 {
1104   if (flags & TCP_FIN) {
1105     LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
1106   }
1107   if (flags & TCP_SYN) {
1108     LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
1109   }
1110   if (flags & TCP_RST) {
1111     LWIP_DEBUGF(TCP_DEBUG, ("RST "));
1112   }
1113   if (flags & TCP_PSH) {
1114     LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
1115   }
1116   if (flags & TCP_ACK) {
1117     LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
1118   }
1119   if (flags & TCP_URG) {
1120     LWIP_DEBUGF(TCP_DEBUG, ("URG "));
1121   }
1122   if (flags & TCP_ECE) {
1123     LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
1124   }
1125   if (flags & TCP_CWR) {
1126     LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
1127   }
1128 }
1129
1130 void
1131 tcp_debug_print_pcbs(void)
1132 {
1133   struct tcp_pcb *pcb;
1134   LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
1135   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1136     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1137                        pcb->local_port, pcb->remote_port,
1138                        pcb->snd_nxt, pcb->rcv_nxt));
1139     tcp_debug_print_state(pcb->state);
1140   }    
1141   LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
1142   for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
1143     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1144                        pcb->local_port, pcb->remote_port,
1145                        pcb->snd_nxt, pcb->rcv_nxt));
1146     tcp_debug_print_state(pcb->state);
1147   }    
1148   LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
1149   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1150     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1151                        pcb->local_port, pcb->remote_port,
1152                        pcb->snd_nxt, pcb->rcv_nxt));
1153     tcp_debug_print_state(pcb->state);
1154   }    
1155 }
1156
1157 s16_t
1158 tcp_pcbs_sane(void)
1159 {
1160   struct tcp_pcb *pcb;
1161   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1162     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
1163     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
1164     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
1165   }
1166   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1167     LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1168   }
1169   return 1;
1170 }
1171 #endif /* TCP_DEBUG */
1172 #endif /* LWIP_TCP */
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182