sntp.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * SNTP support driver
  3. *
  4. * Masami Komiya <mkomiya@sonare.it> 2005
  5. *
  6. */
  7. #include <common.h>
  8. #include <command.h>
  9. #include <net.h>
  10. #include <rtc.h>
  11. #include "sntp.h"
  12. #define SNTP_TIMEOUT 10000UL
  13. static int sntp_our_port;
  14. static void sntp_send(void)
  15. {
  16. struct sntp_pkt_t pkt;
  17. int pktlen = SNTP_PACKET_LEN;
  18. int sport;
  19. debug("%s\n", __func__);
  20. memset(&pkt, 0, sizeof(pkt));
  21. pkt.li = NTP_LI_NOLEAP;
  22. pkt.vn = NTP_VERSION;
  23. pkt.mode = NTP_MODE_CLIENT;
  24. memcpy((char *)net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE,
  25. (char *)&pkt, pktlen);
  26. sntp_our_port = 10000 + (get_timer(0) % 4096);
  27. sport = NTP_SERVICE_PORT;
  28. net_send_udp_packet(net_server_ethaddr, net_ntp_server, sport,
  29. sntp_our_port, pktlen);
  30. }
  31. static void sntp_timeout_handler(void)
  32. {
  33. puts("Timeout\n");
  34. net_set_state(NETLOOP_FAIL);
  35. return;
  36. }
  37. static void sntp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
  38. unsigned src, unsigned len)
  39. {
  40. struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
  41. struct rtc_time tm;
  42. ulong seconds;
  43. debug("%s\n", __func__);
  44. if (dest != sntp_our_port)
  45. return;
  46. /*
  47. * As the RTC's used in U-Boot sepport second resolution only
  48. * we simply ignore the sub-second field.
  49. */
  50. memcpy(&seconds, &rpktp->transmit_timestamp, sizeof(ulong));
  51. to_tm(ntohl(seconds) - 2208988800UL + net_ntp_time_offset, &tm);
  52. #if defined(CONFIG_CMD_DATE)
  53. rtc_set(&tm);
  54. #endif
  55. printf("Date: %4d-%02d-%02d Time: %2d:%02d:%02d\n",
  56. tm.tm_year, tm.tm_mon, tm.tm_mday,
  57. tm.tm_hour, tm.tm_min, tm.tm_sec);
  58. net_set_state(NETLOOP_SUCCESS);
  59. }
  60. void sntp_start(void)
  61. {
  62. debug("%s\n", __func__);
  63. net_set_timeout_handler(SNTP_TIMEOUT, sntp_timeout_handler);
  64. net_set_udp_handler(sntp_handler);
  65. memset(net_server_ethaddr, 0, sizeof(net_server_ethaddr));
  66. sntp_send();
  67. }