1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2017 Rockchip Electronics Co., Ltd.
4  */
5 
6 #include <common.h>
7 #include <dm.h>
8 #include <ram.h>
9 #include <asm/io.h>
10 #include <asm/arch/sdram_common.h>
11 #include <dm/uclass-internal.h>
12 
13 DECLARE_GLOBAL_DATA_PTR;
14 size_t rockchip_sdram_size(phys_addr_t reg)
15 {
16 	u32 rank, col, bk, cs0_row, cs1_row, bw, row_3_4;
17 	size_t chipsize_mb = 0;
18 	size_t size_mb = 0;
19 	u32 ch;
20 
21 	u32 sys_reg = readl(reg);
22 	u32 ch_num = 1 + ((sys_reg >> SYS_REG_NUM_CH_SHIFT)
23 		       & SYS_REG_NUM_CH_MASK);
24 
25 	debug("%s %x %x\n", __func__, (u32)reg, sys_reg);
26 	for (ch = 0; ch < ch_num; ch++) {
27 		rank = 1 + (sys_reg >> SYS_REG_RANK_SHIFT(ch) &
28 			SYS_REG_RANK_MASK);
29 		col = 9 + (sys_reg >> SYS_REG_COL_SHIFT(ch) & SYS_REG_COL_MASK);
30 		bk = 3 - ((sys_reg >> SYS_REG_BK_SHIFT(ch)) & SYS_REG_BK_MASK);
31 		cs0_row = 13 + (sys_reg >> SYS_REG_CS0_ROW_SHIFT(ch) &
32 				SYS_REG_CS0_ROW_MASK);
33 		cs1_row = 13 + (sys_reg >> SYS_REG_CS1_ROW_SHIFT(ch) &
34 				SYS_REG_CS1_ROW_MASK);
35 		bw = (2 >> ((sys_reg >> SYS_REG_BW_SHIFT(ch)) &
36 			SYS_REG_BW_MASK));
37 		row_3_4 = sys_reg >> SYS_REG_ROW_3_4_SHIFT(ch) &
38 			SYS_REG_ROW_3_4_MASK;
39 
40 		chipsize_mb = (1 << (cs0_row + col + bk + bw - 20));
41 
42 		if (rank > 1)
43 			chipsize_mb += chipsize_mb >> (cs0_row - cs1_row);
44 		if (row_3_4)
45 			chipsize_mb = chipsize_mb * 3 / 4;
46 		size_mb += chipsize_mb;
47 		debug("rank %d col %d bk %d cs0_row %d bw %d row_3_4 %d\n",
48 		      rank, col, bk, cs0_row, bw, row_3_4);
49 	}
50 
51 	return (size_t)size_mb << 20;
52 }
53 
54 int dram_init(void)
55 {
56 	struct ram_info ram;
57 	struct udevice *dev;
58 	int ret;
59 
60 	ret = uclass_get_device(UCLASS_RAM, 0, &dev);
61 	if (ret) {
62 		debug("DRAM init failed: %d\n", ret);
63 		return ret;
64 	}
65 	ret = ram_get_info(dev, &ram);
66 	if (ret) {
67 		debug("Cannot get DRAM size: %d\n", ret);
68 		return ret;
69 	}
70 	gd->ram_size = ram.size;
71 	debug("SDRAM base=%lx, size=%lx\n",
72 	      (unsigned long)ram.base, (unsigned long)ram.size);
73 
74 	return 0;
75 }
76 
77 ulong board_get_usable_ram_top(ulong total_size)
78 {
79 	unsigned long top = CONFIG_SYS_SDRAM_BASE + SDRAM_MAX_SIZE;
80 
81 	return (gd->ram_top > top) ? top : gd->ram_top;
82 }
83