sntp.c 1.8 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 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. #ifdef CONFIG_TIMESTAMP
  41. struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
  42. struct rtc_time tm;
  43. ulong seconds;
  44. #endif
  45. debug("%s\n", __func__);
  46. if (dest != sntp_our_port)
  47. return;
  48. #ifdef CONFIG_TIMESTAMP
  49. /*
  50. * As the RTC's used in U-Boot support second resolution only
  51. * we simply ignore the sub-second field.
  52. */
  53. memcpy(&seconds, &rpktp->transmit_timestamp, sizeof(ulong));
  54. rtc_to_tm(ntohl(seconds) - 2208988800UL + net_ntp_time_offset, &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. #endif
  62. net_set_state(NETLOOP_SUCCESS);
  63. }
  64. void sntp_start(void)
  65. {
  66. debug("%s\n", __func__);
  67. net_set_timeout_handler(SNTP_TIMEOUT, sntp_timeout_handler);
  68. net_set_udp_handler(sntp_handler);
  69. memset(net_server_ethaddr, 0, sizeof(net_server_ethaddr));
  70. sntp_send();
  71. }