	# DOL loader, relocation engine
	# (c) Nuke www.usbgecko.com Licensed under GPL V2

.text
#include "ppc.h"

.globl dol_relocstart
dol_relocstart:			

		lis	r3, 0x9350	#copy of our dol in mem2
		ori	r3, r3, 0x0000
		mr	r28, r3
		mr	r29, r3
		li	r30, 0
		mr	r31, r3

text_section:				
		lwz	r11, 0x90(r28)
		cmpwi	cr7, r11, 0
		beq	cr7, textsect_loop
		lwz	r0, 0(r28)
		mtctr	r11
		lwz	r10, 0x48(r28)
		li	r11, 0
		add	r9, r0, r29

do_text:				
		lbz	r0, 0(r9)
		addi	r9, r9, 1
		stbx	r0, r10, r11
		addi	r11, r11, 1
		bdnz	do_text
		lwz	r3, 0x48(r28)
		lwz	r4, 0x90(r28)
		bl	flush_cache

textsect_loop:				
		cmpwi	cr7, r30, 6
		addi	r28, r28, 4
		addi	r30, r30, 1
		bne	cr7, text_section
		
		li	r28, 0
data_section:				
		lwz	r11, 0xAC(r31)
		cmpwi	cr7, r11, 0
		beq	cr7, datasect_loop
		lwz	r0, 0x1C(r31)
		mtctr	r11
		lwz	r10, 0x64(r31)
		li	r11, 0
		add	r9, r0, r29

do_data:				
		lbz	r0, 0(r9)
		addi	r9, r9, 1
		stbx	r0, r10, r11
		addi	r11, r11, 1
		bdnz	do_data
		lwz	r3, 0x64(r31)
		lwz	r4, 0xAC(r31)
		bl	flush_cache

datasect_loop:				
		cmpwi	cr7, r28, 0xA
		addi	r31, r31, 4
		addi	r28, r28, 1
		bne	cr7, data_section
		lwz	r4, 0xDC(r29)
		lwz	r3, 0xD8(r29)
		cmpwi	cr7, r4, 0
		beq	cr7, nobss
		mtctr	r4
		li	r9, 0

clearbss:				
		li	r0, 0
		stbx	r0, r3, r9
		addi	r9, r9, 1
		bdnz	clearbss
		lwz	r4, 0xDC(r29)
		lwz	r3, 0xD8(r29)

nobss:				
		bl	flush_cache
		bl	disableIRQ
		lwz	r28, 0xE0(r29)		# entrypoint
		mtlr	r28
		blr				# jump there

flush_cache:					
		cmplwi	r4, 0
		blelr
		clrlwi.	r5, r3, 27
		beq	flush1
		addi	r4, r4, 0x20

flush1:				
		addi	r4, r4, 0x1F
		srwi	r4, r4, 5
		mtctr	r4

flush2:				
		dcbf	r0, r3
		addi	r3, r3, 0x20
		bdnz	flush2
		blr

disableIRQ:
		li      r9, 0
		li      r0, 0
		ori     r0, r0, 0x8000
		mr      r3, r9
		mfmsr   r3
		andc    r0, r3, r0
		mtmsr   r0
		blr


