Linux Kernel Architecture

(Jacob Rumans) #1

Chapter 12: Networks


ConnectionTermination


Like connection setup, shutdown of TCP connections is also brought about by a multistage exchange of
packets, as shown in Figure 12-25. A connection can be closed in one of two ways:


  1. Agraceful closeterminates the connection at the explicit request of one of the participating
    systems (in rare cases, both systems issue a request at the same time).

  2. Termination orabortcan be brought about by a higher protocol (because, e.g., programs have
    crashed).


Fortunately, since the first situation is by far the more usual, we discuss it and ignore the second.

TCP partners must exchangefourpackets to close a connection gracefully. The sequence of steps is
described below.


  1. The standard library functioncloseis invoked in computer A to send a TCP packet whose
    FIN flag is set in the header. The socket of A switches to the FIN_WAIT_1 state.

  2. B receives the FIN packet and returns an ACK packet. Its socket state changes from ESTAB-
    LISHED to CLOSE_WAIT. The socket is informed of receipt of the FIN by means of an ‘‘end
    of file.’’

  3. After receipt of the ACK packet, the socket state of computer A changes from FIN_WAIT_1
    to FIN_WAIT_2.

  4. The application associated with the socket on computer B also executescloseto
    send a FIN segment from B to A. The state of the socket of computer B then changes
    toLAST_ACK.

  5. Computer A confirms receipt of the FIN with an ACK packet and first goes into the
    TIME_WAIT state before automatically switching to the CLOSED state after a certain
    period.

  6. Computer B receives the ACK packet, which causes its socket also to switch to the CLOSED
    state.


The status transitions are performed in the central dispatcher function (tcp_rcv_state_process), in the
path for existing connections (tcp_rcv_established), and in thetcp_closefunction not yet discussed.

The latter is invoked when the user process decides to call thecloselibrary function to close a connection.
If the state of the socket is LISTEN (i.e., there is no connection to another computer), the approach is
simpler because no external parties need be informed of the end of the connection. This situation is
checked at the beginning of the procedure, and, if it applies, the response is a change of socket state to
CLOSED.

If not,tcp_send_finsends a FIN packet to the other party once the socket state has been set to
FIN_WAIT_1 by thetcp_close_stateandtcp_set_statecall chain.^33

(^33) The approach is not fully compatible with the TCP standard because the socket is not actually allowed to change its state until
afterthe FIN packet has been sent. However, the Linux alternative is simpler to implement and does not give rise to any problems
in practice. This is why kernel developers have gone down this path as noted in a comment to this effect intcp_close.

Free download pdf