1313#include <stdint.h>
1414#include "src/sys.h"
1515
16+ #if defined(MBEDTLS_THREADING_C )
17+ #include "threading_internal.h"
18+ #endif
19+
1620// Sufficient for signing with TF_PSA_CRYPTO_PQCP_MLDSA_87_ENABLED
1721#define TF_PSA_CRYPTO_MLD_ALLOC_BUFFER_SIZE 123200
1822
@@ -22,26 +26,47 @@ struct tf_psa_crypto_mld_context {
2226 int alloc_offset ; // Negative values indicate allocator errors
2327};
2428
29+ #if defined(MBEDTLS_THREADING_C )
30+ #define TF_PSA_CRYPTO_MLD_ALLOC_LOCK () mbedtls_mutex_lock(&mbedtls_threading_pqcp_buffer_alloc_mutex)
31+ #define TF_PSA_CRYPTO_MLD_ALLOC_UNLOCK () mbedtls_mutex_unlock(&mbedtls_threading_pqcp_buffer_alloc_mutex)
32+ #else /* MBEDTLS_THREADING_C */
33+ #define TF_PSA_CRYPTO_MLD_ALLOC_LOCK () 0
34+ #define TF_PSA_CRYPTO_MLD_ALLOC_UNLOCK () 0
35+ #endif /* MBEDTLS_THREADING_C */
36+
2537#define TF_PSA_CRYPTO_MLD_CUSTOM_ALLOC (v , T , N , context ) \
2638 T *(v) = NULL; \
2739 do { \
2840 /* Verify that the allocation would fit in the buffer by itself, avoiding overflows \
2941 This should be optimized away at compile-time */ \
3042 if ((N) > 0 && (N) <= TF_PSA_CRYPTO_MLD_ALLOC_BUFFER_SIZE / sizeof(T)) { \
43+ if ((context).alloc_offset == 0) { \
44+ (context).alloc_offset = TF_PSA_CRYPTO_MLD_ALLOC_LOCK(); \
45+ } \
3146 if ((context).alloc_offset >= 0) { \
3247 if ((size_t) (context).alloc_offset <= \
3348 TF_PSA_CRYPTO_MLD_ALLOC_BUFFER_SIZE - MLD_ALIGN_UP(sizeof(T) * (N))) { \
3449 (v) = (T *) (tf_psa_crypto_mld_alloc_buffer + (context).alloc_offset); \
3550 (context).alloc_offset += MLD_ALIGN_UP(sizeof(T) * (N)); \
3651 } else { \
37- /* Fail all further allocations in this function -> goto cleanup */ \
52+ /* Fail all further allocations in this function -> goto cleanup
53+ * If we ended up here, that implies (alloc_offset != 0) \
54+ * thus we don't need to call UNLOCK */ \
3855 (context ).alloc_offset = PSA_ERROR_INSUFFICIENT_MEMORY ; \
3956 } \
4057 } \
4158 } \
4259 } while (0 )
4360
44- #define TF_PSA_CRYPTO_MLD_CUSTOM_FREE (v , T , N , context )
61+ #define TF_PSA_CRYPTO_MLD_CUSTOM_FREE (v , T , N , context ) \
62+ do { \
63+ if ((v) != NULL) { \
64+ /* Only unlock after freeing the last allocation */ \
65+ if ((uint8_t *) (v) == tf_psa_crypto_mld_alloc_buffer) { \
66+ (void) TF_PSA_CRYPTO_MLD_ALLOC_UNLOCK(); \
67+ } \
68+ } \
69+ } while (0)
4570
4671#endif /* TF_PSA_CRYPTO_PQCP_BUFFER_ALLOC */
4772
0 commit comments