ptp.c 53.1 KB
Newer Older
1
/****************************************************************************
B
Ben Hutchings 已提交
2 3
 * Driver for Solarflare network controllers and boards
 * Copyright 2011-2013 Solarflare Communications Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation, incorporated herein by reference.
 */

/* Theory of operation:
 *
 * PTP support is assisted by firmware running on the MC, which provides
 * the hardware timestamping capabilities.  Both transmitted and received
 * PTP event packets are queued onto internal queues for subsequent processing;
 * this is because the MC operations are relatively long and would block
 * block NAPI/interrupt operation.
 *
 * Receive event processing:
 *	The event contains the packet's UUID and sequence number, together
 *	with the hardware timestamp.  The PTP receive packet queue is searched
 *	for this UUID/sequence number and, if found, put on a pending queue.
 *	Packets not matching are delivered without timestamps (MCDI events will
 *	always arrive after the actual packet).
 *	It is important for the operation of the PTP protocol that the ordering
 *	of packets between the event and general port is maintained.
 *
 * Work queue processing:
 *	If work waiting, synchronise host/hardware time
 *
 *	Transmit: send packet through MC, which returns the transmission time
 *	that is converted to an appropriate timestamp.
 *
 *	Receive: the packet's reception time is converted to an appropriate
 *	timestamp.
 */
#include <linux/ip.h>
#include <linux/udp.h>
#include <linux/time.h>
#include <linux/ktime.h>
#include <linux/module.h>
#include <linux/net_tstamp.h>
#include <linux/pps_kernel.h>
#include <linux/ptp_clock_kernel.h>
#include "net_driver.h"
#include "efx.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
#include "io.h"
49
#include "farch_regs.h"
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#include "nic.h"

/* Maximum number of events expected to make up a PTP event */
#define	MAX_EVENT_FRAGS			3

/* Maximum delay, ms, to begin synchronisation */
#define	MAX_SYNCHRONISE_WAIT_MS		2

/* How long, at most, to spend synchronising */
#define	SYNCHRONISE_PERIOD_NS		250000

/* How often to update the shared memory time */
#define	SYNCHRONISATION_GRANULARITY_NS	200

/* Minimum permitted length of a (corrected) synchronisation time */
65
#define	DEFAULT_MIN_SYNCHRONISATION_NS	120
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

/* Maximum permitted length of a (corrected) synchronisation time */
#define	MAX_SYNCHRONISATION_NS		1000

/* How many (MC) receive events that can be queued */
#define	MAX_RECEIVE_EVENTS		8

/* Length of (modified) moving average. */
#define	AVERAGE_LENGTH			16

/* How long an unmatched event or packet can be held */
#define PKT_EVENT_LIFETIME_MS		10

/* Offsets into PTP packet for identification.  These offsets are from the
 * start of the IP header, not the MAC header.  Note that neither PTP V1 nor
 * PTP V2 permit the use of IPV4 options.
 */
#define PTP_DPORT_OFFSET	22

#define PTP_V1_VERSION_LENGTH	2
#define PTP_V1_VERSION_OFFSET	28

#define PTP_V1_UUID_LENGTH	6
#define PTP_V1_UUID_OFFSET	50

#define PTP_V1_SEQUENCE_LENGTH	2
#define PTP_V1_SEQUENCE_OFFSET	58

/* The minimum length of a PTP V1 packet for offsets, etc. to be valid:
 * includes IP header.
 */
#define	PTP_V1_MIN_LENGTH	64

#define PTP_V2_VERSION_LENGTH	1
#define PTP_V2_VERSION_OFFSET	29

102 103 104
#define PTP_V2_UUID_LENGTH	8
#define PTP_V2_UUID_OFFSET	48

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
/* Although PTP V2 UUIDs are comprised a ClockIdentity (8) and PortNumber (2),
 * the MC only captures the last six bytes of the clock identity. These values
 * reflect those, not the ones used in the standard.  The standard permits
 * mapping of V1 UUIDs to V2 UUIDs with these same values.
 */
#define PTP_V2_MC_UUID_LENGTH	6
#define PTP_V2_MC_UUID_OFFSET	50

#define PTP_V2_SEQUENCE_LENGTH	2
#define PTP_V2_SEQUENCE_OFFSET	58

/* The minimum length of a PTP V2 packet for offsets, etc. to be valid:
 * includes IP header.
 */
#define	PTP_V2_MIN_LENGTH	63

#define	PTP_MIN_LENGTH		63

#define PTP_ADDRESS		0xe0000181	/* 224.0.1.129 */
#define PTP_EVENT_PORT		319
#define PTP_GENERAL_PORT	320

/* Annoyingly the format of the version numbers are different between
 * versions 1 and 2 so it isn't possible to simply look for 1 or 2.
 */
#define	PTP_VERSION_V1		1

#define	PTP_VERSION_V2		2
#define	PTP_VERSION_V2_MASK	0x0f

enum ptp_packet_state {
	PTP_PACKET_STATE_UNMATCHED = 0,
	PTP_PACKET_STATE_MATCHED,
	PTP_PACKET_STATE_TIMED_OUT,
	PTP_PACKET_STATE_MATCH_UNWANTED
};

/* NIC synchronised with single word of time only comprising
 * partial seconds and full nanoseconds: 10^9 ~ 2^30 so 2 bits for seconds.
 */
#define	MC_NANOSECOND_BITS	30
#define	MC_NANOSECOND_MASK	((1 << MC_NANOSECOND_BITS) - 1)
#define	MC_SECOND_MASK		((1 << (32 - MC_NANOSECOND_BITS)) - 1)

/* Maximum parts-per-billion adjustment that is acceptable */
#define MAX_PPB			1000000

/* Number of bits required to hold the above */
#define	MAX_PPB_BITS		20

/* Number of extra bits allowed when calculating fractional ns.
 * EXTRA_BITS + MC_CMD_PTP_IN_ADJUST_BITS + MAX_PPB_BITS should
 * be less than 63.
 */
#define	PPB_EXTRA_BITS		2

/* Precalculate scale word to avoid long long division at runtime */
#define	PPB_SCALE_WORD	((1LL << (PPB_EXTRA_BITS + MC_CMD_PTP_IN_ADJUST_BITS +\
			MAX_PPB_BITS)) / 1000000000LL)

#define PTP_SYNC_ATTEMPTS	4

/**
 * struct efx_ptp_match - Matching structure, stored in sk_buff's cb area.
 * @words: UUID and (partial) sequence number
 * @expiry: Time after which the packet should be delivered irrespective of
 *            event arrival.
 * @state: The state of the packet - whether it is ready for processing or
 *         whether that is of no interest.
 */
struct efx_ptp_match {
	u32 words[DIV_ROUND_UP(PTP_V1_UUID_LENGTH, 4)];
	unsigned long expiry;
	enum ptp_packet_state state;
};

/**
 * struct efx_ptp_event_rx - A PTP receive event (from MC)
 * @seq0: First part of (PTP) UUID
 * @seq1: Second part of (PTP) UUID and sequence number
 * @hwtimestamp: Event timestamp
 */
struct efx_ptp_event_rx {
	struct list_head link;
	u32 seq0;
	u32 seq1;
	ktime_t hwtimestamp;
	unsigned long expiry;
};

/**
 * struct efx_ptp_timeset - Synchronisation between host and MC
 * @host_start: Host time immediately before hardware timestamp taken
198 199
 * @major: Hardware timestamp, major
 * @minor: Hardware timestamp, minor
200
 * @host_end: Host time immediately after hardware timestamp taken
201
 * @wait: Number of NIC clock ticks between hardware timestamp being read and
202 203 204 205 206 207
 *          host end time being seen
 * @window: Difference of host_end and host_start
 * @valid: Whether this timeset is valid
 */
struct efx_ptp_timeset {
	u32 host_start;
208 209
	u32 major;
	u32 minor;
210
	u32 host_end;
211
	u32 wait;
212 213 214 215 216
	u32 window;	/* Derived: end - start, allowing for wrap */
};

/**
 * struct efx_ptp_data - Precision Time Protocol (PTP) state
217 218
 * @efx: The NIC context
 * @channel: The PTP channel (Siena only)
219 220
 * @rx_ts_inline: Flag for whether RX timestamps are inline (else they are
 *	separate events)
221 222 223 224 225
 * @rxq: Receive queue (awaiting timestamps)
 * @txq: Transmit queue
 * @evt_list: List of MC receive events awaiting packets
 * @evt_free_list: List of free events
 * @evt_lock: Lock for manipulating evt_list and evt_free_list
226
 * @evt_overflow: Boolean indicating that event list has overflowed
227 228 229 230 231 232 233 234 235 236
 * @rx_evts: Instantiated events (on evt_list and evt_free_list)
 * @workwq: Work queue for processing pending PTP operations
 * @work: Work task
 * @reset_required: A serious error has occurred and the PTP task needs to be
 *                  reset (disable, enable).
 * @rxfilter_event: Receive filter when operating
 * @rxfilter_general: Receive filter when operating
 * @config: Current timestamp configuration
 * @enabled: PTP operation enabled
 * @mode: Mode in which PTP operating (PTP version)
237 238 239 240 241 242 243 244
 * @time_format: Time format supported by this NIC
 * @ns_to_nic_time: Function to convert from scalar nanoseconds to NIC time
 * @nic_to_kernel_time: Function to convert from NIC to kernel time
 * @min_synchronisation_ns: Minimum acceptable corrected sync window
 * @ts_corrections.tx: Required driver correction of transmit timestamps
 * @ts_corrections.rx: Required driver correction of receive timestamps
 * @ts_corrections.pps_out: PPS output error (information only)
 * @ts_corrections.pps_in: Required driver correction of PPS input timestamps
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
 * @evt_frags: Partly assembled PTP events
 * @evt_frag_idx: Current fragment number
 * @evt_code: Last event code
 * @start: Address at which MC indicates ready for synchronisation
 * @host_time_pps: Host time at last PPS
 * @current_adjfreq: Current ppb adjustment.
 * @phc_clock: Pointer to registered phc device
 * @phc_clock_info: Registration structure for phc device
 * @pps_work: pps work task for handling pps events
 * @pps_workwq: pps work queue
 * @nic_ts_enabled: Flag indicating if NIC generated TS events are handled
 * @txbuf: Buffer for use when transmitting (PTP) packets to MC (avoids
 *         allocations in main data path).
 * @timeset: Last set of synchronisation statistics.
 */
struct efx_ptp_data {
261
	struct efx_nic *efx;
262
	struct efx_channel *channel;
263
	bool rx_ts_inline;
264 265 266 267 268
	struct sk_buff_head rxq;
	struct sk_buff_head txq;
	struct list_head evt_list;
	struct list_head evt_free_list;
	spinlock_t evt_lock;
269
	bool evt_overflow;
270 271 272 273 274 275 276 277 278 279
	struct efx_ptp_event_rx rx_evts[MAX_RECEIVE_EVENTS];
	struct workqueue_struct *workwq;
	struct work_struct work;
	bool reset_required;
	u32 rxfilter_event;
	u32 rxfilter_general;
	bool rxfilter_installed;
	struct hwtstamp_config config;
	bool enabled;
	unsigned int mode;
280 281 282 283 284 285 286 287 288 289 290
	unsigned int time_format;
	void (*ns_to_nic_time)(s64 ns, u32 *nic_major, u32 *nic_minor);
	ktime_t (*nic_to_kernel_time)(u32 nic_major, u32 nic_minor,
				      s32 correction);
	unsigned int min_synchronisation_ns;
	struct {
		s32 tx;
		s32 rx;
		s32 pps_out;
		s32 pps_in;
	} ts_corrections;
291 292 293 294 295 296 297 298 299 300 301
	efx_qword_t evt_frags[MAX_EVENT_FRAGS];
	int evt_frag_idx;
	int evt_code;
	struct efx_buffer start;
	struct pps_event_time host_time_pps;
	s64 current_adjfreq;
	struct ptp_clock *phc_clock;
	struct ptp_clock_info phc_clock_info;
	struct work_struct pps_work;
	struct workqueue_struct *pps_workwq;
	bool nic_ts_enabled;
302
	MCDI_DECLARE_BUF(txbuf, MC_CMD_PTP_IN_TRANSMIT_LENMAX);
303 304 305 306 307 308 309 310 311 312 313 314
	struct efx_ptp_timeset
	timeset[MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_MAXNUM];
};

static int efx_phc_adjfreq(struct ptp_clock_info *ptp, s32 delta);
static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta);
static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec *ts);
static int efx_phc_settime(struct ptp_clock_info *ptp,
			   const struct timespec *e_ts);
static int efx_phc_enable(struct ptp_clock_info *ptp,
			  struct ptp_clock_request *request, int on);

315 316 317 318 319 320 321 322
/* For Siena platforms NIC time is s and ns */
static void efx_ptp_ns_to_s_ns(s64 ns, u32 *nic_major, u32 *nic_minor)
{
	struct timespec ts = ns_to_timespec(ns);
	*nic_major = ts.tv_sec;
	*nic_minor = ts.tv_nsec;
}

323 324
static ktime_t efx_ptp_s_ns_to_ktime_correction(u32 nic_major, u32 nic_minor,
						s32 correction)
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
{
	ktime_t kt = ktime_set(nic_major, nic_minor);
	if (correction >= 0)
		kt = ktime_add_ns(kt, (u64)correction);
	else
		kt = ktime_sub_ns(kt, (u64)-correction);
	return kt;
}

/* To convert from s27 format to ns we multiply then divide by a power of 2.
 * For the conversion from ns to s27, the operation is also converted to a
 * multiply and shift.
 */
#define S27_TO_NS_SHIFT	(27)
#define NS_TO_S27_MULT	(((1ULL << 63) + NSEC_PER_SEC / 2) / NSEC_PER_SEC)
#define NS_TO_S27_SHIFT	(63 - S27_TO_NS_SHIFT)
#define S27_MINOR_MAX	(1 << S27_TO_NS_SHIFT)

/* For Huntington platforms NIC time is in seconds and fractions of a second
 * where the minor register only uses 27 bits in units of 2^-27s.
 */
static void efx_ptp_ns_to_s27(s64 ns, u32 *nic_major, u32 *nic_minor)
{
	struct timespec ts = ns_to_timespec(ns);
	u32 maj = ts.tv_sec;
	u32 min = (u32)(((u64)ts.tv_nsec * NS_TO_S27_MULT +
			 (1ULL << (NS_TO_S27_SHIFT - 1))) >> NS_TO_S27_SHIFT);

	/* The conversion can result in the minor value exceeding the maximum.
	 * In this case, round up to the next second.
	 */
	if (min >= S27_MINOR_MAX) {
		min -= S27_MINOR_MAX;
		maj++;
	}

	*nic_major = maj;
	*nic_minor = min;
}

365
static inline ktime_t efx_ptp_s27_to_ktime(u32 nic_major, u32 nic_minor)
366
{
367 368 369 370
	u32 ns = (u32)(((u64)nic_minor * NSEC_PER_SEC +
			(1ULL << (S27_TO_NS_SHIFT - 1))) >> S27_TO_NS_SHIFT);
	return ktime_set(nic_major, ns);
}
371

372 373 374
static ktime_t efx_ptp_s27_to_ktime_correction(u32 nic_major, u32 nic_minor,
					       s32 correction)
{
375 376 377 378 379 380 381 382 383 384
	/* Apply the correction and deal with carry */
	nic_minor += correction;
	if ((s32)nic_minor < 0) {
		nic_minor += S27_MINOR_MAX;
		nic_major--;
	} else if (nic_minor >= S27_MINOR_MAX) {
		nic_minor -= S27_MINOR_MAX;
		nic_major++;
	}

385
	return efx_ptp_s27_to_ktime(nic_major, nic_minor);
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
}

/* Get PTP attributes and set up time conversions */
static int efx_ptp_get_attributes(struct efx_nic *efx)
{
	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_GET_ATTRIBUTES_LEN);
	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_GET_ATTRIBUTES_LEN);
	struct efx_ptp_data *ptp = efx->ptp_data;
	int rc;
	u32 fmt;
	size_t out_len;

	/* Get the PTP attributes. If the NIC doesn't support the operation we
	 * use the default format for compatibility with older NICs i.e.
	 * seconds and nanoseconds.
	 */
	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_GET_ATTRIBUTES);
	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
			  outbuf, sizeof(outbuf), &out_len);
	if (rc == 0)
		fmt = MCDI_DWORD(outbuf, PTP_OUT_GET_ATTRIBUTES_TIME_FORMAT);
	else if (rc == -EINVAL)
		fmt = MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_NANOSECONDS;
	else
		return rc;

	if (fmt == MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_27FRACTION) {
		ptp->ns_to_nic_time = efx_ptp_ns_to_s27;
415
		ptp->nic_to_kernel_time = efx_ptp_s27_to_ktime_correction;
416 417
	} else if (fmt == MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_NANOSECONDS) {
		ptp->ns_to_nic_time = efx_ptp_ns_to_s_ns;
418
		ptp->nic_to_kernel_time = efx_ptp_s_ns_to_ktime_correction;
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
	} else {
		return -ERANGE;
	}

	ptp->time_format = fmt;

	/* MC_CMD_PTP_OP_GET_ATTRIBUTES is an extended version of an older
	 * operation MC_CMD_PTP_OP_GET_TIME_FORMAT that also returns a value
	 * to use for the minimum acceptable corrected synchronization window.
	 * If we have the extra information store it. For older firmware that
	 * does not implement the extended command use the default value.
	 */
	if (rc == 0 && out_len >= MC_CMD_PTP_OUT_GET_ATTRIBUTES_LEN)
		ptp->min_synchronisation_ns =
			MCDI_DWORD(outbuf,
				   PTP_OUT_GET_ATTRIBUTES_SYNC_WINDOW_MIN);
	else
		ptp->min_synchronisation_ns = DEFAULT_MIN_SYNCHRONISATION_NS;

	return 0;
}

/* Get PTP timestamp corrections */
static int efx_ptp_get_timestamp_corrections(struct efx_nic *efx)
{
	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_GET_TIMESTAMP_CORRECTIONS_LEN);
	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_GET_TIMESTAMP_CORRECTIONS_LEN);
	int rc;

	/* Get the timestamp corrections from the NIC. If this operation is
	 * not supported (older NICs) then no correction is required.
	 */
	MCDI_SET_DWORD(inbuf, PTP_IN_OP,
		       MC_CMD_PTP_OP_GET_TIMESTAMP_CORRECTIONS);
	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);

	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
			  outbuf, sizeof(outbuf), NULL);
	if (rc == 0) {
		efx->ptp_data->ts_corrections.tx = MCDI_DWORD(outbuf,
			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_TRANSMIT);
		efx->ptp_data->ts_corrections.rx = MCDI_DWORD(outbuf,
			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_RECEIVE);
		efx->ptp_data->ts_corrections.pps_out = MCDI_DWORD(outbuf,
			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_PPS_OUT);
		efx->ptp_data->ts_corrections.pps_in = MCDI_DWORD(outbuf,
			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_PPS_IN);
	} else if (rc == -EINVAL) {
		efx->ptp_data->ts_corrections.tx = 0;
		efx->ptp_data->ts_corrections.rx = 0;
		efx->ptp_data->ts_corrections.pps_out = 0;
		efx->ptp_data->ts_corrections.pps_in = 0;
	} else {
		return rc;
	}

	return 0;
}

478 479 480
/* Enable MCDI PTP support. */
static int efx_ptp_enable(struct efx_nic *efx)
{
481
	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ENABLE_LEN);
E
Edward Cree 已提交
482 483
	MCDI_DECLARE_BUF_OUT_OR_ERR(outbuf, 0);
	int rc;
484 485

	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ENABLE);
486
	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
487
	MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_QUEUE,
488 489
		       efx->ptp_data->channel ?
		       efx->ptp_data->channel->channel : 0);
490 491
	MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_MODE, efx->ptp_data->mode);

E
Edward Cree 已提交
492 493 494 495 496 497 498 499
	rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
				outbuf, sizeof(outbuf), NULL);
	rc = (rc == -EALREADY) ? 0 : rc;
	if (rc)
		efx_mcdi_display_error(efx, MC_CMD_PTP,
				       MC_CMD_PTP_IN_ENABLE_LEN,
				       outbuf, sizeof(outbuf), rc);
	return rc;
500 501 502 503 504 505 506 507 508
}

/* Disable MCDI PTP support.
 *
 * Note that this function should never rely on the presence of ptp_data -
 * may be called before that exists.
 */
static int efx_ptp_disable(struct efx_nic *efx)
{
509
	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_DISABLE_LEN);
E
Edward Cree 已提交
510 511
	MCDI_DECLARE_BUF_OUT_OR_ERR(outbuf, 0);
	int rc;
512 513

	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_DISABLE);
514
	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
E
Edward Cree 已提交
515 516 517 518 519 520 521 522
	rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
				outbuf, sizeof(outbuf), NULL);
	rc = (rc == -EALREADY) ? 0 : rc;
	if (rc)
		efx_mcdi_display_error(efx, MC_CMD_PTP,
				       MC_CMD_PTP_IN_DISABLE_LEN,
				       outbuf, sizeof(outbuf), rc);
	return rc;
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
}

static void efx_ptp_deliver_rx_queue(struct sk_buff_head *q)
{
	struct sk_buff *skb;

	while ((skb = skb_dequeue(q))) {
		local_bh_disable();
		netif_receive_skb(skb);
		local_bh_enable();
	}
}

static void efx_ptp_handle_no_channel(struct efx_nic *efx)
{
	netif_err(efx, drv, efx->net_dev,
		  "ERROR: PTP requires MSI-X and 1 additional interrupt"
		  "vector. PTP disabled\n");
}

/* Repeatedly send the host time to the MC which will capture the hardware
 * time.
 */
static void efx_ptp_send_times(struct efx_nic *efx,
			       struct pps_event_time *last_time)
{
	struct pps_event_time now;
	struct timespec limit;
	struct efx_ptp_data *ptp = efx->ptp_data;
	struct timespec start;
	int *mc_running = ptp->start.addr;

	pps_get_ts(&now);
	start = now.ts_real;
	limit = now.ts_real;
	timespec_add_ns(&limit, SYNCHRONISE_PERIOD_NS);

	/* Write host time for specified period or until MC is done */
	while ((timespec_compare(&now.ts_real, &limit) < 0) &&
	       ACCESS_ONCE(*mc_running)) {
		struct timespec update_time;
		unsigned int host_time;

		/* Don't update continuously to avoid saturating the PCIe bus */
		update_time = now.ts_real;
		timespec_add_ns(&update_time, SYNCHRONISATION_GRANULARITY_NS);
		do {
			pps_get_ts(&now);
		} while ((timespec_compare(&now.ts_real, &update_time) < 0) &&
			 ACCESS_ONCE(*mc_running));

		/* Synchronise NIC with single word of time only */
		host_time = (now.ts_real.tv_sec << MC_NANOSECOND_BITS |
			     now.ts_real.tv_nsec);
		/* Update host time in NIC memory */
578
		efx->type->ptp_write_host_time(efx, host_time);
579 580 581 582 583
	}
	*last_time = now;
}

/* Read a timeset from the MC's results and partial process. */
584 585
static void efx_ptp_read_timeset(MCDI_DECLARE_STRUCT_PTR(data),
				 struct efx_ptp_timeset *timeset)
586 587 588 589
{
	unsigned start_ns, end_ns;

	timeset->host_start = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTSTART);
590 591
	timeset->major = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_MAJOR);
	timeset->minor = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_MINOR);
592
	timeset->host_end = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTEND),
593
	timeset->wait = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_WAITNS);
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612

	/* Ignore seconds */
	start_ns = timeset->host_start & MC_NANOSECOND_MASK;
	end_ns = timeset->host_end & MC_NANOSECOND_MASK;
	/* Allow for rollover */
	if (end_ns < start_ns)
		end_ns += NSEC_PER_SEC;
	/* Determine duration of operation */
	timeset->window = end_ns - start_ns;
}

/* Process times received from MC.
 *
 * Extract times from returned results, and establish the minimum value
 * seen.  The minimum value represents the "best" possible time and events
 * too much greater than this are rejected - the machine is, perhaps, too
 * busy. A number of readings are taken so that, hopefully, at least one good
 * synchronisation will be seen in the results.
 */
613 614 615 616
static int
efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),
		      size_t response_length,
		      const struct pps_event_time *last_time)
617
{
618 619 620
	unsigned number_readings =
		MCDI_VAR_ARRAY_LEN(response_length,
				   PTP_OUT_SYNCHRONIZE_TIMESET);
621 622 623 624 625 626 627
	unsigned i;
	unsigned ngood = 0;
	unsigned last_good = 0;
	struct efx_ptp_data *ptp = efx->ptp_data;
	u32 last_sec;
	u32 start_sec;
	struct timespec delta;
628
	ktime_t mc_time;
629 630 631 632

	if (number_readings == 0)
		return -EAGAIN;

633 634 635 636
	/* Read the set of results and find the last good host-MC
	 * synchronization result. The MC times when it finishes reading the
	 * host time so the corrected window time should be fairly constant
	 * for a given platform.
637 638
	 */
	for (i = 0; i < number_readings; i++) {
639
		s32 window, corrected;
640
		struct timespec wait;
641

642 643 644 645
		efx_ptp_read_timeset(
			MCDI_ARRAY_STRUCT_PTR(synch_buf,
					      PTP_OUT_SYNCHRONIZE_TIMESET, i),
			&ptp->timeset[i]);
646

647 648
		wait = ktime_to_timespec(
			ptp->nic_to_kernel_time(0, ptp->timeset[i].wait, 0));
649
		window = ptp->timeset[i].window;
650
		corrected = window - wait.tv_nsec;
651 652 653 654 655 656 657 658 659 660 661 662

		/* We expect the uncorrected synchronization window to be at
		 * least as large as the interval between host start and end
		 * times. If it is smaller than this then this is mostly likely
		 * to be a consequence of the host's time being adjusted.
		 * Check that the corrected sync window is in a reasonable
		 * range. If it is out of range it is likely to be because an
		 * interrupt or other delay occurred between reading the system
		 * time and writing it to MC memory.
		 */
		if (window >= SYNCHRONISATION_GRANULARITY_NS &&
		    corrected < MAX_SYNCHRONISATION_NS &&
663
		    corrected >= ptp->min_synchronisation_ns) {
664 665
			ngood++;
			last_good = i;
666
		}
667
	}
668 669 670

	if (ngood == 0) {
		netif_warn(efx, drv, efx->net_dev,
671
			   "PTP no suitable synchronisations\n");
672 673 674
		return -EAGAIN;
	}

675 676 677 678 679 680
	/* Convert the NIC time into kernel time. No correction is required-
	 * this time is the output of a firmware process.
	 */
	mc_time = ptp->nic_to_kernel_time(ptp->timeset[last_good].major,
					  ptp->timeset[last_good].minor, 0);

681
	/* Calculate delay from actual PPS to last_time */
682 683
	delta = ktime_to_timespec(mc_time);
	delta.tv_nsec +=
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
		last_time->ts_real.tv_nsec -
		(ptp->timeset[last_good].host_start & MC_NANOSECOND_MASK);

	/* It is possible that the seconds rolled over between taking
	 * the start reading and the last value written by the host.  The
	 * timescales are such that a gap of more than one second is never
	 * expected.
	 */
	start_sec = ptp->timeset[last_good].host_start >> MC_NANOSECOND_BITS;
	last_sec = last_time->ts_real.tv_sec & MC_SECOND_MASK;
	if (start_sec != last_sec) {
		if (((start_sec + 1) & MC_SECOND_MASK) != last_sec) {
			netif_warn(efx, hw, efx->net_dev,
				   "PTP bad synchronisation seconds\n");
			return -EAGAIN;
		} else {
			delta.tv_sec = 1;
		}
	} else {
		delta.tv_sec = 0;
	}

	ptp->host_time_pps = *last_time;
	pps_sub_ts(&ptp->host_time_pps, delta);

	return 0;
}

/* Synchronize times between the host and the MC */
static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
{
	struct efx_ptp_data *ptp = efx->ptp_data;
716
	MCDI_DECLARE_BUF(synch_buf, MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX);
717 718 719 720 721 722 723 724
	size_t response_length;
	int rc;
	unsigned long timeout;
	struct pps_event_time last_time = {};
	unsigned int loops = 0;
	int *start = ptp->start.addr;

	MCDI_SET_DWORD(synch_buf, PTP_IN_OP, MC_CMD_PTP_OP_SYNCHRONIZE);
725
	MCDI_SET_DWORD(synch_buf, PTP_IN_PERIPH_ID, 0);
726 727
	MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_NUMTIMESETS,
		       num_readings);
728 729
	MCDI_SET_QWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR,
		       ptp->start.dma_addr);
730 731 732

	/* Clear flag that signals MC ready */
	ACCESS_ONCE(*start) = 0;
B
Ben Hutchings 已提交
733 734 735
	rc = efx_mcdi_rpc_start(efx, MC_CMD_PTP, synch_buf,
				MC_CMD_PTP_IN_SYNCHRONIZE_LEN);
	EFX_BUG_ON_PARANOID(rc);
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761

	/* Wait for start from MCDI (or timeout) */
	timeout = jiffies + msecs_to_jiffies(MAX_SYNCHRONISE_WAIT_MS);
	while (!ACCESS_ONCE(*start) && (time_before(jiffies, timeout))) {
		udelay(20);	/* Usually start MCDI execution quickly */
		loops++;
	}

	if (ACCESS_ONCE(*start))
		efx_ptp_send_times(efx, &last_time);

	/* Collect results */
	rc = efx_mcdi_rpc_finish(efx, MC_CMD_PTP,
				 MC_CMD_PTP_IN_SYNCHRONIZE_LEN,
				 synch_buf, sizeof(synch_buf),
				 &response_length);
	if (rc == 0)
		rc = efx_ptp_process_times(efx, synch_buf, response_length,
					   &last_time);

	return rc;
}

/* Transmit a PTP packet, via the MCDI interface, to the wire. */
static int efx_ptp_xmit_skb(struct efx_nic *efx, struct sk_buff *skb)
{
762
	struct efx_ptp_data *ptp_data = efx->ptp_data;
763 764
	struct skb_shared_hwtstamps timestamps;
	int rc = -EIO;
765
	MCDI_DECLARE_BUF(txtime, MC_CMD_PTP_OUT_TRANSMIT_LEN);
766
	size_t len;
767

768
	MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_OP, MC_CMD_PTP_OP_TRANSMIT);
769
	MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_PERIPH_ID, 0);
770
	MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_TRANSMIT_LENGTH, skb->len);
771 772 773 774 775 776 777 778 779 780 781 782
	if (skb_shinfo(skb)->nr_frags != 0) {
		rc = skb_linearize(skb);
		if (rc != 0)
			goto fail;
	}

	if (skb->ip_summed == CHECKSUM_PARTIAL) {
		rc = skb_checksum_help(skb);
		if (rc != 0)
			goto fail;
	}
	skb_copy_from_linear_data(skb,
783 784
				  MCDI_PTR(ptp_data->txbuf,
					   PTP_IN_TRANSMIT_PACKET),
785 786 787 788
				  skb->len);
	rc = efx_mcdi_rpc(efx, MC_CMD_PTP,
			  ptp_data->txbuf, MC_CMD_PTP_IN_TRANSMIT_LEN(skb->len),
			  txtime, sizeof(txtime), &len);
789 790 791 792
	if (rc != 0)
		goto fail;

	memset(&timestamps, 0, sizeof(timestamps));
793 794 795 796
	timestamps.hwtstamp = ptp_data->nic_to_kernel_time(
		MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_MAJOR),
		MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_MINOR),
		ptp_data->ts_corrections.tx);
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813

	skb_tstamp_tx(skb, &timestamps);

	rc = 0;

fail:
	dev_kfree_skb(skb);

	return rc;
}

static void efx_ptp_drop_time_expired_events(struct efx_nic *efx)
{
	struct efx_ptp_data *ptp = efx->ptp_data;
	struct list_head *cursor;
	struct list_head *next;

814 815 816
	if (ptp->rx_ts_inline)
		return;

817 818 819 820 821 822 823 824 825
	/* Drop time-expired events */
	spin_lock_bh(&ptp->evt_lock);
	if (!list_empty(&ptp->evt_list)) {
		list_for_each_safe(cursor, next, &ptp->evt_list) {
			struct efx_ptp_event_rx *evt;

			evt = list_entry(cursor, struct efx_ptp_event_rx,
					 link);
			if (time_after(jiffies, evt->expiry)) {
826
				list_move(&evt->link, &ptp->evt_free_list);
827 828 829 830 831
				netif_warn(efx, hw, efx->net_dev,
					   "PTP rx event dropped\n");
			}
		}
	}
832 833 834 835 836
	/* If the event overflow flag is set and the event list is now empty
	 * clear the flag to re-enable the overflow warning message.
	 */
	if (ptp->evt_overflow && list_empty(&ptp->evt_list))
		ptp->evt_overflow = false;
837 838 839 840 841 842 843 844 845 846 847 848 849
	spin_unlock_bh(&ptp->evt_lock);
}

static enum ptp_packet_state efx_ptp_match_rx(struct efx_nic *efx,
					      struct sk_buff *skb)
{
	struct efx_ptp_data *ptp = efx->ptp_data;
	bool evts_waiting;
	struct list_head *cursor;
	struct list_head *next;
	struct efx_ptp_match *match;
	enum ptp_packet_state rc = PTP_PACKET_STATE_UNMATCHED;

850 851
	WARN_ON_ONCE(ptp->rx_ts_inline);

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
	spin_lock_bh(&ptp->evt_lock);
	evts_waiting = !list_empty(&ptp->evt_list);
	spin_unlock_bh(&ptp->evt_lock);

	if (!evts_waiting)
		return PTP_PACKET_STATE_UNMATCHED;

	match = (struct efx_ptp_match *)skb->cb;
	/* Look for a matching timestamp in the event queue */
	spin_lock_bh(&ptp->evt_lock);
	list_for_each_safe(cursor, next, &ptp->evt_list) {
		struct efx_ptp_event_rx *evt;

		evt = list_entry(cursor, struct efx_ptp_event_rx, link);
		if ((evt->seq0 == match->words[0]) &&
		    (evt->seq1 == match->words[1])) {
			struct skb_shared_hwtstamps *timestamps;

			/* Match - add in hardware timestamp */
			timestamps = skb_hwtstamps(skb);
			timestamps->hwtstamp = evt->hwtimestamp;

			match->state = PTP_PACKET_STATE_MATCHED;
			rc = PTP_PACKET_STATE_MATCHED;
876
			list_move(&evt->link, &ptp->evt_free_list);
877 878 879
			break;
		}
	}
880 881 882 883 884
	/* If the event overflow flag is set and the event list is now empty
	 * clear the flag to re-enable the overflow warning message.
	 */
	if (ptp->evt_overflow && list_empty(&ptp->evt_list))
		ptp->evt_overflow = false;
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
	spin_unlock_bh(&ptp->evt_lock);

	return rc;
}

/* Process any queued receive events and corresponding packets
 *
 * q is returned with all the packets that are ready for delivery.
 * true is returned if at least one of those packets requires
 * synchronisation.
 */
static bool efx_ptp_process_events(struct efx_nic *efx, struct sk_buff_head *q)
{
	struct efx_ptp_data *ptp = efx->ptp_data;
	bool rc = false;
	struct sk_buff *skb;

	while ((skb = skb_dequeue(&ptp->rxq))) {
		struct efx_ptp_match *match;

		match = (struct efx_ptp_match *)skb->cb;
		if (match->state == PTP_PACKET_STATE_MATCH_UNWANTED) {
			__skb_queue_tail(q, skb);
		} else if (efx_ptp_match_rx(efx, skb) ==
			   PTP_PACKET_STATE_MATCHED) {
			rc = true;
			__skb_queue_tail(q, skb);
		} else if (time_after(jiffies, match->expiry)) {
			match->state = PTP_PACKET_STATE_TIMED_OUT;
914 915 916
			if (net_ratelimit())
				netif_warn(efx, rx_err, efx->net_dev,
					   "PTP packet - no timestamp seen\n");
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
			__skb_queue_tail(q, skb);
		} else {
			/* Replace unprocessed entry and stop */
			skb_queue_head(&ptp->rxq, skb);
			break;
		}
	}

	return rc;
}

/* Complete processing of a received packet */
static inline void efx_ptp_process_rx(struct efx_nic *efx, struct sk_buff *skb)
{
	local_bh_disable();
	netif_receive_skb(skb);
	local_bh_enable();
}

936 937 938 939 940 941 942 943 944 945 946 947 948 949
static void efx_ptp_remove_multicast_filters(struct efx_nic *efx)
{
	struct efx_ptp_data *ptp = efx->ptp_data;

	if (ptp->rxfilter_installed) {
		efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
					  ptp->rxfilter_general);
		efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
					  ptp->rxfilter_event);
		ptp->rxfilter_installed = false;
	}
}

static int efx_ptp_insert_multicast_filters(struct efx_nic *efx)
950 951 952 953 954
{
	struct efx_ptp_data *ptp = efx->ptp_data;
	struct efx_filter_spec rxfilter;
	int rc;

955
	if (!ptp->channel || ptp->rxfilter_installed)
956
		return 0;
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988

	/* Must filter on both event and general ports to ensure
	 * that there is no packet re-ordering.
	 */
	efx_filter_init_rx(&rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
			   efx_rx_queue_index(
				   efx_channel_get_rx_queue(ptp->channel)));
	rc = efx_filter_set_ipv4_local(&rxfilter, IPPROTO_UDP,
				       htonl(PTP_ADDRESS),
				       htons(PTP_EVENT_PORT));
	if (rc != 0)
		return rc;

	rc = efx_filter_insert_filter(efx, &rxfilter, true);
	if (rc < 0)
		return rc;
	ptp->rxfilter_event = rc;

	efx_filter_init_rx(&rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
			   efx_rx_queue_index(
				   efx_channel_get_rx_queue(ptp->channel)));
	rc = efx_filter_set_ipv4_local(&rxfilter, IPPROTO_UDP,
				       htonl(PTP_ADDRESS),
				       htons(PTP_GENERAL_PORT));
	if (rc != 0)
		goto fail;

	rc = efx_filter_insert_filter(efx, &rxfilter, true);
	if (rc < 0)
		goto fail;
	ptp->rxfilter_general = rc;

989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
	ptp->rxfilter_installed = true;
	return 0;

fail:
	efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
				  ptp->rxfilter_event);
	return rc;
}

static int efx_ptp_start(struct efx_nic *efx)
{
	struct efx_ptp_data *ptp = efx->ptp_data;
	int rc;

	ptp->reset_required = false;

	rc = efx_ptp_insert_multicast_filters(efx);
	if (rc)
		return rc;

1009 1010
	rc = efx_ptp_enable(efx);
	if (rc != 0)
1011
		goto fail;
1012 1013 1014 1015 1016 1017 1018

	ptp->evt_frag_idx = 0;
	ptp->current_adjfreq = 0;

	return 0;

fail:
1019
	efx_ptp_remove_multicast_filters(efx);
1020 1021 1022 1023 1024 1025 1026 1027
	return rc;
}

static int efx_ptp_stop(struct efx_nic *efx)
{
	struct efx_ptp_data *ptp = efx->ptp_data;
	struct list_head *cursor;
	struct list_head *next;
1028 1029 1030 1031 1032 1033
	int rc;

	if (ptp == NULL)
		return 0;

	rc = efx_ptp_disable(efx);
1034

1035
	efx_ptp_remove_multicast_filters(efx);
1036 1037 1038 1039 1040 1041 1042 1043

	/* Make sure RX packets are really delivered */
	efx_ptp_deliver_rx_queue(&efx->ptp_data->rxq);
	skb_queue_purge(&efx->ptp_data->txq);

	/* Drop any pending receive events */
	spin_lock_bh(&efx->ptp_data->evt_lock);
	list_for_each_safe(cursor, next, &efx->ptp_data->evt_list) {
1044
		list_move(cursor, &efx->ptp_data->evt_free_list);
1045
	}
1046
	ptp->evt_overflow = false;
1047 1048 1049 1050 1051
	spin_unlock_bh(&efx->ptp_data->evt_lock);

	return rc;
}

1052 1053 1054 1055 1056 1057 1058
static int efx_ptp_restart(struct efx_nic *efx)
{
	if (efx->ptp_data && efx->ptp_data->enabled)
		return efx_ptp_start(efx);
	return 0;
}

1059 1060 1061 1062
static void efx_ptp_pps_worker(struct work_struct *work)
{
	struct efx_ptp_data *ptp =
		container_of(work, struct efx_ptp_data, pps_work);
1063
	struct efx_nic *efx = ptp->efx;
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
	struct ptp_clock_event ptp_evt;

	if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS))
		return;

	ptp_evt.type = PTP_CLOCK_PPSUSR;
	ptp_evt.pps_times = ptp->host_time_pps;
	ptp_clock_event(ptp->phc_clock, &ptp_evt);
}

static void efx_ptp_worker(struct work_struct *work)
{
	struct efx_ptp_data *ptp_data =
		container_of(work, struct efx_ptp_data, work);
1078
	struct efx_nic *efx = ptp_data->efx;
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
	struct sk_buff *skb;
	struct sk_buff_head tempq;

	if (ptp_data->reset_required) {
		efx_ptp_stop(efx);
		efx_ptp_start(efx);
		return;
	}

	efx_ptp_drop_time_expired_events(efx);

	__skb_queue_head_init(&tempq);
	if (efx_ptp_process_events(efx, &tempq) ||
	    !skb_queue_empty(&ptp_data->txq)) {

		while ((skb = skb_dequeue(&ptp_data->txq)))
			efx_ptp_xmit_skb(efx, skb);
	}

	while ((skb = __skb_dequeue(&tempq)))
		efx_ptp_process_rx(efx, skb);
}

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
static const struct ptp_clock_info efx_phc_clock_info = {
	.owner		= THIS_MODULE,
	.name		= "sfc",
	.max_adj	= MAX_PPB,
	.n_alarm	= 0,
	.n_ext_ts	= 0,
	.n_per_out	= 0,
	.pps		= 1,
	.adjfreq	= efx_phc_adjfreq,
	.adjtime	= efx_phc_adjtime,
	.gettime	= efx_phc_gettime,
	.settime	= efx_phc_settime,
	.enable		= efx_phc_enable,
};

1117 1118
/* Initialise PTP state. */
int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel)
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
{
	struct efx_ptp_data *ptp;
	int rc = 0;
	unsigned int pos;

	ptp = kzalloc(sizeof(struct efx_ptp_data), GFP_KERNEL);
	efx->ptp_data = ptp;
	if (!efx->ptp_data)
		return -ENOMEM;

1129 1130
	ptp->efx = efx;
	ptp->channel = channel;
1131
	ptp->rx_ts_inline = efx_nic_rev(efx) >= EFX_REV_HUNT_A0;
1132

1133
	rc = efx_nic_alloc_buffer(efx, &ptp->start, sizeof(int), GFP_KERNEL);
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
	if (rc != 0)
		goto fail1;

	skb_queue_head_init(&ptp->rxq);
	skb_queue_head_init(&ptp->txq);
	ptp->workwq = create_singlethread_workqueue("sfc_ptp");
	if (!ptp->workwq) {
		rc = -ENOMEM;
		goto fail2;
	}

	INIT_WORK(&ptp->work, efx_ptp_worker);
	ptp->config.flags = 0;
	ptp->config.tx_type = HWTSTAMP_TX_OFF;
	ptp->config.rx_filter = HWTSTAMP_FILTER_NONE;
	INIT_LIST_HEAD(&ptp->evt_list);
	INIT_LIST_HEAD(&ptp->evt_free_list);
	spin_lock_init(&ptp->evt_lock);
	for (pos = 0; pos < MAX_RECEIVE_EVENTS; pos++)
		list_add(&ptp->rx_evts[pos].link, &ptp->evt_free_list);
1154
	ptp->evt_overflow = false;
1155

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
	/* Get the NIC PTP attributes and set up time conversions */
	rc = efx_ptp_get_attributes(efx);
	if (rc < 0)
		goto fail3;

	/* Get the timestamp corrections */
	rc = efx_ptp_get_timestamp_corrections(efx);
	if (rc < 0)
		goto fail3;

1166
	ptp->phc_clock_info = efx_phc_clock_info;
1167 1168
	ptp->phc_clock = ptp_clock_register(&ptp->phc_clock_info,
					    &efx->pci_dev->dev);
1169 1170
	if (IS_ERR(ptp->phc_clock)) {
		rc = PTR_ERR(ptp->phc_clock);
1171
		goto fail3;
1172
	}
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198

	INIT_WORK(&ptp->pps_work, efx_ptp_pps_worker);
	ptp->pps_workwq = create_singlethread_workqueue("sfc_pps");
	if (!ptp->pps_workwq) {
		rc = -ENOMEM;
		goto fail4;
	}
	ptp->nic_ts_enabled = false;

	return 0;
fail4:
	ptp_clock_unregister(efx->ptp_data->phc_clock);

fail3:
	destroy_workqueue(efx->ptp_data->workwq);

fail2:
	efx_nic_free_buffer(efx, &ptp->start);

fail1:
	kfree(efx->ptp_data);
	efx->ptp_data = NULL;

	return rc;
}

1199 1200 1201 1202 1203 1204
/* Initialise PTP channel.
 *
 * Setting core_index to zero causes the queue to be initialised and doesn't
 * overlap with 'rxq0' because ptp.c doesn't use skb_record_rx_queue.
 */
static int efx_ptp_probe_channel(struct efx_channel *channel)
1205 1206 1207
{
	struct efx_nic *efx = channel->efx;

1208 1209 1210 1211 1212 1213 1214 1215
	channel->irq_moderation = 0;
	channel->rx_queue.core_index = 0;

	return efx_ptp_probe(efx, channel);
}

void efx_ptp_remove(struct efx_nic *efx)
{
1216 1217 1218
	if (!efx->ptp_data)
		return;

1219
	(void)efx_ptp_disable(efx);
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235

	cancel_work_sync(&efx->ptp_data->work);
	cancel_work_sync(&efx->ptp_data->pps_work);

	skb_queue_purge(&efx->ptp_data->rxq);
	skb_queue_purge(&efx->ptp_data->txq);

	ptp_clock_unregister(efx->ptp_data->phc_clock);

	destroy_workqueue(efx->ptp_data->workwq);
	destroy_workqueue(efx->ptp_data->pps_workwq);

	efx_nic_free_buffer(efx, &efx->ptp_data->start);
	kfree(efx->ptp_data);
}

1236 1237 1238 1239 1240
static void efx_ptp_remove_channel(struct efx_channel *channel)
{
	efx_ptp_remove(channel->efx);
}

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
static void efx_ptp_get_channel_name(struct efx_channel *channel,
				     char *buf, size_t len)
{
	snprintf(buf, len, "%s-ptp", channel->efx->name);
}

/* Determine whether this packet should be processed by the PTP module
 * or transmitted conventionally.
 */
bool efx_ptp_is_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
{
	return efx->ptp_data &&
		efx->ptp_data->enabled &&
		skb->len >= PTP_MIN_LENGTH &&
		skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM &&
		likely(skb->protocol == htons(ETH_P_IP)) &&
1257 1258
		skb_transport_header_was_set(skb) &&
		skb_network_header_len(skb) >= sizeof(struct iphdr) &&
1259
		ip_hdr(skb)->protocol == IPPROTO_UDP &&
1260 1261
		skb_headlen(skb) >=
		skb_transport_offset(skb) + sizeof(struct udphdr) &&
1262 1263 1264 1265 1266 1267 1268
		udp_hdr(skb)->dest == htons(PTP_EVENT_PORT);
}

/* Receive a PTP packet.  Packets are queued until the arrival of
 * the receive timestamp from the MC - this will probably occur after the
 * packet arrival because of the processing in the MC.
 */
1269
static bool efx_ptp_rx(struct efx_channel *channel, struct sk_buff *skb)
1270 1271 1272 1273
{
	struct efx_nic *efx = channel->efx;
	struct efx_ptp_data *ptp = efx->ptp_data;
	struct efx_ptp_match *match = (struct efx_ptp_match *)skb->cb;
1274
	u8 *match_data_012, *match_data_345;
1275 1276 1277 1278 1279 1280
	unsigned int version;

	match->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);

	/* Correct version? */
	if (ptp->mode == MC_CMD_PTP_MODE_V1) {
1281
		if (!pskb_may_pull(skb, PTP_V1_MIN_LENGTH)) {
1282
			return false;
1283 1284 1285
		}
		version = ntohs(*(__be16 *)&skb->data[PTP_V1_VERSION_OFFSET]);
		if (version != PTP_VERSION_V1) {
1286
			return false;
1287
		}
1288 1289 1290 1291 1292 1293

		/* PTP V1 uses all six bytes of the UUID to match the packet
		 * to the timestamp
		 */
		match_data_012 = skb->data + PTP_V1_UUID_OFFSET;
		match_data_345 = skb->data + PTP_V1_UUID_OFFSET + 3;
1294
	} else {
1295
		if (!pskb_may_pull(skb, PTP_V2_MIN_LENGTH)) {
1296
			return false;
1297 1298 1299
		}
		version = skb->data[PTP_V2_VERSION_OFFSET];
		if ((version & PTP_VERSION_V2_MASK) != PTP_VERSION_V2) {
1300
			return false;
1301
		}
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316

		/* The original V2 implementation uses bytes 2-7 of
		 * the UUID to match the packet to the timestamp. This
		 * discards two of the bytes of the MAC address used
		 * to create the UUID (SF bug 33070).  The PTP V2
		 * enhanced mode fixes this issue and uses bytes 0-2
		 * and byte 5-7 of the UUID.
		 */
		match_data_345 = skb->data + PTP_V2_UUID_OFFSET + 5;
		if (ptp->mode == MC_CMD_PTP_MODE_V2) {
			match_data_012 = skb->data + PTP_V2_UUID_OFFSET + 2;
		} else {
			match_data_012 = skb->data + PTP_V2_UUID_OFFSET + 0;
			BUG_ON(ptp->mode != MC_CMD_PTP_MODE_V2_ENHANCED);
		}
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
	}

	/* Does this packet require timestamping? */
	if (ntohs(*(__be16 *)&skb->data[PTP_DPORT_OFFSET]) == PTP_EVENT_PORT) {
		struct skb_shared_hwtstamps *timestamps;

		match->state = PTP_PACKET_STATE_UNMATCHED;

		/* Clear all timestamps held: filled in later */
		timestamps = skb_hwtstamps(skb);
		memset(timestamps, 0, sizeof(*timestamps));

1329 1330 1331 1332 1333 1334
		/* We expect the sequence number to be in the same position in
		 * the packet for PTP V1 and V2
		 */
		BUILD_BUG_ON(PTP_V1_SEQUENCE_OFFSET != PTP_V2_SEQUENCE_OFFSET);
		BUILD_BUG_ON(PTP_V1_SEQUENCE_LENGTH != PTP_V2_SEQUENCE_LENGTH);

1335
		/* Extract UUID/Sequence information */
1336 1337 1338 1339 1340 1341
		match->words[0] = (match_data_012[0]         |
				   (match_data_012[1] << 8)  |
				   (match_data_012[2] << 16) |
				   (match_data_345[0] << 24));
		match->words[1] = (match_data_345[1]         |
				   (match_data_345[2] << 8)  |
1342 1343 1344 1345 1346 1347 1348 1349 1350
				   (skb->data[PTP_V1_SEQUENCE_OFFSET +
					      PTP_V1_SEQUENCE_LENGTH - 1] <<
				    16));
	} else {
		match->state = PTP_PACKET_STATE_MATCH_UNWANTED;
	}

	skb_queue_tail(&ptp->rxq, skb);
	queue_work(ptp->workwq, &ptp->work);
1351 1352

	return true;
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
}

/* Transmit a PTP packet.  This has to be transmitted by the MC
 * itself, through an MCDI call.  MCDI calls aren't permitted
 * in the transmit path so defer the actual transmission to a suitable worker.
 */
int efx_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
{
	struct efx_ptp_data *ptp = efx->ptp_data;

	skb_queue_tail(&ptp->txq, skb);

	if ((udp_hdr(skb)->dest == htons(PTP_EVENT_PORT)) &&
	    (skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM))
		efx_xmit_hwtstamp_pending(skb);
	queue_work(ptp->workwq, &ptp->work);

	return NETDEV_TX_OK;
}

1373 1374 1375 1376 1377 1378 1379
int efx_ptp_get_mode(struct efx_nic *efx)
{
	return efx->ptp_data->mode;
}

int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted,
			unsigned int new_mode)
1380 1381 1382
{
	if ((enable_wanted != efx->ptp_data->enabled) ||
	    (enable_wanted && (efx->ptp_data->mode != new_mode))) {
1383
		int rc = 0;
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399

		if (enable_wanted) {
			/* Change of mode requires disable */
			if (efx->ptp_data->enabled &&
			    (efx->ptp_data->mode != new_mode)) {
				efx->ptp_data->enabled = false;
				rc = efx_ptp_stop(efx);
				if (rc != 0)
					return rc;
			}

			/* Set new operating mode and establish
			 * baseline synchronisation, which must
			 * succeed.
			 */
			efx->ptp_data->mode = new_mode;
1400 1401
			if (netif_running(efx->net_dev))
				rc = efx_ptp_start(efx);
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
			if (rc == 0) {
				rc = efx_ptp_synchronize(efx,
							 PTP_SYNC_ATTEMPTS * 2);
				if (rc != 0)
					efx_ptp_stop(efx);
			}
		} else {
			rc = efx_ptp_stop(efx);
		}

		if (rc != 0)
			return rc;

		efx->ptp_data->enabled = enable_wanted;
	}

	return 0;
}

static int efx_ptp_ts_init(struct efx_nic *efx, struct hwtstamp_config *init)
{
	int rc;

	if (init->flags)
		return -EINVAL;

	if ((init->tx_type != HWTSTAMP_TX_OFF) &&
	    (init->tx_type != HWTSTAMP_TX_ON))
		return -ERANGE;

1432 1433
	rc = efx->type->ptp_set_ts_config(efx, init);
	if (rc)
1434 1435 1436 1437 1438 1439
		return rc;

	efx->ptp_data->config = *init;
	return 0;
}

1440
void efx_ptp_get_ts_info(struct efx_nic *efx, struct ethtool_ts_info *ts_info)
1441 1442 1443 1444
{
	struct efx_ptp_data *ptp = efx->ptp_data;

	if (!ptp)
1445
		return;
1446

1447 1448 1449
	ts_info->so_timestamping |= (SOF_TIMESTAMPING_TX_HARDWARE |
				     SOF_TIMESTAMPING_RX_HARDWARE |
				     SOF_TIMESTAMPING_RAW_HARDWARE);
1450 1451
	ts_info->phc_index = ptp_clock_index(ptp->phc_clock);
	ts_info->tx_types = 1 << HWTSTAMP_TX_OFF | 1 << HWTSTAMP_TX_ON;
1452
	ts_info->rx_filters = ptp->efx->type->hwtstamp_filters;
1453 1454
}

1455
int efx_ptp_set_ts_config(struct efx_nic *efx, struct ifreq *ifr)
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
{
	struct hwtstamp_config config;
	int rc;

	/* Not a PTP enabled port */
	if (!efx->ptp_data)
		return -EOPNOTSUPP;

	if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
		return -EFAULT;

	rc = efx_ptp_ts_init(efx, &config);
	if (rc != 0)
		return rc;

	return copy_to_user(ifr->ifr_data, &config, sizeof(config))
		? -EFAULT : 0;
}

1475 1476 1477 1478 1479 1480 1481 1482 1483
int efx_ptp_get_ts_config(struct efx_nic *efx, struct ifreq *ifr)
{
	if (!efx->ptp_data)
		return -EOPNOTSUPP;

	return copy_to_user(ifr->ifr_data, &efx->ptp_data->config,
			    sizeof(efx->ptp_data->config)) ? -EFAULT : 0;
}

1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
static void ptp_event_failure(struct efx_nic *efx, int expected_frag_len)
{
	struct efx_ptp_data *ptp = efx->ptp_data;

	netif_err(efx, hw, efx->net_dev,
		"PTP unexpected event length: got %d expected %d\n",
		ptp->evt_frag_idx, expected_frag_len);
	ptp->reset_required = true;
	queue_work(ptp->workwq, &ptp->work);
}

/* Process a completed receive event.  Put it on the event queue and
 * start worker thread.  This is required because event and their
 * correspoding packets may come in either order.
 */
static void ptp_event_rx(struct efx_nic *efx, struct efx_ptp_data *ptp)
{
	struct efx_ptp_event_rx *evt = NULL;

1503 1504 1505
	if (WARN_ON_ONCE(ptp->rx_ts_inline))
		return;

1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
	if (ptp->evt_frag_idx != 3) {
		ptp_event_failure(efx, 3);
		return;
	}

	spin_lock_bh(&ptp->evt_lock);
	if (!list_empty(&ptp->evt_free_list)) {
		evt = list_first_entry(&ptp->evt_free_list,
				       struct efx_ptp_event_rx, link);
		list_del(&evt->link);

		evt->seq0 = EFX_QWORD_FIELD(ptp->evt_frags[2], MCDI_EVENT_DATA);
		evt->seq1 = (EFX_QWORD_FIELD(ptp->evt_frags[2],
					     MCDI_EVENT_SRC)        |
			     (EFX_QWORD_FIELD(ptp->evt_frags[1],
					      MCDI_EVENT_SRC) << 8) |
			     (EFX_QWORD_FIELD(ptp->evt_frags[0],
					      MCDI_EVENT_SRC) << 16));
1524
		evt->hwtimestamp = efx->ptp_data->nic_to_kernel_time(
1525
			EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA),
1526 1527
			EFX_QWORD_FIELD(ptp->evt_frags[1], MCDI_EVENT_DATA),
			ptp->ts_corrections.rx);
1528 1529 1530 1531
		evt->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
		list_add_tail(&evt->link, &ptp->evt_list);

		queue_work(ptp->workwq, &ptp->work);
1532 1533 1534 1535 1536 1537 1538
	} else if (!ptp->evt_overflow) {
		/* Log a warning message and set the event overflow flag.
		 * The message won't be logged again until the event queue
		 * becomes empty.
		 */
		netif_err(efx, rx_err, efx->net_dev, "PTP event queue overflow\n");
		ptp->evt_overflow = true;
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
	}
	spin_unlock_bh(&ptp->evt_lock);
}

static void ptp_event_fault(struct efx_nic *efx, struct efx_ptp_data *ptp)
{
	int code = EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA);
	if (ptp->evt_frag_idx != 1) {
		ptp_event_failure(efx, 1);
		return;
	}

	netif_err(efx, hw, efx->net_dev, "PTP error %d\n", code);
}

static void ptp_event_pps(struct efx_nic *efx, struct efx_ptp_data *ptp)
{
	if (ptp->nic_ts_enabled)
		queue_work(ptp->pps_workwq, &ptp->pps_work);
}

void efx_ptp_event(struct efx_nic *efx, efx_qword_t *ev)
{
	struct efx_ptp_data *ptp = efx->ptp_data;
	int code = EFX_QWORD_FIELD(*ev, MCDI_EVENT_CODE);

	if (!ptp->enabled)
		return;

	if (ptp->evt_frag_idx == 0) {
		ptp->evt_code = code;
	} else if (ptp->evt_code != code) {
		netif_err(efx, hw, efx->net_dev,
			  "PTP out of sequence event %d\n", code);
		ptp->evt_frag_idx = 0;
	}

	ptp->evt_frags[ptp->evt_frag_idx++] = *ev;
	if (!MCDI_EVENT_FIELD(*ev, CONT)) {
		/* Process resulting event */
		switch (code) {
		case MCDI_EVENT_CODE_PTP_RX:
			ptp_event_rx(efx, ptp);
			break;
		case MCDI_EVENT_CODE_PTP_FAULT:
			ptp_event_fault(efx, ptp);
			break;
		case MCDI_EVENT_CODE_PTP_PPS:
			ptp_event_pps(efx, ptp);
			break;
		default:
			netif_err(efx, hw, efx->net_dev,
				  "PTP unknown event %d\n", code);
			break;
		}
		ptp->evt_frag_idx = 0;
	} else if (MAX_EVENT_FRAGS == ptp->evt_frag_idx) {
		netif_err(efx, hw, efx->net_dev,
			  "PTP too many event fragments\n");
		ptp->evt_frag_idx = 0;
	}
}

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
void efx_time_sync_event(struct efx_channel *channel, efx_qword_t *ev)
{
	channel->sync_timestamp_major = MCDI_EVENT_FIELD(*ev, PTP_TIME_MAJOR);
	channel->sync_timestamp_minor =
		MCDI_EVENT_FIELD(*ev, PTP_TIME_MINOR_26_19) << 19;
	/* if sync events have been disabled then we want to silently ignore
	 * this event, so throw away result.
	 */
	(void) cmpxchg(&channel->sync_events_state, SYNC_EVENTS_REQUESTED,
		       SYNC_EVENTS_VALID);
}

/* make some assumptions about the time representation rather than abstract it,
 * since we currently only support one type of inline timestamping and only on
 * EF10.
 */
#define MINOR_TICKS_PER_SECOND 0x8000000
/* Fuzz factor for sync events to be out of order with RX events */
#define FUZZ (MINOR_TICKS_PER_SECOND / 10)
#define EXPECTED_SYNC_EVENTS_PER_SECOND 4

static inline u32 efx_rx_buf_timestamp_minor(struct efx_nic *efx, const u8 *eh)
{
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
	return __le32_to_cpup((const __le32 *)(eh + efx->rx_packet_ts_offset));
#else
	const u8 *data = eh + efx->rx_packet_ts_offset;
	return (u32)data[0]       |
	       (u32)data[1] << 8  |
	       (u32)data[2] << 16 |
	       (u32)data[3] << 24;
#endif
}

void __efx_rx_skb_attach_timestamp(struct efx_channel *channel,
				   struct sk_buff *skb)
{
	struct efx_nic *efx = channel->efx;
	u32 pkt_timestamp_major, pkt_timestamp_minor;
	u32 diff, carry;
	struct skb_shared_hwtstamps *timestamps;

	pkt_timestamp_minor = (efx_rx_buf_timestamp_minor(efx,
							  skb_mac_header(skb)) +
			       (u32) efx->ptp_data->ts_corrections.rx) &
			      (MINOR_TICKS_PER_SECOND - 1);

	/* get the difference between the packet and sync timestamps,
	 * modulo one second
	 */
	diff = (pkt_timestamp_minor - channel->sync_timestamp_minor) &
		(MINOR_TICKS_PER_SECOND - 1);
	/* do we roll over a second boundary and need to carry the one? */
	carry = channel->sync_timestamp_minor + diff > MINOR_TICKS_PER_SECOND ?
		1 : 0;

	if (diff <= MINOR_TICKS_PER_SECOND / EXPECTED_SYNC_EVENTS_PER_SECOND +
		    FUZZ) {
		/* packet is ahead of the sync event by a quarter of a second or
		 * less (allowing for fuzz)
		 */
		pkt_timestamp_major = channel->sync_timestamp_major + carry;
	} else if (diff >= MINOR_TICKS_PER_SECOND - FUZZ) {
		/* packet is behind the sync event but within the fuzz factor.
		 * This means the RX packet and sync event crossed as they were
		 * placed on the event queue, which can sometimes happen.
		 */
		pkt_timestamp_major = channel->sync_timestamp_major - 1 + carry;
	} else {
		/* it's outside tolerance in both directions. this might be
		 * indicative of us missing sync events for some reason, so
		 * we'll call it an error rather than risk giving a bogus
		 * timestamp.
		 */
		netif_vdbg(efx, drv, efx->net_dev,
			  "packet timestamp %x too far from sync event %x:%x\n",
			  pkt_timestamp_minor, channel->sync_timestamp_major,
			  channel->sync_timestamp_minor);
		return;
	}

	/* attach the timestamps to the skb */
	timestamps = skb_hwtstamps(skb);
	timestamps->hwtstamp =
		efx_ptp_s27_to_ktime(pkt_timestamp_major, pkt_timestamp_minor);
}

1689 1690 1691 1692 1693
static int efx_phc_adjfreq(struct ptp_clock_info *ptp, s32 delta)
{
	struct efx_ptp_data *ptp_data = container_of(ptp,
						     struct efx_ptp_data,
						     phc_clock_info);
1694
	struct efx_nic *efx = ptp_data->efx;
1695
	MCDI_DECLARE_BUF(inadj, MC_CMD_PTP_IN_ADJUST_LEN);
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
	s64 adjustment_ns;
	int rc;

	if (delta > MAX_PPB)
		delta = MAX_PPB;
	else if (delta < -MAX_PPB)
		delta = -MAX_PPB;

	/* Convert ppb to fixed point ns. */
	adjustment_ns = (((s64)delta * PPB_SCALE_WORD) >>
			 (PPB_EXTRA_BITS + MAX_PPB_BITS));

	MCDI_SET_DWORD(inadj, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
1709
	MCDI_SET_DWORD(inadj, PTP_IN_PERIPH_ID, 0);
1710
	MCDI_SET_QWORD(inadj, PTP_IN_ADJUST_FREQ, adjustment_ns);
1711 1712 1713 1714 1715 1716 1717
	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_SECONDS, 0);
	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_NANOSECONDS, 0);
	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inadj, sizeof(inadj),
			  NULL, 0, NULL);
	if (rc != 0)
		return rc;

1718
	ptp_data->current_adjfreq = adjustment_ns;
1719 1720 1721 1722 1723
	return 0;
}

static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta)
{
1724
	u32 nic_major, nic_minor;
1725 1726 1727
	struct efx_ptp_data *ptp_data = container_of(ptp,
						     struct efx_ptp_data,
						     phc_clock_info);
1728
	struct efx_nic *efx = ptp_data->efx;
1729
	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ADJUST_LEN);
1730

1731 1732
	efx->ptp_data->ns_to_nic_time(delta, &nic_major, &nic_minor);

1733
	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
1734
	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
1735
	MCDI_SET_QWORD(inbuf, PTP_IN_ADJUST_FREQ, ptp_data->current_adjfreq);
1736 1737
	MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_MAJOR, nic_major);
	MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_MINOR, nic_minor);
1738 1739 1740 1741 1742 1743 1744 1745 1746
	return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
			    NULL, 0, NULL);
}

static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec *ts)
{
	struct efx_ptp_data *ptp_data = container_of(ptp,
						     struct efx_ptp_data,
						     phc_clock_info);
1747
	struct efx_nic *efx = ptp_data->efx;
1748 1749
	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_READ_NIC_TIME_LEN);
	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_READ_NIC_TIME_LEN);
1750
	int rc;
1751
	ktime_t kt;
1752 1753

	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_READ_NIC_TIME);
1754
	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
1755 1756 1757 1758 1759 1760

	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
			  outbuf, sizeof(outbuf), NULL);
	if (rc != 0)
		return rc;

1761 1762 1763 1764
	kt = ptp_data->nic_to_kernel_time(
		MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_MAJOR),
		MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_MINOR), 0);
	*ts = ktime_to_timespec(kt);
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
	return 0;
}

static int efx_phc_settime(struct ptp_clock_info *ptp,
			   const struct timespec *e_ts)
{
	/* Get the current NIC time, efx_phc_gettime.
	 * Subtract from the desired time to get the offset
	 * call efx_phc_adjtime with the offset
	 */
	int rc;
	struct timespec time_now;
	struct timespec delta;

	rc = efx_phc_gettime(ptp, &time_now);
	if (rc != 0)
		return rc;

	delta = timespec_sub(*e_ts, time_now);

1785
	rc = efx_phc_adjtime(ptp, timespec_to_ns(&delta));
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
	if (rc != 0)
		return rc;

	return 0;
}

static int efx_phc_enable(struct ptp_clock_info *ptp,
			  struct ptp_clock_request *request,
			  int enable)
{
	struct efx_ptp_data *ptp_data = container_of(ptp,
						     struct efx_ptp_data,
						     phc_clock_info);
	if (request->type != PTP_CLK_REQ_PPS)
		return -EOPNOTSUPP;

	ptp_data->nic_ts_enabled = !!enable;
	return 0;
}

static const struct efx_channel_type efx_ptp_channel_type = {
	.handle_no_channel	= efx_ptp_handle_no_channel,
	.pre_probe		= efx_ptp_probe_channel,
	.post_remove		= efx_ptp_remove_channel,
	.get_name		= efx_ptp_get_channel_name,
	/* no copy operation; there is no need to reallocate this channel */
	.receive_skb		= efx_ptp_rx,
	.keep_eventq		= false,
};

1816
void efx_ptp_defer_probe_with_channel(struct efx_nic *efx)
1817 1818 1819 1820 1821 1822 1823 1824
{
	/* Check whether PTP is implemented on this NIC.  The DISABLE
	 * operation will succeed if and only if it is implemented.
	 */
	if (efx_ptp_disable(efx) == 0)
		efx->extra_channel_type[EFX_EXTRA_CHANNEL_PTP] =
			&efx_ptp_channel_type;
}
1825 1826 1827 1828 1829

void efx_ptp_start_datapath(struct efx_nic *efx)
{
	if (efx_ptp_restart(efx))
		netif_err(efx, drv, efx->net_dev, "Failed to restart PTP.\n");
1830 1831 1832
	/* re-enable timestamping if it was previously enabled */
	if (efx->type->ptp_set_ts_sync_events)
		efx->type->ptp_set_ts_sync_events(efx, true, true);
1833 1834 1835 1836
}

void efx_ptp_stop_datapath(struct efx_nic *efx)
{
1837 1838 1839
	/* temporarily disable timestamping */
	if (efx->type->ptp_set_ts_sync_events)
		efx->type->ptp_set_ts_sync_events(efx, false, true);
1840 1841
	efx_ptp_stop(efx);
}