
/*
 * boot.S - bootloader code
 *
 * Copyright (C) 2002 Magnus Damm <damm@opensource.se>
 *
 * This code is released under the terms of GPL.
 */
	
	
#include "../boot_cmds.h"	
#include "board.h"
			
	SELECT_CPU
	.text

	.global boot_start	
boot_start:	
		
boot_loop:		
	mov.l #0x10000, er6

boot_delay:

	jsr uart_rx_check
	bne do_uart

dont_echo:	
	sub.l #1, er6
	bne boot_delay

	jsr pins_led_toggle
	bra boot_loop


address:	
	.long 0x12345678

do_address_set:
	mov.b r0l, r5l

	jsr do_get_u32
	mov.l er0, @address
	
	mov.b r5l, r0l
	jsr uart_tx
	bra dont_echo
	
do_address_get:
	jsr uart_tx
	mov.l @address, er0
	jsr do_put_u32
		
	bra dont_echo

do_run:
	jsr uart_tx
	mov.l @address, er3
	jsr pins_led_off
	jmp @er3
	
do_bad:	
	mov.b #CMD_REPLY_BAD, r0l	
do_hello:		
	jsr uart_tx
	bra dont_echo		

do_uart:		
	
	jsr uart_rx

	mov.b r0l, r0h
	bset #7, r0l
	
	cmp #CMD_HELLO, r0h
	beq do_hello

	cmp #CMD_ADDRESS_GET, r0h
	beq do_address_get

	cmp #CMD_ADDRESS_SET, r0h
	beq do_address_set

	cmp #CMD_RUN, r0h
	beq do_run

	cmp #CMD_READ_8, r0h
	beq do_read_8

	cmp #CMD_READ_16, r0h
	beq do_read_16

	cmp #CMD_READ_32, r0h
	beq do_read_32

	cmp #CMD_WRITE_8, r0h
	beq do_write_8

	cmp #CMD_WRITE_16, r0h
	beq do_write_16

	cmp #CMD_WRITE_32, r0h
	beq do_write_32

	bra do_bad

do_read_8:
	jsr uart_tx
	mov.l @address, er3
	mov.b @er3, r0l
	jsr uart_tx

	bra do_inc_8

do_read_16:
	jsr uart_tx
	mov.l @address, er3
	mov.w @er3, r0
	jsr do_put_u16

	bra do_inc_16		

do_read_32:
	jsr uart_tx
	mov.l @address, er3
	mov.l @er3, er0
	jsr do_put_u32

	bra do_inc_32		

do_write_8:
	mov.b r0l, r5l

	jsr uart_rx
	mov.l @address, er3
	mov.b r0l, @er3

	mov.b r5l, r0l
	jsr uart_tx

do_inc_8:	
	mov.l #1, er0
	bra do_inc

do_write_16:
	mov.b r0l, r5l

	jsr do_get_u16
	mov.l @address, er3
	mov.w r0, @er3
	
	mov.b r5l, r0l
	jsr uart_tx

do_inc_16:	
	mov.l #2, er0
	bra do_inc

do_write_32:
	mov.b r0l, r5l

	jsr do_get_u32
	mov.l @address, er3
	mov.l er0, @er3
	
	mov.b r5l, r0l
	jsr uart_tx

do_inc_32:	
	mov.l #4, er0
	bra do_inc

do_inc:
	mov.l @address, er3
	add.l er0, er3
	mov.l er3, @address
	jmp dont_echo

/* 16-bit and 32-bit output functions */
	
do_get_u32:	
	jsr uart_rx
	mov.l #0, er3
	mov.b r0l, r3h

	shll.l #2, er3
	shll.l #2, er3
	shll.l #2, er3
	shll.l #2, er3

	jsr uart_rx
	mov.b r0l, r3h

	shll.l #2, er3
	shll.l #2, er3
	shll.l #2, er3
	shll.l #2, er3

	jsr uart_rx
	mov.b r0l, r3h

	jsr uart_rx
	mov.b r0l, r3l
	mov.l er3, er0
	rts	

do_get_u16:	
	jsr uart_rx
	mov.l #0, er3
	mov.b r0l, r3h

	jsr uart_rx
	mov.b r0l, r3l
	mov.l er3, er0
	rts	

do_put_u32:	
	mov.l er0, @-er7

	mov.b @er7, r0l 
	jsr uart_tx
	add.l #1, er7

	mov.b @er7, r0l 
	jsr uart_tx
	add.l #1, er7

	mov.b @er7, r0l 
	jsr uart_tx
	add.l #1, er7

	mov.b @er7, r0l 
	jsr uart_tx
	add.l #1, er7
	rts
	
do_put_u16:	
	mov.w r0, @-er7

	mov.b @er7, r0l 
	jsr uart_tx
	add.l #1, er7

	mov.b @er7, r0l 
	jsr uart_tx
	add.l #1, er7
	rts
	
