]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - net/sntp.c
3e45a8342a36ba8e259607e701bc9870a86d6bdd
[karo-tx-uboot.git] / net / sntp.c
1 /*
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
15 #define SNTP_TIMEOUT 10000UL
16
17 static int SntpOurPort;
18
19 static void
20 SntpSend(void)
21 {
22         struct sntp_pkt_t pkt;
23         int pktlen = SNTP_PACKET_LEN;
24         int sport;
25
26         debug("%s\n", __func__);
27
28         memset(&pkt, 0, sizeof(pkt));
29
30         pkt.li = NTP_LI_NOLEAP;
31         pkt.vn = NTP_VERSION;
32         pkt.mode = NTP_MODE_CLIENT;
33
34         memcpy((char *)NetTxPacket + NetEthHdrSize() + IP_UDP_HDR_SIZE,
35                 (char *)&pkt, pktlen);
36
37         SntpOurPort = 10000 + (get_timer(0) % 4096);
38         sport = NTP_SERVICE_PORT;
39
40         NetSendUDPPacket(NetServerEther, net_ntp_server, sport, SntpOurPort,
41                          pktlen);
42 }
43
44 static void
45 SntpTimeout(void)
46 {
47         puts("Timeout\n");
48         net_set_state(NETLOOP_FAIL);
49         return;
50 }
51
52 static void sntp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
53                          unsigned src, unsigned len)
54 {
55         struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
56         struct rtc_time tm;
57         ulong seconds;
58
59         debug("%s\n", __func__);
60
61         if (dest != SntpOurPort)
62                 return;
63
64         /*
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));
69
70         to_tm(ntohl(seconds) - 2208988800UL + NetTimeOffset, &tm);
71 #if defined(CONFIG_CMD_DATE)
72         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);
77
78         net_set_state(NETLOOP_SUCCESS);
79 }
80
81 void
82 SntpStart(void)
83 {
84         debug("%s\n", __func__);
85
86         NetSetTimeout(SNTP_TIMEOUT, SntpTimeout);
87         net_set_udp_handler(sntp_handler);
88         memset(NetServerEther, 0, sizeof(NetServerEther));
89
90         SntpSend();
91 }