colibri_imx6: fix video stdout in default environment
[oweals/u-boot.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 <dm.h>
11 #include <log.h>
12 #include <net.h>
13 #include <rtc.h>
14
15 #include "sntp.h"
16
17 #define SNTP_TIMEOUT 10000UL
18
19 static int sntp_our_port;
20
21 static void sntp_send(void)
22 {
23         struct sntp_pkt_t pkt;
24         int pktlen = SNTP_PACKET_LEN;
25         int sport;
26
27         debug("%s\n", __func__);
28
29         memset(&pkt, 0, sizeof(pkt));
30
31         pkt.li = NTP_LI_NOLEAP;
32         pkt.vn = NTP_VERSION;
33         pkt.mode = NTP_MODE_CLIENT;
34
35         memcpy((char *)net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE,
36                (char *)&pkt, pktlen);
37
38         sntp_our_port = 10000 + (get_timer(0) % 4096);
39         sport = NTP_SERVICE_PORT;
40
41         net_send_udp_packet(net_server_ethaddr, net_ntp_server, sport,
42                             sntp_our_port, pktlen);
43 }
44
45 static void sntp_timeout_handler(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 #ifdef CONFIG_TIMESTAMP
56         struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
57         struct rtc_time tm;
58         ulong seconds;
59 #endif
60
61         debug("%s\n", __func__);
62
63         if (dest != sntp_our_port)
64                 return;
65
66 #ifdef CONFIG_TIMESTAMP
67         /*
68          * As the RTC's used in U-Boot support second resolution only
69          * we simply ignore the sub-second field.
70          */
71         memcpy(&seconds, &rpktp->transmit_timestamp, sizeof(ulong));
72
73         rtc_to_tm(ntohl(seconds) - 2208988800UL + net_ntp_time_offset, &tm);
74 #if defined(CONFIG_CMD_DATE)
75 #  ifdef CONFIG_DM_RTC
76         struct udevice *dev;
77         int ret;
78
79         ret = uclass_get_device(UCLASS_RTC, 0, &dev);
80         if (ret)
81                 printf("SNTP: cannot find RTC: err=%d\n", ret);
82         else
83                 dm_rtc_set(dev, &tm);
84 #  else
85         rtc_set(&tm);
86 #  endif
87 #endif
88         printf("Date: %4d-%02d-%02d Time: %2d:%02d:%02d\n",
89                tm.tm_year, tm.tm_mon, tm.tm_mday,
90                tm.tm_hour, tm.tm_min, tm.tm_sec);
91 #endif
92
93         net_set_state(NETLOOP_SUCCESS);
94 }
95
96 void sntp_start(void)
97 {
98         debug("%s\n", __func__);
99
100         net_set_timeout_handler(SNTP_TIMEOUT, sntp_timeout_handler);
101         net_set_udp_handler(sntp_handler);
102         memset(net_server_ethaddr, 0, sizeof(net_server_ethaddr));
103
104         sntp_send();
105 }