sfc: PTP changes to support improved UUID filtering mode
[firefly-linux-kernel-4.4.55.git] / drivers / net / ethernet / sfc / ptp.c
1 /****************************************************************************
2  * Driver for Solarflare Solarstorm network controllers and boards
3  * Copyright 2011 Solarflare Communications Inc.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 as published
7  * by the Free Software Foundation, incorporated herein by reference.
8  */
9
10 /* Theory of operation:
11  *
12  * PTP support is assisted by firmware running on the MC, which provides
13  * the hardware timestamping capabilities.  Both transmitted and received
14  * PTP event packets are queued onto internal queues for subsequent processing;
15  * this is because the MC operations are relatively long and would block
16  * block NAPI/interrupt operation.
17  *
18  * Receive event processing:
19  *      The event contains the packet's UUID and sequence number, together
20  *      with the hardware timestamp.  The PTP receive packet queue is searched
21  *      for this UUID/sequence number and, if found, put on a pending queue.
22  *      Packets not matching are delivered without timestamps (MCDI events will
23  *      always arrive after the actual packet).
24  *      It is important for the operation of the PTP protocol that the ordering
25  *      of packets between the event and general port is maintained.
26  *
27  * Work queue processing:
28  *      If work waiting, synchronise host/hardware time
29  *
30  *      Transmit: send packet through MC, which returns the transmission time
31  *      that is converted to an appropriate timestamp.
32  *
33  *      Receive: the packet's reception time is converted to an appropriate
34  *      timestamp.
35  */
36 #include <linux/ip.h>
37 #include <linux/udp.h>
38 #include <linux/time.h>
39 #include <linux/ktime.h>
40 #include <linux/module.h>
41 #include <linux/net_tstamp.h>
42 #include <linux/pps_kernel.h>
43 #include <linux/ptp_clock_kernel.h>
44 #include "net_driver.h"
45 #include "efx.h"
46 #include "mcdi.h"
47 #include "mcdi_pcol.h"
48 #include "io.h"
49 #include "regs.h"
50 #include "nic.h"
51
52 /* Maximum number of events expected to make up a PTP event */
53 #define MAX_EVENT_FRAGS                 3
54
55 /* Maximum delay, ms, to begin synchronisation */
56 #define MAX_SYNCHRONISE_WAIT_MS         2
57
58 /* How long, at most, to spend synchronising */
59 #define SYNCHRONISE_PERIOD_NS           250000
60
61 /* How often to update the shared memory time */
62 #define SYNCHRONISATION_GRANULARITY_NS  200
63
64 /* Minimum permitted length of a (corrected) synchronisation time */
65 #define MIN_SYNCHRONISATION_NS          120
66
67 /* Maximum permitted length of a (corrected) synchronisation time */
68 #define MAX_SYNCHRONISATION_NS          1000
69
70 /* How many (MC) receive events that can be queued */
71 #define MAX_RECEIVE_EVENTS              8
72
73 /* Length of (modified) moving average. */
74 #define AVERAGE_LENGTH                  16
75
76 /* How long an unmatched event or packet can be held */
77 #define PKT_EVENT_LIFETIME_MS           10
78
79 /* Offsets into PTP packet for identification.  These offsets are from the
80  * start of the IP header, not the MAC header.  Note that neither PTP V1 nor
81  * PTP V2 permit the use of IPV4 options.
82  */
83 #define PTP_DPORT_OFFSET        22
84
85 #define PTP_V1_VERSION_LENGTH   2
86 #define PTP_V1_VERSION_OFFSET   28
87
88 #define PTP_V1_UUID_LENGTH      6
89 #define PTP_V1_UUID_OFFSET      50
90
91 #define PTP_V1_SEQUENCE_LENGTH  2
92 #define PTP_V1_SEQUENCE_OFFSET  58
93
94 /* The minimum length of a PTP V1 packet for offsets, etc. to be valid:
95  * includes IP header.
96  */
97 #define PTP_V1_MIN_LENGTH       64
98
99 #define PTP_V2_VERSION_LENGTH   1
100 #define PTP_V2_VERSION_OFFSET   29
101
102 #define PTP_V2_UUID_LENGTH      8
103 #define PTP_V2_UUID_OFFSET      48
104
105 /* Although PTP V2 UUIDs are comprised a ClockIdentity (8) and PortNumber (2),
106  * the MC only captures the last six bytes of the clock identity. These values
107  * reflect those, not the ones used in the standard.  The standard permits
108  * mapping of V1 UUIDs to V2 UUIDs with these same values.
109  */
110 #define PTP_V2_MC_UUID_LENGTH   6
111 #define PTP_V2_MC_UUID_OFFSET   50
112
113 #define PTP_V2_SEQUENCE_LENGTH  2
114 #define PTP_V2_SEQUENCE_OFFSET  58
115
116 /* The minimum length of a PTP V2 packet for offsets, etc. to be valid:
117  * includes IP header.
118  */
119 #define PTP_V2_MIN_LENGTH       63
120
121 #define PTP_MIN_LENGTH          63
122
123 #define PTP_ADDRESS             0xe0000181      /* 224.0.1.129 */
124 #define PTP_EVENT_PORT          319
125 #define PTP_GENERAL_PORT        320
126
127 /* Annoyingly the format of the version numbers are different between
128  * versions 1 and 2 so it isn't possible to simply look for 1 or 2.
129  */
130 #define PTP_VERSION_V1          1
131
132 #define PTP_VERSION_V2          2
133 #define PTP_VERSION_V2_MASK     0x0f
134
135 enum ptp_packet_state {
136         PTP_PACKET_STATE_UNMATCHED = 0,
137         PTP_PACKET_STATE_MATCHED,
138         PTP_PACKET_STATE_TIMED_OUT,
139         PTP_PACKET_STATE_MATCH_UNWANTED
140 };
141
142 /* NIC synchronised with single word of time only comprising
143  * partial seconds and full nanoseconds: 10^9 ~ 2^30 so 2 bits for seconds.
144  */
145 #define MC_NANOSECOND_BITS      30
146 #define MC_NANOSECOND_MASK      ((1 << MC_NANOSECOND_BITS) - 1)
147 #define MC_SECOND_MASK          ((1 << (32 - MC_NANOSECOND_BITS)) - 1)
148
149 /* Maximum parts-per-billion adjustment that is acceptable */
150 #define MAX_PPB                 1000000
151
152 /* Number of bits required to hold the above */
153 #define MAX_PPB_BITS            20
154
155 /* Number of extra bits allowed when calculating fractional ns.
156  * EXTRA_BITS + MC_CMD_PTP_IN_ADJUST_BITS + MAX_PPB_BITS should
157  * be less than 63.
158  */
159 #define PPB_EXTRA_BITS          2
160
161 /* Precalculate scale word to avoid long long division at runtime */
162 #define PPB_SCALE_WORD  ((1LL << (PPB_EXTRA_BITS + MC_CMD_PTP_IN_ADJUST_BITS +\
163                         MAX_PPB_BITS)) / 1000000000LL)
164
165 #define PTP_SYNC_ATTEMPTS       4
166
167 /**
168  * struct efx_ptp_match - Matching structure, stored in sk_buff's cb area.
169  * @words: UUID and (partial) sequence number
170  * @expiry: Time after which the packet should be delivered irrespective of
171  *            event arrival.
172  * @state: The state of the packet - whether it is ready for processing or
173  *         whether that is of no interest.
174  */
175 struct efx_ptp_match {
176         u32 words[DIV_ROUND_UP(PTP_V1_UUID_LENGTH, 4)];
177         unsigned long expiry;
178         enum ptp_packet_state state;
179 };
180
181 /**
182  * struct efx_ptp_event_rx - A PTP receive event (from MC)
183  * @seq0: First part of (PTP) UUID
184  * @seq1: Second part of (PTP) UUID and sequence number
185  * @hwtimestamp: Event timestamp
186  */
187 struct efx_ptp_event_rx {
188         struct list_head link;
189         u32 seq0;
190         u32 seq1;
191         ktime_t hwtimestamp;
192         unsigned long expiry;
193 };
194
195 /**
196  * struct efx_ptp_timeset - Synchronisation between host and MC
197  * @host_start: Host time immediately before hardware timestamp taken
198  * @seconds: Hardware timestamp, seconds
199  * @nanoseconds: Hardware timestamp, nanoseconds
200  * @host_end: Host time immediately after hardware timestamp taken
201  * @waitns: Number of nanoseconds between hardware timestamp being read and
202  *          host end time being seen
203  * @window: Difference of host_end and host_start
204  * @valid: Whether this timeset is valid
205  */
206 struct efx_ptp_timeset {
207         u32 host_start;
208         u32 seconds;
209         u32 nanoseconds;
210         u32 host_end;
211         u32 waitns;
212         u32 window;     /* Derived: end - start, allowing for wrap */
213 };
214
215 /**
216  * struct efx_ptp_data - Precision Time Protocol (PTP) state
217  * @channel: The PTP channel
218  * @rxq: Receive queue (awaiting timestamps)
219  * @txq: Transmit queue
220  * @evt_list: List of MC receive events awaiting packets
221  * @evt_free_list: List of free events
222  * @evt_lock: Lock for manipulating evt_list and evt_free_list
223  * @rx_evts: Instantiated events (on evt_list and evt_free_list)
224  * @workwq: Work queue for processing pending PTP operations
225  * @work: Work task
226  * @reset_required: A serious error has occurred and the PTP task needs to be
227  *                  reset (disable, enable).
228  * @rxfilter_event: Receive filter when operating
229  * @rxfilter_general: Receive filter when operating
230  * @config: Current timestamp configuration
231  * @enabled: PTP operation enabled
232  * @mode: Mode in which PTP operating (PTP version)
233  * @evt_frags: Partly assembled PTP events
234  * @evt_frag_idx: Current fragment number
235  * @evt_code: Last event code
236  * @start: Address at which MC indicates ready for synchronisation
237  * @host_time_pps: Host time at last PPS
238  * @last_sync_ns: Last number of nanoseconds between readings when synchronising
239  * @base_sync_ns: Number of nanoseconds for last synchronisation.
240  * @base_sync_valid: Whether base_sync_time is valid.
241  * @current_adjfreq: Current ppb adjustment.
242  * @phc_clock: Pointer to registered phc device
243  * @phc_clock_info: Registration structure for phc device
244  * @pps_work: pps work task for handling pps events
245  * @pps_workwq: pps work queue
246  * @nic_ts_enabled: Flag indicating if NIC generated TS events are handled
247  * @txbuf: Buffer for use when transmitting (PTP) packets to MC (avoids
248  *         allocations in main data path).
249  * @debug_ptp_dir: PTP debugfs directory
250  * @missed_rx_sync: Number of packets received without syncrhonisation.
251  * @good_syncs: Number of successful synchronisations.
252  * @no_time_syncs: Number of synchronisations with no good times.
253  * @bad_sync_durations: Number of synchronisations with bad durations.
254  * @bad_syncs: Number of failed synchronisations.
255  * @last_sync_time: Number of nanoseconds for last synchronisation.
256  * @sync_timeouts: Number of synchronisation timeouts
257  * @fast_syncs: Number of synchronisations requiring short delay
258  * @min_sync_delta: Minimum time between event and synchronisation
259  * @max_sync_delta: Maximum time between event and synchronisation
260  * @average_sync_delta: Average time between event and synchronisation.
261  *                      Modified moving average.
262  * @last_sync_delta: Last time between event and synchronisation
263  * @mc_stats: Context value for MC statistics
264  * @timeset: Last set of synchronisation statistics.
265  */
266 struct efx_ptp_data {
267         struct efx_channel *channel;
268         struct sk_buff_head rxq;
269         struct sk_buff_head txq;
270         struct list_head evt_list;
271         struct list_head evt_free_list;
272         spinlock_t evt_lock;
273         struct efx_ptp_event_rx rx_evts[MAX_RECEIVE_EVENTS];
274         struct workqueue_struct *workwq;
275         struct work_struct work;
276         bool reset_required;
277         u32 rxfilter_event;
278         u32 rxfilter_general;
279         bool rxfilter_installed;
280         struct hwtstamp_config config;
281         bool enabled;
282         unsigned int mode;
283         efx_qword_t evt_frags[MAX_EVENT_FRAGS];
284         int evt_frag_idx;
285         int evt_code;
286         struct efx_buffer start;
287         struct pps_event_time host_time_pps;
288         unsigned last_sync_ns;
289         unsigned base_sync_ns;
290         bool base_sync_valid;
291         s64 current_adjfreq;
292         struct ptp_clock *phc_clock;
293         struct ptp_clock_info phc_clock_info;
294         struct work_struct pps_work;
295         struct workqueue_struct *pps_workwq;
296         bool nic_ts_enabled;
297         u8 txbuf[ALIGN(MC_CMD_PTP_IN_TRANSMIT_LEN(
298                                MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM), 4)];
299         struct efx_ptp_timeset
300         timeset[MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_MAXNUM];
301 };
302
303 static int efx_phc_adjfreq(struct ptp_clock_info *ptp, s32 delta);
304 static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta);
305 static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec *ts);
306 static int efx_phc_settime(struct ptp_clock_info *ptp,
307                            const struct timespec *e_ts);
308 static int efx_phc_enable(struct ptp_clock_info *ptp,
309                           struct ptp_clock_request *request, int on);
310
311 /* Enable MCDI PTP support. */
312 static int efx_ptp_enable(struct efx_nic *efx)
313 {
314         u8 inbuf[MC_CMD_PTP_IN_ENABLE_LEN];
315
316         MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ENABLE);
317         MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_QUEUE,
318                        efx->ptp_data->channel->channel);
319         MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_MODE, efx->ptp_data->mode);
320
321         return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
322                             NULL, 0, NULL);
323 }
324
325 /* Disable MCDI PTP support.
326  *
327  * Note that this function should never rely on the presence of ptp_data -
328  * may be called before that exists.
329  */
330 static int efx_ptp_disable(struct efx_nic *efx)
331 {
332         u8 inbuf[MC_CMD_PTP_IN_DISABLE_LEN];
333
334         MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_DISABLE);
335         return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
336                             NULL, 0, NULL);
337 }
338
339 static void efx_ptp_deliver_rx_queue(struct sk_buff_head *q)
340 {
341         struct sk_buff *skb;
342
343         while ((skb = skb_dequeue(q))) {
344                 local_bh_disable();
345                 netif_receive_skb(skb);
346                 local_bh_enable();
347         }
348 }
349
350 static void efx_ptp_handle_no_channel(struct efx_nic *efx)
351 {
352         netif_err(efx, drv, efx->net_dev,
353                   "ERROR: PTP requires MSI-X and 1 additional interrupt"
354                   "vector. PTP disabled\n");
355 }
356
357 /* Repeatedly send the host time to the MC which will capture the hardware
358  * time.
359  */
360 static void efx_ptp_send_times(struct efx_nic *efx,
361                                struct pps_event_time *last_time)
362 {
363         struct pps_event_time now;
364         struct timespec limit;
365         struct efx_ptp_data *ptp = efx->ptp_data;
366         struct timespec start;
367         int *mc_running = ptp->start.addr;
368
369         pps_get_ts(&now);
370         start = now.ts_real;
371         limit = now.ts_real;
372         timespec_add_ns(&limit, SYNCHRONISE_PERIOD_NS);
373
374         /* Write host time for specified period or until MC is done */
375         while ((timespec_compare(&now.ts_real, &limit) < 0) &&
376                ACCESS_ONCE(*mc_running)) {
377                 struct timespec update_time;
378                 unsigned int host_time;
379
380                 /* Don't update continuously to avoid saturating the PCIe bus */
381                 update_time = now.ts_real;
382                 timespec_add_ns(&update_time, SYNCHRONISATION_GRANULARITY_NS);
383                 do {
384                         pps_get_ts(&now);
385                 } while ((timespec_compare(&now.ts_real, &update_time) < 0) &&
386                          ACCESS_ONCE(*mc_running));
387
388                 /* Synchronise NIC with single word of time only */
389                 host_time = (now.ts_real.tv_sec << MC_NANOSECOND_BITS |
390                              now.ts_real.tv_nsec);
391                 /* Update host time in NIC memory */
392                 _efx_writed(efx, cpu_to_le32(host_time),
393                             FR_CZ_MC_TREG_SMEM + MC_SMEM_P0_PTP_TIME_OFST);
394         }
395         *last_time = now;
396 }
397
398 /* Read a timeset from the MC's results and partial process. */
399 static void efx_ptp_read_timeset(u8 *data, struct efx_ptp_timeset *timeset)
400 {
401         unsigned start_ns, end_ns;
402
403         timeset->host_start = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTSTART);
404         timeset->seconds = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_SECONDS);
405         timeset->nanoseconds = MCDI_DWORD(data,
406                                          PTP_OUT_SYNCHRONIZE_NANOSECONDS);
407         timeset->host_end = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTEND),
408         timeset->waitns = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_WAITNS);
409
410         /* Ignore seconds */
411         start_ns = timeset->host_start & MC_NANOSECOND_MASK;
412         end_ns = timeset->host_end & MC_NANOSECOND_MASK;
413         /* Allow for rollover */
414         if (end_ns < start_ns)
415                 end_ns += NSEC_PER_SEC;
416         /* Determine duration of operation */
417         timeset->window = end_ns - start_ns;
418 }
419
420 /* Process times received from MC.
421  *
422  * Extract times from returned results, and establish the minimum value
423  * seen.  The minimum value represents the "best" possible time and events
424  * too much greater than this are rejected - the machine is, perhaps, too
425  * busy. A number of readings are taken so that, hopefully, at least one good
426  * synchronisation will be seen in the results.
427  */
428 static int efx_ptp_process_times(struct efx_nic *efx, u8 *synch_buf,
429                                  size_t response_length,
430                                  const struct pps_event_time *last_time)
431 {
432         unsigned number_readings = (response_length /
433                                MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_LEN);
434         unsigned i;
435         unsigned min;
436         unsigned min_set = 0;
437         unsigned total;
438         unsigned ngood = 0;
439         unsigned last_good = 0;
440         struct efx_ptp_data *ptp = efx->ptp_data;
441         bool min_valid = false;
442         u32 last_sec;
443         u32 start_sec;
444         struct timespec delta;
445
446         if (number_readings == 0)
447                 return -EAGAIN;
448
449         /* Find minimum value in this set of results, discarding clearly
450          * erroneous results.
451          */
452         for (i = 0; i < number_readings; i++) {
453                 efx_ptp_read_timeset(synch_buf, &ptp->timeset[i]);
454                 synch_buf += MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_LEN;
455                 if (ptp->timeset[i].window > SYNCHRONISATION_GRANULARITY_NS) {
456                         if (min_valid) {
457                                 if (ptp->timeset[i].window < min_set)
458                                         min_set = ptp->timeset[i].window;
459                         } else {
460                                 min_valid = true;
461                                 min_set = ptp->timeset[i].window;
462                         }
463                 }
464         }
465
466         if (min_valid) {
467                 if (ptp->base_sync_valid && (min_set > ptp->base_sync_ns))
468                         min = ptp->base_sync_ns;
469                 else
470                         min = min_set;
471         } else {
472                 min = SYNCHRONISATION_GRANULARITY_NS;
473         }
474
475         /* Discard excessively long synchronise durations.  The MC times
476          * when it finishes reading the host time so the corrected window
477          * time should be fairly constant for a given platform.
478          */
479         total = 0;
480         for (i = 0; i < number_readings; i++)
481                 if (ptp->timeset[i].window > ptp->timeset[i].waitns) {
482                         unsigned win;
483
484                         win = ptp->timeset[i].window - ptp->timeset[i].waitns;
485                         if (win >= MIN_SYNCHRONISATION_NS &&
486                             win < MAX_SYNCHRONISATION_NS) {
487                                 total += ptp->timeset[i].window;
488                                 ngood++;
489                                 last_good = i;
490                         }
491                 }
492
493         if (ngood == 0) {
494                 netif_warn(efx, drv, efx->net_dev,
495                            "PTP no suitable synchronisations %dns %dns\n",
496                            ptp->base_sync_ns, min_set);
497                 return -EAGAIN;
498         }
499
500         /* Average minimum this synchronisation */
501         ptp->last_sync_ns = DIV_ROUND_UP(total, ngood);
502         if (!ptp->base_sync_valid || (ptp->last_sync_ns < ptp->base_sync_ns)) {
503                 ptp->base_sync_valid = true;
504                 ptp->base_sync_ns = ptp->last_sync_ns;
505         }
506
507         /* Calculate delay from actual PPS to last_time */
508         delta.tv_nsec =
509                 ptp->timeset[last_good].nanoseconds +
510                 last_time->ts_real.tv_nsec -
511                 (ptp->timeset[last_good].host_start & MC_NANOSECOND_MASK);
512
513         /* It is possible that the seconds rolled over between taking
514          * the start reading and the last value written by the host.  The
515          * timescales are such that a gap of more than one second is never
516          * expected.
517          */
518         start_sec = ptp->timeset[last_good].host_start >> MC_NANOSECOND_BITS;
519         last_sec = last_time->ts_real.tv_sec & MC_SECOND_MASK;
520         if (start_sec != last_sec) {
521                 if (((start_sec + 1) & MC_SECOND_MASK) != last_sec) {
522                         netif_warn(efx, hw, efx->net_dev,
523                                    "PTP bad synchronisation seconds\n");
524                         return -EAGAIN;
525                 } else {
526                         delta.tv_sec = 1;
527                 }
528         } else {
529                 delta.tv_sec = 0;
530         }
531
532         ptp->host_time_pps = *last_time;
533         pps_sub_ts(&ptp->host_time_pps, delta);
534
535         return 0;
536 }
537
538 /* Synchronize times between the host and the MC */
539 static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
540 {
541         struct efx_ptp_data *ptp = efx->ptp_data;
542         u8 synch_buf[MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX];
543         size_t response_length;
544         int rc;
545         unsigned long timeout;
546         struct pps_event_time last_time = {};
547         unsigned int loops = 0;
548         int *start = ptp->start.addr;
549
550         MCDI_SET_DWORD(synch_buf, PTP_IN_OP, MC_CMD_PTP_OP_SYNCHRONIZE);
551         MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_NUMTIMESETS,
552                        num_readings);
553         MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR_LO,
554                        (u32)ptp->start.dma_addr);
555         MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR_HI,
556                        (u32)((u64)ptp->start.dma_addr >> 32));
557
558         /* Clear flag that signals MC ready */
559         ACCESS_ONCE(*start) = 0;
560         efx_mcdi_rpc_start(efx, MC_CMD_PTP, synch_buf,
561                            MC_CMD_PTP_IN_SYNCHRONIZE_LEN);
562
563         /* Wait for start from MCDI (or timeout) */
564         timeout = jiffies + msecs_to_jiffies(MAX_SYNCHRONISE_WAIT_MS);
565         while (!ACCESS_ONCE(*start) && (time_before(jiffies, timeout))) {
566                 udelay(20);     /* Usually start MCDI execution quickly */
567                 loops++;
568         }
569
570         if (ACCESS_ONCE(*start))
571                 efx_ptp_send_times(efx, &last_time);
572
573         /* Collect results */
574         rc = efx_mcdi_rpc_finish(efx, MC_CMD_PTP,
575                                  MC_CMD_PTP_IN_SYNCHRONIZE_LEN,
576                                  synch_buf, sizeof(synch_buf),
577                                  &response_length);
578         if (rc == 0)
579                 rc = efx_ptp_process_times(efx, synch_buf, response_length,
580                                            &last_time);
581
582         return rc;
583 }
584
585 /* Transmit a PTP packet, via the MCDI interface, to the wire. */
586 static int efx_ptp_xmit_skb(struct efx_nic *efx, struct sk_buff *skb)
587 {
588         u8 *txbuf = efx->ptp_data->txbuf;
589         struct skb_shared_hwtstamps timestamps;
590         int rc = -EIO;
591         /* MCDI driver requires word aligned lengths */
592         size_t len = ALIGN(MC_CMD_PTP_IN_TRANSMIT_LEN(skb->len), 4);
593         u8 txtime[MC_CMD_PTP_OUT_TRANSMIT_LEN];
594
595         MCDI_SET_DWORD(txbuf, PTP_IN_OP, MC_CMD_PTP_OP_TRANSMIT);
596         MCDI_SET_DWORD(txbuf, PTP_IN_TRANSMIT_LENGTH, skb->len);
597         if (skb_shinfo(skb)->nr_frags != 0) {
598                 rc = skb_linearize(skb);
599                 if (rc != 0)
600                         goto fail;
601         }
602
603         if (skb->ip_summed == CHECKSUM_PARTIAL) {
604                 rc = skb_checksum_help(skb);
605                 if (rc != 0)
606                         goto fail;
607         }
608         skb_copy_from_linear_data(skb,
609                                   &txbuf[MC_CMD_PTP_IN_TRANSMIT_PACKET_OFST],
610                                   len);
611         rc = efx_mcdi_rpc(efx, MC_CMD_PTP, txbuf, len, txtime,
612                           sizeof(txtime), &len);
613         if (rc != 0)
614                 goto fail;
615
616         memset(&timestamps, 0, sizeof(timestamps));
617         timestamps.hwtstamp = ktime_set(
618                 MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_SECONDS),
619                 MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_NANOSECONDS));
620
621         skb_tstamp_tx(skb, &timestamps);
622
623         rc = 0;
624
625 fail:
626         dev_kfree_skb(skb);
627
628         return rc;
629 }
630
631 static void efx_ptp_drop_time_expired_events(struct efx_nic *efx)
632 {
633         struct efx_ptp_data *ptp = efx->ptp_data;
634         struct list_head *cursor;
635         struct list_head *next;
636
637         /* Drop time-expired events */
638         spin_lock_bh(&ptp->evt_lock);
639         if (!list_empty(&ptp->evt_list)) {
640                 list_for_each_safe(cursor, next, &ptp->evt_list) {
641                         struct efx_ptp_event_rx *evt;
642
643                         evt = list_entry(cursor, struct efx_ptp_event_rx,
644                                          link);
645                         if (time_after(jiffies, evt->expiry)) {
646                                 list_move(&evt->link, &ptp->evt_free_list);
647                                 netif_warn(efx, hw, efx->net_dev,
648                                            "PTP rx event dropped\n");
649                         }
650                 }
651         }
652         spin_unlock_bh(&ptp->evt_lock);
653 }
654
655 static enum ptp_packet_state efx_ptp_match_rx(struct efx_nic *efx,
656                                               struct sk_buff *skb)
657 {
658         struct efx_ptp_data *ptp = efx->ptp_data;
659         bool evts_waiting;
660         struct list_head *cursor;
661         struct list_head *next;
662         struct efx_ptp_match *match;
663         enum ptp_packet_state rc = PTP_PACKET_STATE_UNMATCHED;
664
665         spin_lock_bh(&ptp->evt_lock);
666         evts_waiting = !list_empty(&ptp->evt_list);
667         spin_unlock_bh(&ptp->evt_lock);
668
669         if (!evts_waiting)
670                 return PTP_PACKET_STATE_UNMATCHED;
671
672         match = (struct efx_ptp_match *)skb->cb;
673         /* Look for a matching timestamp in the event queue */
674         spin_lock_bh(&ptp->evt_lock);
675         list_for_each_safe(cursor, next, &ptp->evt_list) {
676                 struct efx_ptp_event_rx *evt;
677
678                 evt = list_entry(cursor, struct efx_ptp_event_rx, link);
679                 if ((evt->seq0 == match->words[0]) &&
680                     (evt->seq1 == match->words[1])) {
681                         struct skb_shared_hwtstamps *timestamps;
682
683                         /* Match - add in hardware timestamp */
684                         timestamps = skb_hwtstamps(skb);
685                         timestamps->hwtstamp = evt->hwtimestamp;
686
687                         match->state = PTP_PACKET_STATE_MATCHED;
688                         rc = PTP_PACKET_STATE_MATCHED;
689                         list_move(&evt->link, &ptp->evt_free_list);
690                         break;
691                 }
692         }
693         spin_unlock_bh(&ptp->evt_lock);
694
695         return rc;
696 }
697
698 /* Process any queued receive events and corresponding packets
699  *
700  * q is returned with all the packets that are ready for delivery.
701  * true is returned if at least one of those packets requires
702  * synchronisation.
703  */
704 static bool efx_ptp_process_events(struct efx_nic *efx, struct sk_buff_head *q)
705 {
706         struct efx_ptp_data *ptp = efx->ptp_data;
707         bool rc = false;
708         struct sk_buff *skb;
709
710         while ((skb = skb_dequeue(&ptp->rxq))) {
711                 struct efx_ptp_match *match;
712
713                 match = (struct efx_ptp_match *)skb->cb;
714                 if (match->state == PTP_PACKET_STATE_MATCH_UNWANTED) {
715                         __skb_queue_tail(q, skb);
716                 } else if (efx_ptp_match_rx(efx, skb) ==
717                            PTP_PACKET_STATE_MATCHED) {
718                         rc = true;
719                         __skb_queue_tail(q, skb);
720                 } else if (time_after(jiffies, match->expiry)) {
721                         match->state = PTP_PACKET_STATE_TIMED_OUT;
722                         netif_warn(efx, rx_err, efx->net_dev,
723                                    "PTP packet - no timestamp seen\n");
724                         __skb_queue_tail(q, skb);
725                 } else {
726                         /* Replace unprocessed entry and stop */
727                         skb_queue_head(&ptp->rxq, skb);
728                         break;
729                 }
730         }
731
732         return rc;
733 }
734
735 /* Complete processing of a received packet */
736 static inline void efx_ptp_process_rx(struct efx_nic *efx, struct sk_buff *skb)
737 {
738         local_bh_disable();
739         netif_receive_skb(skb);
740         local_bh_enable();
741 }
742
743 static int efx_ptp_start(struct efx_nic *efx)
744 {
745         struct efx_ptp_data *ptp = efx->ptp_data;
746         struct efx_filter_spec rxfilter;
747         int rc;
748
749         ptp->reset_required = false;
750
751         /* Must filter on both event and general ports to ensure
752          * that there is no packet re-ordering.
753          */
754         efx_filter_init_rx(&rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
755                            efx_rx_queue_index(
756                                    efx_channel_get_rx_queue(ptp->channel)));
757         rc = efx_filter_set_ipv4_local(&rxfilter, IPPROTO_UDP,
758                                        htonl(PTP_ADDRESS),
759                                        htons(PTP_EVENT_PORT));
760         if (rc != 0)
761                 return rc;
762
763         rc = efx_filter_insert_filter(efx, &rxfilter, true);
764         if (rc < 0)
765                 return rc;
766         ptp->rxfilter_event = rc;
767
768         efx_filter_init_rx(&rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
769                            efx_rx_queue_index(
770                                    efx_channel_get_rx_queue(ptp->channel)));
771         rc = efx_filter_set_ipv4_local(&rxfilter, IPPROTO_UDP,
772                                        htonl(PTP_ADDRESS),
773                                        htons(PTP_GENERAL_PORT));
774         if (rc != 0)
775                 goto fail;
776
777         rc = efx_filter_insert_filter(efx, &rxfilter, true);
778         if (rc < 0)
779                 goto fail;
780         ptp->rxfilter_general = rc;
781
782         rc = efx_ptp_enable(efx);
783         if (rc != 0)
784                 goto fail2;
785
786         ptp->evt_frag_idx = 0;
787         ptp->current_adjfreq = 0;
788         ptp->rxfilter_installed = true;
789
790         return 0;
791
792 fail2:
793         efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
794                                   ptp->rxfilter_general);
795 fail:
796         efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
797                                   ptp->rxfilter_event);
798
799         return rc;
800 }
801
802 static int efx_ptp_stop(struct efx_nic *efx)
803 {
804         struct efx_ptp_data *ptp = efx->ptp_data;
805         int rc = efx_ptp_disable(efx);
806         struct list_head *cursor;
807         struct list_head *next;
808
809         if (ptp->rxfilter_installed) {
810                 efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
811                                           ptp->rxfilter_general);
812                 efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
813                                           ptp->rxfilter_event);
814                 ptp->rxfilter_installed = false;
815         }
816
817         /* Make sure RX packets are really delivered */
818         efx_ptp_deliver_rx_queue(&efx->ptp_data->rxq);
819         skb_queue_purge(&efx->ptp_data->txq);
820
821         /* Drop any pending receive events */
822         spin_lock_bh(&efx->ptp_data->evt_lock);
823         list_for_each_safe(cursor, next, &efx->ptp_data->evt_list) {
824                 list_move(cursor, &efx->ptp_data->evt_free_list);
825         }
826         spin_unlock_bh(&efx->ptp_data->evt_lock);
827
828         return rc;
829 }
830
831 static void efx_ptp_pps_worker(struct work_struct *work)
832 {
833         struct efx_ptp_data *ptp =
834                 container_of(work, struct efx_ptp_data, pps_work);
835         struct efx_nic *efx = ptp->channel->efx;
836         struct ptp_clock_event ptp_evt;
837
838         if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS))
839                 return;
840
841         ptp_evt.type = PTP_CLOCK_PPSUSR;
842         ptp_evt.pps_times = ptp->host_time_pps;
843         ptp_clock_event(ptp->phc_clock, &ptp_evt);
844 }
845
846 /* Process any pending transmissions and timestamp any received packets.
847  */
848 static void efx_ptp_worker(struct work_struct *work)
849 {
850         struct efx_ptp_data *ptp_data =
851                 container_of(work, struct efx_ptp_data, work);
852         struct efx_nic *efx = ptp_data->channel->efx;
853         struct sk_buff *skb;
854         struct sk_buff_head tempq;
855
856         if (ptp_data->reset_required) {
857                 efx_ptp_stop(efx);
858                 efx_ptp_start(efx);
859                 return;
860         }
861
862         efx_ptp_drop_time_expired_events(efx);
863
864         __skb_queue_head_init(&tempq);
865         if (efx_ptp_process_events(efx, &tempq) ||
866             !skb_queue_empty(&ptp_data->txq)) {
867
868                 while ((skb = skb_dequeue(&ptp_data->txq)))
869                         efx_ptp_xmit_skb(efx, skb);
870         }
871
872         while ((skb = __skb_dequeue(&tempq)))
873                 efx_ptp_process_rx(efx, skb);
874 }
875
876 /* Initialise PTP channel and state.
877  *
878  * Setting core_index to zero causes the queue to be initialised and doesn't
879  * overlap with 'rxq0' because ptp.c doesn't use skb_record_rx_queue.
880  */
881 static int efx_ptp_probe_channel(struct efx_channel *channel)
882 {
883         struct efx_nic *efx = channel->efx;
884         struct efx_ptp_data *ptp;
885         int rc = 0;
886         unsigned int pos;
887
888         channel->irq_moderation = 0;
889         channel->rx_queue.core_index = 0;
890
891         ptp = kzalloc(sizeof(struct efx_ptp_data), GFP_KERNEL);
892         efx->ptp_data = ptp;
893         if (!efx->ptp_data)
894                 return -ENOMEM;
895
896         rc = efx_nic_alloc_buffer(efx, &ptp->start, sizeof(int));
897         if (rc != 0)
898                 goto fail1;
899
900         ptp->channel = channel;
901         skb_queue_head_init(&ptp->rxq);
902         skb_queue_head_init(&ptp->txq);
903         ptp->workwq = create_singlethread_workqueue("sfc_ptp");
904         if (!ptp->workwq) {
905                 rc = -ENOMEM;
906                 goto fail2;
907         }
908
909         INIT_WORK(&ptp->work, efx_ptp_worker);
910         ptp->config.flags = 0;
911         ptp->config.tx_type = HWTSTAMP_TX_OFF;
912         ptp->config.rx_filter = HWTSTAMP_FILTER_NONE;
913         INIT_LIST_HEAD(&ptp->evt_list);
914         INIT_LIST_HEAD(&ptp->evt_free_list);
915         spin_lock_init(&ptp->evt_lock);
916         for (pos = 0; pos < MAX_RECEIVE_EVENTS; pos++)
917                 list_add(&ptp->rx_evts[pos].link, &ptp->evt_free_list);
918
919         ptp->phc_clock_info.owner = THIS_MODULE;
920         snprintf(ptp->phc_clock_info.name,
921                  sizeof(ptp->phc_clock_info.name),
922                  "%pm", efx->net_dev->perm_addr);
923         ptp->phc_clock_info.max_adj = MAX_PPB;
924         ptp->phc_clock_info.n_alarm = 0;
925         ptp->phc_clock_info.n_ext_ts = 0;
926         ptp->phc_clock_info.n_per_out = 0;
927         ptp->phc_clock_info.pps = 1;
928         ptp->phc_clock_info.adjfreq = efx_phc_adjfreq;
929         ptp->phc_clock_info.adjtime = efx_phc_adjtime;
930         ptp->phc_clock_info.gettime = efx_phc_gettime;
931         ptp->phc_clock_info.settime = efx_phc_settime;
932         ptp->phc_clock_info.enable = efx_phc_enable;
933
934         ptp->phc_clock = ptp_clock_register(&ptp->phc_clock_info,
935                                             &efx->pci_dev->dev);
936         if (!ptp->phc_clock)
937                 goto fail3;
938
939         INIT_WORK(&ptp->pps_work, efx_ptp_pps_worker);
940         ptp->pps_workwq = create_singlethread_workqueue("sfc_pps");
941         if (!ptp->pps_workwq) {
942                 rc = -ENOMEM;
943                 goto fail4;
944         }
945         ptp->nic_ts_enabled = false;
946
947         return 0;
948 fail4:
949         ptp_clock_unregister(efx->ptp_data->phc_clock);
950
951 fail3:
952         destroy_workqueue(efx->ptp_data->workwq);
953
954 fail2:
955         efx_nic_free_buffer(efx, &ptp->start);
956
957 fail1:
958         kfree(efx->ptp_data);
959         efx->ptp_data = NULL;
960
961         return rc;
962 }
963
964 static void efx_ptp_remove_channel(struct efx_channel *channel)
965 {
966         struct efx_nic *efx = channel->efx;
967
968         if (!efx->ptp_data)
969                 return;
970
971         (void)efx_ptp_disable(channel->efx);
972
973         cancel_work_sync(&efx->ptp_data->work);
974         cancel_work_sync(&efx->ptp_data->pps_work);
975
976         skb_queue_purge(&efx->ptp_data->rxq);
977         skb_queue_purge(&efx->ptp_data->txq);
978
979         ptp_clock_unregister(efx->ptp_data->phc_clock);
980
981         destroy_workqueue(efx->ptp_data->workwq);
982         destroy_workqueue(efx->ptp_data->pps_workwq);
983
984         efx_nic_free_buffer(efx, &efx->ptp_data->start);
985         kfree(efx->ptp_data);
986 }
987
988 static void efx_ptp_get_channel_name(struct efx_channel *channel,
989                                      char *buf, size_t len)
990 {
991         snprintf(buf, len, "%s-ptp", channel->efx->name);
992 }
993
994 /* Determine whether this packet should be processed by the PTP module
995  * or transmitted conventionally.
996  */
997 bool efx_ptp_is_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
998 {
999         return efx->ptp_data &&
1000                 efx->ptp_data->enabled &&
1001                 skb->len >= PTP_MIN_LENGTH &&
1002                 skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM &&
1003                 likely(skb->protocol == htons(ETH_P_IP)) &&
1004                 ip_hdr(skb)->protocol == IPPROTO_UDP &&
1005                 udp_hdr(skb)->dest == htons(PTP_EVENT_PORT);
1006 }
1007
1008 /* Receive a PTP packet.  Packets are queued until the arrival of
1009  * the receive timestamp from the MC - this will probably occur after the
1010  * packet arrival because of the processing in the MC.
1011  */
1012 static bool efx_ptp_rx(struct efx_channel *channel, struct sk_buff *skb)
1013 {
1014         struct efx_nic *efx = channel->efx;
1015         struct efx_ptp_data *ptp = efx->ptp_data;
1016         struct efx_ptp_match *match = (struct efx_ptp_match *)skb->cb;
1017         u8 *match_data_012, *match_data_345;
1018         unsigned int version;
1019
1020         match->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
1021
1022         /* Correct version? */
1023         if (ptp->mode == MC_CMD_PTP_MODE_V1) {
1024                 if (skb->len < PTP_V1_MIN_LENGTH) {
1025                         return false;
1026                 }
1027                 version = ntohs(*(__be16 *)&skb->data[PTP_V1_VERSION_OFFSET]);
1028                 if (version != PTP_VERSION_V1) {
1029                         return false;
1030                 }
1031
1032                 /* PTP V1 uses all six bytes of the UUID to match the packet
1033                  * to the timestamp
1034                  */
1035                 match_data_012 = skb->data + PTP_V1_UUID_OFFSET;
1036                 match_data_345 = skb->data + PTP_V1_UUID_OFFSET + 3;
1037         } else {
1038                 if (skb->len < PTP_V2_MIN_LENGTH) {
1039                         return false;
1040                 }
1041                 version = skb->data[PTP_V2_VERSION_OFFSET];
1042                 if ((version & PTP_VERSION_V2_MASK) != PTP_VERSION_V2) {
1043                         return false;
1044                 }
1045
1046                 /* The original V2 implementation uses bytes 2-7 of
1047                  * the UUID to match the packet to the timestamp. This
1048                  * discards two of the bytes of the MAC address used
1049                  * to create the UUID (SF bug 33070).  The PTP V2
1050                  * enhanced mode fixes this issue and uses bytes 0-2
1051                  * and byte 5-7 of the UUID.
1052                  */
1053                 match_data_345 = skb->data + PTP_V2_UUID_OFFSET + 5;
1054                 if (ptp->mode == MC_CMD_PTP_MODE_V2) {
1055                         match_data_012 = skb->data + PTP_V2_UUID_OFFSET + 2;
1056                 } else {
1057                         match_data_012 = skb->data + PTP_V2_UUID_OFFSET + 0;
1058                         BUG_ON(ptp->mode != MC_CMD_PTP_MODE_V2_ENHANCED);
1059                 }
1060         }
1061
1062         /* Does this packet require timestamping? */
1063         if (ntohs(*(__be16 *)&skb->data[PTP_DPORT_OFFSET]) == PTP_EVENT_PORT) {
1064                 struct skb_shared_hwtstamps *timestamps;
1065
1066                 match->state = PTP_PACKET_STATE_UNMATCHED;
1067
1068                 /* Clear all timestamps held: filled in later */
1069                 timestamps = skb_hwtstamps(skb);
1070                 memset(timestamps, 0, sizeof(*timestamps));
1071
1072                 /* We expect the sequence number to be in the same position in
1073                  * the packet for PTP V1 and V2
1074                  */
1075                 BUILD_BUG_ON(PTP_V1_SEQUENCE_OFFSET != PTP_V2_SEQUENCE_OFFSET);
1076                 BUILD_BUG_ON(PTP_V1_SEQUENCE_LENGTH != PTP_V2_SEQUENCE_LENGTH);
1077
1078                 /* Extract UUID/Sequence information */
1079                 match->words[0] = (match_data_012[0]         |
1080                                    (match_data_012[1] << 8)  |
1081                                    (match_data_012[2] << 16) |
1082                                    (match_data_345[0] << 24));
1083                 match->words[1] = (match_data_345[1]         |
1084                                    (match_data_345[2] << 8)  |
1085                                    (skb->data[PTP_V1_SEQUENCE_OFFSET +
1086                                               PTP_V1_SEQUENCE_LENGTH - 1] <<
1087                                     16));
1088         } else {
1089                 match->state = PTP_PACKET_STATE_MATCH_UNWANTED;
1090         }
1091
1092         skb_queue_tail(&ptp->rxq, skb);
1093         queue_work(ptp->workwq, &ptp->work);
1094
1095         return true;
1096 }
1097
1098 /* Transmit a PTP packet.  This has to be transmitted by the MC
1099  * itself, through an MCDI call.  MCDI calls aren't permitted
1100  * in the transmit path so defer the actual transmission to a suitable worker.
1101  */
1102 int efx_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
1103 {
1104         struct efx_ptp_data *ptp = efx->ptp_data;
1105
1106         skb_queue_tail(&ptp->txq, skb);
1107
1108         if ((udp_hdr(skb)->dest == htons(PTP_EVENT_PORT)) &&
1109             (skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM))
1110                 efx_xmit_hwtstamp_pending(skb);
1111         queue_work(ptp->workwq, &ptp->work);
1112
1113         return NETDEV_TX_OK;
1114 }
1115
1116 static int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted,
1117                                unsigned int new_mode)
1118 {
1119         if ((enable_wanted != efx->ptp_data->enabled) ||
1120             (enable_wanted && (efx->ptp_data->mode != new_mode))) {
1121                 int rc;
1122
1123                 if (enable_wanted) {
1124                         /* Change of mode requires disable */
1125                         if (efx->ptp_data->enabled &&
1126                             (efx->ptp_data->mode != new_mode)) {
1127                                 efx->ptp_data->enabled = false;
1128                                 rc = efx_ptp_stop(efx);
1129                                 if (rc != 0)
1130                                         return rc;
1131                         }
1132
1133                         /* Set new operating mode and establish
1134                          * baseline synchronisation, which must
1135                          * succeed.
1136                          */
1137                         efx->ptp_data->mode = new_mode;
1138                         rc = efx_ptp_start(efx);
1139                         if (rc == 0) {
1140                                 rc = efx_ptp_synchronize(efx,
1141                                                          PTP_SYNC_ATTEMPTS * 2);
1142                                 if (rc != 0)
1143                                         efx_ptp_stop(efx);
1144                         }
1145                 } else {
1146                         rc = efx_ptp_stop(efx);
1147                 }
1148
1149                 if (rc != 0)
1150                         return rc;
1151
1152                 efx->ptp_data->enabled = enable_wanted;
1153         }
1154
1155         return 0;
1156 }
1157
1158 static int efx_ptp_ts_init(struct efx_nic *efx, struct hwtstamp_config *init)
1159 {
1160         bool enable_wanted = false;
1161         unsigned int new_mode;
1162         int rc;
1163
1164         if (init->flags)
1165                 return -EINVAL;
1166
1167         if ((init->tx_type != HWTSTAMP_TX_OFF) &&
1168             (init->tx_type != HWTSTAMP_TX_ON))
1169                 return -ERANGE;
1170
1171         new_mode = efx->ptp_data->mode;
1172         /* Determine whether any PTP HW operations are required */
1173         switch (init->rx_filter) {
1174         case HWTSTAMP_FILTER_NONE:
1175                 break;
1176         case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
1177         case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
1178         case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
1179                 init->rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_EVENT;
1180                 new_mode = MC_CMD_PTP_MODE_V1;
1181                 enable_wanted = true;
1182                 break;
1183         case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
1184         case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
1185         case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
1186         /* Although these three are accepted only IPV4 packets will be
1187          * timestamped
1188          */
1189                 init->rx_filter = HWTSTAMP_FILTER_PTP_V2_L4_EVENT;
1190                 new_mode = MC_CMD_PTP_MODE_V2_ENHANCED;
1191                 enable_wanted = true;
1192                 break;
1193         case HWTSTAMP_FILTER_PTP_V2_EVENT:
1194         case HWTSTAMP_FILTER_PTP_V2_SYNC:
1195         case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
1196         case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
1197         case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
1198         case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
1199                 /* Non-IP + IPv6 timestamping not supported */
1200                 return -ERANGE;
1201                 break;
1202         default:
1203                 return -ERANGE;
1204         }
1205
1206         if (init->tx_type != HWTSTAMP_TX_OFF)
1207                 enable_wanted = true;
1208
1209         /* Old versions of the firmware do not support the improved
1210          * UUID filtering option (SF bug 33070).  If the firmware does
1211          * not accept the enhanced mode, fall back to the standard PTP
1212          * v2 UUID filtering.
1213          */
1214         rc = efx_ptp_change_mode(efx, enable_wanted, new_mode);
1215         if ((rc != 0) && (new_mode == MC_CMD_PTP_MODE_V2_ENHANCED))
1216                 rc = efx_ptp_change_mode(efx, enable_wanted, MC_CMD_PTP_MODE_V2);
1217         if (rc != 0)
1218                 return rc;
1219
1220         efx->ptp_data->config = *init;
1221
1222         return 0;
1223 }
1224
1225 int
1226 efx_ptp_get_ts_info(struct net_device *net_dev, struct ethtool_ts_info *ts_info)
1227 {
1228         struct efx_nic *efx = netdev_priv(net_dev);
1229         struct efx_ptp_data *ptp = efx->ptp_data;
1230
1231         if (!ptp)
1232                 return -EOPNOTSUPP;
1233
1234         ts_info->so_timestamping = (SOF_TIMESTAMPING_TX_HARDWARE |
1235                                     SOF_TIMESTAMPING_RX_HARDWARE |
1236                                     SOF_TIMESTAMPING_RAW_HARDWARE);
1237         ts_info->phc_index = ptp_clock_index(ptp->phc_clock);
1238         ts_info->tx_types = 1 << HWTSTAMP_TX_OFF | 1 << HWTSTAMP_TX_ON;
1239         ts_info->rx_filters = (1 << HWTSTAMP_FILTER_NONE |
1240                                1 << HWTSTAMP_FILTER_PTP_V1_L4_EVENT |
1241                                1 << HWTSTAMP_FILTER_PTP_V1_L4_SYNC |
1242                                1 << HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ |
1243                                1 << HWTSTAMP_FILTER_PTP_V2_L4_EVENT |
1244                                1 << HWTSTAMP_FILTER_PTP_V2_L4_SYNC |
1245                                1 << HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ);
1246         return 0;
1247 }
1248
1249 int efx_ptp_ioctl(struct efx_nic *efx, struct ifreq *ifr, int cmd)
1250 {
1251         struct hwtstamp_config config;
1252         int rc;
1253
1254         /* Not a PTP enabled port */
1255         if (!efx->ptp_data)
1256                 return -EOPNOTSUPP;
1257
1258         if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
1259                 return -EFAULT;
1260
1261         rc = efx_ptp_ts_init(efx, &config);
1262         if (rc != 0)
1263                 return rc;
1264
1265         return copy_to_user(ifr->ifr_data, &config, sizeof(config))
1266                 ? -EFAULT : 0;
1267 }
1268
1269 static void ptp_event_failure(struct efx_nic *efx, int expected_frag_len)
1270 {
1271         struct efx_ptp_data *ptp = efx->ptp_data;
1272
1273         netif_err(efx, hw, efx->net_dev,
1274                 "PTP unexpected event length: got %d expected %d\n",
1275                 ptp->evt_frag_idx, expected_frag_len);
1276         ptp->reset_required = true;
1277         queue_work(ptp->workwq, &ptp->work);
1278 }
1279
1280 /* Process a completed receive event.  Put it on the event queue and
1281  * start worker thread.  This is required because event and their
1282  * correspoding packets may come in either order.
1283  */
1284 static void ptp_event_rx(struct efx_nic *efx, struct efx_ptp_data *ptp)
1285 {
1286         struct efx_ptp_event_rx *evt = NULL;
1287
1288         if (ptp->evt_frag_idx != 3) {
1289                 ptp_event_failure(efx, 3);
1290                 return;
1291         }
1292
1293         spin_lock_bh(&ptp->evt_lock);
1294         if (!list_empty(&ptp->evt_free_list)) {
1295                 evt = list_first_entry(&ptp->evt_free_list,
1296                                        struct efx_ptp_event_rx, link);
1297                 list_del(&evt->link);
1298
1299                 evt->seq0 = EFX_QWORD_FIELD(ptp->evt_frags[2], MCDI_EVENT_DATA);
1300                 evt->seq1 = (EFX_QWORD_FIELD(ptp->evt_frags[2],
1301                                              MCDI_EVENT_SRC)        |
1302                              (EFX_QWORD_FIELD(ptp->evt_frags[1],
1303                                               MCDI_EVENT_SRC) << 8) |
1304                              (EFX_QWORD_FIELD(ptp->evt_frags[0],
1305                                               MCDI_EVENT_SRC) << 16));
1306                 evt->hwtimestamp = ktime_set(
1307                         EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA),
1308                         EFX_QWORD_FIELD(ptp->evt_frags[1], MCDI_EVENT_DATA));
1309                 evt->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
1310                 list_add_tail(&evt->link, &ptp->evt_list);
1311
1312                 queue_work(ptp->workwq, &ptp->work);
1313         } else {
1314                 netif_err(efx, rx_err, efx->net_dev, "No free PTP event");
1315         }
1316         spin_unlock_bh(&ptp->evt_lock);
1317 }
1318
1319 static void ptp_event_fault(struct efx_nic *efx, struct efx_ptp_data *ptp)
1320 {
1321         int code = EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA);
1322         if (ptp->evt_frag_idx != 1) {
1323                 ptp_event_failure(efx, 1);
1324                 return;
1325         }
1326
1327         netif_err(efx, hw, efx->net_dev, "PTP error %d\n", code);
1328 }
1329
1330 static void ptp_event_pps(struct efx_nic *efx, struct efx_ptp_data *ptp)
1331 {
1332         if (ptp->nic_ts_enabled)
1333                 queue_work(ptp->pps_workwq, &ptp->pps_work);
1334 }
1335
1336 void efx_ptp_event(struct efx_nic *efx, efx_qword_t *ev)
1337 {
1338         struct efx_ptp_data *ptp = efx->ptp_data;
1339         int code = EFX_QWORD_FIELD(*ev, MCDI_EVENT_CODE);
1340
1341         if (!ptp->enabled)
1342                 return;
1343
1344         if (ptp->evt_frag_idx == 0) {
1345                 ptp->evt_code = code;
1346         } else if (ptp->evt_code != code) {
1347                 netif_err(efx, hw, efx->net_dev,
1348                           "PTP out of sequence event %d\n", code);
1349                 ptp->evt_frag_idx = 0;
1350         }
1351
1352         ptp->evt_frags[ptp->evt_frag_idx++] = *ev;
1353         if (!MCDI_EVENT_FIELD(*ev, CONT)) {
1354                 /* Process resulting event */
1355                 switch (code) {
1356                 case MCDI_EVENT_CODE_PTP_RX:
1357                         ptp_event_rx(efx, ptp);
1358                         break;
1359                 case MCDI_EVENT_CODE_PTP_FAULT:
1360                         ptp_event_fault(efx, ptp);
1361                         break;
1362                 case MCDI_EVENT_CODE_PTP_PPS:
1363                         ptp_event_pps(efx, ptp);
1364                         break;
1365                 default:
1366                         netif_err(efx, hw, efx->net_dev,
1367                                   "PTP unknown event %d\n", code);
1368                         break;
1369                 }
1370                 ptp->evt_frag_idx = 0;
1371         } else if (MAX_EVENT_FRAGS == ptp->evt_frag_idx) {
1372                 netif_err(efx, hw, efx->net_dev,
1373                           "PTP too many event fragments\n");
1374                 ptp->evt_frag_idx = 0;
1375         }
1376 }
1377
1378 static int efx_phc_adjfreq(struct ptp_clock_info *ptp, s32 delta)
1379 {
1380         struct efx_ptp_data *ptp_data = container_of(ptp,
1381                                                      struct efx_ptp_data,
1382                                                      phc_clock_info);
1383         struct efx_nic *efx = ptp_data->channel->efx;
1384         u8 inadj[MC_CMD_PTP_IN_ADJUST_LEN];
1385         s64 adjustment_ns;
1386         int rc;
1387
1388         if (delta > MAX_PPB)
1389                 delta = MAX_PPB;
1390         else if (delta < -MAX_PPB)
1391                 delta = -MAX_PPB;
1392
1393         /* Convert ppb to fixed point ns. */
1394         adjustment_ns = (((s64)delta * PPB_SCALE_WORD) >>
1395                          (PPB_EXTRA_BITS + MAX_PPB_BITS));
1396
1397         MCDI_SET_DWORD(inadj, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
1398         MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_FREQ_LO, (u32)adjustment_ns);
1399         MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_FREQ_HI,
1400                        (u32)(adjustment_ns >> 32));
1401         MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_SECONDS, 0);
1402         MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_NANOSECONDS, 0);
1403         rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inadj, sizeof(inadj),
1404                           NULL, 0, NULL);
1405         if (rc != 0)
1406                 return rc;
1407
1408         ptp_data->current_adjfreq = delta;
1409         return 0;
1410 }
1411
1412 static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta)
1413 {
1414         struct efx_ptp_data *ptp_data = container_of(ptp,
1415                                                      struct efx_ptp_data,
1416                                                      phc_clock_info);
1417         struct efx_nic *efx = ptp_data->channel->efx;
1418         struct timespec delta_ts = ns_to_timespec(delta);
1419         u8 inbuf[MC_CMD_PTP_IN_ADJUST_LEN];
1420
1421         MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
1422         MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_FREQ_LO, 0);
1423         MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_FREQ_HI, 0);
1424         MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_SECONDS, (u32)delta_ts.tv_sec);
1425         MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_NANOSECONDS, (u32)delta_ts.tv_nsec);
1426         return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
1427                             NULL, 0, NULL);
1428 }
1429
1430 static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec *ts)
1431 {
1432         struct efx_ptp_data *ptp_data = container_of(ptp,
1433                                                      struct efx_ptp_data,
1434                                                      phc_clock_info);
1435         struct efx_nic *efx = ptp_data->channel->efx;
1436         u8 inbuf[MC_CMD_PTP_IN_READ_NIC_TIME_LEN];
1437         u8 outbuf[MC_CMD_PTP_OUT_READ_NIC_TIME_LEN];
1438         int rc;
1439
1440         MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_READ_NIC_TIME);
1441
1442         rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
1443                           outbuf, sizeof(outbuf), NULL);
1444         if (rc != 0)
1445                 return rc;
1446
1447         ts->tv_sec = MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_SECONDS);
1448         ts->tv_nsec = MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_NANOSECONDS);
1449         return 0;
1450 }
1451
1452 static int efx_phc_settime(struct ptp_clock_info *ptp,
1453                            const struct timespec *e_ts)
1454 {
1455         /* Get the current NIC time, efx_phc_gettime.
1456          * Subtract from the desired time to get the offset
1457          * call efx_phc_adjtime with the offset
1458          */
1459         int rc;
1460         struct timespec time_now;
1461         struct timespec delta;
1462
1463         rc = efx_phc_gettime(ptp, &time_now);
1464         if (rc != 0)
1465                 return rc;
1466
1467         delta = timespec_sub(*e_ts, time_now);
1468
1469         rc = efx_phc_adjtime(ptp, timespec_to_ns(&delta));
1470         if (rc != 0)
1471                 return rc;
1472
1473         return 0;
1474 }
1475
1476 static int efx_phc_enable(struct ptp_clock_info *ptp,
1477                           struct ptp_clock_request *request,
1478                           int enable)
1479 {
1480         struct efx_ptp_data *ptp_data = container_of(ptp,
1481                                                      struct efx_ptp_data,
1482                                                      phc_clock_info);
1483         if (request->type != PTP_CLK_REQ_PPS)
1484                 return -EOPNOTSUPP;
1485
1486         ptp_data->nic_ts_enabled = !!enable;
1487         return 0;
1488 }
1489
1490 static const struct efx_channel_type efx_ptp_channel_type = {
1491         .handle_no_channel      = efx_ptp_handle_no_channel,
1492         .pre_probe              = efx_ptp_probe_channel,
1493         .post_remove            = efx_ptp_remove_channel,
1494         .get_name               = efx_ptp_get_channel_name,
1495         /* no copy operation; there is no need to reallocate this channel */
1496         .receive_skb            = efx_ptp_rx,
1497         .keep_eventq            = false,
1498 };
1499
1500 void efx_ptp_probe(struct efx_nic *efx)
1501 {
1502         /* Check whether PTP is implemented on this NIC.  The DISABLE
1503          * operation will succeed if and only if it is implemented.
1504          */
1505         if (efx_ptp_disable(efx) == 0)
1506                 efx->extra_channel_type[EFX_EXTRA_CHANNEL_PTP] =
1507                         &efx_ptp_channel_type;
1508 }