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