sntp.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 SntpOurPort;
  14. static void
  15. SntpSend(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 *)NetTxPacket + NetEthHdrSize() + IP_UDP_HDR_SIZE,
  26. (char *)&pkt, pktlen);
  27. SntpOurPort = 10000 + (get_timer(0) % 4096);
  28. sport = NTP_SERVICE_PORT;
  29. NetSendUDPPacket(NetServerEther, NetNtpServerIP, sport, SntpOurPort,
  30. pktlen);
  31. }
  32. static void
  33. SntpTimeout(void)
  34. {
  35. puts("Timeout\n");
  36. net_set_state(NETLOOP_FAIL);
  37. return;
  38. }
  39. static void
  40. SntpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
  41. unsigned len)
  42. {
  43. struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
  44. struct rtc_time tm;
  45. ulong seconds;
  46. debug("%s\n", __func__);
  47. if (dest != SntpOurPort)
  48. return;
  49. /*
  50. * As the RTC's used in U-Boot sepport second resolution only
  51. * we simply ignore the sub-second field.
  52. */
  53. memcpy(&seconds, &rpktp->transmit_timestamp, sizeof(ulong));
  54. to_tm(ntohl(seconds) - 2208988800UL + NetTimeOffset, &tm);
  55. #if defined(CONFIG_CMD_DATE)
  56. rtc_set(&tm);
  57. #endif
  58. printf("Date: %4d-%02d-%02d Time: %2d:%02d:%02d\n",
  59. tm.tm_year, tm.tm_mon, tm.tm_mday,
  60. tm.tm_hour, tm.tm_min, tm.tm_sec);
  61. net_set_state(NETLOOP_SUCCESS);
  62. }
  63. void
  64. SntpStart(void)
  65. {
  66. debug("%s\n", __func__);
  67. NetSetTimeout(SNTP_TIMEOUT, SntpTimeout);
  68. net_set_udp_handler(SntpHandler);
  69. memset(NetServerEther, 0, sizeof(NetServerEther));
  70. SntpSend();
  71. }