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