clocks.rst 21 KB

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