xref: /linux/drivers/net/ethernet/sfc/ptp.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /****************************************************************************
3  * Driver for Solarflare network controllers and boards
4  * Copyright 2011-2013 Solarflare Communications Inc.
5  */
6 
7 /* Theory of operation:
8  *
9  * PTP support is assisted by firmware running on the MC, which provides
10  * the hardware timestamping capabilities.  Both transmitted and received
11  * PTP event packets are queued onto internal queues for subsequent processing;
12  * this is because the MC operations are relatively long and would block
13  * block NAPI/interrupt operation.
14  *
15  * Receive event processing:
16  *	The event contains the packet's UUID and sequence number, together
17  *	with the hardware timestamp.  The PTP receive packet queue is searched
18  *	for this UUID/sequence number and, if found, put on a pending queue.
19  *	Packets not matching are delivered without timestamps (MCDI events will
20  *	always arrive after the actual packet).
21  *	It is important for the operation of the PTP protocol that the ordering
22  *	of packets between the event and general port is maintained.
23  *
24  * Work queue processing:
25  *	If work waiting, synchronise host/hardware time
26  *
27  *	Transmit: send packet through MC, which returns the transmission time
28  *	that is converted to an appropriate timestamp.
29  *
30  *	Receive: the packet's reception time is converted to an appropriate
31  *	timestamp.
32  */
33 #include <linux/ip.h>
34 #include <linux/udp.h>
35 #include <linux/time.h>
36 #include <linux/errno.h>
37 #include <linux/ktime.h>
38 #include <linux/module.h>
39 #include <linux/mutex.h>
40 #include <linux/pps_kernel.h>
41 #include <linux/ptp_clock_kernel.h>
42 #include "net_driver.h"
43 #include "efx.h"
44 #include "mcdi.h"
45 #include "mcdi_pcol.h"
46 #include "io.h"
47 #include "tx.h"
48 #include "nic.h" /* indirectly includes ptp.h */
49 #include "efx_channels.h"
50 
51 /* Maximum number of events expected to make up a PTP event */
52 #define	MAX_EVENT_FRAGS			3
53 
54 /* Maximum delay, ms, to begin synchronisation */
55 #define	MAX_SYNCHRONISE_WAIT_MS		2
56 
57 /* How long, at most, to spend synchronising */
58 #define	SYNCHRONISE_PERIOD_NS		250000
59 
60 /* How often to update the shared memory time */
61 #define	SYNCHRONISATION_GRANULARITY_NS	200
62 
63 /* Minimum permitted length of a (corrected) synchronisation time */
64 #define	DEFAULT_MIN_SYNCHRONISATION_NS	120
65 
66 /* Maximum permitted length of a (corrected) synchronisation time */
67 #define	MAX_SYNCHRONISATION_NS		1000
68 
69 /* How many (MC) receive events that can be queued */
70 #define	MAX_RECEIVE_EVENTS		8
71 
72 /* Length of (modified) moving average. */
73 #define	AVERAGE_LENGTH			16
74 
75 /* How long an unmatched event or packet can be held */
76 #define PKT_EVENT_LIFETIME_MS		10
77 
78 /* How long unused unicast filters can be held */
79 #define UCAST_FILTER_EXPIRY_JIFFIES	msecs_to_jiffies(30000)
80 
81 /* Offsets into PTP packet for identification.  These offsets are from the
82  * start of the IP header, not the MAC header.  Note that neither PTP V1 nor
83  * PTP V2 permit the use of IPV4 options.
84  */
85 #define PTP_DPORT_OFFSET	22
86 
87 #define PTP_V1_VERSION_LENGTH	2
88 #define PTP_V1_VERSION_OFFSET	28
89 
90 #define PTP_V1_SEQUENCE_LENGTH	2
91 #define PTP_V1_SEQUENCE_OFFSET	58
92 
93 /* The minimum length of a PTP V1 packet for offsets, etc. to be valid:
94  * includes IP header.
95  */
96 #define	PTP_V1_MIN_LENGTH	64
97 
98 #define PTP_V2_VERSION_LENGTH	1
99 #define PTP_V2_VERSION_OFFSET	29
100 
101 #define PTP_V2_SEQUENCE_LENGTH	2
102 #define PTP_V2_SEQUENCE_OFFSET	58
103 
104 /* The minimum length of a PTP V2 packet for offsets, etc. to be valid:
105  * includes IP header.
106  */
107 #define	PTP_V2_MIN_LENGTH	63
108 
109 #define	PTP_MIN_LENGTH		63
110 
111 #define PTP_ADDR_IPV4		0xe0000181	/* 224.0.1.129 */
112 
113 /* ff0e::181 */
114 static const struct in6_addr ptp_addr_ipv6 = { { {
115 	0xff, 0x0e, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01, 0x81 } } };
116 
117 /* 01-1B-19-00-00-00 */
118 static const u8 ptp_addr_ether[ETH_ALEN] __aligned(2) = {
119 	0x01, 0x1b, 0x19, 0x00, 0x00, 0x00 };
120 
121 #define PTP_EVENT_PORT		319
122 #define PTP_GENERAL_PORT	320
123 
124 /* Annoyingly the format of the version numbers are different between
125  * versions 1 and 2 so it isn't possible to simply look for 1 or 2.
126  */
127 #define	PTP_VERSION_V1		1
128 
129 #define	PTP_VERSION_V2		2
130 #define	PTP_VERSION_V2_MASK	0x0f
131 
132 enum ptp_packet_state {
133 	PTP_PACKET_STATE_UNMATCHED = 0,
134 	PTP_PACKET_STATE_MATCHED,
135 	PTP_PACKET_STATE_TIMED_OUT,
136 	PTP_PACKET_STATE_MATCH_UNWANTED
137 };
138 
139 /* NIC synchronised with single word of time only comprising
140  * partial seconds and full nanoseconds: 10^9 ~ 2^30 so 2 bits for seconds.
141  */
142 #define	MC_NANOSECOND_BITS	30
143 #define	MC_NANOSECOND_MASK	((1 << MC_NANOSECOND_BITS) - 1)
144 #define	MC_SECOND_MASK		((1 << (32 - MC_NANOSECOND_BITS)) - 1)
145 
146 /* Maximum parts-per-billion adjustment that is acceptable */
147 #define MAX_PPB			1000000
148 
149 /* Precalculate scale word to avoid long long division at runtime */
150 /* This is equivalent to 2^66 / 10^9. */
151 #define PPB_SCALE_WORD  ((1LL << (57)) / 1953125LL)
152 
153 /* How much to shift down after scaling to convert to FP40 */
154 #define PPB_SHIFT_FP40		26
155 /* ... and FP44. */
156 #define PPB_SHIFT_FP44		22
157 
158 #define PTP_SYNC_ATTEMPTS	4
159 
160 /**
161  * struct efx_ptp_match - Matching structure, stored in sk_buff's cb area.
162  * @expiry: Time after which the packet should be delivered irrespective of
163  *            event arrival.
164  * @state: The state of the packet - whether it is ready for processing or
165  *         whether that is of no interest.
166  */
167 struct efx_ptp_match {
168 	unsigned long expiry;
169 	enum ptp_packet_state state;
170 };
171 
172 /**
173  * struct efx_ptp_event_rx - A PTP receive event (from MC)
174  * @link: list of events
175  * @seq0: First part of (PTP) UUID
176  * @seq1: Second part of (PTP) UUID and sequence number
177  * @hwtimestamp: Event timestamp
178  * @expiry: Time which the packet arrived
179  */
180 struct efx_ptp_event_rx {
181 	struct list_head link;
182 	u32 seq0;
183 	u32 seq1;
184 	ktime_t hwtimestamp;
185 	unsigned long expiry;
186 };
187 
188 /**
189  * struct efx_ptp_timeset - Synchronisation between host and MC
190  * @host_start: Host time immediately before hardware timestamp taken
191  * @major: Hardware timestamp, major
192  * @minor: Hardware timestamp, minor
193  * @host_end: Host time immediately after hardware timestamp taken
194  * @wait: Number of NIC clock ticks between hardware timestamp being read and
195  *          host end time being seen
196  * @window: Difference of host_end and host_start
197  */
198 struct efx_ptp_timeset {
199 	u32 host_start;
200 	u32 major;
201 	u32 minor;
202 	u32 host_end;
203 	u32 wait;
204 	u32 window;	/* Derived: end - start, allowing for wrap */
205 };
206 
207 /**
208  * struct efx_ptp_rxfilter - Filter for PTP packets
209  * @list: Node of the list where the filter is added
210  * @ether_type: Network protocol of the filter (ETHER_P_IP / ETHER_P_IPV6)
211  * @loc_port: UDP port of the filter (PTP_EVENT_PORT / PTP_GENERAL_PORT)
212  * @loc_host: IPv4/v6 address of the filter
213  * @expiry: time when the filter expires, in jiffies
214  * @handle: Handle ID for the MCDI filters table
215  */
216 struct efx_ptp_rxfilter {
217 	struct list_head list;
218 	__be16 ether_type;
219 	__be16 loc_port;
220 	__be32 loc_host[4];
221 	unsigned long expiry;
222 	int handle;
223 };
224 
225 /**
226  * struct efx_ptp_data - Precision Time Protocol (PTP) state
227  * @efx: The NIC context
228  * @channel: The PTP channel (for Medford and Medford2)
229  * @rxq: Receive SKB queue (awaiting timestamps)
230  * @txq: Transmit SKB queue
231  * @workwq: Work queue for processing pending PTP operations
232  * @work: Work task
233  * @cleanup_work: Work task for periodic cleanup
234  * @reset_required: A serious error has occurred and the PTP task needs to be
235  *                  reset (disable, enable).
236  * @rxfilters_mcast: Receive filters for multicast PTP packets
237  * @rxfilters_ucast: Receive filters for unicast PTP packets
238  * @config: Current timestamp configuration
239  * @enabled: PTP operation enabled
240  * @mode: Mode in which PTP operating (PTP version)
241  * @ns_to_nic_time: Function to convert from scalar nanoseconds to NIC time
242  * @nic_to_kernel_time: Function to convert from NIC to kernel time
243  * @nic_time: contains time details
244  * @nic_time.minor_max: Wrap point for NIC minor times
245  * @nic_time.sync_event_diff_min: Minimum acceptable difference between time
246  * in packet prefix and last MCDI time sync event i.e. how much earlier than
247  * the last sync event time a packet timestamp can be.
248  * @nic_time.sync_event_diff_max: Maximum acceptable difference between time
249  * in packet prefix and last MCDI time sync event i.e. how much later than
250  * the last sync event time a packet timestamp can be.
251  * @nic_time.sync_event_minor_shift: Shift required to make minor time from
252  * field in MCDI time sync event.
253  * @min_synchronisation_ns: Minimum acceptable corrected sync window
254  * @capabilities: Capabilities flags from the NIC
255  * @ts_corrections: contains corrections details
256  * @ts_corrections.ptp_tx: Required driver correction of PTP packet transmit
257  *                         timestamps
258  * @ts_corrections.ptp_rx: Required driver correction of PTP packet receive
259  *                         timestamps
260  * @ts_corrections.pps_out: PPS output error (information only)
261  * @ts_corrections.pps_in: Required driver correction of PPS input timestamps
262  * @ts_corrections.general_tx: Required driver correction of general packet
263  *                             transmit timestamps
264  * @ts_corrections.general_rx: Required driver correction of general packet
265  *                             receive timestamps
266  * @evt_frags: Partly assembled PTP events
267  * @evt_frag_idx: Current fragment number
268  * @evt_code: Last event code
269  * @start: Address at which MC indicates ready for synchronisation
270  * @adjfreq_ppb_shift: Shift required to convert scaled parts-per-billion
271  * frequency adjustment into a fixed point fractional nanosecond format.
272  * @current_adjfreq: Current ppb adjustment.
273  * @phc_clock: Pointer to registered phc device (if primary function)
274  * @phc_lock: Serializes PHC commands and synchronization, and protects
275  *	      @current_adjfreq
276  * @phc_clock_info: Registration structure for phc device
277  * @pps_work: pps work task for handling pps events
278  * @pps_workwq: pps work queue
279  * @nic_ts_enabled: Flag indicating if NIC generated TS events are handled
280  * @txbuf: Buffer for use when transmitting (PTP) packets to MC (avoids
281  *         allocations in main data path).
282  * @good_syncs: Number of successful synchronisations.
283  * @fast_syncs: Number of synchronisations requiring short delay
284  * @bad_syncs: Number of failed synchronisations.
285  * @sync_timeouts: Number of synchronisation timeouts
286  * @no_time_syncs: Number of synchronisations with no good times.
287  * @invalid_sync_windows: Number of sync windows with bad durations.
288  * @undersize_sync_windows: Number of corrected sync windows that are too small
289  * @oversize_sync_windows: Number of corrected sync windows that are too large
290  * @rx_no_timestamp: Number of packets received without a timestamp.
291  * @timeset: Last set of synchronisation statistics.
292  * @xmit_skb: Transmit SKB function.
293  */
294 struct efx_ptp_data {
295 	struct efx_nic *efx;
296 	struct efx_channel *channel;
297 	struct sk_buff_head rxq;
298 	struct sk_buff_head txq;
299 	struct workqueue_struct *workwq;
300 	struct work_struct work;
301 	struct delayed_work cleanup_work;
302 	bool reset_required;
303 	struct list_head rxfilters_mcast;
304 	struct list_head rxfilters_ucast;
305 	struct kernel_hwtstamp_config config;
306 	bool enabled;
307 	unsigned int mode;
308 	void (*ns_to_nic_time)(s64 ns, u32 *nic_major, u32 *nic_minor);
309 	ktime_t (*nic_to_kernel_time)(u32 nic_major, u32 nic_minor,
310 				      s32 correction);
311 	struct {
312 		u32 minor_max;
313 		u32 sync_event_diff_min;
314 		u32 sync_event_diff_max;
315 		unsigned int sync_event_minor_shift;
316 	} nic_time;
317 	unsigned int min_synchronisation_ns;
318 	unsigned int capabilities;
319 	struct {
320 		s32 ptp_tx;
321 		s32 ptp_rx;
322 		s32 pps_out;
323 		s32 pps_in;
324 		s32 general_tx;
325 		s32 general_rx;
326 	} ts_corrections;
327 	efx_qword_t evt_frags[MAX_EVENT_FRAGS];
328 	int evt_frag_idx;
329 	int evt_code;
330 	struct efx_buffer start;
331 	unsigned int adjfreq_ppb_shift;
332 	s64 current_adjfreq;
333 	struct ptp_clock *phc_clock;
334 	struct mutex phc_lock;
335 	struct ptp_clock_info phc_clock_info;
336 	struct work_struct pps_work;
337 	struct workqueue_struct *pps_workwq;
338 	bool nic_ts_enabled;
339 	efx_dword_t txbuf[MCDI_TX_BUF_LEN(MC_CMD_PTP_IN_TRANSMIT_LENMAX)];
340 
341 	unsigned int good_syncs;
342 	unsigned int fast_syncs;
343 	unsigned int bad_syncs;
344 	unsigned int sync_timeouts;
345 	unsigned int no_time_syncs;
346 	unsigned int invalid_sync_windows;
347 	unsigned int undersize_sync_windows;
348 	unsigned int oversize_sync_windows;
349 	unsigned int rx_no_timestamp;
350 	struct efx_ptp_timeset
351 	timeset[MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_MAXNUM];
352 	void (*xmit_skb)(struct efx_nic *efx, struct sk_buff *skb);
353 };
354 
355 static int efx_phc_adjfine(struct ptp_clock_info *ptp, long scaled_ppm);
356 static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta);
357 static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts);
358 static int efx_phc_settime(struct ptp_clock_info *ptp,
359 			   const struct timespec64 *e_ts);
360 static int efx_phc_enable(struct ptp_clock_info *ptp,
361 			  struct ptp_clock_request *request, int on);
362 static int efx_ptp_insert_unicast_filter(struct efx_nic *efx,
363 					 struct sk_buff *skb);
364 
365 bool efx_ptp_use_mac_tx_timestamps(struct efx_nic *efx)
366 {
367 	return efx_has_cap(efx, TX_MAC_TIMESTAMPING);
368 }
369 
370 /* PTP 'extra' channel is still a traffic channel, but we only create TX queues
371  * if PTP uses MAC TX timestamps, not if PTP uses the MC directly to transmit.
372  */
373 static bool efx_ptp_want_txqs(struct efx_channel *channel)
374 {
375 	return efx_ptp_use_mac_tx_timestamps(channel->efx);
376 }
377 
378 #define PTP_SW_STAT(ext_name, field_name)				\
379 	{ #ext_name, 0, offsetof(struct efx_ptp_data, field_name) }
380 #define PTP_MC_STAT(ext_name, mcdi_name)				\
381 	{ #ext_name, 32, MC_CMD_PTP_OUT_STATUS_STATS_ ## mcdi_name ## _OFST }
382 static const struct efx_hw_stat_desc efx_ptp_stat_desc[] = {
383 	PTP_SW_STAT(ptp_good_syncs, good_syncs),
384 	PTP_SW_STAT(ptp_fast_syncs, fast_syncs),
385 	PTP_SW_STAT(ptp_bad_syncs, bad_syncs),
386 	PTP_SW_STAT(ptp_sync_timeouts, sync_timeouts),
387 	PTP_SW_STAT(ptp_no_time_syncs, no_time_syncs),
388 	PTP_SW_STAT(ptp_invalid_sync_windows, invalid_sync_windows),
389 	PTP_SW_STAT(ptp_undersize_sync_windows, undersize_sync_windows),
390 	PTP_SW_STAT(ptp_oversize_sync_windows, oversize_sync_windows),
391 	PTP_SW_STAT(ptp_rx_no_timestamp, rx_no_timestamp),
392 	PTP_MC_STAT(ptp_tx_timestamp_packets, TX),
393 	PTP_MC_STAT(ptp_rx_timestamp_packets, RX),
394 	PTP_MC_STAT(ptp_timestamp_packets, TS),
395 	PTP_MC_STAT(ptp_filter_matches, FM),
396 	PTP_MC_STAT(ptp_non_filter_matches, NFM),
397 };
398 #define PTP_STAT_COUNT ARRAY_SIZE(efx_ptp_stat_desc)
399 static const unsigned long efx_ptp_stat_mask[] = {
400 	[0 ... BITS_TO_LONGS(PTP_STAT_COUNT) - 1] = ~0UL,
401 };
402 
403 size_t efx_ptp_describe_stats(struct efx_nic *efx, u8 **strings)
404 {
405 	if (!efx->ptp_data)
406 		return 0;
407 
408 	return efx_nic_describe_stats(efx_ptp_stat_desc, PTP_STAT_COUNT,
409 				      efx_ptp_stat_mask, strings);
410 }
411 
412 size_t efx_ptp_update_stats(struct efx_nic *efx, u64 *stats)
413 {
414 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_STATUS_LEN);
415 	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_STATUS_LEN);
416 	size_t i;
417 	int rc;
418 
419 	if (!efx->ptp_data)
420 		return 0;
421 
422 	/* Copy software statistics */
423 	for (i = 0; i < PTP_STAT_COUNT; i++) {
424 		if (efx_ptp_stat_desc[i].dma_width)
425 			continue;
426 		stats[i] = *(unsigned int *)((char *)efx->ptp_data +
427 					     efx_ptp_stat_desc[i].offset);
428 	}
429 
430 	/* Fetch MC statistics.  We *must* fill in all statistics or
431 	 * risk leaking kernel memory to userland, so if the MCDI
432 	 * request fails we pretend we got zeroes.
433 	 */
434 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_STATUS);
435 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
436 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
437 			  outbuf, sizeof(outbuf), NULL);
438 	if (rc)
439 		memset(outbuf, 0, sizeof(outbuf));
440 	efx_nic_update_stats(efx_ptp_stat_desc, PTP_STAT_COUNT,
441 			     efx_ptp_stat_mask,
442 			     stats, _MCDI_PTR(outbuf, 0), false);
443 
444 	return PTP_STAT_COUNT;
445 }
446 
447 /* To convert from s27 format to ns we multiply then divide by a power of 2.
448  * For the conversion from ns to s27, the operation is also converted to a
449  * multiply and shift.
450  */
451 #define S27_TO_NS_SHIFT	(27)
452 #define NS_TO_S27_MULT	(((1ULL << 63) + NSEC_PER_SEC / 2) / NSEC_PER_SEC)
453 #define NS_TO_S27_SHIFT	(63 - S27_TO_NS_SHIFT)
454 #define S27_MINOR_MAX	(1 << S27_TO_NS_SHIFT)
455 
456 /* For Huntington platforms NIC time is in seconds and fractions of a second
457  * where the minor register only uses 27 bits in units of 2^-27s.
458  */
459 static void efx_ptp_ns_to_s27(s64 ns, u32 *nic_major, u32 *nic_minor)
460 {
461 	struct timespec64 ts = ns_to_timespec64(ns);
462 	u32 maj = (u32)ts.tv_sec;
463 	u32 min = (u32)(((u64)ts.tv_nsec * NS_TO_S27_MULT +
464 			 (1ULL << (NS_TO_S27_SHIFT - 1))) >> NS_TO_S27_SHIFT);
465 
466 	/* The conversion can result in the minor value exceeding the maximum.
467 	 * In this case, round up to the next second.
468 	 */
469 	if (min >= S27_MINOR_MAX) {
470 		min -= S27_MINOR_MAX;
471 		maj++;
472 	}
473 
474 	*nic_major = maj;
475 	*nic_minor = min;
476 }
477 
478 static inline ktime_t efx_ptp_s27_to_ktime(u32 nic_major, u32 nic_minor)
479 {
480 	u32 ns = (u32)(((u64)nic_minor * NSEC_PER_SEC +
481 			(1ULL << (S27_TO_NS_SHIFT - 1))) >> S27_TO_NS_SHIFT);
482 	return ktime_set(nic_major, ns);
483 }
484 
485 static ktime_t efx_ptp_s27_to_ktime_correction(u32 nic_major, u32 nic_minor,
486 					       s32 correction)
487 {
488 	/* Apply the correction and deal with carry */
489 	nic_minor += correction;
490 	if ((s32)nic_minor < 0) {
491 		nic_minor += S27_MINOR_MAX;
492 		nic_major--;
493 	} else if (nic_minor >= S27_MINOR_MAX) {
494 		nic_minor -= S27_MINOR_MAX;
495 		nic_major++;
496 	}
497 
498 	return efx_ptp_s27_to_ktime(nic_major, nic_minor);
499 }
500 
501 /* For Medford2 platforms the time is in seconds and quarter nanoseconds. */
502 static void efx_ptp_ns_to_s_qns(s64 ns, u32 *nic_major, u32 *nic_minor)
503 {
504 	struct timespec64 ts = ns_to_timespec64(ns);
505 
506 	*nic_major = (u32)ts.tv_sec;
507 	*nic_minor = ts.tv_nsec * 4;
508 }
509 
510 static ktime_t efx_ptp_s_qns_to_ktime_correction(u32 nic_major, u32 nic_minor,
511 						 s32 correction)
512 {
513 	ktime_t kt;
514 
515 	nic_minor = DIV_ROUND_CLOSEST(nic_minor, 4);
516 	correction = DIV_ROUND_CLOSEST(correction, 4);
517 
518 	kt = ktime_set(nic_major, nic_minor);
519 
520 	if (correction >= 0)
521 		kt = ktime_add_ns(kt, (u64)correction);
522 	else
523 		kt = ktime_sub_ns(kt, (u64)-correction);
524 	return kt;
525 }
526 
527 struct efx_channel *efx_ptp_channel(struct efx_nic *efx)
528 {
529 	return efx->ptp_data ? efx->ptp_data->channel : NULL;
530 }
531 
532 void efx_ptp_update_channel(struct efx_nic *efx, struct efx_channel *channel)
533 {
534 	if (efx->ptp_data)
535 		efx->ptp_data->channel = channel;
536 }
537 
538 static u32 last_sync_timestamp_major(struct efx_nic *efx)
539 {
540 	struct efx_channel *channel = efx_ptp_channel(efx);
541 	u32 major = 0;
542 
543 	if (channel)
544 		major = channel->sync_timestamp_major;
545 	return major;
546 }
547 
548 /* The 8000 series and later can provide the time from the MAC, which is only
549  * 48 bits long and provides meta-information in the top 2 bits.
550  */
551 static ktime_t
552 efx_ptp_mac_nic_to_ktime_correction(struct efx_nic *efx,
553 				    struct efx_ptp_data *ptp,
554 				    u32 nic_major, u32 nic_minor,
555 				    s32 correction)
556 {
557 	u32 sync_timestamp;
558 	ktime_t kt = { 0 };
559 	s16 delta;
560 
561 	if (!(nic_major & 0x80000000)) {
562 		WARN_ON_ONCE(nic_major >> 16);
563 
564 		/* Medford provides 48 bits of timestamp, so we must get the top
565 		 * 16 bits from the timesync event state.
566 		 *
567 		 * We only have the lower 16 bits of the time now, but we do
568 		 * have a full resolution timestamp at some point in past. As
569 		 * long as the difference between the (real) now and the sync
570 		 * is less than 2^15, then we can reconstruct the difference
571 		 * between those two numbers using only the lower 16 bits of
572 		 * each.
573 		 *
574 		 * Put another way
575 		 *
576 		 * a - b = ((a mod k) - b) mod k
577 		 *
578 		 * when -k/2 < (a-b) < k/2. In our case k is 2^16. We know
579 		 * (a mod k) and b, so can calculate the delta, a - b.
580 		 *
581 		 */
582 		sync_timestamp = last_sync_timestamp_major(efx);
583 
584 		/* Because delta is s16 this does an implicit mask down to
585 		 * 16 bits which is what we need, assuming
586 		 * MEDFORD_TX_SECS_EVENT_BITS is 16. delta is signed so that
587 		 * we can deal with the (unlikely) case of sync timestamps
588 		 * arriving from the future.
589 		 */
590 		delta = nic_major - sync_timestamp;
591 
592 		/* Recover the fully specified time now, by applying the offset
593 		 * to the (fully specified) sync time.
594 		 */
595 		nic_major = sync_timestamp + delta;
596 
597 		kt = ptp->nic_to_kernel_time(nic_major, nic_minor,
598 					     correction);
599 	}
600 	return kt;
601 }
602 
603 ktime_t efx_ptp_nic_to_kernel_time(struct efx_tx_queue *tx_queue)
604 {
605 	struct efx_nic *efx = tx_queue->efx;
606 	struct efx_ptp_data *ptp = efx->ptp_data;
607 	ktime_t kt;
608 
609 	if (efx_ptp_use_mac_tx_timestamps(efx))
610 		kt = efx_ptp_mac_nic_to_ktime_correction(efx, ptp,
611 				tx_queue->completed_timestamp_major,
612 				tx_queue->completed_timestamp_minor,
613 				ptp->ts_corrections.general_tx);
614 	else
615 		kt = ptp->nic_to_kernel_time(
616 				tx_queue->completed_timestamp_major,
617 				tx_queue->completed_timestamp_minor,
618 				ptp->ts_corrections.general_tx);
619 	return kt;
620 }
621 
622 /* Get PTP attributes and set up time conversions */
623 static int efx_ptp_get_attributes(struct efx_nic *efx)
624 {
625 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_GET_ATTRIBUTES_LEN);
626 	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_GET_ATTRIBUTES_LEN);
627 	struct efx_ptp_data *ptp = efx->ptp_data;
628 	int rc;
629 	u32 fmt;
630 	size_t out_len;
631 
632 	/* Get the PTP attributes. If the NIC doesn't support the operation we
633 	 * use the default format for compatibility with older NICs i.e.
634 	 * seconds and nanoseconds.
635 	 */
636 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_GET_ATTRIBUTES);
637 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
638 	rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
639 				outbuf, sizeof(outbuf), &out_len);
640 	if (rc == 0) {
641 		fmt = MCDI_DWORD(outbuf, PTP_OUT_GET_ATTRIBUTES_TIME_FORMAT);
642 	} else if (rc == -EINVAL) {
643 		fmt = MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_NANOSECONDS;
644 	} else if (rc == -EPERM) {
645 		pci_info(efx->pci_dev, "no PTP support\n");
646 		return rc;
647 	} else {
648 		efx_mcdi_display_error(efx, MC_CMD_PTP, sizeof(inbuf),
649 				       outbuf, sizeof(outbuf), rc);
650 		return rc;
651 	}
652 
653 	switch (fmt) {
654 	case MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_27FRACTION:
655 		ptp->ns_to_nic_time = efx_ptp_ns_to_s27;
656 		ptp->nic_to_kernel_time = efx_ptp_s27_to_ktime_correction;
657 		ptp->nic_time.minor_max = 1 << 27;
658 		ptp->nic_time.sync_event_minor_shift = 19;
659 		break;
660 	case MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_QTR_NANOSECONDS:
661 		ptp->ns_to_nic_time = efx_ptp_ns_to_s_qns;
662 		ptp->nic_to_kernel_time = efx_ptp_s_qns_to_ktime_correction;
663 		ptp->nic_time.minor_max = 4000000000UL;
664 		ptp->nic_time.sync_event_minor_shift = 24;
665 		break;
666 	default:
667 		return -ERANGE;
668 	}
669 
670 	/* Precalculate acceptable difference between the minor time in the
671 	 * packet prefix and the last MCDI time sync event. We expect the
672 	 * packet prefix timestamp to be after of sync event by up to one
673 	 * sync event interval (0.25s) but we allow it to exceed this by a
674 	 * fuzz factor of (0.1s)
675 	 */
676 	ptp->nic_time.sync_event_diff_min = ptp->nic_time.minor_max
677 		- (ptp->nic_time.minor_max / 10);
678 	ptp->nic_time.sync_event_diff_max = (ptp->nic_time.minor_max / 4)
679 		+ (ptp->nic_time.minor_max / 10);
680 
681 	/* MC_CMD_PTP_OP_GET_ATTRIBUTES has been extended twice from an older
682 	 * operation MC_CMD_PTP_OP_GET_TIME_FORMAT. The function now may return
683 	 * a value to use for the minimum acceptable corrected synchronization
684 	 * window and may return further capabilities.
685 	 * If we have the extra information store it. For older firmware that
686 	 * does not implement the extended command use the default value.
687 	 */
688 	if (rc == 0 &&
689 	    out_len >= MC_CMD_PTP_OUT_GET_ATTRIBUTES_CAPABILITIES_OFST)
690 		ptp->min_synchronisation_ns =
691 			MCDI_DWORD(outbuf,
692 				   PTP_OUT_GET_ATTRIBUTES_SYNC_WINDOW_MIN);
693 	else
694 		ptp->min_synchronisation_ns = DEFAULT_MIN_SYNCHRONISATION_NS;
695 
696 	if (rc == 0 &&
697 	    out_len >= MC_CMD_PTP_OUT_GET_ATTRIBUTES_LEN)
698 		ptp->capabilities = MCDI_DWORD(outbuf,
699 					PTP_OUT_GET_ATTRIBUTES_CAPABILITIES);
700 	else
701 		ptp->capabilities = 0;
702 
703 	/* Set up the shift for conversion between frequency
704 	 * adjustments in parts-per-billion and the fixed-point
705 	 * fractional ns format that the adapter uses.
706 	 */
707 	if (ptp->capabilities & (1 << MC_CMD_PTP_OUT_GET_ATTRIBUTES_FP44_FREQ_ADJ_LBN))
708 		ptp->adjfreq_ppb_shift = PPB_SHIFT_FP44;
709 	else
710 		ptp->adjfreq_ppb_shift = PPB_SHIFT_FP40;
711 
712 	return 0;
713 }
714 
715 /* Get PTP timestamp corrections */
716 static int efx_ptp_get_timestamp_corrections(struct efx_nic *efx)
717 {
718 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_GET_TIMESTAMP_CORRECTIONS_LEN);
719 	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_LEN);
720 	int rc;
721 	size_t out_len;
722 
723 	/* Get the timestamp corrections from the NIC. If this operation is
724 	 * not supported (older NICs) then no correction is required.
725 	 */
726 	MCDI_SET_DWORD(inbuf, PTP_IN_OP,
727 		       MC_CMD_PTP_OP_GET_TIMESTAMP_CORRECTIONS);
728 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
729 
730 	rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
731 				outbuf, sizeof(outbuf), &out_len);
732 	if (rc == 0) {
733 		efx->ptp_data->ts_corrections.ptp_tx = MCDI_DWORD(outbuf,
734 			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_TRANSMIT);
735 		efx->ptp_data->ts_corrections.ptp_rx = MCDI_DWORD(outbuf,
736 			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_RECEIVE);
737 		efx->ptp_data->ts_corrections.pps_out = MCDI_DWORD(outbuf,
738 			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_PPS_OUT);
739 		efx->ptp_data->ts_corrections.pps_in = MCDI_DWORD(outbuf,
740 			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_PPS_IN);
741 
742 		if (out_len >= MC_CMD_PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_LEN) {
743 			efx->ptp_data->ts_corrections.general_tx = MCDI_DWORD(
744 				outbuf,
745 				PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_GENERAL_TX);
746 			efx->ptp_data->ts_corrections.general_rx = MCDI_DWORD(
747 				outbuf,
748 				PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_GENERAL_RX);
749 		} else {
750 			efx->ptp_data->ts_corrections.general_tx =
751 				efx->ptp_data->ts_corrections.ptp_tx;
752 			efx->ptp_data->ts_corrections.general_rx =
753 				efx->ptp_data->ts_corrections.ptp_rx;
754 		}
755 	} else if (rc == -EINVAL) {
756 		efx->ptp_data->ts_corrections.ptp_tx = 0;
757 		efx->ptp_data->ts_corrections.ptp_rx = 0;
758 		efx->ptp_data->ts_corrections.pps_out = 0;
759 		efx->ptp_data->ts_corrections.pps_in = 0;
760 		efx->ptp_data->ts_corrections.general_tx = 0;
761 		efx->ptp_data->ts_corrections.general_rx = 0;
762 	} else {
763 		efx_mcdi_display_error(efx, MC_CMD_PTP, sizeof(inbuf), outbuf,
764 				       sizeof(outbuf), rc);
765 		return rc;
766 	}
767 
768 	return 0;
769 }
770 
771 /* Enable MCDI PTP support. */
772 static int efx_ptp_enable(struct efx_nic *efx)
773 {
774 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ENABLE_LEN);
775 	MCDI_DECLARE_BUF_ERR(outbuf);
776 	int rc;
777 
778 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ENABLE);
779 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
780 	MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_QUEUE,
781 		       efx->ptp_data->channel ?
782 		       efx->ptp_data->channel->channel : 0);
783 	MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_MODE, efx->ptp_data->mode);
784 
785 	rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
786 				outbuf, sizeof(outbuf), NULL);
787 	rc = (rc == -EALREADY) ? 0 : rc;
788 	if (rc)
789 		efx_mcdi_display_error(efx, MC_CMD_PTP,
790 				       MC_CMD_PTP_IN_ENABLE_LEN,
791 				       outbuf, sizeof(outbuf), rc);
792 	return rc;
793 }
794 
795 /* Disable MCDI PTP support.
796  *
797  * Note that this function should never rely on the presence of ptp_data -
798  * may be called before that exists.
799  */
800 static int efx_ptp_disable(struct efx_nic *efx)
801 {
802 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_DISABLE_LEN);
803 	MCDI_DECLARE_BUF_ERR(outbuf);
804 	int rc;
805 
806 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_DISABLE);
807 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
808 	rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
809 				outbuf, sizeof(outbuf), NULL);
810 	rc = (rc == -EALREADY) ? 0 : rc;
811 	/* If we get ENOSYS, the NIC doesn't support PTP, and thus this function
812 	 * should only have been called during probe.
813 	 */
814 	if (rc == -ENOSYS || rc == -EPERM)
815 		pci_info(efx->pci_dev, "no PTP support\n");
816 	else if (rc)
817 		efx_mcdi_display_error(efx, MC_CMD_PTP,
818 				       MC_CMD_PTP_IN_DISABLE_LEN,
819 				       outbuf, sizeof(outbuf), rc);
820 	return rc;
821 }
822 
823 static void efx_ptp_deliver_rx_queue(struct sk_buff_head *q)
824 {
825 	struct sk_buff *skb;
826 
827 	while ((skb = skb_dequeue(q))) {
828 		local_bh_disable();
829 		netif_receive_skb(skb);
830 		local_bh_enable();
831 	}
832 }
833 
834 static void efx_ptp_handle_no_channel(struct efx_nic *efx)
835 {
836 	netif_err(efx, drv, efx->net_dev,
837 		  "ERROR: PTP requires MSI-X and 1 additional interrupt"
838 		  "vector. PTP disabled\n");
839 }
840 
841 /* Repeatedly send the host time to the MC which will capture the hardware
842  * time.
843  */
844 static void efx_ptp_send_times(struct efx_nic *efx,
845 			       struct pps_event_time *last_time)
846 {
847 	struct pps_event_time now;
848 	struct timespec64 limit;
849 	struct efx_ptp_data *ptp = efx->ptp_data;
850 	int *mc_running = ptp->start.addr;
851 
852 	pps_get_ts(&now);
853 	limit = now.ts_real;
854 	timespec64_add_ns(&limit, SYNCHRONISE_PERIOD_NS);
855 
856 	/* Write host time for specified period or until MC is done */
857 	while ((timespec64_compare(&now.ts_real, &limit) < 0) &&
858 	       READ_ONCE(*mc_running)) {
859 		struct timespec64 update_time;
860 		unsigned int host_time;
861 
862 		/* Don't update continuously to avoid saturating the PCIe bus */
863 		update_time = now.ts_real;
864 		timespec64_add_ns(&update_time, SYNCHRONISATION_GRANULARITY_NS);
865 		do {
866 			pps_get_ts(&now);
867 		} while ((timespec64_compare(&now.ts_real, &update_time) < 0) &&
868 			 READ_ONCE(*mc_running));
869 
870 		/* Synchronise NIC with single word of time only */
871 		host_time = (now.ts_real.tv_sec << MC_NANOSECOND_BITS |
872 			     now.ts_real.tv_nsec);
873 		/* Update host time in NIC memory */
874 		efx->type->ptp_write_host_time(efx, host_time);
875 	}
876 	*last_time = now;
877 }
878 
879 /* Read a timeset from the MC's results and partial process. */
880 static void efx_ptp_read_timeset(MCDI_DECLARE_STRUCT_PTR(data),
881 				 struct efx_ptp_timeset *timeset)
882 {
883 	unsigned start_ns, end_ns;
884 
885 	timeset->host_start = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTSTART);
886 	timeset->major = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_MAJOR);
887 	timeset->minor = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_MINOR);
888 	timeset->host_end = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTEND);
889 	timeset->wait = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_WAITNS);
890 
891 	/* Ignore seconds */
892 	start_ns = timeset->host_start & MC_NANOSECOND_MASK;
893 	end_ns = timeset->host_end & MC_NANOSECOND_MASK;
894 	/* Allow for rollover */
895 	if (end_ns < start_ns)
896 		end_ns += NSEC_PER_SEC;
897 	/* Determine duration of operation */
898 	timeset->window = end_ns - start_ns;
899 }
900 
901 /* Process times received from MC.
902  *
903  * Extract times from returned results, and establish the minimum value
904  * seen.  The minimum value represents the "best" possible time and events
905  * too much greater than this are rejected - the machine is, perhaps, too
906  * busy. A number of readings are taken so that, hopefully, at least one good
907  * synchronisation will be seen in the results.
908  */
909 static int
910 efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),
911 		      size_t response_length,
912 		      const struct pps_event_time *last_time,
913 		      struct pps_event_time *host_time_pps)
914 {
915 	unsigned number_readings =
916 		MCDI_VAR_ARRAY_LEN(response_length,
917 				   PTP_OUT_SYNCHRONIZE_TIMESET);
918 	unsigned i;
919 	unsigned ngood = 0;
920 	unsigned last_good = 0;
921 	struct efx_ptp_data *ptp = efx->ptp_data;
922 	u32 last_sec;
923 	u32 start_sec;
924 	struct timespec64 delta;
925 	ktime_t mc_time;
926 
927 	if (number_readings == 0)
928 		return -EAGAIN;
929 
930 	/* Read the set of results and find the last good host-MC
931 	 * synchronization result. The MC times when it finishes reading the
932 	 * host time so the corrected window time should be fairly constant
933 	 * for a given platform. Increment stats for any results that appear
934 	 * to be erroneous.
935 	 */
936 	for (i = 0; i < number_readings; i++) {
937 		s32 window, corrected;
938 		struct timespec64 wait;
939 
940 		efx_ptp_read_timeset(
941 			MCDI_ARRAY_STRUCT_PTR(synch_buf,
942 					      PTP_OUT_SYNCHRONIZE_TIMESET, i),
943 			&ptp->timeset[i]);
944 
945 		wait = ktime_to_timespec64(
946 			ptp->nic_to_kernel_time(0, ptp->timeset[i].wait, 0));
947 		window = ptp->timeset[i].window;
948 		corrected = window - wait.tv_nsec;
949 
950 		/* We expect the uncorrected synchronization window to be at
951 		 * least as large as the interval between host start and end
952 		 * times. If it is smaller than this then this is mostly likely
953 		 * to be a consequence of the host's time being adjusted.
954 		 * Check that the corrected sync window is in a reasonable
955 		 * range. If it is out of range it is likely to be because an
956 		 * interrupt or other delay occurred between reading the system
957 		 * time and writing it to MC memory.
958 		 */
959 		if (window < SYNCHRONISATION_GRANULARITY_NS) {
960 			++ptp->invalid_sync_windows;
961 		} else if (corrected >= MAX_SYNCHRONISATION_NS) {
962 			++ptp->oversize_sync_windows;
963 		} else if (corrected < ptp->min_synchronisation_ns) {
964 			++ptp->undersize_sync_windows;
965 		} else {
966 			ngood++;
967 			last_good = i;
968 		}
969 	}
970 
971 	if (ngood == 0) {
972 		netif_warn(efx, drv, efx->net_dev,
973 			   "PTP no suitable synchronisations\n");
974 		return -EAGAIN;
975 	}
976 
977 	/* Calculate delay from last good sync (host time) to last_time.
978 	 * It is possible that the seconds rolled over between taking
979 	 * the start reading and the last value written by the host.  The
980 	 * timescales are such that a gap of more than one second is never
981 	 * expected.  delta is *not* normalised.
982 	 */
983 	start_sec = ptp->timeset[last_good].host_start >> MC_NANOSECOND_BITS;
984 	last_sec = last_time->ts_real.tv_sec & MC_SECOND_MASK;
985 	if (start_sec != last_sec &&
986 	    ((start_sec + 1) & MC_SECOND_MASK) != last_sec) {
987 		netif_warn(efx, hw, efx->net_dev,
988 			   "PTP bad synchronisation seconds\n");
989 		return -EAGAIN;
990 	}
991 
992 	if (!host_time_pps)
993 		return 0;
994 
995 	delta.tv_sec = (last_sec - start_sec) & 1;
996 	delta.tv_nsec =
997 		last_time->ts_real.tv_nsec -
998 		(ptp->timeset[last_good].host_start & MC_NANOSECOND_MASK);
999 
1000 	/* Convert the NIC time at last good sync into kernel time.
1001 	 * No correction is required - this time is the output of a
1002 	 * firmware process.
1003 	 */
1004 	mc_time = ptp->nic_to_kernel_time(ptp->timeset[last_good].major,
1005 					  ptp->timeset[last_good].minor, 0);
1006 
1007 	/* Calculate delay from NIC top of second to last_time */
1008 	delta.tv_nsec += ktime_to_timespec64(mc_time).tv_nsec;
1009 
1010 	/* Set PPS timestamp to match NIC top of second */
1011 	*host_time_pps = *last_time;
1012 	pps_sub_ts(host_time_pps, delta);
1013 
1014 	return 0;
1015 }
1016 
1017 /* Synchronize times between the host and the MC.
1018  *
1019  * The MC serializes PTP requests, so MC_CMD_PTP_OP_ADJUST cannot be applied
1020  * while MC_CMD_PTP_OP_SYNCHRONIZE is collecting timesets. This holds across
1021  * functions of a controller, which share the clock but adjust it only through
1022  * the function that registered it, so a secondary function can capture here
1023  * without serializing against the primary.
1024  */
1025 static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings,
1026 			       struct pps_event_time *host_time_pps)
1027 {
1028 	struct efx_ptp_data *ptp = efx->ptp_data;
1029 	MCDI_DECLARE_BUF(synch_buf, MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX);
1030 	size_t response_length;
1031 	int rc;
1032 	unsigned long timeout;
1033 	struct pps_event_time last_time = {};
1034 	unsigned int loops = 0;
1035 	int *start = ptp->start.addr;
1036 
1037 	MCDI_SET_DWORD(synch_buf, PTP_IN_OP, MC_CMD_PTP_OP_SYNCHRONIZE);
1038 	MCDI_SET_DWORD(synch_buf, PTP_IN_PERIPH_ID, 0);
1039 	MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_NUMTIMESETS,
1040 		       num_readings);
1041 	MCDI_SET_QWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR,
1042 		       ptp->start.dma_addr);
1043 
1044 	mutex_lock(&ptp->phc_lock);
1045 
1046 	/* Clear flag that signals MC ready */
1047 	WRITE_ONCE(*start, 0);
1048 	rc = efx_mcdi_rpc_start(efx, MC_CMD_PTP, synch_buf,
1049 				MC_CMD_PTP_IN_SYNCHRONIZE_LEN);
1050 	if (rc)
1051 		goto out;
1052 
1053 	/* Wait for start from MCDI (or timeout) */
1054 	timeout = jiffies + msecs_to_jiffies(MAX_SYNCHRONISE_WAIT_MS);
1055 	while (!READ_ONCE(*start) && (time_before(jiffies, timeout))) {
1056 		udelay(20);	/* Usually start MCDI execution quickly */
1057 		loops++;
1058 	}
1059 
1060 	if (loops <= 1)
1061 		++ptp->fast_syncs;
1062 	if (!time_before(jiffies, timeout))
1063 		++ptp->sync_timeouts;
1064 
1065 	if (READ_ONCE(*start))
1066 		efx_ptp_send_times(efx, &last_time);
1067 
1068 	/* Collect results */
1069 	rc = efx_mcdi_rpc_finish(efx, MC_CMD_PTP,
1070 				 MC_CMD_PTP_IN_SYNCHRONIZE_LEN,
1071 				 synch_buf, sizeof(synch_buf),
1072 				 &response_length);
1073 	if (rc == 0) {
1074 		rc = efx_ptp_process_times(efx, synch_buf, response_length,
1075 					   &last_time, host_time_pps);
1076 		if (rc == 0)
1077 			++ptp->good_syncs;
1078 		else
1079 			++ptp->no_time_syncs;
1080 	}
1081 
1082 out:
1083 	/* Increment the bad syncs counter if the synchronize fails, whatever
1084 	 * the reason.
1085 	 */
1086 	if (rc != 0)
1087 		++ptp->bad_syncs;
1088 	mutex_unlock(&ptp->phc_lock);
1089 
1090 	return rc;
1091 }
1092 
1093 /* Transmit a PTP packet via the dedicated hardware timestamped queue. */
1094 static void efx_ptp_xmit_skb_queue(struct efx_nic *efx, struct sk_buff *skb)
1095 {
1096 	struct efx_ptp_data *ptp_data = efx->ptp_data;
1097 	u8 type = efx_tx_csum_type_skb(skb);
1098 	struct efx_tx_queue *tx_queue;
1099 
1100 	tx_queue = efx_channel_get_tx_queue(ptp_data->channel, type);
1101 	if (tx_queue && tx_queue->timestamping) {
1102 		skb_get(skb);
1103 
1104 		/* This code invokes normal driver TX code which is always
1105 		 * protected from softirqs when called from generic TX code,
1106 		 * which in turn disables preemption. Look at __dev_queue_xmit
1107 		 * which uses rcu_read_lock_bh disabling preemption for RCU
1108 		 * plus disabling softirqs. We do not need RCU reader
1109 		 * protection here.
1110 		 *
1111 		 * Although it is theoretically safe for current PTP TX/RX code
1112 		 * running without disabling softirqs, there are three good
1113 		 * reasond for doing so:
1114 		 *
1115 		 *      1) The code invoked is mainly implemented for non-PTP
1116 		 *         packets and it is always executed with softirqs
1117 		 *         disabled.
1118 		 *      2) This being a single PTP packet, better to not
1119 		 *         interrupt its processing by softirqs which can lead
1120 		 *         to high latencies.
1121 		 *      3) netdev_xmit_more checks preemption is disabled and
1122 		 *         triggers a BUG_ON if not.
1123 		 */
1124 		local_bh_disable();
1125 		efx_enqueue_skb(tx_queue, skb);
1126 		local_bh_enable();
1127 
1128 		/* We need to add the filters after enqueuing the packet.
1129 		 * Otherwise, there's high latency in sending back the
1130 		 * timestamp, causing ptp4l timeouts
1131 		 */
1132 		efx_ptp_insert_unicast_filter(efx, skb);
1133 		dev_consume_skb_any(skb);
1134 	} else {
1135 		WARN_ONCE(1, "PTP channel has no timestamped tx queue\n");
1136 		dev_kfree_skb_any(skb);
1137 	}
1138 }
1139 
1140 /* Transmit a PTP packet, via the MCDI interface, to the wire. */
1141 static void efx_ptp_xmit_skb_mc(struct efx_nic *efx, struct sk_buff *skb)
1142 {
1143 	MCDI_DECLARE_BUF(txtime, MC_CMD_PTP_OUT_TRANSMIT_LEN);
1144 	struct efx_ptp_data *ptp_data = efx->ptp_data;
1145 	struct skb_shared_hwtstamps timestamps;
1146 	size_t len;
1147 	int rc;
1148 
1149 	MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_OP, MC_CMD_PTP_OP_TRANSMIT);
1150 	MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_PERIPH_ID, 0);
1151 	MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_TRANSMIT_LENGTH, skb->len);
1152 	if (skb_shinfo(skb)->nr_frags != 0) {
1153 		rc = skb_linearize(skb);
1154 		if (rc != 0)
1155 			goto fail;
1156 	}
1157 
1158 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
1159 		rc = skb_checksum_help(skb);
1160 		if (rc != 0)
1161 			goto fail;
1162 	}
1163 	skb_copy_from_linear_data(skb,
1164 				  MCDI_PTR(ptp_data->txbuf,
1165 					   PTP_IN_TRANSMIT_PACKET),
1166 				  skb->len);
1167 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP,
1168 			  ptp_data->txbuf, MC_CMD_PTP_IN_TRANSMIT_LEN(skb->len),
1169 			  txtime, sizeof(txtime), &len);
1170 	if (rc != 0)
1171 		goto fail;
1172 
1173 	memset(&timestamps, 0, sizeof(timestamps));
1174 	timestamps.hwtstamp = ptp_data->nic_to_kernel_time(
1175 		MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_MAJOR),
1176 		MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_MINOR),
1177 		ptp_data->ts_corrections.ptp_tx);
1178 
1179 	skb_tstamp_tx(skb, &timestamps);
1180 
1181 	/* Add the filters after sending back the timestamp to avoid delaying it
1182 	 * or ptp4l may timeout.
1183 	 */
1184 	efx_ptp_insert_unicast_filter(efx, skb);
1185 
1186 fail:
1187 	dev_kfree_skb_any(skb);
1188 
1189 	return;
1190 }
1191 
1192 /* Process any queued receive events and corresponding packets
1193  *
1194  * q is returned with all the packets that are ready for delivery.
1195  */
1196 static void efx_ptp_process_events(struct efx_nic *efx, struct sk_buff_head *q)
1197 {
1198 	struct efx_ptp_data *ptp = efx->ptp_data;
1199 	struct sk_buff *skb;
1200 
1201 	while ((skb = skb_dequeue(&ptp->rxq))) {
1202 		struct efx_ptp_match *match;
1203 
1204 		match = (struct efx_ptp_match *)skb->cb;
1205 		if (match->state == PTP_PACKET_STATE_MATCH_UNWANTED) {
1206 			__skb_queue_tail(q, skb);
1207 		} else if (time_after(jiffies, match->expiry)) {
1208 			match->state = PTP_PACKET_STATE_TIMED_OUT;
1209 			++ptp->rx_no_timestamp;
1210 			__skb_queue_tail(q, skb);
1211 		} else {
1212 			/* Replace unprocessed entry and stop */
1213 			skb_queue_head(&ptp->rxq, skb);
1214 			break;
1215 		}
1216 	}
1217 }
1218 
1219 /* Complete processing of a received packet */
1220 static inline void efx_ptp_process_rx(struct efx_nic *efx, struct sk_buff *skb)
1221 {
1222 	local_bh_disable();
1223 	netif_receive_skb(skb);
1224 	local_bh_enable();
1225 }
1226 
1227 static struct efx_ptp_rxfilter *
1228 efx_ptp_find_filter(struct list_head *filter_list, struct efx_filter_spec *spec)
1229 {
1230 	struct efx_ptp_rxfilter *rxfilter;
1231 
1232 	list_for_each_entry(rxfilter, filter_list, list) {
1233 		if (rxfilter->ether_type == spec->ether_type &&
1234 		    rxfilter->loc_port == spec->loc_port &&
1235 		    !memcmp(rxfilter->loc_host, spec->loc_host, sizeof(spec->loc_host)))
1236 			return rxfilter;
1237 	}
1238 
1239 	return NULL;
1240 }
1241 
1242 static void efx_ptp_remove_one_filter(struct efx_nic *efx,
1243 				      struct efx_ptp_rxfilter *rxfilter)
1244 {
1245 	efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
1246 				  rxfilter->handle);
1247 	list_del(&rxfilter->list);
1248 	kfree(rxfilter);
1249 }
1250 
1251 static void efx_ptp_remove_filters(struct efx_nic *efx,
1252 				   struct list_head *filter_list)
1253 {
1254 	struct efx_ptp_rxfilter *rxfilter, *tmp;
1255 
1256 	list_for_each_entry_safe(rxfilter, tmp, filter_list, list)
1257 		efx_ptp_remove_one_filter(efx, rxfilter);
1258 }
1259 
1260 static void efx_ptp_init_filter(struct efx_nic *efx,
1261 				struct efx_filter_spec *rxfilter)
1262 {
1263 	struct efx_channel *channel = efx->ptp_data->channel;
1264 	struct efx_rx_queue *queue = efx_channel_get_rx_queue(channel);
1265 
1266 	efx_filter_init_rx(rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
1267 			   efx_rx_queue_index(queue));
1268 }
1269 
1270 static int efx_ptp_insert_filter(struct efx_nic *efx,
1271 				 struct list_head *filter_list,
1272 				 struct efx_filter_spec *spec,
1273 				 unsigned long expiry)
1274 {
1275 	struct efx_ptp_data *ptp = efx->ptp_data;
1276 	struct efx_ptp_rxfilter *rxfilter;
1277 	int rc;
1278 
1279 	rxfilter = efx_ptp_find_filter(filter_list, spec);
1280 	if (rxfilter) {
1281 		rxfilter->expiry = expiry;
1282 		return 0;
1283 	}
1284 
1285 	rxfilter = kzalloc_obj(*rxfilter);
1286 	if (!rxfilter)
1287 		return -ENOMEM;
1288 
1289 	rc = efx_filter_insert_filter(efx, spec, true);
1290 	if (rc < 0)
1291 		goto fail;
1292 
1293 	rxfilter->handle = rc;
1294 	rxfilter->ether_type = spec->ether_type;
1295 	rxfilter->loc_port = spec->loc_port;
1296 	memcpy(rxfilter->loc_host, spec->loc_host, sizeof(spec->loc_host));
1297 	rxfilter->expiry = expiry;
1298 	list_add(&rxfilter->list, filter_list);
1299 
1300 	queue_delayed_work(ptp->workwq, &ptp->cleanup_work,
1301 			   UCAST_FILTER_EXPIRY_JIFFIES + 1);
1302 
1303 	return 0;
1304 
1305 fail:
1306 	kfree(rxfilter);
1307 	return rc;
1308 }
1309 
1310 static int efx_ptp_insert_ipv4_filter(struct efx_nic *efx,
1311 				      struct list_head *filter_list,
1312 				      __be32 addr, u16 port,
1313 				      unsigned long expiry)
1314 {
1315 	struct efx_filter_spec spec;
1316 
1317 	efx_ptp_init_filter(efx, &spec);
1318 	efx_filter_set_ipv4_local(&spec, IPPROTO_UDP, addr, htons(port));
1319 	return efx_ptp_insert_filter(efx, filter_list, &spec, expiry);
1320 }
1321 
1322 static int efx_ptp_insert_ipv6_filter(struct efx_nic *efx,
1323 				      struct list_head *filter_list,
1324 				      const struct in6_addr *addr, u16 port,
1325 				      unsigned long expiry)
1326 {
1327 	struct efx_filter_spec spec;
1328 
1329 	efx_ptp_init_filter(efx, &spec);
1330 	efx_filter_set_ipv6_local(&spec, IPPROTO_UDP, addr, htons(port));
1331 	return efx_ptp_insert_filter(efx, filter_list, &spec, expiry);
1332 }
1333 
1334 static int efx_ptp_insert_eth_multicast_filter(struct efx_nic *efx)
1335 {
1336 	struct efx_ptp_data *ptp = efx->ptp_data;
1337 	struct efx_filter_spec spec;
1338 
1339 	efx_ptp_init_filter(efx, &spec);
1340 	efx_filter_set_eth_local(&spec, EFX_FILTER_VID_UNSPEC, ptp_addr_ether);
1341 	spec.match_flags |= EFX_FILTER_MATCH_ETHER_TYPE;
1342 	spec.ether_type = htons(ETH_P_1588);
1343 	return efx_ptp_insert_filter(efx, &ptp->rxfilters_mcast, &spec, 0);
1344 }
1345 
1346 static int efx_ptp_insert_multicast_filters(struct efx_nic *efx)
1347 {
1348 	struct efx_ptp_data *ptp = efx->ptp_data;
1349 	int rc;
1350 
1351 	if (!ptp->channel || !list_empty(&ptp->rxfilters_mcast))
1352 		return 0;
1353 
1354 	/* Must filter on both event and general ports to ensure
1355 	 * that there is no packet re-ordering.
1356 	 */
1357 	rc = efx_ptp_insert_ipv4_filter(efx, &ptp->rxfilters_mcast,
1358 					htonl(PTP_ADDR_IPV4), PTP_EVENT_PORT,
1359 					0);
1360 	if (rc < 0)
1361 		goto fail;
1362 
1363 	rc = efx_ptp_insert_ipv4_filter(efx, &ptp->rxfilters_mcast,
1364 					htonl(PTP_ADDR_IPV4), PTP_GENERAL_PORT,
1365 					0);
1366 	if (rc < 0)
1367 		goto fail;
1368 
1369 	/* if the NIC supports hw timestamps by the MAC, we can support
1370 	 * PTP over IPv6 and Ethernet
1371 	 */
1372 	if (efx_ptp_use_mac_tx_timestamps(efx)) {
1373 		rc = efx_ptp_insert_ipv6_filter(efx, &ptp->rxfilters_mcast,
1374 						&ptp_addr_ipv6, PTP_EVENT_PORT, 0);
1375 		if (rc < 0)
1376 			goto fail;
1377 
1378 		rc = efx_ptp_insert_ipv6_filter(efx, &ptp->rxfilters_mcast,
1379 						&ptp_addr_ipv6, PTP_GENERAL_PORT, 0);
1380 		if (rc < 0)
1381 			goto fail;
1382 
1383 		rc = efx_ptp_insert_eth_multicast_filter(efx);
1384 
1385 		/* Not all firmware variants support this filter */
1386 		if (rc < 0 && rc != -EPROTONOSUPPORT)
1387 			goto fail;
1388 	}
1389 
1390 	return 0;
1391 
1392 fail:
1393 	efx_ptp_remove_filters(efx, &ptp->rxfilters_mcast);
1394 	return rc;
1395 }
1396 
1397 static bool efx_ptp_valid_unicast_event_pkt(struct sk_buff *skb)
1398 {
1399 	if (skb->protocol == htons(ETH_P_IP)) {
1400 		return ip_hdr(skb)->daddr != htonl(PTP_ADDR_IPV4) &&
1401 			ip_hdr(skb)->protocol == IPPROTO_UDP &&
1402 			udp_hdr(skb)->source == htons(PTP_EVENT_PORT);
1403 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
1404 		return !ipv6_addr_equal(&ipv6_hdr(skb)->daddr, &ptp_addr_ipv6) &&
1405 			ipv6_hdr(skb)->nexthdr == IPPROTO_UDP &&
1406 			udp_hdr(skb)->source == htons(PTP_EVENT_PORT);
1407 	}
1408 	return false;
1409 }
1410 
1411 static int efx_ptp_insert_unicast_filter(struct efx_nic *efx,
1412 					 struct sk_buff *skb)
1413 {
1414 	struct efx_ptp_data *ptp = efx->ptp_data;
1415 	unsigned long expiry;
1416 	int rc;
1417 
1418 	if (!efx_ptp_valid_unicast_event_pkt(skb))
1419 		return -EINVAL;
1420 
1421 	expiry = jiffies + UCAST_FILTER_EXPIRY_JIFFIES;
1422 
1423 	if (skb->protocol == htons(ETH_P_IP)) {
1424 		__be32 addr = ip_hdr(skb)->saddr;
1425 
1426 		rc = efx_ptp_insert_ipv4_filter(efx, &ptp->rxfilters_ucast,
1427 						addr, PTP_EVENT_PORT, expiry);
1428 		if (rc < 0)
1429 			goto out;
1430 
1431 		rc = efx_ptp_insert_ipv4_filter(efx, &ptp->rxfilters_ucast,
1432 						addr, PTP_GENERAL_PORT, expiry);
1433 	} else if (efx_ptp_use_mac_tx_timestamps(efx)) {
1434 		/* IPv6 PTP only supported by devices with MAC hw timestamp */
1435 		struct in6_addr *addr = &ipv6_hdr(skb)->saddr;
1436 
1437 		rc = efx_ptp_insert_ipv6_filter(efx, &ptp->rxfilters_ucast,
1438 						addr, PTP_EVENT_PORT, expiry);
1439 		if (rc < 0)
1440 			goto out;
1441 
1442 		rc = efx_ptp_insert_ipv6_filter(efx, &ptp->rxfilters_ucast,
1443 						addr, PTP_GENERAL_PORT, expiry);
1444 	} else {
1445 		return -EOPNOTSUPP;
1446 	}
1447 
1448 out:
1449 	return rc;
1450 }
1451 
1452 static int efx_ptp_start(struct efx_nic *efx)
1453 {
1454 	struct efx_ptp_data *ptp = efx->ptp_data;
1455 	int rc;
1456 
1457 	ptp->reset_required = false;
1458 
1459 	rc = efx_ptp_insert_multicast_filters(efx);
1460 	if (rc)
1461 		return rc;
1462 
1463 	rc = efx_ptp_enable(efx);
1464 	if (rc != 0)
1465 		goto fail;
1466 
1467 	ptp->evt_frag_idx = 0;
1468 
1469 	return 0;
1470 
1471 fail:
1472 	efx_ptp_remove_filters(efx, &ptp->rxfilters_mcast);
1473 	return rc;
1474 }
1475 
1476 static int efx_ptp_stop(struct efx_nic *efx)
1477 {
1478 	struct efx_ptp_data *ptp = efx->ptp_data;
1479 	int rc;
1480 
1481 	if (ptp == NULL)
1482 		return 0;
1483 
1484 	rc = efx_ptp_disable(efx);
1485 
1486 	efx_ptp_remove_filters(efx, &ptp->rxfilters_mcast);
1487 	efx_ptp_remove_filters(efx, &ptp->rxfilters_ucast);
1488 
1489 	/* Make sure RX packets are really delivered */
1490 	efx_ptp_deliver_rx_queue(&efx->ptp_data->rxq);
1491 	skb_queue_purge(&efx->ptp_data->txq);
1492 
1493 	return rc;
1494 }
1495 
1496 static int efx_ptp_restart(struct efx_nic *efx)
1497 {
1498 	if (efx->ptp_data && efx->ptp_data->enabled)
1499 		return efx_ptp_start(efx);
1500 	return 0;
1501 }
1502 
1503 static void efx_ptp_pps_worker(struct work_struct *work)
1504 {
1505 	struct efx_ptp_data *ptp =
1506 		container_of(work, struct efx_ptp_data, pps_work);
1507 	struct pps_event_time host_time_pps = {};
1508 	struct efx_nic *efx = ptp->efx;
1509 	struct ptp_clock_event ptp_evt;
1510 
1511 	if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS, &host_time_pps))
1512 		return;
1513 
1514 	ptp_evt.type = PTP_CLOCK_PPSUSR;
1515 	ptp_evt.pps_times = host_time_pps;
1516 	ptp_clock_event(ptp->phc_clock, &ptp_evt);
1517 }
1518 
1519 static void efx_ptp_worker(struct work_struct *work)
1520 {
1521 	struct efx_ptp_data *ptp_data =
1522 		container_of(work, struct efx_ptp_data, work);
1523 	struct efx_nic *efx = ptp_data->efx;
1524 	struct sk_buff *skb;
1525 	struct sk_buff_head tempq;
1526 
1527 	if (ptp_data->reset_required) {
1528 		efx_ptp_stop(efx);
1529 		efx_ptp_start(efx);
1530 		return;
1531 	}
1532 
1533 	__skb_queue_head_init(&tempq);
1534 	efx_ptp_process_events(efx, &tempq);
1535 
1536 	while ((skb = skb_dequeue(&ptp_data->txq)))
1537 		ptp_data->xmit_skb(efx, skb);
1538 
1539 	while ((skb = __skb_dequeue(&tempq)))
1540 		efx_ptp_process_rx(efx, skb);
1541 }
1542 
1543 static void efx_ptp_cleanup_worker(struct work_struct *work)
1544 {
1545 	struct efx_ptp_data *ptp =
1546 		container_of(work, struct efx_ptp_data, cleanup_work.work);
1547 	struct efx_ptp_rxfilter *rxfilter, *tmp;
1548 
1549 	list_for_each_entry_safe(rxfilter, tmp, &ptp->rxfilters_ucast, list) {
1550 		if (time_is_before_jiffies(rxfilter->expiry))
1551 			efx_ptp_remove_one_filter(ptp->efx, rxfilter);
1552 	}
1553 
1554 	if (!list_empty(&ptp->rxfilters_ucast)) {
1555 		queue_delayed_work(ptp->workwq, &ptp->cleanup_work,
1556 				   UCAST_FILTER_EXPIRY_JIFFIES + 1);
1557 	}
1558 }
1559 
1560 static const struct ptp_clock_info efx_phc_clock_info = {
1561 	.owner		= THIS_MODULE,
1562 	.name		= "sfc",
1563 	.max_adj	= MAX_PPB,
1564 	.n_alarm	= 0,
1565 	.n_ext_ts	= 0,
1566 	.n_per_out	= 0,
1567 	.n_pins		= 0,
1568 	.pps		= 1,
1569 	.adjfine	= efx_phc_adjfine,
1570 	.adjtime	= efx_phc_adjtime,
1571 	.gettime64	= efx_phc_gettime,
1572 	.settime64	= efx_phc_settime,
1573 	.enable		= efx_phc_enable,
1574 };
1575 
1576 /* Initialise PTP state. */
1577 int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel)
1578 {
1579 	struct efx_ptp_data *ptp;
1580 	int rc = 0;
1581 
1582 	if (efx->ptp_data) {
1583 		efx->ptp_data->channel = channel;
1584 		return 0;
1585 	}
1586 
1587 	ptp = kzalloc_obj(struct efx_ptp_data);
1588 	efx->ptp_data = ptp;
1589 	if (!efx->ptp_data)
1590 		return -ENOMEM;
1591 
1592 	mutex_init(&ptp->phc_lock);
1593 	ptp->efx = efx;
1594 	ptp->channel = channel;
1595 
1596 	rc = efx_nic_alloc_buffer(efx, &ptp->start, sizeof(int), GFP_KERNEL);
1597 	if (rc != 0)
1598 		goto fail1;
1599 
1600 	skb_queue_head_init(&ptp->rxq);
1601 	skb_queue_head_init(&ptp->txq);
1602 	ptp->workwq = create_singlethread_workqueue("sfc_ptp");
1603 	if (!ptp->workwq) {
1604 		rc = -ENOMEM;
1605 		goto fail2;
1606 	}
1607 
1608 	if (efx_ptp_use_mac_tx_timestamps(efx)) {
1609 		ptp->xmit_skb = efx_ptp_xmit_skb_queue;
1610 		/* Request sync events on this channel. */
1611 		channel->sync_events_state = SYNC_EVENTS_QUIESCENT;
1612 	} else {
1613 		ptp->xmit_skb = efx_ptp_xmit_skb_mc;
1614 	}
1615 
1616 	INIT_WORK(&ptp->work, efx_ptp_worker);
1617 	INIT_DELAYED_WORK(&ptp->cleanup_work, efx_ptp_cleanup_worker);
1618 	ptp->config.flags = 0;
1619 	ptp->config.tx_type = HWTSTAMP_TX_OFF;
1620 	ptp->config.rx_filter = HWTSTAMP_FILTER_NONE;
1621 	INIT_LIST_HEAD(&ptp->rxfilters_mcast);
1622 	INIT_LIST_HEAD(&ptp->rxfilters_ucast);
1623 
1624 	/* Get the NIC PTP attributes and set up time conversions */
1625 	rc = efx_ptp_get_attributes(efx);
1626 	if (rc < 0)
1627 		goto fail3;
1628 
1629 	/* Get the timestamp corrections */
1630 	rc = efx_ptp_get_timestamp_corrections(efx);
1631 	if (rc < 0)
1632 		goto fail3;
1633 
1634 	if (efx->mcdi->fn_flags &
1635 	    (1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_PRIMARY)) {
1636 		ptp->phc_clock_info = efx_phc_clock_info;
1637 		ptp->phc_clock = ptp_clock_register(&ptp->phc_clock_info,
1638 						    &efx->pci_dev->dev);
1639 		if (IS_ERR(ptp->phc_clock)) {
1640 			rc = PTR_ERR(ptp->phc_clock);
1641 			goto fail3;
1642 		} else if (ptp->phc_clock) {
1643 			INIT_WORK(&ptp->pps_work, efx_ptp_pps_worker);
1644 			ptp->pps_workwq = create_singlethread_workqueue("sfc_pps");
1645 			if (!ptp->pps_workwq) {
1646 				rc = -ENOMEM;
1647 				goto fail4;
1648 			}
1649 		}
1650 	}
1651 	ptp->nic_ts_enabled = false;
1652 
1653 	return 0;
1654 fail4:
1655 	ptp_clock_unregister(efx->ptp_data->phc_clock);
1656 
1657 fail3:
1658 	destroy_workqueue(efx->ptp_data->workwq);
1659 
1660 fail2:
1661 	efx_nic_free_buffer(efx, &ptp->start);
1662 
1663 fail1:
1664 	mutex_destroy(&ptp->phc_lock);
1665 	kfree(efx->ptp_data);
1666 	efx->ptp_data = NULL;
1667 
1668 	return rc;
1669 }
1670 
1671 /* Initialise PTP channel.
1672  *
1673  * Setting core_index to zero causes the queue to be initialised and doesn't
1674  * overlap with 'rxq0' because ptp.c doesn't use skb_record_rx_queue.
1675  */
1676 static int efx_ptp_probe_channel(struct efx_channel *channel)
1677 {
1678 	struct efx_nic *efx = channel->efx;
1679 	int rc;
1680 
1681 	channel->irq_moderation_us = 0;
1682 	channel->rx_queue.core_index = 0;
1683 
1684 	rc = efx_ptp_probe(efx, channel);
1685 	/* Failure to probe PTP is not fatal; this channel will just not be
1686 	 * used for anything.
1687 	 * In the case of EPERM, efx_ptp_probe will print its own message (in
1688 	 * efx_ptp_get_attributes()), so we don't need to.
1689 	 */
1690 	if (rc && rc != -EPERM)
1691 		netif_warn(efx, drv, efx->net_dev,
1692 			   "Failed to probe PTP, rc=%d\n", rc);
1693 	return 0;
1694 }
1695 
1696 void efx_ptp_remove(struct efx_nic *efx)
1697 {
1698 	if (!efx->ptp_data)
1699 		return;
1700 
1701 	(void)efx_ptp_disable(efx);
1702 
1703 	cancel_work_sync(&efx->ptp_data->work);
1704 	cancel_delayed_work_sync(&efx->ptp_data->cleanup_work);
1705 	if (efx->ptp_data->pps_workwq)
1706 		cancel_work_sync(&efx->ptp_data->pps_work);
1707 
1708 	skb_queue_purge(&efx->ptp_data->rxq);
1709 	skb_queue_purge(&efx->ptp_data->txq);
1710 
1711 	if (efx->ptp_data->phc_clock) {
1712 		destroy_workqueue(efx->ptp_data->pps_workwq);
1713 		ptp_clock_unregister(efx->ptp_data->phc_clock);
1714 	}
1715 
1716 	destroy_workqueue(efx->ptp_data->workwq);
1717 
1718 	efx_nic_free_buffer(efx, &efx->ptp_data->start);
1719 	mutex_destroy(&efx->ptp_data->phc_lock);
1720 	kfree(efx->ptp_data);
1721 	efx->ptp_data = NULL;
1722 }
1723 
1724 static void efx_ptp_remove_channel(struct efx_channel *channel)
1725 {
1726 	efx_ptp_remove(channel->efx);
1727 }
1728 
1729 static void efx_ptp_get_channel_name(struct efx_channel *channel,
1730 				     char *buf, size_t len)
1731 {
1732 	snprintf(buf, len, "%s-ptp", channel->efx->name);
1733 }
1734 
1735 /* Determine whether this packet should be processed by the PTP module
1736  * or transmitted conventionally.
1737  */
1738 bool efx_ptp_is_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
1739 {
1740 	return efx->ptp_data &&
1741 		efx->ptp_data->enabled &&
1742 		skb->len >= PTP_MIN_LENGTH &&
1743 		skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM &&
1744 		likely(skb->protocol == htons(ETH_P_IP)) &&
1745 		skb_transport_header_was_set(skb) &&
1746 		skb_network_header_len(skb) >= sizeof(struct iphdr) &&
1747 		ip_hdr(skb)->protocol == IPPROTO_UDP &&
1748 		skb_headlen(skb) >=
1749 		skb_transport_offset(skb) + sizeof(struct udphdr) &&
1750 		udp_hdr(skb)->dest == htons(PTP_EVENT_PORT);
1751 }
1752 
1753 /* Receive a PTP packet.  Packets are queued until the arrival of
1754  * the receive timestamp from the MC - this will probably occur after the
1755  * packet arrival because of the processing in the MC.
1756  */
1757 static bool efx_ptp_rx(struct efx_channel *channel, struct sk_buff *skb)
1758 {
1759 	struct efx_nic *efx = channel->efx;
1760 	struct efx_ptp_data *ptp = efx->ptp_data;
1761 	struct efx_ptp_match *match = (struct efx_ptp_match *)skb->cb;
1762 	unsigned int version;
1763 	u8 *data;
1764 
1765 	match->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
1766 
1767 	/* Correct version? */
1768 	if (ptp->mode == MC_CMD_PTP_MODE_V1) {
1769 		if (!pskb_may_pull(skb, PTP_V1_MIN_LENGTH)) {
1770 			return false;
1771 		}
1772 		data = skb->data;
1773 		version = ntohs(*(__be16 *)&data[PTP_V1_VERSION_OFFSET]);
1774 		if (version != PTP_VERSION_V1) {
1775 			return false;
1776 		}
1777 	} else {
1778 		if (!pskb_may_pull(skb, PTP_V2_MIN_LENGTH)) {
1779 			return false;
1780 		}
1781 		data = skb->data;
1782 		version = data[PTP_V2_VERSION_OFFSET];
1783 		if ((version & PTP_VERSION_V2_MASK) != PTP_VERSION_V2) {
1784 			return false;
1785 		}
1786 	}
1787 
1788 	/* Does this packet require timestamping? */
1789 	if (ntohs(*(__be16 *)&data[PTP_DPORT_OFFSET]) == PTP_EVENT_PORT) {
1790 		match->state = PTP_PACKET_STATE_UNMATCHED;
1791 
1792 		/* We expect the sequence number to be in the same position in
1793 		 * the packet for PTP V1 and V2
1794 		 */
1795 		BUILD_BUG_ON(PTP_V1_SEQUENCE_OFFSET != PTP_V2_SEQUENCE_OFFSET);
1796 		BUILD_BUG_ON(PTP_V1_SEQUENCE_LENGTH != PTP_V2_SEQUENCE_LENGTH);
1797 	} else {
1798 		match->state = PTP_PACKET_STATE_MATCH_UNWANTED;
1799 	}
1800 
1801 	skb_queue_tail(&ptp->rxq, skb);
1802 	queue_work(ptp->workwq, &ptp->work);
1803 
1804 	return true;
1805 }
1806 
1807 /* Transmit a PTP packet.  This has to be transmitted by the MC
1808  * itself, through an MCDI call.  MCDI calls aren't permitted
1809  * in the transmit path so defer the actual transmission to a suitable worker.
1810  */
1811 int efx_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
1812 {
1813 	struct efx_ptp_data *ptp = efx->ptp_data;
1814 
1815 	skb_queue_tail(&ptp->txq, skb);
1816 
1817 	if ((udp_hdr(skb)->dest == htons(PTP_EVENT_PORT)) &&
1818 	    (skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM))
1819 		efx_xmit_hwtstamp_pending(skb);
1820 	queue_work(ptp->workwq, &ptp->work);
1821 
1822 	return NETDEV_TX_OK;
1823 }
1824 
1825 int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted,
1826 			unsigned int new_mode)
1827 {
1828 	if ((enable_wanted != efx->ptp_data->enabled) ||
1829 	    (enable_wanted && (efx->ptp_data->mode != new_mode))) {
1830 		int rc = 0;
1831 
1832 		if (enable_wanted) {
1833 			/* Change of mode requires disable */
1834 			if (efx->ptp_data->enabled &&
1835 			    (efx->ptp_data->mode != new_mode)) {
1836 				efx->ptp_data->enabled = false;
1837 				rc = efx_ptp_stop(efx);
1838 				if (rc != 0)
1839 					return rc;
1840 			}
1841 
1842 			/* Set new operating mode and establish
1843 			 * baseline synchronisation, which must
1844 			 * succeed.
1845 			 */
1846 			efx->ptp_data->mode = new_mode;
1847 			if (netif_running(efx->net_dev))
1848 				rc = efx_ptp_start(efx);
1849 			if (rc == 0) {
1850 				rc = efx_ptp_synchronize(efx,
1851 							 PTP_SYNC_ATTEMPTS * 2,
1852 							 NULL);
1853 				if (rc != 0)
1854 					efx_ptp_stop(efx);
1855 			}
1856 		} else {
1857 			rc = efx_ptp_stop(efx);
1858 		}
1859 
1860 		if (rc != 0)
1861 			return rc;
1862 
1863 		efx->ptp_data->enabled = enable_wanted;
1864 	}
1865 
1866 	return 0;
1867 }
1868 
1869 static int efx_ptp_ts_init(struct efx_nic *efx, struct kernel_hwtstamp_config *init)
1870 {
1871 	int rc;
1872 
1873 	if ((init->tx_type != HWTSTAMP_TX_OFF) &&
1874 	    (init->tx_type != HWTSTAMP_TX_ON))
1875 		return -ERANGE;
1876 
1877 	rc = efx->type->ptp_set_ts_config(efx, init);
1878 	if (rc)
1879 		return rc;
1880 
1881 	efx->ptp_data->config = *init;
1882 	return 0;
1883 }
1884 
1885 void efx_ptp_get_ts_info(struct efx_nic *efx, struct kernel_ethtool_ts_info *ts_info)
1886 {
1887 	struct efx_ptp_data *ptp = efx->ptp_data;
1888 	struct efx_nic *primary = efx->primary;
1889 
1890 	ASSERT_RTNL();
1891 
1892 	if (!ptp)
1893 		return;
1894 
1895 	ts_info->so_timestamping |= (SOF_TIMESTAMPING_TX_HARDWARE |
1896 				     SOF_TIMESTAMPING_RX_HARDWARE |
1897 				     SOF_TIMESTAMPING_RAW_HARDWARE);
1898 	/* Check licensed features.  If we don't have the license for TX
1899 	 * timestamps, the NIC will not support them.
1900 	 */
1901 	if (efx_ptp_use_mac_tx_timestamps(efx)) {
1902 		struct efx_ef10_nic_data *nic_data = efx->nic_data;
1903 
1904 		if (!(nic_data->licensed_features &
1905 		      (1 << LICENSED_V3_FEATURES_TX_TIMESTAMPS_LBN)))
1906 			ts_info->so_timestamping &=
1907 				~SOF_TIMESTAMPING_TX_HARDWARE;
1908 	}
1909 	if (primary && primary->ptp_data && primary->ptp_data->phc_clock)
1910 		ts_info->phc_index =
1911 			ptp_clock_index(primary->ptp_data->phc_clock);
1912 	ts_info->tx_types = 1 << HWTSTAMP_TX_OFF | 1 << HWTSTAMP_TX_ON;
1913 	ts_info->rx_filters = ptp->efx->type->hwtstamp_filters;
1914 }
1915 
1916 int efx_ptp_set_ts_config(struct efx_nic *efx,
1917 			  struct kernel_hwtstamp_config *config,
1918 			  struct netlink_ext_ack __always_unused *extack)
1919 {
1920 	/* Not a PTP enabled port */
1921 	if (!efx->ptp_data)
1922 		return -EOPNOTSUPP;
1923 
1924 	return efx_ptp_ts_init(efx, config);
1925 }
1926 
1927 int efx_ptp_get_ts_config(struct efx_nic *efx,
1928 			  struct kernel_hwtstamp_config *config)
1929 {
1930 	/* Not a PTP enabled port */
1931 	if (!efx->ptp_data)
1932 		return -EOPNOTSUPP;
1933 	*config = efx->ptp_data->config;
1934 	return 0;
1935 }
1936 
1937 static void ptp_event_failure(struct efx_nic *efx, int expected_frag_len)
1938 {
1939 	struct efx_ptp_data *ptp = efx->ptp_data;
1940 
1941 	netif_err(efx, hw, efx->net_dev,
1942 		"PTP unexpected event length: got %d expected %d\n",
1943 		ptp->evt_frag_idx, expected_frag_len);
1944 	ptp->reset_required = true;
1945 	queue_work(ptp->workwq, &ptp->work);
1946 }
1947 
1948 static void ptp_event_fault(struct efx_nic *efx, struct efx_ptp_data *ptp)
1949 {
1950 	int code = EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA);
1951 	if (ptp->evt_frag_idx != 1) {
1952 		ptp_event_failure(efx, 1);
1953 		return;
1954 	}
1955 
1956 	netif_err(efx, hw, efx->net_dev, "PTP error %d\n", code);
1957 }
1958 
1959 static void ptp_event_pps(struct efx_nic *efx, struct efx_ptp_data *ptp)
1960 {
1961 	if (ptp->nic_ts_enabled)
1962 		queue_work(ptp->pps_workwq, &ptp->pps_work);
1963 }
1964 
1965 void efx_ptp_event(struct efx_nic *efx, efx_qword_t *ev)
1966 {
1967 	struct efx_ptp_data *ptp = efx->ptp_data;
1968 	int code = EFX_QWORD_FIELD(*ev, MCDI_EVENT_CODE);
1969 
1970 	if (!ptp) {
1971 		if (!efx->ptp_warned) {
1972 			netif_warn(efx, drv, efx->net_dev,
1973 				   "Received PTP event but PTP not set up\n");
1974 			efx->ptp_warned = true;
1975 		}
1976 		return;
1977 	}
1978 
1979 	if (!ptp->enabled)
1980 		return;
1981 
1982 	if (ptp->evt_frag_idx == 0) {
1983 		ptp->evt_code = code;
1984 	} else if (ptp->evt_code != code) {
1985 		netif_err(efx, hw, efx->net_dev,
1986 			  "PTP out of sequence event %d\n", code);
1987 		ptp->evt_frag_idx = 0;
1988 	}
1989 
1990 	ptp->evt_frags[ptp->evt_frag_idx++] = *ev;
1991 	if (!MCDI_EVENT_FIELD(*ev, CONT)) {
1992 		/* Process resulting event */
1993 		switch (code) {
1994 		case MCDI_EVENT_CODE_PTP_FAULT:
1995 			ptp_event_fault(efx, ptp);
1996 			break;
1997 		case MCDI_EVENT_CODE_PTP_PPS:
1998 			ptp_event_pps(efx, ptp);
1999 			break;
2000 		default:
2001 			netif_err(efx, hw, efx->net_dev,
2002 				  "PTP unknown event %d\n", code);
2003 			break;
2004 		}
2005 		ptp->evt_frag_idx = 0;
2006 	} else if (MAX_EVENT_FRAGS == ptp->evt_frag_idx) {
2007 		netif_err(efx, hw, efx->net_dev,
2008 			  "PTP too many event fragments\n");
2009 		ptp->evt_frag_idx = 0;
2010 	}
2011 }
2012 
2013 void efx_time_sync_event(struct efx_channel *channel, efx_qword_t *ev)
2014 {
2015 	struct efx_nic *efx = channel->efx;
2016 	struct efx_ptp_data *ptp = efx->ptp_data;
2017 
2018 	/* When extracting the sync timestamp minor value, we should discard
2019 	 * the least significant two bits. These are not required in order
2020 	 * to reconstruct full-range timestamps and they are optionally used
2021 	 * to report status depending on the options supplied when subscribing
2022 	 * for sync events.
2023 	 */
2024 	channel->sync_timestamp_major = MCDI_EVENT_FIELD(*ev, PTP_TIME_MAJOR);
2025 	channel->sync_timestamp_minor =
2026 		(MCDI_EVENT_FIELD(*ev, PTP_TIME_MINOR_MS_8BITS) & 0xFC)
2027 			<< ptp->nic_time.sync_event_minor_shift;
2028 
2029 	/* if sync events have been disabled then we want to silently ignore
2030 	 * this event, so throw away result.
2031 	 */
2032 	(void) cmpxchg(&channel->sync_events_state, SYNC_EVENTS_REQUESTED,
2033 		       SYNC_EVENTS_VALID);
2034 }
2035 
2036 static inline u32 efx_rx_buf_timestamp_minor(struct efx_nic *efx, const u8 *eh)
2037 {
2038 #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
2039 	return __le32_to_cpup((const __le32 *)(eh + efx->rx_packet_ts_offset));
2040 #else
2041 	const u8 *data = eh + efx->rx_packet_ts_offset;
2042 	return (u32)data[0]       |
2043 	       (u32)data[1] << 8  |
2044 	       (u32)data[2] << 16 |
2045 	       (u32)data[3] << 24;
2046 #endif
2047 }
2048 
2049 void __efx_rx_skb_attach_timestamp(struct efx_channel *channel,
2050 				   struct sk_buff *skb)
2051 {
2052 	struct efx_nic *efx = channel->efx;
2053 	struct efx_ptp_data *ptp = efx->ptp_data;
2054 	u32 pkt_timestamp_major, pkt_timestamp_minor;
2055 	u32 diff, carry;
2056 	struct skb_shared_hwtstamps *timestamps;
2057 
2058 	if (channel->sync_events_state != SYNC_EVENTS_VALID)
2059 		return;
2060 
2061 	pkt_timestamp_minor = efx_rx_buf_timestamp_minor(efx, skb_mac_header(skb));
2062 
2063 	/* get the difference between the packet and sync timestamps,
2064 	 * modulo one second
2065 	 */
2066 	diff = pkt_timestamp_minor - channel->sync_timestamp_minor;
2067 	if (pkt_timestamp_minor < channel->sync_timestamp_minor)
2068 		diff += ptp->nic_time.minor_max;
2069 
2070 	/* do we roll over a second boundary and need to carry the one? */
2071 	carry = (channel->sync_timestamp_minor >= ptp->nic_time.minor_max - diff) ?
2072 		1 : 0;
2073 
2074 	if (diff <= ptp->nic_time.sync_event_diff_max) {
2075 		/* packet is ahead of the sync event by a quarter of a second or
2076 		 * less (allowing for fuzz)
2077 		 */
2078 		pkt_timestamp_major = channel->sync_timestamp_major + carry;
2079 	} else if (diff >= ptp->nic_time.sync_event_diff_min) {
2080 		/* packet is behind the sync event but within the fuzz factor.
2081 		 * This means the RX packet and sync event crossed as they were
2082 		 * placed on the event queue, which can sometimes happen.
2083 		 */
2084 		pkt_timestamp_major = channel->sync_timestamp_major - 1 + carry;
2085 	} else {
2086 		/* it's outside tolerance in both directions. this might be
2087 		 * indicative of us missing sync events for some reason, so
2088 		 * we'll call it an error rather than risk giving a bogus
2089 		 * timestamp.
2090 		 */
2091 		netif_vdbg(efx, drv, efx->net_dev,
2092 			  "packet timestamp %x too far from sync event %x:%x\n",
2093 			  pkt_timestamp_minor, channel->sync_timestamp_major,
2094 			  channel->sync_timestamp_minor);
2095 		return;
2096 	}
2097 
2098 	/* attach the timestamps to the skb */
2099 	timestamps = skb_hwtstamps(skb);
2100 	timestamps->hwtstamp =
2101 		ptp->nic_to_kernel_time(pkt_timestamp_major,
2102 					pkt_timestamp_minor,
2103 					ptp->ts_corrections.general_rx);
2104 }
2105 
2106 static int efx_phc_adjfine(struct ptp_clock_info *ptp, long scaled_ppm)
2107 {
2108 	struct efx_ptp_data *ptp_data = container_of(ptp,
2109 						     struct efx_ptp_data,
2110 						     phc_clock_info);
2111 	s32 delta = scaled_ppm_to_ppb(scaled_ppm);
2112 	struct efx_nic *efx = ptp_data->efx;
2113 	MCDI_DECLARE_BUF(inadj, MC_CMD_PTP_IN_ADJUST_LEN);
2114 	s64 adjustment_ns;
2115 	int rc;
2116 
2117 	if (delta > MAX_PPB)
2118 		delta = MAX_PPB;
2119 	else if (delta < -MAX_PPB)
2120 		delta = -MAX_PPB;
2121 
2122 	/* Convert ppb to fixed point ns taking care to round correctly. */
2123 	adjustment_ns = ((s64)delta * PPB_SCALE_WORD +
2124 			 (1 << (ptp_data->adjfreq_ppb_shift - 1))) >>
2125 			ptp_data->adjfreq_ppb_shift;
2126 
2127 	MCDI_SET_DWORD(inadj, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
2128 	MCDI_SET_DWORD(inadj, PTP_IN_PERIPH_ID, 0);
2129 	MCDI_SET_QWORD(inadj, PTP_IN_ADJUST_FREQ, adjustment_ns);
2130 	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_SECONDS, 0);
2131 	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_NANOSECONDS, 0);
2132 	mutex_lock(&ptp_data->phc_lock);
2133 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inadj, sizeof(inadj),
2134 			  NULL, 0, NULL);
2135 	if (!rc)
2136 		ptp_data->current_adjfreq = adjustment_ns;
2137 	mutex_unlock(&ptp_data->phc_lock);
2138 	return rc;
2139 }
2140 
2141 static int _efx_phc_adjtime(struct efx_ptp_data *ptp_data, s64 delta)
2142 	__must_hold(&ptp_data->phc_lock)
2143 {
2144 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ADJUST_LEN);
2145 	struct efx_nic *efx = ptp_data->efx;
2146 	u32 nic_major, nic_minor;
2147 
2148 	lockdep_assert_held(&ptp_data->phc_lock);
2149 
2150 	efx->ptp_data->ns_to_nic_time(delta, &nic_major, &nic_minor);
2151 
2152 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
2153 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
2154 	MCDI_SET_QWORD(inbuf, PTP_IN_ADJUST_FREQ, ptp_data->current_adjfreq);
2155 	MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_MAJOR, nic_major);
2156 	MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_MINOR, nic_minor);
2157 	return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
2158 			    NULL, 0, NULL);
2159 }
2160 
2161 static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta)
2162 {
2163 	struct efx_ptp_data *ptp_data = container_of(ptp, struct efx_ptp_data,
2164 						  phc_clock_info);
2165 	int rc;
2166 
2167 	mutex_lock(&ptp_data->phc_lock);
2168 	rc = _efx_phc_adjtime(ptp_data, delta);
2169 	mutex_unlock(&ptp_data->phc_lock);
2170 	return rc;
2171 }
2172 
2173 static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts)
2174 {
2175 	struct efx_ptp_data *ptp_data = container_of(ptp,
2176 						     struct efx_ptp_data,
2177 						     phc_clock_info);
2178 	struct efx_nic *efx = ptp_data->efx;
2179 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_READ_NIC_TIME_LEN);
2180 	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_READ_NIC_TIME_LEN);
2181 	int rc;
2182 	ktime_t kt;
2183 
2184 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_READ_NIC_TIME);
2185 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
2186 
2187 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
2188 			  outbuf, sizeof(outbuf), NULL);
2189 	if (rc != 0)
2190 		return rc;
2191 
2192 	kt = ptp_data->nic_to_kernel_time(
2193 		MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_MAJOR),
2194 		MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_MINOR), 0);
2195 	*ts = ktime_to_timespec64(kt);
2196 	return 0;
2197 }
2198 
2199 static int efx_phc_settime(struct ptp_clock_info *ptp,
2200 			   const struct timespec64 *e_ts)
2201 {
2202 	/* Get the current NIC time, efx_phc_gettime.
2203 	 * Subtract from the desired time to get the offset
2204 	 * call _efx_phc_adjtime with the offset
2205 	 */
2206 	struct efx_ptp_data *ptp_data = container_of(ptp, struct efx_ptp_data,
2207 						  phc_clock_info);
2208 	struct timespec64 time_now, delta;
2209 	int rc;
2210 
2211 	mutex_lock(&ptp_data->phc_lock);
2212 	rc = efx_phc_gettime(ptp, &time_now);
2213 	if (!rc) {
2214 		delta = timespec64_sub(*e_ts, time_now);
2215 		rc = _efx_phc_adjtime(ptp_data, timespec64_to_ns(&delta));
2216 	}
2217 	mutex_unlock(&ptp_data->phc_lock);
2218 	return rc;
2219 }
2220 
2221 static int efx_phc_enable(struct ptp_clock_info *ptp,
2222 			  struct ptp_clock_request *request,
2223 			  int enable)
2224 {
2225 	struct efx_ptp_data *ptp_data = container_of(ptp,
2226 						     struct efx_ptp_data,
2227 						     phc_clock_info);
2228 	if (request->type != PTP_CLK_REQ_PPS)
2229 		return -EOPNOTSUPP;
2230 
2231 	ptp_data->nic_ts_enabled = !!enable;
2232 	return 0;
2233 }
2234 
2235 static const struct efx_channel_type efx_ptp_channel_type = {
2236 	.handle_no_channel	= efx_ptp_handle_no_channel,
2237 	.pre_probe		= efx_ptp_probe_channel,
2238 	.post_remove		= efx_ptp_remove_channel,
2239 	.get_name		= efx_ptp_get_channel_name,
2240 	.copy                   = efx_copy_channel,
2241 	.receive_skb		= efx_ptp_rx,
2242 	.want_txqs		= efx_ptp_want_txqs,
2243 	.keep_eventq		= false,
2244 };
2245 
2246 void efx_ptp_defer_probe_with_channel(struct efx_nic *efx)
2247 {
2248 	/* Check whether PTP is implemented on this NIC.  The DISABLE
2249 	 * operation will succeed if and only if it is implemented.
2250 	 */
2251 	if (efx_ptp_disable(efx) == 0)
2252 		efx->extra_channel_type[EFX_EXTRA_CHANNEL_PTP] =
2253 			&efx_ptp_channel_type;
2254 }
2255 
2256 void efx_ptp_start_datapath(struct efx_nic *efx)
2257 {
2258 	if (efx_ptp_restart(efx))
2259 		netif_err(efx, drv, efx->net_dev, "Failed to restart PTP.\n");
2260 	/* re-enable timestamping if it was previously enabled */
2261 	if (efx->type->ptp_set_ts_sync_events)
2262 		efx->type->ptp_set_ts_sync_events(efx, true, true);
2263 }
2264 
2265 void efx_ptp_stop_datapath(struct efx_nic *efx)
2266 {
2267 	/* temporarily disable timestamping */
2268 	if (efx->type->ptp_set_ts_sync_events)
2269 		efx->type->ptp_set_ts_sync_events(efx, false, true);
2270 	efx_ptp_stop(efx);
2271 }
2272