firmware-design.rst 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904
  1. Firmware Design
  2. ===============
  3. Trusted Firmware-A (TF-A) implements a subset of the Trusted Board Boot
  4. Requirements (TBBR) Platform Design Document (PDD) for Arm reference
  5. platforms.
  6. The TBB sequence starts when the platform is powered on and runs up
  7. to the stage where it hands-off control to firmware running in the normal
  8. world in DRAM. This is the cold boot path.
  9. TF-A also implements the `PSCI`_ as a runtime service. PSCI is the interface
  10. from normal world software to firmware implementing power management use-cases
  11. (for example, secondary CPU boot, hotplug and idle). Normal world software can
  12. access TF-A runtime services via the Arm SMC (Secure Monitor Call) instruction.
  13. The SMC instruction must be used as mandated by the SMC Calling Convention
  14. (`SMCCC`_).
  15. TF-A implements a framework for configuring and managing interrupts generated
  16. in either security state. The details of the interrupt management framework
  17. and its design can be found in :ref:`Interrupt Management Framework`.
  18. TF-A also implements a library for setting up and managing the translation
  19. tables. The details of this library can be found in
  20. :ref:`Translation (XLAT) Tables Library`.
  21. TF-A can be built to support either AArch64 or AArch32 execution state.
  22. .. note::
  23. The descriptions in this chapter are for the Arm TrustZone architecture.
  24. For changes to the firmware design for the `Arm Confidential Compute
  25. Architecture (Arm CCA)`_ please refer to the chapter :ref:`Realm Management
  26. Extension (RME)`.
  27. Cold boot
  28. ---------
  29. The cold boot path starts when the platform is physically turned on. If
  30. ``COLD_BOOT_SINGLE_CPU=0``, one of the CPUs released from reset is chosen as the
  31. primary CPU, and the remaining CPUs are considered secondary CPUs. The primary
  32. CPU is chosen through platform-specific means. The cold boot path is mainly
  33. executed by the primary CPU, other than essential CPU initialization executed by
  34. all CPUs. The secondary CPUs are kept in a safe platform-specific state until
  35. the primary CPU has performed enough initialization to boot them.
  36. Refer to the :ref:`CPU Reset` for more information on the effect of the
  37. ``COLD_BOOT_SINGLE_CPU`` platform build option.
  38. The cold boot path in this implementation of TF-A depends on the execution
  39. state. For AArch64, it is divided into five steps (in order of execution):
  40. - Boot Loader stage 1 (BL1) *AP Trusted ROM*
  41. - Boot Loader stage 2 (BL2) *Trusted Boot Firmware*
  42. - Boot Loader stage 3-1 (BL31) *EL3 Runtime Software*
  43. - Boot Loader stage 3-2 (BL32) *Secure-EL1 Payload* (optional)
  44. - Boot Loader stage 3-3 (BL33) *Non-trusted Firmware*
  45. For AArch32, it is divided into four steps (in order of execution):
  46. - Boot Loader stage 1 (BL1) *AP Trusted ROM*
  47. - Boot Loader stage 2 (BL2) *Trusted Boot Firmware*
  48. - Boot Loader stage 3-2 (BL32) *EL3 Runtime Software*
  49. - Boot Loader stage 3-3 (BL33) *Non-trusted Firmware*
  50. Arm development platforms (Fixed Virtual Platforms (FVPs) and Juno) implement a
  51. combination of the following types of memory regions. Each bootloader stage uses
  52. one or more of these memory regions.
  53. - Regions accessible from both non-secure and secure states. For example,
  54. non-trusted SRAM, ROM and DRAM.
  55. - Regions accessible from only the secure state. For example, trusted SRAM and
  56. ROM. The FVPs also implement the trusted DRAM which is statically
  57. configured. Additionally, the Base FVPs and Juno development platform
  58. configure the TrustZone Controller (TZC) to create a region in the DRAM
  59. which is accessible only from the secure state.
  60. The sections below provide the following details:
  61. - dynamic configuration of Boot Loader stages
  62. - initialization and execution of the first three stages during cold boot
  63. - specification of the EL3 Runtime Software (BL31 for AArch64 and BL32 for
  64. AArch32) entrypoint requirements for use by alternative Trusted Boot
  65. Firmware in place of the provided BL1 and BL2
  66. Dynamic Configuration during cold boot
  67. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  68. Each of the Boot Loader stages may be dynamically configured if required by the
  69. platform. The Boot Loader stage may optionally specify a firmware
  70. configuration file and/or hardware configuration file as listed below:
  71. - FW_CONFIG - The firmware configuration file. Holds properties shared across
  72. all BLx images.
  73. An example is the "dtb-registry" node, which contains the information about
  74. the other device tree configurations (load-address, size, image_id).
  75. - HW_CONFIG - The hardware configuration file. Can be shared by all Boot Loader
  76. stages and also by the Normal World Rich OS.
  77. - TB_FW_CONFIG - Trusted Boot Firmware configuration file. Shared between BL1
  78. and BL2.
  79. - SOC_FW_CONFIG - SoC Firmware configuration file. Used by BL31.
  80. - TOS_FW_CONFIG - Trusted OS Firmware configuration file. Used by Trusted OS
  81. (BL32).
  82. - NT_FW_CONFIG - Non Trusted Firmware configuration file. Used by Non-trusted
  83. firmware (BL33).
  84. The Arm development platforms use the Flattened Device Tree format for the
  85. dynamic configuration files.
  86. Each Boot Loader stage can pass up to 4 arguments via registers to the next
  87. stage. BL2 passes the list of the next images to execute to the *EL3 Runtime
  88. Software* (BL31 for AArch64 and BL32 for AArch32) via `arg0`. All the other
  89. arguments are platform defined. The Arm development platforms use the following
  90. convention:
  91. - BL1 passes the address of a meminfo_t structure to BL2 via ``arg1``. This
  92. structure contains the memory layout available to BL2.
  93. - When dynamic configuration files are present, the firmware configuration for
  94. the next Boot Loader stage is populated in the first available argument and
  95. the generic hardware configuration is passed the next available argument.
  96. For example,
  97. - FW_CONFIG is loaded by BL1, then its address is passed in ``arg0`` to BL2.
  98. - TB_FW_CONFIG address is retrieved by BL2 from FW_CONFIG device tree.
  99. - If HW_CONFIG is loaded by BL1, then its address is passed in ``arg2`` to
  100. BL2. Note, ``arg1`` is already used for meminfo_t.
  101. - If SOC_FW_CONFIG is loaded by BL2, then its address is passed in ``arg1``
  102. to BL31. Note, ``arg0`` is used to pass the list of executable images.
  103. - Similarly, if HW_CONFIG is loaded by BL1 or BL2, then its address is
  104. passed in ``arg2`` to BL31.
  105. - For other BL3x images, if the firmware configuration file is loaded by
  106. BL2, then its address is passed in ``arg0`` and if HW_CONFIG is loaded
  107. then its address is passed in ``arg1``.
  108. - In case SPMC_AT_EL3 is enabled, populate the BL32 image base, size and max
  109. limit in the entry point information, since there is no platform function
  110. to retrieve these in generic code. We choose ``arg2``, ``arg3`` and
  111. ``arg4`` since the generic code uses ``arg1`` for stashing the SP manifest
  112. size. The SPMC setup uses these arguments to update SP manifest with
  113. actual SP's base address and it size.
  114. - In case of the Arm FVP platform, FW_CONFIG address passed in ``arg1`` to
  115. BL31/SP_MIN, and the SOC_FW_CONFIG and HW_CONFIG details are retrieved
  116. from FW_CONFIG device tree.
  117. BL1
  118. ~~~
  119. This stage begins execution from the platform's reset vector at EL3. The reset
  120. address is platform dependent but it is usually located in a Trusted ROM area.
  121. The BL1 data section is copied to trusted SRAM at runtime.
  122. On the Arm development platforms, BL1 code starts execution from the reset
  123. vector defined by the constant ``BL1_RO_BASE``. The BL1 data section is copied
  124. to the top of trusted SRAM as defined by the constant ``BL1_RW_BASE``.
  125. The functionality implemented by this stage is as follows.
  126. Determination of boot path
  127. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  128. Whenever a CPU is released from reset, BL1 needs to distinguish between a warm
  129. boot and a cold boot. This is done using platform-specific mechanisms (see the
  130. ``plat_get_my_entrypoint()`` function in the :ref:`Porting Guide`). In the case
  131. of a warm boot, a CPU is expected to continue execution from a separate
  132. entrypoint. In the case of a cold boot, the secondary CPUs are placed in a safe
  133. platform-specific state (see the ``plat_secondary_cold_boot_setup()`` function in
  134. the :ref:`Porting Guide`) while the primary CPU executes the remaining cold boot
  135. path as described in the following sections.
  136. This step only applies when ``PROGRAMMABLE_RESET_ADDRESS=0``. Refer to the
  137. :ref:`CPU Reset` for more information on the effect of the
  138. ``PROGRAMMABLE_RESET_ADDRESS`` platform build option.
  139. Architectural initialization
  140. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  141. BL1 performs minimal architectural initialization as follows.
  142. - Exception vectors
  143. BL1 sets up simple exception vectors for both synchronous and asynchronous
  144. exceptions. The default behavior upon receiving an exception is to populate
  145. a status code in the general purpose register ``X0/R0`` and call the
  146. ``plat_report_exception()`` function (see the :ref:`Porting Guide`). The
  147. status code is one of:
  148. For AArch64:
  149. ::
  150. 0x0 : Synchronous exception from Current EL with SP_EL0
  151. 0x1 : IRQ exception from Current EL with SP_EL0
  152. 0x2 : FIQ exception from Current EL with SP_EL0
  153. 0x3 : System Error exception from Current EL with SP_EL0
  154. 0x4 : Synchronous exception from Current EL with SP_ELx
  155. 0x5 : IRQ exception from Current EL with SP_ELx
  156. 0x6 : FIQ exception from Current EL with SP_ELx
  157. 0x7 : System Error exception from Current EL with SP_ELx
  158. 0x8 : Synchronous exception from Lower EL using aarch64
  159. 0x9 : IRQ exception from Lower EL using aarch64
  160. 0xa : FIQ exception from Lower EL using aarch64
  161. 0xb : System Error exception from Lower EL using aarch64
  162. 0xc : Synchronous exception from Lower EL using aarch32
  163. 0xd : IRQ exception from Lower EL using aarch32
  164. 0xe : FIQ exception from Lower EL using aarch32
  165. 0xf : System Error exception from Lower EL using aarch32
  166. For AArch32:
  167. ::
  168. 0x10 : User mode
  169. 0x11 : FIQ mode
  170. 0x12 : IRQ mode
  171. 0x13 : SVC mode
  172. 0x16 : Monitor mode
  173. 0x17 : Abort mode
  174. 0x1a : Hypervisor mode
  175. 0x1b : Undefined mode
  176. 0x1f : System mode
  177. The ``plat_report_exception()`` implementation on the Arm FVP port programs
  178. the Versatile Express System LED register in the following format to
  179. indicate the occurrence of an unexpected exception:
  180. ::
  181. SYS_LED[0] - Security state (Secure=0/Non-Secure=1)
  182. SYS_LED[2:1] - Exception Level (EL3=0x3, EL2=0x2, EL1=0x1, EL0=0x0)
  183. For AArch32 it is always 0x0
  184. SYS_LED[7:3] - Exception Class (Sync/Async & origin). This is the value
  185. of the status code
  186. A write to the LED register reflects in the System LEDs (S6LED0..7) in the
  187. CLCD window of the FVP.
  188. BL1 does not expect to receive any exceptions other than the SMC exception.
  189. For the latter, BL1 installs a simple stub. The stub expects to receive a
  190. limited set of SMC types (determined by their function IDs in the general
  191. purpose register ``X0/R0``):
  192. - ``BL1_SMC_RUN_IMAGE``: This SMC is raised by BL2 to make BL1 pass control
  193. to EL3 Runtime Software.
  194. - All SMCs listed in section "BL1 SMC Interface" in the :ref:`Firmware Update (FWU)`
  195. Design Guide are supported for AArch64 only. These SMCs are currently
  196. not supported when BL1 is built for AArch32.
  197. Any other SMC leads to an assertion failure.
  198. - CPU initialization
  199. BL1 calls the ``reset_handler()`` function which in turn calls the CPU
  200. specific reset handler function (see the section: "CPU specific operations
  201. framework").
  202. Platform initialization
  203. ^^^^^^^^^^^^^^^^^^^^^^^
  204. On Arm platforms, BL1 performs the following platform initializations:
  205. - Enable the Trusted Watchdog.
  206. - Initialize the console.
  207. - Configure the Interconnect to enable hardware coherency.
  208. - Enable the MMU and map the memory it needs to access.
  209. - Configure any required platform storage to load the next bootloader image
  210. (BL2).
  211. - If the BL1 dynamic configuration file, ``TB_FW_CONFIG``, is available, then
  212. load it to the platform defined address and make it available to BL2 via
  213. ``arg0``.
  214. - Configure the system timer and program the `CNTFRQ_EL0` for use by NS-BL1U
  215. and NS-BL2U firmware update images.
  216. Firmware Update detection and execution
  217. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  218. After performing platform setup, BL1 common code calls
  219. ``bl1_plat_get_next_image_id()`` to determine if :ref:`Firmware Update (FWU)` is
  220. required or to proceed with the normal boot process. If the platform code
  221. returns ``BL2_IMAGE_ID`` then the normal boot sequence is executed as described
  222. in the next section, else BL1 assumes that :ref:`Firmware Update (FWU)` is
  223. required and execution passes to the first image in the
  224. :ref:`Firmware Update (FWU)` process. In either case, BL1 retrieves a descriptor
  225. of the next image by calling ``bl1_plat_get_image_desc()``. The image descriptor
  226. contains an ``entry_point_info_t`` structure, which BL1 uses to initialize the
  227. execution state of the next image.
  228. BL2 image load and execution
  229. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  230. In the normal boot flow, BL1 execution continues as follows:
  231. #. BL1 prints the following string from the primary CPU to indicate successful
  232. execution of the BL1 stage:
  233. ::
  234. "Booting Trusted Firmware"
  235. #. BL1 loads a BL2 raw binary image from platform storage, at a
  236. platform-specific base address. Prior to the load, BL1 invokes
  237. ``bl1_plat_handle_pre_image_load()`` which allows the platform to update or
  238. use the image information. If the BL2 image file is not present or if
  239. there is not enough free trusted SRAM the following error message is
  240. printed:
  241. ::
  242. "Failed to load BL2 firmware."
  243. #. BL1 invokes ``bl1_plat_handle_post_image_load()`` which again is intended
  244. for platforms to take further action after image load. This function must
  245. populate the necessary arguments for BL2, which may also include the memory
  246. layout. Further description of the memory layout can be found later
  247. in this document.
  248. #. BL1 passes control to the BL2 image at Secure EL1 (for AArch64) or at
  249. Secure SVC mode (for AArch32), starting from its load address.
  250. BL2
  251. ~~~
  252. BL1 loads and passes control to BL2 at Secure-EL1 (for AArch64) or at Secure
  253. SVC mode (for AArch32) . BL2 is linked against and loaded at a platform-specific
  254. base address (more information can be found later in this document).
  255. The functionality implemented by BL2 is as follows.
  256. Architectural initialization
  257. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  258. For AArch64, BL2 performs the minimal architectural initialization required
  259. for subsequent stages of TF-A and normal world software. EL1 and EL0 are given
  260. access to Floating Point and Advanced SIMD registers by setting the
  261. ``CPACR.FPEN`` bits.
  262. For AArch32, the minimal architectural initialization required for subsequent
  263. stages of TF-A and normal world software is taken care of in BL1 as both BL1
  264. and BL2 execute at PL1.
  265. Platform initialization
  266. ^^^^^^^^^^^^^^^^^^^^^^^
  267. On Arm platforms, BL2 performs the following platform initializations:
  268. - Initialize the console.
  269. - Configure any required platform storage to allow loading further bootloader
  270. images.
  271. - Enable the MMU and map the memory it needs to access.
  272. - Perform platform security setup to allow access to controlled components.
  273. - Reserve some memory for passing information to the next bootloader image
  274. EL3 Runtime Software and populate it.
  275. - Define the extents of memory available for loading each subsequent
  276. bootloader image.
  277. - If BL1 has passed TB_FW_CONFIG dynamic configuration file in ``arg0``,
  278. then parse it.
  279. Image loading in BL2
  280. ^^^^^^^^^^^^^^^^^^^^
  281. BL2 generic code loads the images based on the list of loadable images
  282. provided by the platform. BL2 passes the list of executable images
  283. provided by the platform to the next handover BL image.
  284. The list of loadable images provided by the platform may also contain
  285. dynamic configuration files. The files are loaded and can be parsed as
  286. needed in the ``bl2_plat_handle_post_image_load()`` function. These
  287. configuration files can be passed to next Boot Loader stages as arguments
  288. by updating the corresponding entrypoint information in this function.
  289. SCP_BL2 (System Control Processor Firmware) image load
  290. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  291. Some systems have a separate System Control Processor (SCP) for power, clock,
  292. reset and system control. BL2 loads the optional SCP_BL2 image from platform
  293. storage into a platform-specific region of secure memory. The subsequent
  294. handling of SCP_BL2 is platform specific. For example, on the Juno Arm
  295. development platform port the image is transferred into SCP's internal memory
  296. using the Boot Over MHU (BOM) protocol after being loaded in the trusted SRAM
  297. memory. The SCP executes SCP_BL2 and signals to the Application Processor (AP)
  298. for BL2 execution to continue.
  299. EL3 Runtime Software image load
  300. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  301. BL2 loads the EL3 Runtime Software image from platform storage into a platform-
  302. specific address in trusted SRAM. If there is not enough memory to load the
  303. image or image is missing it leads to an assertion failure.
  304. AArch64 BL32 (Secure-EL1 Payload) image load
  305. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  306. BL2 loads the optional BL32 image from platform storage into a platform-
  307. specific region of secure memory. The image executes in the secure world. BL2
  308. relies on BL31 to pass control to the BL32 image, if present. Hence, BL2
  309. populates a platform-specific area of memory with the entrypoint/load-address
  310. of the BL32 image. The value of the Saved Processor Status Register (``SPSR``)
  311. for entry into BL32 is not determined by BL2, it is initialized by the
  312. Secure-EL1 Payload Dispatcher (see later) within BL31, which is responsible for
  313. managing interaction with BL32. This information is passed to BL31.
  314. BL33 (Non-trusted Firmware) image load
  315. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  316. BL2 loads the BL33 image (e.g. UEFI or other test or boot software) from
  317. platform storage into non-secure memory as defined by the platform.
  318. BL2 relies on EL3 Runtime Software to pass control to BL33 once secure state
  319. initialization is complete. Hence, BL2 populates a platform-specific area of
  320. memory with the entrypoint and Saved Program Status Register (``SPSR``) of the
  321. normal world software image. The entrypoint is the load address of the BL33
  322. image. The ``SPSR`` is determined as specified in Section 5.13 of the
  323. `PSCI`_. This information is passed to the EL3 Runtime Software.
  324. AArch64 BL31 (EL3 Runtime Software) execution
  325. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  326. BL2 execution continues as follows:
  327. #. BL2 passes control back to BL1 by raising an SMC, providing BL1 with the
  328. BL31 entrypoint. The exception is handled by the SMC exception handler
  329. installed by BL1.
  330. #. BL1 turns off the MMU and flushes the caches. It clears the
  331. ``SCTLR_EL3.M/I/C`` bits, flushes the data cache to the point of coherency
  332. and invalidates the TLBs.
  333. #. BL1 passes control to BL31 at the specified entrypoint at EL3.
  334. Running BL2 at EL3 execution level
  335. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  336. Some platforms have a non-TF-A Boot ROM that expects the next boot stage
  337. to execute at EL3. On these platforms, TF-A BL1 is a waste of memory
  338. as its only purpose is to ensure TF-A BL2 is entered at S-EL1. To avoid
  339. this waste, a special mode enables BL2 to execute at EL3, which allows
  340. a non-TF-A Boot ROM to load and jump directly to BL2. This mode is selected
  341. when the build flag RESET_TO_BL2 is enabled.
  342. The main differences in this mode are:
  343. #. BL2 includes the reset code and the mailbox mechanism to differentiate
  344. cold boot and warm boot. It runs at EL3 doing the arch
  345. initialization required for EL3.
  346. #. BL2 does not receive the meminfo information from BL1 anymore. This
  347. information can be passed by the Boot ROM or be internal to the
  348. BL2 image.
  349. #. Since BL2 executes at EL3, BL2 jumps directly to the next image,
  350. instead of invoking the RUN_IMAGE SMC call.
  351. We assume 3 different types of BootROM support on the platform:
  352. #. The Boot ROM always jumps to the same address, for both cold
  353. and warm boot. In this case, we will need to keep a resident part
  354. of BL2 whose memory cannot be reclaimed by any other image. The
  355. linker script defines the symbols __TEXT_RESIDENT_START__ and
  356. __TEXT_RESIDENT_END__ that allows the platform to configure
  357. correctly the memory map.
  358. #. The platform has some mechanism to indicate the jump address to the
  359. Boot ROM. Platform code can then program the jump address with
  360. psci_warmboot_entrypoint during cold boot.
  361. #. The platform has some mechanism to program the reset address using
  362. the PROGRAMMABLE_RESET_ADDRESS feature. Platform code can then
  363. program the reset address with psci_warmboot_entrypoint during
  364. cold boot, bypassing the boot ROM for warm boot.
  365. In the last 2 cases, no part of BL2 needs to remain resident at
  366. runtime. In the first 2 cases, we expect the Boot ROM to be able to
  367. differentiate between warm and cold boot, to avoid loading BL2 again
  368. during warm boot.
  369. This functionality can be tested with FVP loading the image directly
  370. in memory and changing the address where the system jumps at reset.
  371. For example:
  372. -C cluster0.cpu0.RVBAR=0x4022000
  373. --data cluster0.cpu0=bl2.bin@0x4022000
  374. With this configuration, FVP is like a platform of the first case,
  375. where the Boot ROM jumps always to the same address. For simplification,
  376. BL32 is loaded in DRAM in this case, to avoid other images reclaiming
  377. BL2 memory.
  378. AArch64 BL31
  379. ~~~~~~~~~~~~
  380. The image for this stage is loaded by BL2 and BL1 passes control to BL31 at
  381. EL3. BL31 executes solely in trusted SRAM. BL31 is linked against and
  382. loaded at a platform-specific base address (more information can be found later
  383. in this document). The functionality implemented by BL31 is as follows.
  384. Architectural initialization
  385. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  386. Currently, BL31 performs a similar architectural initialization to BL1 as
  387. far as system register settings are concerned. Since BL1 code resides in ROM,
  388. architectural initialization in BL31 allows override of any previous
  389. initialization done by BL1.
  390. BL31 initializes the per-CPU data framework, which provides a cache of
  391. frequently accessed per-CPU data optimised for fast, concurrent manipulation
  392. on different CPUs. This buffer includes pointers to per-CPU contexts, crash
  393. buffer, CPU reset and power down operations, PSCI data, platform data and so on.
  394. It then replaces the exception vectors populated by BL1 with its own. BL31
  395. exception vectors implement more elaborate support for handling SMCs since this
  396. is the only mechanism to access the runtime services implemented by BL31 (PSCI
  397. for example). BL31 checks each SMC for validity as specified by the
  398. `SMC Calling Convention`_ before passing control to the required SMC
  399. handler routine.
  400. BL31 programs the ``CNTFRQ_EL0`` register with the clock frequency of the system
  401. counter, which is provided by the platform.
  402. Platform initialization
  403. ^^^^^^^^^^^^^^^^^^^^^^^
  404. BL31 performs detailed platform initialization, which enables normal world
  405. software to function correctly.
  406. On Arm platforms, this consists of the following:
  407. - Initialize the console.
  408. - Configure the Interconnect to enable hardware coherency.
  409. - Enable the MMU and map the memory it needs to access.
  410. - Initialize the generic interrupt controller.
  411. - Initialize the power controller device.
  412. - Detect the system topology.
  413. Runtime services initialization
  414. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  415. BL31 is responsible for initializing the runtime services. One of them is PSCI.
  416. As part of the PSCI initializations, BL31 detects the system topology. It also
  417. initializes the data structures that implement the state machine used to track
  418. the state of power domain nodes. The state can be one of ``OFF``, ``RUN`` or
  419. ``RETENTION``. All secondary CPUs are initially in the ``OFF`` state. The cluster
  420. that the primary CPU belongs to is ``ON``; any other cluster is ``OFF``. It also
  421. initializes the locks that protect them. BL31 accesses the state of a CPU or
  422. cluster immediately after reset and before the data cache is enabled in the
  423. warm boot path. It is not currently possible to use 'exclusive' based spinlocks,
  424. therefore BL31 uses locks based on Lamport's Bakery algorithm instead.
  425. The runtime service framework and its initialization is described in more
  426. detail in the "EL3 runtime services framework" section below.
  427. Details about the status of the PSCI implementation are provided in the
  428. "Power State Coordination Interface" section below.
  429. AArch64 BL32 (Secure-EL1 Payload) image initialization
  430. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  431. If a BL32 image is present then there must be a matching Secure-EL1 Payload
  432. Dispatcher (SPD) service (see later for details). During initialization
  433. that service must register a function to carry out initialization of BL32
  434. once the runtime services are fully initialized. BL31 invokes such a
  435. registered function to initialize BL32 before running BL33. This initialization
  436. is not necessary for AArch32 SPs.
  437. Details on BL32 initialization and the SPD's role are described in the
  438. :ref:`firmware_design_sel1_spd` section below.
  439. BL33 (Non-trusted Firmware) execution
  440. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  441. EL3 Runtime Software initializes the EL2 or EL1 processor context for normal-
  442. world cold boot, ensuring that no secure state information finds its way into
  443. the non-secure execution state. EL3 Runtime Software uses the entrypoint
  444. information provided by BL2 to jump to the Non-trusted firmware image (BL33)
  445. at the highest available Exception Level (EL2 if available, otherwise EL1).
  446. Using alternative Trusted Boot Firmware in place of BL1 & BL2 (AArch64 only)
  447. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  448. Some platforms have existing implementations of Trusted Boot Firmware that
  449. would like to use TF-A BL31 for the EL3 Runtime Software. To enable this
  450. firmware architecture it is important to provide a fully documented and stable
  451. interface between the Trusted Boot Firmware and BL31.
  452. Future changes to the BL31 interface will be done in a backwards compatible
  453. way, and this enables these firmware components to be independently enhanced/
  454. updated to develop and exploit new functionality.
  455. Required CPU state when calling ``bl31_entrypoint()`` during cold boot
  456. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  457. This function must only be called by the primary CPU.
  458. On entry to this function the calling primary CPU must be executing in AArch64
  459. EL3, little-endian data access, and all interrupt sources masked:
  460. ::
  461. PSTATE.EL = 3
  462. PSTATE.RW = 1
  463. PSTATE.DAIF = 0xf
  464. SCTLR_EL3.EE = 0
  465. X0 and X1 can be used to pass information from the Trusted Boot Firmware to the
  466. platform code in BL31:
  467. ::
  468. X0 : Reserved for common TF-A information
  469. X1 : Platform specific information
  470. BL31 zero-init sections (e.g. ``.bss``) should not contain valid data on entry,
  471. these will be zero filled prior to invoking platform setup code.
  472. Use of the X0 and X1 parameters
  473. '''''''''''''''''''''''''''''''
  474. The parameters are platform specific and passed from ``bl31_entrypoint()`` to
  475. ``bl31_early_platform_setup()``. The value of these parameters is never directly
  476. used by the common BL31 code.
  477. The convention is that ``X0`` conveys information regarding the BL31, BL32 and
  478. BL33 images from the Trusted Boot firmware and ``X1`` can be used for other
  479. platform specific purpose. This convention allows platforms which use TF-A's
  480. BL1 and BL2 images to transfer additional platform specific information from
  481. Secure Boot without conflicting with future evolution of TF-A using ``X0`` to
  482. pass a ``bl31_params`` structure.
  483. BL31 common and SPD initialization code depends on image and entrypoint
  484. information about BL33 and BL32, which is provided via BL31 platform APIs.
  485. This information is required until the start of execution of BL33. This
  486. information can be provided in a platform defined manner, e.g. compiled into
  487. the platform code in BL31, or provided in a platform defined memory location
  488. by the Trusted Boot firmware, or passed from the Trusted Boot Firmware via the
  489. Cold boot Initialization parameters. This data may need to be cleaned out of
  490. the CPU caches if it is provided by an earlier boot stage and then accessed by
  491. BL31 platform code before the caches are enabled.
  492. TF-A's BL2 implementation passes a ``bl31_params`` structure in
  493. ``X0`` and the Arm development platforms interpret this in the BL31 platform
  494. code.
  495. MMU, Data caches & Coherency
  496. ''''''''''''''''''''''''''''
  497. BL31 does not depend on the enabled state of the MMU, data caches or
  498. interconnect coherency on entry to ``bl31_entrypoint()``. If these are disabled
  499. on entry, these should be enabled during ``bl31_plat_arch_setup()``.
  500. Data structures used in the BL31 cold boot interface
  501. ''''''''''''''''''''''''''''''''''''''''''''''''''''
  502. In the cold boot flow, ``entry_point_info`` is used to represent the execution
  503. state of an image; that is, the state of general purpose registers, PC, and
  504. SPSR.
  505. There are two variants of this structure, for AArch64:
  506. .. code:: c
  507. typedef struct entry_point_info {
  508. param_header_t h;
  509. uintptr_t pc;
  510. uint32_t spsr;
  511. aapcs64_params_t args;
  512. }
  513. and, AArch32:
  514. .. code:: c
  515. typedef struct entry_point_info {
  516. param_header_t h;
  517. uintptr_t pc;
  518. uint32_t spsr;
  519. uintptr_t lr_svc;
  520. aapcs32_params_t args;
  521. } entry_point_info_t;
  522. These structures are designed to support compatibility and independent
  523. evolution of the structures and the firmware images. For example, a version of
  524. BL31 that can interpret the BL3x image information from different versions of
  525. BL2, a platform that uses an extended entry_point_info structure to convey
  526. additional register information to BL31, or a ELF image loader that can convey
  527. more details about the firmware images.
  528. To support these scenarios the structures are versioned and sized, which enables
  529. BL31 to detect which information is present and respond appropriately. The
  530. ``param_header`` is defined to capture this information:
  531. .. code:: c
  532. typedef struct param_header {
  533. uint8_t type; /* type of the structure */
  534. uint8_t version; /* version of this structure */
  535. uint16_t size; /* size of this structure in bytes */
  536. uint32_t attr; /* attributes */
  537. } param_header_t;
  538. In `entry_point_info`, Bits 0 and 5 of ``attr`` field are used to encode the
  539. security state; in other words, whether the image is to be executed in Secure,
  540. Non-Secure, or Realm mode.
  541. Other structures using this format are ``image_info`` and ``bl31_params``. The
  542. code that allocates and populates these structures must set the header fields
  543. appropriately, the ``SET_PARAM_HEAD()`` macro is defined to simplify this
  544. action.
  545. Required CPU state for BL31 Warm boot initialization
  546. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  547. When requesting a CPU power-on, or suspending a running CPU, TF-A provides
  548. the platform power management code with a Warm boot initialization
  549. entry-point, to be invoked by the CPU immediately after the reset handler.
  550. On entry to the Warm boot initialization function the calling CPU must be in
  551. AArch64 EL3, little-endian data access and all interrupt sources masked:
  552. ::
  553. PSTATE.EL = 3
  554. PSTATE.RW = 1
  555. PSTATE.DAIF = 0xf
  556. SCTLR_EL3.EE = 0
  557. The PSCI implementation will initialize the processor state and ensure that the
  558. platform power management code is then invoked as required to initialize all
  559. necessary system, cluster and CPU resources.
  560. AArch32 EL3 Runtime Software entrypoint interface
  561. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  562. To enable this firmware architecture it is important to provide a fully
  563. documented and stable interface between the Trusted Boot Firmware and the
  564. AArch32 EL3 Runtime Software.
  565. Future changes to the entrypoint interface will be done in a backwards
  566. compatible way, and this enables these firmware components to be independently
  567. enhanced/updated to develop and exploit new functionality.
  568. Required CPU state when entering during cold boot
  569. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  570. This function must only be called by the primary CPU.
  571. On entry to this function the calling primary CPU must be executing in AArch32
  572. EL3, little-endian data access, and all interrupt sources masked:
  573. ::
  574. PSTATE.AIF = 0x7
  575. SCTLR.EE = 0
  576. R0 and R1 are used to pass information from the Trusted Boot Firmware to the
  577. platform code in AArch32 EL3 Runtime Software:
  578. ::
  579. R0 : Reserved for common TF-A information
  580. R1 : Platform specific information
  581. Use of the R0 and R1 parameters
  582. '''''''''''''''''''''''''''''''
  583. The parameters are platform specific and the convention is that ``R0`` conveys
  584. information regarding the BL3x images from the Trusted Boot firmware and ``R1``
  585. can be used for other platform specific purpose. This convention allows
  586. platforms which use TF-A's BL1 and BL2 images to transfer additional platform
  587. specific information from Secure Boot without conflicting with future
  588. evolution of TF-A using ``R0`` to pass a ``bl_params`` structure.
  589. The AArch32 EL3 Runtime Software is responsible for entry into BL33. This
  590. information can be obtained in a platform defined manner, e.g. compiled into
  591. the AArch32 EL3 Runtime Software, or provided in a platform defined memory
  592. location by the Trusted Boot firmware, or passed from the Trusted Boot Firmware
  593. via the Cold boot Initialization parameters. This data may need to be cleaned
  594. out of the CPU caches if it is provided by an earlier boot stage and then
  595. accessed by AArch32 EL3 Runtime Software before the caches are enabled.
  596. When using AArch32 EL3 Runtime Software, the Arm development platforms pass a
  597. ``bl_params`` structure in ``R0`` from BL2 to be interpreted by AArch32 EL3 Runtime
  598. Software platform code.
  599. MMU, Data caches & Coherency
  600. ''''''''''''''''''''''''''''
  601. AArch32 EL3 Runtime Software must not depend on the enabled state of the MMU,
  602. data caches or interconnect coherency in its entrypoint. They must be explicitly
  603. enabled if required.
  604. Data structures used in cold boot interface
  605. '''''''''''''''''''''''''''''''''''''''''''
  606. The AArch32 EL3 Runtime Software cold boot interface uses ``bl_params`` instead
  607. of ``bl31_params``. The ``bl_params`` structure is based on the convention
  608. described in AArch64 BL31 cold boot interface section.
  609. Required CPU state for warm boot initialization
  610. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  611. When requesting a CPU power-on, or suspending a running CPU, AArch32 EL3
  612. Runtime Software must ensure execution of a warm boot initialization entrypoint.
  613. If TF-A BL1 is used and the PROGRAMMABLE_RESET_ADDRESS build flag is false,
  614. then AArch32 EL3 Runtime Software must ensure that BL1 branches to the warm
  615. boot entrypoint by arranging for the BL1 platform function,
  616. plat_get_my_entrypoint(), to return a non-zero value.
  617. In this case, the warm boot entrypoint must be in AArch32 EL3, little-endian
  618. data access and all interrupt sources masked:
  619. ::
  620. PSTATE.AIF = 0x7
  621. SCTLR.EE = 0
  622. The warm boot entrypoint may be implemented by using TF-A
  623. ``psci_warmboot_entrypoint()`` function. In that case, the platform must fulfil
  624. the pre-requisites mentioned in the
  625. :ref:`PSCI Library Integration guide for Armv8-A AArch32 systems`.
  626. EL3 runtime services framework
  627. ------------------------------
  628. Software executing in the non-secure state and in the secure state at exception
  629. levels lower than EL3 will request runtime services using the Secure Monitor
  630. Call (SMC) instruction. These requests will follow the convention described in
  631. the SMC Calling Convention PDD (`SMCCC`_). The `SMCCC`_ assigns function
  632. identifiers to each SMC request and describes how arguments are passed and
  633. returned.
  634. The EL3 runtime services framework enables the development of services by
  635. different providers that can be easily integrated into final product firmware.
  636. The following sections describe the framework which facilitates the
  637. registration, initialization and use of runtime services in EL3 Runtime
  638. Software (BL31).
  639. The design of the runtime services depends heavily on the concepts and
  640. definitions described in the `SMCCC`_, in particular SMC Function IDs, Owning
  641. Entity Numbers (OEN), Fast and Yielding calls, and the SMC32 and SMC64 calling
  642. conventions. Please refer to that document for more detailed explanation of
  643. these terms.
  644. The following runtime services are expected to be implemented first. They have
  645. not all been instantiated in the current implementation.
  646. #. Standard service calls
  647. This service is for management of the entire system. The Power State
  648. Coordination Interface (`PSCI`_) is the first set of standard service calls
  649. defined by Arm (see PSCI section later).
  650. #. Secure-EL1 Payload Dispatcher service
  651. If a system runs a Trusted OS or other Secure-EL1 Payload (SP) then
  652. it also requires a *Secure Monitor* at EL3 to switch the EL1 processor
  653. context between the normal world (EL1/EL2) and trusted world (Secure-EL1).
  654. The Secure Monitor will make these world switches in response to SMCs. The
  655. `SMCCC`_ provides for such SMCs with the Trusted OS Call and Trusted
  656. Application Call OEN ranges.
  657. The interface between the EL3 Runtime Software and the Secure-EL1 Payload is
  658. not defined by the `SMCCC`_ or any other standard. As a result, each
  659. Secure-EL1 Payload requires a specific Secure Monitor that runs as a runtime
  660. service - within TF-A this service is referred to as the Secure-EL1 Payload
  661. Dispatcher (SPD).
  662. TF-A provides a Test Secure-EL1 Payload (TSP) and its associated Dispatcher
  663. (TSPD). Details of SPD design and TSP/TSPD operation are described in the
  664. :ref:`firmware_design_sel1_spd` section below.
  665. #. CPU implementation service
  666. This service will provide an interface to CPU implementation specific
  667. services for a given platform e.g. access to processor errata workarounds.
  668. This service is currently unimplemented.
  669. Additional services for Arm Architecture, SiP and OEM calls can be implemented.
  670. Each implemented service handles a range of SMC function identifiers as
  671. described in the `SMCCC`_.
  672. Registration
  673. ~~~~~~~~~~~~
  674. A runtime service is registered using the ``DECLARE_RT_SVC()`` macro, specifying
  675. the name of the service, the range of OENs covered, the type of service and
  676. initialization and call handler functions. This macro instantiates a ``const struct rt_svc_desc`` for the service with these details (see ``runtime_svc.h``).
  677. This structure is allocated in a special ELF section ``.rt_svc_descs``, enabling
  678. the framework to find all service descriptors included into BL31.
  679. The specific service for a SMC Function is selected based on the OEN and call
  680. type of the Function ID, and the framework uses that information in the service
  681. descriptor to identify the handler for the SMC Call.
  682. The service descriptors do not include information to identify the precise set
  683. of SMC function identifiers supported by this service implementation, the
  684. security state from which such calls are valid nor the capability to support
  685. 64-bit and/or 32-bit callers (using SMC32 or SMC64). Responding appropriately
  686. to these aspects of a SMC call is the responsibility of the service
  687. implementation, the framework is focused on integration of services from
  688. different providers and minimizing the time taken by the framework before the
  689. service handler is invoked.
  690. Details of the parameters, requirements and behavior of the initialization and
  691. call handling functions are provided in the following sections.
  692. Initialization
  693. ~~~~~~~~~~~~~~
  694. ``runtime_svc_init()`` in ``runtime_svc.c`` initializes the runtime services
  695. framework running on the primary CPU during cold boot as part of the BL31
  696. initialization. This happens prior to initializing a Trusted OS and running
  697. Normal world boot firmware that might in turn use these services.
  698. Initialization involves validating each of the declared runtime service
  699. descriptors, calling the service initialization function and populating the
  700. index used for runtime lookup of the service.
  701. The BL31 linker script collects all of the declared service descriptors into a
  702. single array and defines symbols that allow the framework to locate and traverse
  703. the array, and determine its size.
  704. The framework does basic validation of each descriptor to halt firmware
  705. initialization if service declaration errors are detected. The framework does
  706. not check descriptors for the following error conditions, and may behave in an
  707. unpredictable manner under such scenarios:
  708. #. Overlapping OEN ranges
  709. #. Multiple descriptors for the same range of OENs and ``call_type``
  710. #. Incorrect range of owning entity numbers for a given ``call_type``
  711. Once validated, the service ``init()`` callback is invoked. This function carries
  712. out any essential EL3 initialization before servicing requests. The ``init()``
  713. function is only invoked on the primary CPU during cold boot. If the service
  714. uses per-CPU data this must either be initialized for all CPUs during this call,
  715. or be done lazily when a CPU first issues an SMC call to that service. If
  716. ``init()`` returns anything other than ``0``, this is treated as an initialization
  717. error and the service is ignored: this does not cause the firmware to halt.
  718. The OEN and call type fields present in the SMC Function ID cover a total of
  719. 128 distinct services, but in practice a single descriptor can cover a range of
  720. OENs, e.g. SMCs to call a Trusted OS function. To optimize the lookup of a
  721. service handler, the framework uses an array of 128 indices that map every
  722. distinct OEN/call-type combination either to one of the declared services or to
  723. indicate the service is not handled. This ``rt_svc_descs_indices[]`` array is
  724. populated for all of the OENs covered by a service after the service ``init()``
  725. function has reported success. So a service that fails to initialize will never
  726. have it's ``handle()`` function invoked.
  727. The following figure shows how the ``rt_svc_descs_indices[]`` index maps the SMC
  728. Function ID call type and OEN onto a specific service handler in the
  729. ``rt_svc_descs[]`` array.
  730. |Image 1|
  731. .. _handling-an-smc:
  732. Handling an SMC
  733. ~~~~~~~~~~~~~~~
  734. When the EL3 runtime services framework receives a Secure Monitor Call, the SMC
  735. Function ID is passed in W0 from the lower exception level (as per the
  736. `SMCCC`_). If the calling register width is AArch32, it is invalid to invoke an
  737. SMC Function which indicates the SMC64 calling convention: such calls are
  738. ignored and return the Unknown SMC Function Identifier result code ``0xFFFFFFFF``
  739. in R0/X0.
  740. Bit[31] (fast/yielding call) and bits[29:24] (owning entity number) of the SMC
  741. Function ID are combined to index into the ``rt_svc_descs_indices[]`` array. The
  742. resulting value might indicate a service that has no handler, in this case the
  743. framework will also report an Unknown SMC Function ID. Otherwise, the value is
  744. used as a further index into the ``rt_svc_descs[]`` array to locate the required
  745. service and handler.
  746. The service's ``handle()`` callback is provided with five of the SMC parameters
  747. directly, the others are saved into memory for retrieval (if needed) by the
  748. handler. The handler is also provided with an opaque ``handle`` for use with the
  749. supporting library for parameter retrieval, setting return values and context
  750. manipulation. The ``flags`` parameter indicates the security state of the caller
  751. and the state of the SVE hint bit per the SMCCCv1.3. The framework finally sets
  752. up the execution stack for the handler, and invokes the services ``handle()``
  753. function.
  754. On return from the handler the result registers are populated in X0-X7 as needed
  755. before restoring the stack and CPU state and returning from the original SMC.
  756. Exception Handling Framework
  757. ----------------------------
  758. Please refer to the :ref:`Exception Handling Framework` document.
  759. Power State Coordination Interface
  760. ----------------------------------
  761. TODO: Provide design walkthrough of PSCI implementation.
  762. The PSCI v1.1 specification categorizes APIs as optional and mandatory. All the
  763. mandatory APIs in PSCI v1.1, PSCI v1.0 and in PSCI v0.2 draft specification
  764. `PSCI`_ are implemented. The table lists the PSCI v1.1 APIs and their support
  765. in generic code.
  766. An API implementation might have a dependency on platform code e.g. CPU_SUSPEND
  767. requires the platform to export a part of the implementation. Hence the level
  768. of support of the mandatory APIs depends upon the support exported by the
  769. platform port as well. The Juno and FVP (all variants) platforms export all the
  770. required support.
  771. +-----------------------------+-------------+-------------------------------+
  772. | PSCI v1.1 API | Supported | Comments |
  773. +=============================+=============+===============================+
  774. | ``PSCI_VERSION`` | Yes | The version returned is 1.1 |
  775. +-----------------------------+-------------+-------------------------------+
  776. | ``CPU_SUSPEND`` | Yes\* | |
  777. +-----------------------------+-------------+-------------------------------+
  778. | ``CPU_OFF`` | Yes\* | |
  779. +-----------------------------+-------------+-------------------------------+
  780. | ``CPU_ON`` | Yes\* | |
  781. +-----------------------------+-------------+-------------------------------+
  782. | ``AFFINITY_INFO`` | Yes | |
  783. +-----------------------------+-------------+-------------------------------+
  784. | ``MIGRATE`` | Yes\*\* | |
  785. +-----------------------------+-------------+-------------------------------+
  786. | ``MIGRATE_INFO_TYPE`` | Yes\*\* | |
  787. +-----------------------------+-------------+-------------------------------+
  788. | ``MIGRATE_INFO_CPU`` | Yes\*\* | |
  789. +-----------------------------+-------------+-------------------------------+
  790. | ``SYSTEM_OFF`` | Yes\* | |
  791. +-----------------------------+-------------+-------------------------------+
  792. | ``SYSTEM_RESET`` | Yes\* | |
  793. +-----------------------------+-------------+-------------------------------+
  794. | ``PSCI_FEATURES`` | Yes | |
  795. +-----------------------------+-------------+-------------------------------+
  796. | ``CPU_FREEZE`` | No | |
  797. +-----------------------------+-------------+-------------------------------+
  798. | ``CPU_DEFAULT_SUSPEND`` | No | |
  799. +-----------------------------+-------------+-------------------------------+
  800. | ``NODE_HW_STATE`` | Yes\* | |
  801. +-----------------------------+-------------+-------------------------------+
  802. | ``SYSTEM_SUSPEND`` | Yes\* | |
  803. +-----------------------------+-------------+-------------------------------+
  804. | ``PSCI_SET_SUSPEND_MODE`` | No | |
  805. +-----------------------------+-------------+-------------------------------+
  806. | ``PSCI_STAT_RESIDENCY`` | Yes\* | |
  807. +-----------------------------+-------------+-------------------------------+
  808. | ``PSCI_STAT_COUNT`` | Yes\* | |
  809. +-----------------------------+-------------+-------------------------------+
  810. | ``SYSTEM_RESET2`` | Yes\* | |
  811. +-----------------------------+-------------+-------------------------------+
  812. | ``MEM_PROTECT`` | Yes\* | |
  813. +-----------------------------+-------------+-------------------------------+
  814. | ``MEM_PROTECT_CHECK_RANGE`` | Yes\* | |
  815. +-----------------------------+-------------+-------------------------------+
  816. \*Note : These PSCI APIs require platform power management hooks to be
  817. registered with the generic PSCI code to be supported.
  818. \*\*Note : These PSCI APIs require appropriate Secure Payload Dispatcher
  819. hooks to be registered with the generic PSCI code to be supported.
  820. The PSCI implementation in TF-A is a library which can be integrated with
  821. AArch64 or AArch32 EL3 Runtime Software for Armv8-A systems. A guide to
  822. integrating PSCI library with AArch32 EL3 Runtime Software can be found
  823. at :ref:`PSCI Library Integration guide for Armv8-A AArch32 systems`.
  824. .. _firmware_design_sel1_spd:
  825. Secure-EL1 Payloads and Dispatchers
  826. -----------------------------------
  827. On a production system that includes a Trusted OS running in Secure-EL1/EL0,
  828. the Trusted OS is coupled with a companion runtime service in the BL31
  829. firmware. This service is responsible for the initialisation of the Trusted
  830. OS and all communications with it. The Trusted OS is the BL32 stage of the
  831. boot flow in TF-A. The firmware will attempt to locate, load and execute a
  832. BL32 image.
  833. TF-A uses a more general term for the BL32 software that runs at Secure-EL1 -
  834. the *Secure-EL1 Payload* - as it is not always a Trusted OS.
  835. TF-A provides a Test Secure-EL1 Payload (TSP) and a Test Secure-EL1 Payload
  836. Dispatcher (TSPD) service as an example of how a Trusted OS is supported on a
  837. production system using the Runtime Services Framework. On such a system, the
  838. Test BL32 image and service are replaced by the Trusted OS and its dispatcher
  839. service. The TF-A build system expects that the dispatcher will define the
  840. build flag ``NEED_BL32`` to enable it to include the BL32 in the build either
  841. as a binary or to compile from source depending on whether the ``BL32`` build
  842. option is specified or not.
  843. The TSP runs in Secure-EL1. It is designed to demonstrate synchronous
  844. communication with the normal-world software running in EL1/EL2. Communication
  845. is initiated by the normal-world software
  846. - either directly through a Fast SMC (as defined in the `SMCCC`_)
  847. - or indirectly through a `PSCI`_ SMC. The `PSCI`_ implementation in turn
  848. informs the TSPD about the requested power management operation. This allows
  849. the TSP to prepare for or respond to the power state change
  850. The TSPD service is responsible for.
  851. - Initializing the TSP
  852. - Routing requests and responses between the secure and the non-secure
  853. states during the two types of communications just described
  854. Initializing a BL32 Image
  855. ~~~~~~~~~~~~~~~~~~~~~~~~~
  856. The Secure-EL1 Payload Dispatcher (SPD) service is responsible for initializing
  857. the BL32 image. It needs access to the information passed by BL2 to BL31 to do
  858. so. This is provided by:
  859. .. code:: c
  860. entry_point_info_t *bl31_plat_get_next_image_ep_info(uint32_t);
  861. which returns a reference to the ``entry_point_info`` structure corresponding to
  862. the image which will be run in the specified security state. The SPD uses this
  863. API to get entry point information for the SECURE image, BL32.
  864. In the absence of a BL32 image, BL31 passes control to the normal world
  865. bootloader image (BL33). When the BL32 image is present, it is typical
  866. that the SPD wants control to be passed to BL32 first and then later to BL33.
  867. To do this the SPD has to register a BL32 initialization function during
  868. initialization of the SPD service. The BL32 initialization function has this
  869. prototype:
  870. .. code:: c
  871. int32_t init(void);
  872. and is registered using the ``bl31_register_bl32_init()`` function.
  873. TF-A supports two approaches for the SPD to pass control to BL32 before
  874. returning through EL3 and running the non-trusted firmware (BL33):
  875. #. In the BL32 setup function, use ``bl31_set_next_image_type()`` to
  876. request that the exit from ``bl31_main()`` is to the BL32 entrypoint in
  877. Secure-EL1. BL31 will exit to BL32 using the asynchronous method by
  878. calling ``bl31_prepare_next_image_entry()`` and ``el3_exit()``.
  879. When the BL32 has completed initialization at Secure-EL1, it returns to
  880. BL31 by issuing an SMC, using a Function ID allocated to the SPD. On
  881. receipt of this SMC, the SPD service handler should switch the CPU context
  882. from trusted to normal world and use the ``bl31_set_next_image_type()`` and
  883. ``bl31_prepare_next_image_entry()`` functions to set up the initial return to
  884. the normal world firmware BL33. On return from the handler the framework
  885. will exit to EL2 and run BL33.
  886. #. The BL32 setup function registers an initialization function using
  887. ``bl31_register_bl32_init()`` which provides a SPD-defined mechanism to
  888. invoke a 'world-switch synchronous call' to Secure-EL1 to run the BL32
  889. entrypoint.
  890. .. note::
  891. The Test SPD service included with TF-A provides one implementation
  892. of such a mechanism.
  893. On completion BL32 returns control to BL31 via a SMC, and on receipt the
  894. SPD service handler invokes the synchronous call return mechanism to return
  895. to the BL32 initialization function. On return from this function,
  896. ``bl31_main()`` will set up the return to the normal world firmware BL33 and
  897. continue the boot process in the normal world.
  898. Exception handling in BL31
  899. --------------------------
  900. When exception occurs, PE must execute handler corresponding to exception. The
  901. location in memory where the handler is stored is called the exception vector.
  902. For ARM architecture, exception vectors are stored in a table, called the exception
  903. vector table.
  904. Each EL (except EL0) has its own vector table, VBAR_ELn register stores the base
  905. of vector table. Refer to `AArch64 exception vector table`_
  906. Current EL with SP_EL0
  907. ~~~~~~~~~~~~~~~~~~~~~~
  908. - Sync exception : Not expected except for BRK instruction, its debugging tool which
  909. a programmer may place at specific points in a program, to check the state of
  910. processor flags at these points in the code.
  911. - IRQ/FIQ : Unexpected exception, panic
  912. - SError : "plat_handle_el3_ea", defaults to panic
  913. Current EL with SP_ELx
  914. ~~~~~~~~~~~~~~~~~~~~~~
  915. - Sync exception : Unexpected exception, panic
  916. - IRQ/FIQ : Unexpected exception, panic
  917. - SError : "plat_handle_el3_ea" Except for special handling of lower EL's SError exception
  918. which gets triggered in EL3 when PSTATE.A is unmasked. Its only applicable when lower
  919. EL's EA is routed to EL3 (FFH_SUPPORT=1).
  920. Lower EL Exceptions
  921. ~~~~~~~~~~~~~~~~~~~
  922. Applies to all the exceptions in both AArch64/AArch32 mode of lower EL.
  923. Before handling any lower EL exception, we synchronize the errors at EL3 entry to ensure
  924. that any errors pertaining to lower EL is isolated/identified. If we continue without
  925. identifying these errors early on then these errors will trigger in EL3 (as SError from
  926. current EL) any time after PSTATE.A is unmasked. This is wrong because the error originated
  927. in lower EL but exception happened in EL3.
  928. To solve this problem, synchronize the errors at EL3 entry and check for any pending
  929. errors (async EA). If there is no pending error then continue with original exception.
  930. If there is a pending error then, handle them based on routing model of EA's. Refer to
  931. :ref:`Reliability, Availability, and Serviceability (RAS) Extensions` for details about
  932. routing models.
  933. - KFH : Reflect it back to lower EL using **reflect_pending_async_ea_to_lower_el()**
  934. - FFH : Handle the synchronized error first using **handle_pending_async_ea()** after
  935. that continue with original exception. It is the only scenario where EL3 is capable
  936. of doing nested exception handling.
  937. After synchronizing and handling lower EL SErrors, unmask EA (PSTATE.A) to ensure
  938. that any further EA's caused by EL3 are caught.
  939. Crash Reporting in BL31
  940. -----------------------
  941. BL31 implements a scheme for reporting the processor state when an unhandled
  942. exception is encountered. The reporting mechanism attempts to preserve all the
  943. register contents and report it via a dedicated UART (PL011 console). BL31
  944. reports the general purpose, EL3, Secure EL1 and some EL2 state registers.
  945. A dedicated per-CPU crash stack is maintained by BL31 and this is retrieved via
  946. the per-CPU pointer cache. The implementation attempts to minimise the memory
  947. required for this feature. The file ``crash_reporting.S`` contains the
  948. implementation for crash reporting.
  949. The sample crash output is shown below.
  950. ::
  951. x0 = 0x000000002a4a0000
  952. x1 = 0x0000000000000001
  953. x2 = 0x0000000000000002
  954. x3 = 0x0000000000000003
  955. x4 = 0x0000000000000004
  956. x5 = 0x0000000000000005
  957. x6 = 0x0000000000000006
  958. x7 = 0x0000000000000007
  959. x8 = 0x0000000000000008
  960. x9 = 0x0000000000000009
  961. x10 = 0x0000000000000010
  962. x11 = 0x0000000000000011
  963. x12 = 0x0000000000000012
  964. x13 = 0x0000000000000013
  965. x14 = 0x0000000000000014
  966. x15 = 0x0000000000000015
  967. x16 = 0x0000000000000016
  968. x17 = 0x0000000000000017
  969. x18 = 0x0000000000000018
  970. x19 = 0x0000000000000019
  971. x20 = 0x0000000000000020
  972. x21 = 0x0000000000000021
  973. x22 = 0x0000000000000022
  974. x23 = 0x0000000000000023
  975. x24 = 0x0000000000000024
  976. x25 = 0x0000000000000025
  977. x26 = 0x0000000000000026
  978. x27 = 0x0000000000000027
  979. x28 = 0x0000000000000028
  980. x29 = 0x0000000000000029
  981. x30 = 0x0000000088000b78
  982. scr_el3 = 0x000000000003073d
  983. sctlr_el3 = 0x00000000b0cd183f
  984. cptr_el3 = 0x0000000000000000
  985. tcr_el3 = 0x000000008080351c
  986. daif = 0x00000000000002c0
  987. mair_el3 = 0x00000000004404ff
  988. spsr_el3 = 0x0000000060000349
  989. elr_el3 = 0x0000000088000114
  990. ttbr0_el3 = 0x0000000004018201
  991. esr_el3 = 0x00000000be000000
  992. far_el3 = 0x0000000000000000
  993. spsr_el1 = 0x0000000000000000
  994. elr_el1 = 0x0000000000000000
  995. spsr_abt = 0x0000000000000000
  996. spsr_und = 0x0000000000000000
  997. spsr_irq = 0x0000000000000000
  998. spsr_fiq = 0x0000000000000000
  999. sctlr_el1 = 0x0000000030d00800
  1000. actlr_el1 = 0x0000000000000000
  1001. cpacr_el1 = 0x0000000000000000
  1002. csselr_el1 = 0x0000000000000000
  1003. sp_el1 = 0x0000000000000000
  1004. esr_el1 = 0x0000000000000000
  1005. ttbr0_el1 = 0x0000000000000000
  1006. ttbr1_el1 = 0x0000000000000000
  1007. mair_el1 = 0x0000000000000000
  1008. amair_el1 = 0x0000000000000000
  1009. tcr_el1 = 0x0000000000000000
  1010. tpidr_el1 = 0x0000000000000000
  1011. tpidr_el0 = 0x0000000000000000
  1012. tpidrro_el0 = 0x0000000000000000
  1013. par_el1 = 0x0000000000000000
  1014. mpidr_el1 = 0x0000000080000000
  1015. afsr0_el1 = 0x0000000000000000
  1016. afsr1_el1 = 0x0000000000000000
  1017. contextidr_el1 = 0x0000000000000000
  1018. vbar_el1 = 0x0000000000000000
  1019. cntp_ctl_el0 = 0x0000000000000000
  1020. cntp_cval_el0 = 0x0000000000000000
  1021. cntv_ctl_el0 = 0x0000000000000000
  1022. cntv_cval_el0 = 0x0000000000000000
  1023. cntkctl_el1 = 0x0000000000000000
  1024. sp_el0 = 0x0000000004014940
  1025. isr_el1 = 0x0000000000000000
  1026. dacr32_el2 = 0x0000000000000000
  1027. ifsr32_el2 = 0x0000000000000000
  1028. icc_hppir0_el1 = 0x00000000000003ff
  1029. icc_hppir1_el1 = 0x00000000000003ff
  1030. icc_ctlr_el3 = 0x0000000000080400
  1031. gicd_ispendr regs (Offsets 0x200-0x278)
  1032. Offset Value
  1033. 0x200: 0x0000000000000000
  1034. 0x208: 0x0000000000000000
  1035. 0x210: 0x0000000000000000
  1036. 0x218: 0x0000000000000000
  1037. 0x220: 0x0000000000000000
  1038. 0x228: 0x0000000000000000
  1039. 0x230: 0x0000000000000000
  1040. 0x238: 0x0000000000000000
  1041. 0x240: 0x0000000000000000
  1042. 0x248: 0x0000000000000000
  1043. 0x250: 0x0000000000000000
  1044. 0x258: 0x0000000000000000
  1045. 0x260: 0x0000000000000000
  1046. 0x268: 0x0000000000000000
  1047. 0x270: 0x0000000000000000
  1048. 0x278: 0x0000000000000000
  1049. Guidelines for Reset Handlers
  1050. -----------------------------
  1051. TF-A implements a framework that allows CPU and platform ports to perform
  1052. actions very early after a CPU is released from reset in both the cold and warm
  1053. boot paths. This is done by calling the ``reset_handler()`` function in both
  1054. the BL1 and BL31 images. It in turn calls the platform and CPU specific reset
  1055. handling functions.
  1056. Details for implementing a CPU specific reset handler can be found in
  1057. :ref:`firmware_design_cpu_specific_reset_handling`. Details for implementing a
  1058. platform specific reset handler can be found in the :ref:`Porting Guide` (see
  1059. the``plat_reset_handler()`` function).
  1060. When adding functionality to a reset handler, keep in mind that if a different
  1061. reset handling behavior is required between the first and the subsequent
  1062. invocations of the reset handling code, this should be detected at runtime.
  1063. In other words, the reset handler should be able to detect whether an action has
  1064. already been performed and act as appropriate. Possible courses of actions are,
  1065. e.g. skip the action the second time, or undo/redo it.
  1066. .. _configuring-secure-interrupts:
  1067. Configuring secure interrupts
  1068. -----------------------------
  1069. The GIC driver is responsible for performing initial configuration of secure
  1070. interrupts on the platform. To this end, the platform is expected to provide the
  1071. GIC driver (either GICv2 or GICv3, as selected by the platform) with the
  1072. interrupt configuration during the driver initialisation.
  1073. Secure interrupt configuration are specified in an array of secure interrupt
  1074. properties. In this scheme, in both GICv2 and GICv3 driver data structures, the
  1075. ``interrupt_props`` member points to an array of interrupt properties. Each
  1076. element of the array specifies the interrupt number and its attributes
  1077. (priority, group, configuration). Each element of the array shall be populated
  1078. by the macro ``INTR_PROP_DESC()``. The macro takes the following arguments:
  1079. - 13-bit interrupt number,
  1080. - 8-bit interrupt priority,
  1081. - Interrupt type (one of ``INTR_TYPE_EL3``, ``INTR_TYPE_S_EL1``,
  1082. ``INTR_TYPE_NS``),
  1083. - Interrupt configuration (either ``GIC_INTR_CFG_LEVEL`` or
  1084. ``GIC_INTR_CFG_EDGE``).
  1085. .. _firmware_design_cpu_ops_fwk:
  1086. CPU specific operations framework
  1087. ---------------------------------
  1088. Certain aspects of the Armv8-A architecture are implementation defined,
  1089. that is, certain behaviours are not architecturally defined, but must be
  1090. defined and documented by individual processor implementations. TF-A
  1091. implements a framework which categorises the common implementation defined
  1092. behaviours and allows a processor to export its implementation of that
  1093. behaviour. The categories are:
  1094. #. Processor specific reset sequence.
  1095. #. Processor specific power down sequences.
  1096. #. Processor specific register dumping as a part of crash reporting.
  1097. #. Errata status reporting.
  1098. Each of the above categories fulfils a different requirement.
  1099. #. allows any processor specific initialization before the caches and MMU
  1100. are turned on, like implementation of errata workarounds, entry into
  1101. the intra-cluster coherency domain etc.
  1102. #. allows each processor to implement the power down sequence mandated in
  1103. its Technical Reference Manual (TRM).
  1104. #. allows a processor to provide additional information to the developer
  1105. in the event of a crash, for example Cortex-A53 has registers which
  1106. can expose the data cache contents.
  1107. #. allows a processor to define a function that inspects and reports the status
  1108. of all errata workarounds on that processor.
  1109. Please note that only 2. is mandated by the TRM.
  1110. The CPU specific operations framework scales to accommodate a large number of
  1111. different CPUs during power down and reset handling. The platform can specify
  1112. any CPU optimization it wants to enable for each CPU. It can also specify
  1113. the CPU errata workarounds to be applied for each CPU type during reset
  1114. handling by defining CPU errata compile time macros. Details on these macros
  1115. can be found in the :ref:`Arm CPU Specific Build Macros` document.
  1116. The CPU specific operations framework depends on the ``cpu_ops`` structure which
  1117. needs to be exported for each type of CPU in the platform. It is defined in
  1118. ``include/lib/cpus/aarch64/cpu_macros.S`` and has the following fields : ``midr``,
  1119. ``reset_func()``, ``cpu_pwr_down_ops`` (array of power down functions) and
  1120. ``cpu_reg_dump()``.
  1121. The CPU specific files in ``lib/cpus`` export a ``cpu_ops`` data structure with
  1122. suitable handlers for that CPU. For example, ``lib/cpus/aarch64/cortex_a53.S``
  1123. exports the ``cpu_ops`` for Cortex-A53 CPU. According to the platform
  1124. configuration, these CPU specific files must be included in the build by
  1125. the platform makefile. The generic CPU specific operations framework code exists
  1126. in ``lib/cpus/aarch64/cpu_helpers.S``.
  1127. CPU PCS
  1128. ~~~~~~~
  1129. All assembly functions in CPU files are asked to follow a modified version of
  1130. the Procedure Call Standard (PCS) in their internals. This is done to ensure
  1131. calling these functions from outside the file doesn't unexpectedly corrupt
  1132. registers in the very early environment and to help the internals to be easier
  1133. to understand. Please see the :ref:`firmware_design_cpu_errata_implementation`
  1134. for any function specific restrictions.
  1135. +--------------+---------------------------------+
  1136. | register | use |
  1137. +==============+=================================+
  1138. | x0 - x15 | scratch |
  1139. +--------------+---------------------------------+
  1140. | x16, x17 | do not use (used by the linker) |
  1141. +--------------+---------------------------------+
  1142. | x18 | do not use (platform register) |
  1143. +--------------+---------------------------------+
  1144. | x19 - x28 | callee saved |
  1145. +--------------+---------------------------------+
  1146. | x29, x30 | FP, LR |
  1147. +--------------+---------------------------------+
  1148. .. _firmware_design_cpu_specific_reset_handling:
  1149. CPU specific Reset Handling
  1150. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1151. After a reset, the state of the CPU when it calls generic reset handler is:
  1152. MMU turned off, both instruction and data caches turned off, not part
  1153. of any coherency domain and no stack.
  1154. The BL entrypoint code first invokes the ``plat_reset_handler()`` to allow
  1155. the platform to perform any system initialization required and any system
  1156. errata workarounds that needs to be applied. The ``get_cpu_ops_ptr()`` reads
  1157. the current CPU midr, finds the matching ``cpu_ops`` entry in the ``cpu_ops``
  1158. array and returns it. Note that only the part number and implementer fields
  1159. in midr are used to find the matching ``cpu_ops`` entry. The ``reset_func()`` in
  1160. the returned ``cpu_ops`` is then invoked which executes the required reset
  1161. handling for that CPU and also any errata workarounds enabled by the platform.
  1162. It should be defined using the ``cpu_reset_func_{start,end}`` macros and its
  1163. body may only clobber x0 to x14 with x14 being the cpu_rev parameter.
  1164. CPU specific power down sequence
  1165. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1166. During the BL31 initialization sequence, the pointer to the matching ``cpu_ops``
  1167. entry is stored in per-CPU data by ``init_cpu_ops()`` so that it can be quickly
  1168. retrieved during power down sequences.
  1169. Various CPU drivers register handlers to perform power down at certain power
  1170. levels for that specific CPU. The PSCI service, upon receiving a power down
  1171. request, determines the highest power level at which to execute power down
  1172. sequence for a particular CPU. It uses the ``prepare_cpu_pwr_dwn()`` function to
  1173. pick the right power down handler for the requested level. The function
  1174. retrieves ``cpu_ops`` pointer member of per-CPU data, and from that, further
  1175. retrieves ``cpu_pwr_down_ops`` array, and indexes into the required level. If the
  1176. requested power level is higher than what a CPU driver supports, the handler
  1177. registered for highest level is invoked.
  1178. At runtime the platform hooks for power down are invoked by the PSCI service to
  1179. perform platform specific operations during a power down sequence, for example
  1180. turning off CCI coherency during a cluster power down.
  1181. CPU specific register reporting during crash
  1182. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1183. If the crash reporting is enabled in BL31, when a crash occurs, the crash
  1184. reporting framework calls ``do_cpu_reg_dump`` which retrieves the matching
  1185. ``cpu_ops`` using ``get_cpu_ops_ptr()`` function. The ``cpu_reg_dump()`` in
  1186. ``cpu_ops`` is invoked, which then returns the CPU specific register values to
  1187. be reported and a pointer to the ASCII list of register names in a format
  1188. expected by the crash reporting framework.
  1189. .. _firmware_design_cpu_errata_implementation:
  1190. CPU errata implementation
  1191. ~~~~~~~~~~~~~~~~~~~~~~~~~
  1192. Errata workarounds for CPUs supported in TF-A are applied during both cold and
  1193. warm boots, shortly after reset. Individual Errata workarounds are enabled as
  1194. build options. Some errata workarounds have potential run-time implications;
  1195. therefore some are enabled by default, others not. Platform ports shall
  1196. override build options to enable or disable errata as appropriate. The CPU
  1197. drivers take care of applying errata workarounds that are enabled and applicable
  1198. to a given CPU.
  1199. Each erratum has a build flag in ``lib/cpus/cpu-ops.mk`` of the form:
  1200. ``ERRATA_<cpu_num>_<erratum_id>``. It also has a short description in
  1201. :ref:`arm_cpu_macros_errata_workarounds` on when it should apply.
  1202. Errata framework
  1203. ^^^^^^^^^^^^^^^^
  1204. The errata framework is a convention and a small library to allow errata to be
  1205. automatically discovered. It enables compliant errata to be automatically
  1206. applied and reported at runtime (either by status reporting or the errata ABI).
  1207. To write a compliant mitigation for erratum number ``erratum_id`` on a cpu that
  1208. declared itself (with ``declare_cpu_ops``) as ``cpu_name`` one needs 3 things:
  1209. #. A CPU revision checker function: ``check_erratum_<cpu_name>_<erratum_id>``
  1210. It should check whether this erratum applies on this revision of this CPU.
  1211. It will be called with the CPU revision as its first parameter (x0) and
  1212. should return one of ``ERRATA_APPLIES`` or ``ERRATA_NOT_APPLIES``.
  1213. It may only clobber x0 to x4. The rest should be treated as callee-saved.
  1214. #. A workaround function: ``erratum_<cpu_name>_<erratum_id>_wa``
  1215. It should obtain the cpu revision (with ``cpu_get_rev_var``), call its
  1216. revision checker, and perform the mitigation, should the erratum apply.
  1217. It may only clobber x0 to x8. The rest should be treated as callee-saved.
  1218. #. Register itself to the framework
  1219. Do this with
  1220. ``add_erratum_entry <cpu_name>, ERRATUM(<erratum_id>), <errata_flag>``
  1221. where the ``errata_flag`` is the enable flag in ``cpu-ops.mk`` described
  1222. above.
  1223. See the next section on how to do this easily.
  1224. .. note::
  1225. CVEs have the format ``CVE_<year>_<number>``. To fit them in the framework, the
  1226. ``erratum_id`` for the checker and the workaround functions become the
  1227. ``number`` part of its name and the ``ERRATUM(<number>)`` part of the
  1228. registration should instead be ``CVE(<year>, <number>)``. In the extremely
  1229. unlikely scenario where a CVE and an erratum numbers clash, the CVE number
  1230. should be prefixed with a zero.
  1231. Also, their build flag should be ``WORKAROUND_CVE_<year>_<number>``.
  1232. .. note::
  1233. AArch32 uses the legacy convention. The checker function has the format
  1234. ``check_errata_<erratum_id>`` and the workaround has the format
  1235. ``errata_<cpu_number>_<erratum_id>_wa`` where ``cpu_number`` is the shortform
  1236. letter and number name of the CPU.
  1237. For CVEs the ``erratum_id`` also becomes ``cve_<year>_<number>``.
  1238. Errata framework helpers
  1239. ^^^^^^^^^^^^^^^^^^^^^^^^
  1240. Writing these errata involves lots of boilerplate and repetitive code. On
  1241. AArch64 there are helpers to omit most of this. They are located in
  1242. ``include/lib/cpus/aarch64/cpu_macros.S`` and the preferred way to implement
  1243. errata. Please see their comments on how to use them.
  1244. The most common type of erratum workaround, one that just sets a "chicken" bit
  1245. in some arbitrary register, would have an implementation for the Cortex-A77,
  1246. erratum #1925769 like::
  1247. workaround_reset_start cortex_a77, ERRATUM(1925769), ERRATA_A77_1925769
  1248. sysreg_bit_set CORTEX_A77_CPUECTLR_EL1, CORTEX_A77_CPUECTLR_EL1_BIT_8
  1249. workaround_reset_end cortex_a77, ERRATUM(1925769)
  1250. check_erratum_ls cortex_a77, ERRATUM(1925769), CPU_REV(1, 1)
  1251. Status reporting
  1252. ^^^^^^^^^^^^^^^^
  1253. In a debug build of TF-A, on a CPU that comes out of reset, both BL1 and the
  1254. runtime firmware (BL31 in AArch64, and BL32 in AArch32) will invoke a generic
  1255. errata status reporting function. It will read the ``errata_entries`` list of
  1256. that cpu and will report whether each known erratum was applied and, if not,
  1257. whether it should have been.
  1258. Reporting the status of errata workaround is for informational purpose only; it
  1259. has no functional significance.
  1260. Memory layout of BL images
  1261. --------------------------
  1262. Each bootloader image can be divided in 2 parts:
  1263. - the static contents of the image. These are data actually stored in the
  1264. binary on the disk. In the ELF terminology, they are called ``PROGBITS``
  1265. sections;
  1266. - the run-time contents of the image. These are data that don't occupy any
  1267. space in the binary on the disk. The ELF binary just contains some
  1268. metadata indicating where these data will be stored at run-time and the
  1269. corresponding sections need to be allocated and initialized at run-time.
  1270. In the ELF terminology, they are called ``NOBITS`` sections.
  1271. All PROGBITS sections are grouped together at the beginning of the image,
  1272. followed by all NOBITS sections. This is true for all TF-A images and it is
  1273. governed by the linker scripts. This ensures that the raw binary images are
  1274. as small as possible. If a NOBITS section was inserted in between PROGBITS
  1275. sections then the resulting binary file would contain zero bytes in place of
  1276. this NOBITS section, making the image unnecessarily bigger. Smaller images
  1277. allow faster loading from the FIP to the main memory.
  1278. For BL31, a platform can specify an alternate location for NOBITS sections
  1279. (other than immediately following PROGBITS sections) by setting
  1280. ``SEPARATE_NOBITS_REGION`` to 1 and defining ``BL31_NOBITS_BASE`` and
  1281. ``BL31_NOBITS_LIMIT``.
  1282. Linker scripts and symbols
  1283. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  1284. Each bootloader stage image layout is described by its own linker script. The
  1285. linker scripts export some symbols into the program symbol table. Their values
  1286. correspond to particular addresses. TF-A code can refer to these symbols to
  1287. figure out the image memory layout.
  1288. Linker symbols follow the following naming convention in TF-A.
  1289. - ``__<SECTION>_START__``
  1290. Start address of a given section named ``<SECTION>``.
  1291. - ``__<SECTION>_END__``
  1292. End address of a given section named ``<SECTION>``. If there is an alignment
  1293. constraint on the section's end address then ``__<SECTION>_END__`` corresponds
  1294. to the end address of the section's actual contents, rounded up to the right
  1295. boundary. Refer to the value of ``__<SECTION>_UNALIGNED_END__`` to know the
  1296. actual end address of the section's contents.
  1297. - ``__<SECTION>_UNALIGNED_END__``
  1298. End address of a given section named ``<SECTION>`` without any padding or
  1299. rounding up due to some alignment constraint.
  1300. - ``__<SECTION>_SIZE__``
  1301. Size (in bytes) of a given section named ``<SECTION>``. If there is an
  1302. alignment constraint on the section's end address then ``__<SECTION>_SIZE__``
  1303. corresponds to the size of the section's actual contents, rounded up to the
  1304. right boundary. In other words, ``__<SECTION>_SIZE__ = __<SECTION>_END__ - _<SECTION>_START__``. Refer to the value of ``__<SECTION>_UNALIGNED_SIZE__``
  1305. to know the actual size of the section's contents.
  1306. - ``__<SECTION>_UNALIGNED_SIZE__``
  1307. Size (in bytes) of a given section named ``<SECTION>`` without any padding or
  1308. rounding up due to some alignment constraint. In other words,
  1309. ``__<SECTION>_UNALIGNED_SIZE__ = __<SECTION>_UNALIGNED_END__ - __<SECTION>_START__``.
  1310. Some of the linker symbols are mandatory as TF-A code relies on them to be
  1311. defined. They are listed in the following subsections. Some of them must be
  1312. provided for each bootloader stage and some are specific to a given bootloader
  1313. stage.
  1314. The linker scripts define some extra, optional symbols. They are not actually
  1315. used by any code but they help in understanding the bootloader images' memory
  1316. layout as they are easy to spot in the link map files.
  1317. Common linker symbols
  1318. ^^^^^^^^^^^^^^^^^^^^^
  1319. All BL images share the following requirements:
  1320. - The BSS section must be zero-initialised before executing any C code.
  1321. - The coherent memory section (if enabled) must be zero-initialised as well.
  1322. - The MMU setup code needs to know the extents of the coherent and read-only
  1323. memory regions to set the right memory attributes. When
  1324. ``SEPARATE_CODE_AND_RODATA=1``, it needs to know more specifically how the
  1325. read-only memory region is divided between code and data.
  1326. The following linker symbols are defined for this purpose:
  1327. - ``__BSS_START__``
  1328. - ``__BSS_SIZE__``
  1329. - ``__COHERENT_RAM_START__`` Must be aligned on a page-size boundary.
  1330. - ``__COHERENT_RAM_END__`` Must be aligned on a page-size boundary.
  1331. - ``__COHERENT_RAM_UNALIGNED_SIZE__``
  1332. - ``__RO_START__``
  1333. - ``__RO_END__``
  1334. - ``__TEXT_START__``
  1335. - ``__TEXT_END_UNALIGNED__``
  1336. - ``__TEXT_END__``
  1337. - ``__RODATA_START__``
  1338. - ``__RODATA_END_UNALIGNED__``
  1339. - ``__RODATA_END__``
  1340. BL1's linker symbols
  1341. ^^^^^^^^^^^^^^^^^^^^
  1342. BL1 being the ROM image, it has additional requirements. BL1 resides in ROM and
  1343. it is entirely executed in place but it needs some read-write memory for its
  1344. mutable data. Its ``.data`` section (i.e. its allocated read-write data) must be
  1345. relocated from ROM to RAM before executing any C code.
  1346. The following additional linker symbols are defined for BL1:
  1347. - ``__BL1_ROM_END__`` End address of BL1's ROM contents, covering its code
  1348. and ``.data`` section in ROM.
  1349. - ``__DATA_ROM_START__`` Start address of the ``.data`` section in ROM. Must be
  1350. aligned on a 16-byte boundary.
  1351. - ``__DATA_RAM_START__`` Address in RAM where the ``.data`` section should be
  1352. copied over. Must be aligned on a 16-byte boundary.
  1353. - ``__DATA_SIZE__`` Size of the ``.data`` section (in ROM or RAM).
  1354. - ``__BL1_RAM_START__`` Start address of BL1 read-write data.
  1355. - ``__BL1_RAM_END__`` End address of BL1 read-write data.
  1356. How to choose the right base addresses for each bootloader stage image
  1357. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1358. There is currently no support for dynamic image loading in TF-A. This means
  1359. that all bootloader images need to be linked against their ultimate runtime
  1360. locations and the base addresses of each image must be chosen carefully such
  1361. that images don't overlap each other in an undesired way. As the code grows,
  1362. the base addresses might need adjustments to cope with the new memory layout.
  1363. The memory layout is completely specific to the platform and so there is no
  1364. general recipe for choosing the right base addresses for each bootloader image.
  1365. However, there are tools to aid in understanding the memory layout. These are
  1366. the link map files: ``build/<platform>/<build-type>/bl<x>/bl<x>.map``, with ``<x>``
  1367. being the stage bootloader. They provide a detailed view of the memory usage of
  1368. each image. Among other useful information, they provide the end address of
  1369. each image.
  1370. - ``bl1.map`` link map file provides ``__BL1_RAM_END__`` address.
  1371. - ``bl2.map`` link map file provides ``__BL2_END__`` address.
  1372. - ``bl31.map`` link map file provides ``__BL31_END__`` address.
  1373. - ``bl32.map`` link map file provides ``__BL32_END__`` address.
  1374. For each bootloader image, the platform code must provide its start address
  1375. as well as a limit address that it must not overstep. The latter is used in the
  1376. linker scripts to check that the image doesn't grow past that address. If that
  1377. happens, the linker will issue a message similar to the following:
  1378. ::
  1379. aarch64-none-elf-ld: BLx has exceeded its limit.
  1380. Additionally, if the platform memory layout implies some image overlaying like
  1381. on FVP, BL31 and TSP need to know the limit address that their PROGBITS
  1382. sections must not overstep. The platform code must provide those.
  1383. TF-A does not provide any mechanism to verify at boot time that the memory
  1384. to load a new image is free to prevent overwriting a previously loaded image.
  1385. The platform must specify the memory available in the system for all the
  1386. relevant BL images to be loaded.
  1387. For example, in the case of BL1 loading BL2, ``bl1_plat_sec_mem_layout()`` will
  1388. return the region defined by the platform where BL1 intends to load BL2. The
  1389. ``load_image()`` function performs bounds check for the image size based on the
  1390. base and maximum image size provided by the platforms. Platforms must take
  1391. this behaviour into account when defining the base/size for each of the images.
  1392. Memory layout on Arm development platforms
  1393. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1394. The following list describes the memory layout on the Arm development platforms:
  1395. - A 4KB page of shared memory is used for communication between Trusted
  1396. Firmware and the platform's power controller. This is located at the base of
  1397. Trusted SRAM. The amount of Trusted SRAM available to load the bootloader
  1398. images is reduced by the size of the shared memory.
  1399. The shared memory is used to store the CPUs' entrypoint mailbox. On Juno,
  1400. this is also used for the MHU payload when passing messages to and from the
  1401. SCP.
  1402. - Another 4 KB page is reserved for passing memory layout between BL1 and BL2
  1403. and also the dynamic firmware configurations.
  1404. - On FVP, BL1 is originally sitting in the Trusted ROM at address ``0x0``. On
  1405. Juno, BL1 resides in flash memory at address ``0x0BEC0000``. BL1 read-write
  1406. data are relocated to the top of Trusted SRAM at runtime.
  1407. - BL2 is loaded below BL1 RW
  1408. - EL3 Runtime Software, BL31 for AArch64 and BL32 for AArch32 (e.g. SP_MIN),
  1409. is loaded at the top of the Trusted SRAM, such that its NOBITS sections will
  1410. overwrite BL1 R/W data and BL2. This implies that BL1 global variables
  1411. remain valid only until execution reaches the EL3 Runtime Software entry
  1412. point during a cold boot.
  1413. - On Juno, SCP_BL2 is loaded temporarily into the EL3 Runtime Software memory
  1414. region and transferred to the SCP before being overwritten by EL3 Runtime
  1415. Software.
  1416. - BL32 (for AArch64) can be loaded in one of the following locations:
  1417. - Trusted SRAM
  1418. - Trusted DRAM (FVP only)
  1419. - Secure region of DRAM (top 16MB of DRAM configured by the TrustZone
  1420. controller)
  1421. When BL32 (for AArch64) is loaded into Trusted SRAM, it is loaded below
  1422. BL31.
  1423. The location of the BL32 image will result in different memory maps. This is
  1424. illustrated for both FVP and Juno in the following diagrams, using the TSP as
  1425. an example.
  1426. .. note::
  1427. Loading the BL32 image in TZC secured DRAM doesn't change the memory
  1428. layout of the other images in Trusted SRAM.
  1429. CONFIG section in memory layouts shown below contains:
  1430. ::
  1431. +--------------------+
  1432. |bl2_mem_params_descs|
  1433. |--------------------|
  1434. | fw_configs |
  1435. +--------------------+
  1436. ``bl2_mem_params_descs`` contains parameters passed from BL2 to next the
  1437. BL image during boot.
  1438. ``fw_configs`` includes soc_fw_config, tos_fw_config, tb_fw_config and fw_config.
  1439. **FVP with TSP in Trusted SRAM with firmware configs :**
  1440. (These diagrams only cover the AArch64 case)
  1441. ::
  1442. DRAM
  1443. 0xffffffff +----------+
  1444. | EL3 TZC |
  1445. 0xffe00000 |----------| (secure)
  1446. | AP TZC |
  1447. 0xff000000 +----------+
  1448. : :
  1449. 0x82100000 |----------|
  1450. |HW_CONFIG |
  1451. 0x82000000 |----------| (non-secure)
  1452. | |
  1453. 0x80000000 +----------+
  1454. Trusted DRAM
  1455. 0x08000000 +----------+
  1456. |HW_CONFIG |
  1457. 0x07f00000 |----------|
  1458. : :
  1459. | |
  1460. 0x06000000 +----------+
  1461. Trusted SRAM
  1462. 0x04040000 +----------+ loaded by BL2 +----------------+
  1463. | BL1 (rw) | <<<<<<<<<<<<< | |
  1464. |----------| <<<<<<<<<<<<< | BL31 NOBITS |
  1465. | BL2 | <<<<<<<<<<<<< | |
  1466. |----------| <<<<<<<<<<<<< |----------------|
  1467. | | <<<<<<<<<<<<< | BL31 PROGBITS |
  1468. | | <<<<<<<<<<<<< |----------------|
  1469. | | <<<<<<<<<<<<< | BL32 |
  1470. 0x04003000 +----------+ +----------------+
  1471. | CONFIG |
  1472. 0x04001000 +----------+
  1473. | Shared |
  1474. 0x04000000 +----------+
  1475. Trusted ROM
  1476. 0x04000000 +----------+
  1477. | BL1 (ro) |
  1478. 0x00000000 +----------+
  1479. **FVP with TSP in Trusted DRAM with firmware configs (default option):**
  1480. ::
  1481. DRAM
  1482. 0xffffffff +--------------+
  1483. | EL3 TZC |
  1484. 0xffe00000 |--------------| (secure)
  1485. | AP TZC |
  1486. 0xff000000 +--------------+
  1487. : :
  1488. 0x82100000 |--------------|
  1489. | HW_CONFIG |
  1490. 0x82000000 |--------------| (non-secure)
  1491. | |
  1492. 0x80000000 +--------------+
  1493. Trusted DRAM
  1494. 0x08000000 +--------------+
  1495. | HW_CONFIG |
  1496. 0x07f00000 |--------------|
  1497. : :
  1498. | BL32 |
  1499. 0x06000000 +--------------+
  1500. Trusted SRAM
  1501. 0x04040000 +--------------+ loaded by BL2 +----------------+
  1502. | BL1 (rw) | <<<<<<<<<<<<< | |
  1503. |--------------| <<<<<<<<<<<<< | BL31 NOBITS |
  1504. | BL2 | <<<<<<<<<<<<< | |
  1505. |--------------| <<<<<<<<<<<<< |----------------|
  1506. | | <<<<<<<<<<<<< | BL31 PROGBITS |
  1507. | | +----------------+
  1508. 0x04003000 +--------------+
  1509. | CONFIG |
  1510. 0x04001000 +--------------+
  1511. | Shared |
  1512. 0x04000000 +--------------+
  1513. Trusted ROM
  1514. 0x04000000 +--------------+
  1515. | BL1 (ro) |
  1516. 0x00000000 +--------------+
  1517. **FVP with TSP in TZC-Secured DRAM with firmware configs :**
  1518. ::
  1519. DRAM
  1520. 0xffffffff +----------+
  1521. | EL3 TZC |
  1522. 0xffe00000 |----------| (secure)
  1523. | AP TZC |
  1524. | (BL32) |
  1525. 0xff000000 +----------+
  1526. | |
  1527. 0x82100000 |----------|
  1528. |HW_CONFIG |
  1529. 0x82000000 |----------| (non-secure)
  1530. | |
  1531. 0x80000000 +----------+
  1532. Trusted DRAM
  1533. 0x08000000 +----------+
  1534. |HW_CONFIG |
  1535. 0x7f000000 |----------|
  1536. : :
  1537. | |
  1538. 0x06000000 +----------+
  1539. Trusted SRAM
  1540. 0x04040000 +----------+ loaded by BL2 +----------------+
  1541. | BL1 (rw) | <<<<<<<<<<<<< | |
  1542. |----------| <<<<<<<<<<<<< | BL31 NOBITS |
  1543. | BL2 | <<<<<<<<<<<<< | |
  1544. |----------| <<<<<<<<<<<<< |----------------|
  1545. | | <<<<<<<<<<<<< | BL31 PROGBITS |
  1546. | | +----------------+
  1547. 0x04003000 +----------+
  1548. | CONFIG |
  1549. 0x04001000 +----------+
  1550. | Shared |
  1551. 0x04000000 +----------+
  1552. Trusted ROM
  1553. 0x04000000 +----------+
  1554. | BL1 (ro) |
  1555. 0x00000000 +----------+
  1556. **Juno with BL32 in Trusted SRAM :**
  1557. ::
  1558. DRAM
  1559. 0xFFFFFFFF +----------+
  1560. | SCP TZC |
  1561. 0xFFE00000 |----------|
  1562. | EL3 TZC |
  1563. 0xFFC00000 |----------| (secure)
  1564. | AP TZC |
  1565. 0xFF000000 +----------+
  1566. | |
  1567. : : (non-secure)
  1568. | |
  1569. 0x80000000 +----------+
  1570. Flash0
  1571. 0x0C000000 +----------+
  1572. : :
  1573. 0x0BED0000 |----------|
  1574. | BL1 (ro) |
  1575. 0x0BEC0000 |----------|
  1576. : :
  1577. 0x08000000 +----------+ BL31 is loaded
  1578. after SCP_BL2 has
  1579. Trusted SRAM been sent to SCP
  1580. 0x04040000 +----------+ loaded by BL2 +----------------+
  1581. | BL1 (rw) | <<<<<<<<<<<<< | |
  1582. |----------| <<<<<<<<<<<<< | BL31 NOBITS |
  1583. | BL2 | <<<<<<<<<<<<< | |
  1584. |----------| <<<<<<<<<<<<< |----------------|
  1585. | SCP_BL2 | <<<<<<<<<<<<< | BL31 PROGBITS |
  1586. | | <<<<<<<<<<<<< |----------------|
  1587. | | <<<<<<<<<<<<< | BL32 |
  1588. | | +----------------+
  1589. | |
  1590. 0x04001000 +----------+
  1591. | MHU |
  1592. 0x04000000 +----------+
  1593. **Juno with BL32 in TZC-secured DRAM :**
  1594. ::
  1595. DRAM
  1596. 0xFFFFFFFF +----------+
  1597. | SCP TZC |
  1598. 0xFFE00000 |----------|
  1599. | EL3 TZC |
  1600. 0xFFC00000 |----------| (secure)
  1601. | AP TZC |
  1602. | (BL32) |
  1603. 0xFF000000 +----------+
  1604. | |
  1605. : : (non-secure)
  1606. | |
  1607. 0x80000000 +----------+
  1608. Flash0
  1609. 0x0C000000 +----------+
  1610. : :
  1611. 0x0BED0000 |----------|
  1612. | BL1 (ro) |
  1613. 0x0BEC0000 |----------|
  1614. : :
  1615. 0x08000000 +----------+ BL31 is loaded
  1616. after SCP_BL2 has
  1617. Trusted SRAM been sent to SCP
  1618. 0x04040000 +----------+ loaded by BL2 +----------------+
  1619. | BL1 (rw) | <<<<<<<<<<<<< | |
  1620. |----------| <<<<<<<<<<<<< | BL31 NOBITS |
  1621. | BL2 | <<<<<<<<<<<<< | |
  1622. |----------| <<<<<<<<<<<<< |----------------|
  1623. | SCP_BL2 | <<<<<<<<<<<<< | BL31 PROGBITS |
  1624. | | +----------------+
  1625. 0x04001000 +----------+
  1626. | MHU |
  1627. 0x04000000 +----------+
  1628. .. _firmware_design_fip:
  1629. Firmware Image Package (FIP)
  1630. ----------------------------
  1631. Using a Firmware Image Package (FIP) allows for packing bootloader images (and
  1632. potentially other payloads) into a single archive that can be loaded by TF-A
  1633. from non-volatile platform storage. A driver to load images from a FIP has
  1634. been added to the storage layer and allows a package to be read from supported
  1635. platform storage. A tool to create Firmware Image Packages is also provided
  1636. and described below.
  1637. Firmware Image Package layout
  1638. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1639. The FIP layout consists of a table of contents (ToC) followed by payload data.
  1640. The ToC itself has a header followed by one or more table entries. The ToC is
  1641. terminated by an end marker entry, and since the size of the ToC is 0 bytes,
  1642. the offset equals the total size of the FIP file. All ToC entries describe some
  1643. payload data that has been appended to the end of the binary package. With the
  1644. information provided in the ToC entry the corresponding payload data can be
  1645. retrieved.
  1646. ::
  1647. ------------------
  1648. | ToC Header |
  1649. |----------------|
  1650. | ToC Entry 0 |
  1651. |----------------|
  1652. | ToC Entry 1 |
  1653. |----------------|
  1654. | ToC End Marker |
  1655. |----------------|
  1656. | |
  1657. | Data 0 |
  1658. | |
  1659. |----------------|
  1660. | |
  1661. | Data 1 |
  1662. | |
  1663. ------------------
  1664. The ToC header and entry formats are described in the header file
  1665. ``include/tools_share/firmware_image_package.h``. This file is used by both the
  1666. tool and TF-A.
  1667. The ToC header has the following fields:
  1668. ::
  1669. `name`: The name of the ToC. This is currently used to validate the header.
  1670. `serial_number`: A non-zero number provided by the creation tool
  1671. `flags`: Flags associated with this data.
  1672. Bits 0-31: Reserved
  1673. Bits 32-47: Platform defined
  1674. Bits 48-63: Reserved
  1675. A ToC entry has the following fields:
  1676. ::
  1677. `uuid`: All files are referred to by a pre-defined Universally Unique
  1678. IDentifier [UUID] . The UUIDs are defined in
  1679. `include/tools_share/firmware_image_package.h`. The platform translates
  1680. the requested image name into the corresponding UUID when accessing the
  1681. package.
  1682. `offset_address`: The offset address at which the corresponding payload data
  1683. can be found. The offset is calculated from the ToC base address.
  1684. `size`: The size of the corresponding payload data in bytes.
  1685. `flags`: Flags associated with this entry. None are yet defined.
  1686. Firmware Image Package creation tool
  1687. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1688. The FIP creation tool can be used to pack specified images into a binary
  1689. package that can be loaded by TF-A from platform storage. The tool currently
  1690. only supports packing bootloader images. Additional image definitions can be
  1691. added to the tool as required.
  1692. The tool can be found in ``tools/fiptool``.
  1693. Loading from a Firmware Image Package (FIP)
  1694. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1695. The Firmware Image Package (FIP) driver can load images from a binary package on
  1696. non-volatile platform storage. For the Arm development platforms, this is
  1697. currently NOR FLASH.
  1698. Bootloader images are loaded according to the platform policy as specified by
  1699. the function ``plat_get_image_source()``. For the Arm development platforms, this
  1700. means the platform will attempt to load images from a Firmware Image Package
  1701. located at the start of NOR FLASH0.
  1702. The Arm development platforms' policy is to only allow loading of a known set of
  1703. images. The platform policy can be modified to allow additional images.
  1704. Use of coherent memory in TF-A
  1705. ------------------------------
  1706. There might be loss of coherency when physical memory with mismatched
  1707. shareability, cacheability and memory attributes is accessed by multiple CPUs
  1708. (refer to section B2.9 of `Arm ARM`_ for more details). This possibility occurs
  1709. in TF-A during power up/down sequences when coherency, MMU and caches are
  1710. turned on/off incrementally.
  1711. TF-A defines coherent memory as a region of memory with Device nGnRE attributes
  1712. in the translation tables. The translation granule size in TF-A is 4KB. This
  1713. is the smallest possible size of the coherent memory region.
  1714. By default, all data structures which are susceptible to accesses with
  1715. mismatched attributes from various CPUs are allocated in a coherent memory
  1716. region (refer to section 2.1 of :ref:`Porting Guide`). The coherent memory
  1717. region accesses are Outer Shareable, non-cacheable and they can be accessed with
  1718. the Device nGnRE attributes when the MMU is turned on. Hence, at the expense of
  1719. at least an extra page of memory, TF-A is able to work around coherency issues
  1720. due to mismatched memory attributes.
  1721. The alternative to the above approach is to allocate the susceptible data
  1722. structures in Normal WriteBack WriteAllocate Inner shareable memory. This
  1723. approach requires the data structures to be designed so that it is possible to
  1724. work around the issue of mismatched memory attributes by performing software
  1725. cache maintenance on them.
  1726. Disabling the use of coherent memory in TF-A
  1727. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1728. It might be desirable to avoid the cost of allocating coherent memory on
  1729. platforms which are memory constrained. TF-A enables inclusion of coherent
  1730. memory in firmware images through the build flag ``USE_COHERENT_MEM``.
  1731. This flag is enabled by default. It can be disabled to choose the second
  1732. approach described above.
  1733. The below sections analyze the data structures allocated in the coherent memory
  1734. region and the changes required to allocate them in normal memory.
  1735. Coherent memory usage in PSCI implementation
  1736. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1737. The ``psci_non_cpu_pd_nodes`` data structure stores the platform's power domain
  1738. tree information for state management of power domains. By default, this data
  1739. structure is allocated in the coherent memory region in TF-A because it can be
  1740. accessed by multiple CPUs, either with caches enabled or disabled.
  1741. .. code:: c
  1742. typedef struct non_cpu_pwr_domain_node {
  1743. /*
  1744. * Index of the first CPU power domain node level 0 which has this node
  1745. * as its parent.
  1746. */
  1747. unsigned int cpu_start_idx;
  1748. /*
  1749. * Number of CPU power domains which are siblings of the domain indexed
  1750. * by 'cpu_start_idx' i.e. all the domains in the range 'cpu_start_idx
  1751. * -> cpu_start_idx + ncpus' have this node as their parent.
  1752. */
  1753. unsigned int ncpus;
  1754. /*
  1755. * Index of the parent power domain node.
  1756. */
  1757. unsigned int parent_node;
  1758. plat_local_state_t local_state;
  1759. unsigned char level;
  1760. /* For indexing the psci_lock array*/
  1761. unsigned char lock_index;
  1762. } non_cpu_pd_node_t;
  1763. In order to move this data structure to normal memory, the use of each of its
  1764. fields must be analyzed. Fields like ``cpu_start_idx``, ``ncpus``, ``parent_node``
  1765. ``level`` and ``lock_index`` are only written once during cold boot. Hence removing
  1766. them from coherent memory involves only doing a clean and invalidate of the
  1767. cache lines after these fields are written.
  1768. The field ``local_state`` can be concurrently accessed by multiple CPUs in
  1769. different cache states. A Lamport's Bakery lock ``psci_locks`` is used to ensure
  1770. mutual exclusion to this field and a clean and invalidate is needed after it
  1771. is written.
  1772. Bakery lock data
  1773. ~~~~~~~~~~~~~~~~
  1774. The bakery lock data structure ``bakery_lock_t`` is allocated in coherent memory
  1775. and is accessed by multiple CPUs with mismatched attributes. ``bakery_lock_t`` is
  1776. defined as follows:
  1777. .. code:: c
  1778. typedef struct bakery_lock {
  1779. /*
  1780. * The lock_data is a bit-field of 2 members:
  1781. * Bit[0] : choosing. This field is set when the CPU is
  1782. * choosing its bakery number.
  1783. * Bits[1 - 15] : number. This is the bakery number allocated.
  1784. */
  1785. volatile uint16_t lock_data[BAKERY_LOCK_MAX_CPUS];
  1786. } bakery_lock_t;
  1787. It is a characteristic of Lamport's Bakery algorithm that the volatile per-CPU
  1788. fields can be read by all CPUs but only written to by the owning CPU.
  1789. Depending upon the data cache line size, the per-CPU fields of the
  1790. ``bakery_lock_t`` structure for multiple CPUs may exist on a single cache line.
  1791. These per-CPU fields can be read and written during lock contention by multiple
  1792. CPUs with mismatched memory attributes. Since these fields are a part of the
  1793. lock implementation, they do not have access to any other locking primitive to
  1794. safeguard against the resulting coherency issues. As a result, simple software
  1795. cache maintenance is not enough to allocate them in coherent memory. Consider
  1796. the following example.
  1797. CPU0 updates its per-CPU field with data cache enabled. This write updates a
  1798. local cache line which contains a copy of the fields for other CPUs as well. Now
  1799. CPU1 updates its per-CPU field of the ``bakery_lock_t`` structure with data cache
  1800. disabled. CPU1 then issues a DCIVAC operation to invalidate any stale copies of
  1801. its field in any other cache line in the system. This operation will invalidate
  1802. the update made by CPU0 as well.
  1803. To use bakery locks when ``USE_COHERENT_MEM`` is disabled, the lock data structure
  1804. has been redesigned. The changes utilise the characteristic of Lamport's Bakery
  1805. algorithm mentioned earlier. The bakery_lock structure only allocates the memory
  1806. for a single CPU. The macro ``DEFINE_BAKERY_LOCK`` allocates all the bakery locks
  1807. needed for a CPU into a section ``.bakery_lock``. The linker allocates the memory
  1808. for other cores by using the total size allocated for the bakery_lock section
  1809. and multiplying it with (PLATFORM_CORE_COUNT - 1). This enables software to
  1810. perform software cache maintenance on the lock data structure without running
  1811. into coherency issues associated with mismatched attributes.
  1812. The bakery lock data structure ``bakery_info_t`` is defined for use when
  1813. ``USE_COHERENT_MEM`` is disabled as follows:
  1814. .. code:: c
  1815. typedef struct bakery_info {
  1816. /*
  1817. * The lock_data is a bit-field of 2 members:
  1818. * Bit[0] : choosing. This field is set when the CPU is
  1819. * choosing its bakery number.
  1820. * Bits[1 - 15] : number. This is the bakery number allocated.
  1821. */
  1822. volatile uint16_t lock_data;
  1823. } bakery_info_t;
  1824. The ``bakery_info_t`` represents a single per-CPU field of one lock and
  1825. the combination of corresponding ``bakery_info_t`` structures for all CPUs in the
  1826. system represents the complete bakery lock. The view in memory for a system
  1827. with n bakery locks are:
  1828. ::
  1829. .bakery_lock section start
  1830. |----------------|
  1831. | `bakery_info_t`| <-- Lock_0 per-CPU field
  1832. | Lock_0 | for CPU0
  1833. |----------------|
  1834. | `bakery_info_t`| <-- Lock_1 per-CPU field
  1835. | Lock_1 | for CPU0
  1836. |----------------|
  1837. | .... |
  1838. |----------------|
  1839. | `bakery_info_t`| <-- Lock_N per-CPU field
  1840. | Lock_N | for CPU0
  1841. ------------------
  1842. | XXXXX |
  1843. | Padding to |
  1844. | next Cache WB | <--- Calculate PERCPU_BAKERY_LOCK_SIZE, allocate
  1845. | Granule | continuous memory for remaining CPUs.
  1846. ------------------
  1847. | `bakery_info_t`| <-- Lock_0 per-CPU field
  1848. | Lock_0 | for CPU1
  1849. |----------------|
  1850. | `bakery_info_t`| <-- Lock_1 per-CPU field
  1851. | Lock_1 | for CPU1
  1852. |----------------|
  1853. | .... |
  1854. |----------------|
  1855. | `bakery_info_t`| <-- Lock_N per-CPU field
  1856. | Lock_N | for CPU1
  1857. ------------------
  1858. | XXXXX |
  1859. | Padding to |
  1860. | next Cache WB |
  1861. | Granule |
  1862. ------------------
  1863. Consider a system of 2 CPUs with 'N' bakery locks as shown above. For an
  1864. operation on Lock_N, the corresponding ``bakery_info_t`` in both CPU0 and CPU1
  1865. ``.bakery_lock`` section need to be fetched and appropriate cache operations need
  1866. to be performed for each access.
  1867. On Arm Platforms, bakery locks are used in psci (``psci_locks``) and power controller
  1868. driver (``arm_lock``).
  1869. Non Functional Impact of removing coherent memory
  1870. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1871. Removal of the coherent memory region leads to the additional software overhead
  1872. of performing cache maintenance for the affected data structures. However, since
  1873. the memory where the data structures are allocated is cacheable, the overhead is
  1874. mostly mitigated by an increase in performance.
  1875. There is however a performance impact for bakery locks, due to:
  1876. - Additional cache maintenance operations, and
  1877. - Multiple cache line reads for each lock operation, since the bakery locks
  1878. for each CPU are distributed across different cache lines.
  1879. The implementation has been optimized to minimize this additional overhead.
  1880. Measurements indicate that when bakery locks are allocated in Normal memory, the
  1881. minimum latency of acquiring a lock is on an average 3-4 micro seconds whereas
  1882. in Device memory the same is 2 micro seconds. The measurements were done on the
  1883. Juno Arm development platform.
  1884. As mentioned earlier, almost a page of memory can be saved by disabling
  1885. ``USE_COHERENT_MEM``. Each platform needs to consider these trade-offs to decide
  1886. whether coherent memory should be used. If a platform disables
  1887. ``USE_COHERENT_MEM`` and needs to use bakery locks in the porting layer, it can
  1888. optionally define macro ``PLAT_PERCPU_BAKERY_LOCK_SIZE`` (see the
  1889. :ref:`Porting Guide`). Refer to the reference platform code for examples.
  1890. Isolating code and read-only data on separate memory pages
  1891. ----------------------------------------------------------
  1892. In the Armv8-A VMSA, translation table entries include fields that define the
  1893. properties of the target memory region, such as its access permissions. The
  1894. smallest unit of memory that can be addressed by a translation table entry is
  1895. a memory page. Therefore, if software needs to set different permissions on two
  1896. memory regions then it needs to map them using different memory pages.
  1897. The default memory layout for each BL image is as follows:
  1898. ::
  1899. | ... |
  1900. +-------------------+
  1901. | Read-write data |
  1902. +-------------------+ Page boundary
  1903. | <Padding> |
  1904. +-------------------+
  1905. | Exception vectors |
  1906. +-------------------+ 2 KB boundary
  1907. | <Padding> |
  1908. +-------------------+
  1909. | Read-only data |
  1910. +-------------------+
  1911. | Code |
  1912. +-------------------+ BLx_BASE
  1913. .. note::
  1914. The 2KB alignment for the exception vectors is an architectural
  1915. requirement.
  1916. The read-write data start on a new memory page so that they can be mapped with
  1917. read-write permissions, whereas the code and read-only data below are configured
  1918. as read-only.
  1919. However, the read-only data are not aligned on a page boundary. They are
  1920. contiguous to the code. Therefore, the end of the code section and the beginning
  1921. of the read-only data one might share a memory page. This forces both to be
  1922. mapped with the same memory attributes. As the code needs to be executable, this
  1923. means that the read-only data stored on the same memory page as the code are
  1924. executable as well. This could potentially be exploited as part of a security
  1925. attack.
  1926. TF provides the build flag ``SEPARATE_CODE_AND_RODATA`` to isolate the code and
  1927. read-only data on separate memory pages. This in turn allows independent control
  1928. of the access permissions for the code and read-only data. In this case,
  1929. platform code gets a finer-grained view of the image layout and can
  1930. appropriately map the code region as executable and the read-only data as
  1931. execute-never.
  1932. This has an impact on memory footprint, as padding bytes need to be introduced
  1933. between the code and read-only data to ensure the segregation of the two. To
  1934. limit the memory cost, this flag also changes the memory layout such that the
  1935. code and exception vectors are now contiguous, like so:
  1936. ::
  1937. | ... |
  1938. +-------------------+
  1939. | Read-write data |
  1940. +-------------------+ Page boundary
  1941. | <Padding> |
  1942. +-------------------+
  1943. | Read-only data |
  1944. +-------------------+ Page boundary
  1945. | <Padding> |
  1946. +-------------------+
  1947. | Exception vectors |
  1948. +-------------------+ 2 KB boundary
  1949. | <Padding> |
  1950. +-------------------+
  1951. | Code |
  1952. +-------------------+ BLx_BASE
  1953. With this more condensed memory layout, the separation of read-only data will
  1954. add zero or one page to the memory footprint of each BL image. Each platform
  1955. should consider the trade-off between memory footprint and security.
  1956. This build flag is disabled by default, minimising memory footprint. On Arm
  1957. platforms, it is enabled.
  1958. Publish and Subscribe Framework
  1959. -------------------------------
  1960. The Publish and Subscribe Framework allows EL3 components to define and publish
  1961. events, to which other EL3 components can subscribe.
  1962. The following macros are provided by the framework:
  1963. - ``REGISTER_PUBSUB_EVENT(event)``: Defines an event, and takes one argument,
  1964. the event name, which must be a valid C identifier. All calls to
  1965. ``REGISTER_PUBSUB_EVENT`` macro must be placed in the file
  1966. ``pubsub_events.h``.
  1967. - ``PUBLISH_EVENT_ARG(event, arg)``: Publishes a defined event, by iterating
  1968. subscribed handlers and calling them in turn. The handlers will be passed the
  1969. parameter ``arg``. The expected use-case is to broadcast an event.
  1970. - ``PUBLISH_EVENT(event)``: Like ``PUBLISH_EVENT_ARG``, except that the value
  1971. ``NULL`` is passed to subscribed handlers.
  1972. - ``SUBSCRIBE_TO_EVENT(event, handler)``: Registers the ``handler`` to
  1973. subscribe to ``event``. The handler will be executed whenever the ``event``
  1974. is published.
  1975. - ``for_each_subscriber(event, subscriber)``: Iterates through all handlers
  1976. subscribed for ``event``. ``subscriber`` must be a local variable of type
  1977. ``pubsub_cb_t *``, and will point to each subscribed handler in turn during
  1978. iteration. This macro can be used for those patterns that none of the
  1979. ``PUBLISH_EVENT_*()`` macros cover.
  1980. Publishing an event that wasn't defined using ``REGISTER_PUBSUB_EVENT`` will
  1981. result in build error. Subscribing to an undefined event however won't.
  1982. Subscribed handlers must be of type ``pubsub_cb_t``, with following function
  1983. signature:
  1984. .. code:: c
  1985. typedef void* (*pubsub_cb_t)(const void *arg);
  1986. There may be arbitrary number of handlers registered to the same event. The
  1987. order in which subscribed handlers are notified when that event is published is
  1988. not defined. Subscribed handlers may be executed in any order; handlers should
  1989. not assume any relative ordering amongst them.
  1990. Publishing an event on a PE will result in subscribed handlers executing on that
  1991. PE only; it won't cause handlers to execute on a different PE.
  1992. Note that publishing an event on a PE blocks until all the subscribed handlers
  1993. finish executing on the PE.
  1994. TF-A generic code publishes and subscribes to some events within. Platform
  1995. ports are discouraged from subscribing to them. These events may be withdrawn,
  1996. renamed, or have their semantics altered in the future. Platforms may however
  1997. register, publish, and subscribe to platform-specific events.
  1998. Publish and Subscribe Example
  1999. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2000. A publisher that wants to publish event ``foo`` would:
  2001. - Define the event ``foo`` in the ``pubsub_events.h``.
  2002. .. code:: c
  2003. REGISTER_PUBSUB_EVENT(foo);
  2004. - Depending on the nature of event, use one of ``PUBLISH_EVENT_*()`` macros to
  2005. publish the event at the appropriate path and time of execution.
  2006. A subscriber that wants to subscribe to event ``foo`` published above would
  2007. implement:
  2008. .. code:: c
  2009. void *foo_handler(const void *arg)
  2010. {
  2011. void *result;
  2012. /* Do handling ... */
  2013. return result;
  2014. }
  2015. SUBSCRIBE_TO_EVENT(foo, foo_handler);
  2016. Reclaiming the BL31 initialization code
  2017. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2018. A significant amount of the code used for the initialization of BL31 is never
  2019. needed again after boot time. In order to reduce the runtime memory
  2020. footprint, the memory used for this code can be reclaimed after initialization
  2021. has finished and be used for runtime data.
  2022. The build option ``RECLAIM_INIT_CODE`` can be set to mark this boot time code
  2023. with a ``.text.init.*`` attribute which can be filtered and placed suitably
  2024. within the BL image for later reclamation by the platform. The platform can
  2025. specify the filter and the memory region for this init section in BL31 via the
  2026. plat.ld.S linker script. For example, on the FVP, this section is placed
  2027. overlapping the secondary CPU stacks so that after the cold boot is done, this
  2028. memory can be reclaimed for the stacks. The init memory section is initially
  2029. mapped with ``RO``, ``EXECUTE`` attributes. After BL31 initialization has
  2030. completed, the FVP changes the attributes of this section to ``RW``,
  2031. ``EXECUTE_NEVER`` allowing it to be used for runtime data. The memory attributes
  2032. are changed within the ``bl31_plat_runtime_setup`` platform hook. The init
  2033. section section can be reclaimed for any data which is accessed after cold
  2034. boot initialization and it is upto the platform to make the decision.
  2035. .. _firmware_design_pmf:
  2036. Performance Measurement Framework
  2037. ---------------------------------
  2038. The Performance Measurement Framework (PMF) facilitates collection of
  2039. timestamps by registered services and provides interfaces to retrieve them
  2040. from within TF-A. A platform can choose to expose appropriate SMCs to
  2041. retrieve these collected timestamps.
  2042. By default, the global physical counter is used for the timestamp
  2043. value and is read via ``CNTPCT_EL0``. The framework allows to retrieve
  2044. timestamps captured by other CPUs.
  2045. Timestamp identifier format
  2046. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2047. A PMF timestamp is uniquely identified across the system via the
  2048. timestamp ID or ``tid``. The ``tid`` is composed as follows:
  2049. ::
  2050. Bits 0-7: The local timestamp identifier.
  2051. Bits 8-9: Reserved.
  2052. Bits 10-15: The service identifier.
  2053. Bits 16-31: Reserved.
  2054. #. The service identifier. Each PMF service is identified by a
  2055. service name and a service identifier. Both the service name and
  2056. identifier are unique within the system as a whole.
  2057. #. The local timestamp identifier. This identifier is unique within a given
  2058. service.
  2059. Registering a PMF service
  2060. ~~~~~~~~~~~~~~~~~~~~~~~~~
  2061. To register a PMF service, the ``PMF_REGISTER_SERVICE()`` macro from ``pmf.h``
  2062. is used. The arguments required are the service name, the service ID,
  2063. the total number of local timestamps to be captured and a set of flags.
  2064. The ``flags`` field can be specified as a bitwise-OR of the following values:
  2065. ::
  2066. PMF_STORE_ENABLE: The timestamp is stored in memory for later retrieval.
  2067. PMF_DUMP_ENABLE: The timestamp is dumped on the serial console.
  2068. The ``PMF_REGISTER_SERVICE()`` reserves memory to store captured
  2069. timestamps in a PMF specific linker section at build time.
  2070. Additionally, it defines necessary functions to capture and
  2071. retrieve a particular timestamp for the given service at runtime.
  2072. The macro ``PMF_REGISTER_SERVICE()`` only enables capturing PMF timestamps
  2073. from within TF-A. In order to retrieve timestamps from outside of TF-A, the
  2074. ``PMF_REGISTER_SERVICE_SMC()`` macro must be used instead. This macro
  2075. accepts the same set of arguments as the ``PMF_REGISTER_SERVICE()``
  2076. macro but additionally supports retrieving timestamps using SMCs.
  2077. Capturing a timestamp
  2078. ~~~~~~~~~~~~~~~~~~~~~
  2079. PMF timestamps are stored in a per-service timestamp region. On a
  2080. system with multiple CPUs, each timestamp is captured and stored
  2081. in a per-CPU cache line aligned memory region.
  2082. Having registered the service, the ``PMF_CAPTURE_TIMESTAMP()`` macro can be
  2083. used to capture a timestamp at the location where it is used. The macro
  2084. takes the service name, a local timestamp identifier and a flag as arguments.
  2085. The ``flags`` field argument can be zero, or ``PMF_CACHE_MAINT`` which
  2086. instructs PMF to do cache maintenance following the capture. Cache
  2087. maintenance is required if any of the service's timestamps are captured
  2088. with data cache disabled.
  2089. To capture a timestamp in assembly code, the caller should use
  2090. ``pmf_calc_timestamp_addr`` macro (defined in ``pmf_asm_macros.S``) to
  2091. calculate the address of where the timestamp would be stored. The
  2092. caller should then read ``CNTPCT_EL0`` register to obtain the timestamp
  2093. and store it at the determined address for later retrieval.
  2094. Retrieving a timestamp
  2095. ~~~~~~~~~~~~~~~~~~~~~~
  2096. From within TF-A, timestamps for individual CPUs can be retrieved using either
  2097. ``PMF_GET_TIMESTAMP_BY_MPIDR()`` or ``PMF_GET_TIMESTAMP_BY_INDEX()`` macros.
  2098. These macros accept the CPU's MPIDR value, or its ordinal position
  2099. respectively.
  2100. From outside TF-A, timestamps for individual CPUs can be retrieved by calling
  2101. into ``pmf_smc_handler()``.
  2102. ::
  2103. Interface : pmf_smc_handler()
  2104. Argument : unsigned int smc_fid, u_register_t x1,
  2105. u_register_t x2, u_register_t x3,
  2106. u_register_t x4, void *cookie,
  2107. void *handle, u_register_t flags
  2108. Return : uintptr_t
  2109. smc_fid: Holds the SMC identifier which is either `PMF_SMC_GET_TIMESTAMP_32`
  2110. when the caller of the SMC is running in AArch32 mode
  2111. or `PMF_SMC_GET_TIMESTAMP_64` when the caller is running in AArch64 mode.
  2112. x1: Timestamp identifier.
  2113. x2: The `mpidr` of the CPU for which the timestamp has to be retrieved.
  2114. This can be the `mpidr` of a different core to the one initiating
  2115. the SMC. In that case, service specific cache maintenance may be
  2116. required to ensure the updated copy of the timestamp is returned.
  2117. x3: A flags value that is either 0 or `PMF_CACHE_MAINT`. If
  2118. `PMF_CACHE_MAINT` is passed, then the PMF code will perform a
  2119. cache invalidate before reading the timestamp. This ensures
  2120. an updated copy is returned.
  2121. The remaining arguments, ``x4``, ``cookie``, ``handle`` and ``flags`` are unused
  2122. in this implementation.
  2123. PMF code structure
  2124. ~~~~~~~~~~~~~~~~~~
  2125. #. ``pmf_main.c`` consists of core functions that implement service registration,
  2126. initialization, storing, dumping and retrieving timestamps.
  2127. #. ``pmf_smc.c`` contains the SMC handling for registered PMF services.
  2128. #. ``pmf.h`` contains the public interface to Performance Measurement Framework.
  2129. #. ``pmf_asm_macros.S`` consists of macros to facilitate capturing timestamps in
  2130. assembly code.
  2131. #. ``pmf_helpers.h`` is an internal header used by ``pmf.h``.
  2132. Armv8-A Architecture Extensions
  2133. -------------------------------
  2134. TF-A makes use of Armv8-A Architecture Extensions where applicable. This
  2135. section lists the usage of Architecture Extensions, and build flags
  2136. controlling them.
  2137. Build options
  2138. ~~~~~~~~~~~~~
  2139. ``ARM_ARCH_MAJOR`` and ``ARM_ARCH_MINOR``
  2140. These build options serve dual purpose
  2141. - Determine the architecture extension support in TF-A build: All the mandatory
  2142. architectural features up to ``ARM_ARCH_MAJOR.ARM_ARCH_MINOR`` are included
  2143. and unconditionally enabled by TF-A build system.
  2144. - ``ARM_ARCH_MAJOR`` and ``ARM_ARCH_MINOR`` are passed to a march.mk build utility
  2145. this will try to come up with an appropriate -march value to be passed to compiler
  2146. by probing the compiler and checking what's supported by the compiler and what's best
  2147. that can be used. But if platform provides a ``MARCH_DIRECTIVE`` then it will used
  2148. directly and compiler probing will be skipped.
  2149. The build system requires that the platform provides a valid numeric value based on
  2150. CPU architecture extension, otherwise it defaults to base Armv8.0-A architecture.
  2151. Subsequent Arm Architecture versions also support extensions which were introduced
  2152. in previous versions.
  2153. .. seealso:: :ref:`Build Options`
  2154. For details on the Architecture Extension and available features, please refer
  2155. to the respective Architecture Extension Supplement.
  2156. Armv8.1-A
  2157. ~~~~~~~~~
  2158. This Architecture Extension is targeted when ``ARM_ARCH_MAJOR`` >= 8, or when
  2159. ``ARM_ARCH_MAJOR`` == 8 and ``ARM_ARCH_MINOR`` >= 1.
  2160. - By default, a load-/store-exclusive instruction pair is used to implement
  2161. spinlocks. The ``USE_SPINLOCK_CAS`` build option when set to 1 selects the
  2162. spinlock implementation using the ARMv8.1-LSE Compare and Swap instruction.
  2163. Notice this instruction is only available in AArch64 execution state, so
  2164. the option is only available to AArch64 builds.
  2165. Armv8.2-A
  2166. ~~~~~~~~~
  2167. - The presence of ARMv8.2-TTCNP is detected at runtime. When it is present, the
  2168. Common not Private (TTBRn_ELx.CnP) bit is enabled to indicate that multiple
  2169. Processing Elements in the same Inner Shareable domain use the same
  2170. translation table entries for a given stage of translation for a particular
  2171. translation regime.
  2172. Armv8.3-A
  2173. ~~~~~~~~~
  2174. - Pointer authentication features of Armv8.3-A are unconditionally enabled in
  2175. the Non-secure world so that lower ELs are allowed to use them without
  2176. causing a trap to EL3.
  2177. In order to enable the Secure world to use it, ``CTX_INCLUDE_PAUTH_REGS``
  2178. must be set to 1. This will add all pointer authentication system registers
  2179. to the context that is saved when doing a world switch.
  2180. The TF-A itself has support for pointer authentication at runtime
  2181. that can be enabled by setting ``BRANCH_PROTECTION`` option to non-zero and
  2182. ``CTX_INCLUDE_PAUTH_REGS`` to 1. This enables pointer authentication in BL1,
  2183. BL2, BL31, and the TSP if it is used.
  2184. Note that Pointer Authentication is enabled for Non-secure world irrespective
  2185. of the value of these build flags if the CPU supports it.
  2186. If ``ARM_ARCH_MAJOR == 8`` and ``ARM_ARCH_MINOR >= 3`` the code footprint of
  2187. enabling PAuth is lower because the compiler will use the optimized
  2188. PAuth instructions rather than the backwards-compatible ones.
  2189. Armv8.5-A
  2190. ~~~~~~~~~
  2191. - Branch Target Identification feature is selected by ``BRANCH_PROTECTION``
  2192. option set to 1. This option defaults to 0.
  2193. - Memory Tagging Extension feature has few variants but not all of them require
  2194. enablement from EL3 to be used at lower EL. e.g. Memory tagging only at
  2195. EL0(MTE) does not require EL3 configuration however memory tagging at
  2196. EL2/EL1 (MTE2) does require EL3 enablement and we need to set this option
  2197. ``ENABLE_FEAT_MTE2`` to 1. This option defaults to 0.
  2198. Armv7-A
  2199. ~~~~~~~
  2200. This Architecture Extension is targeted when ``ARM_ARCH_MAJOR`` == 7.
  2201. There are several Armv7-A extensions available. Obviously the TrustZone
  2202. extension is mandatory to support the TF-A bootloader and runtime services.
  2203. Platform implementing an Armv7-A system can to define from its target
  2204. Cortex-A architecture through ``ARM_CORTEX_A<X> = yes`` in their
  2205. ``platform.mk`` script. For example ``ARM_CORTEX_A15=yes`` for a
  2206. Cortex-A15 target.
  2207. Platform can also set ``ARM_WITH_NEON=yes`` to enable neon support.
  2208. Note that using neon at runtime has constraints on non secure world context.
  2209. TF-A does not yet provide VFP context management.
  2210. Directive ``ARM_CORTEX_A<x>`` and ``ARM_WITH_NEON`` are used to set
  2211. the toolchain target architecture directive.
  2212. Platform may choose to not define straight the toolchain target architecture
  2213. directive by defining ``MARCH_DIRECTIVE``.
  2214. I.e:
  2215. .. code:: make
  2216. MARCH_DIRECTIVE := -march=armv7-a
  2217. Code Structure
  2218. --------------
  2219. TF-A code is logically divided between the three boot loader stages mentioned
  2220. in the previous sections. The code is also divided into the following
  2221. categories (present as directories in the source code):
  2222. - **Platform specific.** Choice of architecture specific code depends upon
  2223. the platform.
  2224. - **Common code.** This is platform and architecture agnostic code.
  2225. - **Library code.** This code comprises of functionality commonly used by all
  2226. other code. The PSCI implementation and other EL3 runtime frameworks reside
  2227. as Library components.
  2228. - **Stage specific.** Code specific to a boot stage.
  2229. - **Drivers.**
  2230. - **Services.** EL3 runtime services (eg: SPD). Specific SPD services
  2231. reside in the ``services/spd`` directory (e.g. ``services/spd/tspd``).
  2232. Each boot loader stage uses code from one or more of the above mentioned
  2233. categories. Based upon the above, the code layout looks like this:
  2234. ::
  2235. Directory Used by BL1? Used by BL2? Used by BL31?
  2236. bl1 Yes No No
  2237. bl2 No Yes No
  2238. bl31 No No Yes
  2239. plat Yes Yes Yes
  2240. drivers Yes No Yes
  2241. common Yes Yes Yes
  2242. lib Yes Yes Yes
  2243. services No No Yes
  2244. The build system provides a non configurable build option IMAGE_BLx for each
  2245. boot loader stage (where x = BL stage). e.g. for BL1 , IMAGE_BL1 will be
  2246. defined by the build system. This enables TF-A to compile certain code only
  2247. for specific boot loader stages
  2248. All assembler files have the ``.S`` extension. The linker source files for each
  2249. boot stage have the extension ``.ld.S``. These are processed by GCC to create the
  2250. linker scripts which have the extension ``.ld``.
  2251. FDTs provide a description of the hardware platform and are used by the Linux
  2252. kernel at boot time. These can be found in the ``fdts`` directory.
  2253. .. rubric:: References
  2254. - `Trusted Board Boot Requirements CLIENT (TBBR-CLIENT) Armv8-A (ARM DEN0006D)`_
  2255. - `PSCI`_
  2256. - `SMC Calling Convention`_
  2257. - :ref:`Interrupt Management Framework`
  2258. --------------
  2259. *Copyright (c) 2013-2024, Arm Limited and Contributors. All rights reserved.*
  2260. .. _SMCCC: https://developer.arm.com/docs/den0028/latest
  2261. .. _PSCI: https://developer.arm.com/documentation/den0022/latest/
  2262. .. _Arm ARM: https://developer.arm.com/docs/ddi0487/latest
  2263. .. _SMC Calling Convention: https://developer.arm.com/docs/den0028/latest
  2264. .. _Trusted Board Boot Requirements CLIENT (TBBR-CLIENT) Armv8-A (ARM DEN0006D): https://developer.arm.com/docs/den0006/latest
  2265. .. _Arm Confidential Compute Architecture (Arm CCA): https://www.arm.com/why-arm/architecture/security-features/arm-confidential-compute-architecture
  2266. .. _AArch64 exception vector table: https://developer.arm.com/documentation/100933/0100/AArch64-exception-vector-table
  2267. .. |Image 1| image:: ../resources/diagrams/rt-svc-descs-layout.png