blob: 5de19526e6394b213cd2204d594026d6201a5175 [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001/*
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
17static int SntpOurPort;
18
19static void
20SntpSend(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, NetNtpServerIP, sport, SntpOurPort,
41 pktlen);
42}
43
44static void
45SntpTimeout(void)
46{
47 puts("Timeout\n");
48 net_set_state(NETLOOP_FAIL);
49 return;
50}
51
52static void
53SntpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
54 unsigned len)
55{
56 struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
57 struct rtc_time tm;
58 ulong seconds;
59
60 debug("%s\n", __func__);
61
62 if (dest != SntpOurPort)
63 return;
64
65 /*
66 * As the RTC's used in U-Boot sepport second resolution only
67 * we simply ignore the sub-second field.
68 */
69 memcpy(&seconds, &rpktp->transmit_timestamp, sizeof(ulong));
70
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 tm.tm_year, tm.tm_mon, tm.tm_mday,
77 tm.tm_hour, tm.tm_min, tm.tm_sec);
78
79 net_set_state(NETLOOP_SUCCESS);
80}
81
82void
83SntpStart(void)
84{
85 debug("%s\n", __func__);
86
87 NetSetTimeout(SNTP_TIMEOUT, SntpTimeout);
88 net_set_udp_handler(SntpHandler);
89 memset(NetServerEther, 0, sizeof(NetServerEther));
90
91 SntpSend();
92}