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