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