xref: /dpdk/examples/ptpclient/ptpclient.c (revision 7f2a987ca852a45bdb4520edc7ad7e02c4efd269)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2015 Intel Corporation
3  */
4 
5 /*
6  * This application is a simple Layer 2 PTP v2 client. It shows delta values
7  * which are used to synchronize the PHC clock. if the "-T 1" parameter is
8  * passed to the application the Linux kernel clock is also synchronized.
9  */
10 
11 #include <stdint.h>
12 #include <stdlib.h>
13 #include <inttypes.h>
14 #include <rte_eal.h>
15 #include <rte_ethdev.h>
16 #include <rte_cycles.h>
17 #include <rte_lcore.h>
18 #include <rte_mbuf.h>
19 #include <rte_ip.h>
20 #include <limits.h>
21 #include <sys/time.h>
22 #include <getopt.h>
23 #include <signal.h>
24 
25 static volatile bool force_quit;
26 
27 #define RX_RING_SIZE 1024
28 #define TX_RING_SIZE 1024
29 
30 #define NUM_MBUFS            8191
31 #define MBUF_CACHE_SIZE       250
32 
33 /* Values for the PTP messageType field. */
34 #define SYNC                  0x0
35 #define DELAY_REQ             0x1
36 #define PDELAY_REQ            0x2
37 #define PDELAY_RESP           0x3
38 #define FOLLOW_UP             0x8
39 #define DELAY_RESP            0x9
40 #define PDELAY_RESP_FOLLOW_UP 0xA
41 #define ANNOUNCE              0xB
42 #define SIGNALING             0xC
43 #define MANAGEMENT            0xD
44 
45 #define NSEC_PER_SEC        1000000000L
46 #define KERNEL_TIME_ADJUST_LIMIT  20000
47 #define PTP_PROTOCOL             0x88F7
48 
49 struct rte_mempool *mbuf_pool;
50 uint32_t ptp_enabled_port_mask;
51 uint8_t ptp_enabled_port_nb;
52 static uint8_t ptp_enabled_ports[RTE_MAX_ETHPORTS];
53 
54 static const struct rte_ether_addr ether_multicast = {
55 	.addr_bytes = {0x01, 0x1b, 0x19, 0x0, 0x0, 0x0}
56 };
57 
58 /* Structs used for PTP handling. */
59 struct __rte_packed_begin tstamp {
60 	uint16_t   sec_msb;
61 	uint32_t   sec_lsb;
62 	uint32_t   ns;
63 } __rte_packed_end;
64 
65 struct clock_id {
66 	uint8_t id[8];
67 };
68 
69 struct __rte_packed_begin port_id {
70 	struct clock_id        clock_id;
71 	uint16_t               port_number;
72 } __rte_packed_end;
73 
74 struct __rte_packed_begin ptp_header {
75 	uint8_t              msg_type;
76 	uint8_t              ver;
77 	uint16_t             message_length;
78 	uint8_t              domain_number;
79 	uint8_t              reserved1;
80 	uint8_t              flag_field[2];
81 	int64_t              correction;
82 	uint32_t             reserved2;
83 	struct port_id       source_port_id;
84 	uint16_t             seq_id;
85 	uint8_t              control;
86 	int8_t               log_message_interval;
87 } __rte_packed_end;
88 
89 struct __rte_packed_begin sync_msg {
90 	struct ptp_header   hdr;
91 	struct tstamp       origin_tstamp;
92 } __rte_packed_end;
93 
94 struct __rte_packed_begin follow_up_msg {
95 	struct ptp_header   hdr;
96 	struct tstamp       precise_origin_tstamp;
97 	uint8_t             suffix[];
98 } __rte_packed_end;
99 
100 struct __rte_packed_begin delay_req_msg {
101 	struct ptp_header   hdr;
102 	struct tstamp       origin_tstamp;
103 } __rte_packed_end;
104 
105 struct __rte_packed_begin delay_resp_msg {
106 	struct ptp_header    hdr;
107 	struct tstamp        rx_tstamp;
108 	struct port_id       req_port_id;
109 	uint8_t              suffix[];
110 } __rte_packed_end;
111 
112 struct ptp_message {
113 	union __rte_packed_begin {
114 		struct ptp_header          header;
115 		struct sync_msg            sync;
116 		struct delay_req_msg       delay_req;
117 		struct follow_up_msg       follow_up;
118 		struct delay_resp_msg      delay_resp;
119 	} __rte_packed_end;
120 };
121 
122 struct ptpv2_time_receiver_ordinary {
123 	struct rte_mbuf *m;
124 	struct timespec tstamp1;
125 	struct timespec tstamp2;
126 	struct timespec tstamp3;
127 	struct timespec tstamp4;
128 	struct clock_id client_clock_id;
129 	struct clock_id transmitter_clock_id;
130 	struct timeval new_adj;
131 	int64_t delta;
132 	uint16_t portid;
133 	uint16_t seqID_SYNC;
134 	uint16_t seqID_FOLLOWUP;
135 	uint8_t ptpset;
136 	uint8_t kernel_time_set;
137 	uint16_t current_ptp_port;
138 };
139 
140 static struct ptpv2_time_receiver_ordinary ptp_data;
141 
142 static inline uint64_t timespec64_to_ns(const struct timespec *ts)
143 {
144 	return ((uint64_t) ts->tv_sec * NSEC_PER_SEC) + ts->tv_nsec;
145 }
146 
147 static struct timeval
148 ns_to_timeval(int64_t nsec)
149 {
150 	struct timespec t_spec = {0, 0};
151 	struct timeval t_eval = {0, 0};
152 	int32_t rem;
153 
154 	if (nsec == 0)
155 		return t_eval;
156 	rem = nsec % NSEC_PER_SEC;
157 	t_spec.tv_sec = nsec / NSEC_PER_SEC;
158 
159 	if (rem < 0) {
160 		t_spec.tv_sec--;
161 		rem += NSEC_PER_SEC;
162 	}
163 
164 	t_spec.tv_nsec = rem;
165 	t_eval.tv_sec = t_spec.tv_sec;
166 	t_eval.tv_usec = t_spec.tv_nsec / 1000;
167 
168 	return t_eval;
169 }
170 
171 /*
172  * Initializes a given port using global settings and with the RX buffers
173  * coming from the mbuf_pool passed as a parameter.
174  */
175 static inline int
176 port_init(uint16_t port, struct rte_mempool *mbuf_pool)
177 {
178 	struct rte_eth_dev_info dev_info;
179 	struct rte_eth_conf port_conf;
180 	const uint16_t rx_rings = 1;
181 	const uint16_t tx_rings = 1;
182 	int retval;
183 	uint16_t q;
184 	uint16_t nb_rxd = RX_RING_SIZE;
185 	uint16_t nb_txd = TX_RING_SIZE;
186 
187 	if (!rte_eth_dev_is_valid_port(port))
188 		return -1;
189 
190 	memset(&port_conf, 0, sizeof(struct rte_eth_conf));
191 
192 	retval = rte_eth_dev_info_get(port, &dev_info);
193 	if (retval != 0) {
194 		printf("Error during getting device (port %u) info: %s\n",
195 				port, strerror(-retval));
196 
197 		return retval;
198 	}
199 
200 	if (dev_info.rx_offload_capa & RTE_ETH_RX_OFFLOAD_TIMESTAMP)
201 		port_conf.rxmode.offloads |= RTE_ETH_RX_OFFLOAD_TIMESTAMP;
202 
203 	if (dev_info.tx_offload_capa & RTE_ETH_TX_OFFLOAD_MBUF_FAST_FREE)
204 		port_conf.txmode.offloads |=
205 			RTE_ETH_TX_OFFLOAD_MBUF_FAST_FREE;
206 	/* Force full Tx path in the driver, required for IEEE1588 */
207 	port_conf.txmode.offloads |= RTE_ETH_TX_OFFLOAD_MULTI_SEGS;
208 
209 	/* Configure the Ethernet device. */
210 	retval = rte_eth_dev_configure(port, rx_rings, tx_rings, &port_conf);
211 	if (retval != 0)
212 		return retval;
213 
214 	retval = rte_eth_dev_adjust_nb_rx_tx_desc(port, &nb_rxd, &nb_txd);
215 	if (retval != 0)
216 		return retval;
217 
218 	/* Allocate and set up 1 RX queue per Ethernet port. */
219 	for (q = 0; q < rx_rings; q++) {
220 		struct rte_eth_rxconf *rxconf;
221 
222 		rxconf = &dev_info.default_rxconf;
223 		rxconf->offloads = port_conf.rxmode.offloads;
224 
225 		retval = rte_eth_rx_queue_setup(port, q, nb_rxd,
226 				rte_eth_dev_socket_id(port), rxconf, mbuf_pool);
227 
228 		if (retval < 0)
229 			return retval;
230 	}
231 
232 	/* Allocate and set up 1 TX queue per Ethernet port. */
233 	for (q = 0; q < tx_rings; q++) {
234 		struct rte_eth_txconf *txconf;
235 
236 		txconf = &dev_info.default_txconf;
237 		txconf->offloads = port_conf.txmode.offloads;
238 
239 		retval = rte_eth_tx_queue_setup(port, q, nb_txd,
240 				rte_eth_dev_socket_id(port), txconf);
241 		if (retval < 0)
242 			return retval;
243 	}
244 
245 	/* Start the Ethernet port. */
246 	retval = rte_eth_dev_start(port);
247 	if (retval < 0)
248 		return retval;
249 
250 	/* Enable timesync timestamping for the Ethernet device */
251 	retval = rte_eth_timesync_enable(port);
252 	if (retval < 0) {
253 		printf("Timesync enable failed: %d\n", retval);
254 		return retval;
255 	}
256 
257 	/* Enable RX in promiscuous mode for the Ethernet device. */
258 	retval = rte_eth_promiscuous_enable(port);
259 	if (retval != 0) {
260 		printf("Promiscuous mode enable failed: %s\n",
261 			rte_strerror(-retval));
262 		return retval;
263 	}
264 
265 	return 0;
266 }
267 
268 static void
269 print_clock_info(struct ptpv2_time_receiver_ordinary *ptp_data)
270 {
271 	int64_t nsec;
272 	struct timespec net_time, sys_time;
273 
274 	printf("time transmitter clock id: %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
275 		ptp_data->transmitter_clock_id.id[0],
276 		ptp_data->transmitter_clock_id.id[1],
277 		ptp_data->transmitter_clock_id.id[2],
278 		ptp_data->transmitter_clock_id.id[3],
279 		ptp_data->transmitter_clock_id.id[4],
280 		ptp_data->transmitter_clock_id.id[5],
281 		ptp_data->transmitter_clock_id.id[6],
282 		ptp_data->transmitter_clock_id.id[7]);
283 
284 	printf("\nT2 - time receiver clock.  %lds %ldns",
285 			(ptp_data->tstamp2.tv_sec),
286 			(ptp_data->tstamp2.tv_nsec));
287 
288 	printf("\nT1 - time transmitter clock.  %lds %ldns ",
289 			ptp_data->tstamp1.tv_sec,
290 			(ptp_data->tstamp1.tv_nsec));
291 
292 	printf("\nT3 - time receiver clock.  %lds %ldns",
293 			ptp_data->tstamp3.tv_sec,
294 			(ptp_data->tstamp3.tv_nsec));
295 
296 	printf("\nT4 - time transmitter clock.  %lds %ldns\n",
297 			ptp_data->tstamp4.tv_sec,
298 			(ptp_data->tstamp4.tv_nsec));
299 
300 	printf("\nDelta between transmitter and receiver clocks:%"PRId64"ns\n",
301 		ptp_data->delta);
302 
303 	clock_gettime(CLOCK_REALTIME, &sys_time);
304 	rte_eth_timesync_read_time(ptp_data->current_ptp_port,
305 					&net_time);
306 
307 	time_t ts = net_time.tv_sec;
308 
309 	printf("\n\nComparison between Linux kernel Time and PTP:");
310 
311 	printf("\nCurrent PTP Time: %.24s %.9ld ns",
312 		ctime(&ts), net_time.tv_nsec);
313 
314 	nsec = (int64_t)timespec64_to_ns(&net_time) -
315 		(int64_t)timespec64_to_ns(&sys_time);
316 	ptp_data->new_adj = ns_to_timeval(nsec);
317 
318 	gettimeofday(&ptp_data->new_adj, NULL);
319 
320 	time_t tp = ptp_data->new_adj.tv_sec;
321 
322 	printf("\nCurrent SYS Time: %.24s %.6ld ns",
323 		ctime(&tp), ptp_data->new_adj.tv_usec);
324 
325 	printf("\nDelta between PTP and Linux Kernel time:%"PRId64"ns\n",
326 		nsec);
327 
328 	printf("[Ctrl+C to quit]\n");
329 
330 	/* Clear screen and put cursor in column 1, row 1 */
331 	printf("\033[2J\033[1;1H");
332 }
333 
334 static int64_t
335 delta_eval(struct ptpv2_time_receiver_ordinary *ptp_data)
336 {
337 	int64_t delta;
338 	uint64_t t1 = 0;
339 	uint64_t t2 = 0;
340 	uint64_t t3 = 0;
341 	uint64_t t4 = 0;
342 
343 	t1 = timespec64_to_ns(&ptp_data->tstamp1);
344 	t2 = timespec64_to_ns(&ptp_data->tstamp2);
345 	t3 = timespec64_to_ns(&ptp_data->tstamp3);
346 	t4 = timespec64_to_ns(&ptp_data->tstamp4);
347 
348 	delta = -((int64_t)((t2 - t1) - (t4 - t3))) / 2;
349 
350 	return delta;
351 }
352 
353 /*
354  * Parse the PTP SYNC message.
355  */
356 static void
357 parse_sync(struct ptpv2_time_receiver_ordinary *ptp_data, uint16_t rx_tstamp_idx)
358 {
359 	struct ptp_header *ptp_hdr;
360 
361 	ptp_hdr = rte_pktmbuf_mtod_offset(ptp_data->m, struct ptp_header *,
362 					  sizeof(struct rte_ether_hdr));
363 	ptp_data->seqID_SYNC = rte_be_to_cpu_16(ptp_hdr->seq_id);
364 
365 	if (ptp_data->ptpset == 0) {
366 		rte_memcpy(&ptp_data->transmitter_clock_id,
367 				&ptp_hdr->source_port_id.clock_id,
368 				sizeof(struct clock_id));
369 		ptp_data->ptpset = 1;
370 	}
371 
372 	if (memcmp(&ptp_hdr->source_port_id.clock_id,
373 			&ptp_hdr->source_port_id.clock_id,
374 			sizeof(struct clock_id)) == 0) {
375 
376 		if (ptp_data->ptpset == 1)
377 			rte_eth_timesync_read_rx_timestamp(ptp_data->portid,
378 					&ptp_data->tstamp2, rx_tstamp_idx);
379 	}
380 
381 }
382 
383 /*
384  * Parse the PTP FOLLOWUP message and send DELAY_REQ to the main clock.
385  */
386 static void
387 parse_fup(struct ptpv2_time_receiver_ordinary *ptp_data)
388 {
389 	struct rte_ether_hdr *eth_hdr;
390 	struct rte_ether_addr eth_addr;
391 	struct ptp_header *ptp_hdr;
392 	struct clock_id *client_clkid;
393 	struct ptp_message *ptp_msg;
394 	struct delay_req_msg *req_msg;
395 	struct rte_mbuf *created_pkt;
396 	struct tstamp *origin_tstamp;
397 	struct rte_ether_addr eth_multicast = ether_multicast;
398 	size_t pkt_size;
399 	int wait_us;
400 	struct rte_mbuf *m = ptp_data->m;
401 	int ret;
402 
403 	eth_hdr = rte_pktmbuf_mtod(m, struct rte_ether_hdr *);
404 	ptp_hdr = rte_pktmbuf_mtod_offset(m, struct ptp_header *,
405 					  sizeof(struct rte_ether_hdr));
406 	if (memcmp(&ptp_data->transmitter_clock_id,
407 			&ptp_hdr->source_port_id.clock_id,
408 			sizeof(struct clock_id)) != 0)
409 		return;
410 
411 	ptp_data->seqID_FOLLOWUP = rte_be_to_cpu_16(ptp_hdr->seq_id);
412 	ptp_msg = rte_pktmbuf_mtod_offset(m, struct ptp_message *,
413 					  sizeof(struct rte_ether_hdr));
414 
415 	origin_tstamp = &ptp_msg->follow_up.precise_origin_tstamp;
416 	ptp_data->tstamp1.tv_nsec = ntohl(origin_tstamp->ns);
417 	ptp_data->tstamp1.tv_sec =
418 		((uint64_t)ntohl(origin_tstamp->sec_lsb)) |
419 		(((uint64_t)ntohs(origin_tstamp->sec_msb)) << 32);
420 
421 	if (ptp_data->seqID_FOLLOWUP == ptp_data->seqID_SYNC) {
422 		ret = rte_eth_macaddr_get(ptp_data->portid, &eth_addr);
423 		if (ret != 0) {
424 			printf("\nCore %u: port %u failed to get MAC address: %s\n",
425 				rte_lcore_id(), ptp_data->portid,
426 				rte_strerror(-ret));
427 			return;
428 		}
429 
430 		created_pkt = rte_pktmbuf_alloc(mbuf_pool);
431 		pkt_size = sizeof(struct rte_ether_hdr) +
432 			sizeof(struct delay_req_msg);
433 
434 		if (rte_pktmbuf_append(created_pkt, pkt_size) == NULL) {
435 			rte_pktmbuf_free(created_pkt);
436 			return;
437 		}
438 		created_pkt->data_len = pkt_size;
439 		created_pkt->pkt_len = pkt_size;
440 		eth_hdr = rte_pktmbuf_mtod(created_pkt, struct rte_ether_hdr *);
441 		rte_ether_addr_copy(&eth_addr, &eth_hdr->src_addr);
442 
443 		/* Set multicast address 01-1B-19-00-00-00. */
444 		rte_ether_addr_copy(&eth_multicast, &eth_hdr->dst_addr);
445 
446 		eth_hdr->ether_type = htons(PTP_PROTOCOL);
447 		req_msg = rte_pktmbuf_mtod_offset(created_pkt,
448 			struct delay_req_msg *, sizeof(struct
449 			rte_ether_hdr));
450 
451 		req_msg->hdr.seq_id = htons(ptp_data->seqID_SYNC);
452 		req_msg->hdr.msg_type = DELAY_REQ;
453 		req_msg->hdr.ver = 2;
454 		req_msg->hdr.control = 1;
455 		req_msg->hdr.log_message_interval = 127;
456 		req_msg->hdr.message_length =
457 			htons(sizeof(struct delay_req_msg));
458 		req_msg->hdr.domain_number = ptp_hdr->domain_number;
459 
460 		/* Set up clock id. */
461 		client_clkid =
462 			&req_msg->hdr.source_port_id.clock_id;
463 
464 		client_clkid->id[0] = eth_hdr->src_addr.addr_bytes[0];
465 		client_clkid->id[1] = eth_hdr->src_addr.addr_bytes[1];
466 		client_clkid->id[2] = eth_hdr->src_addr.addr_bytes[2];
467 		client_clkid->id[3] = 0xFF;
468 		client_clkid->id[4] = 0xFE;
469 		client_clkid->id[5] = eth_hdr->src_addr.addr_bytes[3];
470 		client_clkid->id[6] = eth_hdr->src_addr.addr_bytes[4];
471 		client_clkid->id[7] = eth_hdr->src_addr.addr_bytes[5];
472 
473 		rte_memcpy(&ptp_data->client_clock_id,
474 			   client_clkid,
475 			   sizeof(struct clock_id));
476 
477 		/* Enable flag for hardware timestamping. */
478 		created_pkt->ol_flags |= RTE_MBUF_F_TX_IEEE1588_TMST;
479 
480 		/*Read value from NIC to prevent latching with old value. */
481 		rte_eth_timesync_read_tx_timestamp(ptp_data->portid,
482 				&ptp_data->tstamp3);
483 
484 		/* Transmit the packet. */
485 		rte_eth_tx_burst(ptp_data->portid, 0, &created_pkt, 1);
486 
487 		wait_us = 0;
488 		ptp_data->tstamp3.tv_nsec = 0;
489 		ptp_data->tstamp3.tv_sec = 0;
490 
491 		/* Wait at least 1 us to read TX timestamp. */
492 		while ((rte_eth_timesync_read_tx_timestamp(ptp_data->portid,
493 				&ptp_data->tstamp3) < 0) && (wait_us < 1000)) {
494 			rte_delay_us(1);
495 			wait_us++;
496 		}
497 	}
498 }
499 
500 /*
501  * Update the kernel time with the difference between it and the current NIC
502  * time.
503  */
504 static inline void
505 update_kernel_time(void)
506 {
507 	int64_t nsec;
508 	struct timespec net_time, sys_time;
509 
510 	clock_gettime(CLOCK_REALTIME, &sys_time);
511 	rte_eth_timesync_read_time(ptp_data.current_ptp_port, &net_time);
512 
513 	nsec = (int64_t)timespec64_to_ns(&net_time) -
514 	       (int64_t)timespec64_to_ns(&sys_time);
515 
516 	ptp_data.new_adj = ns_to_timeval(nsec);
517 
518 	/*
519 	 * If difference between kernel time and system time in NIC is too big
520 	 * (more than +/- 20 microseconds), use clock_settime to set directly
521 	 * the kernel time, as adjtime is better for small adjustments (takes
522 	 * longer to adjust the time).
523 	 */
524 
525 	if (nsec > KERNEL_TIME_ADJUST_LIMIT || nsec < -KERNEL_TIME_ADJUST_LIMIT)
526 		clock_settime(CLOCK_REALTIME, &net_time);
527 	else
528 		adjtime(&ptp_data.new_adj, 0);
529 
530 
531 }
532 
533 /*
534  * Parse the DELAY_RESP message.
535  */
536 static void
537 parse_drsp(struct ptpv2_time_receiver_ordinary *ptp_data)
538 {
539 	struct rte_mbuf *m = ptp_data->m;
540 	struct ptp_message *ptp_msg;
541 	struct tstamp *rx_tstamp;
542 	uint16_t seq_id;
543 
544 	ptp_msg = rte_pktmbuf_mtod_offset(m, struct ptp_message *,
545 					  sizeof(struct rte_ether_hdr));
546 	seq_id = rte_be_to_cpu_16(ptp_msg->delay_resp.hdr.seq_id);
547 	if (memcmp(&ptp_data->client_clock_id,
548 		   &ptp_msg->delay_resp.req_port_id.clock_id,
549 		   sizeof(struct clock_id)) == 0) {
550 		if (seq_id == ptp_data->seqID_FOLLOWUP) {
551 			rx_tstamp = &ptp_msg->delay_resp.rx_tstamp;
552 			ptp_data->tstamp4.tv_nsec = ntohl(rx_tstamp->ns);
553 			ptp_data->tstamp4.tv_sec =
554 				((uint64_t)ntohl(rx_tstamp->sec_lsb)) |
555 				(((uint64_t)ntohs(rx_tstamp->sec_msb)) << 32);
556 
557 			/* Evaluate the delta for adjustment. */
558 			ptp_data->delta = delta_eval(ptp_data);
559 
560 			rte_eth_timesync_adjust_time(ptp_data->portid,
561 							ptp_data->delta);
562 
563 			ptp_data->current_ptp_port = ptp_data->portid;
564 
565 			/* Update kernel time if enabled in app parameters. */
566 			if (ptp_data->kernel_time_set == 1)
567 				update_kernel_time();
568 
569 
570 
571 		}
572 	}
573 }
574 
575 /* This function processes PTP packets, implementing time receiver PTP IEEE1588 L2
576  * functionality.
577  */
578 
579 /* Parse ptp frames. 8< */
580 static void
581 parse_ptp_frames(uint16_t portid, struct rte_mbuf *m) {
582 	struct ptp_header *ptp_hdr;
583 	struct rte_ether_hdr *eth_hdr;
584 	uint16_t eth_type;
585 
586 	eth_hdr = rte_pktmbuf_mtod(m, struct rte_ether_hdr *);
587 	eth_type = rte_be_to_cpu_16(eth_hdr->ether_type);
588 
589 	if (eth_type == PTP_PROTOCOL) {
590 		ptp_data.m = m;
591 		ptp_data.portid = portid;
592 		ptp_hdr = rte_pktmbuf_mtod_offset(m, struct ptp_header *,
593 						  sizeof(struct rte_ether_hdr));
594 
595 		switch (ptp_hdr->msg_type) {
596 		case SYNC:
597 			parse_sync(&ptp_data, m->timesync);
598 			break;
599 		case FOLLOW_UP:
600 			parse_fup(&ptp_data);
601 			break;
602 		case DELAY_RESP:
603 			parse_drsp(&ptp_data);
604 			print_clock_info(&ptp_data);
605 			break;
606 		default:
607 			break;
608 		}
609 	}
610 }
611 /* >8 End of function processes PTP packets. */
612 
613 /*
614  * The lcore main. This is the main thread that does the work, reading from an
615  * input port and writing to an output port.
616  */
617 static void
618 lcore_main(void)
619 {
620 	uint16_t portid;
621 	unsigned nb_rx;
622 	struct rte_mbuf *m;
623 
624 	printf("\nCore %u Waiting for SYNC packets. [Ctrl+C to quit]\n",
625 			rte_lcore_id());
626 
627 	/* Run until the application is quit or killed. */
628 
629 	while (!force_quit) {
630 		/* Read packet from RX queues. 8< */
631 		for (portid = 0; portid < ptp_enabled_port_nb; portid++) {
632 
633 			portid = ptp_enabled_ports[portid];
634 			nb_rx = rte_eth_rx_burst(portid, 0, &m, 1);
635 
636 			if (likely(nb_rx == 0))
637 				continue;
638 
639 			/* Packet is parsed to determine which type. 8< */
640 			if (m->ol_flags & RTE_MBUF_F_RX_IEEE1588_PTP)
641 				parse_ptp_frames(portid, m);
642 			/* >8 End of packet is parsed to determine which type. */
643 
644 			rte_pktmbuf_free(m);
645 		}
646 		/* >8 End of read packets from RX queues. */
647 	}
648 }
649 
650 static void
651 print_usage(const char *prgname)
652 {
653 	printf("%s [EAL options] -- -p PORTMASK -T VALUE\n"
654 		" -T VALUE: 0 - Disable, 1 - Enable Linux Clock"
655 		" Synchronization (0 default)\n"
656 		" -p PORTMASK: hexadecimal bitmask of ports to configure\n",
657 		prgname);
658 }
659 
660 static int
661 ptp_parse_portmask(const char *portmask)
662 {
663 	char *end = NULL;
664 	unsigned long pm;
665 
666 	/* Parse the hexadecimal string. */
667 	pm = strtoul(portmask, &end, 16);
668 
669 	if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
670 		return 0;
671 
672 	return pm;
673 }
674 
675 static int
676 parse_ptp_kernel(const char *param)
677 {
678 	char *end = NULL;
679 	unsigned long pm;
680 
681 	/* Parse the hexadecimal string. */
682 	pm = strtoul(param, &end, 16);
683 
684 	if ((param[0] == '\0') || (end == NULL) || (*end != '\0'))
685 		return -1;
686 	if (pm == 0)
687 		return 0;
688 
689 	return 1;
690 }
691 
692 /* Parse the commandline arguments. */
693 static int
694 ptp_parse_args(int argc, char **argv)
695 {
696 	int opt, ret;
697 	char **argvopt;
698 	int option_index;
699 	char *prgname = argv[0];
700 	static struct option lgopts[] = { {NULL, 0, 0, 0} };
701 
702 	argvopt = argv;
703 
704 	while ((opt = getopt_long(argc, argvopt, "p:T:",
705 				  lgopts, &option_index)) != EOF) {
706 
707 		switch (opt) {
708 
709 		/* Portmask. */
710 		case 'p':
711 			ptp_enabled_port_mask = ptp_parse_portmask(optarg);
712 			if (ptp_enabled_port_mask == 0) {
713 				printf("invalid portmask\n");
714 				print_usage(prgname);
715 				return -1;
716 			}
717 			break;
718 		/* Time synchronization. */
719 		case 'T':
720 			ret = parse_ptp_kernel(optarg);
721 			if (ret < 0) {
722 				print_usage(prgname);
723 				return -1;
724 			}
725 
726 			ptp_data.kernel_time_set = ret;
727 			break;
728 
729 		default:
730 			print_usage(prgname);
731 			return -1;
732 		}
733 	}
734 
735 	argv[optind-1] = prgname;
736 
737 	optind = 1; /* Reset getopt lib. */
738 
739 	return 0;
740 }
741 
742 static void
743 signal_handler(int signum)
744 {
745 	if (signum == SIGINT || signum == SIGTERM)
746 		force_quit = true;
747 }
748 
749 /*
750  * The main function, which does initialization and calls the per-lcore
751  * functions.
752  */
753 int
754 main(int argc, char *argv[])
755 {
756 	unsigned nb_ports;
757 
758 	uint16_t portid;
759 
760 	/* Initialize the Environment Abstraction Layer (EAL). 8< */
761 	int ret = rte_eal_init(argc, argv);
762 
763 	if (ret < 0)
764 		rte_exit(EXIT_FAILURE, "Error with EAL initialization\n");
765 	/* >8 End of initialization of EAL. */
766 
767 	memset(&ptp_data, 0, sizeof(struct ptpv2_time_receiver_ordinary));
768 
769 	/* Parse specific arguments. 8< */
770 	argc -= ret;
771 	argv += ret;
772 
773 	force_quit = false;
774 	signal(SIGINT, signal_handler);
775 	signal(SIGTERM, signal_handler);
776 
777 	ret = ptp_parse_args(argc, argv);
778 	if (ret < 0)
779 		rte_exit(EXIT_FAILURE, "Error with PTP initialization\n");
780 	/* >8 End of parsing specific arguments. */
781 
782 	/* Check that there is an even number of ports to send/receive on. */
783 	nb_ports = rte_eth_dev_count_avail();
784 
785 	/* Creates a new mempool in memory to hold the mbufs. 8< */
786 	mbuf_pool = rte_pktmbuf_pool_create("MBUF_POOL", NUM_MBUFS * nb_ports,
787 		MBUF_CACHE_SIZE, 0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id());
788 	/* >8 End of a new mempool in memory to hold the mbufs. */
789 
790 	if (mbuf_pool == NULL)
791 		rte_exit(EXIT_FAILURE, "Cannot create mbuf pool\n");
792 
793 	/* Initialize all ports. 8< */
794 	RTE_ETH_FOREACH_DEV(portid) {
795 		if ((ptp_enabled_port_mask & (1 << portid)) != 0) {
796 			if (port_init(portid, mbuf_pool) == 0) {
797 				ptp_enabled_ports[ptp_enabled_port_nb] = portid;
798 				ptp_enabled_port_nb++;
799 			} else {
800 				rte_exit(EXIT_FAILURE,
801 					 "Cannot init port %"PRIu8 "\n",
802 					 portid);
803 			}
804 		} else
805 			printf("Skipping disabled port %u\n", portid);
806 	}
807 	/* >8 End of initialization of all ports. */
808 
809 	if (ptp_enabled_port_nb == 0) {
810 		rte_exit(EXIT_FAILURE,
811 			"All available ports are disabled."
812 			" Please set portmask.\n");
813 	}
814 
815 	if (rte_lcore_count() > 1)
816 		printf("\nWARNING: Too many lcores enabled. Only 1 used.\n");
817 
818 	/* Call lcore_main on the main core only. */
819 	lcore_main();
820 
821 	RTE_ETH_FOREACH_DEV(portid) {
822 		if ((ptp_enabled_port_mask & (1 << portid)) == 0)
823 			continue;
824 
825 		/* Disable timesync timestamping for the Ethernet device */
826 		rte_eth_timesync_disable(portid);
827 
828 		ret = rte_eth_dev_stop(portid);
829 		if (ret != 0)
830 			printf("rte_eth_dev_stop: err=%d, port=%d\n", ret, portid);
831 
832 		rte_eth_dev_close(portid);
833 	}
834 
835 	/* clean up the EAL */
836 	rte_eal_cleanup();
837 
838 	return 0;
839 }
840