1 /*
2  * (C) Copyright 2016 Rockchip Electronics Co., Ltd
3  *
4  * SPDX-License-Identifier:     GPL-2.0+
5  */
6 
7 #include <common.h>
8 #include <adc.h>
9 #include <asm/io.h>
10 #include <asm/arch/boot_mode.h>
11 
12 void set_back_to_bootrom_dnl_flag(void)
13 {
14 	writel(BOOT_BROM_DOWNLOAD, CONFIG_ROCKCHIP_BOOT_MODE_REG);
15 }
16 
17 /*
18  * detect download key status by adc, most rockchip
19  * based boards use adc sample the download key status,
20  * but there are also some use gpio. So it's better to
21  * make this a weak function that can be override by
22  * some special boards.
23  */
24 #define KEY_DOWN_MIN_VAL	0
25 #define KEY_DOWN_MAX_VAL	30
26 
27 __weak int rockchip_dnl_key_pressed(void)
28 {
29 	unsigned int val;
30 
31 	if (adc_channel_single_shot("saradc", 1, &val)) {
32 		pr_err("%s: adc_channel_single_shot fail!\n", __func__);
33 		return false;
34 	}
35 
36 	if ((val >= KEY_DOWN_MIN_VAL) && (val <= KEY_DOWN_MAX_VAL))
37 		return true;
38 	else
39 		return false;
40 }
41 
42 void rockchip_dnl_mode_check(void)
43 {
44 	if (rockchip_dnl_key_pressed()) {
45 		printf("download key pressed, entering download mode...");
46 		set_back_to_bootrom_dnl_flag();
47 		do_reset(NULL, 0, 0, NULL);
48 	}
49 }
50 
51 int setup_boot_mode(void)
52 {
53 	void *reg = (void *)CONFIG_ROCKCHIP_BOOT_MODE_REG;
54 	int boot_mode = readl(reg);
55 
56 	rockchip_dnl_mode_check();
57 
58 	boot_mode = readl(reg);
59 	debug("%s: boot mode 0x%08x\n", __func__, boot_mode);
60 
61 	/* Clear boot mode */
62 	writel(BOOT_NORMAL, reg);
63 
64 	switch (boot_mode) {
65 	case BOOT_FASTBOOT:
66 		debug("%s: enter fastboot!\n", __func__);
67 		env_set("preboot", "setenv preboot; fastboot usb0");
68 		break;
69 	case BOOT_UMS:
70 		debug("%s: enter UMS!\n", __func__);
71 		env_set("preboot", "setenv preboot; ums mmc 0");
72 		break;
73 	}
74 
75 	return 0;
76 }
77