xref: /openbmc/qemu/docs/devel/clocks.rst (revision 64c9a921)
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 and an opaque parameter
84for the callback (this will be explained in a following section).
85Output is simpler; only the name is required. Typically::
86
87    qdev_init_clock_in(DEVICE(dev), "clk_in", clk_in_callback, dev);
88    qdev_init_clock_out(DEVICE(dev), "clk_out");
89
90Both functions return the created Clock pointer, which should be saved in the
91device's state structure for further use.
92
93These objects will be automatically deleted by the QOM reference mechanism.
94
95Note that it is possible to create a static array describing clock inputs and
96outputs. The function ``qdev_init_clocks()`` must be called with the array as
97parameter to initialize the clocks: it has the same behaviour as calling the
98``qdev_init_clock_in/out()`` for each clock in the array. To ease the array
99construction, some macros are defined in ``include/hw/qdev-clock.h``.
100As an example, the following creates 2 clocks to a device: one input and one
101output.
102
103.. code-block:: c
104
105    /* device structure containing pointers to the clock objects */
106    typedef struct MyDeviceState {
107        DeviceState parent_obj;
108        Clock *clk_in;
109        Clock *clk_out;
110    } MyDeviceState;
111
112    /*
113     * callback for the input clock (see "Callback on input clock
114     * change" section below for more information).
115     */
116    static void clk_in_callback(void *opaque);
117
118    /*
119     * static array describing clocks:
120     * + a clock input named "clk_in", whose pointer is stored in
121     *   the clk_in field of a MyDeviceState structure with callback
122     *   clk_in_callback.
123     * + a clock output named "clk_out" whose pointer is stored in
124     *   the clk_out field of a MyDeviceState structure.
125     */
126    static const ClockPortInitArray mydev_clocks = {
127        QDEV_CLOCK_IN(MyDeviceState, clk_in, clk_in_callback),
128        QDEV_CLOCK_OUT(MyDeviceState, clk_out),
129        QDEV_CLOCK_END
130    };
131
132    /* device initialization function */
133    static void mydev_init(Object *obj)
134    {
135        /* cast to MyDeviceState */
136        MyDeviceState *mydev = MYDEVICE(obj);
137        /* create and fill the pointer fields in the MyDeviceState */
138        qdev_init_clocks(mydev, mydev_clocks);
139        [...]
140    }
141
142An alternative way to create a clock is to simply call
143``object_new(TYPE_CLOCK)``. In that case the clock will neither be an
144input nor an output of a device. After the whole QOM hierarchy of the
145clock has been set ``clock_setup_canonical_path()`` should be called.
146
147At creation, the period of the clock is 0: the clock is disabled. You can
148change it using ``clock_set_ns()`` or ``clock_set_hz()``.
149
150Note that if you are creating a clock with a fixed period which will never
151change (for example the main clock source of a board), then you'll have
152nothing else to do. This value will be propagated to other clocks when
153connecting the clocks together and devices will fetch the right value during
154the first reset.
155
156Retrieving clocks from a device
157-------------------------------
158
159``qdev_get_clock_in()`` and ``dev_get_clock_out()`` are available to
160get the clock inputs or outputs of a device. For example:
161
162.. code-block:: c
163
164   Clock *clk = qdev_get_clock_in(DEVICE(mydev), "clk_in");
165
166or:
167
168.. code-block:: c
169
170   Clock *clk = qdev_get_clock_out(DEVICE(mydev), "clk_out");
171
172Connecting two clocks together
173------------------------------
174
175To connect two clocks together, use the ``clock_set_source()`` function.
176Given two clocks ``clk1``, and ``clk2``, ``clock_set_source(clk2, clk1);``
177configures ``clk2`` to follow the ``clk1`` period changes. Every time ``clk1``
178is updated, ``clk2`` will be updated too.
179
180When connecting clock between devices, prefer using the
181``qdev_connect_clock_in()`` function to set the source of an input
182device clock.  For example, to connect the input clock ``clk2`` of
183``devB`` to the output clock ``clk1`` of ``devA``, do:
184
185.. code-block:: c
186
187    qdev_connect_clock_in(devB, "clk2", qdev_get_clock_out(devA, "clk1"))
188
189We used ``qdev_get_clock_out()`` above, but any clock can drive an
190input clock, even another input clock. The following diagram shows
191some examples of connections. Note also that a clock can drive several
192other clocks.
193
194::
195
196  +------------+  +--------------------------------------------------+
197  |  Device A  |  |                   Device B                       |
198  |            |  |               +---------------------+            |
199  |            |  |               |       Device C      |            |
200  |  +-------+ |  | +-------+     | +-------+ +-------+ |  +-------+ |
201  |  |Clock 1|>>-->>|Clock 2|>>+-->>|Clock 3| |Clock 5|>>>>|Clock 6|>>
202  |  | (out) | |  | | (in)  |  |  | | (in)  | | (out) | |  | (out) | |
203  |  +-------+ |  | +-------+  |  | +-------+ +-------+ |  +-------+ |
204  +------------+  |            |  +---------------------+            |
205                  |            |                                     |
206                  |            |  +--------------+                   |
207                  |            |  |   Device D   |                   |
208                  |            |  | +-------+    |                   |
209                  |            +-->>|Clock 4|    |                   |
210                  |               | | (in)  |    |                   |
211                  |               | +-------+    |                   |
212                  |               +--------------+                   |
213                  +--------------------------------------------------+
214
215In the above example, when *Clock 1* is updated by *Device A*, three
216clocks get the new clock period value: *Clock 2*, *Clock 3* and *Clock 4*.
217
218It is not possible to disconnect a clock or to change the clock connection
219after it is connected.
220
221Unconnected input clocks
222------------------------
223
224A newly created input clock is disabled (period of 0). This means the
225clock will be considered as disabled until the period is updated. If
226the clock remains unconnected it will always keep its initial value
227of 0. If this is not the desired behaviour, ``clock_set()``,
228``clock_set_ns()`` or ``clock_set_hz()`` should be called on the Clock
229object during device instance init. For example:
230
231.. code-block:: c
232
233    clk = qdev_init_clock_in(DEVICE(dev), "clk-in", clk_in_callback,
234                             dev);
235    /* set initial value to 10ns / 100MHz */
236    clock_set_ns(clk, 10);
237
238To enforce that the clock is wired up by the board code, you can
239call ``clock_has_source()`` in your device's realize method:
240
241.. code-block:: c
242
243   if (!clock_has_source(s->clk)) {
244       error_setg(errp, "MyDevice: clk input must be connected");
245       return;
246   }
247
248Note that this only checks that the clock has been wired up; it is
249still possible that the output clock connected to it is disabled
250or has not yet been configured, in which case the period will be
251zero. You should use the clock callback to find out when the clock
252period changes.
253
254Fetching clock frequency/period
255-------------------------------
256
257To get the current state of a clock, use the functions ``clock_get()``
258or ``clock_get_hz()``.
259
260``clock_get()`` returns the period of the clock in its fully precise
261internal representation, as an unsigned 64-bit integer in units of
2622^-32 nanoseconds. (For many purposes ``clock_ticks_to_ns()`` will
263be more convenient; see the section below on expiry deadlines.)
264
265``clock_get_hz()`` returns the frequency of the clock, rounded to the
266next lowest integer. This implies some inaccuracy due to the rounding,
267so be cautious about using it in calculations.
268
269It is also possible to register a callback on clock frequency changes.
270Here is an example:
271
272.. code-block:: c
273
274    void clock_callback(void *opaque) {
275        MyDeviceState *s = (MyDeviceState *) opaque;
276        /*
277         * 'opaque' is the argument passed to qdev_init_clock_in();
278         * usually this will be the device state pointer.
279         */
280
281        /* do something with the new period */
282        fprintf(stdout, "device new period is %" PRIu64 "* 2^-32 ns\n",
283                        clock_get(dev->my_clk_input));
284    }
285
286If you are only interested in the frequency for displaying it to
287humans (for instance in debugging), use ``clock_display_freq()``,
288which returns a prettified string-representation, e.g. "33.3 MHz".
289The caller must free the string with g_free() after use.
290
291Calculating expiry deadlines
292----------------------------
293
294A commonly required operation for a clock is to calculate how long
295it will take for the clock to tick N times; this can then be used
296to set a timer expiry deadline. Use the function ``clock_ticks_to_ns()``,
297which takes an unsigned 64-bit count of ticks and returns the length
298of time in nanoseconds required for the clock to tick that many times.
299
300It is important not to try to calculate expiry deadlines using a
301shortcut like multiplying a "period of clock in nanoseconds" value
302by the tick count, because clocks can have periods which are not a
303whole number of nanoseconds, and the accumulated error in the
304multiplication can be significant.
305
306For a clock with a very long period and a large number of ticks,
307the result of this function could in theory be too large to fit in
308a 64-bit value. To avoid overflow in this case, ``clock_ticks_to_ns()``
309saturates the result to INT64_MAX (because this is the largest valid
310input to the QEMUTimer APIs). Since INT64_MAX nanoseconds is almost
311300 years, anything with an expiry later than that is in the "will
312never happen" category. Callers of ``clock_ticks_to_ns()`` should
313therefore generally not special-case the possibility of a saturated
314result but just allow the timer to be set to that far-future value.
315(If you are performing further calculations on the returned value
316rather than simply passing it to a QEMUTimer function like
317``timer_mod_ns()`` then you should be careful to avoid overflow
318in those calculations, of course.)
319
320Changing a clock period
321-----------------------
322
323A device can change its outputs using the ``clock_update()``,
324``clock_update_ns()`` or ``clock_update_hz()`` function. It will trigger
325updates on every connected input.
326
327For example, let's say that we have an output clock *clkout* and we
328have a pointer to it in the device state because we did the following
329in init phase:
330
331.. code-block:: c
332
333   dev->clkout = qdev_init_clock_out(DEVICE(dev), "clkout");
334
335Then at any time (apart from the cases listed below), it is possible to
336change the clock value by doing:
337
338.. code-block:: c
339
340   clock_update_hz(dev->clkout, 1000 * 1000 * 1000); /* 1GHz */
341
342Because updating a clock may trigger any side effects through
343connected clocks and their callbacks, this operation must be done
344while holding the qemu io lock.
345
346For the same reason, one can update clocks only when it is allowed to have
347side effects on other objects. In consequence, it is forbidden:
348
349* during migration,
350* and in the enter phase of reset.
351
352Note that calling ``clock_update[_ns|_hz]()`` is equivalent to calling
353``clock_set[_ns|_hz]()`` (with the same arguments) then
354``clock_propagate()`` on the clock. Thus, setting the clock value can
355be separated from triggering the side-effects. This is often required
356to factorize code to handle reset and migration in devices.
357
358Aliasing clocks
359---------------
360
361Sometimes, one needs to forward, or inherit, a clock from another
362device.  Typically, when doing device composition, a device might
363expose a sub-device's clock without interfering with it.  The function
364``qdev_alias_clock()`` can be used to achieve this behaviour. Note
365that it is possible to expose the clock under a different name.
366``qdev_alias_clock()`` works for both input and output clocks.
367
368For example, if device B is a child of device A,
369``device_a_instance_init()`` may do something like this:
370
371.. code-block:: c
372
373    void device_a_instance_init(Object *obj)
374    {
375        AState *A = DEVICE_A(obj);
376        BState *B;
377        /* create object B as child of A */
378        [...]
379        qdev_alias_clock(B, "clk", A, "b_clk");
380        /*
381         * Now A has a clock "b_clk" which is an alias to
382         * the clock "clk" of its child B.
383         */
384    }
385
386This function does not return any clock object. The new clock has the
387same direction (input or output) as the original one. This function
388only adds a link to the existing clock. In the above example, object B
389remains the only object allowed to use the clock and device A must not
390try to change the clock period or set a callback to the clock. This
391diagram describes the example with an input clock::
392
393    +--------------------------+
394    |        Device A          |
395    |         +--------------+ |
396    |         |   Device B   | |
397    |         | +-------+    | |
398    >>"b_clk">>>| "clk" |    | |
399    |  (in)   | |  (in) |    | |
400    |         | +-------+    | |
401    |         +--------------+ |
402    +--------------------------+
403
404Migration
405---------
406
407Clock state is not migrated automatically. Every device must handle its
408clock migration. Alias clocks must not be migrated.
409
410To ensure clock states are restored correctly during migration, there
411are two solutions.
412
413Clock states can be migrated by adding an entry into the device
414vmstate description. You should use the ``VMSTATE_CLOCK`` macro for this.
415This is typically used to migrate an input clock state. For example:
416
417.. code-block:: c
418
419    MyDeviceState {
420        DeviceState parent_obj;
421        [...] /* some fields */
422        Clock *clk;
423    };
424
425    VMStateDescription my_device_vmstate = {
426        .name = "my_device",
427        .fields = (VMStateField[]) {
428            [...], /* other migrated fields */
429            VMSTATE_CLOCK(clk, MyDeviceState),
430            VMSTATE_END_OF_LIST()
431        }
432    };
433
434The second solution is to restore the clock state using information already
435at our disposal. This can be used to restore output clock states using the
436device state. The functions ``clock_set[_ns|_hz]()`` can be used during the
437``post_load()`` migration callback.
438
439When adding clock support to an existing device, if you care about
440migration compatibility you will need to be careful, as simply adding
441a ``VMSTATE_CLOCK()`` line will break compatibility. Instead, you can
442put the ``VMSTATE_CLOCK()`` line into a vmstate subsection with a
443suitable ``needed`` function, and use ``clock_set()`` in a
444``pre_load()`` function to set the default value that will be used if
445the source virtual machine in the migration does not send the clock
446state.
447
448Care should be taken not to use ``clock_update[_ns|_hz]()`` or
449``clock_propagate()`` during the whole migration procedure because it
450will trigger side effects to other devices in an unknown state.
451