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

#include <common.h>
#include <command.h>
#include <net.h>
#include <rtc.h>

#include "sntp.h"

15
#define SNTP_TIMEOUT 10000UL
16 17 18 19

static int SntpOurPort;

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

Robin Getz's avatar
Robin Getz committed
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
	memcpy((char *)NetTxPacket + NetEthHdrSize() + IP_UDP_HDR_SIZE,
35
		(char *)&pkt, pktlen);
36 37 38 39

	SntpOurPort = 10000 + (get_timer(0) % 4096);
	sport = NTP_SERVICE_PORT;

40 41
	NetSendUDPPacket(NetServerEther, NetNtpServerIP, sport, SntpOurPort,
		pktlen);
42 43 44
}

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

static void
53 54
SntpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
	    unsigned len)
55
{
wdenk's avatar
wdenk committed
56
	struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
57
	struct rtc_time tm;
wdenk's avatar
wdenk committed
58
	ulong seconds;
59

Robin Getz's avatar
Robin Getz committed
60
	debug("%s\n", __func__);
61

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

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

wdenk's avatar
wdenk committed
71
	to_tm(ntohl(seconds) - 2208988800UL + NetTimeOffset, &tm);
72
#if defined(CONFIG_CMD_DATE)
73
	rtc_set(&tm);
74
#endif
75
	printf("Date: %4d-%02d-%02d Time: %2d:%02d:%02d\n",
76 77 78
		tm.tm_year, tm.tm_mon, tm.tm_mday,
		tm.tm_hour, tm.tm_min, tm.tm_sec);

79
	net_set_state(NETLOOP_SUCCESS);
80 81 82
}

void
83
SntpStart(void)
84
{
Robin Getz's avatar
Robin Getz committed
85
	debug("%s\n", __func__);
86

87
	NetSetTimeout(SNTP_TIMEOUT, SntpTimeout);
88
	NetSetHandler(SntpHandler);
89
	memset(NetServerEther, 0, sizeof(NetServerEther));
90

91
	SntpSend();
92
}