Skip to content
Snippets Groups Projects
tcp.c 63.2 KiB
Newer Older
  • Learn to ignore specific revisions
  • Linus Torvalds's avatar
    Linus Torvalds committed
    1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
    	err = sk_stream_error(sk, flags, err);
    	TCP_CHECK_TIMER(sk);
    	release_sock(sk);
    	return err;
    }
    
    /*
     *	Handle reading urgent data. BSD has very simple semantics for
     *	this, no blocking and very strange errors 8)
     */
    
    static int tcp_recv_urg(struct sock *sk, long timeo,
    			struct msghdr *msg, int len, int flags,
    			int *addr_len)
    {
    	struct tcp_sock *tp = tcp_sk(sk);
    
    	/* No URG data to read. */
    	if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
    	    tp->urg_data == TCP_URG_READ)
    		return -EINVAL;	/* Yes this is right ! */
    
    	if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
    		return -ENOTCONN;
    
    	if (tp->urg_data & TCP_URG_VALID) {
    		int err = 0;
    		char c = tp->urg_data;
    
    		if (!(flags & MSG_PEEK))
    			tp->urg_data = TCP_URG_READ;
    
    		/* Read urgent data. */
    		msg->msg_flags |= MSG_OOB;
    
    		if (len > 0) {
    			if (!(flags & MSG_TRUNC))
    				err = memcpy_toiovec(msg->msg_iov, &c, 1);
    			len = 1;
    		} else
    			msg->msg_flags |= MSG_TRUNC;
    
    		return err ? -EFAULT : len;
    	}
    
    	if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
    		return 0;
    
    	/* Fixed the recv(..., MSG_OOB) behaviour.  BSD docs and
    	 * the available implementations agree in this case:
    	 * this call should never block, independent of the
    	 * blocking state of the socket.
    	 * Mike <pall@rz.uni-karlsruhe.de>
    	 */
    	return -EAGAIN;
    }
    
    /* Clean up the receive buffer for full frames taken by the user,
     * then send an ACK if necessary.  COPIED is the number of bytes
     * tcp_recvmsg has given to the user so far, it speeds up the
     * calculation of whether or not we must ACK for the sake of
     * a window update.
     */
    static void cleanup_rbuf(struct sock *sk, int copied)
    {
    	struct tcp_sock *tp = tcp_sk(sk);
    	int time_to_ack = 0;
    
    #if TCP_DEBUG
    	struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
    
    	BUG_TRAP(!skb || before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq));
    #endif
    
    	if (tcp_ack_scheduled(tp)) {
    		   /* Delayed ACKs frequently hit locked sockets during bulk
    		    * receive. */
    		if (tp->ack.blocked ||
    		    /* Once-per-two-segments ACK was not sent by tcp_input.c */
    		    tp->rcv_nxt - tp->rcv_wup > tp->ack.rcv_mss ||
    		    /*
    		     * If this read emptied read buffer, we send ACK, if
    		     * connection is not bidirectional, user drained
    		     * receive buffer and there was a small segment
    		     * in queue.
    		     */
    		    (copied > 0 && (tp->ack.pending & TCP_ACK_PUSHED) &&
    		     !tp->ack.pingpong && !atomic_read(&sk->sk_rmem_alloc)))
    			time_to_ack = 1;
    	}
    
    	/* We send an ACK if we can now advertise a non-zero window
    	 * which has been raised "significantly".
    	 *
    	 * Even if window raised up to infinity, do not send window open ACK
    	 * in states, where we will not receive more. It is useless.
    	 */
    	if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
    		__u32 rcv_window_now = tcp_receive_window(tp);
    
    		/* Optimize, __tcp_select_window() is not cheap. */
    		if (2*rcv_window_now <= tp->window_clamp) {
    			__u32 new_window = __tcp_select_window(sk);
    
    			/* Send ACK now, if this read freed lots of space
    			 * in our buffer. Certainly, new_window is new window.
    			 * We can advertise it now, if it is not less than current one.
    			 * "Lots" means "at least twice" here.
    			 */
    			if (new_window && new_window >= 2 * rcv_window_now)
    				time_to_ack = 1;
    		}
    	}
    	if (time_to_ack)
    		tcp_send_ack(sk);
    }
    
    static void tcp_prequeue_process(struct sock *sk)
    {
    	struct sk_buff *skb;
    	struct tcp_sock *tp = tcp_sk(sk);
    
    	NET_ADD_STATS_USER(LINUX_MIB_TCPPREQUEUED, skb_queue_len(&tp->ucopy.prequeue));
    
    	/* RX process wants to run with disabled BHs, though it is not
    	 * necessary */
    	local_bh_disable();
    	while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL)
    		sk->sk_backlog_rcv(sk, skb);
    	local_bh_enable();
    
    	/* Clear memory counter. */
    	tp->ucopy.memory = 0;
    }
    
    static inline struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
    {
    	struct sk_buff *skb;
    	u32 offset;
    
    	skb_queue_walk(&sk->sk_receive_queue, skb) {
    		offset = seq - TCP_SKB_CB(skb)->seq;
    		if (skb->h.th->syn)
    			offset--;
    		if (offset < skb->len || skb->h.th->fin) {
    			*off = offset;
    			return skb;
    		}
    	}
    	return NULL;
    }
    
    /*
     * This routine provides an alternative to tcp_recvmsg() for routines
     * that would like to handle copying from skbuffs directly in 'sendfile'
     * fashion.
     * Note:
     *	- It is assumed that the socket was locked by the caller.
     *	- The routine does not block.
     *	- At present, there is no support for reading OOB data
     *	  or for 'peeking' the socket using this routine
     *	  (although both would be easy to implement).
     */
    int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
    		  sk_read_actor_t recv_actor)
    {
    	struct sk_buff *skb;
    	struct tcp_sock *tp = tcp_sk(sk);
    	u32 seq = tp->copied_seq;
    	u32 offset;
    	int copied = 0;
    
    	if (sk->sk_state == TCP_LISTEN)
    		return -ENOTCONN;
    	while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
    		if (offset < skb->len) {
    			size_t used, len;
    
    			len = skb->len - offset;
    			/* Stop reading if we hit a patch of urgent data */
    			if (tp->urg_data) {
    				u32 urg_offset = tp->urg_seq - seq;
    				if (urg_offset < len)
    					len = urg_offset;
    				if (!len)
    					break;
    			}
    			used = recv_actor(desc, skb, offset, len);
    			if (used <= len) {
    				seq += used;
    				copied += used;
    				offset += used;
    			}
    			if (offset != skb->len)
    				break;
    		}
    		if (skb->h.th->fin) {
    			sk_eat_skb(sk, skb);
    			++seq;
    			break;
    		}
    		sk_eat_skb(sk, skb);
    		if (!desc->count)
    			break;
    	}
    	tp->copied_seq = seq;
    
    	tcp_rcv_space_adjust(sk);
    
    	/* Clean up data we have read: This will do ACK frames. */
    	if (copied)
    		cleanup_rbuf(sk, copied);
    	return copied;
    }
    
    /*
     *	This routine copies from a sock struct into the user buffer.
     *
     *	Technical note: in 2.3 we work on _locked_ socket, so that
     *	tricks with *seq access order and skb->users are not required.
     *	Probably, code can be easily improved even more.
     */
    
    int tcp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
    		size_t len, int nonblock, int flags, int *addr_len)
    {
    	struct tcp_sock *tp = tcp_sk(sk);
    	int copied = 0;
    	u32 peek_seq;
    	u32 *seq;
    	unsigned long used;
    	int err;
    	int target;		/* Read at least this many bytes */
    	long timeo;
    	struct task_struct *user_recv = NULL;
    
    	lock_sock(sk);
    
    	TCP_CHECK_TIMER(sk);
    
    	err = -ENOTCONN;
    	if (sk->sk_state == TCP_LISTEN)
    		goto out;
    
    	timeo = sock_rcvtimeo(sk, nonblock);
    
    	/* Urgent data needs to be handled specially. */
    	if (flags & MSG_OOB)
    		goto recv_urg;
    
    	seq = &tp->copied_seq;
    	if (flags & MSG_PEEK) {
    		peek_seq = tp->copied_seq;
    		seq = &peek_seq;
    	}
    
    	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
    
    	do {
    		struct sk_buff *skb;
    		u32 offset;
    
    		/* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
    		if (tp->urg_data && tp->urg_seq == *seq) {
    			if (copied)
    				break;
    			if (signal_pending(current)) {
    				copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
    				break;
    			}
    		}
    
    		/* Next get a buffer. */
    
    		skb = skb_peek(&sk->sk_receive_queue);
    		do {
    			if (!skb)
    				break;
    
    			/* Now that we have two receive queues this
    			 * shouldn't happen.
    			 */
    			if (before(*seq, TCP_SKB_CB(skb)->seq)) {
    				printk(KERN_INFO "recvmsg bug: copied %X "
    				       "seq %X\n", *seq, TCP_SKB_CB(skb)->seq);
    				break;
    			}
    			offset = *seq - TCP_SKB_CB(skb)->seq;
    			if (skb->h.th->syn)
    				offset--;
    			if (offset < skb->len)
    				goto found_ok_skb;
    			if (skb->h.th->fin)
    				goto found_fin_ok;
    			BUG_TRAP(flags & MSG_PEEK);
    			skb = skb->next;
    		} while (skb != (struct sk_buff *)&sk->sk_receive_queue);
    
    		/* Well, if we have backlog, try to process it now yet. */
    
    		if (copied >= target && !sk->sk_backlog.tail)
    			break;
    
    		if (copied) {
    			if (sk->sk_err ||
    			    sk->sk_state == TCP_CLOSE ||
    			    (sk->sk_shutdown & RCV_SHUTDOWN) ||
    			    !timeo ||
    			    signal_pending(current) ||
    			    (flags & MSG_PEEK))
    				break;
    		} else {
    			if (sock_flag(sk, SOCK_DONE))
    				break;
    
    			if (sk->sk_err) {
    				copied = sock_error(sk);
    				break;
    			}
    
    			if (sk->sk_shutdown & RCV_SHUTDOWN)
    				break;
    
    			if (sk->sk_state == TCP_CLOSE) {
    				if (!sock_flag(sk, SOCK_DONE)) {
    					/* This occurs when user tries to read
    					 * from never connected socket.
    					 */
    					copied = -ENOTCONN;
    					break;
    				}
    				break;
    			}
    
    			if (!timeo) {
    				copied = -EAGAIN;
    				break;
    			}
    
    			if (signal_pending(current)) {
    				copied = sock_intr_errno(timeo);
    				break;
    			}
    		}
    
    		cleanup_rbuf(sk, copied);
    
    		if (tp->ucopy.task == user_recv) {
    			/* Install new reader */
    			if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) {
    				user_recv = current;
    				tp->ucopy.task = user_recv;
    				tp->ucopy.iov = msg->msg_iov;
    			}
    
    			tp->ucopy.len = len;
    
    			BUG_TRAP(tp->copied_seq == tp->rcv_nxt ||
    				 (flags & (MSG_PEEK | MSG_TRUNC)));
    
    			/* Ugly... If prequeue is not empty, we have to
    			 * process it before releasing socket, otherwise
    			 * order will be broken at second iteration.
    			 * More elegant solution is required!!!
    			 *
    			 * Look: we have the following (pseudo)queues:
    			 *
    			 * 1. packets in flight
    			 * 2. backlog
    			 * 3. prequeue
    			 * 4. receive_queue
    			 *
    			 * Each queue can be processed only if the next ones
    			 * are empty. At this point we have empty receive_queue.
    			 * But prequeue _can_ be not empty after 2nd iteration,
    			 * when we jumped to start of loop because backlog
    			 * processing added something to receive_queue.
    			 * We cannot release_sock(), because backlog contains
    			 * packets arrived _after_ prequeued ones.
    			 *
    			 * Shortly, algorithm is clear --- to process all
    			 * the queues in order. We could make it more directly,
    			 * requeueing packets from backlog to prequeue, if
    			 * is not empty. It is more elegant, but eats cycles,
    			 * unfortunately.
    			 */
    			if (skb_queue_len(&tp->ucopy.prequeue))
    				goto do_prequeue;
    
    			/* __ Set realtime policy in scheduler __ */
    		}
    
    		if (copied >= target) {
    			/* Do not sleep, just process backlog. */
    			release_sock(sk);
    			lock_sock(sk);
    		} else
    			sk_wait_data(sk, &timeo);
    
    		if (user_recv) {
    			int chunk;
    
    			/* __ Restore normal policy in scheduler __ */
    
    			if ((chunk = len - tp->ucopy.len) != 0) {
    				NET_ADD_STATS_USER(LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk);
    				len -= chunk;
    				copied += chunk;
    			}
    
    			if (tp->rcv_nxt == tp->copied_seq &&
    			    skb_queue_len(&tp->ucopy.prequeue)) {
    do_prequeue:
    				tcp_prequeue_process(sk);
    
    				if ((chunk = len - tp->ucopy.len) != 0) {
    					NET_ADD_STATS_USER(LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
    					len -= chunk;
    					copied += chunk;
    				}
    			}
    		}
    		if ((flags & MSG_PEEK) && peek_seq != tp->copied_seq) {
    			if (net_ratelimit())
    				printk(KERN_DEBUG "TCP(%s:%d): Application bug, race in MSG_PEEK.\n",
    				       current->comm, current->pid);
    			peek_seq = tp->copied_seq;
    		}
    		continue;
    
    	found_ok_skb:
    		/* Ok so how much can we use? */
    		used = skb->len - offset;
    		if (len < used)
    			used = len;
    
    		/* Do we have urgent data here? */
    		if (tp->urg_data) {
    			u32 urg_offset = tp->urg_seq - *seq;
    			if (urg_offset < used) {
    				if (!urg_offset) {
    					if (!sock_flag(sk, SOCK_URGINLINE)) {
    						++*seq;
    						offset++;
    						used--;
    						if (!used)
    							goto skip_copy;
    					}
    				} else
    					used = urg_offset;
    			}
    		}
    
    		if (!(flags & MSG_TRUNC)) {
    			err = skb_copy_datagram_iovec(skb, offset,
    						      msg->msg_iov, used);
    			if (err) {
    				/* Exception. Bailout! */
    				if (!copied)
    					copied = -EFAULT;
    				break;
    			}
    		}
    
    		*seq += used;
    		copied += used;
    		len -= used;
    
    		tcp_rcv_space_adjust(sk);
    
    skip_copy:
    		if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
    			tp->urg_data = 0;
    			tcp_fast_path_check(sk, tp);
    		}
    		if (used + offset < skb->len)
    			continue;
    
    		if (skb->h.th->fin)
    			goto found_fin_ok;
    		if (!(flags & MSG_PEEK))
    			sk_eat_skb(sk, skb);
    		continue;
    
    	found_fin_ok:
    		/* Process the FIN. */
    		++*seq;
    		if (!(flags & MSG_PEEK))
    			sk_eat_skb(sk, skb);
    		break;
    	} while (len > 0);
    
    	if (user_recv) {
    		if (skb_queue_len(&tp->ucopy.prequeue)) {
    			int chunk;
    
    			tp->ucopy.len = copied > 0 ? len : 0;
    
    			tcp_prequeue_process(sk);
    
    			if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) {
    				NET_ADD_STATS_USER(LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
    				len -= chunk;
    				copied += chunk;
    			}
    		}
    
    		tp->ucopy.task = NULL;
    		tp->ucopy.len = 0;
    	}
    
    	/* According to UNIX98, msg_name/msg_namelen are ignored
    	 * on connected socket. I was just happy when found this 8) --ANK
    	 */
    
    	/* Clean up data we have read: This will do ACK frames. */
    	cleanup_rbuf(sk, copied);
    
    	TCP_CHECK_TIMER(sk);
    	release_sock(sk);
    	return copied;
    
    out:
    	TCP_CHECK_TIMER(sk);
    	release_sock(sk);
    	return err;
    
    recv_urg:
    	err = tcp_recv_urg(sk, timeo, msg, len, flags, addr_len);
    	goto out;
    }
    
    /*
     *	State processing on a close. This implements the state shift for
     *	sending our FIN frame. Note that we only send a FIN for some
     *	states. A shutdown() may have already sent the FIN, or we may be
     *	closed.
     */
    
    static unsigned char new_state[16] = {
      /* current state:        new state:      action:	*/
      /* (Invalid)		*/ TCP_CLOSE,
      /* TCP_ESTABLISHED	*/ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
      /* TCP_SYN_SENT	*/ TCP_CLOSE,
      /* TCP_SYN_RECV	*/ TCP_FIN_WAIT1 | TCP_ACTION_FIN,
      /* TCP_FIN_WAIT1	*/ TCP_FIN_WAIT1,
      /* TCP_FIN_WAIT2	*/ TCP_FIN_WAIT2,
      /* TCP_TIME_WAIT	*/ TCP_CLOSE,
      /* TCP_CLOSE		*/ TCP_CLOSE,
      /* TCP_CLOSE_WAIT	*/ TCP_LAST_ACK  | TCP_ACTION_FIN,
      /* TCP_LAST_ACK	*/ TCP_LAST_ACK,
      /* TCP_LISTEN		*/ TCP_CLOSE,
      /* TCP_CLOSING	*/ TCP_CLOSING,
    };
    
    static int tcp_close_state(struct sock *sk)
    {
    	int next = (int)new_state[sk->sk_state];
    	int ns = next & TCP_STATE_MASK;
    
    	tcp_set_state(sk, ns);
    
    	return next & TCP_ACTION_FIN;
    }
    
    /*
     *	Shutdown the sending side of a connection. Much like close except
     *	that we don't receive shut down or set_sock_flag(sk, SOCK_DEAD).
     */
    
    void tcp_shutdown(struct sock *sk, int how)
    {
    	/*	We need to grab some memory, and put together a FIN,
    	 *	and then put it into the queue to be sent.
    	 *		Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
    	 */
    	if (!(how & SEND_SHUTDOWN))
    		return;
    
    	/* If we've already sent a FIN, or it's a closed state, skip this. */
    	if ((1 << sk->sk_state) &
    	    (TCPF_ESTABLISHED | TCPF_SYN_SENT |
    	     TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
    		/* Clear out any half completed packets.  FIN if needed. */
    		if (tcp_close_state(sk))
    			tcp_send_fin(sk);
    	}
    }
    
    /*
     * At this point, there should be no process reference to this
     * socket, and thus no user references at all.  Therefore we
     * can assume the socket waitqueue is inactive and nobody will
     * try to jump onto it.
     */
    void tcp_destroy_sock(struct sock *sk)
    {
    	BUG_TRAP(sk->sk_state == TCP_CLOSE);
    	BUG_TRAP(sock_flag(sk, SOCK_DEAD));
    
    	/* It cannot be in hash table! */
    	BUG_TRAP(sk_unhashed(sk));
    
    	/* If it has not 0 inet_sk(sk)->num, it must be bound */
    	BUG_TRAP(!inet_sk(sk)->num || tcp_sk(sk)->bind_hash);
    
    	sk->sk_prot->destroy(sk);
    
    	sk_stream_kill_queues(sk);
    
    	xfrm_sk_free_policy(sk);
    
    #ifdef INET_REFCNT_DEBUG
    	if (atomic_read(&sk->sk_refcnt) != 1) {
    		printk(KERN_DEBUG "Destruction TCP %p delayed, c=%d\n",
    		       sk, atomic_read(&sk->sk_refcnt));
    	}
    #endif
    
    	atomic_dec(&tcp_orphan_count);
    	sock_put(sk);
    }
    
    void tcp_close(struct sock *sk, long timeout)
    {
    	struct sk_buff *skb;
    	int data_was_unread = 0;
    
    	lock_sock(sk);
    	sk->sk_shutdown = SHUTDOWN_MASK;
    
    	if (sk->sk_state == TCP_LISTEN) {
    		tcp_set_state(sk, TCP_CLOSE);
    
    		/* Special case. */
    		tcp_listen_stop(sk);
    
    		goto adjudge_to_death;
    	}
    
    	/*  We need to flush the recv. buffs.  We do this only on the
    	 *  descriptor close, not protocol-sourced closes, because the
    	 *  reader process may not have drained the data yet!
    	 */
    	while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
    		u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq -
    			  skb->h.th->fin;
    		data_was_unread += len;
    		__kfree_skb(skb);
    	}
    
    	sk_stream_mem_reclaim(sk);
    
    	/* As outlined in draft-ietf-tcpimpl-prob-03.txt, section
    	 * 3.10, we send a RST here because data was lost.  To
    	 * witness the awful effects of the old behavior of always
    	 * doing a FIN, run an older 2.1.x kernel or 2.0.x, start
    	 * a bulk GET in an FTP client, suspend the process, wait
    	 * for the client to advertise a zero window, then kill -9
    	 * the FTP client, wheee...  Note: timeout is always zero
    	 * in such a case.
    	 */
    	if (data_was_unread) {
    		/* Unread data was tossed, zap the connection. */
    		NET_INC_STATS_USER(LINUX_MIB_TCPABORTONCLOSE);
    		tcp_set_state(sk, TCP_CLOSE);
    		tcp_send_active_reset(sk, GFP_KERNEL);
    	} else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
    		/* Check zero linger _after_ checking for unread data. */
    		sk->sk_prot->disconnect(sk, 0);
    		NET_INC_STATS_USER(LINUX_MIB_TCPABORTONDATA);
    	} else if (tcp_close_state(sk)) {
    		/* We FIN if the application ate all the data before
    		 * zapping the connection.
    		 */
    
    		/* RED-PEN. Formally speaking, we have broken TCP state
    		 * machine. State transitions:
    		 *
    		 * TCP_ESTABLISHED -> TCP_FIN_WAIT1
    		 * TCP_SYN_RECV	-> TCP_FIN_WAIT1 (forget it, it's impossible)
    		 * TCP_CLOSE_WAIT -> TCP_LAST_ACK
    		 *
    		 * are legal only when FIN has been sent (i.e. in window),
    		 * rather than queued out of window. Purists blame.
    		 *
    		 * F.e. "RFC state" is ESTABLISHED,
    		 * if Linux state is FIN-WAIT-1, but FIN is still not sent.
    		 *
    		 * The visible declinations are that sometimes
    		 * we enter time-wait state, when it is not required really
    		 * (harmless), do not send active resets, when they are
    		 * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
    		 * they look as CLOSING or LAST_ACK for Linux)
    		 * Probably, I missed some more holelets.
    		 * 						--ANK
    		 */
    		tcp_send_fin(sk);
    	}
    
    	sk_stream_wait_close(sk, timeout);
    
    adjudge_to_death:
    	/* It is the last release_sock in its life. It will remove backlog. */
    	release_sock(sk);
    
    
    	/* Now socket is owned by kernel and we acquire BH lock
    	   to finish close. No need to check for user refs.
    	 */
    	local_bh_disable();
    	bh_lock_sock(sk);
    	BUG_TRAP(!sock_owned_by_user(sk));
    
    	sock_hold(sk);
    	sock_orphan(sk);
    
    	/*	This is a (useful) BSD violating of the RFC. There is a
    	 *	problem with TCP as specified in that the other end could
    	 *	keep a socket open forever with no application left this end.
    	 *	We use a 3 minute timeout (about the same as BSD) then kill
    	 *	our end. If they send after that then tough - BUT: long enough
    	 *	that we won't make the old 4*rto = almost no time - whoops
    	 *	reset mistake.
    	 *
    	 *	Nope, it was not mistake. It is really desired behaviour
    	 *	f.e. on http servers, when such sockets are useless, but
    	 *	consume significant resources. Let's do it with special
    	 *	linger2	option.					--ANK
    	 */
    
    	if (sk->sk_state == TCP_FIN_WAIT2) {
    		struct tcp_sock *tp = tcp_sk(sk);
    		if (tp->linger2 < 0) {
    			tcp_set_state(sk, TCP_CLOSE);
    			tcp_send_active_reset(sk, GFP_ATOMIC);
    			NET_INC_STATS_BH(LINUX_MIB_TCPABORTONLINGER);
    		} else {
    			int tmo = tcp_fin_time(tp);
    
    			if (tmo > TCP_TIMEWAIT_LEN) {
    				tcp_reset_keepalive_timer(sk, tcp_fin_time(tp));
    			} else {
    				atomic_inc(&tcp_orphan_count);
    				tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
    				goto out;
    			}
    		}
    	}
    	if (sk->sk_state != TCP_CLOSE) {
    		sk_stream_mem_reclaim(sk);
    		if (atomic_read(&tcp_orphan_count) > sysctl_tcp_max_orphans ||
    		    (sk->sk_wmem_queued > SOCK_MIN_SNDBUF &&
    		     atomic_read(&tcp_memory_allocated) > sysctl_tcp_mem[2])) {
    			if (net_ratelimit())
    				printk(KERN_INFO "TCP: too many of orphaned "
    				       "sockets\n");
    			tcp_set_state(sk, TCP_CLOSE);
    			tcp_send_active_reset(sk, GFP_ATOMIC);
    			NET_INC_STATS_BH(LINUX_MIB_TCPABORTONMEMORY);
    		}
    	}
    	atomic_inc(&tcp_orphan_count);
    
    	if (sk->sk_state == TCP_CLOSE)
    		tcp_destroy_sock(sk);
    	/* Otherwise, socket is reprieved until protocol close. */
    
    out:
    	bh_unlock_sock(sk);
    	local_bh_enable();
    	sock_put(sk);
    }
    
    /* These states need RST on ABORT according to RFC793 */
    
    static inline int tcp_need_reset(int state)
    {
    	return (1 << state) &
    	       (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
    		TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
    }
    
    int tcp_disconnect(struct sock *sk, int flags)
    {
    	struct inet_sock *inet = inet_sk(sk);
    	struct tcp_sock *tp = tcp_sk(sk);
    	int err = 0;
    	int old_state = sk->sk_state;
    
    	if (old_state != TCP_CLOSE)
    		tcp_set_state(sk, TCP_CLOSE);
    
    	/* ABORT function of RFC793 */
    	if (old_state == TCP_LISTEN) {
    		tcp_listen_stop(sk);
    	} else if (tcp_need_reset(old_state) ||
    		   (tp->snd_nxt != tp->write_seq &&
    		    (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
    		/* The last check adjusts for discrepance of Linux wrt. RFC
    		 * states
    		 */
    		tcp_send_active_reset(sk, gfp_any());
    		sk->sk_err = ECONNRESET;
    	} else if (old_state == TCP_SYN_SENT)
    		sk->sk_err = ECONNRESET;
    
    	tcp_clear_xmit_timers(sk);
    	__skb_queue_purge(&sk->sk_receive_queue);
    	sk_stream_writequeue_purge(sk);
    	__skb_queue_purge(&tp->out_of_order_queue);
    
    	inet->dport = 0;
    
    	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
    		inet_reset_saddr(sk);
    
    	sk->sk_shutdown = 0;
    	sock_reset_flag(sk, SOCK_DONE);
    	tp->srtt = 0;
    	if ((tp->write_seq += tp->max_window + 2) == 0)
    		tp->write_seq = 1;
    	tp->backoff = 0;
    	tp->snd_cwnd = 2;
    	tp->probes_out = 0;
    	tp->packets_out = 0;
    	tp->snd_ssthresh = 0x7fffffff;
    	tp->snd_cwnd_cnt = 0;
    	tcp_set_ca_state(tp, TCP_CA_Open);
    	tcp_clear_retrans(tp);
    	tcp_delack_init(tp);
    	sk->sk_send_head = NULL;
    	tp->rx_opt.saw_tstamp = 0;
    	tcp_sack_reset(&tp->rx_opt);
    	__sk_dst_reset(sk);
    
    	BUG_TRAP(!inet->num || tp->bind_hash);
    
    	sk->sk_error_report(sk);
    	return err;
    }
    
    /*
     *	Wait for an incoming connection, avoid race
     *	conditions. This must be called with the socket locked.
     */
    static int wait_for_connect(struct sock *sk, long timeo)
    {
    	struct tcp_sock *tp = tcp_sk(sk);
    	DEFINE_WAIT(wait);
    	int err;
    
    	/*
    	 * True wake-one mechanism for incoming connections: only
    	 * one process gets woken up, not the 'whole herd'.
    	 * Since we do not 'race & poll' for established sockets
    	 * anymore, the common case will execute the loop only once.
    	 *
    	 * Subtle issue: "add_wait_queue_exclusive()" will be added
    	 * after any current non-exclusive waiters, and we know that
    	 * it will always _stay_ after any new non-exclusive waiters
    	 * because all non-exclusive waiters are added at the
    	 * beginning of the wait-queue. As such, it's ok to "drop"
    	 * our exclusiveness temporarily when we get woken up without
    	 * having to remove and re-insert us on the wait queue.
    	 */
    	for (;;) {
    		prepare_to_wait_exclusive(sk->sk_sleep, &wait,
    					  TASK_INTERRUPTIBLE);
    		release_sock(sk);
    		if (!tp->accept_queue)
    			timeo = schedule_timeout(timeo);
    		lock_sock(sk);
    		err = 0;
    		if (tp->accept_queue)
    			break;
    		err = -EINVAL;
    		if (sk->sk_state != TCP_LISTEN)
    			break;
    		err = sock_intr_errno(timeo);
    		if (signal_pending(current))
    			break;
    		err = -EAGAIN;
    		if (!timeo)
    			break;
    	}
    	finish_wait(sk->sk_sleep, &wait);
    	return err;
    }
    
    /*
     *	This will accept the next outstanding connection.
     */
    
    struct sock *tcp_accept(struct sock *sk, int flags, int *err)
    {
    	struct tcp_sock *tp = tcp_sk(sk);
    	struct open_request *req;
    	struct sock *newsk;
    	int error;
    
    	lock_sock(sk);
    
    	/* We need to make sure that this socket is listening,
    	 * and that it has something pending.
    	 */
    	error = -EINVAL;
    	if (sk->sk_state != TCP_LISTEN)
    		goto out;
    
    	/* Find already established connection */
    	if (!tp->accept_queue) {
    		long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
    
    		/* If this is a non blocking socket don't sleep */
    		error = -EAGAIN;
    		if (!timeo)
    			goto out;
    
    		error = wait_for_connect(sk, timeo);
    		if (error)
    			goto out;
    	}
    
    	req = tp->accept_queue;
    	if ((tp->accept_queue = req->dl_next) == NULL)
    		tp->accept_queue_tail = NULL;
    
     	newsk = req->sk;
    	sk_acceptq_removed(sk);
    	tcp_openreq_fastfree(req);
    	BUG_TRAP(newsk->sk_state != TCP_SYN_RECV);
    	release_sock(sk);
    	return newsk;
    
    out:
    	release_sock(sk);
    	*err = error;
    	return NULL;
    }
    
    /*
     *	Socket option code for TCP.
     */
    int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
    		   int optlen)
    {
    	struct tcp_sock *tp = tcp_sk(sk);
    	int val;
    	int err = 0;
    
    	if (level != SOL_TCP)
    		return tp->af_specific->setsockopt(sk, level, optname,
    						   optval, optlen);
    
    	if (optlen < sizeof(int))
    		return -EINVAL;
    
    	if (get_user(val, (int __user *)optval))
    		return -EFAULT;
    
    	lock_sock(sk);
    
    	switch (optname) {
    	case TCP_MAXSEG:
    		/* Values greater than interface MTU won't take effect. However
    		 * at the point when this call is done we typically don't yet
    		 * know which interface is going to be used */
    		if (val < 8 || val > MAX_TCP_WINDOW) {
    			err = -EINVAL;
    			break;
    		}
    		tp->rx_opt.user_mss = val;
    		break;
    
    	case TCP_NODELAY:
    		if (val) {
    			/* TCP_NODELAY is weaker than TCP_CORK, so that
    			 * this option on corked socket is remembered, but
    			 * it is not activated until cork is cleared.
    			 *
    			 * However, when TCP_NODELAY is set we make
    			 * an explicit push, which overrides even TCP_CORK
    			 * for currently queued segments.
    			 */
    			tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
    			tcp_push_pending_frames(sk, tp);
    		} else {
    			tp->nonagle &= ~TCP_NAGLE_OFF;
    		}
    		break;
    
    	case TCP_CORK:
    		/* When set indicates to always queue non-full frames.
    		 * Later the user clears this option and we transmit
    		 * any pending partial frames in the queue.  This is
    		 * meant to be used alongside sendfile() to get properly
    		 * filled frames when the user (for example) must write
    		 * out headers with a write() call first and then use
    		 * sendfile to send out the data parts.