2 * linux/kernel/time/timecounter.c
4 * based on code that migrated away from
5 * linux/kernel/time/clocksource.c
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
18 #include <linux/export.h>
19 #include <linux/timecounter.h>
21 void timecounter_init(struct timecounter *tc,
22 const struct cyclecounter *cc,
26 tc->cycle_last = cc->read(cc);
27 tc->nsec = start_tstamp;
29 EXPORT_SYMBOL_GPL(timecounter_init);
32 * timecounter_read_delta - get nanoseconds since last call of this function
33 * @tc: Pointer to time counter
35 * When the underlying cycle counter runs over, this will be handled
36 * correctly as long as it does not run over more than once between
39 * The first call to this function for a new time counter initializes
40 * the time tracking and returns an undefined result.
42 static u64 timecounter_read_delta(struct timecounter *tc)
44 cycle_t cycle_now, cycle_delta;
47 /* read cycle counter: */
48 cycle_now = tc->cc->read(tc->cc);
50 /* calculate the delta since the last timecounter_read_delta(): */
51 cycle_delta = (cycle_now - tc->cycle_last) & tc->cc->mask;
53 /* convert to nanoseconds: */
54 ns_offset = cyclecounter_cyc2ns(tc->cc, cycle_delta);
56 /* update time stamp of timecounter_read_delta() call: */
57 tc->cycle_last = cycle_now;
62 u64 timecounter_read(struct timecounter *tc)
66 /* increment time by nanoseconds since last call */
67 nsec = timecounter_read_delta(tc);
73 EXPORT_SYMBOL_GPL(timecounter_read);
75 u64 timecounter_cyc2time(struct timecounter *tc,
78 u64 cycle_delta = (cycle_tstamp - tc->cycle_last) & tc->cc->mask;
82 * Instead of always treating cycle_tstamp as more recent
83 * than tc->cycle_last, detect when it is too far in the
84 * future and treat it as old time stamp instead.
86 if (cycle_delta > tc->cc->mask / 2) {
87 cycle_delta = (tc->cycle_last - cycle_tstamp) & tc->cc->mask;
88 nsec = tc->nsec - cyclecounter_cyc2ns(tc->cc, cycle_delta);
90 nsec = cyclecounter_cyc2ns(tc->cc, cycle_delta) + tc->nsec;
95 EXPORT_SYMBOL_GPL(timecounter_cyc2time);