xref: /dpdk/examples/ptpclient/ptpclient.c (revision 7917b0d38e92e8b9ec5a870415b791420e10f11a)
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 tstamp {
60 	uint16_t   sec_msb;
61 	uint32_t   sec_lsb;
62 	uint32_t   ns;
63 }  __rte_packed;
64 
65 struct clock_id {
66 	uint8_t id[8];
67 };
68 
69 struct port_id {
70 	struct clock_id        clock_id;
71 	uint16_t               port_number;
72 }  __rte_packed;
73 
74 struct 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;
88 
89 struct sync_msg {
90 	struct ptp_header   hdr;
91 	struct tstamp       origin_tstamp;
92 } __rte_packed;
93 
94 struct follow_up_msg {
95 	struct ptp_header   hdr;
96 	struct tstamp       precise_origin_tstamp;
97 	uint8_t             suffix[];
98 } __rte_packed;
99 
100 struct delay_req_msg {
101 	struct ptp_header   hdr;
102 	struct tstamp       origin_tstamp;
103 } __rte_packed;
104 
105 struct 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;
111 
112 struct ptp_message {
113 	union {
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;
120 };
121 
122 struct ptpv2_data_slave_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 master_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_data_slave_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_data_slave_ordinary *ptp_data)
270 {
271 	int64_t nsec;
272 	struct timespec net_time, sys_time;
273 
274 	printf("Master Clock id: %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
275 		ptp_data->master_clock_id.id[0],
276 		ptp_data->master_clock_id.id[1],
277 		ptp_data->master_clock_id.id[2],
278 		ptp_data->master_clock_id.id[3],
279 		ptp_data->master_clock_id.id[4],
280 		ptp_data->master_clock_id.id[5],
281 		ptp_data->master_clock_id.id[6],
282 		ptp_data->master_clock_id.id[7]);
283 
284 	printf("\nT2 - Slave  Clock.  %lds %ldns",
285 			(ptp_data->tstamp2.tv_sec),
286 			(ptp_data->tstamp2.tv_nsec));
287 
288 	printf("\nT1 - Master Clock.  %lds %ldns ",
289 			ptp_data->tstamp1.tv_sec,
290 			(ptp_data->tstamp1.tv_nsec));
291 
292 	printf("\nT3 - Slave  Clock.  %lds %ldns",
293 			ptp_data->tstamp3.tv_sec,
294 			(ptp_data->tstamp3.tv_nsec));
295 
296 	printf("\nT4 - Master Clock.  %lds %ldns ",
297 			ptp_data->tstamp4.tv_sec,
298 			(ptp_data->tstamp4.tv_nsec));
299 
300 	printf("\nDelta between master and slave 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, &net_time);
305 
306 	time_t ts = net_time.tv_sec;
307 
308 	printf("\n\nComparison between Linux kernel Time and PTP:");
309 
310 	printf("\nCurrent PTP Time: %.24s %.9ld ns",
311 			ctime(&ts), net_time.tv_nsec);
312 
313 	nsec = (int64_t)timespec64_to_ns(&net_time) -
314 			(int64_t)timespec64_to_ns(&sys_time);
315 	ptp_data->new_adj = ns_to_timeval(nsec);
316 
317 	gettimeofday(&ptp_data->new_adj, NULL);
318 
319 	time_t tp = ptp_data->new_adj.tv_sec;
320 
321 	printf("\nCurrent SYS Time: %.24s %.6ld ns",
322 				ctime(&tp), ptp_data->new_adj.tv_usec);
323 
324 	printf("\nDelta between PTP and Linux Kernel time:%"PRId64"ns\n",
325 				nsec);
326 
327 	printf("[Ctrl+C to quit]\n");
328 
329 	/* Clear screen and put cursor in column 1, row 1 */
330 	printf("\033[2J\033[1;1H");
331 }
332 
333 static int64_t
334 delta_eval(struct ptpv2_data_slave_ordinary *ptp_data)
335 {
336 	int64_t delta;
337 	uint64_t t1 = 0;
338 	uint64_t t2 = 0;
339 	uint64_t t3 = 0;
340 	uint64_t t4 = 0;
341 
342 	t1 = timespec64_to_ns(&ptp_data->tstamp1);
343 	t2 = timespec64_to_ns(&ptp_data->tstamp2);
344 	t3 = timespec64_to_ns(&ptp_data->tstamp3);
345 	t4 = timespec64_to_ns(&ptp_data->tstamp4);
346 
347 	delta = -((int64_t)((t2 - t1) - (t4 - t3))) / 2;
348 
349 	return delta;
350 }
351 
352 /*
353  * Parse the PTP SYNC message.
354  */
355 static void
356 parse_sync(struct ptpv2_data_slave_ordinary *ptp_data, uint16_t rx_tstamp_idx)
357 {
358 	struct ptp_header *ptp_hdr;
359 
360 	ptp_hdr = rte_pktmbuf_mtod_offset(ptp_data->m, struct ptp_header *,
361 					  sizeof(struct rte_ether_hdr));
362 	ptp_data->seqID_SYNC = rte_be_to_cpu_16(ptp_hdr->seq_id);
363 
364 	if (ptp_data->ptpset == 0) {
365 		rte_memcpy(&ptp_data->master_clock_id,
366 				&ptp_hdr->source_port_id.clock_id,
367 				sizeof(struct clock_id));
368 		ptp_data->ptpset = 1;
369 	}
370 
371 	if (memcmp(&ptp_hdr->source_port_id.clock_id,
372 			&ptp_hdr->source_port_id.clock_id,
373 			sizeof(struct clock_id)) == 0) {
374 
375 		if (ptp_data->ptpset == 1)
376 			rte_eth_timesync_read_rx_timestamp(ptp_data->portid,
377 					&ptp_data->tstamp2, rx_tstamp_idx);
378 	}
379 
380 }
381 
382 /*
383  * Parse the PTP FOLLOWUP message and send DELAY_REQ to the main clock.
384  */
385 static void
386 parse_fup(struct ptpv2_data_slave_ordinary *ptp_data)
387 {
388 	struct rte_ether_hdr *eth_hdr;
389 	struct rte_ether_addr eth_addr;
390 	struct ptp_header *ptp_hdr;
391 	struct clock_id *client_clkid;
392 	struct ptp_message *ptp_msg;
393 	struct delay_req_msg *req_msg;
394 	struct rte_mbuf *created_pkt;
395 	struct tstamp *origin_tstamp;
396 	struct rte_ether_addr eth_multicast = ether_multicast;
397 	size_t pkt_size;
398 	int wait_us;
399 	struct rte_mbuf *m = ptp_data->m;
400 	int ret;
401 
402 	eth_hdr = rte_pktmbuf_mtod(m, struct rte_ether_hdr *);
403 	ptp_hdr = rte_pktmbuf_mtod_offset(m, struct ptp_header *,
404 					  sizeof(struct rte_ether_hdr));
405 	if (memcmp(&ptp_data->master_clock_id,
406 			&ptp_hdr->source_port_id.clock_id,
407 			sizeof(struct clock_id)) != 0)
408 		return;
409 
410 	ptp_data->seqID_FOLLOWUP = rte_be_to_cpu_16(ptp_hdr->seq_id);
411 	ptp_msg = rte_pktmbuf_mtod_offset(m, struct ptp_message *,
412 					  sizeof(struct rte_ether_hdr));
413 
414 	origin_tstamp = &ptp_msg->follow_up.precise_origin_tstamp;
415 	ptp_data->tstamp1.tv_nsec = ntohl(origin_tstamp->ns);
416 	ptp_data->tstamp1.tv_sec =
417 		((uint64_t)ntohl(origin_tstamp->sec_lsb)) |
418 		(((uint64_t)ntohs(origin_tstamp->sec_msb)) << 32);
419 
420 	if (ptp_data->seqID_FOLLOWUP == ptp_data->seqID_SYNC) {
421 		ret = rte_eth_macaddr_get(ptp_data->portid, &eth_addr);
422 		if (ret != 0) {
423 			printf("\nCore %u: port %u failed to get MAC address: %s\n",
424 				rte_lcore_id(), ptp_data->portid,
425 				rte_strerror(-ret));
426 			return;
427 		}
428 
429 		created_pkt = rte_pktmbuf_alloc(mbuf_pool);
430 		pkt_size = sizeof(struct rte_ether_hdr) +
431 			sizeof(struct delay_req_msg);
432 
433 		if (rte_pktmbuf_append(created_pkt, pkt_size) == NULL) {
434 			rte_pktmbuf_free(created_pkt);
435 			return;
436 		}
437 		created_pkt->data_len = pkt_size;
438 		created_pkt->pkt_len = pkt_size;
439 		eth_hdr = rte_pktmbuf_mtod(created_pkt, struct rte_ether_hdr *);
440 		rte_ether_addr_copy(&eth_addr, &eth_hdr->src_addr);
441 
442 		/* Set multicast address 01-1B-19-00-00-00. */
443 		rte_ether_addr_copy(&eth_multicast, &eth_hdr->dst_addr);
444 
445 		eth_hdr->ether_type = htons(PTP_PROTOCOL);
446 		req_msg = rte_pktmbuf_mtod_offset(created_pkt,
447 			struct delay_req_msg *, sizeof(struct
448 			rte_ether_hdr));
449 
450 		req_msg->hdr.seq_id = htons(ptp_data->seqID_SYNC);
451 		req_msg->hdr.msg_type = DELAY_REQ;
452 		req_msg->hdr.ver = 2;
453 		req_msg->hdr.control = 1;
454 		req_msg->hdr.log_message_interval = 127;
455 		req_msg->hdr.message_length =
456 			htons(sizeof(struct delay_req_msg));
457 		req_msg->hdr.domain_number = ptp_hdr->domain_number;
458 
459 		/* Set up clock id. */
460 		client_clkid =
461 			&req_msg->hdr.source_port_id.clock_id;
462 
463 		client_clkid->id[0] = eth_hdr->src_addr.addr_bytes[0];
464 		client_clkid->id[1] = eth_hdr->src_addr.addr_bytes[1];
465 		client_clkid->id[2] = eth_hdr->src_addr.addr_bytes[2];
466 		client_clkid->id[3] = 0xFF;
467 		client_clkid->id[4] = 0xFE;
468 		client_clkid->id[5] = eth_hdr->src_addr.addr_bytes[3];
469 		client_clkid->id[6] = eth_hdr->src_addr.addr_bytes[4];
470 		client_clkid->id[7] = eth_hdr->src_addr.addr_bytes[5];
471 
472 		rte_memcpy(&ptp_data->client_clock_id,
473 			   client_clkid,
474 			   sizeof(struct clock_id));
475 
476 		/* Enable flag for hardware timestamping. */
477 		created_pkt->ol_flags |= RTE_MBUF_F_TX_IEEE1588_TMST;
478 
479 		/*Read value from NIC to prevent latching with old value. */
480 		rte_eth_timesync_read_tx_timestamp(ptp_data->portid,
481 				&ptp_data->tstamp3);
482 
483 		/* Transmit the packet. */
484 		rte_eth_tx_burst(ptp_data->portid, 0, &created_pkt, 1);
485 
486 		wait_us = 0;
487 		ptp_data->tstamp3.tv_nsec = 0;
488 		ptp_data->tstamp3.tv_sec = 0;
489 
490 		/* Wait at least 1 us to read TX timestamp. */
491 		while ((rte_eth_timesync_read_tx_timestamp(ptp_data->portid,
492 				&ptp_data->tstamp3) < 0) && (wait_us < 1000)) {
493 			rte_delay_us(1);
494 			wait_us++;
495 		}
496 	}
497 }
498 
499 /*
500  * Update the kernel time with the difference between it and the current NIC
501  * time.
502  */
503 static inline void
504 update_kernel_time(void)
505 {
506 	int64_t nsec;
507 	struct timespec net_time, sys_time;
508 
509 	clock_gettime(CLOCK_REALTIME, &sys_time);
510 	rte_eth_timesync_read_time(ptp_data.current_ptp_port, &net_time);
511 
512 	nsec = (int64_t)timespec64_to_ns(&net_time) -
513 	       (int64_t)timespec64_to_ns(&sys_time);
514 
515 	ptp_data.new_adj = ns_to_timeval(nsec);
516 
517 	/*
518 	 * If difference between kernel time and system time in NIC is too big
519 	 * (more than +/- 20 microseconds), use clock_settime to set directly
520 	 * the kernel time, as adjtime is better for small adjustments (takes
521 	 * longer to adjust the time).
522 	 */
523 
524 	if (nsec > KERNEL_TIME_ADJUST_LIMIT || nsec < -KERNEL_TIME_ADJUST_LIMIT)
525 		clock_settime(CLOCK_REALTIME, &net_time);
526 	else
527 		adjtime(&ptp_data.new_adj, 0);
528 
529 
530 }
531 
532 /*
533  * Parse the DELAY_RESP message.
534  */
535 static void
536 parse_drsp(struct ptpv2_data_slave_ordinary *ptp_data)
537 {
538 	struct rte_mbuf *m = ptp_data->m;
539 	struct ptp_message *ptp_msg;
540 	struct tstamp *rx_tstamp;
541 	uint16_t seq_id;
542 
543 	ptp_msg = rte_pktmbuf_mtod_offset(m, struct ptp_message *,
544 					  sizeof(struct rte_ether_hdr));
545 	seq_id = rte_be_to_cpu_16(ptp_msg->delay_resp.hdr.seq_id);
546 	if (memcmp(&ptp_data->client_clock_id,
547 		   &ptp_msg->delay_resp.req_port_id.clock_id,
548 		   sizeof(struct clock_id)) == 0) {
549 		if (seq_id == ptp_data->seqID_FOLLOWUP) {
550 			rx_tstamp = &ptp_msg->delay_resp.rx_tstamp;
551 			ptp_data->tstamp4.tv_nsec = ntohl(rx_tstamp->ns);
552 			ptp_data->tstamp4.tv_sec =
553 				((uint64_t)ntohl(rx_tstamp->sec_lsb)) |
554 				(((uint64_t)ntohs(rx_tstamp->sec_msb)) << 32);
555 
556 			/* Evaluate the delta for adjustment. */
557 			ptp_data->delta = delta_eval(ptp_data);
558 
559 			rte_eth_timesync_adjust_time(ptp_data->portid,
560 						     ptp_data->delta);
561 
562 			ptp_data->current_ptp_port = ptp_data->portid;
563 
564 			/* Update kernel time if enabled in app parameters. */
565 			if (ptp_data->kernel_time_set == 1)
566 				update_kernel_time();
567 
568 
569 
570 		}
571 	}
572 }
573 
574 /* This function processes PTP packets, implementing slave PTP IEEE1588 L2
575  * functionality.
576  */
577 
578 /* Parse ptp frames. 8< */
579 static void
580 parse_ptp_frames(uint16_t portid, struct rte_mbuf *m) {
581 	struct ptp_header *ptp_hdr;
582 	struct rte_ether_hdr *eth_hdr;
583 	uint16_t eth_type;
584 
585 	eth_hdr = rte_pktmbuf_mtod(m, struct rte_ether_hdr *);
586 	eth_type = rte_be_to_cpu_16(eth_hdr->ether_type);
587 
588 	if (eth_type == PTP_PROTOCOL) {
589 		ptp_data.m = m;
590 		ptp_data.portid = portid;
591 		ptp_hdr = rte_pktmbuf_mtod_offset(m, struct ptp_header *,
592 						  sizeof(struct rte_ether_hdr));
593 
594 		switch (ptp_hdr->msg_type) {
595 		case SYNC:
596 			parse_sync(&ptp_data, m->timesync);
597 			break;
598 		case FOLLOW_UP:
599 			parse_fup(&ptp_data);
600 			break;
601 		case DELAY_RESP:
602 			parse_drsp(&ptp_data);
603 			print_clock_info(&ptp_data);
604 			break;
605 		default:
606 			break;
607 		}
608 	}
609 }
610 /* >8 End of function processes PTP packets. */
611 
612 /*
613  * The lcore main. This is the main thread that does the work, reading from an
614  * input port and writing to an output port.
615  */
616 static void
617 lcore_main(void)
618 {
619 	uint16_t portid;
620 	unsigned nb_rx;
621 	struct rte_mbuf *m;
622 
623 	printf("\nCore %u Waiting for SYNC packets. [Ctrl+C to quit]\n",
624 			rte_lcore_id());
625 
626 	/* Run until the application is quit or killed. */
627 
628 	while (!force_quit) {
629 		/* Read packet from RX queues. 8< */
630 		for (portid = 0; portid < ptp_enabled_port_nb; portid++) {
631 
632 			portid = ptp_enabled_ports[portid];
633 			nb_rx = rte_eth_rx_burst(portid, 0, &m, 1);
634 
635 			if (likely(nb_rx == 0))
636 				continue;
637 
638 			/* Packet is parsed to determine which type. 8< */
639 			if (m->ol_flags & RTE_MBUF_F_RX_IEEE1588_PTP)
640 				parse_ptp_frames(portid, m);
641 			/* >8 End of packet is parsed to determine which type. */
642 
643 			rte_pktmbuf_free(m);
644 		}
645 		/* >8 End of read packets from RX queues. */
646 	}
647 }
648 
649 static void
650 print_usage(const char *prgname)
651 {
652 	printf("%s [EAL options] -- -p PORTMASK -T VALUE\n"
653 		" -T VALUE: 0 - Disable, 1 - Enable Linux Clock"
654 		" Synchronization (0 default)\n"
655 		" -p PORTMASK: hexadecimal bitmask of ports to configure\n",
656 		prgname);
657 }
658 
659 static int
660 ptp_parse_portmask(const char *portmask)
661 {
662 	char *end = NULL;
663 	unsigned long pm;
664 
665 	/* Parse the hexadecimal string. */
666 	pm = strtoul(portmask, &end, 16);
667 
668 	if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
669 		return 0;
670 
671 	return pm;
672 }
673 
674 static int
675 parse_ptp_kernel(const char *param)
676 {
677 	char *end = NULL;
678 	unsigned long pm;
679 
680 	/* Parse the hexadecimal string. */
681 	pm = strtoul(param, &end, 16);
682 
683 	if ((param[0] == '\0') || (end == NULL) || (*end != '\0'))
684 		return -1;
685 	if (pm == 0)
686 		return 0;
687 
688 	return 1;
689 }
690 
691 /* Parse the commandline arguments. */
692 static int
693 ptp_parse_args(int argc, char **argv)
694 {
695 	int opt, ret;
696 	char **argvopt;
697 	int option_index;
698 	char *prgname = argv[0];
699 	static struct option lgopts[] = { {NULL, 0, 0, 0} };
700 
701 	argvopt = argv;
702 
703 	while ((opt = getopt_long(argc, argvopt, "p:T:",
704 				  lgopts, &option_index)) != EOF) {
705 
706 		switch (opt) {
707 
708 		/* Portmask. */
709 		case 'p':
710 			ptp_enabled_port_mask = ptp_parse_portmask(optarg);
711 			if (ptp_enabled_port_mask == 0) {
712 				printf("invalid portmask\n");
713 				print_usage(prgname);
714 				return -1;
715 			}
716 			break;
717 		/* Time synchronization. */
718 		case 'T':
719 			ret = parse_ptp_kernel(optarg);
720 			if (ret < 0) {
721 				print_usage(prgname);
722 				return -1;
723 			}
724 
725 			ptp_data.kernel_time_set = ret;
726 			break;
727 
728 		default:
729 			print_usage(prgname);
730 			return -1;
731 		}
732 	}
733 
734 	argv[optind-1] = prgname;
735 
736 	optind = 1; /* Reset getopt lib. */
737 
738 	return 0;
739 }
740 
741 static void
742 signal_handler(int signum)
743 {
744 	if (signum == SIGINT || signum == SIGTERM)
745 		force_quit = true;
746 }
747 
748 /*
749  * The main function, which does initialization and calls the per-lcore
750  * functions.
751  */
752 int
753 main(int argc, char *argv[])
754 {
755 	unsigned nb_ports;
756 
757 	uint16_t portid;
758 
759 	/* Initialize the Environment Abstraction Layer (EAL). 8< */
760 	int ret = rte_eal_init(argc, argv);
761 
762 	if (ret < 0)
763 		rte_exit(EXIT_FAILURE, "Error with EAL initialization\n");
764 	/* >8 End of initialization of EAL. */
765 
766 	memset(&ptp_data, '\0', sizeof(struct ptpv2_data_slave_ordinary));
767 
768 	/* Parse specific arguments. 8< */
769 	argc -= ret;
770 	argv += ret;
771 
772 	force_quit = false;
773 	signal(SIGINT, signal_handler);
774 	signal(SIGTERM, signal_handler);
775 
776 	ret = ptp_parse_args(argc, argv);
777 	if (ret < 0)
778 		rte_exit(EXIT_FAILURE, "Error with PTP initialization\n");
779 	/* >8 End of parsing specific arguments. */
780 
781 	/* Check that there is an even number of ports to send/receive on. */
782 	nb_ports = rte_eth_dev_count_avail();
783 
784 	/* Creates a new mempool in memory to hold the mbufs. 8< */
785 	mbuf_pool = rte_pktmbuf_pool_create("MBUF_POOL", NUM_MBUFS * nb_ports,
786 		MBUF_CACHE_SIZE, 0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id());
787 	/* >8 End of a new mempool in memory to hold the mbufs. */
788 
789 	if (mbuf_pool == NULL)
790 		rte_exit(EXIT_FAILURE, "Cannot create mbuf pool\n");
791 
792 	/* Initialize all ports. 8< */
793 	RTE_ETH_FOREACH_DEV(portid) {
794 		if ((ptp_enabled_port_mask & (1 << portid)) != 0) {
795 			if (port_init(portid, mbuf_pool) == 0) {
796 				ptp_enabled_ports[ptp_enabled_port_nb] = portid;
797 				ptp_enabled_port_nb++;
798 			} else {
799 				rte_exit(EXIT_FAILURE,
800 					 "Cannot init port %"PRIu8 "\n",
801 					 portid);
802 			}
803 		} else
804 			printf("Skipping disabled port %u\n", portid);
805 	}
806 	/* >8 End of initialization of all ports. */
807 
808 	if (ptp_enabled_port_nb == 0) {
809 		rte_exit(EXIT_FAILURE,
810 			"All available ports are disabled."
811 			" Please set portmask.\n");
812 	}
813 
814 	if (rte_lcore_count() > 1)
815 		printf("\nWARNING: Too many lcores enabled. Only 1 used.\n");
816 
817 	/* Call lcore_main on the main core only. */
818 	lcore_main();
819 
820 	RTE_ETH_FOREACH_DEV(portid) {
821 		if ((ptp_enabled_port_mask & (1 << portid)) == 0)
822 			continue;
823 
824 		/* Disable timesync timestamping for the Ethernet device */
825 		rte_eth_timesync_disable(portid);
826 
827 		ret = rte_eth_dev_stop(portid);
828 		if (ret != 0)
829 			printf("rte_eth_dev_stop: err=%d, port=%d\n", ret, portid);
830 
831 		rte_eth_dev_close(portid);
832 	}
833 
834 	/* clean up the EAL */
835 	rte_eal_cleanup();
836 
837 	return 0;
838 }
839