blob: 0a7f4782cbb5557cdd1ad225c6747725c3868f1f [file] [log] [blame]
wdenkea287de2005-04-01 00:25:43 +00001/*
2 * SNTP support driver
3 *
4 * Masami Komiya <mkomiya@sonare.it> 2005
5 *
6 */
7
8#include <common.h>
9#include <command.h>
10#include <net.h>
11#include <rtc.h>
12
13#include "sntp.h"
14
Jon Loeliger643d1ab2007-07-09 17:45:14 -050015#if (defined(CONFIG_CMD_NET) \
16 && defined(CONFIG_CMD_SNTP)
wdenkea287de2005-04-01 00:25:43 +000017
18#define SNTP_TIMEOUT 10
19
20static int SntpOurPort;
21
22static void
23SntpSend (void)
24{
25 struct sntp_pkt_t pkt;
26 int pktlen = SNTP_PACKET_LEN;
27 int sport;
28
29 debug ("%s\n", __FUNCTION__);
30
31 memset (&pkt, 0, sizeof(pkt));
32
33 pkt.li = NTP_LI_NOLEAP;
34 pkt.vn = NTP_VERSION;
35 pkt.mode = NTP_MODE_CLIENT;
36
37 memcpy ((char *)NetTxPacket + NetEthHdrSize() + IP_HDR_SIZE, (char *)&pkt, pktlen);
38
39 SntpOurPort = 10000 + (get_timer(0) % 4096);
40 sport = NTP_SERVICE_PORT;
41
42 NetSendUDPPacket (NetServerEther, NetNtpServerIP, sport, SntpOurPort, pktlen);
43}
44
45static void
46SntpTimeout (void)
47{
48 puts ("Timeout\n");
49 NetState = NETLOOP_FAIL;
50 return;
51}
52
53static void
54SntpHandler (uchar *pkt, unsigned dest, unsigned src, unsigned len)
55{
wdenk414eec32005-04-02 22:37:54 +000056 struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
wdenkea287de2005-04-01 00:25:43 +000057 struct rtc_time tm;
wdenk414eec32005-04-02 22:37:54 +000058 ulong seconds;
wdenkea287de2005-04-01 00:25:43 +000059
60 debug ("%s\n", __FUNCTION__);
61
62 if (dest != SntpOurPort) return;
63
wdenk414eec32005-04-02 22:37:54 +000064 /*
65 * As the RTC's used in U-Boot sepport second resolution only
66 * we simply ignore the sub-second field.
67 */
68 memcpy (&seconds, &rpktp->transmit_timestamp, sizeof(ulong));
wdenkea287de2005-04-01 00:25:43 +000069
wdenk414eec32005-04-02 22:37:54 +000070 to_tm(ntohl(seconds) - 2208988800UL + NetTimeOffset, &tm);
Jon Loeliger643d1ab2007-07-09 17:45:14 -050071#if defined(CONFIG_CMD_DATE)
wdenkea287de2005-04-01 00:25:43 +000072 rtc_set (&tm);
73#endif
74 printf ("Date: %4d-%02d-%02d Time: %2d:%02d:%02d\n",
75 tm.tm_year, tm.tm_mon, tm.tm_mday,
76 tm.tm_hour, tm.tm_min, tm.tm_sec);
wdenkea287de2005-04-01 00:25:43 +000077
78 NetState = NETLOOP_SUCCESS;
79}
80
81void
82SntpStart (void)
83{
84 debug ("%s\n", __FUNCTION__);
85
86 NetSetTimeout (SNTP_TIMEOUT * CFG_HZ, SntpTimeout);
87 NetSetHandler(SntpHandler);
88 memset (NetServerEther, 0, 6);
89
90 SntpSend ();
91}
92
Jon Loeliger643d1ab2007-07-09 17:45:14 -050093#endif