1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright 2018 NXP
4  */
5 
6 #include <common.h>
7 #include <log.h>
8 #include <linux/kernel.h>
9 #include <asm/arch/ddr.h>
10 #include <asm/arch/lpddr4_define.h>
11 #include <asm/arch/sys_proto.h>
12 
ddr_cfg_phy(struct dram_timing_info * dram_timing)13 int ddr_cfg_phy(struct dram_timing_info *dram_timing)
14 {
15 	struct dram_cfg_param *dram_cfg;
16 	struct dram_fsp_msg *fsp_msg;
17 	unsigned int num;
18 	int i = 0;
19 	int j = 0;
20 	int ret;
21 
22 	/* initialize PHY configuration */
23 	dram_cfg = dram_timing->ddrphy_cfg;
24 	num  = dram_timing->ddrphy_cfg_num;
25 	for (i = 0; i < num; i++) {
26 		/* config phy reg */
27 		dwc_ddrphy_apb_wr(dram_cfg->reg, dram_cfg->val);
28 		dram_cfg++;
29 	}
30 
31 	/* load the frequency setpoint message block config */
32 	fsp_msg = dram_timing->fsp_msg;
33 	for (i = 0; i < dram_timing->fsp_msg_num; i++) {
34 		debug("DRAM PHY training for %dMTS\n", fsp_msg->drate);
35 		/* set dram PHY input clocks to desired frequency */
36 		ddrphy_init_set_dfi_clk(fsp_msg->drate);
37 
38 		/* load the dram training firmware image */
39 		dwc_ddrphy_apb_wr(0xd0000, 0x0);
40 		ddr_load_train_firmware(fsp_msg->fw_type);
41 
42 		/* load the frequency set point message block parameter */
43 		dram_cfg = fsp_msg->fsp_cfg;
44 		num = fsp_msg->fsp_cfg_num;
45 		for (j = 0; j < num; j++) {
46 			dwc_ddrphy_apb_wr(dram_cfg->reg, dram_cfg->val);
47 			dram_cfg++;
48 		}
49 
50 		/*
51 		 * -------------------- excute the firmware --------------------
52 		 * Running the firmware is a simply process to taking the
53 		 * PMU out of reset and stall, then the firwmare will be run
54 		 * 1. reset the PMU;
55 		 * 2. begin the excution;
56 		 * 3. wait for the training done;
57 		 * 4. read the message block result.
58 		 * -------------------------------------------------------------
59 		 */
60 		dwc_ddrphy_apb_wr(0xd0000, 0x1);
61 		dwc_ddrphy_apb_wr(0xd0099, 0x9);
62 		dwc_ddrphy_apb_wr(0xd0099, 0x1);
63 		dwc_ddrphy_apb_wr(0xd0099, 0x0);
64 
65 		/* Wait for the training firmware to complete */
66 		ret = wait_ddrphy_training_complete();
67 		if (ret)
68 			return ret;
69 
70 		/* Halt the microcontroller. */
71 		dwc_ddrphy_apb_wr(0xd0099, 0x1);
72 
73 		/* Read the Message Block results */
74 		dwc_ddrphy_apb_wr(0xd0000, 0x0);
75 
76 		ddrphy_init_read_msg_block(fsp_msg->fw_type);
77 
78 		if(fsp_msg->fw_type != FW_2D_IMAGE)
79 			get_trained_CDD(i);
80 
81 		dwc_ddrphy_apb_wr(0xd0000, 0x1);
82 
83 
84 		fsp_msg++;
85 	}
86 
87 	/* Load PHY Init Engine Image */
88 	dram_cfg = dram_timing->ddrphy_pie;
89 	num = dram_timing->ddrphy_pie_num;
90 	for (i = 0; i < num; i++) {
91 		dwc_ddrphy_apb_wr(dram_cfg->reg, dram_cfg->val);
92 		dram_cfg++;
93 	}
94 
95 	/* save the ddr PHY trained CSR in memory for low power use */
96 	ddrphy_trained_csr_save(ddrphy_trained_csr, ddrphy_trained_csr_num);
97 
98 	return 0;
99 }
100