xref: /openbmc/qemu/docs/devel/clocks.rst (revision abaabb2e)
1Modelling a clock tree in QEMU
2==============================
3
4What are clocks?
5----------------
6
7Clocks are QOM objects developed for the purpose of modelling the
8distribution of clocks in QEMU.
9
10They allow us to model the clock distribution of a platform and detect
11configuration errors in the clock tree such as badly configured PLL, clock
12source selection or disabled clock.
13
14The object is *Clock* and its QOM name is ``clock`` (in C code, the macro
15``TYPE_CLOCK``).
16
17Clocks are typically used with devices where they are used to model inputs
18and outputs. They are created in a similar way to GPIOs. Inputs and outputs
19of different devices can be connected together.
20
21In these cases a Clock object is a child of a Device object, but this
22is not a requirement. Clocks can be independent of devices. For
23example it is possible to create a clock outside of any device to
24model the main clock source of a machine.
25
26Here is an example of clocks::
27
28    +---------+      +----------------------+   +--------------+
29    | Clock 1 |      |       Device B       |   |   Device C   |
30    |         |      | +-------+  +-------+ |   | +-------+    |
31    |         |>>-+-->>|Clock 2|  |Clock 3|>>--->>|Clock 6|    |
32    +---------+   |  | | (in)  |  | (out) | |   | | (in)  |    |
33                  |  | +-------+  +-------+ |   | +-------+    |
34                  |  |            +-------+ |   +--------------+
35                  |  |            |Clock 4|>>
36                  |  |            | (out) | |   +--------------+
37                  |  |            +-------+ |   |   Device D   |
38                  |  |            +-------+ |   | +-------+    |
39                  |  |            |Clock 5|>>--->>|Clock 7|    |
40                  |  |            | (out) | |   | | (in)  |    |
41                  |  |            +-------+ |   | +-------+    |
42                  |  +----------------------+   |              |
43                  |                             | +-------+    |
44                  +----------------------------->>|Clock 8|    |
45                                                | | (in)  |    |
46                                                | +-------+    |
47                                                +--------------+
48
49Clocks are defined in the ``include/hw/clock.h`` header and device
50related functions are defined in the ``include/hw/qdev-clock.h``
51header.
52
53The clock state
54---------------
55
56The state of a clock is its period; it is stored as an integer
57representing it in units of 2 :sup:`-32` ns. The special value of 0 is used to
58represent the clock being inactive or gated. The clocks do not model
59the signal itself (pin toggling) or other properties such as the duty
60cycle.
61
62All clocks contain this state: outputs as well as inputs. This allows
63the current period of a clock to be fetched at any time. When a clock
64is updated, the value is immediately propagated to all connected
65clocks in the tree.
66
67To ease interaction with clocks, helpers with a unit suffix are defined for
68every clock state setter or getter. The suffixes are:
69
70- ``_ns`` for handling periods in nanoseconds
71- ``_hz`` for handling frequencies in hertz
72
73The 0 period value is converted to 0 in hertz and vice versa. 0 always means
74that the clock is disabled.
75
76Adding a new clock
77------------------
78
79Adding clocks to a device must be done during the init method of the Device
80instance.
81
82To add an input clock to a device, the function ``qdev_init_clock_in()``
83must be used.  It takes the name, a callback, an opaque parameter
84for the callback and a mask of events when the callback should be
85called (this will be explained in a following section).
86Output is simpler; only the name is required. Typically::
87
88    qdev_init_clock_in(DEVICE(dev), "clk_in", clk_in_callback, dev, ClockUpdate);
89    qdev_init_clock_out(DEVICE(dev), "clk_out");
90
91Both functions return the created Clock pointer, which should be saved in the
92device's state structure for further use.
93
94These objects will be automatically deleted by the QOM reference mechanism.
95
96Note that it is possible to create a static array describing clock inputs and
97outputs. The function ``qdev_init_clocks()`` must be called with the array as
98parameter to initialize the clocks: it has the same behaviour as calling the
99``qdev_init_clock_in/out()`` for each clock in the array. To ease the array
100construction, some macros are defined in ``include/hw/qdev-clock.h``.
101As an example, the following creates 2 clocks to a device: one input and one
102output.
103
104.. code-block:: c
105
106    /* device structure containing pointers to the clock objects */
107    typedef struct MyDeviceState {
108        DeviceState parent_obj;
109        Clock *clk_in;
110        Clock *clk_out;
111    } MyDeviceState;
112
113    /*
114     * callback for the input clock (see "Callback on input clock
115     * change" section below for more information).
116     */
117    static void clk_in_callback(void *opaque, ClockEvent event);
118
119    /*
120     * static array describing clocks:
121     * + a clock input named "clk_in", whose pointer is stored in
122     *   the clk_in field of a MyDeviceState structure with callback
123     *   clk_in_callback.
124     * + a clock output named "clk_out" whose pointer is stored in
125     *   the clk_out field of a MyDeviceState structure.
126     */
127    static const ClockPortInitArray mydev_clocks = {
128        QDEV_CLOCK_IN(MyDeviceState, clk_in, clk_in_callback, ClockUpdate),
129        QDEV_CLOCK_OUT(MyDeviceState, clk_out),
130        QDEV_CLOCK_END
131    };
132
133    /* device initialization function */
134    static void mydev_init(Object *obj)
135    {
136        /* cast to MyDeviceState */
137        MyDeviceState *mydev = MYDEVICE(obj);
138        /* create and fill the pointer fields in the MyDeviceState */
139        qdev_init_clocks(mydev, mydev_clocks);
140        [...]
141    }
142
143An alternative way to create a clock is to simply call
144``object_new(TYPE_CLOCK)``. In that case the clock will neither be an
145input nor an output of a device. After the whole QOM hierarchy of the
146clock has been set ``clock_setup_canonical_path()`` should be called.
147
148At creation, the period of the clock is 0: the clock is disabled. You can
149change it using ``clock_set_ns()`` or ``clock_set_hz()``.
150
151Note that if you are creating a clock with a fixed period which will never
152change (for example the main clock source of a board), then you'll have
153nothing else to do. This value will be propagated to other clocks when
154connecting the clocks together and devices will fetch the right value during
155the first reset.
156
157Clock callbacks
158---------------
159
160You can give a clock a callback function in several ways:
161
162 * by passing it as an argument to ``qdev_init_clock_in()``
163 * as an argument to the ``QDEV_CLOCK_IN()`` macro initializing an
164   array to be passed to ``qdev_init_clocks()``
165 * by directly calling the ``clock_set_callback()`` function
166
167The callback function must be of this type:
168
169.. code-block:: c
170
171   typedef void ClockCallback(void *opaque, ClockEvent event);
172
173The ``opaque`` argument is the pointer passed to ``qdev_init_clock_in()``
174or ``clock_set_callback()``; for ``qdev_init_clocks()`` it is the
175``dev`` device pointer.
176
177The ``event`` argument specifies why the callback has been called.
178When you register the callback you specify a mask of ClockEvent values
179that you are interested in. The callback will only be called for those
180events.
181
182The events currently supported are:
183
184 * ``ClockPreUpdate`` : called when the input clock's period is about to
185   update. This is useful if the device needs to do some action for
186   which it needs to know the old value of the clock period. During
187   this callback, Clock API functions like ``clock_get()`` or
188   ``clock_ticks_to_ns()`` will use the old period.
189 * ``ClockUpdate`` : called after the input clock's period has changed.
190   During this callback, Clock API functions like ``clock_ticks_to_ns()``
191   will use the new period.
192
193Note that a clock only has one callback: it is not possible to register
194different functions for different events. You must register a single
195callback which listens for all of the events you are interested in,
196and use the ``event`` argument to identify which event has happened.
197
198Retrieving clocks from a device
199-------------------------------
200
201``qdev_get_clock_in()`` and ``dev_get_clock_out()`` are available to
202get the clock inputs or outputs of a device. For example:
203
204.. code-block:: c
205
206   Clock *clk = qdev_get_clock_in(DEVICE(mydev), "clk_in");
207
208or:
209
210.. code-block:: c
211
212   Clock *clk = qdev_get_clock_out(DEVICE(mydev), "clk_out");
213
214Connecting two clocks together
215------------------------------
216
217To connect two clocks together, use the ``clock_set_source()`` function.
218Given two clocks ``clk1``, and ``clk2``, ``clock_set_source(clk2, clk1);``
219configures ``clk2`` to follow the ``clk1`` period changes. Every time ``clk1``
220is updated, ``clk2`` will be updated too.
221
222When connecting clock between devices, prefer using the
223``qdev_connect_clock_in()`` function to set the source of an input
224device clock.  For example, to connect the input clock ``clk2`` of
225``devB`` to the output clock ``clk1`` of ``devA``, do:
226
227.. code-block:: c
228
229    qdev_connect_clock_in(devB, "clk2", qdev_get_clock_out(devA, "clk1"))
230
231We used ``qdev_get_clock_out()`` above, but any clock can drive an
232input clock, even another input clock. The following diagram shows
233some examples of connections. Note also that a clock can drive several
234other clocks.
235
236::
237
238  +------------+  +--------------------------------------------------+
239  |  Device A  |  |                   Device B                       |
240  |            |  |               +---------------------+            |
241  |            |  |               |       Device C      |            |
242  |  +-------+ |  | +-------+     | +-------+ +-------+ |  +-------+ |
243  |  |Clock 1|>>-->>|Clock 2|>>+-->>|Clock 3| |Clock 5|>>>>|Clock 6|>>
244  |  | (out) | |  | | (in)  |  |  | | (in)  | | (out) | |  | (out) | |
245  |  +-------+ |  | +-------+  |  | +-------+ +-------+ |  +-------+ |
246  +------------+  |            |  +---------------------+            |
247                  |            |                                     |
248                  |            |  +--------------+                   |
249                  |            |  |   Device D   |                   |
250                  |            |  | +-------+    |                   |
251                  |            +-->>|Clock 4|    |                   |
252                  |               | | (in)  |    |                   |
253                  |               | +-------+    |                   |
254                  |               +--------------+                   |
255                  +--------------------------------------------------+
256
257In the above example, when *Clock 1* is updated by *Device A*, three
258clocks get the new clock period value: *Clock 2*, *Clock 3* and *Clock 4*.
259
260It is not possible to disconnect a clock or to change the clock connection
261after it is connected.
262
263Clock multiplier and divider settings
264-------------------------------------
265
266By default, when clocks are connected together, the child
267clocks run with the same period as their source (parent) clock.
268The Clock API supports a built-in period multiplier/divider
269mechanism so you can configure a clock to make its children
270run at a different period from its own. If you call the
271``clock_set_mul_div()`` function you can specify the clock's
272multiplier and divider values. The children of that clock
273will all run with a period of ``parent_period * multiplier / divider``.
274For instance, if the clock has a frequency of 8MHz and you set its
275multiplier to 2 and its divider to 3, the child clocks will run
276at 12MHz.
277
278You can change the multiplier and divider of a clock at runtime,
279so you can use this to model clock controller devices which
280have guest-programmable frequency multipliers or dividers.
281
282Similarly to ``clock_set()``, ``clock_set_mul_div()`` returns ``true`` if
283the clock state was modified; that is, if the multiplier or the diviser
284or both were changed by the call.
285
286Note that ``clock_set_mul_div()`` does not automatically call
287``clock_propagate()``. If you make a runtime change to the
288multiplier or divider you must call clock_propagate() yourself.
289
290Unconnected input clocks
291------------------------
292
293A newly created input clock is disabled (period of 0). This means the
294clock will be considered as disabled until the period is updated. If
295the clock remains unconnected it will always keep its initial value
296of 0. If this is not the desired behaviour, ``clock_set()``,
297``clock_set_ns()`` or ``clock_set_hz()`` should be called on the Clock
298object during device instance init. For example:
299
300.. code-block:: c
301
302    clk = qdev_init_clock_in(DEVICE(dev), "clk-in", clk_in_callback,
303                             dev, ClockUpdate);
304    /* set initial value to 10ns / 100MHz */
305    clock_set_ns(clk, 10);
306
307To enforce that the clock is wired up by the board code, you can
308call ``clock_has_source()`` in your device's realize method:
309
310.. code-block:: c
311
312   if (!clock_has_source(s->clk)) {
313       error_setg(errp, "MyDevice: clk input must be connected");
314       return;
315   }
316
317Note that this only checks that the clock has been wired up; it is
318still possible that the output clock connected to it is disabled
319or has not yet been configured, in which case the period will be
320zero. You should use the clock callback to find out when the clock
321period changes.
322
323Fetching clock frequency/period
324-------------------------------
325
326To get the current state of a clock, use the functions ``clock_get()``
327or ``clock_get_hz()``.
328
329``clock_get()`` returns the period of the clock in its fully precise
330internal representation, as an unsigned 64-bit integer in units of
3312^-32 nanoseconds. (For many purposes ``clock_ticks_to_ns()`` will
332be more convenient; see the section below on expiry deadlines.)
333
334``clock_get_hz()`` returns the frequency of the clock, rounded to the
335next lowest integer. This implies some inaccuracy due to the rounding,
336so be cautious about using it in calculations.
337
338It is also possible to register a callback on clock frequency changes.
339Here is an example, which assumes that ``clock_callback`` has been
340specified as the callback for the ``ClockUpdate`` event:
341
342.. code-block:: c
343
344    void clock_callback(void *opaque, ClockEvent event) {
345        MyDeviceState *s = (MyDeviceState *) opaque;
346        /*
347         * 'opaque' is the argument passed to qdev_init_clock_in();
348         * usually this will be the device state pointer.
349         */
350
351        /* do something with the new period */
352        fprintf(stdout, "device new period is %" PRIu64 "* 2^-32 ns\n",
353                        clock_get(dev->my_clk_input));
354    }
355
356If you are only interested in the frequency for displaying it to
357humans (for instance in debugging), use ``clock_display_freq()``,
358which returns a prettified string-representation, e.g. "33.3 MHz".
359The caller must free the string with g_free() after use.
360
361It's also possible to retrieve the clock period from a QTest by
362accessing QOM property ``qtest-clock-period`` using a QMP command.
363This property is only present when the device is being run under
364the ``qtest`` accelerator; it is not available when QEMU is
365being run normally.
366
367Calculating expiry deadlines
368----------------------------
369
370A commonly required operation for a clock is to calculate how long
371it will take for the clock to tick N times; this can then be used
372to set a timer expiry deadline. Use the function ``clock_ticks_to_ns()``,
373which takes an unsigned 64-bit count of ticks and returns the length
374of time in nanoseconds required for the clock to tick that many times.
375
376It is important not to try to calculate expiry deadlines using a
377shortcut like multiplying a "period of clock in nanoseconds" value
378by the tick count, because clocks can have periods which are not a
379whole number of nanoseconds, and the accumulated error in the
380multiplication can be significant.
381
382For a clock with a very long period and a large number of ticks,
383the result of this function could in theory be too large to fit in
384a 64-bit value. To avoid overflow in this case, ``clock_ticks_to_ns()``
385saturates the result to INT64_MAX (because this is the largest valid
386input to the QEMUTimer APIs). Since INT64_MAX nanoseconds is almost
387300 years, anything with an expiry later than that is in the "will
388never happen" category. Callers of ``clock_ticks_to_ns()`` should
389therefore generally not special-case the possibility of a saturated
390result but just allow the timer to be set to that far-future value.
391(If you are performing further calculations on the returned value
392rather than simply passing it to a QEMUTimer function like
393``timer_mod_ns()`` then you should be careful to avoid overflow
394in those calculations, of course.)
395
396Obtaining tick counts
397---------------------
398
399For calculations where you need to know the number of ticks in
400a given duration, use ``clock_ns_to_ticks()``. This function handles
401possible non-whole-number-of-nanoseconds periods and avoids
402potential rounding errors. It will return '0' if the clock is stopped
403(i.e. it has period zero). If the inputs imply a tick count that
404overflows a 64-bit value (a very long duration for a clock with a
405very short period) the output value is truncated, so effectively
406the 64-bit output wraps around.
407
408Changing a clock period
409-----------------------
410
411A device can change its outputs using the ``clock_update()``,
412``clock_update_ns()`` or ``clock_update_hz()`` function. It will trigger
413updates on every connected input.
414
415For example, let's say that we have an output clock *clkout* and we
416have a pointer to it in the device state because we did the following
417in init phase:
418
419.. code-block:: c
420
421   dev->clkout = qdev_init_clock_out(DEVICE(dev), "clkout");
422
423Then at any time (apart from the cases listed below), it is possible to
424change the clock value by doing:
425
426.. code-block:: c
427
428   clock_update_hz(dev->clkout, 1000 * 1000 * 1000); /* 1GHz */
429
430Because updating a clock may trigger any side effects through
431connected clocks and their callbacks, this operation must be done
432while holding the qemu io lock.
433
434For the same reason, one can update clocks only when it is allowed to have
435side effects on other objects. In consequence, it is forbidden:
436
437* during migration,
438* and in the enter phase of reset.
439
440Note that calling ``clock_update[_ns|_hz]()`` is equivalent to calling
441``clock_set[_ns|_hz]()`` (with the same arguments) then
442``clock_propagate()`` on the clock. Thus, setting the clock value can
443be separated from triggering the side-effects. This is often required
444to factorize code to handle reset and migration in devices.
445
446Aliasing clocks
447---------------
448
449Sometimes, one needs to forward, or inherit, a clock from another
450device.  Typically, when doing device composition, a device might
451expose a sub-device's clock without interfering with it.  The function
452``qdev_alias_clock()`` can be used to achieve this behaviour. Note
453that it is possible to expose the clock under a different name.
454``qdev_alias_clock()`` works for both input and output clocks.
455
456For example, if device B is a child of device A,
457``device_a_instance_init()`` may do something like this:
458
459.. code-block:: c
460
461    void device_a_instance_init(Object *obj)
462    {
463        AState *A = DEVICE_A(obj);
464        BState *B;
465        /* create object B as child of A */
466        [...]
467        qdev_alias_clock(B, "clk", A, "b_clk");
468        /*
469         * Now A has a clock "b_clk" which is an alias to
470         * the clock "clk" of its child B.
471         */
472    }
473
474This function does not return any clock object. The new clock has the
475same direction (input or output) as the original one. This function
476only adds a link to the existing clock. In the above example, object B
477remains the only object allowed to use the clock and device A must not
478try to change the clock period or set a callback to the clock. This
479diagram describes the example with an input clock::
480
481    +--------------------------+
482    |        Device A          |
483    |         +--------------+ |
484    |         |   Device B   | |
485    |         | +-------+    | |
486    >>"b_clk">>>| "clk" |    | |
487    |  (in)   | |  (in) |    | |
488    |         | +-------+    | |
489    |         +--------------+ |
490    +--------------------------+
491
492Migration
493---------
494
495Clock state is not migrated automatically. Every device must handle its
496clock migration. Alias clocks must not be migrated.
497
498To ensure clock states are restored correctly during migration, there
499are two solutions.
500
501Clock states can be migrated by adding an entry into the device
502vmstate description. You should use the ``VMSTATE_CLOCK`` macro for this.
503This is typically used to migrate an input clock state. For example:
504
505.. code-block:: c
506
507    MyDeviceState {
508        DeviceState parent_obj;
509        [...] /* some fields */
510        Clock *clk;
511    };
512
513    VMStateDescription my_device_vmstate = {
514        .name = "my_device",
515        .fields = (const VMStateField[]) {
516            [...], /* other migrated fields */
517            VMSTATE_CLOCK(clk, MyDeviceState),
518            VMSTATE_END_OF_LIST()
519        }
520    };
521
522The second solution is to restore the clock state using information already
523at our disposal. This can be used to restore output clock states using the
524device state. The functions ``clock_set[_ns|_hz]()`` can be used during the
525``post_load()`` migration callback.
526
527When adding clock support to an existing device, if you care about
528migration compatibility you will need to be careful, as simply adding
529a ``VMSTATE_CLOCK()`` line will break compatibility. Instead, you can
530put the ``VMSTATE_CLOCK()`` line into a vmstate subsection with a
531suitable ``needed`` function, and use ``clock_set()`` in a
532``pre_load()`` function to set the default value that will be used if
533the source virtual machine in the migration does not send the clock
534state.
535
536Care should be taken not to use ``clock_update[_ns|_hz]()`` or
537``clock_propagate()`` during the whole migration procedure because it
538will trigger side effects to other devices in an unknown state.
539