xref: /linux/drivers/net/ethernet/intel/ice/ice_ptp.c (revision 0fdebc5ec2ca492d69df2d93a6a7abade4941aae)
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 #define E810_OUT_PROP_DELAY_NS 1
9 
10 #define UNKNOWN_INCVAL_E822 0x100000000ULL
11 
12 static const struct ptp_pin_desc ice_pin_desc_e810t[] = {
13 	/* name    idx   func         chan */
14 	{ "GNSS",  GNSS, PTP_PF_EXTTS, 0, { 0, } },
15 	{ "SMA1",  SMA1, PTP_PF_NONE, 1, { 0, } },
16 	{ "U.FL1", UFL1, PTP_PF_NONE, 1, { 0, } },
17 	{ "SMA2",  SMA2, PTP_PF_NONE, 2, { 0, } },
18 	{ "U.FL2", UFL2, PTP_PF_NONE, 2, { 0, } },
19 };
20 
21 /**
22  * ice_get_sma_config_e810t
23  * @hw: pointer to the hw struct
24  * @ptp_pins: pointer to the ptp_pin_desc struture
25  *
26  * Read the configuration of the SMA control logic and put it into the
27  * ptp_pin_desc structure
28  */
29 static int
30 ice_get_sma_config_e810t(struct ice_hw *hw, struct ptp_pin_desc *ptp_pins)
31 {
32 	u8 data, i;
33 	int status;
34 
35 	/* Read initial pin state */
36 	status = ice_read_sma_ctrl_e810t(hw, &data);
37 	if (status)
38 		return status;
39 
40 	/* initialize with defaults */
41 	for (i = 0; i < NUM_PTP_PINS_E810T; i++) {
42 		snprintf(ptp_pins[i].name, sizeof(ptp_pins[i].name),
43 			 "%s", ice_pin_desc_e810t[i].name);
44 		ptp_pins[i].index = ice_pin_desc_e810t[i].index;
45 		ptp_pins[i].func = ice_pin_desc_e810t[i].func;
46 		ptp_pins[i].chan = ice_pin_desc_e810t[i].chan;
47 	}
48 
49 	/* Parse SMA1/UFL1 */
50 	switch (data & ICE_SMA1_MASK_E810T) {
51 	case ICE_SMA1_MASK_E810T:
52 	default:
53 		ptp_pins[SMA1].func = PTP_PF_NONE;
54 		ptp_pins[UFL1].func = PTP_PF_NONE;
55 		break;
56 	case ICE_SMA1_DIR_EN_E810T:
57 		ptp_pins[SMA1].func = PTP_PF_PEROUT;
58 		ptp_pins[UFL1].func = PTP_PF_NONE;
59 		break;
60 	case ICE_SMA1_TX_EN_E810T:
61 		ptp_pins[SMA1].func = PTP_PF_EXTTS;
62 		ptp_pins[UFL1].func = PTP_PF_NONE;
63 		break;
64 	case 0:
65 		ptp_pins[SMA1].func = PTP_PF_EXTTS;
66 		ptp_pins[UFL1].func = PTP_PF_PEROUT;
67 		break;
68 	}
69 
70 	/* Parse SMA2/UFL2 */
71 	switch (data & ICE_SMA2_MASK_E810T) {
72 	case ICE_SMA2_MASK_E810T:
73 	default:
74 		ptp_pins[SMA2].func = PTP_PF_NONE;
75 		ptp_pins[UFL2].func = PTP_PF_NONE;
76 		break;
77 	case (ICE_SMA2_TX_EN_E810T | ICE_SMA2_UFL2_RX_DIS_E810T):
78 		ptp_pins[SMA2].func = PTP_PF_EXTTS;
79 		ptp_pins[UFL2].func = PTP_PF_NONE;
80 		break;
81 	case (ICE_SMA2_DIR_EN_E810T | ICE_SMA2_UFL2_RX_DIS_E810T):
82 		ptp_pins[SMA2].func = PTP_PF_PEROUT;
83 		ptp_pins[UFL2].func = PTP_PF_NONE;
84 		break;
85 	case (ICE_SMA2_DIR_EN_E810T | ICE_SMA2_TX_EN_E810T):
86 		ptp_pins[SMA2].func = PTP_PF_NONE;
87 		ptp_pins[UFL2].func = PTP_PF_EXTTS;
88 		break;
89 	case ICE_SMA2_DIR_EN_E810T:
90 		ptp_pins[SMA2].func = PTP_PF_PEROUT;
91 		ptp_pins[UFL2].func = PTP_PF_EXTTS;
92 		break;
93 	}
94 
95 	return 0;
96 }
97 
98 /**
99  * ice_ptp_set_sma_config_e810t
100  * @hw: pointer to the hw struct
101  * @ptp_pins: pointer to the ptp_pin_desc struture
102  *
103  * Set the configuration of the SMA control logic based on the configuration in
104  * num_pins parameter
105  */
106 static int
107 ice_ptp_set_sma_config_e810t(struct ice_hw *hw,
108 			     const struct ptp_pin_desc *ptp_pins)
109 {
110 	int status;
111 	u8 data;
112 
113 	/* SMA1 and UFL1 cannot be set to TX at the same time */
114 	if (ptp_pins[SMA1].func == PTP_PF_PEROUT &&
115 	    ptp_pins[UFL1].func == PTP_PF_PEROUT)
116 		return -EINVAL;
117 
118 	/* SMA2 and UFL2 cannot be set to RX at the same time */
119 	if (ptp_pins[SMA2].func == PTP_PF_EXTTS &&
120 	    ptp_pins[UFL2].func == PTP_PF_EXTTS)
121 		return -EINVAL;
122 
123 	/* Read initial pin state value */
124 	status = ice_read_sma_ctrl_e810t(hw, &data);
125 	if (status)
126 		return status;
127 
128 	/* Set the right sate based on the desired configuration */
129 	data &= ~ICE_SMA1_MASK_E810T;
130 	if (ptp_pins[SMA1].func == PTP_PF_NONE &&
131 	    ptp_pins[UFL1].func == PTP_PF_NONE) {
132 		dev_info(ice_hw_to_dev(hw), "SMA1 + U.FL1 disabled");
133 		data |= ICE_SMA1_MASK_E810T;
134 	} else if (ptp_pins[SMA1].func == PTP_PF_EXTTS &&
135 		   ptp_pins[UFL1].func == PTP_PF_NONE) {
136 		dev_info(ice_hw_to_dev(hw), "SMA1 RX");
137 		data |= ICE_SMA1_TX_EN_E810T;
138 	} else if (ptp_pins[SMA1].func == PTP_PF_NONE &&
139 		   ptp_pins[UFL1].func == PTP_PF_PEROUT) {
140 		/* U.FL 1 TX will always enable SMA 1 RX */
141 		dev_info(ice_hw_to_dev(hw), "SMA1 RX + U.FL1 TX");
142 	} else if (ptp_pins[SMA1].func == PTP_PF_EXTTS &&
143 		   ptp_pins[UFL1].func == PTP_PF_PEROUT) {
144 		dev_info(ice_hw_to_dev(hw), "SMA1 RX + U.FL1 TX");
145 	} else if (ptp_pins[SMA1].func == PTP_PF_PEROUT &&
146 		   ptp_pins[UFL1].func == PTP_PF_NONE) {
147 		dev_info(ice_hw_to_dev(hw), "SMA1 TX");
148 		data |= ICE_SMA1_DIR_EN_E810T;
149 	}
150 
151 	data &= ~ICE_SMA2_MASK_E810T;
152 	if (ptp_pins[SMA2].func == PTP_PF_NONE &&
153 	    ptp_pins[UFL2].func == PTP_PF_NONE) {
154 		dev_info(ice_hw_to_dev(hw), "SMA2 + U.FL2 disabled");
155 		data |= ICE_SMA2_MASK_E810T;
156 	} else if (ptp_pins[SMA2].func == PTP_PF_EXTTS &&
157 			ptp_pins[UFL2].func == PTP_PF_NONE) {
158 		dev_info(ice_hw_to_dev(hw), "SMA2 RX");
159 		data |= (ICE_SMA2_TX_EN_E810T |
160 			 ICE_SMA2_UFL2_RX_DIS_E810T);
161 	} else if (ptp_pins[SMA2].func == PTP_PF_NONE &&
162 		   ptp_pins[UFL2].func == PTP_PF_EXTTS) {
163 		dev_info(ice_hw_to_dev(hw), "UFL2 RX");
164 		data |= (ICE_SMA2_DIR_EN_E810T | ICE_SMA2_TX_EN_E810T);
165 	} else if (ptp_pins[SMA2].func == PTP_PF_PEROUT &&
166 		   ptp_pins[UFL2].func == PTP_PF_NONE) {
167 		dev_info(ice_hw_to_dev(hw), "SMA2 TX");
168 		data |= (ICE_SMA2_DIR_EN_E810T |
169 			 ICE_SMA2_UFL2_RX_DIS_E810T);
170 	} else if (ptp_pins[SMA2].func == PTP_PF_PEROUT &&
171 		   ptp_pins[UFL2].func == PTP_PF_EXTTS) {
172 		dev_info(ice_hw_to_dev(hw), "SMA2 TX + U.FL2 RX");
173 		data |= ICE_SMA2_DIR_EN_E810T;
174 	}
175 
176 	return ice_write_sma_ctrl_e810t(hw, data);
177 }
178 
179 /**
180  * ice_ptp_set_sma_e810t
181  * @info: the driver's PTP info structure
182  * @pin: pin index in kernel structure
183  * @func: Pin function to be set (PTP_PF_NONE, PTP_PF_EXTTS or PTP_PF_PEROUT)
184  *
185  * Set the configuration of a single SMA pin
186  */
187 static int
188 ice_ptp_set_sma_e810t(struct ptp_clock_info *info, unsigned int pin,
189 		      enum ptp_pin_function func)
190 {
191 	struct ptp_pin_desc ptp_pins[NUM_PTP_PINS_E810T];
192 	struct ice_pf *pf = ptp_info_to_pf(info);
193 	struct ice_hw *hw = &pf->hw;
194 	int err;
195 
196 	if (pin < SMA1 || func > PTP_PF_PEROUT)
197 		return -EOPNOTSUPP;
198 
199 	err = ice_get_sma_config_e810t(hw, ptp_pins);
200 	if (err)
201 		return err;
202 
203 	/* Disable the same function on the other pin sharing the channel */
204 	if (pin == SMA1 && ptp_pins[UFL1].func == func)
205 		ptp_pins[UFL1].func = PTP_PF_NONE;
206 	if (pin == UFL1 && ptp_pins[SMA1].func == func)
207 		ptp_pins[SMA1].func = PTP_PF_NONE;
208 
209 	if (pin == SMA2 && ptp_pins[UFL2].func == func)
210 		ptp_pins[UFL2].func = PTP_PF_NONE;
211 	if (pin == UFL2 && ptp_pins[SMA2].func == func)
212 		ptp_pins[SMA2].func = PTP_PF_NONE;
213 
214 	/* Set up new pin function in the temp table */
215 	ptp_pins[pin].func = func;
216 
217 	return ice_ptp_set_sma_config_e810t(hw, ptp_pins);
218 }
219 
220 /**
221  * ice_verify_pin_e810t
222  * @info: the driver's PTP info structure
223  * @pin: Pin index
224  * @func: Assigned function
225  * @chan: Assigned channel
226  *
227  * Verify if pin supports requested pin function. If the Check pins consistency.
228  * Reconfigure the SMA logic attached to the given pin to enable its
229  * desired functionality
230  */
231 static int
232 ice_verify_pin_e810t(struct ptp_clock_info *info, unsigned int pin,
233 		     enum ptp_pin_function func, unsigned int chan)
234 {
235 	/* Don't allow channel reassignment */
236 	if (chan != ice_pin_desc_e810t[pin].chan)
237 		return -EOPNOTSUPP;
238 
239 	/* Check if functions are properly assigned */
240 	switch (func) {
241 	case PTP_PF_NONE:
242 		break;
243 	case PTP_PF_EXTTS:
244 		if (pin == UFL1)
245 			return -EOPNOTSUPP;
246 		break;
247 	case PTP_PF_PEROUT:
248 		if (pin == UFL2 || pin == GNSS)
249 			return -EOPNOTSUPP;
250 		break;
251 	case PTP_PF_PHYSYNC:
252 		return -EOPNOTSUPP;
253 	}
254 
255 	return ice_ptp_set_sma_e810t(info, pin, func);
256 }
257 
258 /**
259  * ice_set_tx_tstamp - Enable or disable Tx timestamping
260  * @pf: The PF pointer to search in
261  * @on: bool value for whether timestamps are enabled or disabled
262  */
263 static void ice_set_tx_tstamp(struct ice_pf *pf, bool on)
264 {
265 	struct ice_vsi *vsi;
266 	u32 val;
267 	u16 i;
268 
269 	vsi = ice_get_main_vsi(pf);
270 	if (!vsi)
271 		return;
272 
273 	/* Set the timestamp enable flag for all the Tx rings */
274 	ice_for_each_txq(vsi, i) {
275 		if (!vsi->tx_rings[i])
276 			continue;
277 		vsi->tx_rings[i]->ptp_tx = on;
278 	}
279 
280 	/* Configure the Tx timestamp interrupt */
281 	val = rd32(&pf->hw, PFINT_OICR_ENA);
282 	if (on)
283 		val |= PFINT_OICR_TSYN_TX_M;
284 	else
285 		val &= ~PFINT_OICR_TSYN_TX_M;
286 	wr32(&pf->hw, PFINT_OICR_ENA, val);
287 
288 	pf->ptp.tstamp_config.tx_type = on ? HWTSTAMP_TX_ON : HWTSTAMP_TX_OFF;
289 }
290 
291 /**
292  * ice_set_rx_tstamp - Enable or disable Rx timestamping
293  * @pf: The PF pointer to search in
294  * @on: bool value for whether timestamps are enabled or disabled
295  */
296 static void ice_set_rx_tstamp(struct ice_pf *pf, bool on)
297 {
298 	struct ice_vsi *vsi;
299 	u16 i;
300 
301 	vsi = ice_get_main_vsi(pf);
302 	if (!vsi)
303 		return;
304 
305 	/* Set the timestamp flag for all the Rx rings */
306 	ice_for_each_rxq(vsi, i) {
307 		if (!vsi->rx_rings[i])
308 			continue;
309 		vsi->rx_rings[i]->ptp_rx = on;
310 	}
311 
312 	pf->ptp.tstamp_config.rx_filter = on ? HWTSTAMP_FILTER_ALL :
313 					       HWTSTAMP_FILTER_NONE;
314 }
315 
316 /**
317  * ice_ptp_cfg_timestamp - Configure timestamp for init/deinit
318  * @pf: Board private structure
319  * @ena: bool value to enable or disable time stamp
320  *
321  * This function will configure timestamping during PTP initialization
322  * and deinitialization
323  */
324 void ice_ptp_cfg_timestamp(struct ice_pf *pf, bool ena)
325 {
326 	ice_set_tx_tstamp(pf, ena);
327 	ice_set_rx_tstamp(pf, ena);
328 }
329 
330 /**
331  * ice_get_ptp_clock_index - Get the PTP clock index
332  * @pf: the PF pointer
333  *
334  * Determine the clock index of the PTP clock associated with this device. If
335  * this is the PF controlling the clock, just use the local access to the
336  * clock device pointer.
337  *
338  * Otherwise, read from the driver shared parameters to determine the clock
339  * index value.
340  *
341  * Returns: the index of the PTP clock associated with this device, or -1 if
342  * there is no associated clock.
343  */
344 int ice_get_ptp_clock_index(struct ice_pf *pf)
345 {
346 	struct device *dev = ice_pf_to_dev(pf);
347 	enum ice_aqc_driver_params param_idx;
348 	struct ice_hw *hw = &pf->hw;
349 	u8 tmr_idx;
350 	u32 value;
351 	int err;
352 
353 	/* Use the ptp_clock structure if we're the main PF */
354 	if (pf->ptp.clock)
355 		return ptp_clock_index(pf->ptp.clock);
356 
357 	tmr_idx = hw->func_caps.ts_func_info.tmr_index_assoc;
358 	if (!tmr_idx)
359 		param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR0;
360 	else
361 		param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR1;
362 
363 	err = ice_aq_get_driver_param(hw, param_idx, &value, NULL);
364 	if (err) {
365 		dev_err(dev, "Failed to read PTP clock index parameter, err %d aq_err %s\n",
366 			err, ice_aq_str(hw->adminq.sq_last_status));
367 		return -1;
368 	}
369 
370 	/* The PTP clock index is an integer, and will be between 0 and
371 	 * INT_MAX. The highest bit of the driver shared parameter is used to
372 	 * indicate whether or not the currently stored clock index is valid.
373 	 */
374 	if (!(value & PTP_SHARED_CLK_IDX_VALID))
375 		return -1;
376 
377 	return value & ~PTP_SHARED_CLK_IDX_VALID;
378 }
379 
380 /**
381  * ice_set_ptp_clock_index - Set the PTP clock index
382  * @pf: the PF pointer
383  *
384  * Set the PTP clock index for this device into the shared driver parameters,
385  * so that other PFs associated with this device can read it.
386  *
387  * If the PF is unable to store the clock index, it will log an error, but
388  * will continue operating PTP.
389  */
390 static void ice_set_ptp_clock_index(struct ice_pf *pf)
391 {
392 	struct device *dev = ice_pf_to_dev(pf);
393 	enum ice_aqc_driver_params param_idx;
394 	struct ice_hw *hw = &pf->hw;
395 	u8 tmr_idx;
396 	u32 value;
397 	int err;
398 
399 	if (!pf->ptp.clock)
400 		return;
401 
402 	tmr_idx = hw->func_caps.ts_func_info.tmr_index_assoc;
403 	if (!tmr_idx)
404 		param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR0;
405 	else
406 		param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR1;
407 
408 	value = (u32)ptp_clock_index(pf->ptp.clock);
409 	if (value > INT_MAX) {
410 		dev_err(dev, "PTP Clock index is too large to store\n");
411 		return;
412 	}
413 	value |= PTP_SHARED_CLK_IDX_VALID;
414 
415 	err = ice_aq_set_driver_param(hw, param_idx, value, NULL);
416 	if (err) {
417 		dev_err(dev, "Failed to set PTP clock index parameter, err %d aq_err %s\n",
418 			err, ice_aq_str(hw->adminq.sq_last_status));
419 	}
420 }
421 
422 /**
423  * ice_clear_ptp_clock_index - Clear the PTP clock index
424  * @pf: the PF pointer
425  *
426  * Clear the PTP clock index for this device. Must be called when
427  * unregistering the PTP clock, in order to ensure other PFs stop reporting
428  * a clock object that no longer exists.
429  */
430 static void ice_clear_ptp_clock_index(struct ice_pf *pf)
431 {
432 	struct device *dev = ice_pf_to_dev(pf);
433 	enum ice_aqc_driver_params param_idx;
434 	struct ice_hw *hw = &pf->hw;
435 	u8 tmr_idx;
436 	int err;
437 
438 	/* Do not clear the index if we don't own the timer */
439 	if (!hw->func_caps.ts_func_info.src_tmr_owned)
440 		return;
441 
442 	tmr_idx = hw->func_caps.ts_func_info.tmr_index_assoc;
443 	if (!tmr_idx)
444 		param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR0;
445 	else
446 		param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR1;
447 
448 	err = ice_aq_set_driver_param(hw, param_idx, 0, NULL);
449 	if (err) {
450 		dev_dbg(dev, "Failed to clear PTP clock index parameter, err %d aq_err %s\n",
451 			err, ice_aq_str(hw->adminq.sq_last_status));
452 	}
453 }
454 
455 /**
456  * ice_ptp_read_src_clk_reg - Read the source clock register
457  * @pf: Board private structure
458  * @sts: Optional parameter for holding a pair of system timestamps from
459  *       the system clock. Will be ignored if NULL is given.
460  */
461 static u64
462 ice_ptp_read_src_clk_reg(struct ice_pf *pf, struct ptp_system_timestamp *sts)
463 {
464 	struct ice_hw *hw = &pf->hw;
465 	u32 hi, lo, lo2;
466 	u8 tmr_idx;
467 
468 	tmr_idx = ice_get_ptp_src_clock_index(hw);
469 	/* Read the system timestamp pre PHC read */
470 	ptp_read_system_prets(sts);
471 
472 	lo = rd32(hw, GLTSYN_TIME_L(tmr_idx));
473 
474 	/* Read the system timestamp post PHC read */
475 	ptp_read_system_postts(sts);
476 
477 	hi = rd32(hw, GLTSYN_TIME_H(tmr_idx));
478 	lo2 = rd32(hw, GLTSYN_TIME_L(tmr_idx));
479 
480 	if (lo2 < lo) {
481 		/* if TIME_L rolled over read TIME_L again and update
482 		 * system timestamps
483 		 */
484 		ptp_read_system_prets(sts);
485 		lo = rd32(hw, GLTSYN_TIME_L(tmr_idx));
486 		ptp_read_system_postts(sts);
487 		hi = rd32(hw, GLTSYN_TIME_H(tmr_idx));
488 	}
489 
490 	return ((u64)hi << 32) | lo;
491 }
492 
493 /**
494  * ice_ptp_update_cached_phctime - Update the cached PHC time values
495  * @pf: Board specific private structure
496  *
497  * This function updates the system time values which are cached in the PF
498  * structure and the Rx rings.
499  *
500  * This function must be called periodically to ensure that the cached value
501  * is never more than 2 seconds old. It must also be called whenever the PHC
502  * time has been changed.
503  *
504  * Return:
505  * * 0 - OK, successfully updated
506  * * -EAGAIN - PF was busy, need to reschedule the update
507  */
508 static int ice_ptp_update_cached_phctime(struct ice_pf *pf)
509 {
510 	u64 systime;
511 	int i;
512 
513 	if (test_and_set_bit(ICE_CFG_BUSY, pf->state))
514 		return -EAGAIN;
515 
516 	/* Read the current PHC time */
517 	systime = ice_ptp_read_src_clk_reg(pf, NULL);
518 
519 	/* Update the cached PHC time stored in the PF structure */
520 	WRITE_ONCE(pf->ptp.cached_phc_time, systime);
521 
522 	ice_for_each_vsi(pf, i) {
523 		struct ice_vsi *vsi = pf->vsi[i];
524 		int j;
525 
526 		if (!vsi)
527 			continue;
528 
529 		if (vsi->type != ICE_VSI_PF)
530 			continue;
531 
532 		ice_for_each_rxq(vsi, j) {
533 			if (!vsi->rx_rings[j])
534 				continue;
535 			WRITE_ONCE(vsi->rx_rings[j]->cached_phctime, systime);
536 		}
537 	}
538 	clear_bit(ICE_CFG_BUSY, pf->state);
539 
540 	return 0;
541 }
542 
543 /**
544  * ice_ptp_extend_32b_ts - Convert a 32b nanoseconds timestamp to 64b
545  * @cached_phc_time: recently cached copy of PHC time
546  * @in_tstamp: Ingress/egress 32b nanoseconds timestamp value
547  *
548  * Hardware captures timestamps which contain only 32 bits of nominal
549  * nanoseconds, as opposed to the 64bit timestamps that the stack expects.
550  * Note that the captured timestamp values may be 40 bits, but the lower
551  * 8 bits are sub-nanoseconds and generally discarded.
552  *
553  * Extend the 32bit nanosecond timestamp using the following algorithm and
554  * assumptions:
555  *
556  * 1) have a recently cached copy of the PHC time
557  * 2) assume that the in_tstamp was captured 2^31 nanoseconds (~2.1
558  *    seconds) before or after the PHC time was captured.
559  * 3) calculate the delta between the cached time and the timestamp
560  * 4) if the delta is smaller than 2^31 nanoseconds, then the timestamp was
561  *    captured after the PHC time. In this case, the full timestamp is just
562  *    the cached PHC time plus the delta.
563  * 5) otherwise, if the delta is larger than 2^31 nanoseconds, then the
564  *    timestamp was captured *before* the PHC time, i.e. because the PHC
565  *    cache was updated after the timestamp was captured by hardware. In this
566  *    case, the full timestamp is the cached time minus the inverse delta.
567  *
568  * This algorithm works even if the PHC time was updated after a Tx timestamp
569  * was requested, but before the Tx timestamp event was reported from
570  * hardware.
571  *
572  * This calculation primarily relies on keeping the cached PHC time up to
573  * date. If the timestamp was captured more than 2^31 nanoseconds after the
574  * PHC time, it is possible that the lower 32bits of PHC time have
575  * overflowed more than once, and we might generate an incorrect timestamp.
576  *
577  * This is prevented by (a) periodically updating the cached PHC time once
578  * a second, and (b) discarding any Tx timestamp packet if it has waited for
579  * a timestamp for more than one second.
580  */
581 static u64 ice_ptp_extend_32b_ts(u64 cached_phc_time, u32 in_tstamp)
582 {
583 	u32 delta, phc_time_lo;
584 	u64 ns;
585 
586 	/* Extract the lower 32 bits of the PHC time */
587 	phc_time_lo = (u32)cached_phc_time;
588 
589 	/* Calculate the delta between the lower 32bits of the cached PHC
590 	 * time and the in_tstamp value
591 	 */
592 	delta = (in_tstamp - phc_time_lo);
593 
594 	/* Do not assume that the in_tstamp is always more recent than the
595 	 * cached PHC time. If the delta is large, it indicates that the
596 	 * in_tstamp was taken in the past, and should be converted
597 	 * forward.
598 	 */
599 	if (delta > (U32_MAX / 2)) {
600 		/* reverse the delta calculation here */
601 		delta = (phc_time_lo - in_tstamp);
602 		ns = cached_phc_time - delta;
603 	} else {
604 		ns = cached_phc_time + delta;
605 	}
606 
607 	return ns;
608 }
609 
610 /**
611  * ice_ptp_extend_40b_ts - Convert a 40b timestamp to 64b nanoseconds
612  * @pf: Board private structure
613  * @in_tstamp: Ingress/egress 40b timestamp value
614  *
615  * The Tx and Rx timestamps are 40 bits wide, including 32 bits of nominal
616  * nanoseconds, 7 bits of sub-nanoseconds, and a valid bit.
617  *
618  *  *--------------------------------------------------------------*
619  *  | 32 bits of nanoseconds | 7 high bits of sub ns underflow | v |
620  *  *--------------------------------------------------------------*
621  *
622  * The low bit is an indicator of whether the timestamp is valid. The next
623  * 7 bits are a capture of the upper 7 bits of the sub-nanosecond underflow,
624  * and the remaining 32 bits are the lower 32 bits of the PHC timer.
625  *
626  * It is assumed that the caller verifies the timestamp is valid prior to
627  * calling this function.
628  *
629  * Extract the 32bit nominal nanoseconds and extend them. Use the cached PHC
630  * time stored in the device private PTP structure as the basis for timestamp
631  * extension.
632  *
633  * See ice_ptp_extend_32b_ts for a detailed explanation of the extension
634  * algorithm.
635  */
636 static u64 ice_ptp_extend_40b_ts(struct ice_pf *pf, u64 in_tstamp)
637 {
638 	const u64 mask = GENMASK_ULL(31, 0);
639 
640 	return ice_ptp_extend_32b_ts(pf->ptp.cached_phc_time,
641 				     (in_tstamp >> 8) & mask);
642 }
643 
644 /**
645  * ice_ptp_read_time - Read the time from the device
646  * @pf: Board private structure
647  * @ts: timespec structure to hold the current time value
648  * @sts: Optional parameter for holding a pair of system timestamps from
649  *       the system clock. Will be ignored if NULL is given.
650  *
651  * This function reads the source clock registers and stores them in a timespec.
652  * However, since the registers are 64 bits of nanoseconds, we must convert the
653  * result to a timespec before we can return.
654  */
655 static void
656 ice_ptp_read_time(struct ice_pf *pf, struct timespec64 *ts,
657 		  struct ptp_system_timestamp *sts)
658 {
659 	u64 time_ns = ice_ptp_read_src_clk_reg(pf, sts);
660 
661 	*ts = ns_to_timespec64(time_ns);
662 }
663 
664 /**
665  * ice_ptp_write_init - Set PHC time to provided value
666  * @pf: Board private structure
667  * @ts: timespec structure that holds the new time value
668  *
669  * Set the PHC time to the specified time provided in the timespec.
670  */
671 static int ice_ptp_write_init(struct ice_pf *pf, struct timespec64 *ts)
672 {
673 	u64 ns = timespec64_to_ns(ts);
674 	struct ice_hw *hw = &pf->hw;
675 
676 	return ice_ptp_init_time(hw, ns);
677 }
678 
679 /**
680  * ice_ptp_write_adj - Adjust PHC clock time atomically
681  * @pf: Board private structure
682  * @adj: Adjustment in nanoseconds
683  *
684  * Perform an atomic adjustment of the PHC time by the specified number of
685  * nanoseconds.
686  */
687 static int ice_ptp_write_adj(struct ice_pf *pf, s32 adj)
688 {
689 	struct ice_hw *hw = &pf->hw;
690 
691 	return ice_ptp_adj_clock(hw, adj);
692 }
693 
694 /**
695  * ice_base_incval - Get base timer increment value
696  * @pf: Board private structure
697  *
698  * Look up the base timer increment value for this device. The base increment
699  * value is used to define the nominal clock tick rate. This increment value
700  * is programmed during device initialization. It is also used as the basis
701  * for calculating adjustments using scaled_ppm.
702  */
703 static u64 ice_base_incval(struct ice_pf *pf)
704 {
705 	struct ice_hw *hw = &pf->hw;
706 	u64 incval;
707 
708 	if (ice_is_e810(hw))
709 		incval = ICE_PTP_NOMINAL_INCVAL_E810;
710 	else if (ice_e822_time_ref(hw) < NUM_ICE_TIME_REF_FREQ)
711 		incval = ice_e822_nominal_incval(ice_e822_time_ref(hw));
712 	else
713 		incval = UNKNOWN_INCVAL_E822;
714 
715 	dev_dbg(ice_pf_to_dev(pf), "PTP: using base increment value of 0x%016llx\n",
716 		incval);
717 
718 	return incval;
719 }
720 
721 /**
722  * ice_ptp_reset_ts_memory_quad - Reset timestamp memory for one quad
723  * @pf: The PF private data structure
724  * @quad: The quad (0-4)
725  */
726 static void ice_ptp_reset_ts_memory_quad(struct ice_pf *pf, int quad)
727 {
728 	struct ice_hw *hw = &pf->hw;
729 
730 	ice_write_quad_reg_e822(hw, quad, Q_REG_TS_CTRL, Q_REG_TS_CTRL_M);
731 	ice_write_quad_reg_e822(hw, quad, Q_REG_TS_CTRL, ~(u32)Q_REG_TS_CTRL_M);
732 }
733 
734 /**
735  * ice_ptp_check_tx_fifo - Check whether Tx FIFO is in an OK state
736  * @port: PTP port for which Tx FIFO is checked
737  */
738 static int ice_ptp_check_tx_fifo(struct ice_ptp_port *port)
739 {
740 	int quad = port->port_num / ICE_PORTS_PER_QUAD;
741 	int offs = port->port_num % ICE_PORTS_PER_QUAD;
742 	struct ice_pf *pf;
743 	struct ice_hw *hw;
744 	u32 val, phy_sts;
745 	int err;
746 
747 	pf = ptp_port_to_pf(port);
748 	hw = &pf->hw;
749 
750 	if (port->tx_fifo_busy_cnt == FIFO_OK)
751 		return 0;
752 
753 	/* need to read FIFO state */
754 	if (offs == 0 || offs == 1)
755 		err = ice_read_quad_reg_e822(hw, quad, Q_REG_FIFO01_STATUS,
756 					     &val);
757 	else
758 		err = ice_read_quad_reg_e822(hw, quad, Q_REG_FIFO23_STATUS,
759 					     &val);
760 
761 	if (err) {
762 		dev_err(ice_pf_to_dev(pf), "PTP failed to check port %d Tx FIFO, err %d\n",
763 			port->port_num, err);
764 		return err;
765 	}
766 
767 	if (offs & 0x1)
768 		phy_sts = (val & Q_REG_FIFO13_M) >> Q_REG_FIFO13_S;
769 	else
770 		phy_sts = (val & Q_REG_FIFO02_M) >> Q_REG_FIFO02_S;
771 
772 	if (phy_sts & FIFO_EMPTY) {
773 		port->tx_fifo_busy_cnt = FIFO_OK;
774 		return 0;
775 	}
776 
777 	port->tx_fifo_busy_cnt++;
778 
779 	dev_dbg(ice_pf_to_dev(pf), "Try %d, port %d FIFO not empty\n",
780 		port->tx_fifo_busy_cnt, port->port_num);
781 
782 	if (port->tx_fifo_busy_cnt == ICE_PTP_FIFO_NUM_CHECKS) {
783 		dev_dbg(ice_pf_to_dev(pf),
784 			"Port %d Tx FIFO still not empty; resetting quad %d\n",
785 			port->port_num, quad);
786 		ice_ptp_reset_ts_memory_quad(pf, quad);
787 		port->tx_fifo_busy_cnt = FIFO_OK;
788 		return 0;
789 	}
790 
791 	return -EAGAIN;
792 }
793 
794 /**
795  * ice_ptp_check_tx_offset_valid - Check if the Tx PHY offset is valid
796  * @port: the PTP port to check
797  *
798  * Checks whether the Tx offset for the PHY associated with this port is
799  * valid. Returns 0 if the offset is valid, and a non-zero error code if it is
800  * not.
801  */
802 static int ice_ptp_check_tx_offset_valid(struct ice_ptp_port *port)
803 {
804 	struct ice_pf *pf = ptp_port_to_pf(port);
805 	struct device *dev = ice_pf_to_dev(pf);
806 	struct ice_hw *hw = &pf->hw;
807 	u32 val;
808 	int err;
809 
810 	err = ice_ptp_check_tx_fifo(port);
811 	if (err)
812 		return err;
813 
814 	err = ice_read_phy_reg_e822(hw, port->port_num, P_REG_TX_OV_STATUS,
815 				    &val);
816 	if (err) {
817 		dev_err(dev, "Failed to read TX_OV_STATUS for port %d, err %d\n",
818 			port->port_num, err);
819 		return -EAGAIN;
820 	}
821 
822 	if (!(val & P_REG_TX_OV_STATUS_OV_M))
823 		return -EAGAIN;
824 
825 	return 0;
826 }
827 
828 /**
829  * ice_ptp_check_rx_offset_valid - Check if the Rx PHY offset is valid
830  * @port: the PTP port to check
831  *
832  * Checks whether the Rx offset for the PHY associated with this port is
833  * valid. Returns 0 if the offset is valid, and a non-zero error code if it is
834  * not.
835  */
836 static int ice_ptp_check_rx_offset_valid(struct ice_ptp_port *port)
837 {
838 	struct ice_pf *pf = ptp_port_to_pf(port);
839 	struct device *dev = ice_pf_to_dev(pf);
840 	struct ice_hw *hw = &pf->hw;
841 	int err;
842 	u32 val;
843 
844 	err = ice_read_phy_reg_e822(hw, port->port_num, P_REG_RX_OV_STATUS,
845 				    &val);
846 	if (err) {
847 		dev_err(dev, "Failed to read RX_OV_STATUS for port %d, err %d\n",
848 			port->port_num, err);
849 		return err;
850 	}
851 
852 	if (!(val & P_REG_RX_OV_STATUS_OV_M))
853 		return -EAGAIN;
854 
855 	return 0;
856 }
857 
858 /**
859  * ice_ptp_check_offset_valid - Check port offset valid bit
860  * @port: Port for which offset valid bit is checked
861  *
862  * Returns 0 if both Tx and Rx offset are valid, and -EAGAIN if one of the
863  * offset is not ready.
864  */
865 static int ice_ptp_check_offset_valid(struct ice_ptp_port *port)
866 {
867 	int tx_err, rx_err;
868 
869 	/* always check both Tx and Rx offset validity */
870 	tx_err = ice_ptp_check_tx_offset_valid(port);
871 	rx_err = ice_ptp_check_rx_offset_valid(port);
872 
873 	if (tx_err || rx_err)
874 		return -EAGAIN;
875 
876 	return 0;
877 }
878 
879 /**
880  * ice_ptp_wait_for_offset_valid - Check for valid Tx and Rx offsets
881  * @work: Pointer to the kthread_work structure for this task
882  *
883  * Check whether both the Tx and Rx offsets are valid for enabling the vernier
884  * calibration.
885  *
886  * Once we have valid offsets from hardware, update the total Tx and Rx
887  * offsets, and exit bypass mode. This enables more precise timestamps using
888  * the extra data measured during the vernier calibration process.
889  */
890 static void ice_ptp_wait_for_offset_valid(struct kthread_work *work)
891 {
892 	struct ice_ptp_port *port;
893 	int err;
894 	struct device *dev;
895 	struct ice_pf *pf;
896 	struct ice_hw *hw;
897 
898 	port = container_of(work, struct ice_ptp_port, ov_work.work);
899 	pf = ptp_port_to_pf(port);
900 	hw = &pf->hw;
901 	dev = ice_pf_to_dev(pf);
902 
903 	if (ice_ptp_check_offset_valid(port)) {
904 		/* Offsets not ready yet, try again later */
905 		kthread_queue_delayed_work(pf->ptp.kworker,
906 					   &port->ov_work,
907 					   msecs_to_jiffies(100));
908 		return;
909 	}
910 
911 	/* Offsets are valid, so it is safe to exit bypass mode */
912 	err = ice_phy_exit_bypass_e822(hw, port->port_num);
913 	if (err) {
914 		dev_warn(dev, "Failed to exit bypass mode for PHY port %u, err %d\n",
915 			 port->port_num, err);
916 		return;
917 	}
918 }
919 
920 /**
921  * ice_ptp_port_phy_stop - Stop timestamping for a PHY port
922  * @ptp_port: PTP port to stop
923  */
924 static int
925 ice_ptp_port_phy_stop(struct ice_ptp_port *ptp_port)
926 {
927 	struct ice_pf *pf = ptp_port_to_pf(ptp_port);
928 	u8 port = ptp_port->port_num;
929 	struct ice_hw *hw = &pf->hw;
930 	int err;
931 
932 	if (ice_is_e810(hw))
933 		return 0;
934 
935 	mutex_lock(&ptp_port->ps_lock);
936 
937 	kthread_cancel_delayed_work_sync(&ptp_port->ov_work);
938 
939 	err = ice_stop_phy_timer_e822(hw, port, true);
940 	if (err)
941 		dev_err(ice_pf_to_dev(pf), "PTP failed to set PHY port %d down, err %d\n",
942 			port, err);
943 
944 	mutex_unlock(&ptp_port->ps_lock);
945 
946 	return err;
947 }
948 
949 /**
950  * ice_ptp_port_phy_restart - (Re)start and calibrate PHY timestamping
951  * @ptp_port: PTP port for which the PHY start is set
952  *
953  * Start the PHY timestamping block, and initiate Vernier timestamping
954  * calibration. If timestamping cannot be calibrated (such as if link is down)
955  * then disable the timestamping block instead.
956  */
957 static int
958 ice_ptp_port_phy_restart(struct ice_ptp_port *ptp_port)
959 {
960 	struct ice_pf *pf = ptp_port_to_pf(ptp_port);
961 	u8 port = ptp_port->port_num;
962 	struct ice_hw *hw = &pf->hw;
963 	int err;
964 
965 	if (ice_is_e810(hw))
966 		return 0;
967 
968 	if (!ptp_port->link_up)
969 		return ice_ptp_port_phy_stop(ptp_port);
970 
971 	mutex_lock(&ptp_port->ps_lock);
972 
973 	kthread_cancel_delayed_work_sync(&ptp_port->ov_work);
974 
975 	/* temporarily disable Tx timestamps while calibrating PHY offset */
976 	ptp_port->tx.calibrating = true;
977 	ptp_port->tx_fifo_busy_cnt = 0;
978 
979 	/* Start the PHY timer in bypass mode */
980 	err = ice_start_phy_timer_e822(hw, port, true);
981 	if (err)
982 		goto out_unlock;
983 
984 	/* Enable Tx timestamps right away */
985 	ptp_port->tx.calibrating = false;
986 
987 	kthread_queue_delayed_work(pf->ptp.kworker, &ptp_port->ov_work, 0);
988 
989 out_unlock:
990 	if (err)
991 		dev_err(ice_pf_to_dev(pf), "PTP failed to set PHY port %d up, err %d\n",
992 			port, err);
993 
994 	mutex_unlock(&ptp_port->ps_lock);
995 
996 	return err;
997 }
998 
999 /**
1000  * ice_ptp_link_change - Set or clear port registers for timestamping
1001  * @pf: Board private structure
1002  * @port: Port for which the PHY start is set
1003  * @linkup: Link is up or down
1004  */
1005 int ice_ptp_link_change(struct ice_pf *pf, u8 port, bool linkup)
1006 {
1007 	struct ice_ptp_port *ptp_port;
1008 
1009 	if (!test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags))
1010 		return 0;
1011 
1012 	if (port >= ICE_NUM_EXTERNAL_PORTS)
1013 		return -EINVAL;
1014 
1015 	ptp_port = &pf->ptp.port;
1016 	if (ptp_port->port_num != port)
1017 		return -EINVAL;
1018 
1019 	/* Update cached link err for this port immediately */
1020 	ptp_port->link_up = linkup;
1021 
1022 	if (!test_bit(ICE_FLAG_PTP, pf->flags))
1023 		/* PTP is not setup */
1024 		return -EAGAIN;
1025 
1026 	return ice_ptp_port_phy_restart(ptp_port);
1027 }
1028 
1029 /**
1030  * ice_ptp_reset_ts_memory - Reset timestamp memory for all quads
1031  * @pf: The PF private data structure
1032  */
1033 static void ice_ptp_reset_ts_memory(struct ice_pf *pf)
1034 {
1035 	int quad;
1036 
1037 	quad = pf->hw.port_info->lport / ICE_PORTS_PER_QUAD;
1038 	ice_ptp_reset_ts_memory_quad(pf, quad);
1039 }
1040 
1041 /**
1042  * ice_ptp_tx_ena_intr - Enable or disable the Tx timestamp interrupt
1043  * @pf: PF private structure
1044  * @ena: bool value to enable or disable interrupt
1045  * @threshold: Minimum number of packets at which intr is triggered
1046  *
1047  * Utility function to enable or disable Tx timestamp interrupt and threshold
1048  */
1049 static int ice_ptp_tx_ena_intr(struct ice_pf *pf, bool ena, u32 threshold)
1050 {
1051 	struct ice_hw *hw = &pf->hw;
1052 	int err = 0;
1053 	int quad;
1054 	u32 val;
1055 
1056 	ice_ptp_reset_ts_memory(pf);
1057 
1058 	for (quad = 0; quad < ICE_MAX_QUAD; quad++) {
1059 		err = ice_read_quad_reg_e822(hw, quad, Q_REG_TX_MEM_GBL_CFG,
1060 					     &val);
1061 		if (err)
1062 			break;
1063 
1064 		if (ena) {
1065 			val |= Q_REG_TX_MEM_GBL_CFG_INTR_ENA_M;
1066 			val &= ~Q_REG_TX_MEM_GBL_CFG_INTR_THR_M;
1067 			val |= ((threshold << Q_REG_TX_MEM_GBL_CFG_INTR_THR_S) &
1068 				Q_REG_TX_MEM_GBL_CFG_INTR_THR_M);
1069 		} else {
1070 			val &= ~Q_REG_TX_MEM_GBL_CFG_INTR_ENA_M;
1071 		}
1072 
1073 		err = ice_write_quad_reg_e822(hw, quad, Q_REG_TX_MEM_GBL_CFG,
1074 					      val);
1075 		if (err)
1076 			break;
1077 	}
1078 
1079 	if (err)
1080 		dev_err(ice_pf_to_dev(pf), "PTP failed in intr ena, err %d\n",
1081 			err);
1082 	return err;
1083 }
1084 
1085 /**
1086  * ice_ptp_reset_phy_timestamping - Reset PHY timestamping block
1087  * @pf: Board private structure
1088  */
1089 static void ice_ptp_reset_phy_timestamping(struct ice_pf *pf)
1090 {
1091 	ice_ptp_port_phy_restart(&pf->ptp.port);
1092 }
1093 
1094 /**
1095  * ice_ptp_adjfine - Adjust clock increment rate
1096  * @info: the driver's PTP info structure
1097  * @scaled_ppm: Parts per million with 16-bit fractional field
1098  *
1099  * Adjust the frequency of the clock by the indicated scaled ppm from the
1100  * base frequency.
1101  */
1102 static int ice_ptp_adjfine(struct ptp_clock_info *info, long scaled_ppm)
1103 {
1104 	struct ice_pf *pf = ptp_info_to_pf(info);
1105 	u64 freq, divisor = 1000000ULL;
1106 	struct ice_hw *hw = &pf->hw;
1107 	s64 incval, diff;
1108 	int neg_adj = 0;
1109 	int err;
1110 
1111 	incval = ice_base_incval(pf);
1112 
1113 	if (scaled_ppm < 0) {
1114 		neg_adj = 1;
1115 		scaled_ppm = -scaled_ppm;
1116 	}
1117 
1118 	while ((u64)scaled_ppm > div64_u64(U64_MAX, incval)) {
1119 		/* handle overflow by scaling down the scaled_ppm and
1120 		 * the divisor, losing some precision
1121 		 */
1122 		scaled_ppm >>= 2;
1123 		divisor >>= 2;
1124 	}
1125 
1126 	freq = (incval * (u64)scaled_ppm) >> 16;
1127 	diff = div_u64(freq, divisor);
1128 
1129 	if (neg_adj)
1130 		incval -= diff;
1131 	else
1132 		incval += diff;
1133 
1134 	err = ice_ptp_write_incval_locked(hw, incval);
1135 	if (err) {
1136 		dev_err(ice_pf_to_dev(pf), "PTP failed to set incval, err %d\n",
1137 			err);
1138 		return -EIO;
1139 	}
1140 
1141 	return 0;
1142 }
1143 
1144 /**
1145  * ice_ptp_extts_work - Workqueue task function
1146  * @work: external timestamp work structure
1147  *
1148  * Service for PTP external clock event
1149  */
1150 static void ice_ptp_extts_work(struct kthread_work *work)
1151 {
1152 	struct ice_ptp *ptp = container_of(work, struct ice_ptp, extts_work);
1153 	struct ice_pf *pf = container_of(ptp, struct ice_pf, ptp);
1154 	struct ptp_clock_event event;
1155 	struct ice_hw *hw = &pf->hw;
1156 	u8 chan, tmr_idx;
1157 	u32 hi, lo;
1158 
1159 	tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned;
1160 	/* Event time is captured by one of the two matched registers
1161 	 *      GLTSYN_EVNT_L: 32 LSB of sampled time event
1162 	 *      GLTSYN_EVNT_H: 32 MSB of sampled time event
1163 	 * Event is defined in GLTSYN_EVNT_0 register
1164 	 */
1165 	for (chan = 0; chan < GLTSYN_EVNT_H_IDX_MAX; chan++) {
1166 		/* Check if channel is enabled */
1167 		if (pf->ptp.ext_ts_irq & (1 << chan)) {
1168 			lo = rd32(hw, GLTSYN_EVNT_L(chan, tmr_idx));
1169 			hi = rd32(hw, GLTSYN_EVNT_H(chan, tmr_idx));
1170 			event.timestamp = (((u64)hi) << 32) | lo;
1171 			event.type = PTP_CLOCK_EXTTS;
1172 			event.index = chan;
1173 
1174 			/* Fire event */
1175 			ptp_clock_event(pf->ptp.clock, &event);
1176 			pf->ptp.ext_ts_irq &= ~(1 << chan);
1177 		}
1178 	}
1179 }
1180 
1181 /**
1182  * ice_ptp_cfg_extts - Configure EXTTS pin and channel
1183  * @pf: Board private structure
1184  * @ena: true to enable; false to disable
1185  * @chan: GPIO channel (0-3)
1186  * @gpio_pin: GPIO pin
1187  * @extts_flags: request flags from the ptp_extts_request.flags
1188  */
1189 static int
1190 ice_ptp_cfg_extts(struct ice_pf *pf, bool ena, unsigned int chan, u32 gpio_pin,
1191 		  unsigned int extts_flags)
1192 {
1193 	u32 func, aux_reg, gpio_reg, irq_reg;
1194 	struct ice_hw *hw = &pf->hw;
1195 	u8 tmr_idx;
1196 
1197 	if (chan > (unsigned int)pf->ptp.info.n_ext_ts)
1198 		return -EINVAL;
1199 
1200 	tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned;
1201 
1202 	irq_reg = rd32(hw, PFINT_OICR_ENA);
1203 
1204 	if (ena) {
1205 		/* Enable the interrupt */
1206 		irq_reg |= PFINT_OICR_TSYN_EVNT_M;
1207 		aux_reg = GLTSYN_AUX_IN_0_INT_ENA_M;
1208 
1209 #define GLTSYN_AUX_IN_0_EVNTLVL_RISING_EDGE	BIT(0)
1210 #define GLTSYN_AUX_IN_0_EVNTLVL_FALLING_EDGE	BIT(1)
1211 
1212 		/* set event level to requested edge */
1213 		if (extts_flags & PTP_FALLING_EDGE)
1214 			aux_reg |= GLTSYN_AUX_IN_0_EVNTLVL_FALLING_EDGE;
1215 		if (extts_flags & PTP_RISING_EDGE)
1216 			aux_reg |= GLTSYN_AUX_IN_0_EVNTLVL_RISING_EDGE;
1217 
1218 		/* Write GPIO CTL reg.
1219 		 * 0x1 is input sampled by EVENT register(channel)
1220 		 * + num_in_channels * tmr_idx
1221 		 */
1222 		func = 1 + chan + (tmr_idx * 3);
1223 		gpio_reg = ((func << GLGEN_GPIO_CTL_PIN_FUNC_S) &
1224 			    GLGEN_GPIO_CTL_PIN_FUNC_M);
1225 		pf->ptp.ext_ts_chan |= (1 << chan);
1226 	} else {
1227 		/* clear the values we set to reset defaults */
1228 		aux_reg = 0;
1229 		gpio_reg = 0;
1230 		pf->ptp.ext_ts_chan &= ~(1 << chan);
1231 		if (!pf->ptp.ext_ts_chan)
1232 			irq_reg &= ~PFINT_OICR_TSYN_EVNT_M;
1233 	}
1234 
1235 	wr32(hw, PFINT_OICR_ENA, irq_reg);
1236 	wr32(hw, GLTSYN_AUX_IN(chan, tmr_idx), aux_reg);
1237 	wr32(hw, GLGEN_GPIO_CTL(gpio_pin), gpio_reg);
1238 
1239 	return 0;
1240 }
1241 
1242 /**
1243  * ice_ptp_cfg_clkout - Configure clock to generate periodic wave
1244  * @pf: Board private structure
1245  * @chan: GPIO channel (0-3)
1246  * @config: desired periodic clk configuration. NULL will disable channel
1247  * @store: If set to true the values will be stored
1248  *
1249  * Configure the internal clock generator modules to generate the clock wave of
1250  * specified period.
1251  */
1252 static int ice_ptp_cfg_clkout(struct ice_pf *pf, unsigned int chan,
1253 			      struct ice_perout_channel *config, bool store)
1254 {
1255 	u64 current_time, period, start_time, phase;
1256 	struct ice_hw *hw = &pf->hw;
1257 	u32 func, val, gpio_pin;
1258 	u8 tmr_idx;
1259 
1260 	tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned;
1261 
1262 	/* 0. Reset mode & out_en in AUX_OUT */
1263 	wr32(hw, GLTSYN_AUX_OUT(chan, tmr_idx), 0);
1264 
1265 	/* If we're disabling the output, clear out CLKO and TGT and keep
1266 	 * output level low
1267 	 */
1268 	if (!config || !config->ena) {
1269 		wr32(hw, GLTSYN_CLKO(chan, tmr_idx), 0);
1270 		wr32(hw, GLTSYN_TGT_L(chan, tmr_idx), 0);
1271 		wr32(hw, GLTSYN_TGT_H(chan, tmr_idx), 0);
1272 
1273 		val = GLGEN_GPIO_CTL_PIN_DIR_M;
1274 		gpio_pin = pf->ptp.perout_channels[chan].gpio_pin;
1275 		wr32(hw, GLGEN_GPIO_CTL(gpio_pin), val);
1276 
1277 		/* Store the value if requested */
1278 		if (store)
1279 			memset(&pf->ptp.perout_channels[chan], 0,
1280 			       sizeof(struct ice_perout_channel));
1281 
1282 		return 0;
1283 	}
1284 	period = config->period;
1285 	start_time = config->start_time;
1286 	div64_u64_rem(start_time, period, &phase);
1287 	gpio_pin = config->gpio_pin;
1288 
1289 	/* 1. Write clkout with half of required period value */
1290 	if (period & 0x1) {
1291 		dev_err(ice_pf_to_dev(pf), "CLK Period must be an even value\n");
1292 		goto err;
1293 	}
1294 
1295 	period >>= 1;
1296 
1297 	/* For proper operation, the GLTSYN_CLKO must be larger than clock tick
1298 	 */
1299 #define MIN_PULSE 3
1300 	if (period <= MIN_PULSE || period > U32_MAX) {
1301 		dev_err(ice_pf_to_dev(pf), "CLK Period must be > %d && < 2^33",
1302 			MIN_PULSE * 2);
1303 		goto err;
1304 	}
1305 
1306 	wr32(hw, GLTSYN_CLKO(chan, tmr_idx), lower_32_bits(period));
1307 
1308 	/* Allow time for programming before start_time is hit */
1309 	current_time = ice_ptp_read_src_clk_reg(pf, NULL);
1310 
1311 	/* if start time is in the past start the timer at the nearest second
1312 	 * maintaining phase
1313 	 */
1314 	if (start_time < current_time)
1315 		start_time = div64_u64(current_time + NSEC_PER_SEC - 1,
1316 				       NSEC_PER_SEC) * NSEC_PER_SEC + phase;
1317 
1318 	if (ice_is_e810(hw))
1319 		start_time -= E810_OUT_PROP_DELAY_NS;
1320 	else
1321 		start_time -= ice_e822_pps_delay(ice_e822_time_ref(hw));
1322 
1323 	/* 2. Write TARGET time */
1324 	wr32(hw, GLTSYN_TGT_L(chan, tmr_idx), lower_32_bits(start_time));
1325 	wr32(hw, GLTSYN_TGT_H(chan, tmr_idx), upper_32_bits(start_time));
1326 
1327 	/* 3. Write AUX_OUT register */
1328 	val = GLTSYN_AUX_OUT_0_OUT_ENA_M | GLTSYN_AUX_OUT_0_OUTMOD_M;
1329 	wr32(hw, GLTSYN_AUX_OUT(chan, tmr_idx), val);
1330 
1331 	/* 4. write GPIO CTL reg */
1332 	func = 8 + chan + (tmr_idx * 4);
1333 	val = GLGEN_GPIO_CTL_PIN_DIR_M |
1334 	      ((func << GLGEN_GPIO_CTL_PIN_FUNC_S) & GLGEN_GPIO_CTL_PIN_FUNC_M);
1335 	wr32(hw, GLGEN_GPIO_CTL(gpio_pin), val);
1336 
1337 	/* Store the value if requested */
1338 	if (store) {
1339 		memcpy(&pf->ptp.perout_channels[chan], config,
1340 		       sizeof(struct ice_perout_channel));
1341 		pf->ptp.perout_channels[chan].start_time = phase;
1342 	}
1343 
1344 	return 0;
1345 err:
1346 	dev_err(ice_pf_to_dev(pf), "PTP failed to cfg per_clk\n");
1347 	return -EFAULT;
1348 }
1349 
1350 /**
1351  * ice_ptp_disable_all_clkout - Disable all currently configured outputs
1352  * @pf: pointer to the PF structure
1353  *
1354  * Disable all currently configured clock outputs. This is necessary before
1355  * certain changes to the PTP hardware clock. Use ice_ptp_enable_all_clkout to
1356  * re-enable the clocks again.
1357  */
1358 static void ice_ptp_disable_all_clkout(struct ice_pf *pf)
1359 {
1360 	uint i;
1361 
1362 	for (i = 0; i < pf->ptp.info.n_per_out; i++)
1363 		if (pf->ptp.perout_channels[i].ena)
1364 			ice_ptp_cfg_clkout(pf, i, NULL, false);
1365 }
1366 
1367 /**
1368  * ice_ptp_enable_all_clkout - Enable all configured periodic clock outputs
1369  * @pf: pointer to the PF structure
1370  *
1371  * Enable all currently configured clock outputs. Use this after
1372  * ice_ptp_disable_all_clkout to reconfigure the output signals according to
1373  * their configuration.
1374  */
1375 static void ice_ptp_enable_all_clkout(struct ice_pf *pf)
1376 {
1377 	uint i;
1378 
1379 	for (i = 0; i < pf->ptp.info.n_per_out; i++)
1380 		if (pf->ptp.perout_channels[i].ena)
1381 			ice_ptp_cfg_clkout(pf, i, &pf->ptp.perout_channels[i],
1382 					   false);
1383 }
1384 
1385 /**
1386  * ice_ptp_gpio_enable_e810 - Enable/disable ancillary features of PHC
1387  * @info: the driver's PTP info structure
1388  * @rq: The requested feature to change
1389  * @on: Enable/disable flag
1390  */
1391 static int
1392 ice_ptp_gpio_enable_e810(struct ptp_clock_info *info,
1393 			 struct ptp_clock_request *rq, int on)
1394 {
1395 	struct ice_pf *pf = ptp_info_to_pf(info);
1396 	struct ice_perout_channel clk_cfg = {0};
1397 	bool sma_pres = false;
1398 	unsigned int chan;
1399 	u32 gpio_pin;
1400 	int err;
1401 
1402 	if (ice_is_feature_supported(pf, ICE_F_SMA_CTRL))
1403 		sma_pres = true;
1404 
1405 	switch (rq->type) {
1406 	case PTP_CLK_REQ_PEROUT:
1407 		chan = rq->perout.index;
1408 		if (sma_pres) {
1409 			if (chan == ice_pin_desc_e810t[SMA1].chan)
1410 				clk_cfg.gpio_pin = GPIO_20;
1411 			else if (chan == ice_pin_desc_e810t[SMA2].chan)
1412 				clk_cfg.gpio_pin = GPIO_22;
1413 			else
1414 				return -1;
1415 		} else if (ice_is_e810t(&pf->hw)) {
1416 			if (chan == 0)
1417 				clk_cfg.gpio_pin = GPIO_20;
1418 			else
1419 				clk_cfg.gpio_pin = GPIO_22;
1420 		} else if (chan == PPS_CLK_GEN_CHAN) {
1421 			clk_cfg.gpio_pin = PPS_PIN_INDEX;
1422 		} else {
1423 			clk_cfg.gpio_pin = chan;
1424 		}
1425 
1426 		clk_cfg.period = ((rq->perout.period.sec * NSEC_PER_SEC) +
1427 				   rq->perout.period.nsec);
1428 		clk_cfg.start_time = ((rq->perout.start.sec * NSEC_PER_SEC) +
1429 				       rq->perout.start.nsec);
1430 		clk_cfg.ena = !!on;
1431 
1432 		err = ice_ptp_cfg_clkout(pf, chan, &clk_cfg, true);
1433 		break;
1434 	case PTP_CLK_REQ_EXTTS:
1435 		chan = rq->extts.index;
1436 		if (sma_pres) {
1437 			if (chan < ice_pin_desc_e810t[SMA2].chan)
1438 				gpio_pin = GPIO_21;
1439 			else
1440 				gpio_pin = GPIO_23;
1441 		} else if (ice_is_e810t(&pf->hw)) {
1442 			if (chan == 0)
1443 				gpio_pin = GPIO_21;
1444 			else
1445 				gpio_pin = GPIO_23;
1446 		} else {
1447 			gpio_pin = chan;
1448 		}
1449 
1450 		err = ice_ptp_cfg_extts(pf, !!on, chan, gpio_pin,
1451 					rq->extts.flags);
1452 		break;
1453 	default:
1454 		return -EOPNOTSUPP;
1455 	}
1456 
1457 	return err;
1458 }
1459 
1460 /**
1461  * ice_ptp_gettimex64 - Get the time of the clock
1462  * @info: the driver's PTP info structure
1463  * @ts: timespec64 structure to hold the current time value
1464  * @sts: Optional parameter for holding a pair of system timestamps from
1465  *       the system clock. Will be ignored if NULL is given.
1466  *
1467  * Read the device clock and return the correct value on ns, after converting it
1468  * into a timespec struct.
1469  */
1470 static int
1471 ice_ptp_gettimex64(struct ptp_clock_info *info, struct timespec64 *ts,
1472 		   struct ptp_system_timestamp *sts)
1473 {
1474 	struct ice_pf *pf = ptp_info_to_pf(info);
1475 	struct ice_hw *hw = &pf->hw;
1476 
1477 	if (!ice_ptp_lock(hw)) {
1478 		dev_err(ice_pf_to_dev(pf), "PTP failed to get time\n");
1479 		return -EBUSY;
1480 	}
1481 
1482 	ice_ptp_read_time(pf, ts, sts);
1483 	ice_ptp_unlock(hw);
1484 
1485 	return 0;
1486 }
1487 
1488 /**
1489  * ice_ptp_settime64 - Set the time of the clock
1490  * @info: the driver's PTP info structure
1491  * @ts: timespec64 structure that holds the new time value
1492  *
1493  * Set the device clock to the user input value. The conversion from timespec
1494  * to ns happens in the write function.
1495  */
1496 static int
1497 ice_ptp_settime64(struct ptp_clock_info *info, const struct timespec64 *ts)
1498 {
1499 	struct ice_pf *pf = ptp_info_to_pf(info);
1500 	struct timespec64 ts64 = *ts;
1501 	struct ice_hw *hw = &pf->hw;
1502 	int err;
1503 
1504 	/* For Vernier mode, we need to recalibrate after new settime
1505 	 * Start with disabling timestamp block
1506 	 */
1507 	if (pf->ptp.port.link_up)
1508 		ice_ptp_port_phy_stop(&pf->ptp.port);
1509 
1510 	if (!ice_ptp_lock(hw)) {
1511 		err = -EBUSY;
1512 		goto exit;
1513 	}
1514 
1515 	/* Disable periodic outputs */
1516 	ice_ptp_disable_all_clkout(pf);
1517 
1518 	err = ice_ptp_write_init(pf, &ts64);
1519 	ice_ptp_unlock(hw);
1520 
1521 	if (!err)
1522 		ice_ptp_update_cached_phctime(pf);
1523 
1524 	/* Reenable periodic outputs */
1525 	ice_ptp_enable_all_clkout(pf);
1526 
1527 	/* Recalibrate and re-enable timestamp block */
1528 	if (pf->ptp.port.link_up)
1529 		ice_ptp_port_phy_restart(&pf->ptp.port);
1530 exit:
1531 	if (err) {
1532 		dev_err(ice_pf_to_dev(pf), "PTP failed to set time %d\n", err);
1533 		return err;
1534 	}
1535 
1536 	return 0;
1537 }
1538 
1539 /**
1540  * ice_ptp_adjtime_nonatomic - Do a non-atomic clock adjustment
1541  * @info: the driver's PTP info structure
1542  * @delta: Offset in nanoseconds to adjust the time by
1543  */
1544 static int ice_ptp_adjtime_nonatomic(struct ptp_clock_info *info, s64 delta)
1545 {
1546 	struct timespec64 now, then;
1547 	int ret;
1548 
1549 	then = ns_to_timespec64(delta);
1550 	ret = ice_ptp_gettimex64(info, &now, NULL);
1551 	if (ret)
1552 		return ret;
1553 	now = timespec64_add(now, then);
1554 
1555 	return ice_ptp_settime64(info, (const struct timespec64 *)&now);
1556 }
1557 
1558 /**
1559  * ice_ptp_adjtime - Adjust the time of the clock by the indicated delta
1560  * @info: the driver's PTP info structure
1561  * @delta: Offset in nanoseconds to adjust the time by
1562  */
1563 static int ice_ptp_adjtime(struct ptp_clock_info *info, s64 delta)
1564 {
1565 	struct ice_pf *pf = ptp_info_to_pf(info);
1566 	struct ice_hw *hw = &pf->hw;
1567 	struct device *dev;
1568 	int err;
1569 
1570 	dev = ice_pf_to_dev(pf);
1571 
1572 	/* Hardware only supports atomic adjustments using signed 32-bit
1573 	 * integers. For any adjustment outside this range, perform
1574 	 * a non-atomic get->adjust->set flow.
1575 	 */
1576 	if (delta > S32_MAX || delta < S32_MIN) {
1577 		dev_dbg(dev, "delta = %lld, adjtime non-atomic\n", delta);
1578 		return ice_ptp_adjtime_nonatomic(info, delta);
1579 	}
1580 
1581 	if (!ice_ptp_lock(hw)) {
1582 		dev_err(dev, "PTP failed to acquire semaphore in adjtime\n");
1583 		return -EBUSY;
1584 	}
1585 
1586 	/* Disable periodic outputs */
1587 	ice_ptp_disable_all_clkout(pf);
1588 
1589 	err = ice_ptp_write_adj(pf, delta);
1590 
1591 	/* Reenable periodic outputs */
1592 	ice_ptp_enable_all_clkout(pf);
1593 
1594 	ice_ptp_unlock(hw);
1595 
1596 	if (err) {
1597 		dev_err(dev, "PTP failed to adjust time, err %d\n", err);
1598 		return err;
1599 	}
1600 
1601 	ice_ptp_update_cached_phctime(pf);
1602 
1603 	return 0;
1604 }
1605 
1606 #ifdef CONFIG_ICE_HWTS
1607 /**
1608  * ice_ptp_get_syncdevicetime - Get the cross time stamp info
1609  * @device: Current device time
1610  * @system: System counter value read synchronously with device time
1611  * @ctx: Context provided by timekeeping code
1612  *
1613  * Read device and system (ART) clock simultaneously and return the corrected
1614  * clock values in ns.
1615  */
1616 static int
1617 ice_ptp_get_syncdevicetime(ktime_t *device,
1618 			   struct system_counterval_t *system,
1619 			   void *ctx)
1620 {
1621 	struct ice_pf *pf = (struct ice_pf *)ctx;
1622 	struct ice_hw *hw = &pf->hw;
1623 	u32 hh_lock, hh_art_ctl;
1624 	int i;
1625 
1626 	/* Get the HW lock */
1627 	hh_lock = rd32(hw, PFHH_SEM + (PFTSYN_SEM_BYTES * hw->pf_id));
1628 	if (hh_lock & PFHH_SEM_BUSY_M) {
1629 		dev_err(ice_pf_to_dev(pf), "PTP failed to get hh lock\n");
1630 		return -EFAULT;
1631 	}
1632 
1633 	/* Start the ART and device clock sync sequence */
1634 	hh_art_ctl = rd32(hw, GLHH_ART_CTL);
1635 	hh_art_ctl = hh_art_ctl | GLHH_ART_CTL_ACTIVE_M;
1636 	wr32(hw, GLHH_ART_CTL, hh_art_ctl);
1637 
1638 #define MAX_HH_LOCK_TRIES 100
1639 
1640 	for (i = 0; i < MAX_HH_LOCK_TRIES; i++) {
1641 		/* Wait for sync to complete */
1642 		hh_art_ctl = rd32(hw, GLHH_ART_CTL);
1643 		if (hh_art_ctl & GLHH_ART_CTL_ACTIVE_M) {
1644 			udelay(1);
1645 			continue;
1646 		} else {
1647 			u32 hh_ts_lo, hh_ts_hi, tmr_idx;
1648 			u64 hh_ts;
1649 
1650 			tmr_idx = hw->func_caps.ts_func_info.tmr_index_assoc;
1651 			/* Read ART time */
1652 			hh_ts_lo = rd32(hw, GLHH_ART_TIME_L);
1653 			hh_ts_hi = rd32(hw, GLHH_ART_TIME_H);
1654 			hh_ts = ((u64)hh_ts_hi << 32) | hh_ts_lo;
1655 			*system = convert_art_ns_to_tsc(hh_ts);
1656 			/* Read Device source clock time */
1657 			hh_ts_lo = rd32(hw, GLTSYN_HHTIME_L(tmr_idx));
1658 			hh_ts_hi = rd32(hw, GLTSYN_HHTIME_H(tmr_idx));
1659 			hh_ts = ((u64)hh_ts_hi << 32) | hh_ts_lo;
1660 			*device = ns_to_ktime(hh_ts);
1661 			break;
1662 		}
1663 	}
1664 	/* Release HW lock */
1665 	hh_lock = rd32(hw, PFHH_SEM + (PFTSYN_SEM_BYTES * hw->pf_id));
1666 	hh_lock = hh_lock & ~PFHH_SEM_BUSY_M;
1667 	wr32(hw, PFHH_SEM + (PFTSYN_SEM_BYTES * hw->pf_id), hh_lock);
1668 
1669 	if (i == MAX_HH_LOCK_TRIES)
1670 		return -ETIMEDOUT;
1671 
1672 	return 0;
1673 }
1674 
1675 /**
1676  * ice_ptp_getcrosststamp_e822 - Capture a device cross timestamp
1677  * @info: the driver's PTP info structure
1678  * @cts: The memory to fill the cross timestamp info
1679  *
1680  * Capture a cross timestamp between the ART and the device PTP hardware
1681  * clock. Fill the cross timestamp information and report it back to the
1682  * caller.
1683  *
1684  * This is only valid for E822 devices which have support for generating the
1685  * cross timestamp via PCIe PTM.
1686  *
1687  * In order to correctly correlate the ART timestamp back to the TSC time, the
1688  * CPU must have X86_FEATURE_TSC_KNOWN_FREQ.
1689  */
1690 static int
1691 ice_ptp_getcrosststamp_e822(struct ptp_clock_info *info,
1692 			    struct system_device_crosststamp *cts)
1693 {
1694 	struct ice_pf *pf = ptp_info_to_pf(info);
1695 
1696 	return get_device_system_crosststamp(ice_ptp_get_syncdevicetime,
1697 					     pf, NULL, cts);
1698 }
1699 #endif /* CONFIG_ICE_HWTS */
1700 
1701 /**
1702  * ice_ptp_get_ts_config - ioctl interface to read the timestamping config
1703  * @pf: Board private structure
1704  * @ifr: ioctl data
1705  *
1706  * Copy the timestamping config to user buffer
1707  */
1708 int ice_ptp_get_ts_config(struct ice_pf *pf, struct ifreq *ifr)
1709 {
1710 	struct hwtstamp_config *config;
1711 
1712 	if (!test_bit(ICE_FLAG_PTP, pf->flags))
1713 		return -EIO;
1714 
1715 	config = &pf->ptp.tstamp_config;
1716 
1717 	return copy_to_user(ifr->ifr_data, config, sizeof(*config)) ?
1718 		-EFAULT : 0;
1719 }
1720 
1721 /**
1722  * ice_ptp_set_timestamp_mode - Setup driver for requested timestamp mode
1723  * @pf: Board private structure
1724  * @config: hwtstamp settings requested or saved
1725  */
1726 static int
1727 ice_ptp_set_timestamp_mode(struct ice_pf *pf, struct hwtstamp_config *config)
1728 {
1729 	switch (config->tx_type) {
1730 	case HWTSTAMP_TX_OFF:
1731 		ice_set_tx_tstamp(pf, false);
1732 		break;
1733 	case HWTSTAMP_TX_ON:
1734 		ice_set_tx_tstamp(pf, true);
1735 		break;
1736 	default:
1737 		return -ERANGE;
1738 	}
1739 
1740 	switch (config->rx_filter) {
1741 	case HWTSTAMP_FILTER_NONE:
1742 		ice_set_rx_tstamp(pf, false);
1743 		break;
1744 	case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
1745 	case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
1746 	case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
1747 	case HWTSTAMP_FILTER_PTP_V2_EVENT:
1748 	case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
1749 	case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
1750 	case HWTSTAMP_FILTER_PTP_V2_SYNC:
1751 	case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
1752 	case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
1753 	case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
1754 	case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
1755 	case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
1756 	case HWTSTAMP_FILTER_NTP_ALL:
1757 	case HWTSTAMP_FILTER_ALL:
1758 		ice_set_rx_tstamp(pf, true);
1759 		break;
1760 	default:
1761 		return -ERANGE;
1762 	}
1763 
1764 	return 0;
1765 }
1766 
1767 /**
1768  * ice_ptp_set_ts_config - ioctl interface to control the timestamping
1769  * @pf: Board private structure
1770  * @ifr: ioctl data
1771  *
1772  * Get the user config and store it
1773  */
1774 int ice_ptp_set_ts_config(struct ice_pf *pf, struct ifreq *ifr)
1775 {
1776 	struct hwtstamp_config config;
1777 	int err;
1778 
1779 	if (!test_bit(ICE_FLAG_PTP, pf->flags))
1780 		return -EAGAIN;
1781 
1782 	if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
1783 		return -EFAULT;
1784 
1785 	err = ice_ptp_set_timestamp_mode(pf, &config);
1786 	if (err)
1787 		return err;
1788 
1789 	/* Return the actual configuration set */
1790 	config = pf->ptp.tstamp_config;
1791 
1792 	return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ?
1793 		-EFAULT : 0;
1794 }
1795 
1796 /**
1797  * ice_ptp_rx_hwtstamp - Check for an Rx timestamp
1798  * @rx_ring: Ring to get the VSI info
1799  * @rx_desc: Receive descriptor
1800  * @skb: Particular skb to send timestamp with
1801  *
1802  * The driver receives a notification in the receive descriptor with timestamp.
1803  * The timestamp is in ns, so we must convert the result first.
1804  */
1805 void
1806 ice_ptp_rx_hwtstamp(struct ice_rx_ring *rx_ring,
1807 		    union ice_32b_rx_flex_desc *rx_desc, struct sk_buff *skb)
1808 {
1809 	u32 ts_high;
1810 	u64 ts_ns;
1811 
1812 	/* Populate timesync data into skb */
1813 	if (rx_desc->wb.time_stamp_low & ICE_PTP_TS_VALID) {
1814 		struct skb_shared_hwtstamps *hwtstamps;
1815 
1816 		/* Use ice_ptp_extend_32b_ts directly, using the ring-specific
1817 		 * cached PHC value, rather than accessing the PF. This also
1818 		 * allows us to simply pass the upper 32bits of nanoseconds
1819 		 * directly. Calling ice_ptp_extend_40b_ts is unnecessary as
1820 		 * it would just discard these bits itself.
1821 		 */
1822 		ts_high = le32_to_cpu(rx_desc->wb.flex_ts.ts_high);
1823 		ts_ns = ice_ptp_extend_32b_ts(rx_ring->cached_phctime, ts_high);
1824 
1825 		hwtstamps = skb_hwtstamps(skb);
1826 		memset(hwtstamps, 0, sizeof(*hwtstamps));
1827 		hwtstamps->hwtstamp = ns_to_ktime(ts_ns);
1828 	}
1829 }
1830 
1831 /**
1832  * ice_ptp_disable_sma_pins_e810t - Disable E810-T SMA pins
1833  * @pf: pointer to the PF structure
1834  * @info: PTP clock info structure
1835  *
1836  * Disable the OS access to the SMA pins. Called to clear out the OS
1837  * indications of pin support when we fail to setup the E810-T SMA control
1838  * register.
1839  */
1840 static void
1841 ice_ptp_disable_sma_pins_e810t(struct ice_pf *pf, struct ptp_clock_info *info)
1842 {
1843 	struct device *dev = ice_pf_to_dev(pf);
1844 
1845 	dev_warn(dev, "Failed to configure E810-T SMA pin control\n");
1846 
1847 	info->enable = NULL;
1848 	info->verify = NULL;
1849 	info->n_pins = 0;
1850 	info->n_ext_ts = 0;
1851 	info->n_per_out = 0;
1852 }
1853 
1854 /**
1855  * ice_ptp_setup_sma_pins_e810t - Setup the SMA pins
1856  * @pf: pointer to the PF structure
1857  * @info: PTP clock info structure
1858  *
1859  * Finish setting up the SMA pins by allocating pin_config, and setting it up
1860  * according to the current status of the SMA. On failure, disable all of the
1861  * extended SMA pin support.
1862  */
1863 static void
1864 ice_ptp_setup_sma_pins_e810t(struct ice_pf *pf, struct ptp_clock_info *info)
1865 {
1866 	struct device *dev = ice_pf_to_dev(pf);
1867 	int err;
1868 
1869 	/* Allocate memory for kernel pins interface */
1870 	info->pin_config = devm_kcalloc(dev, info->n_pins,
1871 					sizeof(*info->pin_config), GFP_KERNEL);
1872 	if (!info->pin_config) {
1873 		ice_ptp_disable_sma_pins_e810t(pf, info);
1874 		return;
1875 	}
1876 
1877 	/* Read current SMA status */
1878 	err = ice_get_sma_config_e810t(&pf->hw, info->pin_config);
1879 	if (err)
1880 		ice_ptp_disable_sma_pins_e810t(pf, info);
1881 }
1882 
1883 /**
1884  * ice_ptp_setup_pins_e810t - Setup PTP pins in sysfs
1885  * @pf: pointer to the PF instance
1886  * @info: PTP clock capabilities
1887  */
1888 static void
1889 ice_ptp_setup_pins_e810t(struct ice_pf *pf, struct ptp_clock_info *info)
1890 {
1891 	/* Check if SMA controller is in the netlist */
1892 	if (ice_is_feature_supported(pf, ICE_F_SMA_CTRL) &&
1893 	    !ice_is_pca9575_present(&pf->hw))
1894 		ice_clear_feature_support(pf, ICE_F_SMA_CTRL);
1895 
1896 	if (!ice_is_feature_supported(pf, ICE_F_SMA_CTRL)) {
1897 		info->n_ext_ts = N_EXT_TS_E810_NO_SMA;
1898 		info->n_per_out = N_PER_OUT_E810T_NO_SMA;
1899 		return;
1900 	}
1901 
1902 	info->n_per_out = N_PER_OUT_E810T;
1903 	info->n_ext_ts = N_EXT_TS_E810;
1904 	info->n_pins = NUM_PTP_PINS_E810T;
1905 	info->verify = ice_verify_pin_e810t;
1906 
1907 	/* Complete setup of the SMA pins */
1908 	ice_ptp_setup_sma_pins_e810t(pf, info);
1909 }
1910 
1911 /**
1912  * ice_ptp_setup_pins_e810 - Setup PTP pins in sysfs
1913  * @info: PTP clock capabilities
1914  */
1915 static void ice_ptp_setup_pins_e810(struct ptp_clock_info *info)
1916 {
1917 	info->n_per_out = N_PER_OUT_E810;
1918 	info->n_ext_ts = N_EXT_TS_E810;
1919 }
1920 
1921 /**
1922  * ice_ptp_set_funcs_e822 - Set specialized functions for E822 support
1923  * @pf: Board private structure
1924  * @info: PTP info to fill
1925  *
1926  * Assign functions to the PTP capabiltiies structure for E822 devices.
1927  * Functions which operate across all device families should be set directly
1928  * in ice_ptp_set_caps. Only add functions here which are distinct for E822
1929  * devices.
1930  */
1931 static void
1932 ice_ptp_set_funcs_e822(struct ice_pf *pf, struct ptp_clock_info *info)
1933 {
1934 #ifdef CONFIG_ICE_HWTS
1935 	if (boot_cpu_has(X86_FEATURE_ART) &&
1936 	    boot_cpu_has(X86_FEATURE_TSC_KNOWN_FREQ))
1937 		info->getcrosststamp = ice_ptp_getcrosststamp_e822;
1938 #endif /* CONFIG_ICE_HWTS */
1939 }
1940 
1941 /**
1942  * ice_ptp_set_funcs_e810 - Set specialized functions for E810 support
1943  * @pf: Board private structure
1944  * @info: PTP info to fill
1945  *
1946  * Assign functions to the PTP capabiltiies structure for E810 devices.
1947  * Functions which operate across all device families should be set directly
1948  * in ice_ptp_set_caps. Only add functions here which are distinct for e810
1949  * devices.
1950  */
1951 static void
1952 ice_ptp_set_funcs_e810(struct ice_pf *pf, struct ptp_clock_info *info)
1953 {
1954 	info->enable = ice_ptp_gpio_enable_e810;
1955 
1956 	if (ice_is_e810t(&pf->hw))
1957 		ice_ptp_setup_pins_e810t(pf, info);
1958 	else
1959 		ice_ptp_setup_pins_e810(info);
1960 }
1961 
1962 /**
1963  * ice_ptp_set_caps - Set PTP capabilities
1964  * @pf: Board private structure
1965  */
1966 static void ice_ptp_set_caps(struct ice_pf *pf)
1967 {
1968 	struct ptp_clock_info *info = &pf->ptp.info;
1969 	struct device *dev = ice_pf_to_dev(pf);
1970 
1971 	snprintf(info->name, sizeof(info->name) - 1, "%s-%s-clk",
1972 		 dev_driver_string(dev), dev_name(dev));
1973 	info->owner = THIS_MODULE;
1974 	info->max_adj = 999999999;
1975 	info->adjtime = ice_ptp_adjtime;
1976 	info->adjfine = ice_ptp_adjfine;
1977 	info->gettimex64 = ice_ptp_gettimex64;
1978 	info->settime64 = ice_ptp_settime64;
1979 
1980 	if (ice_is_e810(&pf->hw))
1981 		ice_ptp_set_funcs_e810(pf, info);
1982 	else
1983 		ice_ptp_set_funcs_e822(pf, info);
1984 }
1985 
1986 /**
1987  * ice_ptp_create_clock - Create PTP clock device for userspace
1988  * @pf: Board private structure
1989  *
1990  * This function creates a new PTP clock device. It only creates one if we
1991  * don't already have one. Will return error if it can't create one, but success
1992  * if we already have a device. Should be used by ice_ptp_init to create clock
1993  * initially, and prevent global resets from creating new clock devices.
1994  */
1995 static long ice_ptp_create_clock(struct ice_pf *pf)
1996 {
1997 	struct ptp_clock_info *info;
1998 	struct ptp_clock *clock;
1999 	struct device *dev;
2000 
2001 	/* No need to create a clock device if we already have one */
2002 	if (pf->ptp.clock)
2003 		return 0;
2004 
2005 	ice_ptp_set_caps(pf);
2006 
2007 	info = &pf->ptp.info;
2008 	dev = ice_pf_to_dev(pf);
2009 
2010 	/* Attempt to register the clock before enabling the hardware. */
2011 	clock = ptp_clock_register(info, dev);
2012 	if (IS_ERR(clock))
2013 		return PTR_ERR(clock);
2014 
2015 	pf->ptp.clock = clock;
2016 
2017 	return 0;
2018 }
2019 
2020 /**
2021  * ice_ptp_tx_tstamp_work - Process Tx timestamps for a port
2022  * @work: pointer to the kthread_work struct
2023  *
2024  * Process timestamps captured by the PHY associated with this port. To do
2025  * this, loop over each index with a waiting skb.
2026  *
2027  * If a given index has a valid timestamp, perform the following steps:
2028  *
2029  * 1) copy the timestamp out of the PHY register
2030  * 4) clear the timestamp valid bit in the PHY register
2031  * 5) unlock the index by clearing the associated in_use bit.
2032  * 2) extend the 40b timestamp value to get a 64bit timestamp
2033  * 3) send that timestamp to the stack
2034  *
2035  * After looping, if we still have waiting SKBs, then re-queue the work. This
2036  * may cause us effectively poll even when not strictly necessary. We do this
2037  * because it's possible a new timestamp was requested around the same time as
2038  * the interrupt. In some cases hardware might not interrupt us again when the
2039  * timestamp is captured.
2040  *
2041  * Note that we only take the tracking lock when clearing the bit and when
2042  * checking if we need to re-queue this task. The only place where bits can be
2043  * set is the hard xmit routine where an SKB has a request flag set. The only
2044  * places where we clear bits are this work function, or the periodic cleanup
2045  * thread. If the cleanup thread clears a bit we're processing we catch it
2046  * when we lock to clear the bit and then grab the SKB pointer. If a Tx thread
2047  * starts a new timestamp, we might not begin processing it right away but we
2048  * will notice it at the end when we re-queue the work item. If a Tx thread
2049  * starts a new timestamp just after this function exits without re-queuing,
2050  * the interrupt when the timestamp finishes should trigger. Avoiding holding
2051  * the lock for the entire function is important in order to ensure that Tx
2052  * threads do not get blocked while waiting for the lock.
2053  */
2054 static void ice_ptp_tx_tstamp_work(struct kthread_work *work)
2055 {
2056 	struct ice_ptp_port *ptp_port;
2057 	struct ice_ptp_tx *tx;
2058 	struct ice_pf *pf;
2059 	struct ice_hw *hw;
2060 	u8 idx;
2061 
2062 	tx = container_of(work, struct ice_ptp_tx, work);
2063 	if (!tx->init)
2064 		return;
2065 
2066 	ptp_port = container_of(tx, struct ice_ptp_port, tx);
2067 	pf = ptp_port_to_pf(ptp_port);
2068 	hw = &pf->hw;
2069 
2070 	for_each_set_bit(idx, tx->in_use, tx->len) {
2071 		struct skb_shared_hwtstamps shhwtstamps = {};
2072 		u8 phy_idx = idx + tx->quad_offset;
2073 		u64 raw_tstamp, tstamp;
2074 		struct sk_buff *skb;
2075 		int err;
2076 
2077 		ice_trace(tx_tstamp_fw_req, tx->tstamps[idx].skb, idx);
2078 
2079 		err = ice_read_phy_tstamp(hw, tx->quad, phy_idx,
2080 					  &raw_tstamp);
2081 		if (err)
2082 			continue;
2083 
2084 		ice_trace(tx_tstamp_fw_done, tx->tstamps[idx].skb, idx);
2085 
2086 		/* Check if the timestamp is invalid or stale */
2087 		if (!(raw_tstamp & ICE_PTP_TS_VALID) ||
2088 		    raw_tstamp == tx->tstamps[idx].cached_tstamp)
2089 			continue;
2090 
2091 		/* The timestamp is valid, so we'll go ahead and clear this
2092 		 * index and then send the timestamp up to the stack.
2093 		 */
2094 		spin_lock(&tx->lock);
2095 		tx->tstamps[idx].cached_tstamp = raw_tstamp;
2096 		clear_bit(idx, tx->in_use);
2097 		skb = tx->tstamps[idx].skb;
2098 		tx->tstamps[idx].skb = NULL;
2099 		spin_unlock(&tx->lock);
2100 
2101 		/* it's (unlikely but) possible we raced with the cleanup
2102 		 * thread for discarding old timestamp requests.
2103 		 */
2104 		if (!skb)
2105 			continue;
2106 
2107 		/* Extend the timestamp using cached PHC time */
2108 		tstamp = ice_ptp_extend_40b_ts(pf, raw_tstamp);
2109 		shhwtstamps.hwtstamp = ns_to_ktime(tstamp);
2110 
2111 		ice_trace(tx_tstamp_complete, skb, idx);
2112 
2113 		skb_tstamp_tx(skb, &shhwtstamps);
2114 		dev_kfree_skb_any(skb);
2115 	}
2116 
2117 	/* Check if we still have work to do. If so, re-queue this task to
2118 	 * poll for remaining timestamps.
2119 	 */
2120 	spin_lock(&tx->lock);
2121 	if (!bitmap_empty(tx->in_use, tx->len))
2122 		kthread_queue_work(pf->ptp.kworker, &tx->work);
2123 	spin_unlock(&tx->lock);
2124 }
2125 
2126 /**
2127  * ice_ptp_request_ts - Request an available Tx timestamp index
2128  * @tx: the PTP Tx timestamp tracker to request from
2129  * @skb: the SKB to associate with this timestamp request
2130  */
2131 s8 ice_ptp_request_ts(struct ice_ptp_tx *tx, struct sk_buff *skb)
2132 {
2133 	u8 idx;
2134 
2135 	/* Check if this tracker is initialized */
2136 	if (!tx->init || tx->calibrating)
2137 		return -1;
2138 
2139 	spin_lock(&tx->lock);
2140 	/* Find and set the first available index */
2141 	idx = find_first_zero_bit(tx->in_use, tx->len);
2142 	if (idx < tx->len) {
2143 		/* We got a valid index that no other thread could have set. Store
2144 		 * a reference to the skb and the start time to allow discarding old
2145 		 * requests.
2146 		 */
2147 		set_bit(idx, tx->in_use);
2148 		tx->tstamps[idx].start = jiffies;
2149 		tx->tstamps[idx].skb = skb_get(skb);
2150 		skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
2151 		ice_trace(tx_tstamp_request, skb, idx);
2152 	}
2153 
2154 	spin_unlock(&tx->lock);
2155 
2156 	/* return the appropriate PHY timestamp register index, -1 if no
2157 	 * indexes were available.
2158 	 */
2159 	if (idx >= tx->len)
2160 		return -1;
2161 	else
2162 		return idx + tx->quad_offset;
2163 }
2164 
2165 /**
2166  * ice_ptp_process_ts - Spawn kthread work to handle timestamps
2167  * @pf: Board private structure
2168  *
2169  * Queue work required to process the PTP Tx timestamps outside of interrupt
2170  * context.
2171  */
2172 void ice_ptp_process_ts(struct ice_pf *pf)
2173 {
2174 	if (pf->ptp.port.tx.init)
2175 		kthread_queue_work(pf->ptp.kworker, &pf->ptp.port.tx.work);
2176 }
2177 
2178 /**
2179  * ice_ptp_alloc_tx_tracker - Initialize tracking for Tx timestamps
2180  * @tx: Tx tracking structure to initialize
2181  *
2182  * Assumes that the length has already been initialized. Do not call directly,
2183  * use the ice_ptp_init_tx_e822 or ice_ptp_init_tx_e810 instead.
2184  */
2185 static int
2186 ice_ptp_alloc_tx_tracker(struct ice_ptp_tx *tx)
2187 {
2188 	tx->tstamps = kcalloc(tx->len, sizeof(*tx->tstamps), GFP_KERNEL);
2189 	if (!tx->tstamps)
2190 		return -ENOMEM;
2191 
2192 	tx->in_use = bitmap_zalloc(tx->len, GFP_KERNEL);
2193 	if (!tx->in_use) {
2194 		kfree(tx->tstamps);
2195 		tx->tstamps = NULL;
2196 		return -ENOMEM;
2197 	}
2198 
2199 	spin_lock_init(&tx->lock);
2200 	kthread_init_work(&tx->work, ice_ptp_tx_tstamp_work);
2201 
2202 	tx->init = 1;
2203 
2204 	return 0;
2205 }
2206 
2207 /**
2208  * ice_ptp_flush_tx_tracker - Flush any remaining timestamps from the tracker
2209  * @pf: Board private structure
2210  * @tx: the tracker to flush
2211  */
2212 static void
2213 ice_ptp_flush_tx_tracker(struct ice_pf *pf, struct ice_ptp_tx *tx)
2214 {
2215 	u8 idx;
2216 
2217 	for (idx = 0; idx < tx->len; idx++) {
2218 		u8 phy_idx = idx + tx->quad_offset;
2219 
2220 		spin_lock(&tx->lock);
2221 		if (tx->tstamps[idx].skb) {
2222 			dev_kfree_skb_any(tx->tstamps[idx].skb);
2223 			tx->tstamps[idx].skb = NULL;
2224 		}
2225 		clear_bit(idx, tx->in_use);
2226 		spin_unlock(&tx->lock);
2227 
2228 		/* Clear any potential residual timestamp in the PHY block */
2229 		if (!pf->hw.reset_ongoing)
2230 			ice_clear_phy_tstamp(&pf->hw, tx->quad, phy_idx);
2231 	}
2232 }
2233 
2234 /**
2235  * ice_ptp_release_tx_tracker - Release allocated memory for Tx tracker
2236  * @pf: Board private structure
2237  * @tx: Tx tracking structure to release
2238  *
2239  * Free memory associated with the Tx timestamp tracker.
2240  */
2241 static void
2242 ice_ptp_release_tx_tracker(struct ice_pf *pf, struct ice_ptp_tx *tx)
2243 {
2244 	tx->init = 0;
2245 
2246 	kthread_cancel_work_sync(&tx->work);
2247 
2248 	ice_ptp_flush_tx_tracker(pf, tx);
2249 
2250 	kfree(tx->tstamps);
2251 	tx->tstamps = NULL;
2252 
2253 	bitmap_free(tx->in_use);
2254 	tx->in_use = NULL;
2255 
2256 	tx->len = 0;
2257 }
2258 
2259 /**
2260  * ice_ptp_init_tx_e822 - Initialize tracking for Tx timestamps
2261  * @pf: Board private structure
2262  * @tx: the Tx tracking structure to initialize
2263  * @port: the port this structure tracks
2264  *
2265  * Initialize the Tx timestamp tracker for this port. For generic MAC devices,
2266  * the timestamp block is shared for all ports in the same quad. To avoid
2267  * ports using the same timestamp index, logically break the block of
2268  * registers into chunks based on the port number.
2269  */
2270 static int
2271 ice_ptp_init_tx_e822(struct ice_pf *pf, struct ice_ptp_tx *tx, u8 port)
2272 {
2273 	tx->quad = port / ICE_PORTS_PER_QUAD;
2274 	tx->quad_offset = tx->quad * INDEX_PER_PORT;
2275 	tx->len = INDEX_PER_PORT;
2276 
2277 	return ice_ptp_alloc_tx_tracker(tx);
2278 }
2279 
2280 /**
2281  * ice_ptp_init_tx_e810 - Initialize tracking for Tx timestamps
2282  * @pf: Board private structure
2283  * @tx: the Tx tracking structure to initialize
2284  *
2285  * Initialize the Tx timestamp tracker for this PF. For E810 devices, each
2286  * port has its own block of timestamps, independent of the other ports.
2287  */
2288 static int
2289 ice_ptp_init_tx_e810(struct ice_pf *pf, struct ice_ptp_tx *tx)
2290 {
2291 	tx->quad = pf->hw.port_info->lport;
2292 	tx->quad_offset = 0;
2293 	tx->len = INDEX_PER_QUAD;
2294 
2295 	return ice_ptp_alloc_tx_tracker(tx);
2296 }
2297 
2298 /**
2299  * ice_ptp_tx_tstamp_cleanup - Cleanup old timestamp requests that got dropped
2300  * @hw: pointer to the hw struct
2301  * @tx: PTP Tx tracker to clean up
2302  *
2303  * Loop through the Tx timestamp requests and see if any of them have been
2304  * waiting for a long time. Discard any SKBs that have been waiting for more
2305  * than 2 seconds. This is long enough to be reasonably sure that the
2306  * timestamp will never be captured. This might happen if the packet gets
2307  * discarded before it reaches the PHY timestamping block.
2308  */
2309 static void ice_ptp_tx_tstamp_cleanup(struct ice_hw *hw, struct ice_ptp_tx *tx)
2310 {
2311 	u8 idx;
2312 
2313 	if (!tx->init)
2314 		return;
2315 
2316 	for_each_set_bit(idx, tx->in_use, tx->len) {
2317 		struct sk_buff *skb;
2318 		u64 raw_tstamp;
2319 
2320 		/* Check if this SKB has been waiting for too long */
2321 		if (time_is_after_jiffies(tx->tstamps[idx].start + 2 * HZ))
2322 			continue;
2323 
2324 		/* Read tstamp to be able to use this register again */
2325 		ice_read_phy_tstamp(hw, tx->quad, idx + tx->quad_offset,
2326 				    &raw_tstamp);
2327 
2328 		spin_lock(&tx->lock);
2329 		skb = tx->tstamps[idx].skb;
2330 		tx->tstamps[idx].skb = NULL;
2331 		clear_bit(idx, tx->in_use);
2332 		spin_unlock(&tx->lock);
2333 
2334 		/* Free the SKB after we've cleared the bit */
2335 		dev_kfree_skb_any(skb);
2336 	}
2337 }
2338 
2339 static void ice_ptp_periodic_work(struct kthread_work *work)
2340 {
2341 	struct ice_ptp *ptp = container_of(work, struct ice_ptp, work.work);
2342 	struct ice_pf *pf = container_of(ptp, struct ice_pf, ptp);
2343 	int err;
2344 
2345 	if (!test_bit(ICE_FLAG_PTP, pf->flags))
2346 		return;
2347 
2348 	err = ice_ptp_update_cached_phctime(pf);
2349 
2350 	ice_ptp_tx_tstamp_cleanup(&pf->hw, &pf->ptp.port.tx);
2351 
2352 	/* Run twice a second or reschedule if phc update failed */
2353 	kthread_queue_delayed_work(ptp->kworker, &ptp->work,
2354 				   msecs_to_jiffies(err ? 10 : 500));
2355 }
2356 
2357 /**
2358  * ice_ptp_reset - Initialize PTP hardware clock support after reset
2359  * @pf: Board private structure
2360  */
2361 void ice_ptp_reset(struct ice_pf *pf)
2362 {
2363 	struct ice_ptp *ptp = &pf->ptp;
2364 	struct ice_hw *hw = &pf->hw;
2365 	struct timespec64 ts;
2366 	int err, itr = 1;
2367 	u64 time_diff;
2368 
2369 	if (test_bit(ICE_PFR_REQ, pf->state))
2370 		goto pfr;
2371 
2372 	if (!hw->func_caps.ts_func_info.src_tmr_owned)
2373 		goto reset_ts;
2374 
2375 	err = ice_ptp_init_phc(hw);
2376 	if (err)
2377 		goto err;
2378 
2379 	/* Acquire the global hardware lock */
2380 	if (!ice_ptp_lock(hw)) {
2381 		err = -EBUSY;
2382 		goto err;
2383 	}
2384 
2385 	/* Write the increment time value to PHY and LAN */
2386 	err = ice_ptp_write_incval(hw, ice_base_incval(pf));
2387 	if (err) {
2388 		ice_ptp_unlock(hw);
2389 		goto err;
2390 	}
2391 
2392 	/* Write the initial Time value to PHY and LAN using the cached PHC
2393 	 * time before the reset and time difference between stopping and
2394 	 * starting the clock.
2395 	 */
2396 	if (ptp->cached_phc_time) {
2397 		time_diff = ktime_get_real_ns() - ptp->reset_time;
2398 		ts = ns_to_timespec64(ptp->cached_phc_time + time_diff);
2399 	} else {
2400 		ts = ktime_to_timespec64(ktime_get_real());
2401 	}
2402 	err = ice_ptp_write_init(pf, &ts);
2403 	if (err) {
2404 		ice_ptp_unlock(hw);
2405 		goto err;
2406 	}
2407 
2408 	/* Release the global hardware lock */
2409 	ice_ptp_unlock(hw);
2410 
2411 	if (!ice_is_e810(hw)) {
2412 		/* Enable quad interrupts */
2413 		err = ice_ptp_tx_ena_intr(pf, true, itr);
2414 		if (err)
2415 			goto err;
2416 	}
2417 
2418 reset_ts:
2419 	/* Restart the PHY timestamping block */
2420 	ice_ptp_reset_phy_timestamping(pf);
2421 
2422 pfr:
2423 	/* Init Tx structures */
2424 	if (ice_is_e810(&pf->hw)) {
2425 		err = ice_ptp_init_tx_e810(pf, &ptp->port.tx);
2426 	} else {
2427 		kthread_init_delayed_work(&ptp->port.ov_work,
2428 					  ice_ptp_wait_for_offset_valid);
2429 		err = ice_ptp_init_tx_e822(pf, &ptp->port.tx,
2430 					   ptp->port.port_num);
2431 	}
2432 	if (err)
2433 		goto err;
2434 
2435 	set_bit(ICE_FLAG_PTP, pf->flags);
2436 
2437 	/* Start periodic work going */
2438 	kthread_queue_delayed_work(ptp->kworker, &ptp->work, 0);
2439 
2440 	dev_info(ice_pf_to_dev(pf), "PTP reset successful\n");
2441 	return;
2442 
2443 err:
2444 	dev_err(ice_pf_to_dev(pf), "PTP reset failed %d\n", err);
2445 }
2446 
2447 /**
2448  * ice_ptp_prepare_for_reset - Prepare PTP for reset
2449  * @pf: Board private structure
2450  */
2451 void ice_ptp_prepare_for_reset(struct ice_pf *pf)
2452 {
2453 	struct ice_ptp *ptp = &pf->ptp;
2454 	u8 src_tmr;
2455 
2456 	clear_bit(ICE_FLAG_PTP, pf->flags);
2457 
2458 	/* Disable timestamping for both Tx and Rx */
2459 	ice_ptp_cfg_timestamp(pf, false);
2460 
2461 	kthread_cancel_delayed_work_sync(&ptp->work);
2462 	kthread_cancel_work_sync(&ptp->extts_work);
2463 
2464 	if (test_bit(ICE_PFR_REQ, pf->state))
2465 		return;
2466 
2467 	ice_ptp_release_tx_tracker(pf, &pf->ptp.port.tx);
2468 
2469 	/* Disable periodic outputs */
2470 	ice_ptp_disable_all_clkout(pf);
2471 
2472 	src_tmr = ice_get_ptp_src_clock_index(&pf->hw);
2473 
2474 	/* Disable source clock */
2475 	wr32(&pf->hw, GLTSYN_ENA(src_tmr), (u32)~GLTSYN_ENA_TSYN_ENA_M);
2476 
2477 	/* Acquire PHC and system timer to restore after reset */
2478 	ptp->reset_time = ktime_get_real_ns();
2479 }
2480 
2481 /**
2482  * ice_ptp_init_owner - Initialize PTP_1588_CLOCK device
2483  * @pf: Board private structure
2484  *
2485  * Setup and initialize a PTP clock device that represents the device hardware
2486  * clock. Save the clock index for other functions connected to the same
2487  * hardware resource.
2488  */
2489 static int ice_ptp_init_owner(struct ice_pf *pf)
2490 {
2491 	struct ice_hw *hw = &pf->hw;
2492 	struct timespec64 ts;
2493 	int err, itr = 1;
2494 
2495 	err = ice_ptp_init_phc(hw);
2496 	if (err) {
2497 		dev_err(ice_pf_to_dev(pf), "Failed to initialize PHC, err %d\n",
2498 			err);
2499 		return err;
2500 	}
2501 
2502 	/* Acquire the global hardware lock */
2503 	if (!ice_ptp_lock(hw)) {
2504 		err = -EBUSY;
2505 		goto err_exit;
2506 	}
2507 
2508 	/* Write the increment time value to PHY and LAN */
2509 	err = ice_ptp_write_incval(hw, ice_base_incval(pf));
2510 	if (err) {
2511 		ice_ptp_unlock(hw);
2512 		goto err_exit;
2513 	}
2514 
2515 	ts = ktime_to_timespec64(ktime_get_real());
2516 	/* Write the initial Time value to PHY and LAN */
2517 	err = ice_ptp_write_init(pf, &ts);
2518 	if (err) {
2519 		ice_ptp_unlock(hw);
2520 		goto err_exit;
2521 	}
2522 
2523 	/* Release the global hardware lock */
2524 	ice_ptp_unlock(hw);
2525 
2526 	if (!ice_is_e810(hw)) {
2527 		/* Enable quad interrupts */
2528 		err = ice_ptp_tx_ena_intr(pf, true, itr);
2529 		if (err)
2530 			goto err_exit;
2531 	}
2532 
2533 	/* Ensure we have a clock device */
2534 	err = ice_ptp_create_clock(pf);
2535 	if (err)
2536 		goto err_clk;
2537 
2538 	/* Store the PTP clock index for other PFs */
2539 	ice_set_ptp_clock_index(pf);
2540 
2541 	return 0;
2542 
2543 err_clk:
2544 	pf->ptp.clock = NULL;
2545 err_exit:
2546 	return err;
2547 }
2548 
2549 /**
2550  * ice_ptp_init_work - Initialize PTP work threads
2551  * @pf: Board private structure
2552  * @ptp: PF PTP structure
2553  */
2554 static int ice_ptp_init_work(struct ice_pf *pf, struct ice_ptp *ptp)
2555 {
2556 	struct kthread_worker *kworker;
2557 
2558 	/* Initialize work functions */
2559 	kthread_init_delayed_work(&ptp->work, ice_ptp_periodic_work);
2560 	kthread_init_work(&ptp->extts_work, ice_ptp_extts_work);
2561 
2562 	/* Allocate a kworker for handling work required for the ports
2563 	 * connected to the PTP hardware clock.
2564 	 */
2565 	kworker = kthread_create_worker(0, "ice-ptp-%s",
2566 					dev_name(ice_pf_to_dev(pf)));
2567 	if (IS_ERR(kworker))
2568 		return PTR_ERR(kworker);
2569 
2570 	ptp->kworker = kworker;
2571 
2572 	/* Start periodic work going */
2573 	kthread_queue_delayed_work(ptp->kworker, &ptp->work, 0);
2574 
2575 	return 0;
2576 }
2577 
2578 /**
2579  * ice_ptp_init_port - Initialize PTP port structure
2580  * @pf: Board private structure
2581  * @ptp_port: PTP port structure
2582  */
2583 static int ice_ptp_init_port(struct ice_pf *pf, struct ice_ptp_port *ptp_port)
2584 {
2585 	mutex_init(&ptp_port->ps_lock);
2586 
2587 	if (ice_is_e810(&pf->hw))
2588 		return ice_ptp_init_tx_e810(pf, &ptp_port->tx);
2589 
2590 	kthread_init_delayed_work(&ptp_port->ov_work,
2591 				  ice_ptp_wait_for_offset_valid);
2592 	return ice_ptp_init_tx_e822(pf, &ptp_port->tx, ptp_port->port_num);
2593 }
2594 
2595 /**
2596  * ice_ptp_init - Initialize PTP hardware clock support
2597  * @pf: Board private structure
2598  *
2599  * Set up the device for interacting with the PTP hardware clock for all
2600  * functions, both the function that owns the clock hardware, and the
2601  * functions connected to the clock hardware.
2602  *
2603  * The clock owner will allocate and register a ptp_clock with the
2604  * PTP_1588_CLOCK infrastructure. All functions allocate a kthread and work
2605  * items used for asynchronous work such as Tx timestamps and periodic work.
2606  */
2607 void ice_ptp_init(struct ice_pf *pf)
2608 {
2609 	struct ice_ptp *ptp = &pf->ptp;
2610 	struct ice_hw *hw = &pf->hw;
2611 	int err;
2612 
2613 	/* If this function owns the clock hardware, it must allocate and
2614 	 * configure the PTP clock device to represent it.
2615 	 */
2616 	if (hw->func_caps.ts_func_info.src_tmr_owned) {
2617 		err = ice_ptp_init_owner(pf);
2618 		if (err)
2619 			goto err;
2620 	}
2621 
2622 	ptp->port.port_num = hw->pf_id;
2623 	err = ice_ptp_init_port(pf, &ptp->port);
2624 	if (err)
2625 		goto err;
2626 
2627 	/* Start the PHY timestamping block */
2628 	ice_ptp_reset_phy_timestamping(pf);
2629 
2630 	set_bit(ICE_FLAG_PTP, pf->flags);
2631 	err = ice_ptp_init_work(pf, ptp);
2632 	if (err)
2633 		goto err;
2634 
2635 	dev_info(ice_pf_to_dev(pf), "PTP init successful\n");
2636 	return;
2637 
2638 err:
2639 	/* If we registered a PTP clock, release it */
2640 	if (pf->ptp.clock) {
2641 		ptp_clock_unregister(ptp->clock);
2642 		pf->ptp.clock = NULL;
2643 	}
2644 	clear_bit(ICE_FLAG_PTP, pf->flags);
2645 	dev_err(ice_pf_to_dev(pf), "PTP failed %d\n", err);
2646 }
2647 
2648 /**
2649  * ice_ptp_release - Disable the driver/HW support and unregister the clock
2650  * @pf: Board private structure
2651  *
2652  * This function handles the cleanup work required from the initialization by
2653  * clearing out the important information and unregistering the clock
2654  */
2655 void ice_ptp_release(struct ice_pf *pf)
2656 {
2657 	if (!test_bit(ICE_FLAG_PTP, pf->flags))
2658 		return;
2659 
2660 	/* Disable timestamping for both Tx and Rx */
2661 	ice_ptp_cfg_timestamp(pf, false);
2662 
2663 	ice_ptp_release_tx_tracker(pf, &pf->ptp.port.tx);
2664 
2665 	clear_bit(ICE_FLAG_PTP, pf->flags);
2666 
2667 	kthread_cancel_delayed_work_sync(&pf->ptp.work);
2668 
2669 	ice_ptp_port_phy_stop(&pf->ptp.port);
2670 	mutex_destroy(&pf->ptp.port.ps_lock);
2671 	if (pf->ptp.kworker) {
2672 		kthread_destroy_worker(pf->ptp.kworker);
2673 		pf->ptp.kworker = NULL;
2674 	}
2675 
2676 	if (!pf->ptp.clock)
2677 		return;
2678 
2679 	/* Disable periodic outputs */
2680 	ice_ptp_disable_all_clkout(pf);
2681 
2682 	ice_clear_ptp_clock_index(pf);
2683 	ptp_clock_unregister(pf->ptp.clock);
2684 	pf->ptp.clock = NULL;
2685 
2686 	dev_info(ice_pf_to_dev(pf), "Removed PTP clock\n");
2687 }
2688