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