sntp.c 2.0 KB

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