sntp.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 <dm.h>
  10. #include <log.h>
  11. #include <net.h>
  12. #include <rtc.h>
  13. #include "sntp.h"
  14. #define SNTP_TIMEOUT 10000UL
  15. static int sntp_our_port;
  16. static void sntp_send(void)
  17. {
  18. struct sntp_pkt_t pkt;
  19. int pktlen = SNTP_PACKET_LEN;
  20. int sport;
  21. debug("%s\n", __func__);
  22. memset(&pkt, 0, sizeof(pkt));
  23. pkt.li = NTP_LI_NOLEAP;
  24. pkt.vn = NTP_VERSION;
  25. pkt.mode = NTP_MODE_CLIENT;
  26. memcpy((char *)net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE,
  27. (char *)&pkt, pktlen);
  28. sntp_our_port = 10000 + (get_timer(0) % 4096);
  29. sport = NTP_SERVICE_PORT;
  30. net_send_udp_packet(net_server_ethaddr, net_ntp_server, sport,
  31. sntp_our_port, pktlen);
  32. }
  33. static void sntp_timeout_handler(void)
  34. {
  35. puts("Timeout\n");
  36. net_set_state(NETLOOP_FAIL);
  37. return;
  38. }
  39. static void sntp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
  40. unsigned src, unsigned len)
  41. {
  42. #ifdef CONFIG_TIMESTAMP
  43. struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
  44. struct rtc_time tm;
  45. ulong seconds;
  46. #endif
  47. debug("%s\n", __func__);
  48. if (dest != sntp_our_port)
  49. return;
  50. #ifdef CONFIG_TIMESTAMP
  51. /*
  52. * As the RTC's used in U-Boot support second resolution only
  53. * we simply ignore the sub-second field.
  54. */
  55. memcpy(&seconds, &rpktp->transmit_timestamp, sizeof(ulong));
  56. rtc_to_tm(ntohl(seconds) - 2208988800UL + net_ntp_time_offset, &tm);
  57. #if defined(CONFIG_CMD_DATE)
  58. # ifdef CONFIG_DM_RTC
  59. struct udevice *dev;
  60. int ret;
  61. ret = uclass_get_device(UCLASS_RTC, 0, &dev);
  62. if (ret)
  63. printf("SNTP: cannot find RTC: err=%d\n", ret);
  64. else
  65. dm_rtc_set(dev, &tm);
  66. # else
  67. rtc_set(&tm);
  68. # endif
  69. #endif
  70. printf("Date: %4d-%02d-%02d Time: %2d:%02d:%02d\n",
  71. tm.tm_year, tm.tm_mon, tm.tm_mday,
  72. tm.tm_hour, tm.tm_min, tm.tm_sec);
  73. #endif
  74. net_set_state(NETLOOP_SUCCESS);
  75. }
  76. void sntp_start(void)
  77. {
  78. debug("%s\n", __func__);
  79. net_set_timeout_handler(SNTP_TIMEOUT, sntp_timeout_handler);
  80. net_set_udp_handler(sntp_handler);
  81. memset(net_server_ethaddr, 0, sizeof(net_server_ethaddr));
  82. sntp_send();
  83. }