sntp.c 2.05 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*
 * SNTP support driver
 *
 * Masami Komiya <mkomiya@sonare.it> 2005
 *
 */

#include <common.h>
#include <command.h>
10
#include <dm.h>
11 12 13 14 15
#include <net.h>
#include <rtc.h>

#include "sntp.h"

16
#define SNTP_TIMEOUT 10000UL
17

18
static int sntp_our_port;
19

20
static void sntp_send(void)
21 22 23 24 25
{
	struct sntp_pkt_t pkt;
	int pktlen = SNTP_PACKET_LEN;
	int sport;

26
	debug("%s\n", __func__);
27

28
	memset(&pkt, 0, sizeof(pkt));
29 30 31 32 33

	pkt.li = NTP_LI_NOLEAP;
	pkt.vn = NTP_VERSION;
	pkt.mode = NTP_MODE_CLIENT;

34 35
	memcpy((char *)net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE,
	       (char *)&pkt, pktlen);
36

37
	sntp_our_port = 10000 + (get_timer(0) % 4096);
38 39
	sport = NTP_SERVICE_PORT;

40
	net_send_udp_packet(net_server_ethaddr, net_ntp_server, sport,
41
			    sntp_our_port, pktlen);
42 43
}

44
static void sntp_timeout_handler(void)
45
{
46
	puts("Timeout\n");
47
	net_set_state(NETLOOP_FAIL);
48 49 50
	return;
}

51 52
static void sntp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
			 unsigned src, unsigned len)
53
{
54
#ifdef CONFIG_TIMESTAMP
wdenk's avatar
wdenk committed
55
	struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
56
	struct rtc_time tm;
wdenk's avatar
wdenk committed
57
	ulong seconds;
58
#endif
59

60
	debug("%s\n", __func__);
61

62
	if (dest != sntp_our_port)
63
		return;
64

65
#ifdef CONFIG_TIMESTAMP
wdenk's avatar
wdenk committed
66
	/*
67
	 * As the RTC's used in U-Boot support second resolution only
wdenk's avatar
wdenk committed
68 69
	 * we simply ignore the sub-second field.
	 */
70
	memcpy(&seconds, &rpktp->transmit_timestamp, sizeof(ulong));
71

72
	rtc_to_tm(ntohl(seconds) - 2208988800UL + net_ntp_time_offset, &tm);
73
#if defined(CONFIG_CMD_DATE)
74 75 76 77 78 79 80 81 82 83
#  ifdef CONFIG_DM_RTC
	struct udevice *dev;
	int ret;

	ret = uclass_get_device(UCLASS_RTC, 0, &dev);
	if (ret)
		printf("SNTP: cannot find RTC: err=%d\n", ret);
	else
		dm_rtc_set(dev, &tm);
#  else
84
	rtc_set(&tm);
85
#  endif
86
#endif
87
	printf("Date: %4d-%02d-%02d Time: %2d:%02d:%02d\n",
88 89
	       tm.tm_year, tm.tm_mon, tm.tm_mday,
	       tm.tm_hour, tm.tm_min, tm.tm_sec);
90
#endif
91

92
	net_set_state(NETLOOP_SUCCESS);
93 94
}

95
void sntp_start(void)
96
{
97
	debug("%s\n", __func__);
98

99
	net_set_timeout_handler(SNTP_TIMEOUT, sntp_timeout_handler);
100
	net_set_udp_handler(sntp_handler);
101
	memset(net_server_ethaddr, 0, sizeof(net_server_ethaddr));
102

103
	sntp_send();
104
}