Use printf for LOG_DEBUG in sitl.
[inav.git] / src / main / common / memory.c
blobc80c541ca55d77a6511d7abd4bfac0ec4f773dc6
1 /*
2 * This file is part of INAV Project.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
6 * You can obtain one at http://mozilla.org/MPL/2.0/.
8 * Alternatively, the contents of this file may be used under the terms
9 * of the GNU General Public License Version 3, as described below:
11 * This file is free software: you may copy, redistribute and/or modify
12 * it under the terms of the GNU General Public License as published by the
13 * Free Software Foundation, either version 3 of the License, or (at your
14 * option) any later version.
16 * This file is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
19 * Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see http://www.gnu.org/licenses/.
25 #include <stdlib.h>
26 #include <stdint.h>
28 #include "platform.h"
30 #include "common/log.h"
31 #include "common/memory.h"
33 #include "drivers/resource.h"
35 #include "fc/runtime_config.h"
37 #if !defined(DYNAMIC_HEAP_SIZE)
38 #define DYNAMIC_HEAP_SIZE (2048)
39 #endif
41 static uint32_t dynHeap[DYNAMIC_HEAP_SIZE / sizeof(uint32_t)];
42 static uint32_t dynHeapFreeWord = 0;
43 static size_t dynHeapUsage[OWNER_TOTAL_COUNT];
45 void * memAllocate(size_t wantedSize, resourceOwner_e owner)
47 void * retPointer = NULL;
48 const size_t wantedWords = (wantedSize + sizeof(uint32_t) - 1) / sizeof(uint32_t);
50 if ((dynHeapFreeWord + wantedWords) <= DYNAMIC_HEAP_SIZE / sizeof(uint32_t)) {
51 // Success
52 retPointer = &dynHeap[dynHeapFreeWord];
53 dynHeapFreeWord += wantedWords;
54 dynHeapUsage[owner] += wantedWords * sizeof(uint32_t);
55 LOG_DEBUG(SYSTEM, "Memory allocated. Free memory = %ld", (unsigned long)memGetAvailableBytes());
57 else {
58 // OOM
59 LOG_ERROR(SYSTEM, "Out of memory");
60 ENABLE_ARMING_FLAG(ARMING_DISABLED_OOM);
63 return retPointer;
66 size_t memGetUsedBytesByOwner(resourceOwner_e owner)
68 return (owner == OWNER_FREE) ? memGetAvailableBytes() : dynHeapUsage[owner];
71 size_t memGetAvailableBytes(void)
73 return (DYNAMIC_HEAP_SIZE / sizeof(uint32_t) - dynHeapFreeWord) * sizeof(uint32_t);