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