1// SPDX-License-Identifier: GPL-2.0+ OR BSD-3-Clause
2/*
3 * Copyright (C) 2018, STMicroelectronics - All Rights Reserved
4 */
5
6#define LOG_CATEGORY LOGC_ARCH
7
8#include <common.h>
9#include <dm.h>
10#include <image.h>
11#include <init.h>
12#include <lmb.h>
13#include <log.h>
14#include <ram.h>
15#include <asm/global_data.h>
16#include <asm/system.h>
17
18DECLARE_GLOBAL_DATA_PTR;
19
20int dram_init(void)
21{
22	struct ram_info ram;
23	struct udevice *dev;
24	int ret;
25
26	ret = uclass_get_device(UCLASS_RAM, 0, &dev);
27	/* in case there is no RAM driver, retrieve DDR size from DT */
28	if (ret == -ENODEV) {
29		return fdtdec_setup_mem_size_base();
30	} else if (ret) {
31		log_err("RAM init failed: %d\n", ret);
32		return ret;
33	}
34	ret = ram_get_info(dev, &ram);
35	if (ret) {
36		log_debug("Cannot get RAM size: %d\n", ret);
37		return ret;
38	}
39	log_debug("RAM init base=%p, size=%zx\n", (void *)ram.base, ram.size);
40
41	gd->ram_size = ram.size;
42
43	return 0;
44}
45
46phys_addr_t board_get_usable_ram_top(phys_size_t total_size)
47{
48	phys_size_t size;
49	phys_addr_t reg;
50	struct lmb lmb;
51
52	if (!total_size)
53		return gd->ram_top;
54
55	/*
56	 * make sure U-Boot uses address space below 4GB boundaries even
57	 * if the effective available memory is bigger
58	 */
59	gd->ram_top = clamp_val(gd->ram_top, 0, SZ_4G - 1);
60
61	/* found enough not-reserved memory to relocated U-Boot */
62	lmb_init(&lmb);
63	lmb_add(&lmb, gd->ram_base, gd->ram_top - gd->ram_base);
64	boot_fdt_add_mem_rsv_regions(&lmb, (void *)gd->fdt_blob);
65	/* add 8M for reserved memory for display, fdt, gd,... */
66	size = ALIGN(SZ_8M + CONFIG_SYS_MALLOC_LEN + total_size, MMU_SECTION_SIZE),
67	reg = lmb_alloc(&lmb, size, MMU_SECTION_SIZE);
68
69	if (!reg)
70		reg = gd->ram_top - size;
71
72	/* before relocation, mark the U-Boot memory as cacheable by default */
73	if (!(gd->flags & GD_FLG_RELOC))
74		mmu_set_region_dcache_behaviour(reg, size, DCACHE_DEFAULT_OPTION);
75
76	return reg + size;
77}
78