4 * Copyright(c) 2015 Intel Corporation. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
17 * * Neither the name of Intel Corporation nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 * This application is a simple Layer 2 PTP v2 client. It shows delta values
36 * which are used to synchronize the PHC clock. if the "-T 1" parameter is
37 * passed to the application the Linux kernel clock is also synchronized.
43 #include <rte_ethdev.h>
44 #include <rte_cycles.h>
45 #include <rte_lcore.h>
52 #define RX_RING_SIZE 128
53 #define TX_RING_SIZE 512
55 #define NUM_MBUFS 8191
56 #define MBUF_CACHE_SIZE 250
58 /* Values for the PTP messageType field. */
61 #define PDELAY_REQ 0x2
62 #define PDELAY_RESP 0x3
64 #define DELAY_RESP 0x9
65 #define PDELAY_RESP_FOLLOW_UP 0xA
68 #define MANAGEMENT 0xD
70 #define NSEC_PER_SEC 1000000000L
71 #define KERNEL_TIME_ADJUST_LIMIT 20000
72 #define PTP_PROTOCOL 0x88F7
74 struct rte_mempool *mbuf_pool;
75 uint32_t ptp_enabled_port_mask;
76 uint8_t ptp_enabled_port_nb;
77 static uint8_t ptp_enabled_ports[RTE_MAX_ETHPORTS];
79 static const struct rte_eth_conf port_conf_default = {
80 .rxmode = { .max_rx_pkt_len = ETHER_MAX_LEN }
83 static const struct ether_addr ether_multicast = {
84 .addr_bytes = {0x01, 0x1b, 0x19, 0x0, 0x0, 0x0}
87 /* Structs used for PTP handling. */
92 } __attribute__((packed));
99 struct clock_id clock_id;
100 uint16_t port_number;
101 } __attribute__((packed));
106 uint16_t message_length;
107 uint8_t domain_number;
109 uint8_t flag_field[2];
112 struct port_id source_port_id;
115 int8_t log_message_interval;
116 } __attribute__((packed));
119 struct ptp_header hdr;
120 struct tstamp origin_tstamp;
121 } __attribute__((packed));
123 struct follow_up_msg {
124 struct ptp_header hdr;
125 struct tstamp precise_origin_tstamp;
127 } __attribute__((packed));
129 struct delay_req_msg {
130 struct ptp_header hdr;
131 struct tstamp origin_tstamp;
132 } __attribute__((packed));
134 struct delay_resp_msg {
135 struct ptp_header hdr;
136 struct tstamp rx_tstamp;
137 struct port_id req_port_id;
139 } __attribute__((packed));
143 struct ptp_header header;
144 struct sync_msg sync;
145 struct delay_req_msg delay_req;
146 struct follow_up_msg follow_up;
147 struct delay_resp_msg delay_resp;
148 } __attribute__((packed));
151 struct ptpv2_data_slave_ordinary {
153 struct timespec tstamp1;
154 struct timespec tstamp2;
155 struct timespec tstamp3;
156 struct timespec tstamp4;
157 struct clock_id client_clock_id;
158 struct clock_id master_clock_id;
159 struct timeval new_adj;
163 uint16_t seqID_FOLLOWUP;
165 uint8_t kernel_time_set;
166 uint16_t current_ptp_port;
169 static struct ptpv2_data_slave_ordinary ptp_data;
171 static inline uint64_t timespec64_to_ns(const struct timespec *ts)
173 return ((uint64_t) ts->tv_sec * NSEC_PER_SEC) + ts->tv_nsec;
176 static struct timeval
177 ns_to_timeval(int64_t nsec)
179 struct timespec t_spec = {0, 0};
180 struct timeval t_eval = {0, 0};
185 rem = nsec % NSEC_PER_SEC;
186 t_spec.tv_sec = nsec / NSEC_PER_SEC;
193 t_spec.tv_nsec = rem;
194 t_eval.tv_sec = t_spec.tv_sec;
195 t_eval.tv_usec = t_spec.tv_nsec / 1000;
201 * Initializes a given port using global settings and with the RX buffers
202 * coming from the mbuf_pool passed as a parameter.
205 port_init(uint16_t port, struct rte_mempool *mbuf_pool)
207 struct rte_eth_dev_info dev_info;
208 struct rte_eth_conf port_conf = port_conf_default;
209 const uint16_t rx_rings = 1;
210 const uint16_t tx_rings = 1;
213 uint16_t nb_rxd = RX_RING_SIZE;
214 uint16_t nb_txd = TX_RING_SIZE;
216 if (port >= rte_eth_dev_count())
219 /* Configure the Ethernet device. */
220 retval = rte_eth_dev_configure(port, rx_rings, tx_rings, &port_conf);
224 retval = rte_eth_dev_adjust_nb_rx_tx_desc(port, &nb_rxd, &nb_txd);
228 /* Allocate and set up 1 RX queue per Ethernet port. */
229 for (q = 0; q < rx_rings; q++) {
230 retval = rte_eth_rx_queue_setup(port, q, nb_rxd,
231 rte_eth_dev_socket_id(port), NULL, mbuf_pool);
237 /* Allocate and set up 1 TX queue per Ethernet port. */
238 for (q = 0; q < tx_rings; q++) {
239 /* Setup txq_flags */
240 struct rte_eth_txconf *txconf;
242 rte_eth_dev_info_get(q, &dev_info);
243 txconf = &dev_info.default_txconf;
244 txconf->txq_flags = 0;
246 retval = rte_eth_tx_queue_setup(port, q, nb_txd,
247 rte_eth_dev_socket_id(port), txconf);
252 /* Start the Ethernet port. */
253 retval = rte_eth_dev_start(port);
257 /* Enable timesync timestamping for the Ethernet device */
258 rte_eth_timesync_enable(port);
260 /* Enable RX in promiscuous mode for the Ethernet device. */
261 rte_eth_promiscuous_enable(port);
267 print_clock_info(struct ptpv2_data_slave_ordinary *ptp_data)
270 struct timespec net_time, sys_time;
272 printf("Master Clock id: %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
273 ptp_data->master_clock_id.id[0],
274 ptp_data->master_clock_id.id[1],
275 ptp_data->master_clock_id.id[2],
276 ptp_data->master_clock_id.id[3],
277 ptp_data->master_clock_id.id[4],
278 ptp_data->master_clock_id.id[5],
279 ptp_data->master_clock_id.id[6],
280 ptp_data->master_clock_id.id[7]);
282 printf("\nT2 - Slave Clock. %lds %ldns",
283 (ptp_data->tstamp2.tv_sec),
284 (ptp_data->tstamp2.tv_nsec));
286 printf("\nT1 - Master Clock. %lds %ldns ",
287 ptp_data->tstamp1.tv_sec,
288 (ptp_data->tstamp1.tv_nsec));
290 printf("\nT3 - Slave Clock. %lds %ldns",
291 ptp_data->tstamp3.tv_sec,
292 (ptp_data->tstamp3.tv_nsec));
294 printf("\nT4 - Master Clock. %lds %ldns ",
295 ptp_data->tstamp4.tv_sec,
296 (ptp_data->tstamp4.tv_nsec));
298 printf("\nDelta between master and slave clocks:%"PRId64"ns\n",
301 clock_gettime(CLOCK_REALTIME, &sys_time);
302 rte_eth_timesync_read_time(ptp_data->current_ptp_port, &net_time);
304 time_t ts = net_time.tv_sec;
306 printf("\n\nComparison between Linux kernel Time and PTP:");
308 printf("\nCurrent PTP Time: %.24s %.9ld ns",
309 ctime(&ts), net_time.tv_nsec);
311 nsec = (int64_t)timespec64_to_ns(&net_time) -
312 (int64_t)timespec64_to_ns(&sys_time);
313 ptp_data->new_adj = ns_to_timeval(nsec);
315 gettimeofday(&ptp_data->new_adj, NULL);
317 time_t tp = ptp_data->new_adj.tv_sec;
319 printf("\nCurrent SYS Time: %.24s %.6ld ns",
320 ctime(&tp), ptp_data->new_adj.tv_usec);
322 printf("\nDelta between PTP and Linux Kernel time:%"PRId64"ns\n",
325 printf("[Ctrl+C to quit]\n");
327 /* Clear screen and put cursor in column 1, row 1 */
328 printf("\033[2J\033[1;1H");
332 delta_eval(struct ptpv2_data_slave_ordinary *ptp_data)
340 t1 = timespec64_to_ns(&ptp_data->tstamp1);
341 t2 = timespec64_to_ns(&ptp_data->tstamp2);
342 t3 = timespec64_to_ns(&ptp_data->tstamp3);
343 t4 = timespec64_to_ns(&ptp_data->tstamp4);
345 delta = -((int64_t)((t2 - t1) - (t4 - t3))) / 2;
351 * Parse the PTP SYNC message.
354 parse_sync(struct ptpv2_data_slave_ordinary *ptp_data, uint16_t rx_tstamp_idx)
356 struct ptp_header *ptp_hdr;
358 ptp_hdr = (struct ptp_header *)(rte_pktmbuf_mtod(ptp_data->m, char *)
359 + sizeof(struct ether_hdr));
360 ptp_data->seqID_SYNC = rte_be_to_cpu_16(ptp_hdr->seq_id);
362 if (ptp_data->ptpset == 0) {
363 rte_memcpy(&ptp_data->master_clock_id,
364 &ptp_hdr->source_port_id.clock_id,
365 sizeof(struct clock_id));
366 ptp_data->ptpset = 1;
369 if (memcmp(&ptp_hdr->source_port_id.clock_id,
370 &ptp_hdr->source_port_id.clock_id,
371 sizeof(struct clock_id)) == 0) {
373 if (ptp_data->ptpset == 1)
374 rte_eth_timesync_read_rx_timestamp(ptp_data->portid,
375 &ptp_data->tstamp2, rx_tstamp_idx);
381 * Parse the PTP FOLLOWUP message and send DELAY_REQ to the master clock.
384 parse_fup(struct ptpv2_data_slave_ordinary *ptp_data)
386 struct ether_hdr *eth_hdr;
387 struct ptp_header *ptp_hdr;
388 struct clock_id *client_clkid;
389 struct ptp_message *ptp_msg;
390 struct rte_mbuf *created_pkt;
391 struct tstamp *origin_tstamp;
392 struct ether_addr eth_multicast = ether_multicast;
395 struct rte_mbuf *m = ptp_data->m;
397 eth_hdr = rte_pktmbuf_mtod(m, struct ether_hdr *);
398 ptp_hdr = (struct ptp_header *)(rte_pktmbuf_mtod(m, char *)
399 + sizeof(struct ether_hdr));
400 if (memcmp(&ptp_data->master_clock_id,
401 &ptp_hdr->source_port_id.clock_id,
402 sizeof(struct clock_id)) != 0)
405 ptp_data->seqID_FOLLOWUP = rte_be_to_cpu_16(ptp_hdr->seq_id);
406 ptp_msg = (struct ptp_message *) (rte_pktmbuf_mtod(m, char *) +
407 sizeof(struct ether_hdr));
409 origin_tstamp = &ptp_msg->follow_up.precise_origin_tstamp;
410 ptp_data->tstamp1.tv_nsec = ntohl(origin_tstamp->ns);
411 ptp_data->tstamp1.tv_sec =
412 ((uint64_t)ntohl(origin_tstamp->sec_lsb)) |
413 (((uint64_t)ntohs(origin_tstamp->sec_msb)) << 32);
415 if (ptp_data->seqID_FOLLOWUP == ptp_data->seqID_SYNC) {
417 created_pkt = rte_pktmbuf_alloc(mbuf_pool);
418 pkt_size = sizeof(struct ether_hdr) +
419 sizeof(struct ptp_message);
420 created_pkt->data_len = pkt_size;
421 created_pkt->pkt_len = pkt_size;
422 eth_hdr = rte_pktmbuf_mtod(created_pkt, struct ether_hdr *);
423 rte_eth_macaddr_get(ptp_data->portid, ð_hdr->s_addr);
425 /* Set multicast address 01-1B-19-00-00-00. */
426 ether_addr_copy(ð_multicast, ð_hdr->d_addr);
428 eth_hdr->ether_type = htons(PTP_PROTOCOL);
429 ptp_msg = (struct ptp_message *)
430 (rte_pktmbuf_mtod(created_pkt, char *) +
431 sizeof(struct ether_hdr));
433 ptp_msg->delay_req.hdr.seq_id = htons(ptp_data->seqID_SYNC);
434 ptp_msg->delay_req.hdr.msg_type = DELAY_REQ;
435 ptp_msg->delay_req.hdr.ver = 2;
436 ptp_msg->delay_req.hdr.control = 1;
437 ptp_msg->delay_req.hdr.log_message_interval = 127;
439 /* Set up clock id. */
441 &ptp_msg->delay_req.hdr.source_port_id.clock_id;
443 client_clkid->id[0] = eth_hdr->s_addr.addr_bytes[0];
444 client_clkid->id[1] = eth_hdr->s_addr.addr_bytes[1];
445 client_clkid->id[2] = eth_hdr->s_addr.addr_bytes[2];
446 client_clkid->id[3] = 0xFF;
447 client_clkid->id[4] = 0xFE;
448 client_clkid->id[5] = eth_hdr->s_addr.addr_bytes[3];
449 client_clkid->id[6] = eth_hdr->s_addr.addr_bytes[4];
450 client_clkid->id[7] = eth_hdr->s_addr.addr_bytes[5];
452 rte_memcpy(&ptp_data->client_clock_id,
454 sizeof(struct clock_id));
456 /* Enable flag for hardware timestamping. */
457 created_pkt->ol_flags |= PKT_TX_IEEE1588_TMST;
459 /*Read value from NIC to prevent latching with old value. */
460 rte_eth_timesync_read_tx_timestamp(ptp_data->portid,
463 /* Transmit the packet. */
464 rte_eth_tx_burst(ptp_data->portid, 0, &created_pkt, 1);
467 ptp_data->tstamp3.tv_nsec = 0;
468 ptp_data->tstamp3.tv_sec = 0;
470 /* Wait at least 1 us to read TX timestamp. */
471 while ((rte_eth_timesync_read_tx_timestamp(ptp_data->portid,
472 &ptp_data->tstamp3) < 0) && (wait_us < 1000)) {
480 * Update the kernel time with the difference between it and the current NIC
484 update_kernel_time(void)
487 struct timespec net_time, sys_time;
489 clock_gettime(CLOCK_REALTIME, &sys_time);
490 rte_eth_timesync_read_time(ptp_data.current_ptp_port, &net_time);
492 nsec = (int64_t)timespec64_to_ns(&net_time) -
493 (int64_t)timespec64_to_ns(&sys_time);
495 ptp_data.new_adj = ns_to_timeval(nsec);
498 * If difference between kernel time and system time in NIC is too big
499 * (more than +/- 20 microseconds), use clock_settime to set directly
500 * the kernel time, as adjtime is better for small adjustments (takes
501 * longer to adjust the time).
504 if (nsec > KERNEL_TIME_ADJUST_LIMIT || nsec < -KERNEL_TIME_ADJUST_LIMIT)
505 clock_settime(CLOCK_REALTIME, &net_time);
507 adjtime(&ptp_data.new_adj, 0);
513 * Parse the DELAY_RESP message.
516 parse_drsp(struct ptpv2_data_slave_ordinary *ptp_data)
518 struct rte_mbuf *m = ptp_data->m;
519 struct ptp_message *ptp_msg;
520 struct tstamp *rx_tstamp;
523 ptp_msg = (struct ptp_message *) (rte_pktmbuf_mtod(m, char *) +
524 sizeof(struct ether_hdr));
525 seq_id = rte_be_to_cpu_16(ptp_msg->delay_resp.hdr.seq_id);
526 if (memcmp(&ptp_data->client_clock_id,
527 &ptp_msg->delay_resp.req_port_id.clock_id,
528 sizeof(struct clock_id)) == 0) {
529 if (seq_id == ptp_data->seqID_FOLLOWUP) {
530 rx_tstamp = &ptp_msg->delay_resp.rx_tstamp;
531 ptp_data->tstamp4.tv_nsec = ntohl(rx_tstamp->ns);
532 ptp_data->tstamp4.tv_sec =
533 ((uint64_t)ntohl(rx_tstamp->sec_lsb)) |
534 (((uint64_t)ntohs(rx_tstamp->sec_msb)) << 32);
536 /* Evaluate the delta for adjustment. */
537 ptp_data->delta = delta_eval(ptp_data);
539 rte_eth_timesync_adjust_time(ptp_data->portid,
542 ptp_data->current_ptp_port = ptp_data->portid;
544 /* Update kernel time if enabled in app parameters. */
545 if (ptp_data->kernel_time_set == 1)
546 update_kernel_time();
554 /* This function processes PTP packets, implementing slave PTP IEEE1588 L2
558 parse_ptp_frames(uint16_t portid, struct rte_mbuf *m) {
559 struct ptp_header *ptp_hdr;
560 struct ether_hdr *eth_hdr;
563 eth_hdr = rte_pktmbuf_mtod(m, struct ether_hdr *);
564 eth_type = rte_be_to_cpu_16(eth_hdr->ether_type);
566 if (eth_type == PTP_PROTOCOL) {
568 ptp_data.portid = portid;
569 ptp_hdr = (struct ptp_header *)(rte_pktmbuf_mtod(m, char *)
570 + sizeof(struct ether_hdr));
572 switch (ptp_hdr->msg_type) {
574 parse_sync(&ptp_data, m->timesync);
577 parse_fup(&ptp_data);
580 parse_drsp(&ptp_data);
581 print_clock_info(&ptp_data);
590 * The lcore main. This is the main thread that does the work, reading from an
591 * input port and writing to an output port.
593 static __attribute__((noreturn)) void
601 * Check that the port is on the same NUMA node as the polling thread
602 * for best performance.
604 printf("\nCore %u Waiting for SYNC packets. [Ctrl+C to quit]\n",
607 /* Run until the application is quit or killed. */
610 /* Read packet from RX queues. */
611 for (portid = 0; portid < ptp_enabled_port_nb; portid++) {
613 portid = ptp_enabled_ports[portid];
614 nb_rx = rte_eth_rx_burst(portid, 0, &m, 1);
616 if (likely(nb_rx == 0))
619 if (m->ol_flags & PKT_RX_IEEE1588_PTP)
620 parse_ptp_frames(portid, m);
628 print_usage(const char *prgname)
630 printf("%s [EAL options] -- -p PORTMASK -T VALUE\n"
631 " -T VALUE: 0 - Disable, 1 - Enable Linux Clock"
632 " Synchronization (0 default)\n"
633 " -p PORTMASK: hexadecimal bitmask of ports to configure\n",
638 ptp_parse_portmask(const char *portmask)
643 /* Parse the hexadecimal string. */
644 pm = strtoul(portmask, &end, 16);
646 if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
656 parse_ptp_kernel(const char *param)
661 /* Parse the hexadecimal string. */
662 pm = strtoul(param, &end, 16);
664 if ((param[0] == '\0') || (end == NULL) || (*end != '\0'))
672 /* Parse the commandline arguments. */
674 ptp_parse_args(int argc, char **argv)
679 char *prgname = argv[0];
680 static struct option lgopts[] = { {NULL, 0, 0, 0} };
684 while ((opt = getopt_long(argc, argvopt, "p:T:",
685 lgopts, &option_index)) != EOF) {
691 ptp_enabled_port_mask = ptp_parse_portmask(optarg);
692 if (ptp_enabled_port_mask == 0) {
693 printf("invalid portmask\n");
694 print_usage(prgname);
698 /* Time synchronization. */
700 ret = parse_ptp_kernel(optarg);
702 print_usage(prgname);
706 ptp_data.kernel_time_set = ret;
710 print_usage(prgname);
715 argv[optind-1] = prgname;
717 optind = 1; /* Reset getopt lib. */
723 * The main function, which does initialization and calls the per-lcore
727 main(int argc, char *argv[])
733 /* Initialize the Environment Abstraction Layer (EAL). */
734 int ret = rte_eal_init(argc, argv);
737 rte_exit(EXIT_FAILURE, "Error with EAL initialization\n");
739 memset(&ptp_data, '\0', sizeof(struct ptpv2_data_slave_ordinary));
744 ret = ptp_parse_args(argc, argv);
746 rte_exit(EXIT_FAILURE, "Error with PTP initialization\n");
748 /* Check that there is an even number of ports to send/receive on. */
749 nb_ports = rte_eth_dev_count();
751 /* Creates a new mempool in memory to hold the mbufs. */
752 mbuf_pool = rte_pktmbuf_pool_create("MBUF_POOL", NUM_MBUFS * nb_ports,
753 MBUF_CACHE_SIZE, 0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id());
755 if (mbuf_pool == NULL)
756 rte_exit(EXIT_FAILURE, "Cannot create mbuf pool\n");
758 /* Initialize all ports. */
759 for (portid = 0; portid < nb_ports; portid++) {
760 if ((ptp_enabled_port_mask & (1 << portid)) != 0) {
761 if (port_init(portid, mbuf_pool) == 0) {
762 ptp_enabled_ports[ptp_enabled_port_nb] = portid;
763 ptp_enabled_port_nb++;
765 rte_exit(EXIT_FAILURE,
766 "Cannot init port %"PRIu8 "\n",
770 printf("Skipping disabled port %u\n", portid);
773 if (ptp_enabled_port_nb == 0) {
774 rte_exit(EXIT_FAILURE,
775 "All available ports are disabled."
776 " Please set portmask.\n");
779 if (rte_lcore_count() > 1)
780 printf("\nWARNING: Too many lcores enabled. Only 1 used.\n");
782 /* Call lcore_main on the master core only. */