1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Copyright (c) 2011 The Chromium OS Authors.
4 * (C) Copyright 2002-2006
5 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
6 *
7 * (C) Copyright 2002
8 * Sysgo Real-Time Solutions, GmbH <www.elinos.com>
9 * Marius Groeger <mgroeger@sysgo.de>
10 */
11
12#include <common.h>
13#include <bloblist.h>
14#include <bootstage.h>
15#include <clock_legacy.h>
16#include <console.h>
17#include <cpu.h>
18#include <cpu_func.h>
19#include <cyclic.h>
20#include <display_options.h>
21#include <dm.h>
22#include <env.h>
23#include <env_internal.h>
24#include <event.h>
25#include <fdtdec.h>
26#include <fs.h>
27#include <hang.h>
28#include <i2c.h>
29#include <init.h>
30#include <initcall.h>
31#include <log.h>
32#include <malloc.h>
33#include <mapmem.h>
34#include <os.h>
35#include <post.h>
36#include <relocate.h>
37#include <serial.h>
38#include <spl.h>
39#include <status_led.h>
40#include <sysreset.h>
41#include <timer.h>
42#include <trace.h>
43#include <video.h>
44#include <watchdog.h>
45#include <asm/cache.h>
46#include <asm/global_data.h>
47#include <asm/io.h>
48#include <asm/sections.h>
49#include <dm/root.h>
50#include <linux/errno.h>
51#include <linux/log2.h>
52
53DECLARE_GLOBAL_DATA_PTR;
54
55/*
56 * TODO(sjg@chromium.org): IMO this code should be
57 * refactored to a single function, something like:
58 *
59 * void led_set_state(enum led_colour_t colour, int on);
60 */
61/************************************************************************
62 * Coloured LED functionality
63 ************************************************************************
64 * May be supplied by boards if desired
65 */
66__weak void coloured_LED_init(void) {}
67__weak void red_led_on(void) {}
68__weak void red_led_off(void) {}
69__weak void green_led_on(void) {}
70__weak void green_led_off(void) {}
71__weak void yellow_led_on(void) {}
72__weak void yellow_led_off(void) {}
73__weak void blue_led_on(void) {}
74__weak void blue_led_off(void) {}
75
76/*
77 * Why is gd allocated a register? Prior to reloc it might be better to
78 * just pass it around to each function in this file?
79 *
80 * After reloc one could argue that it is hardly used and doesn't need
81 * to be in a register. Or if it is it should perhaps hold pointers to all
82 * global data for all modules, so that post-reloc we can avoid the massive
83 * literal pool we get on ARM. Or perhaps just encourage each module to use
84 * a structure...
85 */
86
87#if defined(CONFIG_WATCHDOG) || defined(CONFIG_HW_WATCHDOG)
88static int init_func_watchdog_init(void)
89{
90# if defined(CONFIG_HW_WATCHDOG) && \
91	(defined(CONFIG_M68K) || defined(CONFIG_MICROBLAZE) || \
92	defined(CONFIG_SH) || \
93	defined(CONFIG_DESIGNWARE_WATCHDOG) || \
94	defined(CONFIG_IMX_WATCHDOG))
95	hw_watchdog_init();
96	puts("       Watchdog enabled\n");
97# endif
98	schedule();
99
100	return 0;
101}
102
103int init_func_watchdog_reset(void)
104{
105	schedule();
106
107	return 0;
108}
109#endif /* CONFIG_WATCHDOG */
110
111__weak void board_add_ram_info(int use_default)
112{
113	/* please define platform specific board_add_ram_info() */
114}
115
116static int init_baud_rate(void)
117{
118	gd->baudrate = env_get_ulong("baudrate", 10, CONFIG_BAUDRATE);
119	return 0;
120}
121
122static int display_text_info(void)
123{
124#if !defined(CONFIG_SANDBOX) && !defined(CONFIG_EFI_APP)
125	ulong bss_start, bss_end, text_base;
126
127	bss_start = (ulong)__bss_start;
128	bss_end = (ulong)__bss_end;
129
130#ifdef CONFIG_TEXT_BASE
131	text_base = CONFIG_TEXT_BASE;
132#else
133	text_base = CONFIG_SYS_MONITOR_BASE;
134#endif
135
136	debug("U-Boot code: %08lX -> %08lX  BSS: -> %08lX\n",
137	      text_base, bss_start, bss_end);
138#endif
139
140	return 0;
141}
142
143#ifdef CONFIG_SYSRESET
144static int print_resetinfo(void)
145{
146	struct udevice *dev;
147	char status[256];
148	bool status_printed = false;
149	int ret;
150
151	/*
152	 * Not all boards have sysreset drivers available during early
153	 * boot, so don't fail if one can't be found.
154	 */
155	for (ret = uclass_first_device_check(UCLASS_SYSRESET, &dev); dev;
156	     ret = uclass_next_device_check(&dev)) {
157		if (ret) {
158			debug("%s: %s sysreset device (error: %d)\n",
159			      __func__, dev->name, ret);
160			continue;
161		}
162
163		if (!sysreset_get_status(dev, status, sizeof(status))) {
164			printf("%s%s", status_printed ? " " : "", status);
165			status_printed = true;
166		}
167	}
168	if (status_printed)
169		printf("\n");
170
171	return 0;
172}
173#endif
174
175#if defined(CONFIG_DISPLAY_CPUINFO) && CONFIG_IS_ENABLED(CPU)
176static int print_cpuinfo(void)
177{
178	struct udevice *dev;
179	char desc[512];
180	int ret;
181
182	dev = cpu_get_current_dev();
183	if (!dev) {
184		debug("%s: Could not get CPU device\n",
185		      __func__);
186		return -ENODEV;
187	}
188
189	ret = cpu_get_desc(dev, desc, sizeof(desc));
190	if (ret) {
191		debug("%s: Could not get CPU description (err = %d)\n",
192		      dev->name, ret);
193		return ret;
194	}
195
196	printf("CPU:   %s\n", desc);
197
198	return 0;
199}
200#endif
201
202static int announce_dram_init(void)
203{
204	puts("DRAM:  ");
205	return 0;
206}
207
208/*
209 * From input size calculate its nearest rounded unit scale (multiply of 2^10)
210 * and value in calculated unit scale multiplied by 10 (as fractional fixed
211 * point number with one decimal digit), which is human natural format,
212 * same what uses print_size() function for displaying. Mathematically it is:
213 * round_nearest(val * 2^scale) = size * 10; where: 10 <= val < 10240.
214 *
215 * For example for size=87654321 we calculate scale=20 and val=836 which means
216 * that input has natural human format 83.6 M (mega = 2^20).
217 */
218#define compute_size_scale_val(size, scale, val) do { \
219	scale = ilog2(size) / 10 * 10; \
220	val = (10 * size + ((1ULL << scale) >> 1)) >> scale; \
221	if (val == 10240) { val = 10; scale += 10; } \
222} while (0)
223
224/*
225 * Check if the sizes in their natural units written in decimal format with
226 * one fraction number are same.
227 */
228static int sizes_near(unsigned long long size1, unsigned long long size2)
229{
230	unsigned int size1_scale, size1_val, size2_scale, size2_val;
231
232	compute_size_scale_val(size1, size1_scale, size1_val);
233	compute_size_scale_val(size2, size2_scale, size2_val);
234
235	return size1_scale == size2_scale && size1_val == size2_val;
236}
237
238static int show_dram_config(void)
239{
240	unsigned long long size;
241	int i;
242
243	debug("\nRAM Configuration:\n");
244	for (i = size = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
245		size += gd->bd->bi_dram[i].size;
246		debug("Bank #%d: %llx ", i,
247		      (unsigned long long)(gd->bd->bi_dram[i].start));
248#ifdef DEBUG
249		print_size(gd->bd->bi_dram[i].size, "\n");
250#endif
251	}
252	debug("\nDRAM:  ");
253
254	print_size(gd->ram_size, "");
255	if (!sizes_near(gd->ram_size, size)) {
256		printf(" (effective ");
257		print_size(size, ")");
258	}
259	board_add_ram_info(0);
260	putc('\n');
261
262	return 0;
263}
264
265__weak int dram_init_banksize(void)
266{
267	gd->bd->bi_dram[0].start = gd->ram_base;
268	gd->bd->bi_dram[0].size = get_effective_memsize();
269
270	return 0;
271}
272
273#if CONFIG_IS_ENABLED(SYS_I2C_LEGACY)
274static int init_func_i2c(void)
275{
276	puts("I2C:   ");
277	i2c_init_all();
278	puts("ready\n");
279	return 0;
280}
281#endif
282
283static int setup_mon_len(void)
284{
285#if defined(CONFIG_ARCH_NEXELL)
286	gd->mon_len = (ulong)__bss_end - (ulong)__image_copy_start;
287#elif defined(__ARM__) || defined(__MICROBLAZE__)
288	gd->mon_len = (ulong)__bss_end - (ulong)_start;
289#elif defined(CONFIG_SANDBOX) && !defined(__riscv)
290	gd->mon_len = (ulong)_end - (ulong)_init;
291#elif defined(CONFIG_SANDBOX)
292	/* gcc does not provide _init in crti.o on RISC-V */
293	gd->mon_len = 0;
294#elif defined(CONFIG_EFI_APP)
295	gd->mon_len = (ulong)_end - (ulong)_init;
296#elif defined(CONFIG_NIOS2) || defined(CONFIG_XTENSA)
297	gd->mon_len = CONFIG_SYS_MONITOR_LEN;
298#elif defined(CONFIG_SH) || defined(CONFIG_RISCV)
299	gd->mon_len = (ulong)(__bss_end) - (ulong)(_start);
300#elif defined(CONFIG_SYS_MONITOR_BASE)
301	/* TODO: use (ulong)__bss_end - (ulong)__text_start; ? */
302	gd->mon_len = (ulong)__bss_end - CONFIG_SYS_MONITOR_BASE;
303#endif
304	return 0;
305}
306
307static int setup_spl_handoff(void)
308{
309#if CONFIG_IS_ENABLED(HANDOFF)
310	gd->spl_handoff = bloblist_find(BLOBLISTT_U_BOOT_SPL_HANDOFF,
311					sizeof(struct spl_handoff));
312	debug("Found SPL hand-off info %p\n", gd->spl_handoff);
313#endif
314
315	return 0;
316}
317
318__weak int arch_cpu_init(void)
319{
320	return 0;
321}
322
323__weak int mach_cpu_init(void)
324{
325	return 0;
326}
327
328/* Get the top of usable RAM */
329__weak phys_addr_t board_get_usable_ram_top(phys_size_t total_size)
330{
331#if defined(CFG_SYS_SDRAM_BASE) && CFG_SYS_SDRAM_BASE > 0
332	/*
333	 * Detect whether we have so much RAM that it goes past the end of our
334	 * 32-bit address space. If so, clip the usable RAM so it doesn't.
335	 */
336	if (gd->ram_top < CFG_SYS_SDRAM_BASE)
337		/*
338		 * Will wrap back to top of 32-bit space when reservations
339		 * are made.
340		 */
341		return 0;
342#endif
343	return gd->ram_top;
344}
345
346__weak int arch_setup_dest_addr(void)
347{
348	return 0;
349}
350
351static int setup_dest_addr(void)
352{
353	debug("Monitor len: %08lX\n", gd->mon_len);
354	/*
355	 * Ram is setup, size stored in gd !!
356	 */
357	debug("Ram size: %08llX\n", (unsigned long long)gd->ram_size);
358#if CONFIG_VAL(SYS_MEM_TOP_HIDE)
359	/*
360	 * Subtract specified amount of memory to hide so that it won't
361	 * get "touched" at all by U-Boot. By fixing up gd->ram_size
362	 * the Linux kernel should now get passed the now "corrected"
363	 * memory size and won't touch it either. This should work
364	 * for arch/ppc and arch/powerpc. Only Linux board ports in
365	 * arch/powerpc with bootwrapper support, that recalculate the
366	 * memory size from the SDRAM controller setup will have to
367	 * get fixed.
368	 */
369	gd->ram_size -= CONFIG_SYS_MEM_TOP_HIDE;
370#endif
371#ifdef CFG_SYS_SDRAM_BASE
372	gd->ram_base = CFG_SYS_SDRAM_BASE;
373#endif
374	gd->ram_top = gd->ram_base + get_effective_memsize();
375	gd->ram_top = board_get_usable_ram_top(gd->mon_len);
376	gd->relocaddr = gd->ram_top;
377	debug("Ram top: %08llX\n", (unsigned long long)gd->ram_top);
378
379	return arch_setup_dest_addr();
380}
381
382#ifdef CFG_PRAM
383/* reserve protected RAM */
384static int reserve_pram(void)
385{
386	ulong reg;
387
388	reg = env_get_ulong("pram", 10, CFG_PRAM);
389	gd->relocaddr -= (reg << 10);		/* size is in kB */
390	debug("Reserving %ldk for protected RAM at %08lx\n", reg,
391	      gd->relocaddr);
392	return 0;
393}
394#endif /* CFG_PRAM */
395
396/* Round memory pointer down to next 4 kB limit */
397static int reserve_round_4k(void)
398{
399	gd->relocaddr &= ~(4096 - 1);
400	return 0;
401}
402
403__weak int arch_reserve_mmu(void)
404{
405	return 0;
406}
407
408static int reserve_video_from_videoblob(void)
409{
410	if (IS_ENABLED(CONFIG_SPL_VIDEO_HANDOFF) && spl_phase() > PHASE_SPL) {
411		struct video_handoff *ho;
412		int ret = 0;
413
414		ho = bloblist_find(BLOBLISTT_U_BOOT_VIDEO, sizeof(*ho));
415		if (!ho)
416			return log_msg_ret("Missing video bloblist", -ENOENT);
417
418		ret = video_reserve_from_bloblist(ho);
419		if (ret)
420			return log_msg_ret("Invalid Video handoff info", ret);
421
422		/* Sanity check fb from blob is before current relocaddr */
423		if (likely(gd->relocaddr > (unsigned long)ho->fb))
424			gd->relocaddr = ho->fb;
425	}
426
427	return 0;
428}
429
430/*
431 * Check if any bloblist received specifying reserved areas from previous stage and adjust
432 * gd->relocaddr accordingly, so that we start reserving after pre-reserved areas
433 * from previous stage.
434 *
435 * NOTE:
436 * IT is recommended that all bloblists from previous stage are reserved from ram_top
437 * as next stage will simply start reserving further regions after them.
438 */
439static int setup_relocaddr_from_bloblist(void)
440{
441	reserve_video_from_videoblob();
442
443	return 0;
444}
445
446static int reserve_video(void)
447{
448	if (CONFIG_IS_ENABLED(VIDEO)) {
449		ulong addr;
450		int ret;
451
452		addr = gd->relocaddr;
453		ret = video_reserve(&addr);
454		if (ret)
455			return ret;
456		debug("Reserving %luk for video at: %08lx\n",
457		      ((unsigned long)gd->relocaddr - addr) >> 10, addr);
458		gd->relocaddr = addr;
459	}
460
461	return 0;
462}
463
464static int reserve_trace(void)
465{
466#ifdef CONFIG_TRACE
467	gd->relocaddr -= CONFIG_TRACE_BUFFER_SIZE;
468	gd->trace_buff = map_sysmem(gd->relocaddr, CONFIG_TRACE_BUFFER_SIZE);
469	debug("Reserving %luk for trace data at: %08lx\n",
470	      (unsigned long)CONFIG_TRACE_BUFFER_SIZE >> 10, gd->relocaddr);
471#endif
472
473	return 0;
474}
475
476static int reserve_uboot(void)
477{
478	if (!(gd->flags & GD_FLG_SKIP_RELOC)) {
479		/*
480		 * reserve memory for U-Boot code, data & bss
481		 * round down to next 4 kB limit
482		 */
483		gd->relocaddr -= gd->mon_len;
484		gd->relocaddr &= ~(4096 - 1);
485	#if defined(CONFIG_E500) || defined(CONFIG_MIPS)
486		/* round down to next 64 kB limit so that IVPR stays aligned */
487		gd->relocaddr &= ~(65536 - 1);
488	#endif
489
490		debug("Reserving %ldk for U-Boot at: %08lx\n",
491		      gd->mon_len >> 10, gd->relocaddr);
492	}
493
494	gd->start_addr_sp = gd->relocaddr;
495
496	return 0;
497}
498
499/*
500 * reserve after start_addr_sp the requested size and make the stack pointer
501 * 16-byte aligned, this alignment is needed for cast on the reserved memory
502 * ref = x86_64 ABI: https://reviews.llvm.org/D30049: 16 bytes
503 *     = ARMv8 Instruction Set Overview: quad word, 16 bytes
504 */
505static unsigned long reserve_stack_aligned(size_t size)
506{
507	return ALIGN_DOWN(gd->start_addr_sp - size, 16);
508}
509
510#ifdef CONFIG_SYS_NONCACHED_MEMORY
511static int reserve_noncached(void)
512{
513	/*
514	 * The value of gd->start_addr_sp must match the value of malloc_start
515	 * calculated in board_r.c:initr_malloc(), which is passed to
516	 * dlmalloc.c:mem_malloc_init() and then used by
517	 * cache.c:noncached_init()
518	 *
519	 * These calculations must match the code in cache.c:noncached_init()
520	 */
521	gd->start_addr_sp = ALIGN(gd->start_addr_sp, MMU_SECTION_SIZE) -
522		MMU_SECTION_SIZE;
523	gd->start_addr_sp -= ALIGN(CONFIG_SYS_NONCACHED_MEMORY,
524				   MMU_SECTION_SIZE);
525	debug("Reserving %dM for noncached_alloc() at: %08lx\n",
526	      CONFIG_SYS_NONCACHED_MEMORY >> 20, gd->start_addr_sp);
527
528	return 0;
529}
530#endif
531
532/* reserve memory for malloc() area */
533static int reserve_malloc(void)
534{
535	gd->start_addr_sp = reserve_stack_aligned(TOTAL_MALLOC_LEN);
536	debug("Reserving %dk for malloc() at: %08lx\n",
537	      TOTAL_MALLOC_LEN >> 10, gd->start_addr_sp);
538#ifdef CONFIG_SYS_NONCACHED_MEMORY
539	reserve_noncached();
540#endif
541
542	return 0;
543}
544
545/* (permanently) allocate a Board Info struct */
546static int reserve_board(void)
547{
548	if (!gd->bd) {
549		gd->start_addr_sp = reserve_stack_aligned(sizeof(struct bd_info));
550		gd->bd = (struct bd_info *)map_sysmem(gd->start_addr_sp,
551						      sizeof(struct bd_info));
552		memset(gd->bd, '\0', sizeof(struct bd_info));
553		debug("Reserving %zu Bytes for Board Info at: %08lx\n",
554		      sizeof(struct bd_info), gd->start_addr_sp);
555	}
556	return 0;
557}
558
559static int reserve_global_data(void)
560{
561	gd->start_addr_sp = reserve_stack_aligned(sizeof(gd_t));
562	gd->new_gd = (gd_t *)map_sysmem(gd->start_addr_sp, sizeof(gd_t));
563	debug("Reserving %zu Bytes for Global Data at: %08lx\n",
564	      sizeof(gd_t), gd->start_addr_sp);
565	return 0;
566}
567
568static int reserve_fdt(void)
569{
570	if (!IS_ENABLED(CONFIG_OF_EMBED)) {
571		/*
572		 * If the device tree is sitting immediately above our image
573		 * then we must relocate it. If it is embedded in the data
574		 * section, then it will be relocated with other data.
575		 */
576		if (gd->fdt_blob) {
577			gd->fdt_size = ALIGN(fdt_totalsize(gd->fdt_blob), 32);
578
579			gd->start_addr_sp = reserve_stack_aligned(gd->fdt_size);
580			gd->new_fdt = map_sysmem(gd->start_addr_sp, gd->fdt_size);
581			debug("Reserving %lu Bytes for FDT at: %08lx\n",
582			      gd->fdt_size, gd->start_addr_sp);
583		}
584	}
585
586	return 0;
587}
588
589static int reserve_bootstage(void)
590{
591#ifdef CONFIG_BOOTSTAGE
592	int size = bootstage_get_size();
593
594	gd->start_addr_sp = reserve_stack_aligned(size);
595	gd->new_bootstage = map_sysmem(gd->start_addr_sp, size);
596	debug("Reserving %#x Bytes for bootstage at: %08lx\n", size,
597	      gd->start_addr_sp);
598#endif
599
600	return 0;
601}
602
603__weak int arch_reserve_stacks(void)
604{
605	return 0;
606}
607
608static int reserve_stacks(void)
609{
610	/* make stack pointer 16-byte aligned */
611	gd->start_addr_sp = reserve_stack_aligned(16);
612
613	/*
614	 * let the architecture-specific code tailor gd->start_addr_sp and
615	 * gd->irq_sp
616	 */
617	return arch_reserve_stacks();
618}
619
620static int reserve_bloblist(void)
621{
622#ifdef CONFIG_BLOBLIST
623	/* Align to a 4KB boundary for easier reading of addresses */
624	gd->start_addr_sp = ALIGN_DOWN(gd->start_addr_sp -
625				       CONFIG_BLOBLIST_SIZE_RELOC, 0x1000);
626	gd->new_bloblist = map_sysmem(gd->start_addr_sp,
627				      CONFIG_BLOBLIST_SIZE_RELOC);
628#endif
629
630	return 0;
631}
632
633static int display_new_sp(void)
634{
635	debug("New Stack Pointer is: %08lx\n", gd->start_addr_sp);
636
637	return 0;
638}
639
640__weak int arch_setup_bdinfo(void)
641{
642	return 0;
643}
644
645int setup_bdinfo(void)
646{
647	struct bd_info *bd = gd->bd;
648
649	if (IS_ENABLED(CONFIG_SYS_HAS_SRAM)) {
650		bd->bi_sramstart = CONFIG_SYS_SRAM_BASE; /* start of SRAM */
651		bd->bi_sramsize = CONFIG_SYS_SRAM_SIZE;  /* size  of SRAM */
652	}
653
654	return arch_setup_bdinfo();
655}
656
657#ifdef CONFIG_POST
658static int init_post(void)
659{
660	post_bootmode_init();
661	post_run(NULL, POST_ROM | post_bootmode_get(0));
662
663	return 0;
664}
665#endif
666
667static int reloc_fdt(void)
668{
669	if (!IS_ENABLED(CONFIG_OF_EMBED)) {
670		if (gd->new_fdt) {
671			memcpy(gd->new_fdt, gd->fdt_blob,
672			       fdt_totalsize(gd->fdt_blob));
673			gd->fdt_blob = gd->new_fdt;
674		}
675	}
676
677	return 0;
678}
679
680static int reloc_bootstage(void)
681{
682#ifdef CONFIG_BOOTSTAGE
683	if (gd->flags & GD_FLG_SKIP_RELOC)
684		return 0;
685	if (gd->new_bootstage) {
686		int size = bootstage_get_size();
687
688		debug("Copying bootstage from %p to %p, size %x\n",
689		      gd->bootstage, gd->new_bootstage, size);
690		memcpy(gd->new_bootstage, gd->bootstage, size);
691		gd->bootstage = gd->new_bootstage;
692		bootstage_relocate();
693	}
694#endif
695
696	return 0;
697}
698
699static int reloc_bloblist(void)
700{
701#ifdef CONFIG_BLOBLIST
702	/*
703	 * Relocate only if we are supposed to send it
704	 */
705	if ((gd->flags & GD_FLG_SKIP_RELOC) &&
706	    CONFIG_BLOBLIST_SIZE == CONFIG_BLOBLIST_SIZE_RELOC) {
707		debug("Not relocating bloblist\n");
708		return 0;
709	}
710	if (gd->new_bloblist) {
711		debug("Copying bloblist from %p to %p, size %x\n",
712		      gd->bloblist, gd->new_bloblist, gd->bloblist->total_size);
713		return bloblist_reloc(gd->new_bloblist,
714				      CONFIG_BLOBLIST_SIZE_RELOC);
715	}
716#endif
717
718	return 0;
719}
720
721void mcheck_on_ramrelocation(size_t offset);
722static int setup_reloc(void)
723{
724	if (!(gd->flags & GD_FLG_SKIP_RELOC)) {
725#ifdef CONFIG_TEXT_BASE
726#ifdef ARM
727		gd->reloc_off = gd->relocaddr - (unsigned long)__image_copy_start;
728#elif defined(CONFIG_MICROBLAZE)
729		gd->reloc_off = gd->relocaddr - (u32)_start;
730#elif defined(CONFIG_M68K)
731		/*
732		 * On all ColdFire arch cpu, monitor code starts always
733		 * just after the default vector table location, so at 0x400
734		 */
735		gd->reloc_off = gd->relocaddr - (CONFIG_TEXT_BASE + 0x400);
736#elif !defined(CONFIG_SANDBOX)
737		gd->reloc_off = gd->relocaddr - CONFIG_TEXT_BASE;
738#endif
739#endif
740	}
741
742	memcpy(gd->new_gd, (char *)gd, sizeof(gd_t));
743
744	if (gd->flags & GD_FLG_SKIP_RELOC) {
745		debug("Skipping relocation due to flag\n");
746	} else {
747#ifdef MCHECK_HEAP_PROTECTION
748		mcheck_on_ramrelocation(gd->reloc_off);
749#endif
750		debug("Relocation Offset is: %08lx\n", gd->reloc_off);
751		debug("Relocating to %08lx, new gd at %08lx, sp at %08lx\n",
752		      gd->relocaddr, (ulong)map_to_sysmem(gd->new_gd),
753		      gd->start_addr_sp);
754	}
755
756	return 0;
757}
758
759#ifdef CONFIG_OF_BOARD_FIXUP
760static int fix_fdt(void)
761{
762	return board_fix_fdt((void *)gd->fdt_blob);
763}
764#endif
765
766/* ARM calls relocate_code from its crt0.S */
767#if !defined(CONFIG_ARM) && !defined(CONFIG_SANDBOX)
768
769static int jump_to_copy(void)
770{
771	if (gd->flags & GD_FLG_SKIP_RELOC)
772		return 0;
773	/*
774	 * x86 is special, but in a nice way. It uses a trampoline which
775	 * enables the dcache if possible.
776	 *
777	 * For now, other archs use relocate_code(), which is implemented
778	 * similarly for all archs. When we do generic relocation, hopefully
779	 * we can make all archs enable the dcache prior to relocation.
780	 */
781#if defined(CONFIG_X86) || defined(CONFIG_ARC)
782	/*
783	 * SDRAM and console are now initialised. The final stack can now
784	 * be setup in SDRAM. Code execution will continue in Flash, but
785	 * with the stack in SDRAM and Global Data in temporary memory
786	 * (CPU cache)
787	 */
788	arch_setup_gd(gd->new_gd);
789# if CONFIG_IS_ENABLED(X86_64)
790		board_init_f_r_trampoline64(gd->new_gd, gd->start_addr_sp);
791# else
792		board_init_f_r_trampoline(gd->start_addr_sp);
793# endif
794#else
795	relocate_code(gd->start_addr_sp, gd->new_gd, gd->relocaddr);
796#endif
797
798	return 0;
799}
800#endif
801
802/* Record the board_init_f() bootstage (after arch_cpu_init()) */
803static int initf_bootstage(void)
804{
805	bool from_spl = IS_ENABLED(CONFIG_SPL_BOOTSTAGE) &&
806			IS_ENABLED(CONFIG_BOOTSTAGE_STASH);
807	int ret;
808
809	ret = bootstage_init(!from_spl);
810	if (ret)
811		return ret;
812	if (from_spl) {
813		const void *stash = map_sysmem(CONFIG_BOOTSTAGE_STASH_ADDR,
814					       CONFIG_BOOTSTAGE_STASH_SIZE);
815
816		ret = bootstage_unstash(stash, CONFIG_BOOTSTAGE_STASH_SIZE);
817		if (ret && ret != -ENOENT) {
818			debug("Failed to unstash bootstage: err=%d\n", ret);
819			return ret;
820		}
821	}
822
823	bootstage_mark_name(BOOTSTAGE_ID_START_UBOOT_F, "board_init_f");
824
825	return 0;
826}
827
828static int initf_dm(void)
829{
830#if defined(CONFIG_DM) && CONFIG_IS_ENABLED(SYS_MALLOC_F)
831	int ret;
832
833	bootstage_start(BOOTSTAGE_ID_ACCUM_DM_F, "dm_f");
834	ret = dm_init_and_scan(true);
835	bootstage_accum(BOOTSTAGE_ID_ACCUM_DM_F);
836	if (ret)
837		return ret;
838
839	if (IS_ENABLED(CONFIG_TIMER_EARLY)) {
840		ret = dm_timer_init();
841		if (ret)
842			return ret;
843	}
844#endif
845
846	return 0;
847}
848
849/* Architecture-specific memory reservation */
850__weak int reserve_arch(void)
851{
852	return 0;
853}
854
855__weak int checkcpu(void)
856{
857	return 0;
858}
859
860__weak int clear_bss(void)
861{
862	return 0;
863}
864
865static const init_fnc_t init_sequence_f[] = {
866	setup_mon_len,
867#ifdef CONFIG_OF_CONTROL
868	fdtdec_setup,
869#endif
870#ifdef CONFIG_TRACE_EARLY
871	trace_early_init,
872#endif
873	initf_malloc,
874	log_init,
875	initf_bootstage,	/* uses its own timer, so does not need DM */
876	event_init,
877	bloblist_maybe_init,
878	setup_spl_handoff,
879#if defined(CONFIG_CONSOLE_RECORD_INIT_F)
880	console_record_init,
881#endif
882	INITCALL_EVENT(EVT_FSP_INIT_F),
883	arch_cpu_init,		/* basic arch cpu dependent setup */
884	mach_cpu_init,		/* SoC/machine dependent CPU setup */
885	initf_dm,
886#if defined(CONFIG_BOARD_EARLY_INIT_F)
887	board_early_init_f,
888#endif
889#if defined(CONFIG_PPC) || defined(CONFIG_SYS_FSL_CLK) || defined(CONFIG_M68K)
890	/* get CPU and bus clocks according to the environment variable */
891	get_clocks,		/* get CPU and bus clocks (etc.) */
892#endif
893#if !defined(CONFIG_M68K) || (defined(CONFIG_M68K) && !defined(CONFIG_MCFTMR))
894	timer_init,		/* initialize timer */
895#endif
896#if defined(CONFIG_BOARD_POSTCLK_INIT)
897	board_postclk_init,
898#endif
899	env_init,		/* initialize environment */
900	init_baud_rate,		/* initialze baudrate settings */
901	serial_init,		/* serial communications setup */
902	console_init_f,		/* stage 1 init of console */
903	display_options,	/* say that we are here */
904	display_text_info,	/* show debugging info if required */
905	checkcpu,
906#if defined(CONFIG_SYSRESET)
907	print_resetinfo,
908#endif
909#if defined(CONFIG_DISPLAY_CPUINFO)
910	print_cpuinfo,		/* display cpu info (and speed) */
911#endif
912#if defined(CONFIG_DTB_RESELECT)
913	embedded_dtb_select,
914#endif
915#if defined(CONFIG_DISPLAY_BOARDINFO)
916	show_board_info,
917#endif
918	INIT_FUNC_WATCHDOG_INIT
919	INITCALL_EVENT(EVT_MISC_INIT_F),
920	INIT_FUNC_WATCHDOG_RESET
921#if CONFIG_IS_ENABLED(SYS_I2C_LEGACY)
922	init_func_i2c,
923#endif
924	announce_dram_init,
925	dram_init,		/* configure available RAM banks */
926#ifdef CONFIG_POST
927	post_init_f,
928#endif
929	INIT_FUNC_WATCHDOG_RESET
930#if defined(CFG_SYS_DRAM_TEST)
931	testdram,
932#endif /* CFG_SYS_DRAM_TEST */
933	INIT_FUNC_WATCHDOG_RESET
934
935#ifdef CONFIG_POST
936	init_post,
937#endif
938	INIT_FUNC_WATCHDOG_RESET
939	/*
940	 * Now that we have DRAM mapped and working, we can
941	 * relocate the code and continue running from DRAM.
942	 *
943	 * Reserve memory at end of RAM for (top down in that order):
944	 *  - area that won't get touched by U-Boot and Linux (optional)
945	 *  - kernel log buffer
946	 *  - protected RAM
947	 *  - LCD framebuffer
948	 *  - monitor code
949	 *  - board info struct
950	 */
951	setup_dest_addr,
952#ifdef CONFIG_OF_BOARD_FIXUP
953	fix_fdt,
954#endif
955#ifdef CFG_PRAM
956	reserve_pram,
957#endif
958	reserve_round_4k,
959	setup_relocaddr_from_bloblist,
960	arch_reserve_mmu,
961	reserve_video,
962	reserve_trace,
963	reserve_uboot,
964	reserve_malloc,
965	reserve_board,
966	reserve_global_data,
967	reserve_fdt,
968	reserve_bootstage,
969	reserve_bloblist,
970	reserve_arch,
971	reserve_stacks,
972	dram_init_banksize,
973	show_dram_config,
974	INIT_FUNC_WATCHDOG_RESET
975	setup_bdinfo,
976	display_new_sp,
977	INIT_FUNC_WATCHDOG_RESET
978	reloc_fdt,
979	reloc_bootstage,
980	reloc_bloblist,
981	setup_reloc,
982#if defined(CONFIG_X86) || defined(CONFIG_ARC)
983	copy_uboot_to_ram,
984	do_elf_reloc_fixups,
985#endif
986	clear_bss,
987	/*
988	 * Deregister all cyclic functions before relocation, so that
989	 * gd->cyclic_list does not contain any references to pre-relocation
990	 * devices. Drivers will register their cyclic functions anew when the
991	 * devices are probed again.
992	 *
993	 * This should happen as late as possible so that the window where a
994	 * watchdog device is not serviced is as small as possible.
995	 */
996	cyclic_unregister_all,
997#if !defined(CONFIG_ARM) && !defined(CONFIG_SANDBOX)
998	jump_to_copy,
999#endif
1000	NULL,
1001};
1002
1003void board_init_f(ulong boot_flags)
1004{
1005	gd->flags = boot_flags;
1006	gd->have_console = 0;
1007
1008	if (initcall_run_list(init_sequence_f))
1009		hang();
1010
1011#if !defined(CONFIG_ARM) && !defined(CONFIG_SANDBOX) && \
1012		!defined(CONFIG_EFI_APP) && !CONFIG_IS_ENABLED(X86_64) && \
1013		!defined(CONFIG_ARC)
1014	/* NOTREACHED - jump_to_copy() does not return */
1015	hang();
1016#endif
1017}
1018
1019#if defined(CONFIG_X86) || defined(CONFIG_ARC)
1020/*
1021 * For now this code is only used on x86.
1022 *
1023 * init_sequence_f_r is the list of init functions which are run when
1024 * U-Boot is executing from Flash with a semi-limited 'C' environment.
1025 * The following limitations must be considered when implementing an
1026 * '_f_r' function:
1027 *  - 'static' variables are read-only
1028 *  - Global Data (gd->xxx) is read/write
1029 *
1030 * The '_f_r' sequence must, as a minimum, copy U-Boot to RAM (if
1031 * supported).  It _should_, if possible, copy global data to RAM and
1032 * initialise the CPU caches (to speed up the relocation process)
1033 *
1034 * NOTE: At present only x86 uses this route, but it is intended that
1035 * all archs will move to this when generic relocation is implemented.
1036 */
1037static const init_fnc_t init_sequence_f_r[] = {
1038#if !CONFIG_IS_ENABLED(X86_64)
1039	init_cache_f_r,
1040#endif
1041
1042	NULL,
1043};
1044
1045void board_init_f_r(void)
1046{
1047	if (initcall_run_list(init_sequence_f_r))
1048		hang();
1049
1050	/*
1051	 * The pre-relocation drivers may be using memory that has now gone
1052	 * away. Mark serial as unavailable - this will fall back to the debug
1053	 * UART if available.
1054	 *
1055	 * Do the same with log drivers since the memory may not be available.
1056	 */
1057	gd->flags &= ~(GD_FLG_SERIAL_READY | GD_FLG_LOG_READY);
1058#ifdef CONFIG_TIMER
1059	gd->timer = NULL;
1060#endif
1061
1062	/*
1063	 * U-Boot has been copied into SDRAM, the BSS has been cleared etc.
1064	 * Transfer execution from Flash to RAM by calculating the address
1065	 * of the in-RAM copy of board_init_r() and calling it
1066	 */
1067	(board_init_r + gd->reloc_off)((gd_t *)gd, gd->relocaddr);
1068
1069	/* NOTREACHED - board_init_r() does not return */
1070	hang();
1071}
1072#endif /* CONFIG_X86 */
1073