blob: ba6c915cefb9442ef5e4c6fe4dde4f8910ec3bba [file] [log] [blame]
Joakim Bech8e5c5b32018-10-25 08:18:32 +02001.. _core:
2
3####
4Core
5####
6
7.. _interrupt_handling:
8
9Interrupt handling
10******************
11This section describes how :ref:`optee_os` handles switches of world execution
Joakim Bech1e506862019-06-24 10:00:51 +020012context based on :ref:`SMC` exceptions and interrupt notifications. Interrupt
Joakim Bech8e5c5b32018-10-25 08:18:32 +020013notifications are IRQ/FIQ exceptions which may also imply switching of world
14execution context: normal world to secure world, or secure world to normal
15world.
16
17Use cases of world context switch
18=================================
19This section lists all the cases where optee_os is involved in world context
20switches. Optee_os executes in the secure world. World switch is done by the
Joakim Becheb397802019-09-13 11:45:06 +020021core's secure monitor level/mode, referred below as the Monitor.
Joakim Bech8e5c5b32018-10-25 08:18:32 +020022
23When the normal world invokes the secure world, the normal world executes a SMC
24instruction. The SMC exception is always trapped by the Monitor. If the related
25service targets the trusted OS, the Monitor will switch to optee_os world
26execution. When the secure world returns to the normal world, optee_os executes
27a SMC that is caught by the Monitor which switches back to the normal world.
28
29When a secure interrupt is signaled by the Arm GIC, it shall reach the optee_os
30interrupt exception vector. If the secure world is executing, optee_os will
31handle straight the interrupt from its exception vector. If the normal world is
32executing when the secure interrupt raises, the Monitor vector must handle the
33exception and invoke the optee_os to serve the interrupt.
34
35When a non-secure interrupt is signaled by the Arm GIC, it shall reach the
36normal world interrupt exception vector. If the normal world is executing, it
37will handle straight the exception from its exception vector. If the secure
38world is executing when the non-secure interrupt raises, optee_os will
39temporarily return back to normal world via the Monitor to let normal world
40serve the interrupt.
41
42Core exception vectors
43======================
44Monitor vector is ``VBAR_EL3`` in AArch64 and ``MVBAR`` in Armv7-A/AArch32.
45Monitor can be reached while normal world or secure world is executing. The
46executing secure state is known to the Monitor through the ``SCR_NS``.
47
48Monitor can be reached from a SMC exception, an IRQ or FIQ exception (so-called
49interrupts) and from asynchronous aborts. Obviously monitor aborts (data,
50prefetch, undef) are local to the Monitor execution.
51
52The Monitor can be external to optee_os (case ``CFG_WITH_ARM_TRUSTED_FW=y``).
53If not, provides a local secure monitor ``core/arch/arm/sm``. Armv7-A platforms
54should use the optee_os secure monitor. Armv8-A platforms are likely to rely on
55an `Trusted Firmware A`_.
56
57When executing outside the Monitor, the system is executing either in the
58normal world (``SCR_NS=1``) or in the secure world (``SCR_NS=0``). Each world
59owns its own exception vector table (state vector):
60
61 - ``VBAR_EL2`` or ``VBAR_EL1`` non-secure or ``VBAR_EL1`` secure for
62 AArch64.
63 - ``HVBAR`` or ``VBAR`` non-secure or ``VBAR`` secure for Armv7-A and
64 AArch32.
65
66All SMC exceptions are trapped in the Monitor vector. IRQ/FIQ exceptions can be
67trapped either in the Monitor vector or in the state vector of the executing
68world.
69
70When the normal world is executing, the system is configured to route:
71
72 - secure interrupts to the Monitor that will forward to optee_os
73 - non-secure interrupts to the executing world exception vector.
74
75When the secure world is executing, the system is configured to route:
76
77 - secure and non-secure interrupts to the executing optee_os exception
78 vector. optee_os shall forward the non-secure interrupts to the normal
79 world.
80
81Optee_os non-secure interrupts are always trapped in the state vector of the
82executing world. This is reflected by a static value of ``SCR_(IRQ|FIQ)``.
83
84.. _native_foreign_irqs:
85
86Native and foreign interrupts
87=============================
88Two types of interrupt are defined in optee_os:
89
90 - **Native interrupt** - The interrupt handled by optee_os (for example:
91 secure interrupt)
92 - **Foreign interrupt** - The interrupt not handled by optee_os (for
93 example: non-secure interrupt which is handled by normal world)
94
95For Arm **GICv2** mode, native interrupt is sent as FIQ and foreign interrupt
96is sent as IRQ. For Arm **GICv3** mode, foreign interrupt is sent as FIQ which
97could be handled by either secure world (aarch32 Monitor mode or aarch64 EL3)
98or normal world. Arm GICv3 mode can be enabled by setting ``CFG_ARM_GICV3=y``.
99For clarity, this document mainly chooses the GICv2 convention and refers the
100IRQ as optee_os foreign interrupts, and FIQ as optee_os native interrupts.
101Native interrupts must be securely routed to optee_os. Foreign interrupts, when
102trapped during secure world execution might need to be efficiently routed to
103the normal world.
104
105Normal World invokes optee_os using SMC
106=======================================
107
108**Entering the Secure Monitor**
109
110The monitor manages all entries and exits of secure world. To enter secure
111world from normal world the monitor saves the state of normal world (general
112purpose registers and system registers which are not banked) and restores the
113previous state of secure world. Then a return from exception is performed and
114the restored secure state is resumed. Exit from secure world to normal world is
115the reverse.
116
117Some general purpose registers are not saved and restored on entry and exit,
118those are used to pass parameters between secure and normal world (see
119ARM_DEN0028A_SMC_Calling_Convention_ for details).
120
121**Entry and exit of Trusted OS**
122
123On entry and exit of Trusted OS each CPU is uses a separate entry stack and runs
124with IRQ and FIQ blocked. SMCs are categorised in two flavors: **fast** and
125**standard**.
126
127 - For **fast** SMCs, optee_os will execute on the entry stack with IRQ/FIQ
128 blocked until the execution returns to normal world.
129
130 - For **standard** SMCs, optee_os will at some point execute the requested
131 service with interrupts unblocked. In order to handle interrupts, mainly
132 forwarding of foreign interrupts, optee_os assigns a trusted thread
133 (`core/arch/arm/kernel/thread.c`_) to the SMC request. The trusted thread
134 stores the execution context of the requested service. This context can be
135 suspended and resumed as the requested service executes and is
136 interrupted. The trusted thread is released only once the service
137 execution returns with a completion status.
138
139 For **standard** SMCs, optee_os allocates or resumes a trusted thread then
140 unblock the IRQ/FIQ lines. When the optee_os needs to invoke the normal
141 world from a foreign interrupt or a remote service call, optee_os blocks
142 IRQ/FIQ and suspends the trusted thread. When suspending, optee_os gets
143 back to the entry stack.
144
145 - **Both** fast and standard SMC end on the entry stack with IRQ/FIQ blocked
146 and optee_os invokes the Monitor through a SMC to return to the normal
147 world.
148
Jens Wiklander2c39d742021-05-10 16:02:08 +0200149
150.. uml::
151 :align: center
152 :caption: SMC entry to secure world
153
154 participant "Normal World" as nwd
155 participant "Secure Monitor" as smon
156 participant "OP-TEE OS entry" as entry
157 participant "OP-TEE OS" as optee
158 == IRQ and FIQ unmasked ==
159 nwd -> smon : smc: TEE_FUNC_INVOKE
160 smon -> smon : Save non-secure context
161 smon -> smon : Restore secure context
162 smon --> entry : eret: TEE_FUNC_INVOKE
163 entry -> entry : assign thread
164 entry -> optee : TEE_FUNC_INVOKE
165 == IRQ and FIQ unmasked ==
166 optee -> optee : process
167 == IRQ and FIQ masked ==
168 optee --> entry : SMC_CALL_RETURN
169 entry -> smon : smc: SMC_CALL_RETURN
170 smon -> smon : Save secure context
171 smon -> smon : Restore non-secure context
172 == IRQ and FIQ unmasked ==
173 smon --> nwd : eret: return
Joakim Bech8e5c5b32018-10-25 08:18:32 +0200174
175Deliver non-secure interrupts to Normal World
176=============================================
177This section uses the Arm GICv1/v2 conventions: IRQ signals non-secure
178interrupts while FIQ signals secure interrupts. On a GICv3 configuration, one
179should exchange IRQ and FIQ in this section.
180
181**Forward a Foreign Interrupt from Secure World to Normal World**
182
183When an IRQ is received in secure world as an IRQ exception then secure world:
184
185 1. Saves trusted thread context (entire state of all processor modes for
186 Armv7-A)
187
188 2. Blocks (masks) all interrupts (IRQ and FIQ)
189
190 3. Switches to entry stack
191
192 4. Issues an SMC with a value to indicates to normal world that an IRQ has
193 been delivered and last SMC call should be continued
194
195The monitor restores normal world context with a return code indicating that an
196IRQ is about to be delivered. Normal world issues a new SMC indicating that it
197should continue last SMC.
198
199The monitor restores secure world context which locates the previously saved
200context and checks that it is a return from IRQ that is requested before
201restoring the context and lets the secure world IRQ handler return from
202exception where the execution would be resumed.
203
204Note that the monitor itself does not know/care that it has just forwarded an
205IRQ to normal world. The bookkeeping is done in the trusted thread handling in
206Trusted OS. Normal world is responsible to decide when the secure world thread
207should resume execution (for details, see :ref:`thread_handling`).
208
209.. figure:: ../images/core/interrupt_handling/irq.png
210 :figclass: align-center
211
212 IRQ received in secure world and forwarded to normal world
213
214**Deliver a non-secure interrupt to normal world when ``SCR_NS`` is set**
215
216Since ``SCR_IRQ`` is cleared, an IRQ will be delivered using the state vector
217(``VBAR``) in the normal world. The IRQ is received as any other exception by
218normal world, the monitor and the Trusted OS are not involved at all.
219
220Deliver secure interrupts to Secure World
221=========================================
222This section uses the Arm GICv1/v2 conventions: FIQ signals secure interrupts
223while IRQ signals non-secure interrupts. On a GICv3 configuration, one should
224exchange IRQ and FIQ in this section. A FIQ can be received during two different
225states, either in normal world (``SCR_NS`` is set) or in secure world
226(``SCR_NS`` is cleared). When the secure monitor is active (Armv8-A EL3 or
227Armv7-A Monitor mode) FIQ is masked. FIQ reception in the two different states
228is described below.
229
230**Deliver FIQ to secure world when SCR_NS is set**
231
232When the monitor gets an FIQ exception it:
233
234 1. Saves normal world context and restores secure world context from last
235 secure world exit (which will have IRQ and FIQ blocked)
236 2. Clears ``SCR_FIQ`` when clearing ``SCR_NS``
237 3. Sets “FIQ” as parameter to secure world entry
238 4. Does a return from exception into secure context
239 5. Secure world unmasks FIQs because of the “FIQ” parameter
240 6. FIQ is received as in exception using the state vector
241 7. The state vector handle returns from exception in secure world
242 8. Secure world issues an SMC to return to normal world
243 9. Monitor saves secure world context and restores normal world context
244 10. Does a return from exception into restored context
245
246.. figure:: ../images/core/interrupt_handling/fiq.png
247 :figclass: align-center
248
249 FIQ received when SCR_NS is set
250
251.. figure:: ../images/core/interrupt_handling/irq_fiq.png
252 :figclass: align-center
253
254 FIQ received while processing an IRQ forwarded from secure world
255
256**Deliver FIQ to secure world when SCR_NS is cleared**
257
258Since ``SCR_FIQ`` is cleared when ``SCR_NS`` is cleared a FIQ will be delivered
259using the state vector (``VBAR``) in secure world. The FIQ is received as any
260other exception by Trusted OS, the monitor is not involved at all.
261
262Trusted thread scheduling
263=========================
264**Trusted thread for standard services**
265
266OP-TEE standard services are carried through standard SMC. Execution of these
267services can be interrupted by foreign interrupts. To suspend and restore the
268service execution, optee_os assigns a trusted thread at standard SMCs entry.
269
270The trusted thread terminates when optee_os returns to the normal world with a
271service completion status.
272
273A trusted thread execution can be interrupted by a native interrupt. In this
274case the native interrupt is handled by the interrupt exception handlers and
275once served, optee_os returns to the execution trusted thread.
276
277A trusted thread execution can be interrupted by a foreign interrupt. In this
278case, optee_os suspends the trusted thread and invokes the normal world through
279the Monitor (optee_os so-called RPC services). The trusted threads will resume
280only once normal world invokes the optee_os with the RPC service status.
281
282A trusted thread execution can lead optee_os to invoke a service in normal
283world: access a file, get the REE current time, etc. The trusted thread is
284suspended/resumed during remote service execution.
285
286**Scheduling considerations**
287
288When a trusted thread is interrupted by a foreign interrupt and when optee_os
289invokes a normal world service, the normal world gets the opportunity to
290reschedule the running applications. The trusted thread will resume only once
291the client application is scheduled back. Thus, a trusted thread execution
292follows the scheduling of the normal world caller context.
293
294Optee_os does not implement any thread scheduling. Each trusted thread is
295expected to track a service that is invoked from the normal world and should
296return to it with an execution status.
297
298The OP-TEE Linux driver (as implemented in `drivers/tee/optee`_ since Linux
299kernel 4.12) is designed so that the Linux thread invoking OP-TEE gets assigned
300a trusted thread on TEE side. The execution of the trusted thread is tied to the
301execution of the caller Linux thread which is under the Linux kernel scheduling
302decision. This means trusted threads are scheduled by the Linux kernel.
303
304**Trusted thread constraints**
305
306TEE core handles a static number of trusted threads, see ``CFG_NUM_THREADS``.
307
308Trusted threads are only expensive on memory constrained system, mainly
309regarding the execution stack size.
310
311On SMP systems, optee_os can execute several trusted threads in parallel if the
312normal world supports scheduling of processes. Even on UP systems, supporting
313several trusted threads in optee_os helps normal world scheduler to be
314efficient.
315
316----
317
318.. _memory_objects:
319
320Memory objects
321**************
322A memory object, **MOBJ**, describes a piece of memory. The interface provided
323is mostly abstract when it comes to using the MOBJ to populate translation
324tables etc. There are different kinds of MOBJs describing:
325
326 - Physically contiguous memory
327 - created with ``mobj_phys_alloc(...)``.
328
329 - Virtual memory
330 - one instance with the name ``mobj_virt`` available.
331 - spans the entire virtual address space.
332
333 - Physically contiguous memory allocated from a ``tee_mm_pool_t *``
334 - created with ``mobj_mm_alloc(...)``.
335
336 - Paged memory
337 - created with ``mobj_paged_alloc(...)``.
338 - only contains the supplied size and makes ``mobj_is_paged(...)``
339 return true if supplied as argument.
340
341 - Secure copy paged shared memory
342 - created with ``mobj_seccpy_shm_alloc(...)``.
343 - makes ``mobj_is_paged(...)`` and ``mobj_is_secure(...)`` return true
344 if supplied as argument.
345
346----
347
348.. _mmu:
349
350MMU
351***
352Translation tables
353==================
354OP-TEE uses several L1 translation tables, one large spanning 4 GiB and two or
355more small tables spanning 32 MiB. The large translation table handles kernel
356mode mapping and matches all addresses not covered by the small translation
357tables. The small translation tables are assigned per thread and covers the
358mapping of the virtual memory space for one TA context.
359
360Memory space between small and large translation table is configured by TTBRC.
361TTBR1 always points to the large translation table. TTBR0 points to the a small
362translation table when user mapping is active and to the large translation table
363when no user mapping is currently active. For details about registers etc,
364please refer to a Technical Reference Manual for your architecture, for example
365`Cortex-A53 TRM`_.
366
367The translation tables has certain alignment constraints, the alignment (of the
368physical address) has to be the same as the size of the translation table. The
369translation tables are statically allocated to avoid fragmentation of memory due
370to the alignment constraints.
371
372Each thread has one small L1 translation table of its own. Each TA context has a
373compact representation of its L1 translation table. The compact representation
374is used to initialize the thread specific L1 translation table when the TA
375context is activated.
376
377.. graphviz::
378
379 digraph xlat_table {
380 graph [
381 rankdir = "LR"
382 ];
383 node [
384 fontsize = "16"
385 shape = "ellipse"
386 ];
387 edge [
388 ];
389 "node_ttb" [
390 label = "<f0> TTBR0 | <f1> TTBR1"
391 shape = "record"
392 ];
393 "node_large_l1" [
394 label = "<f0> Large L1\nSpans 4 GiB"
395 shape = "record"
396 ];
397 "node_small_l1" [
398 label = "Small L1\nSpans 32 MiB\nper entry | <f0> 0 | <f1> 1 | ... | <fn> n"
399 shape = "record"
400 ];
401
402 "node_ttb":f0 -> "node_small_l1":f0 [ label = "Thread 0 ctx active" ];
403 "node_ttb":f0 -> "node_small_l1":f1 [ label = "Thread 1 ctx active" ];
404 "node_ttb":f0 -> "node_small_l1":fn [ label = "Thread n ctx active" ];
405 "node_ttb":f0 -> "node_large_l1" [ label="No active ctx" ];
406 "node_ttb":f1 -> "node_large_l1";
407 }
408
Jens Wiklander03b05a02019-02-25 13:44:38 +0100409Page table cache
410================
411Page tables used to map TAs are managed with the page table cache. When the
412context of a TA is unmapped, all its page tables are released with a call
413to ``pgt_free()``. All page tables needed when mapping a TA are allocated
414using ``pgt_alloc()``.
415
416A fixed maximum number of translation tables are available in a pool. One
417thread may execute a TA which needs all or almost all tables. This can
418block TAs from being executed by other threads. To ensure that all TAs
419eventually will be permitted to execute ``pgt_alloc()`` temporarily frees
420eventual tables allocated before waiting for tables to become available.
421
422The page table cache behaves differently depending on configuration
423options.
424
425Without paging (``CFG_WITH_PAGER=n``)
426-------------------------------------
427This is the easiest configuration. All page tables are statically allocated
428in the ``.nozi.pgt_cache`` section. ``pgt_alloc()`` allocates tables from the
429free-list and ``pgt_free()`` returns the tables directly to the free-list.
430
431With paging enabled (``CFG_WITH_PAGER=y``)
432------------------------------------------
433
434Page tables are allocated as zero initialized locked pages during boot
435using ``tee_pager_alloc()``. Locked pages are populated with physical pages
436on demand from the pager. The physical page can be released when not needed
437any longer with ``tee_pager_release_phys()``.
438
439With ``CFG_WITH_LPAE=y`` each translation table has the same size as a
440physical page which makes it easy to release the physical page when the
441translation table isn't needed any longer. With the short-descriptor table
442format (``CFG_WITH_LPAE=n``) it becomes more complicated as four
443translation tables are stored in each page. Additional bookkeeping is used
444to tell when the page for used by four separate translation tables can be
445released.
446
447With paging of user TA enabled (``CFG_PAGED_USER_TA=y``)
448--------------------------------------------------------
449With paging of user TAs enabled a cache of recently used translation tables
450is used. This can save us from a storm of page faults when restoring the
451mappings of a recently unmapped TA. Which translation tables should be
452cached is indicated with reference counting by the pager on used tables.
453When a table needs to be forcefully freed
454``tee_pager_pgt_save_and_release_entries()`` is called to let the pager
455know that the table can't be used any longer.
456
457When a mapping in a TA is removed it also needs to be purged from cached
458tables with ``pgt_flush_ctx_range()`` to prevent old mappings from being
459accidentally reused.
Joakim Bech8e5c5b32018-10-25 08:18:32 +0200460
461Switching to user mode
462======================
463This section only applies with following configuration flags:
464
465 - ``CFG_WITH_LPAE=n``
466 - ``CFG_CORE_UNMAP_CORE_AT_EL0=y``
467
468When switching to user mode only a minimal kernel mode mapping is kept. This is
469achieved by selecting a zeroed out big L1 translation in TTBR1 when
470transitioning to user mode. When returning back to kernel mode the original L1
471translation table is restored in TTBR1.
472
473Switching to normal world
474=========================
475When switching to normal world either via a foreign interrupt (see
476:ref:`native_foreign_irqs` or RPC there is a chance that secure world will
477resume execution on a different CPU. This means that the new CPU need to be
478configured with the context of the currently active TA. This is solved by always
Jens Wiklanderddde3a82019-02-25 12:46:18 +0100479setting the TA context in the CPU when resuming execution.
Joakim Bech8e5c5b32018-10-25 08:18:32 +0200480
481----
482
483.. _pager:
484
485Pager
486*****
487OP-TEE currently requires >256 KiB RAM for OP-TEE kernel memory. This is not a
488problem if OP-TEE uses TrustZone protected DDR, but for security reasons OP-TEE
489may need to use TrustZone protected SRAM instead. The amount of available SRAM
490varies between platforms, from just a few KiB up to over 512 KiB. Platforms with
491just a few KiB of SRAM cannot be expected to be able to run a complete TEE
492solution in SRAM. But those with 128 to 256 KiB of SRAM can be expected to have
493a capable TEE solution in SRAM. The pager provides a solution to this by demand
494paging parts of OP-TEE using virtual memory.
495
496Secure memory
497=============
498TrustZone protected SRAM is generally considered more secure than TrustZone
499protected DRAM as there is usually more attack vectors on DRAM. The attack
500vectors are hardware dependent and can be different for different platforms.
501
502Backing store
503=============
504TrustZone protected DRAM or in some cases non-secure DRAM is used as backing
505store. The data in the backing store is integrity protected with one hash
506(SHA-256) per page (4KiB). Readonly pages are not encrypted since the OP-TEE
507binary itself is not encrypted.
508
509Partitioning of memory
510======================
511The code that handles demand paging must always be available as it would
512otherwise lead to deadlock. The virtual memory is partitioned as:
513
514 +--------------+-------------------+
515 | Type | Sections |
516 +==============+===================+
517 | unpaged | | text |
518 | | | rodata |
519 | | | data |
520 | | | bss |
521 | | | heap1 |
522 | | | nozi |
523 | | | heap2 |
524 +--------------+-------------------+
525 | init / paged | | text_init |
526 | | | rodata_init |
527 +--------------+-------------------+
528 | paged | | text_pageable |
529 | | | rodata_pageable |
530 +--------------+-------------------+
531 | demand alloc | |
532 +--------------+-------------------+
533
534Where ``nozi`` stands for "not zero initialized", this section contains entry
535stacks (thread stack when TEE pager is not enabled) and translation tables (TEE
536pager cached translation table when the pager is enabled and LPAE MMU is used).
537
538The ``init`` area is available when OP-TEE is initializing and contains
539everything that is needed to initialize the pager. After the pager has been
540initialized this area will be used for demand paged instead.
541
542The ``demand alloc`` area is a special area where the pages are allocated and
543removed from the pager on demand. Those pages are returned when OP-TEE does not
544need them any longer. The thread stacks currently belongs this area. This means
545that when a stack is not used the physical pages can be used by the pager for
546better performance.
547
548The technique to gather code in the different area is based on compiling all
549functions and data into separate sections. The unpaged text and rodata is then
550gathered by linking all object files with ``--gc-sections`` to eliminate
551sections that are outside the dependency graph of the entry functions for
552unpaged functions. A script analyzes this ELF file and generates the bits of the
553final link script. The process is repeated for init text and rodata. What is
554not "unpaged" or "init" becomes "paged".
555
556Partitioning of the binary
557==========================
558.. note::
559 The struct definitions provided in this section are explicitly covered by
560 the following dual license:
561
562 .. code-block:: none
563
564 SPDX-License-Identifier: (BSD-2-Clause OR GPL-2.0)
565
566The binary is partitioned into four parts as:
567
568
569 +----------+
570 | Binary |
571 +==========+
572 | Header |
573 +----------+
574 | Init |
575 +----------+
576 | Hashes |
577 +----------+
578 | Pageable |
579 +----------+
580
581The header is defined as:
582
583.. code-block:: c
584
585 #define OPTEE_MAGIC 0x4554504f
586 #define OPTEE_VERSION 1
587 #define OPTEE_ARCH_ARM32 0
588 #define OPTEE_ARCH_ARM64 1
589
590 struct optee_header {
591 uint32_t magic;
592 uint8_t version;
593 uint8_t arch;
594 uint16_t flags;
595 uint32_t init_size;
596 uint32_t init_load_addr_hi;
597 uint32_t init_load_addr_lo;
598 uint32_t init_mem_usage;
599 uint32_t paged_size;
600 };
601
602The header is only used by the loader of OP-TEE, not OP-TEE itself. To
603initialize OP-TEE the loader loads the complete binary into memory and copies
604what follows the header and the following ``init_size`` bytes to
605``(init_load_addr_hi << 32 | init_load_addr_lo)``. ``init_mem_usage`` is used by
606the loader to be able to check that there is enough physical memory available
607for OP-TEE to be able to initialize at all. The loader supplies in ``r0/x0`` the
608address of the first byte following what was not copied and jumps to the load
609address to start OP-TEE.
610
611In addition to overall binary with partitions inside described as above, three
612extra binaries are generated simultaneously during build process for loaders who
613support loading separate binaries:
614
615 +-----------+
616 | v2 binary |
617 +===========+
618 | Header |
619 +-----------+
620
621 +-----------+
622 | v2 binary |
623 +===========+
624 | Init |
625 +-----------+
626 | Hashes |
627 +-----------+
628
629 +-----------+
630 | v2 binary |
631 +===========+
632 | Pageable |
633 +-----------+
634
635In this case, loaders load header binary first to get image list and information
636of each image; and then load each of them into specific load address assigned in
637structure. These binaries are named with `v2` suffix to distinguish from the
638existing binaries. Header format is updated to help loaders loading binaries
639efficiently:
640
641.. code-block:: c
642
643 #define OPTEE_IMAGE_ID_PAGER 0
644 #define OPTEE_IMAGE_ID_PAGED 1
645
646 struct optee_image {
647 uint32_t load_addr_hi;
648 uint32_t load_addr_lo;
649 uint32_t image_id;
650 uint32_t size;
651 };
652
653 struct optee_header_v2 {
654 uint32_t magic;
655 uint8_t version;
656 uint8_t arch;
657 uint16_t flags;
658 uint32_t nb_images;
659 struct optee_image optee_image[];
660 };
661
662Magic number and architecture are identical as original. Version is increased to
663two. ``load_addr_hi`` and ``load_addr_lo`` may be ``0xFFFFFFFF`` for pageable
664binary since pageable part may get loaded by loader into dynamic available
665position. ``image_id`` indicates how loader handles current binary. Loaders who
666don't support separate loading just ignore all v2 binaries.
667
668Initializing the pager
669======================
670The pager is initialized as early as possible during boot in order to minimize
671the "init" area. The global variable ``tee_mm_vcore`` describes the virtual
672memory range that is covered by the level 2 translation table supplied to
673``tee_pager_init(...)``.
674
675Assign pageable areas
676---------------------
677A virtual memory range to be handled by the pager is registered with a call to
678``tee_pager_add_core_area()``.
679
680.. code-block:: c
681
682 bool tee_pager_add_area(tee_mm_entry_t *mm,
683 uint32_t flags,
684 const void *store,
685 const void *hashes);
686
687which takes a pointer to ``tee_mm_entry_t`` to tell the range, flags to tell how
688memory should be mapped (readonly, execute etc), and pointers to backing store
689and hashes of the pages.
690
691Assign physical pages
692---------------------
693Physical SRAM pages are supplied by calling ``tee_pager_add_pages(...)``
694
695.. code-block:: c
696
697 void tee_pager_add_pages(tee_vaddr_t vaddr,
698 size_t npages,
699 bool unmap);
700
701``tee_pager_add_pages(...)`` takes the physical address stored in the entry
702mapping the virtual address ``vaddr`` and ``npages`` entries after that and uses
703it to map new pages when needed. The unmap parameter tells whether the pages
704should be unmapped immediately since they does not contain initialized data or
705be kept mapped until they need to be recycled. The pages in the "init" area are
706supplied with ``unmap == false`` since those page have valid content and are in
707use.
708
709Invocation
710==========
711The pager is invoked as part of the abort handler. A pool of physical pages are
712used to map different virtual addresses. When a new virtual address needs to be
713mapped a free physical page is mapped at the new address, if a free physical
714page cannot be found the oldest physical page is selected instead. When the page
715is mapped new data is copied from backing store and the hash of the page is
716verified. If it is OK the pager returns from the exception to resume the
717execution.
718
Jens Wiklanderaecf4412019-02-26 12:33:14 +0100719Data structures
720===============
721.. figure:: ../images/core/tee_pager_area.png
722 :figclass: align-center
723
724 How the main pager data structures relates to each other
725
726``struct tee_pager_area``
727-------------------------
728This is a central data structure when handling paged
729memory ranges. It's defined as:
730
731.. code-block:: c
732
733 struct tee_pager_area {
734 struct fobj *fobj;
735 size_t fobj_pgoffs;
736 enum tee_pager_area_type type;
737 uint32_t flags;
738 vaddr_t base;
739 size_t size;
740 struct pgt *pgt;
741 TAILQ_ENTRY(tee_pager_area) link;
742 TAILQ_ENTRY(tee_pager_area) fobj_link;
743 };
744
745Where ``base`` and ``size`` tells the memory range and ``fobj`` and
746``fobj_pgoffs`` holds the content. A ``struct tee_pager_area`` can only use
747``struct fobj`` and one ``struct pgt`` (translation table) so memory ranges
748spanning multiple fobjs or pgts are split into multiple areas.
749
750``struct fobj``
751---------------
752This is a polymorph object, using different implmentations depending on how
753it's initialized. It's defines as:
754
755.. code-block:: c
756
757 struct fobj_ops {
758 void (*free)(struct fobj *fobj);
759 TEE_Result (*load_page)(struct fobj *fobj, unsigned int page_idx,
760 void *va);
761 TEE_Result (*save_page)(struct fobj *fobj, unsigned int page_idx,
762 const void *va);
763 };
764
765 struct fobj {
766 const struct fobj_ops *ops;
767 unsigned int num_pages;
768 struct refcount refc;
769 struct tee_pager_area_head areas;
770 };
771
772:``num_pages``: Tells how many pages this ``fobj`` covers.
773:``refc``: A reference counter, everyone referring to a ``fobj`` need to
774 increase and decrease this as needed.
775:``areas``: A list of areas using this ``fobj``, traversed when making
776 a virtual page unavailable.
777
778``struct tee_pager_pmem``
779-------------------------
780This structure represents a physical page. It's defined as:
781
782.. code-block:: c
783
784 struct tee_pager_pmem {
785 unsigned int flags;
786 unsigned int fobj_pgidx;
787 struct fobj *fobj;
788 void *va_alias;
789 TAILQ_ENTRY(tee_pager_pmem) link;
790 };
791
792:``PMEM_FLAG_DIRTY``: Bit is set in ``flags`` when the page is mapped
793 read/write at at least one location.
794:``PMEM_FLAG_HIDDEN``: Bit is set in ``flags`` when the page is hidden, that
795 is, not accessible anywhere.
796:``fobj_pgidx``: The page at this index in the ``fobj`` is used in this
797 physical page.
798:``fobj``: The ``fobj`` backing this page.
799:``va_alias``: Virtual address where this physical page is updated
800 when loading it from backing store or when writing it
801 back.
802
803All ``struct tee_pager_pmem`` are stored either in the global list
804``tee_pager_pmem_head`` or in ``tee_pager_lock_pmem_head``. The latter is
805used by pages which are mapped and then locked in memory on demand. The
806pages are returned back to ``tee_pager_pmem_head`` when the pages are
807exlicitly released with a call to ``tee_pager_release_phys()``.
808
809A physical page can be used by more than one ``tee_pager_area``
810simultaneously. This is also know as shared secure memory and will appear
811as such for both read-only and read-write mappings.
812
813When a page is hidden it's unmapped from all translation tables and the
814``PMEM_FLAG_HIDDEN`` bit is set, but kept in memory. When a physical page
815is released it's also unmapped from all translation tables and it's content
816is written back to storage, then the ``fobj`` field is set to ``NULL`` to
817note the physical page as unused.
818
819Note that when ``struct tee_pager_pmem`` references a ``fobj`` it doesn't
820update the reference counter since it's already guaranteed to be available
821due the ``struct tee_pager_area`` which must reference the ``fobj`` too.
822
Joakim Bech8e5c5b32018-10-25 08:18:32 +0200823Paging of user TA
824=================
825Paging of user TAs can optionally be enabled with ``CFG_PAGED_USER_TA=y``.
826Paging of user TAs is analogous to paging of OP-TEE kernel parts but with a few
827differences:
828
829 - Read/write pages are paged in addition to read-only pages
830 - Page tables are managed dynamically
831
832``tee_pager_add_uta_area(...)`` is used to setup initial read/write mapping
833needed when populating the TA. When the TA is fully populated and relocated
834``tee_pager_set_uta_area_attr(...)`` changes the mapping of the area to strict
835permissions used when the TA is running.
836
Jens Wiklanderaecf4412019-02-26 12:33:14 +0100837Paging shared secure memory
838---------------------------
839Shared secure memory is achieved by letting several ``tee_pager_area``
840using the same backing ``fobj``. When a ``tee_pager_area`` is allocated and
841assigned a ``fobj`` it's also added to a list for ``tee_pager_areas`` using
842this ``fobj``. This helps when a physical page is released.
843
844When a fault occurs first a matching ``tee_pager_area`` is located. Then
845``tee_pager_pmem_head`` is searched to see if a physical page already holds
846the page of the ``fobj`` needed. If so the ``pgt`` is updated to map the
847physical page at the appropriate locatation. If no physical page was holding
848the page a new physical page is allocated, initialized and finally mapped.
849
850In order to make as few updates to mappings as possible changes to less
851restricted, no access -> read-only or read-only to read-write, is done only
852for the virtual address was used when the page fault occurred. Changes in
853the other direction has to be done in all translation tables used to map
854the physical page.
855
Joakim Bech8e5c5b32018-10-25 08:18:32 +0200856----
857
858.. _stacks:
859
860Stacks
861******
862Different stacks are used during different stages. The stacks are:
863
864 - **Secure monitor stack** (128 bytes), bound to the CPU. Only available if
865 OP-TEE is compiled with a secure monitor always the case if the target is
866 Armv7-A but never for Armv8-A.
867
868 - **Temp stack** (small ~1KB), bound to the CPU. Used when transitioning
869 from one state to another. Interrupts are always disabled when using this
870 stack, aborts are fatal when using the temp stack.
871
872 - **Abort stack** (medium ~2KB), bound to the CPU. Used when trapping a data
873 or pre-fetch abort. Aborts from user space are never fatal the TA is only
874 killed. Aborts from kernel mode are used by the pager to do the demand
875 paging, if pager is disabled all kernel mode aborts are fatal.
876
877 - **Thread stack** (large ~8KB), not bound to the CPU instead used by the
878 current thread/task. Interrupts are usually enabled when using this stack.
879
880Notes for Armv7-A/AArch32
881 .. list-table::
882 :header-rows: 1
883 :widths: 1 5
884
885 * - Stack
886 - Comment
887
888 * - Temp
889 - Assigned to ``SP_SVC`` during entry/exit, always assigned to
890 ``SP_IRQ`` and ``SP_FIQ``
891
892 * - Abort
893 - Always assigned to ``SP_ABT``
894
895 * - Thread
896 - Assigned to ``SP_SVC`` while a thread is active
897
898Notes for AArch64
899 There are only two stack pointers, ``SP_EL1`` and ``SP_EL0``, available for
900 OP-TEE in AArch64. When an exception is received stack pointer is always
901 ``SP_EL1`` which is used temporarily while assigning an appropriate stack
902 pointer for ``SP_EL0``. ``SP_EL1`` is always assigned the value of
903 ``thread_core_local[cpu_id]``. This structure has some spare space for
904 temporary storage of registers and also keeps the relevant stack pointers.
905 In general when we talk about assigning a stack pointer to the CPU below we
906 mean ``SP_EL0``.
907
908Boot
909====
910During early boot the CPU is configured with the temp stack which is used until
911OP-TEE exits to normal world the first time.
912
913Notes for AArch64
914 ``SPSEL`` is always ``0`` on entry/exit to have ``SP_EL0`` acting as stack
915 pointer.
916
917Normal entry
918============
919Each time OP-TEE is entered from normal world the temp stack is used as the
920initial stack. For fast calls, this is the only stack used. For normal calls an
921empty thread slot is selected and the CPU switches to that stack.
922
923Normal exit
924===========
925Normal exit occurs when a thread has finished its task and the thread is freed.
926When the main thread function, ``tee_entry_std(...)``, returns interrupts are
927disabled and the CPU switches to the temp stack instead. The thread is freed and
928OP-TEE exits to normal world.
929
930RPC exit
931========
932RPC exit occurs when OP-TEE need some service from normal world. RPC can
933currently only be performed with a thread is in running state. RPC is initiated
934with a call to ``thread_rpc(...)`` which saves the state in a way that when the
935thread is restored it will continue at the next instruction as if this function
936did a normal return. CPU switches to use the temp stack before returning to
937normal world.
938
939Foreign interrupt exit
940======================
941Foreign interrupt exit occurs when OP-TEE receives a foreign interrupt. For Arm
942GICv2 mode, foreign interrupt is sent as IRQ which is always handled in normal
943world. Foreign interrupt exit is similar to RPC exit but it is
944``thread_irq_handler(...)`` and ``elx_irq(...)`` (respectively for
945Armv7-A/Aarch32 and for Aarch64) that saves the thread state instead. The thread
946is resumed in the same way though. For Arm GICv3 mode, foreign interrupt is sent
947as FIQ which could be handled by either secure world (EL3 in AArch64) or normal
948world. This mode is not supported yet.
949
950Notes for Armv7-A/AArch32
951 SP_IRQ is initialized to temp stack instead of a separate stack. Prior to
952 exiting to normal world CPU state is changed to SVC and temp stack is
953 selected.
954
955Notes for AArch64
956 ``SP_EL0`` is assigned temp stack and is selected during IRQ processing. The
957 original ``SP_EL0`` is saved in the thread context to be restored when
958 resuming.
959
960Resume entry
961============
962OP-TEE is entered using the temp stack in the same way as for normal entry. The
963thread to resume is looked up and the state is restored to resume execution. The
964procedure to resume from an RPC exit or an foreign interrupt exit is exactly the
965same.
966
967Syscall
968=======
969Syscall's are executed using the thread stack.
970
971Notes for Armv7-A/AArch32
972 Nothing special ``SP_SVC`` is already set with thread stack.
973
974Notes for syscall AArch64
975 Early in the exception processing the original ``SP_EL0`` is saved in
976 ``struct thread_svc_regs`` in case the TA is executed in AArch64. Current
977 thread stack is assigned to ``SP_EL0`` which is then selected. When
978 returning ``SP_EL0`` is assigned what is in ``struct thread_svc_regs``. This
979 allows ``tee_svc_sys_return_helper(...)`` having the syscall exception
980 handler return directly to ``thread_unwind_user_mode(...)``.
981
982----
983
984.. _shared_memory:
985
986Shared Memory
987*************
988Shared Memory is a block of memory that is shared between the non-secure and the
989secure world. It is used to transfer data between both worlds.
990
Etienne Carriere9c600252019-03-11 11:01:48 +0100991The shared memory is allocated and managed by the non-secure world, i.e. the
992Linux OP-TEE driver. Secure world only considers the individual shared buffers,
993not their pool. Each shared memory is referenced with associated attributes:
Joakim Bech8e5c5b32018-10-25 08:18:32 +0200994
Etienne Carriere9c600252019-03-11 11:01:48 +0100995 - Buffer start address and byte size,
996 - Cache attributes of the shared memory buffer,
997 - List of chunks if mapped from noncontiguous pages.
Joakim Bech8e5c5b32018-10-25 08:18:32 +0200998
Etienne Carriere9c600252019-03-11 11:01:48 +0100999Shared memory buffer references manipulated must fit inside one of the
1000shared memory areas known from the OP-TEE core. OP-TEE supports two kinds
Jerome Forissier7fa91cf2020-07-30 16:03:59 +02001001of shared memory areas: an area for contiguous buffers and an area for
1002noncontiguous buffers. At least one has to be enabled.
Joakim Bech8e5c5b32018-10-25 08:18:32 +02001003
Etienne Carriere9c600252019-03-11 11:01:48 +01001004Contiguous shared buffers
1005=========================
Etienne Carriere9c600252019-03-11 11:01:48 +01001006Configuration directives ``CFG_SHMEM_START`` and ``CFG_SHMEM_SIZE``
1007define a share memory area where shared memory buffers are contiguous.
1008Generic memory layout registers it as the ``MEM_AREA_NSEC_SHM`` memory area.
1009
1010The non-secure world issues ``OPTEE_SMC_GET_SHM_CONFIG`` to retrieve contiguous
1011shared memory area configuration:
Joakim Bech8e5c5b32018-10-25 08:18:32 +02001012
1013 - Physical address of the start of the pool
1014 - Size of the pool
1015 - Whether or not the memory is cached
1016
Jens Wiklandera70d2f42019-04-25 12:40:49 +02001017Contiguous shared memory (also known as static or reserved shared memory)
1018is enabled with the configuration flag ``CFG_CORE_RESERVED_SHM=y``.
1019
Etienne Carriere9c600252019-03-11 11:01:48 +01001020Noncontiguous shared buffers
1021============================
Etienne Carriere9c600252019-03-11 11:01:48 +01001022To benefit from noncontiguous shared memory buffers, secure world register
1023dynamic shared memory areas and non-secure world must register noncontiguous
1024buffers prior to referring to them using the OP-TEE API.
Joakim Bech8e5c5b32018-10-25 08:18:32 +02001025
Etienne Carriere9c600252019-03-11 11:01:48 +01001026The OP-TEE core generic boot sequence discovers dynamic shared areas from the
1027device tree and/or areas explicitly registered by the platform.
1028
1029Non-secure side needs to register buffers as 4kByte chunks lists into OP-TEE
1030core using the ``OPTEE_MSG_CMD_REGISTER_SHM`` API prior referencing to them
1031using the OP-TEE invocation API.
1032
Jens Wiklandera70d2f42019-04-25 12:40:49 +02001033Noncontiguous shared memory (also known as dynamic shared memory) is
1034enabled with the configuration flag ``CFG_CORE_DYN_SHM=y``.
Joakim Bech8e5c5b32018-10-25 08:18:32 +02001035
Jerome Forissier7fa91cf2020-07-30 16:03:59 +02001036For performance reasons, the TEE Client Library (``libteec``) uses
1037noncontiguous shared memory when available since it avoids copies in some
1038situations.
1039
Joakim Bech8e5c5b32018-10-25 08:18:32 +02001040Shared Memory Chunk Allocation
1041==============================
1042It is the Linux kernel driver for OP-TEE that is responsible for allocating
1043chunks of shared memory. OP-TEE linux kernel driver relies on linux kernel
1044generic allocation support (``CONFIG_GENERIC_ALLOCATION``) to allocation/release
1045of shared memory physical chunks. OP-TEE linux kernel driver relies on linux
1046kernel dma-buf support (``CONFIG_DMA_SHARED_BUFFER``) to track shared memory
1047buffers references.
1048
1049Using shared memory
1050===================
1051From the Client Application
1052 The client application can ask for shared memory allocation using the
1053 GlobalPlatform Client API function ``TEEC_AllocateSharedMemory(...)``. The
Etienne Carriere9c600252019-03-11 11:01:48 +01001054 client application can also register a memory through the GlobalPlatform
1055 Client API function ``TEEC_RegisterSharedMemory(...)``. The shared memory
1056 reference can then be used as parameter when invoking a trusted application.
Joakim Bech8e5c5b32018-10-25 08:18:32 +02001057
1058From the Linux Driver
1059 Occasionally the Linux kernel driver needs to allocate shared memory for the
1060 communication with secure world, for example when using buffers of type
1061 ``TEEC_TempMemoryReference``.
1062
1063From OP-TEE core
1064 In case OP-TEE core needs information from TEE supplicant (dynamic TA
1065 loading, REE time request,...), shared memory must be allocated. Allocation
1066 depends on the use case. OP-TEE core asks for the following shared memory
1067 allocation:
1068
1069 - ``optee_msg_arg`` structure, used to pass the arguments to the
1070 non-secure world, where the allocation will be done by sending a
1071 ``OPTEE_SMC_RPC_FUNC_ALLOC`` message.
1072
1073 - In some cases, a payload might be needed for storing the result from
1074 TEE supplicant, for example when loading a Trusted Application. This
1075 type of allocation will be done by sending the message
1076 ``OPTEE_MSG_RPC_CMD_SHM_ALLOC(OPTEE_MSG_RPC_SHM_TYPE_APPL,...)``,
1077 which then will return:
1078
1079 - the physical address of the shared memory
1080 - a handle to the memory, that later on will be used later on when
1081 freeing this memory.
1082
1083From TEE Supplicant
1084 TEE supplicant is also working with shared memory, used to exchange data
1085 between normal and secure worlds. TEE supplicant receives a memory address
1086 from the OP-TEE core, used to store the data. This is for example the case
1087 when a Trusted Application is loaded. In this case, TEE supplicant must
1088 register the provided shared memory in the same way a client application
1089 would do, involving the Linux driver.
1090
1091----
1092
1093.. _smc:
1094
1095SMC
1096***
1097SMC Interface
1098=============
1099OP-TEE's SMC interface is defined in two levels using optee_smc.h_ and
1100optee_msg.h_. The former file defines SMC identifiers and what is passed in the
1101registers for each SMC. The latter file defines the OP-TEE Message protocol
1102which is not restricted to only SMC even if that currently is the only option
1103available.
1104
1105SMC communication
1106=================
1107The main structure used for the SMC communication is defined in ``struct
1108optee_msg_arg`` (in optee_msg.h_). If we are looking into the source code, we
1109could see that communication mainly is achieved using ``optee_msg_arg`` and
1110``thread_smc_args`` (in thread.h_), where ``optee_msg_arg`` could be seen as the
1111main structure. What will happen is that the :ref:`linux_kernel` driver will get
1112the parameters either from :ref:`optee_client` or directly from an internal
1113service in Linux kernel. The TEE driver will populate the struct
1114``optee_msg_arg`` with the parameters plus some additional bookkeeping
1115information. Parameters for the SMC are passed in registers 1 to 7, register 0
1116holds the SMC id which among other things tells whether it is a standard or a
1117fast call.
1118
1119----
1120
1121.. _thread_handling:
1122
1123Thread handling
1124***************
1125OP-TEE core uses a couple of threads to be able to support running jobs in
1126parallel (not fully enabled!). There are handlers for different purposes. In
1127thread.c_ you will find a function called ``thread_init_primary(...)`` which
1128assigns ``init_handlers`` (functions) that should be called when OP-TEE core
1129receives standard or fast calls, FIQ and PSCI calls. There are default handlers
1130for these services, but the platform can decide if they want to implement their
1131own platform specific handlers instead.
1132
1133Synchronization primitives
1134==========================
1135OP-TEE has three primitives for synchronization of threads and CPUs:
1136*spin-lock*, *mutex*, and *condvar*.
1137
1138Spin-lock
1139 A spin-lock is represented as an ``unsigned int``. This is the most
1140 primitive lock. Interrupts should be disabled before attempting to take a
1141 spin-lock and should remain disabled until the lock is released. A spin-lock
1142 is initialized with ``SPINLOCK_UNLOCK``.
1143
1144 .. list-table:: Spin lock functions
1145 :header-rows: 1
1146 :widths: 1 5
1147
1148 * - Function
1149 - Purpose
1150
1151 * - ``cpu_spin_lock(...)``
1152 - Locks a spin-lock
1153
1154 * - ``cpu_spin_trylock(...)``
1155 - Locks a spin-lock if unlocked and returns ``0`` else the spin-lock
1156 is unchanged and the function returns ``!0``
1157
1158 * - ``cpu_spin_unlock(...)``
1159 - Unlocks a spin-lock
1160
1161Mutex
1162 A mutex is represented by ``struct mutex``. A mutex can be locked and
1163 unlocked with interrupts enabled or disabled, but only from a normal thread.
1164 A mutex cannot be used in an interrupt handler, abort handler or before a
1165 thread has been selected for the CPU. A mutex is initialized with either
1166 ``MUTEX_INITIALIZER`` or ``mutex_init(...)``.
1167
1168 .. list-table:: Mutex functions
1169 :header-rows: 1
1170 :widths: 1 5
1171
1172 * - Function
1173 - Purpose
1174
1175 * - ``mutex_lock(...)``
1176 - Locks a mutex. If the mutex is unlocked this is a fast operation,
1177 else the function issues an RPC to wait in normal world.
1178
1179 * - ``mutex_unlock(...)``
1180 - Unlocks a mutex. If there is no waiters this is a fast operation,
1181 else the function issues an RPC to wake up a waiter in normal world.
1182
1183 * - ``mutex_trylock(...)``
1184 - Locks a mutex if unlocked and returns ``true`` else the mutex is
1185 unchanged and the function returns ``false``.
1186
1187 * - ``mutex_destroy(...)``
1188 - Asserts that the mutex is unlocked and there is no waiters, after
1189 this the memory used by the mutex can be freed.
1190
1191 When a mutex is locked it is owned by the thread calling ``mutex_lock(...)``
1192 or ``mutex_trylock(...)``, the mutex may only be unlocked by the thread
1193 owning the mutex. A thread should not exit to TA user space when holding a
1194 mutex.
1195
1196Condvar
1197 A condvar is represented by ``struct condvar``. A condvar is similar to a
1198 ``pthread_condvar_t`` in the pthreads standard, only less advanced.
1199 Condition variables are used to wait for some condition to be fulfilled and
1200 are always used together a mutex. Once a condition variable has been used
1201 together with a certain mutex, it must only be used with that mutex until
1202 destroyed. A condvar is initialized with ``CONDVAR_INITIALIZER`` or
1203 ``condvar_init(...)``.
1204
1205 .. list-table:: Condvar functions
1206 :header-rows: 1
1207 :widths: 1 5
1208
1209 * - Function
1210 - Purpose
1211
1212 * - ``condvar_wait(...)``
1213 - Atomically unlocks the supplied mutex and waits in normal world via
1214 an RPC for the condition variable to be signaled, when the function
1215 returns the mutex is locked again.
1216
1217 * - ``condvar_signal(...)``
1218 - Wakes up one waiter of the condition variable (waiting in
1219 ``condvar_wait(...)``).
1220
1221 * - ``condvar_broadcast(...)``
1222 - Wake up all waiters of the condition variable.
1223
1224 The caller of ``condvar_signal(...)`` or ``condvar_broadcast(...)`` should
1225 hold the mutex associated with the condition variable to guarantee that a
1226 waiter does not miss the signal.
1227
1228.. _core/arch/arm/kernel/thread.c: https://github.com/OP-TEE/optee_os/blob/master/core/arch/arm/kernel/thread.c
1229.. _optee_msg.h: https://github.com/OP-TEE/optee_os/blob/master/core/include/optee_msg.h
1230.. _optee_smc.h: https://github.com/OP-TEE/optee_os/blob/master/core/arch/arm/include/sm/optee_smc.h
1231.. _thread.c: https://github.com/OP-TEE/optee_os/blob/master/core/arch/arm/kernel/thread.c
1232.. _thread.h: https://github.com/OP-TEE/optee_os/blob/master/core/arch/arm/include/kernel/thread.h
1233
1234.. _ARM_DEN0028A_SMC_Calling_Convention: http://infocenter.arm.com/help/topic/com.arm.doc.den0028b/ARM_DEN0028B_SMC_Calling_Convention.pdf
1235.. _Cortex-A53 TRM: http://infocenter.arm.com/help/topic/com.arm.doc.ddi0500j/DDI0500J_cortex_a53_trm.pdf
1236.. _drivers/tee/optee: https://github.com/torvalds/linux/tree/master/drivers/tee/optee
1237.. _Trusted Firmware A: https://github.com/ARM-software/arm-trusted-firmware