xref: /linux/drivers/net/ethernet/intel/ice/ice_ptp.c (revision 7e1392a42ea288d70a266f6553fe06f57f8647ea)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (C) 2021, Intel Corporation. */
3 
4 #include <linux/rculist.h>
5 #include <linux/srcu.h>
6 #include <linux/wait_bit.h>
7 #include "ice.h"
8 #include "ice_lib.h"
9 #include "ice_trace.h"
10 #include "ice_tspll.h"
11 #include "ice_txclk.h"
12 
13 #define ICE_TSPLL_LOG_INTERVAL		120
14 
15 static const char ice_pin_names[][64] = {
16 	"SDP0",
17 	"SDP1",
18 	"SDP2",
19 	"SDP3",
20 	"TIME_SYNC",
21 	"1PPS"
22 };
23 
24 static const struct ice_ptp_pin_desc ice_pin_desc_e82x[] = {
25 	/* name,        gpio,       delay */
26 	{  TIME_SYNC, {  4, -1 }, { 0,  0 }},
27 	{  ONE_PPS,   { -1,  5 }, { 0, 11 }},
28 };
29 
30 static const struct ice_ptp_pin_desc ice_pin_desc_e825c[] = {
31 	/* name,        gpio,       delay */
32 	{  SDP0,      {  0,  0 }, { 15, 14 }},
33 	{  SDP1,      {  1,  1 }, { 15, 14 }},
34 	{  SDP2,      {  2,  2 }, { 15, 14 }},
35 	{  SDP3,      {  3,  3 }, { 15, 14 }},
36 	{  TIME_SYNC, {  4, -1 }, { 11,  0 }},
37 	{  ONE_PPS,   { -1,  5 }, {  0,  9 }},
38 };
39 
40 static const struct ice_ptp_pin_desc ice_pin_desc_e810[] = {
41 	/* name,        gpio,       delay */
42 	{  SDP0,      {  0,  0 }, { 0, 1 }},
43 	{  SDP1,      {  1,  1 }, { 0, 1 }},
44 	{  SDP2,      {  2,  2 }, { 0, 1 }},
45 	{  SDP3,      {  3,  3 }, { 0, 1 }},
46 	{  ONE_PPS,   { -1,  5 }, { 0, 1 }},
47 };
48 
49 static const char ice_pin_names_dpll[][64] = {
50 	"SDP20",
51 	"SDP21",
52 	"SDP22",
53 	"SDP23",
54 };
55 
56 static const struct ice_ptp_pin_desc ice_pin_desc_dpll[] = {
57 	/* name,   gpio,       delay */
58 	{  SDP0, { -1,  0 }, { 0, 1 }},
59 	{  SDP1, {  1, -1 }, { 0, 0 }},
60 	{  SDP2, { -1,  2 }, { 0, 1 }},
61 	{  SDP3, {  3, -1 }, { 0, 0 }},
62 };
63 
64 static struct ice_ptp *ice_get_ctrl_ptp(struct ice_pf *pf)
65 {
66 	struct ice_pf *ctrl_pf = ice_get_ctrl_pf(pf);
67 
68 	return !ctrl_pf ? NULL : &ctrl_pf->ptp;
69 }
70 
71 /**
72  * ice_ptp_find_pin_idx - Find pin index in ptp_pin_desc
73  * @pf: Board private structure
74  * @func: Pin function
75  * @chan: GPIO channel
76  *
77  * Return: positive pin number when pin is present, -1 otherwise
78  */
79 static int ice_ptp_find_pin_idx(struct ice_pf *pf, enum ptp_pin_function func,
80 				unsigned int chan)
81 {
82 	const struct ptp_clock_info *info = &pf->ptp.info;
83 	int i;
84 
85 	for (i = 0; i < info->n_pins; i++) {
86 		if (info->pin_config[i].func == func &&
87 		    info->pin_config[i].chan == chan)
88 			return i;
89 	}
90 
91 	return -1;
92 }
93 
94 /**
95  * ice_ptp_cfg_tx_interrupt - Configure Tx timestamp interrupt for the device
96  * @pf: Board private structure
97  *
98  * Program the device to respond appropriately to the Tx timestamp interrupt
99  * cause.
100  */
101 static void ice_ptp_cfg_tx_interrupt(struct ice_pf *pf)
102 {
103 	struct ice_hw *hw = &pf->hw;
104 	bool enable;
105 	u32 val;
106 
107 	switch (pf->ptp.tx_interrupt_mode) {
108 	case ICE_PTP_TX_INTERRUPT_ALL:
109 		/* React to interrupts across all quads. */
110 		wr32(hw, PFINT_TSYN_MSK + (0x4 * hw->pf_id), (u32)0x1f);
111 		enable = true;
112 		break;
113 	case ICE_PTP_TX_INTERRUPT_NONE:
114 		/* Do not react to interrupts on any quad. */
115 		wr32(hw, PFINT_TSYN_MSK + (0x4 * hw->pf_id), (u32)0x0);
116 		enable = false;
117 		break;
118 	case ICE_PTP_TX_INTERRUPT_SELF:
119 	default:
120 		enable = pf->ptp.tstamp_config.tx_type == HWTSTAMP_TX_ON;
121 		break;
122 	}
123 
124 	/* Configure the Tx timestamp interrupt */
125 	val = rd32(hw, PFINT_OICR_ENA);
126 	if (enable)
127 		val |= PFINT_OICR_TSYN_TX_M;
128 	else
129 		val &= ~PFINT_OICR_TSYN_TX_M;
130 	wr32(hw, PFINT_OICR_ENA, val);
131 }
132 
133 /**
134  * ice_set_rx_tstamp - Enable or disable Rx timestamping
135  * @pf: The PF pointer to search in
136  * @on: bool value for whether timestamps are enabled or disabled
137  */
138 static void ice_set_rx_tstamp(struct ice_pf *pf, bool on)
139 {
140 	struct ice_vsi *vsi;
141 	u16 i;
142 
143 	vsi = ice_get_main_vsi(pf);
144 	if (!vsi || !vsi->rx_rings)
145 		return;
146 
147 	/* Set the timestamp flag for all the Rx rings */
148 	ice_for_each_rxq(vsi, i) {
149 		if (!vsi->rx_rings[i])
150 			continue;
151 		vsi->rx_rings[i]->ptp_rx = on;
152 	}
153 }
154 
155 /**
156  * ice_ptp_disable_timestamp_mode - Disable current timestamp mode
157  * @pf: Board private structure
158  *
159  * Called during preparation for reset to temporarily disable timestamping on
160  * the device. Called during remove to disable timestamping while cleaning up
161  * driver resources.
162  */
163 static void ice_ptp_disable_timestamp_mode(struct ice_pf *pf)
164 {
165 	struct ice_hw *hw = &pf->hw;
166 	u32 val;
167 
168 	val = rd32(hw, PFINT_OICR_ENA);
169 	val &= ~PFINT_OICR_TSYN_TX_M;
170 	wr32(hw, PFINT_OICR_ENA, val);
171 
172 	ice_set_rx_tstamp(pf, false);
173 }
174 
175 /**
176  * ice_ptp_restore_timestamp_mode - Restore timestamp configuration
177  * @pf: Board private structure
178  *
179  * Called at the end of rebuild to restore timestamp configuration after
180  * a device reset.
181  */
182 void ice_ptp_restore_timestamp_mode(struct ice_pf *pf)
183 {
184 	struct ice_hw *hw = &pf->hw;
185 	bool enable_rx;
186 
187 	ice_ptp_cfg_tx_interrupt(pf);
188 
189 	enable_rx = pf->ptp.tstamp_config.rx_filter == HWTSTAMP_FILTER_ALL;
190 	ice_set_rx_tstamp(pf, enable_rx);
191 
192 	/* Trigger an immediate software interrupt to ensure that timestamps
193 	 * which occurred during reset are handled now.
194 	 */
195 	wr32(hw, PFINT_OICR, PFINT_OICR_TSYN_TX_M);
196 	ice_flush(hw);
197 }
198 
199 /**
200  * ice_ptp_read_src_clk_reg - Read the source clock register
201  * @pf: Board private structure
202  * @sts: Optional parameter for holding a pair of system timestamps from
203  *       the system clock. Will be ignored if NULL is given.
204  */
205 u64 ice_ptp_read_src_clk_reg(struct ice_pf *pf,
206 			     struct ptp_system_timestamp *sts)
207 {
208 	struct ice_hw *hw = &pf->hw;
209 	u32 hi, lo, lo2;
210 	u8 tmr_idx;
211 
212 	if (!ice_is_primary(hw))
213 		hw = ice_get_primary_hw(pf);
214 
215 	tmr_idx = ice_get_ptp_src_clock_index(hw);
216 	guard(spinlock)(&pf->adapter->ptp_gltsyn_time_lock);
217 	/* Read the system timestamp pre PHC read */
218 	ptp_read_system_prets(sts);
219 
220 	if (hw->mac_type == ICE_MAC_E830) {
221 		u64 clk_time = rd64(hw, E830_GLTSYN_TIME_L(tmr_idx));
222 
223 		/* Read the system timestamp post PHC read */
224 		ptp_read_system_postts(sts);
225 
226 		return clk_time;
227 	}
228 
229 	lo = rd32(hw, GLTSYN_TIME_L(tmr_idx));
230 
231 	/* Read the system timestamp post PHC read */
232 	ptp_read_system_postts(sts);
233 
234 	hi = rd32(hw, GLTSYN_TIME_H(tmr_idx));
235 	lo2 = rd32(hw, GLTSYN_TIME_L(tmr_idx));
236 
237 	if (lo2 < lo) {
238 		/* if TIME_L rolled over read TIME_L again and update
239 		 * system timestamps
240 		 */
241 		ptp_read_system_prets(sts);
242 		lo = rd32(hw, GLTSYN_TIME_L(tmr_idx));
243 		ptp_read_system_postts(sts);
244 		hi = rd32(hw, GLTSYN_TIME_H(tmr_idx));
245 	}
246 
247 	return ((u64)hi << 32) | lo;
248 }
249 
250 /**
251  * ice_ptp_extend_32b_ts - Convert a 32b nanoseconds timestamp to 64b
252  * @cached_phc_time: recently cached copy of PHC time
253  * @in_tstamp: Ingress/egress 32b nanoseconds timestamp value
254  *
255  * Hardware captures timestamps which contain only 32 bits of nominal
256  * nanoseconds, as opposed to the 64bit timestamps that the stack expects.
257  * Note that the captured timestamp values may be 40 bits, but the lower
258  * 8 bits are sub-nanoseconds and generally discarded.
259  *
260  * Extend the 32bit nanosecond timestamp using the following algorithm and
261  * assumptions:
262  *
263  * 1) have a recently cached copy of the PHC time
264  * 2) assume that the in_tstamp was captured 2^31 nanoseconds (~2.1
265  *    seconds) before or after the PHC time was captured.
266  * 3) calculate the delta between the cached time and the timestamp
267  * 4) if the delta is smaller than 2^31 nanoseconds, then the timestamp was
268  *    captured after the PHC time. In this case, the full timestamp is just
269  *    the cached PHC time plus the delta.
270  * 5) otherwise, if the delta is larger than 2^31 nanoseconds, then the
271  *    timestamp was captured *before* the PHC time, i.e. because the PHC
272  *    cache was updated after the timestamp was captured by hardware. In this
273  *    case, the full timestamp is the cached time minus the inverse delta.
274  *
275  * This algorithm works even if the PHC time was updated after a Tx timestamp
276  * was requested, but before the Tx timestamp event was reported from
277  * hardware.
278  *
279  * This calculation primarily relies on keeping the cached PHC time up to
280  * date. If the timestamp was captured more than 2^31 nanoseconds after the
281  * PHC time, it is possible that the lower 32bits of PHC time have
282  * overflowed more than once, and we might generate an incorrect timestamp.
283  *
284  * This is prevented by (a) periodically updating the cached PHC time once
285  * a second, and (b) discarding any Tx timestamp packet if it has waited for
286  * a timestamp for more than one second.
287  */
288 static u64 ice_ptp_extend_32b_ts(u64 cached_phc_time, u32 in_tstamp)
289 {
290 	u32 delta, phc_time_lo;
291 	u64 ns;
292 
293 	/* Extract the lower 32 bits of the PHC time */
294 	phc_time_lo = (u32)cached_phc_time;
295 
296 	/* Calculate the delta between the lower 32bits of the cached PHC
297 	 * time and the in_tstamp value
298 	 */
299 	delta = (in_tstamp - phc_time_lo);
300 
301 	/* Do not assume that the in_tstamp is always more recent than the
302 	 * cached PHC time. If the delta is large, it indicates that the
303 	 * in_tstamp was taken in the past, and should be converted
304 	 * forward.
305 	 */
306 	if (delta > (U32_MAX / 2)) {
307 		/* reverse the delta calculation here */
308 		delta = (phc_time_lo - in_tstamp);
309 		ns = cached_phc_time - delta;
310 	} else {
311 		ns = cached_phc_time + delta;
312 	}
313 
314 	return ns;
315 }
316 
317 /**
318  * ice_ptp_extend_40b_ts - Convert a 40b timestamp to 64b nanoseconds
319  * @pf: Board private structure
320  * @in_tstamp: Ingress/egress 40b timestamp value
321  *
322  * The Tx and Rx timestamps are 40 bits wide, including 32 bits of nominal
323  * nanoseconds, 7 bits of sub-nanoseconds, and a valid bit.
324  *
325  *  *--------------------------------------------------------------*
326  *  | 32 bits of nanoseconds | 7 high bits of sub ns underflow | v |
327  *  *--------------------------------------------------------------*
328  *
329  * The low bit is an indicator of whether the timestamp is valid. The next
330  * 7 bits are a capture of the upper 7 bits of the sub-nanosecond underflow,
331  * and the remaining 32 bits are the lower 32 bits of the PHC timer.
332  *
333  * It is assumed that the caller verifies the timestamp is valid prior to
334  * calling this function.
335  *
336  * Extract the 32bit nominal nanoseconds and extend them. Use the cached PHC
337  * time stored in the device private PTP structure as the basis for timestamp
338  * extension.
339  *
340  * See ice_ptp_extend_32b_ts for a detailed explanation of the extension
341  * algorithm.
342  */
343 static u64 ice_ptp_extend_40b_ts(struct ice_pf *pf, u64 in_tstamp)
344 {
345 	const u64 mask = GENMASK_ULL(31, 0);
346 	unsigned long discard_time;
347 
348 	/* Discard the hardware timestamp if the cached PHC time is too old */
349 	discard_time = pf->ptp.cached_phc_jiffies + msecs_to_jiffies(2000);
350 	if (time_is_before_jiffies(discard_time)) {
351 		pf->ptp.tx_hwtstamp_discarded++;
352 		return 0;
353 	}
354 
355 	return ice_ptp_extend_32b_ts(READ_ONCE(pf->ptp.cached_phc_time),
356 				     (in_tstamp >> 8) & mask);
357 }
358 
359 /**
360  * ice_ptp_is_tx_tracker_up - Check if Tx tracker is ready for new timestamps
361  * @tx: the PTP Tx timestamp tracker to check
362  *
363  * Check that a given PTP Tx timestamp tracker is up, i.e. that it is ready
364  * to accept new timestamp requests.
365  *
366  * Assumes the tx->lock spinlock is already held.
367  */
368 static bool
369 ice_ptp_is_tx_tracker_up(struct ice_ptp_tx *tx)
370 {
371 	lockdep_assert_held(&tx->lock);
372 
373 	return tx->init && !tx->disabled;
374 }
375 
376 /**
377  * ice_ptp_req_tx_single_tstamp - Request Tx timestamp for a port from FW
378  * @tx: the PTP Tx timestamp tracker
379  * @idx: index of the timestamp to request
380  */
381 void ice_ptp_req_tx_single_tstamp(struct ice_ptp_tx *tx, u8 idx)
382 {
383 	struct ice_e810_params *params;
384 	struct ice_ptp_port *ptp_port;
385 	unsigned long flags;
386 	struct sk_buff *skb;
387 	struct ice_pf *pf;
388 
389 	if (!tx->init)
390 		return;
391 
392 	ptp_port = container_of(tx, struct ice_ptp_port, tx);
393 	pf = ptp_port_to_pf(ptp_port);
394 	params = &pf->hw.ptp.phy.e810;
395 
396 	/* Drop packets which have waited for more than 2 seconds */
397 	if (time_is_before_jiffies(tx->tstamps[idx].start + 2 * HZ)) {
398 		/* Count the number of Tx timestamps that timed out */
399 		pf->ptp.tx_hwtstamp_timeouts++;
400 
401 		skb = tx->tstamps[idx].skb;
402 		tx->tstamps[idx].skb = NULL;
403 		clear_bit(idx, tx->in_use);
404 
405 		dev_kfree_skb_any(skb);
406 		return;
407 	}
408 
409 	ice_trace(tx_tstamp_fw_req, tx->tstamps[idx].skb, idx);
410 
411 	spin_lock_irqsave(&params->atqbal_wq.lock, flags);
412 
413 	params->atqbal_flags |= ATQBAL_FLAGS_INTR_IN_PROGRESS;
414 
415 	/* Write TS index to read to the PF register so the FW can read it */
416 	wr32(&pf->hw, REG_LL_PROXY_H,
417 	     REG_LL_PROXY_H_TS_INTR_ENA | FIELD_PREP(REG_LL_PROXY_H_TS_IDX, idx) |
418 	     REG_LL_PROXY_H_EXEC);
419 	tx->last_ll_ts_idx_read = idx;
420 
421 	spin_unlock_irqrestore(&params->atqbal_wq.lock, flags);
422 }
423 
424 /**
425  * ice_ptp_complete_tx_single_tstamp - Complete Tx timestamp for a port
426  * @tx: the PTP Tx timestamp tracker
427  */
428 void ice_ptp_complete_tx_single_tstamp(struct ice_ptp_tx *tx)
429 {
430 	struct skb_shared_hwtstamps shhwtstamps = {};
431 	u8 idx = tx->last_ll_ts_idx_read;
432 	struct ice_e810_params *params;
433 	struct ice_ptp_port *ptp_port;
434 	u64 raw_tstamp, tstamp;
435 	bool drop_ts = false;
436 	struct sk_buff *skb;
437 	unsigned long flags;
438 	struct device *dev;
439 	struct ice_pf *pf;
440 	u32 reg_ll_high;
441 
442 	if (!tx->init || tx->last_ll_ts_idx_read < 0)
443 		return;
444 
445 	ptp_port = container_of(tx, struct ice_ptp_port, tx);
446 	pf = ptp_port_to_pf(ptp_port);
447 	dev = ice_pf_to_dev(pf);
448 	params = &pf->hw.ptp.phy.e810;
449 
450 	ice_trace(tx_tstamp_fw_done, tx->tstamps[idx].skb, idx);
451 
452 	spin_lock_irqsave(&params->atqbal_wq.lock, flags);
453 
454 	if (!(params->atqbal_flags & ATQBAL_FLAGS_INTR_IN_PROGRESS))
455 		dev_dbg(dev, "%s: low latency interrupt request not in progress?\n",
456 			__func__);
457 
458 	/* Read the low 32 bit value */
459 	raw_tstamp = rd32(&pf->hw, REG_LL_PROXY_L);
460 	/* Read the status together with high TS part */
461 	reg_ll_high = rd32(&pf->hw, REG_LL_PROXY_H);
462 
463 	/* Wake up threads waiting on low latency interface */
464 	params->atqbal_flags &= ~ATQBAL_FLAGS_INTR_IN_PROGRESS;
465 
466 	wake_up_locked(&params->atqbal_wq);
467 
468 	spin_unlock_irqrestore(&params->atqbal_wq.lock, flags);
469 
470 	/* When the bit is cleared, the TS is ready in the register */
471 	if (reg_ll_high & REG_LL_PROXY_H_EXEC) {
472 		dev_err(ice_pf_to_dev(pf), "Failed to get the Tx tstamp - FW not ready");
473 		return;
474 	}
475 
476 	/* High 8 bit value of the TS is on the bits 16:23 */
477 	raw_tstamp |= ((u64)FIELD_GET(REG_LL_PROXY_H_TS_HIGH, reg_ll_high)) << 32;
478 
479 	/* Devices using this interface always verify the timestamp differs
480 	 * relative to the last cached timestamp value.
481 	 */
482 	if (raw_tstamp == tx->tstamps[idx].cached_tstamp)
483 		return;
484 
485 	tx->tstamps[idx].cached_tstamp = raw_tstamp;
486 	clear_bit(idx, tx->in_use);
487 	skb = tx->tstamps[idx].skb;
488 	tx->tstamps[idx].skb = NULL;
489 	if (test_and_clear_bit(idx, tx->stale))
490 		drop_ts = true;
491 
492 	if (!skb)
493 		return;
494 
495 	if (drop_ts) {
496 		dev_kfree_skb_any(skb);
497 		return;
498 	}
499 
500 	/* Extend the timestamp using cached PHC time */
501 	tstamp = ice_ptp_extend_40b_ts(pf, raw_tstamp);
502 	if (tstamp) {
503 		shhwtstamps.hwtstamp = ns_to_ktime(tstamp);
504 		ice_trace(tx_tstamp_complete, skb, idx);
505 
506 		/* Count the number of Tx timestamps that succeeded */
507 		pf->ptp.tx_hwtstamp_good++;
508 	}
509 
510 	skb_tstamp_tx(skb, &shhwtstamps);
511 	dev_kfree_skb_any(skb);
512 }
513 
514 /**
515  * ice_ptp_process_tx_tstamp - Process Tx timestamps for a port
516  * @tx: the PTP Tx timestamp tracker
517  *
518  * Process timestamps captured by the PHY associated with this port. To do
519  * this, loop over each index with a waiting skb.
520  *
521  * If a given index has a valid timestamp, perform the following steps:
522  *
523  * 1) check that the timestamp request is not stale
524  * 2) check that a timestamp is ready and available in the PHY memory bank
525  * 3) read and copy the timestamp out of the PHY register
526  * 4) unlock the index by clearing the associated in_use bit
527  * 5) check if the timestamp is stale, and discard if so
528  * 6) extend the 40 bit timestamp value to get a 64 bit timestamp value
529  * 7) send this 64 bit timestamp to the stack
530  *
531  * Note that we do not hold the tracking lock while reading the Tx timestamp.
532  * This is because reading the timestamp requires taking a mutex that might
533  * sleep.
534  *
535  * The only place where we set in_use is when a new timestamp is initiated
536  * with a slot index. This is only called in the hard xmit routine where an
537  * SKB has a request flag set. The only places where we clear this bit is this
538  * function, or during teardown when the Tx timestamp tracker is being
539  * removed. A timestamp index will never be re-used until the in_use bit for
540  * that index is cleared.
541  *
542  * If a Tx thread starts a new timestamp, we might not begin processing it
543  * right away but we will notice it at the end when we re-queue the task.
544  *
545  * If a Tx thread starts a new timestamp just after this function exits, the
546  * interrupt for that timestamp should re-trigger this function once
547  * a timestamp is ready.
548  *
549  * In cases where the PTP hardware clock was directly adjusted, some
550  * timestamps may not be able to safely use the timestamp extension math. In
551  * this case, software will set the stale bit for any outstanding Tx
552  * timestamps when the clock is adjusted. Then this function will discard
553  * those captured timestamps instead of sending them to the stack.
554  *
555  * If a Tx packet has been waiting for more than 2 seconds, it is not possible
556  * to correctly extend the timestamp using the cached PHC time. It is
557  * extremely unlikely that a packet will ever take this long to timestamp. If
558  * we detect a Tx timestamp request that has waited for this long we assume
559  * the packet will never be sent by hardware and discard it without reading
560  * the timestamp register.
561  */
562 static void ice_ptp_process_tx_tstamp(struct ice_ptp_tx *tx)
563 {
564 	struct ice_ptp_port *ptp_port;
565 	unsigned long flags;
566 	u32 tstamp_good = 0;
567 	struct ice_pf *pf;
568 	struct ice_hw *hw;
569 	u64 tstamp_ready;
570 	bool link_up;
571 	int err;
572 	u8 idx;
573 
574 	ptp_port = container_of(tx, struct ice_ptp_port, tx);
575 	pf = ptp_port_to_pf(ptp_port);
576 	hw = &pf->hw;
577 
578 	if (!tx->init)
579 		return;
580 
581 	/* Read the Tx ready status first */
582 	if (tx->has_ready_bitmap) {
583 		err = ice_get_phy_tx_tstamp_ready(hw, tx->block, &tstamp_ready);
584 		if (err)
585 			return;
586 	}
587 
588 	/* Drop packets if the link went down */
589 	link_up = ptp_port->link_up;
590 
591 	for_each_set_bit(idx, tx->in_use, tx->len) {
592 		struct skb_shared_hwtstamps shhwtstamps = {};
593 		u8 phy_idx = idx + tx->offset;
594 		u64 raw_tstamp = 0, tstamp;
595 		bool drop_ts = !link_up;
596 		struct sk_buff *skb;
597 
598 		/* Paired with smp_mb__before_atomic() in ice_ptp_request_ts()
599 		 * to ensure ordering the in_use bitmap and the indexed fields
600 		 * in the tstamps array.
601 		 */
602 		smp_rmb();
603 
604 		/* Drop packets which have waited for more than 2 seconds */
605 		if (time_is_before_jiffies(tx->tstamps[idx].start + 2 * HZ)) {
606 			drop_ts = true;
607 
608 			/* Count the number of Tx timestamps that timed out */
609 			pf->ptp.tx_hwtstamp_timeouts++;
610 		}
611 
612 		/* Only read a timestamp from the PHY if its marked as ready
613 		 * by the tstamp_ready register. This avoids unnecessary
614 		 * reading of timestamps which are not yet valid. This is
615 		 * important as we must read all timestamps which are valid
616 		 * and only timestamps which are valid during each interrupt.
617 		 * If we do not, the hardware logic for generating a new
618 		 * interrupt can get stuck on some devices.
619 		 */
620 		if (tx->has_ready_bitmap &&
621 		    !(tstamp_ready & BIT_ULL(phy_idx))) {
622 			if (drop_ts)
623 				goto skip_ts_read;
624 
625 			continue;
626 		}
627 
628 		ice_trace(tx_tstamp_fw_req, tx->tstamps[idx].skb, idx);
629 
630 		err = ice_read_phy_tstamp(hw, tx->block, phy_idx, &raw_tstamp);
631 		if (err && !drop_ts)
632 			continue;
633 
634 		ice_trace(tx_tstamp_fw_done, tx->tstamps[idx].skb, idx);
635 
636 		/* For PHYs which don't implement a proper timestamp ready
637 		 * bitmap, verify that the timestamp value is different
638 		 * from the last cached timestamp. If it is not, skip this for
639 		 * now assuming it hasn't yet been captured by hardware.
640 		 */
641 		if (!drop_ts && !tx->has_ready_bitmap &&
642 		    raw_tstamp == tx->tstamps[idx].cached_tstamp)
643 			continue;
644 
645 		/* Discard any timestamp value without the valid bit set */
646 		if (!(raw_tstamp & ICE_PTP_TS_VALID))
647 			drop_ts = true;
648 
649 skip_ts_read:
650 		spin_lock_irqsave(&tx->lock, flags);
651 		if (!tx->has_ready_bitmap && raw_tstamp)
652 			tx->tstamps[idx].cached_tstamp = raw_tstamp;
653 		clear_bit(idx, tx->in_use);
654 		skb = tx->tstamps[idx].skb;
655 		tx->tstamps[idx].skb = NULL;
656 		if (test_and_clear_bit(idx, tx->stale))
657 			drop_ts = true;
658 		spin_unlock_irqrestore(&tx->lock, flags);
659 
660 		/* It is unlikely but possible that the SKB will have been
661 		 * flushed at this point due to link change or teardown.
662 		 */
663 		if (!skb)
664 			continue;
665 
666 		if (drop_ts) {
667 			dev_kfree_skb_any(skb);
668 			continue;
669 		}
670 
671 		/* Extend the timestamp using cached PHC time */
672 		tstamp = ice_ptp_extend_40b_ts(pf, raw_tstamp);
673 		if (tstamp) {
674 			shhwtstamps.hwtstamp = ns_to_ktime(tstamp);
675 			ice_trace(tx_tstamp_complete, skb, idx);
676 
677 			/* Count the number of Tx timestamps that succeeded */
678 			tstamp_good++;
679 		}
680 
681 		skb_tstamp_tx(skb, &shhwtstamps);
682 		dev_kfree_skb_any(skb);
683 	}
684 
685 	pf->ptp.tx_hwtstamp_good += tstamp_good;
686 }
687 
688 static void ice_ptp_release_port_srcu(struct kref *ref)
689 {
690 	/* wake_up_var() requires full ordering but kref_put only provides
691 	 * release ordering.
692 	 */
693 	smp_mb__after_atomic();
694 	wake_up_var(ref);
695 }
696 
697 static void ice_ptp_tx_tstamp_owner(struct ice_pf *pf)
698 {
699 	struct ice_port_list *ports = &pf->adapter->ports;
700 	struct ice_ptp_port *port;
701 	int srcu_idx;
702 
703 	srcu_idx = srcu_read_lock(&ports->srcu);
704 	list_for_each_entry_srcu(port, &ports->list, list_node,
705 				 srcu_read_lock_held(&ports->srcu)) {
706 		struct ice_ptp_tx *tx = &port->tx;
707 
708 		if (!tx->init)
709 			continue;
710 
711 		if (!kref_get_unless_zero(&port->ref))
712 			continue;
713 
714 		ice_ptp_process_tx_tstamp(tx);
715 
716 		kref_put(&port->ref, ice_ptp_release_port_srcu);
717 	}
718 	srcu_read_unlock(&ports->srcu, srcu_idx);
719 }
720 
721 /**
722  * ice_ptp_alloc_tx_tracker - Initialize tracking for Tx timestamps
723  * @tx: Tx tracking structure to initialize
724  *
725  * Assumes that the length has already been initialized. Do not call directly,
726  * use the ice_ptp_init_tx_* instead.
727  */
728 static int
729 ice_ptp_alloc_tx_tracker(struct ice_ptp_tx *tx)
730 {
731 	unsigned long *in_use, *stale;
732 	struct ice_tx_tstamp *tstamps;
733 
734 	tstamps = kzalloc_objs(*tstamps, tx->len);
735 	in_use = bitmap_zalloc(tx->len, GFP_KERNEL);
736 	stale = bitmap_zalloc(tx->len, GFP_KERNEL);
737 
738 	if (!tstamps || !in_use || !stale) {
739 		kfree(tstamps);
740 		bitmap_free(in_use);
741 		bitmap_free(stale);
742 
743 		return -ENOMEM;
744 	}
745 
746 	tx->tstamps = tstamps;
747 	tx->in_use = in_use;
748 	tx->stale = stale;
749 	tx->init = 1;
750 	tx->last_ll_ts_idx_read = -1;
751 
752 	spin_lock_init(&tx->lock);
753 
754 	return 0;
755 }
756 
757 /**
758  * ice_ptp_flush_tx_tracker - Flush any remaining timestamps from the tracker
759  * @pf: Board private structure
760  * @tx: the tracker to flush
761  *
762  * Called during teardown when a Tx tracker is being removed.
763  */
764 static void
765 ice_ptp_flush_tx_tracker(struct ice_pf *pf, struct ice_ptp_tx *tx)
766 {
767 	struct ice_hw *hw = &pf->hw;
768 	unsigned long flags;
769 	u64 tstamp_ready;
770 	int err;
771 	u8 idx;
772 
773 	err = ice_get_phy_tx_tstamp_ready(hw, tx->block, &tstamp_ready);
774 	if (err) {
775 		dev_dbg(ice_pf_to_dev(pf), "Failed to get the Tx tstamp ready bitmap for block %u, err %d\n",
776 			tx->block, err);
777 
778 		/* If we fail to read the Tx timestamp ready bitmap just
779 		 * skip clearing the PHY timestamps.
780 		 */
781 		tstamp_ready = 0;
782 	}
783 
784 	for_each_set_bit(idx, tx->in_use, tx->len) {
785 		u8 phy_idx = idx + tx->offset;
786 		struct sk_buff *skb;
787 
788 		/* In case this timestamp is ready, we need to clear it. */
789 		if (!hw->reset_ongoing && (tstamp_ready & BIT_ULL(phy_idx)))
790 			ice_clear_phy_tstamp(hw, tx->block, phy_idx);
791 
792 		spin_lock_irqsave(&tx->lock, flags);
793 		skb = tx->tstamps[idx].skb;
794 		tx->tstamps[idx].skb = NULL;
795 		clear_bit(idx, tx->in_use);
796 		clear_bit(idx, tx->stale);
797 		spin_unlock_irqrestore(&tx->lock, flags);
798 
799 		/* Count the number of Tx timestamps flushed */
800 		pf->ptp.tx_hwtstamp_flushed++;
801 
802 		/* Free the SKB after we've cleared the bit */
803 		dev_kfree_skb_any(skb);
804 	}
805 }
806 
807 /**
808  * ice_ptp_mark_tx_tracker_stale - Mark unfinished timestamps as stale
809  * @tx: the tracker to mark
810  *
811  * Mark currently outstanding Tx timestamps as stale. This prevents sending
812  * their timestamp value to the stack. This is required to prevent extending
813  * the 40bit hardware timestamp incorrectly.
814  *
815  * This should be called when the PTP clock is modified such as after a set
816  * time request.
817  */
818 static void
819 ice_ptp_mark_tx_tracker_stale(struct ice_ptp_tx *tx)
820 {
821 	unsigned long flags;
822 
823 	spin_lock_irqsave(&tx->lock, flags);
824 	bitmap_or(tx->stale, tx->stale, tx->in_use, tx->len);
825 	spin_unlock_irqrestore(&tx->lock, flags);
826 }
827 
828 /**
829  * ice_ptp_flush_all_tx_tracker - Flush all timestamp trackers on this clock
830  * @pf: Board private structure
831  *
832  * Called by the clock owner to flush all the Tx timestamp trackers associated
833  * with the clock.
834  */
835 static void
836 ice_ptp_flush_all_tx_tracker(struct ice_pf *pf)
837 {
838 	struct ice_port_list *ports = &pf->adapter->ports;
839 	struct ice_ptp_port *port;
840 	int srcu_idx;
841 
842 	srcu_idx = srcu_read_lock(&ports->srcu);
843 	list_for_each_entry_srcu(port, &ports->list, list_node,
844 				 srcu_read_lock_held(&ports->srcu)) {
845 		if (!kref_get_unless_zero(&port->ref))
846 			continue;
847 		ice_ptp_flush_tx_tracker(ptp_port_to_pf(port), &port->tx);
848 		kref_put(&port->ref, ice_ptp_release_port_srcu);
849 	}
850 	srcu_read_unlock(&ports->srcu, srcu_idx);
851 }
852 
853 /**
854  * ice_ptp_release_tx_tracker - Release allocated memory for Tx tracker
855  * @pf: Board private structure
856  * @tx: Tx tracking structure to release
857  *
858  * Free memory associated with the Tx timestamp tracker.
859  */
860 static void
861 ice_ptp_release_tx_tracker(struct ice_pf *pf, struct ice_ptp_tx *tx)
862 {
863 	unsigned long flags;
864 
865 	spin_lock_irqsave(&tx->lock, flags);
866 	tx->init = 0;
867 	spin_unlock_irqrestore(&tx->lock, flags);
868 
869 	/* wait for potentially outstanding interrupt to complete */
870 	synchronize_irq(pf->oicr_irq.virq);
871 
872 	ice_ptp_flush_tx_tracker(pf, tx);
873 
874 	kfree(tx->tstamps);
875 	tx->tstamps = NULL;
876 
877 	bitmap_free(tx->in_use);
878 	tx->in_use = NULL;
879 
880 	bitmap_free(tx->stale);
881 	tx->stale = NULL;
882 
883 	tx->len = 0;
884 }
885 
886 /**
887  * ice_ptp_init_tx_e82x - Initialize tracking for Tx timestamps
888  * @pf: Board private structure
889  * @tx: the Tx tracking structure to initialize
890  * @port: the port this structure tracks
891  *
892  * Initialize the Tx timestamp tracker for this port. For generic MAC devices,
893  * the timestamp block is shared for all ports in the same quad. To avoid
894  * ports using the same timestamp index, logically break the block of
895  * registers into chunks based on the port number.
896  *
897  * Return: 0 on success, -ENOMEM when out of memory
898  */
899 static int ice_ptp_init_tx_e82x(struct ice_pf *pf, struct ice_ptp_tx *tx,
900 				u8 port)
901 {
902 	tx->block = ICE_GET_QUAD_NUM(port);
903 	tx->offset = (port % ICE_PORTS_PER_QUAD) * INDEX_PER_PORT_E82X;
904 	tx->len = INDEX_PER_PORT_E82X;
905 	tx->has_ready_bitmap = 1;
906 
907 	return ice_ptp_alloc_tx_tracker(tx);
908 }
909 
910 /**
911  * ice_ptp_init_tx - Initialize tracking for Tx timestamps
912  * @pf: Board private structure
913  * @tx: the Tx tracking structure to initialize
914  * @port: the port this structure tracks
915  *
916  * Initialize the Tx timestamp tracker for this PF. For all PHYs except E82X,
917  * each port has its own block of timestamps, independent of the other ports.
918  *
919  * Return: 0 on success, -ENOMEM when out of memory
920  */
921 static int ice_ptp_init_tx(struct ice_pf *pf, struct ice_ptp_tx *tx, u8 port)
922 {
923 	tx->block = port;
924 	tx->offset = 0;
925 	tx->len = INDEX_PER_PORT;
926 
927 	/* The E810 PHY does not provide a timestamp ready bitmap. Instead,
928 	 * verify new timestamps against cached copy of the last read
929 	 * timestamp.
930 	 */
931 	tx->has_ready_bitmap = pf->hw.mac_type != ICE_MAC_E810;
932 
933 	return ice_ptp_alloc_tx_tracker(tx);
934 }
935 
936 /**
937  * ice_ptp_update_cached_phctime - Update the cached PHC time values
938  * @pf: Board specific private structure
939  *
940  * This function updates the system time values which are cached in the PF
941  * structure and the Rx rings.
942  *
943  * This function must be called periodically to ensure that the cached value
944  * is never more than 2 seconds old.
945  *
946  * Note that the cached copy in the PF PTP structure is always updated, even
947  * if we can't update the copy in the Rx rings.
948  *
949  * Return:
950  * * 0 - OK, successfully updated
951  * * -EAGAIN - PF was busy, need to reschedule the update
952  */
953 static int ice_ptp_update_cached_phctime(struct ice_pf *pf)
954 {
955 	struct device *dev = ice_pf_to_dev(pf);
956 	unsigned long update_before;
957 	u64 systime;
958 	int i;
959 
960 	update_before = pf->ptp.cached_phc_jiffies + msecs_to_jiffies(2000);
961 	if (pf->ptp.cached_phc_time &&
962 	    time_is_before_jiffies(update_before)) {
963 		unsigned long time_taken = jiffies - pf->ptp.cached_phc_jiffies;
964 
965 		dev_warn(dev, "%u msecs passed between update to cached PHC time\n",
966 			 jiffies_to_msecs(time_taken));
967 		pf->ptp.late_cached_phc_updates++;
968 	}
969 
970 	/* Read the current PHC time */
971 	systime = ice_ptp_read_src_clk_reg(pf, NULL);
972 
973 	/* Update the cached PHC time stored in the PF structure */
974 	WRITE_ONCE(pf->ptp.cached_phc_time, systime);
975 	WRITE_ONCE(pf->ptp.cached_phc_jiffies, jiffies);
976 
977 	if (test_and_set_bit(ICE_CFG_BUSY, pf->state))
978 		return -EAGAIN;
979 
980 	ice_for_each_vsi(pf, i) {
981 		struct ice_vsi *vsi = pf->vsi[i];
982 		int j;
983 
984 		if (!vsi)
985 			continue;
986 
987 		if (vsi->type != ICE_VSI_PF)
988 			continue;
989 
990 		ice_for_each_rxq(vsi, j) {
991 			if (!vsi->rx_rings[j])
992 				continue;
993 			WRITE_ONCE(vsi->rx_rings[j]->cached_phctime, systime);
994 		}
995 	}
996 	clear_bit(ICE_CFG_BUSY, pf->state);
997 
998 	return 0;
999 }
1000 
1001 /**
1002  * ice_ptp_reset_cached_phctime - Reset cached PHC time after an update
1003  * @pf: Board specific private structure
1004  *
1005  * This function must be called when the cached PHC time is no longer valid,
1006  * such as after a time adjustment. It marks any currently outstanding Tx
1007  * timestamps as stale and updates the cached PHC time for both the PF and Rx
1008  * rings.
1009  *
1010  * If updating the PHC time cannot be done immediately, a warning message is
1011  * logged and the work item is scheduled immediately to minimize the window
1012  * with a wrong cached timestamp.
1013  */
1014 static void ice_ptp_reset_cached_phctime(struct ice_pf *pf)
1015 {
1016 	struct device *dev = ice_pf_to_dev(pf);
1017 	int err;
1018 
1019 	/* Update the cached PHC time immediately if possible, otherwise
1020 	 * schedule the work item to execute soon.
1021 	 */
1022 	err = ice_ptp_update_cached_phctime(pf);
1023 	if (err) {
1024 		/* If another thread is updating the Rx rings, we won't
1025 		 * properly reset them here. This could lead to reporting of
1026 		 * invalid timestamps, but there isn't much we can do.
1027 		 */
1028 		dev_warn(dev, "%s: ICE_CFG_BUSY, unable to immediately update cached PHC time\n",
1029 			 __func__);
1030 
1031 		/* Queue the work item to update the Rx rings when possible */
1032 		kthread_queue_delayed_work(pf->ptp.kworker, &pf->ptp.work,
1033 					   msecs_to_jiffies(10));
1034 	}
1035 
1036 	/* Mark any outstanding timestamps as stale, since they might have
1037 	 * been captured in hardware before the time update. This could lead
1038 	 * to us extending them with the wrong cached value resulting in
1039 	 * incorrect timestamp values.
1040 	 */
1041 	ice_ptp_mark_tx_tracker_stale(&pf->ptp.port.tx);
1042 }
1043 
1044 /**
1045  * ice_ptp_write_init - Set PHC time to provided value
1046  * @pf: Board private structure
1047  * @ts: timespec structure that holds the new time value
1048  *
1049  * Set the PHC time to the specified time provided in the timespec.
1050  */
1051 static int ice_ptp_write_init(struct ice_pf *pf, struct timespec64 *ts)
1052 {
1053 	u64 ns = timespec64_to_ns(ts);
1054 	struct ice_hw *hw = &pf->hw;
1055 
1056 	return ice_ptp_init_time(hw, ns);
1057 }
1058 
1059 /**
1060  * ice_ptp_write_adj - Adjust PHC clock time atomically
1061  * @pf: Board private structure
1062  * @adj: Adjustment in nanoseconds
1063  *
1064  * Perform an atomic adjustment of the PHC time by the specified number of
1065  * nanoseconds.
1066  */
1067 static int ice_ptp_write_adj(struct ice_pf *pf, s32 adj)
1068 {
1069 	struct ice_hw *hw = &pf->hw;
1070 
1071 	return ice_ptp_adj_clock(hw, adj);
1072 }
1073 
1074 /**
1075  * ice_base_incval - Get base timer increment value
1076  * @pf: Board private structure
1077  *
1078  * Look up the base timer increment value for this device. The base increment
1079  * value is used to define the nominal clock tick rate. This increment value
1080  * is programmed during device initialization. It is also used as the basis
1081  * for calculating adjustments using scaled_ppm.
1082  */
1083 static u64 ice_base_incval(struct ice_pf *pf)
1084 {
1085 	struct ice_hw *hw = &pf->hw;
1086 	u64 incval;
1087 
1088 	incval = ice_get_base_incval(hw);
1089 
1090 	dev_dbg(ice_pf_to_dev(pf), "PTP: using base increment value of 0x%016llx\n",
1091 		incval);
1092 
1093 	return incval;
1094 }
1095 
1096 /**
1097  * ice_ptp_check_tx_fifo - Check whether Tx FIFO is in an OK state
1098  * @port: PTP port for which Tx FIFO is checked
1099  */
1100 static int ice_ptp_check_tx_fifo(struct ice_ptp_port *port)
1101 {
1102 	int offs = port->port_num % ICE_PORTS_PER_QUAD;
1103 	int quad = ICE_GET_QUAD_NUM(port->port_num);
1104 	struct ice_pf *pf;
1105 	struct ice_hw *hw;
1106 	u32 val, phy_sts;
1107 	int err;
1108 
1109 	pf = ptp_port_to_pf(port);
1110 	hw = &pf->hw;
1111 
1112 	if (port->tx_fifo_busy_cnt == FIFO_OK)
1113 		return 0;
1114 
1115 	/* need to read FIFO state */
1116 	if (offs == 0 || offs == 1)
1117 		err = ice_read_quad_reg_e82x(hw, quad, Q_REG_FIFO01_STATUS,
1118 					     &val);
1119 	else
1120 		err = ice_read_quad_reg_e82x(hw, quad, Q_REG_FIFO23_STATUS,
1121 					     &val);
1122 
1123 	if (err) {
1124 		dev_err(ice_pf_to_dev(pf), "PTP failed to check port %d Tx FIFO, err %d\n",
1125 			port->port_num, err);
1126 		return err;
1127 	}
1128 
1129 	if (offs & 0x1)
1130 		phy_sts = FIELD_GET(Q_REG_FIFO13_M, val);
1131 	else
1132 		phy_sts = FIELD_GET(Q_REG_FIFO02_M, val);
1133 
1134 	if (phy_sts & FIFO_EMPTY) {
1135 		port->tx_fifo_busy_cnt = FIFO_OK;
1136 		return 0;
1137 	}
1138 
1139 	port->tx_fifo_busy_cnt++;
1140 
1141 	dev_dbg(ice_pf_to_dev(pf), "Try %d, port %d FIFO not empty\n",
1142 		port->tx_fifo_busy_cnt, port->port_num);
1143 
1144 	if (port->tx_fifo_busy_cnt == ICE_PTP_FIFO_NUM_CHECKS) {
1145 		dev_dbg(ice_pf_to_dev(pf),
1146 			"Port %d Tx FIFO still not empty; resetting quad %d\n",
1147 			port->port_num, quad);
1148 		ice_ptp_reset_ts_memory_quad_e82x(hw, quad);
1149 		port->tx_fifo_busy_cnt = FIFO_OK;
1150 		return 0;
1151 	}
1152 
1153 	return -EAGAIN;
1154 }
1155 
1156 /**
1157  * ice_ptp_wait_for_offsets - Check for valid Tx and Rx offsets
1158  * @work: Pointer to the kthread_work structure for this task
1159  *
1160  * Check whether hardware has completed measuring the Tx and Rx offset values
1161  * used to configure and enable vernier timestamp calibration.
1162  *
1163  * Once the offset in either direction is measured, configure the associated
1164  * registers with the calibrated offset values and enable timestamping. The Tx
1165  * and Rx directions are configured independently as soon as their associated
1166  * offsets are known.
1167  *
1168  * This function reschedules itself until both Tx and Rx calibration have
1169  * completed.
1170  */
1171 static void ice_ptp_wait_for_offsets(struct kthread_work *work)
1172 {
1173 	struct ice_ptp_port *port;
1174 	unsigned long flags;
1175 	struct ice_pf *pf;
1176 	struct ice_hw *hw;
1177 	int tx_err;
1178 	int rx_err;
1179 
1180 	port = container_of(work, struct ice_ptp_port, ov_work.work);
1181 	pf = ptp_port_to_pf(port);
1182 	hw = &pf->hw;
1183 
1184 	if (ice_is_reset_in_progress(pf->state)) {
1185 		/* wait for device driver to complete reset */
1186 		kthread_queue_delayed_work(pf->ptp.kworker,
1187 					   &port->ov_work,
1188 					   msecs_to_jiffies(100));
1189 		return;
1190 	}
1191 
1192 	tx_err = ice_ptp_check_tx_fifo(port);
1193 	if (!tx_err)
1194 		tx_err = ice_phy_cfg_tx_offset_e82x(hw, port->port_num);
1195 	if (!tx_err) {
1196 		/* Tx offset has been configured, re-enable Tx timestamps */
1197 		spin_lock_irqsave(&port->tx.lock, flags);
1198 		if (port->tx.disabled) {
1199 			port->tx.disabled = false;
1200 			dev_dbg(ice_pf_to_dev(pf), "PTP Tx offset valid for port %u, Tx timestamps enabled\n",
1201 				port->port_num);
1202 		}
1203 		spin_unlock_irqrestore(&port->tx.lock, flags);
1204 	}
1205 
1206 	rx_err = ice_phy_cfg_rx_offset_e82x(hw, port->port_num);
1207 	if (tx_err || rx_err) {
1208 		/* Tx and/or Rx offset not yet configured, try again later.
1209 		 * This is expected during normal link-up: the vernier offset
1210 		 * calibration cannot complete until at least one packet has
1211 		 * been transmitted, so the first retries routinely land here.
1212 		 */
1213 		dev_dbg(ice_pf_to_dev(pf), "PTP offset not yet valid for port %u (tx_err=%d rx_err=%d)\n",
1214 			port->port_num, tx_err, rx_err);
1215 		kthread_queue_delayed_work(pf->ptp.kworker,
1216 					   &port->ov_work,
1217 					   msecs_to_jiffies(100));
1218 		return;
1219 	}
1220 }
1221 
1222 /**
1223  * ice_ptp_port_phy_stop - Stop timestamping for a PHY port
1224  * @ptp_port: PTP port to stop
1225  */
1226 static int
1227 ice_ptp_port_phy_stop(struct ice_ptp_port *ptp_port)
1228 {
1229 	struct ice_pf *pf = ptp_port_to_pf(ptp_port);
1230 	u8 port = ptp_port->port_num;
1231 	struct ice_hw *hw = &pf->hw;
1232 	int err;
1233 
1234 	mutex_lock(&ptp_port->ps_lock);
1235 
1236 	switch (hw->mac_type) {
1237 	case ICE_MAC_E810:
1238 	case ICE_MAC_E830:
1239 		err = 0;
1240 		break;
1241 	case ICE_MAC_GENERIC:
1242 		kthread_cancel_delayed_work_sync(&ptp_port->ov_work);
1243 
1244 		err = ice_stop_phy_timer_e82x(hw, port, true);
1245 		break;
1246 	case ICE_MAC_GENERIC_3K_E825:
1247 		err = ice_stop_phy_timer_eth56g(hw, port, true);
1248 		break;
1249 	default:
1250 		err = -ENODEV;
1251 	}
1252 	if (err && err != -EBUSY)
1253 		dev_err(ice_pf_to_dev(pf), "PTP failed to set PHY port %d down, err %d\n",
1254 			port, err);
1255 
1256 	mutex_unlock(&ptp_port->ps_lock);
1257 
1258 	return err;
1259 }
1260 
1261 /**
1262  * ice_ptp_port_phy_restart - (Re)start and calibrate PHY timestamping
1263  * @ptp_port: PTP port for which the PHY start is set
1264  *
1265  * Start the PHY timestamping block, and initiate Vernier timestamping
1266  * calibration. If timestamping cannot be calibrated (such as if link is down)
1267  * then disable the timestamping block instead.
1268  */
1269 static int
1270 ice_ptp_port_phy_restart(struct ice_ptp_port *ptp_port)
1271 {
1272 	struct ice_pf *pf = ptp_port_to_pf(ptp_port);
1273 	u8 port = ptp_port->port_num;
1274 	struct ice_hw *hw = &pf->hw;
1275 	unsigned long flags;
1276 	int err;
1277 
1278 	if (!ptp_port->link_up)
1279 		return ice_ptp_port_phy_stop(ptp_port);
1280 
1281 	mutex_lock(&ptp_port->ps_lock);
1282 
1283 	switch (hw->mac_type) {
1284 	case ICE_MAC_E810:
1285 	case ICE_MAC_E830:
1286 		err = 0;
1287 		break;
1288 	case ICE_MAC_GENERIC:
1289 		/* Start the PHY timer in Vernier mode */
1290 		kthread_cancel_delayed_work_sync(&ptp_port->ov_work);
1291 
1292 		/* Disable Tx timestamps until PHY calibration completes */
1293 		spin_lock_irqsave(&ptp_port->tx.lock, flags);
1294 		ptp_port->tx.disabled = true;
1295 		spin_unlock_irqrestore(&ptp_port->tx.lock, flags);
1296 		ptp_port->tx_fifo_busy_cnt = 0;
1297 
1298 		/* Start the PHY timer in Vernier mode */
1299 		err = ice_start_phy_timer_e82x(hw, port);
1300 		if (err)
1301 			break;
1302 
1303 		/* Do not clear disabled flag here. Tx timestamp requests
1304 		 * remain disabled until ice_ptp_wait_for_offsets() has
1305 		 * verified that the Tx offset calibration has completed.
1306 		 */
1307 		kthread_queue_delayed_work(pf->ptp.kworker, &ptp_port->ov_work,
1308 					   0);
1309 		break;
1310 	case ICE_MAC_GENERIC_3K_E825:
1311 		err = ice_start_phy_timer_eth56g(hw, port);
1312 		break;
1313 	default:
1314 		err = -ENODEV;
1315 	}
1316 
1317 	if (err)
1318 		dev_err(ice_pf_to_dev(pf), "PTP failed to set PHY port %d up, err %d\n",
1319 			port, err);
1320 
1321 	mutex_unlock(&ptp_port->ps_lock);
1322 
1323 	return err;
1324 }
1325 
1326 /**
1327  * ice_ptp_link_change - Reconfigure PTP after link status change
1328  * @pf: Board private structure
1329  * @linkup: Link is up or down
1330  */
1331 void ice_ptp_link_change(struct ice_pf *pf, bool linkup)
1332 {
1333 	struct ice_ptp_port *ptp_port;
1334 	struct ice_hw *hw = &pf->hw;
1335 
1336 	if (pf->ptp.state != ICE_PTP_READY)
1337 		return;
1338 
1339 	ptp_port = &pf->ptp.port;
1340 
1341 	/* Update cached link status for this port immediately */
1342 	ptp_port->link_up = linkup;
1343 
1344 	/* Skip HW writes if reset is in progress */
1345 	if (pf->hw.reset_ongoing)
1346 		return;
1347 
1348 	if (hw->mac_type == ICE_MAC_GENERIC_3K_E825 &&
1349 	    test_bit(ICE_FLAG_DPLL, pf->flags)) {
1350 		int pin, err;
1351 
1352 		mutex_lock(&pf->dplls.lock);
1353 		mutex_lock(&pf->adapter->cgu_synce_lock);
1354 		for (pin = 0; pin < ICE_SYNCE_CLK_NUM; pin++) {
1355 			enum ice_synce_clk clk_pin;
1356 			bool active;
1357 			u8 port_num;
1358 
1359 			port_num = ptp_port->port_num;
1360 			clk_pin = (enum ice_synce_clk)pin;
1361 			err = ice_tspll_bypass_mux_active_e825c(hw,
1362 								port_num,
1363 								&active,
1364 								clk_pin);
1365 			if (err) {
1366 				dev_err_once(ice_pf_to_dev(pf),
1367 					     "Failed to read SyncE bypass mux for pin %d, err %d\n",
1368 					     pin, err);
1369 				break;
1370 			}
1371 
1372 			/* The divider is shared, set it only for our port */
1373 			if (!active)
1374 				continue;
1375 
1376 			err = ice_tspll_cfg_synce_ethdiv_e825c(hw, clk_pin);
1377 			if (err) {
1378 				dev_err_once(ice_pf_to_dev(pf),
1379 					     "Failed to configure SyncE ETH divider for pin %d, err %d\n",
1380 					     pin, err);
1381 				break;
1382 			}
1383 		}
1384 		mutex_unlock(&pf->adapter->cgu_synce_lock);
1385 		mutex_unlock(&pf->dplls.lock);
1386 
1387 		if (linkup)
1388 			ice_txclk_update_and_notify(pf);
1389 	}
1390 
1391 	switch (hw->mac_type) {
1392 	case ICE_MAC_E810:
1393 	case ICE_MAC_E830:
1394 		/* Do not reconfigure E810 or E830 PHY */
1395 		return;
1396 	case ICE_MAC_GENERIC:
1397 		ice_ptp_port_phy_restart(ptp_port);
1398 		return;
1399 	case ICE_MAC_GENERIC_3K_E825:
1400 		if (linkup)
1401 			ice_ptp_port_phy_restart(ptp_port);
1402 		return;
1403 	default:
1404 		dev_warn(ice_pf_to_dev(pf), "%s: Unknown PHY type\n", __func__);
1405 	}
1406 }
1407 
1408 /**
1409  * ice_ptp_cfg_phy_interrupt - Configure PHY interrupt settings
1410  * @pf: PF private structure
1411  * @ena: bool value to enable or disable interrupt
1412  * @threshold: Minimum number of packets at which intr is triggered
1413  *
1414  * Utility function to configure all the PHY interrupt settings, including
1415  * whether the PHY interrupt is enabled, and what threshold to use. Also
1416  * configures The E82X timestamp owner to react to interrupts from all PHYs.
1417  *
1418  * Return: 0 on success, -EOPNOTSUPP when PHY model incorrect, other error codes
1419  * when failed to configure PHY interrupt for E82X
1420  */
1421 static int ice_ptp_cfg_phy_interrupt(struct ice_pf *pf, bool ena, u32 threshold)
1422 {
1423 	struct device *dev = ice_pf_to_dev(pf);
1424 	struct ice_hw *hw = &pf->hw;
1425 
1426 	ice_ptp_reset_ts_memory(hw);
1427 
1428 	switch (hw->mac_type) {
1429 	case ICE_MAC_E810:
1430 	case ICE_MAC_E830:
1431 		return 0;
1432 	case ICE_MAC_GENERIC: {
1433 		int quad;
1434 
1435 		for (quad = 0; quad < ICE_GET_QUAD_NUM(hw->ptp.num_lports);
1436 		     quad++) {
1437 			int err;
1438 
1439 			err = ice_phy_cfg_intr_e82x(hw, quad, ena, threshold);
1440 			if (err) {
1441 				dev_err(dev, "Failed to configure PHY interrupt for quad %d, err %d\n",
1442 					quad, err);
1443 				return err;
1444 			}
1445 		}
1446 
1447 		return 0;
1448 	}
1449 	case ICE_MAC_GENERIC_3K_E825: {
1450 		int port;
1451 
1452 		for (port = 0; port < hw->ptp.num_lports; port++) {
1453 			int err;
1454 
1455 			err = ice_phy_cfg_intr_eth56g(hw, port, ena, threshold);
1456 			if (err) {
1457 				dev_err(dev, "Failed to configure PHY interrupt for port %d, err %d\n",
1458 					port, err);
1459 				return err;
1460 			}
1461 		}
1462 
1463 		return 0;
1464 	}
1465 	case ICE_MAC_UNKNOWN:
1466 	default:
1467 		return -EOPNOTSUPP;
1468 	}
1469 }
1470 
1471 /**
1472  * ice_ptp_reset_phy_timestamping - Reset PHY timestamping block
1473  * @pf: Board private structure
1474  */
1475 static void ice_ptp_reset_phy_timestamping(struct ice_pf *pf)
1476 {
1477 	ice_ptp_port_phy_restart(&pf->ptp.port);
1478 }
1479 
1480 /**
1481  * ice_ptp_restart_all_phy - Restart all PHYs to recalibrate timestamping
1482  * @pf: Board private structure
1483  */
1484 static void ice_ptp_restart_all_phy(struct ice_pf *pf)
1485 {
1486 	struct ice_port_list *ports = &pf->adapter->ports;
1487 	struct ice_ptp_port *port;
1488 	int srcu_idx;
1489 
1490 	srcu_idx = srcu_read_lock(&ports->srcu);
1491 	list_for_each_entry_srcu(port, &ports->list, list_node,
1492 				 srcu_read_lock_held(&ports->srcu)) {
1493 		if (!kref_get_unless_zero(&port->ref))
1494 			continue;
1495 
1496 		if (port->link_up)
1497 			ice_ptp_port_phy_restart(port);
1498 
1499 		kref_put(&port->ref, ice_ptp_release_port_srcu);
1500 	}
1501 	srcu_read_unlock(&ports->srcu, srcu_idx);
1502 }
1503 
1504 /**
1505  * ice_ptp_adjfine - Adjust clock increment rate
1506  * @info: the driver's PTP info structure
1507  * @scaled_ppm: Parts per million with 16-bit fractional field
1508  *
1509  * Adjust the frequency of the clock by the indicated scaled ppm from the
1510  * base frequency.
1511  */
1512 static int ice_ptp_adjfine(struct ptp_clock_info *info, long scaled_ppm)
1513 {
1514 	struct ice_pf *pf = ptp_info_to_pf(info);
1515 	struct ice_hw *hw = &pf->hw;
1516 	u64 incval;
1517 	int err;
1518 
1519 	incval = adjust_by_scaled_ppm(ice_base_incval(pf), scaled_ppm);
1520 	err = ice_ptp_write_incval_locked(hw, incval);
1521 	if (err) {
1522 		dev_err(ice_pf_to_dev(pf), "PTP failed to set incval, err %d\n",
1523 			err);
1524 		return -EIO;
1525 	}
1526 
1527 	return 0;
1528 }
1529 
1530 /**
1531  * ice_ptp_extts_event - Process PTP external clock event
1532  * @pf: Board private structure
1533  */
1534 void ice_ptp_extts_event(struct ice_pf *pf)
1535 {
1536 	struct ptp_clock_event event;
1537 	struct ice_hw *hw = &pf->hw;
1538 	u8 chan, tmr_idx;
1539 	u32 hi, lo;
1540 
1541 	/* Don't process timestamp events if PTP is not ready */
1542 	if (pf->ptp.state != ICE_PTP_READY)
1543 		return;
1544 
1545 	tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned;
1546 	/* Event time is captured by one of the two matched registers
1547 	 *      GLTSYN_EVNT_L: 32 LSB of sampled time event
1548 	 *      GLTSYN_EVNT_H: 32 MSB of sampled time event
1549 	 * Event is defined in GLTSYN_EVNT_0 register
1550 	 */
1551 	for (chan = 0; chan < GLTSYN_EVNT_H_IDX_MAX; chan++) {
1552 		int pin_desc_idx;
1553 
1554 		/* Check if channel is enabled */
1555 		if (!(pf->ptp.ext_ts_irq & (1 << chan)))
1556 			continue;
1557 
1558 		lo = rd32(hw, GLTSYN_EVNT_L(chan, tmr_idx));
1559 		hi = rd32(hw, GLTSYN_EVNT_H(chan, tmr_idx));
1560 		event.timestamp = (u64)hi << 32 | lo;
1561 
1562 		/* Add delay compensation */
1563 		pin_desc_idx = ice_ptp_find_pin_idx(pf, PTP_PF_EXTTS, chan);
1564 		if (pin_desc_idx >= 0) {
1565 			const struct ice_ptp_pin_desc *desc;
1566 
1567 			desc = &pf->ptp.ice_pin_desc[pin_desc_idx];
1568 			event.timestamp -= desc->delay[0];
1569 		}
1570 
1571 		event.type = PTP_CLOCK_EXTTS;
1572 		event.index = chan;
1573 		pf->ptp.ext_ts_irq &= ~(1 << chan);
1574 		ptp_clock_event(pf->ptp.clock, &event);
1575 	}
1576 }
1577 
1578 /**
1579  * ice_ptp_cfg_extts - Configure EXTTS pin and channel
1580  * @pf: Board private structure
1581  * @rq: External timestamp request
1582  * @on: Enable/disable flag
1583  *
1584  * Configure an external timestamp event on the requested channel.
1585  *
1586  * Return: 0 on success, negative error code otherwise
1587  */
1588 static int ice_ptp_cfg_extts(struct ice_pf *pf, struct ptp_extts_request *rq,
1589 			     int on)
1590 {
1591 	u32 aux_reg, gpio_reg, irq_reg;
1592 	struct ice_hw *hw = &pf->hw;
1593 	unsigned int chan, gpio_pin;
1594 	int pin_desc_idx;
1595 	u8 tmr_idx;
1596 
1597 	tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned;
1598 	chan = rq->index;
1599 
1600 	pin_desc_idx = ice_ptp_find_pin_idx(pf, PTP_PF_EXTTS, chan);
1601 	if (pin_desc_idx < 0)
1602 		return -EIO;
1603 
1604 	gpio_pin = pf->ptp.ice_pin_desc[pin_desc_idx].gpio[0];
1605 	irq_reg = rd32(hw, PFINT_OICR_ENA);
1606 
1607 	if (on) {
1608 		/* Enable the interrupt */
1609 		irq_reg |= PFINT_OICR_TSYN_EVNT_M;
1610 		aux_reg = GLTSYN_AUX_IN_0_INT_ENA_M;
1611 
1612 #define GLTSYN_AUX_IN_0_EVNTLVL_RISING_EDGE	BIT(0)
1613 #define GLTSYN_AUX_IN_0_EVNTLVL_FALLING_EDGE	BIT(1)
1614 
1615 		/* set event level to requested edge */
1616 		if (rq->flags & PTP_FALLING_EDGE)
1617 			aux_reg |= GLTSYN_AUX_IN_0_EVNTLVL_FALLING_EDGE;
1618 		if (rq->flags & PTP_RISING_EDGE)
1619 			aux_reg |= GLTSYN_AUX_IN_0_EVNTLVL_RISING_EDGE;
1620 
1621 		/* Write GPIO CTL reg.
1622 		 * 0x1 is input sampled by EVENT register(channel)
1623 		 * + num_in_channels * tmr_idx
1624 		 */
1625 		gpio_reg = FIELD_PREP(GLGEN_GPIO_CTL_PIN_FUNC_M,
1626 				      1 + chan + (tmr_idx * 3));
1627 	} else {
1628 		bool last_enabled = true;
1629 
1630 		/* clear the values we set to reset defaults */
1631 		aux_reg = 0;
1632 		gpio_reg = 0;
1633 
1634 		for (unsigned int i = 0; i < pf->ptp.info.n_ext_ts; i++)
1635 			if ((pf->ptp.extts_rqs[i].flags &
1636 			     PTP_ENABLE_FEATURE) &&
1637 			    i != chan) {
1638 				last_enabled = false;
1639 			}
1640 
1641 		if (last_enabled)
1642 			irq_reg &= ~PFINT_OICR_TSYN_EVNT_M;
1643 	}
1644 
1645 	wr32(hw, PFINT_OICR_ENA, irq_reg);
1646 	wr32(hw, GLTSYN_AUX_IN(chan, tmr_idx), aux_reg);
1647 	wr32(hw, GLGEN_GPIO_CTL(gpio_pin), gpio_reg);
1648 
1649 	return 0;
1650 }
1651 
1652 /**
1653  * ice_ptp_disable_all_extts - Disable all EXTTS channels
1654  * @pf: Board private structure
1655  */
1656 static void ice_ptp_disable_all_extts(struct ice_pf *pf)
1657 {
1658 	for (unsigned int i = 0; i < pf->ptp.info.n_ext_ts ; i++)
1659 		if (pf->ptp.extts_rqs[i].flags & PTP_ENABLE_FEATURE)
1660 			ice_ptp_cfg_extts(pf, &pf->ptp.extts_rqs[i],
1661 					  false);
1662 
1663 	synchronize_irq(pf->oicr_irq.virq);
1664 }
1665 
1666 /**
1667  * ice_ptp_enable_all_extts - Enable all EXTTS channels
1668  * @pf: Board private structure
1669  *
1670  * Called during reset to restore user configuration.
1671  */
1672 static void ice_ptp_enable_all_extts(struct ice_pf *pf)
1673 {
1674 	for (unsigned int i = 0; i < pf->ptp.info.n_ext_ts ; i++)
1675 		if (pf->ptp.extts_rqs[i].flags & PTP_ENABLE_FEATURE)
1676 			ice_ptp_cfg_extts(pf, &pf->ptp.extts_rqs[i],
1677 					  true);
1678 }
1679 
1680 /**
1681  * ice_ptp_write_perout - Write periodic wave parameters to HW
1682  * @hw: pointer to the HW struct
1683  * @chan: target channel
1684  * @gpio_pin: target GPIO pin
1685  * @start: target time to start periodic output
1686  * @period: target period
1687  *
1688  * Return: 0 on success, negative error code otherwise
1689  */
1690 static int ice_ptp_write_perout(struct ice_hw *hw, unsigned int chan,
1691 				unsigned int gpio_pin, u64 start, u64 period)
1692 {
1693 
1694 	u8 tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned;
1695 	u32 val = 0;
1696 
1697 	/* 0. Reset mode & out_en in AUX_OUT */
1698 	wr32(hw, GLTSYN_AUX_OUT(chan, tmr_idx), 0);
1699 
1700 	if (hw->mac_type == ICE_MAC_GENERIC_3K_E825) {
1701 		int err;
1702 
1703 		/* Enable/disable CGU 1PPS output for E825C */
1704 		err = ice_tspll_cfg_pps_out_e825c(hw, !!period);
1705 		if (err)
1706 			return err;
1707 	}
1708 
1709 	/* 1. Write perout with half of required period value.
1710 	 * HW toggles output when source clock hits the TGT and then adds
1711 	 * GLTSYN_CLKO value to the target, so it ends up with 50% duty cycle.
1712 	 */
1713 	period >>= 1;
1714 
1715 	/* For proper operation, GLTSYN_CLKO must be larger than clock tick and
1716 	 * period has to fit in 32 bit register.
1717 	 */
1718 #define MIN_PULSE 3
1719 	if (!!period && (period <= MIN_PULSE || period > U32_MAX)) {
1720 		dev_err(ice_hw_to_dev(hw), "CLK period ticks must be >= %d && <= 2^32",
1721 			MIN_PULSE);
1722 		return -EIO;
1723 	}
1724 
1725 	wr32(hw, GLTSYN_CLKO(chan, tmr_idx), lower_32_bits(period));
1726 
1727 	/* 2. Write TARGET time */
1728 	wr32(hw, GLTSYN_TGT_L(chan, tmr_idx), lower_32_bits(start));
1729 	wr32(hw, GLTSYN_TGT_H(chan, tmr_idx), upper_32_bits(start));
1730 
1731 	/* 3. Write AUX_OUT register */
1732 	if (!!period)
1733 		val = GLTSYN_AUX_OUT_0_OUT_ENA_M | GLTSYN_AUX_OUT_0_OUTMOD_M;
1734 	wr32(hw, GLTSYN_AUX_OUT(chan, tmr_idx), val);
1735 
1736 	/* 4. write GPIO CTL reg */
1737 	val = GLGEN_GPIO_CTL_PIN_DIR_M;
1738 	if (!!period)
1739 		val |= FIELD_PREP(GLGEN_GPIO_CTL_PIN_FUNC_M,
1740 				  8 + chan + (tmr_idx * 4));
1741 
1742 	wr32(hw, GLGEN_GPIO_CTL(gpio_pin), val);
1743 	ice_flush(hw);
1744 
1745 	return 0;
1746 }
1747 
1748 /**
1749  * ice_ptp_cfg_perout - Configure clock to generate periodic wave
1750  * @pf: Board private structure
1751  * @rq: Periodic output request
1752  * @on: Enable/disable flag
1753  *
1754  * Configure the internal clock generator modules to generate the clock wave of
1755  * specified period.
1756  *
1757  * Return: 0 on success, negative error code otherwise
1758  */
1759 static int ice_ptp_cfg_perout(struct ice_pf *pf, struct ptp_perout_request *rq,
1760 			      int on)
1761 {
1762 	unsigned int gpio_pin, prop_delay_ns;
1763 	u64 clk, period, start, phase;
1764 	struct ice_hw *hw = &pf->hw;
1765 	int pin_desc_idx;
1766 
1767 	pin_desc_idx = ice_ptp_find_pin_idx(pf, PTP_PF_PEROUT, rq->index);
1768 	if (pin_desc_idx < 0)
1769 		return -EIO;
1770 
1771 	gpio_pin = pf->ptp.ice_pin_desc[pin_desc_idx].gpio[1];
1772 	prop_delay_ns = pf->ptp.ice_pin_desc[pin_desc_idx].delay[1];
1773 	period = rq->period.sec * NSEC_PER_SEC + rq->period.nsec;
1774 
1775 	/* If we're disabling the output or period is 0, clear out CLKO and TGT
1776 	 * and keep output level low.
1777 	 */
1778 	if (!on || !period)
1779 		return ice_ptp_write_perout(hw, rq->index, gpio_pin, 0, 0);
1780 
1781 	if (strncmp(pf->ptp.pin_desc[pin_desc_idx].name, "1PPS", 64) == 0 &&
1782 	    period != NSEC_PER_SEC && hw->mac_type == ICE_MAC_GENERIC) {
1783 		dev_err(ice_pf_to_dev(pf), "1PPS pin supports only 1 s period\n");
1784 		return -EOPNOTSUPP;
1785 	}
1786 
1787 	if (period & 0x1) {
1788 		dev_err(ice_pf_to_dev(pf), "CLK Period must be an even value\n");
1789 		return -EIO;
1790 	}
1791 
1792 	start = rq->start.sec * NSEC_PER_SEC + rq->start.nsec;
1793 
1794 	/* If PTP_PEROUT_PHASE is set, rq has phase instead of start time */
1795 	if (rq->flags & PTP_PEROUT_PHASE)
1796 		phase = start;
1797 	else
1798 		div64_u64_rem(start, period, &phase);
1799 
1800 	/* If we have only phase or start time is in the past, start the timer
1801 	 * at the next multiple of period, maintaining phase at least 0.5 second
1802 	 * from now, so we have time to write it to HW.
1803 	 */
1804 	clk = ice_ptp_read_src_clk_reg(pf, NULL) + NSEC_PER_MSEC * 500;
1805 	if (rq->flags & PTP_PEROUT_PHASE || start <= clk - prop_delay_ns)
1806 		start = div64_u64(clk + period - 1, period) * period + phase;
1807 
1808 	/* Compensate for propagation delay from the generator to the pin. */
1809 	start -= prop_delay_ns;
1810 
1811 	return ice_ptp_write_perout(hw, rq->index, gpio_pin, start, period);
1812 }
1813 
1814 /**
1815  * ice_ptp_disable_all_perout - Disable all currently configured outputs
1816  * @pf: Board private structure
1817  *
1818  * Disable all currently configured clock outputs. This is necessary before
1819  * certain changes to the PTP hardware clock. Use ice_ptp_enable_all_perout to
1820  * re-enable the clocks again.
1821  */
1822 static void ice_ptp_disable_all_perout(struct ice_pf *pf)
1823 {
1824 	for (unsigned int i = 0; i < pf->ptp.info.n_per_out; i++)
1825 		if (pf->ptp.perout_rqs[i].period.sec ||
1826 		    pf->ptp.perout_rqs[i].period.nsec)
1827 			ice_ptp_cfg_perout(pf, &pf->ptp.perout_rqs[i],
1828 					   false);
1829 }
1830 
1831 /**
1832  * ice_ptp_enable_all_perout - Enable all configured periodic clock outputs
1833  * @pf: Board private structure
1834  *
1835  * Enable all currently configured clock outputs. Use this after
1836  * ice_ptp_disable_all_perout to reconfigure the output signals according to
1837  * their configuration.
1838  */
1839 static void ice_ptp_enable_all_perout(struct ice_pf *pf)
1840 {
1841 	for (unsigned int i = 0; i < pf->ptp.info.n_per_out; i++)
1842 		if (pf->ptp.perout_rqs[i].period.sec ||
1843 		    pf->ptp.perout_rqs[i].period.nsec)
1844 			ice_ptp_cfg_perout(pf, &pf->ptp.perout_rqs[i],
1845 					   true);
1846 }
1847 
1848 /**
1849  * ice_verify_pin - verify if pin supports requested pin function
1850  * @info: the driver's PTP info structure
1851  * @pin: Pin index
1852  * @func: Assigned function
1853  * @chan: Assigned channel
1854  *
1855  * Return: 0 on success, -EOPNOTSUPP when function is not supported.
1856  */
1857 static int ice_verify_pin(struct ptp_clock_info *info, unsigned int pin,
1858 			  enum ptp_pin_function func, unsigned int chan)
1859 {
1860 	struct ice_pf *pf = ptp_info_to_pf(info);
1861 	const struct ice_ptp_pin_desc *pin_desc;
1862 
1863 	pin_desc = &pf->ptp.ice_pin_desc[pin];
1864 
1865 	/* Is assigned function allowed? */
1866 	switch (func) {
1867 	case PTP_PF_EXTTS:
1868 		if (pin_desc->gpio[0] < 0)
1869 			return -EOPNOTSUPP;
1870 		break;
1871 	case PTP_PF_PEROUT:
1872 		if (pin_desc->gpio[1] < 0)
1873 			return -EOPNOTSUPP;
1874 		break;
1875 	case PTP_PF_NONE:
1876 		break;
1877 	case PTP_PF_PHYSYNC:
1878 	default:
1879 		return -EOPNOTSUPP;
1880 	}
1881 
1882 	return 0;
1883 }
1884 
1885 /**
1886  * ice_ptp_gpio_enable - Enable/disable ancillary features of PHC
1887  * @info: The driver's PTP info structure
1888  * @rq: The requested feature to change
1889  * @on: Enable/disable flag
1890  *
1891  * Return: 0 on success, negative error code otherwise
1892  */
1893 static int ice_ptp_gpio_enable(struct ptp_clock_info *info,
1894 			       struct ptp_clock_request *rq, int on)
1895 {
1896 	struct ice_pf *pf = ptp_info_to_pf(info);
1897 	int err;
1898 
1899 	switch (rq->type) {
1900 	case PTP_CLK_REQ_PEROUT:
1901 	{
1902 		struct ptp_perout_request *cached =
1903 			&pf->ptp.perout_rqs[rq->perout.index];
1904 
1905 		err = ice_ptp_cfg_perout(pf, &rq->perout, on);
1906 		if (!err) {
1907 			*cached = rq->perout;
1908 		} else {
1909 			cached->period.sec = 0;
1910 			cached->period.nsec = 0;
1911 		}
1912 		return err;
1913 	}
1914 	case PTP_CLK_REQ_EXTTS:
1915 	{
1916 		struct ptp_extts_request *cached =
1917 			&pf->ptp.extts_rqs[rq->extts.index];
1918 
1919 		err = ice_ptp_cfg_extts(pf, &rq->extts, on);
1920 		if (!err)
1921 			*cached = rq->extts;
1922 		else
1923 			cached->flags &= ~PTP_ENABLE_FEATURE;
1924 		return err;
1925 	}
1926 	default:
1927 		return -EOPNOTSUPP;
1928 	}
1929 }
1930 
1931 /**
1932  * ice_ptp_gettimex64 - Get the time of the clock
1933  * @info: the driver's PTP info structure
1934  * @ts: timespec64 structure to hold the current time value
1935  * @sts: Optional parameter for holding a pair of system timestamps from
1936  *       the system clock. Will be ignored if NULL is given.
1937  *
1938  * Read the device clock and return the correct value on ns, after converting it
1939  * into a timespec struct.
1940  */
1941 static int
1942 ice_ptp_gettimex64(struct ptp_clock_info *info, struct timespec64 *ts,
1943 		   struct ptp_system_timestamp *sts)
1944 {
1945 	struct ice_pf *pf = ptp_info_to_pf(info);
1946 	u64 time_ns;
1947 
1948 	time_ns = ice_ptp_read_src_clk_reg(pf, sts);
1949 	*ts = ns_to_timespec64(time_ns);
1950 	return 0;
1951 }
1952 
1953 /**
1954  * ice_ptp_settime64 - Set the time of the clock
1955  * @info: the driver's PTP info structure
1956  * @ts: timespec64 structure that holds the new time value
1957  *
1958  * Set the device clock to the user input value. The conversion from timespec
1959  * to ns happens in the write function.
1960  */
1961 static int
1962 ice_ptp_settime64(struct ptp_clock_info *info, const struct timespec64 *ts)
1963 {
1964 	struct ice_pf *pf = ptp_info_to_pf(info);
1965 	struct timespec64 ts64 = *ts;
1966 	struct ice_hw *hw = &pf->hw;
1967 	int err;
1968 
1969 	/* For Vernier mode on E82X, we need to recalibrate after new settime.
1970 	 * Start with marking timestamps as invalid.
1971 	 */
1972 	if (hw->mac_type == ICE_MAC_GENERIC) {
1973 		err = ice_ptp_clear_phy_offset_ready_e82x(hw);
1974 		if (err)
1975 			dev_warn(ice_pf_to_dev(pf), "Failed to mark timestamps as invalid before settime\n");
1976 	}
1977 
1978 	if (!ice_ptp_lock(hw)) {
1979 		err = -EBUSY;
1980 		goto exit;
1981 	}
1982 
1983 	/* Disable periodic outputs */
1984 	ice_ptp_disable_all_perout(pf);
1985 
1986 	err = ice_ptp_write_init(pf, &ts64);
1987 	ice_ptp_unlock(hw);
1988 
1989 	if (!err)
1990 		ice_ptp_reset_cached_phctime(pf);
1991 
1992 	/* Reenable periodic outputs */
1993 	ice_ptp_enable_all_perout(pf);
1994 
1995 	/* Recalibrate and re-enable timestamp blocks for E822/E823 */
1996 	if (hw->mac_type == ICE_MAC_GENERIC)
1997 		ice_ptp_restart_all_phy(pf);
1998 exit:
1999 	if (err) {
2000 		dev_err(ice_pf_to_dev(pf), "PTP failed to set time %d\n", err);
2001 		return err;
2002 	}
2003 
2004 	return 0;
2005 }
2006 
2007 /**
2008  * ice_ptp_adjtime_nonatomic - Do a non-atomic clock adjustment
2009  * @info: the driver's PTP info structure
2010  * @delta: Offset in nanoseconds to adjust the time by
2011  */
2012 static int ice_ptp_adjtime_nonatomic(struct ptp_clock_info *info, s64 delta)
2013 {
2014 	struct timespec64 now, then;
2015 	int ret;
2016 
2017 	then = ns_to_timespec64(delta);
2018 	ret = ice_ptp_gettimex64(info, &now, NULL);
2019 	if (ret)
2020 		return ret;
2021 	now = timespec64_add(now, then);
2022 
2023 	return ice_ptp_settime64(info, (const struct timespec64 *)&now);
2024 }
2025 
2026 /**
2027  * ice_ptp_adjtime - Adjust the time of the clock by the indicated delta
2028  * @info: the driver's PTP info structure
2029  * @delta: Offset in nanoseconds to adjust the time by
2030  */
2031 static int ice_ptp_adjtime(struct ptp_clock_info *info, s64 delta)
2032 {
2033 	struct ice_pf *pf = ptp_info_to_pf(info);
2034 	struct ice_hw *hw = &pf->hw;
2035 	struct device *dev;
2036 	int err;
2037 
2038 	dev = ice_pf_to_dev(pf);
2039 
2040 	/* Hardware only supports atomic adjustments using signed 32-bit
2041 	 * integers. For any adjustment outside this range, perform
2042 	 * a non-atomic get->adjust->set flow.
2043 	 */
2044 	if (delta > S32_MAX || delta < S32_MIN) {
2045 		dev_dbg(dev, "delta = %lld, adjtime non-atomic\n", delta);
2046 		return ice_ptp_adjtime_nonatomic(info, delta);
2047 	}
2048 
2049 	if (!ice_ptp_lock(hw)) {
2050 		dev_err(dev, "PTP failed to acquire semaphore in adjtime\n");
2051 		return -EBUSY;
2052 	}
2053 
2054 	/* Disable periodic outputs */
2055 	ice_ptp_disable_all_perout(pf);
2056 
2057 	err = ice_ptp_write_adj(pf, delta);
2058 
2059 	/* Reenable periodic outputs */
2060 	ice_ptp_enable_all_perout(pf);
2061 
2062 	ice_ptp_unlock(hw);
2063 
2064 	if (err) {
2065 		dev_err(dev, "PTP failed to adjust time, err %d\n", err);
2066 		return err;
2067 	}
2068 
2069 	ice_ptp_reset_cached_phctime(pf);
2070 
2071 	return 0;
2072 }
2073 
2074 /**
2075  * struct ice_crosststamp_cfg - Device cross timestamp configuration
2076  * @lock_reg: The hardware semaphore lock to use
2077  * @lock_busy: Bit in the semaphore lock indicating the lock is busy
2078  * @ctl_reg: The hardware register to request cross timestamp
2079  * @ctl_active: Bit in the control register to request cross timestamp
2080  * @art_time_l: Lower 32-bits of ART system time
2081  * @art_time_h: Upper 32-bits of ART system time
2082  * @dev_time_l: Lower 32-bits of device time (per timer index)
2083  * @dev_time_h: Upper 32-bits of device time (per timer index)
2084  */
2085 struct ice_crosststamp_cfg {
2086 	/* HW semaphore lock register */
2087 	u32 lock_reg;
2088 	u32 lock_busy;
2089 
2090 	/* Capture control register */
2091 	u32 ctl_reg;
2092 	u32 ctl_active;
2093 
2094 	/* Time storage */
2095 	u32 art_time_l;
2096 	u32 art_time_h;
2097 	u32 dev_time_l[2];
2098 	u32 dev_time_h[2];
2099 };
2100 
2101 static const struct ice_crosststamp_cfg ice_crosststamp_cfg_e82x = {
2102 	.lock_reg = PFHH_SEM,
2103 	.lock_busy = PFHH_SEM_BUSY_M,
2104 	.ctl_reg = GLHH_ART_CTL,
2105 	.ctl_active = GLHH_ART_CTL_ACTIVE_M,
2106 	.art_time_l = GLHH_ART_TIME_L,
2107 	.art_time_h = GLHH_ART_TIME_H,
2108 	.dev_time_l[0] = GLTSYN_HHTIME_L(0),
2109 	.dev_time_h[0] = GLTSYN_HHTIME_H(0),
2110 	.dev_time_l[1] = GLTSYN_HHTIME_L(1),
2111 	.dev_time_h[1] = GLTSYN_HHTIME_H(1),
2112 };
2113 
2114 #ifdef CONFIG_ICE_HWTS
2115 static const struct ice_crosststamp_cfg ice_crosststamp_cfg_e830 = {
2116 	.lock_reg = E830_PFPTM_SEM,
2117 	.lock_busy = E830_PFPTM_SEM_BUSY_M,
2118 	.ctl_reg = E830_GLPTM_ART_CTL,
2119 	.ctl_active = E830_GLPTM_ART_CTL_ACTIVE_M,
2120 	.art_time_l = E830_GLPTM_ART_TIME_L,
2121 	.art_time_h = E830_GLPTM_ART_TIME_H,
2122 	.dev_time_l[0] = E830_GLTSYN_PTMTIME_L(0),
2123 	.dev_time_h[0] = E830_GLTSYN_PTMTIME_H(0),
2124 	.dev_time_l[1] = E830_GLTSYN_PTMTIME_L(1),
2125 	.dev_time_h[1] = E830_GLTSYN_PTMTIME_H(1),
2126 };
2127 
2128 #endif /* CONFIG_ICE_HWTS */
2129 /**
2130  * struct ice_crosststamp_ctx - Device cross timestamp context
2131  * @snapshot: snapshot of system clocks for historic interpolation
2132  * @snapshot_clock_id: System clock ID for @snapshot
2133  * @pf: pointer to the PF private structure
2134  * @cfg: pointer to hardware configuration for cross timestamp
2135  */
2136 struct ice_crosststamp_ctx {
2137 	struct system_time_snapshot snapshot;
2138 	clockid_t snapshot_clock_id;
2139 	struct ice_pf *pf;
2140 	const struct ice_crosststamp_cfg *cfg;
2141 };
2142 
2143 /**
2144  * ice_capture_crosststamp - Capture a device/system cross timestamp
2145  * @device: Current device time
2146  * @system: System counter value read synchronously with device time
2147  * @__ctx: Context passed from ice_ptp_getcrosststamp
2148  *
2149  * Read device and system (ART) clock simultaneously and return the corrected
2150  * clock values in ns.
2151  *
2152  * Return: zero on success, or a negative error code on failure.
2153  */
2154 static int ice_capture_crosststamp(ktime_t *device,
2155 				   struct system_counterval_t *system,
2156 				   void *__ctx)
2157 {
2158 	struct ice_crosststamp_ctx *ctx = __ctx;
2159 	const struct ice_crosststamp_cfg *cfg;
2160 	u32 lock, ctl, ts_lo, ts_hi, tmr_idx;
2161 	struct ice_pf *pf;
2162 	struct ice_hw *hw;
2163 	int err;
2164 	u64 ts;
2165 
2166 	cfg = ctx->cfg;
2167 	pf = ctx->pf;
2168 	hw = &pf->hw;
2169 
2170 	tmr_idx = hw->func_caps.ts_func_info.tmr_index_assoc;
2171 	if (tmr_idx > 1)
2172 		return -EINVAL;
2173 
2174 	/* Poll until we obtain the cross-timestamp hardware semaphore */
2175 	err = rd32_poll_timeout(hw, cfg->lock_reg, lock,
2176 				!(lock & cfg->lock_busy),
2177 				10 * USEC_PER_MSEC, 50 * USEC_PER_MSEC);
2178 	if (err) {
2179 		dev_err(ice_pf_to_dev(pf), "PTP failed to get cross timestamp lock\n");
2180 		return -EBUSY;
2181 	}
2182 
2183 	/* Snapshot system time for historic interpolation */
2184 	ktime_get_snapshot_id(ctx->snapshot_clock_id, &ctx->snapshot);
2185 
2186 	/* Program cmd to master timer */
2187 	ice_ptp_src_cmd(hw, ICE_PTP_READ_TIME);
2188 
2189 	/* Start the ART and device clock sync sequence */
2190 	ctl = rd32(hw, cfg->ctl_reg);
2191 	ctl |= cfg->ctl_active;
2192 	wr32(hw, cfg->ctl_reg, ctl);
2193 
2194 	/* Poll until hardware completes the capture */
2195 	err = rd32_poll_timeout(hw, cfg->ctl_reg, ctl, !(ctl & cfg->ctl_active),
2196 				5, 20 * USEC_PER_MSEC);
2197 	if (err)
2198 		goto err_timeout;
2199 
2200 	/* Read ART system time */
2201 	ts_lo = rd32(hw, cfg->art_time_l);
2202 	ts_hi = rd32(hw, cfg->art_time_h);
2203 	ts = ((u64)ts_hi << 32) | ts_lo;
2204 	system->cycles = ts;
2205 	system->cs_id = CSID_X86_ART;
2206 	system->use_nsecs = true;
2207 
2208 	/* Read Device source clock time */
2209 	ts_lo = rd32(hw, cfg->dev_time_l[tmr_idx]);
2210 	ts_hi = rd32(hw, cfg->dev_time_h[tmr_idx]);
2211 	ts = ((u64)ts_hi << 32) | ts_lo;
2212 	*device = ns_to_ktime(ts);
2213 
2214 err_timeout:
2215 	/* Clear the master timer */
2216 	ice_ptp_src_cmd(hw, ICE_PTP_NOP);
2217 
2218 	/* Release HW lock */
2219 	lock = rd32(hw, cfg->lock_reg);
2220 	lock &= ~cfg->lock_busy;
2221 	wr32(hw, cfg->lock_reg, lock);
2222 
2223 	return err;
2224 }
2225 
2226 /**
2227  * ice_ptp_getcrosststamp - Capture a device cross timestamp
2228  * @info: the driver's PTP info structure
2229  * @cts: The memory to fill the cross timestamp info
2230  *
2231  * Capture a cross timestamp between the ART and the device PTP hardware
2232  * clock. Fill the cross timestamp information and report it back to the
2233  * caller.
2234  *
2235  * In order to correctly correlate the ART timestamp back to the TSC time, the
2236  * CPU must have X86_FEATURE_TSC_KNOWN_FREQ.
2237  *
2238  * Return: zero on success, or a negative error code on failure.
2239  */
2240 static int ice_ptp_getcrosststamp(struct ptp_clock_info *info,
2241 				  struct system_device_crosststamp *cts)
2242 {
2243 	struct ice_pf *pf = ptp_info_to_pf(info);
2244 	struct ice_crosststamp_ctx ctx = {
2245 		.snapshot_clock_id = cts->clock_id,
2246 		.pf = pf,
2247 	};
2248 
2249 	switch (pf->hw.mac_type) {
2250 	case ICE_MAC_GENERIC:
2251 	case ICE_MAC_GENERIC_3K_E825:
2252 		ctx.cfg = &ice_crosststamp_cfg_e82x;
2253 		break;
2254 #ifdef CONFIG_ICE_HWTS
2255 	case ICE_MAC_E830:
2256 		ctx.cfg = &ice_crosststamp_cfg_e830;
2257 		break;
2258 #endif /* CONFIG_ICE_HWTS */
2259 	default:
2260 		return -EOPNOTSUPP;
2261 	}
2262 
2263 	return get_device_system_crosststamp(ice_capture_crosststamp, &ctx,
2264 					     &ctx.snapshot, cts);
2265 }
2266 
2267 /**
2268  * ice_ptp_hwtstamp_get - interface to read the timestamping config
2269  * @netdev: Pointer to network interface device structure
2270  * @config: Timestamping configuration structure
2271  *
2272  * Copy the timestamping config to user buffer
2273  */
2274 int ice_ptp_hwtstamp_get(struct net_device *netdev,
2275 			 struct kernel_hwtstamp_config *config)
2276 {
2277 	struct ice_pf *pf = ice_netdev_to_pf(netdev);
2278 
2279 	if (pf->ptp.state != ICE_PTP_READY)
2280 		return -EIO;
2281 
2282 	*config = pf->ptp.tstamp_config;
2283 
2284 	return 0;
2285 }
2286 
2287 /**
2288  * ice_ptp_set_timestamp_mode - Setup driver for requested timestamp mode
2289  * @pf: Board private structure
2290  * @config: hwtstamp settings requested or saved
2291  */
2292 static int ice_ptp_set_timestamp_mode(struct ice_pf *pf,
2293 				      struct kernel_hwtstamp_config *config)
2294 {
2295 	switch (config->tx_type) {
2296 	case HWTSTAMP_TX_OFF:
2297 		pf->ptp.tstamp_config.tx_type = HWTSTAMP_TX_OFF;
2298 		break;
2299 	case HWTSTAMP_TX_ON:
2300 		pf->ptp.tstamp_config.tx_type = HWTSTAMP_TX_ON;
2301 		break;
2302 	default:
2303 		return -ERANGE;
2304 	}
2305 
2306 	switch (config->rx_filter) {
2307 	case HWTSTAMP_FILTER_NONE:
2308 		pf->ptp.tstamp_config.rx_filter = HWTSTAMP_FILTER_NONE;
2309 		break;
2310 	case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
2311 	case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
2312 	case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
2313 	case HWTSTAMP_FILTER_PTP_V2_EVENT:
2314 	case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
2315 	case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
2316 	case HWTSTAMP_FILTER_PTP_V2_SYNC:
2317 	case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
2318 	case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
2319 	case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
2320 	case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
2321 	case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
2322 	case HWTSTAMP_FILTER_NTP_ALL:
2323 	case HWTSTAMP_FILTER_ALL:
2324 		pf->ptp.tstamp_config.rx_filter = HWTSTAMP_FILTER_ALL;
2325 		break;
2326 	default:
2327 		return -ERANGE;
2328 	}
2329 
2330 	/* Immediately update the device timestamping mode */
2331 	ice_ptp_restore_timestamp_mode(pf);
2332 
2333 	return 0;
2334 }
2335 
2336 /**
2337  * ice_ptp_hwtstamp_set - interface to control the timestamping
2338  * @netdev: Pointer to network interface device structure
2339  * @config: Timestamping configuration structure
2340  * @extack: Netlink extended ack structure for error reporting
2341  *
2342  * Get the user config and store it
2343  */
2344 int ice_ptp_hwtstamp_set(struct net_device *netdev,
2345 			 struct kernel_hwtstamp_config *config,
2346 			 struct netlink_ext_ack *extack)
2347 {
2348 	struct ice_pf *pf = ice_netdev_to_pf(netdev);
2349 	int err;
2350 
2351 	if (pf->ptp.state != ICE_PTP_READY)
2352 		return -EAGAIN;
2353 
2354 	err = ice_ptp_set_timestamp_mode(pf, config);
2355 	if (err)
2356 		return err;
2357 
2358 	/* Return the actual configuration set */
2359 	*config = pf->ptp.tstamp_config;
2360 
2361 	return 0;
2362 }
2363 
2364 /**
2365  * ice_ptp_get_rx_hwts - Get packet Rx timestamp in ns
2366  * @rx_desc: Receive descriptor
2367  * @pkt_ctx: Packet context to get the cached time
2368  *
2369  * The driver receives a notification in the receive descriptor with timestamp.
2370  */
2371 u64 ice_ptp_get_rx_hwts(const union ice_32b_rx_flex_desc *rx_desc,
2372 			const struct ice_pkt_ctx *pkt_ctx)
2373 {
2374 	u64 ts_ns, cached_time;
2375 	u32 ts_high;
2376 
2377 	if (!(rx_desc->wb.time_stamp_low & ICE_PTP_TS_VALID))
2378 		return 0;
2379 
2380 	cached_time = READ_ONCE(pkt_ctx->cached_phctime);
2381 
2382 	/* Do not report a timestamp if we don't have a cached PHC time */
2383 	if (!cached_time)
2384 		return 0;
2385 
2386 	/* Use ice_ptp_extend_32b_ts directly, using the ring-specific cached
2387 	 * PHC value, rather than accessing the PF. This also allows us to
2388 	 * simply pass the upper 32bits of nanoseconds directly. Calling
2389 	 * ice_ptp_extend_40b_ts is unnecessary as it would just discard these
2390 	 * bits itself.
2391 	 */
2392 	ts_high = le32_to_cpu(rx_desc->wb.flex_ts.ts_high);
2393 	ts_ns = ice_ptp_extend_32b_ts(cached_time, ts_high);
2394 
2395 	ice_trace(rx_hwtstamp, cached_time, ts_high, ts_ns);
2396 
2397 	return ts_ns;
2398 }
2399 
2400 /**
2401  * ice_ptp_setup_pin_cfg - setup PTP pin_config structure
2402  * @pf: Board private structure
2403  */
2404 static void ice_ptp_setup_pin_cfg(struct ice_pf *pf)
2405 {
2406 	for (unsigned int i = 0; i < pf->ptp.info.n_pins; i++) {
2407 		const struct ice_ptp_pin_desc *desc = &pf->ptp.ice_pin_desc[i];
2408 		struct ptp_pin_desc *pin = &pf->ptp.pin_desc[i];
2409 		const char *name;
2410 
2411 		if (!ice_is_feature_supported(pf, ICE_F_SMA_CTRL))
2412 			name = ice_pin_names[desc->name_idx];
2413 		else
2414 			name = ice_pin_names_dpll[desc->name_idx];
2415 
2416 		strscpy(pin->name, name, sizeof(pin->name));
2417 
2418 		pin->index = i;
2419 	}
2420 
2421 	pf->ptp.info.pin_config = pf->ptp.pin_desc;
2422 }
2423 
2424 /**
2425  * ice_ptp_disable_pins - Disable PTP pins
2426  * @pf: pointer to the PF structure
2427  *
2428  * Disable the OS access to the pins. Called to clear out the OS
2429  * indications of pin support when we fail to setup pin array.
2430  */
2431 static void ice_ptp_disable_pins(struct ice_pf *pf)
2432 {
2433 	struct ptp_clock_info *info = &pf->ptp.info;
2434 
2435 	dev_warn(ice_pf_to_dev(pf), "Failed to configure PTP pin control\n");
2436 
2437 	info->enable = NULL;
2438 	info->verify = NULL;
2439 	info->n_pins = 0;
2440 	info->n_ext_ts = 0;
2441 	info->n_per_out = 0;
2442 }
2443 
2444 /**
2445  * ice_ptp_parse_sdp_entries - update ice_ptp_pin_desc structure from NVM
2446  * @pf: pointer to the PF structure
2447  * @entries: SDP connection section from NVM
2448  * @num_entries: number of valid entries in sdp_entries
2449  * @pins: PTP pins array to update
2450  *
2451  * Return: 0 on success, negative error code otherwise.
2452  */
2453 static int ice_ptp_parse_sdp_entries(struct ice_pf *pf, __le16 *entries,
2454 				     unsigned int num_entries,
2455 				     struct ice_ptp_pin_desc *pins)
2456 {
2457 	unsigned int n_pins = 0;
2458 	unsigned int i;
2459 
2460 	/* Setup ice_pin_desc array */
2461 	for (i = 0; i < ICE_N_PINS_MAX; i++) {
2462 		pins[i].name_idx = -1;
2463 		pins[i].gpio[0] = -1;
2464 		pins[i].gpio[1] = -1;
2465 	}
2466 
2467 	for (i = 0; i < num_entries; i++) {
2468 		u16 entry = le16_to_cpu(entries[i]);
2469 		DECLARE_BITMAP(bitmap, GPIO_NA);
2470 		unsigned int idx;
2471 		bool dir;
2472 		u16 gpio;
2473 
2474 		*bitmap = FIELD_GET(ICE_AQC_NVM_SDP_AC_PIN_M, entry);
2475 
2476 		/* Check if entry's pin bitmap is valid. */
2477 		if (bitmap_empty(bitmap, GPIO_NA))
2478 			continue;
2479 
2480 		dir = !!FIELD_GET(ICE_AQC_NVM_SDP_AC_DIR_M, entry);
2481 		gpio = FIELD_GET(ICE_AQC_NVM_SDP_AC_SDP_NUM_M, entry);
2482 
2483 		for (idx = 0; idx < ICE_N_PINS_MAX; idx++) {
2484 			if (pins[idx].name_idx == gpio)
2485 				break;
2486 		}
2487 
2488 		if (idx == ICE_N_PINS_MAX) {
2489 			/* Pin not found, setup its entry and name */
2490 			idx = n_pins++;
2491 			pins[idx].name_idx = gpio;
2492 		}
2493 		pins[idx].gpio[dir] = gpio;
2494 	}
2495 
2496 	for (i = 0; i < n_pins; i++) {
2497 		dev_dbg(ice_pf_to_dev(pf),
2498 			"NVM pin entry[%d] : name_idx %d gpio_out %d gpio_in %d\n",
2499 			i, pins[i].name_idx, pins[i].gpio[1], pins[i].gpio[0]);
2500 	}
2501 
2502 	pf->ptp.info.n_pins = n_pins;
2503 	return 0;
2504 }
2505 
2506 /**
2507  * ice_ptp_set_funcs_e82x - Set specialized functions for E82X support
2508  * @pf: Board private structure
2509  *
2510  * Assign functions to the PTP capabilities structure for E82X devices.
2511  * Functions which operate across all device families should be set directly
2512  * in ice_ptp_set_caps. Only add functions here which are distinct for E82X
2513  * devices.
2514  */
2515 static void ice_ptp_set_funcs_e82x(struct ice_pf *pf)
2516 {
2517 	pf->ptp.info.getcrosststamp = ice_ptp_getcrosststamp;
2518 
2519 	if (pf->hw.mac_type == ICE_MAC_GENERIC_3K_E825) {
2520 		pf->ptp.ice_pin_desc = ice_pin_desc_e825c;
2521 		pf->ptp.info.n_pins = ARRAY_SIZE(ice_pin_desc_e825c);
2522 	} else {
2523 		pf->ptp.ice_pin_desc = ice_pin_desc_e82x;
2524 		pf->ptp.info.n_pins = ARRAY_SIZE(ice_pin_desc_e82x);
2525 	}
2526 	ice_ptp_setup_pin_cfg(pf);
2527 }
2528 
2529 /**
2530  * ice_ptp_set_funcs_e810 - Set specialized functions for E810 support
2531  * @pf: Board private structure
2532  *
2533  * Assign functions to the PTP capabiltiies structure for E810 devices.
2534  * Functions which operate across all device families should be set directly
2535  * in ice_ptp_set_caps. Only add functions here which are distinct for E810
2536  * devices.
2537  */
2538 static void ice_ptp_set_funcs_e810(struct ice_pf *pf)
2539 {
2540 	__le16 entries[ICE_AQC_NVM_SDP_AC_MAX_SIZE];
2541 	struct ice_ptp_pin_desc *desc = NULL;
2542 	struct ice_ptp *ptp = &pf->ptp;
2543 	unsigned int num_entries;
2544 	int err;
2545 
2546 	err = ice_ptp_read_sdp_ac(&pf->hw, entries, &num_entries);
2547 	if (err) {
2548 		/* SDP section does not exist in NVM or is corrupted */
2549 		if (ice_is_feature_supported(pf, ICE_F_SMA_CTRL)) {
2550 			ptp->ice_pin_desc = ice_pin_desc_dpll;
2551 			ptp->info.n_pins = ARRAY_SIZE(ice_pin_desc_dpll);
2552 		} else {
2553 			pf->ptp.ice_pin_desc = ice_pin_desc_e810;
2554 			pf->ptp.info.n_pins = ARRAY_SIZE(ice_pin_desc_e810);
2555 		}
2556 		err = 0;
2557 	} else {
2558 		desc = devm_kzalloc_objs(ice_pf_to_dev(pf),
2559 					 struct ice_ptp_pin_desc,
2560 					 ICE_N_PINS_MAX);
2561 		if (!desc)
2562 			goto err;
2563 
2564 		err = ice_ptp_parse_sdp_entries(pf, entries, num_entries, desc);
2565 		if (err)
2566 			goto err;
2567 
2568 		ptp->ice_pin_desc = (const struct ice_ptp_pin_desc *)desc;
2569 	}
2570 
2571 	ptp->info.pin_config = ptp->pin_desc;
2572 	ice_ptp_setup_pin_cfg(pf);
2573 
2574 err:
2575 	if (err) {
2576 		devm_kfree(ice_pf_to_dev(pf), desc);
2577 		ice_ptp_disable_pins(pf);
2578 	}
2579 }
2580 
2581 /**
2582  * ice_ptp_set_funcs_e830 - Set specialized functions for E830 support
2583  * @pf: Board private structure
2584  *
2585  * Assign functions to the PTP capabiltiies structure for E830 devices.
2586  * Functions which operate across all device families should be set directly
2587  * in ice_ptp_set_caps. Only add functions here which are distinct for E830
2588  * devices.
2589  */
2590 static void ice_ptp_set_funcs_e830(struct ice_pf *pf)
2591 {
2592 #ifdef CONFIG_ICE_HWTS
2593 	if (pcie_ptm_enabled(pf->pdev) && boot_cpu_has(X86_FEATURE_ART))
2594 		pf->ptp.info.getcrosststamp = ice_ptp_getcrosststamp;
2595 
2596 #endif /* CONFIG_ICE_HWTS */
2597 	/* Rest of the config is the same as base E810 */
2598 	pf->ptp.ice_pin_desc = ice_pin_desc_e810;
2599 	pf->ptp.info.n_pins = ARRAY_SIZE(ice_pin_desc_e810);
2600 	ice_ptp_setup_pin_cfg(pf);
2601 }
2602 
2603 /**
2604  * ice_ptp_set_caps - Set PTP capabilities
2605  * @pf: Board private structure
2606  */
2607 static void ice_ptp_set_caps(struct ice_pf *pf)
2608 {
2609 	struct ptp_clock_info *info = &pf->ptp.info;
2610 	struct device *dev = ice_pf_to_dev(pf);
2611 
2612 	snprintf(info->name, sizeof(info->name) - 1, "%s-%s-clk",
2613 		 dev_driver_string(dev), dev_name(dev));
2614 	info->owner = THIS_MODULE;
2615 	info->max_adj = 100000000;
2616 	info->adjtime = ice_ptp_adjtime;
2617 	info->adjfine = ice_ptp_adjfine;
2618 	info->gettimex64 = ice_ptp_gettimex64;
2619 	info->settime64 = ice_ptp_settime64;
2620 	info->n_per_out = GLTSYN_TGT_H_IDX_MAX;
2621 	info->n_ext_ts = GLTSYN_EVNT_H_IDX_MAX;
2622 	info->enable = ice_ptp_gpio_enable;
2623 	info->verify = ice_verify_pin;
2624 
2625 	info->supported_extts_flags = PTP_RISING_EDGE |
2626 				      PTP_FALLING_EDGE |
2627 				      PTP_STRICT_FLAGS;
2628 	info->supported_perout_flags = PTP_PEROUT_PHASE;
2629 
2630 	switch (pf->hw.mac_type) {
2631 	case ICE_MAC_E810:
2632 		ice_ptp_set_funcs_e810(pf);
2633 		return;
2634 	case ICE_MAC_E830:
2635 		ice_ptp_set_funcs_e830(pf);
2636 		return;
2637 	case ICE_MAC_GENERIC:
2638 	case ICE_MAC_GENERIC_3K_E825:
2639 		ice_ptp_set_funcs_e82x(pf);
2640 		return;
2641 	default:
2642 		return;
2643 	}
2644 }
2645 
2646 /**
2647  * ice_ptp_create_clock - Create PTP clock device for userspace
2648  * @pf: Board private structure
2649  *
2650  * This function creates a new PTP clock device. It only creates one if we
2651  * don't already have one. Will return error if it can't create one, but success
2652  * if we already have a device. Should be used by ice_ptp_init to create clock
2653  * initially, and prevent global resets from creating new clock devices.
2654  */
2655 static long ice_ptp_create_clock(struct ice_pf *pf)
2656 {
2657 	struct ptp_clock_info *info;
2658 	struct device *dev;
2659 
2660 	/* No need to create a clock device if we already have one */
2661 	if (pf->ptp.clock)
2662 		return 0;
2663 
2664 	ice_ptp_set_caps(pf);
2665 
2666 	info = &pf->ptp.info;
2667 	dev = ice_pf_to_dev(pf);
2668 
2669 	/* Attempt to register the clock before enabling the hardware. */
2670 	pf->ptp.clock = ptp_clock_register(info, dev);
2671 	if (IS_ERR(pf->ptp.clock)) {
2672 		dev_err(ice_pf_to_dev(pf), "Failed to register PTP clock device");
2673 		return PTR_ERR(pf->ptp.clock);
2674 	}
2675 
2676 	return 0;
2677 }
2678 
2679 /**
2680  * ice_ptp_request_ts - Request an available Tx timestamp index
2681  * @tx: the PTP Tx timestamp tracker to request from
2682  * @skb: the SKB to associate with this timestamp request
2683  */
2684 s8 ice_ptp_request_ts(struct ice_ptp_tx *tx, struct sk_buff *skb)
2685 {
2686 	unsigned long flags;
2687 	u8 idx;
2688 
2689 	spin_lock_irqsave(&tx->lock, flags);
2690 
2691 	/* Check that this tracker is accepting new timestamp requests */
2692 	if (!ice_ptp_is_tx_tracker_up(tx)) {
2693 		spin_unlock_irqrestore(&tx->lock, flags);
2694 		return -1;
2695 	}
2696 
2697 	/* Find and set the first available index */
2698 	idx = find_next_zero_bit(tx->in_use, tx->len,
2699 				 tx->last_ll_ts_idx_read + 1);
2700 	if (idx == tx->len)
2701 		idx = find_first_zero_bit(tx->in_use, tx->len);
2702 
2703 	if (idx < tx->len) {
2704 		/* We got a valid index that no other thread could have set. Store
2705 		 * a reference to the skb and the start time to allow discarding old
2706 		 * requests.
2707 		 */
2708 		tx->tstamps[idx].start = jiffies;
2709 		tx->tstamps[idx].skb = skb_get(skb);
2710 		skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
2711 		clear_bit(idx, tx->stale);
2712 		/* Ensure index is setup before marking it as used */
2713 		smp_mb__before_atomic();
2714 		set_bit(idx, tx->in_use);
2715 		ice_trace(tx_tstamp_request, skb, idx);
2716 	}
2717 
2718 	spin_unlock_irqrestore(&tx->lock, flags);
2719 
2720 	/* return the appropriate PHY timestamp register index, -1 if no
2721 	 * indexes were available.
2722 	 */
2723 	if (idx >= tx->len)
2724 		return -1;
2725 	else
2726 		return idx + tx->offset;
2727 }
2728 
2729 void ice_ptp_process_ts(struct ice_pf *pf)
2730 {
2731 	switch (pf->ptp.tx_interrupt_mode) {
2732 	case ICE_PTP_TX_INTERRUPT_NONE:
2733 		/* This device has the clock owner handle timestamps for it */
2734 		return;
2735 	case ICE_PTP_TX_INTERRUPT_SELF:
2736 		/* This device handles its own timestamps */
2737 		ice_ptp_process_tx_tstamp(&pf->ptp.port.tx);
2738 		return;
2739 	case ICE_PTP_TX_INTERRUPT_ALL:
2740 		/* This device handles timestamps for all ports */
2741 		ice_ptp_tx_tstamp_owner(pf);
2742 		return;
2743 	default:
2744 		WARN_ONCE(1, "Unexpected Tx timestamp interrupt mode %u\n",
2745 			  pf->ptp.tx_interrupt_mode);
2746 		return;
2747 	}
2748 }
2749 
2750 static bool ice_port_has_timestamps(struct ice_ptp_tx *tx)
2751 {
2752 	bool more_timestamps;
2753 
2754 	scoped_guard(spinlock_irqsave, &tx->lock) {
2755 		if (!tx->init)
2756 			return false;
2757 
2758 		more_timestamps = !bitmap_empty(tx->in_use, tx->len);
2759 	}
2760 
2761 	return more_timestamps;
2762 }
2763 
2764 static bool ice_any_port_has_timestamps(struct ice_pf *pf)
2765 {
2766 	struct ice_port_list *ports = &pf->adapter->ports;
2767 	bool have_tstamps = false;
2768 	struct ice_ptp_port *port;
2769 	int srcu_idx;
2770 
2771 	srcu_idx = srcu_read_lock(&ports->srcu);
2772 	list_for_each_entry_srcu(port, &ports->list, list_node,
2773 				 srcu_read_lock_held(&ports->srcu)) {
2774 		if (!kref_get_unless_zero(&port->ref))
2775 			continue;
2776 
2777 		if (ice_port_has_timestamps(&port->tx))
2778 			have_tstamps = true;
2779 
2780 		kref_put(&port->ref, ice_ptp_release_port_srcu);
2781 
2782 		if (have_tstamps)
2783 			break;
2784 	}
2785 	srcu_read_unlock(&ports->srcu, srcu_idx);
2786 
2787 	return have_tstamps;
2788 }
2789 
2790 bool ice_ptp_tx_tstamps_pending(struct ice_pf *pf)
2791 {
2792 	struct ice_hw *hw = &pf->hw;
2793 	int ret;
2794 
2795 	/* Check software indicator */
2796 	switch (pf->ptp.tx_interrupt_mode) {
2797 	case ICE_PTP_TX_INTERRUPT_NONE:
2798 		return false;
2799 	case ICE_PTP_TX_INTERRUPT_SELF:
2800 		if (ice_port_has_timestamps(&pf->ptp.port.tx))
2801 			return true;
2802 		break;
2803 	case ICE_PTP_TX_INTERRUPT_ALL:
2804 		if (ice_any_port_has_timestamps(pf))
2805 			return true;
2806 		break;
2807 	default:
2808 		WARN_ONCE(1, "Unexpected Tx timestamp interrupt mode %u\n",
2809 			  pf->ptp.tx_interrupt_mode);
2810 		break;
2811 	}
2812 
2813 	/* Check hardware indicator */
2814 	ret = ice_check_phy_tx_tstamp_ready(hw);
2815 	if (ret < 0) {
2816 		dev_dbg(ice_pf_to_dev(pf), "Unable to read PHY Tx timestamp ready bitmap, err %d\n",
2817 			ret);
2818 		/* Stop triggering IRQs if we're unable to read PHY */
2819 		return false;
2820 	}
2821 
2822 	/* ice_check_phy_tx_tstamp_ready() returns 1 if there are timestamps
2823 	 * available, 0 if there are no waiting timestamps, and a negative
2824 	 * value if there was an error (which we checked for above).
2825 	 */
2826 	return ret > 0;
2827 }
2828 
2829 /**
2830  * ice_ptp_ts_irq - Process the PTP Tx timestamps in IRQ context
2831  * @pf: Board private structure
2832  *
2833  * Return: IRQ_WAKE_THREAD if Tx timestamp read has to be handled in the bottom
2834  *         half of the interrupt and IRQ_HANDLED otherwise.
2835  */
2836 irqreturn_t ice_ptp_ts_irq(struct ice_pf *pf)
2837 {
2838 	struct ice_hw *hw = &pf->hw;
2839 
2840 	switch (hw->mac_type) {
2841 	case ICE_MAC_E810:
2842 		/* E810 capable of low latency timestamping with interrupt can
2843 		 * request a single timestamp in the top half and wait for
2844 		 * a second LL TS interrupt from the FW when it's ready.
2845 		 */
2846 		if (hw->dev_caps.ts_dev_info.ts_ll_int_read) {
2847 			struct ice_ptp_tx *tx = &pf->ptp.port.tx;
2848 			u8 idx, last;
2849 
2850 			if (!ice_pf_state_is_nominal(pf))
2851 				return IRQ_HANDLED;
2852 
2853 			spin_lock(&tx->lock);
2854 			if (tx->init) {
2855 				last = tx->last_ll_ts_idx_read + 1;
2856 				idx = find_next_bit_wrap(tx->in_use, tx->len,
2857 							 last);
2858 				if (idx != tx->len)
2859 					ice_ptp_req_tx_single_tstamp(tx, idx);
2860 			}
2861 			spin_unlock(&tx->lock);
2862 
2863 			return IRQ_HANDLED;
2864 		}
2865 		fallthrough; /* non-LL_TS E810 */
2866 	case ICE_MAC_GENERIC:
2867 	case ICE_MAC_GENERIC_3K_E825:
2868 		/* All other devices process timestamps in the bottom half due
2869 		 * to sleeping or polling.
2870 		 */
2871 		if (!ice_ptp_pf_handles_tx_interrupt(pf))
2872 			return IRQ_HANDLED;
2873 
2874 		set_bit(ICE_MISC_THREAD_TX_TSTAMP, pf->misc_thread);
2875 		return IRQ_WAKE_THREAD;
2876 	case ICE_MAC_E830:
2877 		/* E830 can read timestamps in the top half using rd32() */
2878 		ice_ptp_process_ts(pf);
2879 
2880 		if (ice_ptp_tx_tstamps_pending(pf)) {
2881 			/* Process outstanding Tx timestamps. If there
2882 			 * is more work, re-arm the interrupt to trigger again.
2883 			 */
2884 			wr32(hw, PFINT_OICR, PFINT_OICR_TSYN_TX_M);
2885 			ice_flush(hw);
2886 		}
2887 		return IRQ_HANDLED;
2888 	default:
2889 		return IRQ_HANDLED;
2890 	}
2891 }
2892 
2893 /**
2894  * ice_ptp_maybe_trigger_tx_interrupt - Trigger Tx timstamp interrupt
2895  * @pf: Board private structure
2896  *
2897  * The device PHY issues Tx timestamp interrupts to the driver for processing
2898  * timestamp data from the PHY. It will not interrupt again until all
2899  * current timestamp data is read. In rare circumstances, it is possible that
2900  * the driver fails to read all outstanding data.
2901  *
2902  * To avoid getting permanently stuck, periodically check if the PHY has
2903  * outstanding timestamp data. If so, trigger an interrupt from software to
2904  * process this data.
2905  */
2906 static void ice_ptp_maybe_trigger_tx_interrupt(struct ice_pf *pf)
2907 {
2908 	struct device *dev = ice_pf_to_dev(pf);
2909 	struct ice_hw *hw = &pf->hw;
2910 	int ret;
2911 
2912 	if (!pf->ptp.port.tx.has_ready_bitmap)
2913 		return;
2914 
2915 	if (!ice_pf_src_tmr_owned(pf))
2916 		return;
2917 
2918 	ret = ice_check_phy_tx_tstamp_ready(hw);
2919 	if (ret < 0) {
2920 		dev_dbg(dev, "PTP periodic task unable to read PHY timestamp ready bitmap, err %d\n",
2921 			ret);
2922 	} else if (ret) {
2923 		dev_dbg(dev, "PTP periodic task detected waiting timestamps. Triggering Tx timestamp interrupt now.\n");
2924 
2925 		wr32(hw, PFINT_OICR, PFINT_OICR_TSYN_TX_M);
2926 		ice_flush(hw);
2927 	}
2928 }
2929 
2930 /**
2931  * ice_ptp_tspll_monitor - poll and recover TSPLL lock on E825 owner PFs
2932  * @pf: Board private structure
2933  *
2934  * Called from the PTP periodic worker. On E825 devices that own the source
2935  * timer, poll the TSPLL lock status via CGU registers and trigger a restart
2936  * if the lock has been lost. The result is cached in @pf->ptp.tspll_locked
2937  * so it can be consumed by the DPLL periodic worker via READ_ONCE().
2938  *
2939  * TSPLL lock is critical for PHC operation and must be monitored regardless
2940  * of whether DPLL init succeeded or CONFIG_DPLL is enabled. Placing the
2941  * monitor here makes recovery independent of the dpll subsystem.
2942  *
2943  * AQ read errors are rate-limited and do not stop monitoring. Lock-lost
2944  * events are logged every 120 retries (~60 s at normal poll rate) to
2945  * surface persistent failures without flooding the log.
2946  */
2947 static void ice_ptp_tspll_monitor(struct ice_pf *pf)
2948 {
2949 	bool lock_lost;
2950 	int err;
2951 
2952 	if (pf->hw.mac_type != ICE_MAC_GENERIC_3K_E825 ||
2953 	    !ice_pf_src_tmr_owned(pf))
2954 		return;
2955 
2956 	/* Serialize the entire monitor tick against TSPLL userspace reconfig
2957 	 * (ice_dpll_tspll_state_on_dpll_set()). Both paths read HW state and
2958 	 * write pf->ptp.tspll_locked; without holding pf->dplls.lock across
2959 	 * the HW read here, a preempted monitor could observe stale HW state
2960 	 * and then overwrite an accurate cache update from the DPLL callback.
2961 	 * pf->dplls.lock is initialized in ice_init_features() before the PTP
2962 	 * kworker starts and destroyed in ice_deinit_features() only after
2963 	 * ice_ptp_release() has drained the kworker, so it is always valid.
2964 	 */
2965 	mutex_lock(&pf->dplls.lock);
2966 	err = ice_tspll_lost_lock_e825c(&pf->hw, &lock_lost);
2967 	if (err) {
2968 		mutex_unlock(&pf->dplls.lock);
2969 		dev_err_ratelimited(ice_pf_to_dev(pf),
2970 				    "Failed reading TimeSync PLL lock status (err: %d). Retrying.\n",
2971 				    err);
2972 		return;
2973 	}
2974 
2975 	if (lock_lost) {
2976 		WRITE_ONCE(pf->ptp.tspll_locked, false);
2977 		if (!(pf->ptp.tspll_lock_retries % ICE_TSPLL_LOG_INTERVAL))
2978 			dev_warn(ice_pf_to_dev(pf),
2979 				 "TimeSync PLL lock lost. Retrying to acquire lock.\n");
2980 		err = ice_tspll_restart_e825c(&pf->hw);
2981 		if (err)
2982 			dev_err_ratelimited(ice_pf_to_dev(pf),
2983 					    "Failed to restart TimeSync PLL (err: %d).\n",
2984 					    err);
2985 		pf->ptp.tspll_lock_retries++;
2986 	} else {
2987 		if (pf->ptp.tspll_lock_retries) {
2988 			const char *src_str = "unknown";
2989 			enum ice_clk_src clk_src;
2990 
2991 			if (!ice_tspll_get_clk_src(&pf->hw, &clk_src))
2992 				src_str = ice_tspll_clk_src_str(clk_src);
2993 			dev_info(ice_pf_to_dev(pf),
2994 				 "TimeSync PLL lock acquired with %s clock source after %u retries.\n",
2995 				 src_str, pf->ptp.tspll_lock_retries);
2996 		}
2997 		WRITE_ONCE(pf->ptp.tspll_locked, true);
2998 		pf->ptp.tspll_lock_retries = 0;
2999 	}
3000 	mutex_unlock(&pf->dplls.lock);
3001 }
3002 
3003 static void ice_ptp_periodic_work(struct kthread_work *work)
3004 {
3005 	struct ice_ptp *ptp = container_of(work, struct ice_ptp, work.work);
3006 	struct ice_pf *pf = container_of(ptp, struct ice_pf, ptp);
3007 	int err;
3008 
3009 	if (pf->ptp.state != ICE_PTP_READY)
3010 		return;
3011 
3012 	ice_ptp_tspll_monitor(pf);
3013 
3014 	err = ice_ptp_update_cached_phctime(pf);
3015 
3016 	ice_ptp_maybe_trigger_tx_interrupt(pf);
3017 
3018 	/* Run twice a second or reschedule if phc update failed */
3019 	kthread_queue_delayed_work(ptp->kworker, &ptp->work,
3020 				   msecs_to_jiffies(err ? 10 : 500));
3021 }
3022 
3023 /**
3024  * ice_ptp_queue_work - Queue PTP periodic work for a PF
3025  * @pf: Board private structure
3026  *
3027  * Helper function to queue PTP periodic work after VSI rebuild completes.
3028  * This ensures that PTP work only runs when VSI structures are ready.
3029  */
3030 void ice_ptp_queue_work(struct ice_pf *pf)
3031 {
3032 	if (test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags) &&
3033 	    pf->ptp.state == ICE_PTP_READY)
3034 		kthread_queue_delayed_work(pf->ptp.kworker, &pf->ptp.work, 0);
3035 }
3036 
3037 /**
3038  * ice_ptp_prepare_rebuild_sec - Prepare second NAC for PTP reset or rebuild
3039  * @pf: Board private structure
3040  * @rebuild: rebuild if true, prepare if false
3041  * @reset_type: the reset type being performed
3042  */
3043 static void ice_ptp_prepare_rebuild_sec(struct ice_pf *pf, bool rebuild,
3044 					enum ice_reset_req reset_type)
3045 {
3046 	struct ice_port_list *ports = &pf->adapter->ports;
3047 	struct ice_ptp_port *port;
3048 	int srcu_idx;
3049 
3050 	srcu_idx = srcu_read_lock(&ports->srcu);
3051 	list_for_each_entry_srcu(port, &ports->list, list_node,
3052 				 srcu_read_lock_held(&ports->srcu)) {
3053 		struct ice_pf *peer_pf = ptp_port_to_pf(port);
3054 
3055 		if (!kref_get_unless_zero(&port->ref))
3056 			continue;
3057 
3058 		if (!ice_is_primary(&peer_pf->hw)) {
3059 			if (rebuild) {
3060 				/* TODO: When implementing rebuild=true:
3061 				 * 1. Ensure secondary PFs' VSIs are rebuilt
3062 				 * 2. Call ice_ptp_queue_work(peer_pf) after VSI rebuild
3063 				 */
3064 				ice_ptp_rebuild(peer_pf, reset_type);
3065 			} else {
3066 				ice_ptp_prepare_for_reset(peer_pf, reset_type);
3067 			}
3068 		}
3069 
3070 		kref_put(&port->ref, ice_ptp_release_port_srcu);
3071 	}
3072 	srcu_read_unlock(&ports->srcu, srcu_idx);
3073 }
3074 
3075 /**
3076  * ice_ptp_prepare_for_reset - Prepare PTP for reset
3077  * @pf: Board private structure
3078  * @reset_type: the reset type being performed
3079  */
3080 void ice_ptp_prepare_for_reset(struct ice_pf *pf, enum ice_reset_req reset_type)
3081 {
3082 	struct ice_ptp *ptp = &pf->ptp;
3083 	struct ice_hw *hw = &pf->hw;
3084 	u8 src_tmr;
3085 
3086 	if (ptp->state != ICE_PTP_READY)
3087 		return;
3088 
3089 	ptp->state = ICE_PTP_RESETTING;
3090 
3091 	/* Disable timestamping for both Tx and Rx */
3092 	ice_ptp_disable_timestamp_mode(pf);
3093 
3094 	kthread_cancel_delayed_work_sync(&ptp->work);
3095 
3096 	if (reset_type == ICE_RESET_PFR)
3097 		return;
3098 
3099 	if (ice_pf_src_tmr_owned(pf) && hw->mac_type == ICE_MAC_GENERIC_3K_E825)
3100 		ice_ptp_prepare_rebuild_sec(pf, false, reset_type);
3101 
3102 	ice_ptp_release_tx_tracker(pf, &pf->ptp.port.tx);
3103 
3104 	/* Disable periodic outputs */
3105 	ice_ptp_disable_all_perout(pf);
3106 
3107 	src_tmr = ice_get_ptp_src_clock_index(&pf->hw);
3108 
3109 	/* Disable source clock */
3110 	wr32(&pf->hw, GLTSYN_ENA(src_tmr), (u32)~GLTSYN_ENA_TSYN_ENA_M);
3111 
3112 	/* Acquire PHC and system timer to restore after reset */
3113 	ptp->reset_time = ktime_get_real_ns();
3114 }
3115 
3116 /**
3117  * ice_ptp_rebuild_owner - Initialize PTP clock owner after reset
3118  * @pf: Board private structure
3119  *
3120  * Companion function for ice_ptp_rebuild() which handles tasks that only the
3121  * PTP clock owner instance should perform.
3122  */
3123 static int ice_ptp_rebuild_owner(struct ice_pf *pf)
3124 {
3125 	struct ice_ptp *ptp = &pf->ptp;
3126 	struct ice_hw *hw = &pf->hw;
3127 	struct timespec64 ts;
3128 	u64 time_diff;
3129 	int err;
3130 
3131 	err = ice_ptp_init_phc(hw);
3132 	if (err)
3133 		return err;
3134 
3135 	err = ice_tspll_init(hw);
3136 	if (err)
3137 		return err;
3138 	/* Rebuild reinitialized TSPLL, so reset monitor retry state. */
3139 	WRITE_ONCE(ptp->tspll_locked, true);
3140 	ptp->tspll_lock_retries = 0;
3141 
3142 	/* Acquire the global hardware lock */
3143 	if (!ice_ptp_lock(hw)) {
3144 		err = -EBUSY;
3145 		return err;
3146 	}
3147 
3148 	/* Write the increment time value to PHY and LAN */
3149 	err = ice_ptp_write_incval(hw, ice_base_incval(pf));
3150 	if (err)
3151 		goto err_unlock;
3152 
3153 	/* Write the initial Time value to PHY and LAN using the cached PHC
3154 	 * time before the reset and time difference between stopping and
3155 	 * starting the clock.
3156 	 */
3157 	if (ptp->cached_phc_time) {
3158 		time_diff = ktime_get_real_ns() - ptp->reset_time;
3159 		ts = ns_to_timespec64(ptp->cached_phc_time + time_diff);
3160 	} else {
3161 		ts = ktime_to_timespec64(ktime_get_real());
3162 	}
3163 	err = ice_ptp_write_init(pf, &ts);
3164 	if (err)
3165 		goto err_unlock;
3166 
3167 	/* Release the global hardware lock */
3168 	ice_ptp_unlock(hw);
3169 
3170 	/* Flush software tracking of any outstanding timestamps since we're
3171 	 * about to flush the PHY timestamp block.
3172 	 */
3173 	ice_ptp_flush_all_tx_tracker(pf);
3174 
3175 	/* Enable quad interrupts */
3176 	err = ice_ptp_cfg_phy_interrupt(pf, true, 1);
3177 	if (err)
3178 		return err;
3179 
3180 	ice_ptp_restart_all_phy(pf);
3181 
3182 	/* Re-enable all periodic outputs and external timestamp events */
3183 	ice_ptp_enable_all_perout(pf);
3184 	ice_ptp_enable_all_extts(pf);
3185 
3186 	return 0;
3187 
3188 err_unlock:
3189 	ice_ptp_unlock(hw);
3190 	return err;
3191 }
3192 
3193 /**
3194  * ice_ptp_rebuild - Initialize PTP hardware clock support after reset
3195  * @pf: Board private structure
3196  * @reset_type: the reset type being performed
3197  */
3198 void ice_ptp_rebuild(struct ice_pf *pf, enum ice_reset_req reset_type)
3199 {
3200 	struct ice_ptp *ptp = &pf->ptp;
3201 	int err;
3202 
3203 	if (ptp->state == ICE_PTP_UNINIT) {
3204 		dev_dbg(ice_pf_to_dev(pf), "PTP was not initialized, skipping rebuild\n");
3205 		return;
3206 	}
3207 
3208 	if (ptp->state == ICE_PTP_READY) {
3209 		ice_ptp_prepare_for_reset(pf, reset_type);
3210 	} else if (ptp->state != ICE_PTP_RESETTING) {
3211 		err = -EINVAL;
3212 		dev_err(ice_pf_to_dev(pf), "PTP was not initialized\n");
3213 		goto err;
3214 	}
3215 
3216 	if (ice_pf_src_tmr_owned(pf) && reset_type != ICE_RESET_PFR) {
3217 		err = ice_ptp_rebuild_owner(pf);
3218 		if (err)
3219 			goto err;
3220 	}
3221 
3222 	ptp->state = ICE_PTP_READY;
3223 
3224 	dev_info(ice_pf_to_dev(pf), "PTP reset successful\n");
3225 	return;
3226 
3227 err:
3228 	ptp->state = ICE_PTP_ERROR;
3229 	dev_err(ice_pf_to_dev(pf), "PTP reset failed %d\n", err);
3230 }
3231 
3232 static void ice_ptp_setup_adapter(struct ice_pf *pf)
3233 {
3234 	pf->adapter->ctrl_pf = pf;
3235 }
3236 
3237 static int ice_ptp_setup_pf(struct ice_pf *pf)
3238 {
3239 	struct ice_ptp *ctrl_ptp = ice_get_ctrl_ptp(pf);
3240 	struct ice_ptp *ptp = &pf->ptp;
3241 
3242 	if (!ctrl_ptp) {
3243 		dev_info(ice_pf_to_dev(pf),
3244 			 "PTP unavailable: no controlling PF\n");
3245 		return -EOPNOTSUPP;
3246 	}
3247 
3248 	if (pf->hw.mac_type == ICE_MAC_UNKNOWN)
3249 		return -ENODEV;
3250 
3251 	INIT_LIST_HEAD(&ptp->port.list_node);
3252 	kref_init(&ptp->port.ref);
3253 
3254 	spin_lock(&pf->adapter->ports.lock);
3255 	list_add_rcu(&ptp->port.list_node, &pf->adapter->ports.list);
3256 	spin_unlock(&pf->adapter->ports.lock);
3257 
3258 	/* Seed the per-PHY Tx reference clock usage map for this port.
3259 	 * Only meaningful on E825 (other MAC types don't expose tx-clk
3260 	 * selection). No locking is needed because this runs during
3261 	 * ice_ptp_init() before pf->dplls.lock exists and before any
3262 	 * link event or DPLL callback can observe the map.
3263 	 */
3264 	if (pf->hw.mac_type == ICE_MAC_GENERIC_3K_E825) {
3265 		u8 port_num, phy;
3266 
3267 		port_num = ptp->port.port_num;
3268 		phy = port_num / pf->hw.ptp.ports_per_phy;
3269 		set_bit(port_num,
3270 			&ctrl_ptp->tx_refclks[phy][pf->ptp.port.tx_clk]);
3271 	}
3272 
3273 	return 0;
3274 }
3275 
3276 static void ice_ptp_cleanup_pf(struct ice_pf *pf)
3277 {
3278 	struct ice_port_list *ports = &pf->adapter->ports;
3279 	struct ice_ptp *ptp = &pf->ptp;
3280 	struct kref *ref;
3281 
3282 	if (pf->hw.mac_type == ICE_MAC_UNKNOWN)
3283 		return;
3284 
3285 	spin_lock(&ports->lock);
3286 	list_del_rcu(&ptp->port.list_node);
3287 	spin_unlock(&ports->lock);
3288 
3289 	ref = &ptp->port.ref;
3290 	kref_put(ref, ice_ptp_release_port_srcu);
3291 
3292 	wait_var_event(ref, !kref_read(ref));
3293 
3294 	synchronize_srcu(&ports->srcu);
3295 }
3296 
3297 /**
3298  * ice_ptp_clock_index - Get the PTP clock index for this device
3299  * @pf: Board private structure
3300  *
3301  * Returns: the PTP clock index associated with this PF, or -1 if no PTP clock
3302  * is associated.
3303  */
3304 int ice_ptp_clock_index(struct ice_pf *pf)
3305 {
3306 	struct ice_ptp *ctrl_ptp = ice_get_ctrl_ptp(pf);
3307 	struct ptp_clock *clock;
3308 
3309 	if (!ctrl_ptp)
3310 		return -1;
3311 	clock = ctrl_ptp->clock;
3312 
3313 	return clock ? ptp_clock_index(clock) : -1;
3314 }
3315 
3316 /**
3317  * ice_ptp_init_owner - Initialize PTP_1588_CLOCK device
3318  * @pf: Board private structure
3319  *
3320  * Setup and initialize a PTP clock device that represents the device hardware
3321  * clock. Save the clock index for other functions connected to the same
3322  * hardware resource.
3323  */
3324 static int ice_ptp_init_owner(struct ice_pf *pf)
3325 {
3326 	struct ice_hw *hw = &pf->hw;
3327 	struct timespec64 ts;
3328 	int err;
3329 
3330 	err = ice_ptp_init_phc(hw);
3331 	if (err) {
3332 		dev_err(ice_pf_to_dev(pf), "Failed to initialize PHC, err %d\n",
3333 			err);
3334 		return err;
3335 	}
3336 
3337 	err = ice_tspll_init(hw);
3338 	if (err) {
3339 		dev_err(ice_pf_to_dev(pf), "Failed to initialize CGU, status %d\n",
3340 			err);
3341 		return err;
3342 	}
3343 
3344 	/* Acquire the global hardware lock */
3345 	if (!ice_ptp_lock(hw)) {
3346 		err = -EBUSY;
3347 		goto err_exit;
3348 	}
3349 
3350 	/* Write the increment time value to PHY and LAN */
3351 	err = ice_ptp_write_incval(hw, ice_base_incval(pf));
3352 	if (err)
3353 		goto err_unlock;
3354 
3355 	ts = ktime_to_timespec64(ktime_get_real());
3356 	/* Write the initial Time value to PHY and LAN */
3357 	err = ice_ptp_write_init(pf, &ts);
3358 	if (err)
3359 		goto err_unlock;
3360 
3361 	/* Release the global hardware lock */
3362 	ice_ptp_unlock(hw);
3363 
3364 	/* Configure PHY interrupt settings */
3365 	err = ice_ptp_cfg_phy_interrupt(pf, true, 1);
3366 	if (err)
3367 		goto err_exit;
3368 
3369 	/* Ensure we have a clock device */
3370 	err = ice_ptp_create_clock(pf);
3371 	if (err)
3372 		goto err_clk;
3373 
3374 	return 0;
3375 err_clk:
3376 	pf->ptp.clock = NULL;
3377 err_exit:
3378 	return err;
3379 
3380 err_unlock:
3381 	ice_ptp_unlock(hw);
3382 	return err;
3383 }
3384 
3385 /**
3386  * ice_ptp_init_work - Initialize PTP work threads
3387  * @pf: Board private structure
3388  * @ptp: PF PTP structure
3389  */
3390 static int ice_ptp_init_work(struct ice_pf *pf, struct ice_ptp *ptp)
3391 {
3392 	struct kthread_worker *kworker;
3393 
3394 	/* Initialize work functions */
3395 	kthread_init_delayed_work(&ptp->work, ice_ptp_periodic_work);
3396 
3397 	/* Allocate a kworker for handling work required for the ports
3398 	 * connected to the PTP hardware clock.
3399 	 */
3400 	kworker = kthread_run_worker(0, "ice-ptp-%s",
3401 					dev_name(ice_pf_to_dev(pf)));
3402 	if (IS_ERR(kworker))
3403 		return PTR_ERR(kworker);
3404 
3405 	ptp->kworker = kworker;
3406 
3407 	/* Start periodic work going */
3408 	kthread_queue_delayed_work(ptp->kworker, &ptp->work, 0);
3409 
3410 	return 0;
3411 }
3412 
3413 /**
3414  * ice_ptp_init_port - Initialize PTP port structure
3415  * @pf: Board private structure
3416  * @ptp_port: PTP port structure
3417  *
3418  * Return: 0 on success, -ENODEV on invalid MAC type, -ENOMEM on failed alloc.
3419  */
3420 static int ice_ptp_init_port(struct ice_pf *pf, struct ice_ptp_port *ptp_port)
3421 {
3422 	struct ice_hw *hw = &pf->hw;
3423 
3424 	mutex_init(&ptp_port->ps_lock);
3425 
3426 	switch (hw->mac_type) {
3427 	case ICE_MAC_E810:
3428 	case ICE_MAC_E830:
3429 	case ICE_MAC_GENERIC_3K_E825:
3430 		return ice_ptp_init_tx(pf, &ptp_port->tx, ptp_port->port_num);
3431 	case ICE_MAC_GENERIC:
3432 		kthread_init_delayed_work(&ptp_port->ov_work,
3433 					  ice_ptp_wait_for_offsets);
3434 		return ice_ptp_init_tx_e82x(pf, &ptp_port->tx,
3435 					    ptp_port->port_num);
3436 	default:
3437 		return -ENODEV;
3438 	}
3439 }
3440 
3441 /**
3442  * ice_ptp_init_tx_interrupt_mode - Initialize device Tx interrupt mode
3443  * @pf: Board private structure
3444  *
3445  * Initialize the Tx timestamp interrupt mode for this device. For most device
3446  * types, each PF processes the interrupt and manages its own timestamps. For
3447  * E822-based devices, only the clock owner processes the timestamps. Other
3448  * PFs disable the interrupt and do not process their own timestamps.
3449  */
3450 static void ice_ptp_init_tx_interrupt_mode(struct ice_pf *pf)
3451 {
3452 	switch (pf->hw.mac_type) {
3453 	case ICE_MAC_GENERIC:
3454 	case ICE_MAC_GENERIC_3K_E825:
3455 		/* E82x hardware has the clock owner process timestamps for
3456 		 * all ports.
3457 		 */
3458 		if (ice_pf_src_tmr_owned(pf))
3459 			pf->ptp.tx_interrupt_mode = ICE_PTP_TX_INTERRUPT_ALL;
3460 		else
3461 			pf->ptp.tx_interrupt_mode = ICE_PTP_TX_INTERRUPT_NONE;
3462 		break;
3463 	default:
3464 		/* other PHY types handle their own Tx interrupt */
3465 		pf->ptp.tx_interrupt_mode = ICE_PTP_TX_INTERRUPT_SELF;
3466 	}
3467 }
3468 
3469 /**
3470  * ice_ptp_init - Initialize PTP hardware clock support
3471  * @pf: Board private structure
3472  *
3473  * Set up the device for interacting with the PTP hardware clock for all
3474  * functions, both the function that owns the clock hardware, and the
3475  * functions connected to the clock hardware.
3476  *
3477  * The clock owner will allocate and register a ptp_clock with the
3478  * PTP_1588_CLOCK infrastructure. All functions allocate a kthread and work
3479  * items used for asynchronous work such as Tx timestamps and periodic work.
3480  */
3481 void ice_ptp_init(struct ice_pf *pf)
3482 {
3483 	struct ice_ptp *ptp = &pf->ptp;
3484 	struct ice_hw *hw = &pf->hw;
3485 	int err;
3486 
3487 	ptp->state = ICE_PTP_INITIALIZING;
3488 
3489 	if (hw->lane_num < 0) {
3490 		err = hw->lane_num;
3491 		goto err_exit;
3492 	}
3493 	ptp->port.port_num = hw->lane_num;
3494 
3495 	ptp->tspll_locked = true;
3496 	ice_ptp_init_hw(hw);
3497 
3498 	ice_ptp_init_tx_interrupt_mode(pf);
3499 
3500 	/* If this function owns the clock hardware, it must allocate and
3501 	 * configure the PTP clock device to represent it.
3502 	 */
3503 	if (ice_pf_src_tmr_owned(pf)) {
3504 		ice_ptp_setup_adapter(pf);
3505 
3506 		err = ice_ptp_init_owner(pf);
3507 		if (err)
3508 			goto err_exit;
3509 	}
3510 
3511 	ptp->port.tx_clk = ICE_REF_CLK_ENET;
3512 	ptp->port.tx_clk_req = ICE_REF_CLK_ENET;
3513 	if (hw->mac_type == ICE_MAC_GENERIC_3K_E825) {
3514 		enum ice_e825c_ref_clk tx_ref_clk;
3515 
3516 		err = ice_get_serdes_ref_sel_e825c(hw, ptp->port.port_num,
3517 						   &tx_ref_clk);
3518 		if (!err) {
3519 			ptp->port.tx_clk = tx_ref_clk;
3520 			ptp->port.tx_clk_req = tx_ref_clk;
3521 		}
3522 	}
3523 
3524 	err = ice_ptp_setup_pf(pf);
3525 	if (err)
3526 		goto err_exit;
3527 
3528 	err = ice_ptp_init_port(pf, &ptp->port);
3529 	if (err)
3530 		goto err_clean_pf;
3531 
3532 	/* Start the PHY timestamping block */
3533 	ice_ptp_reset_phy_timestamping(pf);
3534 
3535 	/* Configure initial Tx interrupt settings */
3536 	ice_ptp_cfg_tx_interrupt(pf);
3537 
3538 	ptp->state = ICE_PTP_READY;
3539 
3540 	err = ice_ptp_init_work(pf, ptp);
3541 	if (err)
3542 		goto err_exit;
3543 
3544 	dev_info(ice_pf_to_dev(pf), "PTP init successful\n");
3545 	return;
3546 
3547 err_clean_pf:
3548 	mutex_destroy(&ptp->port.ps_lock);
3549 	ice_ptp_cleanup_pf(pf);
3550 err_exit:
3551 	/* If we registered a PTP clock, release it */
3552 	if (pf->ptp.clock) {
3553 		ptp_clock_unregister(ptp->clock);
3554 		pf->ptp.clock = NULL;
3555 	}
3556 	/* Keep ICE_PTP_UNINIT state to avoid ambiguity at driver unload
3557 	 * and to avoid duplicated resources release.
3558 	 */
3559 	ptp->state = ICE_PTP_UNINIT;
3560 	dev_err(ice_pf_to_dev(pf), "PTP failed %d\n", err);
3561 }
3562 
3563 /**
3564  * ice_ptp_release - Disable the driver/HW support and unregister the clock
3565  * @pf: Board private structure
3566  *
3567  * This function handles the cleanup work required from the initialization by
3568  * clearing out the important information and unregistering the clock
3569  */
3570 void ice_ptp_release(struct ice_pf *pf)
3571 {
3572 	if (pf->ptp.state == ICE_PTP_UNINIT)
3573 		return;
3574 
3575 	if (pf->ptp.state != ICE_PTP_READY) {
3576 		mutex_destroy(&pf->ptp.port.ps_lock);
3577 		ice_ptp_cleanup_pf(pf);
3578 		if (pf->ptp.clock) {
3579 			ptp_clock_unregister(pf->ptp.clock);
3580 			pf->ptp.clock = NULL;
3581 		}
3582 		return;
3583 	}
3584 
3585 	pf->ptp.state = ICE_PTP_UNINIT;
3586 
3587 	/* Disable timestamping for both Tx and Rx */
3588 	ice_ptp_disable_timestamp_mode(pf);
3589 
3590 	ice_ptp_cleanup_pf(pf);
3591 
3592 	ice_ptp_release_tx_tracker(pf, &pf->ptp.port.tx);
3593 
3594 	ice_ptp_disable_all_extts(pf);
3595 
3596 	kthread_cancel_delayed_work_sync(&pf->ptp.work);
3597 
3598 	ice_ptp_port_phy_stop(&pf->ptp.port);
3599 	mutex_destroy(&pf->ptp.port.ps_lock);
3600 	if (pf->ptp.kworker) {
3601 		kthread_destroy_worker(pf->ptp.kworker);
3602 		pf->ptp.kworker = NULL;
3603 	}
3604 
3605 	if (!pf->ptp.clock)
3606 		return;
3607 
3608 	/* Disable periodic outputs */
3609 	ice_ptp_disable_all_perout(pf);
3610 
3611 	ptp_clock_unregister(pf->ptp.clock);
3612 	pf->ptp.clock = NULL;
3613 
3614 	dev_info(ice_pf_to_dev(pf), "Removed PTP clock\n");
3615 }
3616