Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/net
[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 total;
436         unsigned ngood = 0;
437         unsigned last_good = 0;
438         struct efx_ptp_data *ptp = efx->ptp_data;
439         u32 last_sec;
440         u32 start_sec;
441         struct timespec delta;
442
443         if (number_readings == 0)
444                 return -EAGAIN;
445
446         /* Read the set of results and increment stats for any results that
447          * appera to be erroneous.
448          */
449         for (i = 0; i < number_readings; i++) {
450                 efx_ptp_read_timeset(synch_buf, &ptp->timeset[i]);
451                 synch_buf += MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_LEN;
452         }
453
454         /* Find the last good host-MC synchronization result. The MC times
455          * when it finishes reading the host time so the corrected window time
456          * should be fairly constant for a given platform.
457          */
458         total = 0;
459         for (i = 0; i < number_readings; i++)
460                 if (ptp->timeset[i].window > ptp->timeset[i].waitns) {
461                         unsigned win;
462
463                         win = ptp->timeset[i].window - ptp->timeset[i].waitns;
464                         if (win >= MIN_SYNCHRONISATION_NS &&
465                             win < MAX_SYNCHRONISATION_NS) {
466                                 total += ptp->timeset[i].window;
467                                 ngood++;
468                                 last_good = i;
469                         }
470                 }
471
472         if (ngood == 0) {
473                 netif_warn(efx, drv, efx->net_dev,
474                            "PTP no suitable synchronisations %dns\n",
475                            ptp->base_sync_ns);
476                 return -EAGAIN;
477         }
478
479         /* Average minimum this synchronisation */
480         ptp->last_sync_ns = DIV_ROUND_UP(total, ngood);
481         if (!ptp->base_sync_valid || (ptp->last_sync_ns < ptp->base_sync_ns)) {
482                 ptp->base_sync_valid = true;
483                 ptp->base_sync_ns = ptp->last_sync_ns;
484         }
485
486         /* Calculate delay from actual PPS to last_time */
487         delta.tv_nsec =
488                 ptp->timeset[last_good].nanoseconds +
489                 last_time->ts_real.tv_nsec -
490                 (ptp->timeset[last_good].host_start & MC_NANOSECOND_MASK);
491
492         /* It is possible that the seconds rolled over between taking
493          * the start reading and the last value written by the host.  The
494          * timescales are such that a gap of more than one second is never
495          * expected.
496          */
497         start_sec = ptp->timeset[last_good].host_start >> MC_NANOSECOND_BITS;
498         last_sec = last_time->ts_real.tv_sec & MC_SECOND_MASK;
499         if (start_sec != last_sec) {
500                 if (((start_sec + 1) & MC_SECOND_MASK) != last_sec) {
501                         netif_warn(efx, hw, efx->net_dev,
502                                    "PTP bad synchronisation seconds\n");
503                         return -EAGAIN;
504                 } else {
505                         delta.tv_sec = 1;
506                 }
507         } else {
508                 delta.tv_sec = 0;
509         }
510
511         ptp->host_time_pps = *last_time;
512         pps_sub_ts(&ptp->host_time_pps, delta);
513
514         return 0;
515 }
516
517 /* Synchronize times between the host and the MC */
518 static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
519 {
520         struct efx_ptp_data *ptp = efx->ptp_data;
521         u8 synch_buf[MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX];
522         size_t response_length;
523         int rc;
524         unsigned long timeout;
525         struct pps_event_time last_time = {};
526         unsigned int loops = 0;
527         int *start = ptp->start.addr;
528
529         MCDI_SET_DWORD(synch_buf, PTP_IN_OP, MC_CMD_PTP_OP_SYNCHRONIZE);
530         MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_NUMTIMESETS,
531                        num_readings);
532         MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR_LO,
533                        (u32)ptp->start.dma_addr);
534         MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR_HI,
535                        (u32)((u64)ptp->start.dma_addr >> 32));
536
537         /* Clear flag that signals MC ready */
538         ACCESS_ONCE(*start) = 0;
539         efx_mcdi_rpc_start(efx, MC_CMD_PTP, synch_buf,
540                            MC_CMD_PTP_IN_SYNCHRONIZE_LEN);
541
542         /* Wait for start from MCDI (or timeout) */
543         timeout = jiffies + msecs_to_jiffies(MAX_SYNCHRONISE_WAIT_MS);
544         while (!ACCESS_ONCE(*start) && (time_before(jiffies, timeout))) {
545                 udelay(20);     /* Usually start MCDI execution quickly */
546                 loops++;
547         }
548
549         if (ACCESS_ONCE(*start))
550                 efx_ptp_send_times(efx, &last_time);
551
552         /* Collect results */
553         rc = efx_mcdi_rpc_finish(efx, MC_CMD_PTP,
554                                  MC_CMD_PTP_IN_SYNCHRONIZE_LEN,
555                                  synch_buf, sizeof(synch_buf),
556                                  &response_length);
557         if (rc == 0)
558                 rc = efx_ptp_process_times(efx, synch_buf, response_length,
559                                            &last_time);
560
561         return rc;
562 }
563
564 /* Transmit a PTP packet, via the MCDI interface, to the wire. */
565 static int efx_ptp_xmit_skb(struct efx_nic *efx, struct sk_buff *skb)
566 {
567         u8 *txbuf = efx->ptp_data->txbuf;
568         struct skb_shared_hwtstamps timestamps;
569         int rc = -EIO;
570         /* MCDI driver requires word aligned lengths */
571         size_t len = ALIGN(MC_CMD_PTP_IN_TRANSMIT_LEN(skb->len), 4);
572         u8 txtime[MC_CMD_PTP_OUT_TRANSMIT_LEN];
573
574         MCDI_SET_DWORD(txbuf, PTP_IN_OP, MC_CMD_PTP_OP_TRANSMIT);
575         MCDI_SET_DWORD(txbuf, PTP_IN_TRANSMIT_LENGTH, skb->len);
576         if (skb_shinfo(skb)->nr_frags != 0) {
577                 rc = skb_linearize(skb);
578                 if (rc != 0)
579                         goto fail;
580         }
581
582         if (skb->ip_summed == CHECKSUM_PARTIAL) {
583                 rc = skb_checksum_help(skb);
584                 if (rc != 0)
585                         goto fail;
586         }
587         skb_copy_from_linear_data(skb,
588                                   &txbuf[MC_CMD_PTP_IN_TRANSMIT_PACKET_OFST],
589                                   len);
590         rc = efx_mcdi_rpc(efx, MC_CMD_PTP, txbuf, len, txtime,
591                           sizeof(txtime), &len);
592         if (rc != 0)
593                 goto fail;
594
595         memset(&timestamps, 0, sizeof(timestamps));
596         timestamps.hwtstamp = ktime_set(
597                 MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_SECONDS),
598                 MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_NANOSECONDS));
599
600         skb_tstamp_tx(skb, &timestamps);
601
602         rc = 0;
603
604 fail:
605         dev_kfree_skb(skb);
606
607         return rc;
608 }
609
610 static void efx_ptp_drop_time_expired_events(struct efx_nic *efx)
611 {
612         struct efx_ptp_data *ptp = efx->ptp_data;
613         struct list_head *cursor;
614         struct list_head *next;
615
616         /* Drop time-expired events */
617         spin_lock_bh(&ptp->evt_lock);
618         if (!list_empty(&ptp->evt_list)) {
619                 list_for_each_safe(cursor, next, &ptp->evt_list) {
620                         struct efx_ptp_event_rx *evt;
621
622                         evt = list_entry(cursor, struct efx_ptp_event_rx,
623                                          link);
624                         if (time_after(jiffies, evt->expiry)) {
625                                 list_move(&evt->link, &ptp->evt_free_list);
626                                 netif_warn(efx, hw, efx->net_dev,
627                                            "PTP rx event dropped\n");
628                         }
629                 }
630         }
631         spin_unlock_bh(&ptp->evt_lock);
632 }
633
634 static enum ptp_packet_state efx_ptp_match_rx(struct efx_nic *efx,
635                                               struct sk_buff *skb)
636 {
637         struct efx_ptp_data *ptp = efx->ptp_data;
638         bool evts_waiting;
639         struct list_head *cursor;
640         struct list_head *next;
641         struct efx_ptp_match *match;
642         enum ptp_packet_state rc = PTP_PACKET_STATE_UNMATCHED;
643
644         spin_lock_bh(&ptp->evt_lock);
645         evts_waiting = !list_empty(&ptp->evt_list);
646         spin_unlock_bh(&ptp->evt_lock);
647
648         if (!evts_waiting)
649                 return PTP_PACKET_STATE_UNMATCHED;
650
651         match = (struct efx_ptp_match *)skb->cb;
652         /* Look for a matching timestamp in the event queue */
653         spin_lock_bh(&ptp->evt_lock);
654         list_for_each_safe(cursor, next, &ptp->evt_list) {
655                 struct efx_ptp_event_rx *evt;
656
657                 evt = list_entry(cursor, struct efx_ptp_event_rx, link);
658                 if ((evt->seq0 == match->words[0]) &&
659                     (evt->seq1 == match->words[1])) {
660                         struct skb_shared_hwtstamps *timestamps;
661
662                         /* Match - add in hardware timestamp */
663                         timestamps = skb_hwtstamps(skb);
664                         timestamps->hwtstamp = evt->hwtimestamp;
665
666                         match->state = PTP_PACKET_STATE_MATCHED;
667                         rc = PTP_PACKET_STATE_MATCHED;
668                         list_move(&evt->link, &ptp->evt_free_list);
669                         break;
670                 }
671         }
672         spin_unlock_bh(&ptp->evt_lock);
673
674         return rc;
675 }
676
677 /* Process any queued receive events and corresponding packets
678  *
679  * q is returned with all the packets that are ready for delivery.
680  * true is returned if at least one of those packets requires
681  * synchronisation.
682  */
683 static bool efx_ptp_process_events(struct efx_nic *efx, struct sk_buff_head *q)
684 {
685         struct efx_ptp_data *ptp = efx->ptp_data;
686         bool rc = false;
687         struct sk_buff *skb;
688
689         while ((skb = skb_dequeue(&ptp->rxq))) {
690                 struct efx_ptp_match *match;
691
692                 match = (struct efx_ptp_match *)skb->cb;
693                 if (match->state == PTP_PACKET_STATE_MATCH_UNWANTED) {
694                         __skb_queue_tail(q, skb);
695                 } else if (efx_ptp_match_rx(efx, skb) ==
696                            PTP_PACKET_STATE_MATCHED) {
697                         rc = true;
698                         __skb_queue_tail(q, skb);
699                 } else if (time_after(jiffies, match->expiry)) {
700                         match->state = PTP_PACKET_STATE_TIMED_OUT;
701                         netif_warn(efx, rx_err, efx->net_dev,
702                                    "PTP packet - no timestamp seen\n");
703                         __skb_queue_tail(q, skb);
704                 } else {
705                         /* Replace unprocessed entry and stop */
706                         skb_queue_head(&ptp->rxq, skb);
707                         break;
708                 }
709         }
710
711         return rc;
712 }
713
714 /* Complete processing of a received packet */
715 static inline void efx_ptp_process_rx(struct efx_nic *efx, struct sk_buff *skb)
716 {
717         local_bh_disable();
718         netif_receive_skb(skb);
719         local_bh_enable();
720 }
721
722 static int efx_ptp_start(struct efx_nic *efx)
723 {
724         struct efx_ptp_data *ptp = efx->ptp_data;
725         struct efx_filter_spec rxfilter;
726         int rc;
727
728         ptp->reset_required = false;
729
730         /* Must filter on both event and general ports to ensure
731          * that there is no packet re-ordering.
732          */
733         efx_filter_init_rx(&rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
734                            efx_rx_queue_index(
735                                    efx_channel_get_rx_queue(ptp->channel)));
736         rc = efx_filter_set_ipv4_local(&rxfilter, IPPROTO_UDP,
737                                        htonl(PTP_ADDRESS),
738                                        htons(PTP_EVENT_PORT));
739         if (rc != 0)
740                 return rc;
741
742         rc = efx_filter_insert_filter(efx, &rxfilter, true);
743         if (rc < 0)
744                 return rc;
745         ptp->rxfilter_event = rc;
746
747         efx_filter_init_rx(&rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
748                            efx_rx_queue_index(
749                                    efx_channel_get_rx_queue(ptp->channel)));
750         rc = efx_filter_set_ipv4_local(&rxfilter, IPPROTO_UDP,
751                                        htonl(PTP_ADDRESS),
752                                        htons(PTP_GENERAL_PORT));
753         if (rc != 0)
754                 goto fail;
755
756         rc = efx_filter_insert_filter(efx, &rxfilter, true);
757         if (rc < 0)
758                 goto fail;
759         ptp->rxfilter_general = rc;
760
761         rc = efx_ptp_enable(efx);
762         if (rc != 0)
763                 goto fail2;
764
765         ptp->evt_frag_idx = 0;
766         ptp->current_adjfreq = 0;
767         ptp->rxfilter_installed = true;
768
769         return 0;
770
771 fail2:
772         efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
773                                   ptp->rxfilter_general);
774 fail:
775         efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
776                                   ptp->rxfilter_event);
777
778         return rc;
779 }
780
781 static int efx_ptp_stop(struct efx_nic *efx)
782 {
783         struct efx_ptp_data *ptp = efx->ptp_data;
784         int rc = efx_ptp_disable(efx);
785         struct list_head *cursor;
786         struct list_head *next;
787
788         if (ptp->rxfilter_installed) {
789                 efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
790                                           ptp->rxfilter_general);
791                 efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
792                                           ptp->rxfilter_event);
793                 ptp->rxfilter_installed = false;
794         }
795
796         /* Make sure RX packets are really delivered */
797         efx_ptp_deliver_rx_queue(&efx->ptp_data->rxq);
798         skb_queue_purge(&efx->ptp_data->txq);
799
800         /* Drop any pending receive events */
801         spin_lock_bh(&efx->ptp_data->evt_lock);
802         list_for_each_safe(cursor, next, &efx->ptp_data->evt_list) {
803                 list_move(cursor, &efx->ptp_data->evt_free_list);
804         }
805         spin_unlock_bh(&efx->ptp_data->evt_lock);
806
807         return rc;
808 }
809
810 static void efx_ptp_pps_worker(struct work_struct *work)
811 {
812         struct efx_ptp_data *ptp =
813                 container_of(work, struct efx_ptp_data, pps_work);
814         struct efx_nic *efx = ptp->channel->efx;
815         struct ptp_clock_event ptp_evt;
816
817         if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS))
818                 return;
819
820         ptp_evt.type = PTP_CLOCK_PPSUSR;
821         ptp_evt.pps_times = ptp->host_time_pps;
822         ptp_clock_event(ptp->phc_clock, &ptp_evt);
823 }
824
825 /* Process any pending transmissions and timestamp any received packets.
826  */
827 static void efx_ptp_worker(struct work_struct *work)
828 {
829         struct efx_ptp_data *ptp_data =
830                 container_of(work, struct efx_ptp_data, work);
831         struct efx_nic *efx = ptp_data->channel->efx;
832         struct sk_buff *skb;
833         struct sk_buff_head tempq;
834
835         if (ptp_data->reset_required) {
836                 efx_ptp_stop(efx);
837                 efx_ptp_start(efx);
838                 return;
839         }
840
841         efx_ptp_drop_time_expired_events(efx);
842
843         __skb_queue_head_init(&tempq);
844         if (efx_ptp_process_events(efx, &tempq) ||
845             !skb_queue_empty(&ptp_data->txq)) {
846
847                 while ((skb = skb_dequeue(&ptp_data->txq)))
848                         efx_ptp_xmit_skb(efx, skb);
849         }
850
851         while ((skb = __skb_dequeue(&tempq)))
852                 efx_ptp_process_rx(efx, skb);
853 }
854
855 /* Initialise PTP channel and state.
856  *
857  * Setting core_index to zero causes the queue to be initialised and doesn't
858  * overlap with 'rxq0' because ptp.c doesn't use skb_record_rx_queue.
859  */
860 static int efx_ptp_probe_channel(struct efx_channel *channel)
861 {
862         struct efx_nic *efx = channel->efx;
863         struct efx_ptp_data *ptp;
864         int rc = 0;
865         unsigned int pos;
866
867         channel->irq_moderation = 0;
868         channel->rx_queue.core_index = 0;
869
870         ptp = kzalloc(sizeof(struct efx_ptp_data), GFP_KERNEL);
871         efx->ptp_data = ptp;
872         if (!efx->ptp_data)
873                 return -ENOMEM;
874
875         rc = efx_nic_alloc_buffer(efx, &ptp->start, sizeof(int));
876         if (rc != 0)
877                 goto fail1;
878
879         ptp->channel = channel;
880         skb_queue_head_init(&ptp->rxq);
881         skb_queue_head_init(&ptp->txq);
882         ptp->workwq = create_singlethread_workqueue("sfc_ptp");
883         if (!ptp->workwq) {
884                 rc = -ENOMEM;
885                 goto fail2;
886         }
887
888         INIT_WORK(&ptp->work, efx_ptp_worker);
889         ptp->config.flags = 0;
890         ptp->config.tx_type = HWTSTAMP_TX_OFF;
891         ptp->config.rx_filter = HWTSTAMP_FILTER_NONE;
892         INIT_LIST_HEAD(&ptp->evt_list);
893         INIT_LIST_HEAD(&ptp->evt_free_list);
894         spin_lock_init(&ptp->evt_lock);
895         for (pos = 0; pos < MAX_RECEIVE_EVENTS; pos++)
896                 list_add(&ptp->rx_evts[pos].link, &ptp->evt_free_list);
897
898         ptp->phc_clock_info.owner = THIS_MODULE;
899         snprintf(ptp->phc_clock_info.name,
900                  sizeof(ptp->phc_clock_info.name),
901                  "%pm", efx->net_dev->perm_addr);
902         ptp->phc_clock_info.max_adj = MAX_PPB;
903         ptp->phc_clock_info.n_alarm = 0;
904         ptp->phc_clock_info.n_ext_ts = 0;
905         ptp->phc_clock_info.n_per_out = 0;
906         ptp->phc_clock_info.pps = 1;
907         ptp->phc_clock_info.adjfreq = efx_phc_adjfreq;
908         ptp->phc_clock_info.adjtime = efx_phc_adjtime;
909         ptp->phc_clock_info.gettime = efx_phc_gettime;
910         ptp->phc_clock_info.settime = efx_phc_settime;
911         ptp->phc_clock_info.enable = efx_phc_enable;
912
913         ptp->phc_clock = ptp_clock_register(&ptp->phc_clock_info,
914                                             &efx->pci_dev->dev);
915         if (!ptp->phc_clock)
916                 goto fail3;
917
918         INIT_WORK(&ptp->pps_work, efx_ptp_pps_worker);
919         ptp->pps_workwq = create_singlethread_workqueue("sfc_pps");
920         if (!ptp->pps_workwq) {
921                 rc = -ENOMEM;
922                 goto fail4;
923         }
924         ptp->nic_ts_enabled = false;
925
926         return 0;
927 fail4:
928         ptp_clock_unregister(efx->ptp_data->phc_clock);
929
930 fail3:
931         destroy_workqueue(efx->ptp_data->workwq);
932
933 fail2:
934         efx_nic_free_buffer(efx, &ptp->start);
935
936 fail1:
937         kfree(efx->ptp_data);
938         efx->ptp_data = NULL;
939
940         return rc;
941 }
942
943 static void efx_ptp_remove_channel(struct efx_channel *channel)
944 {
945         struct efx_nic *efx = channel->efx;
946
947         if (!efx->ptp_data)
948                 return;
949
950         (void)efx_ptp_disable(channel->efx);
951
952         cancel_work_sync(&efx->ptp_data->work);
953         cancel_work_sync(&efx->ptp_data->pps_work);
954
955         skb_queue_purge(&efx->ptp_data->rxq);
956         skb_queue_purge(&efx->ptp_data->txq);
957
958         ptp_clock_unregister(efx->ptp_data->phc_clock);
959
960         destroy_workqueue(efx->ptp_data->workwq);
961         destroy_workqueue(efx->ptp_data->pps_workwq);
962
963         efx_nic_free_buffer(efx, &efx->ptp_data->start);
964         kfree(efx->ptp_data);
965 }
966
967 static void efx_ptp_get_channel_name(struct efx_channel *channel,
968                                      char *buf, size_t len)
969 {
970         snprintf(buf, len, "%s-ptp", channel->efx->name);
971 }
972
973 /* Determine whether this packet should be processed by the PTP module
974  * or transmitted conventionally.
975  */
976 bool efx_ptp_is_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
977 {
978         return efx->ptp_data &&
979                 efx->ptp_data->enabled &&
980                 skb->len >= PTP_MIN_LENGTH &&
981                 skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM &&
982                 likely(skb->protocol == htons(ETH_P_IP)) &&
983                 ip_hdr(skb)->protocol == IPPROTO_UDP &&
984                 udp_hdr(skb)->dest == htons(PTP_EVENT_PORT);
985 }
986
987 /* Receive a PTP packet.  Packets are queued until the arrival of
988  * the receive timestamp from the MC - this will probably occur after the
989  * packet arrival because of the processing in the MC.
990  */
991 static bool efx_ptp_rx(struct efx_channel *channel, struct sk_buff *skb)
992 {
993         struct efx_nic *efx = channel->efx;
994         struct efx_ptp_data *ptp = efx->ptp_data;
995         struct efx_ptp_match *match = (struct efx_ptp_match *)skb->cb;
996         u8 *match_data_012, *match_data_345;
997         unsigned int version;
998
999         match->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
1000
1001         /* Correct version? */
1002         if (ptp->mode == MC_CMD_PTP_MODE_V1) {
1003                 if (!pskb_may_pull(skb, PTP_V1_MIN_LENGTH)) {
1004                         return false;
1005                 }
1006                 version = ntohs(*(__be16 *)&skb->data[PTP_V1_VERSION_OFFSET]);
1007                 if (version != PTP_VERSION_V1) {
1008                         return false;
1009                 }
1010
1011                 /* PTP V1 uses all six bytes of the UUID to match the packet
1012                  * to the timestamp
1013                  */
1014                 match_data_012 = skb->data + PTP_V1_UUID_OFFSET;
1015                 match_data_345 = skb->data + PTP_V1_UUID_OFFSET + 3;
1016         } else {
1017                 if (!pskb_may_pull(skb, PTP_V2_MIN_LENGTH)) {
1018                         return false;
1019                 }
1020                 version = skb->data[PTP_V2_VERSION_OFFSET];
1021                 if ((version & PTP_VERSION_V2_MASK) != PTP_VERSION_V2) {
1022                         return false;
1023                 }
1024
1025                 /* The original V2 implementation uses bytes 2-7 of
1026                  * the UUID to match the packet to the timestamp. This
1027                  * discards two of the bytes of the MAC address used
1028                  * to create the UUID (SF bug 33070).  The PTP V2
1029                  * enhanced mode fixes this issue and uses bytes 0-2
1030                  * and byte 5-7 of the UUID.
1031                  */
1032                 match_data_345 = skb->data + PTP_V2_UUID_OFFSET + 5;
1033                 if (ptp->mode == MC_CMD_PTP_MODE_V2) {
1034                         match_data_012 = skb->data + PTP_V2_UUID_OFFSET + 2;
1035                 } else {
1036                         match_data_012 = skb->data + PTP_V2_UUID_OFFSET + 0;
1037                         BUG_ON(ptp->mode != MC_CMD_PTP_MODE_V2_ENHANCED);
1038                 }
1039         }
1040
1041         /* Does this packet require timestamping? */
1042         if (ntohs(*(__be16 *)&skb->data[PTP_DPORT_OFFSET]) == PTP_EVENT_PORT) {
1043                 struct skb_shared_hwtstamps *timestamps;
1044
1045                 match->state = PTP_PACKET_STATE_UNMATCHED;
1046
1047                 /* Clear all timestamps held: filled in later */
1048                 timestamps = skb_hwtstamps(skb);
1049                 memset(timestamps, 0, sizeof(*timestamps));
1050
1051                 /* We expect the sequence number to be in the same position in
1052                  * the packet for PTP V1 and V2
1053                  */
1054                 BUILD_BUG_ON(PTP_V1_SEQUENCE_OFFSET != PTP_V2_SEQUENCE_OFFSET);
1055                 BUILD_BUG_ON(PTP_V1_SEQUENCE_LENGTH != PTP_V2_SEQUENCE_LENGTH);
1056
1057                 /* Extract UUID/Sequence information */
1058                 match->words[0] = (match_data_012[0]         |
1059                                    (match_data_012[1] << 8)  |
1060                                    (match_data_012[2] << 16) |
1061                                    (match_data_345[0] << 24));
1062                 match->words[1] = (match_data_345[1]         |
1063                                    (match_data_345[2] << 8)  |
1064                                    (skb->data[PTP_V1_SEQUENCE_OFFSET +
1065                                               PTP_V1_SEQUENCE_LENGTH - 1] <<
1066                                     16));
1067         } else {
1068                 match->state = PTP_PACKET_STATE_MATCH_UNWANTED;
1069         }
1070
1071         skb_queue_tail(&ptp->rxq, skb);
1072         queue_work(ptp->workwq, &ptp->work);
1073
1074         return true;
1075 }
1076
1077 /* Transmit a PTP packet.  This has to be transmitted by the MC
1078  * itself, through an MCDI call.  MCDI calls aren't permitted
1079  * in the transmit path so defer the actual transmission to a suitable worker.
1080  */
1081 int efx_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
1082 {
1083         struct efx_ptp_data *ptp = efx->ptp_data;
1084
1085         skb_queue_tail(&ptp->txq, skb);
1086
1087         if ((udp_hdr(skb)->dest == htons(PTP_EVENT_PORT)) &&
1088             (skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM))
1089                 efx_xmit_hwtstamp_pending(skb);
1090         queue_work(ptp->workwq, &ptp->work);
1091
1092         return NETDEV_TX_OK;
1093 }
1094
1095 static int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted,
1096                                unsigned int new_mode)
1097 {
1098         if ((enable_wanted != efx->ptp_data->enabled) ||
1099             (enable_wanted && (efx->ptp_data->mode != new_mode))) {
1100                 int rc;
1101
1102                 if (enable_wanted) {
1103                         /* Change of mode requires disable */
1104                         if (efx->ptp_data->enabled &&
1105                             (efx->ptp_data->mode != new_mode)) {
1106                                 efx->ptp_data->enabled = false;
1107                                 rc = efx_ptp_stop(efx);
1108                                 if (rc != 0)
1109                                         return rc;
1110                         }
1111
1112                         /* Set new operating mode and establish
1113                          * baseline synchronisation, which must
1114                          * succeed.
1115                          */
1116                         efx->ptp_data->mode = new_mode;
1117                         rc = efx_ptp_start(efx);
1118                         if (rc == 0) {
1119                                 rc = efx_ptp_synchronize(efx,
1120                                                          PTP_SYNC_ATTEMPTS * 2);
1121                                 if (rc != 0)
1122                                         efx_ptp_stop(efx);
1123                         }
1124                 } else {
1125                         rc = efx_ptp_stop(efx);
1126                 }
1127
1128                 if (rc != 0)
1129                         return rc;
1130
1131                 efx->ptp_data->enabled = enable_wanted;
1132         }
1133
1134         return 0;
1135 }
1136
1137 static int efx_ptp_ts_init(struct efx_nic *efx, struct hwtstamp_config *init)
1138 {
1139         bool enable_wanted = false;
1140         unsigned int new_mode;
1141         int rc;
1142
1143         if (init->flags)
1144                 return -EINVAL;
1145
1146         if ((init->tx_type != HWTSTAMP_TX_OFF) &&
1147             (init->tx_type != HWTSTAMP_TX_ON))
1148                 return -ERANGE;
1149
1150         new_mode = efx->ptp_data->mode;
1151         /* Determine whether any PTP HW operations are required */
1152         switch (init->rx_filter) {
1153         case HWTSTAMP_FILTER_NONE:
1154                 break;
1155         case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
1156         case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
1157         case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
1158                 init->rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_EVENT;
1159                 new_mode = MC_CMD_PTP_MODE_V1;
1160                 enable_wanted = true;
1161                 break;
1162         case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
1163         case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
1164         case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
1165         /* Although these three are accepted only IPV4 packets will be
1166          * timestamped
1167          */
1168                 init->rx_filter = HWTSTAMP_FILTER_PTP_V2_L4_EVENT;
1169                 new_mode = MC_CMD_PTP_MODE_V2_ENHANCED;
1170                 enable_wanted = true;
1171                 break;
1172         case HWTSTAMP_FILTER_PTP_V2_EVENT:
1173         case HWTSTAMP_FILTER_PTP_V2_SYNC:
1174         case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
1175         case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
1176         case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
1177         case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
1178                 /* Non-IP + IPv6 timestamping not supported */
1179                 return -ERANGE;
1180                 break;
1181         default:
1182                 return -ERANGE;
1183         }
1184
1185         if (init->tx_type != HWTSTAMP_TX_OFF)
1186                 enable_wanted = true;
1187
1188         /* Old versions of the firmware do not support the improved
1189          * UUID filtering option (SF bug 33070).  If the firmware does
1190          * not accept the enhanced mode, fall back to the standard PTP
1191          * v2 UUID filtering.
1192          */
1193         rc = efx_ptp_change_mode(efx, enable_wanted, new_mode);
1194         if ((rc != 0) && (new_mode == MC_CMD_PTP_MODE_V2_ENHANCED))
1195                 rc = efx_ptp_change_mode(efx, enable_wanted, MC_CMD_PTP_MODE_V2);
1196         if (rc != 0)
1197                 return rc;
1198
1199         efx->ptp_data->config = *init;
1200
1201         return 0;
1202 }
1203
1204 int
1205 efx_ptp_get_ts_info(struct net_device *net_dev, struct ethtool_ts_info *ts_info)
1206 {
1207         struct efx_nic *efx = netdev_priv(net_dev);
1208         struct efx_ptp_data *ptp = efx->ptp_data;
1209
1210         if (!ptp)
1211                 return -EOPNOTSUPP;
1212
1213         ts_info->so_timestamping = (SOF_TIMESTAMPING_TX_HARDWARE |
1214                                     SOF_TIMESTAMPING_RX_HARDWARE |
1215                                     SOF_TIMESTAMPING_RAW_HARDWARE);
1216         ts_info->phc_index = ptp_clock_index(ptp->phc_clock);
1217         ts_info->tx_types = 1 << HWTSTAMP_TX_OFF | 1 << HWTSTAMP_TX_ON;
1218         ts_info->rx_filters = (1 << HWTSTAMP_FILTER_NONE |
1219                                1 << HWTSTAMP_FILTER_PTP_V1_L4_EVENT |
1220                                1 << HWTSTAMP_FILTER_PTP_V1_L4_SYNC |
1221                                1 << HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ |
1222                                1 << HWTSTAMP_FILTER_PTP_V2_L4_EVENT |
1223                                1 << HWTSTAMP_FILTER_PTP_V2_L4_SYNC |
1224                                1 << HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ);
1225         return 0;
1226 }
1227
1228 int efx_ptp_ioctl(struct efx_nic *efx, struct ifreq *ifr, int cmd)
1229 {
1230         struct hwtstamp_config config;
1231         int rc;
1232
1233         /* Not a PTP enabled port */
1234         if (!efx->ptp_data)
1235                 return -EOPNOTSUPP;
1236
1237         if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
1238                 return -EFAULT;
1239
1240         rc = efx_ptp_ts_init(efx, &config);
1241         if (rc != 0)
1242                 return rc;
1243
1244         return copy_to_user(ifr->ifr_data, &config, sizeof(config))
1245                 ? -EFAULT : 0;
1246 }
1247
1248 static void ptp_event_failure(struct efx_nic *efx, int expected_frag_len)
1249 {
1250         struct efx_ptp_data *ptp = efx->ptp_data;
1251
1252         netif_err(efx, hw, efx->net_dev,
1253                 "PTP unexpected event length: got %d expected %d\n",
1254                 ptp->evt_frag_idx, expected_frag_len);
1255         ptp->reset_required = true;
1256         queue_work(ptp->workwq, &ptp->work);
1257 }
1258
1259 /* Process a completed receive event.  Put it on the event queue and
1260  * start worker thread.  This is required because event and their
1261  * correspoding packets may come in either order.
1262  */
1263 static void ptp_event_rx(struct efx_nic *efx, struct efx_ptp_data *ptp)
1264 {
1265         struct efx_ptp_event_rx *evt = NULL;
1266
1267         if (ptp->evt_frag_idx != 3) {
1268                 ptp_event_failure(efx, 3);
1269                 return;
1270         }
1271
1272         spin_lock_bh(&ptp->evt_lock);
1273         if (!list_empty(&ptp->evt_free_list)) {
1274                 evt = list_first_entry(&ptp->evt_free_list,
1275                                        struct efx_ptp_event_rx, link);
1276                 list_del(&evt->link);
1277
1278                 evt->seq0 = EFX_QWORD_FIELD(ptp->evt_frags[2], MCDI_EVENT_DATA);
1279                 evt->seq1 = (EFX_QWORD_FIELD(ptp->evt_frags[2],
1280                                              MCDI_EVENT_SRC)        |
1281                              (EFX_QWORD_FIELD(ptp->evt_frags[1],
1282                                               MCDI_EVENT_SRC) << 8) |
1283                              (EFX_QWORD_FIELD(ptp->evt_frags[0],
1284                                               MCDI_EVENT_SRC) << 16));
1285                 evt->hwtimestamp = ktime_set(
1286                         EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA),
1287                         EFX_QWORD_FIELD(ptp->evt_frags[1], MCDI_EVENT_DATA));
1288                 evt->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
1289                 list_add_tail(&evt->link, &ptp->evt_list);
1290
1291                 queue_work(ptp->workwq, &ptp->work);
1292         } else {
1293                 netif_err(efx, rx_err, efx->net_dev, "No free PTP event");
1294         }
1295         spin_unlock_bh(&ptp->evt_lock);
1296 }
1297
1298 static void ptp_event_fault(struct efx_nic *efx, struct efx_ptp_data *ptp)
1299 {
1300         int code = EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA);
1301         if (ptp->evt_frag_idx != 1) {
1302                 ptp_event_failure(efx, 1);
1303                 return;
1304         }
1305
1306         netif_err(efx, hw, efx->net_dev, "PTP error %d\n", code);
1307 }
1308
1309 static void ptp_event_pps(struct efx_nic *efx, struct efx_ptp_data *ptp)
1310 {
1311         if (ptp->nic_ts_enabled)
1312                 queue_work(ptp->pps_workwq, &ptp->pps_work);
1313 }
1314
1315 void efx_ptp_event(struct efx_nic *efx, efx_qword_t *ev)
1316 {
1317         struct efx_ptp_data *ptp = efx->ptp_data;
1318         int code = EFX_QWORD_FIELD(*ev, MCDI_EVENT_CODE);
1319
1320         if (!ptp->enabled)
1321                 return;
1322
1323         if (ptp->evt_frag_idx == 0) {
1324                 ptp->evt_code = code;
1325         } else if (ptp->evt_code != code) {
1326                 netif_err(efx, hw, efx->net_dev,
1327                           "PTP out of sequence event %d\n", code);
1328                 ptp->evt_frag_idx = 0;
1329         }
1330
1331         ptp->evt_frags[ptp->evt_frag_idx++] = *ev;
1332         if (!MCDI_EVENT_FIELD(*ev, CONT)) {
1333                 /* Process resulting event */
1334                 switch (code) {
1335                 case MCDI_EVENT_CODE_PTP_RX:
1336                         ptp_event_rx(efx, ptp);
1337                         break;
1338                 case MCDI_EVENT_CODE_PTP_FAULT:
1339                         ptp_event_fault(efx, ptp);
1340                         break;
1341                 case MCDI_EVENT_CODE_PTP_PPS:
1342                         ptp_event_pps(efx, ptp);
1343                         break;
1344                 default:
1345                         netif_err(efx, hw, efx->net_dev,
1346                                   "PTP unknown event %d\n", code);
1347                         break;
1348                 }
1349                 ptp->evt_frag_idx = 0;
1350         } else if (MAX_EVENT_FRAGS == ptp->evt_frag_idx) {
1351                 netif_err(efx, hw, efx->net_dev,
1352                           "PTP too many event fragments\n");
1353                 ptp->evt_frag_idx = 0;
1354         }
1355 }
1356
1357 static int efx_phc_adjfreq(struct ptp_clock_info *ptp, s32 delta)
1358 {
1359         struct efx_ptp_data *ptp_data = container_of(ptp,
1360                                                      struct efx_ptp_data,
1361                                                      phc_clock_info);
1362         struct efx_nic *efx = ptp_data->channel->efx;
1363         u8 inadj[MC_CMD_PTP_IN_ADJUST_LEN];
1364         s64 adjustment_ns;
1365         int rc;
1366
1367         if (delta > MAX_PPB)
1368                 delta = MAX_PPB;
1369         else if (delta < -MAX_PPB)
1370                 delta = -MAX_PPB;
1371
1372         /* Convert ppb to fixed point ns. */
1373         adjustment_ns = (((s64)delta * PPB_SCALE_WORD) >>
1374                          (PPB_EXTRA_BITS + MAX_PPB_BITS));
1375
1376         MCDI_SET_DWORD(inadj, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
1377         MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_FREQ_LO, (u32)adjustment_ns);
1378         MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_FREQ_HI,
1379                        (u32)(adjustment_ns >> 32));
1380         MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_SECONDS, 0);
1381         MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_NANOSECONDS, 0);
1382         rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inadj, sizeof(inadj),
1383                           NULL, 0, NULL);
1384         if (rc != 0)
1385                 return rc;
1386
1387         ptp_data->current_adjfreq = delta;
1388         return 0;
1389 }
1390
1391 static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta)
1392 {
1393         struct efx_ptp_data *ptp_data = container_of(ptp,
1394                                                      struct efx_ptp_data,
1395                                                      phc_clock_info);
1396         struct efx_nic *efx = ptp_data->channel->efx;
1397         struct timespec delta_ts = ns_to_timespec(delta);
1398         u8 inbuf[MC_CMD_PTP_IN_ADJUST_LEN];
1399
1400         MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
1401         MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_FREQ_LO, 0);
1402         MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_FREQ_HI, 0);
1403         MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_SECONDS, (u32)delta_ts.tv_sec);
1404         MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_NANOSECONDS, (u32)delta_ts.tv_nsec);
1405         return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
1406                             NULL, 0, NULL);
1407 }
1408
1409 static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec *ts)
1410 {
1411         struct efx_ptp_data *ptp_data = container_of(ptp,
1412                                                      struct efx_ptp_data,
1413                                                      phc_clock_info);
1414         struct efx_nic *efx = ptp_data->channel->efx;
1415         u8 inbuf[MC_CMD_PTP_IN_READ_NIC_TIME_LEN];
1416         u8 outbuf[MC_CMD_PTP_OUT_READ_NIC_TIME_LEN];
1417         int rc;
1418
1419         MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_READ_NIC_TIME);
1420
1421         rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
1422                           outbuf, sizeof(outbuf), NULL);
1423         if (rc != 0)
1424                 return rc;
1425
1426         ts->tv_sec = MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_SECONDS);
1427         ts->tv_nsec = MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_NANOSECONDS);
1428         return 0;
1429 }
1430
1431 static int efx_phc_settime(struct ptp_clock_info *ptp,
1432                            const struct timespec *e_ts)
1433 {
1434         /* Get the current NIC time, efx_phc_gettime.
1435          * Subtract from the desired time to get the offset
1436          * call efx_phc_adjtime with the offset
1437          */
1438         int rc;
1439         struct timespec time_now;
1440         struct timespec delta;
1441
1442         rc = efx_phc_gettime(ptp, &time_now);
1443         if (rc != 0)
1444                 return rc;
1445
1446         delta = timespec_sub(*e_ts, time_now);
1447
1448         rc = efx_phc_adjtime(ptp, timespec_to_ns(&delta));
1449         if (rc != 0)
1450                 return rc;
1451
1452         return 0;
1453 }
1454
1455 static int efx_phc_enable(struct ptp_clock_info *ptp,
1456                           struct ptp_clock_request *request,
1457                           int enable)
1458 {
1459         struct efx_ptp_data *ptp_data = container_of(ptp,
1460                                                      struct efx_ptp_data,
1461                                                      phc_clock_info);
1462         if (request->type != PTP_CLK_REQ_PPS)
1463                 return -EOPNOTSUPP;
1464
1465         ptp_data->nic_ts_enabled = !!enable;
1466         return 0;
1467 }
1468
1469 static const struct efx_channel_type efx_ptp_channel_type = {
1470         .handle_no_channel      = efx_ptp_handle_no_channel,
1471         .pre_probe              = efx_ptp_probe_channel,
1472         .post_remove            = efx_ptp_remove_channel,
1473         .get_name               = efx_ptp_get_channel_name,
1474         /* no copy operation; there is no need to reallocate this channel */
1475         .receive_skb            = efx_ptp_rx,
1476         .keep_eventq            = false,
1477 };
1478
1479 void efx_ptp_probe(struct efx_nic *efx)
1480 {
1481         /* Check whether PTP is implemented on this NIC.  The DISABLE
1482          * operation will succeed if and only if it is implemented.
1483          */
1484         if (efx_ptp_disable(efx) == 0)
1485                 efx->extra_channel_type[EFX_EXTRA_CHANNEL_PTP] =
1486                         &efx_ptp_channel_type;
1487 }