dwt_prof: Enable write access for DWT counters

prof_hal_init() performs the initialization of the DWT unit.

However, the effective writes to its registers may be protected
by an architecture-defined software locks (LSR, LAR).
The current implementation does not take into account the above
protection mechanism and thus in some platforms the DWT may not
be configured and the counters are not enabled. The result is that
the profiling metrics are all 0.

Add a step to check for software locks implemented and, if positive,
enable the writes into DWT.

Signed-off-by: Nicola Mazzucato <nicola.mazzucato@arm.com>
Change-Id: Ia34c97a872359b8a099c3d8c9b89abd86a58cbc4
diff --git a/profiling/export/platform/tfm_hal_dwt_prof.c b/profiling/export/platform/tfm_hal_dwt_prof.c
index f757fc0..b8d837b 100644
--- a/profiling/export/platform/tfm_hal_dwt_prof.c
+++ b/profiling/export/platform/tfm_hal_dwt_prof.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2023, Arm Limited. All rights reserved.
+ * Copyright (c) 2023-2024, Arm Limited. All rights reserved.
  *
  * SPDX-License-Identifier: BSD-3-Clause
  *
@@ -7,10 +7,28 @@
 
 #include "cmsis.h"
 
+/*
+ * From CoreSight version 3.0 onwards, implementation of the Software lock
+ * mechanism that is controlled by LAR and LSR is deprecated and their
+ * definitions may not be available.
+ * Explicitly define them here.
+ */
+#define DWT_LAR (uint32_t *)(DWT_BASE + 0xFB0UL)
+#define DWT_LSR (uint32_t *)(DWT_BASE + 0xFB4UL)
+
+#define LSR_SLI_Pos  0U /*!< LSR, SLI: Software Lock Implemented */
+#define LSR_SLI_Mask (1UL /* << LSR_SLI_Pos */)
+
 /* Initialize the timer/cycle counter hardware for profiling */
 void prof_hal_init(void)
 {
     DCB->DEMCR       = DCB_DEMCR_TRCENA_Msk; /* Enable DWT. */
+
+    if((*DWT_LSR & LSR_SLI_Mask) > 0) {
+        /* Software Lock is implemented, enable write access to DWT unit */
+        *DWT_LAR = 0xC5ACCE55;
+    }
+
     DWT->CTRL        = DWT_CTRL_CYCCNTENA_Msk;     /* Enable CYCCNT. */
     DWT->CYCCNT      = 0x0;                        /* Reset the processor cycle counter. */
 }