1/*
2 * PTP 1588 clock support
3 *
4 * Copyright (C) 2010 OMICRON electronics GmbH
5 *
6 *  This program is free software; you can redistribute it and/or modify
7 *  it under the terms of the GNU General Public License as published by
8 *  the Free Software Foundation; either version 2 of the License, or
9 *  (at your option) any later version.
10 *
11 *  This program is distributed in the hope that it will be useful,
12 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 *  GNU General Public License for more details.
15 *
16 *  You should have received a copy of the GNU General Public License
17 *  along with this program; if not, write to the Free Software
18 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20#include <linux/idr.h>
21#include <linux/device.h>
22#include <linux/err.h>
23#include <linux/init.h>
24#include <linux/kernel.h>
25#include <linux/module.h>
26#include <linux/posix-clock.h>
27#include <linux/pps_kernel.h>
28#include <linux/slab.h>
29#include <linux/syscalls.h>
30#include <linux/uaccess.h>
31
32#include "ptp_private.h"
33
34#define PTP_MAX_ALARMS 4
35#define PTP_PPS_DEFAULTS (PPS_CAPTUREASSERT | PPS_OFFSETASSERT)
36#define PTP_PPS_EVENT PPS_CAPTUREASSERT
37#define PTP_PPS_MODE (PTP_PPS_DEFAULTS | PPS_CANWAIT | PPS_TSFMT_TSPEC)
38
39/* private globals */
40
41static dev_t ptp_devt;
42static struct class *ptp_class;
43
44static DEFINE_IDA(ptp_clocks_map);
45
46/* time stamp event queue operations */
47
48static inline int queue_free(struct timestamp_event_queue *q)
49{
50	return PTP_MAX_TIMESTAMPS - queue_cnt(q) - 1;
51}
52
53static void enqueue_external_timestamp(struct timestamp_event_queue *queue,
54				       struct ptp_clock_event *src)
55{
56	struct ptp_extts_event *dst;
57	unsigned long flags;
58	s64 seconds;
59	u32 remainder;
60
61	seconds = div_u64_rem(src->timestamp, 1000000000, &remainder);
62
63	spin_lock_irqsave(&queue->lock, flags);
64
65	dst = &queue->buf[queue->tail];
66	dst->index = src->index;
67	dst->t.sec = seconds;
68	dst->t.nsec = remainder;
69
70	if (!queue_free(queue))
71		queue->head = (queue->head + 1) % PTP_MAX_TIMESTAMPS;
72
73	queue->tail = (queue->tail + 1) % PTP_MAX_TIMESTAMPS;
74
75	spin_unlock_irqrestore(&queue->lock, flags);
76}
77
78static s32 scaled_ppm_to_ppb(long ppm)
79{
80	/*
81	 * The 'freq' field in the 'struct timex' is in parts per
82	 * million, but with a 16 bit binary fractional field.
83	 *
84	 * We want to calculate
85	 *
86	 *    ppb = scaled_ppm * 1000 / 2^16
87	 *
88	 * which simplifies to
89	 *
90	 *    ppb = scaled_ppm * 125 / 2^13
91	 */
92	s64 ppb = 1 + ppm;
93	ppb *= 125;
94	ppb >>= 13;
95	return (s32) ppb;
96}
97
98/* posix clock implementation */
99
100static int ptp_clock_getres(struct posix_clock *pc, struct timespec *tp)
101{
102	tp->tv_sec = 0;
103	tp->tv_nsec = 1;
104	return 0;
105}
106
107static int ptp_clock_settime(struct posix_clock *pc, const struct timespec *tp)
108{
109	struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);
110	struct timespec64 ts = timespec_to_timespec64(*tp);
111
112	return  ptp->info->settime64(ptp->info, &ts);
113}
114
115static int ptp_clock_gettime(struct posix_clock *pc, struct timespec *tp)
116{
117	struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);
118	struct timespec64 ts;
119	int err;
120
121	err = ptp->info->gettime64(ptp->info, &ts);
122	if (!err)
123		*tp = timespec64_to_timespec(ts);
124	return err;
125}
126
127static int ptp_clock_adjtime(struct posix_clock *pc, struct timex *tx)
128{
129	struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);
130	struct ptp_clock_info *ops;
131	int err = -EOPNOTSUPP;
132
133	ops = ptp->info;
134
135	if (tx->modes & ADJ_SETOFFSET) {
136		struct timespec ts;
137		ktime_t kt;
138		s64 delta;
139
140		ts.tv_sec  = tx->time.tv_sec;
141		ts.tv_nsec = tx->time.tv_usec;
142
143		if (!(tx->modes & ADJ_NANO))
144			ts.tv_nsec *= 1000;
145
146		if ((unsigned long) ts.tv_nsec >= NSEC_PER_SEC)
147			return -EINVAL;
148
149		kt = timespec_to_ktime(ts);
150		delta = ktime_to_ns(kt);
151		err = ops->adjtime(ops, delta);
152	} else if (tx->modes & ADJ_FREQUENCY) {
153		s32 ppb = scaled_ppm_to_ppb(tx->freq);
154		if (ppb > ops->max_adj || ppb < -ops->max_adj)
155			return -ERANGE;
156		err = ops->adjfreq(ops, ppb);
157		ptp->dialed_frequency = tx->freq;
158	} else if (tx->modes == 0) {
159		tx->freq = ptp->dialed_frequency;
160		err = 0;
161	}
162
163	return err;
164}
165
166static struct posix_clock_operations ptp_clock_ops = {
167	.owner		= THIS_MODULE,
168	.clock_adjtime	= ptp_clock_adjtime,
169	.clock_gettime	= ptp_clock_gettime,
170	.clock_getres	= ptp_clock_getres,
171	.clock_settime	= ptp_clock_settime,
172	.ioctl		= ptp_ioctl,
173	.open		= ptp_open,
174	.poll		= ptp_poll,
175	.read		= ptp_read,
176};
177
178static void delete_ptp_clock(struct posix_clock *pc)
179{
180	struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);
181
182	mutex_destroy(&ptp->tsevq_mux);
183	mutex_destroy(&ptp->pincfg_mux);
184	ida_simple_remove(&ptp_clocks_map, ptp->index);
185	kfree(ptp);
186}
187
188/* public interface */
189
190struct ptp_clock *ptp_clock_register(struct ptp_clock_info *info,
191				     struct device *parent)
192{
193	struct ptp_clock *ptp;
194	int err = 0, index, major = MAJOR(ptp_devt);
195
196	if (info->n_alarm > PTP_MAX_ALARMS)
197		return ERR_PTR(-EINVAL);
198
199	/* Initialize a clock structure. */
200	err = -ENOMEM;
201	ptp = kzalloc(sizeof(struct ptp_clock), GFP_KERNEL);
202	if (ptp == NULL)
203		goto no_memory;
204
205	index = ida_simple_get(&ptp_clocks_map, 0, MINORMASK + 1, GFP_KERNEL);
206	if (index < 0) {
207		err = index;
208		goto no_slot;
209	}
210
211	ptp->clock.ops = ptp_clock_ops;
212	ptp->clock.release = delete_ptp_clock;
213	ptp->info = info;
214	ptp->devid = MKDEV(major, index);
215	ptp->index = index;
216	spin_lock_init(&ptp->tsevq.lock);
217	mutex_init(&ptp->tsevq_mux);
218	mutex_init(&ptp->pincfg_mux);
219	init_waitqueue_head(&ptp->tsev_wq);
220
221	/* Create a new device in our class. */
222	ptp->dev = device_create(ptp_class, parent, ptp->devid, ptp,
223				 "ptp%d", ptp->index);
224	if (IS_ERR(ptp->dev))
225		goto no_device;
226
227	dev_set_drvdata(ptp->dev, ptp);
228
229	err = ptp_populate_sysfs(ptp);
230	if (err)
231		goto no_sysfs;
232
233	/* Register a new PPS source. */
234	if (info->pps) {
235		struct pps_source_info pps;
236		memset(&pps, 0, sizeof(pps));
237		snprintf(pps.name, PPS_MAX_NAME_LEN, "ptp%d", index);
238		pps.mode = PTP_PPS_MODE;
239		pps.owner = info->owner;
240		ptp->pps_source = pps_register_source(&pps, PTP_PPS_DEFAULTS);
241		if (!ptp->pps_source) {
242			pr_err("failed to register pps source\n");
243			goto no_pps;
244		}
245	}
246
247	/* Create a posix clock. */
248	err = posix_clock_register(&ptp->clock, ptp->devid);
249	if (err) {
250		pr_err("failed to create posix clock\n");
251		goto no_clock;
252	}
253
254	return ptp;
255
256no_clock:
257	if (ptp->pps_source)
258		pps_unregister_source(ptp->pps_source);
259no_pps:
260	ptp_cleanup_sysfs(ptp);
261no_sysfs:
262	device_destroy(ptp_class, ptp->devid);
263no_device:
264	mutex_destroy(&ptp->tsevq_mux);
265	mutex_destroy(&ptp->pincfg_mux);
266no_slot:
267	kfree(ptp);
268no_memory:
269	return ERR_PTR(err);
270}
271EXPORT_SYMBOL(ptp_clock_register);
272
273int ptp_clock_unregister(struct ptp_clock *ptp)
274{
275	ptp->defunct = 1;
276	wake_up_interruptible(&ptp->tsev_wq);
277
278	/* Release the clock's resources. */
279	if (ptp->pps_source)
280		pps_unregister_source(ptp->pps_source);
281	ptp_cleanup_sysfs(ptp);
282	device_destroy(ptp_class, ptp->devid);
283
284	posix_clock_unregister(&ptp->clock);
285	return 0;
286}
287EXPORT_SYMBOL(ptp_clock_unregister);
288
289void ptp_clock_event(struct ptp_clock *ptp, struct ptp_clock_event *event)
290{
291	struct pps_event_time evt;
292
293	switch (event->type) {
294
295	case PTP_CLOCK_ALARM:
296		break;
297
298	case PTP_CLOCK_EXTTS:
299		enqueue_external_timestamp(&ptp->tsevq, event);
300		wake_up_interruptible(&ptp->tsev_wq);
301		break;
302
303	case PTP_CLOCK_PPS:
304		pps_get_ts(&evt);
305		pps_event(ptp->pps_source, &evt, PTP_PPS_EVENT, NULL);
306		break;
307
308	case PTP_CLOCK_PPSUSR:
309		pps_event(ptp->pps_source, &event->pps_times,
310			  PTP_PPS_EVENT, NULL);
311		break;
312	}
313}
314EXPORT_SYMBOL(ptp_clock_event);
315
316int ptp_clock_index(struct ptp_clock *ptp)
317{
318	return ptp->index;
319}
320EXPORT_SYMBOL(ptp_clock_index);
321
322int ptp_find_pin(struct ptp_clock *ptp,
323		 enum ptp_pin_function func, unsigned int chan)
324{
325	struct ptp_pin_desc *pin = NULL;
326	int i;
327
328	mutex_lock(&ptp->pincfg_mux);
329	for (i = 0; i < ptp->info->n_pins; i++) {
330		if (ptp->info->pin_config[i].func == func &&
331		    ptp->info->pin_config[i].chan == chan) {
332			pin = &ptp->info->pin_config[i];
333			break;
334		}
335	}
336	mutex_unlock(&ptp->pincfg_mux);
337
338	return pin ? i : -1;
339}
340EXPORT_SYMBOL(ptp_find_pin);
341
342/* module operations */
343
344static void __exit ptp_exit(void)
345{
346	class_destroy(ptp_class);
347	unregister_chrdev_region(ptp_devt, MINORMASK + 1);
348	ida_destroy(&ptp_clocks_map);
349}
350
351static int __init ptp_init(void)
352{
353	int err;
354
355	ptp_class = class_create(THIS_MODULE, "ptp");
356	if (IS_ERR(ptp_class)) {
357		pr_err("ptp: failed to allocate class\n");
358		return PTR_ERR(ptp_class);
359	}
360
361	err = alloc_chrdev_region(&ptp_devt, 0, MINORMASK + 1, "ptp");
362	if (err < 0) {
363		pr_err("ptp: failed to allocate device region\n");
364		goto no_region;
365	}
366
367	ptp_class->dev_groups = ptp_groups;
368	pr_info("PTP clock support registered\n");
369	return 0;
370
371no_region:
372	class_destroy(ptp_class);
373	return err;
374}
375
376subsys_initcall(ptp_init);
377module_exit(ptp_exit);
378
379MODULE_AUTHOR("Richard Cochran <richardcochran@gmail.com>");
380MODULE_DESCRIPTION("PTP clocks support");
381MODULE_LICENSE("GPL");
382