xref: /openbmc/u-boot/net/sntp.c (revision 53ab4af3)
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 sntp_our_port;
18 
19 static void sntp_send(void)
20 {
21 	struct sntp_pkt_t pkt;
22 	int pktlen = SNTP_PACKET_LEN;
23 	int sport;
24 
25 	debug("%s\n", __func__);
26 
27 	memset(&pkt, 0, sizeof(pkt));
28 
29 	pkt.li = NTP_LI_NOLEAP;
30 	pkt.vn = NTP_VERSION;
31 	pkt.mode = NTP_MODE_CLIENT;
32 
33 	memcpy((char *)net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE,
34 	       (char *)&pkt, pktlen);
35 
36 	sntp_our_port = 10000 + (get_timer(0) % 4096);
37 	sport = NTP_SERVICE_PORT;
38 
39 	net_send_udp_packet(net_server_ethaddr, net_ntp_server, sport,
40 			    sntp_our_port, pktlen);
41 }
42 
43 static void sntp_timeout_handler(void)
44 {
45 	puts("Timeout\n");
46 	net_set_state(NETLOOP_FAIL);
47 	return;
48 }
49 
50 static void sntp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
51 			 unsigned src, unsigned len)
52 {
53 #ifdef CONFIG_TIMESTAMP
54 	struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
55 	struct rtc_time tm;
56 	ulong seconds;
57 #endif
58 
59 	debug("%s\n", __func__);
60 
61 	if (dest != sntp_our_port)
62 		return;
63 
64 #ifdef CONFIG_TIMESTAMP
65 	/*
66 	 * As the RTC's used in U-Boot support 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 + net_ntp_time_offset, &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 #endif
79 
80 	net_set_state(NETLOOP_SUCCESS);
81 }
82 
83 void sntp_start(void)
84 {
85 	debug("%s\n", __func__);
86 
87 	net_set_timeout_handler(SNTP_TIMEOUT, sntp_timeout_handler);
88 	net_set_udp_handler(sntp_handler);
89 	memset(net_server_ethaddr, 0, sizeof(net_server_ethaddr));
90 
91 	sntp_send();
92 }
93