1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2024 Intel Corporation. */
3 
4 #include "iavf.h"
5 #include "iavf_ptp.h"
6 
7 #define iavf_clock_to_adapter(info)				\
8 	container_of_const(info, struct iavf_adapter, ptp.info)
9 
10 /**
11  * iavf_ptp_disable_rx_tstamp - Disable timestamping in Rx rings
12  * @adapter: private adapter structure
13  *
14  * Disable timestamp reporting for all Rx rings.
15  */
iavf_ptp_disable_rx_tstamp(struct iavf_adapter * adapter)16 static void iavf_ptp_disable_rx_tstamp(struct iavf_adapter *adapter)
17 {
18 	for (u32 i = 0; i < adapter->num_active_queues; i++)
19 		adapter->rx_rings[i].flags &= ~IAVF_TXRX_FLAGS_HW_TSTAMP;
20 }
21 
22 /**
23  * iavf_ptp_enable_rx_tstamp - Enable timestamping in Rx rings
24  * @adapter: private adapter structure
25  *
26  * Enable timestamp reporting for all Rx rings.
27  */
iavf_ptp_enable_rx_tstamp(struct iavf_adapter * adapter)28 static void iavf_ptp_enable_rx_tstamp(struct iavf_adapter *adapter)
29 {
30 	for (u32 i = 0; i < adapter->num_active_queues; i++)
31 		adapter->rx_rings[i].flags |= IAVF_TXRX_FLAGS_HW_TSTAMP;
32 }
33 
34 /**
35  * iavf_ptp_set_timestamp_mode - Set device timestamping mode
36  * @adapter: private adapter structure
37  * @config: pointer to kernel_hwtstamp_config
38  *
39  * Set the timestamping mode requested from the userspace.
40  *
41  * Note: this function always translates Rx timestamp requests for any packet
42  * category into HWTSTAMP_FILTER_ALL.
43  *
44  * Return: 0 on success, negative error code otherwise.
45  */
iavf_ptp_set_timestamp_mode(struct iavf_adapter * adapter,struct kernel_hwtstamp_config * config)46 static int iavf_ptp_set_timestamp_mode(struct iavf_adapter *adapter,
47 				       struct kernel_hwtstamp_config *config)
48 {
49 	/* Reserved for future extensions. */
50 	if (config->flags)
51 		return -EINVAL;
52 
53 	switch (config->tx_type) {
54 	case HWTSTAMP_TX_OFF:
55 		break;
56 	case HWTSTAMP_TX_ON:
57 		return -EOPNOTSUPP;
58 	default:
59 		return -ERANGE;
60 	}
61 
62 	if (config->rx_filter == HWTSTAMP_FILTER_NONE) {
63 		iavf_ptp_disable_rx_tstamp(adapter);
64 		return 0;
65 	} else if (config->rx_filter > HWTSTAMP_FILTER_NTP_ALL) {
66 		return -ERANGE;
67 	} else if (!(iavf_ptp_cap_supported(adapter,
68 					    VIRTCHNL_1588_PTP_CAP_RX_TSTAMP))) {
69 		return -EOPNOTSUPP;
70 	}
71 
72 	config->rx_filter = HWTSTAMP_FILTER_ALL;
73 	iavf_ptp_enable_rx_tstamp(adapter);
74 
75 	return 0;
76 }
77 
78 /**
79  * iavf_ptp_set_ts_config - Set timestamping configuration
80  * @adapter: private adapter structure
81  * @config: pointer to kernel_hwtstamp_config structure
82  * @extack: pointer to netlink_ext_ack structure
83  *
84  * Program the requested timestamping configuration to the device.
85  *
86  * Return: 0 on success, negative error code otherwise.
87  */
iavf_ptp_set_ts_config(struct iavf_adapter * adapter,struct kernel_hwtstamp_config * config,struct netlink_ext_ack * extack)88 int iavf_ptp_set_ts_config(struct iavf_adapter *adapter,
89 			   struct kernel_hwtstamp_config *config,
90 			   struct netlink_ext_ack *extack)
91 {
92 	int err;
93 
94 	err = iavf_ptp_set_timestamp_mode(adapter, config);
95 	if (err)
96 		return err;
97 
98 	/* Save successful settings for future reference */
99 	adapter->ptp.hwtstamp_config = *config;
100 
101 	return 0;
102 }
103 
104 /**
105  * iavf_ptp_cap_supported - Check if a PTP capability is supported
106  * @adapter: private adapter structure
107  * @cap: the capability bitmask to check
108  *
109  * Return: true if every capability set in cap is also set in the enabled
110  *         capabilities reported by the PF, false otherwise.
111  */
iavf_ptp_cap_supported(const struct iavf_adapter * adapter,u32 cap)112 bool iavf_ptp_cap_supported(const struct iavf_adapter *adapter, u32 cap)
113 {
114 	if (!IAVF_PTP_ALLOWED(adapter))
115 		return false;
116 
117 	/* Only return true if every bit in cap is set in hw_caps.caps */
118 	return (adapter->ptp.hw_caps.caps & cap) == cap;
119 }
120 
121 /**
122  * iavf_allocate_ptp_cmd - Allocate a PTP command message structure
123  * @v_opcode: the virtchnl opcode
124  * @msglen: length in bytes of the associated virtchnl structure
125  *
126  * Allocates a PTP command message and pre-fills it with the provided message
127  * length and opcode.
128  *
129  * Return: allocated PTP command.
130  */
iavf_allocate_ptp_cmd(enum virtchnl_ops v_opcode,u16 msglen)131 static struct iavf_ptp_aq_cmd *iavf_allocate_ptp_cmd(enum virtchnl_ops v_opcode,
132 						     u16 msglen)
133 {
134 	struct iavf_ptp_aq_cmd *cmd;
135 
136 	cmd = kzalloc(struct_size(cmd, msg, msglen), GFP_KERNEL);
137 	if (!cmd)
138 		return NULL;
139 
140 	cmd->v_opcode = v_opcode;
141 	cmd->msglen = msglen;
142 
143 	return cmd;
144 }
145 
146 /**
147  * iavf_queue_ptp_cmd - Queue PTP command for sending over virtchnl
148  * @adapter: private adapter structure
149  * @cmd: the command structure to send
150  *
151  * Queue the given command structure into the PTP virtchnl command queue tos
152  * end to the PF.
153  */
iavf_queue_ptp_cmd(struct iavf_adapter * adapter,struct iavf_ptp_aq_cmd * cmd)154 static void iavf_queue_ptp_cmd(struct iavf_adapter *adapter,
155 			       struct iavf_ptp_aq_cmd *cmd)
156 {
157 	mutex_lock(&adapter->ptp.aq_cmd_lock);
158 	list_add_tail(&cmd->list, &adapter->ptp.aq_cmds);
159 	mutex_unlock(&adapter->ptp.aq_cmd_lock);
160 
161 	adapter->aq_required |= IAVF_FLAG_AQ_SEND_PTP_CMD;
162 	mod_delayed_work(adapter->wq, &adapter->watchdog_task, 0);
163 }
164 
165 /**
166  * iavf_send_phc_read - Send request to read PHC time
167  * @adapter: private adapter structure
168  *
169  * Send a request to obtain the PTP hardware clock time. This allocates the
170  * VIRTCHNL_OP_1588_PTP_GET_TIME message and queues it up to send to
171  * indirectly read the PHC time.
172  *
173  * This function does not wait for the reply from the PF.
174  *
175  * Return: 0 if success, error code otherwise.
176  */
iavf_send_phc_read(struct iavf_adapter * adapter)177 static int iavf_send_phc_read(struct iavf_adapter *adapter)
178 {
179 	struct iavf_ptp_aq_cmd *cmd;
180 
181 	if (!adapter->ptp.clock)
182 		return -EOPNOTSUPP;
183 
184 	cmd = iavf_allocate_ptp_cmd(VIRTCHNL_OP_1588_PTP_GET_TIME,
185 				    sizeof(struct virtchnl_phc_time));
186 	if (!cmd)
187 		return -ENOMEM;
188 
189 	iavf_queue_ptp_cmd(adapter, cmd);
190 
191 	return 0;
192 }
193 
194 /**
195  * iavf_read_phc_indirect - Indirectly read the PHC time via virtchnl
196  * @adapter: private adapter structure
197  * @ts: storage for the timestamp value
198  * @sts: system timestamp values before and after the read
199  *
200  * Used when the device does not have direct register access to the PHC time.
201  * Indirectly reads the time via the VIRTCHNL_OP_1588_PTP_GET_TIME, and waits
202  * for the reply from the PF.
203  *
204  * Based on some simple measurements using ftrace and phc2sys, this clock
205  * access method has about a ~110 usec latency even when the system is not
206  * under load. In order to achieve acceptable results when using phc2sys with
207  * the indirect clock access method, it is recommended to use more
208  * conservative proportional and integration constants with the P/I servo.
209  *
210  * Return: 0 if success, error code otherwise.
211  */
iavf_read_phc_indirect(struct iavf_adapter * adapter,struct timespec64 * ts,struct ptp_system_timestamp * sts)212 static int iavf_read_phc_indirect(struct iavf_adapter *adapter,
213 				  struct timespec64 *ts,
214 				  struct ptp_system_timestamp *sts)
215 {
216 	long ret;
217 	int err;
218 
219 	adapter->ptp.phc_time_ready = false;
220 
221 	ptp_read_system_prets(sts);
222 
223 	err = iavf_send_phc_read(adapter);
224 	if (err)
225 		return err;
226 
227 	ret = wait_event_interruptible_timeout(adapter->ptp.phc_time_waitqueue,
228 					       adapter->ptp.phc_time_ready,
229 					       HZ);
230 
231 	ptp_read_system_postts(sts);
232 
233 	if (ret < 0)
234 		return ret;
235 	else if (!ret)
236 		return -EBUSY;
237 
238 	*ts = ns_to_timespec64(adapter->ptp.cached_phc_time);
239 
240 	return 0;
241 }
242 
iavf_ptp_gettimex64(struct ptp_clock_info * info,struct timespec64 * ts,struct ptp_system_timestamp * sts)243 static int iavf_ptp_gettimex64(struct ptp_clock_info *info,
244 			       struct timespec64 *ts,
245 			       struct ptp_system_timestamp *sts)
246 {
247 	struct iavf_adapter *adapter = iavf_clock_to_adapter(info);
248 
249 	if (!adapter->ptp.clock)
250 		return -EOPNOTSUPP;
251 
252 	return iavf_read_phc_indirect(adapter, ts, sts);
253 }
254 
255 /**
256  * iavf_ptp_cache_phc_time - Cache PHC time for performing timestamp extension
257  * @adapter: private adapter structure
258  *
259  * Periodically cache the PHC time in order to allow for timestamp extension.
260  * This is required because the Tx and Rx timestamps only contain 32bits of
261  * nanoseconds. Timestamp extension allows calculating the corrected 64bit
262  * timestamp. This algorithm relies on the cached time being within ~1 second
263  * of the timestamp.
264  */
iavf_ptp_cache_phc_time(struct iavf_adapter * adapter)265 static void iavf_ptp_cache_phc_time(struct iavf_adapter *adapter)
266 {
267 	if (!time_is_before_jiffies(adapter->ptp.cached_phc_updated + HZ))
268 		return;
269 
270 	/* The response from virtchnl will store the time into
271 	 * cached_phc_time.
272 	 */
273 	iavf_send_phc_read(adapter);
274 }
275 
276 /**
277  * iavf_ptp_do_aux_work - Perform periodic work required for PTP support
278  * @info: PTP clock info structure
279  *
280  * Handler to take care of periodic work required for PTP operation. This
281  * includes the following tasks:
282  *
283  *   1) updating cached_phc_time
284  *
285  *      cached_phc_time is used by the Tx and Rx timestamp flows in order to
286  *      perform timestamp extension, by carefully comparing the timestamp
287  *      32bit nanosecond timestamps and determining the corrected 64bit
288  *      timestamp value to report to userspace. This algorithm only works if
289  *      the cached_phc_time is within ~1 second of the Tx or Rx timestamp
290  *      event. This task periodically reads the PHC time and stores it, to
291  *      ensure that timestamp extension operates correctly.
292  *
293  * Returns: time in jiffies until the periodic task should be re-scheduled.
294  */
iavf_ptp_do_aux_work(struct ptp_clock_info * info)295 static long iavf_ptp_do_aux_work(struct ptp_clock_info *info)
296 {
297 	struct iavf_adapter *adapter = iavf_clock_to_adapter(info);
298 
299 	iavf_ptp_cache_phc_time(adapter);
300 
301 	/* Check work about twice a second */
302 	return msecs_to_jiffies(500);
303 }
304 
305 /**
306  * iavf_ptp_register_clock - Register a new PTP for userspace
307  * @adapter: private adapter structure
308  *
309  * Allocate and register a new PTP clock device if necessary.
310  *
311  * Return: 0 if success, error otherwise.
312  */
iavf_ptp_register_clock(struct iavf_adapter * adapter)313 static int iavf_ptp_register_clock(struct iavf_adapter *adapter)
314 {
315 	struct ptp_clock_info *ptp_info = &adapter->ptp.info;
316 	struct device *dev = &adapter->pdev->dev;
317 	struct ptp_clock *clock;
318 
319 	snprintf(ptp_info->name, sizeof(ptp_info->name), "%s-%s-clk",
320 		 KBUILD_MODNAME, dev_name(dev));
321 	ptp_info->owner = THIS_MODULE;
322 	ptp_info->gettimex64 = iavf_ptp_gettimex64;
323 	ptp_info->do_aux_work = iavf_ptp_do_aux_work;
324 
325 	clock = ptp_clock_register(ptp_info, dev);
326 	if (IS_ERR(clock))
327 		return PTR_ERR(clock);
328 
329 	adapter->ptp.clock = clock;
330 
331 	dev_dbg(&adapter->pdev->dev, "PTP clock %s registered\n",
332 		adapter->ptp.info.name);
333 
334 	return 0;
335 }
336 
337 /**
338  * iavf_ptp_init - Initialize PTP support if capability was negotiated
339  * @adapter: private adapter structure
340  *
341  * Initialize PTP functionality, based on the capabilities that the PF has
342  * enabled for this VF.
343  */
iavf_ptp_init(struct iavf_adapter * adapter)344 void iavf_ptp_init(struct iavf_adapter *adapter)
345 {
346 	int err;
347 
348 	if (!iavf_ptp_cap_supported(adapter, VIRTCHNL_1588_PTP_CAP_READ_PHC)) {
349 		pci_notice(adapter->pdev,
350 			   "Device does not have PTP clock support\n");
351 		return;
352 	}
353 
354 	err = iavf_ptp_register_clock(adapter);
355 	if (err) {
356 		pci_err(adapter->pdev,
357 			"Failed to register PTP clock device (%p)\n",
358 			ERR_PTR(err));
359 		return;
360 	}
361 
362 	for (int i = 0; i < adapter->num_active_queues; i++) {
363 		struct iavf_ring *rx_ring = &adapter->rx_rings[i];
364 
365 		rx_ring->ptp = &adapter->ptp;
366 	}
367 
368 	ptp_schedule_worker(adapter->ptp.clock, 0);
369 }
370 
371 /**
372  * iavf_ptp_release - Disable PTP support
373  * @adapter: private adapter structure
374  *
375  * Release all PTP resources that were previously initialized.
376  */
iavf_ptp_release(struct iavf_adapter * adapter)377 void iavf_ptp_release(struct iavf_adapter *adapter)
378 {
379 	struct iavf_ptp_aq_cmd *cmd, *tmp;
380 
381 	if (!adapter->ptp.clock)
382 		return;
383 
384 	pci_dbg(adapter->pdev, "removing PTP clock %s\n",
385 		adapter->ptp.info.name);
386 	ptp_clock_unregister(adapter->ptp.clock);
387 	adapter->ptp.clock = NULL;
388 
389 	/* Cancel any remaining uncompleted PTP clock commands */
390 	mutex_lock(&adapter->ptp.aq_cmd_lock);
391 	list_for_each_entry_safe(cmd, tmp, &adapter->ptp.aq_cmds, list) {
392 		list_del(&cmd->list);
393 		kfree(cmd);
394 	}
395 	adapter->aq_required &= ~IAVF_FLAG_AQ_SEND_PTP_CMD;
396 	mutex_unlock(&adapter->ptp.aq_cmd_lock);
397 
398 	adapter->ptp.hwtstamp_config.rx_filter = HWTSTAMP_FILTER_NONE;
399 	iavf_ptp_disable_rx_tstamp(adapter);
400 }
401 
402 /**
403  * iavf_ptp_process_caps - Handle change in PTP capabilities
404  * @adapter: private adapter structure
405  *
406  * Handle any state changes necessary due to change in PTP capabilities, such
407  * as after a device reset or change in configuration from the PF.
408  */
iavf_ptp_process_caps(struct iavf_adapter * adapter)409 void iavf_ptp_process_caps(struct iavf_adapter *adapter)
410 {
411 	bool phc = iavf_ptp_cap_supported(adapter, VIRTCHNL_1588_PTP_CAP_READ_PHC);
412 
413 	/* Check if the device gained or lost necessary access to support the
414 	 * PTP hardware clock. If so, driver must respond appropriately by
415 	 * creating or destroying the PTP clock device.
416 	 */
417 	if (adapter->ptp.clock && !phc)
418 		iavf_ptp_release(adapter);
419 	else if (!adapter->ptp.clock && phc)
420 		iavf_ptp_init(adapter);
421 
422 	/* Check if the device lost access to Rx timestamp incoming packets */
423 	if (!iavf_ptp_cap_supported(adapter, VIRTCHNL_1588_PTP_CAP_RX_TSTAMP)) {
424 		adapter->ptp.hwtstamp_config.rx_filter = HWTSTAMP_FILTER_NONE;
425 		iavf_ptp_disable_rx_tstamp(adapter);
426 	}
427 }
428 
429 /**
430  * iavf_ptp_extend_32b_timestamp - Convert a 32b nanoseconds timestamp to 64b
431  * nanoseconds
432  * @cached_phc_time: recently cached copy of PHC time
433  * @in_tstamp: Ingress/egress 32b nanoseconds timestamp value
434  *
435  * Hardware captures timestamps which contain only 32 bits of nominal
436  * nanoseconds, as opposed to the 64bit timestamps that the stack expects.
437  *
438  * Extend the 32bit nanosecond timestamp using the following algorithm and
439  * assumptions:
440  *
441  * 1) have a recently cached copy of the PHC time
442  * 2) assume that the in_tstamp was captured 2^31 nanoseconds (~2.1
443  *    seconds) before or after the PHC time was captured.
444  * 3) calculate the delta between the cached time and the timestamp
445  * 4) if the delta is smaller than 2^31 nanoseconds, then the timestamp was
446  *    captured after the PHC time. In this case, the full timestamp is just
447  *    the cached PHC time plus the delta.
448  * 5) otherwise, if the delta is larger than 2^31 nanoseconds, then the
449  *    timestamp was captured *before* the PHC time, i.e. because the PHC
450  *    cache was updated after the timestamp was captured by hardware. In this
451  *    case, the full timestamp is the cached time minus the inverse delta.
452  *
453  * This algorithm works even if the PHC time was updated after a Tx timestamp
454  * was requested, but before the Tx timestamp event was reported from
455  * hardware.
456  *
457  * This calculation primarily relies on keeping the cached PHC time up to
458  * date. If the timestamp was captured more than 2^31 nanoseconds after the
459  * PHC time, it is possible that the lower 32bits of PHC time have
460  * overflowed more than once, and we might generate an incorrect timestamp.
461  *
462  * This is prevented by (a) periodically updating the cached PHC time once
463  * a second, and (b) discarding any Tx timestamp packet if it has waited for
464  * a timestamp for more than one second.
465  *
466  * Return: extended timestamp (to 64b).
467  */
iavf_ptp_extend_32b_timestamp(u64 cached_phc_time,u32 in_tstamp)468 u64 iavf_ptp_extend_32b_timestamp(u64 cached_phc_time, u32 in_tstamp)
469 {
470 	u32 low = lower_32_bits(cached_phc_time);
471 	u32 delta = in_tstamp - low;
472 	u64 ns;
473 
474 	/* Do not assume that the in_tstamp is always more recent than the
475 	 * cached PHC time. If the delta is large, it indicates that the
476 	 * in_tstamp was taken in the past, and should be converted
477 	 * forward.
478 	 */
479 	if (delta > S32_MAX)
480 		ns = cached_phc_time - (low - in_tstamp);
481 	else
482 		ns = cached_phc_time + delta;
483 
484 	return ns;
485 }
486