commit 38956611b884bd0a90438bcae7c25979462bbfd4 Author: Gitea Date: Mon Jul 25 22:05:08 2022 +0300 first commit diff --git a/Basic_test/Basic_test.c b/Basic_test/Basic_test.c new file mode 100644 index 0000000..9875b70 --- /dev/null +++ b/Basic_test/Basic_test.c @@ -0,0 +1,39 @@ +#include "Basic_test.h" + +/* +void init_drawing_environment(framebuffer_t *frame, zbuffer_t *z){ + + packet_t *packet = packet_init(16,PACKET_NORMAL); + + // This is our generic qword pointer. + qword_t *q = packet->data; + + // This will setup a default drawing environment. + q = draw_setup_environment(q,0,frame,z); + + // Now reset the primitive origin to 2048-width/2,2048-height/2. + q = draw_primitive_xyoffset(q,0,(2048-320),(2048-256)); + + // Finish setting up the environment. + q = draw_finish(q); + + // Now send the packet, no need to wait since it's the first. + dma_channel_send_normal( DMA_CHANNEL_GIF, packet->data,q - packet->data, 0, 0); + dma_wait_fast(); + + packet_free(packet); + +} +*/ + + + + +int main( int argc, char *argv[] ){ + uint8_t cnt = 0; + for ( ; cnt < 100; cnt++ ) { + //printf("hello world\n"); + }; + return(0); +}; + diff --git a/Basic_test/Basic_test.h b/Basic_test/Basic_test.h new file mode 100644 index 0000000..c3ca49b --- /dev/null +++ b/Basic_test/Basic_test.h @@ -0,0 +1,6 @@ +#ifndef __BASIC_TEST__ +#define __BASIC_TEST__ + +#include "../sps2_basement/core/base/basicTypes.h" + +#endif diff --git a/Basic_test/Basic_test.vpj b/Basic_test/Basic_test.vpj new file mode 100644 index 0000000..9fae0c0 --- /dev/null +++ b/Basic_test/Basic_test.vpj @@ -0,0 +1,485 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Basic_test/Debug/Basic_test.elf b/Basic_test/Debug/Basic_test.elf new file mode 100644 index 0000000..42360fe Binary files /dev/null and b/Basic_test/Debug/Basic_test.elf differ diff --git a/Basic_test/Debug/Basic_test.o b/Basic_test/Debug/Basic_test.o new file mode 100644 index 0000000..41b8475 Binary files /dev/null and b/Basic_test/Debug/Basic_test.o differ diff --git a/Basic_test/Debug/bios.o b/Basic_test/Debug/bios.o new file mode 100644 index 0000000..35adf8c Binary files /dev/null and b/Basic_test/Debug/bios.o differ diff --git a/Basic_test/Debug/crc16.o b/Basic_test/Debug/crc16.o new file mode 100644 index 0000000..e70f063 Binary files /dev/null and b/Basic_test/Debug/crc16.o differ diff --git a/Basic_test/Debug/crc32.o b/Basic_test/Debug/crc32.o new file mode 100644 index 0000000..1157c00 Binary files /dev/null and b/Basic_test/Debug/crc32.o differ diff --git a/Basic_test/Debug/crc7.o b/Basic_test/Debug/crc7.o new file mode 100644 index 0000000..ba245c2 Binary files /dev/null and b/Basic_test/Debug/crc7.o differ diff --git a/Basic_test/Debug/crc8.o b/Basic_test/Debug/crc8.o new file mode 100644 index 0000000..fbd18ff Binary files /dev/null and b/Basic_test/Debug/crc8.o differ diff --git a/Basic_test/Debug/dma.o b/Basic_test/Debug/dma.o new file mode 100644 index 0000000..afedcfb Binary files /dev/null and b/Basic_test/Debug/dma.o differ diff --git a/Basic_test/Debug/dma_packets.o b/Basic_test/Debug/dma_packets.o new file mode 100644 index 0000000..6fa9500 Binary files /dev/null and b/Basic_test/Debug/dma_packets.o differ diff --git a/Basic_test/Debug/ee_sbus.o b/Basic_test/Debug/ee_sbus.o new file mode 100644 index 0000000..5bd8b9a Binary files /dev/null and b/Basic_test/Debug/ee_sbus.o differ diff --git a/Basic_test/Debug/gif.o b/Basic_test/Debug/gif.o new file mode 100644 index 0000000..43407ab Binary files /dev/null and b/Basic_test/Debug/gif.o differ diff --git a/Basic_test/Debug/md5.o b/Basic_test/Debug/md5.o new file mode 100644 index 0000000..627faa9 Binary files /dev/null and b/Basic_test/Debug/md5.o differ diff --git a/Basic_test/Debug/ps2_sbus.o b/Basic_test/Debug/ps2_sbus.o new file mode 100644 index 0000000..ff0cb28 Binary files /dev/null and b/Basic_test/Debug/ps2_sbus.o differ diff --git a/Basic_test/Debug/sha1.o b/Basic_test/Debug/sha1.o new file mode 100644 index 0000000..5e68194 Binary files /dev/null and b/Basic_test/Debug/sha1.o differ diff --git a/Basic_test/Debug/sha256.o b/Basic_test/Debug/sha256.o new file mode 100644 index 0000000..74dd510 Binary files /dev/null and b/Basic_test/Debug/sha256.o differ diff --git a/Basic_test/build b/Basic_test/build new file mode 100644 index 0000000..78e2b39 --- /dev/null +++ b/Basic_test/build @@ -0,0 +1,11 @@ +#! /bin/sh + + +make clean -e "CFG=Debug" +make -e "CFG=Debug" + + +make clean -e "CFG=Release" +make -e "CFG=Release" +/usr/local/ps2dev/ee/bin/ee-strip ./Release/*.elf + diff --git a/Basic_test/makefile b/Basic_test/makefile new file mode 100644 index 0000000..420f209 --- /dev/null +++ b/Basic_test/makefile @@ -0,0 +1,356 @@ +# SlickEdit generated file. Do not edit this file except in designated areas. + +# Make command to use for dependencies +MAKE=make +RM=rm +MKDIR=mkdir + +# -----Begin user-editable area----- + +# -----End user-editable area----- + +# If no configuration is specified, "Debug" will be used +ifndef CFG +CFG=Debug +endif + +# +# Configuration: Debug +# +ifeq "$(CFG)" "Debug" +OUTDIR=Debug +OUTFILE=$(OUTDIR)/Basic_test.elf +CFG_INC= +CFG_LIB= +CFG_OBJ= +COMMON_OBJ=$(OUTDIR)/ee_sbus.o $(OUTDIR)/ps2_sbus.o $(OUTDIR)/bios.o \ + $(OUTDIR)/gif.o $(OUTDIR)/dma.o $(OUTDIR)/dma_packets.o \ + $(OUTDIR)/crc16.o $(OUTDIR)/crc32.o $(OUTDIR)/crc7.o \ + $(OUTDIR)/crc8.o $(OUTDIR)/md5.o $(OUTDIR)/sha1.o $(OUTDIR)/sha256.o \ + $(OUTDIR)/Basic_test.o +OBJ=$(COMMON_OBJ) $(CFG_OBJ) +ALL_OBJ=$(OUTDIR)/ee_sbus.o $(OUTDIR)/ps2_sbus.o $(OUTDIR)/bios.o \ + $(OUTDIR)/gif.o $(OUTDIR)/dma.o $(OUTDIR)/dma_packets.o \ + $(OUTDIR)/crc16.o $(OUTDIR)/crc32.o $(OUTDIR)/crc7.o \ + $(OUTDIR)/crc8.o $(OUTDIR)/md5.o $(OUTDIR)/sha1.o $(OUTDIR)/sha256.o \ + $(OUTDIR)/Basic_test.o + +COMPILE=ee-gcc -c "-D_EE" -g -fshort-double -ffast-math -mhard-float -mips3 -mfp32 -mno-abicalls -G0 -o "$(OUTDIR)/$(*F).o" $(CFG_INC) $< +LINK=ee-gcc -g -o "$(OUTFILE)" $(ALL_OBJ) +COMPILE_ADA=gnat -g -c -o "$(OUTDIR)/$(*F).o" "$<" +COMPILE_ADB=gnat -g -c -o "$(OUTDIR)/$(*F).o" "$<" +COMPILE_F=gfortran -c -g -o "$(OUTDIR)/$(*F).o" "$<" +COMPILE_F90=gfortran -c -g -o "$(OUTDIR)/$(*F).o" "$<" +COMPILE_D=gdc -c -g -o "$(OUTDIR)/$(*F).o" "$<" + +# Pattern rules +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.d + $(COMPILE_D) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.d + $(COMPILE_D) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.d + $(COMPILE_D) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.d + $(COMPILE_D) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.d + $(COMPILE_D) + +$(OUTDIR)/%.o : %.d + $(COMPILE_D) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : %.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.f + $(COMPILE_F) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.f + $(COMPILE_F) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.f + $(COMPILE_F) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.f + $(COMPILE_F) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.f + $(COMPILE_F) + +$(OUTDIR)/%.o : %.f + $(COMPILE_F) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : %.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.c + $(COMPILE) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.c + $(COMPILE) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.c + $(COMPILE) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.c + $(COMPILE) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.c + $(COMPILE) + +$(OUTDIR)/%.o : %.c + $(COMPILE) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.adb + $(COMPILE_ADB) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.adb + $(COMPILE_ADB) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.adb + $(COMPILE_ADB) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.adb + $(COMPILE_ADB) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.adb + $(COMPILE_ADB) + +$(OUTDIR)/%.o : %.adb + $(COMPILE_ADB) + +# Build rules +all: $(OUTFILE) + +$(OUTFILE): $(OUTDIR) $(OBJ) + $(LINK) + +$(OUTDIR): + $(MKDIR) -p "$(OUTDIR)" + +# Rebuild this project +rebuild: cleanall + @$(MAKE) -f "$(strip $(MAKEFILE_LIST))" $(MAKEFLAGS) all + +# Clean this project +clean: + $(RM) -f $(OUTFILE) + $(RM) -f $(OBJ) + +# Clean this project and all dependencies +cleanall: clean +endif + +# +# Configuration: Release +# +ifeq "$(CFG)" "Release" +OUTDIR=Release +OUTFILE=$(OUTDIR)/Basic_test.elf +CFG_INC=-I/usr/local/ps2dev/ps2sdk/ee/include \ + -I/usr/local/ps2dev/ps2sdk/common/include +CFG_LIB=-L/usr/local/ps2dev/ee/ee/lib -L \ + /usr/local/ps2dev/ps2sdk/ee/lib +CFG_OBJ= +COMMON_OBJ=$(OUTDIR)/ee_sbus.o $(OUTDIR)/ps2_sbus.o $(OUTDIR)/bios.o \ + $(OUTDIR)/gif.o $(OUTDIR)/dma.o $(OUTDIR)/dma_packets.o \ + $(OUTDIR)/crc16.o $(OUTDIR)/crc32.o $(OUTDIR)/crc7.o \ + $(OUTDIR)/crc8.o $(OUTDIR)/md5.o $(OUTDIR)/sha1.o $(OUTDIR)/sha256.o \ + $(OUTDIR)/Basic_test.o +OBJ=$(COMMON_OBJ) $(CFG_OBJ) +ALL_OBJ=$(OUTDIR)/ee_sbus.o $(OUTDIR)/ps2_sbus.o $(OUTDIR)/bios.o \ + $(OUTDIR)/gif.o $(OUTDIR)/dma.o $(OUTDIR)/dma_packets.o \ + $(OUTDIR)/crc16.o $(OUTDIR)/crc32.o $(OUTDIR)/crc7.o \ + $(OUTDIR)/crc8.o $(OUTDIR)/md5.o $(OUTDIR)/sha1.o $(OUTDIR)/sha256.o \ + $(OUTDIR)/Basic_test.o -L/usr/local/ps2dev/ee/ee/lib -L \ + /usr/local/ps2dev/ps2sdk/ee/lib + +COMPILE=ee-gcc -c -v "-D_EE" -O2 -G0 -s -o "$(OUTDIR)/$(*F).o" $(CFG_INC) $< +LINK=ee-gcc -v -O2 -lc -lkernel -ldraw -lgraph -lmath3d -lmf -lpacket -ldma -o "$(OUTFILE)" $(ALL_OBJ) +COMPILE_ADA=gnat -O -c -o "$(OUTDIR)/$(*F).o" "$<" +COMPILE_ADB=gnat -O -c -o "$(OUTDIR)/$(*F).o" "$<" +COMPILE_F=gfortran -O -g -o "$(OUTDIR)/$(*F).o" "$<" +COMPILE_F90=gfortran -O -g -o "$(OUTDIR)/$(*F).o" "$<" +COMPILE_D=gdc -c -g -o "$(OUTDIR)/$(*F).o" "$<" + +# Pattern rules +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.d + $(COMPILE_D) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.d + $(COMPILE_D) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.d + $(COMPILE_D) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.d + $(COMPILE_D) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.d + $(COMPILE_D) + +$(OUTDIR)/%.o : %.d + $(COMPILE_D) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : %.f90 + $(COMPILE_F90) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.f + $(COMPILE_F) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.f + $(COMPILE_F) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.f + $(COMPILE_F) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.f + $(COMPILE_F) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.f + $(COMPILE_F) + +$(OUTDIR)/%.o : %.f + $(COMPILE_F) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : %.ada + $(COMPILE_ADA) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.c + $(COMPILE) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.c + $(COMPILE) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.c + $(COMPILE) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.c + $(COMPILE) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.c + $(COMPILE) + +$(OUTDIR)/%.o : %.c + $(COMPILE) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/gs/gif/%.adb + $(COMPILE_ADB) + +$(OUTDIR)/%.o : ../sps2_basement/core/alg/%.adb + $(COMPILE_ADB) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/ee/dmac/%.adb + $(COMPILE_ADB) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbios/%.adb + $(COMPILE_ADB) + +$(OUTDIR)/%.o : ../sps2_basement/hardware/sbus/%.adb + $(COMPILE_ADB) + +$(OUTDIR)/%.o : %.adb + $(COMPILE_ADB) + +# Build rules +all: $(OUTFILE) + +$(OUTFILE): $(OUTDIR) $(OBJ) + $(LINK) + +$(OUTDIR): + $(MKDIR) -p "$(OUTDIR)" + +# Rebuild this project +rebuild: cleanall + @$(MAKE) -f "$(strip $(MAKEFILE_LIST))" $(MAKEFLAGS) all + +# Clean this project +clean: + $(RM) -f $(OUTFILE) + $(RM) -f $(OBJ) + +# Clean this project and all dependencies +cleanall: clean +endif + +# +# include dependencies: +# +$(OUTDIR)/ee_sbus.o: ../sps2_basement/hardware/sbus/ee_sbus.c ../sps2_basement/hardware/sbus/sbus.h ../sps2_basement/hardware/sbus/sbus_regs.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h ../sps2_basement/hardware/ee/ee_regs.h ../sps2_basement/hardware/sbus/iop/iop_regs.h ../sps2_basement/hardware/sbus/sbus_priv.h ../sps2_basement/hardware/sbios/bios.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h ../sps2_basement/hardware/sbios/sifdma.h +$(OUTDIR)/ps2_sbus.o: ../sps2_basement/hardware/sbus/ps2_sbus.c ../sps2_basement/hardware/sbus/sbus.h ../sps2_basement/hardware/sbus/sbus_regs.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h ../sps2_basement/hardware/ee/ee_regs.h ../sps2_basement/hardware/sbus/iop/iop_regs.h ../sps2_basement/hardware/sbus/sbus_priv.h ../sps2_basement/hardware/sbus/sbus_priv.h ../sps2_basement/hardware/sbios/bios.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h ../sps2_basement/hardware/sbios/sifdma.h +$(OUTDIR)/bios.o: ../sps2_basement/hardware/sbios/bios.c ../sps2_basement/hardware/sbios/bios.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h ../sps2_basement/hardware/sbios/sifdma.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h +$(OUTDIR)/gif.o: ../sps2_basement/hardware/gs/gif/gif.c ../sps2_basement/hardware/gs/gif/gif.h ../sps2_basement/hardware/ee/dmac/dma.h +$(OUTDIR)/dma.o: ../sps2_basement/hardware/ee/dmac/dma.c ../sps2_basement/hardware/ee/dmac/dma.h +$(OUTDIR)/dma_packets.o: ../sps2_basement/hardware/ee/dmac/dma_packets.c ../sps2_basement/hardware/ee/dmac/dma_packets.h +$(OUTDIR)/crc16.o: ../sps2_basement/core/alg/crc16.c ../sps2_basement/core/alg/crc.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h +$(OUTDIR)/crc32.o: ../sps2_basement/core/alg/crc32.c ../sps2_basement/core/alg/crc.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h +$(OUTDIR)/crc7.o: ../sps2_basement/core/alg/crc7.c ../sps2_basement/core/alg/crc.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h +$(OUTDIR)/crc8.o: ../sps2_basement/core/alg/crc8.c ../sps2_basement/core/alg/crc.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h +$(OUTDIR)/md5.o: ../sps2_basement/core/alg/md5.c ../sps2_basement/core/alg/md5.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h +$(OUTDIR)/sha1.o: ../sps2_basement/core/alg/sha1.c ../sps2_basement/core/alg/sha1.h +$(OUTDIR)/sha256.o: ../sps2_basement/core/alg/sha256.c ../sps2_basement/core/alg/sha256.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h +$(OUTDIR)/Basic_test.o: Basic_test.c Basic_test.h ../sps2_basement/core/base/basicTypes.h ../sps2_basement/core/base/basicConfig.h ../sps2_basement/core/base/errno.h ../sps2_basement/core/base/assert.h diff --git a/Basic_test/out.txt b/Basic_test/out.txt new file mode 100644 index 0000000..3e51089 --- /dev/null +++ b/Basic_test/out.txt @@ -0,0 +1 @@ +ee-gcc -c "-D_EE" -g -fshort-double -ffast-math -mhard-float -mips3 -mfp32 -mno-abicalls -G0 -o "Debug/crc32.o" ../sps2_basement/core/alg/crc32.c diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/SonyPS2.vpw b/SonyPS2.vpw new file mode 100644 index 0000000..9fc5696 --- /dev/null +++ b/SonyPS2.vpw @@ -0,0 +1,6 @@ + + + + + + diff --git a/SonyPS2.vpwhist b/SonyPS2.vpwhist new file mode 100644 index 0000000..4747bff --- /dev/null +++ b/SonyPS2.vpwhist @@ -0,0 +1,528 @@ +[Global] +CurrentProject=Basic_test\Basic_test.vpj +[ProjectDates] +Basic_test\Basic_test.vpj=20220520154915477 +[ActiveConfig] +Basic_test.vpj=,Debug +Basic_test\Basic_test.vpj=,Debug +[TreeExpansion2] +-@ Basic_test\Basic_test.vpj + - Source Files + + Hardware + - sbus + + iop + - sif + - sbios + - gs + - gif + + ee + - dmac + - vu + - ipu + - fpu + - core + - kernel + - alg + - base + - Header Files + - Hardware + - ee + - sbios + - sbus + - sif + - iop + - include + - core + - base + - alg + + Resource Files + + Bitmaps + + Other Files +scroll:0 +[State] +MONITOR_CONFIGS: 345 +MONITOR_CONFIG: 113 0 0 1920 1080,-1920 0 1920 1080 +SCREEN: 1920 1080 130 130 1484 803 0 0 M 0 0 0 0 1476 943 0 +MDISTATE: 1 +AAAAAwAAAAIAAAAB2gAAAAIAMAAAAAAAAAA1AAAHfwAAA+MAAAAAAAAAAAAAB38AAAQPAAAAAuoAAAaKAAAAAvsAAAAJAAAACQAAAAcAAAAAAAAAAwAAAAgAAAAGAAAABQAAAAQAAAACAAAAAfsAAAAJAAAACQAAAAAAAAAGAAAABQAAAAgAAAAEAAAAAwAAAAcAAAACAAAAAfwAAAClAAAAAJgAMQAwADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABjAG8AcgBlAFwAYgBhAHMAZQBcAGEAcwBzAGUAcgB0AC4AaAAA/////wAA/AAAAK0AAAAAoAAzADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABjAG8AcgBlAFwAYgBhAHMAZQBcAGIAYQBzAGkAYwBDAG8AbgBmAGkAZwAuAGgAAP////8AAPwAAACrAAAAAJ4ANAA6ADoAOgBDADoAXABNAGkAbgBHAFcAXABtAHMAeQBzAFwAMQAuADAAXABoAG8AbQBlAFwAYgB1AGkAbABkAFwAVwBvAHIAawBTAHAAYQBjAGUAXABzAHAAcwAyAF8AYgBhAHMAZQBtAGUAbgB0AFwAYwBvAHIAZQBcAGIAYQBzAGUAXABiAGEAcwBpAGMAVAB5AHAAZQBzAC4AaAAA/////wAA/AAAAKkAAAAAnAA3ADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABoAGEAcgBkAHcAYQByAGUAXABzAGIAaQBvAHMAXABiAGkAbwBzAC4AYwAA/////wAA/AAAAKkAAAAAnAA4ADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABoAGEAcgBkAHcAYQByAGUAXABzAGIAaQBvAHMAXABiAGkAbwBzAC4AaAAA/////wAA/AAAAKkAAAAAnAAyADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABoAGEAcgBkAHcAYQByAGUAXABnAHMAXABnAGkAZgBcAGcAaQBmAC4AYwAA/////wAA/AAAAKkAAAAAnAA1ADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABoAGEAcgBkAHcAYQByAGUAXABnAHMAXABnAGkAZgBcAGcAaQBmAC4AaAAA/////wAA/AAAAKsAAAAAngA2ADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABoAGEAcgBkAHcAYQByAGUAXABzAGIAaQBvAHMAXABzAGIAaQBvAHMALgBoAQD/////AAH8AAAAswAAAACmADkAOgA6ADoAQwA6AFwATQBpAG4ARwBXAFwAbQBzAHkAcwBcADEALgAwAFwAaABvAG0AZQBcAGIAdQBpAGwAZABcAFcAbwByAGsAUwBwAGEAYwBlAFwAcwBwAHMAMgBfAGIAYQBzAGUAbQBlAG4AdABcAGgAYQByAGQAdwBhAHIAZQBcAHMAYgBpAG8AcwBcAHMAeQBzAGMAYQBsAGwAbgByAC4AaAAA/////wAAAAAAAA== +STANDARD_LAYOUT: 54 1 44 5 4 M 0 +_tbbufftabs_form F=11 +_tbprojects_form F=8 +_tbdebug_watches_form F=64 +_tbbaseclasses_form F=40 +_tbdeltasave_form F=0 +_tbdebug_regs_form F=64 +_tbFTPOpen_form F=0 +_tbdebug_threads_form F=64 +_tbclipboard_form F=44 +_tbopen_form F=40 +_tbterminal_form F=8 +_tbdebug_exceptions_form F=384 +_tbdebug_classes_form F=64 +_tbtagwin_form F=8 +_tbdebug_autovars_form F=64 +_tbsymbolcallers_form F=40 +_tbFTPClient_form F=0 +_tbtagrefs_form F=8 +_tbfind_symbol_form F=32 +_tbdebug_locals_form F=64 +_tbdebug_members_form F=64 +_tbdebug_memory_form F=64 +_tbsymbol_args_form F=8 +_tbdebug_stack_form F=64 +_tbsymbolcalls_form F=40 +_tbsymbol_props_form F=8 +_tbfilelist_form F=44 +_tboutputwin_form F=8 +_tbclass_form F=8 +_tbunittest_form F=0 +_tbfind_form F=36 +_tbmessages_browser_form F=8 +_tbannotations_browser_form F=0 +_tbdebug_breakpoints_form F=384 +_tbnotification_form F=36 +_tbinteractive_form F=8 +_tbproctree_form F=8 +_tbbookmarks_form F=8 +_tbregex_form F=40 +_tbslickc_stack_form F=8 +_tbderivedclasses_form F=40 +_tbshell_form F=8 +_tbcbrowser_form F=8 +_tbsearch_form F=8 +_tbclass_form T=0 +_tbproctree_form T=0 +_tbprojects_form T=0 +_tbcbrowser_form T=0 +_tbopen_form T=0 +AAAAAwAAAAEAAAAB2gAAAAIAMAAAAAAAAAA1AAAHfwAAA+MAAAAAAAAAAAAAB38AAAQPAAAAAesAAAUOAAAAAPsAAAACAAAAAgAAAAEAAAAA+wAAAAIAAAACAAAAAAAAAAH9AAABoQAAAAAaADoAOgA6AC8AdgBEAG8AYwBrAEEAcgBlAGEBAAAAAbcAAAAAAAL7AAAABQAAAAUAAAAAAAAABAAAAAMAAAACAAAAAfsAAAAFAAAABQAAAAAAAAABAAAAAgAAAAMAAAAE/AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGoAZQBjAHQAcwBfAGYAbwByAG0BAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGMAdAByAGUAZQBfAGYAbwByAG0AAP////8AAP///////////AAAADcAAAAAIgAwADoAOgA6AF8AdABiAGMAbABhAHMAcwBfAGYAbwByAG0AAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAGMAYgByAG8AdwBzAGUAcgBfAGYAbwByAG0AAP////8AAP///////////AAAADUAAAAAIAAwADoAOgA6AF8AdABiAG8AcABlAG4AXwBmAG8AcgBtAAD/////AAD///////////0AAAMZAAAAABoAOgA6ADoALwB2AEQAbwBjAGsAQQByAGUAYQEAAAAFxAABAAAAAfsAAAACAAAAAgAAAAAAAAAB+wAAAAIAAAACAAAAAQAAAAD8AAAAKQAAAAAcADoAOgA6AE0ARABJAEEAUgBFAEEAVABJAEwARQEAAAABiAAB/QAAApkAAAAAGgA6ADoAOgAvAHYARABvAGMAawBBAHIAZQBhAAAAAAIiAAAAAAAC+wAAAAcAAAAHAAAAAAAAAAIAAAABAAAABgAAAAUAAAAEAAAAA/sAAAAHAAAABwAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAb8AAAARQEAAAAkADEAOgA6ADoAXwB0AGIAcwBlAGEAcgBjAGgAXwBmAG8AcgBtAAD/////AAAAAAXuAAACDQAAAYCg5oZ4AAAAAPwAAABFAQAAACQAMAA6ADoAOgBfAHQAYgB0AGEAZwB3AGkAbgBfAGYAbwByAG0AAP////8AAAAABf0AAACzAAABfyzVyuYAAAAA/AAAAEcBAAAAJgAxADoAOgA6AF8AdABiAHQAYQBnAHIAZQBmAHMAXwBmAG8AcgBtAAD/////AAAAAAXMAAABTwAAAYBjGM+NAAAAAPwAAABDAQAAACIAMAA6ADoAOgBfAHQAYgBzAGgAZQBsAGwAXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1b7yAAAAAPwAAABZAQAAADgAMAA6ADoAOgBfAHQAYgBtAGUAcwBzAGEAZwBlAHMAXwBiAHIAbwB3AHMAZQByAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXCJAAAAAD8AAAASQEAAAAoADAAOgA6ADoAXwB0AGIAdABlAHIAbQBpAG4AYQBsAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXEsgAAAAD8AAAASwEAAAAqADAAOgA6ADoAXwB0AGIAbwB1AHQAcAB1AHQAdwBpAG4AXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1caQAAAAAAAAAADbAAAAAAAAAALbAAAAAAAAAAHbAAAAAAAAAAPbAAAAAAAAAAA= +QTOOLBAR 2 0 +AAAA/wAAAAD9AAAAAAAAB4AAAAOvAAAABAAAAAQAAAAIAAAACPwAAAABAAAAAgAAAAIAAAAQAFMAdABhAG4AZABhAHIAZAEAAAAA/////wAAAAAAAAAAAAAAHgBDAHUAcgByAGUAbgB0ACAAQwBvAG4AdABlAHgAdAEAAAJx/////wAAAAAAAAAA +_tbstandard_form 1 +_tbcontext_form 1 +APP_LAYOUT: 54 1 44 5 4 M 0 +_tbbufftabs_form F=11 +_tbprojects_form F=8 +_tbdebug_watches_form F=64 +_tbbaseclasses_form F=40 +_tbdeltasave_form F=0 +_tbdebug_regs_form F=64 +_tbFTPOpen_form F=0 +_tbdebug_threads_form F=64 +_tbclipboard_form F=44 +_tbopen_form F=40 +_tbterminal_form F=8 +_tbdebug_exceptions_form F=384 +_tbdebug_classes_form F=64 +_tbtagwin_form F=8 +_tbdebug_autovars_form F=64 +_tbsymbolcallers_form F=40 +_tbFTPClient_form F=0 +_tbtagrefs_form F=8 +_tbfind_symbol_form F=32 +_tbdebug_locals_form F=64 +_tbdebug_members_form F=64 +_tbdebug_memory_form F=64 +_tbsymbol_args_form F=8 +_tbdebug_stack_form F=64 +_tbsymbolcalls_form F=40 +_tbsymbol_props_form F=8 +_tbfilelist_form F=44 +_tboutputwin_form F=8 +_tbclass_form F=8 +_tbunittest_form F=0 +_tbfind_form F=36 +_tbmessages_browser_form F=8 +_tbannotations_browser_form F=0 +_tbdebug_breakpoints_form F=384 +_tbnotification_form F=36 +_tbinteractive_form F=8 +_tbproctree_form F=8 +_tbbookmarks_form F=8 +_tbregex_form F=40 +_tbslickc_stack_form F=8 +_tbderivedclasses_form F=40 +_tbshell_form F=8 +_tbcbrowser_form F=8 +_tbsearch_form F=8 +_tbclass_form T=0 +_tbproctree_form T=0 +_tbprojects_form T=0 +_tbcbrowser_form T=0 +_tbopen_form T=0 +AAAAAwAAAAEAAAAB2gAAAAIAMAAAAAAAAAA1AAAHfwAAA+MAAAAAAAAAAAAAB38AAAQPAAAAAesAAAUOAAAAAPsAAAACAAAAAgAAAAEAAAAA+wAAAAIAAAACAAAAAAAAAAH9AAABoQAAAAAaADoAOgA6AC8AdgBEAG8AYwBrAEEAcgBlAGEBAAAAAbcAAAAAAAL7AAAABQAAAAUAAAAAAAAABAAAAAMAAAACAAAAAfsAAAAFAAAABQAAAAAAAAABAAAAAgAAAAMAAAAE/AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGoAZQBjAHQAcwBfAGYAbwByAG0BAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGMAdAByAGUAZQBfAGYAbwByAG0AAP////8AAP///////////AAAADcAAAAAIgAwADoAOgA6AF8AdABiAGMAbABhAHMAcwBfAGYAbwByAG0AAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAGMAYgByAG8AdwBzAGUAcgBfAGYAbwByAG0AAP////8AAP///////////AAAADUAAAAAIAAwADoAOgA6AF8AdABiAG8AcABlAG4AXwBmAG8AcgBtAAD/////AAD///////////0AAAMZAAAAABoAOgA6ADoALwB2AEQAbwBjAGsAQQByAGUAYQEAAAAFxAABAAAAAfsAAAACAAAAAgAAAAAAAAAB+wAAAAIAAAACAAAAAQAAAAD8AAAAKQAAAAAcADoAOgA6AE0ARABJAEEAUgBFAEEAVABJAEwARQEAAAABiAAB/QAAApkAAAAAGgA6ADoAOgAvAHYARABvAGMAawBBAHIAZQBhAAAAAAIiAAAAAAAC+wAAAAcAAAAHAAAAAAAAAAIAAAABAAAABgAAAAUAAAAEAAAAA/sAAAAHAAAABwAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAb8AAAARQEAAAAkADEAOgA6ADoAXwB0AGIAcwBlAGEAcgBjAGgAXwBmAG8AcgBtAAD/////AAAAAAXuAAACDQAAAYCg5oZ4AAAAAPwAAABFAQAAACQAMAA6ADoAOgBfAHQAYgB0AGEAZwB3AGkAbgBfAGYAbwByAG0AAP////8AAAAABf0AAACzAAABfyzVyuYAAAAA/AAAAEcBAAAAJgAxADoAOgA6AF8AdABiAHQAYQBnAHIAZQBmAHMAXwBmAG8AcgBtAAD/////AAAAAAXMAAABTwAAAYBjGM+NAAAAAPwAAABDAQAAACIAMAA6ADoAOgBfAHQAYgBzAGgAZQBsAGwAXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1b7yAAAAAPwAAABZAQAAADgAMAA6ADoAOgBfAHQAYgBtAGUAcwBzAGEAZwBlAHMAXwBiAHIAbwB3AHMAZQByAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXCJAAAAAD8AAAASQEAAAAoADAAOgA6ADoAXwB0AGIAdABlAHIAbQBpAG4AYQBsAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXEsgAAAAD8AAAASwEAAAAqADAAOgA6ADoAXwB0AGIAbwB1AHQAcAB1AHQAdwBpAG4AXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1caQAAAAAAAAAADbAAAAAAAAAALbAAAAAAAAAAHbAAAAAAAAAAPbAAAAAAAAAAA= +QTOOLBAR 2 0 +AAAA/wAAAAD9AAAAAAAAB4AAAAOvAAAABAAAAAQAAAAIAAAACPwAAAABAAAAAgAAAAIAAAAQAFMAdABhAG4AZABhAHIAZAEAAAAA/////wAAAAAAAAAAAAAAHgBDAHUAcgByAGUAbgB0ACAAQwBvAG4AdABlAHgAdAEAAAJx/////wAAAAAAAAAA +_tbstandard_form 1 +_tbcontext_form 1 +MONITOR_CONFIG: 114 0 0 1920 1080,-1680 30 1680 1050 +SCREEN: 1920 1080 130 130 1453 772 0 0 M 0 0 0 0 1498 943 0 +MDISTATE: 1 +AAAAAwAAAAIAAAAB2gAAAAIAMAAAAAAAAAA1AAAHfwAAA+MAAAAAAAAAAAAAB38AAAQPAAAAAuoAAAMyAAAAAvsAAAAGAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABfsAAAAGAAAABgAAAAEAAAAFAAAABAAAAAMAAAAAAAAAAvwAAABlAAAAAFgAMwA6ADoAOgBaADoAXABkAHIAXwBmAHIAdQBjAGgAdABcAGwAaQBiAFwAcgBnAG8AbwBzAGUAXAByAGcAbwBvAHMAZQBDAGEAbQBlAHIAYQAuAGMAcABwAQD/////AAH8AAAAlQAAAACIADcAOgA6ADoAWgA6AFwAZAByAF8AZgByAHUAYwBoAHQAXABsAGkAYgBcAHIAZwBvAG8AcwBlAFwAcgBnAG8AbwBzAGUASABhAHIAZAB3AGEAcgBlAFIAZQBzAG8AdQByAGMAZQBTAGUAcgBpAGEAbABQAHIAbwB2AGkAZABlAHIALgBjAHAAcAAA/////wAA/AAAAHkAAAAAbAAyADoAOgA6AFoAOgBcAGQAcgBfAGYAcgB1AGMAaAB0AFwAbABpAGIAXAByAGcAbwBvAHMAZQBcAHIAZwBvAG8AcwBlAE0AbwBkAHUAbABlAEUAbQBiAGUAZABWAGkAZABlAG8ALgBjAHAAcAAA/////wAA/AAAAHsAAAAAbgA0ADoAOgA6AFoAOgBcAGQAcgBfAGYAcgB1AGMAaAB0AFwAbABpAGIAXAByAGcAbwBvAHMAZQBcAHIAZwBvAG8AcwBlAE4AbwBkAGUAUABUAFoAQwBhAG0AQwBvAG4AdAByAG8AbAAuAGMAcABwAAD/////AAD8AAAAgQAAAAB0ADUAOgA6ADoAWgA6AFwAZAByAF8AZgByAHUAYwBoAHQAXABsAGkAYgBcAHIAZwBvAG8AcwBlAFwAcgBnAG8AbwBzAGUATgBvAGQAZQBTAHQAYQB0AGkAYwBDAGEAbQBDAG8AbgB0AHIAbwBsAC4AYwBwAHAAAP////8AAPwAAABfAAAAAFIANgA6ADoAOgBaADoAXABkAHIAXwBmAHIAdQBjAGgAdABcAGwAaQBiAFwAcgBnAG8AbwBzAGUAXAByAGcAbwBvAHMAZQBUAHkAcABlAHMALgBoAAD/////AAAAAAAA +APP_LAYOUT: 54 1 44 5 4 M 0 +_tbbufftabs_form F=11 +_tbprojects_form F=8 +_tbdebug_watches_form F=64 +_tbbaseclasses_form F=40 +_tbdeltasave_form F=0 +_tbdebug_regs_form F=64 +_tbFTPOpen_form F=0 +_tbdebug_threads_form F=64 +_tbclipboard_form F=44 +_tbopen_form F=40 +_tbterminal_form F=8 +_tbdebug_exceptions_form F=384 +_tbdebug_classes_form F=64 +_tbtagwin_form F=8 +_tbdebug_autovars_form F=64 +_tbsymbolcallers_form F=40 +_tbFTPClient_form F=0 +_tbtagrefs_form F=8 +_tbfind_symbol_form F=32 +_tbdebug_locals_form F=64 +_tbdebug_members_form F=64 +_tbdebug_memory_form F=64 +_tbsymbol_args_form F=8 +_tbdebug_stack_form F=64 +_tbsymbolcalls_form F=40 +_tbsymbol_props_form F=8 +_tbfilelist_form F=44 +_tboutputwin_form F=8 +_tbclass_form F=8 +_tbunittest_form F=0 +_tbfind_form F=36 +_tbmessages_browser_form F=8 +_tbannotations_browser_form F=0 +_tbdebug_breakpoints_form F=384 +_tbnotification_form F=36 +_tbinteractive_form F=8 +_tbproctree_form F=8 +_tbbookmarks_form F=8 +_tbregex_form F=40 +_tbslickc_stack_form F=8 +_tbderivedclasses_form F=40 +_tbshell_form F=8 +_tbcbrowser_form F=8 +_tbsearch_form F=8 +_tbproctree_form T=0 +_tbcbrowser_form T=0 +_tbopen_form T=0 +_tbprojects_form T=0 +_tbclass_form T=0 +AAAAAwAAAAEAAAAB2gAAAAIAMAAAAAAAAAA1AAAHfwAAA+MAAAAAAAAAAAAAB38AAAQPAAAAAesAAAUOAAAAAPsAAAACAAAAAgAAAAEAAAAA+wAAAAIAAAACAAAAAAAAAAH9AAABoQAAAAAaADoAOgA6AC8AdgBEAG8AYwBrAEEAcgBlAGEBAAAAAaEAAAAAAAL7AAAABQAAAAUAAAAAAAAABAAAAAMAAAACAAAAAfsAAAAFAAAABQAAAAAAAAABAAAAAgAAAAMAAAAE/AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGoAZQBjAHQAcwBfAGYAbwByAG0BAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGMAdAByAGUAZQBfAGYAbwByAG0AAP////8AAP///////////AAAADcAAAAAIgAwADoAOgA6AF8AdABiAGMAbABhAHMAcwBfAGYAbwByAG0AAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAGMAYgByAG8AdwBzAGUAcgBfAGYAbwByAG0AAP////8AAP///////////AAAADUAAAAAIAAwADoAOgA6AF8AdABiAG8AcABlAG4AXwBmAG8AcgBtAAD/////AAD///////////0AAAMZAAAAABoAOgA6ADoALwB2AEQAbwBjAGsAQQByAGUAYQEAAAAF2gABAAAAAfsAAAACAAAAAgAAAAAAAAAB+wAAAAIAAAACAAAAAQAAAAD8AAAAKQAAAAAcADoAOgA6AE0ARABJAEEAUgBFAEEAVABJAEwARQEAAAACRgAB/QAAApkAAAAAGgA6ADoAOgAvAHYARABvAGMAawBBAHIAZQBhAAAAAAFkAAAAAAAC+wAAAAcAAAAHAAAAAAAAAAIAAAABAAAABgAAAAUAAAAEAAAAA/sAAAAHAAAABwAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAb8AAAARQEAAAAkADEAOgA6ADoAXwB0AGIAcwBlAGEAcgBjAGgAXwBmAG8AcgBtAAD/////AAAAAAXaAAABTwAAAX+VhBd7AAAAAPwAAABFAQAAACQAMAA6ADoAOgBfAHQAYgB0AGEAZwB3AGkAbgBfAGYAbwByAG0AAP////8AAAAABf0AAACzAAABfyzVyuYAAAAA/AAAAEcBAAAAJgAwADoAOgA6AF8AdABiAHQAYQBnAHIAZQBmAHMAXwBmAG8AcgBtAAD/////AAAAAAX/AAAA0QAAAX8s1c3cAAAAAPwAAABDAQAAACIAMAA6ADoAOgBfAHQAYgBzAGgAZQBsAGwAXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1b7yAAAAAPwAAABZAQAAADgAMAA6ADoAOgBfAHQAYgBtAGUAcwBzAGEAZwBlAHMAXwBiAHIAbwB3AHMAZQByAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXCJAAAAAD8AAAASQEAAAAoADAAOgA6ADoAXwB0AGIAdABlAHIAbQBpAG4AYQBsAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXEsgAAAAD8AAAASwEAAAAqADAAOgA6ADoAXwB0AGIAbwB1AHQAcAB1AHQAdwBpAG4AXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1caQAAAAAAAAAADbAAAAAAAAAALbAAAAAAAAAAHbAAAAAAAAAAPbAAAAAAAAAAA= +QTOOLBAR 2 0 +AAAA/wAAAAD9AAAAAAAAB4AAAAOvAAAABAAAAAQAAAAIAAAACPwAAAABAAAAAgAAAAIAAAAQAFMAdABhAG4AZABhAHIAZAEAAAAA/////wAAAAAAAAAAAAAAHgBDAHUAcgByAGUAbgB0ACAAQwBvAG4AdABlAHgAdAEAAAJx/////wAAAAAAAAAA +_tbstandard_form 1 +_tbcontext_form 1 + +STANDARD_LAYOUT: 54 1 44 5 4 M 0 +_tbbufftabs_form F=11 +_tbprojects_form F=8 +_tbdebug_watches_form F=64 +_tbbaseclasses_form F=40 +_tbdeltasave_form F=0 +_tbdebug_regs_form F=64 +_tbFTPOpen_form F=0 +_tbdebug_threads_form F=64 +_tbclipboard_form F=44 +_tbopen_form F=40 +_tbterminal_form F=8 +_tbdebug_exceptions_form F=384 +_tbdebug_classes_form F=64 +_tbtagwin_form F=8 +_tbdebug_autovars_form F=64 +_tbsymbolcallers_form F=40 +_tbFTPClient_form F=0 +_tbtagrefs_form F=8 +_tbfind_symbol_form F=32 +_tbdebug_locals_form F=64 +_tbdebug_members_form F=64 +_tbdebug_memory_form F=64 +_tbsymbol_args_form F=8 +_tbdebug_stack_form F=64 +_tbsymbolcalls_form F=40 +_tbsymbol_props_form F=8 +_tbfilelist_form F=44 +_tboutputwin_form F=8 +_tbclass_form F=8 +_tbunittest_form F=0 +_tbfind_form F=36 +_tbmessages_browser_form F=8 +_tbannotations_browser_form F=0 +_tbdebug_breakpoints_form F=384 +_tbnotification_form F=36 +_tbinteractive_form F=8 +_tbproctree_form F=8 +_tbbookmarks_form F=8 +_tbregex_form F=40 +_tbslickc_stack_form F=8 +_tbderivedclasses_form F=40 +_tbshell_form F=8 +_tbcbrowser_form F=8 +_tbsearch_form F=8 +_tbproctree_form T=0 +_tbcbrowser_form T=0 +_tbopen_form T=0 +_tbprojects_form T=0 +_tbclass_form T=0 +AAAAAwAAAAEAAAAB2gAAAAIAMAAAAAAAAAA1AAAHfwAAA+MAAAAAAAAAAAAAB38AAAQPAAAAAesAAAUOAAAAAPsAAAACAAAAAgAAAAEAAAAA+wAAAAIAAAACAAAAAAAAAAH9AAABoQAAAAAaADoAOgA6AC8AdgBEAG8AYwBrAEEAcgBlAGEBAAAAAaEAAAAAAAL7AAAABQAAAAUAAAAAAAAABAAAAAMAAAACAAAAAfsAAAAFAAAABQAAAAAAAAABAAAAAgAAAAMAAAAE/AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGoAZQBjAHQAcwBfAGYAbwByAG0BAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGMAdAByAGUAZQBfAGYAbwByAG0AAP////8AAP///////////AAAADcAAAAAIgAwADoAOgA6AF8AdABiAGMAbABhAHMAcwBfAGYAbwByAG0AAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAGMAYgByAG8AdwBzAGUAcgBfAGYAbwByAG0AAP////8AAP///////////AAAADUAAAAAIAAwADoAOgA6AF8AdABiAG8AcABlAG4AXwBmAG8AcgBtAAD/////AAD///////////0AAAMZAAAAABoAOgA6ADoALwB2AEQAbwBjAGsAQQByAGUAYQEAAAAF2gABAAAAAfsAAAACAAAAAgAAAAAAAAAB+wAAAAIAAAACAAAAAQAAAAD8AAAAKQAAAAAcADoAOgA6AE0ARABJAEEAUgBFAEEAVABJAEwARQEAAAACRgAB/QAAApkAAAAAGgA6ADoAOgAvAHYARABvAGMAawBBAHIAZQBhAAAAAAFkAAAAAAAC+wAAAAcAAAAHAAAAAAAAAAIAAAABAAAABgAAAAUAAAAEAAAAA/sAAAAHAAAABwAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAb8AAAARQEAAAAkADEAOgA6ADoAXwB0AGIAcwBlAGEAcgBjAGgAXwBmAG8AcgBtAAD/////AAAAAAXaAAABTwAAAX+VhBd7AAAAAPwAAABFAQAAACQAMAA6ADoAOgBfAHQAYgB0AGEAZwB3AGkAbgBfAGYAbwByAG0AAP////8AAAAABf0AAACzAAABfyzVyuYAAAAA/AAAAEcBAAAAJgAwADoAOgA6AF8AdABiAHQAYQBnAHIAZQBmAHMAXwBmAG8AcgBtAAD/////AAAAAAX/AAAA0QAAAX8s1c3cAAAAAPwAAABDAQAAACIAMAA6ADoAOgBfAHQAYgBzAGgAZQBsAGwAXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1b7yAAAAAPwAAABZAQAAADgAMAA6ADoAOgBfAHQAYgBtAGUAcwBzAGEAZwBlAHMAXwBiAHIAbwB3AHMAZQByAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXCJAAAAAD8AAAASQEAAAAoADAAOgA6ADoAXwB0AGIAdABlAHIAbQBpAG4AYQBsAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXEsgAAAAD8AAAASwEAAAAqADAAOgA6ADoAXwB0AGIAbwB1AHQAcAB1AHQAdwBpAG4AXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1caQAAAAAAAAAADbAAAAAAAAAALbAAAAAAAAAAHbAAAAAAAAAAPbAAAAAAAAAAA= +QTOOLBAR 2 0 +AAAA/wAAAAD9AAAAAAAAB4AAAAOvAAAABAAAAAQAAAAIAAAACPwAAAABAAAAAgAAAAIAAAAQAFMAdABhAG4AZABhAHIAZAEAAAAA/////wAAAAAAAAAAAAAAHgBDAHUAcgByAGUAbgB0ACAAQwBvAG4AdABlAHgAdAEAAAJx/////wAAAAAAAAAA +_tbstandard_form 1 +_tbcontext_form 1 +MONITOR_CONFIG: 114 0 0 1280 1024 +SCREEN: 1280 1024 91 70 1133 879 0 0 M 0 0 0 0 987 887 0 +MDISTATE: 1 +AAAAAwAAAAIAAAAB2gAAAAIAMAAAAAAAAAA1AAAHfwAAA+MAAAAAAAAAAAAAB38AAAQPAAAAAuoAAAXYAAAAAvsAAAAIAAAACAAAAAIAAAAHAAAABQAAAAYAAAAEAAAAAwAAAAEAAAAA+wAAAAgAAAAIAAAABQAAAAQAAAAHAAAAAwAAAAIAAAAGAAAAAQAAAAD8AAAArQAAAACgADMAOgA6ADoAQwA6AFwATQBpAG4ARwBXAFwAbQBzAHkAcwBcADEALgAwAFwAaABvAG0AZQBcAGIAdQBpAGwAZABcAFcAbwByAGsAUwBwAGEAYwBlAFwAcwBwAHMAMgBfAGIAYQBzAGUAbQBlAG4AdABcAGMAbwByAGUAXABiAGEAcwBlAFwAYgBhAHMAaQBjAEMAbwBuAGYAaQBnAC4AaAAA/////wAA/AAAAKsAAAAAngA0ADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABjAG8AcgBlAFwAYgBhAHMAZQBcAGIAYQBzAGkAYwBUAHkAcABlAHMALgBoAAD/////AAD8AAAAqQAAAACcADcAOgA6ADoAQwA6AFwATQBpAG4ARwBXAFwAbQBzAHkAcwBcADEALgAwAFwAaABvAG0AZQBcAGIAdQBpAGwAZABcAFcAbwByAGsAUwBwAGEAYwBlAFwAcwBwAHMAMgBfAGIAYQBzAGUAbQBlAG4AdABcAGgAYQByAGQAdwBhAHIAZQBcAHMAYgBpAG8AcwBcAGIAaQBvAHMALgBjAQD/////AAH8AAAAqQAAAACcADgAOgA6ADoAQwA6AFwATQBpAG4ARwBXAFwAbQBzAHkAcwBcADEALgAwAFwAaABvAG0AZQBcAGIAdQBpAGwAZABcAFcAbwByAGsAUwBwAGEAYwBlAFwAcwBwAHMAMgBfAGIAYQBzAGUAbQBlAG4AdABcAGgAYQByAGQAdwBhAHIAZQBcAHMAYgBpAG8AcwBcAGIAaQBvAHMALgBoAAD/////AAD8AAAAqQAAAACcADIAOgA6ADoAQwA6AFwATQBpAG4ARwBXAFwAbQBzAHkAcwBcADEALgAwAFwAaABvAG0AZQBcAGIAdQBpAGwAZABcAFcAbwByAGsAUwBwAGEAYwBlAFwAcwBwAHMAMgBfAGIAYQBzAGUAbQBlAG4AdABcAGgAYQByAGQAdwBhAHIAZQBcAGcAcwBcAGcAaQBmAFwAZwBpAGYALgBjAAD/////AAD8AAAAqQAAAACcADUAOgA6ADoAQwA6AFwATQBpAG4ARwBXAFwAbQBzAHkAcwBcADEALgAwAFwAaABvAG0AZQBcAGIAdQBpAGwAZABcAFcAbwByAGsAUwBwAGEAYwBlAFwAcwBwAHMAMgBfAGIAYQBzAGUAbQBlAG4AdABcAGgAYQByAGQAdwBhAHIAZQBcAGcAcwBcAGcAaQBmAFwAZwBpAGYALgBoAAD/////AAD8AAAAqwAAAACeADYAOgA6ADoAQwA6AFwATQBpAG4ARwBXAFwAbQBzAHkAcwBcADEALgAwAFwAaABvAG0AZQBcAGIAdQBpAGwAZABcAFcAbwByAGsAUwBwAGEAYwBlAFwAcwBwAHMAMgBfAGIAYQBzAGUAbQBlAG4AdABcAGgAYQByAGQAdwBhAHIAZQBcAHMAYgBpAG8AcwBcAHMAYgBpAG8AcwAuAGgAAP////8AAPwAAACzAAAAAKYAOQA6ADoAOgBDADoAXABNAGkAbgBHAFcAXABtAHMAeQBzAFwAMQAuADAAXABoAG8AbQBlAFwAYgB1AGkAbABkAFwAVwBvAHIAawBTAHAAYQBjAGUAXABzAHAAcwAyAF8AYgBhAHMAZQBtAGUAbgB0AFwAaABhAHIAZAB3AGEAcgBlAFwAcwBiAGkAbwBzAFwAcwB5AHMAYwBhAGwAbABuAHIALgBoAAD/////AAAAAAAA +APP_LAYOUT: 54 1 44 5 4 M 0 +_tbbufftabs_form F=11 +_tbprojects_form F=8 +_tbdebug_watches_form F=64 +_tbbaseclasses_form F=40 +_tbdeltasave_form F=0 +_tbdebug_regs_form F=64 +_tbFTPOpen_form F=0 +_tbdebug_threads_form F=64 +_tbclipboard_form F=44 +_tbopen_form F=40 +_tbterminal_form F=8 +_tbdebug_exceptions_form F=384 +_tbdebug_classes_form F=64 +_tbtagwin_form F=8 +_tbdebug_autovars_form F=64 +_tbsymbolcallers_form F=40 +_tbFTPClient_form F=0 +_tbtagrefs_form F=8 +_tbfind_symbol_form F=32 +_tbdebug_locals_form F=64 +_tbdebug_members_form F=64 +_tbdebug_memory_form F=64 +_tbsymbol_args_form F=8 +_tbdebug_stack_form F=64 +_tbsymbolcalls_form F=40 +_tbsymbol_props_form F=8 +_tbfilelist_form F=44 +_tboutputwin_form F=8 +_tbclass_form F=8 +_tbunittest_form F=0 +_tbfind_form F=36 +_tbmessages_browser_form F=8 +_tbannotations_browser_form F=0 +_tbdebug_breakpoints_form F=384 +_tbnotification_form F=36 +_tbinteractive_form F=8 +_tbproctree_form F=8 +_tbbookmarks_form F=8 +_tbregex_form F=40 +_tbslickc_stack_form F=8 +_tbderivedclasses_form F=40 +_tbshell_form F=8 +_tbcbrowser_form F=8 +_tbsearch_form F=8 +_tbcbrowser_form T=0 +_tbprojects_form T=0 +_tbclass_form T=0 +_tbproctree_form T=0 +_tbopen_form T=0 +AAAAAwAAAAEAAAAB2gAAAAIAMAAAAAAAAAA1AAAE/wAAA6sAAAAAAAAAAAAABP8AAAPXAAAAAesAAAUOAAAAAPsAAAACAAAAAgAAAAEAAAAA+wAAAAIAAAACAAAAAAAAAAH9AAABoQAAAAAaADoAOgA6AC8AdgBEAG8AYwBrAEEAcgBlAGEBAAAAASAAAAAAAAL7AAAABQAAAAUAAAAAAAAABAAAAAMAAAACAAAAAfsAAAAFAAAABQAAAAAAAAABAAAAAgAAAAMAAAAE/AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGoAZQBjAHQAcwBfAGYAbwByAG0BAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGMAdAByAGUAZQBfAGYAbwByAG0AAP////8AAP///////////AAAADcAAAAAIgAwADoAOgA6AF8AdABiAGMAbABhAHMAcwBfAGYAbwByAG0AAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAGMAYgByAG8AdwBzAGUAcgBfAGYAbwByAG0AAP////8AAP///////////AAAADUAAAAAIAAwADoAOgA6AF8AdABiAG8AcABlAG4AXwBmAG8AcgBtAAD/////AAD///////////0AAAMZAAAAABoAOgA6ADoALwB2AEQAbwBjAGsAQQByAGUAYQEAAAAD2wABAAAAAfsAAAACAAAAAgAAAAAAAAAB+wAAAAIAAAACAAAAAQAAAAD8AAAAKQAAAAAcADoAOgA6AE0ARABJAEEAUgBFAEEAVABJAEwARQEAAAABcAAB/QAAApkAAAAAGgA6ADoAOgAvAHYARABvAGMAawBBAHIAZQBhAAAAAAICAAAAAAAC+wAAAAcAAAAHAAAAAAAAAAIAAAABAAAABgAAAAUAAAAEAAAAA/sAAAAHAAAABwAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAb8AAAARQEAAAAkADEAOgA6ADoAXwB0AGIAcwBlAGEAcgBjAGgAXwBmAG8AcgBtAAD/////AAAAAAPbAAAB7QAAAYC45jwMAAAAAPwAAABFAQAAACQAMAA6ADoAOgBfAHQAYgB0AGEAZwB3AGkAbgBfAGYAbwByAG0AAP////8AAAAABf0AAACzAAABfyzVyuYAAAAA/AAAAEcBAAAAJgAwADoAOgA6AF8AdABiAHQAYQBnAHIAZQBmAHMAXwBmAG8AcgBtAAD/////AAAAAAX/AAAA0QAAAX8s1c3cAAAAAPwAAABDAQAAACIAMAA6ADoAOgBfAHQAYgBzAGgAZQBsAGwAXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1b7yAAAAAPwAAABZAQAAADgAMAA6ADoAOgBfAHQAYgBtAGUAcwBzAGEAZwBlAHMAXwBiAHIAbwB3AHMAZQByAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXCJAAAAAD8AAAASQEAAAAoADAAOgA6ADoAXwB0AGIAdABlAHIAbQBpAG4AYQBsAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXEsgAAAAD8AAAASwEAAAAqADAAOgA6ADoAXwB0AGIAbwB1AHQAcAB1AHQAdwBpAG4AXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1caQAAAAAAAAAADbAAAAAAAAAALbAAAAAAAAAAHbAAAAAAAAAAPbAAAAAAAAAAA= +QTOOLBAR 2 0 +AAAA/wAAAAD9AAAAAAAABQAAAAN3AAAABAAAAAQAAAAIAAAACPwAAAABAAAAAgAAAAIAAAAQAFMAdABhAG4AZABhAHIAZAEAAAAA/////wAAAAAAAAAAAAAAHgBDAHUAcgByAGUAbgB0ACAAQwBvAG4AdABlAHgAdAEAAAJx/////wAAAAAAAAAA +_tbstandard_form 1 +_tbcontext_form 1 + +STANDARD_LAYOUT: 54 1 44 5 4 M 0 +_tbbufftabs_form F=11 +_tbprojects_form F=8 +_tbdebug_watches_form F=64 +_tbbaseclasses_form F=40 +_tbdeltasave_form F=0 +_tbdebug_regs_form F=64 +_tbFTPOpen_form F=0 +_tbdebug_threads_form F=64 +_tbclipboard_form F=44 +_tbopen_form F=40 +_tbterminal_form F=8 +_tbdebug_exceptions_form F=384 +_tbdebug_classes_form F=64 +_tbtagwin_form F=8 +_tbdebug_autovars_form F=64 +_tbsymbolcallers_form F=40 +_tbFTPClient_form F=0 +_tbtagrefs_form F=8 +_tbfind_symbol_form F=32 +_tbdebug_locals_form F=64 +_tbdebug_members_form F=64 +_tbdebug_memory_form F=64 +_tbsymbol_args_form F=8 +_tbdebug_stack_form F=64 +_tbsymbolcalls_form F=40 +_tbsymbol_props_form F=8 +_tbfilelist_form F=44 +_tboutputwin_form F=8 +_tbclass_form F=8 +_tbunittest_form F=0 +_tbfind_form F=36 +_tbmessages_browser_form F=8 +_tbannotations_browser_form F=0 +_tbdebug_breakpoints_form F=384 +_tbnotification_form F=36 +_tbinteractive_form F=8 +_tbproctree_form F=8 +_tbbookmarks_form F=8 +_tbregex_form F=40 +_tbslickc_stack_form F=8 +_tbderivedclasses_form F=40 +_tbshell_form F=8 +_tbcbrowser_form F=8 +_tbsearch_form F=8 +_tbcbrowser_form T=0 +_tbprojects_form T=0 +_tbclass_form T=0 +_tbproctree_form T=0 +_tbopen_form T=0 +AAAAAwAAAAEAAAAB2gAAAAIAMAAAAAAAAAA1AAAE/wAAA6sAAAAAAAAAAAAABP8AAAPXAAAAAesAAAUOAAAAAPsAAAACAAAAAgAAAAEAAAAA+wAAAAIAAAACAAAAAAAAAAH9AAABoQAAAAAaADoAOgA6AC8AdgBEAG8AYwBrAEEAcgBlAGEBAAAAASAAAAAAAAL7AAAABQAAAAUAAAAAAAAABAAAAAMAAAACAAAAAfsAAAAFAAAABQAAAAAAAAABAAAAAgAAAAMAAAAE/AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGoAZQBjAHQAcwBfAGYAbwByAG0BAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAHAAcgBvAGMAdAByAGUAZQBfAGYAbwByAG0AAP////8AAP///////////AAAADcAAAAAIgAwADoAOgA6AF8AdABiAGMAbABhAHMAcwBfAGYAbwByAG0AAP////8AAP///////////AAAAD0AAAAAKAAwADoAOgA6AF8AdABiAGMAYgByAG8AdwBzAGUAcgBfAGYAbwByAG0AAP////8AAP///////////AAAADUAAAAAIAAwADoAOgA6AF8AdABiAG8AcABlAG4AXwBmAG8AcgBtAAD/////AAD///////////0AAAMZAAAAABoAOgA6ADoALwB2AEQAbwBjAGsAQQByAGUAYQEAAAAD2wABAAAAAfsAAAACAAAAAgAAAAAAAAAB+wAAAAIAAAACAAAAAQAAAAD8AAAAKQAAAAAcADoAOgA6AE0ARABJAEEAUgBFAEEAVABJAEwARQEAAAABcAAB/QAAApkAAAAAGgA6ADoAOgAvAHYARABvAGMAawBBAHIAZQBhAAAAAAICAAAAAAAC+wAAAAcAAAAHAAAAAAAAAAIAAAABAAAABgAAAAUAAAAEAAAAA/sAAAAHAAAABwAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAb8AAAARQEAAAAkADEAOgA6ADoAXwB0AGIAcwBlAGEAcgBjAGgAXwBmAG8AcgBtAAD/////AAAAAAPbAAAB7QAAAYC45jwMAAAAAPwAAABFAQAAACQAMAA6ADoAOgBfAHQAYgB0AGEAZwB3AGkAbgBfAGYAbwByAG0AAP////8AAAAABf0AAACzAAABfyzVyuYAAAAA/AAAAEcBAAAAJgAwADoAOgA6AF8AdABiAHQAYQBnAHIAZQBmAHMAXwBmAG8AcgBtAAD/////AAAAAAX/AAAA0QAAAX8s1c3cAAAAAPwAAABDAQAAACIAMAA6ADoAOgBfAHQAYgBzAGgAZQBsAGwAXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1b7yAAAAAPwAAABZAQAAADgAMAA6ADoAOgBfAHQAYgBtAGUAcwBzAGEAZwBlAHMAXwBiAHIAbwB3AHMAZQByAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXCJAAAAAD8AAAASQEAAAAoADAAOgA6ADoAXwB0AGIAdABlAHIAbQBpAG4AYQBsAF8AZgBvAHIAbQAA/////wAAAAAF/QAAALMAAAF/LNXEsgAAAAD8AAAASwEAAAAqADAAOgA6ADoAXwB0AGIAbwB1AHQAcAB1AHQAdwBpAG4AXwBmAG8AcgBtAAD/////AAAAAAX9AAAAswAAAX8s1caQAAAAAAAAAADbAAAAAAAAAALbAAAAAAAAAAHbAAAAAAAAAAPbAAAAAAAAAAA= +QTOOLBAR 2 0 +AAAA/wAAAAD9AAAAAAAABQAAAAN3AAAABAAAAAQAAAAIAAAACPwAAAABAAAAAgAAAAIAAAAQAFMAdABhAG4AZABhAHIAZAEAAAAA/////wAAAAAAAAAAAAAAHgBDAHUAcgByAGUAbgB0ACAAQwBvAG4AdABlAHgAdAEAAAJx/////wAAAAAAAAAA +_tbstandard_form 1 +_tbcontext_form 1 +END_MONITOR_CONFIGS: +CWD: Basic_test +BUFFER: BN="sps2_basement\core\base\basicConfig.h""""" +BI: MA=1 74 1 TABS= WWS=9 IWT= ST=8 IN=2 BW=0 US=32000 RO=0 SE=1 SN=0 BIN=0 MN= HM=0 MF=33554432 TL=0 MLL=0 ASE=0 LNL=1 LCF=6 CAPS=0 E=0 ESBU2=-1 CL="Chalkboard" SC="" SCE= SCU= ALM=0 FWRM=0 HMRE=0 HMRBW=0 SPCWT= SWF=2 SM= STAT= +VIEW: LN=.4949 CL=1 LE=0 CX=2 CY=56 WI=5 BI=7 HT=0 HN=0 HF=0 HC=4 HB=4 +BUFFER: BN="sps2_basement\core\base\basicTypes.h""""" +BI: MA=1 74 1 TABS= WWS=9 IWT= ST=8 IN=2 BW=0 US=32000 RO=0 SE=1 SN=0 BIN=0 MN= HM=0 MF=33554432 TL=0 MLL=0 ASE=0 LNL=1 LCF=6 CAPS=0 E=0 ESBU2=-1 CL="Chalkboard" SC="" SCE= SCU= ALM=0 FWRM=0 HMRE=0 HMRBW=0 SPCWT= SWF=2 SM= STAT= +VIEW: LN=.7496 CL=26 LE=0 CX=27 CY=43 WI=5 BI=8 HT=0 HN=0 HF=0 HC=4 HB=4 +BUFFER: BN="sps2_basement\hardware\sbios\bios.h""""" +BI: MA=1 74 1 TABS= WWS=9 IWT= ST=8 IN=2 BW=0 US=32000 RO=0 SE=1 SN=0 BIN=0 MN= HM=0 MF=33554432 TL=0 MLL=0 ASE=0 LNL=1 LCF=6 CAPS=0 E=0 ESBU2=-1 CL="Chalkboard" SC="" SCE= SCU= ALM=0 FWRM=0 HMRE=0 HMRBW=0 SPCWT= SWF=2 SM= STAT= +VIEW: LN=.17925 CL=34 LE=0 CX=35 CY=48 WI=5 BI=6 HT=0 HN=0 HF=0 HC=4 HB=4 +BUFFER: BN="sps2_basement\hardware\gs\gif\gif.c""""" +BI: MA=1 74 1 TABS= WWS=9 IWT= ST=8 IN=2 BW=0 US=32000 RO=0 SE=1 SN=0 BIN=0 MN= HM=0 MF=33554432 TL=0 MLL=0 ASE=0 LNL=1 LCF=6 CAPS=0 E=0 ESBU2=-1 CL="Chalkboard" SC="" SCE= SCU= ALM=0 FWRM=0 HMRE=0 HMRBW=0 SPCWT= SWF=2 SM= STAT= +VIEW: LN=.0 CL=14 LE=0 CX=15 CY=0 WI=5 BI=3 HT=0 HN=0 HF=0 HC=4 HB=4 +BUFFER: BN="sps2_basement\hardware\sbios\sbios.h""""" +BI: MA=1 74 1 TABS= WWS=9 IWT= ST=8 IN=2 BW=0 US=32000 RO=0 SE=1 SN=0 BIN=0 MN= HM=0 MF=119603808 TL=0 MLL=0 ASE=0 LNL=1 LCF=6 CAPS=0 E=0 ESBU2=-1 CL="Chalkboard" SC="" SCE= SCU= ALM=0 FWRM=0 HMRE=0 HMRBW=0 SPCWT= SWF=2 SM= STAT= +VIEW: LN=.13431 CL=32 LE=0 CX=33 CY=13 WI=5 BI=1 HT=0 HN=0 HF=0 HC=4 HB=4 +BUFFER: BN="sps2_basement\hardware\gs\gif\gif.h""""" +BI: MA=1 74 1 TABS= WWS=9 IWT= ST=8 IN=2 BW=0 US=32000 RO=0 SE=1 SN=0 BIN=0 MN= HM=0 MF=33554432 TL=0 MLL=0 ASE=0 LNL=1 LCF=6 CAPS=0 E=0 ESBU2=-1 CL="Chalkboard" SC="" SCE= SCU= ALM=0 FWRM=0 HMRE=0 HMRBW=0 SPCWT= SWF=2 SM= STAT= +VIEW: LN=.457 CL=1 LE=0 CX=2 CY=12 WI=5 BI=4 HT=0 HN=0 HF=0 HC=4 HB=4 +BUFFER: BN="sps2_basement\hardware\sbios\syscallnr.h""""" +BI: MA=1 74 1 TABS= WWS=9 IWT= ST=8 IN=2 BW=0 US=32000 RO=0 SE=1 SN=0 BIN=0 MN= HM=0 MF=33554432 TL=0 MLL=0 ASE=0 LNL=1 LCF=6 CAPS=0 E=0 ESBU2=-1 CL="Chalkboard" SC="" SCE= SCU= ALM=0 FWRM=0 HMRE=0 HMRBW=0 SPCWT= SWF=2 SM= STAT= +VIEW: LN=.626 CL=27 LE=0 CX=28 CY=18 WI=5 BI=5 HT=0 HN=0 HF=0 HC=4 HB=4 +BUFFER: BN="sps2_basement\hardware\sbios\bios.c""""" +BI: MA=1 74 1 TABS= WWS=9 IWT= ST=8 IN=2 BW=0 US=32000 RO=0 SE=1 SN=0 BIN=0 MN= HM=0 MF=119603808 TL=0 MLL=0 ASE=0 LNL=1 LCF=6 CAPS=0 E=0 ESBU2=-1 CL="Chalkboard" SC="" SCE= SCU= ALM=0 FWRM=0 HMRE=0 HMRBW=0 SPCWT= SWF=2 SM= STAT= +VIEW: LN=.2266 CL=46 LE=0 CX=47 CY=32 WI=5 BI=2 HT=0 HN=0 HF=0 HC=4 HB=4 +BUFFER: BN="sps2_basement\core\base\assert.h""""" +BI: MA=1 74 1 TABS= WWS=9 IWT= ST=8 IN=2 BW=0 US=32000 RO=0 SE=1 SN=0 BIN=0 MN= HM=0 MF=119603744 TL=0 MLL=0 ASE=0 LNL=1 LCF=6 CAPS=0 E=0 ESBU2=-1 CL="Chalkboard" SC="" SCE= SCU= ALM=0 FWRM=0 HMRE=0 HMRBW=0 SPCWT= SWF=2 SM= STAT= +VIEW: LN=.17 CL=19 LE=0 CX=20 CY=4 WI=5 BI=9 HT=0 HN=0 HF=0 HC=4 HB=4 +WINDOW: 1 22 1563 920 0 0 N WF=0 WT=3 ",,," DID=0 MI="*,,," +BUFFER: BN="sps2_basement\core\base\basicConfig.h""""" +VIEW: LN=.4949 CL=1 LE=0 CX=5 CY=56 WI=128 BI=7 HT=0 HN=0 HF=0 HC=4 HB=4 +WINDOW: 1 22 1563 920 0 0 N WF=0 WT=4 ",,," DID=0 MI="*,,," +BUFFER: BN="sps2_basement\core\base\basicTypes.h""""" +VIEW: LN=.7496 CL=26 LE=0 CX=31 CY=43 WI=127 BI=8 HT=0 HN=0 HF=0 HC=4 HB=4 +WINDOW: 1 22 1563 920 0 0 N WF=0 WT=8 ",,," DID=0 MI="*,,," +BUFFER: BN="sps2_basement\hardware\sbios\bios.h""""" +VIEW: LN=.17925 CL=34 LE=0 CX=39 CY=48 WI=15 BI=6 HT=0 HN=0 HF=0 HC=4 HB=4 +WINDOW: 1 22 1563 920 0 0 N WF=0 WT=2 ",,," DID=0 MI="*,,," +BUFFER: BN="sps2_basement\hardware\gs\gif\gif.c""""" +VIEW: LN=.0 CL=14 LE=0 CX=18 CY=0 WI=13 BI=3 HT=0 HN=0 HF=0 HC=4 HB=4 +WINDOW: 1 22 1563 920 0 0 N WF=0 WT=5 ",,," DID=0 MI="*,,," +BUFFER: BN="sps2_basement\hardware\gs\gif\gif.h""""" +VIEW: LN=.457 CL=1 LE=0 CX=5 CY=12 WI=134 BI=4 HT=0 HN=0 HF=0 HC=4 HB=4 +WINDOW: 1 22 1563 920 0 0 N WF=0 WT=9 ",,," DID=0 MI="*,,," +BUFFER: BN="sps2_basement\hardware\sbios\syscallnr.h""""" +VIEW: LN=.626 CL=27 LE=0 CX=32 CY=18 WI=137 BI=5 HT=0 HN=0 HF=0 HC=4 HB=4 +WINDOW: 1 22 1474 920 0 0 N WF=0 WT=7 ",,," DID=0 MI="*,,," +BUFFER: BN="sps2_basement\hardware\sbios\bios.c""""" +VIEW: LN=.2266 CL=46 LE=0 CX=51 CY=32 WI=140 BI=2 HT=0 HN=0 HF=0 HC=4 HB=4 +WINDOW: 1 22 1474 920 0 0 N WF=0 WT=10 ",,," DID=0 MI="*,,," +BUFFER: BN="sps2_basement\core\base\assert.h""""" +VIEW: LN=.17 CL=19 LE=0 CX=23 CY=4 WI=179 BI=9 HT=0 HN=0 HF=0 HC=4 HB=4 +WINDOW: 1 22 1474 920 0 0 N WF=0 WT=6 ",,," DID=0 MI="*,,," +BUFFER: BN="sps2_basement\hardware\sbios\sbios.h""""" +VIEW: LN=.13693 CL=32 LE=0 CX=37 CY=27 WI=131 BI=1 HT=0 HN=0 HF=0 HC=4 HB=4 +MDISTATE: 1 +AAAAAwAAAAIAAAAB2gAAAAIAMAAAAAAAAAA1AAAHfwAAA+MAAAAAAAAAAAAAB38AAAQPAAAAAuoAAAaKAAAAAvsAAAAJAAAACQAAAAcAAAAAAAAAAwAAAAgAAAAGAAAABQAAAAQAAAACAAAAAfsAAAAJAAAACQAAAAAAAAAGAAAABQAAAAgAAAAEAAAAAwAAAAcAAAACAAAAAfwAAAClAAAAAJgAMQAwADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABjAG8AcgBlAFwAYgBhAHMAZQBcAGEAcwBzAGUAcgB0AC4AaAAA/////wAA/AAAAK0AAAAAoAAzADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABjAG8AcgBlAFwAYgBhAHMAZQBcAGIAYQBzAGkAYwBDAG8AbgBmAGkAZwAuAGgAAP////8AAPwAAACrAAAAAJ4ANAA6ADoAOgBDADoAXABNAGkAbgBHAFcAXABtAHMAeQBzAFwAMQAuADAAXABoAG8AbQBlAFwAYgB1AGkAbABkAFwAVwBvAHIAawBTAHAAYQBjAGUAXABzAHAAcwAyAF8AYgBhAHMAZQBtAGUAbgB0AFwAYwBvAHIAZQBcAGIAYQBzAGUAXABiAGEAcwBpAGMAVAB5AHAAZQBzAC4AaAAA/////wAA/AAAAKkAAAAAnAA3ADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABoAGEAcgBkAHcAYQByAGUAXABzAGIAaQBvAHMAXABiAGkAbwBzAC4AYwAA/////wAA/AAAAKkAAAAAnAA4ADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABoAGEAcgBkAHcAYQByAGUAXABzAGIAaQBvAHMAXABiAGkAbwBzAC4AaAAA/////wAA/AAAAKkAAAAAnAAyADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABoAGEAcgBkAHcAYQByAGUAXABnAHMAXABnAGkAZgBcAGcAaQBmAC4AYwAA/////wAA/AAAAKkAAAAAnAA1ADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABoAGEAcgBkAHcAYQByAGUAXABnAHMAXABnAGkAZgBcAGcAaQBmAC4AaAAA/////wAA/AAAAKsAAAAAngA2ADoAOgA6AEMAOgBcAE0AaQBuAEcAVwBcAG0AcwB5AHMAXAAxAC4AMABcAGgAbwBtAGUAXABiAHUAaQBsAGQAXABXAG8AcgBrAFMAcABhAGMAZQBcAHMAcABzADIAXwBiAGEAcwBlAG0AZQBuAHQAXABoAGEAcgBkAHcAYQByAGUAXABzAGIAaQBvAHMAXABzAGIAaQBvAHMALgBoAQD/////AAH8AAAAswAAAACmADkAOgA6ADoAQwA6AFwATQBpAG4ARwBXAFwAbQBzAHkAcwBcADEALgAwAFwAaABvAG0AZQBcAGIAdQBpAGwAZABcAFcAbwByAGsAUwBwAGEAYwBlAFwAcwBwAHMAMgBfAGIAYQBzAGUAbQBlAG4AdABcAGgAYQByAGQAdwBhAHIAZQBcAHMAYgBpAG8AcwBcAHMAeQBzAGMAYQBsAGwAbgByAC4AaAAA/////wAAAAAAAA== +FILEHIST: 9 +sps2_basement\core\alg\crc.h +sps2_basement\core\base\basicTypes.h +sps2_basement\hardware\sbios\syscallnr.h +sps2_basement\hardware\sbios\bios.h +sps2_basement\hardware\gs\gif\gif.c +sps2_basement\hardware\gs\gif\gif.h +sps2_basement\hardware\sbios\bios.c +sps2_basement\core\base\assert.h +sps2_basement\hardware\sbios\sbios.h +ALLFILEHIST: 64 +sps2_basement\hardware\sbios\syscallnr.h +sps2_basement\hardware\sbios\sifdma.h +sps2_basement\core\alg\sha256.h +sps2_basement\core\alg\sha256.c +sps2_basement\core\alg\sha1.h +sps2_basement\core\alg\sha1.c +sps2_basement\hardware\sbus\sbus_regs.h +sps2_basement\hardware\sbus\sbus_priv.h +sps2_basement\hardware\sbus\sbus.h +sps2_basement\hardware\sbios\sbios.h +sps2_basement\hardware\sbus\ps2_sbus.c +Basic_test\packet2_types.h +Basic_test\packet2.h +Basic_test\packet.c +sps2_basement\core\alg\md5.h +sps2_basement\core\alg\md5.c +sps2_basement\hardware\sbus\iop\iop_regs.h +sps2_basement\hardware\gs\gif\gif.h +sps2_basement\hardware\graphic_synthesizer\gif.h +Basic_test\gif.h +sps2_basement\hardware\gs\gif\gif.c +sps2_basement\hardware\graphic_synthesizer\gif.c +Basic_test\gif.c +sps2_basement\core\base\errno.h +sps2_basement\hardware\sbus\ee_sbus.c +sps2_basement\hardware\emotion_engine\ee_regs.h +sps2_basement\hardware\ee\ee_regs.h +sps2_basement\hardware\sbus\ee_low.S +sps2_basement\hardware\ee\dmac\dma_packets.h +sps2_basement\hardware\dmac\dma_packets.h +sps2_basement\hardware\dma\dma_packets.h +Basic_test\dma_packets.h +sps2_basement\hardware\ee\dmac\dma_packets.c +sps2_basement\hardware\dmac\dma_packets.c +sps2_basement\hardware\dma\dma_packets.c +sps2_basement\hardware\ee\dmac\dma.h +sps2_basement\hardware\dmac\dma.h +sps2_basement\hardware\dma\dma.h +Basic_test\dma.h +sps2_basement\hardware\ee\dmac\dma.c +sps2_basement\hardware\dmac\dma.c +sps2_basement\hardware\dma\dma.c +Basic_test\dma.c +sps2_basement\core\alg\crc8.c +sps2_basement\core\alg\crc7.c +sps2_basement\core\alg\crc32.c +sps2_basement\core\alg\crc16.c +sps2_basement\core\alg\crc.h +sps2_basement\hardware\sbios\bios.S +sps2_basement\hardware\sbios\bios.h +sps2_basement\hardware\sbios\bios.c +sps2_basement\core\base\basicTypes.h +Z:\dr_frucht\lib\components\base\basicEventHeap.cpp +Z:\dr_frucht\lib\components\base\basicEvent.h +Z:\dr_frucht\lib\components\base\basicEvent.cpp +Z:\dr_frucht\lib\components\base\basicEngine.h +Z:\dr_frucht\lib\components\base\basicEngine.cpp +sps2_basement\core\base\basicConfig.h +Basic_test\Basic_test.h +Basic_test\Basic_test.c +Basic_test.c +sps2_basement\core\base\assert.h +Z:\dr_frucht\lib\App\argus\ArgusBackend.cpp +Z:\dr_frucht\lib\hardware\soc\general\3DLRF.h +DEBUG: 0 0 0 0 5 0 gdb +printf +strcpy +strcmp +std::* +boost::* +DEBUG2: 0 +TBCLASS: 0 0 diff --git a/SonyPS2.vtg b/SonyPS2.vtg new file mode 100644 index 0000000..04e32a5 Binary files /dev/null and b/SonyPS2.vtg differ diff --git a/sps2_basement/core/alg/crc.h b/sps2_basement/core/alg/crc.h new file mode 100644 index 0000000..87729d1 --- /dev/null +++ b/sps2_basement/core/alg/crc.h @@ -0,0 +1,48 @@ +/* + *========================================================================== + * + * crc.h + * + * Interface for the CRC algorithms. + * + *========================================================================== + * SPDX-License-Identifier: eCos-2.0 + *========================================================================== + *#####DESCRIPTIONBEGIN#### + * + * Author(s): Andrew Lunn + * Contributors: Andrew Lunn + * Date: 2002-08-06 + * Purpose: + * Description: + * + * This code is part of eCos (tm). + * + *####DESCRIPTIONEND#### + * + *========================================================================== + */ + +#ifndef _SERVICES_CRC_CRC_H_ +#define _SERVICES_CRC_CRC_H_ + +#include "../base/basicTypes.h" + +#define DYNAMIC_CRC_TABLE + +__externC const uint8_t crc7_syndrome_table[256]; +static inline uint8_t crc7_byte( uint8_t crc, uint8_t data ){ return crc7_syndrome_table[(crc << 1) ^ data]; } +__externC uint8_t crc7( uint8_t crc, uint8_t const *buffer, size_t len); + +#if __BYTE_ORDER == __LITTLE_ENDIAN + //__externC uint32_t crc32_le( uint32_t crc, uint8_t const *buffer, size_t len ); + //#define crc32( seed, data, length ) crc32_le( seed, (uint8_t const *) data, length ) +#else + //__externC uint32_t crc32_be( uint32_t crc, uint8_t const *buffer, size_t len ); + //#define crc32( seed, data, length ) crc32_be( seed, (uint8_t const *) data, length ) +#endif + +__externC uint32_t crc32( uint32_t crc, const uint8_t *p, uint32_t len ); + + +#endif /* _SERVICES_CRC_CRC_H_ */ diff --git a/sps2_basement/core/alg/crc16.c b/sps2_basement/core/alg/crc16.c new file mode 100644 index 0000000..c63fde9 --- /dev/null +++ b/sps2_basement/core/alg/crc16.c @@ -0,0 +1,75 @@ +/* + *========================================================================== + * + * crc16.c + * + * 16 bit CRC with polynomial x^16+x^12+x^5+1 + * + *========================================================================== + * SPDX-License-Identifier: eCos-2.0 + *========================================================================== + *#####DESCRIPTIONBEGIN#### + * + * Author(s): gthomas + * Contributors: gthomas,asl + * Date: 2001-01-31 + * Purpose: + * Description: + * + * This code is part of eCos (tm). + * + *####DESCRIPTIONEND#### + * + *========================================================================== + */ + +#include "crc.h" + +/* Table of CRC constants - implements x^16+x^12+x^5+1 */ +static const uint16_t crc16_tab[] = { + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, +}; + +uint16_t +cyg_crc16(unsigned char *buf, int len) +{ + int i; + uint16_t cksum; + + cksum = 0; + for (i = 0; i < len; i++) { + cksum = crc16_tab[((cksum>>8) ^ *buf++) & 0xFF] ^ (cksum << 8); + } + return cksum; +} diff --git a/sps2_basement/core/alg/crc32.c b/sps2_basement/core/alg/crc32.c new file mode 100644 index 0000000..0c9fbab --- /dev/null +++ b/sps2_basement/core/alg/crc32.c @@ -0,0 +1,254 @@ +/* + * This file is derived from crc32.c from the zlib-1.1.3 distribution + * by Jean-loup Gailly and Mark Adler. + */ + +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "crc.h" + +#ifdef USE_HOSTCC + //#include +#else + //#include +#endif + +//#include +//#include + +#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) + //#include +#endif + +//#include "u-boot/zlib.h" + +#define local static +#define ZEXPORT /* empty */ + +#define tole(x) cpu_to_le32(x) + +#ifdef DYNAMIC_CRC_TABLE + +local int crc_table_empty = 1; +local uint32_t crc_table[256]; +//local void make_crc_table OF((void)); + +/* + Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The table is simply the CRC of all possible eight bit values. This is all + the information needed to generate CRC's on data a byte at a time for all + combinations of CRC register values and incoming bytes. +*/ +local void make_crc_table( ){ + uint32_t c; + uint32_t n, k; + uint64_t poly = 0; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static const uint8_t p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* make exclusive-or pattern from polynomial (0xedb88320L) */ + for (n = 0; n < sizeof(p)/sizeof(uint8_t); n++) poly |= 1L << (31 - p[n]); + for (n = 0; n < 256; n++) { + c = n; + for (k = 0; k < 8; k++) c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[n] = tole(c); + }; + crc_table_empty = 0; +}; + +#else +/* ======================================================================== + * Table of CRC-32's of all single-byte values (made by make_crc_table) + */ + +local const uint32_t crc_table[256] = { +tole(0x00000000L), tole(0x77073096L), tole(0xee0e612cL), tole(0x990951baL), +tole(0x076dc419L), tole(0x706af48fL), tole(0xe963a535L), tole(0x9e6495a3L), +tole(0x0edb8832L), tole(0x79dcb8a4L), tole(0xe0d5e91eL), tole(0x97d2d988L), +tole(0x09b64c2bL), tole(0x7eb17cbdL), tole(0xe7b82d07L), tole(0x90bf1d91L), +tole(0x1db71064L), tole(0x6ab020f2L), tole(0xf3b97148L), tole(0x84be41deL), +tole(0x1adad47dL), tole(0x6ddde4ebL), tole(0xf4d4b551L), tole(0x83d385c7L), +tole(0x136c9856L), tole(0x646ba8c0L), tole(0xfd62f97aL), tole(0x8a65c9ecL), +tole(0x14015c4fL), tole(0x63066cd9L), tole(0xfa0f3d63L), tole(0x8d080df5L), +tole(0x3b6e20c8L), tole(0x4c69105eL), tole(0xd56041e4L), tole(0xa2677172L), +tole(0x3c03e4d1L), tole(0x4b04d447L), tole(0xd20d85fdL), tole(0xa50ab56bL), +tole(0x35b5a8faL), tole(0x42b2986cL), tole(0xdbbbc9d6L), tole(0xacbcf940L), +tole(0x32d86ce3L), tole(0x45df5c75L), tole(0xdcd60dcfL), tole(0xabd13d59L), +tole(0x26d930acL), tole(0x51de003aL), tole(0xc8d75180L), tole(0xbfd06116L), +tole(0x21b4f4b5L), tole(0x56b3c423L), tole(0xcfba9599L), tole(0xb8bda50fL), +tole(0x2802b89eL), tole(0x5f058808L), tole(0xc60cd9b2L), tole(0xb10be924L), +tole(0x2f6f7c87L), tole(0x58684c11L), tole(0xc1611dabL), tole(0xb6662d3dL), +tole(0x76dc4190L), tole(0x01db7106L), tole(0x98d220bcL), tole(0xefd5102aL), +tole(0x71b18589L), tole(0x06b6b51fL), tole(0x9fbfe4a5L), tole(0xe8b8d433L), +tole(0x7807c9a2L), tole(0x0f00f934L), tole(0x9609a88eL), tole(0xe10e9818L), +tole(0x7f6a0dbbL), tole(0x086d3d2dL), tole(0x91646c97L), tole(0xe6635c01L), +tole(0x6b6b51f4L), tole(0x1c6c6162L), tole(0x856530d8L), tole(0xf262004eL), +tole(0x6c0695edL), tole(0x1b01a57bL), tole(0x8208f4c1L), tole(0xf50fc457L), +tole(0x65b0d9c6L), tole(0x12b7e950L), tole(0x8bbeb8eaL), tole(0xfcb9887cL), +tole(0x62dd1ddfL), tole(0x15da2d49L), tole(0x8cd37cf3L), tole(0xfbd44c65L), +tole(0x4db26158L), tole(0x3ab551ceL), tole(0xa3bc0074L), tole(0xd4bb30e2L), +tole(0x4adfa541L), tole(0x3dd895d7L), tole(0xa4d1c46dL), tole(0xd3d6f4fbL), +tole(0x4369e96aL), tole(0x346ed9fcL), tole(0xad678846L), tole(0xda60b8d0L), +tole(0x44042d73L), tole(0x33031de5L), tole(0xaa0a4c5fL), tole(0xdd0d7cc9L), +tole(0x5005713cL), tole(0x270241aaL), tole(0xbe0b1010L), tole(0xc90c2086L), +tole(0x5768b525L), tole(0x206f85b3L), tole(0xb966d409L), tole(0xce61e49fL), +tole(0x5edef90eL), tole(0x29d9c998L), tole(0xb0d09822L), tole(0xc7d7a8b4L), +tole(0x59b33d17L), tole(0x2eb40d81L), tole(0xb7bd5c3bL), tole(0xc0ba6cadL), +tole(0xedb88320L), tole(0x9abfb3b6L), tole(0x03b6e20cL), tole(0x74b1d29aL), +tole(0xead54739L), tole(0x9dd277afL), tole(0x04db2615L), tole(0x73dc1683L), +tole(0xe3630b12L), tole(0x94643b84L), tole(0x0d6d6a3eL), tole(0x7a6a5aa8L), +tole(0xe40ecf0bL), tole(0x9309ff9dL), tole(0x0a00ae27L), tole(0x7d079eb1L), +tole(0xf00f9344L), tole(0x8708a3d2L), tole(0x1e01f268L), tole(0x6906c2feL), +tole(0xf762575dL), tole(0x806567cbL), tole(0x196c3671L), tole(0x6e6b06e7L), +tole(0xfed41b76L), tole(0x89d32be0L), tole(0x10da7a5aL), tole(0x67dd4accL), +tole(0xf9b9df6fL), tole(0x8ebeeff9L), tole(0x17b7be43L), tole(0x60b08ed5L), +tole(0xd6d6a3e8L), tole(0xa1d1937eL), tole(0x38d8c2c4L), tole(0x4fdff252L), +tole(0xd1bb67f1L), tole(0xa6bc5767L), tole(0x3fb506ddL), tole(0x48b2364bL), +tole(0xd80d2bdaL), tole(0xaf0a1b4cL), tole(0x36034af6L), tole(0x41047a60L), +tole(0xdf60efc3L), tole(0xa867df55L), tole(0x316e8eefL), tole(0x4669be79L), +tole(0xcb61b38cL), tole(0xbc66831aL), tole(0x256fd2a0L), tole(0x5268e236L), +tole(0xcc0c7795L), tole(0xbb0b4703L), tole(0x220216b9L), tole(0x5505262fL), +tole(0xc5ba3bbeL), tole(0xb2bd0b28L), tole(0x2bb45a92L), tole(0x5cb36a04L), +tole(0xc2d7ffa7L), tole(0xb5d0cf31L), tole(0x2cd99e8bL), tole(0x5bdeae1dL), +tole(0x9b64c2b0L), tole(0xec63f226L), tole(0x756aa39cL), tole(0x026d930aL), +tole(0x9c0906a9L), tole(0xeb0e363fL), tole(0x72076785L), tole(0x05005713L), +tole(0x95bf4a82L), tole(0xe2b87a14L), tole(0x7bb12baeL), tole(0x0cb61b38L), +tole(0x92d28e9bL), tole(0xe5d5be0dL), tole(0x7cdcefb7L), tole(0x0bdbdf21L), +tole(0x86d3d2d4L), tole(0xf1d4e242L), tole(0x68ddb3f8L), tole(0x1fda836eL), +tole(0x81be16cdL), tole(0xf6b9265bL), tole(0x6fb077e1L), tole(0x18b74777L), +tole(0x88085ae6L), tole(0xff0f6a70L), tole(0x66063bcaL), tole(0x11010b5cL), +tole(0x8f659effL), tole(0xf862ae69L), tole(0x616bffd3L), tole(0x166ccf45L), +tole(0xa00ae278L), tole(0xd70dd2eeL), tole(0x4e048354L), tole(0x3903b3c2L), +tole(0xa7672661L), tole(0xd06016f7L), tole(0x4969474dL), tole(0x3e6e77dbL), +tole(0xaed16a4aL), tole(0xd9d65adcL), tole(0x40df0b66L), tole(0x37d83bf0L), +tole(0xa9bcae53L), tole(0xdebb9ec5L), tole(0x47b2cf7fL), tole(0x30b5ffe9L), +tole(0xbdbdf21cL), tole(0xcabac28aL), tole(0x53b39330L), tole(0x24b4a3a6L), +tole(0xbad03605L), tole(0xcdd70693L), tole(0x54de5729L), tole(0x23d967bfL), +tole(0xb3667a2eL), tole(0xc4614ab8L), tole(0x5d681b02L), tole(0x2a6f2b94L), +tole(0xb40bbe37L), tole(0xc30c8ea1L), tole(0x5a05df1bL), tole(0x2d02ef8dL) +}; +#endif + +#if 0 +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const uint32_t * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) make_crc_table(); +#endif + return (const uint32_t *)crc_table; +} +#endif + +/* ========================================================================= */ +# if __BYTE_ORDER == __LITTLE_ENDIAN +# define DO_CRC(x) crc = tab[(crc ^ (x)) & 255] ^ (crc >> 8) +# else +# define DO_CRC(x) crc = tab[((crc >> 24) ^ (x)) & 255] ^ (crc << 8) +# endif + +/* ========================================================================= */ + +/* No ones complement version. JFFS2 (and other things ?) + * don't use ones compliment in their CRC calculations. + */ +uint32_t ZEXPORT crc32_no_comp(uint32_t crc, const uint8_t *buf, uint32_t len){ + + const uint32_t *tab = crc_table; + const uint32_t *b =(const uint32_t *)buf; + size_t rem_len; +#ifdef DYNAMIC_CRC_TABLE + if( crc_table_empty ) make_crc_table(); +#endif + crc = cpu_to_le32(crc); + /* Align it */ + if(((uint32_t)b) & 3 && len) { + uint8_t *p = (uint8_t *)b; + do{ + DO_CRC(*p++); + } while ((--len) && ((uint32_t)p)&3); + b = (uint32_t *)p; + }; + + rem_len = len & 3; + len = len >> 2; + for (--b; len; --len) { + /* load data 32 bits wide, xor data 32 bits wide. */ + crc ^= *++b; /* use pre increment for speed */ + DO_CRC(0); + DO_CRC(0); + DO_CRC(0); + DO_CRC(0); + } + len = rem_len; + /* And the last few bytes */ + if (len) { + uint8_t *p = (uint8_t *)(b + 1) - 1; + do { + DO_CRC(*++p); /* use pre increment for speed */ + } while (--len); + } + + return le32_to_cpu(crc); +} +#undef DO_CRC + +uint32_t ZEXPORT crc32 (uint32_t crc, const uint8_t *p, uint32_t len){ + return crc32_no_comp(crc ^ 0xffffffffL, p, len) ^ 0xffffffffL; +} + +/* + * Calculate the crc32 checksum triggering the watchdog every 'chunk_sz' bytes + * of input. + */ +uint32_t ZEXPORT crc32_wd (uint32_t crc, const uint8_t *buf, uint32_t len, uint32_t chunk_sz){ + +#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) + const unsigned char *end, *curr; + int chunk; + + curr = buf; + end = buf + len; + while (curr < end) { + chunk = end - curr; + if (chunk > chunk_sz) + chunk = chunk_sz; + crc = crc32 (crc, curr, chunk); + curr += chunk; + WATCHDOG_RESET (); + } +#else + crc = crc32 (crc, buf, len); +#endif + return crc; +}; + +void crc32_wd_buf(const uint8_t *input, uint32_t ilen, uint8_t *output, uint32_t chunk_sz ){ + uint32_t crc; + crc = crc32_wd( 0, input, ilen, chunk_sz ); + crc = cpu_to_be32( crc ); //htonl -> Net Byte Order is BE! + memcpy( output, &crc, sizeof(crc)); +}; diff --git a/sps2_basement/core/alg/crc7.c b/sps2_basement/core/alg/crc7.c new file mode 100644 index 0000000..8809d9b --- /dev/null +++ b/sps2_basement/core/alg/crc7.c @@ -0,0 +1,60 @@ +/* + * crc7.c + * + * This source code is licensed under the GNU General Public License, + * Version 2. See the file COPYING for more details. + */ + +//#include +//#include +#include "crc.h" + +/* Table for CRC-7 (polynomial x^7 + x^3 + 1) */ +const uint8_t crc7_syndrome_table[256] = { + 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, + 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, + 0x19, 0x10, 0x0b, 0x02, 0x3d, 0x34, 0x2f, 0x26, + 0x51, 0x58, 0x43, 0x4a, 0x75, 0x7c, 0x67, 0x6e, + 0x32, 0x3b, 0x20, 0x29, 0x16, 0x1f, 0x04, 0x0d, + 0x7a, 0x73, 0x68, 0x61, 0x5e, 0x57, 0x4c, 0x45, + 0x2b, 0x22, 0x39, 0x30, 0x0f, 0x06, 0x1d, 0x14, + 0x63, 0x6a, 0x71, 0x78, 0x47, 0x4e, 0x55, 0x5c, + 0x64, 0x6d, 0x76, 0x7f, 0x40, 0x49, 0x52, 0x5b, + 0x2c, 0x25, 0x3e, 0x37, 0x08, 0x01, 0x1a, 0x13, + 0x7d, 0x74, 0x6f, 0x66, 0x59, 0x50, 0x4b, 0x42, + 0x35, 0x3c, 0x27, 0x2e, 0x11, 0x18, 0x03, 0x0a, + 0x56, 0x5f, 0x44, 0x4d, 0x72, 0x7b, 0x60, 0x69, + 0x1e, 0x17, 0x0c, 0x05, 0x3a, 0x33, 0x28, 0x21, + 0x4f, 0x46, 0x5d, 0x54, 0x6b, 0x62, 0x79, 0x70, + 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, + 0x41, 0x48, 0x53, 0x5a, 0x65, 0x6c, 0x77, 0x7e, + 0x09, 0x00, 0x1b, 0x12, 0x2d, 0x24, 0x3f, 0x36, + 0x58, 0x51, 0x4a, 0x43, 0x7c, 0x75, 0x6e, 0x67, + 0x10, 0x19, 0x02, 0x0b, 0x34, 0x3d, 0x26, 0x2f, + 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, + 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, + 0x6a, 0x63, 0x78, 0x71, 0x4e, 0x47, 0x5c, 0x55, + 0x22, 0x2b, 0x30, 0x39, 0x06, 0x0f, 0x14, 0x1d, + 0x25, 0x2c, 0x37, 0x3e, 0x01, 0x08, 0x13, 0x1a, + 0x6d, 0x64, 0x7f, 0x76, 0x49, 0x40, 0x5b, 0x52, + 0x3c, 0x35, 0x2e, 0x27, 0x18, 0x11, 0x0a, 0x03, + 0x74, 0x7d, 0x66, 0x6f, 0x50, 0x59, 0x42, 0x4b, + 0x17, 0x1e, 0x05, 0x0c, 0x33, 0x3a, 0x21, 0x28, + 0x5f, 0x56, 0x4d, 0x44, 0x7b, 0x72, 0x69, 0x60, + 0x0e, 0x07, 0x1c, 0x15, 0x2a, 0x23, 0x38, 0x31, + 0x46, 0x4f, 0x54, 0x5d, 0x62, 0x6b, 0x70, 0x79 +}; + +/** + * crc7 - update the CRC7 for the data buffer + * @crc: previous CRC7 value + * @buffer: data pointer + * @len: number of bytes in the buffer + * Context: any + * + * Returns the updated CRC7 value. + */ +uint8_t crc7( uint8_t crc, const uint8_t *buffer, size_t len ){ + while (len--) crc = crc7_byte( crc, *buffer++ ); + return crc; +}; diff --git a/sps2_basement/core/alg/crc8.c b/sps2_basement/core/alg/crc8.c new file mode 100644 index 0000000..cca86c9 --- /dev/null +++ b/sps2_basement/core/alg/crc8.c @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2013 Google, Inc + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include "crc.h" + +uint32_t crc8(const uint8_t *vptr, size_t len ){ + const uint8_t * data = vptr; + uint32_t crc = 0; + uint32_t i, j; + for( j = len; j; j--, data++ ){ + crc ^= (*data << 8); + for (i = 8; i; i--) { + if (crc & 0x8000) crc ^= (0x1070 << 3); + crc <<= 1; + }; + }; + return (crc >> 8) & 0xff; +}; + diff --git a/sps2_basement/core/alg/md5.c b/sps2_basement/core/alg/md5.c new file mode 100644 index 0000000..db91fe2 --- /dev/null +++ b/sps2_basement/core/alg/md5.c @@ -0,0 +1,295 @@ +/* + * This file was transplanted with slight modifications from Linux sources + * (fs/cifs/md5.c) into U-Boot by Bartlomiej Sieka . + */ + +/* + * This code implements the MD5 message-digest algorithm. + * The algorithm is due to Ron Rivest. This code was + * written by Colin Plumb in 1993, no copyright is claimed. + * This code is in the public domain; do with it what you wish. + * + * Equivalent code is available from RSA Data Security, Inc. + * This code has been tested against that, and is equivalent, + * except that you don't need to include two pages of legalese + * with every copy. + * + * To compute the message digest of a chunk of bytes, declare an + * MD5Context structure, pass it to MD5Init, call MD5Update as + * needed on buffers full of bytes, and then call MD5Final, which + * will fill a supplied 16-byte array with the digest. + */ + +/* This code slightly modified to fit into Samba by + abartlet@samba.org Jun 2001 + and to fit the cifs vfs by + Steve French sfrench@us.ibm.com */ + +#include "md5.h" + +static void MD5Transform( uint32_t buf[4], uint32_t const in[16] ); + +/* + * Note: this code is harmless on little-endian machines. + */ +static void byteReverse( uint8_t *buf, unsigned longs){ + uint32_t t; + do { + t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 | + ((unsigned) buf[1] << 8 | buf[0]); + *(uint32_t *) buf = t; + buf += 4; + } while (--longs); +}; + +/* + * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious + * initialization constants. + */ +static void MD5Init( struct MD5Context *ctx ){ + + ctx->buf[0] = 0x67452301; + ctx->buf[1] = 0xefcdab89; + ctx->buf[2] = 0x98badcfe; + ctx->buf[3] = 0x10325476; + + ctx->bits[0] = 0; + ctx->bits[1] = 0; +}; + +/* + * Update context to reflect the concatenation of another buffer full + * of bytes. + */ +static void MD5Update( struct MD5Context *ctx, uint8_t const *buf, unsigned len ){ + register uint32_t t; + + /* Update bitcount */ + + t = ctx->bits[0]; + if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) + ctx->bits[1]++; /* Carry from low to high */ + ctx->bits[1] += len >> 29; + + t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ + + /* Handle any leading odd-sized chunks */ + + if (t) { + unsigned char *p = (unsigned char *) ctx->in + t; + + t = 64 - t; + if (len < t) { + memmove(p, buf, len); + return; + } + memmove(p, buf, t); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32_t *) ctx->in); + buf += t; + len -= t; + } + /* Process data in 64-byte chunks */ + + while (len >= 64) { + memmove(ctx->in, buf, 64); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32_t *) ctx->in); + buf += 64; + len -= 64; + } + + /* Handle any remaining bytes of data. */ + + memmove(ctx->in, buf, len); +} + +/* + * Final wrapup - pad to 64-byte boundary with the bit pattern + * 1 0* (64-bit count of bits processed, MSB-first) + */ +static void MD5Final( uint8_t digest[16], struct MD5Context *ctx ){ + uint32_t count; + uint8_t * p; + + /* Compute number of bytes mod 64 */ + count = (ctx->bits[0] >> 3) & 0x3F; + + /* Set the first char of padding to 0x80. This is safe since there is + always at least one byte free */ + p = ctx->in + count; + *p++ = 0x80; + + /* Bytes of padding needed to make 64 bytes */ + count = 64 - 1 - count; + + /* Pad out to 56 mod 64 */ + if (count < 8) { + /* Two lots of padding: Pad the first block to 64 bytes */ + memset(p, 0, count); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32_t *) ctx->in); + + /* Now fill the next block with 56 bytes */ + memset(ctx->in, 0, 56); + } else { + /* Pad block to 56 bytes */ + memset(p, 0, count - 8); + } + byteReverse(ctx->in, 14); + + /* Append length in bits and transform */ + ctx->in32[14] = ctx->bits[0]; + ctx->in32[15] = ctx->bits[1]; + + MD5Transform(ctx->buf, (uint32_t *) ctx->in); + byteReverse((unsigned char *) ctx->buf, 4); + memmove(digest, ctx->buf, 16); + memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */ +}; + +/* The four core functions - F1 is optimized somewhat */ + +/* #define F1(x, y, z) (x & y | ~x & z) */ +#define F1(x, y, z) (z ^ (x & (y ^ z))) +#define F2(x, y, z) F1(z, x, y) +#define F3(x, y, z) (x ^ y ^ z) +#define F4(x, y, z) (y ^ (x | ~z)) + +/* This is the central step in the MD5 algorithm. */ +#define MD5STEP(f, w, x, y, z, data, s) \ + ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) + +/* + * The core of the MD5 algorithm, this alters an existing MD5 hash to + * reflect the addition of 16 longwords of new data. MD5Update blocks + * the data and converts bytes into longwords for this routine. + */ +static void MD5Transform( uint32_t buf[4], uint32_t const in[16] ){ + register uint32_t a, b, c, d; + + a = buf[0]; + b = buf[1]; + c = buf[2]; + d = buf[3]; + + MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); + MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); + MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); + MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); + MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); + MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); + MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); + MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); + MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); + MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); + MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); + MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); + MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); + MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); + MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); + MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); + + MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); + MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); + MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); + MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); + MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); + MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); + MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); + MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); + MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); + MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); + MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); + MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); + MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); + MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); + MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); + MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); + + MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); + MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); + MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); + MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); + MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); + MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); + MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); + MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); + MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); + MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); + MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); + MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); + MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); + MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); + MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); + MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); + + MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); + MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); + MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); + MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); + MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); + MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); + MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); + MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); + MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); + MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); + MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); + MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); + MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); + MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); + MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); + MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +}; + +/* + * Calculate and store in 'output' the MD5 digest of 'len' bytes at + * 'input'. 'output' must have enough space to hold 16 bytes. + */ +void md5( uint8_t *input, int len, uint8_t output[16] ){ + struct MD5Context context; + MD5Init(&context); + MD5Update(&context, input, len); + MD5Final(output, &context); +} + + +/* + * Calculate and store in 'output' the MD5 digest of 'len' bytes at 'input'. + * 'output' must have enough space to hold 16 bytes. If 'chunk' Trigger the + * watchdog every 'chunk_sz' bytes of input processed. + */ +void +md5_wd (unsigned char *input, int len, unsigned char output[16], + unsigned int chunk_sz) +{ + struct MD5Context context; +#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) + unsigned char *end, *curr; + int chunk; +#endif + + MD5Init(&context); + +#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) + curr = input; + end = input + len; + while (curr < end) { + chunk = end - curr; + if (chunk > chunk_sz) + chunk = chunk_sz; + MD5Update(&context, curr, chunk); + curr += chunk; + WATCHDOG_RESET (); + } +#else + MD5Update(&context, input, len); +#endif + + MD5Final(output, &context); +} diff --git a/sps2_basement/core/alg/md5.h b/sps2_basement/core/alg/md5.h new file mode 100644 index 0000000..d765605 --- /dev/null +++ b/sps2_basement/core/alg/md5.h @@ -0,0 +1,34 @@ +/* + * This file was transplanted with slight modifications from Linux sources + * (fs/cifs/md5.h) into U-Boot by Bartlomiej Sieka . + */ + +#ifndef _MD5_H +#define _MD5_H + +#include "../base/basicTypes.h" + +struct MD5Context { + uint32_t buf[4]; + uint32_t bits[2]; + union { + uint8_t in[64]; + uint32_t in32[16]; + }; +}; + +/* + * Calculate and store in 'output' the MD5 digest of 'len' bytes at + * 'input'. 'output' must have enough space to hold 16 bytes. + */ +void md5 (unsigned char *input, int len, unsigned char output[16]); + +/* + * Calculate and store in 'output' the MD5 digest of 'len' bytes at 'input'. + * 'output' must have enough space to hold 16 bytes. If 'chunk' Trigger the + * watchdog every 'chunk_sz' bytes of input processed. + */ +void md5_wd (unsigned char *input, int len, unsigned char output[16], + unsigned int chunk_sz); + +#endif /* _MD5_H */ diff --git a/sps2_basement/core/alg/sha1.c b/sps2_basement/core/alg/sha1.c new file mode 100644 index 0000000..6cc351c --- /dev/null +++ b/sps2_basement/core/alg/sha1.c @@ -0,0 +1,455 @@ +/* + * Heiko Schocher, DENX Software Engineering, hs@denx.de. + * based on: + * FIPS-180-1 compliant SHA-1 implementation + * + * Copyright (C) 2003-2006 Christophe Devine + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License, version 2.1 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +/* + * The SHA-1 standard was published by NIST in 1993. + * + * http://www.itl.nist.gov/fipspubs/fip180-1.htm + */ + +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif + +//#ifndef USE_HOSTCC +//#include +//#include +//#else +//#include +//#endif /* USE_HOSTCC */ +//#include +#include "sha1.h" + +/* + * 32-bit integer manipulation macros (big endian) + */ +#ifndef GET_UINT32_BE +#define GET_UINT32_BE(n,b,i) { \ + (n) = ( (unsigned long) (b)[(i) ] << 24 ) \ + | ( (unsigned long) (b)[(i) + 1] << 16 ) \ + | ( (unsigned long) (b)[(i) + 2] << 8 ) \ + | ( (unsigned long) (b)[(i) + 3] ); \ +} +#endif +#ifndef PUT_UINT32_BE +#define PUT_UINT32_BE(n,b,i) { \ + (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ + (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ + (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ + (b)[(i) + 3] = (unsigned char) ( (n) ); \ +} +#endif + +/* + * SHA-1 context setup + */ +void sha1_starts (sha1_context * ctx) +{ + ctx->total[0] = 0; + ctx->total[1] = 0; + + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xEFCDAB89; + ctx->state[2] = 0x98BADCFE; + ctx->state[3] = 0x10325476; + ctx->state[4] = 0xC3D2E1F0; +} + +static void sha1_process(sha1_context *ctx, const unsigned char data[64]) +{ + unsigned long temp, W[16], A, B, C, D, E; + + GET_UINT32_BE (W[0], data, 0); + GET_UINT32_BE (W[1], data, 4); + GET_UINT32_BE (W[2], data, 8); + GET_UINT32_BE (W[3], data, 12); + GET_UINT32_BE (W[4], data, 16); + GET_UINT32_BE (W[5], data, 20); + GET_UINT32_BE (W[6], data, 24); + GET_UINT32_BE (W[7], data, 28); + GET_UINT32_BE (W[8], data, 32); + GET_UINT32_BE (W[9], data, 36); + GET_UINT32_BE (W[10], data, 40); + GET_UINT32_BE (W[11], data, 44); + GET_UINT32_BE (W[12], data, 48); + GET_UINT32_BE (W[13], data, 52); + GET_UINT32_BE (W[14], data, 56); + GET_UINT32_BE (W[15], data, 60); + +#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) + +#define R(t) ( \ + temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ \ + W[(t - 14) & 0x0F] ^ W[ t & 0x0F], \ + ( W[t & 0x0F] = S(temp,1) ) \ +) + +#define P(a,b,c,d,e,x) { \ + e += S(a,5) + F(b,c,d) + K + x; b = S(b,30); \ +} + + A = ctx->state[0]; + B = ctx->state[1]; + C = ctx->state[2]; + D = ctx->state[3]; + E = ctx->state[4]; + +#define F(x,y,z) (z ^ (x & (y ^ z))) +#define K 0x5A827999 + + P (A, B, C, D, E, W[0]); + P (E, A, B, C, D, W[1]); + P (D, E, A, B, C, W[2]); + P (C, D, E, A, B, W[3]); + P (B, C, D, E, A, W[4]); + P (A, B, C, D, E, W[5]); + P (E, A, B, C, D, W[6]); + P (D, E, A, B, C, W[7]); + P (C, D, E, A, B, W[8]); + P (B, C, D, E, A, W[9]); + P (A, B, C, D, E, W[10]); + P (E, A, B, C, D, W[11]); + P (D, E, A, B, C, W[12]); + P (C, D, E, A, B, W[13]); + P (B, C, D, E, A, W[14]); + P (A, B, C, D, E, W[15]); + P (E, A, B, C, D, R (16)); + P (D, E, A, B, C, R (17)); + P (C, D, E, A, B, R (18)); + P (B, C, D, E, A, R (19)); + +#undef K +#undef F + +#define F(x,y,z) (x ^ y ^ z) +#define K 0x6ED9EBA1 + + P (A, B, C, D, E, R (20)); + P (E, A, B, C, D, R (21)); + P (D, E, A, B, C, R (22)); + P (C, D, E, A, B, R (23)); + P (B, C, D, E, A, R (24)); + P (A, B, C, D, E, R (25)); + P (E, A, B, C, D, R (26)); + P (D, E, A, B, C, R (27)); + P (C, D, E, A, B, R (28)); + P (B, C, D, E, A, R (29)); + P (A, B, C, D, E, R (30)); + P (E, A, B, C, D, R (31)); + P (D, E, A, B, C, R (32)); + P (C, D, E, A, B, R (33)); + P (B, C, D, E, A, R (34)); + P (A, B, C, D, E, R (35)); + P (E, A, B, C, D, R (36)); + P (D, E, A, B, C, R (37)); + P (C, D, E, A, B, R (38)); + P (B, C, D, E, A, R (39)); + +#undef K +#undef F + +#define F(x,y,z) ((x & y) | (z & (x | y))) +#define K 0x8F1BBCDC + + P (A, B, C, D, E, R (40)); + P (E, A, B, C, D, R (41)); + P (D, E, A, B, C, R (42)); + P (C, D, E, A, B, R (43)); + P (B, C, D, E, A, R (44)); + P (A, B, C, D, E, R (45)); + P (E, A, B, C, D, R (46)); + P (D, E, A, B, C, R (47)); + P (C, D, E, A, B, R (48)); + P (B, C, D, E, A, R (49)); + P (A, B, C, D, E, R (50)); + P (E, A, B, C, D, R (51)); + P (D, E, A, B, C, R (52)); + P (C, D, E, A, B, R (53)); + P (B, C, D, E, A, R (54)); + P (A, B, C, D, E, R (55)); + P (E, A, B, C, D, R (56)); + P (D, E, A, B, C, R (57)); + P (C, D, E, A, B, R (58)); + P (B, C, D, E, A, R (59)); + +#undef K +#undef F + +#define F(x,y,z) (x ^ y ^ z) +#define K 0xCA62C1D6 + + P (A, B, C, D, E, R (60)); + P (E, A, B, C, D, R (61)); + P (D, E, A, B, C, R (62)); + P (C, D, E, A, B, R (63)); + P (B, C, D, E, A, R (64)); + P (A, B, C, D, E, R (65)); + P (E, A, B, C, D, R (66)); + P (D, E, A, B, C, R (67)); + P (C, D, E, A, B, R (68)); + P (B, C, D, E, A, R (69)); + P (A, B, C, D, E, R (70)); + P (E, A, B, C, D, R (71)); + P (D, E, A, B, C, R (72)); + P (C, D, E, A, B, R (73)); + P (B, C, D, E, A, R (74)); + P (A, B, C, D, E, R (75)); + P (E, A, B, C, D, R (76)); + P (D, E, A, B, C, R (77)); + P (C, D, E, A, B, R (78)); + P (B, C, D, E, A, R (79)); + +#undef K +#undef F + + ctx->state[0] += A; + ctx->state[1] += B; + ctx->state[2] += C; + ctx->state[3] += D; + ctx->state[4] += E; +} + +/* + * SHA-1 process buffer + */ +void sha1_update(sha1_context *ctx, const unsigned char *input, + unsigned int ilen) +{ + int fill; + unsigned long left; + + if (ilen <= 0) + return; + + left = ctx->total[0] & 0x3F; + fill = 64 - left; + + ctx->total[0] += ilen; + ctx->total[0] &= 0xFFFFFFFF; + + if (ctx->total[0] < (unsigned long) ilen) + ctx->total[1]++; + + if (left && ilen >= fill) { + memcpy ((void *) (ctx->buffer + left), (void *) input, fill); + sha1_process (ctx, ctx->buffer); + input += fill; + ilen -= fill; + left = 0; + } + + while (ilen >= 64) { + sha1_process (ctx, input); + input += 64; + ilen -= 64; + } + + if (ilen > 0) { + memcpy ((void *) (ctx->buffer + left), (void *) input, ilen); + } +} + +static const unsigned char sha1_padding[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +/* + * SHA-1 final digest + */ +void sha1_finish (sha1_context * ctx, unsigned char output[20]) +{ + unsigned long last, padn; + unsigned long high, low; + unsigned char msglen[8]; + + high = (ctx->total[0] >> 29) + | (ctx->total[1] << 3); + low = (ctx->total[0] << 3); + + PUT_UINT32_BE (high, msglen, 0); + PUT_UINT32_BE (low, msglen, 4); + + last = ctx->total[0] & 0x3F; + padn = (last < 56) ? (56 - last) : (120 - last); + + sha1_update (ctx, (unsigned char *) sha1_padding, padn); + sha1_update (ctx, msglen, 8); + + PUT_UINT32_BE (ctx->state[0], output, 0); + PUT_UINT32_BE (ctx->state[1], output, 4); + PUT_UINT32_BE (ctx->state[2], output, 8); + PUT_UINT32_BE (ctx->state[3], output, 12); + PUT_UINT32_BE (ctx->state[4], output, 16); +} + +/* + * Output = SHA-1( input buffer ) + */ +void sha1_csum(const unsigned char *input, unsigned int ilen, + unsigned char *output) +{ + sha1_context ctx; + + sha1_starts (&ctx); + sha1_update (&ctx, input, ilen); + sha1_finish (&ctx, output); +} + +/* + * Output = SHA-1( input buffer ). Trigger the watchdog every 'chunk_sz' + * bytes of input processed. + */ +void sha1_csum_wd(const unsigned char *input, unsigned int ilen, + unsigned char *output, unsigned int chunk_sz) +{ + sha1_context ctx; +#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) + const unsigned char *end, *curr; + int chunk; +#endif + + sha1_starts (&ctx); + +#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) + curr = input; + end = input + ilen; + while (curr < end) { + chunk = end - curr; + if (chunk > chunk_sz) + chunk = chunk_sz; + sha1_update (&ctx, curr, chunk); + curr += chunk; + WATCHDOG_RESET (); + } +#else + sha1_update (&ctx, input, ilen); +#endif + + sha1_finish (&ctx, output); +} + +/* + * Output = HMAC-SHA-1( input buffer, hmac key ) + */ +void sha1_hmac(const unsigned char *key, int keylen, + const unsigned char *input, unsigned int ilen, + unsigned char *output) +{ + int i; + sha1_context ctx; + unsigned char k_ipad[64]; + unsigned char k_opad[64]; + unsigned char tmpbuf[20]; + + memset (k_ipad, 0x36, 64); + memset (k_opad, 0x5C, 64); + + for (i = 0; i < keylen; i++) { + if (i >= 64) + break; + + k_ipad[i] ^= key[i]; + k_opad[i] ^= key[i]; + } + + sha1_starts (&ctx); + sha1_update (&ctx, k_ipad, 64); + sha1_update (&ctx, input, ilen); + sha1_finish (&ctx, tmpbuf); + + sha1_starts (&ctx); + sha1_update (&ctx, k_opad, 64); + sha1_update (&ctx, tmpbuf, 20); + sha1_finish (&ctx, output); + + memset (k_ipad, 0, 64); + memset (k_opad, 0, 64); + memset (tmpbuf, 0, 20); + memset (&ctx, 0, sizeof (sha1_context)); +} + +static const char _sha1_src[] = "_sha1_src"; + +#ifdef SELF_TEST +/* + * FIPS-180-1 test vectors + */ +static const char sha1_test_str[3][57] = { + {"abc"}, + {"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"}, + {""} +}; + +static const unsigned char sha1_test_sum[3][20] = { + {0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, + 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D}, + {0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE, + 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1}, + {0x34, 0xAA, 0x97, 0x3C, 0xD4, 0xC4, 0xDA, 0xA4, 0xF6, 0x1E, + 0xEB, 0x2B, 0xDB, 0xAD, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6F} +}; + +/* + * Checkup routine + */ +int sha1_self_test (void) +{ + int i, j; + unsigned char buf[1000]; + unsigned char sha1sum[20]; + sha1_context ctx; + + for (i = 0; i < 3; i++) { + printf (" SHA-1 test #%d: ", i + 1); + + sha1_starts (&ctx); + + if (i < 2) + sha1_update (&ctx, (unsigned char *) sha1_test_str[i], + strlen (sha1_test_str[i])); + else { + memset (buf, 'a', 1000); + for (j = 0; j < 1000; j++) + sha1_update (&ctx, buf, 1000); + } + + sha1_finish (&ctx, sha1sum); + + if (memcmp (sha1sum, sha1_test_sum[i], 20) != 0) { + printf ("failed\n"); + return (1); + } + + printf ("passed\n"); + } + + printf ("\n"); + return (0); +} +#else +int sha1_self_test (void) +{ + return (0); +} +#endif diff --git a/sps2_basement/core/alg/sha1.h b/sps2_basement/core/alg/sha1.h new file mode 100644 index 0000000..da09dab --- /dev/null +++ b/sps2_basement/core/alg/sha1.h @@ -0,0 +1,118 @@ +/** + * \file sha1.h + * based from http://xyssl.org/code/source/sha1/ + * FIPS-180-1 compliant SHA-1 implementation + * + * Copyright (C) 2003-2006 Christophe Devine + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License, version 2.1 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +/* + * The SHA-1 standard was published by NIST in 1993. + * + * http://www.itl.nist.gov/fipspubs/fip180-1.htm + */ +#ifndef _SHA1_H +#define _SHA1_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define SHA1_SUM_POS -0x20 +#define SHA1_SUM_LEN 20 + +/** + * \brief SHA-1 context structure + */ +typedef struct +{ + unsigned long total[2]; /*!< number of bytes processed */ + unsigned long state[5]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ +} +sha1_context; + +/** + * \brief SHA-1 context setup + * + * \param ctx SHA-1 context to be initialized + */ +void sha1_starts( sha1_context *ctx ); + +/** + * \brief SHA-1 process buffer + * + * \param ctx SHA-1 context + * \param input buffer holding the data + * \param ilen length of the input data + */ +void sha1_update(sha1_context *ctx, const unsigned char *input, + unsigned int ilen); + +/** + * \brief SHA-1 final digest + * + * \param ctx SHA-1 context + * \param output SHA-1 checksum result + */ +void sha1_finish( sha1_context *ctx, unsigned char output[20] ); + +/** + * \brief Output = SHA-1( input buffer ) + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output SHA-1 checksum result + */ +void sha1_csum(const unsigned char *input, unsigned int ilen, + unsigned char *output); + +/** + * \brief Output = SHA-1( input buffer ), with watchdog triggering + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output SHA-1 checksum result + * \param chunk_sz watchdog triggering period (in bytes of input processed) + */ +void sha1_csum_wd(const unsigned char *input, unsigned int ilen, + unsigned char *output, unsigned int chunk_sz); + +/** + * \brief Output = HMAC-SHA-1( input buffer, hmac key ) + * + * \param key HMAC secret key + * \param keylen length of the HMAC key + * \param input buffer holding the data + * \param ilen length of the input data + * \param output HMAC-SHA-1 result + */ +void sha1_hmac(const unsigned char *key, int keylen, + const unsigned char *input, unsigned int ilen, + unsigned char *output); + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int sha1_self_test( void ); + +#ifdef __cplusplus +} +#endif + +#endif /* sha1.h */ diff --git a/sps2_basement/core/alg/sha256.c b/sps2_basement/core/alg/sha256.c new file mode 100644 index 0000000..7fd7114 --- /dev/null +++ b/sps2_basement/core/alg/sha256.c @@ -0,0 +1,283 @@ +/* + * FIPS-180-2 compliant SHA-256 implementation + * + * Copyright (C) 2001-2003 Christophe Devine + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +//#ifndef USE_HOSTCC +//#include +//#endif /* USE_HOSTCC */ +//#include +//#include +#include "sha256.h" + +/* + * 32-bit integer manipulation macros (big endian) + */ +#ifndef GET_UINT32_BE +#define GET_UINT32_BE(n,b,i) { \ + (n) = ( (unsigned long) (b)[(i) ] << 24 ) \ + | ( (unsigned long) (b)[(i) + 1] << 16 ) \ + | ( (unsigned long) (b)[(i) + 2] << 8 ) \ + | ( (unsigned long) (b)[(i) + 3] ); \ +} +#endif +#ifndef PUT_UINT32_BE +#define PUT_UINT32_BE(n,b,i) { \ + (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ + (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ + (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ + (b)[(i) + 3] = (unsigned char) ( (n) ); \ +} +#endif + +void sha256_starts(sha256_context * ctx) +{ + ctx->total[0] = 0; + ctx->total[1] = 0; + + ctx->state[0] = 0x6A09E667; + ctx->state[1] = 0xBB67AE85; + ctx->state[2] = 0x3C6EF372; + ctx->state[3] = 0xA54FF53A; + ctx->state[4] = 0x510E527F; + ctx->state[5] = 0x9B05688C; + ctx->state[6] = 0x1F83D9AB; + ctx->state[7] = 0x5BE0CD19; +} + +static void sha256_process(sha256_context *ctx, const uint8_t data[64]) +{ + uint32_t temp1, temp2; + uint32_t W[64]; + uint32_t A, B, C, D, E, F, G, H; + + GET_UINT32_BE(W[0], data, 0); + GET_UINT32_BE(W[1], data, 4); + GET_UINT32_BE(W[2], data, 8); + GET_UINT32_BE(W[3], data, 12); + GET_UINT32_BE(W[4], data, 16); + GET_UINT32_BE(W[5], data, 20); + GET_UINT32_BE(W[6], data, 24); + GET_UINT32_BE(W[7], data, 28); + GET_UINT32_BE(W[8], data, 32); + GET_UINT32_BE(W[9], data, 36); + GET_UINT32_BE(W[10], data, 40); + GET_UINT32_BE(W[11], data, 44); + GET_UINT32_BE(W[12], data, 48); + GET_UINT32_BE(W[13], data, 52); + GET_UINT32_BE(W[14], data, 56); + GET_UINT32_BE(W[15], data, 60); + +#define SHR(x,n) ((x & 0xFFFFFFFF) >> n) +#define ROTR(x,n) (SHR(x,n) | (x << (32 - n))) + +#define S0(x) (ROTR(x, 7) ^ ROTR(x,18) ^ SHR(x, 3)) +#define S1(x) (ROTR(x,17) ^ ROTR(x,19) ^ SHR(x,10)) + +#define S2(x) (ROTR(x, 2) ^ ROTR(x,13) ^ ROTR(x,22)) +#define S3(x) (ROTR(x, 6) ^ ROTR(x,11) ^ ROTR(x,25)) + +#define F0(x,y,z) ((x & y) | (z & (x | y))) +#define F1(x,y,z) (z ^ (x & (y ^ z))) + +#define R(t) \ +( \ + W[t] = S1(W[t - 2]) + W[t - 7] + \ + S0(W[t - 15]) + W[t - 16] \ +) + +#define P(a,b,c,d,e,f,g,h,x,K) { \ + temp1 = h + S3(e) + F1(e,f,g) + K + x; \ + temp2 = S2(a) + F0(a,b,c); \ + d += temp1; h = temp1 + temp2; \ +} + + A = ctx->state[0]; + B = ctx->state[1]; + C = ctx->state[2]; + D = ctx->state[3]; + E = ctx->state[4]; + F = ctx->state[5]; + G = ctx->state[6]; + H = ctx->state[7]; + + P(A, B, C, D, E, F, G, H, W[0], 0x428A2F98); + P(H, A, B, C, D, E, F, G, W[1], 0x71374491); + P(G, H, A, B, C, D, E, F, W[2], 0xB5C0FBCF); + P(F, G, H, A, B, C, D, E, W[3], 0xE9B5DBA5); + P(E, F, G, H, A, B, C, D, W[4], 0x3956C25B); + P(D, E, F, G, H, A, B, C, W[5], 0x59F111F1); + P(C, D, E, F, G, H, A, B, W[6], 0x923F82A4); + P(B, C, D, E, F, G, H, A, W[7], 0xAB1C5ED5); + P(A, B, C, D, E, F, G, H, W[8], 0xD807AA98); + P(H, A, B, C, D, E, F, G, W[9], 0x12835B01); + P(G, H, A, B, C, D, E, F, W[10], 0x243185BE); + P(F, G, H, A, B, C, D, E, W[11], 0x550C7DC3); + P(E, F, G, H, A, B, C, D, W[12], 0x72BE5D74); + P(D, E, F, G, H, A, B, C, W[13], 0x80DEB1FE); + P(C, D, E, F, G, H, A, B, W[14], 0x9BDC06A7); + P(B, C, D, E, F, G, H, A, W[15], 0xC19BF174); + P(A, B, C, D, E, F, G, H, R(16), 0xE49B69C1); + P(H, A, B, C, D, E, F, G, R(17), 0xEFBE4786); + P(G, H, A, B, C, D, E, F, R(18), 0x0FC19DC6); + P(F, G, H, A, B, C, D, E, R(19), 0x240CA1CC); + P(E, F, G, H, A, B, C, D, R(20), 0x2DE92C6F); + P(D, E, F, G, H, A, B, C, R(21), 0x4A7484AA); + P(C, D, E, F, G, H, A, B, R(22), 0x5CB0A9DC); + P(B, C, D, E, F, G, H, A, R(23), 0x76F988DA); + P(A, B, C, D, E, F, G, H, R(24), 0x983E5152); + P(H, A, B, C, D, E, F, G, R(25), 0xA831C66D); + P(G, H, A, B, C, D, E, F, R(26), 0xB00327C8); + P(F, G, H, A, B, C, D, E, R(27), 0xBF597FC7); + P(E, F, G, H, A, B, C, D, R(28), 0xC6E00BF3); + P(D, E, F, G, H, A, B, C, R(29), 0xD5A79147); + P(C, D, E, F, G, H, A, B, R(30), 0x06CA6351); + P(B, C, D, E, F, G, H, A, R(31), 0x14292967); + P(A, B, C, D, E, F, G, H, R(32), 0x27B70A85); + P(H, A, B, C, D, E, F, G, R(33), 0x2E1B2138); + P(G, H, A, B, C, D, E, F, R(34), 0x4D2C6DFC); + P(F, G, H, A, B, C, D, E, R(35), 0x53380D13); + P(E, F, G, H, A, B, C, D, R(36), 0x650A7354); + P(D, E, F, G, H, A, B, C, R(37), 0x766A0ABB); + P(C, D, E, F, G, H, A, B, R(38), 0x81C2C92E); + P(B, C, D, E, F, G, H, A, R(39), 0x92722C85); + P(A, B, C, D, E, F, G, H, R(40), 0xA2BFE8A1); + P(H, A, B, C, D, E, F, G, R(41), 0xA81A664B); + P(G, H, A, B, C, D, E, F, R(42), 0xC24B8B70); + P(F, G, H, A, B, C, D, E, R(43), 0xC76C51A3); + P(E, F, G, H, A, B, C, D, R(44), 0xD192E819); + P(D, E, F, G, H, A, B, C, R(45), 0xD6990624); + P(C, D, E, F, G, H, A, B, R(46), 0xF40E3585); + P(B, C, D, E, F, G, H, A, R(47), 0x106AA070); + P(A, B, C, D, E, F, G, H, R(48), 0x19A4C116); + P(H, A, B, C, D, E, F, G, R(49), 0x1E376C08); + P(G, H, A, B, C, D, E, F, R(50), 0x2748774C); + P(F, G, H, A, B, C, D, E, R(51), 0x34B0BCB5); + P(E, F, G, H, A, B, C, D, R(52), 0x391C0CB3); + P(D, E, F, G, H, A, B, C, R(53), 0x4ED8AA4A); + P(C, D, E, F, G, H, A, B, R(54), 0x5B9CCA4F); + P(B, C, D, E, F, G, H, A, R(55), 0x682E6FF3); + P(A, B, C, D, E, F, G, H, R(56), 0x748F82EE); + P(H, A, B, C, D, E, F, G, R(57), 0x78A5636F); + P(G, H, A, B, C, D, E, F, R(58), 0x84C87814); + P(F, G, H, A, B, C, D, E, R(59), 0x8CC70208); + P(E, F, G, H, A, B, C, D, R(60), 0x90BEFFFA); + P(D, E, F, G, H, A, B, C, R(61), 0xA4506CEB); + P(C, D, E, F, G, H, A, B, R(62), 0xBEF9A3F7); + P(B, C, D, E, F, G, H, A, R(63), 0xC67178F2); + + ctx->state[0] += A; + ctx->state[1] += B; + ctx->state[2] += C; + ctx->state[3] += D; + ctx->state[4] += E; + ctx->state[5] += F; + ctx->state[6] += G; + ctx->state[7] += H; +} + +void sha256_update(sha256_context *ctx, const uint8_t *input, uint32_t length) +{ + uint32_t left, fill; + + if (!length) + return; + + left = ctx->total[0] & 0x3F; + fill = 64 - left; + + ctx->total[0] += length; + ctx->total[0] &= 0xFFFFFFFF; + + if (ctx->total[0] < length) + ctx->total[1]++; + + if (left && length >= fill) { + memcpy((void *) (ctx->buffer + left), (void *) input, fill); + sha256_process(ctx, ctx->buffer); + length -= fill; + input += fill; + left = 0; + } + + while (length >= 64) { + sha256_process(ctx, input); + length -= 64; + input += 64; + } + + if (length) + memcpy((void *) (ctx->buffer + left), (void *) input, length); +} + +static uint8_t sha256_padding[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +void sha256_finish(sha256_context * ctx, uint8_t digest[32]) +{ + uint32_t last, padn; + uint32_t high, low; + uint8_t msglen[8]; + + high = ((ctx->total[0] >> 29) + | (ctx->total[1] << 3)); + low = (ctx->total[0] << 3); + + PUT_UINT32_BE(high, msglen, 0); + PUT_UINT32_BE(low, msglen, 4); + + last = ctx->total[0] & 0x3F; + padn = (last < 56) ? (56 - last) : (120 - last); + + sha256_update(ctx, sha256_padding, padn); + sha256_update(ctx, msglen, 8); + + PUT_UINT32_BE(ctx->state[0], digest, 0); + PUT_UINT32_BE(ctx->state[1], digest, 4); + PUT_UINT32_BE(ctx->state[2], digest, 8); + PUT_UINT32_BE(ctx->state[3], digest, 12); + PUT_UINT32_BE(ctx->state[4], digest, 16); + PUT_UINT32_BE(ctx->state[5], digest, 20); + PUT_UINT32_BE(ctx->state[6], digest, 24); + PUT_UINT32_BE(ctx->state[7], digest, 28); +} + +/* + * Output = SHA-256( input buffer ). Trigger the watchdog every 'chunk_sz' + * bytes of input processed. + */ +void sha256_csum_wd(const unsigned char *input, unsigned int ilen, + unsigned char *output, unsigned int chunk_sz) +{ + sha256_context ctx; +#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) + unsigned char *end, *curr; + int chunk; +#endif + + sha256_starts(&ctx); + +#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) + curr = input; + end = input + ilen; + while (curr < end) { + chunk = end - curr; + if (chunk > chunk_sz) + chunk = chunk_sz; + sha256_update(&ctx, curr, chunk); + curr += chunk; + WATCHDOG_RESET(); + } +#else + sha256_update(&ctx, input, ilen); +#endif + + sha256_finish(&ctx, output); +} diff --git a/sps2_basement/core/alg/sha256.h b/sps2_basement/core/alg/sha256.h new file mode 100644 index 0000000..97a77d4 --- /dev/null +++ b/sps2_basement/core/alg/sha256.h @@ -0,0 +1,24 @@ +#ifndef _SHA256_H +#define _SHA256_H + +#include "../base/basicTypes.h" + +#define SHA256_SUM_LEN 32 + +/* Reset watchdog each time we process this many bytes */ +#define CHUNKSZ_SHA256 (64 * 1024) + +typedef struct { + uint32_t total[2]; + uint32_t state[8]; + uint8_t buffer[64]; +} sha256_context; + +void sha256_starts(sha256_context * ctx); +void sha256_update(sha256_context *ctx, const uint8_t *input, uint32_t length); +void sha256_finish(sha256_context * ctx, uint8_t digest[SHA256_SUM_LEN]); + +void sha256_csum_wd(const unsigned char *input, unsigned int ilen, + unsigned char *output, unsigned int chunk_sz); + +#endif /* _SHA256_H */ diff --git a/sps2_basement/core/base/assert.h b/sps2_basement/core/base/assert.h new file mode 100644 index 0000000..b681a85 --- /dev/null +++ b/sps2_basement/core/base/assert.h @@ -0,0 +1,29 @@ +/* + assert.h +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "_ansi.h" + +#undef assert + +#ifdef NDEBUG /* required by ANSI standard */ +#define assert(p) ((void)0) +#else + +#ifdef __STDC__ +#define assert(e) ((e) ? (void)0 : __assert(__FILE__, __LINE__, #e)) +#else /* PCC */ +#define assert(e) ((e) ? (void)0 : __assert(__FILE__, __LINE__, "e")) +#endif + +#endif /* NDEBUG */ + +void _EXFUN(__assert,(const char *, int, const char *)); + +#ifdef __cplusplus +} +#endif diff --git a/sps2_basement/core/base/basicConfig.h b/sps2_basement/core/base/basicConfig.h new file mode 100644 index 0000000..0fab9fd --- /dev/null +++ b/sps2_basement/core/base/basicConfig.h @@ -0,0 +1,78 @@ +#ifndef __SPS2_SYSTEM_CONFIGURATION_HEADER__ +#define __SPS2_SYSTEM_CONFIGURATION_HEADER__ +// System Info: +/* + CPU: MIPS III R5900-based "Emotion Engine", clocked at 294.912 MHz (299 MHz on newer versions), with 128-bit SIMD capabilities + 250-nm CMOS manufacturing (ending with 65-nm CMOS), 13.5 million transistors, 225 mm? die size, 15 W dissipation (combined EE+GS in SCPH-7500x and later SCPH-7000x): 86 mm?, 53.5 million transistors) + (combined EE+GS+RDRAM+DRAM in SCPH-7900x ended with 65 nm CMOS design) + + CPU core: MIPS R5900 (COP0), 64-bit, little endian (mipsel). + CPU is a superscalar, in-order execution 2-issue design with 6-stage long integer pipelines, + 32 32-bit GPR registers, + 32 128-bit SIMD linear scalar registers, + two 64-bit integer ALUs, + 128-bit load-store unit (LSU) and a branch execution unit (BXU). + Instruction set: MIPS III, MIPS IV subset with Sony's proprietary 107 vector SIMD multimedia instructions (MMI). + The custom instruction set was implemented by grouping the two 64-bit integer ALUs. + 32-bit FPU coprocessor (COP1) with 6-stage long pipeline (floating point multiply accumulator + 1, floating point divider + 1). FPU is not IEEE compliant. + Two 32-bit VLIW-SIMD vector units at 294.912 MHz: VPU0 and VPU1 (floating point multiply accumulator + 9, floating point divider + 1) each VPU contains a vector unit (VU), instruction cache, data cache and interface unit. + Each vector unit also has upper execution unit containing + 4 FMAC and lower execution unit containing FDIV, integer ALU, load-store unit, branch logic, + 16 16-bit integer registers and + 32 128-bit floating point registers. + VPU1 has an additional EFU unit. + VPU0 (COP2; FMAC ? 4, FDIV ? 1) is tightly coupled with the main CPU and is typically used for polygon and geometry transformations (under parallel or serial connection), + physics and other gameplay related tasks + VPU1 (Elementary Functional Unit, EFU; FMAC ? 5, FDIV ? 2) operates independently controlled by microcode, parallel to the CPU core, + is typically used for polygon and geometry transformations, clipping, culling, lighting and other visual based calculations (texture matrix able for 2 coordinates (UV/ST)) + + Parallel: results of VU0/FPU sent as another display list via MFIFO (for e.g. complex characters/vehicles/etc.) + + Serial: results of VU0/FPU sent to VU1 (via 3 methods) and can act as an optional geometry pre-processor that does all base work to update the scene every frame + (for e.g. camera, perspective, boning and laws of movement such as animations or physics) + + Image Processing Unit (IPU): MPEG-2 compressed image macroblock layer decoder allowing playback of DVDs and game FMV. + It also allowed vector quantization for 2D graphics data. + Memory management unit (MMU),[12] RDRAM controller and DMA controller: handle memory access within the system + Cache memory: 16 KB instruction cache, 8 KB + 16 KB scratchpad (ScrP) data cache + Scratchpad (SPR) is extended area of memory visible to the EE CPU. + This extended memory provides 16 kilobytes of fast RAM available to be used by the application. + Scratchpad memory can be used to store temporary data that is waiting to be sent via DMA or for any other temporary storage that the programmer can define. + + I/O processor interconnection: remote procedure call over a serial link, DMA controller for bulk transfer + Main RDRAM memory bus. Bandwidth: 3.2 GB/s + Graphics interface (GIF), DMA channel that connects the EE CPU to the GS co-processor. To draw something to the screen, one must send render commands to the GS via the GIF channel: 64-bit, 150 MHz bus, maximum theoretical bandwidth of 1.2 GB/s.[6] + Display lists generated by CPU/VPU0 and VPU1 are sent to the GIF, which prioritizes them before dispatching them to the Graphics Synthesizer for rendering. + Vector Unit Interface (VIF), consists of two DMA channels VIF0 for VPU0 and VIF1 for VPU1. Vector units and the main CPU communicate via VIF DMA channels. + SIF – Serial Interface or Subsystem Interface which consists of 3 DMA channels: + Subsystem Interface 0 (SIF0) and Subsystem Interface 1 (SIF1), used for communication between the EE main CPU and IOP co-processor. These are serial DMA channels where both CPUs can send commands and establish communication through an RPC protocol. + Subsystem Interface 2 (SIF2), used for backwards compatibility with PS1 games and debugging. +*/ + +#include "basicTypes.h" + +#if !defined(_EE) && !defined(_IOP) + #error Either _EE or _IOP must be defined! +#endif + +#ifndef __BYTE_ORDER + #define __BYTE_ORDER __LITTLE_ENDIAN +#endif + +typedef struct s_ps2_sysconf { + uint16_t timezone; + uint8_t aspect; + uint8_t datenotation; + uint8_t language; + uint8_t spdif; + uint8_t summertime; + uint8_t timenotation; + uint8_t video; +}ps2_sysconf_t; + + +#endif diff --git a/sps2_basement/core/base/basicTypes.h b/sps2_basement/core/base/basicTypes.h new file mode 100644 index 0000000..3c0589b --- /dev/null +++ b/sps2_basement/core/base/basicTypes.h @@ -0,0 +1,364 @@ +#ifndef __SPS2_BASIC_TYPES_HEADER__ +#define __SPS2_BASIC_TYPES_HEADER__ + +#include "errno.h" +#include "assert.h" + +#if !defined(_EE) && !defined(_IOP) + #error Either _EE or _IOP must be defined! +#endif + +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; + +typedef uint8_t * puint8_t; +typedef uint8_t * puint16_t; + +typedef volatile uint8_t vuint8_t; +typedef volatile uint16_t vuint16_t; + +typedef vuint8_t * pvuint8_t; +typedef vuint16_t * pvuint16_t; + +#ifdef _EE + #ifndef __BYTE_ORDER + #define __BYTE_ORDER __LITTLE_ENDIAN + #endif + typedef unsigned int uint32_t; + + #if __GNUC__ > 3 + typedef unsigned long long uint64_t; + #else + typedef unsigned long uint64_t; + #endif + typedef unsigned int uint128_t __attribute__(( mode(TI) )); + + typedef uint32_t * puint32_t; + typedef uint64_t * puint64_t; + typedef uint128_t * puint128_t; + + typedef volatile uint32_t vuint32_t; + typedef volatile uint64_t vuint64_t; + typedef volatile uint128_t vuint128_t __attribute__(( mode(TI) )); + + typedef vuint32_t * pvuint32_t; + typedef vuint64_t * pvuint64_t; + typedef vuint128_t * pvuint128_t; + +#endif //_EE + +#ifdef _IOP + typedef unsigned long uint32_t; + typedef unsigned long long uint64_t; + + typedef volatile uint32_t vuint32_t; + typedef volatile uint64_t vuint64_t; +#endif + +typedef signed char int8_t; +typedef signed short int16_t; +typedef volatile int8_t vint8_t; +typedef volatile int16_t vint16_t; + +#ifdef _EE + typedef signed int int32_t; + #if __GNUC__ > 3 + typedef signed long long int64_t; + #else + typedef signed long int64_t; + #endif + typedef signed int int128_t __attribute__(( mode(TI) )); + + typedef int32_t * pint32_t; + typedef int64_t * pint64_t; + typedef int128_t * pint128_t; + + typedef volatile int32_t vint32_t; + typedef volatile int64_t vint64_t; + typedef volatile int128_t vint128_t __attribute__(( mode(TI) )); + + typedef vint32_t * pvint32_t; + typedef vint64_t * pvint64_t; + typedef vint128_t * pvint128_t; + +#endif + +#ifdef _IOP + typedef signed long int32_t; + typedef signed long long int64_t; + typedef volatile int32_t vint32_t; + typedef volatile int64_t vint64_t; +#endif + +#ifdef _EE + typedef union u_qword_t{ + uint128_t qw; + uint8_t b[16]; + uint16_t hw[8]; + uint32_t sw[4]; + uint64_t dw[2]; + } qword_t; +#endif + +#ifndef NULL + #define NULL (void *)0 +#endif + +static inline uint8_t _lb(uint32_t addr) { return *(vuint8_t *)addr; } +static inline uint16_t _lh(uint32_t addr) { return *(vuint16_t *)addr; } +static inline uint32_t _lw(uint32_t addr) { return *(vuint32_t *)addr; } + +static inline void _sb(uint8_t val, uint32_t addr) { *(vuint8_t *)addr = val; } +static inline void _sh(uint16_t val, uint32_t addr) { *(vuint16_t *)addr = val; } +static inline void _sw(uint32_t val, uint32_t addr) { *(vuint32_t *)addr = val; } + +#ifdef _EE + static inline uint64_t _ld(uint32_t addr) { return *(vuint64_t *)addr; } + static inline uint128_t _lq(uint32_t addr) { return *(vuint128_t *)addr; } + static inline void _sd(uint64_t val, uint32_t addr) { *(vuint64_t *)addr = val; } + static inline void _sq(uint128_t val, uint32_t addr) { *(vuint128_t *)addr = val; } +#endif + +#define uswap_16(x) \ + ((((x) & 0xff00) >> 8) | \ + (((x) & 0x00ff) << 8)) + +#define uswap_32(x) \ + ((((x) & 0xff000000) >> 24) | \ + (((x) & 0x00ff0000) >> 8) | \ + (((x) & 0x0000ff00) << 8) | \ + (((x) & 0x000000ff) << 24)) + +#define _uswap_64(x, sfx) \ + ((((x) & 0xff00000000000000##sfx) >> 56) | \ + (((x) & 0x00ff000000000000##sfx) >> 40) | \ + (((x) & 0x0000ff0000000000##sfx) >> 24) | \ + (((x) & 0x000000ff00000000##sfx) >> 8) | \ + (((x) & 0x00000000ff000000##sfx) << 8) | \ + (((x) & 0x0000000000ff0000##sfx) << 24) | \ + (((x) & 0x000000000000ff00##sfx) << 40) | \ + (((x) & 0x00000000000000ff##sfx) << 56)) + +#define _uswap_128(x, sfx) \ + ((((x) & 0xff000000000000000000000000000000##sfx) >> 120) | \ + (((x) & 0x00ff0000000000000000000000000000##sfx) >> 104) | \ + (((x) & 0x0000ff00000000000000000000000000##sfx) >> 88) | \ + (((x) & 0x000000ff000000000000000000000000##sfx) >> 72) | \ + (((x) & 0x00000000ff0000000000000000000000##sfx) >> 56) | \ + (((x) & 0x0000000000ff00000000000000000000##sfx) >> 40) | \ + (((x) & 0x000000000000ff000000000000000000##sfx) >> 24) | \ + (((x) & 0x00000000000000ff0000000000000000##sfx) >> 8) | \ + (((x) & 0x0000000000000000ff00000000000000##sfx) << 8) | \ + (((x) & 0x000000000000000000ff000000000000##sfx) << 24) | \ + (((x) & 0x00000000000000000000ff0000000000##sfx) << 40) | \ + (((x) & 0x0000000000000000000000ff00000000##sfx) << 56) | \ + (((x) & 0x000000000000000000000000ff000000##sfx) << 72) | \ + (((x) & 0x00000000000000000000000000ff0000##sfx) << 88) | \ + (((x) & 0x0000000000000000000000000000ff00##sfx) << 104) | \ + (((x) & 0x000000000000000000000000000000ff##sfx) << 120)) + + +#if defined(__GNUC__) + #define uswap_64(x) _uswap_64(x, ull) + #define uswap_128(x) _uswap_128(x, ull) +#else + #define uswap_64(x) _uswap_64(x, ) + #define uswap_128(x) _uswap_128(x, ) +#endif + +#if __BYTE_ORDER == __LITTLE_ENDIAN + #define cpu_to_le16(x) (x) + #define cpu_to_le32(x) (x) + #define cpu_to_le64(x) (x) + #define cpu_to_le128(x) (x) + #define le16_to_cpu(x) (x) + #define le32_to_cpu(x) (x) + #define le64_to_cpu(x) (x) + #define le128_to_cpu(x) (x) + #define cpu_to_be16(x) uswap_16(x) + #define cpu_to_be32(x) uswap_32(x) + #define cpu_to_be64(x) uswap_64(x) + #define cpu_to_be128(x) uswap_128(x) + #define be16_to_cpu(x) uswap_16(x) + #define be32_to_cpu(x) uswap_32(x) + #define be64_to_cpu(x) uswap_64(x) + #define be128_to_cpu(x) uswap_128(x) +#else + #define cpu_to_le16(x) uswap_16(x) + #define cpu_to_le32(x) uswap_32(x) + #define cpu_to_le64(x) uswap_64(x) + #define cpu_to_le128(x) uswap_128(x) + #define le16_to_cpu(x) uswap_16(x) + #define le32_to_cpu(x) uswap_32(x) + #define le64_to_cpu(x) uswap_64(x) + #define le128_to_cpu(x) uswap_128(x) + #define cpu_to_be16(x) (x) + #define cpu_to_be32(x) (x) + #define cpu_to_be64(x) (x) + #define cpu_to_be128(x) (x) + #define be16_to_cpu(x) (x) + #define be32_to_cpu(x) (x) + #define be64_to_cpu(x) (x) + #define be128_to_cpu(x) (x) +#endif + +//#include +//#include +//#include +#ifndef _SIZE_T + #define _SIZE_T + typedef uint32_t size_t; +#endif + +#ifndef __externC + #ifdef __cplusplus + #define __externC extern "C" + #else + #define __externC extern + #endif +#endif + +#ifdef __KERNEL_STRICT_NAMES_____________ + + typedef __kernel_fd_set fd_set; + typedef __kernel_dev_t dev_t; + typedef __kernel_ino_t ino_t; + typedef __kernel_mode_t mode_t; + typedef __kernel_nlink_t nlink_t; + typedef __kernel_off_t off_t; + typedef __kernel_pid_t pid_t; + typedef __kernel_daddr_t daddr_t; + typedef __kernel_key_t key_t; + typedef __kernel_suseconds_t suseconds_t; + + #ifdef __KERNEL__ + typedef __kernel_uid32_t uid_t; + typedef __kernel_gid32_t gid_t; + typedef __kernel_uid16_t uid16_t; + typedef __kernel_gid16_t gid16_t; + + #ifdef CONFIG_UID16 + /* This is defined by include/asm-{arch}/posix_types.h */ + typedef __kernel_old_uid_t old_uid_t; + typedef __kernel_old_gid_t old_gid_t; + #endif /* CONFIG_UID16 */ + + /* libc5 includes this file to define uid_t, thus uid_t can never change + * when it is included by non-kernel code + */ + #else + typedef __kernel_uid_t uid_t; + typedef __kernel_gid_t gid_t; + #endif /* __KERNEL__ */ + + #if defined(__GNUC__) && !defined(__STRICT_ANSI__) + typedef __kernel_loff_t loff_t; + #endif + + /* + * The following typedefs are also protected by individual ifdefs for + * historical reasons: + */ + #ifndef _SIZE_T + #define _SIZE_T + typedef __kernel_size_t size_t; + #endif + + #ifndef _SSIZE_T + #define _SSIZE_T + typedef __kernel_ssize_t ssize_t; + #endif + + #ifndef _PTRDIFF_T + #define _PTRDIFF_T + typedef __kernel_ptrdiff_t ptrdiff_t; + #endif + + #ifndef _TIME_T + #define _TIME_T + typedef __kernel_time_t time_t; + #endif + + #ifndef _CLOCK_T + #define _CLOCK_T + typedef __kernel_clock_t clock_t; + #endif + + #ifndef _CADDR_T + #define _CADDR_T + typedef __kernel_caddr_t caddr_t; + #endif + + /* bsd */ + typedef unsigned char u_char; + typedef unsigned short u_short; + typedef unsigned int u_int; + typedef unsigned long u_long; + + /* sysv */ + typedef unsigned char unchar; + typedef unsigned short ushort; + typedef unsigned int uint; + typedef unsigned long ulong; + + #ifndef __BIT_TYPES_DEFINED__ + #define __BIT_TYPES_DEFINED__ + + typedef __u8 u_int8_t; + typedef __s8 int8_t; + typedef __u16 u_int16_t; + typedef __s16 int16_t; + typedef __u32 u_int32_t; + typedef __s32 int32_t; + #endif /* !(__BIT_TYPES_DEFINED__) */ + + typedef __u8 uint8_t; + typedef __u16 uint16_t; + typedef __u32 uint32_t; + + #if defined(__GNUC__) && !defined(__STRICT_ANSI__) + typedef __u64 uint64_t; + typedef __u64 u_int64_t; + typedef __s64 int64_t; + #endif +#endif /* __KERNEL_STRICT_NAMES */ + +/* + * Below are truly Linux-specific types that should never collide with + * any application/library that wants linux/types.h. + */ +#ifdef __CHECKER__ + #define __bitwise__ __attribute__((bitwise)) +#else + #define __bitwise__ +#endif + +#ifdef __CHECK_ENDIAN__ + #define __bitwise __bitwise__ +#else + #define __bitwise +#endif + +//typedef __u16 __bitwise __le16; +//typedef __u16 __bitwise __be16; +//typedef __u32 __bitwise __le32; +//typedef __u32 __bitwise __be32; + +//#if defined(__GNUC__) +// typedef __u64 __bitwise __le64; +// typedef __u64 __bitwise __be64; +//#endif + +//typedef __u16 __bitwise __sum16; +//typedef __u32 __bitwise __wsum; + +typedef unsigned __bitwise__ gfp_t; + +//struct ustat { +// __kernel_daddr_t f_tfree; +// __kernel_ino_t f_tinode; +// char f_fname[6]; +// char f_fpack[6]; +//}; + +#endif diff --git a/sps2_basement/core/base/elf.h b/sps2_basement/core/base/elf.h new file mode 100644 index 0000000..b8ecc41 --- /dev/null +++ b/sps2_basement/core/base/elf.h @@ -0,0 +1,573 @@ +/* + * Copyright (c) 1995, 1996, 2001, 2002 + * Erik Theisen. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * This is the ELF ABI header file + * formerly known as "elf_abi.h". + */ + +#ifndef _ELF_H +#define _ELF_H + +#include "compiler.h" + +/* + * This version doesn't work for 64-bit ABIs - Erik. + */ + +/* + * These typedefs need to be handled better. + */ +typedef uint32_t Elf32_Addr; /* Unsigned program address */ +typedef uint32_t Elf32_Off; /* Unsigned file offset */ +typedef int32_t Elf32_Sword; /* Signed large integer */ +typedef uint32_t Elf32_Word; /* Unsigned large integer */ +typedef uint16_t Elf32_Half; /* Unsigned medium integer */ + +/* e_ident[] identification indexes */ +#define EI_MAG0 0 /* file ID */ +#define EI_MAG1 1 /* file ID */ +#define EI_MAG2 2 /* file ID */ +#define EI_MAG3 3 /* file ID */ +#define EI_CLASS 4 /* file class */ +#define EI_DATA 5 /* data encoding */ +#define EI_VERSION 6 /* ELF header version */ +#define EI_OSABI 7 /* OS/ABI specific ELF extensions */ +#define EI_ABIVERSION 8 /* ABI target version */ +#define EI_PAD 9 /* start of pad bytes */ +#define EI_NIDENT 16 /* Size of e_ident[] */ + +/* e_ident[] magic number */ +#define ELFMAG0 0x7f /* e_ident[EI_MAG0] */ +#define ELFMAG1 'E' /* e_ident[EI_MAG1] */ +#define ELFMAG2 'L' /* e_ident[EI_MAG2] */ +#define ELFMAG3 'F' /* e_ident[EI_MAG3] */ +#define ELFMAG "\177ELF" /* magic */ +#define SELFMAG 4 /* size of magic */ + +/* e_ident[] file class */ +#define ELFCLASSNONE 0 /* invalid */ +#define ELFCLASS32 1 /* 32-bit objs */ +#define ELFCLASS64 2 /* 64-bit objs */ +#define ELFCLASSNUM 3 /* number of classes */ + +/* e_ident[] data encoding */ +#define ELFDATANONE 0 /* invalid */ +#define ELFDATA2LSB 1 /* Little-Endian */ +#define ELFDATA2MSB 2 /* Big-Endian */ +#define ELFDATANUM 3 /* number of data encode defines */ + +/* e_ident[] OS/ABI specific ELF extensions */ +#define ELFOSABI_NONE 0 /* No extension specified */ +#define ELFOSABI_HPUX 1 /* Hewlett-Packard HP-UX */ +#define ELFOSABI_NETBSD 2 /* NetBSD */ +#define ELFOSABI_LINUX 3 /* Linux */ +#define ELFOSABI_SOLARIS 6 /* Sun Solaris */ +#define ELFOSABI_AIX 7 /* AIX */ +#define ELFOSABI_IRIX 8 /* IRIX */ +#define ELFOSABI_FREEBSD 9 /* FreeBSD */ +#define ELFOSABI_TRU64 10 /* Compaq TRU64 UNIX */ +#define ELFOSABI_MODESTO 11 /* Novell Modesto */ +#define ELFOSABI_OPENBSD 12 /* OpenBSD */ +/* 64-255 Architecture-specific value range */ + +/* e_ident[] ABI Version */ +#define ELFABIVERSION 0 + +/* e_ident */ +#define IS_ELF(ehdr) ((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \ + (ehdr).e_ident[EI_MAG1] == ELFMAG1 && \ + (ehdr).e_ident[EI_MAG2] == ELFMAG2 && \ + (ehdr).e_ident[EI_MAG3] == ELFMAG3) + +/* ELF Header */ +typedef struct elfhdr{ + unsigned char e_ident[EI_NIDENT]; /* ELF Identification */ + Elf32_Half e_type; /* object file type */ + Elf32_Half e_machine; /* machine */ + Elf32_Word e_version; /* object file version */ + Elf32_Addr e_entry; /* virtual entry point */ + Elf32_Off e_phoff; /* program header table offset */ + Elf32_Off e_shoff; /* section header table offset */ + Elf32_Word e_flags; /* processor-specific flags */ + Elf32_Half e_ehsize; /* ELF header size */ + Elf32_Half e_phentsize; /* program header entry size */ + Elf32_Half e_phnum; /* number of program header entries */ + Elf32_Half e_shentsize; /* section header entry size */ + Elf32_Half e_shnum; /* number of section header entries */ + Elf32_Half e_shstrndx; /* section header table's "section + header string table" entry offset */ +} Elf32_Ehdr; + +/* e_type */ +#define ET_NONE 0 /* No file type */ +#define ET_REL 1 /* relocatable file */ +#define ET_EXEC 2 /* executable file */ +#define ET_DYN 3 /* shared object file */ +#define ET_CORE 4 /* core file */ +#define ET_NUM 5 /* number of types */ +#define ET_LOOS 0xfe00 /* reserved range for operating */ +#define ET_HIOS 0xfeff /* system specific e_type */ +#define ET_LOPROC 0xff00 /* reserved range for processor */ +#define ET_HIPROC 0xffff /* specific e_type */ + +/* e_machine */ +#define EM_NONE 0 /* No Machine */ +#define EM_M32 1 /* AT&T WE 32100 */ +#define EM_SPARC 2 /* SPARC */ +#define EM_386 3 /* Intel 80386 */ +#define EM_68K 4 /* Motorola 68000 */ +#define EM_88K 5 /* Motorola 88000 */ +#if 0 +#define EM_486 6 /* RESERVED - was Intel 80486 */ +#endif +#define EM_860 7 /* Intel 80860 */ +#define EM_MIPS 8 /* MIPS R3000 Big-Endian only */ +#define EM_S370 9 /* IBM System/370 Processor */ +#define EM_MIPS_RS4_BE 10 /* MIPS R4000 Big-Endian */ +#if 0 +#define EM_SPARC64 11 /* RESERVED - was SPARC v9 + 64-bit unoffical */ +#endif +/* RESERVED 11-14 for future use */ +#define EM_PARISC 15 /* HPPA */ +/* RESERVED 16 for future use */ +#define EM_VPP500 17 /* Fujitsu VPP500 */ +#define EM_SPARC32PLUS 18 /* Enhanced instruction set SPARC */ +#define EM_960 19 /* Intel 80960 */ +#define EM_PPC 20 /* PowerPC */ +#define EM_PPC64 21 /* 64-bit PowerPC */ +#define EM_S390 22 /* IBM System/390 Processor */ +/* RESERVED 23-35 for future use */ +#define EM_V800 36 /* NEC V800 */ +#define EM_FR20 37 /* Fujitsu FR20 */ +#define EM_RH32 38 /* TRW RH-32 */ +#define EM_RCE 39 /* Motorola RCE */ +#define EM_ARM 40 /* Advanced Risc Machines ARM */ +#define EM_ALPHA 41 /* Digital Alpha */ +#define EM_SH 42 /* Hitachi SH */ +#define EM_SPARCV9 43 /* SPARC Version 9 */ +#define EM_TRICORE 44 /* Siemens TriCore embedded processor */ +#define EM_ARC 45 /* Argonaut RISC Core */ +#define EM_H8_300 46 /* Hitachi H8/300 */ +#define EM_H8_300H 47 /* Hitachi H8/300H */ +#define EM_H8S 48 /* Hitachi H8S */ +#define EM_H8_500 49 /* Hitachi H8/500 */ +#define EM_IA_64 50 /* Intel Merced */ +#define EM_MIPS_X 51 /* Stanford MIPS-X */ +#define EM_COLDFIRE 52 /* Motorola Coldfire */ +#define EM_68HC12 53 /* Motorola M68HC12 */ +#define EM_MMA 54 /* Fujitsu MMA Multimedia Accelerator*/ +#define EM_PCP 55 /* Siemens PCP */ +#define EM_NCPU 56 /* Sony nCPU embeeded RISC */ +#define EM_NDR1 57 /* Denso NDR1 microprocessor */ +#define EM_STARCORE 58 /* Motorola Start*Core processor */ +#define EM_ME16 59 /* Toyota ME16 processor */ +#define EM_ST100 60 /* STMicroelectronic ST100 processor */ +#define EM_TINYJ 61 /* Advanced Logic Corp. Tinyj emb.fam*/ +#define EM_X86_64 62 /* AMD x86-64 */ +#define EM_PDSP 63 /* Sony DSP Processor */ +/* RESERVED 64,65 for future use */ +#define EM_FX66 66 /* Siemens FX66 microcontroller */ +#define EM_ST9PLUS 67 /* STMicroelectronics ST9+ 8/16 mc */ +#define EM_ST7 68 /* STmicroelectronics ST7 8 bit mc */ +#define EM_68HC16 69 /* Motorola MC68HC16 microcontroller */ +#define EM_68HC11 70 /* Motorola MC68HC11 microcontroller */ +#define EM_68HC08 71 /* Motorola MC68HC08 microcontroller */ +#define EM_68HC05 72 /* Motorola MC68HC05 microcontroller */ +#define EM_SVX 73 /* Silicon Graphics SVx */ +#define EM_ST19 74 /* STMicroelectronics ST19 8 bit mc */ +#define EM_VAX 75 /* Digital VAX */ +#define EM_CHRIS 76 /* Axis Communications embedded proc. */ +#define EM_JAVELIN 77 /* Infineon Technologies emb. proc. */ +#define EM_FIREPATH 78 /* Element 14 64-bit DSP Processor */ +#define EM_ZSP 79 /* LSI Logic 16-bit DSP Processor */ +#define EM_MMIX 80 /* Donald Knuth's edu 64-bit proc. */ +#define EM_HUANY 81 /* Harvard University mach-indep objs */ +#define EM_PRISM 82 /* SiTera Prism */ +#define EM_AVR 83 /* Atmel AVR 8-bit microcontroller */ +#define EM_FR30 84 /* Fujitsu FR30 */ +#define EM_D10V 85 /* Mitsubishi DV10V */ +#define EM_D30V 86 /* Mitsubishi DV30V */ +#define EM_V850 87 /* NEC v850 */ +#define EM_M32R 88 /* Mitsubishi M32R */ +#define EM_MN10300 89 /* Matsushita MN10200 */ +#define EM_MN10200 90 /* Matsushita MN10200 */ +#define EM_PJ 91 /* picoJava */ +#define EM_NUM 92 /* number of machine types */ + +/* Version */ +#define EV_NONE 0 /* Invalid */ +#define EV_CURRENT 1 /* Current */ +#define EV_NUM 2 /* number of versions */ + +/* Section Header */ +typedef struct { + Elf32_Word sh_name; /* name - index into section header + string table section */ + Elf32_Word sh_type; /* type */ + Elf32_Word sh_flags; /* flags */ + Elf32_Addr sh_addr; /* address */ + Elf32_Off sh_offset; /* file offset */ + Elf32_Word sh_size; /* section size */ + Elf32_Word sh_link; /* section header table index link */ + Elf32_Word sh_info; /* extra information */ + Elf32_Word sh_addralign; /* address alignment */ + Elf32_Word sh_entsize; /* section entry size */ +} Elf32_Shdr; + +/* Special Section Indexes */ +#define SHN_UNDEF 0 /* undefined */ +#define SHN_LORESERVE 0xff00 /* lower bounds of reserved indexes */ +#define SHN_LOPROC 0xff00 /* reserved range for processor */ +#define SHN_HIPROC 0xff1f /* specific section indexes */ +#define SHN_LOOS 0xff20 /* reserved range for operating */ +#define SHN_HIOS 0xff3f /* specific semantics */ +#define SHN_ABS 0xfff1 /* absolute value */ +#define SHN_COMMON 0xfff2 /* common symbol */ +#define SHN_XINDEX 0xffff /* Index is an extra table */ +#define SHN_HIRESERVE 0xffff /* upper bounds of reserved indexes */ + +/* sh_type */ +#define SHT_NULL 0 /* inactive */ +#define SHT_PROGBITS 1 /* program defined information */ +#define SHT_SYMTAB 2 /* symbol table section */ +#define SHT_STRTAB 3 /* string table section */ +#define SHT_RELA 4 /* relocation section with addends*/ +#define SHT_HASH 5 /* symbol hash table section */ +#define SHT_DYNAMIC 6 /* dynamic section */ +#define SHT_NOTE 7 /* note section */ +#define SHT_NOBITS 8 /* no space section */ +#define SHT_REL 9 /* relation section without addends */ +#define SHT_SHLIB 10 /* reserved - purpose unknown */ +#define SHT_DYNSYM 11 /* dynamic symbol table section */ +#define SHT_INIT_ARRAY 14 /* Array of constructors */ +#define SHT_FINI_ARRAY 15 /* Array of destructors */ +#define SHT_PREINIT_ARRAY 16 /* Array of pre-constructors */ +#define SHT_GROUP 17 /* Section group */ +#define SHT_SYMTAB_SHNDX 18 /* Extended section indeces */ +#define SHT_NUM 19 /* number of section types */ +#define SHT_LOOS 0x60000000 /* Start OS-specific */ +#define SHT_HIOS 0x6fffffff /* End OS-specific */ +#define SHT_LOPROC 0x70000000 /* reserved range for processor */ +#define SHT_HIPROC 0x7fffffff /* specific section header types */ +#define SHT_LOUSER 0x80000000 /* reserved range for application */ +#define SHT_HIUSER 0xffffffff /* specific indexes */ + +/* Section names */ +#define ELF_BSS ".bss" /* uninitialized data */ +#define ELF_COMMENT ".comment" /* version control information */ +#define ELF_DATA ".data" /* initialized data */ +#define ELF_DATA1 ".data1" /* initialized data */ +#define ELF_DEBUG ".debug" /* debug */ +#define ELF_DYNAMIC ".dynamic" /* dynamic linking information */ +#define ELF_DYNSTR ".dynstr" /* dynamic string table */ +#define ELF_DYNSYM ".dynsym" /* dynamic symbol table */ +#define ELF_FINI ".fini" /* termination code */ +#define ELF_FINI_ARRAY ".fini_array" /* Array of destructors */ +#define ELF_GOT ".got" /* global offset table */ +#define ELF_HASH ".hash" /* symbol hash table */ +#define ELF_INIT ".init" /* initialization code */ +#define ELF_INIT_ARRAY ".init_array" /* Array of constuctors */ +#define ELF_INTERP ".interp" /* Pathname of program interpreter */ +#define ELF_LINE ".line" /* Symbolic line numnber information */ +#define ELF_NOTE ".note" /* Contains note section */ +#define ELF_PLT ".plt" /* Procedure linkage table */ +#define ELF_PREINIT_ARRAY ".preinit_array" /* Array of pre-constructors */ +#define ELF_REL_DATA ".rel.data" /* relocation data */ +#define ELF_REL_FINI ".rel.fini" /* relocation termination code */ +#define ELF_REL_INIT ".rel.init" /* relocation initialization code */ +#define ELF_REL_DYN ".rel.dyn" /* relocaltion dynamic link info */ +#define ELF_REL_RODATA ".rel.rodata" /* relocation read-only data */ +#define ELF_REL_TEXT ".rel.text" /* relocation code */ +#define ELF_RODATA ".rodata" /* read-only data */ +#define ELF_RODATA1 ".rodata1" /* read-only data */ +#define ELF_SHSTRTAB ".shstrtab" /* section header string table */ +#define ELF_STRTAB ".strtab" /* string table */ +#define ELF_SYMTAB ".symtab" /* symbol table */ +#define ELF_SYMTAB_SHNDX ".symtab_shndx"/* symbol table section index */ +#define ELF_TBSS ".tbss" /* thread local uninit data */ +#define ELF_TDATA ".tdata" /* thread local init data */ +#define ELF_TDATA1 ".tdata1" /* thread local init data */ +#define ELF_TEXT ".text" /* code */ + +/* Section Attribute Flags - sh_flags */ +#define SHF_WRITE 0x1 /* Writable */ +#define SHF_ALLOC 0x2 /* occupies memory */ +#define SHF_EXECINSTR 0x4 /* executable */ +#define SHF_MERGE 0x10 /* Might be merged */ +#define SHF_STRINGS 0x20 /* Contains NULL terminated strings */ +#define SHF_INFO_LINK 0x40 /* sh_info contains SHT index */ +#define SHF_LINK_ORDER 0x80 /* Preserve order after combining*/ +#define SHF_OS_NONCONFORMING 0x100 /* Non-standard OS specific handling */ +#define SHF_GROUP 0x200 /* Member of section group */ +#define SHF_TLS 0x400 /* Thread local storage */ +#define SHF_MASKOS 0x0ff00000 /* OS specific */ +#define SHF_MASKPROC 0xf0000000 /* reserved bits for processor */ + /* specific section attributes */ + +/* Section Group Flags */ +#define GRP_COMDAT 0x1 /* COMDAT group */ +#define GRP_MASKOS 0x0ff00000 /* Mask OS specific flags */ +#define GRP_MASKPROC 0xf0000000 /* Mask processor specific flags */ + +/* Symbol Table Entry */ +typedef struct elf32_sym { + Elf32_Word st_name; /* name - index into string table */ + Elf32_Addr st_value; /* symbol value */ + Elf32_Word st_size; /* symbol size */ + unsigned char st_info; /* type and binding */ + unsigned char st_other; /* 0 - no defined meaning */ + Elf32_Half st_shndx; /* section header index */ +} Elf32_Sym; + +/* Symbol table index */ +#define STN_UNDEF 0 /* undefined */ + +/* Extract symbol info - st_info */ +#define ELF32_ST_BIND(x) ((x) >> 4) +#define ELF32_ST_TYPE(x) (((unsigned int) x) & 0xf) +#define ELF32_ST_INFO(b,t) (((b) << 4) + ((t) & 0xf)) +#define ELF32_ST_VISIBILITY(x) ((x) & 0x3) + +/* Symbol Binding - ELF32_ST_BIND - st_info */ +#define STB_LOCAL 0 /* Local symbol */ +#define STB_GLOBAL 1 /* Global symbol */ +#define STB_WEAK 2 /* like global - lower precedence */ +#define STB_NUM 3 /* number of symbol bindings */ +#define STB_LOOS 10 /* reserved range for operating */ +#define STB_HIOS 12 /* system specific symbol bindings */ +#define STB_LOPROC 13 /* reserved range for processor */ +#define STB_HIPROC 15 /* specific symbol bindings */ + +/* Symbol type - ELF32_ST_TYPE - st_info */ +#define STT_NOTYPE 0 /* not specified */ +#define STT_OBJECT 1 /* data object */ +#define STT_FUNC 2 /* function */ +#define STT_SECTION 3 /* section */ +#define STT_FILE 4 /* file */ +#define STT_NUM 5 /* number of symbol types */ +#define STT_TLS 6 /* Thread local storage symbol */ +#define STT_LOOS 10 /* reserved range for operating */ +#define STT_HIOS 12 /* system specific symbol types */ +#define STT_LOPROC 13 /* reserved range for processor */ +#define STT_HIPROC 15 /* specific symbol types */ + +/* Symbol visibility - ELF32_ST_VISIBILITY - st_other */ +#define STV_DEFAULT 0 /* Normal visibility rules */ +#define STV_INTERNAL 1 /* Processor specific hidden class */ +#define STV_HIDDEN 2 /* Symbol unavailable in other mods */ +#define STV_PROTECTED 3 /* Not preemptible, not exported */ + + +/* Relocation entry with implicit addend */ +typedef struct +{ + Elf32_Addr r_offset; /* offset of relocation */ + Elf32_Word r_info; /* symbol table index and type */ +} Elf32_Rel; + +/* Relocation entry with explicit addend */ +typedef struct +{ + Elf32_Addr r_offset; /* offset of relocation */ + Elf32_Word r_info; /* symbol table index and type */ + Elf32_Sword r_addend; +} Elf32_Rela; + +/* Extract relocation info - r_info */ +#define ELF32_R_SYM(i) ((i) >> 8) +#define ELF32_R_TYPE(i) ((unsigned char) (i)) +#define ELF32_R_INFO(s,t) (((s) << 8) + (unsigned char)(t)) + +/* Program Header */ +typedef struct { + Elf32_Word p_type; /* segment type */ + Elf32_Off p_offset; /* segment offset */ + Elf32_Addr p_vaddr; /* virtual address of segment */ + Elf32_Addr p_paddr; /* physical address - ignored? */ + Elf32_Word p_filesz; /* number of bytes in file for seg. */ + Elf32_Word p_memsz; /* number of bytes in mem. for seg. */ + Elf32_Word p_flags; /* flags */ + Elf32_Word p_align; /* memory alignment */ +} Elf32_Phdr; + +/* Segment types - p_type */ +#define PT_NULL 0 /* unused */ +#define PT_LOAD 1 /* loadable segment */ +#define PT_DYNAMIC 2 /* dynamic linking section */ +#define PT_INTERP 3 /* the RTLD */ +#define PT_NOTE 4 /* auxiliary information */ +#define PT_SHLIB 5 /* reserved - purpose undefined */ +#define PT_PHDR 6 /* program header */ +#define PT_TLS 7 /* Thread local storage template */ +#define PT_NUM 8 /* Number of segment types */ +#define PT_LOOS 0x60000000 /* reserved range for operating */ +#define PT_HIOS 0x6fffffff /* system specific segment types */ +#define PT_LOPROC 0x70000000 /* reserved range for processor */ +#define PT_HIPROC 0x7fffffff /* specific segment types */ + +/* Segment flags - p_flags */ +#define PF_X 0x1 /* Executable */ +#define PF_W 0x2 /* Writable */ +#define PF_R 0x4 /* Readable */ +#define PF_MASKOS 0x0ff00000 /* OS specific segment flags */ +#define PF_MASKPROC 0xf0000000 /* reserved bits for processor */ + /* specific segment flags */ +/* Dynamic structure */ +typedef struct +{ + Elf32_Sword d_tag; /* controls meaning of d_val */ + union + { + Elf32_Word d_val; /* Multiple meanings - see d_tag */ + Elf32_Addr d_ptr; /* program virtual address */ + } d_un; +} Elf32_Dyn; + +extern Elf32_Dyn _DYNAMIC[]; + +/* Dynamic Array Tags - d_tag */ +#define DT_NULL 0 /* marks end of _DYNAMIC array */ +#define DT_NEEDED 1 /* string table offset of needed lib */ +#define DT_PLTRELSZ 2 /* size of relocation entries in PLT */ +#define DT_PLTGOT 3 /* address PLT/GOT */ +#define DT_HASH 4 /* address of symbol hash table */ +#define DT_STRTAB 5 /* address of string table */ +#define DT_SYMTAB 6 /* address of symbol table */ +#define DT_RELA 7 /* address of relocation table */ +#define DT_RELASZ 8 /* size of relocation table */ +#define DT_RELAENT 9 /* size of relocation entry */ +#define DT_STRSZ 10 /* size of string table */ +#define DT_SYMENT 11 /* size of symbol table entry */ +#define DT_INIT 12 /* address of initialization func. */ +#define DT_FINI 13 /* address of termination function */ +#define DT_SONAME 14 /* string table offset of shared obj */ +#define DT_RPATH 15 /* string table offset of library + search path */ +#define DT_SYMBOLIC 16 /* start sym search in shared obj. */ +#define DT_REL 17 /* address of rel. tbl. w addends */ +#define DT_RELSZ 18 /* size of DT_REL relocation table */ +#define DT_RELENT 19 /* size of DT_REL relocation entry */ +#define DT_PLTREL 20 /* PLT referenced relocation entry */ +#define DT_DEBUG 21 /* bugger */ +#define DT_TEXTREL 22 /* Allow rel. mod. to unwritable seg */ +#define DT_JMPREL 23 /* add. of PLT's relocation entries */ +#define DT_BIND_NOW 24 /* Process relocations of object */ +#define DT_INIT_ARRAY 25 /* Array with addresses of init fct */ +#define DT_FINI_ARRAY 26 /* Array with addresses of fini fct */ +#define DT_INIT_ARRAYSZ 27 /* Size in bytes of DT_INIT_ARRAY */ +#define DT_FINI_ARRAYSZ 28 /* Size in bytes of DT_FINI_ARRAY */ +#define DT_RUNPATH 29 /* Library search path */ +#define DT_FLAGS 30 /* Flags for the object being loaded */ +#define DT_ENCODING 32 /* Start of encoded range */ +#define DT_PREINIT_ARRAY 32 /* Array with addresses of preinit fct*/ +#define DT_PREINIT_ARRAYSZ 33 /* size in bytes of DT_PREINIT_ARRAY */ +#define DT_NUM 34 /* Number used. */ +#define DT_LOOS 0x60000000 /* reserved range for OS */ +#define DT_HIOS 0x6fffffff /* specific dynamic array tags */ +#define DT_LOPROC 0x70000000 /* reserved range for processor */ +#define DT_HIPROC 0x7fffffff /* specific dynamic array tags */ + +/* Dynamic Tag Flags - d_un.d_val */ +#define DF_ORIGIN 0x01 /* Object may use DF_ORIGIN */ +#define DF_SYMBOLIC 0x02 /* Symbol resolutions starts here */ +#define DF_TEXTREL 0x04 /* Object contains text relocations */ +#define DF_BIND_NOW 0x08 /* No lazy binding for this object */ +#define DF_STATIC_TLS 0x10 /* Static thread local storage */ + +/* Standard ELF hashing function */ +unsigned long elf_hash(const unsigned char *name); + +#define ELF_TARG_VER 1 /* The ver for which this code is intended */ + +/* + * XXX - PowerPC defines really don't belong in here, + * but we'll put them in for simplicity. + */ + +/* Values for Elf32/64_Ehdr.e_flags. */ +#define EF_PPC_EMB 0x80000000 /* PowerPC embedded flag */ + +/* Cygnus local bits below */ +#define EF_PPC_RELOCATABLE 0x00010000 /* PowerPC -mrelocatable flag*/ +#define EF_PPC_RELOCATABLE_LIB 0x00008000 /* PowerPC -mrelocatable-lib + flag */ + +/* PowerPC relocations defined by the ABIs */ +#define R_PPC_NONE 0 +#define R_PPC_ADDR32 1 /* 32bit absolute address */ +#define R_PPC_ADDR24 2 /* 26bit address, 2 bits ignored. */ +#define R_PPC_ADDR16 3 /* 16bit absolute address */ +#define R_PPC_ADDR16_LO 4 /* lower 16bit of absolute address */ +#define R_PPC_ADDR16_HI 5 /* high 16bit of absolute address */ +#define R_PPC_ADDR16_HA 6 /* adjusted high 16bit */ +#define R_PPC_ADDR14 7 /* 16bit address, 2 bits ignored */ +#define R_PPC_ADDR14_BRTAKEN 8 +#define R_PPC_ADDR14_BRNTAKEN 9 +#define R_PPC_REL24 10 /* PC relative 26 bit */ +#define R_PPC_REL14 11 /* PC relative 16 bit */ +#define R_PPC_REL14_BRTAKEN 12 +#define R_PPC_REL14_BRNTAKEN 13 +#define R_PPC_GOT16 14 +#define R_PPC_GOT16_LO 15 +#define R_PPC_GOT16_HI 16 +#define R_PPC_GOT16_HA 17 +#define R_PPC_PLTREL24 18 +#define R_PPC_COPY 19 +#define R_PPC_GLOB_DAT 20 +#define R_PPC_JMP_SLOT 21 +#define R_PPC_RELATIVE 22 +#define R_PPC_LOCAL24PC 23 +#define R_PPC_UADDR32 24 +#define R_PPC_UADDR16 25 +#define R_PPC_REL32 26 +#define R_PPC_PLT32 27 +#define R_PPC_PLTREL32 28 +#define R_PPC_PLT16_LO 29 +#define R_PPC_PLT16_HI 30 +#define R_PPC_PLT16_HA 31 +#define R_PPC_SDAREL16 32 +#define R_PPC_SECTOFF 33 +#define R_PPC_SECTOFF_LO 34 +#define R_PPC_SECTOFF_HI 35 +#define R_PPC_SECTOFF_HA 36 +/* Keep this the last entry. */ +#define R_PPC_NUM 37 + +/* The remaining relocs are from the Embedded ELF ABI, and are not + in the SVR4 ELF ABI. */ +#define R_PPC_EMB_NADDR32 101 +#define R_PPC_EMB_NADDR16 102 +#define R_PPC_EMB_NADDR16_LO 103 +#define R_PPC_EMB_NADDR16_HI 104 +#define R_PPC_EMB_NADDR16_HA 105 +#define R_PPC_EMB_SDAI16 106 +#define R_PPC_EMB_SDA2I16 107 +#define R_PPC_EMB_SDA2REL 108 +#define R_PPC_EMB_SDA21 109 /* 16 bit offset in SDA */ +#define R_PPC_EMB_MRKREF 110 +#define R_PPC_EMB_RELSEC16 111 +#define R_PPC_EMB_RELST_LO 112 +#define R_PPC_EMB_RELST_HI 113 +#define R_PPC_EMB_RELST_HA 114 +#define R_PPC_EMB_BIT_FLD 115 +#define R_PPC_EMB_RELSDA 116 /* 16 bit relative offset in SDA */ + +/* Diab tool relocations. */ +#define R_PPC_DIAB_SDA21_LO 180 /* like EMB_SDA21, but lower 16 bit */ +#define R_PPC_DIAB_SDA21_HI 181 /* like EMB_SDA21, but high 16 bit */ +#define R_PPC_DIAB_SDA21_HA 182 /* like EMB_SDA21, adjusted high 16 */ +#define R_PPC_DIAB_RELSDA_LO 183 /* like EMB_RELSDA, but lower 16 bit */ +#define R_PPC_DIAB_RELSDA_HI 184 /* like EMB_RELSDA, but high 16 bit */ +#define R_PPC_DIAB_RELSDA_HA 185 /* like EMB_RELSDA, adjusted high 16 */ + +/* This is a phony reloc to handle any old fashioned TOC16 references + that may still be in object files. */ +#define R_PPC_TOC16 255 + +#endif /* _ELF_H */ diff --git a/sps2_basement/core/base/errno.h b/sps2_basement/core/base/errno.h new file mode 100644 index 0000000..a1318b8 --- /dev/null +++ b/sps2_basement/core/base/errno.h @@ -0,0 +1,140 @@ +/* + * U-boot - errno.h Error number defines + * + * Copyright (c) 2005-2007 Analog Devices Inc. + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#ifndef _GENERIC_ERRNO_H +#define _GENERIC_ERRNO_H + +#define EPERM 1 /* Operation not permitted */ +#define ENOENT 2 /* No such file or directory */ +#define ESRCH 3 /* No such process */ +#define EINTR 4 /* Interrupted system call */ +#define EIO 5 /* I/O error */ +#define ENXIO 6 /* No such device or address */ +#define E2BIG 7 /* Argument list too long */ +#define ENOEXEC 8 /* Exec format error */ +#define EBADF 9 /* Bad file number */ +#define ECHILD 10 /* No child processes */ +#define EAGAIN 11 /* Try again */ +#define ENOMEM 12 /* Out of memory */ +#define EACCES 13 /* Permission denied */ +#define EFAULT 14 /* Bad address */ +#define ENOTBLK 15 /* Block device required */ +#define EBUSY 16 /* Device or resource busy */ +#define EEXIST 17 /* File exists */ +#define EXDEV 18 /* Cross-device link */ +#define ENODEV 19 /* No such device */ +#define ENOTDIR 20 /* Not a directory */ +#define EISDIR 21 /* Is a directory */ +#define EINVAL 22 /* Invalid argument */ +#define ENFILE 23 /* File table overflow */ +#define EMFILE 24 /* Too many open files */ +#define ENOTTY 25 /* Not a typewriter */ +#define ETXTBSY 26 /* Text file busy */ +#define EFBIG 27 /* File too large */ +#define ENOSPC 28 /* No space left on device */ +#define ESPIPE 29 /* Illegal seek */ +#define EROFS 30 /* Read-only file system */ +#define EMLINK 31 /* Too many links */ +#define EPIPE 32 /* Broken pipe */ +#define EDOM 33 /* Math argument out of domain of func */ +#define ERANGE 34 /* Math result not representable */ +#define EDEADLK 35 /* Resource deadlock would occur */ +#define ENAMETOOLONG 36 /* File name too long */ +#define ENOLCK 37 /* No record locks available */ +#define ENOSYS 38 /* Function not implemented */ +#define ENOTEMPTY 39 /* Directory not empty */ +#define ELOOP 40 /* Too many symbolic links encountered */ +#define EWOULDBLOCK EAGAIN 41 /* Operation would block */ +#define ENOMSG 42 /* No message of desired type */ +#define EIDRM 43 /* Identifier removed */ +#define ECHRNG 44 /* Channel number out of range */ +#define EL2NSYNC 45 /* Level 2 not synchronized */ +#define EL3HLT 46 /* Level 3 halted */ +#define EL3RST 47 /* Level 3 reset */ +#define ELNRNG 48 /* Link number out of range */ +#define EUNATCH 49 /* Protocol driver not attached */ +#define ENOCSI 50 /* No CSI structure available */ +#define EL2HLT 51 /* Level 2 halted */ +#define EBADE 52 /* Invalid exchange */ +#define EBADR 53 /* Invalid request descriptor */ +#define EXFULL 54 /* Exchange full */ +#define ENOANO 55 /* No anode */ +#define EBADRQC 56 /* Invalid request code */ +#define EBADSLT 57 /* Invalid slot */ + +#define EDEADLOCK EDEADLK + +#define EBFONT 59 /* Bad font file format */ +#define ENOSTR 60 /* Device not a stream */ +#define ENODATA 61 /* No data available */ +#define ETIME 62 /* Timer expired */ +#define ENOSR 63 /* Out of streams resources */ +#define ENONET 64 /* Machine is not on the network */ +#define ENOPKG 65 /* Package not installed */ +#define EREMOTE 66 /* Object is remote */ +#define ENOLINK 67 /* Link has been severed */ +#define EADV 68 /* Advertise error */ +#define ESRMNT 69 /* Srmount error */ +#define ECOMM 70 /* Communication error on send */ +#define EPROTO 71 /* Protocol error */ +#define EMULTIHOP 72 /* Multihop attempted */ +#define EDOTDOT 73 /* RFS specific error */ +#define EBADMSG 74 /* Not a data message */ +#define EOVERFLOW 75 /* Value too large for defined data type */ +#define ENOTUNIQ 76 /* Name not unique on network */ +#define EBADFD 77 /* File descriptor in bad state */ +#define EREMCHG 78 /* Remote address changed */ +#define ELIBACC 79 /* Can not access a needed shared library */ +#define ELIBBAD 80 /* Accessing a corrupted shared library */ +#define ELIBSCN 81 /* .lib section in a.out corrupted */ +#define ELIBMAX 82 /* Attempting to link in too many shared libraries */ +#define ELIBEXEC 83 /* Cannot exec a shared library directly */ +#define EILSEQ 84 /* Illegal byte sequence */ +#define ERESTART 85 /* Interrupted system call should be restarted */ +#define ESTRPIPE 86 /* Streams pipe error */ +#define EUSERS 87 /* Too many users */ +#define ENOTSOCK 88 /* Socket operation on non-socket */ +#define EDESTADDRREQ 89 /* Destination address required */ +#define EMSGSIZE 90 /* Message too long */ +#define EPROTOTYPE 91 /* Protocol wrong type for socket */ +#define ENOPROTOOPT 92 /* Protocol not available */ +#define EPROTONOSUPPORT 93 /* Protocol not supported */ +#define ESOCKTNOSUPPORT 94 /* Socket type not supported */ +#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define EPFNOSUPPORT 96 /* Protocol family not supported */ +#define EAFNOSUPPORT 97 /* Address family not supported by protocol */ +#define EADDRINUSE 98 /* Address already in use */ +#define EADDRNOTAVAIL 99 /* Cannot assign requested address */ +#define ENETDOWN 100 /* Network is down */ +#define ENETUNREACH 101 /* Network is unreachable */ +#define ENETRESET 102 /* Network dropped connection because of reset */ +#define ECONNABORTED 103 /* Software caused connection abort */ +#define ECONNRESET 104 /* Connection reset by peer */ +#define ENOBUFS 105 /* No buffer space available */ +#define EISCONN 106 /* Transport endpoint is already connected */ +#define ENOTCONN 107 /* Transport endpoint is not connected */ +#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ +#define ETOOMANYREFS 109 /* Too many references: cannot splice */ +#define ETIMEDOUT 110 /* Connection timed out */ +#define ECONNREFUSED 111 /* Connection refused */ +#define EHOSTDOWN 112 /* Host is down */ +#define EHOSTUNREACH 113 /* No route to host */ +#define EALREADY 114 /* Operation already in progress */ +#define EINPROGRESS 115 /* Operation now in progress */ +#define ESTALE 116 /* Stale NFS file handle */ +#define EUCLEAN 117 /* Structure needs cleaning */ +#define ENOTNAM 118 /* Not a XENIX named type file */ +#define ENAVAIL 119 /* No XENIX semaphores available */ +#define EISNAM 120 /* Is a named type file */ +#define EREMOTEIO 121 /* Remote I/O error */ +#define EDQUOT 122 /* Quota exceeded */ +#define ENOMEDIUM 123 /* No medium found */ +#define EMEDIUMTYPE 124 /* Wrong medium type */ + +#endif + diff --git a/sps2_basement/hardware/Makefile b/sps2_basement/hardware/Makefile new file mode 100644 index 0000000..0be6085 --- /dev/null +++ b/sps2_basement/hardware/Makefile @@ -0,0 +1,34 @@ +OBJECTSEKS = eks1.o eks2.o eks3.o vutest.o eks4.o eks5.o eks5vu.o eks6.o eks7.o eks7vu.o +OBJECTSLIB = texture.o math.o dma.o matrix.o gif.o vu.o malloc.o +OBJECTSDATA = logo.o logo_alpha.o dot.o dot2.o font.o font_alpha.o mainbg1.o mainbg1_alpha.o mainbg2.o mainbg2_alpha.o fslogo.o kantlogo.o kantfade.o scroll.o druckluft.o druckluft_a.o gibson.o gibson_a.o + +OBJECTS = main.o $(OBJECTSEKS) $(OBJECTSLIB) $(OBJECTSDATA) +EXEFILE = main.elf + +#CPATH = ../ee-bin/bin/mips64r5900-sce-elf- +CPATH = +CC = $(CPATH)gcc.exe +VAS = $(CPATH)dvp-as.exe +AS = $(CPATH)as.exe +LD = $(CPATH)ld.exe +OBJCOPY = $(CPATH)objcopy.exe +ASFLAGS = -mcpu=5900 -EL +CPPFLAGS = -fshort-double -O6 -c -Werror +LFLAGS = -Tlinkfile + +.SUFFIXES: .c .s .vsm .o .pcx .elf .asm + +.c.o: + $(CC) $(CPPFLAGS) $< -o $@ +.pcx.asm: + ./rawtoasm $< $@ $@ +.asm.o: + $(AS) $(ASFLAGS) $< -o $@ +.vsm.o: + $(VAS) $< -o $@ +.s.o: + $(AS) $(ASFLAGS) $< -o $@ +$(EXEFILE):$(OBJECTS); + $(CC) $(LFLAGS) -o $(EXEFILE) $(OBJECTS) +crt0.s.o: + $(AS) $(ASFLAGS) crt0.s -o crt0.o diff --git a/sps2_basement/hardware/common/alloc.c b/sps2_basement/hardware/common/alloc.c new file mode 100644 index 0000000..d9718f1 --- /dev/null +++ b/sps2_basement/hardware/common/alloc.c @@ -0,0 +1,457 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Copyright (c) 2004 adresd +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Basic alloc library + */ + +#include + +#include "types.h" +#include "defs.h" +#include "alloc.h" +#include "irx_imports.h" + + +#define MODNAME "alloc" +IRX_ID("Basic alloc library", 1, 1); + +extern struct irx_export_table _exp_alloc; + +static vs32 alloc_sema = -1; + +#define DEFAULT_HEAP_SIZE 128 * 1024 + +u32 heap_size = DEFAULT_HEAP_SIZE; +static u8 * heap_start, * heap_end, * _heap_ptr; + +static void alloc_lock() { + if (alloc_sema >= 0) { + WaitSema(alloc_sema); + } +} + +static void alloc_unlock() { + if (alloc_sema >= 0) { + SignalSema(alloc_sema); + } +} + +int _start(int argc, char **argv) +{ + iop_sema_t sem_info; + + if (RegisterLibraryEntries(&_exp_alloc) != 0) + return 1; + + // check arguments for a heap_size parameter. + if (argc > 1) { + heap_size = strtoul(argv[1], NULL, 0); + } + + if (!(heap_start = AllocSysMemory(ALLOC_FIRST, heap_size, NULL))) + return -1; + heap_end = heap_start + heap_size; + _heap_ptr = heap_start; + + sem_info.attr = 1; + sem_info.option = 1; + sem_info.initial = 1; + sem_info.max = 1; + + alloc_sema = CreateSema(&sem_info); + + return 0; +} + + +int shutdown() +{ + if (alloc_sema >= 0) { + DeleteSema(alloc_sema); + } + + FreeSysMemory(heap_start); + + return 0; +} + +/** Use this to set the default malloc() alignment. */ +#define DEFAULT_ALIGNMENT 16 + +#ifndef ALIGN +#define ALIGN(x, align) (((x)+((align)-1))&~((align)-1)) +#endif + +/* _heap_mem_block_header structure. */ +typedef struct _heap_mem_header { + void * ptr; + size_t size; + struct _heap_mem_header * prev; + struct _heap_mem_header * next; +} heap_mem_header_t; + +static void * __alloc_heap_base = NULL; +static heap_mem_header_t *__alloc_heap_head = NULL; +static heap_mem_header_t *__alloc_heap_tail = NULL; + +static void * alloc_sbrk(size_t increment) +{ + u8 *mp, *ret = (void *)-1; + + if (increment == 0) + return _heap_ptr; + + /* If the area we want to allocated is past the end of our heap, we have a problem. */ + mp = _heap_ptr + increment; + if (mp <= heap_end) { + ret = _heap_ptr; + _heap_ptr = mp; + } + + return ret; +} + +/** Find the lowest block that we can allocate AFTER, returning NULL if there are none. */ +static heap_mem_header_t * _heap_mem_fit(heap_mem_header_t *head, size_t size) +{ + heap_mem_header_t *prev_mem = head; + u32 prev_top, next_bot; + + while (prev_mem != NULL) { + if (prev_mem->next != NULL) { + prev_top = (u32)prev_mem->ptr + prev_mem->size; + next_bot = (u32)prev_mem->next - prev_top; + if (next_bot >= size) + return prev_mem; + } + + prev_mem = prev_mem->next; + } + + return prev_mem; +} + +void * malloc(size_t size) +{ + void *ptr = NULL, *mem_ptr; + heap_mem_header_t *new_mem, *prev_mem; + size_t mem_sz, heap_align_bytes; + + mem_sz = size + sizeof(heap_mem_header_t); + + if ((mem_sz & (DEFAULT_ALIGNMENT - 1)) != 0) + mem_sz = ALIGN(mem_sz, DEFAULT_ALIGNMENT); + + alloc_lock(); + + /* If we don't have any allocated blocks, reserve the first block from + the OS and initialize __alloc_heap_tail. */ + if (__alloc_heap_head == NULL) { + /* Align the bottom of the heap to our default alignment. */ + if (__alloc_heap_base == NULL) { + heap_align_bytes = (u32)alloc_sbrk(0) & (DEFAULT_ALIGNMENT - 1); + alloc_sbrk(heap_align_bytes); + __alloc_heap_base = alloc_sbrk(0); + } + + /* Allocate the physical heap and setup the head block. */ + if ((mem_ptr = alloc_sbrk(mem_sz)) == (void *)-1) + return ptr; /* NULL */ + + ptr = (void *)((u32)mem_ptr + sizeof(heap_mem_header_t)); + + __alloc_heap_head = (heap_mem_header_t *)mem_ptr; + __alloc_heap_head->ptr = ptr; + __alloc_heap_head->size = mem_sz - sizeof(heap_mem_header_t); + __alloc_heap_head->prev = NULL; + __alloc_heap_head->next = NULL; + + __alloc_heap_tail = __alloc_heap_head; + + alloc_unlock(); + return ptr; + } + + /* Check to see if there's free space at the bottom of the heap. */ + if ((__alloc_heap_base + mem_sz) < (void *)__alloc_heap_head) { + new_mem = (heap_mem_header_t *)__alloc_heap_base; + ptr = (void *)((u32)new_mem + sizeof(heap_mem_header_t)); + + new_mem->ptr = ptr; + new_mem->size = mem_sz - sizeof(heap_mem_header_t); + new_mem->prev = NULL; + new_mem->next = __alloc_heap_head; + new_mem->next->prev = new_mem; + __alloc_heap_head = new_mem; + + alloc_unlock(); + return ptr; + } + + /* See if we can allocate the block without extending the heap. */ + prev_mem = _heap_mem_fit(__alloc_heap_head, mem_sz); + if (prev_mem != NULL) { + new_mem = (heap_mem_header_t *)((u32)prev_mem->ptr + prev_mem->size); + ptr = (void *)((u32)new_mem + sizeof(heap_mem_header_t)); + + new_mem->ptr = ptr; + new_mem->size = mem_sz - sizeof(heap_mem_header_t); + new_mem->prev = prev_mem; + new_mem->next = prev_mem->next; + new_mem->next->prev = new_mem; + prev_mem->next = new_mem; + + alloc_unlock(); + return ptr; + } + + /* Extend the heap, but make certain the block is inserted in + order. */ + if ((mem_ptr = alloc_sbrk(mem_sz)) == (void *)-1) { + alloc_unlock(); + return ptr; /* NULL */ + } + + ptr = (void *)((u32)mem_ptr + sizeof(heap_mem_header_t)); + + new_mem = (heap_mem_header_t *)mem_ptr; + new_mem->ptr = ptr; + new_mem->size = mem_sz - sizeof(heap_mem_header_t); + new_mem->prev = __alloc_heap_tail; + new_mem->next = NULL; + + __alloc_heap_tail->next = new_mem; + __alloc_heap_tail = new_mem; + + alloc_unlock(); + return ptr; +} + +void * realloc(void *ptr, size_t size) +{ + heap_mem_header_t *prev_mem; + void *new_ptr = NULL; + + if (!size && ptr != NULL) { + free(ptr); + return new_ptr; + } + + if (ptr == NULL) + return malloc(size); + + if ((size & (DEFAULT_ALIGNMENT - 1)) != 0) + size = ALIGN(size, DEFAULT_ALIGNMENT); + + alloc_lock(); + prev_mem = (heap_mem_header_t *)((u32)ptr - sizeof(heap_mem_header_t)); + + + /* Don't do anything if asked for same sized block. */ + /* If the new size is shorter, let's just shorten the block. */ + if (prev_mem->size >= size) { + /* However, if this is the last block, we have to shrink the heap. */ + if (!prev_mem->next) + alloc_sbrk(ptr + size - alloc_sbrk(0)); + prev_mem->size = size; + + alloc_unlock(); + return ptr; + } + + + /* We are asked for a larger block of memory. */ + + /* Are we the last memory block ? */ + if (!prev_mem->next) { + /* Yes, let's just extend the heap then. */ + if (alloc_sbrk(size - prev_mem->size) == (void*) -1) + return NULL; + prev_mem->size = size; + + alloc_unlock(); + return ptr; + } + + /* Is the next block far enough so we can extend the current block ? */ + if ((prev_mem->next->ptr - ptr) > size) { + prev_mem->size = size; + + alloc_unlock(); + return ptr; + } + + alloc_unlock(); + + /* We got out of luck, let's allocate a new block of memory. */ + if ((new_ptr = malloc(size)) == NULL) + return new_ptr; + + /* New block is larger, we only copy the old data. */ + memcpy(new_ptr, ptr, prev_mem->size); + + free(ptr); + return new_ptr; +} + +void * calloc(size_t n, size_t size) +{ + void *ptr = NULL; + size_t sz = n * size; + + if ((ptr = malloc(sz)) == NULL) + return ptr; + + memset(ptr, 0, sz); + return ptr; +} + +void * memalign(size_t align, size_t size) +{ + heap_mem_header_t new_mem; + heap_mem_header_t *cur_mem; + heap_mem_header_t *old_mem; + void *ptr = NULL; + + if (align <= DEFAULT_ALIGNMENT) + return malloc(size); + + /* Allocate with extra alignment bytes just in case it isn't aligned + properly by malloc. */ + if ((ptr = malloc(size + align)) == NULL) + return ptr; /* NULL */ + + /* If malloc returned it aligned for us we're fine. */ + if (((u32)ptr & (align - 1)) == 0) + return ptr; + + alloc_lock(); + cur_mem = (heap_mem_header_t *)((u32)ptr - sizeof(heap_mem_header_t)); + cur_mem->size -= align; + + /* Otherwise, align the pointer and fixup our hearder accordingly. */ + ptr = (void *)ALIGN((u32)ptr, align); + + old_mem = cur_mem; + + /* Copy the heap_mem_header_t locally, before repositioning (to make + sure we don't overwrite ourselves. */ + memcpy(&new_mem, cur_mem, sizeof(heap_mem_header_t)); + cur_mem = (heap_mem_header_t *)((u32)ptr - sizeof(heap_mem_header_t)); + memcpy(cur_mem, &new_mem, sizeof(heap_mem_header_t)); + + if (cur_mem->prev) + cur_mem->prev->next = cur_mem; + if (cur_mem->next) + cur_mem->next->prev = cur_mem; + + if (__alloc_heap_head == old_mem) + __alloc_heap_head = cur_mem; + + if (__alloc_heap_tail == old_mem) + __alloc_heap_tail = cur_mem; + + cur_mem->ptr = ptr; + + alloc_unlock(); + return ptr; +} + +void free(void *ptr) +{ + heap_mem_header_t *cur; + void *heap_top; + size_t size; + + if (!ptr) + return; + + alloc_lock(); + + if (!__alloc_heap_head) { + alloc_unlock(); + return; + } + + + /* Freeing the head pointer is a special case. */ + if (ptr == __alloc_heap_head->ptr) { + size = __alloc_heap_head->size + + (size_t)(__alloc_heap_head->ptr - (void *)__alloc_heap_head); + + __alloc_heap_head = __alloc_heap_head->next; + + if (__alloc_heap_head != NULL) { + __alloc_heap_head->prev = NULL; + } else { + __alloc_heap_tail = NULL; + + alloc_sbrk(-size); + } + + alloc_unlock(); + return; + } + + cur = __alloc_heap_head; + while (ptr != cur->ptr) { + /* ptr isn't in our list */ + if (cur->next == NULL) { + alloc_unlock(); + return; + } + + cur = cur->next; + } + + /* Deallocate the block. */ + if (cur->next != NULL) { + cur->next->prev = cur->prev; + } else { + /* If this block was the last one in the list, shrink the heap. */ + __alloc_heap_tail = cur->prev; + + /* We need to free (heap top) - (prev->ptr + prev->size), or else + we'll end up with an unallocatable block of heap. */ + heap_top = alloc_sbrk(0); + size = (u32)heap_top - (u32)(cur->prev->ptr + cur->prev->size); + alloc_sbrk(-size); + } + + cur->prev->next = cur->next; + + alloc_unlock(); +} + +void * __mem_walk_begin() { + return __alloc_heap_head; +} + +void __mem_walk_read(void * token, u32 * size, void ** ptr, int * valid) { + heap_mem_header_t * cur = (heap_mem_header_t *) token; + + *valid = 1; + + *size = cur->size; + *ptr = cur->ptr; +} + +void * __mem_walk_inc(void * token) { + heap_mem_header_t * cur = (heap_mem_header_t *) token; + + return cur->next; +} + +int __mem_walk_end(void * token) { + return token == NULL; +} diff --git a/sps2_basement/hardware/common/alloc.h b/sps2_basement/hardware/common/alloc.h new file mode 100644 index 0000000..a750a46 --- /dev/null +++ b/sps2_basement/hardware/common/alloc.h @@ -0,0 +1,45 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Basic alloc library + */ + +#ifndef __ALLOC_H__ +#define __ALLOC_H__ + +#include +#include + +void * malloc(size_t size); +void * realloc(void * ptr, size_t size); +void free(void * ptr); +void * calloc(size_t n, size_t size); +void * memalign(size_t align, size_t size); +void * __mem_walk_begin(); +void __mem_walk_read(void * token, u32 * size, void ** ptr, int * valid); +void * __mem_walk_inc(void * token); +int __mem_walk_end(void * token); + +#define alloc_IMPORTS_start DECLARE_IMPORT_TABLE(alloc, 1, 1) +#define alloc_IMPORTS_end END_IMPORT_TABLE + +#define I_malloc DECLARE_IMPORT(4, malloc) +#define I_realloc DECLARE_IMPORT(5, realloc) +#define I_free DECLARE_IMPORT(6, free) +#define I_calloc DECLARE_IMPORT(7, calloc) +#define I_memalign DECLARE_IMPORT(8, memalign) +#define I___mem_walk_begin DECLARE_IMPORT(9, __mem_walk_begin) +#define I___mem_walk_read DECLARE_IMPORT(10, __mem_walk_read) +#define I___mem_walk_inc DECLARE_IMPORT(11, __mem_walk_inc) +#define I___mem_walk_end DECLARE_IMPORT(12, __mem_walk_end) + +#endif /* __ALLOC_H__ */ diff --git a/sps2_basement/hardware/debug/Makefile b/sps2_basement/hardware/debug/Makefile new file mode 100644 index 0000000..ae09885 --- /dev/null +++ b/sps2_basement/hardware/debug/Makefile @@ -0,0 +1,12 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +SUBDIRS = iopdebug iop_sbusdbg ioptrap sior + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/Rules.make diff --git a/sps2_basement/hardware/debug/assert.h b/sps2_basement/hardware/debug/assert.h new file mode 100644 index 0000000..b681a85 --- /dev/null +++ b/sps2_basement/hardware/debug/assert.h @@ -0,0 +1,29 @@ +/* + assert.h +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "_ansi.h" + +#undef assert + +#ifdef NDEBUG /* required by ANSI standard */ +#define assert(p) ((void)0) +#else + +#ifdef __STDC__ +#define assert(e) ((e) ? (void)0 : __assert(__FILE__, __LINE__, #e)) +#else /* PCC */ +#define assert(e) ((e) ? (void)0 : __assert(__FILE__, __LINE__, "e")) +#endif + +#endif /* NDEBUG */ + +void _EXFUN(__assert,(const char *, int, const char *)); + +#ifdef __cplusplus +} +#endif diff --git a/sps2_basement/hardware/debug/iop_sbusdbg/Makefile b/sps2_basement/hardware/debug/iop_sbusdbg/Makefile new file mode 100644 index 0000000..acb2ca0 --- /dev/null +++ b/sps2_basement/hardware/debug/iop_sbusdbg/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_INCS += -I$(PS2SDKSRC)/common/sbus/include -I$(PS2SDKSRC)/iop/debug/iopdebug/include + +IOP_OBJS = main.o sbus_dbg_low.o sbus_tty.o sbus_dbg.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/debug/iop_sbusdbg/include/iop_sbusdbg.h b/sps2_basement/hardware/debug/iop_sbusdbg/include/iop_sbusdbg.h new file mode 100644 index 0000000..20a0c33 --- /dev/null +++ b/sps2_basement/hardware/debug/iop_sbusdbg/include/iop_sbusdbg.h @@ -0,0 +1,38 @@ +/** + * @file + * IOP SBUS debug library. + */ + +#ifndef __IOP_SBUSDBG_H__ +#define __IOP_SBUSDBG_H__ + +#include +#include + +int iop_dbg_install(void); +int iop_dbg_remove(void); + +u32 iop_dbg_get_dcic(void); +u32 iop_dbg_get_bpc(void); +u32 iop_dbg_get_bpcm(void); +u32 iop_dbg_get_bda(void); +u32 iop_dbg_get_bdam(void); + +void iop_dbg_set_dcic(u32 v); +void iop_dbg_set_bpc(u32 v); +void iop_dbg_set_bpcm(u32 v); +void iop_dbg_set_bda(u32 v); +void iop_dbg_set_bdam(u32 v); + +void iop_dbg_set_bpr(u32 addr, u32 mask, u32 user_mask); +void iop_dbg_set_bpw(u32 addr, u32 mask, u32 user_mask); +void iop_dbg_set_bpx(u32 addr, u32 mask, u32 user_mask); + +void iop_dbg_clear(void); +void iop_dbg_clr_bpda(void); +void iop_dbg_clr_bpx(void); + +void tty_puts(const char *str); +void signal_iop_exception(IOP_RegFrame *frame); + +#endif /* __IOP_SBUSDBG_H__ */ diff --git a/sps2_basement/hardware/debug/iop_sbusdbg/src/imports.lst b/sps2_basement/hardware/debug/iop_sbusdbg/src/imports.lst new file mode 100644 index 0000000..0306369 --- /dev/null +++ b/sps2_basement/hardware/debug/iop_sbusdbg/src/imports.lst @@ -0,0 +1,62 @@ +loadcore_IMPORTS_start +I_FlushIcache +I_FlushDcache +loadcore_IMPORTS_end + +sysmem_IMPORTS_start +I_Kprintf +I_KprintfSet +sysmem_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_prnt +I_setjmp +I_strcmp +I_strncmp +I_strcpy +I_memcpy +I_strlen +I_memcmp +sysclib_IMPORTS_end + +ioman_IMPORTS_start +I_open +I_read +I_close +I_AddDrv +I_DelDrv +ioman_IMPORTS_end + +excepman_IMPORTS_start +I_RegisterDefaultExceptionHandler +I_RegisterPriorityExceptionHandler +excepman_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +sbus_IMPORTS_start +I_SIF2_send_cmd +I_SIF2_set_cmd_handler +I_SBUS_check_intr +sbus_IMPORTS_end + +thbase_IMPORTS_start +I_GetThreadId +I_CreateThread +I_StartThread +I_SleepThread +I_iWakeupThread +thbase_IMPORTS_end + +iopdebug_IMPORTS_start +I_iop_dbg_set_handler +I_iop_dbg_get_reg_frames +iopdebug_IMPORTS_end + diff --git a/sps2_basement/hardware/debug/iop_sbusdbg/src/irx_imports.h b/sps2_basement/hardware/debug/iop_sbusdbg/src/irx_imports.h new file mode 100644 index 0000000..024d797 --- /dev/null +++ b/sps2_basement/hardware/debug/iop_sbusdbg/src/irx_imports.h @@ -0,0 +1,30 @@ +/* + * irx_imports.h - Defines all IRX imports. + * + * Copyright (c) 2003 Marcus R. Brown + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "cdvdman.h" +#include "loadcore.h" +#include "sifman.h" +#include "sifcmd.h" +#include "stdio.h" +#include "sysmem.h" +#include "sysclib.h" +#include "thbase.h" +#include "ioman.h" +#include "modload.h" +#include "intrman.h" +#include "excepman.h" +#include "ps2_sbus.h" +#include "iopdebug.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/debug/iop_sbusdbg/src/main.c b/sps2_basement/hardware/debug/iop_sbusdbg/src/main.c new file mode 100644 index 0000000..53646f5 --- /dev/null +++ b/sps2_basement/hardware/debug/iop_sbusdbg/src/main.c @@ -0,0 +1,107 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "sbus_tty.h" + +IRX_ID("sbusdebug", 1, 0); + +volatile int _iop_controlled = 0; +volatile int _iop_exception_state = 0; + +extern void signal_iop_exception(IOP_RegFrame *frame); + +// this is called by the IOP debug/exception handler +void _iop_ex_handler(IOP_RegFrame *frame) +{ + int excode = M_IOP_GET_CAUSE_EXCODE(frame->cause); + + if(excode == IOP_EXCEPTION_HDB) + { + _iop_exception_state = 2; + } + else + { + _iop_exception_state = 1; + } + + _iop_controlled = 1; + + // signal to the EE that an IOP exception occured. + signal_iop_exception(frame); + + // wait for EE to send a "IOP control" command and release the IOP. + while(_iop_controlled) + { + // since we're spinning in an interrupt-disabled state, we have to manually + // poll for SBUS interrupts from EE, otherwise we'll never get released! + SBUS_check_intr(); + } +} + +int tid; + +extern void soft_break(void); + +void _controller_thread(void) +{ + while(1) + { +// printf("IOP: Controller thread going to sleep(%d)...\n", _iop_exception_state); + SleepThread(); +// printf("IOP: Controller thread woke up!\n"); + soft_break(); + } +} + +void create_th(void) +{ + iop_thread_t param; + + param.attr = TH_C; + param.thread = (void *) _controller_thread; + param.priority = 9; // highest possible priority + param.stacksize = 512; // tiny stack, not much is needed! + param.option = 0; + + tid = CreateThread(¶m); + StartThread(tid, 0); +} + +extern void SBUS_dbg_init(void); + +int _start(int argc, char *argv[]) +{ + int i; + + for(i = 2; i <= 7; i++) + { + iop_dbg_set_handler(i, (IOP_ExceptionHandler *) _iop_ex_handler); + } + + for(i = 9; i <= 15; i++) + { + iop_dbg_set_handler(i, (IOP_ExceptionHandler *) _iop_ex_handler); + } + + create_th(); + + if(sbus_tty_init() != 0) + { + printf("Failed initializing SBUS TTY system!\n"); + return(1); + } + + SBUS_dbg_init(); + + FlushIcache(); + FlushDcache(); + + printf("IOP SBUS Debug installed!\n"); + + return(0); // return resident! +} diff --git a/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_dbg.c b/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_dbg.c new file mode 100644 index 0000000..f860c92 --- /dev/null +++ b/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_dbg.c @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "iopdebug.h" + +#define SIF2_CMD_DBG_PUTS (1) +#define SIF2_CMD_DBG_EXC (2) +#define SIF2_CMD_DBG_CTRL (3) + +extern int _iop_exception_state; + +static IOP_RegFrame *_iop_ex_def_frame; +static IOP_RegFrame *_iop_ex_dbg_frame; + +typedef struct st_SBUS_ControlCPU_Params +{ + u32 mode; // 0 = update register frame and release, 1 = control + IOP_RegFrame reg_frame; +} SBUS_ControlCPU_Params; + +extern int _iop_controlled; + +// send a string to EE for output. +void sbus_tty_puts(const char *str) +{ + SIF2_send_cmd(SIF2_CMD_DBG_PUTS, (void *) str, strlen(str) + 1); +} + +void signal_iop_exception(IOP_RegFrame *frame) +{ + SIF2_send_cmd(SIF2_CMD_DBG_EXC, (void *) frame, sizeof(IOP_RegFrame)); +} + +extern int tid; + +void _sif2_cmd_dbg_control(SIF2_CmdPkt *cmd, void *param) +{ + SBUS_ControlCPU_Params *params; + IOP_RegFrame *frame; + + params = (SBUS_ControlCPU_Params *) ((((u32) cmd) + sizeof(SIF2_CmdPkt)) | 0x00000000); + + if(params->mode == 1) + { + // wake up the controller thread. + iWakeupThread(tid); + } + else + { + if(_iop_exception_state == 0) { return; } + + if(_iop_exception_state == 1) { frame = _iop_ex_def_frame; } + else { frame = _iop_ex_dbg_frame; } + + // update the register frame and release the CPU. + memcpy(frame, ¶ms->reg_frame, sizeof(IOP_RegFrame)); + + FlushIcache(); + FlushDcache(); + + _iop_exception_state = 0; + _iop_controlled = 0; + } +} + +void SBUS_dbg_init(void) +{ + iop_dbg_get_reg_frames(&_iop_ex_def_frame, &_iop_ex_dbg_frame); + SIF2_set_cmd_handler(SIF2_CMD_DBG_CTRL, &_sif2_cmd_dbg_control, NULL); +} diff --git a/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_dbg_low.S b/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_dbg_low.S new file mode 100644 index 0000000..2e776ef --- /dev/null +++ b/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_dbg_low.S @@ -0,0 +1,15 @@ +.set push +.set noreorder +.set noat + +.global soft_break +.ent soft_break +soft_break: + nop + break + nop + jr $ra + nop +.end soft_break + +.set pop diff --git a/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_tty.c b/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_tty.c new file mode 100644 index 0000000..5cb9309 --- /dev/null +++ b/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_tty.c @@ -0,0 +1,176 @@ +/* + +IOP->EE TTY over SBUS by Herben + +This file contains the file system driver and glue needed to create a TTY file file system and redirect it to EE over SBUS. + +Additionally it installs a Kprintf handler so you can even see the things you don't normally see like the error messages WaitSema gives +for those naughty ps2ip modules. ;) + +Of course this requires that the EE-side code accept this command and output the string to screen/sio... + +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "iopdebug.h" + +extern void sbus_tty_puts(const char *str); + +static int ttyfs_error() { return -1; } + +static int ttyfs_init() +{ + //DBG_puts("SIOTTY: FS Init()\n"); + return 0; +} + +static int ttyfs_deinit() +{ + //DBG_puts("SIOTTY: FS Deinit()\n"); + return 0; +} + +static int ttyfs_open(iop_file_t *file, const char *name, int flags, int mode) +{ + //DBG_puts("SIOTTY: FS Open()\n"); + return 0; +} + +static int ttyfs_close(iop_file_t *file, int fd) +{ + //DBG_puts("SIOTTY: FS Close()\n"); + return(0); +} + +static int ttyfs_read(iop_file_t *file, void *ptr, size_t size) { + //DBG_puts("SIOTTY: FS Read()\n"); + return(-1); +} + +static int ttyfs_write(iop_file_t *file, u8 *ptr, size_t size) { + char temp[65]; + int bCount = 0, toWrite; + + //DBG_puts("SIOTTY: FS Write()\n"); + + while(bCount < size) + { + toWrite = (size - bCount); + if(toWrite > 64) + toWrite = 64; + + memcpy(temp, &ptr[bCount], toWrite); + temp[toWrite] = '\0'; + sbus_tty_puts(temp); + + bCount += toWrite; + } + + return(bCount); +} + +static int ttyfs_lseek(iop_file_t *file, int offset, int mode) { + //DBG_puts("SIOTTY: FS Lseek()\n"); + + return(-1); +} + +static int ttyfs_format(iop_file_t *file, const char *dev, const char *blockdev, void *arg, size_t arglen) { + //DBG_puts("SIOTTY: FS Format()\n"); + + return(-1); +} + +static int ttyfs_remove(iop_file_t *file, const char *name) { + //DBG_puts("SIOTTY: FS Remove()\n"); + + return(-1); +} + +static int ttyfs_dread(iop_file_t *file, iox_dirent_t *dirent) { + //DBG_puts("SIOTTY: FS Dread()\n"); + + return(-1); +} + +static int ttyfs_getstat(iop_file_t *file, const char *name, iox_stat_t *stat) { + //DBG_puts("SIOTTY: FS GetStat()\n"); + + return(-1); +} + +static int ttyfs_devctl(iop_file_t *file, const char *name, int cmd, void *arg, size_t arglen, void *buf, size_t buflen) { + //DBG_puts("SIOTTY: FS DEVCTL()\n"); + + return(-1); +} + +static int ttyfs_ioctl2(iop_file_t *file, int cmd, void *arg, size_t arglen, void *buf, size_t buflen) { + //DBG_puts("SIOTTY: FS IOCTL2()\n"); + + return(-1); +} + + +static void *fsd_ops[] = { ttyfs_init, ttyfs_deinit, ttyfs_format, ttyfs_open, ttyfs_close, + ttyfs_read, ttyfs_write, ttyfs_lseek, ttyfs_error, ttyfs_remove, ttyfs_error, ttyfs_error, + ttyfs_open, ttyfs_close, ttyfs_dread, ttyfs_getstat, ttyfs_error, ttyfs_error, ttyfs_error, + ttyfs_error, ttyfs_error, ttyfs_error, ttyfs_error, ttyfs_devctl, ttyfs_error, ttyfs_error, + ttyfs_ioctl2 +}; + +iop_device_t tty_fsd = +{ + "tty", + 0x10, + 1, + "TTY via EE SIO", + (iop_device_ops_t *) &fsd_ops +}; + +void sprintf_putchar(void *context, int c) +{ + char **string = (char **)context; + + if(c < 0x100) { ((*string)++)[0] = c; } + else { (*string)[0] = 0; } +} + +extern int _vsprintf(char * str, const char * format, va_list ap); + +static char kprint_buffer[1024]; + +int _kPrintf(void *context, const char * format, va_list ap) +{ + int r = prnt(&sprintf_putchar, &format, format, ap); + sbus_tty_puts(kprint_buffer); + return r; +} + +int sbus_tty_init(void) +{ + close(0); + close(1); + DelDrv("tty"); + DelDrv("dummytty"); + + if(AddDrv(&tty_fsd) != 0) { return(-1); } + + open("tty:", O_RDONLY); + open("tty:", O_WRONLY); + + KprintfSet(&_kPrintf, NULL); + + return(0); +} diff --git a/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_tty.h b/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_tty.h new file mode 100644 index 0000000..2951d77 --- /dev/null +++ b/sps2_basement/hardware/debug/iop_sbusdbg/src/sbus_tty.h @@ -0,0 +1,9 @@ +#ifndef _SBUS_TTY_H +#define _SBUS_TTY_H + +#include "tamtypes.h" + +// Prototypes +int sbus_tty_init(void); + +#endif diff --git a/sps2_basement/hardware/debug/iopdebug/Makefile b/sps2_basement/hardware/debug/iopdebug/Makefile new file mode 100644 index 0000000..b7b3a77 --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/Makefile @@ -0,0 +1,14 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_OBJS = main.o iop_debug.o iop_exceptions.o iop_dbg_low.o imports.o exports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/debug/iopdebug/include/iopdebug.h b/sps2_basement/hardware/debug/iopdebug/include/iopdebug.h new file mode 100644 index 0000000..98ccbaf --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/include/iopdebug.h @@ -0,0 +1,79 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOPDEBUG - IOP debugging library. + * Definitions for the IOPDEBUG library. + */ + +#ifndef __IOPDEBUG_H__ +#define __IOPDEBUG_H__ + +#include +#include +#include +#include + +typedef int (IOP_ExceptionHandler)(struct st_IOP_RegFrame *); + +int iop_dbg_install(void); +int iop_dbg_remove(void); +IOP_ExceptionHandler *iop_dbg_get_handler(int cause); +IOP_ExceptionHandler *iop_dbg_set_handler(int cause, IOP_ExceptionHandler *handler); +void iop_dbg_get_reg_frames(IOP_RegFrame **def_frame_ptr, IOP_RegFrame **dbg_frame_ptr); +u32 iop_dbg_get_dcic(void); +void iop_dbg_set_dcic(u32 v); + +u32 iop_dbg_get_bpc(void); +void iop_dbg_set_bpc(u32 v); + +u32 iop_dbg_get_bpcm(void); +void iop_dbg_set_bpcm(u32 v); + +u32 iop_dbg_get_bda(void); +void iop_dbg_set_bda(u32 v); +u32 iop_dbg_get_bdam(void); +void iop_dbg_set_bdam(u32 v); + +void iop_dbg_set_bpr(u32 addr, u32 mask, u32 user_mask); +void iop_dbg_set_bpw(u32 addr, u32 mask, u32 user_mask); +void iop_dbg_set_bpx(u32 addr, u32 mask, u32 user_mask); + +void iop_dbg_clr_bps(void); +void iop_dbg_clr_bpda(void); +void iop_dbg_clr_bpx(void); + +#define iopdebug_IMPORTS_start DECLARE_IMPORT_TABLE(iopdebug, 1, 1) +#define iopdebug_IMPORTS_end END_IMPORT_TABLE + +#define I_iop_dbg_install DECLARE_IMPORT(5, iop_dbg_install) +#define I_iop_dbg_remove DECLARE_IMPORT(6, iop_dbg_remove) +#define I_iop_dbg_get_handler DECLARE_IMPORT(7, iop_dbg_get_handler) +#define I_iop_dbg_set_handler DECLARE_IMPORT(8, iop_dbg_set_handler) +#define I_iop_dbg_get_reg_frames DECLARE_IMPORT(9, iop_dbg_get_reg_frames) +#define I_iop_dbg_get_dcic DECLARE_IMPORT(10, iop_dbg_get_dcic) +#define I_iop_dbg_set_dcic DECLARE_IMPORT(11, iop_dbg_set_dcic) +#define I_iop_dbg_get_bpc DECLARE_IMPORT(12, iop_dbg_get_bpc) +#define I_iop_dbg_set_bpc DECLARE_IMPORT(13, iop_dbg_set_bpc) +#define I_iop_dbg_get_bpcm DECLARE_IMPORT(14, iop_dbg_get_bpcm) +#define I_iop_dbg_set_bpcm DECLARE_IMPORT(15, iop_dbg_set_bpcm) +#define I_iop_dbg_bda DECLARE_IMPORT(16, iop_dbg_bda) +#define I_iop_dbg_set_bda DECLARE_IMPORT(17, iop_dbg_set_bda) +#define I_iop_dbg_bdam DECLARE_IMPORT(18, iop_dbg_bdam) +#define I_iop_dbg_set_bdam DECLARE_IMPORT(19, iop_dbg_bdam) +#define I_iop_dbg_set_bpr DECLARE_IMPORT(20, iop_dbg_set_bpr) +#define I_iop_dbg_set_bpw DECLARE_IMPORT(21, iop_dbg_set_bpw) +#define I_iop_dbg_set_bpx DECLARE_IMPORT(22, iop_dbg_bpx) +#define I_iop_dbg_clr_bps DECLARE_IMPORT(23, iop_dbg_clr_bps) +#define I_iop_dbg_clr_bpda DECLARE_IMPORT(24, iop_dbg_clr_bpda) +#define I_iop_dbg_clr_bpx DECLARE_IMPORT(25, iop_dbg_clr_bpx) + +#endif /* __IOPDEBUG_H__ */ diff --git a/sps2_basement/hardware/debug/iopdebug/src/exports.tab b/sps2_basement/hardware/debug/iopdebug/src/exports.tab new file mode 100644 index 0000000..744c927 --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/src/exports.tab @@ -0,0 +1,39 @@ +/* Exports for IOPDEBUG */ + +DECLARE_EXPORT_TABLE(iopdebug, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_stop) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) +/* 5 */ + DECLARE_EXPORT(iop_dbg_install) + DECLARE_EXPORT(iop_dbg_remove) + DECLARE_EXPORT(iop_dbg_get_handler) + DECLARE_EXPORT(iop_dbg_set_handler) + DECLARE_EXPORT(iop_dbg_get_reg_frames) +/* 10 */ + DECLARE_EXPORT(iop_dbg_get_dcic) + DECLARE_EXPORT(iop_dbg_set_dcic) + DECLARE_EXPORT(iop_dbg_get_bpc) + DECLARE_EXPORT(iop_dbg_set_bpc) + DECLARE_EXPORT(iop_dbg_get_bpcm) +/* 15 */ + DECLARE_EXPORT(iop_dbg_set_bpcm) + DECLARE_EXPORT(iop_dbg_get_bda) + DECLARE_EXPORT(iop_dbg_set_bda) + DECLARE_EXPORT(iop_dbg_get_bdam) + DECLARE_EXPORT(iop_dbg_set_bdam) +/* 20 */ + DECLARE_EXPORT(iop_dbg_set_bpr) + DECLARE_EXPORT(iop_dbg_set_bpw) + DECLARE_EXPORT(iop_dbg_set_bpx) + DECLARE_EXPORT(iop_dbg_clr_bps) + DECLARE_EXPORT(iop_dbg_clr_bpda) +/* 25 */ + DECLARE_EXPORT(iop_dbg_clr_bpx) + +END_EXPORT_TABLE + +void _retonly() {} + diff --git a/sps2_basement/hardware/debug/iopdebug/src/imports.lst b/sps2_basement/hardware/debug/iopdebug/src/imports.lst new file mode 100644 index 0000000..5bdb7e0 --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/src/imports.lst @@ -0,0 +1,31 @@ +loadcore_IMPORTS_start +I_RegisterLibraryEntries +I_FlushIcache +I_FlushDcache +loadcore_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_prnt +I_setjmp +I_strcmp +I_strncmp +I_strcpy +I_memcpy +I_strlen +I_memcmp +sysclib_IMPORTS_end + +excepman_IMPORTS_start +I_RegisterDefaultExceptionHandler +I_RegisterPriorityExceptionHandler +excepman_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + diff --git a/sps2_basement/hardware/debug/iopdebug/src/iop_dbg_low.S b/sps2_basement/hardware/debug/iopdebug/src/iop_dbg_low.S new file mode 100644 index 0000000..bad5b87 --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/src/iop_dbg_low.S @@ -0,0 +1,172 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOPDEBUG - IOP debugging library. + * low-level IOP "debug" helper functions. + */ + +#include +#include "iopdebug_defs.h" +#include "as_reg_compat.h" + +.set push +.set noreorder +.set noat + +.global iop_dbg_get_dcic +.ent iop_dbg_get_dcic +iop_dbg_get_dcic: + mfc0 $v0, IOP_COP0_DCIC + nop + jr $ra + nop +.end iop_dbg_get_dcic + +.global iop_dbg_get_bpc +.ent iop_dbg_get_bpc +iop_dbg_get_bpc: + mtc0 $v0, IOP_COP0_BPC + nop + jr $ra + nop +.end iop_dbg_get_bpc + +.global iop_dbg_get_bpcm +.ent iop_dbg_get_bpcm +iop_dbg_get_bpcm: + mfc0 $v0, IOP_COP0_BPCM + nop + jr $ra + nop + +.end iop_dbg_get_bpcm + +.global iop_dbg_get_bda +.ent iop_dbg_get_bda +iop_dbg_get_bda: + mfc0 $v0, IOP_COP0_BDA + nop + jr $ra + nop +.end iop_dbg_get_bda + +.global iop_dbg_get_bdam +.ent iop_dbg_get_bdam +iop_dbg_get_bdam: + mfc0 $v0, IOP_COP0_BDAM + nop + jr $ra + nop +.end iop_dbg_get_bdam + +.global iop_dbg_set_dcic +.ent iop_dbg_set_dcic +iop_dbg_set_dcic: + mtc0 $a0, IOP_COP0_DCIC + nop + jr $ra + nop +.end iop_dbg_set_dcic + +.global iop_dbg_set_bpc +.ent iop_dbg_set_bpc +iop_dbg_set_bpc: + mtc0 $a0, IOP_COP0_BPC + nop + jr $ra + nop +.end iop_dbg_set_bpc + +.global iop_dbg_set_bpcm +.ent iop_dbg_set_bpcm +iop_dbg_set_bpcm: + mtc0 $a0, IOP_COP0_BPCM + nop + jr $ra + nop +.end iop_dbg_set_bpcm + + +.global iop_dbg_set_bda +.ent iop_dbg_set_bda +iop_dbg_set_bda: + mtc0 $a0, IOP_COP0_BDA + nop + jr $ra + nop +.end iop_dbg_set_bda + +.global iop_dbg_set_bdam +.ent iop_dbg_set_bdam +iop_dbg_set_bdam: + mtc0 $a0, IOP_COP0_BDAM + nop + jr $ra + nop +.end iop_dbg_set_bdam + +.global _iop_dbg_set_bpda +.ent _iop_dbg_set_bpda +_iop_dbg_set_bpda: + + mfc0 $t0, IOP_COP0_DCIC + nop + nop + mtc0 $zero, IOP_COP0_DCIC + nop + nop + + mtc0 $a0, IOP_COP0_BDA + mtc0 $a1, IOP_COP0_BDAM + + li $t1, ~(IOP_DCIC_DR | IOP_DCIC_DW) + and $t0, $t0, $t1 + + li $t1, (IOP_DCIC_TR | IOP_DCIC_DAE | IOP_DCIC_DE) + or $t0, $t0, $t1 + or $t0, $t0, $a2 + mtc0 $t0, IOP_COP0_DCIC + nop + jr $ra + nop + +.end _iop_dbg_set_bpda + +.global _iop_dbg_set_bpx +.ent _iop_dbg_set_bpx +_iop_dbg_set_bpx: + + mfc0 $t0, IOP_COP0_DCIC + nop + nop + mtc0 $zero, IOP_COP0_DCIC + nop + nop + + mtc0 $a0, IOP_COP0_BPC + mtc0 $a1, IOP_COP0_BPCM + nop + + li $t1, ~(IOP_DCIC_PC) + and $t0, $t0, $t1 + + li $t1, (IOP_DCIC_TR | IOP_DCIC_PCE | IOP_DCIC_DE) + or $t0, $t0, $t1 + or $t0, $t0, $a2 + mtc0 $t0, IOP_COP0_DCIC + nop + jr $ra + nop + +.end _iop_dbg_set_bpx + +.set pop diff --git a/sps2_basement/hardware/debug/iopdebug/src/iop_debug.c b/sps2_basement/hardware/debug/iopdebug/src/iop_debug.c new file mode 100644 index 0000000..5d2c657 --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/src/iop_debug.c @@ -0,0 +1,198 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOPDEBUG - IOP debugging library. + * high-level IOP debugging library code. + */ + +#include +#include +#include +#include + +#include "iopdebug.h" +#include "iopdebug_priv.h" +#include "iopdebug_defs.h" + +u32 _iop_ex_def_stack[_EX_DEF_STACK_SIZE / 4]; +u32 _iop_ex_dbg_stack[_EX_DBG_STACK_SIZE / 4]; + +IOP_RegFrame _iop_ex_def_frame; +IOP_RegFrame _iop_ex_dbg_frame; + +static int _is_iop_dbg_installed = 0; + +static void *orig_iop_def_ex_handler = NULL; +static void *orig_iop_break_ex_handler = NULL; +static void *orig_iop_dbg_ex_handler = NULL; + +static IOP_ExceptionHandler *iop_exception_handlers[16]; + +IOP_ExceptionHandler *iop_dbg_get_handler(int cause) +{ + if((cause < 0) || (cause > 15)) { return(NULL); } + + return(iop_exception_handlers[cause]); +} + +IOP_ExceptionHandler *iop_dbg_set_handler(int cause, IOP_ExceptionHandler *handler) +{ + IOP_ExceptionHandler *old_handler; + u32 old_state; + + if((cause < 0) || (cause > 15)) { return(NULL); } + + EnterCritical(&old_state); + + old_handler = iop_exception_handlers[cause]; + iop_exception_handlers[cause] = handler; + + ExitCritical(old_state); + + return(old_handler); +} + +// this is called by the IOP debug/exception handlers +void iop_exception_dispatcher(IOP_RegFrame *frame) +{ + int excode = M_IOP_GET_CAUSE_EXCODE(frame->cause); + IOP_ExceptionHandler *handler = iop_exception_handlers[excode]; + + if(handler) + { + handler(frame); + } +} + +extern void _iop_dbg_set_bpda(u32 addr, u32 mask, u32 user_mask); +extern void _iop_dbg_set_bpx(u32 addr, u32 mask, u32 user_mask); + +// ex: iop_dbg_set_bpr(&var, 0xFFFFFFFF, (IOP_DCIC_UD | IOP_DCIC_KD)); +void iop_dbg_set_bpr(u32 addr, u32 mask, u32 user_mask) { _iop_dbg_set_bpda(addr, mask, IOP_DCIC_DR | user_mask); } + +// ex: iop_dbg_set_bpw(&var, 0xFFFFFFFF, (IOP_DCIC_UD | IOP_DCIC_KD)); +void iop_dbg_set_bpw(u32 addr, u32 mask, u32 user_mask) { _iop_dbg_set_bpda(addr, mask, IOP_DCIC_DW | user_mask); } + +// ex: iop_dbg_set_bpx(&func, 0xFFFFFFFF, (IOP_DCIC_UD | IOP_DCIC_KD)); +void iop_dbg_set_bpx(u32 addr, u32 mask, u32 user_mask) { _iop_dbg_set_bpx(addr, mask, user_mask); } + +void iop_dbg_clr_bpda(void) +{ + u32 dcic = iop_dbg_get_dcic(); + dcic &= ~(IOP_DCIC_DW | IOP_DCIC_DR | IOP_DCIC_DAE); + if(!(dcic & IOP_DCIC_PCE)) { dcic = 0; } + iop_dbg_set_dcic(dcic); +} + +void iop_dbg_clr_bpx(void) +{ + u32 dcic = iop_dbg_get_dcic(); + dcic &= ~(IOP_DCIC_PCE); + if(!(dcic & IOP_DCIC_DAE)) { dcic = 0; } + iop_dbg_set_dcic(dcic); +} + +void iop_dbg_clr_bps(void) +{ + iop_dbg_set_dcic(0); + iop_dbg_set_bda(0); + iop_dbg_set_bdam(0); + iop_dbg_set_bpc(0); + iop_dbg_set_bpcm(0); +} + +extern void _iop_ex_def_handler(void); +extern void _iop_ex_dbg_handler(void); +extern void _iop_ex_break_handler(void); + +int iop_dbg_install(void) +{ + int i; + + // if already installed, return with an error. + if(_is_iop_dbg_installed) { return(-1); } + + // initialize our exception handler pointers. + for(i = 0; i < 16; i++) + { + iop_exception_handlers[i] = NULL; + } + + // todo: preserve original exception handlers here! + // This will require using "EXCEPMAN" export 3.. + + // register our "default" exception handler. + if(RegisterDefaultExceptionHandler((exception_handler_t) _iop_ex_def_handler) < 0) + { + orig_iop_def_ex_handler = NULL; + return(-2); + } + + // register our "BREAK" instruction exception handler. + if(RegisterPriorityExceptionHandler(IOP_EXCEPTION_BP, 0, (exception_handler_t) _iop_ex_break_handler) < 0) + { + RegisterDefaultExceptionHandler((exception_handler_t) orig_iop_def_ex_handler); + orig_iop_def_ex_handler = NULL; + orig_iop_break_ex_handler = NULL; + return(-3); + } + + // register our "Hardware DeBug"(aka "Hardware BreakPoint") exception handler. + if(RegisterPriorityExceptionHandler(IOP_EXCEPTION_HDB, 0, (exception_handler_t) _iop_ex_dbg_handler) < 0) + { + RegisterDefaultExceptionHandler((exception_handler_t) orig_iop_def_ex_handler); + orig_iop_def_ex_handler = NULL; + + RegisterPriorityExceptionHandler(IOP_EXCEPTION_BP, 0, (exception_handler_t) orig_iop_break_ex_handler); + orig_iop_break_ex_handler = NULL; + + orig_iop_dbg_ex_handler = NULL; + return(-4); + } + + _is_iop_dbg_installed = 1; + return(0); +} + +int iop_dbg_remove(void) +{ + // if not installed, return with an error. + if(!_is_iop_dbg_installed) { return(-1); } + + if(orig_iop_def_ex_handler) + { + RegisterDefaultExceptionHandler((exception_handler_t) orig_iop_def_ex_handler); + orig_iop_def_ex_handler = NULL; + } + + if(orig_iop_break_ex_handler) + { + RegisterPriorityExceptionHandler(IOP_EXCEPTION_BP, 0, (exception_handler_t) orig_iop_break_ex_handler); + orig_iop_break_ex_handler = NULL; + } + + if(orig_iop_dbg_ex_handler) + { + RegisterPriorityExceptionHandler(IOP_EXCEPTION_HDB, 0, (exception_handler_t) orig_iop_dbg_ex_handler); + orig_iop_dbg_ex_handler = NULL; + } + + _is_iop_dbg_installed = 0; + return(0); +} + +void iop_dbg_get_reg_frames(IOP_RegFrame **def_frame_ptr, IOP_RegFrame **dbg_frame_ptr) +{ + if(def_frame_ptr) { *def_frame_ptr = &_iop_ex_def_frame; } + if(dbg_frame_ptr) { *dbg_frame_ptr = &_iop_ex_dbg_frame; } +} + diff --git a/sps2_basement/hardware/debug/iopdebug/src/iop_exceptions.S b/sps2_basement/hardware/debug/iopdebug/src/iop_exceptions.S new file mode 100644 index 0000000..3a134aa --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/src/iop_exceptions.S @@ -0,0 +1,288 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOPDEBUG - IOP debugging library. + * low-level IOP exception-handler code. + */ + +#include +#include "iopdebug_defs.h" +#include "as_reg_compat.h" + +.set push +.set noreorder +.set noat + +.global _iop_save_frame +.ent _iop_save_frame +_iop_save_frame: + sw $zero, 0x000($s0) + + sw $at, 0x004($s0) + + sw $v0, 0x008($s0) + sw $v1, 0x00C($s0) + + sw $a0, 0x010($s0) + sw $a1, 0x014($s0) + sw $a2, 0x018($s0) + sw $a3, 0x01C($s0) + + sw $t0, 0x020($s0) + sw $t1, 0x024($s0) + sw $t2, 0x028($s0) + sw $t3, 0x02C($s0) + sw $t4, 0x030($s0) + sw $t5, 0x034($s0) + sw $t6, 0x038($s0) + sw $t7, 0x03C($s0) + +// sw $s0, 0x040($s0) + sw $s1, 0x044($s0) + sw $s2, 0x048($s0) + sw $s3, 0x04C($s0) + sw $s4, 0x050($s0) + sw $s5, 0x054($s0) + sw $s6, 0x058($s0) + sw $s7, 0x05C($s0) + + sw $t8, 0x060($s0) + sw $t9, 0x064($s0) + +// sw $k0, 0x068($s0) + sw $k1, 0x06C($s0) + + sw $gp, 0x070($s0) +// sw $sp, 0x074($s0) + sw $fp, 0x078($s0) +// sw $ra, 0x07C($s0) + + mfhi $t0 // hi + mflo $t1 // lo + nop // necessary?? + sw $t0, 0x080($s0) + sw $t1, 0x084($s0) + nop // necessary?? + + mfc0 $t0, $3 // IOP_COP0_BPC + mfc0 $t1, $5 // IOP_COP0_BDA + mfc0 $t2, $8 // IOP_COP0_BADVADDR + mfc0 $t3, $9 // IOP_COP0_BDAM + mfc0 $t4, $11 // IOP_COP0_BPCM + mfc0 $t5, $12 // SR + mfc0 $t6, $13 // Cause + mfc0 $t7, $14 // EPC + + sw $t0, 0x088($s0) + sw $t1, 0x08C($s0) + // gap for IOP_COP0_DCIC + sw $t2, 0x094($s0) + sw $t3, 0x098($s0) + sw $t4, 0x09C($s0) + sw $t5, 0x0A0($s0) + sw $t6, 0x0A4($s0) + sw $t7, 0x0A8($s0) + + jr $ra + nop +.end _iop_save_frame + +.global _iop_load_frame +.ent _iop_load_frame +_iop_load_frame: +// lw $zero, 0x000($s0) + + lw $at, 0x004($s0) + + lw $v0, 0x008($s0) + lw $v1, 0x00C($s0) + + lw $a0, 0x010($s0) + lw $a1, 0x014($s0) + lw $a2, 0x018($s0) + lw $a3, 0x01C($s0) + +// lw $s0, 0x040($s0) + lw $s1, 0x044($s0) + lw $s2, 0x048($s0) + lw $s3, 0x04C($s0) + lw $s4, 0x050($s0) + lw $s5, 0x054($s0) + lw $s6, 0x058($s0) + lw $s7, 0x05C($s0) + + lw $t8, 0x060($s0) + lw $t9, 0x064($s0) + +// lw $k0, 0x068($s0) + lw $k1, 0x06C($s0) + + lw $gp, 0x070($s0) +// lw $sp, 0x074($s0) + lw $fp, 0x078($s0) +// lw $ra, 0x07C($s0) + + lw $t0, 0x080($s0) + lw $t1, 0x084($s0) + mthi $t0 // hi + mtlo $t1 // lo + nop + nop + + lw $t0, 0x088($s0) + lw $t1, 0x08C($s0) + mtc0 $t0, $3 // IOP_COP0_BPC + mtc0 $t1, $5 // IOP_COP0_BDA + + // gap for IOP_COP0_DCIC + lw $t2, 0x094($s0) + lw $t3, 0x098($s0) + mtc0 $t2, $8 // IOP_COP0_BADVADDR + mtc0 $t3, $9 // IOP_COP0_BDAM + + lw $t4, 0x09C($s0) + lw $t5, 0x0A0($s0) + mtc0 $t4, $11 // IOP_COP0_BPCM + mtc0 $t5, $12 // SR + + lw $t6, 0x0A4($s0) + lw $t7, 0x0A8($s0) + mtc0 $t6, $13 // Cause + mtc0 $t7, $14 // EPC + + lw $t0, 0x020($s0) + lw $t1, 0x024($s0) + lw $t2, 0x028($s0) + lw $t3, 0x02c($s0) + lw $t4, 0x030($s0) + lw $t5, 0x034($s0) + lw $t6, 0x038($s0) + lw $t7, 0x03C($s0) + + jr $ra + nop +.end _iop_load_frame + +.global _iop_ex_cmn +.ent _iop_ex_cmn +_iop_ex_cmn: + addiu $sp, $sp, -0x10 + sw $ra, 0x00($sp) + nop + + jal _iop_save_frame + nop + + jal iop_exception_dispatcher + move $a0, $s0 + + jal _iop_load_frame + nop + + lw $ra, 0x00($sp) + nop + jr $ra + addiu $sp, $sp, 0x10 +.end _iop_ex_cmn + +.global _iop_ex_def_handler +.ent _iop_ex_def_handler +_iop_ex_def_handler: + nop + nop + +___iop_ex_def_handler_start: + la $k0, _iop_ex_def_frame + + sw $s0, 0x040($k0) // Save $s0 + sw $sp, 0x074($k0) // Save $sp + mfc0 $s0, IOP_COP0_DCIC + sw $ra, 0x07C($k0) // Save $ra + lw $sp, 0x410($zero) // k0 saved here by default exception prologue (at 0x80) + sw $s0, 0x090($k0) // Save IOP_COP0_DCIC + sw $sp, 0x068($k0) // Save $k0 + lw $at, 0x400($0) // at is saved here by default exception prologue (at 0x80) + la $sp, _iop_ex_def_stack + _EX_DEF_STACK_SIZE + + jal _iop_ex_cmn + move $s0, $k0 + + lw $k0, 0x068($s0) // restore k0 + lw $sp, 0x074($s0) // restore sp + lw $ra, 0x07C($s0) // restore ra + + lw $k1, 0x090($s0) // restore IOP_COP0_DCIC + nop + mtc0 $k1, IOP_COP0_DCIC + nop + + lw $k1, 0x0A8($s0) + nop + mtc0 $k1, $14 // EPC + lw $s0, 0x040($s0) // restore s0 + nop + jr $k1 + cop0 0x10 + nop + nop +.end _iop_ex_def_handler + +.global _iop_ex_break_handler +.ent _iop_ex_break_handler +_iop_ex_break_handler: + nop + nop + j ___iop_ex_def_handler_start + nop +.end _iop_ex_break_handler + +.global _iop_ex_dbg_handler +.ent _iop_ex_dbg_handler +_iop_ex_dbg_handler: + nop + nop + + la $k0, _iop_ex_dbg_frame + + sw $s0, 0x040($k0) // Save $s0 + sw $sp, 0x074($k0) // Save $sp + sw $ra, 0x07C($k0) // Save $ra + lw $sp, 0x420($zero) // k0 saved here by debug exception prologue (at 0x40) + lw $s0, 0x430($0) // IOP_COP0_DCIC is saved here by debug exception prologue (at 0x40) + sw $sp, 0x068($k0) // Save $k0 + sw $s0, 0x090($k0) // Save IOP_COP0_DCIC + la $sp, _iop_ex_dbg_stack + _EX_DBG_STACK_SIZE + + jal _iop_ex_cmn + move $s0, $k0 + + lw $k0, 0x068($s0) // restore k0 + lw $sp, 0x074($s0) // restore sp + lw $ra, 0x07C($s0) // restore ra + + lw $k1, 0x090($s0) // restore IOP_COP0_DCIC + nop + mtc0 $k1, IOP_COP0_DCIC + nop + + lw $k1, 0x0A8($s0) + nop + mtc0 $k1, $14 // EPC + lw $s0, 0x040($s0) // restore s0 + nop + jr $k1 + cop0 0x10 + nop + nop +.end _iop_ex_dbg_handler + +.set pop diff --git a/sps2_basement/hardware/debug/iopdebug/src/iopdebug_defs.h b/sps2_basement/hardware/debug/iopdebug/src/iopdebug_defs.h new file mode 100644 index 0000000..0339be9 --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/src/iopdebug_defs.h @@ -0,0 +1,27 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOPDEBUG - IOP debugging library. + * internal definitions for the IOPDEBUG project. Must be ".S"-friendly! + */ + +#ifndef _IOPDEBUG_DEFS_H_ +#define _IOPDEBUG_DEFS_H_ + +/** size of the IOP "default" exception handler stack, in bytes. */ +#define _EX_DEF_STACK_SIZE (4 * 1024) + +/** size of the IOP "debug" exception handler stack, in bytes. */ +#define _EX_DBG_STACK_SIZE (4 * 1024) + +#endif // #ifndef _IOPDEBUG_DEFS_H_ + diff --git a/sps2_basement/hardware/debug/iopdebug/src/iopdebug_priv.h b/sps2_basement/hardware/debug/iopdebug/src/iopdebug_priv.h new file mode 100644 index 0000000..a6fe9ee --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/src/iopdebug_priv.h @@ -0,0 +1,37 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOPDEBUG - IOP debugging library. + * "private" header for internal definitions for the IOPDEBUG project. + */ + +#ifndef _IOP_DEBUG_PRIV_H +#define _IOP_DEBUG_PRIV_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** Enter a critical state(interrupts are disabled) */ +static inline void EnterCritical(u32 *old_state) { CpuSuspendIntr((int *) old_state); } + +/** Exit a critical state(interrupts are resumed) */ +static inline void ExitCritical(u32 old_state) { CpuResumeIntr((int) old_state); } + +#ifdef __cplusplus +} +#endif + +#endif // #ifndef _IOP_DEBUG_PRIV_H diff --git a/sps2_basement/hardware/debug/iopdebug/src/irx_imports.h b/sps2_basement/hardware/debug/iopdebug/src/irx_imports.h new file mode 100644 index 0000000..c0d0eef --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/src/irx_imports.h @@ -0,0 +1,29 @@ +/* + * irx_imports.h - Defines all IRX imports. + * + * Copyright (c) 2009 PS2DEV.org + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "cdvdman.h" +#include "loadcore.h" +#include "sifman.h" +#include "sifcmd.h" +#include "stdio.h" +#include "sysmem.h" +#include "sysclib.h" +#include "thbase.h" +#include "ioman.h" +#include "modload.h" +#include "intrman.h" +#include "excepman.h" + +#endif /* IOP_IRX_IMPORTS_H */ + diff --git a/sps2_basement/hardware/debug/iopdebug/src/main.c b/sps2_basement/hardware/debug/iopdebug/src/main.c new file mode 100644 index 0000000..ae5a4c2 --- /dev/null +++ b/sps2_basement/hardware/debug/iopdebug/src/main.c @@ -0,0 +1,54 @@ +/** + * @file + * IOPDEBUG - IOP debugging library. + * startup code + */ + +#include +#include +#include +#include +#include "iopdebug.h" + +#include "iopdebug_priv.h" + +IRX_ID("iopdebug", 1, 0); + +extern struct irx_export_table _exp_iopdebug; +int _start(int argc, char *argv[]) +{ + // install IOP debug system. + if(iop_dbg_install() != 0) + { + //printf("Failed installing IOP debug system!\n"); + return(1); // return "non-resident" + } + + // register our IRX exports. + if(RegisterLibraryEntries(&_exp_iopdebug) != 0) + { + iop_dbg_remove(); + + //printf("Error registering library!\n"); + return(1); + } + + FlushIcache(); + FlushDcache(); + + //printf("IOPDEBUG installed!\n"); + + return(0); // return "resident" +} +// export 2, called when the module is being unloaded(like when IOP is being "rebooted"). +int _stop(int argc, char *argv[]) +{ + // remove IOP debug system. + if(iop_dbg_remove() != 0) + { + //printf("Failed removing IOP debug handlers!\n"); + } + + return(1); // return "non-resident" +} + diff --git a/sps2_basement/hardware/debug/ioptrap/Makefile b/sps2_basement/hardware/debug/ioptrap/Makefile new file mode 100644 index 0000000..9428921 --- /dev/null +++ b/sps2_basement/hardware/debug/ioptrap/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +# IOP_CFLAGS += -DTEST_TRAP + +IOP_OBJS = ioptrap.o handler.o breakpoint.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/debug/ioptrap/include/ioptrap.h b/sps2_basement/hardware/debug/ioptrap/include/ioptrap.h new file mode 100644 index 0000000..a942fa2 --- /dev/null +++ b/sps2_basement/hardware/debug/ioptrap/include/ioptrap.h @@ -0,0 +1,96 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOP exception handling. + */ + +#ifndef __IOPTRAP_H__ +#define __IOPTRAP_H__ + +#include +#include + +/* IDT_R3000_20.pdf 3-11 table 3.5 */ +typedef enum { + EXCEPTION_Int, /* note you can't really work with this one. */ + EXCEPTION_Mod, + EXCEPTION_TLBL, + EXCEPTION_TLBS, + EXCEPTION_AdEL, + EXCEPTION_AdES, + EXCEPTION_IBE, + EXCEPTION_DBE, + EXCEPTION_Syscall, + EXCEPTION_Bp, + EXCEPTION_RI, + EXCEPTION_CpU, + EXCEPTION_Ov, + EXCEPTION_RESERVED13, + EXCEPTION_RESERVED14 /* would be FPE, but that's not going to happen on the IOP */ +} exception_type_t; + +typedef struct exception_frame +{ + u32 epc; + u32 cause; + u32 badvaddr; + u32 sr; + u32 regs[32]; + u32 hi; + u32 lo; + u32 dcic; +} exception_frame_t; + +/* Beware: the handler will be run in a 'bad' state. Consider you are + on interrupt mode, so, only i* functions. */ +typedef void (*trap_exception_handler_t)(exception_type_t, exception_frame_t *); + +#define DCIC_WR (1 << 27) +#define DCIC_RD (1 << 26) +#define DCIC_DA (1 << 25) +#define DCIC_PC (1 << 24) + +const char *get_exception_name(exception_type_t type); + +/* Will act as a setjmp. Returns 0 to say it was the first call, + otherwise, returns the exception number. (note that you'll never + get any interrupt...) Note that using this will completely disable + user defined exception handlers. */ +exception_type_t dbg_setjmp(); + +/* Will return the old handler. */ +trap_exception_handler_t set_exception_handler(exception_type_t type, trap_exception_handler_t handler); +trap_exception_handler_t get_exception_handler(exception_type_t type); + +/* Breakpoint stuff. */ +void set_dba(u32 v); +void set_dbam(u32 v); +void set_dcic(u32 v); +u32 get_dba(); +u32 get_dbam(); +u32 get_dcic(); + +#define ioptrap_IMPORTS_start DECLARE_IMPORT_TABLE(ioptrap, 1, 1) +#define ioptrap_IMPORTS_end END_IMPORT_TABLE + +#define I_get_exception_name DECLARE_IMPORT(4, get_exception_name) +#define I_dbg_setjmp DECLARE_IMPORT(5, dbg_setjmp) +#define I_set_exception_handler DECLARE_IMPORT(6, set_exception_handler) +#define I_get_exception_handler DECLARE_IMPORT(7, get_exception_handler) +#define I_set_dba DECLARE_IMPORT(8, set_dba) +#define I_set_dbam DECLARE_IMPORT(9, set_dbam) +#define I_set_dcic DECLARE_IMPORT(10, set_dcic) +#define I_get_dba DECLARE_IMPORT(11, get_dba) +#define I_get_dbam DECLARE_IMPORT(12, get_dbam) +#define I_get_dcic DECLARE_IMPORT(13, get_dcic) + +#endif /* __IOPTRAP_H__ */ diff --git a/sps2_basement/hardware/debug/ioptrap/src/breakpoint.c b/sps2_basement/hardware/debug/ioptrap/src/breakpoint.c new file mode 100644 index 0000000..e4b1b8f --- /dev/null +++ b/sps2_basement/hardware/debug/ioptrap/src/breakpoint.c @@ -0,0 +1,43 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include "ioptrap.h" + +void set_dba(u32 v) { + __asm__ __volatile__("mtc0 %0, $5" : : "r" (v)); +} + +void set_dbam(u32 v) { + __asm__ __volatile__("mtc0 %0, $9" : : "r" (v)); +} + +void set_dcic(u32 v) { + __asm__ __volatile__("mtc0 %0, $7" : : "r" (v)); +} + +u32 get_dba() { + u32 v; + __asm__ __volatile__("mfc0 %0, $5" : "=&r" (v)); + return v; +} + +u32 get_dbam() { + u32 v; + __asm__ __volatile__("mfc0 %0, $9" : "=&r" (v)); + return v; +} + +u32 get_dcic() { + u32 v; + __asm__ __volatile__("mfc0 %0, $7" : "=&r" (v)); + return v; +} + + diff --git a/sps2_basement/hardware/debug/ioptrap/src/exports.tab b/sps2_basement/hardware/debug/ioptrap/src/exports.tab new file mode 100644 index 0000000..64683ca --- /dev/null +++ b/sps2_basement/hardware/debug/ioptrap/src/exports.tab @@ -0,0 +1,20 @@ +DECLARE_EXPORT_TABLE(ioptrap, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(shutdown) + DECLARE_EXPORT(_retonly) + + DECLARE_EXPORT(get_exception_name) +/*05*/ DECLARE_EXPORT(dbg_setjmp) + DECLARE_EXPORT(set_exception_handler) + DECLARE_EXPORT(get_exception_handler) + DECLARE_EXPORT(set_dba) + DECLARE_EXPORT(set_dbam) +/*10*/ DECLARE_EXPORT(set_dcic) + DECLARE_EXPORT(get_dba) + DECLARE_EXPORT(get_dbam) + DECLARE_EXPORT(get_dcic) + +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/debug/ioptrap/src/handler.S b/sps2_basement/hardware/debug/ioptrap/src/handler.S new file mode 100644 index 0000000..ab6451b --- /dev/null +++ b/sps2_basement/hardware/debug/ioptrap/src/handler.S @@ -0,0 +1,291 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + + +#include "as_reg_compat.h" + +#define GENERAL_ATSAVE 0x400 +#define GENERAL_SRSAVE + + .global def_exc_handler + .ent def_exc_handler +def_exc_handler: + .set noreorder + .set noat + .word 0 + .word 0 + la $k0, __trap_frame + sw $0, 0x10($k0) + + lw $1, 0x400($0) + nop + sw $1, 0x14($k0) + + sw $2, 0x18($k0) + sw $3, 0x1c($k0) + sw $4, 0x20($k0) + sw $5, 0x24($k0) + sw $6, 0x28($k0) + sw $7, 0x2c($k0) + sw $8, 0x30($k0) + sw $9, 0x34($k0) + sw $10, 0x38($k0) + sw $11, 0x3c($k0) + sw $12, 0x40($k0) + sw $13, 0x44($k0) + sw $14, 0x48($k0) + sw $15, 0x4c($k0) + sw $16, 0x50($k0) + sw $17, 0x54($k0) + sw $18, 0x58($k0) + sw $19, 0x5c($k0) + sw $20, 0x60($k0) + sw $21, 0x64($k0) + sw $22, 0x68($k0) + sw $23, 0x6c($k0) + sw $24, 0x70($k0) + sw $25, 0x74($k0) + sw $26, 0x78($k0) + sw $27, 0x7c($k0) + sw $28, 0x80($k0) + sw $29, 0x84($k0) + sw $30, 0x88($k0) + sw $31, 0x8c($k0) + mfhi $a0 + nop + sw $a0, 0x90($k0) + + mflo $a0 + nop + sw $a0, 0x94($k0) + + + # lw $a0, 0x404($0) # saved EPC + mfc0 $a0, $14 # EPC + nop + sw $a0, 0($k0) + + # lw $a0, 0x408($0) # saved SR + mfc0 $a0, $12 # SR + nop + sw $a0, 0xc($k0) + + mfc0 $a0, $8 # BadVaddr + nop + sw $a0, 0x8($k0) + + sw $0, 0x98($k0) + + + # lw $a0, 0x40c($0) # saved Cause + mfc0 $a0, $13 # Cause + nop + sw $a0, 4($k0) + + sll $a0, 25 + srl $a0, 27 + jal trap + or $a1, $k0, $0 + + la $k0, __trap_frame + + lw $a0, 0x94($k0) + nop + mtlo $a0 + + lw $a0, 0x90($k0) + nop + mthi $a0 + + # lw $0, 0x10($k0) + lw $1, 0x14($k0) + lw $2, 0x18($k0) + lw $3, 0x1c($k0) + lw $4, 0x20($k0) + lw $5, 0x24($k0) + lw $6, 0x28($k0) + lw $7, 0x2c($k0) + lw $8, 0x30($k0) + lw $9, 0x34($k0) + lw $10, 0x38($k0) + lw $11, 0x3c($k0) + lw $12, 0x40($k0) + lw $13, 0x44($k0) + lw $14, 0x48($k0) + lw $15, 0x4c($k0) + lw $16, 0x50($k0) + lw $17, 0x54($k0) + lw $18, 0x58($k0) + lw $19, 0x5c($k0) + lw $20, 0x60($k0) + lw $21, 0x64($k0) + lw $22, 0x68($k0) + lw $23, 0x6c($k0) + lw $24, 0x70($k0) + lw $25, 0x74($k0) + # lw $26, 0x78($k0) + # lw $27, 0x7c($k0) + lw $28, 0x80($k0) + lw $29, 0x84($k0) + lw $30, 0x88($k0) + lw $31, 0x8c($k0) + + lw $k1, 0xc($k0) + nop + srl $k1, 1 + sll $k1, 1 + mtc0 $k1, $12 # restore SR + + lw $k1, 0($k0) + lw $k0, 0x410($0) # k0 saved here by exception prologue (at 0x80) + jr $k1 + cop0 0x10 + nop + .end def_exc_handler + + .global bp_exc_handler + .ent bp_exc_handler +bp_exc_handler: + .set noreorder + .set noat + .word 0 + .word 0 + la $k0, __trap_frame + sw $0, 0x10($k0) + sw $1, 0x14($k0) + sw $2, 0x18($k0) + sw $3, 0x1c($k0) + sw $4, 0x20($k0) + sw $5, 0x24($k0) + sw $6, 0x28($k0) + sw $7, 0x2c($k0) + sw $8, 0x30($k0) + sw $9, 0x34($k0) + sw $10, 0x38($k0) + sw $11, 0x3c($k0) + sw $12, 0x40($k0) + sw $13, 0x44($k0) + sw $14, 0x48($k0) + sw $15, 0x4c($k0) + sw $16, 0x50($k0) + sw $17, 0x54($k0) + sw $18, 0x58($k0) + sw $19, 0x5c($k0) + sw $20, 0x60($k0) + sw $21, 0x64($k0) + sw $22, 0x68($k0) + sw $23, 0x6c($k0) + sw $24, 0x70($k0) + sw $25, 0x74($k0) + sw $26, 0x78($k0) + sw $27, 0x7c($k0) + sw $28, 0x80($k0) + sw $29, 0x84($k0) + sw $30, 0x88($k0) + sw $31, 0x8c($k0) + mfhi $a0 + nop + sw $a0, 0x90($k0) + + mflo $a0 + nop + sw $a0, 0x94($k0) + + + # lw $a0, 0x424($0) # saved EPC + mfc0 $a0, $14 # EPC + nop + sw $a0, 0($k0) + + # lw $a0, 0x42c($0) # saved SR + mfc0 $a0, $12 # SR + nop + sw $a0, 0xc($k0) + + mfc0 $a0, $8 # BadVaddr + nop + sw $a0, 0x8($k0) + + lw $a0, 0x430($0) # saved DCIC + nop + sw $a0, 0x98($k0) + + + # lw $a0, 0x428($0) # saved Cause + mfc0 $a0, $13 # Cause + nop + sw $a0, 4($k0) + + sll $a0, 25 + srl $a0, 27 + jal trap + or $a1, $k0, $0 + + + la $k0, __trap_frame + + lw $a0, 0x94($k0) + nop + mtlo $a0 + + lw $a0, 0x90($k0) + nop + mthi $a0 + + lw $a0, 0x98($k0) + nop + mtc0 $a0, $7 + + # lw $0, 0x10($k0) + lw $1, 0x14($k0) + lw $2, 0x18($k0) + lw $3, 0x1c($k0) + lw $4, 0x20($k0) + lw $5, 0x24($k0) + lw $6, 0x28($k0) + lw $7, 0x2c($k0) + lw $8, 0x30($k0) + lw $9, 0x34($k0) + lw $10, 0x38($k0) + lw $11, 0x3c($k0) + lw $12, 0x40($k0) + lw $13, 0x44($k0) + lw $14, 0x48($k0) + lw $15, 0x4c($k0) + lw $16, 0x50($k0) + lw $17, 0x54($k0) + lw $18, 0x58($k0) + lw $19, 0x5c($k0) + lw $20, 0x60($k0) + lw $21, 0x64($k0) + lw $22, 0x68($k0) + lw $23, 0x6c($k0) + lw $24, 0x70($k0) + lw $25, 0x74($k0) + # lw $26, 0x78($k0) + # lw $27, 0x7c($k0) + lw $28, 0x80($k0) + lw $29, 0x84($k0) + lw $30, 0x88($k0) + lw $31, 0x8c($k0) + + lw $k1, 0xc($k0) + nop + srl $k1, 1 + sll $k1, 1 + mtc0 $k1, $12 # restore SR + + lw $k1, 0($k0) + lw $k0, 0x420($0) # k0 saved here by debug exception prologue (at 0x40) + jr $k1 + cop0 0x10 + nop + .end bp_exc_handler + diff --git a/sps2_basement/hardware/debug/ioptrap/src/imports.lst b/sps2_basement/hardware/debug/ioptrap/src/imports.lst new file mode 100644 index 0000000..8c11bc8 --- /dev/null +++ b/sps2_basement/hardware/debug/ioptrap/src/imports.lst @@ -0,0 +1,31 @@ +#ifdef TEST_TRAP +thbase_IMPORTS_start +I_CreateThread +I_DelayThread +I_StartThread +I_ExitDeleteThread +thbase_IMPORTS_end +#endif + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +excepman_IMPORTS_start +I_RegisterDefaultExceptionHandler +I_RegisterPriorityExceptionHandler +excepman_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_setjmp +I_memset +sysclib_IMPORTS_end diff --git a/sps2_basement/hardware/debug/ioptrap/src/ioptrap.c b/sps2_basement/hardware/debug/ioptrap/src/ioptrap.c new file mode 100644 index 0000000..9f69619 --- /dev/null +++ b/sps2_basement/hardware/debug/ioptrap/src/ioptrap.c @@ -0,0 +1,230 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOP exception handling. + */ + +#include "types.h" +#include "defs.h" +#include "irx.h" + +#include "ioptrap.h" + +#include "excepman.h" +#include "loadcore.h" +#include "intrman.h" +#include "sifman.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" + +IRX_ID("ioptrap_driver", 1, 1); + +extern struct irx_export_table _exp_ioptrap; + + +static const char *exception_type_name[] = { + "Interrupt", + "TLB Modification", + "TLB Miss Load", + "TLB Miss Store", + "Address Error Load", + "Address Error Store", + "Instruction Bus Error", + "Data Bus Error", + "Syscall", + "Breakpoint", + "Reserved Instruction", + "Coprocessor Unusable", + "Overflow", + "Reserved 13", + "Reserved 14" /* "Floating point exception" */ +}; + +const char *get_exception_name(exception_type_t type) +{ + return exception_type_name[type]; +} + +exception_frame_t __trap_frame; +extern void def_exc_handler(); +extern void bp_exc_handler(); + +int dbg_jmp_buf_setup = 0; +jmp_buf dbg_jmp_buf; + +exception_type_t dbg_setjmp() +{ + int v; + if (0 == (v = setjmp(dbg_jmp_buf))) { + dbg_jmp_buf_setup = 1; + } else { + dbg_jmp_buf_setup = 0; + } + return v; +} + +#define JUMP_BUF_PC 0 +#define JUMP_BUF_SP 1 +#define JUMP_BUF_FP 2 +#define JUMP_BUF_S0 3 +#define JUMP_BUF_S1 4 +#define JUMP_BUF_S2 5 +#define JUMP_BUF_S3 6 +#define JUMP_BUF_S4 7 +#define JUMP_BUF_S5 8 +#define JUMP_BUF_S6 9 +#define JUMP_BUF_S7 10 +#define JUMP_BUF_GP 11 + +// Define this to something else if you want... maybe some ee_sio stuff :P +#define TRAP_PRINTF(args...) + +static trap_exception_handler_t handlers[16]; + +trap_exception_handler_t set_exception_handler(exception_type_t type, trap_exception_handler_t handler) +{ + trap_exception_handler_t old_handler = handlers[type]; + handlers[type] = handler; + return old_handler; +} + +trap_exception_handler_t get_exception_handler(exception_type_t type) +{ + return handlers[type]; +} + +void trap(exception_type_t type, struct exception_frame *ex) +{ + u32 i; + if (dbg_jmp_buf_setup) { + u32 *p = (u32 *)dbg_jmp_buf; + /* simulate longjmp */ + ex->epc = p[JUMP_BUF_PC]; + ex->regs[29] = p[JUMP_BUF_SP]; + ex->regs[30] = p[JUMP_BUF_FP]; + ex->regs[16] = p[JUMP_BUF_S0]; + ex->regs[17] = p[JUMP_BUF_S1]; + ex->regs[18] = p[JUMP_BUF_S2]; + ex->regs[19] = p[JUMP_BUF_S3]; + ex->regs[20] = p[JUMP_BUF_S4]; + ex->regs[21] = p[JUMP_BUF_S5]; + ex->regs[22] = p[JUMP_BUF_S6]; + ex->regs[23] = p[JUMP_BUF_S7]; + ex->regs[28] = p[JUMP_BUF_GP]; + ex->regs[2] = type; /* return value from setjmp */ + return; + } + TRAP_PRINTF("IOP Exception : %s\n", exception_type_name[type]); + TRAP_PRINTF("EPC=%08x CAUSE=%08x SR=%08x BADVADDR=%08x DCIC=%08x\n", ex->epc, ex->cause, ex->sr, ex->badvaddr, ex->dcic); + for (i = 0; i != 32; i += 4) { + TRAP_PRINTF("r[%02d]=%08x r[%02d]=%08x r[%02d]=%08x r[%02d]=%08x", + i, ex->regs[i], i + 1, ex->regs[i + 1], i + 2, ex->regs[i + 2], i + 3, ex->regs[i + 3]); + } + + if (handlers[type]) { + handlers[type](type, ex); + } + + if (type == EXCEPTION_Bp) { + ex->dcic = 0; + } else { + if (ex->cause & (1 << 31)) { + ex->cause &= ~(1 << 31); /* clear BD */ + } else { + ex->epc += 4; + } + } +} + +#ifdef TEST_TRAP +static void trigger() +{ + u32 v; + printf("trigger=%p\n", trigger); + printf("badaddr\n"); + if (0 == (v = setjmp(dbg_jmp_buf))) { + dbg_jmp_buf_setup = 1; + *(u32 *)0xdeadbeef = 0xfeedface; + } else { + printf("exception occurred in command, v=%08x\n", v); + } + dbg_jmp_buf_setup = 0; + printf("done.\n"); +} + +void main_thread(void *unused) +{ + int i = 0; + + DelayThread(1000 * 1000); + + printf("IOP: about to trap!\n"); + trigger(); + printf("IOP: back from trap!\n"); + while (1) { + printf("IOP: still running %d\n", i++); + DelayThread(2000 * 1000); + if (i == 10) + break; + } + ExitDeleteThread(); +} + +int create_main_thread(void) +{ + iop_thread_t thread; + + thread.attr = 0x2000000; + thread.option = 0; + thread.thread = main_thread; + thread.stacksize = 0x8000; + thread.priority = 0x18; + return CreateThread(&thread); +} + +void do_tests() +{ + int thid; + thid = create_main_thread(); + StartThread(thid, NULL); +} +#else +#define do_tests() +#endif + +int _start(int argc, char **argv) +{ + int rv; + + if (RegisterLibraryEntries(&_exp_ioptrap) != 0) + return 1; + + memset(handlers, 0, sizeof(trap_exception_handler_t) * 16); + printf("ioptrap starts.\n"); + if ((rv = RegisterDefaultExceptionHandler((exception_handler_t)def_exc_handler)) < 0) { + printf("RegisterDefaultExceptionHandler failed, rv=%d\n", rv); + return 1; + } + if ((rv = RegisterPriorityExceptionHandler(IOP_EXCEPTION_HDB, 0, (exception_handler_t)bp_exc_handler)) < 0) { + // shouldn't we release the default exception handler here... ? + printf("RegisterDefaultExceptionHandler failed, rv=%d\n", rv); + return 1; + } + do_tests(); + return 0; +} + +int shutdown() +{ + return 0; +} diff --git a/sps2_basement/hardware/debug/ioptrap/src/irx_imports.h b/sps2_basement/hardware/debug/ioptrap/src/irx_imports.h new file mode 100644 index 0000000..d2aaa89 --- /dev/null +++ b/sps2_basement/hardware/debug/ioptrap/src/irx_imports.h @@ -0,0 +1,29 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "excepman.h" +#include "loadcore.h" +#include "intrman.h" +#include "sifman.h" +#include "stdio.h" +#include "sysclib.h" +#ifdef TEST_TRAP +#include "thbase.h" +#endif + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/debug/sior/Makefile b/sps2_basement/hardware/debug/sior/Makefile new file mode 100644 index 0000000..3d1dc73 --- /dev/null +++ b/sps2_basement/hardware/debug/sior/Makefile @@ -0,0 +1,14 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_OBJS = sior.o xprintf.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/debug/sior/src/exports.tab b/sps2_basement/hardware/debug/sior/src/exports.tab new file mode 100644 index 0000000..1090f77 --- /dev/null +++ b/sps2_basement/hardware/debug/sior/src/exports.tab @@ -0,0 +1,22 @@ +DECLARE_EXPORT_TABLE(sior, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + + DECLARE_EXPORT(sio_init) +/*05*/ DECLARE_EXPORT(sio_putc) + DECLARE_EXPORT(sio_getc) + DECLARE_EXPORT(sio_getc_block) + DECLARE_EXPORT(sio_write) + DECLARE_EXPORT(sio_read) +/*10*/ DECLARE_EXPORT(sio_puts) + DECLARE_EXPORT(sio_putsn) + DECLARE_EXPORT(sio_gets) + DECLARE_EXPORT(sio_flush) + DECLARE_EXPORT(sio_printf) +/*15*/ DECLARE_EXPORT(sio_vprintf) + +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/debug/sior/src/imports.lst b/sps2_basement/hardware/debug/sior/src/imports.lst new file mode 100644 index 0000000..ce70749 --- /dev/null +++ b/sps2_basement/hardware/debug/sior/src/imports.lst @@ -0,0 +1,24 @@ +loadcore_IMPORTS_start +I_FlushDcache +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +sifcmd_IMPORTS_start +I_sceSifBindRpc +I_sceSifCallRpc +sifcmd_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memset +I_strlen +//I_vsprintf broken !!! +I_look_ctype_table +sysclib_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +thbase_IMPORTS_end diff --git a/sps2_basement/hardware/debug/sior/src/irx_imports.h b/sps2_basement/hardware/debug/sior/src/irx_imports.h new file mode 100644 index 0000000..9dceb79 --- /dev/null +++ b/sps2_basement/hardware/debug/sior/src/irx_imports.h @@ -0,0 +1,25 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2001, 2005 ps2dev - http;//www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "loadcore.h" +#include "sifcmd.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/debug/sior/src/sior.c b/sps2_basement/hardware/debug/sior/src/sior.c new file mode 100644 index 0000000..f31cb88 --- /dev/null +++ b/sps2_basement/hardware/debug/sior/src/sior.c @@ -0,0 +1,141 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# IOP exception handling. +*/ + +#include + +#include "types.h" +#include "defs.h" +#include "irx.h" + +#include "sior.h" +#include "xprintf.h" + +#include "irx_imports.h" +IRX_ID("sioremote_driver", 1, 1); + +extern struct irx_export_table _exp_sior; + +static struct t_SifRpcClientData cd0; +static union siorCommsData buffer; +static char tbuf[2048]; + +void sio_init(u32 baudrate, u8 lcr_ueps, u8 lcr_upen, u8 lcr_usbl, u8 lcr_umode) { + struct siorInitArgs * i = &buffer.init; + i->baudrate = baudrate; + i->lcr_ueps = lcr_ueps; + i->lcr_upen = lcr_upen; + i->lcr_usbl = lcr_usbl; + i->lcr_umode = lcr_umode; + SifCallRpc(&cd0, SIOR_INIT, 0, &buffer, sizeof(struct siorInitArgs), NULL, 0, NULL, NULL); +} + +int sio_putc(int c) { + buffer.result = c; + SifCallRpc(&cd0, SIOR_PUTC, 0, &buffer, sizeof(int), &buffer, sizeof(int), NULL, NULL); + return buffer.result; +} + +int sio_getc(void) { + SifCallRpc(&cd0, SIOR_GETC, 0, 0, 0, &buffer, sizeof(int), NULL, NULL); + return buffer.result; +} + +int sio_getc_block(void) { + SifCallRpc(&cd0, SIOR_GETCBLOCK, 0, 0, 0, &buffer, sizeof(int), NULL, NULL); + return buffer.result; +} + +size_t sio_write(const char *buf, size_t size) { + buffer.write.buf = buf; + buffer.write.len = size; + SifCallRpc(&cd0, SIOR_WRITE, 0, &buffer, 8, &buffer, 4, NULL, NULL); + return buffer.result; +} + +size_t sio_read(char *buf, size_t size) { + buffer.read.buf = buf; + buffer.read.len = size; + SifCallRpc(&cd0, SIOR_READ, 0, &buffer, 8, &buffer, 4, NULL, NULL); + return buffer.result; +} + +int sio_puts(const char * str) { + buffer.cstr = str; + SifCallRpc(&cd0, SIOR_PUTS, 0, &buffer, 4, &buffer, 4, NULL, NULL); + return buffer.result; +} + +int sio_putsn(const char * str) { + buffer.cstr = str; + SifCallRpc(&cd0, SIOR_PUTSN, 0, &buffer, 4, &buffer, 4, NULL, NULL); + return buffer.result; +} + +char *sio_gets(char * str) { + buffer.str = str; + SifCallRpc(&cd0, SIOR_GETS, 0, &buffer, 4, &buffer, 4, NULL, NULL); + return buffer.str; +} + +void sio_flush(void) { + SifCallRpc(&cd0, SIOR_FLUSH, 0, NULL, 0, NULL, 0, NULL, NULL); +} + +int sio_vprintf(const char * str, va_list args) { + int res; + + res = vsnprintf(tbuf, sizeof(tbuf), str, args); + printf("%s", tbuf); + sio_putsn(tbuf); + + return res; +} + +int sio_printf(const char * str, ...) { + int res; + va_list args; + + va_start(args, str); + res = sio_vprintf(str, args); + va_end(args); + + return res; +} + +int _start(int argc, char **argv) +{ + int retries; + + memset(&cd0, 0, sizeof(cd0)); + + for (retries = 0; retries < 15; retries++) { + printf("Binding RPC.\n"); + if (SifBindRpc(&cd0, SIOR_IRX, 0) < 0) { + printf("Failed!\n"); + return MODULE_NO_RESIDENT_END; + } + if (cd0.server != 0) { + printf("Registering library.\n"); + if (RegisterLibraryEntries(&_exp_sior)) { + printf("Couldn't register.\n"); + return MODULE_NO_RESIDENT_END; + } + return MODULE_RESIDENT_END; + } + printf("Huh, not available, retrying... ?\n"); + DelayThread(1000); + } + + printf("Giving up.\n"); + + return MODULE_NO_RESIDENT_END; +} diff --git a/sps2_basement/hardware/debug/sior/src/xprintf.c b/sps2_basement/hardware/debug/sior/src/xprintf.c new file mode 100644 index 0000000..0459259 --- /dev/null +++ b/sps2_basement/hardware/debug/sior/src/xprintf.c @@ -0,0 +1,1119 @@ +/* + * xprintf.c from ps2sdk/ee/libc/src adapted to IOP + * + * Copyright (C) 2007-2009 misfire + * + * Licensed under the Academic Free License version 2.0. See file LICENSE. + * + * Unfortunately, some sysclib functions like sprintf and vsprintf are broken + * (at least on my machine). Therefore, instead of importing them, we define + * our own. + */ + +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Some portions of this file Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Various *printf functions. +*/ + +/* Code borrowed from mysql's xprintf.c, by Richard Hipp */ +/* This xprintf.c file on which this one is based is in public domain. */ + +#include +#include +#include +/*#include */ +#include +/*#include */ +/*#include */ +/*#include */ +#include +#include + +#include +#include + +/*#include "sio.h"*/ + +#include "xprintf.h" + +/* +** The maximum number of digits of accuracy in a floating-point conversion. +*/ +#define MAXDIG 20 + +#ifdef F_vxprintf +/* +** Conversion types fall into various categories as defined by the +** following enumeration. +*/ + +enum e_type { /* The type of the format field */ + RADIX, /* Integer types. %d, %x, %o, and so forth */ + FLOAT, /* Floating point. %f */ + EXP, /* Exponentional notation. %e and %E */ + GENERIC, /* Floating or exponential, depending on exponent. %g */ + SIZE, /* Return number of characters processed so far. %n */ + STRING, /* Strings. %s */ + PERCENT, /* Percent symbol. %% */ + CHAR, /* Characters. %c */ + ERROR, /* Used to indicate no such conversion type */ +/* The rest are extensions, not normally found in printf() */ + CHARLIT, /* Literal characters. %' */ + SEEIT, /* Strings with visible control characters. %S */ + MEM_STRING, /* A string which should be deleted after use. %z */ + ORDINAL, /* 1st, 2nd, 3rd and so forth */ +}; + +/* +** Each builtin conversion character (ex: the 'd' in "%d") is described +** by an instance of the following structure +*/ +typedef struct s_info { /* Information about each format field */ + int fmttype; /* The format field code letter */ + int base; /* The base for radix conversion */ + char *charset; /* The character set for conversion */ + int flag_signed; /* Is the quantity signed? */ + char *prefix; /* Prefix on non-zero values in alt format */ + enum e_type type; /* Conversion paradigm */ +} info; + +/* +** The following table is searched linearly, so it is good to put the +** most frequently used conversion types first. +*/ +static info fmtinfo[] = { + { 'd', 10, "0123456789", 1, 0, RADIX, }, + { 's', 0, 0, 0, 0, STRING, }, + { 'S', 0, 0, 0, 0, SEEIT, }, + { 'z', 0, 0, 0, 0, MEM_STRING, }, + { 'c', 0, 0, 0, 0, CHAR, }, + { 'o', 8, "01234567", 0, "0", RADIX, }, + { 'u', 10, "0123456789", 0, 0, RADIX, }, + { 'x', 16, "0123456789abcdef", 0, "x0", RADIX, }, + { 'X', 16, "0123456789ABCDEF", 0, "X0", RADIX, }, + { 'r', 10, "0123456789", 0, 0, ORDINAL, }, + { 'f', 0, 0, 1, 0, FLOAT, }, + { 'e', 0, "e", 1, 0, EXP, }, + { 'E', 0, "E", 1, 0, EXP, }, + { 'g', 0, "e", 1, 0, GENERIC, }, + { 'G', 0, "E", 1, 0, GENERIC, }, + { 'i', 10, "0123456789", 1, 0, RADIX, }, + { 'n', 0, 0, 0, 0, SIZE, }, + { 'S', 0, 0, 0, 0, SEEIT, }, + { '%', 0, 0, 0, 0, PERCENT, }, + { 'b', 2, "01", 0, "b0", RADIX, }, /* Binary notation */ + { 'p', 16, "0123456789ABCDEF", 0, "x0", RADIX, }, /* Pointers */ + { '\'', 0, 0, 0, 0, CHARLIT, }, /* Literal char */ +}; +#define NINFO (sizeof(fmtinfo)/sizeof(info)) /* Size of the fmtinfo table */ + +/* +** If NOFLOATINGPOINT is defined, then none of the floating point +** conversions will work. +*/ +#ifndef NOFLOATINGPOINT +/* +** "*val" is a double such that 0.1 <= *val < 10.0 +** Return the ascii code for the leading digit of *val, then +** multiply "*val" by 10.0 to renormalize. +** +** Example: +** input: *val = 3.14159 +** output: *val = 1.4159 function return = '3' +** +** The counter *cnt is incremented each time. After counter exceeds +** 16 (the number of significant digits in a 64-bit float) '0' is +** always returned. +*/ +static int getdigit(long double *val, int *cnt){ + int digit; + long double d; + if( (*cnt)++ >= MAXDIG ) return '0'; + digit = (int)*val; + d = digit; + digit += '0'; + *val = (*val - d)*10.0; + return digit; +} +#endif + +/* +** Setting the size of the BUFFER involves trade-offs. No %d or %f +** conversion can have more than BUFSIZE characters. If the field +** width is larger than BUFSIZE, it is silently shortened. On the +** other hand, this routine consumes more stack space with larger +** BUFSIZEs. If you have some threads for which you want to minimize +** stack space, you should keep BUFSIZE small. +*/ +#define BUFSIZE 100 /* Size of the output buffer */ + +/* +** The root program. All variations call this core. +** +** INPUTS: +** func This is a pointer to a function taking three arguments +** 1. A pointer to the list of characters to be output +** (Note, this list is NOT null terminated.) +** 2. An integer number of characters to be output. +** (Note: This number might be zero.) +** 3. A pointer to anything. Same as the "arg" parameter. +** +** arg This is the pointer to anything which will be passed as the +** third argument to "func". Use it for whatever you like. +** +** fmt This is the format string, as in the usual print. +** +** ap This is a pointer to a list of arguments. Same as in +** vfprint. +** +** OUTPUTS: +** The return value is the total number of characters sent to +** the function "func". Returns -1 on a error. +** +** Note that the order in which automatic variables are declared below +** seems to make a big difference in determining how fast this beast +** will run. +*/ + +int vxprintf(func,arg,format,ap) + void (*func)(char*,int,void*); + void *arg; + const char *format; + va_list ap; +{ + register const char *fmt; /* The format string. */ + register int c; /* Next character in the format string */ + register char *bufpt; /* Pointer to the conversion buffer */ + register int precision; /* Precision of the current field */ + register int length; /* Length of the field */ + register int idx; /* A general purpose loop counter */ + int count; /* Total number of characters output */ + int width; /* Width of the current field */ + int flag_leftjustify; /* True if "-" flag is present */ + int flag_plussign; /* True if "+" flag is present */ + int flag_blanksign; /* True if " " flag is present */ + int flag_alternateform; /* True if "#" flag is present */ + int flag_zeropad; /* True if field width constant starts with zero */ + int flag_long; /* True if "l" flag is present */ + int flag_center; /* True if "=" flag is present */ + unsigned long longvalue; /* Value for integer types */ + +#ifndef NOFLOATINGPOINT + long double realvalue; /* Value for real types */ +#endif + info *infop; /* Pointer to the appropriate info structure */ + char buf[BUFSIZE]; /* Conversion buffer */ + char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ + int errorflag = 0; /* True if an error is encountered */ + enum e_type xtype; /* Conversion paradigm */ + char *zMem = 0; /* String to be freed */ + static char spaces[] = + " "; +#define SPACESIZE (sizeof(spaces)-1) +#ifndef NOFLOATINGPOINT + int exp; /* exponent of real numbers */ + long double rounder; /* Used for rounding floating point values */ + int flag_dp; /* True if decimal point should be shown */ + int flag_rtz; /* True if trailing zeros should be removed */ + int flag_exp; /* True to force display of the exponent */ + int nsd; /* Number of significant digits returned */ +#endif + + fmt = format; /* Put in a register for speed */ + count = length = 0; + bufpt = 0; + for(; (c=(*fmt))!=0; ++fmt){ + if( c!='%' ){ + register int amt; + bufpt = (char *)fmt; + amt = 1; + while( (c=(*++fmt))!='%' && c!=0 ) amt++; + (*func)(bufpt,amt,arg); + count += amt; + if( c==0 ) break; + } + if( (c=(*++fmt))==0 ){ + errorflag = 1; + (*func)("%",1,arg); + count++; + break; + } + /* Find out what flags are present */ + flag_leftjustify = flag_plussign = flag_blanksign = + flag_alternateform = flag_zeropad = flag_center = 0; + do{ + switch( c ){ + case '-': flag_leftjustify = 1; c = 0; break; + case '+': flag_plussign = 1; c = 0; break; + case ' ': flag_blanksign = 1; c = 0; break; + case '#': flag_alternateform = 1; c = 0; break; + case '0': flag_zeropad = 1; c = 0; break; + case '=': flag_center = 1; c = 0; break; + default: break; + } + }while( c==0 && (c=(*++fmt))!=0 ); + if( flag_center ) flag_leftjustify = 0; + /* Get the field width */ + width = 0; + if( c=='*' ){ + width = va_arg(ap,int); + if( width<0 ){ + flag_leftjustify = 1; + width = -width; + } + c = *++fmt; + }else{ + while( isdigit(c) ){ + width = width*10 + c - '0'; + c = *++fmt; + } + } + if( width > BUFSIZE-10 ){ + width = BUFSIZE-10; + } + /* Get the precision */ + if( c=='.' ){ + precision = 0; + c = *++fmt; + if( c=='*' ){ + precision = va_arg(ap,int); +#ifndef COMPATIBILITY + /* This is sensible, but SUN OS 4.1 doesn't do it. */ + if( precision<0 ) precision = -precision; +#endif + c = *++fmt; + }else{ + while( isdigit(c) ){ + precision = precision*10 + c - '0'; + c = *++fmt; + } + } + /* Limit the precision to prevent overflowing buf[] during conversion */ + if( precision>BUFSIZE-40 ) precision = BUFSIZE-40; + }else{ + precision = -1; + } + /* Get the conversion type modifier */ + if( c=='l' ){ + flag_long = 1; + c = *++fmt; + }else{ + flag_long = 0; + } + /* Fetch the info entry for the field */ + infop = 0; + for(idx=0; idxtype; + } + + /* + ** At this point, variables are initialized as follows: + ** + ** flag_alternateform TRUE if a '#' is present. + ** flag_plussign TRUE if a '+' is present. + ** flag_leftjustify TRUE if a '-' is present or if the + ** field width was negative. + ** flag_zeropad TRUE if the width began with 0. + ** flag_long TRUE if the letter 'l' (ell) prefixed + ** the conversion character. + ** flag_blanksign TRUE if a ' ' is present. + ** width The specified field width. This is + ** always non-negative. Zero is the default. + ** precision The specified precision. The default + ** is -1. + ** xtype The class of the conversion. + ** infop Pointer to the appropriate info struct. + */ + switch( xtype ){ + case ORDINAL: + case RADIX: + if(( flag_long )&&( infop->flag_signed )){ + signed long t = va_arg(ap,signed long); + longvalue = t; + }else if(( flag_long )&&( !infop->flag_signed )){ + unsigned long t = va_arg(ap,unsigned long); + longvalue = t; + }else if(( !flag_long )&&( infop->flag_signed )){ + signed int t = va_arg(ap,signed int) & ((unsigned long) 0xffffffff); + longvalue = t; + }else{ + unsigned int t = va_arg(ap,unsigned int) & ((unsigned long) 0xffffffff); + longvalue = t; + } +#ifdef COMPATIBILITY + /* For the format %#x, the value zero is printed "0" not "0x0". + ** I think this is stupid. */ + if( longvalue==0 ) flag_alternateform = 0; +#else + /* More sensible: turn off the prefix for octal (to prevent "00"), + ** but leave the prefix for hex. */ + if( longvalue==0 && infop->base==8 ) flag_alternateform = 0; +#endif + if( infop->flag_signed ){ + if( *(long*)&longvalue<0 ){ + longvalue = -*(long*)&longvalue; + prefix = '-'; + }else if( flag_plussign ) prefix = '+'; + else if( flag_blanksign ) prefix = ' '; + else prefix = 0; + }else prefix = 0; + if( flag_zeropad && precision3 || (b>10 && b<14) ){ + bufpt[0] = 't'; + bufpt[1] = 'h'; + }else if( a==1 ){ + bufpt[0] = 's'; + bufpt[1] = 't'; + }else if( a==2 ){ + bufpt[0] = 'n'; + bufpt[1] = 'd'; + }else if( a==3 ){ + bufpt[0] = 'r'; + bufpt[1] = 'd'; + } + } + { + register char *cset; /* Use registers for speed */ + register int base; + cset = infop->charset; + base = infop->base; + do{ /* Convert to ascii */ + *(--bufpt) = cset[longvalue%base]; + longvalue = longvalue/base; + }while( longvalue>0 ); + } + length = (int)(&buf[BUFSIZE]-bufpt); + if(infop->fmttype == 'p') + { + precision = 8; + flag_alternateform = 1; + } + + for(idx=precision-length; idx>0; idx--){ + *(--bufpt) = '0'; /* Zero pad */ + } + if( prefix ) *(--bufpt) = prefix; /* Add sign */ + if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ + char *pre, x; + pre = infop->prefix; + if( *bufpt!=pre[0] ){ + for(pre=infop->prefix; (x=(*pre))!=0; pre++) *(--bufpt) = x; + } + } + + length = (int)(&buf[BUFSIZE]-bufpt); + break; + case FLOAT: + case EXP: + case GENERIC: +#ifdef NOFLOATINGPOINT + va_arg(ap,double); +#else + realvalue = va_arg(ap,double); + if( precision<0 ) precision = 6; /* Set default precision */ + if( precision>BUFSIZE-10 ) precision = BUFSIZE-10; + if( realvalue<0.0 ){ + realvalue = -realvalue; + prefix = '-'; + }else{ + if( flag_plussign ) prefix = '+'; + else if( flag_blanksign ) prefix = ' '; + else prefix = 0; + } + if( infop->type==GENERIC && precision>0 ) precision--; + rounder = 0.0; +#ifdef COMPATIBILITY + /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */ + for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1); +#else + /* It makes more sense to use 0.5 */ + if( precision>MAXDIG-1 ) idx = MAXDIG-1; + else idx = precision; + for(rounder=0.5; idx>0; idx--, rounder*=0.1); +#endif + if( infop->type==FLOAT ) realvalue += rounder; + /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */ + exp = 0; + if( realvalue>0.0 ){ + int k = 0; + while( realvalue>=1e8 && k++<100 ){ realvalue *= 1e-8; exp+=8; } + while( realvalue>=10.0 && k++<100 ){ realvalue *= 0.1; exp++; } + while( realvalue<1e-8 && k++<100 ){ realvalue *= 1e8; exp-=8; } + while( realvalue<1.0 && k++<100 ){ realvalue *= 10.0; exp--; } + if( k>=100 ){ + bufpt = "NaN"; + length = 3; + break; + } + } + bufpt = buf; + /* + ** If the field type is GENERIC, then convert to either EXP + ** or FLOAT, as appropriate. + */ + flag_exp = xtype==EXP; + if( xtype!=FLOAT ){ + realvalue += rounder; + if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; } + } + if( xtype==GENERIC ){ + flag_rtz = !flag_alternateform; + if( exp<-4 || exp>precision ){ + xtype = EXP; + }else{ + precision = precision - exp; + xtype = FLOAT; + } + }else{ + flag_rtz = 0; + } + /* + ** The "exp+precision" test causes output to be of type EXP if + ** the precision is too large to fit in buf[]. + */ + nsd = 0; + if( xtype==FLOAT && exp+precision0 || flag_alternateform); + if( prefix ) *(bufpt++) = prefix; /* Sign */ + if( exp<0 ) *(bufpt++) = '0'; /* Digits before "." */ + else for(; exp>=0; exp--) *(bufpt++) = getdigit(&realvalue,&nsd); + if( flag_dp ) *(bufpt++) = '.'; /* The decimal point */ + for(exp++; exp<0 && precision>0; precision--, exp++){ + *(bufpt++) = '0'; + } + while( (precision--)>0 ) *(bufpt++) = getdigit(&realvalue,&nsd); + *(bufpt--) = 0; /* Null terminate */ + if( flag_rtz && flag_dp ){ /* Remove trailing zeros and "." */ + while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0; + if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0; + } + bufpt++; /* point to next free slot */ + }else{ /* EXP or GENERIC */ + flag_dp = (precision>0 || flag_alternateform); + if( prefix ) *(bufpt++) = prefix; /* Sign */ + *(bufpt++) = getdigit(&realvalue,&nsd); /* First digit */ + if( flag_dp ) *(bufpt++) = '.'; /* Decimal point */ + while( (precision--)>0 ) *(bufpt++) = getdigit(&realvalue,&nsd); + bufpt--; /* point to last digit */ + if( flag_rtz && flag_dp ){ /* Remove tail zeros */ + while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0; + if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0; + } + bufpt++; /* point to next free slot */ + if( exp || flag_exp ){ + *(bufpt++) = infop->charset[0]; + if( exp<0 ){ *(bufpt++) = '-'; exp = -exp; } /* sign of exp */ + else { *(bufpt++) = '+'; } + if( exp>=100 ){ + *(bufpt++) = (exp/100)+'0'; /* 100's digit */ + exp %= 100; + } + *(bufpt++) = exp/10+'0'; /* 10's digit */ + *(bufpt++) = exp%10+'0'; /* 1's digit */ + } + } + /* The converted number is in buf[] and zero terminated. Output it. + ** Note that the number is in the usual order, not reversed as with + ** integer conversions. */ + length = (int)(bufpt-buf); + bufpt = buf; + + /* Special case: Add leading zeros if the flag_zeropad flag is + ** set and we are not left justified */ + if( flag_zeropad && !flag_leftjustify && length < width){ + int i; + int nPad = width - length; + for(i=width; i>=nPad; i--){ + bufpt[i] = bufpt[i-nPad]; + } + i = prefix!=0; + while( nPad-- ) bufpt[i++] = '0'; + length = width; + } +#endif + break; + case SIZE: + *(va_arg(ap,int*)) = count; + length = width = 0; + break; + case PERCENT: + buf[0] = '%'; + bufpt = buf; + length = 1; + break; + case CHARLIT: + case CHAR: + c = buf[0] = (xtype==CHAR ? va_arg(ap,int) : *++fmt); + if( precision>=0 ){ + for(idx=1; idx=0 && precision=0x7f ){ + buf[i++] = '^'; + buf[i] = (c&0x1f)+0x40; + }else{ + buf[i] = c; + } + } + bufpt = buf; + length = i; + if( precision>=0 && precision0 ){ + if( flag_center ){ + nspace = nspace/2; + width -= nspace; + flag_leftjustify = 1; + } + count += nspace; + while( nspace>=SPACESIZE ){ + (*func)(spaces,SPACESIZE,arg); + nspace -= SPACESIZE; + } + if( nspace>0 ) (*func)(spaces,nspace,arg); + } + } + if( length>0 ){ + (*func)(bufpt,length,arg); + count += length; + } + if( xtype==MEM_STRING && zMem ){ +/* Not needed + free(zMem);*/ + } + if( flag_leftjustify ){ + register int nspace; + nspace = width-length; + if( nspace>0 ){ + count += nspace; + while( nspace>=SPACESIZE ){ + (*func)(spaces,SPACESIZE,arg); + nspace -= SPACESIZE; + } + if( nspace>0 ) (*func)(spaces,nspace,arg); + } + } + }/* End for loop over the format string */ + return errorflag ? -1 : count; +} /* End of function */ +#endif + +#ifdef F_xprintf +/* +** This non-standard function is still occasionally useful.... +*/ +int xprintf( + void (*func)(char*,int,void*), + void *arg, + const char *format, + ... +){ + va_list ap; + va_start(ap,format); + return vxprintf(func,arg,format,ap); +} +#endif + +/* +** Now for string-print, also as found in any standard library. +** Add to this the snprint function which stops added characters +** to the string at a given length. +** +** Note that snprint returns the length of the string as it would +** be if there were no limit on the output. +*/ +struct s_strargument { /* Describes the string being written to */ + char *next; /* Next free slot in the string */ + char *last; /* Last available slot in the string */ +}; + +void __sout(char *, int, void *); +#ifdef F___sout +void __sout(txt,amt,arg) + char *txt; + int amt; + void *arg; +{ + register char *head; + register const char *t; + register int a; + register char *tail; + a = amt; + t = txt; + head = ((struct s_strargument*)arg)->next; + tail = ((struct s_strargument*)arg)->last; + if( tail ){ + while( a-- >0 && head0 ) *(head++) = *(t++); + } + *head = 0; + ((struct s_strargument*)arg)->next = head; +} +#endif + +#ifdef F_vsnprintf +int vsnprintf(char *buf, size_t n, const char *fmt, va_list ap){ + struct s_strargument arg; + arg.next = buf; + arg.last = &buf[n-1]; + *buf = 0; + return vxprintf(__sout,&arg,fmt,ap); +} +#endif + +#ifdef F_snprintf +int snprintf(char *str, size_t sz, const char *format, ...) +{ + va_list args; + struct s_strargument arg; + int ret; + + arg.next = str; + arg.last = &str[sz-1]; + + va_start(args, format); + ret = vxprintf(__sout, &arg, format, args); + va_end(args); + + return ret; +} +#endif + +#ifdef F_vsprintf +int vsprintf(char *buf, const char *fmt, va_list ap){ + struct s_strargument arg; + arg.next = buf; + arg.last = NULL; + *buf = 0; + return vxprintf(__sout,&arg,fmt,ap); +} +#endif + +#ifdef F_sprintf +__attribute__((weak)) +int sprintf (char *str, const char *format, ...) +{ + va_list args; + struct s_strargument arg; + int ret; + + arg.next = str; + arg.last = NULL; + + va_start(args, format); + ret = vxprintf(__sout, &arg, format, args); + va_end(args); + + return ret; +} +#endif + +/* +** The following section of code handles the mprintf routine, that +** writes to memory obtained from malloc(). +*/ + +/* This structure is used to store state information about the +** write in progress +*/ +__attribute__((weak)) +struct sgMprintf { + char *zBase; /* A base allocation */ + char *zText; /* The string collected so far */ + int nChar; /* Length of the string so far */ + int nAlloc; /* Amount of space allocated in zText */ +}; + +void __mout(char *, int, void*); + +#ifdef F___mout +/* The xprintf callback function. */ +void __mout(zNewText,nNewChar,arg) + char *zNewText; + int nNewChar; + void *arg; +{ + struct sgMprintf *pM = (struct sgMprintf*)arg; + if( pM->nChar + nNewChar + 1 > pM->nAlloc ){ + pM->nAlloc = pM->nChar + nNewChar*2 + 1; + if( pM->zText==pM->zBase ){ + pM->zText = malloc(pM->nAlloc); + if( pM->zText && pM->nChar ) memcpy(pM->zText,pM->zBase,pM->nChar); + }else{ + pM->zText = realloc(pM->zText, pM->nAlloc); + } + } + if( pM->zText ){ + memcpy(&pM->zText[pM->nChar], zNewText, nNewChar); + pM->nChar += nNewChar; + pM->zText[pM->nChar] = 0; + } +} +#endif + +/* +** mprintf() works like printf(), but allocations memory to hold the +** resulting string and returns a pointer to the allocated memory. +** +** We changed the name to TclMPrint() to conform with the Tcl private +** routine naming conventions. +*/ + +#ifdef F_mprintf +char *mprintf(const char *zFormat, ...){ + va_list ap; + struct sgMprintf sMprintf; + char *zNew; + char zBuf[200]; + + va_start(ap,zFormat); + sMprintf.nChar = 0; + sMprintf.nAlloc = sizeof(zBuf); + sMprintf.zText = zBuf; + sMprintf.zBase = zBuf; + vxprintf(__mout,&sMprintf,zFormat,ap); + va_end(ap); + if( sMprintf.zText==sMprintf.zBase ){ + zNew = malloc( sMprintf.nChar+1 ); + if( zNew ) strcpy(zNew,zBuf); + }else{ + zNew = realloc(sMprintf.zText,sMprintf.nChar+1); + } + + return zNew; +} +#endif + +/* This is the varargs version of mprintf. +** +** The name is changed to TclVMPrintf() to conform with Tcl naming +** conventions. +*/ +#ifdef F_vmprintf +char *vmprintf(const char *zFormat,va_list ap){ + struct sgMprintf sMprintf; + char zBuf[200]; + sMprintf.nChar = 0; + sMprintf.zText = zBuf; + sMprintf.nAlloc = sizeof(zBuf); + sMprintf.zBase = zBuf; + vxprintf(__mout,&sMprintf,zFormat,ap); + if( sMprintf.zText==sMprintf.zBase ){ + sMprintf.zText = malloc( strlen(zBuf)+1 ); + if( sMprintf.zText ) strcpy(sMprintf.zText,zBuf); + }else{ + sMprintf.zText = realloc(sMprintf.zText,sMprintf.nChar+1); + } + return sMprintf.zText; +} +#endif + +#ifdef F_asprintf +int asprintf(char ** strp, const char *zFormat, ...){ + va_list ap; + struct sgMprintf sMprintf; + char *zNew; + char zBuf[200]; + + va_start(ap,zFormat); + sMprintf.nChar = 0; + sMprintf.nAlloc = sizeof(zBuf); + sMprintf.zText = zBuf; + sMprintf.zBase = zBuf; + vxprintf(__mout,&sMprintf,zFormat,ap); + va_end(ap); + if( sMprintf.zText==sMprintf.zBase ){ + zNew = malloc( sMprintf.nChar+1 ); + if( zNew ) strcpy(zNew,zBuf); + }else{ + zNew = realloc(sMprintf.zText,sMprintf.nChar+1); + } + + *strp = zNew; + + return sMprintf.nChar+1; +} +#endif + +#ifdef F_vasprintf +int vasprintf(char **strp, const char *format, va_list ap) { + struct sgMprintf sMprintf; + char zBuf[200]; + sMprintf.nChar = 0; + sMprintf.zText = zBuf; + sMprintf.nAlloc = sizeof(zBuf); + sMprintf.zBase = zBuf; + vxprintf(__mout,&sMprintf,format,ap); + if( sMprintf.zText==sMprintf.zBase ){ + sMprintf.zText = malloc( strlen(zBuf)+1 ); + if( sMprintf.zText ) strcpy(sMprintf.zText,zBuf); + }else{ + sMprintf.zText = realloc(sMprintf.zText,sMprintf.nChar+1); + } + *strp = sMprintf.zText; + return sMprintf.nChar; +} +#endif + +/* +** The following section of code handles the standard fprintf routines +** for pthreads. +*/ + +void __fout(char *, int, void *); + +#ifdef F___fout +void __fout(zNewText,nNewChar,arg) + char *zNewText; + int nNewChar; + void *arg; +{ + fwrite(zNewText,1,nNewChar,(FILE*)arg); +} +#endif + +#ifdef F_fprintf +/* The public interface routines */ +int fprintf(FILE *pOut, const char *zFormat, ...){ + va_list ap; + int retc; + + va_start(ap,zFormat); + retc = vxprintf(__fout,pOut,zFormat,ap); + va_end(ap); + return retc; +} +#endif + +#ifdef F_vfprintf +int vfprintf(FILE *pOut, const char *zFormat, va_list ap){ + return vxprintf(__fout,pOut,zFormat,ap); +} +#endif + + +#ifdef F_printf +int printf(const char *format, ...) +{ + va_list args; + int ret; + + va_start(args, format); + ret = vprintf(format, args); + va_end(args); + + return ret; +} +#endif + +#ifdef F_vprintf +int vprintf(const char *format, va_list args) +{ + static char buf[PS2LIB_STR_MAX]; + int ret; + + ret = vsnprintf(buf, PS2LIB_STR_MAX, format, args); + + write(1, buf, ret); + return ret; +} +#endif + +#ifdef F_putchar +int putchar( int chr ) +{ + write(1, &chr, 1); + return chr; +} +#endif + +/* Napalm puts() and printf() */ +/* Who are still using them anyway? :P */ + +#ifdef F_npmPuts + +#define NPM_RPC_SERVER 0x14d704e +#define NPM_RPC_PUTS 1 + +extern int _iop_reboot_count; + +static int npm_puts_sema = -1; +static int init = 0; +static SifRpcClientData_t npm_cd; + +static int npm_puts_init() +{ + int res; + ee_sema_t sema; + static int _rb_count = 0; + if(_rb_count != _iop_reboot_count) + { + _rb_count = _iop_reboot_count; + init = 0; + } + + if(init) + return(0); + + sema.init_count = 0; + sema.max_count = 1; + sema.option = 0; + if ((npm_puts_sema = CreateSema(&sema)) < 0) + return -1; + + SifInitRpc(0); + + while (((res = SifBindRpc(&npm_cd, NPM_RPC_SERVER, 0)) >= 0) && + (npm_cd.server == NULL)) + nopdelay(); + + if (res < 0) + return res; + + SignalSema(npm_puts_sema); + + init = 1; + return 0; +} + +int npmPuts(const char *buf) +{ + u8 puts_buf[512]; /* Implicitly aligned. */ + void *p = puts_buf; + + if (npm_puts_init() < 0) + return -E_LIB_API_INIT; + + WaitSema(npm_puts_sema); + + /* If the buffer is already 16-byte aligned, no need to copy it. */ + if (((u32)buf & 15) == 0) + p = (void *)buf; + else { + strncpy(p, buf, 511); + ((char *) p)[511] = '\0'; + } + + if (SifCallRpc(&npm_cd, NPM_RPC_PUTS, 0, p, 512, NULL, 0, NULL, NULL) < 0) + return -E_SIF_RPC_CALL; + + SignalSema(npm_puts_sema); + + return 1; +} +#endif + +#ifdef F_nprintf +int nprintf(const char *format, ...) +{ + char buf[PS2LIB_STR_MAX]; + va_list args; + int ret; + + va_start(args, format); + ret = vsnprintf(buf, PS2LIB_STR_MAX, format, args); + va_end(args); + + npmPuts(buf); + return ret; +} +#endif + +#ifdef F_vnprintf +int vnprintf(const char *format, va_list args) +{ + char buf[PS2LIB_STR_MAX]; + int ret; + + ret = vsnprintf(buf, PS2LIB_STR_MAX, format, args); + npmPuts(buf); + + return ret; +} +#endif + +#ifdef F_sio_printf +int sio_printf(const char *format, ...) +{ + static char buf[PS2LIB_STR_MAX]; + va_list args; + int size; + + va_start(args, format); + size = vsnprintf(buf, PS2LIB_STR_MAX, format, args); + va_end(args); + + /* A bit hackish, but if the last character is '\n' then strip it off + and pass the string to sio_puts(). */ + if (buf[size - 1] == '\n') { + buf[size - 1] = '\0'; + size++; /* Account for the '\r'. */ + sio_puts(buf); + } else { + sio_write(buf, size); + } + + return size; +} +#endif diff --git a/sps2_basement/hardware/debug/sior/src/xprintf.h b/sps2_basement/hardware/debug/sior/src/xprintf.h new file mode 100644 index 0000000..3847eb2 --- /dev/null +++ b/sps2_basement/hardware/debug/sior/src/xprintf.h @@ -0,0 +1,40 @@ +/* + * xprinf.h + * + * Copyright (C) 2007-2009 misfire + * + * Licensed under the Academic Free License version 2.0. See file LICENSE. + */ + +#ifndef _XPRINTF_H_ +#define _XPRINTF_H_ + +#include + +/* Define available functions here */ +#define F_vxprintf +#define NOFLOATINGPOINT /* won't compile without it */ +#define F___sout + +//#define F_sprintf +//#define F_snprintf +//#define F_vsprintf +#define F_vsnprintf + +#ifdef F_sprintf +int sprintf(char *str, const char *format, ...); +#endif + +#ifdef F_snprintf +int snprintf(char *str, size_t sz, const char *format, ...); +#endif + +#ifdef F_vsprintf +int vsprintf(char *buf, const char *fmt, va_list ap); +#endif + +#ifdef F_vsnprintf +int vsnprintf(char *buf, size_t n, const char *fmt, va_list ap); +#endif + +#endif /* _XPRINTF_H_ */ diff --git a/sps2_basement/hardware/dev9/Makefile b/sps2_basement/hardware/dev9/Makefile new file mode 100644 index 0000000..95c278f --- /dev/null +++ b/sps2_basement/hardware/dev9/Makefile @@ -0,0 +1,12 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +SUBDIRS = dev9 extflash poweroff atad hdpro_atad pvrdrv + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/Rules.make diff --git a/sps2_basement/hardware/dev9/atad/Makefile b/sps2_basement/hardware/dev9/atad/Makefile new file mode 100644 index 0000000..fbdc578 --- /dev/null +++ b/sps2_basement/hardware/dev9/atad/Makefile @@ -0,0 +1,45 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +# Enable to perform the SCE HDD check at the end of ATA device initialization. +ATA_SCE_AUTH_HDD ?= 0 + +# Enable to enable support for Multi-Word DMA (MWDMA) modes, as in early ATAD modules. +ATA_MWDMA_MODES ?= 0 + +# Enable to enable support for PIO modes 0-4 (as in early ATAD modules), instead of just PIO mode 0. +ATA_ALL_PIO_MODES ?= 0 + +# Disable to disable the workaround for bad GameStar compatible adaptors. +ATA_GAMESTAR_WORKAROUND ?= 1 + +IOP_BIN ?= ps2atad.irx + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/dev9/include +IOP_OBJS = ps2atad.o imports.o exports.o + +ifeq ($(ATA_SCE_AUTH_HDD),1) +IOP_CFLAGS += -DATA_SCE_AUTH_HDD=1 +endif + +ifeq ($(ATA_MWDMA_MODES),1) +IOP_CFLAGS += -DATA_MWDMA_MODES=1 +endif + +ifeq ($(ATA_ALL_PIO_MODES),1) +IOP_CFLAGS += -DATA_ALL_PIO_MODES=1 +endif + +ifeq ($(ATA_GAMESTAR_WORKAROUND),1) +IOP_CFLAGS += -DATA_GAMESTAR_WORKAROUND=1 +endif + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dev9/atad/include/atad.h b/sps2_basement/hardware/dev9/atad/include/atad.h new file mode 100644 index 0000000..5e8240a --- /dev/null +++ b/sps2_basement/hardware/dev9/atad/include/atad.h @@ -0,0 +1,96 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * ATA Device Driver definitions and imports. + */ + +#ifndef __ATAD_H__ +#define __ATAD_H__ + +#include +#include + +/* These are used with the dir parameter of ata_device_sector_io(). */ +#define ATA_DIR_READ 0 +#define ATA_DIR_WRITE 1 + +typedef struct _ata_devinfo +{ + /** Was successfully probed. */ + s32 exists; + /** Supports the PACKET command set. */ + s32 has_packet; + /** Total number of user sectors. */ + u32 total_sectors; + /** Word 0x100 of the identify info. */ + u32 security_status; + /** Supports the 48-bit LBA command set (unofficial). */ + u32 lba48; + /** Total number of 48-bit LBA user sectors (unofficial). */ + u32 total_sectors_lba48; +} ata_devinfo_t; + +/* Error definitions. */ +#define ATA_RES_ERR_NOTREADY -501 +#define ATA_RES_ERR_TIMEOUT -502 +#define ATA_RES_ERR_IO -503 +#define ATA_RES_ERR_NODATA -504 +#define ATA_RES_ERR_NODEV -505 +#define ATA_RES_ERR_CMD -506 +#define ATA_RES_ERR_LOCKED -509 +#define ATA_RES_ERR_ICRC -510 + +ata_devinfo_t *ata_get_devinfo(int device); + +int ata_reset_devices(void); + +int ata_io_start(void *buf, u32 blkcount, u16 feature, u16 nsector, u16 sector, u16 lcyl, u16 hcyl, u16 select, u16 command); +int ata_io_finish(void); + +int ata_get_error(void); + +#define ata_device_dma_transfer ata_device_sector_io // Backward-compatibility +int ata_device_sector_io(int device, void *buf, u32 lba, u32 nsectors, int dir); + +// DRM functions that were meant to keep users from sharing disks (and hence the contained content). Supported by only Sony-modified HDDs (e.g. the SCPH-20400). +int ata_device_sce_sec_set_password(int device, void *password); +int ata_device_sce_sec_unlock(int device, void *password); +int ata_device_sce_sec_erase(int device); + +int ata_device_idle(int device, int period); +int ata_device_sce_identify_drive(int device, void *data); +int ata_device_smart_get_status(int device); +int ata_device_smart_save_attr(int device); +int ata_device_flush_cache(int device); +int ata_device_idle_immediate(int device); + +#define atad_IMPORTS_start DECLARE_IMPORT_TABLE(atad, 1, 3) +#define atad_IMPORTS_end END_IMPORT_TABLE + +#define I_ata_get_devinfo DECLARE_IMPORT(4, ata_get_devinfo) +#define I_ata_reset_devices DECLARE_IMPORT(5, ata_reset_devices) +#define I_ata_io_start DECLARE_IMPORT(6, ata_io_start) +#define I_ata_io_finish DECLARE_IMPORT(7, ata_io_finish) +#define I_ata_get_error DECLARE_IMPORT(8, ata_get_error) +#define I_ata_device_dma_transfer I_ata_device_sector_io // Backward-compatibility +#define I_ata_device_sector_io DECLARE_IMPORT(9, ata_device_sector_io) +#define I_ata_device_sce_sec_set_password DECLARE_IMPORT(10, ata_device_sce_sec_set_password) +#define I_ata_device_sce_sec_unlock DECLARE_IMPORT(11, ata_device_sce_sec_unlock) +#define I_ata_device_sce_sec_erase DECLARE_IMPORT(12, ata_device_sce_sec_erase) +#define I_ata_device_idle DECLARE_IMPORT(13, ata_device_idle) +#define I_ata_device_sce_identify_drive DECLARE_IMPORT(14, ata_device_sce_identify_drive) +#define I_ata_device_smart_get_status DECLARE_IMPORT(15, ata_device_smart_get_status) +#define I_ata_device_smart_save_attr DECLARE_IMPORT(16, ata_device_smart_save_attr) +#define I_ata_device_flush_cache DECLARE_IMPORT(17, ata_device_flush_cache) +#define I_ata_device_idle_immediate DECLARE_IMPORT(18, ata_device_idle_immediate) + +#endif /* __ATAD_H__ */ diff --git a/sps2_basement/hardware/dev9/atad/src/exports.tab b/sps2_basement/hardware/dev9/atad/src/exports.tab new file mode 100644 index 0000000..c205b59 --- /dev/null +++ b/sps2_basement/hardware/dev9/atad/src/exports.tab @@ -0,0 +1,26 @@ +/* We conform to the 1.3 version of atad.irx exports. */ + +DECLARE_EXPORT_TABLE(atad, 1, 3) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_exit) + DECLARE_EXPORT(_retonly) + + DECLARE_EXPORT(ata_get_devinfo) +/*05*/ DECLARE_EXPORT(ata_reset_devices) + DECLARE_EXPORT(ata_io_start) + DECLARE_EXPORT(ata_io_finish) + DECLARE_EXPORT(ata_get_error) + DECLARE_EXPORT(ata_device_sector_io) +/*10*/ DECLARE_EXPORT(ata_device_sce_sec_set_password) + DECLARE_EXPORT(ata_device_sce_sec_unlock) + DECLARE_EXPORT(ata_device_sce_sec_erase) + DECLARE_EXPORT(ata_device_idle) + DECLARE_EXPORT(ata_device_sce_identify_drive) +/*15*/ DECLARE_EXPORT(ata_device_smart_get_status) + DECLARE_EXPORT(ata_device_smart_save_attr) + DECLARE_EXPORT(ata_device_flush_cache) + DECLARE_EXPORT(ata_device_idle_immediate) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/dev9/atad/src/imports.lst b/sps2_basement/hardware/dev9/atad/src/imports.lst new file mode 100644 index 0000000..beb7b34 --- /dev/null +++ b/sps2_basement/hardware/dev9/atad/src/imports.lst @@ -0,0 +1,37 @@ +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +I_SetAlarm +I_CancelAlarm +I_USec2SysClock +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_iSetEventFlag +I_ClearEventFlag +I_WaitEventFlag +thevent_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memcpy +I_memset +sysclib_IMPORTS_end + +dev9_IMPORTS_start +I_dev9RegisterIntrCb +I_dev9DmaTransfer +I_dev9IntrEnable +I_dev9IntrDisable +I_dev9LEDCtl +I_dev9RegisterShutdownCb +I_dev9RegisterPreDmaCb +I_dev9RegisterPostDmaCb +dev9_IMPORTS_end diff --git a/sps2_basement/hardware/dev9/atad/src/irx_imports.h b/sps2_basement/hardware/dev9/atad/src/irx_imports.h new file mode 100644 index 0000000..c468b8f --- /dev/null +++ b/sps2_basement/hardware/dev9/atad/src/irx_imports.h @@ -0,0 +1,26 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dev9/atad/src/ps2atad.c b/sps2_basement/hardware/dev9/atad/src/ps2atad.c new file mode 100644 index 0000000..4f27503 --- /dev/null +++ b/sps2_basement/hardware/dev9/atad/src/ps2atad.c @@ -0,0 +1,1241 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * ATA device driver. + * This module provides the low-level ATA support for hard disk drives, based on ATAD v2.7. + * It is 100% compatible with its proprietary counterpart called atad.irx. + * + * This module also include support for 48-bit feature set (done by Clement). + * To avoid causing an "emergency park" for some HDDs, shutdown callback 15 of dev9 + * is used for issuing the STANDBY IMMEDIATE command prior to DEV9 getting shut down. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define MODNAME "atad" +// TODO: last sdk 3.1.0 has ATAD module version 2.9 with significant changes. +// Check what was changed, and maybe port changes. +// CRC32: C2337807 +IRX_ID(MODNAME, 2, 7); + +#define M_PRINTF(format, args...) \ + printf(MODNAME ": " format, ##args) + +#define BANNER "ATA device driver %s - Copyright (c) 2003 Marcus R. Brown\n" +#define VERSION "v1.2" + +#define ATA_XFER_MODE_PIO 0x08 +#ifdef ATA_MWDMA_MODES +#define ATA_XFER_MODE_MDMA 0x20 +#endif +#define ATA_XFER_MODE_UDMA 0x40 + +#define ATA_EV_TIMEOUT 1 +#define ATA_EV_COMPLETE 2 + +static int ata_devinfo_init = 0; +static int ata_evflg = -1; + +// Workarounds +static u8 ata_dvrp_workaround = 0; //Please read the comments in _start(). +#ifdef ATA_GAMESTAR_WORKAROUND +static u8 ata_gamestar_workaround = 0; +#endif + +/* Local device info kept for drives 0 and 1. */ +static ata_devinfo_t atad_devinfo[2]; + +/* Data returned from DEVICE IDENTIFY is kept here. Also, this is used by the + security commands to set and unlock the password. */ +static u16 ata_param[256]; + +/* ATA command info. */ +typedef struct _ata_cmd_info +{ + u8 command; + u8 type; +} ata_cmd_info_t; + +static const ata_cmd_info_t ata_cmd_table[] = { + {ATA_C_NOP, 1}, + {ATA_C_CFA_REQUEST_EXTENDED_ERROR_CODE, 1}, + {ATA_C_DEVICE_RESET, 5}, + {ATA_C_READ_SECTOR, 2}, + {ATA_C_READ_SECTOR_EXT, 0x82}, + {ATA_C_READ_DMA_EXT, 0x84}, + {ATA_C_READ_NATIVE_MAX_ADDRESS_EXT, 0x81}, + {ATA_C_READ_MULTIPLE_EXT, 0x82}, + {ATA_C_WRITE_SECTOR, 3}, + {ATA_C_WRITE_LONG, 8}, + {ATA_C_WRITE_SECTOR_EXT, 0x83}, + {ATA_C_WRITE_DMA_EXT, 0x84}, + {ATA_C_SET_MAX_ADDRESS_EXT, 0x81}, + {ATA_C_CFA_WRITE_SECTORS_WITHOUT_ERASE, 3}, + {ATA_C_WRITE_MULTIPLE_EXT, 0x83}, + {ATA_C_READ_VERIFY_SECTOR, 1}, + {ATA_C_READ_VERIFY_SECTOR_EXT, 0x81}, + {ATA_C_SEEK, 1}, + {ATA_C_CFA_TRANSLATE_SECTOR, 2}, + {ATA_C_SCE_SECURITY_CONTROL, 7}, + {ATA_C_EXECUTE_DEVICE_DIAGNOSTIC, 6}, + {ATA_C_INITIALIZE_DEVICE_PARAMETERS, 1}, + {ATA_C_DOWNLOAD_MICROCODE, 3}, + {ATA_C_IDENTIFY_PACKET_DEVICE, 2}, + {ATA_C_SMART, 7}, + {ATA_C_CFA_ERASE_SECTORS, 1}, + {ATA_C_READ_MULTIPLE, 2}, + {ATA_C_WRITE_MULTIPLE, 3}, + {ATA_C_SET_MULTIPLE_MODE, 1}, + {ATA_C_READ_DMA, 4}, + {ATA_C_WRITE_DMA, 4}, + {ATA_C_CFA_WRITE_MULTIPLE_WITHOUT_ERASE, 3}, + {ATA_C_GET_MEDIA_STATUS, 1}, + {ATA_C_MEDIA_LOCK, 1}, + {ATA_C_MEDIA_UNLOCK, 1}, + {ATA_C_STANDBY_IMMEDIATE, 1}, + {ATA_C_IDLE_IMMEDIATE, 1}, + {ATA_C_STANDBY, 1}, + {ATA_C_IDLE, 1}, + {ATA_C_READ_BUFFER, 2}, + {ATA_C_CHECK_POWER_MODE, 1}, + {ATA_C_SLEEP, 1}, + {ATA_C_FLUSH_CACHE, 1}, + {ATA_C_WRITE_BUFFER, 3}, + {ATA_C_FLUSH_CACHE_EXT, 1}, + {ATA_C_IDENTIFY_DEVICE, 2}, + {ATA_C_MEDIA_EJECT, 1}, + {ATA_C_SET_FEATURES, 1}, + {ATA_C_SECURITY_SET_PASSWORD, 3}, + {ATA_C_SECURITY_UNLOCK, 3}, + {ATA_C_SECURITY_ERASE_PREPARE, 1}, + {ATA_C_SECURITY_ERASE_UNIT, 3}, + {ATA_C_SECURITY_FREEZE_LOCK, 1}, + {ATA_C_SECURITY_DISABLE_PASSWORD, 3}, + {ATA_C_READ_NATIVE_MAX_ADDRESS, 1}, + {ATA_C_SET_MAX_ADDRESS, 1}}; +#define ATA_CMD_TABLE_SIZE (sizeof ata_cmd_table / sizeof(ata_cmd_info_t)) + +static const ata_cmd_info_t sec_ctrl_cmd_table[] = { + {ATA_SCE_IDENTIFY_DRIVE, 2}, + {ATA_SCE_SECURITY_ERASE_PREPARE, 1}, + {ATA_SCE_SECURITY_ERASE_UNIT, 1}, + {ATA_SCE_SECURITY_FREEZE_LOCK, 1}, + {ATA_SCE_SECURITY_SET_PASSWORD, 3}, + {ATA_SCE_SECURITY_UNLOCK, 3}, + {ATA_SCE_SECURITY_WRITE_ID, 3}, + {ATA_SCE_SECURITY_READ_ID, 2}}; +#define SEC_CTRL_CMD_TABLE_SIZE (sizeof sec_ctrl_cmd_table / sizeof(ata_cmd_info_t)) + +static const ata_cmd_info_t smart_cmd_table[] = { + {ATA_S_SMART_READ_DATA, 2}, + {ATA_S_SMART_ENABLE_DISABLE_AUTOSAVE, 1}, + {ATA_S_SMART_SAVE_ATTRIBUTE_VALUES, 1}, + {ATA_S_SMART_EXECUTE_OFF_LINE, 1}, + {ATA_S_SMART_READ_LOG, 2}, + {ATA_S_SMART_WRITE_LOG, 3}, + {ATA_S_SMART_ENABLE_OPERATIONS, 1}, + {ATA_S_SMART_DISABLE_OPERATIONS, 1}, + {ATA_S_SMART_RETURN_STATUS, 1}}; +#define SMART_CMD_TABLE_SIZE (sizeof smart_cmd_table / sizeof(ata_cmd_info_t)) + +/* This is the state info tracked between ata_io_start() and ata_io_finish(). */ +typedef struct _ata_cmd_state +{ + s32 type; /* The ata_cmd_info_t type field. */ + union + { + void *buf; + u8 *buf8; + u16 *buf16; + }; + u32 blkcount; /* The number of 512-byte blocks (sectors) to transfer. */ + s32 dir; /* DMA direction: 0 - to RAM, 1 - from RAM. */ +} ata_cmd_state_t; + +static ata_cmd_state_t atad_cmd_state; + +static int ata_intr_cb(int flag); +static unsigned int ata_alarm_cb(void *unused); + +static void ata_set_dir(int dir); + +static void ata_pio_mode(int mode); +#ifdef ATA_MWDMA_MODES +static void ata_multiword_dma_mode(int mode); +#endif +static void ata_ultra_dma_mode(int mode); +static void ata_shutdown_cb(void); + +extern struct irx_export_table _exp_atad; + +//In v1.04, DMA was enabled in ata_set_dir() instead. +static void ata_pre_dma_cb(int bcr, int dir) +{ + USE_SPD_REGS; + + SPD_REG16(SPD_R_XFR_CTRL) |= 0x80; +} + +static void ata_post_dma_cb(int bcr, int dir) +{ + USE_SPD_REGS; + + SPD_REG16(SPD_R_XFR_CTRL) &= ~0x80; +} + +static int ata_create_event_flag(void) +{ + iop_event_t event; + + event.attr = EA_SINGLE; //In v1.04, EA_MULTI was specified. + event.bits = 0; + return CreateEventFlag(&event); +} + +int _start(int argc, char *argv[]) +{ + USE_SPD_REGS; + int res = 1; + + printf(BANNER, VERSION); + + if (!(SPD_REG16(SPD_R_REV_3) & SPD_CAPS_ATA) || !(SPD_REG16(SPD_R_REV_8) & 0x02)) { + M_PRINTF("HDD is not connected, exiting.\n"); + goto out; + } + + /* The PSX (Not the PlayStation or PSOne, but a PS2 with a DVR unit) has got an extra processor (Fujitsu MB91302A, aka the "DVRP") that seems to be emulating the console's PS2 ATA interface. + The stock disks of all PSX units are definitely 48-bit LBA compliant because of their capacities, but the DVRP's emulation seems to have a design problem: + 1. It indicates that 48-bit LBA is supported. + 2. The 48-bit LBA capacity fields show the true capacity of the disk. + 3. Accesses to beyond the 28-bit LBA capacity (Which is 40.000GB by default) will result in I/O errors. + 4. (For some PSX units like the DESR-7500): Double-writes to the ATA registers seem to cause the ATA interface to stall. + + The problem is obviously in the DVRP's firmware, but we currently have no way to fix these bugs because the DVRP is even more heavily secured that the IOP. + In the eyes of Sony, there isn't a problem because none of their retail PlayStation 2 software ever supported 48-bit LBA. + + The workaround here is to return the 28-bit LBA as the total size and only use 48-bit LBA commands when required. */ + ata_dvrp_workaround = (SPD_REG16(SPD_R_REV_3) & SPD_CAPS_DVR) ? 1 : 0; + +#ifdef ATA_GAMESTAR_WORKAROUND + /* Some compatible adaptors may malfunction if transfers are not done according to the old ps2atad design. + Official adaptors appear to have a 0x0001 set for this register, but not compatibles. + While official I/O to this register are 8-bit, some compatibles have a 0x01 for the lower 8-bits, + but the upper 8-bits contain some random value. Hence perform a 16-bit read instead. */ + if (SPD_REG16(0x20) != 1) { + ata_gamestar_workaround = 1; + M_PRINTF("Compatible adaptor detected.\n"); + } else { + ata_gamestar_workaround = 0; + } +#endif + + if ((ata_evflg = ata_create_event_flag()) < 0) { + M_PRINTF("Couldn't create event flag, exiting.\n"); + res = 1; + goto out; + } + + /* In v1.04, PIO mode 0 was set here. In late versions, it is set in ata_init_devices(). */ + dev9RegisterIntrCb(1, &ata_intr_cb); + dev9RegisterIntrCb(0, &ata_intr_cb); +#ifdef ATA_GAMESTAR_WORKAROUND + if (!ata_gamestar_workaround) { +#endif + dev9RegisterPreDmaCb(0, &ata_pre_dma_cb); + dev9RegisterPostDmaCb(0, &ata_post_dma_cb); +#ifdef ATA_GAMESTAR_WORKAROUND + } +#endif + /* Register this at the last position, as it should be the last thing done before shutdown. */ + dev9RegisterShutdownCb(15, &ata_shutdown_cb); + + if ((res = RegisterLibraryEntries(&_exp_atad)) != 0) { + M_PRINTF("Library is already registered, exiting.\n"); + goto out; + } + + res = 0; + M_PRINTF("Driver loaded.\n"); +out: + return res; +} + +int _exit(void) { return 0; } + +static int ata_intr_cb(int flag) +{ + if (flag == 1) { /* New card, invalidate device info. */ + memset(atad_devinfo, 0, sizeof atad_devinfo); + } else { + dev9IntrDisable(SPD_INTR_ATA); + iSetEventFlag(ata_evflg, ATA_EV_COMPLETE); + } + + return 1; +} + +static unsigned int ata_alarm_cb(void *unused) +{ + iSetEventFlag(ata_evflg, ATA_EV_TIMEOUT); + return 0; +} + +/* Export 8 */ +int ata_get_error(void) +{ + USE_ATA_REGS; + return ata_hwport->r_error & 0xff; +} + +#define ATA_WAIT_BUSY 0x80 +#define ATA_WAIT_BUSBUSY 0x88 + +#define ata_wait_busy() gen_ata_wait_busy(ATA_WAIT_BUSY) +#define ata_wait_bus_busy() gen_ata_wait_busy(ATA_WAIT_BUSBUSY) + +/* 0x80 for busy, 0x88 for bus busy. + In the original ATAD, the busy and bus-busy functions were separate, but similar. */ +static int gen_ata_wait_busy(int bits) +{ + USE_ATA_REGS; + int i, didx, delay; + + for (i = 0; i < 80; i++) { + if (!(ata_hwport->r_control & bits)) + return 0; + + didx = i / 10; + switch (didx) { + case 0: + continue; + case 1: + delay = 100; + break; + case 2: + delay = 1000; + break; + case 3: + delay = 10000; + break; + case 4: + delay = 100000; + break; + default: + delay = 1000000; + } + + DelayThread(delay); + } + + M_PRINTF("Timeout while waiting on busy (0x%02x).\n", bits); + return ATA_RES_ERR_TIMEOUT; +} + +static int ata_device_select(int device) +{ + USE_ATA_REGS; + int res; + + if ((res = ata_wait_bus_busy()) < 0) + return res; + + /* If the device was already selected, nothing to do. */ + if (((ata_hwport->r_select >> 4) & 1) == device) + return 0; + + /* Select the device. */ + ata_hwport->r_select = (device & 1) << 4; + res = ata_hwport->r_control; + res = ata_hwport->r_control; //Only done once in v1.04. + + return ata_wait_bus_busy(); +} + +/* Export 6 */ +/* + 28-bit LBA: + sector (7:0) -> LBA (7:0) + lcyl (7:0) -> LBA (15:8) + hcyl (7:0) -> LBA (23:16) + device (3:0) -> LBA (27:24) + + 48-bit LBA just involves writing the upper 24 bits in the format above into each respective register on the first write pass, before writing the lower 24 bits in the 2nd write pass. The LBA bits within the device field are not used in either write pass. +*/ +int ata_io_start(void *buf, u32 blkcount, u16 feature, u16 nsector, u16 sector, u16 lcyl, u16 hcyl, u16 select, u16 command) +{ + USE_ATA_REGS; + iop_sys_clock_t cmd_timeout; + const ata_cmd_info_t *cmd_table; + int i, res, type, cmd_table_size; + int using_timeout, device = (select >> 4) & 1; + u8 searchcmd; + + ClearEventFlag(ata_evflg, 0); + + if (!atad_devinfo[device].exists) + return ATA_RES_ERR_NODEV; + + if ((res = ata_device_select(device)) != 0) + return res; + + /* For the SCE and SMART commands, we need to search on the subcommand + specified in the feature register. */ + if (command == ATA_C_SCE_SECURITY_CONTROL) { + cmd_table = sec_ctrl_cmd_table; + cmd_table_size = SEC_CTRL_CMD_TABLE_SIZE; + searchcmd = (u8)feature; + } else if (command == ATA_C_SMART) { + cmd_table = smart_cmd_table; + cmd_table_size = SMART_CMD_TABLE_SIZE; + searchcmd = (u8)feature; + } else { + cmd_table = ata_cmd_table; + cmd_table_size = ATA_CMD_TABLE_SIZE; + searchcmd = (u8)command; + } + + type = 0; + for (i = 0; i < cmd_table_size; i++) { + if (searchcmd == cmd_table[i].command) { + type = cmd_table[i].type; + break; + } + } + + if (!(atad_cmd_state.type = type & 0x7F)) // Non-SONY: ignore the 48-bit LBA flag. + return ATA_RES_ERR_CMD; + + atad_cmd_state.buf = buf; + atad_cmd_state.blkcount = blkcount; + + /* Check that the device is ready if this the appropiate command. */ + if (!(ata_hwport->r_control & 0x40)) { + switch (command) { + case ATA_C_DEVICE_RESET: + case ATA_C_EXECUTE_DEVICE_DIAGNOSTIC: + case ATA_C_INITIALIZE_DEVICE_PARAMETERS: + case ATA_C_PACKET: + case ATA_C_IDENTIFY_PACKET_DEVICE: + break; + default: + M_PRINTF("Error: Device %d is not ready.\n", device); + return ATA_RES_ERR_NOTREADY; + } + } + + /* Does this command need a timeout? */ + using_timeout = 0; + switch (type & 0x7F) { // Non-SONY: ignore the 48-bit LBA flag. + case 1: + case 6: + using_timeout = 1; + break; + case 4: + atad_cmd_state.dir = (command != ATA_C_READ_DMA && command != ATA_C_READ_DMA_EXT); + using_timeout = 1; + break; + } + + if (using_timeout) { + cmd_timeout.lo = 0x41eb0000; + cmd_timeout.hi = 0; + + /* SECURITY ERASE UNIT needs a bit more time. */ + if (command == ATA_C_SCE_SECURITY_CONTROL && feature == ATA_SCE_SECURITY_ERASE_UNIT) + USec2SysClock(180000000, &cmd_timeout); + + if ((res = SetAlarm(&cmd_timeout, &ata_alarm_cb, NULL)) < 0) + return res; + } + + /* Enable the command completion interrupt. */ + if ((type & 0x7F) == 1) + dev9IntrEnable(SPD_INTR_ATA0); + + /* Finally! We send off the ATA command with arguments. */ + ata_hwport->r_control = (using_timeout == 0) << 1; + + if (type & 0x80) { //For the sake of achieving improved performance, write the registers twice only if required! This is also required for compatibility with the buggy firmware of certain PSX units. + /* 48-bit LBA requires writing to the address registers twice, + 24 bits of the LBA address is written each time. + Writing to registers twice does not affect 28-bit LBA since + only the latest data stored in address registers is used. */ + ata_hwport->r_feature = (feature >> 8) & 0xff; + ata_hwport->r_nsector = (nsector >> 8) & 0xff; + ata_hwport->r_sector = (sector >> 8) & 0xff; + ata_hwport->r_lcyl = (lcyl >> 8) & 0xff; + ata_hwport->r_hcyl = (hcyl >> 8) & 0xff; + } + + ata_hwport->r_feature = feature & 0xff; + ata_hwport->r_nsector = nsector & 0xff; + ata_hwport->r_sector = sector & 0xff; + ata_hwport->r_lcyl = lcyl & 0xff; + ata_hwport->r_hcyl = hcyl & 0xff; + ata_hwport->r_select = (select | ATA_SEL_LBA) & 0xff; // In v1.04, LBA was enabled in the ata_device_sector_io function. + ata_hwport->r_command = command & 0xff; + + /* Turn on the LED. */ + dev9LEDCtl(1); + + return 0; +} + +/* Do a PIO transfer, to or from the device. */ +static int ata_pio_transfer(ata_cmd_state_t *cmd_state) +{ + USE_ATA_REGS; + u8 *buf8; + u16 *buf16; + int i, type; + u16 status = ata_hwport->r_status & 0xff; + + if (status & ATA_STAT_ERR) { + M_PRINTF("Error: PIO cmd error: status 0x%02x, error 0x%02x.\n", status, ata_get_error()); + return ATA_RES_ERR_IO; + } + + /* DRQ must be set (data request). */ + if (!(status & ATA_STAT_DRQ)) + return ATA_RES_ERR_NODATA; + + type = cmd_state->type; + + if (type == 3 || type == 8) { + /* PIO data out */ + buf16 = cmd_state->buf16; + for (i = 0; i < 256; i++) { + ata_hwport->r_data = *buf16; + cmd_state->buf16 = ++buf16; + } + if (cmd_state->type == 8) { + buf8 = cmd_state->buf8; + for (i = 0; i < 4; i++) { + ata_hwport->r_data = *buf8; + cmd_state->buf8 = ++buf8; + } + } + } else if (type == 2) { + /* PIO data in */ + buf16 = cmd_state->buf16; + for (i = 0; i < 256; i++) { + *buf16 = ata_hwport->r_data; + cmd_state->buf16 = ++buf16; + } + } + + return 0; +} + +/* Complete a DMA transfer, to or from the device. */ +static int ata_dma_complete(void *buf, u32 blkcount, int dir) +{ + USE_ATA_REGS; + USE_SPD_REGS; + u32 bits, count, nbytes; + int i, res; + u16 dma_stat; + + while (blkcount) { + for (i = 0; i < 20; i++) + if ((dma_stat = SPD_REG16(0x38) & 0x1f)) + goto next_transfer; + + if (dma_stat) + goto next_transfer; + + dev9IntrEnable(SPD_INTR_ATA); + /* Wait for the previous transfer to complete or a timeout. */ + WaitEventFlag(ata_evflg, ATA_EV_TIMEOUT | ATA_EV_COMPLETE, WEF_CLEAR | WEF_OR, &bits); + + if (bits & ATA_EV_TIMEOUT) { /* Timeout. */ + M_PRINTF("Error: DMA timeout.\n"); + return ATA_RES_ERR_TIMEOUT; + } + /* No DMA completion bit? Spurious interrupt. */ + if (!(SPD_REG16(SPD_R_INTR_STAT) & 0x02)) { + if (ata_hwport->r_control & 0x01) { + M_PRINTF("Error: Command error while doing DMA.\n"); + M_PRINTF("Error: Command error status 0x%02x, error 0x%02x.\n", ata_hwport->r_status, ata_get_error()); + /* In v1.04, there was no check for ICRC. */ + return ((ata_get_error() & ATA_ERR_ICRC) ? ATA_RES_ERR_ICRC : ATA_RES_ERR_IO); + } else { + M_PRINTF("Warning: Got command interrupt, but not an error.\n"); + continue; + } + } + + dma_stat = SPD_REG16(0x38) & 0x1f; + + next_transfer: + count = (blkcount < dma_stat) ? blkcount : dma_stat; + nbytes = count * 512; + if ((res = dev9DmaTransfer(0, buf, (nbytes << 9) | 32, dir)) < 0) + return res; + + buf = (void *)((u8 *)buf + nbytes); + blkcount -= count; + } + + return 0; +} + +/* Export 7 */ +int ata_io_finish(void) +{ + USE_SPD_REGS; + USE_ATA_REGS; + ata_cmd_state_t *cmd_state = &atad_cmd_state; + u32 bits; + int i, res = 0, type = cmd_state->type; + u16 stat; + + if (type == 1 || type == 6) { /* Non-data commands. */ + WaitEventFlag(ata_evflg, ATA_EV_TIMEOUT | ATA_EV_COMPLETE, WEF_CLEAR | WEF_OR, &bits); + if (bits & ATA_EV_TIMEOUT) { /* Timeout. */ + M_PRINTF("Error: ATA timeout on a non-data command.\n"); + return ATA_RES_ERR_TIMEOUT; + } + } else if (type == 4) { /* DMA. */ + if ((res = ata_dma_complete(cmd_state->buf, cmd_state->blkcount, + cmd_state->dir)) < 0) + goto finish; + + for (i = 0; i < 100; i++) + if ((stat = SPD_REG16(SPD_R_INTR_STAT) & 0x01)) + break; + if (!stat) { + dev9IntrEnable(SPD_INTR_ATA0); + WaitEventFlag(ata_evflg, ATA_EV_TIMEOUT | ATA_EV_COMPLETE, WEF_CLEAR | WEF_OR, &bits); + if (bits & ATA_EV_TIMEOUT) { + M_PRINTF("Error: ATA timeout on DMA completion, buffer stat %04x\n", SPD_REG16(0x38)); + M_PRINTF("Error: istat %x, ienable %x\n", SPD_REG16(SPD_R_INTR_STAT), SPD_REG16(SPD_R_INTR_MASK)); + res = ATA_RES_ERR_TIMEOUT; + } + } + } else { /* PIO transfers. */ + stat = ata_hwport->r_control; + if ((res = ata_wait_busy()) < 0) + goto finish; + + /* Transfer each PIO data block. */ + while (--cmd_state->blkcount != -1) { + if ((res = ata_pio_transfer(cmd_state)) < 0) + goto finish; + if ((res = ata_wait_busy()) < 0) + goto finish; + } + } + + if (res) + goto finish; + + /* Wait until the device isn't busy. */ + if (ata_hwport->r_status & ATA_STAT_BUSY) + res = ata_wait_busy(); + if ((stat = ata_hwport->r_status) & ATA_STAT_ERR) { + M_PRINTF("Error: Command error: status 0x%02x, error 0x%02x.\n", stat, ata_get_error()); + /* In v1.04, there was no check for ICRC. */ + res = (ata_get_error() & ATA_ERR_ICRC) ? ATA_RES_ERR_ICRC : ATA_RES_ERR_IO; + } + +finish: + /* The command has completed (with an error or not), so clean things up. */ + CancelAlarm(&ata_alarm_cb, NULL); + /* Turn off the LED. */ + dev9LEDCtl(0); + + if (res) + M_PRINTF("error: ATA failed, %d\n", res); + + return res; +} + +/* Reset the ATA controller/bus. */ +static int ata_bus_reset(void) +{ + USE_SPD_REGS; + SPD_REG16(SPD_R_IF_CTRL) = SPD_IF_ATA_RESET; + DelayThread(100); + SPD_REG16(SPD_R_IF_CTRL) = 0; //Not present in v1.04. + SPD_REG16(SPD_R_IF_CTRL) = 0x48; + DelayThread(3000); + return ata_wait_busy(); +} + +/* Export 5 */ +int ata_reset_devices(void) +{ + USE_ATA_REGS; + + if (ata_hwport->r_control & 0x80) + return ATA_RES_ERR_NOTREADY; + + /* Disables device interrupt assertion and asserts SRST. */ + ata_hwport->r_control = 6; + DelayThread(100); + + /* Disable ATA interrupts. */ + ata_hwport->r_control = 2; + DelayThread(3000); + + return ata_wait_busy(); +} + +/* Export 17 */ +int ata_device_flush_cache(int device) +{ + int res; + + if (!(res = ata_io_start(NULL, 1, 0, 0, 0, 0, 0, (device << 4) & 0xffff, (atad_devinfo[device].lba48 && !ata_dvrp_workaround) ? ATA_C_FLUSH_CACHE_EXT : ATA_C_FLUSH_CACHE))) + res = ata_io_finish(); + + return res; +} + +/* Export 13 */ +int ata_device_idle(int device, int period) +{ + int res; + + if (!(res = ata_io_start(NULL, 1, 0, period & 0xff, 0, 0, 0, (device << 4) & 0xffff, ATA_C_IDLE))) + res = ata_io_finish(); + + return res; +} + +static int ata_device_identify(int device, void *info) +{ + int res; + + if (!(res = ata_io_start(info, 1, 0, 0, 0, 0, 0, (device << 4) & 0xffff, ATA_C_IDENTIFY_DEVICE))) + res = ata_io_finish(); + + return res; +} + +static int ata_device_pkt_identify(int device, void *info) +{ + int res; + + res = ata_io_start(info, 1, 0, 0, 0, 0, 0, (device << 4) & 0xffff, ATA_C_IDENTIFY_PACKET_DEVICE); + if (!res) + return ata_io_finish(); + return res; +} + +/* Export 14 */ +int ata_device_sce_identify_drive(int device, void *data) +{ + int res; + + if (!(res = ata_io_start(data, 1, ATA_SCE_IDENTIFY_DRIVE, 0, 0, 0, 0, (device << 4) & 0xffff, ATA_C_SCE_SECURITY_CONTROL))) + res = ata_io_finish(); + + return res; +} + +static int ata_device_smart_enable(int device) +{ + int res; + + if (!(res = ata_io_start(NULL, 1, ATA_S_SMART_ENABLE_OPERATIONS, 0, 0, 0x4f, 0xc2, (device << 4) & 0xffff, ATA_C_SMART))) + res = ata_io_finish(); + + return res; +} + +/* Export 16 */ +int ata_device_smart_save_attr(int device) +{ + int res; + + if (!(res = ata_io_start(NULL, 1, ATA_S_SMART_SAVE_ATTRIBUTE_VALUES, 0, 0, 0x4f, 0xc2, (device << 4) & 0xffff, ATA_C_SMART))) + res = ata_io_finish(); + + return res; +} + +/* Export 15 */ +int ata_device_smart_get_status(int device) +{ + USE_ATA_REGS; + int res; + + res = ata_io_start(NULL, 1, ATA_S_SMART_RETURN_STATUS, 0, 0, 0x4f, 0xc2, (device << 4) & 0xffff, ATA_C_SMART); + if (res) + return res; + + res = ata_io_finish(); + if (res) + return res; + + /* Check to see if the report exceeded the threshold. */ + if (((ata_hwport->r_lcyl & 0xFF) != 0x4f) || ((ata_hwport->r_hcyl & 0xFF) != 0xc2)) { + M_PRINTF("Error: SMART report exceeded threshold.\n"); + return 1; + } + + return res; +} + +/* Set features - set transfer mode. */ +static int ata_device_set_transfer_mode(int device, int type, int mode) +{ + int res; + + res = ata_io_start(NULL, 1, 3, (type | mode) & 0xff, 0, 0, 0, (device << 4) & 0xffff, ATA_C_SET_FEATURES); + if (res) + return res; + + res = ata_io_finish(); + if (res) + return res; + + switch (type) { +#ifdef ATA_MWDMA_MODES + case ATA_XFER_MODE_MDMA: + ata_multiword_dma_mode(mode); + break; +#endif + case ATA_XFER_MODE_UDMA: + ata_ultra_dma_mode(mode); + break; + case ATA_XFER_MODE_PIO: + ata_pio_mode(mode); + break; + } + + return 0; +} + +/* Export 9 */ +/* Note: this can only support DMA modes, due to the commands issued. */ +int ata_device_sector_io(int device, void *buf, u32 lba, u32 nsectors, int dir) +{ + USE_SPD_REGS; + int res = 0, retries; + u16 sector, lcyl, hcyl, select, command, len; + + while (res == 0 && nsectors > 0) { + /* Variable lba is only 32 bits so no change for lcyl and hcyl. */ + lcyl = (lba >> 8) & 0xff; + hcyl = (lba >> 16) & 0xff; + + if (atad_devinfo[device].lba48 && (ata_dvrp_workaround ? (lba >= atad_devinfo[device].total_sectors) : 1)) { + /* Setup for 48-bit LBA. */ + len = (nsectors > 65536) ? 65536 : nsectors; + + /* Combine bits 24-31 and bits 0-7 of lba into sector. */ + sector = ((lba >> 16) & 0xff00) | (lba & 0xff); + /* In v1.04, LBA was enabled here. */ + select = (device << 4) & 0xffff; + command = (dir == 1) ? ATA_C_WRITE_DMA_EXT : ATA_C_READ_DMA_EXT; + } else { + /* Setup for 28-bit LBA. */ + len = (nsectors > 256) ? 256 : nsectors; + sector = lba & 0xff; + /* In v1.04, LBA was enabled here. */ + select = ((device << 4) | ((lba >> 24) & 0xf)) & 0xffff; + command = (dir == 1) ? ATA_C_WRITE_DMA : ATA_C_READ_DMA; + } + + for (retries = 3; retries > 0; retries--) { +#ifdef ATA_GAMESTAR_WORKAROUND + /* Due to the retry loop, put this call (for the GameStar workaround) here instead of the old location. */ + if (ata_gamestar_workaround) + ata_set_dir(dir); +#endif + + if ((res = ata_io_start(buf, len, 0, len, sector, lcyl, hcyl, select, command)) != 0) + break; + +#ifdef ATA_GAMESTAR_WORKAROUND + if (!ata_gamestar_workaround) + ata_set_dir(dir); +#else + /* Set up (part of) the transfer here. In v1.04, this was called at the top of the outer loop. */ + ata_set_dir(dir); +#endif + + res = ata_io_finish(); + + /* In v1.04, this was not done. Neither was there a mechanism to retry if a non-permanent error occurs. */ + SPD_REG16(SPD_R_IF_CTRL) &= ~SPD_IF_DMA_ENABLE; + + if (res != ATA_RES_ERR_ICRC) + break; + } + + buf = (void *)((u8 *)buf + len * 512); + lba += len; + nsectors -= len; + } + + return res; +} + +static void ata_get_security_status(int device, ata_devinfo_t *devinfo, u16 *param) +{ + if (ata_device_identify(device, param) == 0) + devinfo[device].security_status = param[ATA_ID_SECURITY_STATUS]; +} + +/* Export 10 */ +int ata_device_sce_sec_set_password(int device, void *password) +{ + ata_devinfo_t *devinfo = atad_devinfo; + u16 *param = ata_param; + int res; + + if (devinfo[device].security_status & ATA_F_SEC_ENABLED) + return 0; + + memset(param, 0, 512); + memcpy(param + 1, password, 32); + + res = ata_io_start(param, 1, ATA_SCE_SECURITY_SET_PASSWORD, 0, 0, 0, 0, (device << 4) & 0xffff, ATA_C_SCE_SECURITY_CONTROL); + if (res == 0) + res = ata_io_finish(); + + ata_get_security_status(device, devinfo, param); + return res; +} + +/* Export 11 */ +int ata_device_sce_sec_unlock(int device, void *password) +{ + ata_devinfo_t *devinfo = atad_devinfo; + u16 *param = ata_param; + int res; + + if (!(devinfo[device].security_status & ATA_F_SEC_LOCKED)) + return 0; + + memset(param, 0, 512); + memcpy(param + 1, password, 32); + + if ((res = ata_io_start(param, 1, ATA_SCE_SECURITY_UNLOCK, 0, 0, 0, 0, (device << 4) & 0xffff, ATA_C_SCE_SECURITY_CONTROL)) != 0) + return res; + if ((res = ata_io_finish()) != 0) + return res; + + /* Check to see if the drive was actually unlocked. */ + ata_get_security_status(device, devinfo, param); + if (devinfo[device].security_status & ATA_F_SEC_LOCKED) + return ATA_RES_ERR_LOCKED; + + return 0; +} + +/* Export 12 */ +int ata_device_sce_sec_erase(int device) +{ + ata_devinfo_t *devinfo = atad_devinfo; + int res; + + if (!(devinfo[device].security_status & ATA_F_SEC_ENABLED) || !(devinfo[device].security_status & ATA_F_SEC_LOCKED)) + return 0; + + /* First send the mandatory ERASE PREPARE command. */ + if ((res = ata_io_start(NULL, 1, ATA_SCE_SECURITY_ERASE_PREPARE, 0, 0, 0, 0, (device << 4) & 0xffff, ATA_C_SCE_SECURITY_CONTROL)) != 0) + goto finish; + if ((res = ata_io_finish()) != 0) + goto finish; + + if ((res = ata_io_start(NULL, 1, ATA_SCE_SECURITY_ERASE_UNIT, 0, 0, 0, 0, (device << 4) & 0xffff, ATA_C_SCE_SECURITY_CONTROL)) == 0) + res = ata_io_finish(); + +finish: + ata_get_security_status(device, devinfo, NULL); + return res; +} + +static void ata_device_probe(ata_devinfo_t *devinfo) +{ + USE_ATA_REGS; + u16 nsector, sector, lcyl, hcyl; + + devinfo->exists = 0; + devinfo->has_packet = 2; + + if (ata_hwport->r_control & 0x88) + return; + + nsector = ata_hwport->r_nsector & 0xff; + sector = ata_hwport->r_sector & 0xff; + lcyl = ata_hwport->r_lcyl & 0xff; + hcyl = ata_hwport->r_hcyl & 0xff; + (void)ata_hwport->r_select; + + if ((nsector != 1) || (sector != 1)) + return; + devinfo->exists = 1; + + if ((lcyl == 0x00) && (hcyl == 0x00)) + devinfo->has_packet = 0; + else if ((lcyl == 0x14) && (hcyl == 0xeb)) + devinfo->has_packet = 1; + + /* Seems to be for ensuring that there is a device connected. + Not sure why this has to be done, but is present in v2.4. */ + ata_hwport->r_lcyl = 0x55; + ata_hwport->r_hcyl = 0xaa; + lcyl = ata_hwport->r_lcyl & 0xff; + hcyl = ata_hwport->r_hcyl & 0xff; + + if ((lcyl != 0x55) || (hcyl != 0xaa)) + devinfo->exists = 0; +} + +static int ata_init_devices(ata_devinfo_t *devinfo) +{ + USE_ATA_REGS; + int i, res; + u32 total_sectors_nonlba48, total_sectors_lba48; + + if ((res = ata_reset_devices()) != 0) + return res; + + ata_device_probe(&devinfo[0]); + if (!devinfo[0].exists) { + M_PRINTF("Error: Unable to detect HDD 0.\n"); + devinfo[1].exists = 0; + return ATA_RES_ERR_NODEV; //Returns 0 in v1.04. + } + + /* If there is a device 1, grab it's info too. */ + if ((res = ata_device_select(1)) != 0) + return res; + if (ata_hwport->r_control & 0xff) + ata_device_probe(&devinfo[1]); + else + devinfo[1].exists = 0; + + ata_pio_mode(0); //PIO mode is set here, in late ATAD versions. + + for (i = 0; i < 2; i++) { + if (!devinfo[i].exists) + continue; + + /* Send the IDENTIFY DEVICE command. if it doesn't succeed + devinfo is disabled. */ + if (!devinfo[i].has_packet) { + res = ata_device_identify(i, ata_param); + devinfo[i].exists = (res == 0); + } else if (devinfo[i].has_packet == 1) { + /* If it's a packet device, send the IDENTIFY PACKET + DEVICE command. */ + res = ata_device_pkt_identify(i, ata_param); + devinfo[i].exists = (res == 0); + } + /* Otherwise, do nothing if has_packet = 2. */ + + /* This next section is HDD-specific: if no device or it's a + packet (ATAPI) device, we're done. */ + if (!devinfo[i].exists || devinfo[i].has_packet) + continue; + + /* This section is to detect whether the HDD supports 48-bit LBA + (IDENITFY DEVICE bit 10 word 83) and get the total sectors from + either words(61:60) for 28-bit or words(103:100) for 48-bit. */ + devinfo[i].lba48 = (ata_param[ATA_ID_COMMAND_SETS_SUPPORTED] & 0x0400) != 0; + + /* Save the total sector counts before we overwrite ata_param with the value of Sony identify drive command. */ + total_sectors_nonlba48 = (ata_param[ATA_ID_SECTOTAL_HI] << 16) | ata_param[ATA_ID_SECTOTAL_LO]; + if (ata_param[ATA_ID_48BIT_SECTOTAL_HI]) { + total_sectors_lba48 = 0xffffffff; + } else { + total_sectors_lba48 = (ata_param[ATA_ID_48BIT_SECTOTAL_MI] << 16) | ata_param[ATA_ID_48BIT_SECTOTAL_LO]; + } + + devinfo[i].security_status = ata_param[ATA_ID_SECURITY_STATUS]; + + /* Ultra DMA mode 4. */ + ata_device_set_transfer_mode(i, ATA_XFER_MODE_UDMA, 4); + ata_device_smart_enable(i); + /* Set standby timer to 21min 15s. */ + ata_device_idle(i, 0xff); + + if (devinfo[i].lba48 != 0) { + /* If this device has the Sony firmware or is emulated through the DVRP, use the non-48-bit LBA size. */ + if (ata_device_sce_identify_drive(i, ata_param) == 0) { + devinfo[i].total_sectors = total_sectors_nonlba48; + } else { + devinfo[i].total_sectors = total_sectors_lba48; + } + devinfo[i].total_sectors_lba48 = total_sectors_lba48; + } else { + devinfo[i].total_sectors = total_sectors_nonlba48; + devinfo[i].total_sectors_lba48 = total_sectors_nonlba48; + } + + /* Call the proprietary identify command. */ +#ifdef ATA_SCE_AUTH_HDD + if (ata_device_sce_identify_drive(i, ata_param) != 0) { + M_PRINTF("error: This is not SCE genuine HDD.\n"); + memset(&devinfo[i], 0, sizeof(devinfo[i])); + } +#endif + } + return 0; +} + +/* Export 4 */ +ata_devinfo_t *ata_get_devinfo(int device) +{ + if (!ata_devinfo_init) { + ata_devinfo_init = 1; + if (ata_bus_reset() || ata_init_devices(atad_devinfo)) + return NULL; + } + + return &atad_devinfo[device]; +} + +static void ata_set_dir(int dir) +{ + USE_SPD_REGS; + u16 val; + + SPD_REG16(0x38) = 3; + val = SPD_REG16(SPD_R_IF_CTRL) & 1; + val |= (dir == ATA_DIR_WRITE) ? 0x4c : 0x4e; + SPD_REG16(SPD_R_IF_CTRL) = val; +#ifdef ATA_GAMESTAR_WORKAROUND + SPD_REG16(SPD_R_XFR_CTRL) = dir | (ata_gamestar_workaround ? 0x86 : 0x6); +#else + SPD_REG16(SPD_R_XFR_CTRL) = dir | 0x6; // In v1.04, DMA was enabled here (0x86 instead of 0x6) +#endif +} + +static void ata_pio_mode(int mode) +{ + USE_SPD_REGS; +#ifdef ATA_ALL_PIO_MODES + u16 val; + + switch (mode) { + case 1: + val = 0x72; + break; + case 2: + val = 0x32; + break; + case 3: + val = 0x24; + break; + case 4: + val = 0x23; + break; + default: + val = 0x92; + } + + SPD_REG16(SPD_R_PIO_MODE) = val; +#else + /* In the late ATAD versions, PIO mode 0 is always used if PIO mode is utilized. */ + SPD_REG16(SPD_R_PIO_MODE) = 0x92; +#endif +} + +#ifdef ATA_MWDMA_MODES +static void ata_multiword_dma_mode(int mode) +{ + USE_SPD_REGS; + u16 val; + + switch (mode) { + case 1: + val = 0x45; + break; + case 2: + val = 0x24; + break; + default: + val = 0xff; + } + + SPD_REG16(SPD_R_MWDMA_MODE) = val; + SPD_REG16(SPD_R_IF_CTRL) = (SPD_REG16(SPD_R_IF_CTRL) & 0xfffe) | 0x48; +} +#endif + +static void ata_ultra_dma_mode(int mode) +{ + USE_SPD_REGS; + u16 val; + + switch (mode) { + case 1: + val = 0x85; + break; + case 2: + val = 0x63; + break; + case 3: + val = 0x62; + break; + case 4: + val = 0x61; + break; + default: + val = 0xa7; + } + + SPD_REG16(SPD_R_UDMA_MODE) = val; + SPD_REG16(SPD_R_IF_CTRL) |= 0x49; +} + +/* Export 18 */ +int ata_device_idle_immediate(int device) +{ + int res; + + if (!(res = ata_io_start(NULL, 1, 0, 0, 0, 0, 0, (device << 4) & 0xFFFF, ATA_C_IDLE_IMMEDIATE))) + res = ata_io_finish(); + + return res; +} + +static int ata_device_standby_immediate(int device) +{ + int res; + + if (!(res = ata_io_start(NULL, 1, 0, 0, 0, 0, 0, (device << 4) & 0xFFFF, ATA_C_STANDBY_IMMEDIATE))) + res = ata_io_finish(); + + return res; +} + +static void ata_shutdown_cb(void) +{ + int i; + + for (i = 0; i < 2; i++) { + if (atad_devinfo[i].exists) + ata_device_standby_immediate(i); + } +} diff --git a/sps2_basement/hardware/dev9/dev9/Makefile b/sps2_basement/hardware/dev9/dev9/Makefile new file mode 100644 index 0000000..af05d33 --- /dev/null +++ b/sps2_basement/hardware/dev9/dev9/Makefile @@ -0,0 +1,38 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +# Enable to disable initialization of SMAP within DEV9 (i.e. clone adaptor compatibility). +DEV9_SKIP_SMAP_INIT ?= 0 + +# Enable to enable support for the PSX's devices +DEV9_PSX_SUPPORT ?= 1 + +# Disable to disable the workaround (skip SMAP initialization) for bad GameStar compatible adaptors. +DEV9_GAMESTAR_WORKAROUND ?= 1 + +IOP_BIN ?= ps2dev9.irx + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/poweroff/include +IOP_OBJS = ps2dev9.o exports.o imports.o + +ifeq ($(DEV9_SKIP_SMAP_INIT),1) +IOP_CFLAGS += -DDEV9_SKIP_SMAP_INIT=1 +endif + +ifeq ($(DEV9_PSX_SUPPORT),1) +IOP_CFLAGS += -DDEV9_PSX_SUPPORT=1 +endif + +ifeq ($(DEV9_GAMESTAR_WORKAROUND),1) +IOP_CFLAGS += -DDEV9_GAMESTAR_WORKAROUND=1 +endif + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dev9/dev9/include/dev9.h b/sps2_basement/hardware/dev9/dev9/include/dev9.h new file mode 100644 index 0000000..82a25b6 --- /dev/null +++ b/sps2_basement/hardware/dev9/dev9/include/dev9.h @@ -0,0 +1,64 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * DEV9 Device Driver definitions and imports. + */ + +#ifndef __DEV9_H__ +#define __DEV9_H__ + +#include +#include + +#include + +typedef int (*dev9_intr_cb_t)(int flag); +typedef void (*dev9_shutdown_cb_t)(void); +typedef void (*dev9_dma_cb_t)(int bcr, int dir); + +void dev9RegisterIntrCb(int intr, dev9_intr_cb_t cb); + +int dev9DmaTransfer(int ctrl, void *buf, int bcr, int dir); + +void dev9Shutdown(void); +void dev9IntrEnable(int mask); +void dev9IntrDisable(int mask); + +int dev9GetEEPROM(u16 *buf); + +void dev9LEDCtl(int ctl); +void dev9LED2Ctl(int ctl); +void dev9ControlPIO3(int ctl); + +int dev9RegisterShutdownCb(int idx, dev9_shutdown_cb_t cb); + +void dev9RegisterPreDmaCb(int ctrl, dev9_dma_cb_t cb); + +void dev9RegisterPostDmaCb(int ctrl, dev9_dma_cb_t cb); + +#define dev9_IMPORTS_start DECLARE_IMPORT_TABLE(dev9, 1, 9) +#define dev9_IMPORTS_end END_IMPORT_TABLE + +#define I_dev9RegisterIntrCb DECLARE_IMPORT(4, dev9RegisterIntrCb) +#define I_dev9DmaTransfer DECLARE_IMPORT(5, dev9DmaTransfer) +#define I_dev9Shutdown DECLARE_IMPORT(6, dev9Shutdown) +#define I_dev9IntrEnable DECLARE_IMPORT(7, dev9IntrEnable) +#define I_dev9IntrDisable DECLARE_IMPORT(8, dev9IntrDisable) +#define I_dev9GetEEPROM DECLARE_IMPORT(9, dev9GetEEPROM) +#define I_dev9LEDCtl DECLARE_IMPORT(10, dev9LEDCtl) +#define I_dev9RegisterShutdownCb DECLARE_IMPORT(11, dev9RegisterShutdownCb) +#define I_dev9RegisterPreDmaCb DECLARE_IMPORT(12, dev9RegisterPreDmaCb) +#define I_dev9RegisterPostDmaCb DECLARE_IMPORT(13, dev9RegisterPostDmaCb) +#define I_dev9ControlPIO3 DECLARE_IMPORT(14, dev9ControlPIO3) +#define I_dev9LED2Ctl DECLARE_IMPORT(15, dev9LED2Ctl) + +#endif /* __DEV9_H__ */ diff --git a/sps2_basement/hardware/dev9/dev9/src/exports.tab b/sps2_basement/hardware/dev9/dev9/src/exports.tab new file mode 100644 index 0000000..d63fcc6 --- /dev/null +++ b/sps2_basement/hardware/dev9/dev9/src/exports.tab @@ -0,0 +1,22 @@ +DECLARE_EXPORT_TABLE(dev9, 1, 9) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_exit) + DECLARE_EXPORT(_retonly) + + /* 4 */ + DECLARE_EXPORT(dev9RegisterIntrCb) + DECLARE_EXPORT(dev9DmaTransfer) + DECLARE_EXPORT(dev9Shutdown) + DECLARE_EXPORT(dev9IntrEnable) + DECLARE_EXPORT(dev9IntrDisable) + DECLARE_EXPORT(dev9GetEEPROM) + DECLARE_EXPORT(dev9LEDCtl) + DECLARE_EXPORT(dev9RegisterShutdownCb) + DECLARE_EXPORT(dev9RegisterPreDmaCb) + DECLARE_EXPORT(dev9RegisterPostDmaCb) + DECLARE_EXPORT(dev9ControlPIO3) + DECLARE_EXPORT(dev9LED2Ctl) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/dev9/dev9/src/imports.lst b/sps2_basement/hardware/dev9/dev9/src/imports.lst new file mode 100644 index 0000000..657acde --- /dev/null +++ b/sps2_basement/hardware/dev9/dev9/src/imports.lst @@ -0,0 +1,41 @@ +dmacman_IMPORTS_start +I_dmac_get_dpcr2 +I_dmac_set_dpcr2 +dmacman_IMPORTS_end + +intrman_IMPORTS_start +I_RegisterIntrHandler +I_EnableIntr +I_DisableIntr +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +ioman_IMPORTS_start +I_AddDrv +I_DelDrv +ioman_IMPORTS_end + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +I_QueryBootMode +loadcore_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_strcmp +I_strrchr +sysclib_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/dev9/dev9/src/irx_imports.h b/sps2_basement/hardware/dev9/dev9/src/irx_imports.h new file mode 100644 index 0000000..a547c41 --- /dev/null +++ b/sps2_basement/hardware/dev9/dev9/src/irx_imports.h @@ -0,0 +1,28 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "dmacman.h" +#include "intrman.h" +#include "ioman.h" +#include "loadcore.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thsemap.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dev9/dev9/src/ps2dev9.c b/sps2_basement/hardware/dev9/dev9/src/ps2dev9.c new file mode 100644 index 0000000..68a33ea --- /dev/null +++ b/sps2_basement/hardware/dev9/dev9/src/ps2dev9.c @@ -0,0 +1,1282 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * DEV9 Device Driver. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define MODNAME "dev9" +#define DRIVERNAME "dev9" +// This is version from last SDK 3.1.0 +IRX_ID(MODNAME, 2, 8); + +#define M_PRINTF(format, args...) \ + printf(MODNAME ": " format, ##args) + +#define VERSION "1.0" +#define BANNER "\nDEV9 device driver v%s - Copyright (c) 2003 Marcus R. Brown\n\n" + +/* SSBUS registers. */ +#define SSBUS_R_1418 0xbf801418 +#define SSBUS_R_141c 0xbf80141c +#define SSBUS_R_1420 0xbf801420 + +static int semaAttrGlobal; /* Semaphore attribute value to use. */ +static const char *mod_name; /* Module name. */ +static int dev9type = -1; /* 0 for PCMCIA, 1 for expansion bay */ +static int using_aif = 0; /* 1 if using AIF on a T10K */ + +static int dma_lock_sem; /* used to arbitrate DMA */ + +enum PC_CARD_TYPE { + PC_CARD_TYPE_NONE = 0, + PC_CARD_TYPE_PCMCIA, + PC_CARD_TYPE_CARDBUS, +}; + +enum PC_CARD_VOLTAGE { + PC_CARD_VOLTAGE_INVALID = 0, + PC_CARD_VOLTAGE_3V, + PC_CARD_VOLTAGE_5V, + PC_CARD_VOLTAGE_04h +}; + +static int pcic_cardtype; /* Translated value of bits 0-1 of 0xbf801462 */ +static int pcic_voltage; /* Translated value of bits 2-3 of 0xbf801462 */ + +static s16 eeprom_data[5]; /* 2-byte EEPROM status (0/-1 = invalid, 1 = valid), + 6-byte MAC address, + 2-byte MAC address checksum. */ + +typedef int (*dev9IntrDispatchCb_t)(int flag); +static dev9IntrDispatchCb_t p_dev9_intr_cb = NULL; +static void dev9RegisterIntrDispatchCb(dev9IntrDispatchCb_t callback); + +/* Each driver can register callbacks that correspond to each bit of the + SMAP interrupt status register (0xbx000028). */ +static dev9_intr_cb_t dev9_intr_cbs[16]; + +static dev9_shutdown_cb_t dev9_shutdown_cbs[16]; + +static dev9_dma_cb_t dev9_predma_cbs[4], dev9_postdma_cbs[4]; + +static u8 dev9_has_dvr_capability = 0; + +static int dev9_intr_dispatch(int flag); + +static void dev9_set_stat(int stat); +static int dev9_ssbus_mode(int mode); +static int dev9_device_probe(void); +static int dev9_device_reset(void); +static int dev9_card_find_manfid(u32 manfid); + +static int read_eeprom_data(void); +static int dev9_init(int sema_attr); +static int speed_device_init(void); + +static void pcmcia_set_stat(int stat); +static int pcic_ssbus_mode(int mode); +static int pcmcia_device_probe(void); +static int pcmcia_device_reset(void); +static int card_find_manfid(u32 manfid); +static int pcmcia_init(int sema_attr); + +static void expbay_set_stat(int stat); +static int expbay_device_probe(void); +static int expbay_device_reset(void); +static int expbay_init(int sema_attr); + +extern struct irx_export_table _exp_dev9; + +static int dev9x_dummy(void) +{ + return 0; +} + +static int dev9x_devctl(iop_file_t *f, const char *name, int cmd, void *args, unsigned int arglen, void *buf, unsigned int buflen) +{ + switch (cmd) { + case DDIOC_MODEL: + return dev9type; + case DDIOC_OFF: + dev9Shutdown(); + return 0; + case DDIOC_SETPIO3: + dev9ControlPIO3(((u32 *)args)[0]); + return 0; + case DDIOC_LED2CTL: + dev9LED2Ctl(((u32 *)args)[0]); + return 0; + default: + return 0; + } +} + +static iop_device_ops_t dev9x_ops = + { + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + (void *)&dev9x_dummy, + &dev9x_devctl}; + +static iop_device_t dev9x_device = + { + "dev9x", + IOP_DT_FS | IOP_DT_FSEXT, + 1, + "DEV9", + &dev9x_ops}; + +static int print_help(void) +{ // The original made a printf() call for each line. + printf("Usage:\n" + " %s [-sa] ]\n" + " -sa You can specify attibute of sempahore for queuing thread.\n" + " List of possible :\n" + " SA_THPRI(default), SA_THFIFO\n", + mod_name); + + return MODULE_NO_RESIDENT_END; +} + +int _start(int argc, char **argv) +{ + USE_DEV9_REGS; + const char *pModName; + int idx, res; + u16 dev9hw; + + semaAttrGlobal = SA_THPRI; + + printf(BANNER, VERSION); + + mod_name = (pModName = strrchr(argv[0], '/')) != NULL ? pModName + 1 : argv[0]; + + for (--argc, ++argv; argc > 0; argc--, argv++) { + if ((*argv)[0] != '-') + break; + + if (strcmp("-sa", *argv) == 0) { + --argc; + ++argv; + if (argc > 0) { + if (strcmp("SA_THFIFO", *argv) == 0) { + semaAttrGlobal = SA_THFIFO; + } else if (strcmp("SA_THPRI", *argv) == 0) { + semaAttrGlobal = SA_THPRI; + } else { + return print_help(); + } + } else { + return print_help(); + } + } else { + return print_help(); + } + } + + for (idx = 0; idx < 16; idx++) + dev9_shutdown_cbs[idx] = NULL; + + dev9hw = DEV9_REG(DEV9_R_REV) & 0xf0; + if (dev9hw == 0x20) { /* CXD9566 (PCMCIA) */ + dev9type = DEV9_TYPE_PCMCIA; + M_PRINTF("CXD9566 detected.\n"); + res = pcmcia_init(semaAttrGlobal); + } else if (dev9hw == 0x30) { /* CXD9611 (Expansion Bay) */ + dev9type = DEV9_TYPE_EXPBAY; + M_PRINTF("CXD9611 detected.\n"); + res = expbay_init(semaAttrGlobal); + } else { + M_PRINTF("unknown dev9 hardware.\n"); + res = MODULE_NO_RESIDENT_END; + } + + if (res) + return res; + + DelDrv("dev9x"); + if (AddDrv(&dev9x_device) != 0) { + return MODULE_NO_RESIDENT_END; + } + + return MODULE_RESIDENT_END; +} + +int _exit(void) { return 0; } + +/* Export 4 */ +void dev9RegisterIntrCb(int intr, dev9_intr_cb_t cb) +{ + dev9_intr_cbs[intr] = cb; +} + +/* Export 12 */ +void dev9RegisterPreDmaCb(int ctrl, dev9_dma_cb_t cb) +{ + dev9_predma_cbs[ctrl] = cb; +} + +/* Export 13 */ +void dev9RegisterPostDmaCb(int ctrl, dev9_dma_cb_t cb) +{ + dev9_postdma_cbs[ctrl] = cb; +} + +// flag is 1 if a card (pcmcia) was removed or added +static int dev9_intr_dispatch(int flag) +{ + USE_SPD_REGS; + int i, bit; + + if (flag) { + for (i = 0; i < 16; i++) + if (dev9_intr_cbs[i] != NULL) + dev9_intr_cbs[i](flag); + } + + while (SPD_REG16(SPD_R_INTR_STAT) & SPD_REG16(SPD_R_INTR_MASK)) { + for (i = 0; i < 16; i++) { + if (dev9_intr_cbs[i] != NULL) { + bit = (SPD_REG16(SPD_R_INTR_STAT) & + SPD_REG16(SPD_R_INTR_MASK)) >> + i; + if (bit & 0x01) + dev9_intr_cbs[i](flag); + } + } + } + + return 0; +} + +static void dev9_set_stat(int stat) +{ + switch (dev9type) { + case DEV9_TYPE_PCMCIA: + pcmcia_set_stat(stat); + break; + case DEV9_TYPE_EXPBAY: + expbay_set_stat(stat); + break; + } +} + +static int dev9_ssbus_mode(int mode) +{ + switch (dev9type) { + case DEV9_TYPE_PCMCIA: + return pcic_ssbus_mode(mode); + case DEV9_TYPE_EXPBAY: + return 0; + } + + return -1; +} + +static int dev9_device_probe(void) +{ + switch (dev9type) { + case DEV9_TYPE_PCMCIA: + return pcmcia_device_probe(); + case DEV9_TYPE_EXPBAY: + return expbay_device_probe(); + } + + return -1; +} + +static int dev9_device_reset(void) +{ + switch (dev9type) { + case DEV9_TYPE_PCMCIA: + return pcmcia_device_reset(); + case DEV9_TYPE_EXPBAY: + return expbay_device_reset(); + } + + return -1; +} + +/* Export 6 */ +void dev9Shutdown(void) +{ + int idx; + USE_DEV9_REGS; + + for (idx = 0; idx < 16; idx++) + if (dev9_shutdown_cbs[idx]) + dev9_shutdown_cbs[idx](); + + if (dev9type == DEV9_TYPE_PCMCIA) { /* PCMCIA */ + DEV9_REG(DEV9_R_POWER) = 0; + DEV9_REG(DEV9_R_1474) = 0; + } else if (dev9type == DEV9_TYPE_EXPBAY) { + DEV9_REG(DEV9_R_1466) = 1; + DEV9_REG(DEV9_R_1464) = 0; + DEV9_REG(DEV9_R_1460) = DEV9_REG(DEV9_R_1464); + DEV9_REG(DEV9_R_POWER) = DEV9_REG(DEV9_R_POWER) & ~4; + DEV9_REG(DEV9_R_POWER) = DEV9_REG(DEV9_R_POWER) & ~1; + } + DelayThread(1000000); +} + +static int dev9_card_find_manfid(u32 manfid) +{ + switch (dev9type) { + case DEV9_TYPE_PCMCIA: + return card_find_manfid(manfid); + case DEV9_TYPE_EXPBAY: + return 0; + } + + return -1; +} + +/* Export 7 */ +void dev9IntrEnable(int mask) +{ + USE_SPD_REGS; + int flags; + + CpuSuspendIntr(&flags); + SPD_REG16(SPD_R_INTR_MASK) = SPD_REG16(SPD_R_INTR_MASK) | mask; + CpuResumeIntr(flags); +} + +/* Export 8 */ +void dev9IntrDisable(int mask) +{ + USE_SPD_REGS; + int flags; + + CpuSuspendIntr(&flags); + SPD_REG16(SPD_R_INTR_MASK) = SPD_REG16(SPD_R_INTR_MASK) & ~mask; + CpuResumeIntr(flags); +} + +/* Export 5 */ +int dev9DmaTransfer(int device, void *buf, int bcr, int dir) +{ + USE_SPD_REGS; + volatile iop_dmac_chan_t *dev9_chan = (iop_dmac_chan_t *)DEV9_DMAC_BASE; + int res, dmactrl, OldState; + + if (device >= 2) { + if (dev9_predma_cbs[device] == NULL) + return -1; + if (dev9_postdma_cbs[device] == NULL) + return -1; + } + + if ((res = WaitSema(dma_lock_sem)) < 0) + return res; + + switch (device) { + case 0: + dmactrl = 0; + break; + case 1: + dmactrl = 1; + break; +#ifdef DEV9_PSX_SUPPORT + // Used for the PSX + case 2: + dmactrl = 0x10; + break; + case 3: + dmactrl = 0x20; + break; +#endif + default: + dmactrl = 0; + } + + SPD_REG16(SPD_R_DMA_CTRL) = (SPD_REG16(SPD_R_REV_1) < 17) ? (dmactrl & 0x03) | 0x04 : dmactrl | 0x06; + + if (dev9_predma_cbs[device]) + dev9_predma_cbs[device](bcr, dir); + + dev9_chan->madr = (u32)buf; + + /* Older versions of DEV9 do not suspend interrupts. Not sure why this must be done though. */ + CpuSuspendIntr(&OldState); + dev9_chan->bcr = bcr; + dev9_chan->chcr = DMAC_CHCR_30 | DMAC_CHCR_TR | DMAC_CHCR_CO | (dir & DMAC_CHCR_DR); + CpuResumeIntr(OldState); + + /* Wait for DMA to complete. Do not use a semaphore as thread switching hurts throughput greatly. */ + while (dev9_chan->chcr & DMAC_CHCR_TR) {} + + if (dev9_postdma_cbs[device]) + dev9_postdma_cbs[device](bcr, dir); + + SignalSema(dma_lock_sem); + return 0; +} + +static int read_eeprom_data(void) +{ + USE_SPD_REGS; + int i, j, res = -2; + u8 val; + + if (eeprom_data[0] < 0) + goto out; + + SPD_REG8(SPD_R_PIO_DIR) = 0xe0 | (dev9_has_dvr_capability ? 7 : 1); + DelayThread(1); + SPD_REG8(SPD_R_PIO_DATA) = 0x80; + DelayThread(1); + + for (i = 0; i < 2; i++) { + SPD_REG8(SPD_R_PIO_DATA) = 0xa0; + DelayThread(1); + SPD_REG8(SPD_R_PIO_DATA) = 0xe0; + DelayThread(1); + } + for (i = 0; i < 7; i++) { + SPD_REG8(SPD_R_PIO_DATA) = 0x80; + DelayThread(1); + SPD_REG8(SPD_R_PIO_DATA) = 0xc0; + DelayThread(1); + } + SPD_REG8(SPD_R_PIO_DATA) = 0xc0; + DelayThread(1); + + val = SPD_REG8(SPD_R_PIO_DATA); + DelayThread(1); + if (val & 0x10) { /* Error. */ + SPD_REG8(SPD_R_PIO_DATA) = 0; + DelayThread(1); + res = -1; + eeprom_data[0] = 0; + goto out; + } + + SPD_REG8(SPD_R_PIO_DATA) = 0x80; + DelayThread(1); + + /* Read the MAC address and checksum from the EEPROM. */ + for (i = 0; i < 4; i++) { + eeprom_data[i + 1] = 0; + + for (j = 15; j >= 0; j--) { + SPD_REG8(SPD_R_PIO_DATA) = 0xc0; + DelayThread(1); + val = SPD_REG8(SPD_R_PIO_DATA); + if (val & 0x10) + eeprom_data[i + 1] |= (1 << j); + SPD_REG8(SPD_R_PIO_DATA) = 0x80; + DelayThread(1); + } + } + + SPD_REG8(SPD_R_PIO_DATA) = 0; + DelayThread(1); + eeprom_data[0] = 1; /* The EEPROM data is valid. */ + res = 0; + +out: + SPD_REG8(SPD_R_PIO_DIR) = dev9_has_dvr_capability ? 7 : 1; + return res; +} + +/* Export 9 */ +int dev9GetEEPROM(u16 *buf) +{ + int i; + + if (!eeprom_data[0]) + return -1; + if (eeprom_data[0] < 0) + return -2; + + /* We only return the MAC address and checksum. */ + for (i = 0; i < 4; i++) + buf[i] = eeprom_data[i + 1]; + + return 0; +} + +// Exerpt from Wisi's SPEED.txt: +// 1:0 Dev9 LED Control. 0=On/1=Off. +// Clearing either to 0 will light the LED. +// Each is connected to the cathode of a diode, sharing a common anode. +// The anode has a 10kohm pull-up to Vcc, and is connected to the base of an PNP transistor, +// with collector grounded and emitter, connecting through a 240ohm resistor to the ACS_LED +// pin (90) of the Expansion Bay connector. It connects to the cathode of the HDD Activity LED +// in the PS2, the anode of which connects through 180ohm resistor to +5V. + +// The specific LED part used is the Citizen CITILED CL-200TLY-C, which has a "Lemon Yellow" color. + +/* Export 10 */ +void dev9LEDCtl(int ctl) +{ + USE_SPD_REGS; + if (dev9_has_dvr_capability) + { + SPD_REG8(SPD_R_PIO_DIR) |= 1; + SPD_REG8(SPD_R_PIO_DATA) = (SPD_REG8(SPD_R_PIO_DATA) & 0xE) | (ctl ? 0 : 1); + } + else + { + SPD_REG8(SPD_R_PIO_DATA) = (ctl == 0); + } +} + +/* Export 15 */ +void dev9LED2Ctl(int ctl) +{ + if (dev9_has_dvr_capability) + { + USE_SPD_REGS; + SPD_REG8(SPD_R_PIO_DIR) |= 2; + DelayThread(1); + SPD_REG8(SPD_R_PIO_DATA) = (SPD_REG8(SPD_R_PIO_DATA) & 0xD) | (ctl ? 0 : 2); + DelayThread(1); + } +} + +// Exerpt from Wisi's SPEED.txt: +// 3:2 On SCPH-70000, each is connected through 10kohm R to Vcc, so they were inputs once. +// On the SCPH-10350 Network Adapter - as well. + +/* Export 14 */ +void dev9ControlPIO3(int ctl) +{ + if (dev9_has_dvr_capability) + { + USE_SPD_REGS; + SPD_REG8(SPD_R_PIO_DIR) |= 4; + DelayThread(1); + SPD_REG8(SPD_R_PIO_DATA) = (SPD_REG8(SPD_R_PIO_DATA) & 0xB) | (ctl ? 0 : 4); + DelayThread(1); + } +} + +static void dev9RegisterIntrDispatchCb(dev9IntrDispatchCb_t callback) +{ + p_dev9_intr_cb = callback; +} + +/* Export 11 */ +int dev9RegisterShutdownCb(int idx, dev9_shutdown_cb_t cb) +{ + if (idx < 16) { + dev9_shutdown_cbs[idx] = cb; + return 0; + } + return -1; +} + +static int dev9_init(int sema_attr) +{ + iop_sema_t sema; + int i, flags; + + sema.attr = sema_attr; + sema.initial = 1; + sema.max = 1; + if ((dma_lock_sem = CreateSema(&sema)) < 0) + return -1; + + CpuSuspendIntr(&flags); + /* Enable the DEV9 DMAC channel. */ + dmac_set_dpcr2(dmac_get_dpcr2() | 0x80); + CpuResumeIntr(flags); + + /* Not quite sure what this enables yet. */ + dev9_set_stat(0x103); + + /* Disable all device interrupts. */ + dev9IntrDisable(0xffff); + + /* Register interrupt dispatch callback handler. */ + dev9RegisterIntrDispatchCb(&dev9_intr_dispatch); + + /* Reset the SMAP interrupt callback table. */ + for (i = 0; i < 16; i++) + dev9_intr_cbs[i] = NULL; + + for (i = 0; i < 4; i++) { + dev9_predma_cbs[i] = NULL; + dev9_postdma_cbs[i] = NULL; + } + + /* Read in the MAC address. */ + read_eeprom_data(); + + dev9LED2Ctl(0); + dev9ControlPIO3(0); + + /* Turn the LED off. */ + dev9LEDCtl(0); + return 0; +} + +#ifndef DEV9_SKIP_SMAP_INIT +static int dev9_smap_read_phy(volatile u8 *emac3_regbase, unsigned int address, unsigned int *data) +{ + unsigned int i, PHYRegisterValue; + int result; + + PHYRegisterValue = (address & SMAP_E3_PHY_REG_ADDR_MSK) | SMAP_E3_PHY_READ | ((SMAP_DsPHYTER_ADDRESS & SMAP_E3_PHY_ADDR_MSK) << SMAP_E3_PHY_ADDR_BITSFT); + + i = 0; + result = 0; + SMAP_EMAC3_SET(SMAP_R_EMAC3_STA_CTRL, PHYRegisterValue); + + do { + if (SMAP_EMAC3_GET(SMAP_R_EMAC3_STA_CTRL) & SMAP_E3_PHY_OP_COMP) { + if (SMAP_EMAC3_GET(SMAP_R_EMAC3_STA_CTRL) & SMAP_E3_PHY_OP_COMP) { + if ((result = SMAP_EMAC3_GET(SMAP_R_EMAC3_STA_CTRL)) & SMAP_E3_PHY_OP_COMP) { + result >>= SMAP_E3_PHY_DATA_BITSFT; + break; + } + } + } + + DelayThread(1000); + i++; + } while (i < 100); + + if (i >= 100) { + return 1; + } else { + *data = result; + return 0; + } +} + +static int dev9_smap_write_phy(volatile u8 *emac3_regbase, unsigned char address, unsigned short int value) +{ + unsigned int i, PHYRegisterValue; + + PHYRegisterValue = (address & SMAP_E3_PHY_REG_ADDR_MSK) | SMAP_E3_PHY_WRITE | ((SMAP_DsPHYTER_ADDRESS & SMAP_E3_PHY_ADDR_MSK) << SMAP_E3_PHY_ADDR_BITSFT); + PHYRegisterValue |= ((unsigned int)value) << SMAP_E3_PHY_DATA_BITSFT; + + i = 0; + SMAP_EMAC3_SET(SMAP_R_EMAC3_STA_CTRL, PHYRegisterValue); + + for (; !(SMAP_EMAC3_GET(SMAP_R_EMAC3_STA_CTRL) & SMAP_E3_PHY_OP_COMP); i++) { + DelayThread(1000); + if (i >= 100) + break; + } + + return ((i >= 100) ? 1 : 0); +} + +static int dev9_smap_init(void) +{ + unsigned int value; + USE_SPD_REGS; + USE_SMAP_REGS; + USE_SMAP_EMAC3_REGS; + USE_SMAP_TX_BD; + USE_SMAP_RX_BD; + int i; + + // Do not perform SMAP initialization if the SPEED device does not have such an interface + if (!(SPD_REG16(SPD_R_REV_3) & SPD_CAPS_SMAP) +#ifdef DEV9_GAMESTAR_WORKAROUND + /* If this adaptor is a compatible adaptor, do not initialize SMAP. + Official adaptors appear to have a 0x0001 set for this register, but not compatibles. + While official I/O to this register are 8-bit, some compatibles have a 0x01 for the lower 8-bits, + but the upper 8-bits contain some random value. Hence perform a 16-bit read instead. */ + || (SPD_REG16(0x20) != 1) +#endif + ) + return 0; + + SMAP_REG8(SMAP_R_TXFIFO_CTRL) = SMAP_TXFIFO_RESET; + for (i = 9; SMAP_REG8(SMAP_R_TXFIFO_CTRL) & SMAP_TXFIFO_RESET; i--) { + if (i <= 0) + return 1; + DelayThread(1000); + } + + SMAP_REG8(SMAP_R_RXFIFO_CTRL) = SMAP_RXFIFO_RESET; + for (i = 9; SMAP_REG8(SMAP_R_RXFIFO_CTRL) & SMAP_RXFIFO_RESET; i--) { + if (i <= 0) + return 1; + DelayThread(1000); + } + + SMAP_EMAC3_SET(SMAP_R_EMAC3_MODE0, SMAP_E3_SOFT_RESET); + for (i = 9; SMAP_EMAC3_GET(SMAP_R_EMAC3_MODE0) & SMAP_E3_SOFT_RESET; i--) { + if (i <= 0) + return 3; + DelayThread(1000); + } + + // Unlike the SMAP driver, this reset operation is done in big-endian. + if (SPD_REG16(SPD_R_REV_1) >= 0x11) + SMAP_REG8(SMAP_R_BD_MODE) = SMAP_BD_SWAP; + + for (i = 0; i < SMAP_BD_MAX_ENTRY; i++) { + tx_bd[i].ctrl_stat = 0; + tx_bd[i].reserved = 0; + tx_bd[i].length = 0; + tx_bd[i].pointer = 0; + } + + for (i = 0; i < SMAP_BD_MAX_ENTRY; i++) { + rx_bd[i].ctrl_stat = 0x80; // SMAP_BD_RX_EMPTY + rx_bd[i].reserved = 0; + rx_bd[i].length = 0; + rx_bd[i].pointer = 0; + } + + SMAP_REG16(SMAP_R_INTR_CLR) = SMAP_INTR_BITMSK; + if (SPD_REG16(SPD_R_REV_1) < 0x11) + SPD_REG8(0x100) = 1; + + SMAP_EMAC3_SET(SMAP_R_EMAC3_MODE1, SMAP_E3_FDX_ENABLE | SMAP_E3_IGNORE_SQE | SMAP_E3_MEDIA_100M | SMAP_E3_RXFIFO_2K | SMAP_E3_TXFIFO_1K | SMAP_E3_TXREQ0_MULTI | SMAP_E3_TXREQ1_SINGLE); + SMAP_EMAC3_SET(SMAP_R_EMAC3_TxMODE1, 7 << SMAP_E3_TX_LOW_REQ_BITSFT | 15 << SMAP_E3_TX_URG_REQ_BITSFT); + SMAP_EMAC3_SET(SMAP_R_EMAC3_RxMODE, SMAP_E3_RX_RX_RUNT_FRAME | SMAP_E3_RX_RX_FCS_ERR | SMAP_E3_RX_RX_TOO_LONG_ERR | SMAP_E3_RX_RX_IN_RANGE_ERR | SMAP_E3_RX_PROP_PF | SMAP_E3_RX_PROMISC); + SMAP_EMAC3_SET(SMAP_R_EMAC3_INTR_STAT, SMAP_E3_INTR_TX_ERR_0 | SMAP_E3_INTR_SQE_ERR_0 | SMAP_E3_INTR_DEAD_0); + SMAP_EMAC3_SET(SMAP_R_EMAC3_INTR_ENABLE, SMAP_E3_INTR_TX_ERR_0 | SMAP_E3_INTR_SQE_ERR_0 | SMAP_E3_INTR_DEAD_0); + SMAP_EMAC3_SET(SMAP_R_EMAC3_ADDR_HI, 0); + SMAP_EMAC3_SET(SMAP_R_EMAC3_ADDR_LO, 0); + SMAP_EMAC3_SET(SMAP_R_EMAC3_PAUSE_TIMER, 0xFFFF); + SMAP_EMAC3_SET(SMAP_R_EMAC3_INTER_FRAME_GAP, 4); + SMAP_EMAC3_SET(SMAP_R_EMAC3_TX_THRESHOLD, 12 << SMAP_E3_TX_THRESHLD_BITSFT); + SMAP_EMAC3_SET(SMAP_R_EMAC3_RX_WATERMARK, 16 << SMAP_E3_RX_LO_WATER_BITSFT | 128 << SMAP_E3_RX_HI_WATER_BITSFT); + + dev9_smap_write_phy(emac3_regbase, SMAP_DsPHYTER_BMCR, SMAP_PHY_BMCR_RST); + for (i = 9;; i--) { + if (dev9_smap_read_phy(emac3_regbase, SMAP_DsPHYTER_BMCR, &value)) + return 4; + if (!(value & SMAP_PHY_BMCR_RST)) + break; + if (i <= 0) + return 5; + } + + dev9_smap_write_phy(emac3_regbase, SMAP_DsPHYTER_BMCR, SMAP_PHY_BMCR_LPBK | SMAP_PHY_BMCR_100M | SMAP_PHY_BMCR_DUPM); + DelayThread(10000); + SMAP_EMAC3_SET(SMAP_R_EMAC3_MODE0, SMAP_E3_TXMAC_ENABLE | SMAP_E3_RXMAC_ENABLE); + value = SMAP_REG16(SMAP_R_TXFIFO_WR_PTR) + SMAP_TX_BASE; + + for (i = 0; i < 0x5EA; i += 4) + SMAP_REG32(SMAP_R_TXFIFO_DATA) = i; + + tx_bd[0].length = 0xEA05; + tx_bd[0].pointer = (value >> 8) | (value << 8); + SMAP_REG8(SMAP_R_TXFIFO_FRAME_INC) = 0; + tx_bd[0].ctrl_stat = 0x83; // SMAP_BD_TX_READY|SMAP_BD_TX_GENFCS|SMAP_BD_TX_GENPAD + + SMAP_EMAC3_SET(SMAP_R_EMAC3_TxMODE0, SMAP_E3_TX_GNP_0); + for (i = 9;; i--) { + value = SPD_REG16(SPD_R_INTR_STAT); + + if ((value & (SMAP_INTR_RXEND | SMAP_INTR_TXEND | SMAP_INTR_TXDNV)) == (SMAP_INTR_RXEND | SMAP_INTR_TXEND | SMAP_INTR_TXDNV)) + break; + if (i <= 0) + return 6; + DelayThread(1000); + } + SMAP_EMAC3_SET(SMAP_R_EMAC3_MODE0, SMAP_E3_SOFT_RESET); + + return 0; +} +#endif + +static int speed_device_init(void) +{ + USE_SPD_REGS; + const char *spdnames[] = {"(unknown)", "TS", "ES1", "ES2"}; + int idx, res; + u16 spdrev; +#ifndef DEV9_SKIP_SMAP_INIT + int i; +#endif + + eeprom_data[0] = 0; + +#ifndef DEV9_SKIP_SMAP_INIT + for (i = 0; i < 8; i++) { +#endif + if (dev9_device_probe() < 0) { + M_PRINTF("No device.\n"); + return -1; + } + + dev9_device_reset(); + + /* Locate the SPEED Lite chip and get the bus ready for the + PCMCIA device. */ + if ((res = dev9_card_find_manfid(0xf15300))) + M_PRINTF("SPEED Lite not found.\n"); + + if (!res && (res = dev9_ssbus_mode(5))) + M_PRINTF("Unable to change SSBUS mode.\n"); + + if (res) { + dev9Shutdown(); + return -1; + } + +#ifndef DEV9_SKIP_SMAP_INIT + if ((res = dev9_smap_init()) == 0) { + break; + } + + dev9Shutdown(); + DelayThread(4500000); + } + + if (res) { + M_PRINTF("SMAP initialization failed: %d\n", res); + eeprom_data[0] = -1; + } +#endif + + /* Print out the SPEED chip revision. */ + spdrev = SPD_REG16(SPD_R_REV_1); + idx = (spdrev & 0xffff) - 14; + if (spdrev == 9) + idx = 1; /* TS */ + else if (spdrev < 9 || (spdrev < 16 || spdrev > 17)) + idx = 0; /* Unknown revision */ + + M_PRINTF("SPEED chip '%s', revision %0x\n", spdnames[idx], spdrev); + return 0; +} + +static int pcic_get_cardtype(void) +{ + USE_DEV9_REGS; + u16 val = DEV9_REG(DEV9_R_1462) & 0x03; + + if (val == 0) + return PC_CARD_TYPE_PCMCIA; /* 16-bit */ + else if (val < 3) // If the bit pattern is either 10b or 01b + return PC_CARD_TYPE_CARDBUS; /* CardBus */ + return PC_CARD_TYPE_NONE; +} + +static int pcic_get_voltage(void) +{ + USE_DEV9_REGS; + u16 val = DEV9_REG(DEV9_R_1462) & 0x0c; + + if (val == 0x04) + return PC_CARD_VOLTAGE_04h; + if (val == 0 || val == 0x08) + return PC_CARD_VOLTAGE_3V; + if (val == 0x0c) + return PC_CARD_VOLTAGE_5V; + return PC_CARD_VOLTAGE_INVALID; +} + +static int pcic_power(int voltage, int flag) +{ + USE_DEV9_REGS; + u16 cstc1, cstc2; + u16 val = (voltage == 1) << 2; + + DEV9_REG(DEV9_R_POWER) = 0; + + if (voltage == 2) + val |= 0x08; + if (flag == 1) + val |= 0x10; + + DEV9_REG(DEV9_R_POWER) = val; + DelayThread(22000); + + if (DEV9_REG(DEV9_R_1462) & 0x100) + return 0; + + DEV9_REG(DEV9_R_POWER) = 0; + DEV9_REG(DEV9_R_1464) = cstc1 = DEV9_REG(DEV9_R_1464); + DEV9_REG(DEV9_R_1466) = cstc2 = DEV9_REG(DEV9_R_1466); + return -1; +} + +static void pcmcia_set_stat(int stat) +{ + USE_DEV9_REGS; + u16 val = stat & 0x01; + + if (stat & 0x10) + val = 1; + if (stat & 0x02) + val |= 0x02; + if (stat & 0x20) + val |= 0x02; + if (stat & 0x04) + val |= 0x08; + if (stat & 0x08) + val |= 0x10; + if (stat & 0x200) + val |= 0x20; + if (stat & 0x100) + val |= 0x40; + if (stat & 0x400) + val |= 0x80; + if (stat & 0x800) + val |= 0x04; + DEV9_REG(DEV9_R_1476) = val & 0xff; +} + +static int pcic_ssbus_mode(int mode) +{ + USE_DEV9_REGS; + USE_SPD_REGS; + u16 stat = DEV9_REG(DEV9_R_1474) & 7; + + if (mode != 3 && mode != 5) + return -1; + + DEV9_REG(DEV9_R_1460) = 2; + if (stat) + return -1; + + if (mode == 3) { + DEV9_REG(DEV9_R_1474) = 1; + DEV9_REG(DEV9_R_1460) = 1; + SPD_REG8(0x20) = 1; + DEV9_REG(DEV9_R_1474) = mode; + } else if (mode == 5) { + DEV9_REG(DEV9_R_1474) = mode; + DEV9_REG(DEV9_R_1460) = 1; + SPD_REG8(0x20) = 1; + DEV9_REG(DEV9_R_1474) = 7; + } + _sw(0xe01a3043, SSBUS_R_1418); + + DelayThread(5000); + DEV9_REG(DEV9_R_POWER) = DEV9_REG(DEV9_R_POWER) & ~1; + return 0; +} + +static int pcmcia_device_probe(void) +{ + const char *pcic_ct_names[] = {"No", "16-bit", "CardBus"}; + int voltage; + + pcic_voltage = pcic_get_voltage(); + pcic_cardtype = pcic_get_cardtype(); + voltage = (pcic_voltage == PC_CARD_VOLTAGE_5V ? 5 : (pcic_voltage == PC_CARD_VOLTAGE_3V ? 3 : 0)); + + M_PRINTF("%s PCMCIA card detected. Vcc = %dV\n", + pcic_ct_names[pcic_cardtype], voltage); + + if (pcic_voltage == PC_CARD_VOLTAGE_04h || pcic_cardtype != PC_CARD_TYPE_PCMCIA) + return -1; + + return 0; +} + +static int pcmcia_device_reset(void) +{ + USE_DEV9_REGS; + u16 cstc1, cstc2; + + /* The card must be 16-bit (type 2?) */ + if ((DEV9_REG(DEV9_R_1462) & 0x03) != 0) + return -1; + + DEV9_REG(DEV9_R_147E) = 1; + if (pcic_power(pcic_voltage, 1) < 0) + return -1; + + DEV9_REG(DEV9_R_POWER) = DEV9_REG(DEV9_R_POWER) | 0x02; + DelayThread(500000); + + DEV9_REG(DEV9_R_POWER) = DEV9_REG(DEV9_R_POWER) | 0x01; + DEV9_REG(DEV9_R_1464) = cstc1 = DEV9_REG(DEV9_R_1464); + DEV9_REG(DEV9_R_1466) = cstc2 = DEV9_REG(DEV9_R_1466); + return 0; +} + +static int card_find_manfid(u32 manfid) +{ + USE_DEV9_REGS; + USE_SPD_REGS; + u32 spdaddr, spdend, next, tuple; + u8 hdr, ofs; + + DEV9_REG(DEV9_R_1460) = 2; + _sw(0x1a00bb, SSBUS_R_1418); + + /* Scan the card for the MANFID tuple. */ + spdaddr = 0; + spdend = 0x1000; + /* I hate this code, and it hates me. */ + while (spdaddr < spdend) { + hdr = SPD_REG8(spdaddr) & 0xff; + spdaddr += 2; + if (!hdr) + continue; + if (hdr == 0xff) + break; + if (spdaddr >= spdend) + goto error; + + ofs = SPD_REG8(spdaddr) & 0xff; + spdaddr += 2; + if (ofs == 0xff) + break; + + next = spdaddr + (ofs * 2); + if (next >= spdend) + goto error; + + if (hdr == 0x20) { + if ((spdaddr + 8) >= spdend) + goto error; + + tuple = (SPD_REG8(spdaddr + 2) << 24) | + (SPD_REG8(spdaddr) << 16) | + (SPD_REG8(spdaddr + 6) << 8) | + SPD_REG8(spdaddr + 4); + if (manfid == tuple) + return 0; + M_PRINTF("MANFID 0x%08lx doesn't match expected 0x%08lx\n", + tuple, manfid); + return -1; + } + spdaddr = next; + } + + M_PRINTF("MANFID 0x%08lx not found.\n", manfid); + return -1; +error: + M_PRINTF("Invalid tuples at offset 0x%08lx.\n", spdaddr - SPD_REGBASE); + return -1; +} + +static int pcmcia_intr(void *unused) +{ + USE_AIF_REGS; + USE_DEV9_REGS; + u16 cstc1, cstc2; + + cstc1 = DEV9_REG(DEV9_R_1464); + cstc2 = DEV9_REG(DEV9_R_1466); + + if (using_aif) { + if (aif_regs[AIF_INTSR] & AIF_INTR_PCMCIA) + aif_regs[AIF_INTCL] = AIF_INTR_PCMCIA; + else + return 0; /* Unknown interrupt. */ + } + + /* Acknowledge the interrupt. */ + DEV9_REG(DEV9_R_1464) = cstc1; + DEV9_REG(DEV9_R_1466) = cstc2; + if (cstc1 & 0x03 || cstc2 & 0x03) { /* Card removed or added? */ + if (p_dev9_intr_cb) + p_dev9_intr_cb(1); + + /* Shutdown the card. */ + DEV9_REG(DEV9_R_POWER) = 0; + DEV9_REG(DEV9_R_1474) = 0; + + pcmcia_device_probe(); + } + if (cstc1 & 0x80 || cstc2 & 0x80) { + if (p_dev9_intr_cb) + p_dev9_intr_cb(0); + } + + DEV9_REG(DEV9_R_147E) = 1; + DEV9_REG(DEV9_R_147E) = 0; + return 1; +} + +static int pcmcia_init(int sema_attr) +{ + USE_DEV9_REGS; + USE_AIF_REGS; + int *mode; + int flags; + u16 cstc1, cstc2; + + _sw(0x51011, SSBUS_R_1420); + _sw(0x1a00bb, SSBUS_R_1418); + _sw(0xef1a3043, SSBUS_R_141c); + + /* If we are a T10K, then we go through AIF. */ + if ((mode = QueryBootMode(6)) != NULL) { + if ((*(u16 *)mode & 0xfe) == 0x60) { + M_PRINTF("T10K detected.\n"); + + if (aif_regs[AIF_IDENT] == 0xa1) { + aif_regs[AIF_INTEN] = AIF_INTR_PCMCIA; + using_aif = 1; + } else { + M_PRINTF("AIF not detected.\n"); + return 1; + } + } + } + + if (DEV9_REG(DEV9_R_POWER) == 0) { + DEV9_REG(DEV9_R_POWER) = 0; + DEV9_REG(DEV9_R_147E) = 1; + DEV9_REG(DEV9_R_1460) = 0; + DEV9_REG(DEV9_R_1474) = 0; + DEV9_REG(DEV9_R_1464) = cstc1 = DEV9_REG(DEV9_R_1464); + DEV9_REG(DEV9_R_1466) = cstc2 = DEV9_REG(DEV9_R_1466); + DEV9_REG(DEV9_R_1468) = 0x10; + DEV9_REG(DEV9_R_146A) = 0x90; + DEV9_REG(DEV9_R_147C) = 1; + DEV9_REG(DEV9_R_147A) = DEV9_REG(DEV9_R_147C); + + pcic_voltage = pcic_get_voltage(); + pcic_cardtype = pcic_get_cardtype(); + + if (speed_device_init() != 0) + return 1; + } else { + _sw(0xe01a3043, SSBUS_R_1418); + } + + if (dev9_init(sema_attr) != 0) + return 1; + + CpuSuspendIntr(&flags); + RegisterIntrHandler(IOP_IRQ_DEV9, 1, &pcmcia_intr, NULL); + EnableIntr(IOP_IRQ_DEV9); + CpuResumeIntr(flags); + + DEV9_REG(DEV9_R_147E) = 0; + + if (RegisterLibraryEntries(&_exp_dev9) != 0) + return 1; + + M_PRINTF("CXD9566 (PCMCIA) driver start.\n"); + return 0; +} + +static void expbay_set_stat(int stat) +{ + USE_DEV9_REGS; + DEV9_REG(DEV9_R_1464) = stat & 0x3f; +} + +static int expbay_device_probe(void) +{ + USE_DEV9_REGS; + return (DEV9_REG(DEV9_R_1462) & 0x01) ? -1 : 0; +} + +static int expbay_device_reset(void) +{ + USE_DEV9_REGS; + + if (expbay_device_probe() < 0) + return -1; + + DEV9_REG(DEV9_R_POWER) = (DEV9_REG(DEV9_R_POWER) & ~1) | 0x04; // power on + DelayThread(500000); + + DEV9_REG(DEV9_R_1460) = DEV9_REG(DEV9_R_1460) | 0x01; + DEV9_REG(DEV9_R_POWER) = DEV9_REG(DEV9_R_POWER) | 0x01; + DelayThread(500000); + return 0; +} + +static int expbay_intr(void *unused) +{ + USE_DEV9_REGS; + + if (p_dev9_intr_cb) + p_dev9_intr_cb(0); + + if (!dev9_has_dvr_capability) { + DEV9_REG(DEV9_R_1466) = 1; + } + DEV9_REG(DEV9_R_1466) = 0; + return 1; +} + +static int expbay_init(int sema_attr) +{ + USE_DEV9_REGS; + USE_SPD_REGS; + int flags; + + _sw(0x51011, SSBUS_R_1420); + _sw(0xe01a3043, SSBUS_R_1418); + _sw(0xef1a3043, SSBUS_R_141c); + + if ((DEV9_REG(DEV9_R_POWER) & 0x04) == 0) { // if not already powered + DEV9_REG(DEV9_R_1466) = 1; + DEV9_REG(DEV9_R_1464) = 0; + DEV9_REG(DEV9_R_1460) = DEV9_REG(DEV9_R_1464); + + if (speed_device_init() != 0) + return 1; + } + + /* Disable control of LED 2 and PIO 3 if the dev9 device does not have DVR capabilities. */ + dev9_has_dvr_capability = (SPD_REG16(SPD_R_REV_3) & SPD_CAPS_DVR) ? 1 : 0; + + if (dev9_init(sema_attr) != 0) + return 1; + + CpuSuspendIntr(&flags); + RegisterIntrHandler(IOP_IRQ_DEV9, 1, &expbay_intr, NULL); + EnableIntr(IOP_IRQ_DEV9); + CpuResumeIntr(flags); + + DEV9_REG(DEV9_R_1466) = 0; + + if (RegisterLibraryEntries(&_exp_dev9) != 0) + return 1; + + M_PRINTF("CXD9611 (SSBUS Buffer) driver start.\n"); + return 0; +} diff --git a/sps2_basement/hardware/dev9/extflash/Makefile b/sps2_basement/hardware/dev9/extflash/Makefile new file mode 100644 index 0000000..8920619 --- /dev/null +++ b/sps2_basement/hardware/dev9/extflash/Makefile @@ -0,0 +1,18 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN_ALTNAMES = flash.irx + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/dev9/include + +IOP_OBJS = extflash.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dev9/extflash/README b/sps2_basement/hardware/dev9/extflash/README new file mode 100644 index 0000000..b83727d --- /dev/null +++ b/sps2_basement/hardware/dev9/extflash/README @@ -0,0 +1,29 @@ +extflash - Flash interface via expansion port. + +Copyright (c) 2003 Marcus R. Brown +-- + +The PS2 50000 series BIOS introduced a new expansion (Dev9) device driver for +NAND (serial) flash and a method for booting off of this device - the "External +Flash ROM". This flash is the same type as the 64Mbit flash found in the PS2 +memory card. As far as I know, these chips come from either Samsung or Toshiba +(datasheets can be found on their semiconductor websites). Toshiba part numbers +are listed below. + + Part No. Size + TC48V64BFT 64Mbit (8MB) + TC58128AFT 128Mbit (16MB) + TC58256AFT 256Mbit (32MB) + TC58512FT 512Mbit (64MB) + TH58100FT 1024Mbit (128MB) + +These devices are accessed via SmartMedia commands. + +Apparently these devices are formatted using MCFS, the filesystem used on +normal PS2 memory cards. The OSD can boot from these devices the same way it +can boot from the HDD. + +Why SCEI would include this driver within the 50k BIOS remains a mystery. It's +possible that this is the "firmware update" inside the PSX. I wrote the +extflash driver to get a better understanding of the hardware interface to +these devices. diff --git a/sps2_basement/hardware/dev9/extflash/include/fls.h b/sps2_basement/hardware/dev9/extflash/include/fls.h new file mode 100644 index 0000000..d2f28f1 --- /dev/null +++ b/sps2_basement/hardware/dev9/extflash/include/fls.h @@ -0,0 +1,45 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Expansion bay flash driver. + * Supported in ROM in SCPH-5xxxx models and integrated in DESR-xxxx models. + */ + +#ifndef __FLS_H__ +#define __FLS_H__ + +typedef struct { + u32 id; + u32 mbits; + u32 page_bytes; /* bytes/page */ + u32 block_pages; /* pages/block */ + u32 blocks; +} flash_info_t; + +extern int flash_detect(void); +extern int flash_device_reset(void); +extern int flash_get_info(flash_info_t *info); +extern int flash_page_erase(flash_info_t *info, u32 page); +extern int flash_page_read(flash_info_t *info, u32 page, u32 count, void *buf); +extern int flash_page_write(flash_info_t *info, u32 page, void *buf); + +#define fls_IMPORTS_start DECLARE_IMPORT_TABLE(fls, 1, 1) +#define fls_IMPORTS_end END_IMPORT_TABLE + +#define I_flash_detect DECLARE_IMPORT(4, flash_detect) +#define I_flash_device_reset DECLARE_IMPORT(5, flash_device_reset) +#define I_flash_get_info DECLARE_IMPORT(6, flash_get_info) +#define I_flash_page_erase DECLARE_IMPORT(7, flash_page_erase) +#define I_flash_page_read DECLARE_IMPORT(8, flash_page_read) +#define I_flash_page_write DECLARE_IMPORT(9, flash_page_write) + +#endif diff --git a/sps2_basement/hardware/dev9/extflash/src/exports.tab b/sps2_basement/hardware/dev9/extflash/src/exports.tab new file mode 100644 index 0000000..efedb5d --- /dev/null +++ b/sps2_basement/hardware/dev9/extflash/src/exports.tab @@ -0,0 +1,19 @@ +DECLARE_EXPORT_TABLE(fls, 1, 1) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(flash_detect) + DECLARE_EXPORT(flash_device_reset) + DECLARE_EXPORT(flash_get_info) + DECLARE_EXPORT(flash_page_erase) + DECLARE_EXPORT(flash_page_read) + DECLARE_EXPORT(flash_page_write) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_start) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/dev9/extflash/src/extflash.c b/sps2_basement/hardware/dev9/extflash/src/extflash.c new file mode 100644 index 0000000..794efc5 --- /dev/null +++ b/sps2_basement/hardware/dev9/extflash/src/extflash.c @@ -0,0 +1,362 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# NAND Flash via Dev9 driver. +*/ + +#include "types.h" +#include "defs.h" +#include "irx.h" + +#include "loadcore.h" +#include "thbase.h" +#include "stdio.h" +#include "sysclib.h" + +#include "dev9regs.h" +#include "speedregs.h" + +#include "fls.h" + +#define MODNAME "flash" +#define M_PRINTF(format, args...) \ + printf(MODNAME ": " format, ## args) + +IRX_ID(MODNAME, 0, 0); + +#define FLASH_ID_64MBIT 0xe6 +#define FLASH_ID_128MBIT 0x73 +#define FLASH_ID_256MBIT 0x75 +#define FLASH_ID_512MBIT 0x76 +#define FLASH_ID_1024MBIT 0x79 + +/* SmartMedia commands. */ +#define SM_CMD_READ1 0x00 +#define SM_CMD_READ2 0x01 +#define SM_CMD_READ3 0x50 +#define SM_CMD_RESET 0xff +#define SM_CMD_WRITEDATA 0x80 +#define SM_CMD_PROGRAMPAGE 0x10 +#define SM_CMD_ERASEBLOCK 0x60 +#define SM_CMD_ERASECONFIRM 0xd0 +#define SM_CMD_GETSTATUS 0x70 +#define SM_CMD_READID 0x90 + +static flash_info_t devices[] = { + { FLASH_ID_64MBIT, 64, 528, 16, 1024 }, + { FLASH_ID_128MBIT, 128, 528, 32, 1024 }, + { FLASH_ID_256MBIT, 256, 528, 32, 2048 }, + { FLASH_ID_512MBIT, 512, 528, 32, 4096 }, + { FLASH_ID_1024MBIT, 1024, 528, 32, 8192 } +}; +#define NUM_DEVICES (sizeof(devices)/sizeof(flash_info_t)) + +static iop_sys_clock_t timeout; +static u32 timeout_cb(void *); + +extern struct irx_export_table _exp_fls; + +int _start(int argc, char *argv[]) +{ + if (flash_detect() < 0) + return MODULE_NO_RESIDENT_END; + + return RegisterLibraryEntries(&_exp_fls) != 0; +} + +/* #4: Check to see if flash is connected to the expansion bay. */ +int flash_detect(void) +{ + USE_DEV9_REGS; + USE_SPD_REGS; + u16 rev; + + if ((DEV9_REG(DEV9_R_REV) & 0xf0) != DEV9_DEV9C_9611) { + M_PRINTF("CXD9611 required for flash interface.\n"); + return -1; + } + + /* Check bit 5 of the revision register. */ + if ((rev = SPD_REG16(SPD_R_REV_3)) & SPD_CAPS_FLASH) { + M_PRINTF("Detected flash (rev3 0x%02x).\n", rev); + return 0; + } + + M_PRINTF("No flash detected (rev3 0x%02x).\n", rev); + return -1; +} + +/* #5: Reset the device. */ +int flash_device_reset(void) +{ + USE_SPD_REGS; + u32 has_timedout = 0; + u16 tmp __attribute__((unused)); + + SPD_REG16(0x480c) = 0x100; + SPD_REG16(0x4804) = SM_CMD_RESET; + tmp = SPD_REG16(0x480c); + tmp = SPD_REG16(0x480c); + + SetAlarm(&timeout, (void *)timeout_cb, &has_timedout); + + while ((SPD_REG16(0x480c) & 0x01) == 0) { + if (has_timedout) { + if (SPD_REG16(0x480c) & 0x01) + break; + + M_PRINTF("Device erase: timed out.\n"); + return -3; + } + } + + CancelAlarm((void *)timeout_cb, &has_timedout); + + SPD_REG16(0x4804) = SM_CMD_GETSTATUS; + if (SPD_REG16(0x4814) & 0x01) { + M_PRINTF("Device erase: status error.\n"); + return -6; + } + + SPD_REG16(0x480c) = 0; + return 0; +} + +/* #6: Get information about the attached device. */ +int flash_get_info(flash_info_t *info) +{ + USE_SPD_REGS; + int i; + u16 tmp __attribute__((unused)), id; + + SPD_REG16(0x480c) = 0x100; + SPD_REG16(0x4804) = SM_CMD_READID; + SPD_REG16(0x4808) = 0; + tmp = SPD_REG16(0x480c); + tmp = SPD_REG16(0x4814); + id = SPD_REG16(0x4814); + SPD_REG16(0x480c) = 0; + + memset(info, 0, sizeof(flash_info_t)); + + for (i = 0; i < NUM_DEVICES; i++) { + if (id != devices[i].id) + continue; + + memcpy(info, &devices[i], sizeof(flash_info_t)); + M_PRINTF("Device: ID 0x%02x, %ld Mbit, %ld bytes/page, %ld pages/block, %ld blocks total.\n", + id, info->mbits, info->page_bytes, info->block_pages, info->blocks); + return 0; + } + + return -5; +} + +/* Set the page offset register based on the type of flash (id). */ +static void flash_set_page(u32 id, u32 pageofs) +{ + USE_SPD_REGS; + + switch (id) { + case FLASH_ID_64MBIT: + SPD_REG16(0x4808) = ((pageofs >> 9) & 0xff) | 0x100; + SPD_REG16(0x4808) = ((pageofs >> 17) & 0x3f); + break; + case FLASH_ID_128MBIT: + SPD_REG16(0x4808) = ((pageofs >> 9) & 0xff) | 0x100; + SPD_REG16(0x4808) = ((pageofs >> 17) & 0x7f); + break; + case FLASH_ID_256MBIT: + SPD_REG16(0x4808) = ((pageofs >> 9) & 0xff) | 0x100; + SPD_REG16(0x4808) = ((pageofs >> 17) & 0xff); + break; + case FLASH_ID_512MBIT: + SPD_REG16(0x4808) = ((pageofs >> 17) & 0xff) | 0x100; + SPD_REG16(0x4808) = ((pageofs >> 25) & 0x01); + break; + case FLASH_ID_1024MBIT: + SPD_REG16(0x4808) = ((pageofs >> 17) & 0xff) | 0x100; + SPD_REG16(0x4808) = ((pageofs >> 25) & 0x02); + break; + } +} + +/* #7: Erase a page. */ +int flash_page_erase(flash_info_t *info, u32 page) +{ + USE_SPD_REGS; + u32 pageofs = page * 512; + u32 has_timedout = 0; + u16 tmp __attribute__((unused)); + + SPD_REG16(0x480c) = 0x180; + SPD_REG16(0x4804) = SM_CMD_ERASEBLOCK; + + flash_set_page(info->id, pageofs); + + SPD_REG16(0x4804) = SM_CMD_ERASECONFIRM; + tmp = SPD_REG16(0x480c); + tmp = SPD_REG16(0x480c); + + SetAlarm(&timeout, (void *)timeout_cb, &has_timedout); + + while ((SPD_REG16(0x480c) & 0x01) == 0) { + if (has_timedout) { + if (SPD_REG16(0x480c) & 0x01) + break; + + M_PRINTF("Page erase: timed out.\n"); + return -3; + } + } + + CancelAlarm((void *)timeout_cb, &has_timedout); + + SPD_REG16(0x4804) = SM_CMD_GETSTATUS; + if (SPD_REG16(0x4814) & 0x01) { + M_PRINTF("Page erase: status error.\n"); + return -6; + } + + SPD_REG16(0x480c) = 0; + return 0; +} + +/* #8: Read one or more pages. You can select how much of the page you want to + * read by setting the page_bytes member of the info struct. The default set + * by the driver is 528 bytes: + * Bytes 0 - 511: Data + * Bytes 512 - 527: Metadata? + * + * You can also set page_bytes to 512 or 16 bytes. */ +int flash_page_read(flash_info_t *info, u32 page, u32 count, void *buf) +{ + USE_SPD_REGS; + u32 *buf_w; + u16 *buf_h; + int i, j; + u32 byteofs, pageofs = page * 512; + u32 has_timedout; + u16 tmp __attribute__((unused)), func = 0x100; + + if (info->page_bytes == 512) + func = 0x1100; + + SPD_REG16(0x480c) = func; + + if (info->page_bytes == 16) { + SPD_REG16(0x4804) = SM_CMD_READ3; + byteofs = pageofs & 0x0f; + } else { + SPD_REG16(0x4804) = SM_CMD_READ1; + byteofs = pageofs & 0x1ff; + } + + SPD_REG16(0x4808) = (byteofs & 0xff) | 0x100; + /* Set the rest of the page info. */ + flash_set_page(info->id, pageofs); + + buf_w = (u32 *)buf; + buf_h = (u16 *)buf; + + for (i = 0; i < count; i++) { + tmp = SPD_REG16(0x480c); + tmp = SPD_REG16(0x480c); + + has_timedout = 0; + SetAlarm(&timeout, (void *)timeout_cb, &has_timedout); + + while ((SPD_REG16(0x480c) & 0x01) == 0) { + if (has_timedout) { + if (SPD_REG16(0x480c) & 0x01) + break; + + M_PRINTF("Page read: timed out.\n"); + return -3; + } + } + + CancelAlarm((void *)timeout_cb, &has_timedout); + + SPD_REG16(0x480c) = func | 0x800; + + if (byteofs == 0) { + /* 32-bit copy. */ + for (j = 0; j < (info->page_bytes / 4); j++) + *buf_w++ = SPD_REG32(0x4800); + } else { + /* 16-bit copy. */ + for (j = (byteofs + (byteofs >> 31)) / 2; j < (info->page_bytes / 2); j++) + *buf_h++ = SPD_REG16(0x4800); + } + + byteofs = 0; + SPD_REG16(0x480c) = func; + } + + SPD_REG16(0x480c) = 0; + return 0; +} + +/* #9: Write a single page. + * Bytes 0 - 511: Data + * Bytes 512 - 527: Metadata? */ +int flash_page_write(flash_info_t *info, u32 page, void *buf) +{ + USE_SPD_REGS; + u16 *buf_h = buf; + int i; + u32 pageofs = page * 512; + u32 has_timedout = 0; + u16 tmp __attribute__((unused)); + + SPD_REG16(0x480c) = 0x180; + SPD_REG16(0x4804) = SM_CMD_WRITEDATA; + + SPD_REG16(0x4808) = 0x100; + flash_set_page(info->id, pageofs); + + for (i = 0; i < (info->page_bytes / 2); i++) + SPD_REG16(0x4800) = *buf_h++; + + SPD_REG16(0x4804) = SM_CMD_PROGRAMPAGE; + tmp = SPD_REG16(0x480c); + tmp = SPD_REG16(0x480c); + + SetAlarm(&timeout, (void *)timeout_cb, &has_timedout); + + while ((SPD_REG16(0x480c) & 0x01) == 0) { + if (has_timedout) { + if (SPD_REG16(0x480c) & 0x01) + break; + + M_PRINTF("Page write: timed out.\n"); + return -3; + } + } + + CancelAlarm((void *)timeout_cb, &has_timedout); + + SPD_REG16(0x4804) = SM_CMD_GETSTATUS; + if (SPD_REG16(0x4814) & 0x01) { + M_PRINTF("Page write: status error.\n"); + return -6; + } + + SPD_REG16(0x480c) = 0; + return 0; +} + +static u32 timeout_cb(void *arg) +{ + u32 *has_timedout = (u32 *)arg; + + *has_timedout = 1; + return 0; +} diff --git a/sps2_basement/hardware/dev9/extflash/src/imports.lst b/sps2_basement/hardware/dev9/extflash/src/imports.lst new file mode 100644 index 0000000..b0b5717 --- /dev/null +++ b/sps2_basement/hardware/dev9/extflash/src/imports.lst @@ -0,0 +1,17 @@ +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_SetAlarm +I_CancelAlarm +thbase_IMPORTS_end + +sysclib_IMPORTS_start +I_memcpy +I_memset +sysclib_IMPORTS_end diff --git a/sps2_basement/hardware/dev9/extflash/src/irx_imports.h b/sps2_basement/hardware/dev9/extflash/src/irx_imports.h new file mode 100644 index 0000000..9f87717 --- /dev/null +++ b/sps2_basement/hardware/dev9/extflash/src/irx_imports.h @@ -0,0 +1,34 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "dev9.h" +#include "dmacman.h" +#include "intrman.h" +#include "iomanX.h" +#include "libsd.h" +#include "loadcore.h" +#include "stdio.h" +#include "sysclib.h" +#include "sysmem.h" +#include "thbase.h" +#include "thevent.h" +#include "thmsgbx.h" +#include "thsemap.h" +#include "vblank.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dev9/hdpro_atad/Makefile b/sps2_basement/hardware/dev9/hdpro_atad/Makefile new file mode 100644 index 0000000..172ba15 --- /dev/null +++ b/sps2_basement/hardware/dev9/hdpro_atad/Makefile @@ -0,0 +1,18 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN ?= hdproatad.irx + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/atad/include + +IOP_OBJS = hdproatad.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dev9/hdpro_atad/src/exports.tab b/sps2_basement/hardware/dev9/hdpro_atad/src/exports.tab new file mode 100644 index 0000000..976c219 --- /dev/null +++ b/sps2_basement/hardware/dev9/hdpro_atad/src/exports.tab @@ -0,0 +1,32 @@ +/* We conform to the 1.3 version of atad.irx exports. + Note: most exports were removed because hdpro_io_start and hdpro_io_end must be caused around the code that accesses HDPro. */ + +DECLARE_EXPORT_TABLE(atad, 1, 3) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(shutdown) + DECLARE_EXPORT(_retonly) + + DECLARE_EXPORT(ata_get_devinfo) +/*05*/ DECLARE_EXPORT(_unsupported) + DECLARE_EXPORT(_unsupported) + DECLARE_EXPORT(_unsupported) + DECLARE_EXPORT(_unsupported) + DECLARE_EXPORT(ata_device_sector_io) +/*10*/ DECLARE_EXPORT(_unsupported) + DECLARE_EXPORT(ata_device_sce_sec_unlock) + DECLARE_EXPORT(_unsupported) + DECLARE_EXPORT(_unsupported) + DECLARE_EXPORT(_unsupported) +/*15*/ DECLARE_EXPORT(_unsupported) + DECLARE_EXPORT(_unsupported) + DECLARE_EXPORT(ata_device_flush_cache) + DECLARE_EXPORT(_unsupported) + +END_EXPORT_TABLE + +void _retonly() {} + +int _unsupported(void) { + return -1; +} diff --git a/sps2_basement/hardware/dev9/hdpro_atad/src/hdproatad.c b/sps2_basement/hardware/dev9/hdpro_atad/src/hdproatad.c new file mode 100644 index 0000000..2d51fa2 --- /dev/null +++ b/sps2_basement/hardware/dev9/hdpro_atad/src/hdproatad.c @@ -0,0 +1,984 @@ +/* + Copyright 2011, jimmikaelkael + Licenced under Academic Free License version 3.0 + + ATA Driver for the HD Pro Kit, based on original & updated ATAD from ps2sdk: + + Copyright (c) 2003 Marcus R. Brown + Licenced under Academic Free License version 2.0 + Review ps2sdk README & LICENSE files for further details. + + ATA device driver. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define MODNAME "hdcombo_driver" +IRX_ID(MODNAME, 1, 1); + +#define M_PRINTF(format, args...) \ + printf(MODNAME ": " format, ## args) + +#define BANNER "ATA device driver for HD Pro Kit %s\n" +#define VERSION "v1.0" + +#define ATA_XFER_MODE_PIO 0x08 + +#define ATA_EV_TIMEOUT 1 +#define ATA_EV_COMPLETE 2 //Unused as there is no completion interrupt + +// HD Pro Kit is mapping the 1st word in ROM0 seg as a main ATA controller, +// The pseudo ATA controller registers are accessed (input/ouput) by writing +// an id to the main ATA controller (id specific to HDpro, see registers id below). +#define HDPROreg_IO8 (*(vu8 *)0xBFC00000) +#define HDPROreg_IO32 (*(vu32 *)0xBFC00000) + +#define CDVDreg_STATUS (*(vu8 *)0xBF40200A) + +// Pseudo ATA controller registers id - Output +#define ATAreg_CONTROL_RD 0x68 +#define ATAreg_SELECT_RD 0x70 +#define ATAreg_STATUS_RD 0xf0 +#define ATAreg_ERROR_RD 0x90 +#define ATAreg_NSECTOR_RD 0x50 +#define ATAreg_SECTOR_RD 0xd0 +#define ATAreg_LCYL_RD 0x30 +#define ATAreg_HCYL_RD 0xb0 +#define ATAreg_DATA_RD 0x41 + +// Pseudo ATA controller registers id - Input +#define ATAreg_CONTROL_WR 0x6a +#define ATAreg_SELECT_WR 0x72 +#define ATAreg_COMMAND_WR 0xf2 +#define ATAreg_FEATURE_WR 0x92 +#define ATAreg_NSECTOR_WR 0x52 +#define ATAreg_SECTOR_WR 0xd2 +#define ATAreg_LCYL_WR 0x32 +#define ATAreg_HCYL_WR 0xb2 +#define ATAreg_DATA_WR 0x12 + +static int ata_devinfo_init = 0; +static int ata_evflg = -1; + +/* Local device info kept for drives 0 and 1. */ +static ata_devinfo_t atad_devinfo[2]; + +/* Data returned from DEVICE IDENTIFY is kept here. Also, this is used by the + security commands to set and unlock the password. */ +static u16 ata_param[256]; + +/* ATA command info. */ +typedef struct _ata_cmd_info { + u8 command; + u8 type; +} ata_cmd_info_t; + +//DMA commands have been removed, since there is no support for DMA. +static const ata_cmd_info_t ata_cmd_table[] = { + {ATA_C_NOP,1}, + {ATA_C_CFA_REQUEST_EXTENDED_ERROR_CODE,1}, + {ATA_C_DEVICE_RESET,5}, + {ATA_C_READ_SECTOR,2}, + {ATA_C_READ_SECTOR_EXT,0x82}, + {ATA_C_WRITE_SECTOR,3}, + {ATA_C_WRITE_LONG,8}, + {ATA_C_WRITE_SECTOR_EXT,0x83}, + {ATA_C_CFA_WRITE_SECTORS_WITHOUT_ERASE,3}, + {ATA_C_READ_VERIFY_SECTOR,1}, + {ATA_C_READ_VERIFY_SECTOR_EXT,0x81}, + {ATA_C_SEEK,1}, + {ATA_C_CFA_TRANSLATE_SECTOR,2}, + {ATA_C_SCE_SECURITY_CONTROL,7}, + {ATA_C_EXECUTE_DEVICE_DIAGNOSTIC,6}, + {ATA_C_INITIALIZE_DEVICE_PARAMETERS,1}, + {ATA_C_DOWNLOAD_MICROCODE,3}, + {ATA_C_IDENTIFY_PACKET_DEVICE,2}, + {ATA_C_SMART,7}, + {ATA_C_CFA_ERASE_SECTORS,1}, + {ATA_C_READ_MULTIPLE,2}, + {ATA_C_WRITE_MULTIPLE,3}, + {ATA_C_SET_MULTIPLE_MODE,1}, + {ATA_C_CFA_WRITE_MULTIPLE_WITHOUT_ERASE,3}, + {ATA_C_GET_MEDIA_STATUS,1}, + {ATA_C_MEDIA_LOCK,1}, + {ATA_C_MEDIA_UNLOCK,1}, + {ATA_C_STANDBY_IMMEDIATE,1}, + {ATA_C_IDLE_IMMEDIATE,1}, + {ATA_C_STANDBY,1}, + {ATA_C_IDLE,1}, + {ATA_C_READ_BUFFER,2}, + {ATA_C_CHECK_POWER_MODE,1}, + {ATA_C_SLEEP,1}, + {ATA_C_FLUSH_CACHE,1}, + {ATA_C_WRITE_BUFFER,3}, + {ATA_C_FLUSH_CACHE_EXT,1}, + {ATA_C_IDENTIFY_DEVICE,2}, + {ATA_C_MEDIA_EJECT,1}, + {ATA_C_SET_FEATURES,1}, + {ATA_C_SECURITY_SET_PASSWORD,3}, + {ATA_C_SECURITY_UNLOCK,3}, + {ATA_C_SECURITY_ERASE_PREPARE,1}, + {ATA_C_SECURITY_ERASE_UNIT,3}, + {ATA_C_SECURITY_FREEZE_LOCK,1}, + {ATA_C_SECURITY_DISABLE_PASSWORD,3}, + {ATA_C_READ_NATIVE_MAX_ADDRESS,1}, + {ATA_C_SET_MAX_ADDRESS,1} +}; +#define ATA_CMD_TABLE_SIZE (sizeof ata_cmd_table/sizeof(ata_cmd_info_t)) + +static const ata_cmd_info_t smart_cmd_table[] = { + {ATA_S_SMART_READ_DATA,2}, + {ATA_S_SMART_ENABLE_DISABLE_AUTOSAVE,1}, + {ATA_S_SMART_SAVE_ATTRIBUTE_VALUES,1}, + {ATA_S_SMART_EXECUTE_OFF_LINE,1}, + {ATA_S_SMART_READ_LOG,2}, + {ATA_S_SMART_WRITE_LOG,3}, + {ATA_S_SMART_ENABLE_OPERATIONS,1}, + {ATA_S_SMART_DISABLE_OPERATIONS,1}, + {ATA_S_SMART_RETURN_STATUS,1} +}; +#define SMART_CMD_TABLE_SIZE (sizeof smart_cmd_table/sizeof(ata_cmd_info_t)) + +/* This is the state info tracked between ata_io_start() and ata_io_finish(). */ +typedef struct _ata_cmd_state { + s32 type; /* The ata_cmd_info_t type field. */ + union { + void *buf; + u8 *buf8; + u16 *buf16; + }; + u32 blkcount; /* The number of 512-byte blocks (sectors) to transfer. */ +} ata_cmd_state_t; + +static ata_cmd_state_t atad_cmd_state; + +static int hdpro_io_active = 0; +static int intr_suspended = 0; +static int intr_state; + +static int hdpro_io_start(void); +static int hdpro_io_finish(void); +static void hdpro_io_write(u8 cmd, u16 val); +static int hdpro_io_read(u8 cmd); +static int ata_bus_reset(void); +static int ata_init_devices(ata_devinfo_t *devinfo); +static int gen_ata_wait_busy(int bits); + +extern struct irx_export_table _exp_atad; + +static unsigned int ata_alarm_cb(void *unused) +{ + iSetEventFlag(ata_evflg, ATA_EV_TIMEOUT); + return 0; +} + +static void suspend_intr(void) +{ + if (!intr_suspended) { + CpuSuspendIntr(&intr_state); + + intr_suspended = 1; + } +} + +static void resume_intr(void) +{ + if (intr_suspended) { + CpuResumeIntr(intr_state); + + intr_suspended = 0; + } +} + +static int ata_create_event_flag(void) { + iop_event_t event; + + event.attr = EA_SINGLE; //In v1.04, EA_MULTI was specified. + event.bits = 0; + return CreateEventFlag(&event); +} + +int _start(int argc, char *argv[]) +{ + int res = MODULE_NO_RESIDENT_END; + + printf(BANNER, VERSION); + + if (!hdpro_io_start()) { + M_PRINTF("Failed to detect HD Pro, exiting.\n"); + goto out; + } + + hdpro_io_finish(); + + if ((ata_evflg = ata_create_event_flag()) < 0) { + M_PRINTF("Couldn't create event flag, exiting.\n"); + goto out; + } + + if ((res = RegisterLibraryEntries(&_exp_atad)) != 0) { + M_PRINTF("Library is already registered, exiting.\n"); + goto out; + } + + res = MODULE_RESIDENT_END; + M_PRINTF("Driver loaded.\n"); + +out: + return res; +} + +int shutdown(void) +{ + return 0; +} + +/* Export 8 */ +int ata_get_error(void) +{ + return hdpro_io_read(ATAreg_ERROR_RD) & 0xff; +} + +#define ATA_WAIT_BUSY 0x80 +#define ATA_WAIT_BUSBUSY 0x88 + +#define ata_wait_busy() gen_ata_wait_busy(ATA_WAIT_BUSY) +#define ata_wait_bus_busy() gen_ata_wait_busy(ATA_WAIT_BUSBUSY) + +/* 0x80 for busy, 0x88 for bus busy. + In the original ATAD, the busy and bus-busy functions were separate, but similar. */ +static int gen_ata_wait_busy(int bits) +{ + int i, didx, delay; + int res = 0; + + for (i = 0; i < 80; i++) { + + hdpro_io_start(); + + u16 r_control = hdpro_io_read(ATAreg_CONTROL_RD); + + hdpro_io_finish(); + + if (r_control == 0xffff) //Differs from the normal ATAD here. + return ATA_RES_ERR_TIMEOUT; + + if (!(r_control & bits)) + goto out; + + didx = i / 10; + switch (didx) { + case 0: + continue; + case 1: + delay = 100; + break; + case 2: + delay = 1000; + break; + case 3: + delay = 10000; + break; + case 4: + delay = 100000; + break; + default: + delay = 1000000; + + } + + DelayThread(delay); + } + + res = ATA_RES_ERR_TIMEOUT; + M_PRINTF("Timeout while waiting on busy (0x%02x).\n", bits); + +out: + hdpro_io_start(); + + return res; +} + +//Must be called before any I/O is done with HDPro +static int hdpro_io_start(void) +{ + if (hdpro_io_active) + return 0; + + hdpro_io_active = 0; + + suspend_intr(); + + // HD Pro IO start commands sequence + HDPROreg_IO8 = 0x72; + CDVDreg_STATUS = 0; + HDPROreg_IO8 = 0x34; + CDVDreg_STATUS = 0; + HDPROreg_IO8 = 0x61; + CDVDreg_STATUS = 0; + unsigned int res = HDPROreg_IO8; + CDVDreg_STATUS = 0; + + resume_intr(); + + // check result + if ((res & 0xff) == 0xe7) + hdpro_io_active = 1; + + return hdpro_io_active; +} + +//Must be called after I/O is done with HDPro +static int hdpro_io_finish(void) +{ + if (!hdpro_io_active) + return 0; + + suspend_intr(); + + // HD Pro IO finish commands sequence + HDPROreg_IO8 = 0xf3; + CDVDreg_STATUS = 0; + + resume_intr(); + + DelayThread(200); + + if (HDPROreg_IO32 == 0x401a7800) // check the 1st in ROM0 seg get + hdpro_io_active = 0; // back to it's original state + + return hdpro_io_active ^ 1; +} + +static void hdpro_io_write(u8 cmd, u16 val) +{ + suspend_intr(); + + // IO write to HD Pro + HDPROreg_IO8 = cmd; + CDVDreg_STATUS = 0; + HDPROreg_IO8 = val; + CDVDreg_STATUS = 0; + HDPROreg_IO8 = (val & 0xffff) >> 8; + CDVDreg_STATUS = 0; + + resume_intr(); +} + +static int hdpro_io_read(u8 cmd) +{ + suspend_intr(); + + // IO read from HD Pro + HDPROreg_IO8 = cmd; + CDVDreg_STATUS = 0; + unsigned int res0 = HDPROreg_IO8; + CDVDreg_STATUS = 0; + unsigned int res1 = HDPROreg_IO8; + CDVDreg_STATUS = 0; + res0 = (res0 & 0xff) | (res1 << 8); + + resume_intr(); + + return res0 & 0xffff; +} + +/* Reset the ATA controller/bus. */ +static int ata_bus_reset(void) +{ + suspend_intr(); + + // HD Pro IO initialization commands sequence + HDPROreg_IO8 = 0x13; + CDVDreg_STATUS = 0; + HDPROreg_IO8 = 0x00; + CDVDreg_STATUS = 0; + + resume_intr(); + + DelayThread(100); + + suspend_intr(); + + HDPROreg_IO8 = 0x13; + CDVDreg_STATUS = 0; + HDPROreg_IO8 = 0x01; + CDVDreg_STATUS = 0; + + resume_intr(); + + DelayThread(3000); + + return ata_wait_busy(); +} + +static int ata_device_select(int device) +{ + int res; + + if ((res = ata_wait_bus_busy()) < 0) + return res; + + /* If the device was already selected, nothing to do. */ + if (((hdpro_io_read(ATAreg_SELECT_RD) >> 4) & 1) == device) + return 0; + + /* Select the device. */ + hdpro_io_write(ATAreg_SELECT_WR, (device & 1) << 4); + res = hdpro_io_read(ATAreg_CONTROL_RD); + + return ata_wait_bus_busy(); +} + +/* Export 6 */ +int ata_io_start(void *buf, u32 blkcount, u16 feature, u16 nsector, u16 sector, u16 lcyl, u16 hcyl, u16 select, u16 command) +{ + iop_sys_clock_t cmd_timeout; + const ata_cmd_info_t *cmd_table; + int i, res, type, cmd_table_size; + int using_timeout, device = (select >> 4) & 1; + u8 searchcmd; + + ClearEventFlag(ata_evflg, 0); + + if (!atad_devinfo[device].exists) + return ATA_RES_ERR_NODEV; + + if ((res = ata_device_select(device)) != 0) + return res; + + /* For the SMART commands, we need to search on the subcommand + specified in the feature register. */ + if (command == ATA_C_SMART) { + cmd_table = smart_cmd_table; + cmd_table_size = SMART_CMD_TABLE_SIZE; + searchcmd = feature; + } else { + cmd_table = ata_cmd_table; + cmd_table_size = ATA_CMD_TABLE_SIZE; + searchcmd = command & 0xff; + } + + type = 0; + for (i = 0; i < cmd_table_size; i++) { + if (searchcmd == cmd_table[i].command) { + type = cmd_table[i].type; + break; + } + } + + if (!(atad_cmd_state.type = type & 0x7F)) + return ATA_RES_ERR_CMD; + + atad_cmd_state.buf = buf; + atad_cmd_state.blkcount = blkcount; + + /* Check that the device is ready if this the appropiate command. */ + if (!(hdpro_io_read(ATAreg_CONTROL_RD) & 0x40)) { + switch (command) { + case ATA_C_DEVICE_RESET: + case ATA_C_EXECUTE_DEVICE_DIAGNOSTIC: + case ATA_C_INITIALIZE_DEVICE_PARAMETERS: + case ATA_C_PACKET: + case ATA_C_IDENTIFY_PACKET_DEVICE: + break; + default: + M_PRINTF("Error: Device %d is not ready.\n", device); + return ATA_RES_ERR_NOTREADY; + } + } + + /* Does this command need a timeout? */ + using_timeout = 0; + switch (type & 0x7F) { + case 1: + case 6: + using_timeout = 1; + break; + //Support for DMA commands (type = 4) is removed because HDPro cannot support DMA. The original HDPro driver still had code for it though. + } + + if (using_timeout) { + cmd_timeout.lo = 0x41eb0000; + cmd_timeout.hi = 0; + + if ((res = SetAlarm(&cmd_timeout, &ata_alarm_cb, NULL)) < 0) + return res; + } + + /* Enable the command completion interrupt. */ + suspend_intr(); + HDPROreg_IO8 = 0x21; + CDVDreg_STATUS = 0; + unsigned int dummy __attribute__((unused)) = HDPROreg_IO8; + CDVDreg_STATUS = 0; + resume_intr(); + dummy = 0; + + /* Finally! We send off the ATA command with arguments. */ + hdpro_io_write(ATAreg_CONTROL_WR, (using_timeout == 0) << 1); + + if(type&0x80) { //For the sake of achieving improved performance, write the registers twice only if required! + /* 48-bit LBA requires writing to the address registers twice, + 24 bits of the LBA address is written each time. + Writing to registers twice does not affect 28-bit LBA since + only the latest data stored in address registers is used. */ + hdpro_io_write(ATAreg_FEATURE_WR, (feature & 0xffff) >> 8); + hdpro_io_write(ATAreg_NSECTOR_WR, (nsector & 0xffff) >> 8); + hdpro_io_write(ATAreg_SECTOR_WR, (sector & 0xffff) >> 8); + hdpro_io_write(ATAreg_LCYL_WR, (lcyl & 0xffff) >> 8); + hdpro_io_write(ATAreg_HCYL_WR, (hcyl & 0xffff) >> 8); + } + + hdpro_io_write(ATAreg_FEATURE_WR, feature & 0xff); + hdpro_io_write(ATAreg_NSECTOR_WR, nsector & 0xff); + hdpro_io_write(ATAreg_SECTOR_WR, sector & 0xff); + hdpro_io_write(ATAreg_LCYL_WR, lcyl & 0xff); + hdpro_io_write(ATAreg_HCYL_WR, hcyl & 0xff); + + hdpro_io_write(ATAreg_SELECT_WR, (select | ATA_SEL_LBA) & 0xff); //In v1.04, LBA was enabled in the ata_device_sector_io function. + hdpro_io_write(ATAreg_COMMAND_WR, command & 0xff); + + return 0; +} + +/* Do a PIO transfer, to or from the device. */ +static int ata_pio_transfer(ata_cmd_state_t *cmd_state) +{ + u8 *buf8; + u16 *buf16; + int i, type; + int res = 0, chk = 0; + u16 status = hdpro_io_read(ATAreg_STATUS_RD); + + if (status & ATA_STAT_ERR) { + M_PRINTF("Error: Command error: status 0x%02x, error 0x%02x.\n", status, ata_get_error()); + return ATA_RES_ERR_IO; + } + + /* DRQ must be set (data request). */ + if (!(status & ATA_STAT_DRQ)) + return ATA_RES_ERR_NODATA; + + type = cmd_state->type; + + if (type == 3 || type == 8) { + /* PIO data out */ + buf16 = cmd_state->buf16; + + HDPROreg_IO8 = 0x43; + CDVDreg_STATUS = 0; + + for (i = 0; i < 256; i++) { + u16 r_data = *buf16; + hdpro_io_write(ATAreg_DATA_WR, r_data); + chk ^= r_data + i; + cmd_state->buf = ++buf16; + } + + u16 out = hdpro_io_read(ATAreg_DATA_RD) & 0xffff; + if (out != (chk & 0xffff)) + return ATA_RES_ERR_IO; + + if (cmd_state->type == 8) { + buf8 = cmd_state->buf8; + for (i = 0; i < 4; i++) { + hdpro_io_write(ATAreg_DATA_WR, *buf8); + cmd_state->buf = ++buf8; + } + } + + } else if (type == 2) { + /* PIO data in */ + buf16 = cmd_state->buf16; + + suspend_intr(); + + HDPROreg_IO8 = 0x53; + CDVDreg_STATUS = 0; + CDVDreg_STATUS = 0; + + for (i = 0; i < 256; i++) { + + unsigned int res0 = HDPROreg_IO8; + CDVDreg_STATUS = 0; + unsigned int res1 = HDPROreg_IO8; + CDVDreg_STATUS = 0; + + res0 = (res0 & 0xff) | (res1 << 8); + chk ^= res0 + i; + + *buf16 = res0 & 0xffff; + cmd_state->buf16 = ++buf16; + } + + HDPROreg_IO8 = 0x51; + CDVDreg_STATUS = 0; + CDVDreg_STATUS = 0; + + resume_intr(); + + u16 r_data = hdpro_io_read(ATAreg_DATA_RD) & 0xffff; + if (r_data != (chk & 0xffff)) + return ATA_RES_ERR_IO; + } + + return res; +} + +/* Export 5 */ +int ata_reset_devices(void) +{ + if (hdpro_io_read(ATAreg_CONTROL_RD) & 0x80) + return ATA_RES_ERR_NOTREADY; + + /* Disables device interrupt assertion and asserts SRST. */ + hdpro_io_write(ATAreg_CONTROL_WR, 6); + DelayThread(100); + + /* Disable ATA interrupts. */ + hdpro_io_write(ATAreg_CONTROL_WR, 2); + DelayThread(3000); + + return ata_wait_busy(); +} + +/* Export 11 */ +int ata_device_sce_sec_unlock(int device, void *password) +{ //Device can always be unlocked. + return 0; +} + +static void ata_device_probe(ata_devinfo_t *devinfo) +{ + u16 nsector, lcyl, hcyl, sector; + + devinfo->exists = 0; + devinfo->has_packet = 2; + + if (hdpro_io_read(ATAreg_CONTROL_RD) & 0x88) + return; + + nsector = hdpro_io_read(ATAreg_NSECTOR_RD) & 0xff; + sector = hdpro_io_read(ATAreg_SECTOR_RD) & 0xff; + lcyl = hdpro_io_read(ATAreg_LCYL_RD) & 0xff; + hcyl = hdpro_io_read(ATAreg_HCYL_RD) & 0xff; + (void)(hdpro_io_read(ATAreg_SELECT_RD) & 0xff); + + /* The original HDPro driver did not check sector. + However, by the ATA-4 specification (9.1), sector should be 1. + So it should be perfectly fine to check. */ + if ((nsector != 1) || (sector != 1)) + return; + devinfo->exists = 1; + + if ((lcyl == 0x00) && (hcyl == 0x00)) + devinfo->has_packet = 0; + else if ((lcyl == 0x14) && (hcyl == 0xeb)) + devinfo->has_packet = 1; + + /* Seems to be for ensuring that there is a device connected. + Not sure why this has to be done, but is present in v2.4. */ + hdpro_io_write(ATAreg_LCYL_WR, 0x55); + hdpro_io_write(ATAreg_HCYL_WR, 0xaa); + lcyl = hdpro_io_read(ATAreg_LCYL_RD) & 0xff; + hcyl = hdpro_io_read(ATAreg_HCYL_RD) & 0xff; + + if((lcyl != 0x55) || (hcyl != 0xaa)) + devinfo->exists = 0; +} + +/* Export 17 */ +int ata_device_flush_cache(int device) +{ + int res; + + if (!hdpro_io_start()) + return -1; + + if(!(res = ata_io_start(NULL, 1, 0, 0, 0, 0, 0, (device << 4) & 0xffff, atad_devinfo[device].lba48?ATA_C_FLUSH_CACHE_EXT:ATA_C_FLUSH_CACHE))) res=ata_io_finish(); + + if (!hdpro_io_finish()) + return -2; + + return res; +} + +/* Export 13 */ +int ata_device_idle(int device, int period) +{ + int res; + + res = ata_io_start(NULL, 1, 0, period & 0xff, 0, 0, 0, (device << 4) & 0xffff, ATA_C_IDLE); + if (res) + return res; + + return ata_io_finish(); +} + +/* Set features - set transfer mode. */ +static int ata_device_set_transfer_mode(int device, int type, int mode) +{ + int res; + + res = ata_io_start(NULL, 1, 3, (type|mode) & 0xff, 0, 0, 0, (device << 4) & 0xffff, ATA_C_SET_FEATURES); + if (res) + return res; + + res = ata_io_finish(); + if (res) + return res; + + return 0; +} + +static int ata_device_identify(int device, void *info) +{ + int res; + + res = ata_io_start(info, 1, 0, 0, 0, 0, 0, (device << 4) & 0xffff, ATA_C_IDENTIFY_DEVICE); + if (res) + return res; + + return ata_io_finish(); +} + +static int ata_device_smart_enable(int device) +{ + int res; + + if(!(res = ata_io_start(NULL, 1, ATA_S_SMART_ENABLE_OPERATIONS, 0, 0, 0x4f, 0xc2, (device << 4) & 0xffff, ATA_C_SMART))) res=ata_io_finish(); + + return res; +} + +static int ata_init_devices(ata_devinfo_t *devinfo) +{ + int i, res; + + if((res = ata_reset_devices()) != 0) + return res; + + ata_device_probe(&devinfo[0]); + if (!devinfo[0].exists) { + M_PRINTF("Error: Unable to detect HDD 0.\n"); + devinfo[1].exists = 0; + return ATA_RES_ERR_NODEV; //Returns 0 in v1.04. + } + + /* If there is a device 1, grab it's info too. */ + if ((res = ata_device_select(1)) != 0) + return res; + if (hdpro_io_read(ATAreg_CONTROL_RD) & 0xff) + ata_device_probe(&devinfo[1]); + else + devinfo[1].exists = 0; + + for (i = 0; i < 2; i++) { + if (!devinfo[i].exists) + continue; + + /* Send the IDENTIFY DEVICE command. if it doesn't succeed + devinfo is disabled. */ + if (!devinfo[i].has_packet) { + res = ata_device_identify(i, ata_param); + devinfo[i].exists = (res == 0); + } else if (devinfo[i].has_packet == 1) { + /* If it's a packet device, send the IDENTIFY PACKET + DEVICE command. */ + /* Packet devices are not supported: + + The original HDPro driver issues the IDENTIFY PACKET DEVICE command, + but does not export ata_io_start and ata_io_finish. + This makes packet device support impossible. */ + res = -1; + devinfo[i].exists = (res == 0); + } + /* Otherwise, do nothing if has_packet = 2. */ + + /* This next section is HDD-specific: if no device or it's a + packet (ATAPI) device, we're done. */ + if (!devinfo[i].exists || devinfo[i].has_packet) + continue; + + /* This section is to detect whether the HDD supports 48-bit LBA + (IDENITFY DEVICE bit 10 word 83) and get the total sectors from + either words(61:60) for 28-bit or words(103:100) for 48-bit. */ + if (ata_param[ATA_ID_COMMAND_SETS_SUPPORTED] & 0x0400) { + atad_devinfo[i].lba48 = 1; + /* I don't think anyone would use a >2TB HDD but just in case. */ + if (ata_param[ATA_ID_48BIT_SECTOTAL_HI]) { + devinfo[i].total_sectors = 0xffffffff; + } else { + devinfo[i].total_sectors = + (ata_param[ATA_ID_48BIT_SECTOTAL_MI] << 16)| + ata_param[ATA_ID_48BIT_SECTOTAL_LO]; + } + } else { + atad_devinfo[i].lba48 = 0; + devinfo[i].total_sectors = (ata_param[ATA_ID_SECTOTAL_HI] << 16)| + ata_param[ATA_ID_SECTOTAL_LO]; + } + devinfo[i].security_status = ata_param[ATA_ID_SECURITY_STATUS]; + + /* PIO mode 0 (flow control). */ + ata_device_set_transfer_mode(i, ATA_XFER_MODE_PIO, 0); + ata_device_smart_enable(i); + /* Disable idle timeout. */ + ata_device_idle(i, 0); + } + return 0; +} + +/* Export 7 */ +int ata_io_finish(void) +{ + ata_cmd_state_t *cmd_state = &atad_cmd_state; + u32 bits; + int res = 0, type = cmd_state->type; + u16 stat; + + if (type == 1 || type == 6) { /* Non-data commands. */ + + //Unlike ATAD, poll until the device either completes its command or times out. There is no completion interrupt. + while(1) + { + suspend_intr(); + + HDPROreg_IO8 = 0x21; + CDVDreg_STATUS = 0; + unsigned int ret = HDPROreg_IO8; + CDVDreg_STATUS = 0; + + resume_intr(); + + if (((ret & 0xff) & 1) != 0) { + //Command completed. + break; + } + + /* The original did not check on the return value of PollEventFlag, + but PollEventFlag does not seem to return the event flag's bits if the wait condition is not satisfied. */ + if(PollEventFlag(ata_evflg, ATA_EV_TIMEOUT | ATA_EV_COMPLETE, WEF_CLEAR|WEF_OR, &bits) == 0) + { + if (bits & ATA_EV_TIMEOUT) { /* Timeout. */ + M_PRINTF("Error: ATA timeout on a non-data command.\n"); + return ATA_RES_ERR_TIMEOUT; + } + } + + DelayThread(500); + } + + /* Support for DMA commands (type = 4) is removed because HDPro cannot support DMA. + The original would return ATA_RES_ERR_TIMEOUT for type = 4. */ + } else { /* PIO transfers. */ + stat = hdpro_io_read(ATAreg_CONTROL_RD); + if ((res = ata_wait_busy()) < 0) + goto finish; + + /* Transfer each PIO data block. */ + while (--cmd_state->blkcount != -1) { + if ((res = ata_pio_transfer(cmd_state)) < 0) + goto finish; + if ((res = ata_wait_busy()) < 0) + goto finish; + } + } + + if (res) + goto finish; + + /* Wait until the device isn't busy. */ + if (hdpro_io_read(ATAreg_STATUS_RD) & ATA_STAT_BUSY) + res = ata_wait_busy(); + if ((stat = hdpro_io_read(ATAreg_STATUS_RD)) & ATA_STAT_ERR) { + M_PRINTF("Error: Command error: status 0x%02x, error 0x%02x.\n", stat, ata_get_error()); + res = ATA_RES_ERR_IO; + } + +finish: + /* The command has completed (with an error or not), so clean things up. */ + CancelAlarm(&ata_alarm_cb, NULL); + + return res; +} + +/* Export 9 */ +int ata_device_sector_io(int device, void *buf, u32 lba, u32 nsectors, int dir) +{ + int res = 0; + u16 sector, lcyl, hcyl, select, command, len; + + if (!hdpro_io_start()) + return -1; + + while (nsectors) { + len = (nsectors > 256) ? 256 : nsectors; + + /* Variable lba is only 32 bits so no change for lcyl and hcyl. */ + lcyl = (lba >> 8) & 0xff; + hcyl = (lba >> 16) & 0xff; + + if (atad_devinfo[device].lba48) { + /* Setup for 48-bit LBA. */ + /* Combine bits 24-31 and bits 0-7 of lba into sector. */ + sector = ((lba >> 16) & 0xff00) | (lba & 0xff); + /* In v1.04, LBA was enabled here. */ + select = (device << 4) & 0xffff; + command = (dir == 1) ? ATA_C_WRITE_SECTOR_EXT : ATA_C_READ_SECTOR_EXT; + } else { + /* Setup for 28-bit LBA. */ + sector = lba & 0xff; + /* In v1.04, LBA was enabled here. */ + select = ((device << 4) | ((lba >> 24) & 0xf)) & 0xffff; + command = (dir == 1) ? ATA_C_WRITE_SECTOR : ATA_C_READ_SECTOR; + } + + //Unlike ATAD, retry indefinitely until the I/O operation succeeds. + if ((res = ata_io_start(buf, len, 0, len, sector, lcyl, + hcyl, select, command)) != 0) + continue; + if ((res = ata_io_finish()) != 0) + continue; + + buf = (void*)((u8 *)buf + len * 512); + lba += len; + nsectors -= len; + } + + if (!hdpro_io_finish()) + return -2; + + return res; +} + +/* Export 4 */ +ata_devinfo_t * ata_get_devinfo(int device) +{ + if(!ata_devinfo_init){ + ata_devinfo_init = 1; + + if (!hdpro_io_start()) + return NULL; + + HDPROreg_IO8 = 0xe3; + CDVDreg_STATUS = 0; + + if ((ata_bus_reset() != 0) || (ata_init_devices(atad_devinfo) != 0) || (!hdpro_io_finish())) + return NULL; + } + + return &atad_devinfo[device]; +} diff --git a/sps2_basement/hardware/dev9/hdpro_atad/src/imports.lst b/sps2_basement/hardware/dev9/hdpro_atad/src/imports.lst new file mode 100644 index 0000000..9f2fc4c --- /dev/null +++ b/sps2_basement/hardware/dev9/hdpro_atad/src/imports.lst @@ -0,0 +1,32 @@ + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +I_SetAlarm +I_CancelAlarm +I_USec2SysClock +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_iSetEventFlag +I_ClearEventFlag +I_PollEventFlag +thevent_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memcpy +I_memset +sysclib_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end diff --git a/sps2_basement/hardware/dev9/hdpro_atad/src/irx_imports.h b/sps2_basement/hardware/dev9/hdpro_atad/src/irx_imports.h new file mode 100644 index 0000000..8c8b9af --- /dev/null +++ b/sps2_basement/hardware/dev9/hdpro_atad/src/irx_imports.h @@ -0,0 +1,26 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "intrman.h" +#include "loadcore.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thevent.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dev9/poweroff/Makefile b/sps2_basement/hardware/dev9/poweroff/Makefile new file mode 100644 index 0000000..6a27820 --- /dev/null +++ b/sps2_basement/hardware/dev9/poweroff/Makefile @@ -0,0 +1,14 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_OBJS = poweroff.o imports.o exports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dev9/poweroff/include/poweroff.h b/sps2_basement/hardware/dev9/poweroff/include/poweroff.h new file mode 100644 index 0000000..e74620b --- /dev/null +++ b/sps2_basement/hardware/dev9/poweroff/include/poweroff.h @@ -0,0 +1,36 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Power-off processing definitions and imports. + */ + +#ifndef __POWEROFF_H__ +#define __POWEROFF_H__ + +#include + +typedef void (*pwoffcb)(void*); + +void SetPowerButtonHandler(pwoffcb func, void* param); +void AddPowerOffHandler(pwoffcb func, void* param); +void RemovePowerOffHandler(pwoffcb func); +void PoweroffShutdown(); + +#define poweroff_IMPORTS_start DECLARE_IMPORT_TABLE(poweroff, 1, 1) +#define poweroff_IMPORTS_end END_IMPORT_TABLE + +#define I_SetPowerButtonHandler DECLARE_IMPORT(4, SetPowerButtonHandler) +#define I_AddPowerOffHandler DECLARE_IMPORT(5, AddPowerOffHandler) +#define I_RemovePowerOffHandler DECLARE_IMPORT(6, RemovePowerOffHandler) +#define I_PoweroffShutdown DECLARE_IMPORT(7, PoweroffShutdown) + +#endif /* __POWEROFF_H__ */ diff --git a/sps2_basement/hardware/dev9/poweroff/src/exports.tab b/sps2_basement/hardware/dev9/poweroff/src/exports.tab new file mode 100644 index 0000000..7140f1c --- /dev/null +++ b/sps2_basement/hardware/dev9/poweroff/src/exports.tab @@ -0,0 +1,14 @@ +DECLARE_EXPORT_TABLE(poweroff, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + + /* 4 */ + DECLARE_EXPORT(SetPowerButtonHandler) + DECLARE_EXPORT(AddPowerOffHandler) + DECLARE_EXPORT(RemovePowerOffHandler) + DECLARE_EXPORT(PoweroffShutdown) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/dev9/poweroff/src/imports.lst b/sps2_basement/hardware/dev9/poweroff/src/imports.lst new file mode 100644 index 0000000..8709673 --- /dev/null +++ b/sps2_basement/hardware/dev9/poweroff/src/imports.lst @@ -0,0 +1,30 @@ +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +sifcmd_IMPORTS_start +I_isceSifSendCmd +I_sceSifInitRpc +I_sceSifSetRpcQueue +I_sceSifRegisterRpc +I_sceSifRpcLoop +I_sceSifBindRpc +I_sceSifCallRpc +sifcmd_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memset +sysclib_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_StartThread +I_GetThreadId +I_SleepThread +I_DelayThread +I_iWakeupThread +thbase_IMPORTS_end diff --git a/sps2_basement/hardware/dev9/poweroff/src/irx_imports.h b/sps2_basement/hardware/dev9/poweroff/src/irx_imports.h new file mode 100644 index 0000000..f478122 --- /dev/null +++ b/sps2_basement/hardware/dev9/poweroff/src/irx_imports.h @@ -0,0 +1,25 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "loadcore.h" +#include "sifcmd.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dev9/poweroff/src/poweroff.c b/sps2_basement/hardware/dev9/poweroff/src/poweroff.c new file mode 100644 index 0000000..4304040 --- /dev/null +++ b/sps2_basement/hardware/dev9/poweroff/src/poweroff.c @@ -0,0 +1,282 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include "types.h" +#include "defs.h" +#include "irx.h" +#include "loadcore.h" +#include "sysmem.h" +#include "stdio.h" +#include "sysclib.h" +#include "sifcmd.h" +#include "thbase.h" +#include "intrman.h" +#include "loadcore.h" +#include "thsemap.h" +#include "poweroff.h" +#include "pwroff_rpc.h" + +//#define DEBUG + +#define TYPE_C 1 +#define CDVDreg_PWOFF (*(volatile unsigned char*)0xBF402008) + +#define MAX_CALLBACKS 8 + +#define MODNAME "Poweroff_Handler" +IRX_ID(MODNAME, 1, 1); + +#define M_PRINTF(format, args...) \ + printf(MODNAME ": " format, ##args) + +#ifdef DEBUG +#define M_DEBUG M_PRINTF +#else +#define M_DEBUG(format, args...) +#endif + +extern struct irx_export_table _exp_poweroff; + +//--------------------------------------------------------------------- + +int _start(int, char**); +static void Shutdown(); +static void SendCmd(void* data); + +//--------------------------------------------------------------------- +typedef int (*intrhandler)(void*); + +static intrhandler oldCdHandler=0; + +struct handlerTableEntry{ + intrhandler handler; + void *param; +}; + +struct CallbackEntry +{ + pwoffcb cb; + void *data; +} CallbackTable[MAX_CALLBACKS]; + +//--------------------------------------------------------------------- + +static char cmdData[16]; +static pwoffcb poweroff_button_cb = 0; +static void *poweroff_button_data = 0; +static struct t_SifRpcDataQueue qd; +static struct t_SifRpcServerData sd0; +static int PowerOffThreadID = -1; +static SifRpcClientData_t client; + +static int myCdHandler(void *param) +{ + if (((CDVDreg_PWOFF & 1)==0) && (CDVDreg_PWOFF & 4)) + { + /* can't seem to register a sif cmd callback in ps2link so... */ + /* Clear interrupt bit */ + CDVDreg_PWOFF = 4; + M_DEBUG("Poweroff!!!! %08x\n", CDVDreg_PWOFF); + + if (poweroff_button_cb) + poweroff_button_cb(poweroff_button_data); + } + + return oldCdHandler(param); +} + +static void Shutdown(void* data) +{ + M_DEBUG("Shutdown\n"); + + int i; + /* Do callbacks in reverse order */ + for(i = MAX_CALLBACKS-1; i >= 0; i--) + { + if(CallbackTable[i].cb) + { + CallbackTable[i].cb(CallbackTable[i].data); + } + } + + // Turn off PS2 + *((unsigned char *)0xBF402017) = 0; + *((unsigned char *)0xBF402016) = 0xF; +} + +static void SendCmd(void* data) +{ + iWakeupThread(PowerOffThreadID); +} + +static void PowerOffThread(void *arg) +{ + SleepThread(); + sceSifCallRpc(&client, POFF_RPC_BUTTON, 0, NULL, 0, NULL, 0, NULL, NULL); +} + +static void InitPowerOffThread(void) +{ + iop_thread_t thread; + + if(PowerOffThreadID < 0) + { + thread.thread = &PowerOffThread; + thread.attr = TH_C; + thread.option = PWROFF_IRX; + thread.stacksize = 0x400; + thread.priority = 0x27; + PowerOffThreadID = CreateThread(&thread); + StartThread(PowerOffThreadID, NULL); + + client.server = NULL; + while(sceSifBindRpc(&client, PWROFF_IRX, 0) < 0 || client.server == NULL) DelayThread(500); + } +} + +//--------------------------------------------------------------------- +//-----------------------------------------------------------entrypoint +//--------------------------------------------------------------------- + +void SetPowerButtonHandler(pwoffcb func, void* param) +{ + poweroff_button_cb = func; + poweroff_button_data = param; +} + +void AddPowerOffHandler(pwoffcb func, void* param) +{ + int i; + + for(i = 0; i < MAX_CALLBACKS; i++) + { + if(CallbackTable[i].cb == 0) + { + CallbackTable[i].cb = func; + CallbackTable[i].data = param; + M_DEBUG("Added callback at position %d\n", i); + break; + } + } + + if(i == MAX_CALLBACKS) + { + M_PRINTF("Could not add poweroff callback\n"); + } +} + +void RemovePowerOffHandler(pwoffcb func) +{ + int i; + + for(i = 0; i < MAX_CALLBACKS; i++) + { + if(CallbackTable[i].cb == func) + { + break; + } + } + + if(i < MAX_CALLBACKS) + { + for(; i < (MAX_CALLBACKS-1); i++) + { + CallbackTable[i] = CallbackTable[i+1]; + } + memset(&CallbackTable[i], 0, sizeof(struct CallbackEntry)); + } +} + +void PoweroffShutdown() +{ + Shutdown(0); +} + +void* poweroff_rpc_server(int fno, void *data, int size) +{ + switch(fno) { + case PWROFF_SHUTDOWN: + Shutdown(0); + break; + + case PWROFF_ENABLE_AUTO_SHUTOFF: + InitPowerOffThread(); + + int* sbuff = data; + if (sbuff[0]) + SetPowerButtonHandler(Shutdown, 0); + else + SetPowerButtonHandler(SendCmd, 0); + sbuff[0] = 1; + return sbuff; + } + return NULL; +} + +void poweroff_rpc_Thread(void* param) +{ + SifInitRpc(0); + + SifSetRpcQueue(&qd, GetThreadId()); + SifRegisterRpc(&sd0, PWROFF_IRX, poweroff_rpc_server, cmdData, NULL, NULL, &qd); + SifRpcLoop(&qd); +} + +int _start(int argc, char* argv[]) +{ + register struct handlerTableEntry *handlers=(struct handlerTableEntry*)0x480;//iopmem + iop_thread_t mythread; + int i; + + if(RegisterLibraryEntries(&_exp_poweroff) != 0) + { + M_PRINTF("Poweroff already registered\n"); + return 1; + } + + SetPowerButtonHandler(Shutdown, 0); + + if (handlers[IOP_IRQ_CDVD].handler==0) { + M_PRINTF("No CDROM handler. Run CDVDMAN first\n"); + return 1; + } + + if (((int)handlers[IOP_IRQ_CDVD].handler & 3) != TYPE_C){ + M_PRINTF("Cannot chain to non-C handler\n"); + return 1; + } + + oldCdHandler=(intrhandler)((int)handlers[IOP_IRQ_CDVD].handler & ~3); + handlers[IOP_IRQ_CDVD].handler=(intrhandler)((int)myCdHandler | TYPE_C); + + memset(CallbackTable, 0, sizeof(struct CallbackEntry) * MAX_CALLBACKS); + + mythread.attr = TH_C; + mythread.option = PWROFF_IRX; + mythread.thread = poweroff_rpc_Thread; + mythread.stacksize = 0x1000; + mythread.priority = 0x27; + + int pid = CreateThread(&mythread); + + if (pid > 0) { + if ((i=StartThread(pid, NULL)) < 0) { + M_PRINTF("StartThread failed (%d)\n", i); + return MODULE_NO_RESIDENT_END; + } + } + else { + M_PRINTF("CreateThread failed (%d)\n", pid); + return MODULE_NO_RESIDENT_END; + } + + M_PRINTF("Poweroff installed\n"); + return MODULE_RESIDENT_END; +} diff --git a/sps2_basement/hardware/dev9/pvrdrv/Makefile b/sps2_basement/hardware/dev9/pvrdrv/Makefile new file mode 100644 index 0000000..53a3f67 --- /dev/null +++ b/sps2_basement/hardware/dev9/pvrdrv/Makefile @@ -0,0 +1,10 @@ + +IOP_BIN ?= dvrdrv.irx + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/dev9/include +IOP_OBJS = dvrdrv.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dev9/pvrdrv/include/pvrdrv.h b/sps2_basement/hardware/dev9/pvrdrv/include/pvrdrv.h new file mode 100644 index 0000000..9f4e5ad --- /dev/null +++ b/sps2_basement/hardware/dev9/pvrdrv/include/pvrdrv.h @@ -0,0 +1,69 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Personal video recorder driver. + * Interface to the DVRP through the DEV9 interface. + */ + +#ifndef __PVRDRV_H__ +#define __PVRDRV_H__ + +#include +#include + +typedef struct __attribute__((aligned(4))) drvdrv_exec_cmd_ack_ +{ + u16 command; + u16 input_word[64]; + u32 input_word_count; + u16 status_4220_ack; + u16 ack_status_ack; + u16 output_word[64]; + u32 status_4228_ack; + u16 status_4220_comp; + u16 comp_status; + u16 return_result_word[64]; + u32 status_4228_comp; + u32 timeout; + void *input_buffer; + u32 input_buffer_length; + void *output_buffer; + int ack_status_ack2; + int phase; +} drvdrv_exec_cmd_ack; + +extern int DvrdrvResetSystem(); +extern int DvrdrvEnableIntr(u16 a1); +extern int DvrdrvDisableIntr(s16 a1); +extern int DvrdrvRegisterIntrHandler(int a1, void *arg, void (*a3)(int, void *)); +extern int DvrdrvUnregisterIntrHandler(void (*a1)(int, void *)); +extern int DvrdrvExecCmdAck(drvdrv_exec_cmd_ack *a1); +extern int DvrdrvExecCmdAckComp(drvdrv_exec_cmd_ack *a1); +extern int DvrdrvExecCmdAckDmaSendComp(drvdrv_exec_cmd_ack *a1); +extern int DvrdrvExecCmdAckDmaRecvComp(drvdrv_exec_cmd_ack *a1); +extern int DvrdrvExecCmdAckDma2Comp(drvdrv_exec_cmd_ack *a1); + +#define pvrdrv_IMPORTS_start DECLARE_IMPORT_TABLE(pvrdrv, 1, 1) +#define pvrdrv_IMPORTS_end END_IMPORT_TABLE + +#define I_DvrdrvResetSystem DECLARE_IMPORT(4, DvrdrvResetSystem) +#define I_DvrdrvEnableIntr DECLARE_IMPORT(5, DvrdrvEnableIntr) +#define I_DvrdrvDisableIntr DECLARE_IMPORT(6, DvrdrvDisableIntr) +#define I_DvrdrvRegisterIntrHandler DECLARE_IMPORT(7, DvrdrvRegisterIntrHandler) +#define I_DvrdrvUnregisterIntrHandler DECLARE_IMPORT(8, DvrdrvUnregisterIntrHandler) +#define I_DvrdrvExecCmdAck DECLARE_IMPORT(9, DvrdrvExecCmdAck) +#define I_DvrdrvExecCmdAckComp DECLARE_IMPORT(10, DvrdrvExecCmdAckComp) +#define I_DvrdrvExecCmdAckDmaSendComp DECLARE_IMPORT(11, DvrdrvExecCmdAckDmaSendComp) +#define I_DvrdrvExecCmdAckDmaRecvComp DECLARE_IMPORT(12, DvrdrvExecCmdAckDmaRecvComp) +#define I_DvrdrvExecCmdAckDma2Comp DECLARE_IMPORT(13, DvrdrvExecCmdAckDma2Comp) + +#endif diff --git a/sps2_basement/hardware/dev9/pvrdrv/src/dvrdrv.c b/sps2_basement/hardware/dev9/pvrdrv/src/dvrdrv.c new file mode 100644 index 0000000..1006a28 --- /dev/null +++ b/sps2_basement/hardware/dev9/pvrdrv/src/dvrdrv.c @@ -0,0 +1,1341 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include "irx.h" +#include "tamtypes.h" +#include "stdbool.h" +#include "dev9.h" +#include "sysmem.h" +#include "intrman.h" +#include "loadcore.h" +#include "stdio.h" +#include "thbase.h" +#include "thsemap.h" +#include "speedregs.h" + +#include "pvrdrv.h" + +// Based off of DESR / PSX DVR system software version 1.31. +#define MODNAME "DVR_Basic_driver" +IRX_ID(MODNAME, 1, 1); + +typedef struct struct_itr_sid_tbl_ +{ + u16 command; + u8 gap2[2]; + int sema; + u16 error; + u8 timed_out; + u8 byteB; +} struct_itr_sid_tbl; + +typedef struct __attribute__((aligned(4))) struct_itr_sema_ +{ + int sema; + u8 used; +} struct_itr_sema; + +typedef struct struct_dvrdrv_ +{ + int mainthread_id; + u16 dvr_ready; +} struct_dvrdrv; + +int _start(int a1); +int module_start(); +int module_stop(); +int DvrdrvInit(); +int DvrdrvSendCmdAck(struct_itr_sema *itrsema, u16 command, u16 *input_word, s32 input_word_count, u16 *status_4220, u16 *ack_status, u32 *status_4228); +int DvrdrvSetDmaDirection(u32 arg); +int DvrdrvTransferDma(u8 *output_buffer, int a2); +void DvrPreDmaHandler(int bcr, int dir); +void DvrPostDmaHandler(int bcr, int dir); +int DvrdrvPrepareWaitDmaEnd(struct_itr_sema *itrsema, u16 command); +int DvrdrvCancelWaitDmaEnd(u16 command); +int DvrdrvWaitDmaEnd(struct_itr_sema *itrsema, u16 command); +int DvrdrvPrepareWaitCmdComp(struct_itr_sema *itrsema, u16 command, u32 timeout); +int DvrdrvCancelWaitCmdComp(u16 command); +int DvrdrvWaitCmdComp(struct_itr_sema *itrsema, u16 command, u16 *status_4220, u16 *comp_status, u32 *status_4228); +s32 DvrdrvBlockPhase(); +s32 DvrdrvUnblockPhase(); +int DvrdrvEnd(); +int DVR_INTR_HANDLER(int flag); +int INTR_DVRRDY_HANDLER(int a1, struct_dvrdrv *a2); +int INTR_DVRRDY_TO_HANDLER(void *a1); +void INTR_CMD_ACK_HANDLER(int, void *); +int INTR_CMD_ACK_TO_HANDLER(struct_itr_sid_tbl *a1); +void INTR_CMD_COMP_HANDLER(int, void *); +unsigned int INTR_CMD_COMP_TO_HANDLER(struct_itr_sid_tbl *a1); +void INTR_DMAACK_HANDLER(int, void *); +unsigned int INTR_DMAACK_TO_HANDLER(struct_itr_sid_tbl *a1); +void INTR_DMAEND_HANDLER(int, void *); +int BlockAPI(); +int UnblockAPI(); +struct_itr_sid_tbl *SetItrSidTbl(int itrsid_index, u16 command, int sema); +struct_itr_sid_tbl *GetItrSidTbl(int itrsid_index, u16 command); +int ClearItrSidTbl(struct_itr_sid_tbl *a1); +struct_itr_sema *AllocItrSema(); +int ReleaseItrSema(struct_itr_sema *itrsema); + +extern struct irx_export_table _exp_pvrdrv; +struct_dvrdrv DVRDRV; +s32 api_sema_id; +s32 phase_sema_id; +void (*intrhandler_callbacks[32])(int, void *); +int intrhandler_intrnum[32]; +void *intrhandler_callbacksarg[32]; +struct_itr_sid_tbl itrsid_table[3][32]; +struct_itr_sema itr_sema_table[32]; + +int _start(int a1) +{ + int result; + + if (a1 >= 0) + result = module_start(); + else + result = module_stop(); + return result; +} + +int module_start() +{ + int result = MODULE_NO_RESIDENT_END; + + if (DvrdrvInit() != -1) { + if (RegisterLibraryEntries(&_exp_pvrdrv) == 0) { +#if 0 + result = MODULE_REMOVABLE_END; +#else + result = MODULE_RESIDENT_END; +#endif + } + } + return result; +} + +int module_stop() +{ + bool v0; + int result; + + ReleaseLibraryEntries(&_exp_pvrdrv); + v0 = DvrdrvEnd() == 0; +#if 0 + result = MODULE_NO_RESIDENT_END; +#else + result = MODULE_RESIDENT_END; +#endif + if (!v0) + result = MODULE_REMOVABLE_END; + return result; +} + +int DvrdrvInit() +{ + int v0; + int v1; + iop_sema_t v12; + iop_sema_t v13; + + DVRDRV.mainthread_id = -1; + v12.attr = 0; + v12.initial = 1; + v12.max = 1; + v12.option = 0; + v0 = CreateSema(&v12); + if (v0 < 0) + return -1; + api_sema_id = v0; + v13.attr = 0; + v13.initial = 1; + v13.max = 1; + v13.option = 0; + v1 = CreateSema(&v13); + if (v1 < 0) + return -1; + phase_sema_id = v1; + v13.attr = 0; + v13.initial = 0; + v13.max = 1; + v13.option = 0; + for (int i = 0; i < 32; i += 1) { + itr_sema_table[i].sema = CreateSema(&v13); + itr_sema_table[i].used = 0; + } + for (int i = 0; i < 32; i += 1) { + intrhandler_callbacks[i] = 0; + intrhandler_intrnum[i] = 0; + } + for (int i = 0; i < 3; i += 1) { + for (int j = 0; j < 32; j += 1) { + ClearItrSidTbl(&itrsid_table[i][j]); + } + } + dev9RegisterIntrCb(9, DVR_INTR_HANDLER); + DvrdrvRegisterIntrHandler(1, &DVRDRV, (void (*)(int, void *))INTR_DVRRDY_HANDLER); + DvrdrvRegisterIntrHandler(2, &DVRDRV, INTR_CMD_ACK_HANDLER); + DvrdrvRegisterIntrHandler(4, &DVRDRV, INTR_CMD_COMP_HANDLER); + DvrdrvRegisterIntrHandler(8, &DVRDRV, INTR_DMAACK_HANDLER); + DvrdrvRegisterIntrHandler(16, &DVRDRV, INTR_DMAEND_HANDLER); + DvrdrvEnableIntr(0x1Fu); + dev9RegisterPreDmaCb(2, DvrPreDmaHandler); + dev9RegisterPostDmaCb(2, DvrPostDmaHandler); + return 0; +} + +int DvrdrvResetSystem() +{ + s32 v0; + bool v1; + int v2; + iop_sys_clock_t v4; + USE_SPD_REGS; + + BlockAPI(); + SPD_REG8(0x4008) &= 0xFEu; + DelayThread(100000); + SPD_REG8(0x4008) |= 1u; + DVRDRV.mainthread_id = GetThreadId(); + USec2SysClock(0x1C9C380u, &v4); + SetAlarm(&v4, (unsigned int (*)(void *))INTR_DVRRDY_TO_HANDLER, &DVRDRV); + v0 = SleepThread(); + CancelAlarm((unsigned int (*)(void *))INTR_DVRRDY_TO_HANDLER, &DVRDRV); + v1 = v0 != 0; + v2 = -2; + if (!v1) { + v2 = -1; + if ((DVRDRV.dvr_ready & 1) != 0) + v2 = 0; + DVRDRV.dvr_ready = 0; + } + DvrdrvDisableIntr(1); + UnblockAPI(); + return v2; +} + +int DvrdrvSendCmdAck(struct_itr_sema *itrsema, u16 command, u16 *input_word, s32 input_word_count, u16 *status_4220, u16 *ack_status, u32 *status_4228) +{ + int v11; + int v12; + struct_itr_sid_tbl *v14; + s32 v15; + u16 *v16; + s16 v17; + int v18; + unsigned int (*v19)(void *); + int v20; + int v21; + unsigned int (*v22)(void *); + s16 v23; + unsigned int v24; + int v25; + s32 i; + iop_sys_clock_t v28; + USE_SPD_REGS; + + v11 = -1; + v12 = 0; + do { + if ((SPD_REG16(0x4230) & 2) != 0) + break; + DelayThread(1000); + ++v12; + } while (v12 < 100); + if (v12 == 100) { + printf("DvrdrvSendCmdAck -> Command is running... (Time out)\n"); + return -2; + } + BlockAPI(); + v14 = SetItrSidTbl(0, command, itrsema->sema); + if (!v14) { + v11 = -1; + printf("DvrdrvSendCmdAck() -> SetItrSidTbl Error\n"); + goto LABEL_44; + } + SPD_REG16(0x4218) |= 0x80u; + while ((SPD_REG16(0x4218) & 0x80) != 0) + ; + v15 = 0; + if (input_word_count > 0) { + v16 = input_word; + do { + v17 = *v16++; + ++v15; + SPD_REG16(0x4214) = v17; + } while (v15 < input_word_count); + } + USec2SysClock(0x1C9C380u, &v28); + v18 = (u16)(command & 0xF00) >> 8; + if (v18 == 1) { + v19 = (unsigned int (*)(void *))INTR_CMD_ACK_TO_HANDLER; + LABEL_18: + SetAlarm(&v28, v19, v14); + goto LABEL_19; + } + if (v18 && (u16)(command & 0xF00) >> 8 < 4u) { + v19 = (unsigned int (*)(void *))INTR_DMAACK_TO_HANDLER; + goto LABEL_18; + } +LABEL_19: + v20 = itrsema->sema; + SPD_REG16(0x4210) = command; + WaitSema(v20); + v21 = (u16)(command & 0xF00) >> 8; + if (v21 == 1) { + v22 = (unsigned int (*)(void *))INTR_CMD_ACK_TO_HANDLER; + } else { + if (!v21 || (u16)(command & 0xF00) >> 8 >= 4u) { + printf("DvrdrvSendCmdAck() -> Error!\n"); + goto LABEL_26; + } + v22 = (unsigned int (*)(void *))INTR_DMAACK_TO_HANDLER; + } + CancelAlarm(v22, v14); +LABEL_26: + if (!v14->timed_out || v14->error) { + v23 = v14->error; + v24 = command & 0xF00; + if ((v23 & 0x8000) == 0) { + if (v24 >> 8 == 1) { + v11 = 0; + if ((v23 & 2) == 0) { + v11 = -1; + printf("DvrdrvSendCmdAck -> Interrupt Flag Error!,%04X\n", (u16)v14->error); + goto LABEL_44; + } + } else if (v24 >> 8) { + if (v24 >> 8 < 4) { + v11 = 0; + if ((v14->error & 8) == 0) { + v11 = -1; + goto LABEL_44; + } + } + } + v25 = 64; + if ((SPD_REG16(0x4228) & 1) == 0) + v25 = (u8)(SPD_REG16(0x4228) & 0xFC) >> 2; + *status_4228 = v25; + for (i = 0; i < *status_4228; ++ack_status) { + ++i; + *ack_status = SPD_REG16(0x4224); + } + *status_4220 = SPD_REG16(0x4220); + goto LABEL_44; + } + v11 = -3; + } else { + v11 = -2; + printf("DvrdrvSendCmdAck() -> TO!\n"); + } +LABEL_44: + ClearItrSidTbl(v14); + UnblockAPI(); + return v11; +} + +int DvrdrvSetDmaDirection(u32 arg) +{ + USE_SPD_REGS; + if (arg < 2 && (SPD_REG16(0x4100) & 2) != 0) { + while ((SPD_REG16(0x4100) & 2) != 0) + ; + } + if ((SPD_REG8(0x4004) & 7) == arg) + return 0; + SPD_REG8(0x4004) = arg | (SPD_REG8(0x4004) & 0xF8); + SPD_REG16(0x4100) |= 1u; + while ((SPD_REG16(0x4100) & 1) != 0) + ; + return 0; +} + +int DvrdrvTransferDma(u8 *output_buffer, int a2) +{ + int v4; + int result; + int v6; + int v7; + u32 *v8; + USE_SPD_REGS; + + v4 = 0; + if (((u32)output_buffer & 3) != 0) + return -1; + BlockAPI(); + v6 = a2 / 128; + v7 = a2 % 128; + SPD_REG16(0x4108) = a2 / 128; + SPD_REG16(0x410C) = 32; + v8 = (u32 *)&output_buffer[128 * (u16)(a2 / 128)]; + switch (SPD_REG8(0x4004) & 7) { + case 0: + case 2: + case 7: + v4 = 0; + goto LABEL_7; + case 1: + case 3: + v4 = 1; + goto LABEL_7; + case 4: + case 5: + case 6: + UnblockAPI(); + return -1; + default: + LABEL_7: + dev9DmaTransfer(2, output_buffer, (v6 << 16) | 0x20, v4); + if (v7 > 0) { + do { + v7 -= 4; + SPD_REG16(0x4120) = ((*((u32 *)v8)) & 0x0000FFFF); + SPD_REG16(0x4122) = ((*((u32 *)v8)) & 0xFFFF0000) >> 16; + v8 += 1; + } while (v7 > 0); + } + UnblockAPI(); + result = 0; + break; + } + return result; +} + +void DvrPreDmaHandler(int bcr, int dir) +{ + USE_SPD_REGS; + SPD_REG16(0x4100) |= 2u; +} + +void DvrPostDmaHandler(int bcr, int dir) +{ + USE_SPD_REGS; + while ((SPD_REG16(0x4100) & 2) != 0) + ; +} + +int DvrdrvPrepareWaitDmaEnd(struct_itr_sema *itrsema, u16 command) +{ + int v4; + + BlockAPI(); + if (itrsema) { + v4 = 0; + SetItrSidTbl(1, command, itrsema->sema); + } else { + v4 = -1; + printf("DvrdrvPrepareWaitDmaEnd : itrsema==NULL\n"); + } + UnblockAPI(); + return v4; +} + +int DvrdrvCancelWaitDmaEnd(u16 command) +{ + struct_itr_sid_tbl *v2; + int v3; + + BlockAPI(); + v2 = GetItrSidTbl(1, command); + if (v2) { + ClearItrSidTbl(v2); + v3 = 0; + } else { + v3 = -1; + printf("DvrdrvCancelWaitDmaEnd -> Cannot found Sid!!\n"); + } + UnblockAPI(); + return v3; +} + +int DvrdrvWaitDmaEnd(struct_itr_sema *itrsema, u16 command) +{ + struct_itr_sid_tbl *v3; + s16 v4; + int v5; + u8 v6; + int v7; + char *v8; + char v10; + USE_SPD_REGS; + + WaitSema(itrsema->sema); + v3 = GetItrSidTbl(1, command); + v4 = v3->error; + v5 = -3; + if ((v4 & 0x8000) == 0) { + if ((v4 & 0x10) != 0) { + v5 = 0; + if ((SPD_REG16(0x4228) & 1) != 0) + v6 = 64; + else + v6 = (u8)(SPD_REG16(0x4228) & 0xFC) >> 2; + v7 = 0; + if (v6) { + v8 = &v10; + do { + ++v7; + *(u16 *)v8 = SPD_REG16(0x4224); + v8 += 2; + } while (v7 < v6); + } + } else { + v5 = -1; + printf("DvrdrvWaitDmaEnd -> Interrupt Flag Error!,%04X\n", (u16)v3->error); + } + } + ClearItrSidTbl(v3); + return v5; +} + +int DvrdrvPrepareWaitCmdComp(struct_itr_sema *itrsema, u16 command, u32 timeout) +{ + int v6; + int v7; + struct_itr_sid_tbl *v8; + iop_sys_clock_t v10; + + BlockAPI(); + if (itrsema) { + v7 = itrsema->sema; + v6 = 0; + v8 = SetItrSidTbl(2, command, v7); + USec2SysClock(timeout, &v10); + SetAlarm(&v10, (unsigned int (*)(void *))INTR_CMD_COMP_TO_HANDLER, v8); + } else { + v6 = -1; + printf("DvrdrvPrepareWaitCmdComp : itrsema==NULL\n"); + } + UnblockAPI(); + return v6; +} + +int DvrdrvCancelWaitCmdComp(u16 command) +{ + struct_itr_sid_tbl *v2; + struct_itr_sid_tbl *v3; + int v4; + + BlockAPI(); + v2 = GetItrSidTbl(2, command); + v3 = v2; + if (v2) { + CancelAlarm((unsigned int (*)(void *))INTR_CMD_COMP_TO_HANDLER, v2); + ClearItrSidTbl(v3); + v4 = 0; + } else { + v4 = -1; + printf("DvrdrvCancelWaitCmdComp -> Cannot found Sid!!\n"); + } + UnblockAPI(); + return v4; +} + +int DvrdrvWaitCmdComp(struct_itr_sema *itrsema, u16 command, u16 *status_4220, u16 *comp_status, u32 *status_4228) +{ + struct_itr_sid_tbl *v8; + int v9; + s16 v10; + int v11; + s32 v12; + u16 *v13; + USE_SPD_REGS; + + WaitSema(itrsema->sema); + v8 = GetItrSidTbl(2, command); + CancelAlarm((unsigned int (*)(void *))INTR_CMD_COMP_TO_HANDLER, v8); + v9 = -2; + if (!v8->timed_out) { + v10 = v8->error; + v9 = -3; + if ((v10 & 0x8000) == 0) { + if ((v10 & 4) != 0) { + v9 = 0; + if ((SPD_REG16(0x4228) & 1) != 0) + v11 = 64; + else + v11 = (u8)(SPD_REG16(0x4228) & 0xFC) >> 2; + *status_4228 = v11; + v12 = 0; + if (*status_4228 > 0) { + v13 = comp_status; + do { + ++v12; + *v13++ = SPD_REG16(0x4224); + } while (v12 < *status_4228); + } + *status_4220 = SPD_REG16(0x4220); + } else { + v9 = -1; + printf("DvrdrvWaitCmdComp -> Interrupt Flag Error!,%04X\n", (u16)v8->error); + } + } + } + ClearItrSidTbl(v8); + return v9; +} + +s32 DvrdrvBlockPhase() +{ + return WaitSema(phase_sema_id); +} + +s32 DvrdrvUnblockPhase() +{ + return SignalSema(phase_sema_id); +} + +int DvrdrvEnableIntr(u16 a1) +{ + int state; + USE_SPD_REGS; + + CpuSuspendIntr(&state); + SPD_REG16(0x4208) |= a1; + dev9IntrEnable(0x200); + CpuResumeIntr(state); + return 0; +} + +int DvrdrvDisableIntr(s16 a1) +{ + int state; + USE_SPD_REGS; + + CpuSuspendIntr(&state); + SPD_REG16(0x4208) &= ~a1; + SPD_REG16(0x4204) = a1; + if (!SPD_REG16(0x4208)) + dev9IntrDisable(0x200); + CpuResumeIntr(state); + return 0; +} + +int DvrdrvRegisterIntrHandler(int a1, void *arg, void (*a3)(int, void *)) +{ + int i; + + BlockAPI(); + for (i = 0; i < 32; i += 1) + { + if (intrhandler_callbacks[i] == NULL) + { + intrhandler_callbacks[i] = a3; + intrhandler_intrnum[i] = a1; + intrhandler_callbacksarg[i] = arg; + UnblockAPI(); + return 0; + } + } + UnblockAPI(); + return -1; +} + +int DvrdrvUnregisterIntrHandler(void (*a1)(int, void *)) +{ + int i; + + BlockAPI(); + for (i = 0; i < 32; i += 1) + { + if (intrhandler_callbacks[i] == a1) + { + intrhandler_callbacks[i] = NULL; + intrhandler_intrnum[i] = 0; + intrhandler_callbacksarg[i] = 0; + UnblockAPI(); + return 0; + } + } + UnblockAPI(); + return -1; +} + +int DvrdrvEnd() +{ + int result; + + result = -1; + if (api_sema_id < 0) + return result; + result = -1; + if (phase_sema_id < 0) + return result; + DvrdrvDisableIntr(0x801F); + DvrdrvUnregisterIntrHandler((void *)INTR_DVRRDY_HANDLER); + DvrdrvUnregisterIntrHandler((void *)INTR_CMD_ACK_HANDLER); + DvrdrvUnregisterIntrHandler((void *)INTR_CMD_COMP_HANDLER); + DvrdrvUnregisterIntrHandler((void *)INTR_DMAACK_HANDLER); + DvrdrvUnregisterIntrHandler((void *)INTR_DMAEND_HANDLER); + DeleteSema(api_sema_id); + DeleteSema(phase_sema_id); + api_sema_id = -1; + phase_sema_id = -1; +#if 0 + for (int i = 0; i < 32; i += 1) { + DeleteSema(itr_sema_table[i].sema); + } +#endif + return 0; +} + +int DVR_INTR_HANDLER(int flag) +{ + int i; + s16 v1; + int v4; + USE_SPD_REGS; + + v1 = 0; + v4 = SPD_REG16(0x4200); + for (i = 0; i < 32; i += 1) + { + if ((intrhandler_intrnum[i] & v4) != 0) + { + if (intrhandler_callbacks[i]) + { + intrhandler_callbacks[i](v4, intrhandler_callbacksarg[i]); + v1 |= intrhandler_intrnum[i]; + } + } + } + SPD_REG16(0x4204) = v1; + return 1; +} + +int INTR_DVRRDY_HANDLER(int a1, struct_dvrdrv *a2) +{ + a2->dvr_ready |= 1u; + if (a2->mainthread_id >= 0) + iWakeupThread(a2->mainthread_id); + return 0; +} + +int INTR_DVRRDY_TO_HANDLER(void *a1) +{ + s32 v1; + + v1 = *(s32 *)a1; + if (v1 >= 0) + iReleaseWaitThread(v1); + return 0; +} + +void INTR_CMD_ACK_HANDLER(int a1, void *a2) +{ + struct_itr_sid_tbl *v2; + int v3; + int v4; + char *v5; + s32 v6; + char v7; + USE_SPD_REGS; + + v2 = GetItrSidTbl(0, SPD_REG16(0x4220)); + if (v2) { + v6 = v2->sema; + v2->error |= 2u; + if (v6 < 0) + Kprintf("Illegal Sema ID : %d\n", v6); + else + iSignalSema(v6); + } else { + Kprintf("ACK:GetItrSidTbl(%04Xh) error\n", SPD_REG16(0x4220)); + Kprintf("Clear \"Reply FIFO\"\n"); + v3 = 64; + if ((SPD_REG16(0x4228) & 1) == 0) + v3 = (u8)(SPD_REG16(0x4228) & 0xFC) >> 2; + v4 = 0; + if (v3) { + v5 = &v7; + do { + ++v4; + *(u16 *)v5 = SPD_REG16(0x4224); + v5 += 2; + } while (v4 < v3); + } + } +} + +int INTR_CMD_ACK_TO_HANDLER(struct_itr_sid_tbl *a1) +{ + unsigned int v1; + s32 v3; + iop_sys_clock_t clock; + + GetSystemTime(&clock); + v1 = clock.lo; + Kprintf("CMDACK_TO:[%u]\n", v1); + v3 = a1->sema; + a1->timed_out = 1; + iSignalSema(v3); + return 0; +} + +void INTR_CMD_COMP_HANDLER(int a1, void *a2) +{ + struct_itr_sid_tbl *v2; + int v3; + int v4; + char *v5; + s32 v6; + char v7; + USE_SPD_REGS; + + v2 = GetItrSidTbl(2, SPD_REG16(0x4220)); + if (v2) { + v6 = v2->sema; + v2->error |= 4u; + if (v6 < 0) + Kprintf("Illegal thread ID : %d\n", v6); + else + iSignalSema(v6); + } else { + Kprintf("COMP:GetItrSidTbl(%04Xh) error\n", SPD_REG16(0x4220)); + Kprintf("Clear \"Reply FIFO\"\n"); + v3 = 64; + if ((SPD_REG16(0x4228) & 1) == 0) + v3 = (u8)(SPD_REG16(0x4228) & 0xFC) >> 2; + v4 = 0; + if (v3) { + v5 = &v7; + do { + ++v4; + *(u16 *)v5 = SPD_REG16(0x4224); + v5 += 2; + } while (v4 < v3); + } + } +} + +unsigned int INTR_CMD_COMP_TO_HANDLER(struct_itr_sid_tbl *a1) +{ + unsigned int v1; + s32 v3; + iop_sys_clock_t clock; + + GetSystemTime(&clock); + v1 = clock.lo; + Kprintf("COMP TO:[%u]\n", v1); + v3 = a1->sema; + a1->timed_out = 1; + iSignalSema(v3); + return 0; +} + +void INTR_DMAACK_HANDLER(int a1, void *a2) +{ + struct_itr_sid_tbl *v2; + s32 v3; + USE_SPD_REGS; + + v2 = GetItrSidTbl(0, SPD_REG16(0x4220)); + if (v2) { + v3 = v2->sema; + v2->error |= 8u; + if (v3 < 0) + Kprintf("Illegal thread ID : %d\n", v3); + else + iSignalSema(v3); + } else { + Kprintf("GetItrSidTbl(%04Xh) error\n", SPD_REG16(0x4220)); + } +} + +unsigned int INTR_DMAACK_TO_HANDLER(struct_itr_sid_tbl *a1) +{ + unsigned int v1; + iop_sys_clock_t clock; + + GetSystemTime(&clock); + v1 = clock.lo; + Kprintf("DMAACK_TO:[%u]\n", v1); + GetItrSidTbl(0, a1->command)->timed_out = 1; + iSignalSema(a1->sema); + return 0; +} + +void INTR_DMAEND_HANDLER(int a1, void *a2) +{ + struct_itr_sid_tbl *v2; + s32 v3; + USE_SPD_REGS; + + v2 = GetItrSidTbl(1, SPD_REG16(0x4220)); + if (v2) { + v3 = v2->sema; + v2->error |= 0x10u; + if (v3 < 0) + Kprintf("Illegal thread ID : %d\n", v3); + else + iSignalSema(v3); + } else { + Kprintf("GetItrSidTbl(%04Xh) error\n", SPD_REG16(0x4220)); + } +} + +int BlockAPI() +{ + WaitSema(api_sema_id); + return 0; +} + +int UnblockAPI() +{ + SignalSema(api_sema_id); + return 0; +} + +struct_itr_sid_tbl *SetItrSidTbl(int itrsid_index, u16 command, int sema) +{ + int state; + int i = 0; + + CpuSuspendIntr(&state); + for (i = 0; i < 32; i += 1) { + if (itrsid_table[itrsid_index][i].sema == -1 || itrsid_table[itrsid_index][i].command == command) { + itrsid_table[itrsid_index][i].command = command; + itrsid_table[itrsid_index][i].sema = sema; + itrsid_table[itrsid_index][i].error = 0; + break; + } + } + CpuResumeIntr(state); + if (i != 32) + return &itrsid_table[itrsid_index][i]; + Kprintf("SetItrSidTbl : Error!\n"); + return 0; +} + +struct_itr_sid_tbl *GetItrSidTbl(int itrsid_index, u16 command) +{ + int state; + int i = 0; + + CpuSuspendIntr(&state); + for (i = 0; i < 32; i += 1) { + if (itrsid_table[itrsid_index][i].command == command) { + break; + } + } + CpuResumeIntr(state); + if (i != 32) + return &itrsid_table[itrsid_index][i]; + Kprintf("GetItrSidTbl : Error!\n"); + return 0; +} + +int ClearItrSidTbl(struct_itr_sid_tbl *a1) +{ + int v2; + int state; + + CpuSuspendIntr(&state); + a1->timed_out = 0; + v2 = state; + a1->command = 0; + a1->sema = -1; + a1->error = 0; + return CpuResumeIntr(v2); +} + +struct_itr_sema *AllocItrSema() +{ + int i; + struct_itr_sema *result; + int state; + + result = 0; + CpuSuspendIntr(&state); + for (i = 0; i < 32; i += 1) + { + if (!itr_sema_table[i].used) + { + itr_sema_table[i].used = 1; + result = &itr_sema_table[i]; + break; + } + } + CpuResumeIntr(state); + if (result) + return result; + printf("AllocItrSema : empty\n"); + return 0; +} + +int ReleaseItrSema(struct_itr_sema *itrsema) +{ + int i; + int result; + int state; + + CpuSuspendIntr(&state); + for (i = 0; i < 32; i += 1) + { + if (&itr_sema_table[i] == itrsema) + { + itr_sema_table[i].used = 0; + break; + } + } + CpuResumeIntr(state); + result = 0; + if (i != 32) + return result; + printf("ReleaseItrSema : full\n"); + return -1; +} + +int DvrdrvExecCmdAck(drvdrv_exec_cmd_ack *a1) +{ + struct_itr_sema *v2; + u16 v3; + int v4; + int result; + + v2 = AllocItrSema(); + if (v2) { + DvrdrvBlockPhase(); + v3 = a1->command; + a1->phase = 1; + v4 = DvrdrvSendCmdAck( + v2, + v3, + a1->input_word, + a1->input_word_count, + &a1->status_4220_ack, + &a1->ack_status_ack, + &a1->status_4228_ack); + DvrdrvUnblockPhase(); + ReleaseItrSema(v2); + result = v4; + } else { + printf("DvrdrvExecCmdAck : Cannot alloc sema\n"); + result = -1; + } + return result; +} + +int DvrdrvExecCmdAckComp(drvdrv_exec_cmd_ack *a1) +{ + struct_itr_sema *v2; + struct_itr_sema *v3; + int result; + u16 v5; + int v6; + u16 v7; + + v2 = AllocItrSema(); + v3 = v2; + if (v2) { + DvrdrvPrepareWaitCmdComp(v2, a1->command, a1->timeout); + DvrdrvBlockPhase(); + v5 = a1->command; + a1->phase = 1; + v6 = DvrdrvSendCmdAck( + v3, + v5, + a1->input_word, + a1->input_word_count, + &a1->status_4220_ack, + &a1->ack_status_ack, + &a1->status_4228_ack); + if (v6) { + DvrdrvCancelWaitCmdComp(a1->command); + DvrdrvUnblockPhase(); + } else { + DvrdrvUnblockPhase(); + v7 = a1->command; + a1->phase = 4; + v6 = DvrdrvWaitCmdComp(v3, v7, &a1->status_4220_comp, &a1->comp_status, &a1->status_4228_comp); + } + ReleaseItrSema(v3); + result = v6; + } else { + printf("DvrdrvExecCmdAck : Cannot alloc sema\n"); + result = -1; + } + return result; +} + +int DvrdrvExecCmdAckDmaSendComp(drvdrv_exec_cmd_ack *a1) +{ + struct_itr_sema *v2; + struct_itr_sema *v3; + int v5; + int v6; + u16 v7; + int v8; + s16 v9; + struct_itr_sema *v10; + u16 v11; + u16 v12; + u16 v13[65]; + s32 input_word_count; + u16 v15; + u16 ack_status[65]; + u32 v17[37]; + int v18; + + v2 = AllocItrSema(); + v3 = v2; + if (!v2) { + printf("DvrdrvExecCmdAck : Cannot alloc sema\n"); + return -1; + } + DvrdrvPrepareWaitCmdComp(v2, a1->command, a1->timeout); + a1->phase = 1; + DvrdrvBlockPhase(); + v5 = DvrdrvSendCmdAck( + v3, + a1->command, + a1->input_word, + a1->input_word_count, + &a1->status_4220_ack, + &a1->ack_status_ack, + &a1->status_4228_ack); + v6 = v5; + if (v5) { + printf("Phase1 error -> %d\n", v5); + v7 = a1->command; + } else { + DvrdrvUnblockPhase(); + a1->phase = 2; + DvrdrvBlockPhase(); + DvrdrvSetDmaDirection(1u); + v8 = a1->input_buffer_length; + if ((v8 & 0x7F) != 0) + v18 = (v8 / 128 + 1) << 7; + else + v18 = a1->input_buffer_length; + v9 = a1->command; + input_word_count = 2; + v12 = (v9 & 0xF0FF) | 0x200; + v13[0] = (v18 & 0xFFFF0000) >> 16; + v13[1] = v18; + v10 = AllocItrSema(); + DvrdrvPrepareWaitDmaEnd(v10, v12); + v6 = DvrdrvSendCmdAck(v3, v12, v13, input_word_count, &v15, ack_status, v17); + if (v6) { + v7 = a1->command; + } else { + v6 = -1; + if (!ack_status[0]) { + if (v18 <= 0) { + DvrdrvCancelWaitDmaEnd(v12); + } else { + DvrdrvTransferDma(a1->input_buffer, v18); + DvrdrvWaitDmaEnd(v10, v12); + } + ReleaseItrSema(v10); + DvrdrvUnblockPhase(); + v11 = a1->command; + a1->phase = 4; + v6 = DvrdrvWaitCmdComp(v3, v11, &a1->status_4220_comp, &a1->comp_status, &a1->status_4228_comp); + goto LABEL_17; + } + v7 = a1->command; + } + } + DvrdrvCancelWaitCmdComp(v7); + DvrdrvUnblockPhase(); +LABEL_17: + ReleaseItrSema(v3); + return v6; +} + +int DvrdrvExecCmdAckDmaRecvComp(drvdrv_exec_cmd_ack *a1) +{ + struct_itr_sema *v2; + struct_itr_sema *v3; + int v5; + u16 v6; + s16 v7; + struct_itr_sema *v8; + int v9; + u16 v10; + u16 v11; + u16 v12[65]; + s32 input_word_count; + u16 v14; + u16 ack_status[65]; + u32 v16[41]; + + v2 = AllocItrSema(); + v3 = v2; + if (!v2) { + printf("DvrdrvExecCmdAck : Cannot alloc sema\n"); + return -1; + } + DvrdrvPrepareWaitCmdComp(v2, a1->command, a1->timeout); + a1->phase = 1; + DvrdrvBlockPhase(); + v5 = DvrdrvSendCmdAck( + v3, + a1->command, + a1->input_word, + a1->input_word_count, + &a1->status_4220_ack, + &a1->ack_status_ack, + &a1->status_4228_ack); + if (v5) { + v6 = a1->command; + } else { + DvrdrvUnblockPhase(); + a1->phase = 3; + DvrdrvBlockPhase(); + DvrdrvSetDmaDirection(0); + v7 = a1->command; + input_word_count = 0; + v11 = (v7 & 0xF0FF) | 0x300; + v8 = AllocItrSema(); + DvrdrvPrepareWaitDmaEnd(v8, v11); + v5 = DvrdrvSendCmdAck(v3, v11, v12, input_word_count, &v14, ack_status, v16); + if (v5) { + v6 = a1->command; + } else { + v5 = -1; + if (!ack_status[0]) { + v9 = (ack_status[1] << 16) + ack_status[2]; + a1->ack_status_ack2 = v9; + if (v9 <= 0) { + DvrdrvCancelWaitDmaEnd(v11); + } else { + DvrdrvTransferDma((u8 *)a1->output_buffer, v9); + DvrdrvWaitDmaEnd(v8, v11); + } + ReleaseItrSema(v8); + DvrdrvUnblockPhase(); + v10 = a1->command; + a1->phase = 4; + v5 = DvrdrvWaitCmdComp(v3, v10, &a1->status_4220_comp, &a1->comp_status, &a1->status_4228_comp); + goto LABEL_14; + } + v6 = a1->command; + } + } + DvrdrvCancelWaitCmdComp(v6); + DvrdrvUnblockPhase(); +LABEL_14: + ReleaseItrSema(v3); + return v5; +} + +int DvrdrvExecCmdAckDma2Comp(drvdrv_exec_cmd_ack *a1) +{ + struct_itr_sema *v2; + struct_itr_sema *v3; + int v5; + int v6; + s16 v7; + struct_itr_sema *v8; + u16 v9; + s16 v10; + struct_itr_sema *v11; + int v12; + u16 v13; + u16 v14; + u16 v15[65]; + s32 input_word_count; + u16 v17; + u16 ack_status[65]; + u32 v19[37]; + int v20; + u16 v21; + u16 v22[65]; + s32 v23; + u16 v24; + u16 v25[65]; + u32 v26[41]; + + v2 = AllocItrSema(); + v3 = v2; + if (!v2) { + printf("DvrdrvExecCmdAck : Cannot alloc sema\n"); + return -1; + } + DvrdrvPrepareWaitCmdComp(v2, a1->command, a1->timeout); + a1->phase = 1; + DvrdrvBlockPhase(); + v5 = DvrdrvSendCmdAck( + v3, + a1->command, + a1->input_word, + a1->input_word_count, + &a1->status_4220_ack, + &a1->ack_status_ack, + &a1->status_4228_ack); + if (v5) + goto LABEL_15; + DvrdrvUnblockPhase(); + a1->phase = 2; + DvrdrvBlockPhase(); + DvrdrvSetDmaDirection(1u); + v6 = a1->input_buffer_length; + v20 = (v6 & 0x7F) != 0 ? (v6 / 128 + 1) << 7 : a1->input_buffer_length; + v7 = a1->command; + input_word_count = 2; + v14 = (v7 & 0xF0FF) | 0x200; + v15[0] = (v20 & 0xFFFF0000) >> 16; + v15[1] = v20; + v8 = AllocItrSema(); + DvrdrvPrepareWaitDmaEnd(v8, v14); + v5 = DvrdrvSendCmdAck(v3, v14, v15, input_word_count, &v17, ack_status, v19); + if (v5) { + LABEL_15: + v9 = a1->command; + goto LABEL_16; + } + v5 = -1; + if (!ack_status[0]) { + if (v20 <= 0) { + DvrdrvCancelWaitDmaEnd(v14); + } else { + DvrdrvTransferDma(a1->input_buffer, v20); + DvrdrvWaitDmaEnd(v8, v14); + } + ReleaseItrSema(v8); + DvrdrvUnblockPhase(); + a1->phase = 3; + DvrdrvBlockPhase(); + DvrdrvSetDmaDirection(0); + v10 = a1->command; + v23 = 0; + v21 = (v10 & 0xF0FF) | 0x300; + v11 = AllocItrSema(); + DvrdrvPrepareWaitDmaEnd(v11, v21); + v5 = DvrdrvSendCmdAck(v3, v21, v22, v23, &v24, v25, v26); + if (!v5 && !v25[0]) { + v12 = (v25[1] << 16) + v25[2]; + a1->ack_status_ack2 = v12; + if (v12 <= 0) { + DvrdrvCancelWaitDmaEnd(v21); + } else { + DvrdrvTransferDma((u8 *)a1->output_buffer, v12); + DvrdrvWaitDmaEnd(v11, v21); + } + ReleaseItrSema(v11); + DvrdrvUnblockPhase(); + v13 = a1->command; + a1->phase = 4; + v5 = DvrdrvWaitCmdComp(v3, v13, &a1->status_4220_comp, &a1->comp_status, &a1->status_4228_comp); + goto LABEL_21; + } + goto LABEL_15; + } + v9 = a1->command; +LABEL_16: + DvrdrvCancelWaitCmdComp(v9); + DvrdrvUnblockPhase(); +LABEL_21: + ReleaseItrSema(v3); + return v5; +} diff --git a/sps2_basement/hardware/dev9/pvrdrv/src/exports.tab b/sps2_basement/hardware/dev9/pvrdrv/src/exports.tab new file mode 100644 index 0000000..9a56d18 --- /dev/null +++ b/sps2_basement/hardware/dev9/pvrdrv/src/exports.tab @@ -0,0 +1,19 @@ + +DECLARE_EXPORT_TABLE(pvrdrv, 1, 1) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(DvrdrvResetSystem) + DECLARE_EXPORT(DvrdrvEnableIntr) + DECLARE_EXPORT(DvrdrvDisableIntr) + DECLARE_EXPORT(DvrdrvRegisterIntrHandler) + DECLARE_EXPORT(DvrdrvUnregisterIntrHandler) + DECLARE_EXPORT(DvrdrvExecCmdAck) + DECLARE_EXPORT(DvrdrvExecCmdAckComp) + DECLARE_EXPORT(DvrdrvExecCmdAckDmaSendComp) + DECLARE_EXPORT(DvrdrvExecCmdAckDmaRecvComp) + DECLARE_EXPORT(DvrdrvExecCmdAckDma2Comp) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/dev9/pvrdrv/src/imports.lst b/sps2_basement/hardware/dev9/pvrdrv/src/imports.lst new file mode 100644 index 0000000..8a90afa --- /dev/null +++ b/sps2_basement/hardware/dev9/pvrdrv/src/imports.lst @@ -0,0 +1,47 @@ + +dev9_IMPORTS_start +I_dev9RegisterIntrCb +I_dev9DmaTransfer +I_dev9IntrEnable +I_dev9IntrDisable +I_dev9RegisterPreDmaCb +I_dev9RegisterPostDmaCb +dev9_IMPORTS_end + +sysmem_IMPORTS_start +I_Kprintf +sysmem_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +I_ReleaseLibraryEntries +loadcore_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_iReleaseWaitThread +I_GetThreadId +I_SleepThread +I_iWakeupThread +I_DelayThread +I_SetAlarm +I_CancelAlarm +I_USec2SysClock +I_GetSystemTime +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_iSignalSema +I_WaitSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/dev9/pvrdrv/src/irx_imports.h b/sps2_basement/hardware/dev9/pvrdrv/src/irx_imports.h new file mode 100644 index 0000000..01c964a --- /dev/null +++ b/sps2_basement/hardware/dev9/pvrdrv/src/irx_imports.h @@ -0,0 +1,27 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "dev9.h" +#include "intrman.h" +#include "loadcore.h" +#include "stdio.h" +#include "sysmem.h" +#include "thbase.h" +#include "thsemap.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dvrp/Makefile b/sps2_basement/hardware/dvrp/Makefile new file mode 100644 index 0000000..a5deb58 --- /dev/null +++ b/sps2_basement/hardware/dvrp/Makefile @@ -0,0 +1,12 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +SUBDIRS = dvr dvrav dvrdv dvrfile dvripl dvrmisc + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/Rules.make diff --git a/sps2_basement/hardware/dvrp/dvr/Makefile b/sps2_basement/hardware/dvrp/dvr/Makefile new file mode 100644 index 0000000..c336f03 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvr/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/pvrdrv/include +IOP_OBJS = dvr.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dvrp/dvr/src/dvr.c b/sps2_basement/hardware/dvrp/dvr/src/dvr.c new file mode 100644 index 0000000..e4e4650 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvr/src/dvr.c @@ -0,0 +1,1410 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thsemap.h" +#include "speedregs.h" +#include "errno.h" + +extern int module_start(); +extern int module_stop(); +extern int dvr_df_init(iop_device_t *dev); +extern int dvr_df_exit(iop_device_t *dev); +extern int dvr_df_ioctl(iop_file_t *f, int cmd, void *param); +extern int dvr_df_devctl(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvr_df_ioctl2(iop_file_t *f, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvr_df_null(); +extern s64 dvr_df_null_long(); +extern int dvrioctl2_rec_start(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_rec_pause(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_rec_stop(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_set_rec_end_time(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_rec_info(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_rec_time(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_read_resfile(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_clear_resfile_flag(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_rec_prohibit(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_status_register(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_ifo_time_entry(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_ifo_vobu_entry(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_epg_test(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_send_timer_event(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_epg_cancel(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_tevent_buf_clr(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_tevent_buf_send(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_tevent_buf_trans_dvrp(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_start_hdd_test(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_stop_hdd_test(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_hdd_test_stat(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_pre_update_a(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_pre_update_b(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_rec_vro_pckn(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_enc_dec_test(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_tevent_buf_recv_first(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_tevent_buf_recv_next(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_finish_auto_process(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_make_menu(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_re_enc_start(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_rec_pictclip(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrpAuthEnc(u16); + +// The following has been excluded. +unsigned char dvrpAuth_tbl[256] = {0x00}; + +struct DevctlCmdTbl_t +{ + u16 cmd; + int (*fn)(iop_file_t *, const char *, int, void *, unsigned int, void *, unsigned int); +} DevctlCmdTbl[31] = + { + {0x5663, &dvrioctl2_get_status_register}, + {0x5638, &dvrioctl2_get_ifo_time_entry}, + {0x5639, &dvrioctl2_get_ifo_vobu_entry}, + {0x5632, &dvrioctl2_rec_start}, + {0x5633, &dvrioctl2_rec_pause}, + {0x5634, &dvrioctl2_rec_stop}, + {0x5635, &dvrioctl2_set_rec_end_time}, + {0x5636, &dvrioctl2_get_rec_info}, + {0x5637, &dvrioctl2_get_rec_time}, + {0x563A, &dvrioctl2_read_resfile}, + {0x563B, &dvrioctl2_clear_resfile_flag}, + {0x563F, &dvrioctl2_rec_prohibit}, + {0x5640, &dvrioctl2_epg_test}, + {0x5641, &dvrioctl2_send_timer_event}, + {0x5642, &dvrioctl2_epg_cancel}, + {0x565A, &dvrioctl2_tevent_buf_clr}, + {0x565B, &dvrioctl2_tevent_buf_send}, + {0x565C, &dvrioctl2_tevent_buf_trans_dvrp}, + {0x5643, &dvrioctl2_start_hdd_test}, + {0x5644, &dvrioctl2_stop_hdd_test}, + {0x5645, &dvrioctl2_get_hdd_test_stat}, + {0x5646, &dvrioctl2_pre_update_a}, + {0x5647, &dvrioctl2_pre_update_b}, + {0x5648, &dvrioctl2_get_rec_vro_pckn}, + {0x5649, &dvrioctl2_enc_dec_test}, + {0x565D, &dvrioctl2_tevent_buf_recv_first}, + {0x565E, &dvrioctl2_tevent_buf_recv_next}, + {0x5651, &dvrioctl2_finish_auto_process}, + {0x564A, &dvrioctl2_make_menu}, + {0x564B, &dvrioctl2_re_enc_start}, + {0x5650, &dvrioctl2_rec_pictclip}, +}; + +struct _iop_device_ops DvrFuncTbl = + { + &dvr_df_init, + &dvr_df_exit, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_ioctl, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null, + &dvr_df_null_long, + &dvr_df_devctl, + &dvr_df_null, + &dvr_df_null, + &dvr_df_ioctl2}; +char TEVENT_BUF[6144]; +char *tevent_p; +int tevent_data_sz; +iop_device_t DVR; +s32 sema_id; + +// Based off of DESR / PSX DVR system software version 1.31. +// Added additional functions from DESR / PSX DVR system software version 2.11. +#define MODNAME "DVR" +IRX_ID(MODNAME, 1, 1); + +int _start(int a1, char **argv) +{ + if (a1 >= 0) + return module_start(); + else + return module_stop(); +} + +int module_start() +{ + int i; + + for (i = 0; i < 30000; ++i) { + if (((*((vu32 *)0xB0004230)) & 0x10) != 0) + break; + DelayThread(1000); + } + if (i == 30000) { + printf("DVR task of DVRP is not running...\n"); + return 1; + } else { + DVR.name = "dvr"; + DVR.desc = "Digital Video Recorder DVR task"; + DVR.type = 0x10000010; + DVR.ops = &DvrFuncTbl; + if (AddDrv(&DVR) != 0) + return 1; + } +#if 0 + return 2; +#else + return 0; +#endif +} + +int module_stop() +{ + if (DelDrv("dvr") != 0) + return 2; + return 1; +} + +int dvr_df_init(iop_device_t *dev) +{ + int v1; + iop_sema_t v3; + + v3.attr = 0; + v3.initial = 1; + v3.max = 1; + v3.option = 0; + v1 = CreateSema(&v3); + if (v1 < 0) + return -1; + sema_id = v1; + return 0; +} + +int dvr_df_exit(iop_device_t *dev) +{ + if (DeleteSema(sema_id) != 0) + return -1; + return 0; +} + +int dvr_df_ioctl(iop_file_t *f, int cmd, void *param) +{ + WaitSema(sema_id); + SignalSema(sema_id); + return -22; +} + +int dvr_df_devctl( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v11; + unsigned int v12; + unsigned int v13; + + v11 = 0; + v12 = 0; + WaitSema(sema_id); + v13 = 0; + while (DevctlCmdTbl[v13].cmd != cmd) { + v13 = ++v12; + if (v12 >= sizeof(DevctlCmdTbl) / sizeof(DevctlCmdTbl[0])) + goto LABEL_5; + } + v11 = DevctlCmdTbl[v13].fn(a1, name, cmd, arg, arglen, buf, buflen); +LABEL_5: + if (v12 == sizeof(DevctlCmdTbl) / sizeof(DevctlCmdTbl[0])) + v11 = -22; + SignalSema(sema_id); + return v11; +} + +int dvr_df_ioctl2(iop_file_t *f, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen) +{ + WaitSema(sema_id); + SignalSema(sema_id); + return -22; +} + +int dvr_df_null() +{ + return -48; +} + +s64 dvr_df_null_long() +{ + return -48LL; +} + +int dvrioctl2_rec_start( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int busywait; + int cmdackerr; + int err; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2101; + cmdack.input_word[0] = *((u16 *)arg + 1); + cmdack.input_word[1] = *(u16 *)arg; + cmdack.input_word[2] = *((u16 *)arg + 3); + cmdack.input_word[3] = *((u16 *)arg + 2); + cmdack.input_word[4] = *((u16 *)arg + 4); + cmdack.input_word[5] = *((u16 *)arg + 5); + cmdack.input_word[6] = *((u16 *)arg + 6); + busywait = 0x4; + while (busywait-- >= 0) + ; + cmdack.input_word_count = 7; + cmdack.timeout = 5000000; + cmdackerr = DvrdrvExecCmdAckComp(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_rec_start -> Handshake error!,%d\n", cmdackerr); + return -5; + } + err = cmdack.ack_status_ack; + if (!cmdack.ack_status_ack) { + if (!cmdack.comp_status) + return 0; + err = cmdack.comp_status; + } + printf("dvrioctl2_rec_start -> Status error!,%04X\n", err); + return -68; +} + +int dvrioctl2_rec_pause( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v7; + drvdrv_exec_cmd_ack *p_cmdack; + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + v7 = 0; + p_cmdack = &cmdack; + cmdack.command = 0x2102; + do { + ++v7; + p_cmdack->input_word[0] = *(u16 *)arg; + arg = (char *)arg + 2; + p_cmdack = (drvdrv_exec_cmd_ack *)((char *)p_cmdack + 2); + } while (v7 <= 0); + cmdack.input_word_count = 1; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_rec_pause -> Handshake error!,%d\n", cmdackerr); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_rec_pause -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_rec_stop( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2103; + cmdack.input_word_count = 0; + cmdack.timeout = 5000000; + cmdackerr = DvrdrvExecCmdAckComp(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_rec_stop -> Handshake error!,%d\n", cmdackerr); + return -5; + } + if (cmdack.ack_status_ack) { + printf("dvrioctl2_rec_stop -> Status error!,%04X\n", cmdack.ack_status_ack); + } else { + if (!cmdack.comp_status) + return 0; + printf("dvrioctl2_rec_start -> Status error!,%04X\n", cmdack.comp_status); + } + return -68; +} + +int dvrioctl2_set_rec_end_time( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2104; + cmdack.input_word[0] = (*(u32 *)arg) >> 16; + cmdack.input_word_count = 2; + cmdack.input_word[1] = *(u16 *)arg; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_rec_end_time -> Handshake error!,%d\n", cmdackerr); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_rec_end_time -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_get_rec_info( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + if (buflen >= 0x15) { + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + cmdack.command = 0x2105; + cmdack.input_word_count = 0; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_get_rec_info -> Handshake error!,%d\n", cmdackerr); + return -5; + } else { + int v9; + v9 = 0; + if (cmdack.ack_status_ack) { + printf("dvrioctl2_get_rec_info -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } else { + int v10; + *(u16 *)buf = 0; + v10 = 0; + do { + u16 *v11; + v9 += 1; + v11 = &cmdack.output_word[v9]; + *((u8 *)buf + v10 + 3) = (*v11 & 0xFF00) >> 8; + *((u8 *)buf + v10 + 2) = (*v11 & 0x00FF); + v10 = 2 * v9; + } while (v9 < 10); + *((u8 *)buf + 22) = 0; + return 0; + } + } + } else { + printf("dvrioctl2_get_rec_info -> buflen is smaller than 21.\n"); + return -22; + } +} + +int dvrioctl2_get_rec_time( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2106; + cmdack.input_word_count = 0; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_get_rec_time -> Handshake error!,%d\n", cmdackerr); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_get_rec_time -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } else { + *(u16 *)buf = 0; + *((u32 *)buf + 1) = (cmdack.output_word[0] << 16) + cmdack.output_word[1]; + } + } + return 0; +} + +int dvrioctl2_get_ifo_time_entry( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2107; + cmdack.input_word_count = 0; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_get_ifo_time_entry -> Handshake error!,%d\n", cmdackerr); + return -5; + } else if (cmdack.ack_status_ack) { + printf("dvrioctl2_get_ifo_time_entry -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } else { + *(u16 *)buf = 0; + *((u16 *)buf + 1) = cmdack.output_word[0]; + *((u16 *)buf + 2) = cmdack.output_word[1]; + *((u16 *)buf + 3) = cmdack.output_word[2]; + *((u32 *)buf + 2) = (cmdack.output_word[3] << 16) + cmdack.output_word[4]; + } + return 0; +} + +int dvrioctl2_get_ifo_vobu_entry( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2108; + cmdack.input_word_count = 0; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_get_ifo_vobu_entry -> Handshake error!,%d\n", cmdackerr); + return -5; + } else if (cmdack.ack_status_ack) { + printf("dvrioctl2_get_ifo_vobu_entry -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } else { + *(u16 *)buf = 0; + *((u16 *)buf + 1) = cmdack.output_word[0]; + *((u16 *)buf + 2) = cmdack.output_word[1]; + *((u16 *)buf + 3) = cmdack.output_word[2]; + } + return 0; +} + +int dvrioctl2_read_resfile( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2109; + cmdack.input_word_count = 0; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_read_resfile -> Handshake error!,%d\n", cmdackerr); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_read_resfile -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_clear_resfile_flag( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x210A; + cmdack.input_word_count = 0; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_clear_resfile_flag -> Handshake error!,%d\n", cmdackerr); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_clear_resfile_flag -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_rec_prohibit( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x210E; + cmdack.input_word_count = 1; + cmdack.input_word[0] = *(u16 *)arg; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_rec_prohibit -> Handshake error!,%d\n", cmdackerr); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_rec_prohibit -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_epg_test( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x210F; + cmdack.input_word_count = 1; + cmdack.input_word[0] = *(u16 *)arg; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_epg_test -> Handshake error!,%d\n", cmdackerr); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_epg_test -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_send_timer_event( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2110; + cmdack.input_word_count = 0; + cmdack.input_buffer = arg; + cmdack.timeout = 10000000; + cmdack.input_buffer_length = arglen; + if (DvrdrvExecCmdAckDmaSendComp(&cmdack)) { + printf("dvrioctl2_send_timer_event -> IO error (phase %d)\n", cmdack.phase); + return -5; + } else { + if (cmdack.comp_status) { + printf( + "dvrioctl2_send_timer_event -> Complete parameter (%04X) error (phase %d)\n", + cmdack.comp_status, + cmdack.phase); + return -5; + } + } + return 0; +} + +int dvrioctl2_epg_cancel( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2111; + cmdack.input_word_count = 0; + cmdack.input_word[0] = *(u16 *)arg; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_epg_cancel -> Handshake error!,%d\n", cmdackerr); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_epg_cancel -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_get_status_register( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + *(u16 *)buf = (*((vu32 *)0xB0004230)); + *((u16 *)buf + 1) = (*((vu32 *)0xB0004234)); + *((u16 *)buf + 2) = (*((vu32 *)0xB0004238)); + *((u16 *)buf + 3) = (*((vu32 *)0xB000423C)); + return 0; +} + +int dvrioctl2_tevent_buf_clr( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v7; + char *v8; + + v7 = 6143; + v8 = &TEVENT_BUF[6143]; + do { + *v8 = 0; + --v7; + --v8; + } while (v7 >= 0); + tevent_p = TEVENT_BUF; + tevent_data_sz = 0; + return 0; +} + +int dvrioctl2_tevent_buf_send( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + if ((int)(tevent_data_sz + arglen) < 0x1801) { + signed int i; + for (i = 0; i < (int)arglen; arg = (char *)arg + 1) { + ++i; + *tevent_p = *(u8 *)arg; + tevent_p += 1; + } + tevent_data_sz += arglen; + } + return 0; +} + +int dvrioctl2_tevent_buf_trans_dvrp( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2110; + cmdack.input_word_count = 0; + cmdack.input_buffer = TEVENT_BUF; + cmdack.timeout = 10000000; + cmdack.input_buffer_length = tevent_data_sz; + if (DvrdrvExecCmdAckDmaSendComp(&cmdack)) { + printf("dvrioctl2_tevent_buf_trans_dvrp -> IO error (phase %d)\n", cmdack.phase); + return -5; + } else { + if (cmdack.comp_status) { + printf( + "dvrioctl2_tevent_buf_trans_dvrp -> Complete parameter (%04X) error (phase %d)\n", + cmdack.comp_status, + cmdack.phase); + return -5; + } + } + return 0; +} + +int dvrioctl2_start_hdd_test( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + int ack_status_ack; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2112; + cmdack.input_word[0] = *(u16 *)arg; + cmdack.input_word[1] = *((u16 *)arg + 3); + cmdack.input_word[2] = *((u16 *)arg + 2); + cmdack.input_word[3] = *((u16 *)arg + 5); + cmdack.input_word[4] = *((u16 *)arg + 4); + cmdack.input_word[5] = *((u16 *)arg + 6); + cmdack.input_word[6] = *((u16 *)arg + 7); + cmdack.input_word[7] = *((u16 *)arg + 8); + cmdack.input_word_count = 8; + cmdack.timeout = 1000000 * (*((u16 *)arg + 8) + 30); + cmdackerr = DvrdrvExecCmdAckComp(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_start_hdd_test -> Handshake error!,%d\n", cmdackerr); + return -5; + } + ack_status_ack = cmdack.ack_status_ack; + if (!cmdack.ack_status_ack) { + if (!cmdack.comp_status) + return 0; + ack_status_ack = cmdack.comp_status; + } + printf("dvrioctl2_start_hdd_test -> Status error!,%04X\n", ack_status_ack); + return -68; +} + +int dvrioctl2_stop_hdd_test( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + int ack_status_ack; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2113; + cmdack.input_word_count = 0; + cmdack.timeout = 30000000; + cmdackerr = DvrdrvExecCmdAckComp(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_stop_hdd_test -> Handshake error!,%d\n", cmdackerr); + return -5; + } + ack_status_ack = cmdack.ack_status_ack; + if (!cmdack.ack_status_ack) { + if (!cmdack.comp_status) + return 0; + ack_status_ack = cmdack.comp_status; + } + printf("dvrioctl2_stop_hdd_test -> Status error!,%04X\n", ack_status_ack); + return -68; +} + +int dvrioctl2_get_hdd_test_stat( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2114; + cmdack.input_word_count = 0; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_get_hdd_test_stat -> Handshake error!,%d\n", cmdackerr); + return -5; + } else if (cmdack.ack_status_ack) { + printf("dvrioctl2_get_hdd_test_stat -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + *((u32 *)buf + 1) = (cmdack.output_word[1] << 16) + cmdack.output_word[2]; + *((u32 *)buf + 2) = (cmdack.output_word[3] << 16) + cmdack.output_word[4]; + *((u16 *)buf + 6) = cmdack.output_word[5]; + *((u16 *)buf + 7) = cmdack.output_word[6]; + *((u16 *)buf + 8) = cmdack.output_word[7]; + } + return 0; +} + +int dvrioctl2_pre_update_a( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2115; + cmdack.input_word_count = 0; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_pre_update_a -> Handshake error!,%d\n", cmdackerr); + return -5; + } else if (cmdack.ack_status_ack) { + printf("dvrioctl2_pre_update_a -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } else { + *(u16 *)buf = dvrpAuthEnc(cmdack.output_word[0]); + return 0; + } +} + +int dvrioctl2_pre_update_b( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + int ack_status_ack; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2116; + cmdack.input_word_count = 1; + cmdack.timeout = 10000000; + cmdack.input_word[0] = *(u16 *)arg; + cmdackerr = DvrdrvExecCmdAckComp(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_pre_update_b -> Handshake error!,%d\n", cmdackerr); + return -5; + } + ack_status_ack = cmdack.ack_status_ack; + if (!cmdack.ack_status_ack) { + if (!cmdack.comp_status) + return 0; + ack_status_ack = cmdack.comp_status; + } + printf("dvrioctl2_pre_update_b -> Status error!,%04X\n", ack_status_ack); + return -68; +} + +int dvrioctl2_get_rec_vro_pckn( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2117; + cmdack.input_word_count = 0; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_get_rec_vro_pckn -> Handshake error!,%d\n", cmdackerr); + return -5; + } + if (cmdack.ack_status_ack == 0xFFFE) { + printf("dvrioctl2_get_rec_vro_pckn -> Mode error!,%04X\n", 0xFFFE); + } else { + if (!cmdack.ack_status_ack) { + *(u32 *)buf = (cmdack.output_word[0] << 16) + cmdack.output_word[1]; + return 0; + } + printf("dvrioctl2_get_rec_vro_pckn -> Status error!,%04X\n", cmdack.ack_status_ack); + } + return -68; +} + +int dvrioctl2_enc_dec_test( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2118; + cmdack.input_word_count = 1; + cmdack.timeout = 10000000; + cmdack.input_word[0] = *(u16 *)arg; + cmdackerr = DvrdrvExecCmdAckComp(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_enc_dec_test -> ACK Handshake error!,%d\n", cmdackerr); + return -5; + } + if (cmdack.ack_status_ack) { + printf("dvrioctl2_enc_dec_test -> ACK Status error!,%04X\n", cmdack.ack_status_ack); + } else { + if (!cmdack.comp_status) + return 0; + printf("dvrioctl2_enc_dec_test -> COMP Status error!,%04X\n", cmdack.comp_status); + } + return -68; +} + +int dvrioctl2_make_menu( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v7; + int v8; + int v9; + u16 *v11; + int cmdackerr; + int v16; + int v17; + u16 *input_word; + int v19; + int busywait; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x2119; + cmdack.input_word[0] = *((u16 *)arg + 1); + cmdack.input_word[1] = *(u16 *)arg; + cmdack.input_word[2] = *((u16 *)arg + 3); + cmdack.input_word[3] = *((u16 *)arg + 2); + cmdack.input_word[4] = *((u16 *)arg + 4); + cmdack.input_word[5] = 0; + v7 = 6; + v8 = 1; + v9 = 0; + v11 = &cmdack.input_word[5]; + do { + char *v12; + char *v13; + v12 = (char *)arg + v8; + v8 += 2; + v13 = (char *)arg + v9; + v9 += 2; + ++v7; + v11[1] = v13[10] + ((u8)v12[10] << 8); + ++v11; + } while (v7 < 16); + cmdack.input_word_count = 16; + cmdack.timeout = 30000000; + cmdackerr = DvrdrvExecCmdAckComp(&cmdack); + *(u16 *)buf = cmdack.comp_status; + if (cmdackerr) { + printf("dvrioctl2_make_menu -> ACK Handshake error!,%d\n", cmdackerr); + return -5; + } + if (cmdack.ack_status_ack) { + printf("dvrioctl2_make_menu -> ACK Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + v16 = 1; + if (cmdack.comp_status) { + printf("dvrioctl2_make_menu -> COMP Status error!,%04X\n", cmdack.comp_status); + return -68; + } + v17 = 1; + input_word = cmdack.return_result_word; + v19 = 0; + do { + char *v20; + char *v21; + v20 = (char *)buf + v17; + v21 = (char *)buf + v19; + v17 += 2; + v19 += 2; + v16 += 1; + v21[2] = (*input_word & 0x00FF); + v20[2] = (*input_word & 0xFF00) >> 8; + input_word += 1; + } while (v16 < 11); + *((u8 *)buf + 22) = 0; + busywait = 0x14; + while (busywait-- >= 0) + ; + return 0; +} + +int dvrioctl2_re_enc_start( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v7; + int v8; + int v9; + u16 *v10; + int v13; + int v14; + int v15; + u16 *v16; + int busywait; + int cmdackerr; + int v24; + int v25; + u16 *v26; + int v27; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x211A; + cmdack.input_word[0] = *((u16 *)arg + 1); + cmdack.input_word[1] = *(u16 *)arg; + cmdack.input_word[2] = *((u16 *)arg + 3); + cmdack.input_word[3] = *((u16 *)arg + 2); + cmdack.input_word[4] = *((u16 *)arg + 4); + cmdack.input_word[5] = *((u16 *)arg + 5); + cmdack.input_word[6] = *((u16 *)arg + 6); + v7 = 7; + v8 = 1; + v9 = 0; + v10 = &cmdack.input_word[6]; + do { + u8 *v11; + u8 *v12; + v11 = (u8 *)arg + v8; + v12 = (u8 *)arg + v9; + v10[1] = v12[14] + ((u8)v11[14] << 8); + v8 += 2; + v9 += 2; + v7 += 1; + v10 += 1; + } while (v7 < 17); + cmdack.input_word[17] = 0; + v13 = 18; + v14 = 1; + v15 = 0; + v16 = &cmdack.input_word[17]; + do { + u8 *v17; + u8 *v18; + v17 = (u8 *)arg + v14; + v18 = (u8 *)arg + v15; + v16[1] = v18[35] + ((u8)v17[35] << 8); + v14 += 2; + v15 += 2; + v13 += 1; + v16 += 1; + } while (v13 < 28); + cmdack.input_word[26] = 0; + cmdack.input_word[27] = 0; + cmdack.input_word[28] = *((u16 *)arg + 28); + cmdack.input_word[29] = *((u16 *)arg + 29); + cmdack.input_word[30] = *((u16 *)arg + 30); + cmdack.input_word[31] = *((u16 *)arg + 31); + cmdack.input_word[32] = 0; + busywait = 0x1f; + while (busywait-- >= 0) + ; + cmdack.input_word_count = 33; + cmdack.timeout = 30000000; + cmdackerr = DvrdrvExecCmdAckComp(&cmdack); + *(u16 *)buf = cmdack.comp_status; + if (cmdackerr) { + printf("dvrioctl2_re_enc_start -> ACK Handshake error!,%d\n", cmdackerr); + return -5; + } + if (cmdack.ack_status_ack) { + printf("dvrioctl2_re_enc_start -> ACK Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + v24 = 2; + if (cmdack.comp_status) { + printf("dvrioctl2_re_enc_start -> COMP Status error!,%04X\n", cmdack.comp_status); + return -68; + } + v25 = 1; + v26 = &cmdack.input_word[1]; + v27 = 0; + do { + u8 *v28; + u8 *v29; + v28 = (u8 *)buf + v25; + v29 = (u8 *)buf + v27; + v29[2] = *((u8 *)v26 + 274); + v28[2] = v26[137] >> 8; + v25 += 2; + v27 += 2; + v24 += 1; + v26 += 1; + } while (v24 < 12); + *((u8 *)buf + 22) = 0; + return 0; +} + +int dvrpAuthEnc(u16 a1) +{ + return (u8)dvrpAuth_tbl[(u8)a1] | ((u8)dvrpAuth_tbl[a1 >> 8] << 8); +} + +int dvr_recv_dma(iop_file_t *a1, u8 *buf, int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + printf("------------------- 2 ------------------ dvr_recv_dma(io=%p, buf=%p, buflen=%d)\n", a1, buf, buflen); + if (((u32)buf & 3) != 0) { + printf("dvr_recv_dma : Address is not a multiple of 4.\n"); + return -14; + } else { + u8 *buf_tmp; + int buflen_tmp; + int ack_status_ack2; + int err; + buf_tmp = buf; + if ((buflen & 0x7F) != 0) + printf("buflen is not a multiple of 128.\n"); + buflen_tmp = buflen; + while (buflen_tmp > 0) { + cmdack.command = 0x211B; + cmdack.input_word[0] = 0; + cmdack.input_word[1] = 0; + cmdack.input_word[2] = 0; + cmdack.input_word[3] = 6144; + cmdack.input_word_count = 4; + cmdack.output_buffer = buf_tmp; + cmdack.timeout = 0x10000; + if (DvrdrvExecCmdAckDmaRecvComp(&cmdack)) { + err = -5; + printf("dvr_recv_dma : IO error (phase %d)\n", cmdack.phase); + goto finish; + } + if (cmdack.comp_status) { + err = -5; + printf("dvr_recv_dma : Complete parameter error (phase %d), %04X\n", cmdack.phase, cmdack.comp_status); + goto finish; + } + ack_status_ack2 = cmdack.ack_status_ack2; + printf("rsize : %d / %d \n", cmdack.ack_status_ack2, 6144); + if (ack_status_ack2 <= 0) + break; + buflen_tmp -= ack_status_ack2; + if (ack_status_ack2 < 0x1801) + break; + buf_tmp += ack_status_ack2; + } + err = cmdack.ack_status_ack2; + finish: + printf("dvr_recv_dma: ret = %d\n", err); + return err; + } +} + +u8 TELTEXT_BUF[0x1800]; +unsigned int TELTEXT_ACTLEN; +unsigned int TELTEXT_BUFOFFSET; + +int dvrioctl2_tevent_buf_recv_first( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + TELTEXT_BUFOFFSET = 0; + TELTEXT_ACTLEN = 0; + printf("dvr_tevent_buf_recv_first(io=%p, cmd=%d buf=%p, nbyte=%u)\n", a1, cmd, buf, buflen); + TELTEXT_ACTLEN = dvr_recv_dma(a1, TELTEXT_BUF, sizeof(TELTEXT_BUF)); + if ((TELTEXT_ACTLEN & 0x80000000) == 0) { + if (buflen == 1024) { + memcpy(buf, (u8 *)TELTEXT_BUF + TELTEXT_BUFOFFSET, 1024); + TELTEXT_BUFOFFSET += 1024; + if (TELTEXT_ACTLEN <= 0x400) { + printf("tevent_buf_recv_first: actlen:%u request-buflen:%d return 0 < DMA EOT >\n", TELTEXT_ACTLEN, 1024); + return 0; + } else { + printf("tevent_buf_recv_first: return \n"); + return 0xFFE5; + } + } else { + printf("tevent_buf_recv_first: bufflen error! return 0 < EOT > .\n"); + return 0; + } + } else { + printf("tevent_buf_recv_first: dma error! return 0 < EOT >.\n"); + return 0; + } +} + +int dvrioctl2_tevent_buf_recv_next( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + printf("dvr_tevent_buf_recv_next(io=%p, cmd=%d buf=%p, nbyte=%u)\n", a1, cmd, buf, buflen); + if (buflen == 1024) { + if (TELTEXT_BUFOFFSET + 1024 < sizeof(TELTEXT_BUF)) { + memcpy(buf, TELTEXT_BUF + TELTEXT_BUFOFFSET, 1024); + TELTEXT_BUFOFFSET += 1024; + if ((int)TELTEXT_BUFOFFSET < (int)TELTEXT_ACTLEN) { + printf("tevent_buf_recv_next: return \n"); + return 65509; + } + printf("tevent_buf_recv_next: return 0 < DMA EOT >!\n"); + } else { + printf("tevent_buf_recv_next: bufflen error!\n"); + } + } else { + printf("tevent_buf_recv_next: bufflen error!\n"); + } + return 0; +} + +int dvrioctl2_finish_auto_process( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x211C; + cmdack.input_word_count = 1; + cmdack.timeout = 5000000; + cmdack.input_word[0] = *(u16 *)arg; + cmdackerr = DvrdrvExecCmdAck(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_finish_auto_process -> Handshake error!,%d\n", cmdackerr); + return -5; + } + if (cmdack.ack_status_ack == 0xFFFE) { + printf("dvrioctl2_finish_auto_process -> Mode error!,%04X\n", 0xFFFE); + } else { + if (!cmdack.ack_status_ack) { + *(u32 *)buf = (cmdack.output_word[0] << 16) + cmdack.output_word[1]; + return 0; + } + printf("dvrioctl2_finish_auto_process -> Status error!,%04X\n", cmdack.ack_status_ack); + } + return -68; +} + +int dvrioctl2_rec_pictclip( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int busywait; + int cmdackerr; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x211D; + cmdack.input_word[0] = *((u16 *)arg + 1); + cmdack.input_word[1] = *((u16 *)arg + 0); + cmdack.input_word[2] = *((u16 *)arg + 3); + cmdack.input_word[3] = *((u16 *)arg + 2); + cmdack.input_word[4] = *((u16 *)arg + 4); + cmdack.input_word[5] = *((u16 *)arg + 5); + cmdack.input_word[6] = *((u16 *)arg + 6); + busywait = 4; + while (busywait-- >= 0) + ; + cmdack.input_word_count = 7; + cmdack.timeout = 30000000; + cmdackerr = DvrdrvExecCmdAckComp(&cmdack); + if (cmdackerr) { + printf("dvrioctl2_re_enc_start -> ACK Handshake error!,%d\n", cmdackerr); + return -5; + } + if (cmdack.ack_status_ack) { + printf("dvrioctl2_re_enc_start -> ACK Status error!,%04X\n", cmdack.ack_status_ack); + } else { + if (!cmdack.comp_status) + return 0; + printf("dvrioctl2_re_enc_start -> COMP Status error!,%04X\n", cmdack.comp_status); + } + return -68; +} diff --git a/sps2_basement/hardware/dvrp/dvr/src/imports.lst b/sps2_basement/hardware/dvrp/dvr/src/imports.lst new file mode 100644 index 0000000..ae3f42a --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvr/src/imports.lst @@ -0,0 +1,31 @@ + +iomanX_IMPORTS_start +I_AddDrv +I_DelDrv +iomanX_IMPORTS_end + +pvrdrv_IMPORTS_start +I_DvrdrvExecCmdAck +I_DvrdrvExecCmdAckComp +I_DvrdrvExecCmdAckDmaRecvComp +I_DvrdrvExecCmdAckDmaSendComp +pvrdrv_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memcpy +sysclib_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/dvrp/dvr/src/irx_imports.h b/sps2_basement/hardware/dvrp/dvr/src/irx_imports.h new file mode 100644 index 0000000..a56243d --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvr/src/irx_imports.h @@ -0,0 +1,24 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thsemap.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dvrp/dvrav/Makefile b/sps2_basement/hardware/dvrp/dvrav/Makefile new file mode 100644 index 0000000..33edc68 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrav/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/pvrdrv/include +IOP_OBJS = dvrav.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dvrp/dvrav/src/dvrav.c b/sps2_basement/hardware/dvrp/dvrav/src/dvrav.c new file mode 100644 index 0000000..cdb575e --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrav/src/dvrav.c @@ -0,0 +1,1046 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "thbase.h" +#include "thsemap.h" +#include "speedregs.h" +#include "errno.h" + +extern int module_start(); +extern int module_stop(); +extern int dvrav_df_init(iop_device_t *dev); +extern int dvrav_df_exit(iop_device_t *dev); +extern int dvrav_df_ioctl(iop_file_t *f, int cmd, void *param); +extern int dvrav_df_devctl(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrav_df_ioctl2(iop_file_t *f, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrav_df_null(); +extern s64 dvrav_df_null_long(); +extern int avioctl2_select_position(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_position(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_position_up(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_position_down(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_set_d_audio_sel(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_tun_offset(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_tun_offset_up(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_tun_offset_down(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_tun_scan_ch(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_bs_gain(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_set_preset_info(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_change_sound(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_set_d_video_sel(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_av_src(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_preset_info(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_set_position_info(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_position_info(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_tun_scan_mode(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_f_select_position(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_select_rec_src(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_rec_src(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_tun_scan_mode_euro(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_tun_scan_ch_euro(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_curfreq_info(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_teletext_ver_no(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_set_tv_guide_page(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_tv_guide_page(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_change_mode_tv_to_dvd(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_vps_data(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_pdc_data(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_format1_data(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_get_header_time_data(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int avioctl2_set_acs_position_euro(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); + +struct DevctlCmdTbl_t +{ + u16 cmd; + int (*fn)(iop_file_t *, int, void *, unsigned int, void *, unsigned int); +} DevctlCmdTbl[33] = + { + {0x5616, &avioctl2_select_position}, + {0x5619, &avioctl2_get_position}, + {0x5617, &avioctl2_position_up}, + {0x5618, &avioctl2_position_down}, + {0x5612, &avioctl2_set_d_audio_sel}, + {0x560B, &avioctl2_get_tun_offset}, + {0x560C, &avioctl2_tun_offset_up}, + {0x560D, &avioctl2_tun_offset_down}, + {0x560E, &avioctl2_tun_scan_ch}, + {0x560F, &avioctl2_get_bs_gain}, + {0x5610, &avioctl2_set_preset_info}, + {0x5611, &avioctl2_change_sound}, + {0x5613, &avioctl2_set_d_video_sel}, + {0x5614, &avioctl2_get_av_src}, + {0x5615, &avioctl2_get_preset_info}, + {0x561A, &avioctl2_set_position_info}, + {0x561B, &avioctl2_get_position_info}, + {0x561C, &avioctl2_tun_scan_mode}, + {0x561D, &avioctl2_f_select_position}, + {0x561E, &avioctl2_select_rec_src}, + {0x561F, &avioctl2_get_rec_src}, + {0x5618, &avioctl2_tun_scan_mode_euro}, + {0x5619, &avioctl2_tun_scan_ch_euro}, + {0x561A, &avioctl2_get_curfreq_info}, + {0x561B, &avioctl2_get_teletext_ver_no}, + {0x561C, &avioctl2_set_tv_guide_page}, + {0x561D, &avioctl2_get_tv_guide_page}, + {0x561E, &avioctl2_change_mode_tv_to_dvd}, + {0x561F, &avioctl2_get_vps_data}, + {0x5620, &avioctl2_get_pdc_data}, + {0x5621, &avioctl2_get_format1_data}, + {0x5622, &avioctl2_get_header_time_data}, + {0x5623, &avioctl2_set_acs_position_euro}, +}; + +struct _iop_device_ops DvrFuncTbl = + { + &dvrav_df_init, + &dvrav_df_exit, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_ioctl, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_null_long, + &dvrav_df_devctl, + &dvrav_df_null, + &dvrav_df_null, + &dvrav_df_ioctl2}; +iop_device_t DVRAV; +s32 sema_id; + +// Based off of DESR / PSX DVR system software version 1.31. +// Added additional functions from DESR / PSX DVR system software version 2.11. +#define MODNAME "DVRAV" +IRX_ID(MODNAME, 1, 1); + +int _start(int a1, char **argv) +{ + if (a1 >= 0) + return module_start(); + else + return module_stop(); +} + +int module_start() +{ + int i; + + for (i = 0; i < 30000; ++i) { + if (((*((vu32 *)0xB0004230)) & 8) != 0) + break; + DelayThread(1000); + } + if (i == 30000) { + printf("AV task of DVRP is not running...\n"); + return 1; + } else { + DVRAV.name = "dvr_av"; + DVRAV.desc = "Digital Video Recorder AV task"; + DVRAV.type = 0x10000010; + DVRAV.ops = &DvrFuncTbl; + if (AddDrv(&DVRAV) != 0) + return 1; + } +#if 0 + return 2; +#else + return 0; +#endif +} + +int module_stop() +{ + if (DelDrv("dvr_av") != 0) + return 2; + return 1; +} + +int dvrav_df_init(iop_device_t *dev) +{ + int v1; + iop_sema_t v3; + + v3.attr = 0; + v3.initial = 1; + v3.max = 1; + v3.option = 0; + v1 = CreateSema(&v3); + if (v1 < 0) + return -1; + sema_id = v1; + return 0; +} + +int dvrav_df_exit(iop_device_t *dev) +{ + if (DeleteSema(sema_id) != 0) + return -1; + return 0; +} + +int dvrav_df_ioctl(iop_file_t *f, int cmd, void *param) +{ + WaitSema(sema_id); + SignalSema(sema_id); + return -22; +} + +int dvrav_df_devctl( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v10; + unsigned int v11; + unsigned int v12; + + v10 = 0; + v11 = 0; + WaitSema(sema_id); + v12 = 0; + while (DevctlCmdTbl[v12].cmd != cmd) { + v12 = ++v11; + if (v11 >= sizeof(DevctlCmdTbl) / sizeof(DevctlCmdTbl[0])) + goto LABEL_5; + } + v10 = DevctlCmdTbl[v12].fn(a1, cmd, arg, arglen, buf, buflen); +LABEL_5: + if (v11 == sizeof(DevctlCmdTbl) / sizeof(DevctlCmdTbl[0])) + v10 = -22; + SignalSema(sema_id); + return v10; +} + +int dvrav_df_ioctl2(iop_file_t *f, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen) +{ + WaitSema(sema_id); + SignalSema(sema_id); + return -22; +} + +int dvrav_df_null() +{ + return -48; +} + +s64 dvrav_df_null_long() +{ + return -48LL; +} + +int avioctl2_get_tun_offset( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3102; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_get_tun_offset -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack) { + printf("avioctl2_get_tun_offset -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + *((u16 *)buf + 1) = cmdack.output_word[1]; + } + return 0; +} + +int avioctl2_tun_offset_up( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3103; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_tun_offset_up -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack) { + printf("avioctl2_tun_offset_up -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + *((u16 *)buf + 1) = cmdack.output_word[1]; + *((u16 *)buf + 2) = cmdack.output_word[2]; + *((u16 *)buf + 3) = cmdack.output_word[3]; + *((u16 *)buf + 4) = cmdack.output_word[4]; + } + return 0; +} + +int avioctl2_tun_offset_down( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3104; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_tun_offset_down -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack) { + printf("avioctl2_tun_offset_down -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + *((u16 *)buf + 1) = cmdack.output_word[1]; + *((u16 *)buf + 2) = cmdack.output_word[2]; + *((u16 *)buf + 3) = cmdack.output_word[3]; + *((u16 *)buf + 4) = cmdack.output_word[4]; + } + return 0; +} + +int avioctl2_tun_scan_ch( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3105; + cmdack.input_word[0] = *(u16 *)arg; + cmdack.input_word[1] = *((u16 *)arg + 1); + cmdack.input_word[2] = *((u16 *)arg + 2); + cmdack.input_word_count = 3; + cmdack.timeout = 35000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("avioctl2_tun_scan_ch -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack || cmdack.comp_status) { + printf("avioctl2_tun_scan_ch -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.return_result_word[0]; + *((u16 *)buf + 1) = cmdack.return_result_word[1]; + *((u16 *)buf + 2) = cmdack.return_result_word[2]; + *((u16 *)buf + 3) = cmdack.return_result_word[3]; + *((u16 *)buf + 4) = cmdack.return_result_word[4]; + *((u16 *)buf + 5) = cmdack.return_result_word[5]; + } + return 0; +} + +int avioctl2_get_bs_gain( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3106; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_get_bs_gain -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_get_bs_gain -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + } + } + return 0; +} + +int avioctl2_set_preset_info( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3107; + cmdack.input_word[0] = *(u16 *)arg; + cmdack.input_word[1] = *((u16 *)arg + 1); + cmdack.input_word_count = 2; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_set_preset_info -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_set_preset_info -> Status error!\n"); + return -68; + } + } + return 0; +} + +int avioctl2_change_sound( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3108; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_change_sound -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_change_sound -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + } + } + return 0; +} + +int avioctl2_set_d_audio_sel( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3109; + cmdack.input_word[0] = *(u16 *)arg; + cmdack.input_word[1] = *((u16 *)arg + 1); + cmdack.input_word[2] = *((u16 *)arg + 2); + cmdack.input_word[3] = *((u16 *)arg + 3); + cmdack.input_word_count = 4; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_set_d_audio_sel -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_set_d_audio_sel -> Status error!\n"); + return -68; + } + } + return 0; +} + +int avioctl2_set_d_video_sel( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x310A; + cmdack.input_word_count = 1; + cmdack.input_word[0] = *(u16 *)arg; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_set_d_video_sel -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_set_d_video_sel -> Status error!\n"); + return -68; + } + } + return 0; +} + +int avioctl2_get_av_src( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x310B; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_get_av_src -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack) { + printf("avioctl2_get_av_src -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + *((u16 *)buf + 1) = cmdack.output_word[1]; + } + return 0; +} + +int avioctl2_get_preset_info( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x310C; + cmdack.input_word_count = 1; + cmdack.input_word[0] = *(u16 *)arg; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_get_preset_info -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_get_preset_info -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + } + } + return 0; +} + +int avioctl2_select_position( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x310E; + cmdack.input_word_count = 1; + cmdack.input_word[0] = *(u16 *)arg; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_select_position -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_select_position -> Status error!\n"); + return -68; + } + } + return 0; +} + +int avioctl2_position_up( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x310F; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_position_up -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_position_up -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + } + } + return 0; +} + +int avioctl2_position_down( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3110; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_position_down -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_position_down -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + } + } + return 0; +} + +int avioctl2_get_position( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3111; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_get_position -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack) { + printf("avioctl2_get_position -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + printf("Now position = %d\n", cmdack.output_word[0]); + return 0; + } +} + +int avioctl2_set_position_info( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3112; + cmdack.input_word[0] = *(u16 *)arg; + cmdack.input_word[1] = *((u16 *)arg + 1); + cmdack.input_word[2] = *((u16 *)arg + 2); + cmdack.input_word[3] = *((u16 *)arg + 3); + cmdack.input_word[4] = *((u16 *)arg + 4); + cmdack.input_word_count = 5; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_set_position_info -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_set_position_info -> Status error!\n"); + return -68; + } + } + return 0; +} + +int avioctl2_get_position_info( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3113; + cmdack.input_word_count = 1; + cmdack.input_word[0] = *(u16 *)arg; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_get_position_info -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack) { + printf("avioctl2_get_position_info -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = *(u16 *)arg; + *((u16 *)buf + 1) = cmdack.output_word[0]; + *((u16 *)buf + 2) = cmdack.output_word[1]; + *((u16 *)buf + 3) = cmdack.output_word[2]; + *((u16 *)buf + 4) = cmdack.output_word[3]; + } + return 0; +} + +int avioctl2_tun_scan_mode( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3114; + cmdack.input_word_count = 1; + cmdack.input_word[0] = *(u16 *)arg; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_tun_scan_mode -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_tun_scan_mode -> Status error!\n"); + return -68; + } + } + return 0; +} + +int avioctl2_f_select_position( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3115; + cmdack.input_word_count = 1; + cmdack.input_word[0] = *(u16 *)arg; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_f_select_position -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_f_select_position -> Status error!\n"); + return -68; + } + } + return 0; +} + +int avioctl2_select_rec_src( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3116; + cmdack.input_word_count = 1; + cmdack.timeout = 10000000; + cmdack.input_word[0] = *(u16 *)arg; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("avioctl2_select_rec_src -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack || cmdack.comp_status) { + printf("avioctl2_select_rec_src -> Status error!\n"); + return -68; + } + return 0; +} + +int avioctl2_get_rec_src( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x3117; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("avioctl2_get_rec_src -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("avioctl2_get_rec_src -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + } + } + return 0; +} + +int avioctl2_cmd_ack( + const char *a1, + u32 a2, + iop_file_t *a3, + u8 cmd, + void *arg, + unsigned int arglen, + void *buf) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = cmd | 0x3100; + if (arglen >> 1) { + u16 *input_word_tmp; + unsigned int input_word_copied; + input_word_tmp = (u16 *)&cmdack.input_word[0]; + input_word_copied = 0; + do { + *input_word_tmp = *(u16 *)arg; + arg = (char *)arg + 2; + input_word_copied += 1; + input_word_tmp += 1; + } while (input_word_copied < arglen >> 1); + } + cmdack.input_word_count = arglen >> 1; + if (DvrdrvExecCmdAck(&cmdack)) { + printf(" %s -> Handshake error!\n", a1); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf(" %s -> Status error!\n", a1); + return -68; + } else { + u16 *input_word; + char *buf_tmp; + int out_count; + input_word = cmdack.output_word; + buf_tmp = (char *)buf; + out_count = 1; + do { + *(u16 *)buf_tmp = *input_word; + out_count += 1; + input_word += 1; + buf_tmp += 2; + } while (out_count < 16); + return 0; + } + } +} + +int avioctl2_cmd_ack_comp( + const char *a1, + u32 a2, + iop_file_t *a3, + u8 cmd, + void *arg, + unsigned int arglen, + void *buf) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = cmd | 0x3100; + if (arglen >> 1) { + u16 *input_word_tmp; + unsigned int input_word_copied; + input_word_tmp = (u16 *)&cmdack.input_word[0]; + input_word_copied = 0; + do { + *input_word_tmp = *(u16 *)arg; + input_word_tmp += 1; + arg = (char *)arg + 2; + input_word_copied += 1; + } while (input_word_copied < arglen >> 1); + } + cmdack.input_word_count = arglen >> 1; + cmdack.timeout = a2; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf(" %s -> Handshake error!\n", a1); + return -5; + } else if (cmdack.ack_status_ack || cmdack.comp_status) { + printf(" %s -> Status error!\n", a1); + return -68; + } else { + int out_count; + u16 *input_word; + u16 *buf_tmp; + out_count = 1; + input_word = cmdack.return_result_word; + buf_tmp = (u16 *)buf; + do { + *buf_tmp = *input_word; + out_count += 1; + input_word += 1; + buf_tmp += 1; + } while (out_count < 16); + return 0; + } +} + +int avioctl2_tun_scan_mode_euro( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack("avioctl2_tun_scan_mode_euro", 0x8000, a1, cmd, arg, arglen, buf); +} + +int avioctl2_tun_scan_ch_euro( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack_comp("avioctl2_tun_scan_ch_euro", 0x8000, a1, cmd, arg, arglen, buf); +} + +int avioctl2_get_curfreq_info( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack("avioctl2_get_curfreq_info", 0x8000, a1, cmd, arg, arglen, buf); +} + +int avioctl2_get_teletext_ver_no( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack_comp("avioctl2_get_teletext_ver_no", 0x8000, a1, cmd, arg, arglen, buf); +} + +int avioctl2_set_tv_guide_page( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack("avioctl2_set_tv_guide_page", 0x8000, a1, cmd, arg, arglen, buf); +} + +int avioctl2_get_tv_guide_page( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack("avioctl2_get_tv_guide_page", 0x8000, a1, cmd, arg, arglen, buf); +} + +int avioctl2_change_mode_tv_to_dvd( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack("avioctl2_change_mode_tv_to_dvd", 0x8000, a1, cmd, arg, arglen, buf); +} + +int avioctl2_get_vps_data( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack_comp("avioctl2_get_vps_data", 0x6B6C0, a1, cmd, arg, arglen, buf); +} + +int avioctl2_get_pdc_data( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack_comp("avioctl2_get_pdc_data", 0x2DC6C0, a1, cmd, arg, arglen, buf); +} + +int avioctl2_get_format1_data( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack_comp("avioctl2_get_format1_data", 0x2DC6C0, a1, cmd, arg, arglen, buf); +} + +int avioctl2_get_header_time_data( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack_comp("avioctl2_get_header_time_data", 0x2DC6C0, a1, cmd, arg, arglen, buf); +} + +int avioctl2_set_acs_position_euro( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + return avioctl2_cmd_ack("avioctl2_set_acs_position_euro", 0x8000, a1, cmd, arg, arglen, buf); +} diff --git a/sps2_basement/hardware/dvrp/dvrav/src/imports.lst b/sps2_basement/hardware/dvrp/dvrav/src/imports.lst new file mode 100644 index 0000000..8593cda --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrav/src/imports.lst @@ -0,0 +1,25 @@ + +iomanX_IMPORTS_start +I_AddDrv +I_DelDrv +iomanX_IMPORTS_end + +pvrdrv_IMPORTS_start +I_DvrdrvExecCmdAck +I_DvrdrvExecCmdAckComp +pvrdrv_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/dvrp/dvrav/src/irx_imports.h b/sps2_basement/hardware/dvrp/dvrav/src/irx_imports.h new file mode 100644 index 0000000..a56243d --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrav/src/irx_imports.h @@ -0,0 +1,24 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thsemap.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dvrp/dvrdv/Makefile b/sps2_basement/hardware/dvrp/dvrdv/Makefile new file mode 100644 index 0000000..eaac6e4 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrdv/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/pvrdrv/include +IOP_OBJS = dvrdv.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dvrp/dvrdv/src/dvrdv.c b/sps2_basement/hardware/dvrp/dvrdv/src/dvrdv.c new file mode 100644 index 0000000..ce7b8ca --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrdv/src/dvrdv.c @@ -0,0 +1,410 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "thbase.h" +#include "thsemap.h" +#include "speedregs.h" +#include "errno.h" + +extern int module_start(); +extern int module_stop(); +extern int dvrdv_df_init(iop_device_t *dev); +extern int dvrdv_df_exit(iop_device_t *dev); +extern int dvrdv_df_ioctl(iop_file_t *f, int cmd, void *param); +extern int dvrdv_df_devctl(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrdv_df_ioctl2(iop_file_t *f, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrdv_df_null(); +extern s64 dvrdv_df_null_long(); +extern int dvrioctl2_dv_dubb_start(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_dv_dubb_stop(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_dv_dubb_rec_start(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_dv_dubb_rec_stop(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_dvcam_info(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_dvcam_name(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); + +struct DevctlCmdTbl_t +{ + u16 cmd; + int (*fn)(iop_file_t *, const char *, int, void *, unsigned int, void *, unsigned int); +} DevctlCmdTbl[6] = + { + {0x5601, &dvrioctl2_dv_dubb_start}, + {0x5602, &dvrioctl2_dv_dubb_stop}, + {0x5603, &dvrioctl2_dv_dubb_rec_start}, + {0x5604, &dvrioctl2_dv_dubb_rec_stop}, + {0x5607, &dvrioctl2_get_dvcam_info}, + {0x5608, &dvrioctl2_get_dvcam_name}, +}; +struct _iop_device_ops DvrFuncTbl = + { + &dvrdv_df_init, + &dvrdv_df_exit, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_ioctl, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_null_long, + &dvrdv_df_devctl, + &dvrdv_df_null, + &dvrdv_df_null, + &dvrdv_df_ioctl2}; +iop_device_t DVR; +s32 sema_id; + +// Based off of DESR / PSX DVR system software version 2.11. +#define MODNAME "DVRDV" +IRX_ID(MODNAME, 1, 0); + +int _start(int a1, char **argv) +{ + if (a1 >= 0) + return module_start(); + else + return module_stop(); +} + +int module_start() +{ + int i; + + for (i = 0; i < 30000; ++i) { + if (((*((vu32 *)0xB0004230)) & 4) != 0) + break; + DelayThread(1000); + } + if (i == 30000) { + printf("DVR task of DVRP is not running...\n"); + return 1; + } else { + DVR.name = "dvr_dv"; + DVR.desc = "Digital Video Recorder DVR task"; + DVR.type = 0x10000010; + DVR.ops = &DvrFuncTbl; + if (AddDrv(&DVR) != 0) + return 1; + } +#if 0 + return 2; +#else + return 0; +#endif +} + +int module_stop() +{ + if (DelDrv("dvr_dv") != 0) + return 2; + return 1; +} + +int dvrdv_df_init(iop_device_t *dev) +{ + int v1; + iop_sema_t v3; + + v3.attr = 0; + v3.initial = 1; + v3.max = 1; + v3.option = 0; + v1 = CreateSema(&v3); + if (v1 < 0) + return -1; + sema_id = v1; + return 0; +} + +int dvrdv_df_exit(iop_device_t *dev) +{ + if (DeleteSema(sema_id) != 0) + return -1; + return 0; +} + +int dvrdv_df_ioctl(iop_file_t *f, int cmd, void *param) +{ + WaitSema(sema_id); + SignalSema(sema_id); + return -22; +} + +int dvrdv_df_devctl( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v10; + unsigned int v11; + unsigned int v12; + + v10 = 0; + v11 = 0; + WaitSema(sema_id); + v12 = 0; + while (DevctlCmdTbl[v12].cmd != cmd) { + v12 = ++v11; + if (v11 >= sizeof(DevctlCmdTbl) / sizeof(DevctlCmdTbl[0])) + goto LABEL_5; + } + v10 = DevctlCmdTbl[v12].fn(a1, name, cmd, arg, arglen, buf, buflen); +LABEL_5: + if (v11 == sizeof(DevctlCmdTbl) / sizeof(DevctlCmdTbl[0])) + v10 = -22; + SignalSema(sema_id); + return v10; +} + +int dvrdv_df_ioctl2( + iop_file_t *f, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + WaitSema(sema_id); + SignalSema(sema_id); + return -22; +} + +int dvrdv_df_null() +{ + return -48; +} + +s64 dvrdv_df_null_long() +{ + return -48LL; +} + +int dvrioctl2_dv_dubb_start( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdack_err; + drvdrv_exec_cmd_ack cmdack; + + printf("------------------------------ dv dubb start!!!\n"); + cmdack.command = 0x4101; + cmdack.input_word_count = 0; + cmdack_err = DvrdrvExecCmdAck(&cmdack); + if (cmdack_err) { + printf("dvrioctl2_dv_dubb_start -> Handshake error!,%d\n", cmdack_err); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_dv_dubb_start -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_dv_dubb_stop( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdack_err; + drvdrv_exec_cmd_ack cmdack; + + printf("------------------------------ dv dubb stop!!!\n"); + cmdack.command = 0x4102; + cmdack.input_word_count = 0; + cmdack_err = DvrdrvExecCmdAck(&cmdack); + if (cmdack_err) { + printf("dvrioctl2_dv_dubb_stop -> Handshake error!,%d\n", cmdack_err); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_dv_dubb_stop -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_dv_dubb_rec_start( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v8; + u16 *v9; + u16 *v10; + int cmdack_err; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x4103; + printf("------------------------------ dv dubb rec start!!!\n"); + v8 = 4; + v9 = (u16 *)((u8 *)arg + 8); + v10 = &cmdack.input_word[4]; + do { + *v10 = *v9; + v9 += 1; + v8 += 1; + v10 += 1; + } while (v8 < 7); + cmdack.input_word[0] = *((u16 *)arg + 1); + cmdack.input_word[1] = *(u16 *)arg; + cmdack.input_word[2] = *((u16 *)arg + 3); + cmdack.input_word[3] = *((u16 *)arg + 2); + cmdack.input_word_count = 7; + cmdack_err = DvrdrvExecCmdAck(&cmdack); + if (cmdack_err) { + printf("dvrioctl2_dv_dubb_rec_start -> Handshake error!,%d\n", cmdack_err); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_dv_dubb_rec_start -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_dv_dubb_rec_stop( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdack_err; + drvdrv_exec_cmd_ack cmdack; + + printf("------------------------------ dv dubb rec stop!!!\n"); + cmdack.command = 0x4104; + cmdack.input_word_count = 0; + cmdack.timeout = 5000000; + cmdack_err = DvrdrvExecCmdAckComp(&cmdack); + if (cmdack_err) { + printf("phase %d\n", cmdack.phase); + printf("dvrioctl2_dv_dubb_rec_stop -> Handshake error!,%d\n", cmdack_err); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("phase %d\n", cmdack.phase); + printf("dvrioctl2_dv_dubb_rec_stop -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } + } + return 0; +} + +int dvrioctl2_get_dvcam_info( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdack_err; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x4107; + cmdack.input_word_count = 0; + cmdack_err = DvrdrvExecCmdAck(&cmdack); + if (cmdack_err) { + printf("phase %d\n", cmdack.phase); + printf("dvrioctl2_get_dvcam_info -> Handshake error!,%d\n", cmdack_err); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_get_dvcam_info -> Status error!,%04X\n", cmdack.ack_status_ack); + return -68; + } else { + u16 *v11; + int cpy_cnt; + v11 = &cmdack.output_word[0]; + cpy_cnt = 0; + do { + cpy_cnt += 1; + *(u16 *)buf = *v11; + buf = (char *)buf + 2; + v11 += 1; + } while (cpy_cnt < 4); + return 0; + } + } +} + +int dvrioctl2_get_dvcam_name( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + printf("dvrioctl2_get_dvcam_name(io=%p, cmd=%d buf=%p, nbyte=%u)\n", a1, cmd, buf, buflen); + cmdack.command = 0x4108; + cmdack.input_word[0] = 0; + cmdack.input_word[1] = 0; + cmdack.input_word[2] = (buflen & 0xFFFF0000) >> 16; + cmdack.input_word[3] = buflen; + cmdack.input_word_count = 4; + cmdack.output_buffer = buf; + cmdack.timeout = 5000000; + if (DvrdrvExecCmdAckDmaRecvComp(&cmdack)) { + printf("dvrioctl2_get_dvcam_name : IO error (phase %d)\n", cmdack.phase); + return -5; + } else { + if (cmdack.comp_status) { + printf("dvrioctl2_get_dvcam_name : Complete parameter error (phase %d), %04X\n", cmdack.phase, cmdack.comp_status); + return -5; + } + } + return 0; +} diff --git a/sps2_basement/hardware/dvrp/dvrdv/src/imports.lst b/sps2_basement/hardware/dvrp/dvrdv/src/imports.lst new file mode 100644 index 0000000..4d8adff --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrdv/src/imports.lst @@ -0,0 +1,26 @@ + +iomanX_IMPORTS_start +I_AddDrv +I_DelDrv +iomanX_IMPORTS_end + +pvrdrv_IMPORTS_start +I_DvrdrvExecCmdAck +I_DvrdrvExecCmdAckComp +I_DvrdrvExecCmdAckDmaRecvComp +pvrdrv_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/dvrp/dvrdv/src/irx_imports.h b/sps2_basement/hardware/dvrp/dvrdv/src/irx_imports.h new file mode 100644 index 0000000..1943733 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrdv/src/irx_imports.h @@ -0,0 +1,23 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "thbase.h" +#include "thsemap.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dvrp/dvrfile/Makefile b/sps2_basement/hardware/dvrp/dvrfile/Makefile new file mode 100644 index 0000000..5035cef --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrfile/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/pvrdrv/include +IOP_OBJS = dvrfile.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dvrp/dvrfile/src/dvrfile.c b/sps2_basement/hardware/dvrp/dvrfile/src/dvrfile.c new file mode 100644 index 0000000..ae142a7 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrfile/src/dvrfile.c @@ -0,0 +1,1135 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thsemap.h" +#include "speedregs.h" +#include "errno.h" + +extern int module_start(int argc, const char **argv); +extern int module_stop(); +extern int dvrf_df_init(iop_device_t *f); +extern int dvrf_df_exit(iop_device_t *f); +extern int dvrf_df_chdir(iop_file_t *f, const char *name); +extern int dvrf_df_chstat(iop_file_t *f, const char *name, iox_stat_t *stat, unsigned int statmask); +extern int dvrf_df_close(iop_file_t *f); +extern int dvrf_df_dclose(iop_file_t *f); +extern int dvrf_df_devctl(iop_file_t *f, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrf_df_dopen(iop_file_t *f, const char *path); +extern int dvrf_df_dread(iop_file_t *f, iox_dirent_t *buf); +extern int dvrf_df_format(iop_file_t *f, const char *dev, const char *blockdev, void *arg, int arglen); +extern int dvrf_df_getstat(iop_file_t *f, const char *name, iox_stat_t *stat); +extern int dvrf_df_ioctl(iop_file_t *f, int cmd, void *param); +extern int dvrf_df_ioctl2(iop_file_t *f, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrf_df_lseek(iop_file_t *f, int offset, int mode); +extern s64 dvrf_df_lseek64(iop_file_t *f, s64 offset, int whence); +extern int dvrf_df_mkdir(iop_file_t *f, const char *path, int mode); +extern int dvrf_df_mount(iop_file_t *f, const char *fsname, const char *devname, int flag, void *arg, int arglen); +extern int dvrf_df_open(iop_file_t *f, const char *name, int flags, int mode); +extern int dvrf_df_read(iop_file_t *f, void *ptr, int size); +extern int dvrf_df_readlink(iop_file_t *f, const char *path, char *buf, unsigned int buflen); +extern int dvrf_df_remove(iop_file_t *f, const char *name); +extern int dvrf_df_rename(iop_file_t *f, const char *old, const char *new_1); +extern int dvrf_df_rmdir(iop_file_t *f, const char *path); +extern int dvrf_df_symlink(iop_file_t *f, const char *old, const char *new_1); +extern int dvrf_df_sync(iop_file_t *f, const char *dev, int flag); +extern int dvrf_df_umount(iop_file_t *f, const char *fsname); +extern int dvrf_df_write(iop_file_t *f, void *ptr, int size); +extern void CopySceStat(iox_stat_t *stat, u8 *dvrp_stat); + +static inline u32 bswap32(u32 val) +{ +#if 0 + return __builtin_bswap32(val); +#else + return (val << 24) + ((val & 0xFF00) << 8) + ((val >> 8) & 0xFF00) + ((val >> 24) & 0xFF); +#endif +} + +static int dvrf_translator_df_chdir(iop_file_t *f, const char *name) +{ + char translated_name[1040]; + + sprintf(translated_name, "%s%d:%s", f->device->name, f->unit, name); + return dvrf_df_chdir(f, translated_name); +} + +static int dvrf_translator_df_chstat(iop_file_t *f, const char *name, iox_stat_t *stat, unsigned int statmask) +{ + char translated_name[1040]; + + sprintf(translated_name, "%s%d:%s", f->device->name, f->unit, name); + return dvrf_df_chstat(f, translated_name, stat, statmask); +} + +static int dvrf_translator_df_devctl(iop_file_t *f, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen) +{ + char translated_name[1040]; + + sprintf(translated_name, "%s%d:%s", f->device->name, f->unit, name); + return dvrf_df_devctl(f, translated_name, cmd, arg, arglen, buf, buflen); +} + +static int dvrf_translator_df_dopen(iop_file_t *f, const char *path) +{ + char translated_path[1040]; + + sprintf(translated_path, "%s%d:%s", f->device->name, f->unit, path); + return dvrf_df_dopen(f, translated_path); +} + +static int dvrf_translator_df_format(iop_file_t *f, const char *dev, const char *blockdev, void *arg, int arglen) +{ + char translated_dev[1040]; + + if (strcmp(f->device->name, "dvr_hdd") != 0) { + sprintf(translated_dev, "%s:%s", f->device->name, dev); + *(u32 *)arg = bswap32(*(u32 *)arg); + } else { + sprintf(translated_dev, "%s%d:%s", f->device->name, f->unit, dev); + } + return dvrf_df_format(f, translated_dev, blockdev, arg, arglen); +} + +static int dvrf_translator_df_getstat(iop_file_t *f, const char *name, iox_stat_t *stat) +{ + char translated_name[1040]; + + sprintf(translated_name, "%s%d:%s", f->device->name, f->unit, name); + return dvrf_df_getstat(f, translated_name, stat); +} + +static int dvrf_translator_df_mkdir(iop_file_t *f, const char *path, int mode) +{ + char translated_path[1040]; + + sprintf(translated_path, "%s%d:%s", f->device->name, f->unit, path); + return dvrf_df_mkdir(f, translated_path, mode); +} + +static int dvrf_translator_df_mount(iop_file_t *f, const char *fsname, const char *devname, int flag, void *arg, int arglen) +{ + char translated_fsname[1040]; + + sprintf(translated_fsname, "%s%d:%s", f->device->name, f->unit, fsname); + return dvrf_df_mount(f, translated_fsname, devname, flag, arg, arglen); +} + +static int dvrf_translator_df_open(iop_file_t *f, const char *name, int flags, int mode) +{ + char translated_name[1040]; + + sprintf(translated_name, "%s%d:%s", f->device->name, f->unit, name); + return dvrf_df_open(f, translated_name, flags, mode); +} + +static int dvrf_translator_df_readlink(iop_file_t *f, const char *path, char *buf, unsigned int buflen) +{ + char translated_path[1040]; + + sprintf(translated_path, "%s%d:%s", f->device->name, f->unit, path); + return dvrf_df_readlink(f, translated_path, buf, buflen); +} + +static int dvrf_translator_df_remove(iop_file_t *f, const char *name) +{ + char translated_name[1040]; + + sprintf(translated_name, "%s%d:%s", f->device->name, f->unit, name); + return dvrf_df_remove(f, translated_name); +} + +static int dvrf_translator_df_rename(iop_file_t *f, const char *old, const char *new_1) +{ + char translated_old[1040]; + char translated_new[1040]; + + sprintf(translated_old, "%s%d:%s", f->device->name, f->unit, old); + sprintf(translated_new, "%s%d:%s", f->device->name, f->unit, new_1); + return dvrf_df_rename(f, translated_old, translated_new); +} + +static int dvrf_translator_df_rmdir(iop_file_t *f, const char *path) +{ + char translated_path[1040]; + + sprintf(translated_path, "%s%d:%s", f->device->name, f->unit, path); + return dvrf_df_rmdir(f, translated_path); +} + +static int dvrf_translator_df_symlink(iop_file_t *f, const char *old, const char *new_1) +{ + char translated_old[1040]; + char translated_new[1040]; + + sprintf(translated_old, "%s%d:%s", f->device->name, f->unit, old); + sprintf(translated_new, "%s%d:%s", f->device->name, f->unit, new_1); + return dvrf_df_symlink(f, translated_old, translated_new); +} + +static int dvrf_translator_df_sync(iop_file_t *f, const char *dev, int flag) +{ + char translated_dev[1040]; + + sprintf(translated_dev, "%s%d:%s", f->device->name, f->unit, dev); + return dvrf_df_sync(f, translated_dev, flag); +} + +static int dvrf_translator_df_umount(iop_file_t *f, const char *fsname) +{ + char translated_fsname[1040]; + + sprintf(translated_fsname, "%s%d:%s", f->device->name, f->unit, fsname); + return dvrf_df_umount(f, translated_fsname); +} + +static iop_device_ops_t dvrf_translator_functbl = { + dvrf_df_init, + dvrf_df_exit, + dvrf_translator_df_format, + dvrf_translator_df_open, + dvrf_df_close, + dvrf_df_read, + dvrf_df_write, + dvrf_df_lseek, + dvrf_df_ioctl, + dvrf_translator_df_remove, + dvrf_translator_df_mkdir, + dvrf_translator_df_rmdir, + dvrf_translator_df_dopen, + dvrf_df_dclose, + dvrf_df_dread, + dvrf_translator_df_getstat, + dvrf_translator_df_chstat, + dvrf_translator_df_rename, + dvrf_translator_df_chdir, + dvrf_translator_df_sync, + dvrf_translator_df_mount, + dvrf_translator_df_umount, + dvrf_df_lseek64, + dvrf_translator_df_devctl, + dvrf_translator_df_symlink, + dvrf_translator_df_readlink, + dvrf_df_ioctl2, +}; + +#define GEN_TRANSLATION_FUNCS(basefuncname, basedevname, shouldbswapformatarg, drvname) \ + static iop_device_t basefuncname##_drv = { \ + basedevname, \ + (IOP_DT_FS | IOP_DT_FSEXT), \ + 1, \ + drvname, \ + &dvrf_translator_functbl}; + +GEN_TRANSLATION_FUNCS(dvrpfs, "dvr_pfs", 1, "PFS Driver for DVR"); +GEN_TRANSLATION_FUNCS(dvrhdd, "dvr_hdd", 0, "HDD Driver for DVR"); +GEN_TRANSLATION_FUNCS(dvrhdck, "dvr_hdck", 1, "HDCK Driver for DVR"); +GEN_TRANSLATION_FUNCS(dvrfssk, "dvr_fssk", 1, "FSSK Driver for DVR"); +GEN_TRANSLATION_FUNCS(dvrfsck, "dvr_fsck", 1, "FSCK Driver for DVR"); + +s32 sema_id; +int current_chunk_size; +int RBUF[32768]; +int SBUF[32768]; + +// Based off of DESR / PSX DVR system software version 1.31. +#define MODNAME "DVRFILE" +IRX_ID("DVRFILE", 1, 1); + +int _start(int argc, const char **argv) +{ + if (argc >= 0) + return module_start(argc, argv); + else + return module_stop(argc, argv); +} + +int module_start(int argc, const char **argv) +{ + int i; + USE_SPD_REGS; + + for (i = 0; i < 30000; i += 1) { + if ((SPD_REG16(0x4230) & 0x20) != 0) { + break; + } + DelayThread(1000); + } + + if (i == 30000) { + printf("IOMAN task of DVRP is not running...\n"); + return 1; + } + sema_id = -1; + current_chunk_size = 0x4000; + if (AddDrv(&dvrpfs_drv) || AddDrv(&dvrhdd_drv)) { + goto fail; + } + for (i = 0; i < argc; i += 1) { + if (!strcmp(argv[i], "fschk")) + goto setup_fschk; + } +#if 0 + return 2; +#else + return 0; +#endif +setup_fschk: + printf("dvrfile.irx : FILE SYSTEM CHECK MODE\n"); + + if (AddDrv(&dvrhdck_drv)) { + printf("hdck\n"); + goto fail; + } + if (AddDrv(&dvrfssk_drv)) { + printf("fssk\n"); + goto fail; + } + if (AddDrv(&dvrfsck_drv)) { + printf("fsck\n"); + goto fail; + } +#if 0 + return 2; +#else + return 0; +#endif +fail: + DelDrv(dvrpfs_drv.name); + DelDrv(dvrhdd_drv.name); + DelDrv(dvrhdck_drv.name); + DelDrv(dvrfssk_drv.name); + DelDrv(dvrfsck_drv.name); + return 1; +} + +int module_stop() +{ + if (DelDrv(dvrpfs_drv.name) || DelDrv(dvrhdd_drv.name)) { +#if 0 + return 2; +#else + return 0; +#endif + } + return 1; +} + +static int check_cmdack_err(int (*func)(drvdrv_exec_cmd_ack *cmdack), drvdrv_exec_cmd_ack *cmdack, int *retval, const char *funcname) +{ + if (func(cmdack)) { + *retval = -EIO; + printf("%s -> IO error (phase %d)\n", funcname, cmdack->phase); + return 1; + } + if (cmdack->comp_status) { + *retval = -EIO; + printf("%s -> Complete parameter error (phase %d), %04X\n", funcname, cmdack->phase, cmdack->comp_status); + return 1; + } + *retval = (cmdack->return_result_word[0] << 16) + cmdack->return_result_word[1]; + return 0; +} + +int dvrf_df_init(iop_device_t *f) +{ + int this_sema_id; + iop_sema_t sema_struct; + + if (sema_id >= 0) { + return 0; + } + sema_struct.attr = 0; + sema_struct.initial = 1; + sema_struct.max = 1; + sema_struct.option = 0; + this_sema_id = CreateSema(&sema_struct); + if (this_sema_id < 0) { + return -1; + } + sema_id = this_sema_id; + return 0; +} + +int dvrf_df_exit(iop_device_t *f) +{ + if (sema_id < 0) { + return 0; + } + if (DeleteSema(sema_id)) { + return -1; + } + sema_id = -1; + return 0; +} + +int dvrf_df_chdir(iop_file_t *f, const char *name) +{ + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + strcpy((char *)SBUF, name); + cmdack.command = 0x1101; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = strlen(name) + 1; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_chstat(iop_file_t *f, const char *name, iox_stat_t *stat, unsigned int statmask) +{ + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + SBUF[0] = statmask; + strcpy((char *)&SBUF[1], name); + cmdack.command = 0x1102; + cmdack.input_buffer = SBUF; + cmdack.input_word_count = 2; + cmdack.input_buffer_length = strlen(name) + 5; + cmdack.output_buffer = RBUF; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDma2Comp, &cmdack, &retval, __func__)) { + goto finish; + } + CopySceStat(stat, (u8 *)RBUF); +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_close(iop_file_t *f) +{ + int retval; + int dvrp_fd; + drvdrv_exec_cmd_ack cmdack; + + retval = 0; + WaitSema(sema_id); + cmdack.command = 0x1103; + dvrp_fd = (int)f->privdata; + cmdack.input_word[0] = (dvrp_fd >> 16) & 0xFFFF; + cmdack.input_word[1] = dvrp_fd; + cmdack.input_word_count = 2; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckComp, &cmdack, &retval, __func__)) { + goto finish; + } + retval = 0; + f->privdata = NULL; +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_dclose(iop_file_t *f) +{ + int retval; + int dvrp_fd; + drvdrv_exec_cmd_ack cmdack; + + retval = 0; + WaitSema(sema_id); + cmdack.command = 0x1104; + dvrp_fd = (int)f->privdata; + cmdack.input_word[0] = (dvrp_fd >> 16) & 0xFFFF; + cmdack.input_word[1] = dvrp_fd; + cmdack.input_word_count = 2; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckComp, &cmdack, &retval, __func__)) { + goto finish; + } + retval = 0; + f->privdata = NULL; +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_devctl(iop_file_t *f, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen) +{ + int retval; + u32 argoffset; + drvdrv_exec_cmd_ack cmdack; + + retval = 0; + WaitSema(sema_id); + if (cmd == 0x5065) { + if ((*(u32 *)arg & 0x7F) != 0) { + retval = -EINVAL; + } else if (*(int *)arg <= 0x20000) { + current_chunk_size = *(u32 *)arg; + } else { + retval = -EDOM; + } + goto finish; + } + argoffset = arglen + 16; + SBUF[0] = bswap32(argoffset); + SBUF[1] = bswap32((u32)cmd); + SBUF[2] = bswap32(buflen); + SBUF[3] = bswap32(arglen); + memcpy(&SBUF[4], arg, arglen); + strcpy((char *)SBUF + argoffset, name); + cmdack.input_buffer_length = argoffset + strlen(name) + 1; + cmdack.command = 0x1105; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.output_buffer = RBUF; + cmdack.timeout = 30000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDma2Comp, &cmdack, &retval, __func__)) { + goto finish; + } + if (!retval && buf) { + memcpy(buf, cmdack.output_buffer, buflen); + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_dopen(iop_file_t *f, const char *path) +{ + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + strcpy((char *)SBUF, path); + cmdack.command = 0x1106; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = strlen(path) + 1; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } + if (retval < 0) { + printf("%s -> fd error (fd=%d)\n", __func__, retval); + goto finish; + } + f->privdata = (void *)retval; +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_dread(iop_file_t *f, iox_dirent_t *buf) +{ + int dvrp_fd; + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + cmdack.command = 0x1107; + dvrp_fd = (int)f->privdata; + cmdack.input_word[0] = (dvrp_fd >> 16) & 0xFFFF; + cmdack.input_word[1] = dvrp_fd; + cmdack.input_word_count = 2; + cmdack.output_buffer = RBUF; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaRecvComp, &cmdack, &retval, __func__)) { + goto finish; + } + memcpy(buf, RBUF, sizeof(*buf)); + buf->stat.mode = bswap32(buf->stat.mode); + buf->stat.attr = bswap32(buf->stat.attr); + buf->stat.size = bswap32(buf->stat.size); + buf->stat.hisize = bswap32(buf->stat.hisize); + buf->stat.private_0 = bswap32(buf->stat.private_0); + buf->stat.private_1 = bswap32(buf->stat.private_1); + buf->stat.private_2 = bswap32(buf->stat.private_2); + buf->stat.private_3 = bswap32(buf->stat.private_3); + buf->stat.private_4 = bswap32(buf->stat.private_4); + buf->stat.private_5 = bswap32(buf->stat.private_5); + u8 tmp; + tmp = buf->stat.ctime[6]; + buf->stat.ctime[6] = buf->stat.ctime[7]; + buf->stat.ctime[7] = tmp; + tmp = buf->stat.atime[6]; + buf->stat.atime[6] = buf->stat.atime[7]; + buf->stat.atime[7] = tmp; + tmp = buf->stat.mtime[6]; + buf->stat.mtime[6] = buf->stat.mtime[7]; + buf->stat.mtime[7] = tmp; +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_format(iop_file_t *f, const char *dev, const char *blockdev, void *arg, int arglen) +{ + size_t blockdev_len; + u32 dev_len; + const char *dev_; + u32 arg_offset; + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + dev_len = strlen(dev) + 13; + blockdev_len = strlen(blockdev); + dev_ = dev; + arg_offset = dev_len + blockdev_len + 1; + SBUF[1] = bswap32(arg_offset); + SBUF[0] = bswap32(dev_len); + SBUF[2] = bswap32(arglen); + strcpy((char *)&SBUF[3], dev_); + strcpy((char *)SBUF + dev_len, blockdev); + memcpy((char *)SBUF + arg_offset, arg, arglen); + cmdack.command = 0x1108; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = arg_offset + arglen; + cmdack.timeout = 3600000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_getstat(iop_file_t *f, const char *name, iox_stat_t *stat) +{ + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + strcpy((char *)SBUF, name); + cmdack.command = 0x1109; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = strlen(name) + 1; + cmdack.output_buffer = RBUF; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDma2Comp, &cmdack, &retval, __func__)) { + goto finish; + } + CopySceStat(stat, (u8 *)RBUF); +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_ioctl(iop_file_t *f, int cmd, void *param) +{ + int dvrp_fd; + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + dvrp_fd = (int)f->privdata; + cmdack.command = 0x110A; + cmdack.input_word[0] = (dvrp_fd >> 16) & 0xFFFF; + cmdack.input_word[1] = dvrp_fd; + cmdack.input_word[2] = (cmd >> 16) & 0xFFFF; + cmdack.input_word[3] = cmd; + cmdack.input_word[4] = ((u32)param >> 16) & 0xFFFF; + cmdack.input_word[5] = (u32)param & 0xFFFF; + cmdack.input_word_count = 6; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_ioctl2(iop_file_t *f, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen) +{ + int dvrp_fd; + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + dvrp_fd = (int)f->privdata; + SBUF[1] = bswap32(cmd); + SBUF[2] = bswap32(buflen); + SBUF[0] = bswap32(dvrp_fd); + SBUF[3] = bswap32(arglen); + memcpy(((u8 *)SBUF) + 0x10, arg, arglen); + cmdack.command = 0x110B; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = arglen + 16; + cmdack.input_word_count = 0; + cmdack.output_buffer = RBUF; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDma2Comp, &cmdack, &retval, __func__)) { + goto finish; + } + memcpy(buf, RBUF, buflen); +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_lseek(iop_file_t *f, int offset, int mode) +{ + int dvrp_fd; + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + dvrp_fd = (int)f->privdata; + cmdack.command = 0x110C; + cmdack.input_word[0] = (dvrp_fd >> 16) & 0xFFFF; + cmdack.input_word[1] = dvrp_fd; + cmdack.input_word[2] = (offset >> 16) & 0xFFFF; + cmdack.input_word[3] = offset; + cmdack.input_word[4] = (mode >> 16) & 0xFFFF; + cmdack.input_word[5] = mode; + cmdack.input_word_count = 6; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +s64 dvrf_df_lseek64(iop_file_t *f, s64 offset, int whence) +{ + int dvrp_fd; + s64 retval; + int rretval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + dvrp_fd = (int)f->privdata; + cmdack.command = 0x110D; + cmdack.input_word[0] = (dvrp_fd >> 16) & 0xFFFF; + cmdack.input_word[1] = dvrp_fd; + cmdack.input_word[2] = (offset >> 48) & 0xFFFF; + cmdack.input_word[3] = (offset >> 32) & 0xFFFF; + cmdack.input_word[4] = (offset >> 16) & 0xFFFF; + cmdack.input_word[5] = offset; + cmdack.input_word[6] = (whence >> 16) & 0xFFFF; + cmdack.input_word[7] = whence; + cmdack.input_word_count = 8; + cmdack.timeout = 10000000; + rretval = 0; + if (check_cmdack_err(&DvrdrvExecCmdAckComp, &cmdack, &rretval, __func__)) { + retval = rretval; + goto finish; + } + retval = ((s64)cmdack.return_result_word[0] << 48) | ((s64)cmdack.return_result_word[1] << 32) | ((s64)cmdack.return_result_word[2] << 16) | (s64)cmdack.return_result_word[3]; +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_mkdir(iop_file_t *f, const char *path, int mode) +{ + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + SBUF[0] = bswap32(mode); + strcpy((char *)&SBUF[1], path); + cmdack.command = 0x110E; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = strlen(path) + 5; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_mount(iop_file_t *f, const char *fsname, const char *devname, int flag, void *arg, int arglen) +{ + size_t devname_len; + u32 fsname_len; + const char *fsname_; + unsigned int arg_offs; + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + SBUF[0] = bswap32(flag); + fsname_len = strlen(fsname) + 17; + devname_len = strlen(devname); + fsname_ = fsname; + arg_offs = fsname_len + devname_len + 1; + SBUF[2] = bswap32(arg_offs); + SBUF[1] = bswap32(fsname_len); + SBUF[3] = bswap32(arglen); + strcpy((char *)&SBUF[4], fsname_); + strcpy((char *)SBUF + fsname_len, devname); + memcpy(((u8 *)SBUF) + arg_offs, arg, arglen); + + cmdack.command = 0x110F; + cmdack.input_buffer = SBUF; + cmdack.input_word_count = 0; + cmdack.input_buffer_length = arg_offs + arglen; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_open(iop_file_t *f, const char *name, int flags, int mode) +{ + u16 mode_; + int retval; + drvdrv_exec_cmd_ack cmdack; + + mode_ = mode; + WaitSema(sema_id); + SBUF[0] = bswap32(flags); + mode_ = (mode_ << 8) + (mode_ >> 8); + memcpy(&SBUF[1], &mode_, sizeof(mode_)); + strcpy((char *)&SBUF[1] + 2, name); + cmdack.command = 0x1110; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = strlen(name) + 7; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } + if (retval < 0) { + printf("%s -> fd error (fd=%d)\n", __func__, retval); + goto finish; + } + f->privdata = (void *)retval; +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_read(iop_file_t *f, void *ptr, int size) +{ + size_t total_read; + char *out_buf; + int retval; + int dvrp_fd; + int remain_size; + int chunk_size; + int unaligned_size; + drvdrv_exec_cmd_ack cmdack; + + total_read = 0; + unaligned_size = 0; + if (((u32)ptr & 3) != 0) { + unaligned_size = 4 - ((u32)ptr & 3); + } + WaitSema(sema_id); + out_buf = (char *)ptr; + dvrp_fd = (int)f->privdata; + remain_size = size; + cmdack.command = 0x1111; + cmdack.input_word[0] = (dvrp_fd >> 16) & 0xFFFF; + cmdack.input_word[1] = dvrp_fd; + cmdack.input_word_count = 4; + cmdack.timeout = 10000000; + while (1) { + int read_size; + if (remain_size <= 0) { + break; + } + chunk_size = current_chunk_size; + if (remain_size < current_chunk_size) { + chunk_size = remain_size; + } + if (unaligned_size != 0) { + chunk_size = unaligned_size; + } + cmdack.input_word[2] = (chunk_size >> 16) & 0xFFFF; + cmdack.input_word[3] = chunk_size; + if ((chunk_size & 0x7F) != 0 || unaligned_size != 0) { + cmdack.output_buffer = (char *)RBUF; + } else { + cmdack.output_buffer = out_buf; + } + if (check_cmdack_err(&DvrdrvExecCmdAckDmaRecvComp, &cmdack, &read_size, __func__)) { + retval = read_size; + goto finish; + } + if ((chunk_size & 0x7F) != 0 || unaligned_size != 0) { + memcpy(out_buf, RBUF, chunk_size); + if (unaligned_size != 0) { + unaligned_size = 0; + } + } + if (read_size <= 0) { + break; + } + remain_size -= read_size; + out_buf += read_size; + total_read += read_size; + } + retval = total_read; +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_readlink(iop_file_t *f, const char *path, char *buf, unsigned int buflen) +{ + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + SBUF[0] = bswap32(buflen); + strcpy((char *)&SBUF[1], path); + cmdack.input_buffer_length = strlen(path) + 5; + cmdack.command = 0x1112; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.output_buffer = RBUF; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDma2Comp, &cmdack, &retval, __func__)) { + goto finish; + } + memcpy(buf, RBUF, buflen); +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_remove(iop_file_t *f, const char *name) +{ + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + strcpy((char *)SBUF, name); + cmdack.command = 0x1113; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = strlen(name) + 1; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_rename(iop_file_t *f, const char *old, const char *new_1) +{ + size_t old_strlen; + const char *old_; + size_t new_offs; + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + old_strlen = strlen(old); + old_ = old; + new_offs = old_strlen + 5; + SBUF[0] = bswap32(new_offs); + strcpy((char *)&SBUF[1], old_); + strcpy((char *)SBUF + new_offs, new_1); + cmdack.command = 0x1114; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = new_offs + strlen(new_1) + 1; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_rmdir(iop_file_t *f, const char *path) +{ + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + strcpy((char *)SBUF, path); + cmdack.command = 0x1115; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = strlen(path) + 1; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_symlink(iop_file_t *f, const char *old, const char *new_1) +{ + size_t old_len; + const char *old_; + size_t new_offs; + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + old_len = strlen(old); + old_ = old; + new_offs = old_len + 5; + SBUF[0] = bswap32(new_offs); + strcpy((char *)&SBUF[1], old_); + strcpy((char *)SBUF + new_offs, new_1); + cmdack.command = 0x1116; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = new_offs + strlen(new_1) + 1; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_sync(iop_file_t *f, const char *dev, int flag) +{ + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + SBUF[0] = bswap32(flag); + strcpy((char *)&SBUF[1], dev); + cmdack.command = 0x1117; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = strlen(dev) + 5; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_umount(iop_file_t *f, const char *fsname) +{ + int retval; + drvdrv_exec_cmd_ack cmdack; + + WaitSema(sema_id); + strcpy((char *)SBUF, fsname); + cmdack.command = 0x1118; + cmdack.input_word_count = 0; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = strlen(fsname) + 1; + cmdack.timeout = 10000000; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } +finish: + SignalSema(sema_id); + return retval; +} + +int dvrf_df_write(iop_file_t *f, void *ptr, int size) +{ + int total_write; + char *in_buffer; + int retval; + int dvrp_fd; + int remain_size; + int unaligned_size; + drvdrv_exec_cmd_ack cmdack; + + total_write = 0; + in_buffer = (char *)ptr; + unaligned_size = 0; + if (((u32)ptr & 3) != 0) { + unaligned_size = 4 - ((u32)ptr & 3); + memcpy(RBUF, ptr, unaligned_size); + } + WaitSema(sema_id); + dvrp_fd = (int)f->privdata; + remain_size = size; + cmdack.command = 0x1119; + cmdack.input_word[0] = (dvrp_fd >> 16) & 0xFFFF; + cmdack.input_word[1] = dvrp_fd; + cmdack.input_word_count = 4; + cmdack.timeout = 10000000; + while (remain_size > 0) { + u32 chunk_size; + chunk_size = current_chunk_size; + if (remain_size < current_chunk_size) { + chunk_size = remain_size; + } + if (unaligned_size != 0) { + chunk_size = unaligned_size; + } + cmdack.input_word[2] = (chunk_size >> 16) & 0xFFFF; + cmdack.input_word[3] = chunk_size; + if (unaligned_size != 0) { + cmdack.input_buffer = (char *)RBUF; + unaligned_size = 0; + } else { + cmdack.input_buffer = in_buffer; + } + cmdack.input_buffer_length = chunk_size; + if (check_cmdack_err(&DvrdrvExecCmdAckDmaSendComp, &cmdack, &retval, __func__)) { + goto finish; + } + if (retval <= 0) { + goto finish; + } + remain_size -= retval; + in_buffer += retval; + total_write += retval; + } + retval = total_write; +finish: + SignalSema(sema_id); + return retval; +} + +void CopySceStat(iox_stat_t *stat, u8 *dvrp_stat) +{ + stat->mode = bswap32(((u32 *)dvrp_stat)[0]); + stat->attr = bswap32(((u32 *)dvrp_stat)[1]); + stat->size = bswap32(((u32 *)dvrp_stat)[2]); + memcpy(stat->ctime, &((u32 *)dvrp_stat)[3], 6); + stat->ctime[6] = ((u8 *)dvrp_stat)[19]; + stat->ctime[7] = ((u8 *)dvrp_stat)[18]; + memcpy(stat->atime, &((u32 *)dvrp_stat)[5], 6); + stat->atime[6] = ((u8 *)dvrp_stat)[27]; + stat->atime[7] = ((u8 *)dvrp_stat)[26]; + memcpy(stat->mtime, &((u32 *)dvrp_stat)[7], 6); + stat->mtime[6] = ((u8 *)dvrp_stat)[35]; + stat->mtime[7] = ((u8 *)dvrp_stat)[34]; + stat->hisize = bswap32(((u32 *)dvrp_stat)[9]); + stat->private_0 = bswap32(((u32 *)dvrp_stat)[10]); + stat->private_1 = bswap32(((u32 *)dvrp_stat)[11]); + stat->private_2 = bswap32(((u32 *)dvrp_stat)[12]); + stat->private_3 = bswap32(((u32 *)dvrp_stat)[13]); + stat->private_4 = bswap32(((u32 *)dvrp_stat)[14]); + stat->private_5 = bswap32(((u32 *)dvrp_stat)[15]); +} diff --git a/sps2_basement/hardware/dvrp/dvrfile/src/imports.lst b/sps2_basement/hardware/dvrp/dvrfile/src/imports.lst new file mode 100644 index 0000000..96bf947 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrfile/src/imports.lst @@ -0,0 +1,35 @@ + +iomanX_IMPORTS_start +I_AddDrv +I_DelDrv +iomanX_IMPORTS_end + +pvrdrv_IMPORTS_start +I_DvrdrvExecCmdAckComp +I_DvrdrvExecCmdAckDma2Comp +I_DvrdrvExecCmdAckDmaRecvComp +I_DvrdrvExecCmdAckDmaSendComp +pvrdrv_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memcpy +I_sprintf +I_strcmp +I_strcpy +I_strlen +sysclib_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/dvrp/dvrfile/src/irx_imports.h b/sps2_basement/hardware/dvrp/dvrfile/src/irx_imports.h new file mode 100644 index 0000000..a56243d --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrfile/src/irx_imports.h @@ -0,0 +1,24 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thsemap.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dvrp/dvripl/Makefile b/sps2_basement/hardware/dvrp/dvripl/Makefile new file mode 100644 index 0000000..f814591 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvripl/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/pvrdrv/include +IOP_OBJS = dvripl.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dvrp/dvripl/src/dvripl.c b/sps2_basement/hardware/dvrp/dvripl/src/dvripl.c new file mode 100644 index 0000000..905e031 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvripl/src/dvripl.c @@ -0,0 +1,345 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "thbase.h" +#include "thsemap.h" +#include "speedregs.h" +#include "errno.h" +#include "timrman.h" +#include "sysmem.h" + +extern int module_start(); +extern int module_stop(); +extern int dvripl_df_init(iop_device_t *dev); +extern int dvripl_df_exit(iop_device_t *dev); +extern int dvripl_df_ioctl(iop_file_t *f, int cmd, void *param); +extern int dvripl_df_devctl(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvripl_df_ioctl2(iop_file_t *f, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvripl_df_null(); +extern s64 dvripl_df_null_long(); +extern int iplioctl2_update(iop_file_t *a1, int cmd, void *arg); +extern void dvr_ready(int a1, void *a2); + +struct _iop_device_ops DvrFuncTbl = + { + &dvripl_df_init, + &dvripl_df_exit, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_ioctl, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_null_long, + &dvripl_df_devctl, + &dvripl_df_null, + &dvripl_df_null, + &dvripl_df_ioctl2}; +s32 dvr_ready_flag; +iop_device_t DVRMAN; +s32 sema_id; +char SBUF[32768]; + +// Based off of DESR / PSX DVR system software version 1.31. +#define MODNAME "DVRIPL" +IRX_ID(MODNAME, 1, 1); + +int _start(int a1, char **argv) +{ + if (a1 >= 0) + return module_start(); + else + return module_stop(); +} + +int module_start() +{ + bool v0; + + DVRMAN.name = "dvr_ipl"; + DVRMAN.desc = "Digital Video Recorder"; + DVRMAN.ops = &DvrFuncTbl; + DVRMAN.type = 0x10000010; + v0 = AddDrv(&DVRMAN) == 0; + if (!v0) + return 1; +#if 0 + return 2; +#else + return 0; +#endif +} + +int module_stop() +{ + bool v0; + + v0 = DelDrv("dvr_ipl") == 0; + if (!v0) + return 2; + return 1; +} + +int dvripl_df_init(iop_device_t *dev) +{ + int v1; + iop_sema_t v3; + + printf("dvripl_df_init\n"); + v3.attr = 0; + v3.initial = 1; + v3.max = 1; + v3.option = 0; + v1 = CreateSema(&v3); + if (v1 < 0) + return -1; + sema_id = v1; + return 0; +} + +int dvripl_df_exit(iop_device_t *dev) +{ + bool v1; + + printf("dvripl_df_exit\n"); + v1 = DeleteSema(sema_id) == 0; + if (!v1) + return -1; + return 0; +} + +int dvripl_df_ioctl(iop_file_t *f, int cmd, void *param) +{ + printf("dvripl_df_ioctl\n"); + WaitSema(sema_id); + SignalSema(sema_id); + return -22; +} + +int dvripl_df_devctl( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + bool v10; + int v11; + + printf("dvripl_df_devctl\n"); + WaitSema(sema_id); + v10 = cmd != 0x5602; + v11 = -22; + if (!v10) + v11 = iplioctl2_update(a1, 0x5602, arg); + SignalSema(sema_id); + return v11; +} + +int dvripl_df_ioctl2(iop_file_t *f, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen) +{ + printf("dvripl_df_ioctl2\n"); + WaitSema(sema_id); + SignalSema(sema_id); + return -22; +} + +int dvripl_df_null() +{ + return -48; +} + +s64 dvripl_df_null_long() +{ + return -48LL; +} + +int iplioctl2_update(iop_file_t *a1, int cmd, void *arg) +{ + int total_size; + int retval; + int csum; + int cmdackerr1; + int cmdackerr2; + int cmdackerr3; + int update_fd; +#if 0 + int hard_timer; + u32 system_clock; +#endif + int cmdackerr4; + drvdrv_exec_cmd_ack cmdack; + + total_size = 0; + retval = 0; + csum = 0; + printf("iplioctl2_update\n"); + printf("NOP\n"); + cmdack.command = 0x101; + cmdack.input_word_count = 0; + cmdackerr1 = DvrdrvExecCmdAck(&cmdack); + printf("dvrcmd.ack_p[0]:%x\n", cmdack.ack_status_ack); + if (cmdackerr1) + goto LABEL_2; + if (cmdack.ack_status_ack) { + printf("NOP -> Status error!\n"); + return -5; + } + printf("VERSION\n"); + cmdack.command = 0x102; + cmdack.input_word_count = 0; + cmdackerr2 = DvrdrvExecCmdAck(&cmdack); + printf("dvrcmd.ack_p[0]:%x\n", cmdack.ack_status_ack); + if (cmdackerr2) { + LABEL_2: + printf("NOP -> Handshake error!\n"); + return -5; + } + if (cmdack.ack_status_ack) { + printf("NOP -> Status error!\n"); + return -5; + } + printf("major : %04x\n", cmdack.output_word[0]); + printf("minor : %04x\n", cmdack.output_word[1]); + printf("CONFIG\n"); + cmdack.command = 0x106; + cmdack.input_word[0] = 1; + cmdack.input_word[1] = 6; + cmdack.input_word[2] = 0x1000; + cmdack.input_word[3] = 0x8968; + cmdack.input_word[4] = 0x115A; + cmdack.input_word[5] = 0x6048; + cmdack.input_word[6] = 0xF; + cmdack.input_word[7] = 0x5353; + cmdack.input_word_count = 8; + cmdackerr3 = DvrdrvExecCmdAck(&cmdack); + printf("dvrcmd.ack_p[0]:%x\n", cmdack.ack_status_ack); + if (cmdackerr3) { + printf("CONFIG -> Handshake error!(%d)\n", cmdackerr3); + return -5; + } + if (cmdack.ack_status_ack) { + printf("CONFIG -> Status error!\n"); + return -5; + } + update_fd = open((const char *)arg, 1, 0x124); + if (update_fd >= 0) { + int chunk_offset; + chunk_offset = 0x10000000; + printf("Opened \"%s\"\n", (const char *)arg); + printf("Downloading \"%s\"\n", (const char *)arg); +#if 0 + hard_timer = AllocHardTimer(1, 32, 1); + SetupHardTimer(hard_timer, 1, 0, 1); + StartHardTimer(hard_timer); +#endif + while (1) { + int read_buf_offs; + int *read_buf; + s32 chunk_size; + int read_size; + printf("%08X\n", chunk_offset); + read_size = read(update_fd, SBUF, 0x8000); + chunk_size = read_size; + if (read_size < 0) { + retval = -5; + printf("Cannot read \"%s\"\n", (const char *)arg); + goto LABEL_30; + } + read_buf = (int *)SBUF; + if (!read_size) + break; + read_buf_offs = 0; + while (read_buf_offs++ < chunk_size / 4) { + unsigned int read_buf_tmp; + read_buf_tmp = *read_buf++; + csum += (read_buf_tmp << 24) + ((read_buf_tmp & 0xFF00) << 8) + ((read_buf_tmp & 0xFF0000) >> 8) + ((read_buf_tmp & 0xff000000) >> 24); + } + cmdack.command = 0x103; + cmdack.input_word[0] = chunk_offset >> 16; + cmdack.input_word[1] = chunk_offset; + cmdack.input_word_count = 2; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = chunk_size; + if (DvrdrvExecCmdAckDmaSendComp(&cmdack)) { + retval = -5; + printf("Handshake error! (phase:%d)\n", cmdack.phase); + goto LABEL_30; + } + chunk_offset += chunk_size; + if (cmdack.ack_status_ack) + goto LABEL_29; + total_size += chunk_size; + } +#if 0 + system_clock = GetTimerCounter(hard_timer); + printf("System Clock : %ld\n", system_clock); + StopHardTimer(hard_timer); + FreeHardTimer(hard_timer); +#endif + printf("CHECK SUM\n"); + printf("total_size:%d\n", total_size); + printf("csum : %x\n", csum); + cmdack.command = 0x105; + cmdack.input_word[0] = 0x1000; + cmdack.input_word[2] = total_size >> 16; + cmdack.input_word[4] = csum >> 16; + cmdack.input_word[1] = 0; + cmdack.input_word[3] = total_size; + cmdack.input_word[5] = csum; + cmdack.input_word_count = 6; + cmdackerr4 = DvrdrvExecCmdAck(&cmdack); + printf("result: %d\n", cmdackerr4); + printf("dvrcmd.ack_p[0]:%x\n", cmdack.ack_status_ack); + printf("dvrcmd.ack_p[1]:%x\n", cmdack.output_word[0]); + printf("dvrcmd.ack_p[2]:%x\n", cmdack.output_word[1]); + if (cmdackerr4) { + retval = -5; + goto LABEL_30; + } + if (cmdack.ack_status_ack) + LABEL_29: + retval = -5; + } else { + retval = -89; + } +LABEL_30: + close(update_fd); + DvrdrvUnregisterIntrHandler(dvr_ready); + printf("done.\n"); + return retval; +} + +void dvr_ready(int a1, void *a2) +{ + Kprintf("DVRRDY INTERRUPT\n"); + dvr_ready_flag = 1; + iWakeupThread(*(u32 *)a2); +} diff --git a/sps2_basement/hardware/dvrp/dvripl/src/imports.lst b/sps2_basement/hardware/dvrp/dvripl/src/imports.lst new file mode 100644 index 0000000..238194c --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvripl/src/imports.lst @@ -0,0 +1,44 @@ + +iomanX_IMPORTS_start +I_AddDrv +I_DelDrv +I_open +I_close +I_read +iomanX_IMPORTS_end + +pvrdrv_IMPORTS_start +I_DvrdrvUnregisterIntrHandler +I_DvrdrvExecCmdAck +I_DvrdrvExecCmdAckDmaSendComp +pvrdrv_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysmem_IMPORTS_start +I_Kprintf +sysmem_IMPORTS_end + +thbase_IMPORTS_start +I_iWakeupThread +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end + +timrman_IMPORTS_start +I_AllocHardTimer +I_FreeHardTimer +I_GetTimerCounter +#if 0 +I_SetupHardTimer +I_StartHardTimer +I_StopHardTimer +#endif +timrman_IMPORTS_end diff --git a/sps2_basement/hardware/dvrp/dvripl/src/irx_imports.h b/sps2_basement/hardware/dvrp/dvripl/src/irx_imports.h new file mode 100644 index 0000000..537ac80 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvripl/src/irx_imports.h @@ -0,0 +1,25 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "sysmem.h" +#include "thbase.h" +#include "thsemap.h" +#include "timrman.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/dvrp/dvrmisc/Makefile b/sps2_basement/hardware/dvrp/dvrmisc/Makefile new file mode 100644 index 0000000..33f557b --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrmisc/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/pvrdrv/include +IOP_OBJS = dvrmisc.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/dvrp/dvrmisc/src/dvrmisc.c b/sps2_basement/hardware/dvrp/dvrmisc/src/dvrmisc.c new file mode 100644 index 0000000..c7b58d5 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrmisc/src/dvrmisc.c @@ -0,0 +1,1229 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thsemap.h" +#include "speedregs.h" +#include "errno.h" + +extern int module_start(); +extern int module_stop(); +extern int dvrmisc_df_init(iop_device_t *dev); +extern int dvrmisc_df_exit(iop_device_t *dev); +extern int dvrmisc_df_ioctl(iop_file_t *f, int cmd, void *param); +extern int dvrmisc_df_devctl(iop_file_t *a1, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrmisc_df_ioctl2(iop_file_t *f, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrmisc_df_null(); +extern s64 dvrmisc_df_null_long(); +extern int dvrioctl2_nop(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_version(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_led_hdd_rec(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_led_dvd_rec(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_sircs(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_time(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_set_timezone(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_save_preset_info(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_load_preset_info(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_test_dev_rst(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_test_sdram_chk(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_test_mpe_chk(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_test_mpd_chk(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_test_vdec_chk(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_partition_free(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_buzzer(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_clr_preset_info(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_vbi_err_rate(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_update_dvrp_firmware(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_flash_write_status(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_set_device_key(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_device_key(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_set_dv_nodeid(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_get_dv_nodeid(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); +extern int dvrioctl2_diag_test(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen); + +struct DevctlCmdTbl_t +{ + u16 cmd; + int (*fn)(iop_file_t *, int, void *, unsigned int, void *, unsigned int); +} DevctlCmdTbl[25] = + { + {0x5668, &dvrioctl2_get_sircs}, + {0x5666, &dvrioctl2_led_hdd_rec}, + {0x5667, &dvrioctl2_led_dvd_rec}, + {0x5669, &dvrioctl2_get_time}, + {0x566A, &dvrioctl2_set_timezone}, + {0x566B, &dvrioctl2_save_preset_info}, + {0x566C, &dvrioctl2_load_preset_info}, + {0x5664, &dvrioctl2_nop}, + {0x5665, &dvrioctl2_version}, + {0x566D, &dvrioctl2_test_dev_rst}, + {0x566E, &dvrioctl2_test_sdram_chk}, + {0x566F, &dvrioctl2_test_mpe_chk}, + {0x5670, &dvrioctl2_test_mpd_chk}, + {0x5671, &dvrioctl2_test_vdec_chk}, + {0x5672, &dvrioctl2_partition_free}, + {0x5673, &dvrioctl2_buzzer}, + {0x5674, &dvrioctl2_clr_preset_info}, + {0x5675, &dvrioctl2_get_vbi_err_rate}, + {0x5676, &dvrioctl2_update_dvrp_firmware}, + {0x5677, &dvrioctl2_flash_write_status}, + {0x5678, &dvrioctl2_set_device_key}, + {0x5679, &dvrioctl2_get_device_key}, + {0x567A, &dvrioctl2_set_dv_nodeid}, + {0x567B, &dvrioctl2_get_dv_nodeid}, + {0x5682, &dvrioctl2_diag_test}, +}; +struct _iop_device_ops DvrFuncTbl = + { + &dvrmisc_df_init, + &dvrmisc_df_exit, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_ioctl, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_null_long, + &dvrmisc_df_devctl, + &dvrmisc_df_null, + &dvrmisc_df_null, + &dvrmisc_df_ioctl2}; +iop_device_t DVRMISC; +s32 sema_id; +char SBUF[16384]; + +// Based off of DESR / PSX DVR system software version 1.31. +// Added additional functions from DESR / PSX DVR system software version 2.11. +#define MODNAME "DVRMISC" +IRX_ID(MODNAME, 1, 1); + +int _start(int a1, char **argv) +{ + if (a1 >= 0) + return module_start(); + else + return module_stop(); +} + +int module_start() +{ + int i; + + for (i = 0; i < 30000; ++i) { + if (((*((vu32 *)0xB0004230)) & 4) != 0) + break; + DelayThread(1000); + } + if (i == 30000) { + printf("MISC task of DVRP is not running...\n"); + return 1; + } else { + DVRMISC.name = "dvr_misc"; + DVRMISC.desc = "Digital Video Recorder MISC task"; + DVRMISC.type = 0x10000010; + DVRMISC.ops = &DvrFuncTbl; + if (AddDrv(&DVRMISC) != 0) + return 1; + } +#if 0 + return 2; +#else + return 0; +#endif +} + +int module_stop() +{ + if (DelDrv("dvr_misc") != 0) + return 2; + return 1; +} + +int dvrmisc_df_init(iop_device_t *dev) +{ + int v1; + iop_sema_t v3; + + v3.attr = 0; + v3.initial = 1; + v3.max = 1; + v3.option = 0; + v1 = CreateSema(&v3); + if (v1 < 0) + return -1; + sema_id = v1; + return 0; +} + +int dvrmisc_df_exit(iop_device_t *dev) +{ + if (DeleteSema(sema_id) != 0) + return -1; + return 0; +} + +int dvrmisc_df_ioctl(iop_file_t *f, int cmd, void *param) +{ + WaitSema(sema_id); + SignalSema(sema_id); + return -22; +} + +int dvrmisc_df_devctl( + iop_file_t *a1, + const char *name, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v10; + unsigned int v11; + unsigned int v12; + + v10 = 0; + v11 = 0; + WaitSema(sema_id); + v12 = 0; + while (DevctlCmdTbl[v12].cmd != cmd) { + v12 = ++v11; + if (v11 >= sizeof(DevctlCmdTbl) / sizeof(DevctlCmdTbl[0])) + goto LABEL_5; + } + v10 = DevctlCmdTbl[v12].fn(a1, cmd, arg, arglen, buf, buflen); +LABEL_5: + if (v11 == sizeof(DevctlCmdTbl) / sizeof(DevctlCmdTbl[0])) + v10 = -22; + SignalSema(sema_id); + return v10; +} + +int dvrmisc_df_ioctl2( + iop_file_t *f, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + WaitSema(sema_id); + SignalSema(sema_id); + return -22; +} + +int dvrmisc_df_null() +{ + return -48; +} + +s64 dvrmisc_df_null_long() +{ + return -48LL; +} + +int dvrioctl2_nop(iop_file_t *a1, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5101; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("dvrioctl2_nop -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_nop -> Status error!\n"); + return -68; + } + } + return 0; +} + +int dvrioctl2_version( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5102; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("dvrioctl2_version -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack) { + printf("dvrioctl2_version -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + *((u16 *)buf + 1) = cmdack.output_word[1]; + } + return 0; +} + +int dvrioctl2_led_hdd_rec( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5104; + cmdack.input_word_count = 1; + cmdack.input_word[0] = *(u16 *)arg; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("dvrioctl2_led_hdd_rec -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_led_hdd_rec -> Status error!\n"); + return -68; + } + } + return 0; +} + +int dvrioctl2_led_dvd_rec( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5106; + cmdack.input_word_count = 1; + cmdack.input_word[0] = *(u16 *)arg; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("dvrioctl2_led_dvd_rec -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_led_dvd_rec -> Status error!\n"); + return -68; + } + } + return 0; +} + +int dvrioctl2_get_sircs( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5107; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("dvrioctl2_get_sircs -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack) { + printf("dvrioctl2_get_sircs -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + *((u16 *)buf + 1) = cmdack.output_word[1]; + *((u16 *)buf + 2) = cmdack.output_word[2]; + *((u16 *)buf + 3) = cmdack.output_word[3]; + *((u16 *)buf + 4) = cmdack.output_word[4]; + } + return 0; +} + +int dvrioctl2_get_time( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5108; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("dvrioctl2_get_time -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack) { + printf("dvrioctl2_get_time -> Status error!\n"); + return -68; + } else { + *(u8 *)buf = cmdack.output_word[0]; + *((u8 *)buf + 1) = cmdack.output_word[1]; + *((u8 *)buf + 2) = cmdack.output_word[2]; + *((u8 *)buf + 3) = cmdack.output_word[3]; + *((u8 *)buf + 5) = cmdack.output_word[5]; + *((u8 *)buf + 6) = cmdack.output_word[6]; + *((u8 *)buf + 7) = cmdack.output_word[7]; + } + return 0; +} + +int dvrioctl2_set_timezone( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5109; + cmdack.input_word[0] = *(u16 *)arg; + cmdack.input_word_count = 2; + cmdack.input_word[1] = *((u16 *)arg + 1); + if (DvrdrvExecCmdAck(&cmdack)) { + printf("dvrioctl2_set_timezone -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_set_timezone -> Status error!\n"); + return -68; + } + } + return 0; +} + +int dvrioctl2_save_preset_info( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x510A; + cmdack.input_word_count = 0; + cmdack.timeout = 15000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("dvrioctl2_save_preset_info -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack || cmdack.comp_status) { + printf("dvrioctl2_save_preset_info -> Status error!\n"); + return -68; + } + return 0; +} + +int dvrioctl2_load_preset_info( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x510B; + cmdack.input_word_count = 0; + cmdack.timeout = 15000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("dvrioctl2_load_preset_info -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack || cmdack.comp_status) { + printf("dvrioctl2_load_preset_info -> Status error!\n"); + return -68; + } + return 0; +} + +int dvrioctl2_test_dev_rst( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x510C; + cmdack.input_word_count = 0; + cmdack.timeout = 15000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("dvrioctl2_test_dev_rst -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack || cmdack.comp_status) { + printf("dvrioctl2_test_dev_rst -> Status error!\n"); + return -68; + } + return 0; +} + +int dvrioctl2_test_sdram_chk( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x510D; + cmdack.input_word_count = 0; + cmdack.timeout = 20000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("dvrioctl2_test_sdram_chk -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack || cmdack.comp_status) { + printf("dvrioctl2_test_sdram_chk -> Status error!\n"); + return -68; + } else { + *(u32 *)buf = (cmdack.return_result_word[0] << 16) + cmdack.return_result_word[1]; + *((u32 *)buf + 1) = (cmdack.return_result_word[2] << 16) + cmdack.return_result_word[3]; + *((u32 *)buf + 2) = (cmdack.return_result_word[4] << 16) + cmdack.return_result_word[5]; + } + return 0; +} + +int dvrioctl2_test_mpe_chk( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x510E; + cmdack.input_word_count = 0; + cmdack.timeout = 15000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("dvrioctl2_test_mpe_chk -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack || cmdack.comp_status) { + printf("dvrioctl2_test_mpe_chk -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.return_result_word[0]; + } + return 0; +} + +int dvrioctl2_test_mpd_chk( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x510F; + cmdack.input_word_count = 0; + cmdack.timeout = 15000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("dvrioctl2_test_mpd_chk -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack || cmdack.comp_status) { + printf("dvrioctl2_test_mpd_chk -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.return_result_word[0]; + } + return 0; +} + +int dvrioctl2_test_vdec_chk( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5110; + cmdack.input_word_count = 0; + cmdack.timeout = 15000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("dvrioctl2_test_vdec_chk -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack || cmdack.comp_status) { + printf("dvrioctl2_test_vdec_chk -> Status error!\n"); + return -68; + } + return 0; +} + +int dvrioctl2_partition_free( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v7; + int v8; + int v9; + s64 v10; + + v7 = devctl((const char *)arg, 0x5002, 0, 0, 0, 0); + v8 = v7; + if (v7 < 0) { + printf("dvrioctl2_partition_free : Cannot execute PDIOC_ZONEFREE.,%d\n", v7); + return -5; + } + v9 = devctl((const char *)arg, 0x5001, 0, 0, 0, 0); + v10 = v8 * (s64)v9; + if (v9 < 0) { + printf("dvrioctl2_partition_free : Cannot execute PDIOC_ZONESZ.,%d\n", v9); + return -5; + } + *(u64 *)buf = v10; + if (*(s64 *)buf <= 0x7FFFFFF) { + *(u32 *)buf = 0; + *((u32 *)buf + 1) = 0; + } else { + *(u32 *)buf = v10 - 0x8000000; + *((u32 *)buf + 1) = (v10 >> 32) - 1 + ((unsigned int)(v10 - 0x8000000) < 0xF8000000); + } + return 0; +} + +int dvrioctl2_buzzer( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5111; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("dvrioctl2_buzzer -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_buzzer -> Status error!\n"); + return -68; + } + } + return 0; +} + +int dvrioctl2_clr_preset_info( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5112; + cmdack.input_word_count = 0; + cmdack.timeout = 20000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("dvrioctl2_clr_preset_info -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_clr_preset_info -> Status error!\n"); + return -68; + } + } + return 0; +} + +int dvrioctl2_get_vbi_err_rate( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5113; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("dvrioctl2_get_vbi_err_rate -> Handshake error!\n"); + return -5; + } else { + if (cmdack.ack_status_ack) { + printf("dvrioctl2_get_vbi_err_rate -> Status error!\n"); + return -68; + } else { + *(u32 *)buf = (cmdack.output_word[0] << 16) + cmdack.output_word[1]; + *((u32 *)buf + 1) = (cmdack.output_word[2] << 16) + cmdack.output_word[3]; + } + } + return 0; +} + +int dvrioctl2_update_dvrp_firmware( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int read_offset; + int checksum; + int retval; + int update_fd; + int update_size; + int i; + drvdrv_exec_cmd_ack cmdack; + + read_offset = 0; + checksum = 0; + retval = -1; + update_fd = open((const char *)arg, 1, 0x49, arglen); + if (update_fd < 0) { + retval = -2; + goto LABEL_38; + } + update_size = lseek(update_fd, 0, 2); + if (lseek(update_fd, 0, 0) < 0) + goto LABEL_38; + cmdack.command = 0x5114; + cmdack.input_word[0] = update_size >> 16; + cmdack.input_word[1] = update_size; + cmdack.input_word_count = 2; + cmdack.timeout = 10000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("FLASH_DATA_TOTALSIZE -> Handshake error!\n"); + LABEL_37: + retval = -5; + goto LABEL_38; + } + if (cmdack.ack_status_ack) { + printf("FLASH_DATA_TOTALSIZE -> Status error!\n"); + goto LABEL_37; + } + if (cmdack.comp_status) { + printf("FLASH_DATA_TOTALSIZE -> Status error!\n"); + goto LABEL_37; + } + if (update_size != (cmdack.return_result_word[0] << 16) + cmdack.return_result_word[1]) + printf("Size of firmware is not equal to Size of buffer on DVRP memory.\n"); + for (i = 0x3FFF;; i = 0x3FFF) { + char *v13; + int read_size; + int j; + v13 = &SBUF[0x3FFF]; + do { + *v13 = 0; + --i; + --v13; + } while (i >= 0); + read_size = read(update_fd, SBUF, 0x4000); + if (read_size <= 0) + break; + cmdack.command = 0x5115; + cmdack.input_word[0] = read_offset >> 16; + cmdack.input_word[1] = read_offset; + cmdack.input_word_count = 2; + cmdack.input_buffer = SBUF; + cmdack.input_buffer_length = read_size; + cmdack.timeout = 10000000; + if (DvrdrvExecCmdAckDmaSendComp(&cmdack)) { + printf("MISCCMD_FLASH_DATA_DOWNLOAD -> Handshake error!\n"); + goto LABEL_37; + } + if (cmdack.ack_status_ack || (read_offset += read_size, cmdack.comp_status)) { + printf("MISCCMD_FLASH_DATA_DOWNLOAD -> Status error!\n"); + goto LABEL_37; + } + for (j = 0; j < read_size; ++j) { + checksum += (u8)SBUF[j]; + } + } + cmdack.command = 0x5116; + cmdack.input_word[0] = update_size >> 16; + cmdack.input_word[2] = checksum >> 16; + cmdack.input_word[1] = update_size; + cmdack.input_word[3] = checksum; + cmdack.input_word[4] = 0; + cmdack.input_word[5] = 0; + cmdack.input_word_count = 6; + cmdack.timeout = 10000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("MISCCMD_FLASH_DATA_CHECKSUM -> Handshake error!\n"); + goto LABEL_37; + } + if (cmdack.ack_status_ack) { + printf("MISCCMD_FLASH_DATA_CHECKSUM -> ACK Status error!\n"); + } else { + if (cmdack.comp_status) { + retval = -68; + printf("MISCCMD_FLASH_DATA_CHECKSUM -> COMP Status error!\n"); + printf( + "Check sum error! IOP:%08X,DVRP:%08X\n", + checksum, + (cmdack.return_result_word[0] << 16) | cmdack.return_result_word[1]); + goto LABEL_38; + } + cmdack.command = 0x5117; + cmdack.input_word_count = 0; + cmdack.timeout = 10000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("MISCCMD_FLASH_DATA_WRITE -> Handshake error!\n"); + goto LABEL_37; + } + if (cmdack.ack_status_ack) { + printf("MISCCMD_FLASH_DATA_WRITE -> ACK Status error!\n"); + } else { + retval = 0; + if (!cmdack.comp_status) + goto LABEL_38; + printf("MISCCMD_FLASH_DATA_WRITE -> COMP Status error!\n"); + } + } + retval = -68; +LABEL_38: + close(update_fd); + return retval; +} + +int dvrioctl2_flash_write_status( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x5118; + cmdack.input_word_count = 0; + if (DvrdrvExecCmdAck(&cmdack)) { + printf("dvrioctl2_flash_write_status -> Handshake error!\n"); + return -5; + } else if (cmdack.ack_status_ack) { + printf("dvrioctl2_flash_write_status -> Status error!\n"); + return -68; + } else { + *(u16 *)buf = cmdack.output_word[0]; + *((u16 *)buf + 1) = cmdack.output_word[1]; + } + return 0; +} + +int dvrioctl2_set_device_key( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdack_err; + int bsize; + int *byteswap_tmp2; + int *byteswap_tmp; + int *byteswap_tmp_end; + int cmdack_err3; + int cmdack_err2; + drvdrv_exec_cmd_ack cmdack; + + printf( + "dvrioctl2_set_device_key (io=%p,cmd=%08X,argp=%p,arglen=%u,bufp=%p,buflen=%u)\n", + a1, + cmd, + arg, + arglen, + buf, + buflen); + cmdack.command = 0x511B; + cmdack.input_word[0] = 0; + cmdack.input_word[1] = 456; + cmdack.input_word_count = 2; + cmdack.timeout = 10000000; + printf("dvrcmd.cmd_p[0]:%x\n", 0); + printf("dvrcmd.cmd_p[1]:%x\n", 456); + cmdack_err = DvrdrvExecCmdAckComp(&cmdack); + printf("dvrcmd.ack_p[0]:%x\n", cmdack.ack_status_ack); + if (cmdack_err) { + printf("DEVKEY_TOTALSIZE -> Handshake error!\n"); + return -5; + } + if (cmdack.ack_status_ack || cmdack.comp_status) { + printf("DEVKEY_TOTALSIZE -> Status error!\n"); + return -5; + } + bsize = (cmdack.return_result_word[0] << 16) + cmdack.return_result_word[1]; + if (bsize != 456) + printf("Size of firmware is not equal to Size of buffer on DVRP memory.\n"); + printf("FSIZE:%08X\n", 456); + printf("BSIZE:%08X\n", bsize); + cmdack.command = 0x511C; + ((u32 *)SBUF)[0] = *(u32 *)"XESD"; + byteswap_tmp2 = (int *)&SBUF[4]; + byteswap_tmp = (int *)arg; + byteswap_tmp_end = (int *)((char *)arg + 448); + do { + byteswap_tmp2[0] = byteswap_tmp[0]; + byteswap_tmp2[1] = byteswap_tmp[1]; + byteswap_tmp2[2] = byteswap_tmp[2]; + byteswap_tmp2[3] = byteswap_tmp[3]; + byteswap_tmp += 4; + byteswap_tmp2 += 4; + } while (byteswap_tmp != byteswap_tmp_end); + *byteswap_tmp2 = *byteswap_tmp; + cmdack.input_word_count = 2; + cmdack.input_word[0] = 0; + cmdack.input_word[1] = 0; + cmdack.input_buffer = &SBUF; + cmdack.input_buffer_length = 456; + cmdack.timeout = 10000000; + cmdack_err3 = DvrdrvExecCmdAckDmaSendComp(&cmdack); + printf("dvrcmd.ack_p[0]:%x\n", cmdack.ack_status_ack); + if (cmdack_err3) { + printf("MISCCMD_DEVKEY_DOWNLOAD -> Handshake error!\n"); + return -5; + } + if (cmdack.ack_status_ack) { + printf("MISCCMD_DEVKEY_DOWNLOAD -> Status error!\n"); + return -5; + } + if (cmdack.comp_status) { + printf("MISCCMD_DEVKEY_DOWNLOAD -> Status error!\n"); + return -5; + } + cmdack.command = 0x5119; + cmdack.input_word_count = 0; + cmdack.timeout = 10000000; + cmdack_err2 = DvrdrvExecCmdAckComp(&cmdack); + printf("dvrcmd.ack_p[0]:%x\n", cmdack.ack_status_ack); + if (cmdack_err2) { + printf("MISCCMD_SAVE_DEVKEY_INFO -> Handshake error!\n"); + return -5; + } + if (cmdack.ack_status_ack) { + printf("MISCCMD_SAVE_DEVKEY_INFO -> Status error!\n"); + return -68; + } + if (cmdack.comp_status) { + printf("MISCCMD_SAVE_DEVKEY_INFO -> Status error!\n"); + return -5; + } + return 0; +} + +int dvrioctl2_get_device_key( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int v6; + u16 *return_result_word; + int busywait; + drvdrv_exec_cmd_ack cmdack; + u8 v27[8]; + + cmdack.command = 0x511A; + cmdack.input_word[0] = 0; + cmdack.input_word[1] = 4; + cmdack.input_word_count = 2; + cmdack.timeout = 15000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("MISCCMD_GET_DEVKEY_INFO -> Handshake error!\n"); + return -5; + } + if (cmdack.ack_status_ack) { + printf("MISCCMD_GET_DEVKEY_INFO -> Status error!\n"); + return -68; + } + if (cmdack.comp_status) { + printf("MISCCMD_GET_DEVKEY_INFO -> Status error!\n"); + return -5; + } + v6 = 0; + return_result_word = cmdack.return_result_word; + do { + u8 *v8; + v8 = &v27[v6]; + v6 += 2; + v8[0] = (*return_result_word & 0xFF00) >> 8; + v8[1] = (*return_result_word & 0x00FF); + return_result_word += 1; + } while (v6 < 4); + busywait = 2; + do { + } while (busywait-- >= 0); + if (memcmp(v27, "XESD", 4) == 0) { + int v13; + u16 *in_word_tmp; + u16 v17; + int v18; + int v19; + unsigned int v20; + v13 = 0; + in_word_tmp = &cmdack.return_result_word[2]; + do { + u8 *v15; + v15 = (u8 *)buf + v13; + v13 += 2; + v15[0] = (*in_word_tmp & 0xFF00) >> 8; + v15[1] = (*in_word_tmp & 0x00FF); + in_word_tmp += 1; + } while (v13 < 4); + v17 = 4; + v18 = 224; + v19 = 0; + v20 = 224; + while (1) { + int v21; + int v22; + v21 = v18; + if (v20 >= 0x11) + v21 = 16; + cmdack.command = 0x511A; + cmdack.input_word[0] = v17; + cmdack.input_word[1] = v21; + cmdack.input_word_count = 2; + cmdack.timeout = 30000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("MISCCMD_GET_DEVKEY_INFO -> Handshake error!\n"); + return -5; + } + if (cmdack.ack_status_ack) { + printf("MISCCMD_GET_DEVKEY_INFO -> Status error!\n"); + return -68; + } + v22 = 1; + if (cmdack.comp_status) { + printf("MISCCMD_GET_DEVKEY_INFO -> Status error!\n"); + return -5; + } + if ((u16)v21 + 1 > 1) { + u16 *in_word_tmp2; + in_word_tmp2 = cmdack.return_result_word; + do { + u8 *v24; + v24 = (u8 *)buf + v19; + v19 += 2; + v22 += 1; + v24[4] = (*in_word_tmp2 & 0xFF00) >> 8; + v24[5] = (*in_word_tmp2 & 0x00FF); + in_word_tmp2 += 1; + } while (v22 < (u16)v21 + 1); + } + v18 -= v21; + v20 = (u16)v18; + v17 += v21; + if (!(u16)v18) + return 0; + } + } + return -68; +} + +int dvrioctl2_set_dv_nodeid( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + unsigned int argwalked; + drvdrv_exec_cmd_ack cmdack; + + argwalked = 0; + cmdack.command = 0x511D; + if (arglen) { + u8 *inword_tmp; + inword_tmp = ((u8 *)&cmdack.input_word[0]); + do { + u8 *inword_tmp2; + inword_tmp2 = ((u8 *)arg + argwalked); + inword_tmp[0] = inword_tmp2[1]; + inword_tmp[1] = inword_tmp2[0]; + inword_tmp += 2; + argwalked += 2; + } while (argwalked < arglen); + } + cmdack.input_word_count = 4; + cmdack.timeout = 10000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("MISCCMD_SAVE_DV_NODEID -> Handshake error!\n"); + return -5; + } + if (cmdack.ack_status_ack) { + printf("MISCCMD_SAVE_DV_NODEID -> Status error!\n"); + return -68; + } + if (cmdack.comp_status) { + printf("MISCCMD_SAVE_DV_NODEID -> Status error!\n"); + return -5; + } + return 0; +} + +int dvrioctl2_get_dv_nodeid( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + unsigned int bufwalked; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x511E; + cmdack.input_word_count = 0; + cmdack.timeout = 15000000; + if (DvrdrvExecCmdAckComp(&cmdack)) { + printf("MISCCMD_GET_DV_NODEID -> Handshake error!\n"); + return -5; + } + if (cmdack.ack_status_ack) { + printf("MISCCMD_GET_DV_NODEID -> Status error!\n"); + return -68; + } + if (cmdack.comp_status) { + printf("MISCCMD_GET_DV_NODEID -> Status error!\n"); + return -5; + } + bufwalked = 0; + if (buflen) { + u16 *return_result_word; + return_result_word = cmdack.return_result_word; + do { + char *buftmp; + buftmp = (char *)buf + bufwalked; + bufwalked += 2; + buftmp[0] = (*return_result_word & 0xFF00) >> 8; + buftmp[1] = (*return_result_word & 0x00FF); + return_result_word += 1; + } while (bufwalked < buflen); + } + if (buflen) { + int bufbusyloop; + bufbusyloop = 0; + while (bufbusyloop++ < buflen) + ; + } + return 0; +} + +int test_count = 0; + +int dvrioctl2_diag_test( + iop_file_t *a1, + int cmd, + void *arg, + unsigned int arglen, + void *buf, + unsigned int buflen) +{ + int cmdack_err; + int testcnt_tmp; + int outbuf_cnt; + u16 *outbuf_tmp; + drvdrv_exec_cmd_ack cmdack; + + cmdack.command = 0x511F; + cmdack.input_word[0] = *(u16 *)arg; + cmdack.input_word[1] = *((u16 *)arg + 1); + cmdack.input_word[2] = *((u16 *)arg + 2); + cmdack.input_word[3] = *((u16 *)arg + 3); + cmdack.input_word[4] = *((u16 *)arg + 4); + cmdack.input_word_count = 5; + cmdack.timeout = 120000000; + if (cmdack.input_word[2]) { + printf("------------------- > SetTO:%d msec\n", 120000); + cmdack.timeout = 10000000 * cmdack.input_word[2]; + } + printf("arg : %4x", cmdack.input_word[0]); + printf(" %4x", cmdack.input_word[1]); + printf(" %4x ", cmdack.input_word[2]); + printf(" SetTimeOutTo : %d usec\n", cmdack.timeout); + cmdack_err = DvrdrvExecCmdAckComp(&cmdack); + testcnt_tmp = test_count++; + printf( + "cmd ID : %d -------------------- TEST VERSION - diag test -------------------- r %d -- c %d\n", + 31, + cmdack_err, + testcnt_tmp); + printf("diag_test dvrcmd.ack_p[0]:%x\n", cmdack.ack_status_ack); + printf("diag_test dvrcmd.phase:%x\n", cmdack.phase); + if (cmdack_err) { + printf("dvrioctl2_diag_test -> Handshake error!\n"); + return -5; + } + if (cmdack.ack_status_ack) { + printf("dvrioctl2_diag_test -> Status error in ACK! param:%04x\n", cmdack.ack_status_ack); + return -68; + } + if (cmdack.comp_status) { + printf("dvrioctl2_diag_test -> Status error in COMP! param:%04x\n", cmdack.comp_status); + return -68; + } + outbuf_cnt = 0; + printf("---------------------------- return buffer\n"); + outbuf_tmp = (u16 *)&cmdack.return_result_word[0]; + do { + outbuf_cnt += 1; + printf(" %4x", *outbuf_tmp); + *(u16 *)buf = *outbuf_tmp; + outbuf_tmp += 1; + buf = (char *)buf + 2; + } while (outbuf_cnt < 16); + printf("\n"); + return 0; +} diff --git a/sps2_basement/hardware/dvrp/dvrmisc/src/imports.lst b/sps2_basement/hardware/dvrp/dvrmisc/src/imports.lst new file mode 100644 index 0000000..bab2547 --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrmisc/src/imports.lst @@ -0,0 +1,35 @@ + +iomanX_IMPORTS_start +I_AddDrv +I_DelDrv +I_open +I_close +I_read +I_lseek +I_devctl +iomanX_IMPORTS_end + +pvrdrv_IMPORTS_start +I_DvrdrvExecCmdAck +I_DvrdrvExecCmdAckComp +I_DvrdrvExecCmdAckDmaSendComp +pvrdrv_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memcmp +sysclib_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/dvrp/dvrmisc/src/irx_imports.h b/sps2_basement/hardware/dvrp/dvrmisc/src/irx_imports.h new file mode 100644 index 0000000..a56243d --- /dev/null +++ b/sps2_basement/hardware/dvrp/dvrmisc/src/irx_imports.h @@ -0,0 +1,24 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2021-2021, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "iomanX.h" +#include "pvrdrv.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thsemap.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/ee/dmac/dma.c b/sps2_basement/hardware/ee/dmac/dma.c new file mode 100644 index 0000000..a378ad1 --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/dma.c @@ -0,0 +1,541 @@ +#include "dma.h" + +/** DMA Control Register */ +#define DMA_REG_CTRL ((volatile uint32_t *)0x1000E000) +/** Interrupt Status Register */ +#define DMA_REG_STAT ((volatile uint32_t *)0x1000E010) +/** Priority Control Register */ +#define DMA_REG_PCR ((volatile uint32_t *)0x1000E020) +/** Interleave Size Register */ +#define DMA_REG_SQWC ((volatile uint32_t *)0x1000E030) +/** Ring Buffer Size Register */ +#define DMA_REG_RBSR ((volatile uint32_t *)0x1000E040) +/** Ring Buffer Address Register */ +#define DMA_REG_RBOR ((volatile uint32_t *)0x1000E050) +/** Stall Address Register */ +#define DMA_REG_STADR ((volatile uint32_t *)0x1000E060) +/** DMA Hold State Register */ +#define DMA_REG_ENABLER ((volatile uint32_t *)0x1000F520) +/** DMA Hold Control Register */ +#define DMA_REG_ENABLEW ((volatile uint32_t *)0x1000F590) + + + +/** Enable DMA Controller */ +#define DMAE_DISABLE 0 +#define DMAE_ENABLE 1 + +/** Enable Cycle Stealing */ +#define RELE_OFF 0 +#define RELE_ON 1 + +/** fifo drain? */ +#define MFD_OFF 0 +#define MFD_RES 1 +#define MFD_VIF 2 +#define MFD_GIF 3 + +/** stall source? */ +#define STS_UNSPEC 0 +#define STS_SIF 1 +#define STS_SPR 2 +#define STS_IPU 3 + +/** stall drain? */ +#define STD_OFF 0 +#define STD_VIF 1 +#define STD_GIF 2 +#define STD_SIF 3 + +/** Cycles to release control */ +#define RCYC_8 0 +#define RCYC_16 1 +#define RCYC_32 2 +#define RCYC_64 3 +#define RCYC_128 4 +#define RCYC_256 5 + +#define DMA_SET_CTRL(DMAE,RELE,MFD,STS,STD,RCYC) \ + (uint32_t)(DMAE & 0x00000001) << 0 | (uint32_t)(RELE & 0x00000001) << 1 | \ + (uint32_t)(MFD & 0x00000003) << 2 | (uint32_t)(STS & 0x00000003) << 4 | \ + (uint32_t)(STD & 0x00000003) << 6 | (uint32_t)(RCYC & 0x00000007) << 8 + +#define DMA_SET_STAT(CIS,SIS,MEIS,BEIS,CIM,SIM,MEIM) \ + (uint32_t)((CIS) & 0x000003FF) << 0 | (uint32_t)((SIS) & 0x00000001) << 13 | \ + (uint32_t)((MEIS) & 0x00000001) << 14 | (uint32_t)((BEIS) & 0x00000001) << 15 | \ + (uint32_t)((CIM) & 0x000003FF) << 16 | (uint32_t)((SIM) & 0x00000001) << 29 | \ + (uint32_t)((MEIM) & 0x00000001) << 30 + +#define DMA_SET_PCR(CPCOND,CDE,PCE) \ + (uint32_t)((CPCOND) & 0x000003FF) << 0 | (uint32_t)((CDE) & 0x000003FF) << 16 | \ + (uint32_t)((PCE) & 0x00000001) << 31 + +#define DMA_SET_SQWC(SQWC,TQWC) \ + (uint32_t)((SQWC) & 0x000000FF) << 0 | (uint32_t)((TQWC) & 0x000000FF) << 16 + +#define DMA_SET_RBOR(ADDR) (uint32_t)((ADDR) & 0x00007FFF) + +#define DMA_SET_RBSR(RMSK) (uint32_t)((RMSK) & 0x00007FFF) + +#define DMA_SET_STADR(ADDR) (uint32_t)((ADDR) & 0x00007FFF) + +#define DMA_SET_ENABLEW(A) (uint32_t)((A) & 0x00000001) << 16 + +#define DMA_SET_ENABLER(A) (uint32_t)((A) & 0x00000001) << 16 + +/** Per-dma channel registers */ +#define DMA_SET_CHCR(DIR,MODE,ASP,TTE,TIE,STR,TAG) \ + (uint32_t)((DIR) & 0x00000001) << 0 | (uint32_t)((MODE) & 0x00000003) << 2 | \ + (uint32_t)((ASP) & 0x00000003) << 4 | (uint32_t)((TTE ) & 0x00000001) << 6 | \ + (uint32_t)((TIE) & 0x00000001) << 7 | (uint32_t)((STR ) & 0x00000001) << 8 | \ + (uint32_t)((TAG) & 0x0000FFFF) << 16 + + +#define DMA_SET_MADR(ADDR,SPR) \ + (uint32_t)(((uint32_t)ADDR) & 0x7FFFFFFF) << 0 | (uint32_t)((SPR) & 0x00000001) << 31 + +#define DMA_SET_TADR(ADDR,SPR) \ + (uint32_t)(((uint32_t)ADDR) & 0x7FFFFFFF) << 0 | (uint32_t)((SPR) & 0x00000001) << 31 + +#define DMA_SET_ASR0(ADDR,SPR) \ + (uint32_t)(((uint32_t)ADDR) & 0x7FFFFFFF) << 0 | (uint32_t)((SPR) & 0x00000001) << 31 + +#define DMA_SET_ASR1(ADDR,SPR) \ + (uint32_t)(((uint32_t)ADDR) & 0x7FFFFFFF) << 0 | (uint32_t)((SPR) & 0x00000001) << 31 + +#define DMA_SET_SADR(ADDR) (uint32_t)(((uint32_t)ADDR) & 0x00003FFF) + +#define DMA_SET_QWC(QWC) (uint32_t)((QWC) & 0x0000FFFF) + +#define DMA_SET_SIZE(A) \ +(uint32_t)(A & 0x0000FFFF) << 0 + + +/** + * T = location of qwords + * D = next dmatag to be read + * QWC = quadword count for dmatag + */ + +/** T=QWC D=QWC+1 MADR => STADR */ +#define DMA_TAG_CNTS 0x00 +/** T=ADDR then END */ +#define DMA_TAG_REFE 0x00 +/** T=QWC D=QWC+1 */ +#define DMA_TAG_CNT 0x01 +/** T=QWC D=ADDR */ +#define DMA_TAG_NEXT 0x02 +/** D=D+1 T=ADDR */ +#define DMA_TAG_REF 0x03 +/** .. + stall ctrl */ +#define DMA_TAG_REFS 0x04 +/** T=QWC D=ADDR QWC+1 => ASR0 */ +#define DMA_TAG_CALL 0x05 +/** T=QWC (ASR0 => D) if !ASR0 then END */ +#define DMA_TAG_RET 0x06 +/** T=QWC then END */ +#define DMA_TAG_END 0x07 + +#define DMATAG(QWC,PCE,ID,IRQ,ADDR,SPR) \ + (u64)((QWC) & 0x0000FFFF) << 0 | (u64)((PCE) & 0x00000003) << 26 | \ + (u64)((ID) & 0x00000007) << 28 | (u64)((IRQ) & 0x00000001) << 31 | \ + (u64)((ADDR) & 0x7FFFFFFF) << 32 | (u64)((SPR) & 0x00000001) << 63 + +#define PACK_DMATAG(Q,D0,W2,W3) \ + Q->dw[0] = (u64)(D0), \ + Q->sw[2] = (u32)(W2), \ + Q->sw[3] = (u32)(W3) + +/** Insert before qword block, and add dmatag after qword block to continue */ +#define DMATAG_CNT(Q,QWC,SPR,W2,W3) \ + Q->dw[0] = DMATAG(QWC,0,DMA_TAG_CNT,0,0,SPR), \ + Q->sw[2] = (u32)(W2), \ + Q->sw[3] = (u32)(W3) + +/** Insert before qword block, and add dmatag after qword block to continue */ +#define DMATAG_CNTS(Q,QWC,SPR,W2,W3) \ + Q->dw[0] = DMATAG(QWC,0,DMA_TAG_CNTS,0,0,SPR), \ + Q->sw[2] = (u32)(W2), \ + Q->sw[3] = (u32)(W3) + +/** Insert before qword block, and add dmatag at addr to continue */ +#define DMATAG_NEXT(Q,QWC,ADDR,SPR,W2,W3), \ + Q->dw[0] = DMATAG(QWC,0,DMA_TAG_NEXT,0,ADDR,SPR), \ + Q->sw[2] = (u32)(W2), \ + Q->sw[3] = (u32)(W3) + +/** Insert before final qword block, or by itself to end transfer */ +#define DMATAG_END(Q,QWC,SPR,W2,W3) \ + Q->dw[0] = DMATAG(QWC,0,DMA_TAG_END,0,0,SPR), \ + Q->sw[2] = (u32)(W2), \ + Q->sw[3] = (u32)(W3) + +/** Insert before qword block, and add dmatag at qword after qwc to be saved (up to 2) */ +#define DMATAG_CALL(Q,QWC,ADDR,SPR,W2,W3) \ + Q->dw[0] = DMATAG(QWC,0,DMA_TAG_CALL,0,ADDR,SPR), \ + Q->sw[2] = (u32)(W2), \ + Q->sw[3] = (u32)(W3) + +/** Insert before qword block, and continues with saved dmatag */ +#define DMATAG_RET(Q,QWC,SPR,W2,W3) \ + Q->dw[0] = DMATAG(QWC,0,DMA_TAG_RET,0,0,SPR), \ + Q->sw[2] = (u32)(W2), \ + Q->sw[3] = (u32)(W3) + +/** Insert anywhere, qwc at addr is sent, reads next qword to continue */ +#define DMATAG_REF(Q,QWC,ADDR,SPR,W2,W3) \ + Q->dw[0] = DMATAG(QWC,0,DMA_TAG_REF,0,ADDR,SPR), \ + Q->sw[2] = (u32)(W2), \ + Q->sw[3] = (u32)(W3) + +/** Insert anywhere, qwc at addr is sent, reads next qword to continue */ +#define DMATAG_REFS(Q,QWC,ADDR,SPR,W2,W3) \ + Q->dw[0] = DMATAG(QWC,0,DMA_TAG_REFS,0,ADDR,SPR), \ + Q->sw[2] = (u32)(W2), \ + Q->sw[3] = (u32)(W3) + +/** Insert anywhere, qwc at addr is sent, then ends transfer */ +#define DMATAG_REFE(Q,QWC,ADDR,SPR,W2,W3) \ + Q->dw[0] = DMATAG(qwc, 0, DMA_TAG_REFE, 0, addr, spr), \ + Q->sw[2] = (u32)(W2), \ + Q->sw[3] = (u32)(W3) + + +// Channel Control +static volatile uint32_t * dma_chcr[10] = { + (volatile uint32_t *)0x10008000, + (volatile uint32_t *)0x10009000, + (volatile uint32_t *)0x1000A000, + (volatile uint32_t *)0x1000B000, + (volatile uint32_t *)0x1000B400, + (volatile uint32_t *)0x1000C000, + (volatile uint32_t *)0x1000C400, + (volatile uint32_t *)0x1000C800, + (volatile uint32_t *)0x1000D000, + (volatile uint32_t *)0x1000D400 +}; + +// Quadword Count +static volatile uint32_t * dma_qwc[10] = { + (volatile uint32_t *)0x10008020, + (volatile uint32_t *)0x10009020, + (volatile uint32_t *)0x1000A020, + (volatile uint32_t *)0x1000B020, + (volatile uint32_t *)0x1000B420, + (volatile uint32_t *)0x1000C020, + (volatile uint32_t *)0x1000C420, + (volatile uint32_t *)0x1000C820, + (volatile uint32_t *)0x1000D020, + (volatile uint32_t *)0x1000D420 +}; + +// Memory Address +static volatile uint32_t * dma_madr[10] = { + (volatile uint32_t *)0x10008010, + (volatile uint32_t *)0x10009010, + (volatile uint32_t *)0x1000A010, + (volatile uint32_t *)0x1000B010, + (volatile uint32_t *)0x1000B410, + (volatile uint32_t *)0x1000C010, + (volatile uint32_t *)0x1000C410, + (volatile uint32_t *)0x1000C810, + (volatile uint32_t *)0x1000D010, + (volatile uint32_t *)0x1000D410 +}; + +// Tag Address +static volatile uint32_t * dma_tadr[10] = { + (volatile uint32_t *)0x10008030, + (volatile uint32_t *)0x10009030, + (volatile uint32_t *)0x1000A030, + (volatile uint32_t *)0x1000B030, + (volatile uint32_t *)0x1000B430, + (volatile uint32_t *)0x1000C030, + (volatile uint32_t *)0x1000C430, + (volatile uint32_t *)0x1000C830, + (volatile uint32_t *)0x1000D030, + (volatile uint32_t *)0x1000D430 +}; + +// Tag Address Save 0 +static volatile uint32_t * dma_asr0[10] = { + (volatile uint32_t *)0x10008040, + (volatile uint32_t *)0x10009040, + (volatile uint32_t *)0x1000A040, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000 +}; + +// Tag Address Save 1 +static volatile uint32_t * dma_asr1[10] = { + (volatile uint32_t *)0x10008050, + (volatile uint32_t *)0x10009050, + (volatile uint32_t *)0x1000A050, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000 +}; + +// SPR Transfer Address +static volatile uint32_t * dma_sadr[10] = { + (volatile uint32_t *)0x10008080, + (volatile uint32_t *)0x10009080, + (volatile uint32_t *)0x1000A080, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x00000000, + (volatile uint32_t *)0x1000D080, + (volatile uint32_t *)0x1000D480 +}; + +int _dma_init(){ + // Reset the control registers. + *DMA_REG_CTRL = 0x00000000; + *DMA_REG_STAT = 0x00000000; + *DMA_REG_PCR = 0x00000000; + *DMA_REG_SQWC = 0x00000000; + *DMA_REG_RBSR = 0x00000000; + *DMA_REG_RBOR = 0x00000000; + // Enable all channels, enable cycle stealing. + *DMA_REG_CTRL = DMA_SET_CTRL( 1, 1, 0, 0, 0, 0 ); + // End function. + return 0; +}; + +static uint32_t dma_handler_id[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + +static uint8_t dma_channel_initialized[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + +int dma_reset(void){ + uint8_t idx = 0; + for(; idx < 10; idx++){ + dma_channel_shutdown( idx, 0 ); + } + ResetEE( 0x01 ); + return 0; +}; + +int dma_channel_initialize( uint8_t channel, void *handler, uint32_t flags ){ + // Shut down the channel before making changes. + if( dma_channel_shutdown(channel, flags ) < 0 ) return -1; + // Clear any saved dmatags + if( *dma_asr0[channel] ){ + *dma_asr0[channel] = 0; + *dma_asr1[channel] = 0; + }; + // Clear saved spr address + if( *dma_sadr[channel] ){ + *dma_sadr[channel] = 0; + }; + // If a handler is provided... + if( handler != NULL ){ + // Add the handler, storing the handler id. + dma_handler_id[channel] = AddDmacHandler( channel, handler, 0 ); + // Enable the channel interrupt. + if( flags & DMA_FLAG_INTERRUPTSAFE ) { + iEnableDmac(channel); + } else { + EnableDmac(channel); + }; + }; + // Tell everyone we are initialized. + dma_channel_initialized[channel] = 1; + // End function. + return 0; +}; + +// allows for cpcond0 checking +//void dma_channel_fast_waits( uint8_t channel ){ +// *DMA_REG_PCR |= 1 << channel; +//}; + + + +void dma_wait_fast(void){ + __asm__ ( + "sync.l; sync.p;" \ + "0:" \ + "bc0t 0f; nop;" \ + "bc0t 0f; nop;" \ + "bc0t 0f; nop;" \ + "bc0f 0b; nop;" \ + "0:" + ); +}; + +int dma_channel_wait( uint8_t channel, uint32_t timeout ){ + // While the channel is not ready... + while( *dma_chcr[channel] & 0x00000100 ){ + // Decrement the timeout counter, exiting if it expires. + if( !( timeout-- ) ) return -1; + }; + // End function. + return 0; +}; + +void dma_channel_send_packet2( packet2_t *packet2, uint8_t channel, uint8_t flush_cache ){ + if( packet2 == NULL ) return; + // dma_channel_send_chain does NOT flush all data that is "source chained" + if( packet2->mode == P2_MODE_CHAIN ){ + // "dma_channel_send_normal always flushes the data cache" + if( flush_cache ) FlushCache(0); + dma_channel_send_chain( channel, + (void *)((uint32_t)packet2->base & 0x0FFFFFFF ), + 0, + packet2->tte ? DMA_FLAG_TRANSFERTAG : 0, + 0 + ); + } else { + dma_channel_send_normal( + channel, + (void *)((uint32_t)packet2->base & 0x0FFFFFFF), // make ptr normal + ((uint32_t)packet2->next - (uint32_t)packet2->base) >> 4, // length in qwords + 0, + 0 + ); + }; +}; + + +int dma_channel_send_chain( uint8_t channel, void *data, uint32_t data_size, uint32_t flags, uint32_t spr ){ + if( data == NULL ) return -1; + // clear channel status + *DMA_REG_STAT = DMA_SET_STAT(1 << channel,0,0,0,0,0,0); + if( flags & DMA_FLAG_INTERRUPTSAFE ){ + iSyncDCache( data, data + (data_size<<4) ); + } else { + SyncDCache( data, data + (data_size<<4) ); + }; + // Set the size of the data, in quadwords. + *dma_qwc[channel] = DMA_SET_QWC(0); + // Set the address of the data. + *dma_madr[channel] = DMA_SET_MADR(0, 0); + // Set the address of the data tag. + *dma_tadr[channel] = DMA_SET_TADR( data, spr ); + // Start the transfer. + *dma_chcr[channel] = DMA_SET_CHCR( 1, 1, 0, flags & DMA_FLAG_TRANSFERTAG, 1, 1, 0 ); + return 0; +}; + +int dma_channel_send_chain_ucab( uint8_t channel, void *data, uint32_t qwc, uint32_t flags){ + if( data == NULL ) return -1; + // clear channel status + *DMA_REG_STAT = 1 << channel; + // Set the size of the data, in quadwords. + *dma_qwc[channel] = DMA_SET_QWC(0); + // Set the address of the data. + *dma_madr[channel] = DMA_SET_MADR(0, 0); + // Set the address of the data tag. + *dma_tadr[channel] = DMA_SET_TADR( data - 0x30000000, 0 ); + // Start the transfer. + *dma_chcr[channel] = DMA_SET_CHCR( 1, 1, 0, flags & DMA_FLAG_TRANSFERTAG, 1, 1, 0 ); + // End function. + return 0; +}; + +int dma_channel_send_normal( uint8_t channel, void *data, uint32_t qwc, uint32_t flags, uint32_t spr){ + if( data == NULL ) return -1; + // clear channel status + *DMA_REG_STAT = DMA_SET_STAT(1 << channel,0,0,0,0,0,0); + // Not sure if this should be here. + if( flags & DMA_FLAG_INTERRUPTSAFE ){ + iSyncDCache( data, data + (qwc<<4) ); + } else { + SyncDCache( data, data + (qwc<<4) ); + }; + // Set the size of the data, in quadwords. + *dma_qwc[channel] = DMA_SET_QWC( qwc ); + // Set the address of the data. + *dma_madr[channel] = DMA_SET_MADR( data, spr ); + // Start the transfer. + *dma_chcr[channel] = DMA_SET_CHCR( 1, 0, 0, flags & DMA_FLAG_TRANSFERTAG, 1, 1, 0 ); + return 0; +}; + +int dma_channel_send_normal_ucab( uint8_t channel, void *data, uint32_t qwc, uint32_t flags ){ + if( data == NULL ) return -1; + // clear channel status + *DMA_REG_STAT = DMA_SET_STAT(1 << channel,0,0,0,0,0,0); + // Not sure if this should be here. + if( flags & DMA_FLAG_INTERRUPTSAFE ){ + iSyncDCache(data, data + (qwc<<4)); + } else { + SyncDCache(data, data + (qwc<<4)); + }; + // Set the size of the data, in quadwords. + *dma_qwc[channel] = DMA_SET_QWC(qwc); + // Set the address of the data. + *dma_madr[channel] = DMA_SET_MADR( data - 0x30000000, 0); + // Start the transfer. + *dma_chcr[channel] = DMA_SET_CHCR(1, 0, 0, flags & DMA_FLAG_TRANSFERTAG, 1, 1, 0); + return 0; +} + +int dma_channel_receive_chain( uint8_t channel, void *data, uint32_t data_size, uint32_t flags, uint32_t spr ){ + if( data == NULL ) return -1; + // If we are not initialized... + if( !dma_channel_initialized[channel] ){ + // Initialize the channel. + if( dma_channel_initialize( channel, NULL, flags ) < 0 ) return -1; + }; + // Set the size of the data, in quadwords. + *dma_qwc[channel] = DMA_SET_QWC((data_size + 15) >> 4); + // Set the address of the data. + *dma_madr[channel] = DMA_SET_MADR( data, spr ); + // Start the transfer. + *dma_chcr[channel] = DMA_SET_CHCR( 0, 1, 0, 0, 0, 1, 0 ); + // End function. + return 0; +}; + +int dma_channel_receive_normal( uint8_t channel, void *data, uint32_t data_size, uint32_t flags, uint32_t spr){ + if( data == NULL ) return -1; + // If we are not initialized... + if( !dma_channel_initialized[channel] ) { + // Initialize the channel. + if( dma_channel_initialize( channel, NULL, flags ) < 0 ) return -1; + }; + // Set the size of the data, in quadwords. + *dma_qwc[channel] = DMA_SET_QWC( (data_size + 15) >> 4 ); + // Set the address of the data. + *dma_madr[channel] = DMA_SET_MADR( data, spr ); + // Start the transfer. + *dma_chcr[channel] = DMA_SET_CHCR( 0, 0, 0, 0, 0, 1, 0 ); + // End function. + return 0; +}; + +int dma_channel_shutdown( uint8_t channel, uint32_t flags ){ + // If we are not initialized, no need to shut down. + if( !dma_channel_initialized[channel] ) return 0; + // If a handler was provided... + if( dma_handler_id[channel] != 0 ){ + // Disable the channel. + if( flags & DMA_FLAG_INTERRUPTSAFE ){ + iDisableDmac( channel ); + } else { + DisableDmac( channel ); + }; + // Remove the handler. + RemoveDmacHandler( channel, dma_handler_id[channel] ); + // Clear the handler id. + dma_handler_id[channel] = 0; + }; + // Tell everyone we are not initialized. + dma_channel_initialized[channel] = 0; + // End function. + return 0; +}; + diff --git a/sps2_basement/hardware/ee/dmac/dma.h b/sps2_basement/hardware/ee/dmac/dma.h new file mode 100644 index 0000000..6fd3927 --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/dma.h @@ -0,0 +1,78 @@ +#ifndef __SPS2_DMA_OPERATION_HEADERS__ +#define __SPS2_DMA_OPERATION_HEADERS__ + +#include "dma_packets.h" + +#ifndef NULL + #define NULL ((void *)0) +#endif + +#define DMA_CHANNEL_VIF0 0x00 +#define DMA_CHANNEL_VIF1 0x01 +#define DMA_CHANNEL_GIF 0x02 +#define DMA_CHANNEL_fromIPU 0x03 +#define DMA_CHANNEL_toIPU 0x04 +#define DMA_CHANNEL_fromSIF0 0x05 +#define DMA_CHANNEL_toSIF1 0x06 +#define DMA_CHANNEL_SIF2 0x07 +#define DMA_CHANNEL_fromSPR 0x08 +#define DMA_CHANNEL_toSPR 0x09 + +#define DMA_FLAG_TRANSFERTAG 0x01 +#define DMA_FLAG_INTERRUPTSAFE 0x02 + + +#ifdef __cplusplus +extern "C" { +#endif + +int dma_reset(void); + +/** Initializes the specified dma channel. */ +int dma_channel_initialize( uint8_t channel, void *handler, uint32_t flags ); + +/** Enables dma fast waits for that channel */ +static inline void dma_channel_fast_waits( uint8_t channel ){ /*DMA_REG_PCR*/ *((volatile uint32_t *)0x1000E020) |= ( 1 << channel ); }; + +/** Waits until channel is usable based on coprocessor status */ +void dma_wait_fast(void); + +/** Wait until the specified dma channel is ready. */ +int dma_channel_wait( uint8_t channel, uint32_t timeout ); + +/** + * Send packet2. + * Type chain/normal is choosen from packet2_t. + * @param packet2 Pointer to packet. + * @param channel DMA channel. + * @param flush_cache Should be cache flushed before send? + */ +void dma_channel_send_packet2( packet2_t *packet2, uint8_t channel, uint8_t flush_cache ); + +/** Send a dmachain to the specified dma channel. */ +int dma_channel_send_chain( uint8_t channel, void *data, uint32_t qwc, uint32_t flags, uint32_t spr ); + +/** Send a ucab dmachain to the specified dma channel. */ +int dma_channel_send_chain_ucab( uint8_t channel, void *data, uint32_t qwc, uint32_t flags ); + +/** Send data to the specified dma channel. */ +int dma_channel_send_normal( uint8_t channel, void *data, uint32_t qwc, uint32_t flags, uint32_t spr ); + +/** Send ucab data to the specified dma channel. */ +int dma_channel_send_normal_ucab( uint8_t channel, void *data, uint32_t qwc, uint32_t flags ); + +/** Receive data from the specified dma channel. */ +int dma_channel_receive_normal( uint8_t channel, void *data, uint32_t data_size, uint32_t flags, uint32_t spr ); + +/** Receive data from the specified dma channel. */ +int dma_channel_receive_chain( uint8_t channel, void *data, uint32_t data_size, uint32_t flags, uint32_t spr ); + +/** Shut down the specified dma channel. */ +int dma_channel_shutdown( uint8_t channel, uint32_t flags ); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/sps2_basement/hardware/ee/dmac/dma_packets.c b/sps2_basement/hardware/ee/dmac/dma_packets.c new file mode 100644 index 0000000..ffa2a2b --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/dma_packets.c @@ -0,0 +1,209 @@ +#include "dma_packets.h" + +#define SPR_BEGIN 0x70000000 +#define P_ALIGNMENT 64 +#define P2_ALIGNMENT 64 +#define P2_MAKE_PTR_NORMAL(PTR) ((uint32_t)(PTR)&0x0FFFFFFF) + +packet_t *packet_init( uint32_t qwords, uint16_t type){ + uint32_t byte_size = 0; + packet_t *packet = (packet_t*)malloc(sizeof(packet_t)); + if( packet == NULL ) return NULL; + if( type == PACKET_SPR ){ + packet->data = (qword_t *) SPR_BEGIN; + packet->qwc = 0x1000; + } else { + // Size of qwords in bytes. + byte_size = qwords << 4; + // Allocate the data area in bytes aligned to cache line. + if(( packet->data = (qword_t *) memalign( P_ALIGNMENT, byte_size)) == NULL ){ + free( packet ); + return NULL; + }; + }; + // Set the pointer attribute to ucab space. + if( type == PACKET_UCAB ){ + packet->data = (qword_t *)((uint32_t)packet->data | 0x30000000); + }; + // Clear the packet area. + memset( packet->data, 0, byte_size ); + // Set the packet counts + packet->qwc = 0; + packet->qwords = qwords; + packet->type = type; + // End function. + return packet; +}; + +void packet_free( packet_t *packet ){ + if( packet == NULL ) return; + // Free the allocated data buffer. + if( packet->type == PACKET_SPR ){ + packet->data = NULL; + } else { + if( packet->type == PACKET_UCAB ){ + packet->data = (qword_t *)((uint32_t)packet->data ^ 0x30000000); + }; + free(packet->data); + }; + free(packet); +}; + +void packet_reset( packet_t *packet ){ + if( packet == NULL ) return; + // Reset the quadword counter. + packet->qwc = 0; + if( packet->type == PACKET_SPR ){ + packet->data = (qword_t *)SPR_BEGIN; + return; + }; + // Zero out the data + memset(packet->data, 0, packet->qwords << 4); +}; + +// --- +// Packet2 management +// --- + +packet2_t* packet2_create(uint16_t qwords, packet2_type_t type, packet2_mode_t mode, uint8_t tte ){ + packet2_t *packet2 = (packet2_t *)malloc(sizeof(packet2_t)); + if( packet2 == NULL ) return NULL; + memset( packet2, 0 , sizeof( packet2_t )); + packet2->max_qwords_count = qwords; + packet2->type = type; + packet2->mode = mode; + packet2->tte = tte; + packet2->tag_opened_at = NULL; + packet2->vif_code_opened_at = NULL; + // Dma buffer size should be a whole number of cache lines (64 bytes = 4 quads) + assert(!((packet2->type == P2_TYPE_UNCACHED || packet2->type == P2_TYPE_UNCACHED_ACCL) && packet2->max_qwords_count & (4 - 1))); + uint32_t byte_size = packet2->max_qwords_count << 4; + if((packet2->base = (qword_t *) memalign(P2_ALIGNMENT, byte_size)) == NULL){ + free(packet2); + return NULL; + }; + packet2->base = packet2->next = (qword_t *)((uint32_t)packet2->base | packet2->type); + memset(packet2->base, 0, byte_size); + // "I hate to do this, but I've wasted FAR too much time hunting down cache incoherency" + if (packet2->type == P2_TYPE_UNCACHED || packet2->type == P2_TYPE_UNCACHED_ACCL) FlushCache(0); + return packet2; +}; + +packet2_t* packet2_create_from( qword_t *base, qword_t *next, uint16_t qwords, packet2_type_t type, packet2_mode_t mode, uint8_t tte ){ + // Dma buffer size should be a whole number of cache lines (64 bytes = 4 quads) + assert(!((type == P2_TYPE_UNCACHED || type == P2_TYPE_UNCACHED_ACCL) && qwords & (4 - 1))); + // Dma buffer should be aligned on a cache line (64-byte boundary) + assert(!((type == P2_TYPE_UNCACHED || type == P2_TYPE_UNCACHED_ACCL) && (uint32_t)base & (64 - 1))); + packet2_t *packet2 = (packet2_t *) malloc(sizeof(packet2_t)); + if (packet2 == NULL) return NULL; + memset( packet2, 0 , sizeof( packet2_t )); + packet2->base = base; + packet2->next = next; + packet2->max_qwords_count = qwords; + packet2->type = type; + packet2->tte = tte; + packet2->mode = mode; + return packet2; +}; + +void packet2_free( packet2_t *packet2 ){ + if( packet2 == NULL ) return; + if( packet2->base != NULL ) free((qword_t *)P2_MAKE_PTR_NORMAL(packet2->base)); + free( packet2 ); +}; + +void packet2_reset( packet2_t *packet2, uint8_t clear_mem ){ + if( packet2 == NULL ) return; + packet2->next = packet2->base; + packet2->vif_code_opened_at = NULL; + packet2->tag_opened_at = NULL; + if( clear_mem ) memset( packet2->base, 0, packet2->max_qwords_count << 4 ); +}; + +// --- +// Utils +// --- + +void packet2_add( packet2_t *a, packet2_t *b ){ + if( a== NULL || b == NULL ) return; + assert(packet2_get_qw_count(a) + packet2_get_qw_count(b) <= a->max_qwords_count); + memcpy(a->next, b->base, (uint32_t)b->next - (uint32_t)b->base); + a->next = a->base + packet2_get_qw_count(b) + 1; +}; + +void packet2_print( packet2_t *packet2, uint32_t qw_count){ + if( packet2 == NULL ) return; + if( qw_count == 0 ) qw_count = ((uint32_t)packet2->next - (uint32_t)packet2->base) >> 4; + printf("\n============================\n"); + printf("Packet2: Dumping %d words...\n", ((uint32_t)packet2->next - (uint32_t)packet2->base) >> 2); + uint32_t i = 0; + uint32_t * nextWord; + for( nextWord = (uint32_t *)packet2->base; nextWord != (uint32_t *)packet2->next; nextWord++, i++ ){ + if ((i % 4) == 0) printf("\n0x%08x: ", (uint32_t)nextWord ); + printf( "0x%08x ", *nextWord ); + if (i / 4 == qw_count) break; + } + printf("\n============================\n"); +}; + +void packet2_print_qw_count( packet2_t *packet2 ){ + if ( packet2 == NULL ) return; + printf("Packet2: Qwords count:%d \n", packet2_get_qw_count(packet2)); +}; + +void packet2_vif_add_micro_program( packet2_t *packet2, uint32_t dest, puint32_t start, puint32_t end ){ + // get the size of the code as we can only send 256 instructions in each MPGtag + uint32_t count = (end - start) >> 1; + if( count & 1 ) count++; + puint32_t l_start = start; + while( count > 0 ){ + uint16_t curr_count = ( count > 256 )? 256 : count; + packet2_chain_ref( packet2, l_start, ( curr_count >> 1 ), 0, 0, 0); + packet2_vif_nop( packet2, 0 ); + packet2_vif_mpg( packet2, curr_count & 0xFF, dest, 0 ); + l_start += ( curr_count << 1 ); + count -= curr_count; + dest += curr_count; + }; +}; + +uint32_t packet2_vif_close_unpack_auto( packet2_t *packet2, uint32_t wl, uint32_t cl ){ + if( packet2 == NULL ) return 0; + assert(packet2->vif_code_opened_at != NULL); // There is open UNPACK/DIRECT. + assert(((uint32_t)packet2->next & 0x3) == 0); // Make sure we're u32 aligned + assert((packet2->vif_code_opened_at->cmd & 0x60) == 0x60); // It was UNPACK + + uint32_t vn = (packet2->vif_code_opened_at->cmd & 0xC) >> 2; + uint32_t vl = packet2->vif_code_opened_at->cmd & 0x3; + + // "the goal here is to find the num field of the open unpack, which is the number of + // qwords ACTUALLY WRITTEN to vu memory (it does not count quads that are skipped in + // "skipping write" mode.) But first forget about skipping/filling writes and compute the number + // of qwords that the data in this packet will expand to." + uint32_t bytes_count = (uint32_t)packet2->next - (uint32_t)packet2->vif_code_opened_at - 4; + uint32_t block_bytes_count = 4 >> vl; + uint32_t quad_blocks_count = vn + 1; + + // "make sure that the data length is a multiple of 8, 16, or 32 bits, whichever is appropriate" + assert((bytes_count & (block_bytes_count - 1)) == 0); + uint32_t quads_count = (bytes_count / block_bytes_count) / quad_blocks_count; + + // "We have the number of quads our data will directly expand to, so now we need to account for + // skipping/filling write modes."" + + // "skipping write is easy -- we are already done" + + // "filling write: now we get ambiguous -- what to do when quads_count == CL in the last + // block? I will say that in this case the vif should still do the full wl length block, filling + // with internal registers. If you want different behavior call packet2_vif_close_unpack_manual + // with a num field you've computed yourself" + if( cl < wl ){ + uint32_t wl_blocks_count = (quads_count / cl); + uint32_t last_block_quads = quads_count - wl_blocks_count * cl; + if (last_block_quads == cl) last_block_quads = wl; + quads_count = wl_blocks_count * wl + last_block_quads; + }; + packet2_vif_close_unpack_manual( packet2, quads_count ); + return quads_count; +}; + diff --git a/sps2_basement/hardware/ee/dmac/dma_packets.h b/sps2_basement/hardware/ee/dmac/dma_packets.h new file mode 100644 index 0000000..ebb77c5 --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/dma_packets.h @@ -0,0 +1,1119 @@ +#ifndef __SPS2_DMA_PACKETS_HEADER__ +#define __SPS2_DMA_PACKETS_HEADER__ + +#include "../../../core/base/basicTypes.h" + +/** Maximum number allowed, but each channel has its own limitations. */ +#define QWC_MAX 65535 + +#define PACKET_NORMAL 0x00 +#define PACKET_UCAB 0x01 +#define PACKET_SPR 0x02 + +#define PACKET2_COUNT_QWC (1 << 16) + +/** + * Dmatags use qwc for the number of qwords for they handle. + * + * The dma channel QWC register uses it as the total number of qwords that + * are being sent at a time. + */ +typedef struct s_packet_t { + uint32_t qwords; + uint16_t qwc; + uint16_t type; + qword_t * data __attribute__((aligned(64))); +} packet_t; + +#ifdef __cplusplus + extern "C" { +#endif + + /** Allocate a new packet for use, size in quadwords. */ + packet_t *packet_init( uint32_t qwords, uint16_t type ); + + /** Reset the packet quadword counter and zero out data. */ + void packet_reset( packet_t *packet ); + + /** Free the space allocated by packet. */ + void packet_free( packet_t *packet ); + + /** Advances the qwc and returns the current qword count. */ + qword_t *packet_increment_qwc(packet_t *packet, uint32_t num ); + + /** For those that like getters and setters */ + static inline qword_t *packet_get_qword( packet_t *packet ){ + return (packet)?NULL:packet->data; + }; + +#ifdef __cplusplus + } +#endif + +typedef enum e_packet2_mode{ + P2_MODE_NORMAL = 0, + P2_MODE_CHAIN = 1, +}packet2_mode_t; + +/** Types of memory mapping. */ +typedef enum e_packet2_type{ + /** Normal. */ + P2_TYPE_NORMAL = 0x00000000, + /** Uncached. */ + P2_TYPE_UNCACHED = 0x20000000, + /** Uncached accelerated. */ + P2_TYPE_UNCACHED_ACCL = 0x30000000, + /** Scratchpad memory. */ + P2_TYPE_SPRAM = 0x70000000 +}packet2_type_t; + +/** DMA tag types */ +typedef enum e_dma_tag_type{ + /** Transfers the QWC qword from the ADDR field, clears the Dn_CHCR.STR to 0, and ends transfer. */ + P2_DMA_TAG_REFE = 0, + /** Transfers the QWC qword following the tag and reads the succeeding qword as the next tag. */ + P2_DMA_TAG_CNT = 1, + /** Transfers the QWC qword following the tag and reads the qword of the ADDR field as the next tag. */ + P2_DMA_TAG_NEXT = 2, + /** Transfers the QWC qword from the ADDR field and reads the qword following the tag as the next tag. */ + P2_DMA_TAG_REF = 3, + /** + * Transfers the QWC qword from the ADDR field while controlling stalls + * and reads the qword following the tag as the next tag. + * @note Effective only on the VIF1, GIF, and SIF1 channels. + */ + P2_DMA_TAG_REFS = 4, + /** + * Transfers the QWC qword following the tag, pushes the next field into + * the Dn_ASR register, and reads the qword of the ADDR field as the next tag. + * @note Effective only on the VIF0, VIF1, and GIF channels. + * Addresses can be pushed up to 2 levels + */ + P2_DMA_TAG_CALL = 5, + /** + * Transfers the QWC qword following the tag and reads the + * qword of the field popped from the Dn_ASR register as the + * next tag. + * Transfers the QWC qword following the tag, clears the + * Dn_CHCR.STR to 0, and ends transfer when there is no + * pushed address. + * @note Effective only on the VIF0, VIF1, and GIF channels. + */ + P2_DMA_TAG_RET = 6, + /** Transfers the QWC qword following the tag, clears the Dn_CHCR.STR to 0, and ends transfer. */ + P2_DMA_TAG_END = 7 +} dma_tag_type_t; + +/** Destination chain tag. */ +typedef struct s_dma_tag{ + /** Quadword count. */ + uint64_t QWC : 16; + uint64_t PAD : 10; + /** + * Priority Control Enable. + * 00 Nothing performed + * 01 Reserved + * 10 Priority setting disabled (D_PCR.PCE = 0) + * 11 Priority setting enabled (D_PCR.PCE = 1) + */ + uint64_t PCE : 2; + /** Tag ID. (look at DmaTagType) */ + uint64_t ID : 3; + /** + * Interrupt Request. + * 0 No interrupt request + * 1 Interrupt request at end of packet transfer + */ + uint64_t IRQ : 1; + /** + * Address. + * Address of packet or next tag instruction + * (With qword alignment, lower 4 bits become 0.) + */ + uint64_t ADDR : 31; + /** + * Memory/SPR Selection. + * 0 Memory address + * 1 SPR address + */ + uint64_t SPR : 1; + + + uint32_t OPT1; + uint32_t OPT2; +}dma_tag_t __attribute__((aligned(16))); + +/** + * Unpack modes. + * V2 = 2 dimensions, S = Single = 1 dimension + * _32 = 32 bits of data length. + */ +typedef enum e_unpack_mode{ + P2_UNPACK_S_32 = 0x00, + P2_UNPACK_S_16 = 0x01, + P2_UNPACK_S_8 = 0x02, + P2_UNPACK_V2_32 = 0x04, + P2_UNPACK_V2_16 = 0x05, + P2_UNPACK_V2_8 = 0x06, + P2_UNPACK_V3_32 = 0x08, + P2_UNPACK_V3_16 = 0x09, + P2_UNPACK_V3_8 = 0x0A, + P2_UNPACK_V4_32 = 0x0C, + P2_UNPACK_V4_16 = 0x0D, + P2_UNPACK_V4_8 = 0x0E, + P2_UNPACK_V4_5 = 0x0F, +}unpack_mode_t; + +/** VIF opcodes. */ +typedef enum e_vif_opcode{ + /** + * No operation. + * No operation is performed. + * NOP is used to adjust the data alignment in the VIF packet. + */ + P2_VIF_NOP = 0, + /** + * Sets write recycle. + * STCYCL writes the value of the IMMEDIATE field to the VIFn_CYCLE register. + */ + P2_VIF_STCYCL = 1, + /** + * Sets the double buffer offset. + * OFFSET writes the lower 10 bits of the IMMEDIATE field to the VIF1_OFST register. + * At the same time, the DBF flag of the VIF1_STAT register is cleared to 0, and the VIF1_BASE register + * value is set to the VIF1_TOPS. That is, the pointer for the double buffer points to the BASE. + */ + P2_VIF_OFFSET = 2, + /** + * Sets the base address of the double buffer. + * BASE writes the lower 10 bits of the IMMEDIATE field to the VIF1_BASE register. + * These bits become the base address of the double buffers. + */ + P2_VIF_BASE = 3, + /** + * Sets the data pointer. + * ITOP writes the lower 10 bits of the IMMEDIATE field to the VIFn_ITOPS register. + * This value is read from the VU by the XITOP instruction. + */ + P2_VIF_ITOP = 4, + /** + * Sets the addition decompression mode. + * STMOD writes the lower 2 bits of the IMMEDIATE field to the VIFn_MODE register. + * This becomes the addition decompression mode setting. + */ + P2_VIF_STMOD = 5, + /** + * Sets the PATH3 mask. + * MSKPATH3 enables/disables transfer processing via the GIF PATH3. + * The setting of this register applies to the next data block or later. + */ + P2_VIF_MSKPATH3 = 6, + /** + * Sets the MARK value. + * MARK writes the value of the IMMEDIATE field to the VIFn_MARK register. + * By properly setting the MARK value, it becomes possible to use this value for + * synchronization with the EE Core and debugging. + */ + P2_VIF_MARK = 7, + /** + * Waits for end of the microprogram. + * FLUSHE waits for the state in which the microprogram in VU0/VU1 has been ended. + */ + P2_VIF_FLUSHE = 16, + /** + * Waits for end of the microprogram. + * FLUSH waits for the state in which transfers to the GIF from PATH1 and PATH2 have been ended after + * end of microprogram in VU1. FLUSH does not wait for the end of the transfer via PATH1 by + * the XGKICK instruction with the E bit. + */ + P2_VIF_FLUSH = 17, + /** + * Waits for end of the microprogram. + * FLUSHA waits for the state in which there is no transfer request from PATH3 after the end of micro + * program in VU1 and end of transfer to the GIF from PATH1 and PATH2. + */ + P2_VIF_FLUSHA = 18, + /** + * Activates the microprogram. + * MSCAL waits for the end of the microprogram under execution and activates the micro program with the + * value of the IMMEDIATE field as the starting address. + */ + P2_VIF_MSCAL = 20, + /** + * Activates the microprogram. + * MSCNT waits for the end of the microprogram under execution and executes the next microprogram from + * the address following the most recently ended one in the PC (program counter). + */ + P2_VIF_MSCNT = 23, + /** + * Activates the microprogram. + * MSCALF waits for the end of both the microprogram and the GIF(PATH1/PATH2) transfer and executes + * the microprogram with the value of the IMMEDIATE field as the starting address. + */ + P2_VIF_MSCALF = 21, + /** + * Sets the data mask pattern. + * STMASK stores the next 1 word of data in the VIFn_MASK register. + * This data becomes the mask pattern of the write data. + */ + P2_VIF_STMASK = 32, + /** + * Sets the filling data. + * STROW stores the following 4 words of data in the VIFn_R0 - VIFn_R3 registers. + * These are used as filling data when decompressed by the VIFcode UNPACK. + */ + P2_VIF_STROW = 48, + /** + * Sets the filling data. + * STCOL stores the following 4 words of data in the VIFn_C0 - VIFn_C3 registers. + * These are used as filling data when decompressed by the VIFcode UNPACK. + */ + P2_VIF_STCOL = 49, + /** + * Transfers the microprogram. + * MPG waits for the end of the microprogram and transfers the following NUM pieces of 64-bit data. + * (microinstruction code) to the MicroMem address shown by the IMMEDIATE field. + */ + P2_VIF_MPG = 74, + /** + * Transfers data to the GIF(GS). + * DIRECT transfers the following IMMEDIATE pieces of 128-bit data to the GS via GIF PATH2. It is + * necessary to put the appropriate GIFtag to the data. + */ + P2_VIF_DIRECT = 80, + /** + * Transfers data to the GIF(GS). + * DIRECTHL transfers the following IMMEDIATE pieces of 128-bit data to the GS via GIF PATH2. + * The appropriate GIFtag must be attached to the data. + * Interruption of PATH3 IMAGE mode data does not occur during the data transfer via PATH2 by + * DIRECTHL. Moreover, when the IMAGE mode data is being transferred via PATH3, DIRECTHL stalls + * until the end of the transfer. + */ + P2_VIF_DIRECTHL = 81 +}vif_opcode_t; + +/** VIFCode structure. */ +typedef struct s_vif_code{ + /** The contents of the IMMEDIATE field vary according to the CMD field. */ + uint32_t immediate : 16; + /** + * The NUM field shows the amount of data written to the VU Mem or MicroMem (Data is in 128-bit units + * and microinstruction code is in 64-bit units). When NUM=0, it is considered to be 256. + * Note that it is not the amount of data in the VIF packet. NUM pieces of data can be written even when the + * amount of data in the packet is 0 depending on the CYCLE register setting. + */ + uint32_t num : 8; + /** + * The CMD field directs the operation of the VIF, that is, the decompression + * method of the following data. + */ + uint32_t cmd : 8; +}vif_code_t; + +/** + * DMA data packet. + * Successor of standard packet. + */ +typedef struct s_packet2{ + /** Maximum number of qwords which was defined in packet2_create(). */ + uint16_t max_qwords_count; + /** Type of packet's memory mapping. */ + packet2_type_t type; + /** Packet mode. */ + packet2_mode_t mode; + /** + * Tag transfer enable. + * Effective only in chain mode. + * If >0 transfer tag is set during packet sending and + * add_dma_tag() (so also every open_tag()) will move buffer by DWORD, + * so remember to align memory! + */ + uint8_t tte; + /** Start position of the buffer. */ + qword_t * base __attribute__((aligned(64))); + /** Current position of the buffer. */ + qword_t * next; + /** + * The buffer position where DMA tag was opened. + * NULL, if no dma tag is open. + */ + dma_tag_t * tag_opened_at; + /** + * The buffer position where DIRECT/UNPACK was opened. + * NULL, if no DIRECT/UNPACK is open. + */ + vif_code_t * vif_code_opened_at; +}packet2_t; + +/** Mask, used in VIF's STMASK opcode. */ +typedef union u_vif_mask{ + struct{ + uint32_t m0 : 2; + uint32_t m1 : 2; + uint32_t m2 : 2; + uint32_t m3 : 2; + uint32_t m4 : 2; + uint32_t m5 : 2; + uint32_t m6 : 2; + uint32_t m7 : 2; + uint32_t m8 : 2; + uint32_t m9 : 2; + uint32_t m10 : 2; + uint32_t m11 : 2; + uint32_t m12 : 2; + uint32_t m13 : 2; + uint32_t m14 : 2; + uint32_t m15 : 2; + }; + uint32_t m; +} vif_mask_t; + + +#ifdef __cplusplus + extern "C" + { +#endif + + // --- + // Packet2 management + // --- + + /** + * Allocate new packet2. + * @param qwords Maximum data size in qwords (128bit). + * @param type Memory mapping type. + * @param mode Packet mode. Normal or chain. + * @param tte Tag transfer enable. + * Used only for CHAIN mode! + * If >0 transfer tag is set during packet sending and + * add_dma_tag() (so also every open_tag()) will move buffer by DWORD, + * so remember to align memory! + * @returns Pointer to packet2 on success or NULL if memory allocation fail. + */ + packet2_t* packet2_create(uint16_t qwords, packet2_type_t type, packet2_mode_t mode, uint8_t tte); + + /** + * Create new packet2 with given data pointer. + * @param base Pointer to base (start of buffer). + * @param next Pointer to next (current position of buffer). + * @param qwords Maximum data size in qwords (128bit). + * @param type Memory mapping type. + * @param mode Packet mode. Normal or chain (so also vif/vu). + * @param tte Tag transfer enable. + * Used only for CHAIN mode! + * If >0 transfer tag is set during packet sending and + * add_dma_tag() (so also every open_tag()) will move buffer by DWORD, + * so remember to align memory! + * @returns Pointer to packet2 on success or NULL if memory allocation fail. + */ + packet2_t *packet2_create_from(qword_t *base, qword_t *next, uint16_t qwords, packet2_type_t type, packet2_mode_t mode, uint8_t tte); + + /** + * Free packet2 memory. + * @param packet2 Pointer to packet2. + */ + void packet2_free(packet2_t *packet2); + + /** + * Reset packet. + * Move next pointer back to base pointer, + * Make all "openedAt" vars to NULL + * Do memset on data if required. + * @param packet2 Pointer to packet. + * @param clear_mem If >0, data is cleared via memset(). SLOW! + */ + void packet2_reset(packet2_t *packet2, uint8_t clear_mem); + + /** + * Update current position of packet buffer. + * Useful with drawlib functions. + */ + static inline void packet2_update(packet2_t *packet2, qword_t *qw) { packet2->next = qw; }; + + // --- + // Basic add + // --- + + /** Move "next" pointer forward. */ + static inline void packet2_advance_next(packet2_t *packet2, uint32_t i ){ + packet2->next = (qword_t *)((puint8_t)packet2->next + i); + }; + + static inline void packet2_add_u128(packet2_t *packet2, const uint128_t val){ + *((puint128_t) packet2->next ) = val; + packet2_advance_next(packet2, sizeof(uint128_t)); + }; + + /** @note Alignment alert. Size of dword (1/2) */ + static inline void packet2_add_s64(packet2_t *packet2, const int64_t val){ + *((pint64_t) packet2->next ) = val; + packet2_advance_next(packet2, sizeof(int64_t)); + }; + + static inline void packet2_add_2x_s64(packet2_t *packet2, const int64_t v1, const int64_t v2){ + packet2_add_s64(packet2, v1); + packet2_add_s64(packet2, v2); + }; + + static inline void packet2_add_s128(packet2_t *packet2, const int128_t val){ + *((pint128_t)packet2->next) = val; + packet2_advance_next(packet2, sizeof(int128_t)); + }; + + /** @note Alignment alert. Size of dword (1/2) */ + static inline void packet2_add_u64(packet2_t *packet2, const uint64_t val){ + *((puint64_t)packet2->next) = val; + packet2_advance_next(packet2, sizeof(uint64_t)); + }; + + /** @note Alignment alert. Size of word (1/4) */ + static inline void packet2_add_u32(packet2_t *packet2, const uint32_t val){ + *((puint32_t)packet2->next) = val; + packet2_advance_next(packet2, sizeof(uint32_t)); + }; + + /** @note Alignment alert. Size of word (1/4) */ + static inline void packet2_add_s32(packet2_t *packet2, const int32_t val){ + *((pint32_t)packet2->next) = val; + packet2_advance_next(packet2, sizeof(int32_t)); + }; + + /** @note Alignment alert. Size of word (1/4) */ + static inline void packet2_add_float(packet2_t *packet2, const float val){ + *((float *)packet2->next) = val; + packet2_advance_next(packet2, sizeof(float)); + }; + + static inline void packet2_add_data(packet2_t *packet2, puint128_t t_data, uint32_t t_size ){ + uint32_t i = 0; + for( ; i < t_size; i++) packet2_add_u128( packet2, t_data[i] ); + }; + /* + ToDo: make according functions to consume various data types + + static inline void packet2_add_data(packet2_t *packet2, void *t_data, uint32_t t_size){ + uint32_t i; + for (i = 0; i < t_size; i++) packet2_add_u128( packet2,((puint128_t)t_data)[i]); + }; + static inline void packet2_add_data(packet2_t *packet2, void *t_data, uint32_t t_size){ + uint32_t i; + for (i = 0; i < t_size; i++) packet2_add_u128( packet2,((puint128_t)t_data)[i]); + }; + static inline void packet2_add_data(packet2_t *packet2, void *t_data, uint32_t t_size){ + uint32_t i; + for (i = 0; i < t_size; i++) packet2_add_u128( packet2,((puint128_t)t_data)[i]); + }; + static inline void packet2_add_data(packet2_t *packet2, void *t_data, uint32_t t_size){ + uint32_t i; + for (i = 0; i < t_size; i++) packet2_add_u128( packet2,((puint128_t)t_data)[i]); + }; + static inline void packet2_add_data(packet2_t *packet2, void *t_data, uint32_t t_size){ + uint32_t i; + for (i = 0; i < t_size; i++) packet2_add_u128( packet2,((puint128_t)t_data)[i]); + }; + */ + + /** + * Fill to align to 96bits + */ + static inline void packet2_pad96( packet2_t *packet2, const uint32_t val ){ + while ((((uint32_t)packet2->next + 4) & 0xf) != 0) packet2_add_u32( packet2, val ); + }; + + /** + * Fill to align to 128bits + */ + static inline void packet2_pad128(packet2_t *packet2, const uint32_t val){ + while (((uint32_t)packet2->next & 0xf) != 0) packet2_add_u32( packet2, val ); + }; + + // --- + // Other + // --- + + /** + * Print data of packet. + * @param packet2 Pointer to packet. + * @param clear_mem Count of qwords, type 0 for all. + */ + void packet2_print(packet2_t *packet2, uint32_t qw_count); + + /** + * Print amount of qwords of packet. + * @param packet2 Pointer to packet. + */ + void packet2_print_qw_count( packet2_t *packet2 ); + + /** Copy data from b packet into a packet with memcpy() */ + void packet2_add(packet2_t *a, packet2_t *b); + + /** Returns count of added qwords into packet. */ + static inline uint32_t packet2_get_qw_count(packet2_t *packet2) { return ((uint32_t)packet2->next - (uint32_t)packet2->base) >> 4; } + + /** True if packet doesnt have even number of quads. */ + static inline uint8_t packet2_doesnt_have_even_number_of_quads(packet2_t *packet2) { return ((uint32_t)packet2->next & 0xF) != 0; } + + /** True if dma tag is opened. */ + static inline uint8_t packet2_is_dma_tag_opened(packet2_t *packet2) { return packet2->tag_opened_at != NULL; } + + /** True if DIRECT/UNPACK is opened. */ + static inline uint8_t packet2_is_vif_code_opened(packet2_t *packet2) { return packet2->vif_code_opened_at != NULL; } + +#ifdef __cplusplus + } +#endif + + +#ifdef __cplusplus + extern "C" + { +#endif + + // --- + // DMA tag management + // --- + + /** + * Set dma tag. + * For more details, check description of dma_tag_t. + * @param tag Pointer to DMA tag to set. + * @param qwc Qword count. + * @param pce Priority Control Enable. 0 by default. + * @param id Tag ID. + * @param irq Interrupt Request. False by default. + * @param addr Address. + * @param spr Memory/SPR Selection. False by default. + */ + static inline void packet2_chain_set_dma_tag( dma_tag_t *tag, uint32_t qwc, uint32_t pce, dma_tag_type_t id, uint8_t irq, const uint128_t *addr, uint8_t spr){ + tag->QWC = qwc; + tag->PCE = pce; + tag->ID = id; + tag->IRQ = irq; + tag->ADDR = (uint64_t)((uint32_t)addr); + tag->SPR = spr; + }; + + /** + * Add dma tag. + * For more details, check description of dma_tag_t. + * Will move current buffer position by: + * DWORD if packet->tte == true, + * QWORD if packet->tte == false + * @param packet2 Pointer to packet. + * @param qwc Qword count. If you want to use + * packet2_chain_close_tag(), and count qwords + * automatically, set value to PACKET2_COUNT_QWC. + * @param pce Priority Control Enable. 0 by default. + * @param id Tag ID. + * @param irq Interrupt Request. False by default. + * @param addr Address. + * @param spr Memory/SPR Selection. False by default. + */ + static inline void packet2_chain_add_dma_tag( packet2_t *packet2, uint32_t qwc, uint32_t pce, dma_tag_type_t id, uint8_t irq, const uint128_t *addr, uint8_t spr){ + assert(((uint32_t)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + assert(packet2->tag_opened_at == NULL); // All previous tags are closed. + + if( qwc == PACKET2_COUNT_QWC ){ + packet2_chain_set_dma_tag((dma_tag_t *)packet2->next, 0, pce, id, irq, addr, spr); // placeholder + packet2->tag_opened_at = (dma_tag_t *)packet2->next; + } else{ + packet2_chain_set_dma_tag((dma_tag_t *)packet2->next, qwc, pce, id, irq, addr, spr); + packet2->tag_opened_at = (dma_tag_t *)NULL; + }; + if( !packet2->tte ){ + packet2_advance_next(packet2, sizeof(dma_tag_t)); + } else{ + packet2_advance_next(packet2, sizeof(uint64_t)); + }; + }; + + /** + * Close dma tag. + * In reality, get back to pointer "tag_opened_at" and fix qwc value. + * @param packet2 Pointer to packet. + */ + static inline void packet2_chain_close_tag(packet2_t *packet2){ + assert(packet2->tag_opened_at != NULL); // There is opened tag. + assert(((uint32_t)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2->tag_opened_at->QWC = (((uint32_t)packet2->next - (uint32_t)packet2->tag_opened_at) / 16 - 1); + packet2->tag_opened_at = (dma_tag_t *)NULL; + } + + // --- + // DMA tags + // --- + + /** + * Add CNT tag. + * @note packet2_chain_close_tag() required. Qwords + * are counted automatically. + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + * @param pce Priority Control Enable. 0 by default. + * @param spr Memory/SPR Selection. False by default. + */ + static inline void packet2_chain_open_cnt( packet2_t *packet2, uint8_t irq, uint32_t pce, uint8_t spr ){ + packet2_chain_add_dma_tag(packet2, PACKET2_COUNT_QWC, pce, P2_DMA_TAG_CNT, irq, 0, spr); + }; + + /** + * Add END tag. + * @note packet2_chain_close_tag() required. Qwords + * are counted automatically. + * For more details, check description of dma_tag_t. + * @note Don't forget about close_tag()! + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_open_end( packet2_t *packet2, uint8_t irq, uint32_t pce ){ + packet2_chain_add_dma_tag(packet2, PACKET2_COUNT_QWC, pce, P2_DMA_TAG_END, irq, 0, 0); + }; + + /** + * Add REF tag. + * @note Qwords are NOT counted automatically, so + * there is NO need to use packet2_chain_close_tag(); + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param ref_data Pointer to data. + * @param qw_length Size of data in qwords. + * @param irq Interrupt Request. False by default. + * @param spr Memory/SPR Selection. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_ref(packet2_t *packet2, const void *ref_data, uint32_t qw_length, uint8_t irq, uint8_t spr, uint32_t pce ){ + assert(((uint32_t)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2_chain_add_dma_tag(packet2, qw_length, pce, P2_DMA_TAG_REF, irq, (const uint128_t *)ref_data, spr); + }; + + /** + * Add NEXT tag. + * @note packet2_chain_close_tag() required. Qwords + * are counted automatically. + * For more details, check description of dma_tag_t. + * @param next_tag Pointer to next tag. + * @param irq Interrupt Request. False by default. + * @param spr Memory/SPR Selection. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_next(packet2_t *packet2, const dma_tag_t *next_tag, uint8_t irq, uint8_t spr, uint32_t pce){ + assert(((uint32_t)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2_chain_add_dma_tag( packet2, PACKET2_COUNT_QWC, pce, P2_DMA_TAG_NEXT, irq, (const uint128_t *)next_tag, spr ); + }; + + /** + * Add REFS tag. + * @note Qwords are NOT counted automatically, so + * there is NO need to use packet2_chain_close_tag(); + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param ref_data Pointer to data. + * @param qw_length Size of data in qwords. + * @param irq Interrupt Request. False by default. + * @param spr Memory/SPR Selection. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_refs( packet2_t *packet2, const void *ref_data, uint32_t qw_length, uint8_t irq, uint8_t spr, uint32_t pce){ + assert(((uint32_t)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2_chain_add_dma_tag(packet2, qw_length, pce, P2_DMA_TAG_REFS, irq, (const uint128_t *)ref_data, spr); + } + + /** + * Add REFE tag. + * @note Qwords are NOT counted automatically, so + * there is NO need to use packet2_chain_close_tag(); + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param ref_data Pointer to data. + * @param qw_length Size of data in qwords. + * @param irq Interrupt Request. False by default. + * @param spr Memory/SPR Selection. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_refe( packet2_t *packet2, const void *ref_data, uint32_t qw_length, uint8_t irq, uint8_t spr, uint32_t pce ){ + assert(((uint32_t)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2_chain_add_dma_tag(packet2, qw_length, pce, P2_DMA_TAG_REFE, irq, (const uint128_t *)ref_data, spr); + }; + + /** + * Add CALL tag. + * @note packet2_chain_close_tag() required. Qwords + * are counted automatically. + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param next_tag Pointer to next tag. + * @param irq Interrupt Request. False by default. + * @param spr Memory/SPR Selection. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_call( packet2_t *packet2, const void *next_tag, uint8_t irq, uint8_t spr, uint32_t pce ){ + assert(((uint32_t)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2_chain_add_dma_tag(packet2, PACKET2_COUNT_QWC, pce, P2_DMA_TAG_CALL, irq, (const uint128_t *)next_tag, spr); + }; + + /** + * Add RET tag. + * @note packet2_chain_close_tag() required. Qwords + * are counted automatically. + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_ret(packet2_t *packet2, uint8_t irq, uint32_t pce){ + packet2_chain_add_dma_tag(packet2, PACKET2_COUNT_QWC, pce, P2_DMA_TAG_RET, irq, 0, 0); + }; + +#ifdef __cplusplus + } +#endif + + +#define MAKE_VIF_CODE(_immediate, _num, _cmd, _irq) ((uint32_t)(_immediate) | ((uint32_t)(_num) << 16) | ((uint32_t)(_cmd) << 24) | ((uint32_t)(_irq) << 31)) + +#ifdef __cplusplus + extern "C" + { +#endif + + /** + * Add UNPACK VIF opcode. + * @note packet2_vif_close_unpack() required. Qwords + * are counted automatically. + * For more details, check description of vif_code_t. + * @param packet2 Pointer to packet. + * @param mode Unpack mode + * @param vuAddr Memory address (divided by 16). + * @param dblBuffered (VIF1 only) + * 1 - Adds VIF1_TOPS register to ADDR + * 0 - Does not use VIF1_TOPS register. + * @param masked Is masked + * @param usigned + * 1 - Unsigned - Decompress by padding 0 to the upper field + * 0 - Signed - Decompress by sign extension + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_open_unpack(packet2_t *packet2, unpack_mode_t mode, uint32_t vuAddr, uint8_t dblBuffered, uint8_t masked, uint8_t usigned, uint8_t irq){ + assert(packet2->vif_code_opened_at == NULL); // All previous UNPACK/DIRECT are closed. + packet2->vif_code_opened_at = (vif_code_t *)packet2->next; + packet2_add_u32( packet2, MAKE_VIF_CODE(vuAddr | ((uint32_t)usigned << 14) | ((uint32_t)dblBuffered << 15), 0, mode | ((uint32_t)masked << 4) | 0x60, irq) ); + }; + + /** + * Close UNPACK manually. + * In reality, get back to pointer "vif_code_opened_at" and + * fix num value with qwords counted from last packet2_vif_open_unpack(). + * @param packet2 Pointer to packet. + * @param unpack_num Amount of data written to the VU Mem (qwords) or MicroMem (dwords). + * 256 is max value! + */ + static inline void packet2_vif_close_unpack_manual(packet2_t *packet2, uint32_t unpack_num){ + assert(packet2->vif_code_opened_at != NULL); // There is open UNPACK/DIRECT. + assert(((uint32_t)packet2->next & 0x3) == 0); // Make sure we're u32 aligned + assert((packet2->vif_code_opened_at->cmd & 0x60) == 0x60); // It was UNPACK + assert(unpack_num <= 256); + packet2->vif_code_opened_at->num = (unpack_num == 256) ? 0 : unpack_num; + packet2->vif_code_opened_at = (vif_code_t *)NULL; + } + + /** + * Close UNPACK automatically. + * In reality, get back to pointer "vif_code_opened_at" and + * fix num value with qwords counted from last packet2_vif_open_unpack(). + * @param packet2 Pointer to packet. + * @param wl WL Value (look at STCYCL) + * @param cl CL Value (look at STCYCL) + * @returns Unpacked qwords count + */ + uint32_t packet2_vif_close_unpack_auto(packet2_t *packet2, uint32_t wl, uint32_t cl); + + /** + * Add DIRECT VIF opcode. + * @note Direct must be closed via + * packet2_vif_close_direct_manual() or + * packet2_vif_close : "memory" + */ + static inline void packet2_vif_open_direct(packet2_t *packet2, uint8_t irq){ + assert(packet2->vif_code_opened_at == NULL); // All previous UNPACK/DIRECT are closed. + packet2->vif_code_opened_at = (vif_code_t *)packet2->next; + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_DIRECT, irq)); + }; + + /** + * Close DIRECT manually. + * In reality, get back to pointer "vif_code_opened_at" and + * fix immediate value with given value. + * @param packet2 Pointer to packet. + * @param qwords Qwords count. + */ + static inline void packet2_vif_close_direct_manual(packet2_t *packet2, uint32_t qwords){ + assert(packet2->vif_code_opened_at != NULL); // There is open UNPACK/DIRECT. + assert((((uint32_t)packet2->next - ((uint32_t)packet2->vif_code_opened_at + 4)) & 0xF) == 0); + packet2->vif_code_opened_at->immediate = qwords; + packet2->vif_code_opened_at = (vif_code_t *)NULL; + }; + + /** + * Close DIRECT automatically. + * In reality, get back to pointer "vif_code_opened_at" and + * fix immediate value with qwords counted from last packet2_vif_open_direct(). + * @param packet2 Pointer to packet. + */ + static inline void packet2_vif_close_direct_auto(packet2_t *packet2){ + return packet2_vif_close_direct_manual(packet2, ((uint32_t)packet2->next - ((uint32_t)packet2->vif_code_opened_at + 4)) >> 4); + }; + + /** + * Add NOP VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_nop(packet2_t *packet2, uint8_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_NOP, irq)); + }; + + /** + * Fill with NOP VIF opcode to align to 96bits + * @param packet2 Pointer to packet. + */ + static inline void packet2_vif_pad96(packet2_t *packet2){ + packet2_pad96(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_NOP, 0)); + }; + + /** + * Fill with NOP VIF opcode to align to 128bits + * @param packet2 Pointer to packet. + */ + static inline void packet2_vif_pad128(packet2_t *packet2){ + packet2_pad128(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_NOP, 0)); + }; + + /** + * Add MPG VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param num Number of 64-bit data. + * @param addr Address. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mpg(packet2_t *packet2, uint32_t num, uint32_t addr, uint8_t irq ){ + packet2_add_u32(packet2, MAKE_VIF_CODE(addr, num, P2_VIF_MPG, irq)); + }; + + /** + * Add STCYCL VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param wl WL field. + * @param cl CL field. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_stcycl(packet2_t *packet2, uint32_t wl, uint32_t cl, uint8_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(cl | (wl << 8), 0, P2_VIF_STCYCL, irq)); + }; + + /** + * Add OFFSET VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param offset Offset. BASE+OFFSET will be the address of second buffer. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_offset( packet2_t *packet2, uint32_t offset, uint8_t irq ){ + packet2_add_u32(packet2, MAKE_VIF_CODE(offset, 0, P2_VIF_OFFSET, irq)); + }; + + /** + * Add BASE VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param base Base address of double buffer. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_base( packet2_t *packet2, uint32_t base, uint8_t irq ){ + packet2_add_u32(packet2, MAKE_VIF_CODE(base, 0, P2_VIF_BASE, irq)); + }; + + /** + * Add FLUSH VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_flush( packet2_t *packet2, uint8_t irq ){ + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_FLUSH, irq)); + }; + + /** + * Add MSCAL VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param addr Starting address. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mscal( packet2_t *packet2, uint32_t addr, uint8_t irq ){ + packet2_add_u32(packet2, MAKE_VIF_CODE(addr, 0, P2_VIF_MSCAL, irq)); + }; + + /** + * Add MSCNT VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mscnt( packet2_t *packet2, uint8_t irq ){ + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_MSCNT, irq)); + }; + + /** + * Add ITOP VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param itops Value for VU XITOP instruction. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_itop(packet2_t *packet2, uint32_t itops, uint8_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(itops, 0, P2_VIF_ITOP, irq)); + }; + + /** + * Add MSKPATH3 VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param mode Decompression mode. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_stmod(packet2_t *packet2, uint32_t mode, uint8_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(mode, 0, P2_VIF_STMOD, irq)); + }; + + /** + * Add MSKPATH3 VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param mask Mask. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mskpath3(packet2_t *packet2, uint32_t mask, uint8_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(mask, 0, P2_VIF_MSKPATH3, irq)); + }; + + /** + * Add MARK VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param value Value. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mark(packet2_t *packet2, uint32_t value, uint8_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(value, 0, P2_VIF_MARK, irq)); + }; + + /** + * Add FLUSHE VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_flushe(packet2_t *packet2, uint8_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_FLUSHE, irq)); + }; + + /** + * Add FLUSHA VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_flusha(packet2_t *packet2, uint8_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_FLUSHA, irq)); + }; + + /** + * Add MSCALF VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param addr Address. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mscalf(packet2_t *packet2, uint32_t addr, uint32_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(addr, 0, P2_VIF_MSCALF, irq)); + }; + + /** + * Add STMASK VIF opcode. + * @note Alignment alert. Size of dword (1/2). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param mask Mask. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_stmask(packet2_t *packet2, vif_mask_t mask, uint8_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_STMASK, irq)); + packet2_add_u32(packet2, mask.m); + }; + + /** + * Add STROW VIF opcode. + * @note Alignment alert. Size of 5 x word (1+1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param row_arr Row array. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_strow(packet2_t *packet2, const uint32_t *row_arr, uint8_t irq){ + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_STROW, irq)); + packet2_add_u32(packet2, row_arr[0]); + packet2_add_u32(packet2, row_arr[1]); + packet2_add_u32(packet2, row_arr[2]); + packet2_add_u32(packet2, row_arr[3]); + }; + + /** + * Add STCOL VIF opcode. + * @note Alignment alert. Size of 5 x word (1+1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param col_arr Column array. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_stcol(packet2_t *packet2, const uint32_t *col_arr, uint8_t irq ){ + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_STCOL, irq)); + packet2_add_u32(packet2, col_arr[0]); + packet2_add_u32(packet2, col_arr[1]); + packet2_add_u32(packet2, col_arr[2]); + packet2_add_u32(packet2, col_arr[3]); + }; + + /** + * Add VU micro program into packet2. + * Packet2 MODE for micro program upload: Chain + * @param dest VU destination address (divided by 16). + * @param start Start address. + * @param end End address. + */ + void packet2_vif_add_micro_program(packet2_t *packet2, uint32_t dest, uint32_t *start, uint32_t *end); + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/sps2_basement/hardware/ee/dmac/packet.c b/sps2_basement/hardware/ee/dmac/packet.c new file mode 100644 index 0000000..5ac399d --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/packet.c @@ -0,0 +1,106 @@ +#include +#include +#include +#include + +#define SPR_BEGIN 0x70000000 + +packet_t *packet_init(int qwords, int type) +{ + + int byte_size = 0; + packet_t *packet = (packet_t*)calloc(1,sizeof(packet_t)); + + if (packet == NULL) + { + + return NULL; + + } + + if (type == PACKET_SPR) + { + + packet->data = (qword_t *)SPR_BEGIN; + packet->qwc = 0x1000; + + } + else + { + // Size of qwords in bytes. + byte_size = qwords << 4; + + // Allocate the data area in bytes aligned to cache line. + if ((packet->data = memalign(64, byte_size)) == NULL) + { + free(packet); + return NULL; + + } + } + + // Set the pointer attribute to ucab space. + if (type == PACKET_UCAB) + { + + packet->data = (qword_t *)((u32)packet->data | 0x30000000); + + } + + // Clear the packet area. + memset(packet->data, 0, byte_size); + + // Set the packet counts + packet->qwc = 0; + packet->qwords = qwords; + packet->type = type; + + // End function. + return packet; + +} + +void packet_free(packet_t *packet) +{ + + // Free the allocated data buffer. + if (packet->type == PACKET_SPR) + { + + packet->data = NULL; + + } + else + { + if (packet->type == PACKET_UCAB) + { + + packet->data = (qword_t *)((u32)packet->data ^ 0x30000000); + + } + + free(packet->data); + } + + free(packet); + +} + +void packet_reset(packet_t *packet) +{ + + // Reset the quadword counter. + packet->qwc = 0; + + if (packet->type == PACKET_SPR) + { + + packet->data = (qword_t *)SPR_BEGIN; + return; + + } + + // Zero out the data + memset(packet->data, 0, packet->qwords << 4); + +} diff --git a/sps2_basement/hardware/ee/dmac/packet.h b/sps2_basement/hardware/ee/dmac/packet.h new file mode 100644 index 0000000..063fbcd --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/packet.h @@ -0,0 +1,56 @@ +/** + * @file + * Packet library functions. + */ + +#ifndef __PACKET_H__ +#define __PACKET_H__ + +#include + +/** Maximum number allowed, but each channel has its own limitations. */ +#define QWC_MAX 65535 + +#define PACKET_NORMAL 0x00 +#define PACKET_UCAB 0x01 +#define PACKET_SPR 0x02 +/** + * Dmatags use qwc for the number of qwords for they handle. + * + * The dma channel QWC register uses it as the total number of qwords that + * are being sent at a time. + */ +typedef struct { + u32 qwords; + u16 qwc; + u16 type; + qword_t *data __attribute__((aligned(64))); +} packet_t; + +#ifdef __cplusplus +extern "C" { +#endif + +/** Allocate a new packet for use, size in quadwords. */ +packet_t *packet_init(int qwords, int type); + +/** Reset the packet quadword counter and zero out data. */ +void packet_reset(packet_t *packet); + +/** Free the space allocated by packet. */ +void packet_free(packet_t *packet); + +/** Advances the qwc and returns the current qword count. */ +qword_t *packet_increment_qwc(packet_t *packet, int num); + +/** For those that like getters and setters */ +static inline qword_t *packet_get_qword(packet_t *packet) +{ + return packet->data; +} + +#ifdef __cplusplus +} +#endif + +#endif /* __PACKET_H__ */ diff --git a/sps2_basement/hardware/ee/dmac/packet2.c b/sps2_basement/hardware/ee/dmac/packet2.c new file mode 100644 index 0000000..8f47534 --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/packet2.c @@ -0,0 +1,130 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (c) 2020 h4570 Sandro Sobczyński +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include +#include +#include +#include +#include +#include + +#define P2_ALIGNMENT 64 +#define P2_MAKE_PTR_NORMAL(PTR) ((u32)(PTR)&0x0FFFFFFF) + +// --- +// Packet2 management +// --- + +packet2_t *packet2_create(u16 qwords, enum Packet2Type type, enum Packet2Mode mode, u8 tte) +{ + packet2_t *packet2 = (packet2_t *)calloc(1, sizeof(packet2_t)); + if (packet2 == NULL) + return NULL; + + packet2->max_qwords_count = qwords; + packet2->type = type; + packet2->mode = mode; + packet2->tte = tte; + packet2->tag_opened_at = NULL; + packet2->vif_code_opened_at = NULL; + + // Dma buffer size should be a whole number of cache lines (64 bytes = 4 quads) + assert(!((packet2->type == P2_TYPE_UNCACHED || packet2->type == P2_TYPE_UNCACHED_ACCL) && packet2->max_qwords_count & (4 - 1))); + + u32 byte_size = packet2->max_qwords_count << 4; + + if ((packet2->base = memalign(P2_ALIGNMENT, byte_size)) == NULL) + { + free(packet2); + return NULL; + } + + packet2->base = packet2->next = (qword_t *)((u32)packet2->base | packet2->type); + + memset(packet2->base, 0, byte_size); + + // "I hate to do this, but I've wasted FAR too much time hunting down cache incoherency" + if (packet2->type == P2_TYPE_UNCACHED || packet2->type == P2_TYPE_UNCACHED_ACCL) + FlushCache(0); + + return packet2; +} + +packet2_t *packet2_create_from(qword_t *base, qword_t *next, u16 qwords, enum Packet2Type type, enum Packet2Mode mode, u8 tte) +{ + // Dma buffer size should be a whole number of cache lines (64 bytes = 4 quads) + assert(!((type == P2_TYPE_UNCACHED || type == P2_TYPE_UNCACHED_ACCL) && qwords & (4 - 1))); + + // Dma buffer should be aligned on a cache line (64-byte boundary) + assert(!((type == P2_TYPE_UNCACHED || type == P2_TYPE_UNCACHED_ACCL) && (u32)base & (64 - 1))); + + packet2_t *packet2 = (packet2_t *)calloc(1, sizeof(packet2_t)); + if (packet2 == NULL) + return NULL; + + packet2->base = base; + packet2->next = next; + packet2->max_qwords_count = qwords; + packet2->type = type; + packet2->tte = tte; + packet2->mode = mode; + return packet2; +} + +void packet2_free(packet2_t *packet2) +{ + if (packet2->base != NULL) + free((qword_t *)P2_MAKE_PTR_NORMAL(packet2->base)); + free(packet2); +} + +void packet2_reset(packet2_t *packet2, u8 clear_mem) +{ + packet2->next = packet2->base; + packet2->vif_code_opened_at = NULL; + packet2->tag_opened_at = NULL; + if (clear_mem) + memset(packet2->base, 0, packet2->max_qwords_count << 4); +} + +// --- +// Utils +// --- + +void packet2_add(packet2_t *a, packet2_t *b) +{ + assert(packet2_get_qw_count(a) + packet2_get_qw_count(b) <= a->max_qwords_count); + memcpy(a->next, b->base, (u32)b->next - (u32)b->base); + a->next = a->base + packet2_get_qw_count(b) + 1; +} + +void packet2_print(packet2_t *packet2, u32 qw_count) +{ + if (qw_count == 0) + qw_count = ((u32)packet2->next - (u32)packet2->base) >> 4; + printf("\n============================\n"); + printf("Packet2: Dumping %d words...\n", ((u32)packet2->next - (u32)packet2->base) >> 2); + u32 i = 0; + u32 *nextWord; + for (nextWord = (u32 *)packet2->base; nextWord != (u32 *)packet2->next; nextWord++, i++) + { + if ((i % 4) == 0) + printf("\n0x%08x: ", (u32)nextWord); + printf("0x%08x ", *nextWord); + if (i / 4 == qw_count) + break; + } + printf("\n============================\n"); +} + +void packet2_print_qw_count(packet2_t *packet2) +{ + printf("Packet2: Qwords count:%d \n", packet2_get_qw_count(packet2)); +} diff --git a/sps2_basement/hardware/ee/dmac/packet2.h b/sps2_basement/hardware/ee/dmac/packet2.h new file mode 100644 index 0000000..b5e28cb --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/packet2.h @@ -0,0 +1,217 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (c) 2020 h4570 Sandro Sobczyński +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file Successor of standard packet library. + * @defgroup packet2 Packet2 library + * Successor of packet_t. Main goal of this library is to + * create simple API for packet management. + * Library is splitted into several parts: + * - This - core functionality of libpacket2 + * - "_types" - Enums and structures used in libpacket2 + * - "_chain" - DMA tags + * - "_vif" - VU related + * - "_utils" - useful functions, and examples + * @{ + */ + +#ifndef __PACKET2_H__ +#define __PACKET2_H__ + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + // --- + // Packet2 management + // --- + + /** + * Allocate new packet2. + * @param qwords Maximum data size in qwords (128bit). + * @param type Memory mapping type. + * @param mode Packet mode. Normal or chain. + * @param tte Tag transfer enable. + * Used only for CHAIN mode! + * If >0 transfer tag is set during packet sending and + * add_dma_tag() (so also every open_tag()) will move buffer by DWORD, + * so remember to align memory! + * @returns Pointer to packet2 on success or NULL if memory allocation fail. + */ + packet2_t *packet2_create(u16 qwords, enum Packet2Type type, enum Packet2Mode mode, u8 tte); + + /** + * Create new packet2 with given data pointer. + * @param base Pointer to base (start of buffer). + * @param next Pointer to next (current position of buffer). + * @param qwords Maximum data size in qwords (128bit). + * @param type Memory mapping type. + * @param mode Packet mode. Normal or chain (so also vif/vu). + * @param tte Tag transfer enable. + * Used only for CHAIN mode! + * If >0 transfer tag is set during packet sending and + * add_dma_tag() (so also every open_tag()) will move buffer by DWORD, + * so remember to align memory! + * @returns Pointer to packet2 on success or NULL if memory allocation fail. + */ + packet2_t *packet2_create_from(qword_t *base, qword_t *next, u16 qwords, enum Packet2Type type, enum Packet2Mode mode, u8 tte); + + /** + * Free packet2 memory. + * @param packet2 Pointer to packet2. + */ + void packet2_free(packet2_t *packet2); + + /** + * Reset packet. + * Move next pointer back to base pointer, + * Make all "openedAt" vars to NULL + * Do memset on data if required. + * @param packet2 Pointer to packet. + * @param clear_mem If >0, data is cleared via memset(). SLOW! + */ + void packet2_reset(packet2_t *packet2, u8 clear_mem); + + /** + * Update current position of packet buffer. + * Useful with drawlib functions. + */ + static inline void packet2_update(packet2_t *packet2, qword_t *qw) { packet2->next = qw; } + + // --- + // Basic add + // --- + + /** Move "next" pointer forward. */ + static inline void packet2_advance_next(packet2_t *packet2, u32 i) + { + packet2->next = (qword_t *)((u8 *)packet2->next + i); + } + + static inline void packet2_add_u128(packet2_t *packet2, const u128 val) + { + *((u128 *)packet2->next) = val; + packet2_advance_next(packet2, sizeof(u128)); + } + + /** @note Alignment alert. Size of dword (1/2) */ + static inline void packet2_add_s64(packet2_t *packet2, const s64 val) + { + *((s64 *)packet2->next) = val; + packet2_advance_next(packet2, sizeof(s64)); + } + + static inline void packet2_add_2x_s64(packet2_t *packet2, const s64 v1, const s64 v2) + { + packet2_add_s64(packet2, v1); + packet2_add_s64(packet2, v2); + } + + static inline void packet2_add_s128(packet2_t *packet2, const s128 val) + { + *((s128 *)packet2->next) = val; + packet2_advance_next(packet2, sizeof(s128)); + } + + /** @note Alignment alert. Size of dword (1/2) */ + static inline void packet2_add_u64(packet2_t *packet2, const u64 val) + { + *((u64 *)packet2->next) = val; + packet2_advance_next(packet2, sizeof(u64)); + } + + /** @note Alignment alert. Size of word (1/4) */ + static inline void packet2_add_u32(packet2_t *packet2, const u32 val) + { + *((u32 *)packet2->next) = val; + packet2_advance_next(packet2, sizeof(u32)); + } + + /** @note Alignment alert. Size of word (1/4) */ + static inline void packet2_add_s32(packet2_t *packet2, const s32 val) + { + *((s32 *)packet2->next) = val; + packet2_advance_next(packet2, sizeof(s32)); + } + + /** @note Alignment alert. Size of word (1/4) */ + static inline void packet2_add_float(packet2_t *packet2, const float val) + { + *((float *)packet2->next) = val; + packet2_advance_next(packet2, sizeof(float)); + } + + static inline void packet2_add_data(packet2_t *packet2, void *t_data, u32 t_size) + { + int i; + for (i = 0; i < t_size; i++) + packet2_add_u128(packet2, ((u128 *)t_data)[i]); + } + + /** + * Fill to align to 96bits + */ + static inline void packet2_pad96(packet2_t *packet2, const u32 val) + { + while ((((u32)packet2->next + 4) & 0xf) != 0) + packet2_add_u32(packet2, val); + } + + /** + * Fill to align to 128bits + */ + static inline void packet2_pad128(packet2_t *packet2, const u32 val) + { + while (((u32)packet2->next & 0xf) != 0) + packet2_add_u32(packet2, val); + } + + // --- + // Other + // --- + + /** + * Print data of packet. + * @param packet2 Pointer to packet. + * @param clear_mem Count of qwords, type 0 for all. + */ + void packet2_print(packet2_t *packet2, u32 qw_count); + + /** + * Print amount of qwords of packet. + * @param packet2 Pointer to packet. + */ + void packet2_print_qw_count(packet2_t *packet2); + + /** Copy data from b packet into a packet with memcpy() */ + void packet2_add(packet2_t *a, packet2_t *b); + + /** Returns count of added qwords into packet. */ + static inline u32 packet2_get_qw_count(packet2_t *packet2) { return ((u32)packet2->next - (u32)packet2->base) >> 4; } + + /** True if packet doesnt have even number of quads. */ + static inline u8 packet2_doesnt_have_even_number_of_quads(packet2_t *packet2) { return ((u32)packet2->next & 0xF) != 0; } + + /** True if dma tag is opened. */ + static inline u8 packet2_is_dma_tag_opened(packet2_t *packet2) { return packet2->tag_opened_at != NULL; } + + /** True if DIRECT/UNPACK is opened. */ + static inline u8 packet2_is_vif_code_opened(packet2_t *packet2) { return packet2->vif_code_opened_at != NULL; } + +#ifdef __cplusplus +} +#endif + +#endif /* __PACKET2_H__ */ + +/** @} */ // end of packet2 group diff --git a/sps2_basement/hardware/ee/dmac/packet2_chain.h b/sps2_basement/hardware/ee/dmac/packet2_chain.h new file mode 100644 index 0000000..b742520 --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/packet2_chain.h @@ -0,0 +1,249 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (c) 2020 h4570 Sandro Sobczyński +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file Chain mode related functions for packet2. + * @defgroup packet2_chain Chain + * Chain mode related functions of libpacket2. + * @ingroup packet2 + * @{ + */ + +#ifndef __PACKET2_CHAIN_H__ +#define __PACKET2_CHAIN_H__ + +#include +#include +#include + +#define PACKET2_COUNT_QWC 1 << 16 + +#ifdef __cplusplus +extern "C" +{ +#endif + + // --- + // DMA tag management + // --- + + /** + * Set dma tag. + * For more details, check description of dma_tag_t. + * @param tag Pointer to DMA tag to set. + * @param qwc Qword count. + * @param pce Priority Control Enable. 0 by default. + * @param id Tag ID. + * @param irq Interrupt Request. False by default. + * @param addr Address. + * @param spr Memory/SPR Selection. False by default. + */ + static inline void packet2_chain_set_dma_tag(dma_tag_t *tag, u32 qwc, u32 pce, u32 id, u8 irq, const u128 *addr, u8 spr) + { + tag->QWC = qwc; + tag->PCE = pce; + tag->ID = id; + tag->IRQ = irq; + tag->ADDR = (u64)((u32)addr); + tag->SPR = spr; + } + + /** + * Add dma tag. + * For more details, check description of dma_tag_t. + * Will move current buffer position by: + * DWORD if packet->tte == true, + * QWORD if packet->tte == false + * @param packet2 Pointer to packet. + * @param qwc Qword count. If you want to use + * packet2_chain_close_tag(), and count qwords + * automatically, set value to PACKET2_COUNT_QWC. + * @param pce Priority Control Enable. 0 by default. + * @param id Tag ID. + * @param irq Interrupt Request. False by default. + * @param addr Address. + * @param spr Memory/SPR Selection. False by default. + */ + static inline void packet2_chain_add_dma_tag(packet2_t *packet2, u32 qwc, u32 pce, enum DmaTagType id, u8 irq, const u128 *addr, u8 spr) + { + assert(((u32)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + assert(packet2->tag_opened_at == NULL); // All previous tags are closed. + + if (qwc == PACKET2_COUNT_QWC) + { + packet2_chain_set_dma_tag((dma_tag_t *)packet2->next, 0, pce, id, irq, addr, spr); // placeholder + packet2->tag_opened_at = (dma_tag_t *)packet2->next; + } + else + { + packet2_chain_set_dma_tag((dma_tag_t *)packet2->next, qwc, pce, id, irq, addr, spr); + packet2->tag_opened_at = (dma_tag_t *)NULL; + } + if (!packet2->tte) + packet2_advance_next(packet2, sizeof(dma_tag_t)); + else + packet2_advance_next(packet2, sizeof(u64)); + } + + /** + * Close dma tag. + * In reality, get back to pointer "tag_opened_at" and fix qwc value. + * @param packet2 Pointer to packet. + */ + static inline void packet2_chain_close_tag(packet2_t *packet2) + { + assert(packet2->tag_opened_at != NULL); // There is opened tag. + assert(((u32)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2->tag_opened_at->QWC = (((u32)packet2->next - (u32)packet2->tag_opened_at) / 16 - 1); + packet2->tag_opened_at = (dma_tag_t *)NULL; + } + + // --- + // DMA tags + // --- + + /** + * Add CNT tag. + * @note packet2_chain_close_tag() required. Qwords + * are counted automatically. + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + * @param pce Priority Control Enable. 0 by default. + * @param spr Memory/SPR Selection. False by default. + */ + static inline void packet2_chain_open_cnt(packet2_t *packet2, u8 irq, u32 pce, u8 spr) + { + packet2_chain_add_dma_tag(packet2, PACKET2_COUNT_QWC, pce, P2_DMA_TAG_CNT, irq, 0, spr); + } + + /** + * Add END tag. + * @note packet2_chain_close_tag() required. Qwords + * are counted automatically. + * For more details, check description of dma_tag_t. + * @note Don't forget about close_tag()! + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_open_end(packet2_t *packet2, u8 irq, u32 pce) + { + packet2_chain_add_dma_tag(packet2, PACKET2_COUNT_QWC, pce, P2_DMA_TAG_END, irq, 0, 0); + } + + /** + * Add REF tag. + * @note Qwords are NOT counted automatically, so + * there is NO need to use packet2_chain_close_tag(); + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param ref_data Pointer to data. + * @param qw_length Size of data in qwords. + * @param irq Interrupt Request. False by default. + * @param spr Memory/SPR Selection. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_ref(packet2_t *packet2, const void *ref_data, u32 qw_length, u8 irq, u8 spr, u32 pce) + { + assert(((u32)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2_chain_add_dma_tag(packet2, qw_length, pce, P2_DMA_TAG_REF, irq, (const u128 *)ref_data, spr); + } + + /** + * Add NEXT tag. + * @note packet2_chain_close_tag() required. Qwords + * are counted automatically. + * For more details, check description of dma_tag_t. + * @param next_tag Pointer to next tag. + * @param irq Interrupt Request. False by default. + * @param spr Memory/SPR Selection. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_next(packet2_t *packet2, const dma_tag_t *next_tag, u8 irq, u8 spr, u32 pce) + { + assert(((u32)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2_chain_add_dma_tag(packet2, PACKET2_COUNT_QWC, pce, P2_DMA_TAG_NEXT, irq, (u128 *)next_tag, spr); + } + + /** + * Add REFS tag. + * @note Qwords are NOT counted automatically, so + * there is NO need to use packet2_chain_close_tag(); + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param ref_data Pointer to data. + * @param qw_length Size of data in qwords. + * @param irq Interrupt Request. False by default. + * @param spr Memory/SPR Selection. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_refs(packet2_t *packet2, const void *ref_data, u32 qw_length, u8 irq, u8 spr, u32 pce) + { + assert(((u32)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2_chain_add_dma_tag(packet2, qw_length, pce, P2_DMA_TAG_REFS, irq, (const u128 *)ref_data, spr); + } + + /** + * Add REFE tag. + * @note Qwords are NOT counted automatically, so + * there is NO need to use packet2_chain_close_tag(); + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param ref_data Pointer to data. + * @param qw_length Size of data in qwords. + * @param irq Interrupt Request. False by default. + * @param spr Memory/SPR Selection. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_refe(packet2_t *packet2, const void *ref_data, u32 qw_length, u8 irq, u8 spr, u32 pce) + { + assert(((u32)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2_chain_add_dma_tag(packet2, qw_length, pce, P2_DMA_TAG_REFE, irq, (const u128 *)ref_data, spr); + } + + /** + * Add CALL tag. + * @note packet2_chain_close_tag() required. Qwords + * are counted automatically. + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param next_tag Pointer to next tag. + * @param irq Interrupt Request. False by default. + * @param spr Memory/SPR Selection. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_call(packet2_t *packet2, const void *next_tag, u8 irq, u8 spr, u32 pce) + { + assert(((u32)packet2->next & 0xF) == 0); // Free space in packet is aligned properly. + packet2_chain_add_dma_tag(packet2, PACKET2_COUNT_QWC, pce, P2_DMA_TAG_CALL, irq, (u128 *)next_tag, spr); + } + + /** + * Add RET tag. + * @note packet2_chain_close_tag() required. Qwords + * are counted automatically. + * For more details, check description of dma_tag_t. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + * @param pce Priority Control Enable. 0 by default. + */ + static inline void packet2_chain_ret(packet2_t *packet2, u8 irq, u32 pce) + { + packet2_chain_add_dma_tag(packet2, PACKET2_COUNT_QWC, pce, P2_DMA_TAG_RET, irq, 0, 0); + } + +#ifdef __cplusplus +} +#endif + +#endif /* __PACKET2_CHAIN_H__ */ + +/** @} */ // end of packet2_chain subgroup diff --git a/sps2_basement/hardware/ee/dmac/packet2_types.h b/sps2_basement/hardware/ee/dmac/packet2_types.h new file mode 100644 index 0000000..f26969d --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/packet2_types.h @@ -0,0 +1,359 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (c) 2020 h4570 Sandro Sobczyński +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file Structs and enums used in packet2 library + * @defgroup packet2_types Types + * Structures and enums used in libpacket2. + * @ingroup packet2 + * @{ + */ + +#ifndef __PACKET2_DATA_TYPES_H__ +#define __PACKET2_DATA_TYPES_H__ + +#include + +/** + * Two modes are commonly used with the DMA Controller (DMAC): normal mode and + * chain mode. In normal mode, transfers are issued one at a time. In chain mode, a + * series of transfers are issued simultaneously by initiating a transfer that contains + * "DMA Tags", which in turn contains instructions for further transfers. You will + * probably use chain mode for the majority of your transfers. + */ +enum Packet2Mode +{ + P2_MODE_NORMAL = 0, + P2_MODE_CHAIN = 1, +}; + +/** Types of memory mapping. */ +enum Packet2Type +{ + /** Normal. */ + P2_TYPE_NORMAL = 0x00000000, + /** Uncached. */ + P2_TYPE_UNCACHED = 0x20000000, + /** Uncached accelerated. */ + P2_TYPE_UNCACHED_ACCL = 0x30000000, + /** Scratchpad memory. */ + P2_TYPE_SPRAM = 0x70000000 +}; + +/** DMA tag types */ +enum DmaTagType +{ + /** Transfers the QWC qword from the ADDR field, clears the Dn_CHCR.STR to 0, and ends transfer. */ + P2_DMA_TAG_REFE = 0, + /** Transfers the QWC qword following the tag and reads the succeeding qword as the next tag. */ + P2_DMA_TAG_CNT = 1, + /** Transfers the QWC qword following the tag and reads the qword of the ADDR field as the next tag. */ + P2_DMA_TAG_NEXT = 2, + /** Transfers the QWC qword from the ADDR field and reads the qword following the tag as the next tag. */ + P2_DMA_TAG_REF = 3, + /** + * Transfers the QWC qword from the ADDR field while controlling stalls + * and reads the qword following the tag as the next tag. + * @note Effective only on the VIF1, GIF, and SIF1 channels. + */ + P2_DMA_TAG_REFS = 4, + /** + * Transfers the QWC qword following the tag, pushes the next field into + * the Dn_ASR register, and reads the qword of the ADDR field as the next tag. + * @note Effective only on the VIF0, VIF1, and GIF channels. + * Addresses can be pushed up to 2 levels + */ + P2_DMA_TAG_CALL = 5, + /** + * Transfers the QWC qword following the tag and reads the + * qword of the field popped from the Dn_ASR register as the + * next tag. + * Transfers the QWC qword following the tag, clears the + * Dn_CHCR.STR to 0, and ends transfer when there is no + * pushed address. + * @note Effective only on the VIF0, VIF1, and GIF channels. + */ + P2_DMA_TAG_RET = 6, + /** Transfers the QWC qword following the tag, clears the Dn_CHCR.STR to 0, and ends transfer. */ + P2_DMA_TAG_END = 7 +}; + +/** Destination chain tag. */ +typedef struct +{ + /** Quadword count. */ + u64 QWC : 16; + u64 PAD : 10; + /** + * Priority Control Enable. + * 00 Nothing performed + * 01 Reserved + * 10 Priority setting disabled (D_PCR.PCE = 0) + * 11 Priority setting enabled (D_PCR.PCE = 1) + */ + u64 PCE : 2; + /** Tag ID. (look at DmaTagType) */ + u64 ID : 3; + /** + * Interrupt Request. + * 0 No interrupt request + * 1 Interrupt request at end of packet transfer + */ + u64 IRQ : 1; + /** + * Address. + * Address of packet or next tag instruction + * (With qword alignment, lower 4 bits become 0.) + */ + u64 ADDR : 31; + /** + * Memory/SPR Selection. + * 0 Memory address + * 1 SPR address + */ + u64 SPR : 1; + u32 OPT1; + u32 OPT2; +} dma_tag_t __attribute__((aligned(16))); + +/** + * Unpack modes. + * V2 = 2 dimensions, S = Single = 1 dimension + * _32 = 32 bits of data length. + */ +enum UnpackMode +{ + P2_UNPACK_S_32 = 0x00, + P2_UNPACK_S_16 = 0x01, + P2_UNPACK_S_8 = 0x02, + P2_UNPACK_V2_32 = 0x04, + P2_UNPACK_V2_16 = 0x05, + P2_UNPACK_V2_8 = 0x06, + P2_UNPACK_V3_32 = 0x08, + P2_UNPACK_V3_16 = 0x09, + P2_UNPACK_V3_8 = 0x0A, + P2_UNPACK_V4_32 = 0x0C, + P2_UNPACK_V4_16 = 0x0D, + P2_UNPACK_V4_8 = 0x0E, + P2_UNPACK_V4_5 = 0x0F, +}; + +/** VIF opcodes. */ +enum VIFOpcode +{ + /** + * No operation. + * No operation is performed. + * NOP is used to adjust the data alignment in the VIF packet. + */ + P2_VIF_NOP = 0, + /** + * Sets write recycle. + * STCYCL writes the value of the IMMEDIATE field to the VIFn_CYCLE register. + */ + P2_VIF_STCYCL = 1, + /** + * Sets the double buffer offset. + * OFFSET writes the lower 10 bits of the IMMEDIATE field to the VIF1_OFST register. + * At the same time, the DBF flag of the VIF1_STAT register is cleared to 0, and the VIF1_BASE register + * value is set to the VIF1_TOPS. That is, the pointer for the double buffer points to the BASE. + */ + P2_VIF_OFFSET = 2, + /** + * Sets the base address of the double buffer. + * BASE writes the lower 10 bits of the IMMEDIATE field to the VIF1_BASE register. + * These bits become the base address of the double buffers. + */ + P2_VIF_BASE = 3, + /** + * Sets the data pointer. + * ITOP writes the lower 10 bits of the IMMEDIATE field to the VIFn_ITOPS register. + * This value is read from the VU by the XITOP instruction. + */ + P2_VIF_ITOP = 4, + /** + * Sets the addition decompression mode. + * STMOD writes the lower 2 bits of the IMMEDIATE field to the VIFn_MODE register. + * This becomes the addition decompression mode setting. + */ + P2_VIF_STMOD = 5, + /** + * Sets the PATH3 mask. + * MSKPATH3 enables/disables transfer processing via the GIF PATH3. + * The setting of this register applies to the next data block or later. + */ + P2_VIF_MSKPATH3 = 6, + /** + * Sets the MARK value. + * MARK writes the value of the IMMEDIATE field to the VIFn_MARK register. + * By properly setting the MARK value, it becomes possible to use this value for + * synchronization with the EE Core and debugging. + */ + P2_VIF_MARK = 7, + /** + * Waits for end of the microprogram. + * FLUSHE waits for the state in which the microprogram in VU0/VU1 has been ended. + */ + P2_VIF_FLUSHE = 16, + /** + * Waits for end of the microprogram. + * FLUSH waits for the state in which transfers to the GIF from PATH1 and PATH2 have been ended after + * end of microprogram in VU1. FLUSH does not wait for the end of the transfer via PATH1 by + * the XGKICK instruction with the E bit. + */ + P2_VIF_FLUSH = 17, + /** + * Waits for end of the microprogram. + * FLUSHA waits for the state in which there is no transfer request from PATH3 after the end of micro + * program in VU1 and end of transfer to the GIF from PATH1 and PATH2. + */ + P2_VIF_FLUSHA = 18, + /** + * Activates the microprogram. + * MSCAL waits for the end of the microprogram under execution and activates the micro program with the + * value of the IMMEDIATE field as the starting address. + */ + P2_VIF_MSCAL = 20, + /** + * Activates the microprogram. + * MSCNT waits for the end of the microprogram under execution and executes the next microprogram from + * the address following the most recently ended one in the PC (program counter). + */ + P2_VIF_MSCNT = 23, + /** + * Activates the microprogram. + * MSCALF waits for the end of both the microprogram and the GIF(PATH1/PATH2) transfer and executes + * the microprogram with the value of the IMMEDIATE field as the starting address. + */ + P2_VIF_MSCALF = 21, + /** + * Sets the data mask pattern. + * STMASK stores the next 1 word of data in the VIFn_MASK register. + * This data becomes the mask pattern of the write data. + */ + P2_VIF_STMASK = 32, + /** + * Sets the filling data. + * STROW stores the following 4 words of data in the VIFn_R0 - VIFn_R3 registers. + * These are used as filling data when decompressed by the VIFcode UNPACK. + */ + P2_VIF_STROW = 48, + /** + * Sets the filling data. + * STCOL stores the following 4 words of data in the VIFn_C0 - VIFn_C3 registers. + * These are used as filling data when decompressed by the VIFcode UNPACK. + */ + P2_VIF_STCOL = 49, + /** + * Transfers the microprogram. + * MPG waits for the end of the microprogram and transfers the following NUM pieces of 64-bit data. + * (microinstruction code) to the MicroMem address shown by the IMMEDIATE field. + */ + P2_VIF_MPG = 74, + /** + * Transfers data to the GIF(GS). + * DIRECT transfers the following IMMEDIATE pieces of 128-bit data to the GS via GIF PATH2. It is + * necessary to put the appropriate GIFtag to the data. + */ + P2_VIF_DIRECT = 80, + /** + * Transfers data to the GIF(GS). + * DIRECTHL transfers the following IMMEDIATE pieces of 128-bit data to the GS via GIF PATH2. + * The appropriate GIFtag must be attached to the data. + * Interruption of PATH3 IMAGE mode data does not occur during the data transfer via PATH2 by + * DIRECTHL. Moreover, when the IMAGE mode data is being transferred via PATH3, DIRECTHL stalls + * until the end of the transfer. + */ + P2_VIF_DIRECTHL = 81 +}; + +/** VIFCode structure. */ +typedef struct +{ + /** The contents of the IMMEDIATE field vary according to the CMD field. */ + u32 immediate : 16; + /** + * The NUM field shows the amount of data written to the VU Mem or MicroMem (Data is in 128-bit units + * and microinstruction code is in 64-bit units). When NUM=0, it is considered to be 256. + * Note that it is not the amount of data in the VIF packet. NUM pieces of data can be written even when the + * amount of data in the packet is 0 depending on the CYCLE register setting. + */ + u32 num : 8; + /** + * The CMD field directs the operation of the VIF, that is, the decompression + * method of the following data. + */ + u32 cmd : 8; +} vif_code_t; + +/** + * DMA data packet. + * Successor of standard packet. + */ +typedef struct +{ + /** Maximum number of qwords which was defined in packet2_create(). */ + u16 max_qwords_count; + /** Type of packet's memory mapping. */ + enum Packet2Type type; + /** Packet mode. */ + enum Packet2Mode mode; + /** + * Tag transfer enable. + * Effective only in chain mode. + * If >0 transfer tag is set during packet sending and + * add_dma_tag() (so also every open_tag()) will move buffer by DWORD, + * so remember to align memory! + */ + u8 tte; + /** Start position of the buffer. */ + qword_t *base __attribute__((aligned(64))); + /** Current position of the buffer. */ + qword_t *next; + /** + * The buffer position where DMA tag was opened. + * NULL, if no dma tag is open. + */ + dma_tag_t *tag_opened_at; + /** + * The buffer position where DIRECT/UNPACK was opened. + * NULL, if no DIRECT/UNPACK is open. + */ + vif_code_t *vif_code_opened_at; +} packet2_t; + +/** Mask, used in VIF's STMASK opcode. */ +typedef union +{ + struct + { + unsigned int m0 : 2; + unsigned int m1 : 2; + unsigned int m2 : 2; + unsigned int m3 : 2; + unsigned int m4 : 2; + unsigned int m5 : 2; + unsigned int m6 : 2; + unsigned int m7 : 2; + unsigned int m8 : 2; + unsigned int m9 : 2; + unsigned int m10 : 2; + unsigned int m11 : 2; + unsigned int m12 : 2; + unsigned int m13 : 2; + unsigned int m14 : 2; + unsigned int m15 : 2; + }; + unsigned int m; +} Mask; + +#endif /* __PACKET2_DATA_TYPES_H__ */ + +/** @} */ // end of packet2_types subgroup diff --git a/sps2_basement/hardware/ee/dmac/packet2_utils.h b/sps2_basement/hardware/ee/dmac/packet2_utils.h new file mode 100644 index 0000000..d04b311 --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/packet2_utils.h @@ -0,0 +1,264 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (c) 2020 h4570 Sandro Sobczyński +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file Helper functions for packet2. + * @defgroup packet2_utils Utils + * Useful functions and examples for libpacket2. + * @ingroup packet2 + * @{ + */ + +#ifndef __PACKET2_UTILS_H__ +#define __PACKET2_UTILS_H__ + +#include "packet2.h" +#include "packet2_chain.h" +#include "packet2_vif.h" + +#include +#include +#include +#include +#include + +#define VU_GS_PRIM(PRIM, IIP, TME, FGE, ABE, AA1, FST, CTXT, FIX) (u128)(((FIX << 10) | (CTXT << 9) | (FST << 8) | (AA1 << 7) | (ABE << 6) | (FGE << 5) | (TME << 4) | (IIP << 3) | (PRIM))) +#define VU_GS_GIFTAG(NLOOP, EOP, PRE, PRIM, FLG, NREG) (((u64)(NREG) << 60) | ((u64)(FLG) << 58) | ((u64)(PRIM) << 47) | ((u64)(PRE) << 46) | (EOP << 15) | (NLOOP << 0)) + +#ifdef __cplusplus +extern "C" +{ +#endif + + // ---- + // VU + // ---- + + /** + * Add VU buffers size settings. + * @param t_base Base address (qw) + * @param t_offset Offset address (qw) + */ + static inline void packet2_utils_vu_add_double_buffer(packet2_t *packet2, u16 base, u16 offset) + { + packet2_chain_open_cnt(packet2, 0, 0, 0); + packet2_vif_base(packet2, base, 0); + packet2_vif_offset(packet2, offset, 0); + packet2_chain_close_tag(packet2); + } + + /** + * Add data via REF tag and UNPACK. + * Please be sure that data is aligned, + * and there is no any open UNPACK/DIRECT. + * @param packet2 Pointer to packet2. + * @param t_dest_address Destination address. + * @param t_data Data pointer. + * @param t_size Size in quadwords. + * @param t_use_top Unpack to current double buffer? + */ + static inline void packet2_utils_vu_add_unpack_data(packet2_t *packet2, u32 t_dest_address, void *t_data, u32 t_size, u8 t_use_top) + { + packet2_chain_ref(packet2, t_data, t_size, 0, 0, 0); + packet2_vif_stcycl(packet2, 0, 0x0101, 0); + packet2_vif_open_unpack(packet2, P2_UNPACK_V4_32, t_dest_address, t_use_top, 0, 1, 0); + packet2_vif_close_unpack_manual(packet2, t_size); + } + + /** + * Open CNT tag + VU unpack. + * @param packet2 Pointer to packet2. + * @param t_dest_address Destination address. + * @param t_use_top Unpack to current double buffer? + */ + static inline void packet2_utils_vu_open_unpack(packet2_t *packet2, u32 t_dest_address, u8 t_use_top) + { + packet2_chain_open_cnt(packet2, 0, 0, 0); + packet2_vif_stcycl(packet2, 0, 0x0101, 0); + packet2_vif_open_unpack(packet2, P2_UNPACK_V4_32, t_dest_address, t_use_top, 0, 1, 0); + } + + /** + * Close CNT tag + VU unpack. + * @returns Unpacked qwords count + */ + static inline u32 packet2_utils_vu_close_unpack(packet2_t *packet2) + { + packet2_vif_pad128(packet2); + packet2_chain_close_tag(packet2); + return packet2_vif_close_unpack_auto(packet2, 0, 0x0101); + } + + /** + * Continue VU micro program (from --cont line). + * Adds FLUSH and MSCNT VIF opcodes. + */ + static inline void packet2_utils_vu_add_continue_program(packet2_t *packet2) + { + packet2_chain_open_cnt(packet2, 0, 0, 0); + packet2_vif_flush(packet2, 0); + packet2_vif_mscnt(packet2, 0); + packet2_chain_close_tag(packet2); + } + + /** + * Start VU micro program. + * Adds FLUSH and MSCAL VIF opcodes. + */ + static inline void packet2_utils_vu_add_start_program(packet2_t *packet2, u32 addr) + { + packet2_chain_open_cnt(packet2, 0, 0, 0); + packet2_vif_flush(packet2, 0); + packet2_vif_mscal(packet2, addr, 0); + packet2_chain_close_tag(packet2); + } + + /** Add aligned END tag (with nops). */ + static inline void packet2_utils_vu_add_end_tag(packet2_t *packet2) + { + packet2_chain_open_end(packet2, 0, 0); + packet2_vif_nop(packet2, 0); + packet2_vif_nop(packet2, 0); + packet2_chain_close_tag(packet2); + } + + /** + * Get program size in qws + * @param start Start address. + * @param end End address. + * @returns Packet size in qws for specified program (instructions/256 + 1qw for tolerance). + */ + static inline u32 packet2_utils_get_packet_size_for_program(u32 *start, u32 *end) + { + // Count instructions + u32 count = (end - start) / 2; + if (count & 1) + count++; + return (count >> 8) + 1; + } + + // ---- + // GIF + // ---- + + /** + * Add set GIFTag which will be + * sent from VU1 via XGKICK instruction. + * @param packet2 Pointer to packet2. + * @param loops_count How many GIF tags there will be? + */ + static inline void packet2_utils_gif_add_set(packet2_t *packet2, u32 loops_count) + { + packet2_add_2x_s64(packet2, GIF_SET_TAG(loops_count, 0, 0, 0, GIF_FLG_PACKED, 1), GIF_REG_AD); + } + + // ---- + // GS + // ---- + + /** + * Add lod GIFTag which will be + * sent from VU1 via XGKICK instruction. + * @param packet2 Pointer to packet2. + * @param lod Pointer to lod settings. + */ + static inline void packet2_utils_gs_add_lod(packet2_t *packet2, lod_t *lod) + { + packet2_add_2x_s64( + packet2, + GS_SET_TEX1( + lod->calculation, + lod->max_level, + lod->mag_filter, + lod->min_filter, + lod->mipmap_select, + lod->l, + (int)(lod->k * 16.0F)), + GS_REG_TEX1); + } + + /** + * Add texture buffer / clut GIFTag which will be + * sent from VU1 via XGKICK instruction. + * @param packet2 Pointer to packet2. + * @param texbuff Pointer to texture buffer. + * @param clut Pointer to clut buffer. + */ + static inline void packet2_utils_gs_add_texbuff_clut(packet2_t *packet2, texbuffer_t *texbuff, clutbuffer_t *clut) + { + packet2_add_2x_s64( + packet2, + GS_SET_TEX0( + texbuff->address >> 6, + texbuff->width >> 6, + texbuff->psm, + texbuff->info.width, + texbuff->info.height, + texbuff->info.components, + texbuff->info.function, + clut->address >> 6, + clut->psm, + clut->storage_mode, + clut->start, + clut->load_method), + GS_REG_TEX0); + } + + /** + * Add draw finish event GIFTag which will be sent from VU1 via + * XGKICK instruction. + * Used for synchronization via draw_wait_finish() + * @param packet2 Pointer to packet2. + */ + static inline void packet2_utils_gs_add_draw_finish_giftag(packet2_t *packet2) + { + packet2_add_2x_s64(packet2, 1, GS_REG_FINISH); + } + + /** + * Add drawing (prim) GIFTag which will be sent from VU1 via + * XGKICK instruction. + * @param packet2 Pointer to packet2. + * @param prim Pointer to prim settings. + * @param loops_count GIF tag loops count. + * @param nreg What types of data we will use? + * @param nreg_count How many types there are in nreg? + * @param context Drawing context + */ + static inline void packet2_utils_gs_add_prim_giftag(packet2_t *packet2, prim_t *prim, u32 loops_count, u32 nreg, u8 nreg_count, u8 context) + { + packet2_add_2x_s64( + packet2, + VU_GS_GIFTAG( + loops_count, // Information for GS. Amount of loops + 1, + 1, + VU_GS_PRIM( + prim->type, + prim->shading, + prim->mapping, + prim->fogging, + prim->blending, + prim->antialiasing, + prim->mapping_type, + context, // context + prim->colorfix), + 0, + nreg_count), + nreg); + } + +#ifdef __cplusplus +} +#endif + +#endif /* __PACKET2_UTILS_H__ */ + +/** @} */ // end of packet2_utils subgroup diff --git a/sps2_basement/hardware/ee/dmac/packet2_vif.c b/sps2_basement/hardware/ee/dmac/packet2_vif.c new file mode 100644 index 0000000..71d454a --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/packet2_vif.c @@ -0,0 +1,75 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (c) 2020 h4570 Sandro Sobczyński +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include "packet2_vif.h" +#include "packet2_chain.h" + +void packet2_vif_add_micro_program(packet2_t *packet2, u32 dest, u32 *start, u32 *end) +{ + // get the size of the code as we can only send 256 instructions in each MPGtag + u32 count = (end - start) / 2; + if (count & 1) + count++; + + u32 *l_start = start; + while (count > 0) + { + u16 curr_count = count > 256 ? 256 : count; + packet2_chain_ref(packet2, l_start, curr_count / 2, 0, 0, 0); + packet2_vif_nop(packet2, 0); + packet2_vif_mpg(packet2, curr_count & 0xFF, dest, 0); + l_start += curr_count * 2; + count -= curr_count; + dest += curr_count; + } +} + +u32 packet2_vif_close_unpack_auto(packet2_t *packet2, u32 wl, u32 cl) +{ + assert(packet2->vif_code_opened_at != NULL); // There is open UNPACK/DIRECT. + assert(((u32)packet2->next & 0x3) == 0); // Make sure we're u32 aligned + assert((packet2->vif_code_opened_at->cmd & 0x60) == 0x60); // It was UNPACK + + u32 vn = (packet2->vif_code_opened_at->cmd & 0xC) >> 2; + u32 vl = packet2->vif_code_opened_at->cmd & 0x3; + + // "the goal here is to find the num field of the open unpack, which is the number of + // qwords ACTUALLY WRITTEN to vu memory (it does not count quads that are skipped in + // "skipping write" mode.) But first forget about skipping/filling writes and compute the number + // of qwords that the data in this packet will expand to." + u32 bytes_count = (u32)packet2->next - (u32)packet2->vif_code_opened_at - 4; + u32 block_bytes_count = 4 >> vl; + u32 quad_blocks_count = vn + 1; + + // "make sure that the data length is a multiple of 8, 16, or 32 bits, whichever is appropriate" + assert((bytes_count & (block_bytes_count - 1)) == 0); + u32 quads_count = (bytes_count / block_bytes_count) / quad_blocks_count; + + // "We have the number of quads our data will directly expand to, so now we need to account for + // skipping/filling write modes."" + + // "skipping write is easy -- we are already done" + + // "filling write: now we get ambiguous -- what to do when quads_count == CL in the last + // block? I will say that in this case the vif should still do the full wl length block, filling + // with internal registers. If you want different behavior call packet2_vif_close_unpack_manual + // with a num field you've computed yourself" + if (cl < wl) + { + u32 wl_blocks_count = (quads_count / cl); + u32 last_block_quads = quads_count - wl_blocks_count * cl; + if (last_block_quads == cl) + last_block_quads = wl; + quads_count = wl_blocks_count * wl + last_block_quads; + } + + packet2_vif_close_unpack_manual(packet2, quads_count); + return quads_count; +} diff --git a/sps2_basement/hardware/ee/dmac/packet2_vif.h b/sps2_basement/hardware/ee/dmac/packet2_vif.h new file mode 100644 index 0000000..6d75cf8 --- /dev/null +++ b/sps2_basement/hardware/ee/dmac/packet2_vif.h @@ -0,0 +1,401 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (c) 2020 h4570 Sandro Sobczyński +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file VIF related functions for packet2. + * @defgroup packet2_vif VIF + * VIF related functions of libpacket2. + * @ingroup packet2 + * @{ + */ + +#ifndef __PACKET2_VIF_H__ +#define __PACKET2_VIF_H__ + +#include +#include +#include + +#define MAKE_VIF_CODE(_immediate, _num, _cmd, _irq) ((u32)(_immediate) | ((u32)(_num) << 16) | ((u32)(_cmd) << 24) | ((u32)(_irq) << 31)) + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * Add UNPACK VIF opcode. + * @note packet2_vif_close_unpack() required. Qwords + * are counted automatically. + * For more details, check description of vif_code_t. + * @param packet2 Pointer to packet. + * @param mode Unpack mode + * @param vuAddr Memory address (divided by 16). + * @param dblBuffered (VIF1 only) + * 1 - Adds VIF1_TOPS register to ADDR + * 0 - Does not use VIF1_TOPS register. + * @param masked Is masked + * @param usigned + * 1 - Unsigned - Decompress by padding 0 to the upper field + * 0 - Signed - Decompress by sign extension + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_open_unpack(packet2_t *packet2, enum UnpackMode mode, u32 vuAddr, u8 dblBuffered, u8 masked, u8 usigned, u8 irq) + { + assert(packet2->vif_code_opened_at == NULL); // All previous UNPACK/DIRECT are closed. + packet2->vif_code_opened_at = (vif_code_t *)packet2->next; + packet2_add_u32(packet2, + MAKE_VIF_CODE(vuAddr | ((u32)usigned << 14) | ((u32)dblBuffered << 15), + 0, + mode | ((u32)masked << 4) | 0x60, irq)); + } + + /** + * Close UNPACK manually. + * In reality, get back to pointer "vif_code_opened_at" and + * fix num value with qwords counted from last packet2_vif_open_unpack(). + * @param packet2 Pointer to packet. + * @param unpack_num Amount of data written to the VU Mem (qwords) or MicroMem (dwords). + * 256 is max value! + */ + static inline void packet2_vif_close_unpack_manual(packet2_t *packet2, u32 unpack_num) + { + assert(packet2->vif_code_opened_at != NULL); // There is open UNPACK/DIRECT. + assert(((u32)packet2->next & 0x3) == 0); // Make sure we're u32 aligned + assert((packet2->vif_code_opened_at->cmd & 0x60) == 0x60); // It was UNPACK + assert(unpack_num <= 256); + packet2->vif_code_opened_at->num = (unpack_num == 256) ? 0 : unpack_num; + packet2->vif_code_opened_at = (vif_code_t *)NULL; + } + + /** + * Close UNPACK automatically. + * In reality, get back to pointer "vif_code_opened_at" and + * fix num value with qwords counted from last packet2_vif_open_unpack(). + * @param packet2 Pointer to packet. + * @param wl WL Value (look at STCYCL) + * @param cl CL Value (look at STCYCL) + * @returns Unpacked qwords count + */ + u32 packet2_vif_close_unpack_auto(packet2_t *packet2, u32 wl, u32 cl); + + /** + * Add DIRECT VIF opcode. + * @note Direct must be closed via + * packet2_vif_close_direct_manual() or + * packet2_vif_close : "memory" + */ + static inline void packet2_vif_open_direct(packet2_t *packet2, u8 irq) + { + assert(packet2->vif_code_opened_at == NULL); // All previous UNPACK/DIRECT are closed. + packet2->vif_code_opened_at = (vif_code_t *)packet2->next; + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_DIRECT, irq)); + } + + /** + * Close DIRECT manually. + * In reality, get back to pointer "vif_code_opened_at" and + * fix immediate value with given value. + * @param packet2 Pointer to packet. + * @param qwords Qwords count. + */ + static inline void packet2_vif_close_direct_manual(packet2_t *packet2, u32 qwords) + { + assert(packet2->vif_code_opened_at != NULL); // There is open UNPACK/DIRECT. + assert((((u32)packet2->next - ((u32)packet2->vif_code_opened_at + 4)) & 0xF) == 0); + packet2->vif_code_opened_at->immediate = qwords; + packet2->vif_code_opened_at = (vif_code_t *)NULL; + } + + /** + * Close DIRECT automatically. + * In reality, get back to pointer "vif_code_opened_at" and + * fix immediate value with qwords counted from last packet2_vif_open_direct(). + * @param packet2 Pointer to packet. + */ + static inline void packet2_vif_close_direct_auto(packet2_t *packet2) + { + return packet2_vif_close_direct_manual(packet2, ((u32)packet2->next - ((u32)packet2->vif_code_opened_at + 4)) >> 4); + } + + /** + * Add NOP VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_nop(packet2_t *packet2, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_NOP, irq)); + } + + /** + * Fill with NOP VIF opcode to align to 96bits + * @param packet2 Pointer to packet. + */ + static inline void packet2_vif_pad96(packet2_t *packet2) + { + packet2_pad96(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_NOP, 0)); + } + + /** + * Fill with NOP VIF opcode to align to 128bits + * @param packet2 Pointer to packet. + */ + static inline void packet2_vif_pad128(packet2_t *packet2) + { + packet2_pad128(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_NOP, 0)); + } + + /** + * Add MPG VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param num Number of 64-bit data. + * @param addr Address. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mpg(packet2_t *packet2, u32 num, u32 addr, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(addr, num, P2_VIF_MPG, irq)); + } + + /** + * Add STCYCL VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param wl WL field. + * @param cl CL field. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_stcycl(packet2_t *packet2, u32 wl, u32 cl, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(cl | (wl << 8), 0, P2_VIF_STCYCL, irq)); + } + + /** + * Add OFFSET VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param offset Offset. BASE+OFFSET will be the address of second buffer. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_offset(packet2_t *packet2, u32 offset, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(offset, 0, P2_VIF_OFFSET, irq)); + } + + /** + * Add BASE VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param base Base address of double buffer. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_base(packet2_t *packet2, u32 base, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(base, 0, P2_VIF_BASE, irq)); + } + + /** + * Add FLUSH VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_flush(packet2_t *packet2, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_FLUSH, irq)); + } + + /** + * Add MSCAL VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param addr Starting address. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mscal(packet2_t *packet2, u32 addr, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(addr, 0, P2_VIF_MSCAL, irq)); + } + + /** + * Add MSCNT VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mscnt(packet2_t *packet2, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_MSCNT, irq)); + } + + /** + * Add ITOP VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param itops Value for VU XITOP instruction. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_itop(packet2_t *packet2, u32 itops, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(itops, 0, P2_VIF_ITOP, irq)); + } + + /** + * Add MSKPATH3 VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param mode Decompression mode. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_stmod(packet2_t *packet2, u32 mode, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(mode, 0, P2_VIF_STMOD, irq)); + } + + /** + * Add MSKPATH3 VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param mask Mask. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mskpath3(packet2_t *packet2, u32 mask, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(mask, 0, P2_VIF_MSKPATH3, irq)); + } + + /** + * Add MARK VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param value Value. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mark(packet2_t *packet2, u32 value, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(value, 0, P2_VIF_MARK, irq)); + } + + /** + * Add FLUSHE VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_flushe(packet2_t *packet2, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_FLUSHE, irq)); + } + + /** + * Add FLUSHA VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_flusha(packet2_t *packet2, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_FLUSHA, irq)); + } + + /** + * Add MSCALF VIF opcode. + * @note Alignment alert. Size of word (1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param addr Address. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_mscalf(packet2_t *packet2, u32 addr, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(addr, 0, P2_VIF_MSCALF, irq)); + } + + /** + * Add STMASK VIF opcode. + * @note Alignment alert. Size of dword (1/2). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param mask Mask. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_stmask(packet2_t *packet2, Mask mask, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_STMASK, irq)); + packet2_add_u32(packet2, mask.m); + } + + /** + * Add STROW VIF opcode. + * @note Alignment alert. Size of 5 x word (1+1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param row_arr Row array. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_strow(packet2_t *packet2, const u32 *row_arr, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_STROW, irq)); + packet2_add_u32(packet2, row_arr[0]); + packet2_add_u32(packet2, row_arr[1]); + packet2_add_u32(packet2, row_arr[2]); + packet2_add_u32(packet2, row_arr[3]); + } + + /** + * Add STCOL VIF opcode. + * @note Alignment alert. Size of 5 x word (1+1/4). + * For more details, check description of VIFOpcode. + * @param packet2 Pointer to packet. + * @param col_arr Column array. + * @param irq Interrupt Request. False by default. + */ + static inline void packet2_vif_stcol(packet2_t *packet2, const u32 *col_arr, u8 irq) + { + packet2_add_u32(packet2, MAKE_VIF_CODE(0, 0, P2_VIF_STCOL, irq)); + packet2_add_u32(packet2, col_arr[0]); + packet2_add_u32(packet2, col_arr[1]); + packet2_add_u32(packet2, col_arr[2]); + packet2_add_u32(packet2, col_arr[3]); + } + + /** + * Add VU micro program into packet2. + * Packet2 MODE for micro program upload: Chain + * @param dest VU destination address (divided by 16). + * @param start Start address. + * @param end End address. + */ + void packet2_vif_add_micro_program(packet2_t *packet2, u32 dest, u32 *start, u32 *end); + +#ifdef __cplusplus +} +#endif + +#endif /* __PACKET2_VIF_H__ */ + +/** @} */ // end of packet2_vif subgroup diff --git a/sps2_basement/hardware/ee/ee_cop0_defs.h b/sps2_basement/hardware/ee/ee_cop0_defs.h new file mode 100644 index 0000000..18f628a --- /dev/null +++ b/sps2_basement/hardware/ee/ee_cop0_defs.h @@ -0,0 +1,116 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 PS2DEV.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * EE Co-processor 0(COP0) register definitions. + */ + +#ifndef __EE_COP0_DEFS_H__ +#define __EE_COP0_DEFS_H__ + +#define M_EE_GET_CAUSE_EXCODE(__cause) (((__cause) >> 2) & 0x1F) +#define M_EE_GET_CAUSE_EXC2(__cause) (((__cause) >> 16) & 0x7) + +// EE COP0 Register name defs +#define EE_COP0_Index $0 +#define EE_COP0_Random $1 +#define EE_COP0_EntryLo0 $2 +#define EE_COP0_EntryLo1 $3 +#define EE_COP0_Context $4 +#define EE_COP0_Wired $5 +#define EE_COP0_BadVAddr $8 +#define EE_COP0_Count $9 +#define EE_COP0_EntryHi $10 +#define EE_COP0_Compare $11 +#define EE_COP0_Status $12 +#define EE_COP0_Cause $13 +#define EE_COP0_EPC $14 +#define EE_COP0_PRId $15 +#define EE_COP0_Config $16 +#define EE_COP0_BadPAddr $23 +#define EE_COP0_TagLo $28 +#define EE_COP0_TagHi $29 +#define EE_COP0_ErrorEPC $30 + +// Bits for COP0 "Status" register. +#define EE_STATUS_IE (1 << 0) +#define EE_STATUS_EXL (1 << 1) +#define EE_STATUS_ERL (1 << 2) + +#define EE_EXC2_RST (0) +#define EE_EXC2_NMI (1) +#define EE_EXC2_PERF (2) +#define EE_EXC2_DBG (3) + +// Bits for COP0 "Cause" register. +#define EE_CAUSE_BD (1 << 31) +#define EE_CAUSE_BD2 (1 << 30) + +/** Serial I/O pending flag */ +#define EE_CAUSE_SIO (1 << 12) + +// Bits in EE Cop0 Breakpoint Control(BPC) + +/* Instruction Address breakpoint Enable */ +#define EE_BPC_IAE (1 << 31) + +/* Data Read breakpoint Enable */ +#define EE_BPC_DRE (1 << 30) + +/* Data Write breakpoint Enable */ +#define EE_BPC_DWE (1 << 29) + +/* Data Value breakpoint Enable */ +#define EE_BPC_DVE (1 << 28) + +/* Instruction address breakpoint - User mode Enable */ +#define EE_BPC_IUE (1 << 26) + +/* Instruction address breakpoint - Supervisor mode Enable */ +#define EE_BPC_ISE (1 << 25) + +/* Instruction address breakpoint - Kernel mode Enable */ +#define EE_BPC_IKE (1 << 24) + +/* Instruction address breakpoint - EXL mode Enable */ +#define EE_BPC_IXE (1 << 23) + +/* Data breakpoint - User mode Enable */ +#define EE_BPC_DUE (1 << 21) + +/* Data breakpoint - Supervisor mode Enable */ +#define EE_BPC_DSE (1 << 20) + +/* Data breakpoint - Kernel mode Enable */ +#define EE_BPC_DKE (1 << 19) + +/* Data breakpoint - EXL mode Enable */ +#define EE_BPC_DXE (1 << 18) + +/* Instruction address breakpoint - Trigger generation Enable */ +#define EE_BPC_ITE (1 << 17) + +/* Data breakpoint - Trigger generation Enable */ +#define EE_BPC_DTE (1 << 16) + +/* Breakpoint Exception Disable */ +#define EE_BPC_BED (1 << 15) + +/* Data Write Breakpoint establishment flag */ +#define EE_BPC_DWB (1 << 2) + +/* Data Read Breakpoint establishment flag */ +#define EE_BPC_DRB (1 << 1) + +/* Instruction Address Breakpoint */ +#define EE_BPC_IAB (1 << 0) + +#endif /* __EE_COP0_DEFS_H__ */ diff --git a/sps2_basement/hardware/ee/ee_regs.h b/sps2_basement/hardware/ee/ee_regs.h new file mode 100644 index 0000000..05978ec --- /dev/null +++ b/sps2_basement/hardware/ee/ee_regs.h @@ -0,0 +1,612 @@ +#ifndef __EE_REGS_H__ +#define __EE_REGS_H__ + +#include "../../core/base/basicTypes.h" + +#define A_EE_SBUS_REG_BASE (0x1000F200) +#define A_EE_PGIF_REG_BASE (0x1000F300) + +#define A_EE_T0_COUNT (0x10000000) +#define A_EE_T0_MODE (0x10000010) +#define A_EE_T0_COMP (0x10000020) +#define A_EE_T0_HOLD (0x10000030) +#define A_EE_T1_COUNT (0x10000800) +#define A_EE_T1_MODE (0x10000810) +#define A_EE_T1_COMP (0x10000820) +#define A_EE_T1_HOLD (0x10000830) +#define A_EE_T2_COUNT (0x10001000) +#define A_EE_T2_MODE (0x10001010) +#define A_EE_T2_COMP (0x10001020) +#define A_EE_T3_COUNT (0x10001800) +#define A_EE_T3_MODE (0x10001810) +#define A_EE_T3_COMP (0x10001820) +#define A_EE_IPU_CMD (0x10002000) +#define A_EE_IPU_CTRL (0x10002010) +#define A_EE_IPU_BP (0x10002020) +#define A_EE_IPU_TOP (0x10002030) +#define A_EE_GIF_CTRL (0x10003000) +#define A_EE_GIF_MODE (0x10003010) +#define A_EE_GIF_STAT (0x10003020) +#define A_EE_GIF_TAG0 (0x10003040) +#define A_EE_GIF_TAG1 (0x10003050) +#define A_EE_GIF_TAG2 (0x10003060) +#define A_EE_GIF_TAG3 (0x10003070) +#define A_EE_GIF_CNT (0x10003080) +#define A_EE_GIF_P3CNT (0x10003090) +#define A_EE_GIF_P3TAG (0x100030a0) +#define A_EE_VIF0_STAT (0x10003800) +#define A_EE_VIF0_FBRST (0x10003810) +#define A_EE_VIF0_ERR (0x10003820) +#define A_EE_VIF0_MARK (0x10003830) +#define A_EE_VIF0_CYCLE (0x10003840) +#define A_EE_VIF0_MODE (0x10003850) +#define A_EE_VIF0_NUM (0x10003860) +#define A_EE_VIF0_MASK (0x10003870) +#define A_EE_VIF0_CODE (0x10003880) +#define A_EE_VIF0_ITOPS (0x10003890) +#define A_EE_VIF0_ITOP (0x100038d0) +#define A_EE_VIF0_R0 (0x10003900) +#define A_EE_VIF0_R1 (0x10003910) +#define A_EE_VIF0_R2 (0x10003920) +#define A_EE_VIF0_R3 (0x10003930) +#define A_EE_VIF0_C0 (0x10003940) +#define A_EE_VIF0_C1 (0x10003950) +#define A_EE_VIF0_C2 (0x10003960) +#define A_EE_VIF0_C3 (0x10003970) +#define A_EE_VIF1_STAT (0x10003c00) +#define A_EE_VIF1_FBRST (0x10003c10) +#define A_EE_VIF1_ERR (0x10003c20) +#define A_EE_VIF1_MARK (0x10003c30) +#define A_EE_VIF1_CYCLE (0x10003c40) +#define A_EE_VIF1_MODE (0x10003c50) +#define A_EE_VIF1_NUM (0x10003c60) +#define A_EE_VIF1_MASK (0x10003c70) +#define A_EE_VIF1_CODE (0x10003c80) +#define A_EE_VIF1_ITOPS (0x10003c90) +#define A_EE_VIF1_BASE (0x10003ca0) +#define A_EE_VIF1_OFST (0x10003cb0) +#define A_EE_VIF1_TOPS (0x10003cc0) +#define A_EE_VIF1_ITOP (0x10003cd0) +#define A_EE_VIF1_TOP (0x10003ce0) +#define A_EE_VIF1_R0 (0x10003d00) +#define A_EE_VIF1_R1 (0x10003d10) +#define A_EE_VIF1_R2 (0x10003d20) +#define A_EE_VIF1_R3 (0x10003d30) +#define A_EE_VIF1_C0 (0x10003d40) +#define A_EE_VIF1_C1 (0x10003d50) +#define A_EE_VIF1_C2 (0x10003d60) +#define A_EE_VIF1_C3 (0x10003d70) +#define A_EE_VIF0_FIFO (0x10004000) +#define A_EE_VIF1_FIFO (0x10005000) +#define A_EE_GIF_FIFO (0x10006000) +#define A_EE_IPU_out_FIFO (0x10007000) +#define A_EE_IPU_in_FIFO (0x10007010) +#define A_EE_D0_CHCR (0x10008000) +#define A_EE_D0_MADR (0x10008010) +#define A_EE_D0_QWC (0x10008020) +#define A_EE_D0_TADR (0x10008030) +#define A_EE_D0_ASR0 (0x10008040) +#define A_EE_D0_ASR1 (0x10008050) +#define A_EE_D1_CHCR (0x10009000) +#define A_EE_D1_MADR (0x10009010) +#define A_EE_D1_QWC (0x10009020) +#define A_EE_D1_TADR (0x10009030) +#define A_EE_D1_ASR0 (0x10009040) +#define A_EE_D1_ASR1 (0x10009050) +#define A_EE_D2_CHCR (0x1000a000) +#define A_EE_D2_MADR (0x1000a010) +#define A_EE_D2_QWC (0x1000a020) +#define A_EE_D2_TADR (0x1000a030) +#define A_EE_D2_ASR0 (0x1000a040) +#define A_EE_D2_ASR1 (0x1000a050) +#define A_EE_D3_CHCR (0x1000b000) +#define A_EE_D3_MADR (0x1000b010) +#define A_EE_D3_QWC (0x1000b020) +#define A_EE_D4_CHCR (0x1000b400) +#define A_EE_D4_MADR (0x1000b410) +#define A_EE_D4_QWC (0x1000b420) +#define A_EE_D4_TADR (0x1000b430) +#define A_EE_D5_CHCR (0x1000c000) +#define A_EE_D5_MADR (0x1000C010) +#define A_EE_D5_QWC (0x1000C020) +#define A_EE_D6_CHCR (0x1000C400) +#define A_EE_D6_MADR (0x1000C410) +#define A_EE_D6_QWC (0x1000C420) +#define A_EE_D6_TADR (0x1000C430) +#define A_EE_D7_CHCR (0x1000C800) +#define A_EE_D7_MADR (0x1000C810) +#define A_EE_D7_QWC (0x1000C820) +#define A_EE_D8_CHCR (0x1000D000) +#define A_EE_D8_MADR (0x1000D010) +#define A_EE_D8_QWC (0x1000D020) +#define A_EE_D8_SADR (0x1000D080) +#define A_EE_D9_CHCR (0x1000D400) +#define A_EE_D9_MADR (0x1000D410) +#define A_EE_D9_QWC (0x1000D420) +#define A_EE_D9_TADR (0x1000D430) +#define A_EE_D9_SADR (0x1000D480) +#define A_EE_D_CTRL (0x1000e000) +#define A_EE_D_STAT (0x1000e010) +#define A_EE_D_PCR (0x1000e020) +#define A_EE_D_SQWC (0x1000e030) +#define A_EE_D_RBSR (0x1000e040) +#define A_EE_D_RBOR (0x1000e050) +#define A_EE_D_STADR (0x1000e060) +#define A_EE_I_STAT (0x1000f000) +#define A_EE_I_MASK (0x1000f010) +#define A_EE_SIO_LCR (0x1000F100) +#define A_EE_SIO_LSR (0x1000F110) +#define A_EE_SIO_IER (0x1000F120) +#define A_EE_SIO_ISR (0x1000F130) +#define A_EE_SIO_FCR (0x1000F140) +#define A_EE_SIO_BRC (0x1000F150) +#define A_EE_SIO_REG60 (0x1000F160) +#define A_EE_SIO_REG70 (0x1000F170) +#define A_EE_SIO_TXFIFO (0x1000F180) +#define A_EE_SIO_REG90 (0x1000F190) +#define A_EE_SIO_REGA0 (0x1000F1A0) +#define A_EE_SIO_REGB0 (0x1000F1B0) +#define A_EE_SIO_RXFIFO (0x1000F1C0) +#define A_EE_SBUS_MADDR (0x1000F200) +#define A_EE_SBUS_SADDR (0x1000F210) +#define A_EE_SBUS_MSFLAG (0x1000F220) +#define A_EE_SBUS_SMFLAG (0x1000F230) +#define A_EE_SBUS_REG40 (0x1000F240) +#define A_EE_SBUS_REG50 (0x1000F250) +#define A_EE_SBUS_REG60 (0x1000F260) +#define A_EE_SBUS_REG70 (0x1000F270) +#define A_EE_SBUS_REG80 (0x1000F280) +#define A_EE_SBUS_REG90 (0x1000F290) +#define A_EE_SBUS_REGA0 (0x1000F2A0) +#define A_EE_SBUS_REGB0 (0x1000F2B0) +#define A_EE_SBUS_REGC0 (0x1000F2C0) +#define A_EE_SBUS_REGD0 (0x1000F2D0) +#define A_EE_SBUS_REGE0 (0x1000F2E0) +#define A_EE_SBUS_REGF0 (0x1000F2F0) +#define A_EE_PGIF_GPU_STAT (0x1000F300) +#define A_EE_PGIF_REG10 (0x1000F310) +#define A_EE_PGIF_REG20 (0x1000F320) +#define A_EE_PGIF_REG30 (0x1000F330) +#define A_EE_PGIF_REG40 (0x1000F340) +#define A_EE_PGIF_REG50 (0x1000F350) +#define A_EE_PGIF_REG60 (0x1000F360) +#define A_EE_PGIF_REG70 (0x1000F370) +#define A_EE_PGIF_CFIFO_STAT (0x1000F380) +#define A_EE_PGIF_REG90 (0x1000F390) +#define A_EE_PGIF_REGA0 (0x1000F3A0) +#define A_EE_PGIF_REGB0 (0x1000F3B0) +#define A_EE_PGIF_CFIFO_DATA (0x1000F3C0) +#define A_EE_PGIF_REGD0 (0x1000F3D0) +#define A_EE_PGIF_REGE0 (0x1000F3E0) +#define A_EE_PGIF_REGF0 (0x1000F3F0) +#define A_EE_D_ENABLER (0x1000f520) +#define A_EE_D_ENABLEW (0x1000f590) +#define A_EE_GS_PMODE (0x12000000) +#define A_EE_GS_SMODE1 (0x12000010) +#define A_EE_GS_SMODE2 (0x12000020) +#define A_EE_GS_SRFSH (0x12000030) +#define A_EE_GS_SYNCH1 (0x12000040) +#define A_EE_GS_SYNCH2 (0x12000050) +#define A_EE_GS_SYNCV (0x12000060) +#define A_EE_GS_DISPFB1 (0x12000070) +#define A_EE_GS_DISPLAY1 (0x12000080) +#define A_EE_GS_DISPFB2 (0x12000090) +#define A_EE_GS_DISPLAY2 (0x120000a0) +#define A_EE_GS_EXTBUF (0x120000b0) +#define A_EE_GS_EXTDATA (0x120000c0) +#define A_EE_GS_EXTWRITE (0x120000d0) +#define A_EE_GS_BGCOLOR (0x120000e0) +#define A_EE_GS_CSR (0x12001000) +#define A_EE_GS_IMR (0x12001010) +#define A_EE_GS_BUSDIR (0x12001040) + +/** Timer 0 counter value */ +#define R_EE_T0_COUNT ((pvuint32_t) A_EE_T0_COUNT) +/** Timer 0 mode/status */ +#define R_EE_T0_MODE ((pvuint32_t) A_EE_T0_MODE) +/** Timer 0 compare value */ +#define R_EE_T0_COMP ((pvuint32_t) A_EE_T0_COMP) +/** Timer 0 hold value */ +#define R_EE_T0_HOLD ((pvuint32_t) A_EE_T0_HOLD) +/** Timer 1 counter value */ +#define R_EE_T1_COUNT ((pvuint32_t) A_EE_T1_COUNT) +/** Timer 1 mode/status */ +#define R_EE_T1_MODE ((pvuint32_t) A_EE_T1_MODE) +/** Timer 1 compare value */ +#define R_EE_T1_COMP ((pvuint32_t) A_EE_T1_COMP) +/** Timer 1 hold value */ +#define R_EE_T1_HOLD ((pvuint32_t) A_EE_T1_HOLD) +/** Timer 2 counter value */ +#define R_EE_T2_COUNT ((pvuint32_t) A_EE_T2_COUNT) +/** Timer 2 mode/status */ +#define R_EE_T2_MODE ((pvuint32_t) A_EE_T2_MODE) +/** Timer 2 compare value */ +#define R_EE_T2_COMP ((pvuint32_t) A_EE_T2_COMP) +/** Timer 3 counter value */ +#define R_EE_T3_COUNT ((pvuint32_t) A_EE_T3_COUNT) +/** Timer 3 mode/status */ +#define R_EE_T3_MODE ((pvuint32_t) A_EE_T3_MODE) +/** Timer 3 compare value */ +#define R_EE_T3_COMP ((pvuint32_t) A_EE_T3_COMP) +/** IPU command */ +#define R_EE_IPU_CMD ((pvuint64_t) A_EE_IPU_CMD) +/** IPU control */ +#define R_EE_IPU_CTRL ((pvuint32_t) A_EE_IPU_CTRL) +/** IPU input FIFO control */ +#define R_EE_IPU_BP ((pvuint32_t) A_EE_IPU_BP) +/** First data of bit stream */ +#define R_EE_IPU_TOP ((pvuint32_t) A_EE_IPU_TOP) +/** GIF control */ +#define R_EE_GIF_CTRL ((pvuint32_t) A_EE_GIF_CTRL) +/** GIF mode setting */ +#define R_EE_GIF_MODE ((pvuint32_t) A_EE_GIF_MODE) +/** GIF status */ +#define R_EE_GIF_STAT ((pvuint32_t) A_EE_GIF_STAT) +/** GIFtag ((pvuint32_t) bits 31-0) immediately before */ +#define R_EE_GIF_TAG0 ((pvuint32_t) A_EE_GIF_TAG0) +/** GIFtag ((pvuint32_t) bits 63-32) immediately before */ +#define R_EE_GIF_TAG1 ((pvuint32_t) A_EE_GIF_TAG1) +/** GIFtag ((pvuint32_t) bits 95-64) immediately before */ +#define R_EE_GIF_TAG2 ((pvuint32_t) A_EE_GIF_TAG2) +/** GIFtag ((pvuint32_t) bits 127-96) immediately before */ +#define R_EE_GIF_TAG3 ((pvuint32_t) A_EE_GIF_TAG3) +/** Transfer status counter */ +#define R_EE_GIF_CNT ((pvuint32_t) A_EE_GIF_CNT) +/** PATH3 transfer status counter */ +#define R_EE_GIF_P3CNT ((pvuint32_t) A_EE_GIF_P3CNT) +/** PATH3 tag value */ +#define R_EE_GIF_P3TAG ((pvuint32_t) A_EE_GIF_P3TAG) +/** Status */ +#define R_EE_VIF0_STAT ((pvuint32_t) A_EE_VIF0_STAT) +/** Operation control */ +#define R_EE_VIF0_FBRST ((pvuint32_t) A_EE_VIF0_FBRST) +/** Error status */ +#define R_EE_VIF0_ERR ((pvuint32_t) A_EE_VIF0_ERR) +/** Mark value */ +#define R_EE_VIF0_MARK ((pvuint32_t) A_EE_VIF0_MARK) +/** Data write cycle */ +#define R_EE_VIF0_CYCLE ((pvuint32_t) A_EE_VIF0_CYCLE) +/** ADD mode */ +#define R_EE_VIF0_MODE ((pvuint32_t) A_EE_VIF0_MODE) +/** Amount of non-transferred data */ +#define R_EE_VIF0_NUM ((pvuint32_t) A_EE_VIF0_NUM) +/** Write mask pattern */ +#define R_EE_VIF0_MASK ((pvuint32_t) A_EE_VIF0_MASK) +/** Last processed VIFcode */ +#define R_EE_VIF0_CODE ((pvuint32_t) A_EE_VIF0_CODE) +/** Next ITOP value */ +#define R_EE_VIF0_ITOPS ((pvuint32_t) A_EE_VIF0_ITOPS) +/** ITOP value */ +#define R_EE_VIF0_ITOP ((pvuint32_t) A_EE_VIF0_ITOP) +/** Filling data R0 ((pvuint32_t) Row register) */ +#define R_EE_VIF0_R0 ((pvuint32_t) A_EE_VIF0_R0) +/** Filling data R1 ((pvuint32_t) Row register) */ +#define R_EE_VIF0_R1 ((pvuint32_t) A_EE_VIF0_R1) +/** Filling data R2 ((pvuint32_t) Row register) */ +#define R_EE_VIF0_R2 ((pvuint32_t) A_EE_VIF0_R2) +/** Filling data R3 ((pvuint32_t) Row register) */ +#define R_EE_VIF0_R3 ((pvuint32_t) A_EE_VIF0_R3) +/** Filling data C0 ((pvuint32_t) Col register) */ +#define R_EE_VIF0_C0 ((pvuint32_t) A_EE_VIF0_C0) +/** Filling data C1 ((pvuint32_t) Col register) */ +#define R_EE_VIF0_C1 ((pvuint32_t) A_EE_VIF0_C1) +/** Filling data C2 ((pvuint32_t) Col register) */ +#define R_EE_VIF0_C2 ((pvuint32_t) A_EE_VIF0_C2) +/** Filling data C3 ((pvuint32_t) Col register) */ +#define R_EE_VIF0_C3 ((pvuint32_t) A_EE_VIF0_C3) +/** Status */ +#define R_EE_VIF1_STAT ((pvuint32_t) A_EE_VIF1_STAT) +/** Operation control */ +#define R_EE_VIF1_FBRST ((pvuint32_t) A_EE_VIF1_FBRST) +/** Error status */ +#define R_EE_VIF1_ERR ((pvuint32_t) A_EE_VIF1_ERR) +/** Mark value */ +#define R_EE_VIF1_MARK ((pvuint32_t) A_EE_VIF1_MARK) +/** Data write cycle */ +#define R_EE_VIF1_CYCLE ((pvuint32_t) A_EE_VIF1_CYCLE) +/** ADD mode */ +#define R_EE_VIF1_MODE ((pvuint32_t) A_EE_VIF1_MODE) +/** Amount of non-transferred data */ +#define R_EE_VIF1_NUM ((pvuint32_t) A_EE_VIF1_NUM) +/** Write mask pattern */ +#define R_EE_VIF1_MASK ((pvuint32_t) A_EE_VIF1_MASK) +/** Last processed VIFcode */ +#define R_EE_VIF1_CODE ((pvuint32_t) A_EE_VIF1_CODE) +/** Next ITOP value */ +#define R_EE_VIF1_ITOPS ((pvuint32_t) A_EE_VIF1_ITOPS) +/** Base address of double buffer */ +#define R_EE_VIF1_BASE ((pvuint32_t) A_EE_VIF1_BASE) +/** Offset of double buffer */ +#define R_EE_VIF1_OFST ((pvuint32_t) A_EE_VIF1_OFST) +/** Next TOP value/data write address */ +#define R_EE_VIF1_TOPS ((pvuint32_t) A_EE_VIF1_TOPS) +/** ITOP value */ +#define R_EE_VIF1_ITOP ((pvuint32_t) A_EE_VIF1_ITOP) +/** TOP value */ +#define R_EE_VIF1_TOP ((pvuint32_t) A_EE_VIF1_TOP) +/** Filling data R0 ((pvuint32_t) Row register) */ +#define R_EE_VIF1_R0 ((pvuint32_t) A_EE_VIF1_R0) +/** Filling data R1 ((pvuint32_t) Row register) */ +#define R_EE_VIF1_R1 ((pvuint32_t) A_EE_VIF1_R1) +/** Filling data R2 ((pvuint32_t) Row register) */ +#define R_EE_VIF1_R2 ((pvuint32_t) A_EE_VIF1_R2) +/** Filling data R3 ((pvuint32_t) Row register) */ +#define R_EE_VIF1_R3 ((pvuint32_t) A_EE_VIF1_R3) +/** Filling data C0 ((pvuint32_t) Col register) */ +#define R_EE_VIF1_C0 ((pvuint32_t) A_EE_VIF1_C0) +/** Filling data C1 ((pvuint32_t) Col register) */ +#define R_EE_VIF1_C1 ((pvuint32_t) A_EE_VIF1_C1) +/** Filling data C2 ((pvuint32_t) Col register) */ +#define R_EE_VIF1_C2 ((pvuint32_t) A_EE_VIF1_C2) +/** Filling data C3 ((pvuint32_t) Col register) */ +#define R_EE_VIF1_C3 ((pvuint32_t) A_EE_VIF1_C3) +/** VIF0 FIFO ((pvuint32_t) write) */ +#define R_EE_VIF0_FIFO ((pvuint32_t) A_EE_VIF0_FIFO) +/** VIF1 FIFO ((pvuint32_t) read/write) */ +#define R_EE_VIF1_FIFO ((pvuint32_t) A_EE_VIF1_FIFO) +/** GIF FIFO ((pvuint32_t) write) */ +#define R_EE_GIF_FIFO ((pvuint32_t) A_EE_GIF_FIFO) +/** IPU FIFO ((pvuint32_t) read) */ +#define R_EE_IPU_out_FIFO ((pvuint32_t) A_EE_IPU_out_FIFO) +/** IPU FIFO ((pvuint32_t) write) */ +#define R_EE_IPU_in_FIFO ((pvuint32_t) A_EE_IPU_in_FIFO) +/** Ch0 channel control */ +#define R_EE_D0_CHCR ((pvuint32_t) A_EE_D0_CHCR) +/** Ch0 memory address */ +#define R_EE_D0_MADR ((pvuint32_t) A_EE_D0_MADR) +/** Ch0 quad word count */ +#define R_EE_D0_QWC ((pvuint32_t) A_EE_D0_QWC) +/** Ch0 tag address */ +#define R_EE_D0_TADR ((pvuint32_t) A_EE_D0_TADR) +/** Ch0 address stack 0 */ +#define R_EE_D0_ASR0 ((pvuint32_t) A_EE_D0_ASR0) +/** Ch0 address stack 1 */ +#define R_EE_D0_ASR1 ((pvuint32_t) A_EE_D0_ASR1) +/** Ch1 channel control */ +#define R_EE_D1_CHCR ((pvuint32_t) A_EE_D1_CHCR) +/** Ch1 memory address */ +#define R_EE_D1_MADR ((pvuint32_t) A_EE_D1_MADR) +/** Ch1 quad word count */ +#define R_EE_D1_QWC ((pvuint32_t) A_EE_D1_QWC) +/** Ch1 tag address */ +#define R_EE_D1_TADR ((pvuint32_t) A_EE_D1_TADR) +/** Ch1 address stack 0 */ +#define R_EE_D1_ASR0 ((pvuint32_t) A_EE_D1_ASR0) +/** Ch1 address stack 1 */ +#define R_EE_D1_ASR1 ((pvuint32_t) A_EE_D1_ASR1) +/** Ch2 channel control */ +#define R_EE_D2_CHCR ((pvuint32_t) A_EE_D2_CHCR) +/** Ch2 memory address */ +#define R_EE_D2_MADR ((pvuint32_t) A_EE_D2_MADR) +/** Ch2 quad word count */ +#define R_EE_D2_QWC ((pvuint32_t) A_EE_D2_QWC) +/** Ch2 tag address */ +#define R_EE_D2_TADR ((pvuint32_t) A_EE_D2_TADR) +/** Ch2 address stack 0 */ +#define R_EE_D2_ASR0 ((pvuint32_t) A_EE_D2_ASR0) +/** Ch2 address stack 1 */ +#define R_EE_D2_ASR1 ((pvuint32_t) A_EE_D2_ASR1) +/** Ch3 channel control */ +#define R_EE_D3_CHCR ((pvuint32_t) A_EE_D3_CHCR) +/** Ch3 memory address */ +#define R_EE_D3_MADR ((pvuint32_t) A_EE_D3_MADR) +/** Ch3 quad word count */ +#define R_EE_D3_QWC ((pvuint32_t) A_EE_D3_QWC) +/** Ch4 chnnel control */ +#define R_EE_D4_CHCR ((pvuint32_t) A_EE_D4_CHCR) +/** Ch4 memory address */ +#define R_EE_D4_MADR ((pvuint32_t) A_EE_D4_MADR) +/** Ch4 quad word count */ +#define R_EE_D4_QWC ((pvuint32_t) A_EE_D4_QWC) +/** Ch4 tag address */ +#define R_EE_D4_TADR ((pvuint32_t) A_EE_D4_TADR) +/** Ch5 channel control */ +#define R_EE_D5_CHCR ((pvuint32_t) A_EE_D5_CHCR) +/** Ch5 memory address */ +#define R_EE_D5_MADR ((pvuint32_t) A_EE_D5_MADR) +/** Ch5 quad word count */ +#define R_EE_D5_QWC ((pvuint32_t) A_EE_D5_QWC) +/** Ch6 channel control */ +#define R_EE_D6_CHCR ((pvuint32_t) A_EE_D6_CHCR) +/** Ch6 memory address */ +#define R_EE_D6_MADR ((pvuint32_t) A_EE_D6_MADR) +/** Ch6 quad word count */ +#define R_EE_D6_QWC ((pvuint32_t) A_EE_D6_QWC) +/** Ch6 tag address */ +#define R_EE_D6_TADR ((pvuint32_t) A_EE_D6_TADR) +/** Ch7 channel control */ +#define R_EE_D7_CHCR ((pvuint32_t) A_EE_D7_CHCR) +/** Ch7 memory address */ +#define R_EE_D7_MADR ((pvuint32_t) A_EE_D7_MADR) +/** Ch7 quad word count */ +#define R_EE_D7_QWC ((pvuint32_t) A_EE_D7_QWC) +/** Ch8 channel control */ +#define R_EE_D8_CHCR ((pvuint32_t) A_EE_D8_CHCR) +/** Ch8 memory address */ +#define R_EE_D8_MADR ((pvuint32_t) A_EE_D8_MADR) +/** Ch8 quad word count */ +#define R_EE_D8_QWC ((pvuint32_t) A_EE_D8_QWC) +/** Ch8 SPR address */ +#define R_EE_D8_SADR ((pvuint32_t) A_EE_D8_SADR) +/** Ch9 channel control */ +#define R_EE_D9_CHCR ((pvuint32_t) A_EE_D9_CHCR) +/** Ch9 memory address */ +#define R_EE_D9_MADR ((pvuint32_t) A_EE_D9_MADR) +/** Ch9 quad word count */ +#define R_EE_D9_QWC ((pvuint32_t) A_EE_D9_QWC) +/** Ch9 tag address */ +#define R_EE_D9_TADR ((pvuint32_t) A_EE_D9_TADR) +/** Ch9 SPR address */ +#define R_EE_D9_SADR ((pvuint32_t) A_EE_D9_SADR) +/** DMAC control */ +#define R_EE_D_CTRL ((pvuint32_t) A_EE_D_CTRL) +/** DMAC status */ +#define R_EE_D_STAT ((pvuint32_t) A_EE_D_STAT) +/** DMAC priority control */ +#define R_EE_D_PCR ((pvuint32_t) A_EE_D_PCR) +/** DMAC skip quad word */ +#define R_EE_D_SQWC ((pvuint32_t) A_EE_D_SQWC) +/** DMAC ring buffer size */ +#define R_EE_D_RBSR ((pvuint32_t) A_EE_D_RBSR) +/** DMAC ring buffer offset */ +#define R_EE_D_RBOR ((pvuint32_t) A_EE_D_RBOR) +/** DMA stall address */ +#define R_EE_D_STADR ((pvuint32_t) A_EE_D_STADR) +/** Interrupt status */ +#define R_EE_I_STAT ((pvuint32_t) A_EE_I_STAT) +/** Interrupt mask */ +#define R_EE_I_MASK ((pvuint32_t) A_EE_I_MASK) + + +/** EE SIO Line Control Register */ +#define R_EE_SIO_LCR ((pvuint32_t) A_EE_SIO_LCR) +/** EE SIO Line Status Register */ +#define R_EE_SIO_LSR ((pvuint32_t) A_EE_SIO_LSR) +/** EE SIO Interrupt Enable Register */ +#define R_EE_SIO_IER ((pvuint32_t) A_EE_SIO_IER) +/** EE SIO Interrupt Status Register */ +#define R_EE_SIO_ISR ((pvuint32_t) A_EE_SIO_ISR) +/** EE SIO FIFO Control Register */ +#define R_EE_SIO_FCR ((pvuint32_t) A_EE_SIO_FCR) +/** EE SIO Baud Rate Control Register */ +#define R_EE_SIO_BRC ((pvuint32_t) A_EE_SIO_BRC) +/** Unknown SIO Register 0x60 */ +#define R_EE_SIO_REG60 ((pvuint8_t) A_EE_SIO_REG60) +/** Unknown SIO Register 0x70 */ +#define R_EE_SIO_REG70 ((pvuint8_t) A_EE_SIO_REG70) +/** Transfer Holding Register */ +#define R_EE_SIO_TXFIFO ((pvuint8_t) A_EE_SIO_TXFIFO) +/** Unknown SIO Register 0x90 */ +#define R_EE_SIO_REG90 ((pvuint8_t) A_EE_SIO_REG90) +/** Unknown SIO Register 0xA0 */ +#define R_EE_SIO_REGA0 ((pvuint8_t) A_EE_SIO_REGA0) +/** Unknown SIO Register 0xB0 */ +#define R_EE_SIO_REGB0 ((pvuint8_t) A_EE_SIO_REGB0) +/** Recieve Buffer Register */ +#define R_EE_SIO_RXFIFO ((pvuint8_t) A_EE_SIO_RXFIFO) + +/** SBUS Unknown Reg 0x00 */ +#define R_EE_SBUS_MADDR ((pvuint32_t) A_EE_SBUS_REG00) +/** SBUS Unknown Reg 0x10 */ +#define R_EE_SBUS_SADDR ((pvuint32_t) A_EE_SBUS_REG10) +/** SBUS Main -> Sub Flag */ +#define R_EE_SBUS_MSFLAG ((pvuint32_t) A_EE_SBUS_MSFLAG) +/** SBUS Sub -> Main Flag */ +#define R_EE_SBUS_SMFLAG ((pvuint32_t) A_EE_SBUS_SMFLAG) +/** SBUS Unknown Reg 0x40 */ +#define R_EE_SBUS_REG40 ((pvuint32_t) A_EE_SBUS_REG40) +/** SBUS Unknown Reg 0x50 */ +#define R_EE_SBUS_REG50 ((pvuint32_t) A_EE_SBUS_REG50) +/** SBUS Unknown Reg 0x60 */ +#define R_EE_SBUS_REG60 ((pvuint32_t) A_EE_SBUS_REG60) +/** SBUS Unknown Reg 0x70 */ +#define R_EE_SBUS_REG70 ((pvuint32_t) A_EE_SBUS_REG70) +/** SBUS Unknown Reg 0x80 */ +#define R_EE_SBUS_REG80 ((pvuint32_t) A_EE_SBUS_REG80) +/** SBUS Unknown Reg 0x90 */ +#define R_EE_SBUS_REG90 ((pvuint32_t) A_EE_SBUS_REG90) +/** SBUS Unknown Reg 0xA0 */ +#define R_EE_SBUS_REGA0 ((pvuint32_t) A_EE_SBUS_REGA0) +/** SBUS Unknown Reg 0xB0 */ +#define R_EE_SBUS_REGB0 ((pvuint32_t) A_EE_SBUS_REGB0) +/** SBUS Unknown Reg 0xC0 */ +#define R_EE_SBUS_REGC0 ((pvuint32_t) A_EE_SBUS_REGC0) +/** SBUS Unknown Reg 0xD0 */ +#define R_EE_SBUS_REGD0 ((pvuint32_t) A_EE_SBUS_REGD0) +/** SBUS Unknown Reg 0xE0 */ +#define R_EE_SBUS_REGE0 ((pvuint32_t) A_EE_SBUS_REGE0) +/** SBUS Unknown Reg 0xF0 */ +#define R_EE_SBUS_REGF0 ((pvuint32_t) A_EE_SBUS_REGF0) + +/** PGIF GPU Status */ +#define R_EE_PGIF_GPU_STAT ((pvuint32_t) A_EE_PGIF_GPU_STAT) +/** PGIF Unknown Reg 0x10 */ +#define R_EE_PGIF_REG10 ((pvuint32_t) A_EE_PGIF_REG10) +/** PGIF Unknown Reg 0x20 */ +#define R_EE_PGIF_REG20 ((pvuint32_t) A_EE_PGIF_REG20) +/** PGIF Unknown Reg 0x30 */ +#define R_EE_PGIF_REG30 ((pvuint32_t) A_EE_PGIF_REG30) +/** PGIF Unknown Reg 0x40 */ +#define R_EE_PGIF_REG40 ((pvuint32_t) A_EE_PGIF_REG40) +/** PGIF Unknown Reg 0x50 */ +#define R_EE_PGIF_REG50 ((pvuint32_t) A_EE_PGIF_REG50) +/** PGIF Unknown Reg 0x60 */ +#define R_EE_PGIF_REG60 ((pvuint32_t) A_EE_PGIF_REG60) +/** PGIF Unknown Reg 0x70 */ +#define R_EE_PGIF_REG70 ((pvuint32_t) A_EE_PGIF_REG70) +/** PGIF GPU Command FIFO Status */ +#define R_EE_PGIF_CFIFO_STAT ((pvuint32_t) A_EE_PGIF_CFIFO_STAT) +/** PGIF Unknown Reg 0x90 */ +#define R_EE_PGIF_REG90 ((pvuint32_t) A_EE_PGIF_REG90) +/** PGIF Unknown Reg 0xA0 */ +#define R_EE_PGIF_REGA0 ((pvuint32_t) A_EE_PGIF_REGA0) +/** PGIF Unknown Reg 0xB0 */ +#define R_EE_PGIF_REGB0 ((pvuint32_t) A_EE_PGIF_REGB0) +/** PGIF GPU Command FIFO Data */ +#define R_EE_PGIF_CFIFO_DATA ((pvuint32_t) A_EE_PGIF_CFIFO_DATA) +/** PGIF Unknown Reg 0xD0 */ +#define R_EE_PGIF_REGD0 ((pvuint32_t) A_EE_PGIF_REGD0) +/** PGIF Unknown Reg 0xE0 */ +#define R_EE_PGIF_REGE0 ((pvuint32_t) A_EE_PGIF_REGE0) +/** PGIF Unknown Reg 0xF0 */ +#define R_EE_PGIF_REGF0 ((pvuint32_t) A_EE_PGIF_REGF0) +/** Acquisition of DMA suspend status */ +#define R_EE_D_ENABLER ((pvuint32_t) A_EE_D_ENABLER) +/** DMA suspend control */ +#define R_EE_D_ENABLEW ((pvuint32_t) A_EE_D_ENABLEW) + +/* EE GS Registers */ + +/** Various PCRTC modes */ +#define R_EE_GS_PMODE ((pvuint64_t) A_EE_GS_PMODE) +/** Related to Sync */ +#define R_EE_GS_SMODE1 ((pvuint64_t) A_EE_GS_SMODE1) +/** Related to Sync */ +#define R_EE_GS_SMODE2 ((pvuint64_t) A_EE_GS_SMODE2) +/** DRAM refresh */ +#define R_EE_GS_SRFSH ((pvuint64_t) A_EE_GS_SRFSH) +/** Related to Sync */ +#define R_EE_GS_SYNCH1 ((pvuint64_t) A_EE_GS_SYNCH1) +/** Related to Sync */ +#define R_EE_GS_SYNCH2 ((pvuint64_t) A_EE_GS_SYNCH2) +/** Related to Sync/start */ +#define R_EE_GS_SYNCV ((pvuint64_t) A_EE_GS_SYNCV) +/** Related to display buffer of Rectangular Area 1 */ +#define R_EE_GS_DISPFB1 ((pvuint64_t) A_EE_GS_DISPFB1) +/** Rectangular Area 1 display position etc. */ +#define R_EE_GS_DISPLAY1 ((pvuint64_t) A_EE_GS_DISPLAY1) +/** Related to display buffer of Rectangular Area 2 */ +#define R_EE_GS_DISPFB2 ((pvuint64_t) A_EE_GS_DISPFB2) +/** Rectangular Area 2 display position etc. */ +#define R_EE_GS_DISPLAY2 ((pvuint64_t) A_EE_GS_DISPLAY2) +/** Rectangular area write buffer */ +#define R_EE_GS_EXTBUF ((pvuint64_t) A_EE_GS_EXTBUF) +/** Rectangular area write data */ +#define R_EE_GS_EXTDATA ((pvuint64_t) A_EE_GS_EXTDATA) +/** Rectangular area write start */ +#define R_EE_GS_EXTWRITE ((pvuint64_t) A_EE_GS_EXTWRITE) +/** Background color */ +#define R_EE_GS_BGCOLOR ((pvuint64_t) A_EE_GS_BGCOLOR) +/** Various GS status */ +#define R_EE_GS_CSR ((pvuint64_t) A_EE_GS_CSR) +/** Interrupt mask */ +#define R_EE_GS_IMR ((pvuint64_t) A_EE_GS_IMR) +/** Host I/F switching */ +#define R_EE_GS_BUSDIR ((pvuint64_t) A_EE_GS_BUSDIR) + +#define EE_CHCR_MOD_NORM (0) +#define EE_CHCR_MOD_CHAIN (1) +#define EE_CHCR_MOD_INTER (2) + +#define EE_CHCR_MOD (3 << 2) +#define EE_CHCR_ASP (3 << 4) +#define EE_CHCR_TTE (1 << 6) +#define EE_CHCR_TIE (1 << 7) +#define EE_CHCR_STR (1 << 8) + +#define EE_I_STAT_GS (1 << 0) +#define EE_I_STAT_SBUS (1 << 1) +#define EE_I_STAT_VSS (1 << 2) +#define EE_I_STAT_VSE (1 << 3) + +#endif /* __EE_REGS_H__ */ diff --git a/sps2_basement/hardware/ee/vu/vu.c b/sps2_basement/hardware/ee/vu/vu.c new file mode 100644 index 0000000..3edd41f --- /dev/null +++ b/sps2_basement/hardware/ee/vu/vu.c @@ -0,0 +1,75 @@ +#include "vu.h" +#include "hwreg.h" + +void vu1_uploadcode(void *begin, void *end) +{ + int *begin_=begin,*end_=end; + volatile int *dest=(void*)vu1_micromem; + + while(begin_ +#include + +/* Definitions of frame buffers */ + +#define FB_MAX 32 /* sufficient for now */ + +#define FB_TYPE_PACKED_PIXELS 0 /* Packed Pixels */ + +#define FB_VISUAL_MONO01 0 /* Monochr. 1=Black 0=White */ +#define FB_VISUAL_MONO10 1 /* Monochr. 1=White 0=Black */ +#define FB_VISUAL_TRUECOLOR 2 /* True color */ +#define FB_VISUAL_PSEUDOCOLOR 3 /* Pseudo color (like atari) */ +#define FB_VISUAL_DIRECTCOLOR 4 /* Direct color */ +#define FB_VISUAL_STATIC_PSEUDOCOLOR 5 /* Pseudo color readonly */ + +#define FB_ACCEL_NONE 0 /* no hardware accelerator */ + +struct fb_fix_screeninfo { + char id[16]; /* identification string eg "TT Builtin" */ + unsigned long smem_start; /* Start of frame buffer mem */ + /* (physical address) */ + __u32 smem_len; /* Length of frame buffer mem */ + __u32 type; /* see FB_TYPE_* */ + __u32 type_aux; /* Interleave for interleaved Planes */ + __u32 visual; /* see FB_VISUAL_* */ + __u16 xpanstep; /* zero if no hardware panning */ + __u16 ypanstep; /* zero if no hardware panning */ + __u16 ywrapstep; /* zero if no hardware ywrap */ + __u32 line_length; /* length of a line in bytes */ + unsigned long mmio_start; /* Start of Memory Mapped I/O */ + /* (physical address) */ + __u32 mmio_len; /* Length of Memory Mapped I/O */ + __u32 accel; /* Indicate to driver which */ + /* specific chip/card we have */ + __u16 reserved[3]; /* Reserved for future compatibility */ +}; + +/* + * Interpretation of offset for color fields: All offsets are from the right, + * inside a "pixel" value, which is exactly 'bits_per_pixel' wide (means: you + * can use the offset as right argument to <<). A pixel afterwards is a bit + * stream and is written to video memory as that unmodified. + * + * For pseudocolor: offset and length should be the same for all color + * components. Offset specifies the position of the least significant bit + * of the pallette index in a pixel value. Length indicates the number + * of available palette entries (i.e. # of entries = 1 << length). + */ +struct fb_bitfield { + __u32 offset; /* beginning of bitfield */ + __u32 length; /* length of bitfield */ + __u32 msb_right; + +}; + +#define FB_NONSTD_HAM 1 /* Hold-And-Modify (HAM) */ +#define FB_NONSTD_REV_PIX_IN_B 2 /* order of pixels in each byte is reversed */ + +#define FB_ACTIVATE_NOW 0 /* set values immediately (or vbl)*/ +#define FB_ACTIVATE_NXTOPEN 1 /* activate on next open */ +#define FB_ACTIVATE_TEST 2 /* don't set, round up impossible */ +#define FB_ACTIVATE_MASK 15 + /* values */ +#define FB_ACTIVATE_VBL 16 /* activate values on next vbl */ +#define FB_CHANGE_CMAP_VBL 32 /* change colormap on vbl */ +#define FB_ACTIVATE_ALL 64 /* change all VCs on this fb */ +#define FB_ACTIVATE_FORCE 128 /* force apply even when no change*/ +#define FB_ACTIVATE_INV_MODE 256 /* invalidate videomode */ + +#define FB_SYNC_HOR_HIGH_ACT 1 /* horizontal sync high active */ +#define FB_SYNC_VERT_HIGH_ACT 2 /* vertical sync high active */ +#define FB_SYNC_EXT 4 /* external sync */ +#define FB_SYNC_COMP_HIGH_ACT 8 /* composite sync high active */ +#define FB_SYNC_BROADCAST 16 /* broadcast video timings */ + /* vtotal = 144d/288n/576i => PAL */ + /* vtotal = 121d/242n/484i => NTSC */ +#define FB_SYNC_ON_GREEN 32 /* sync on green */ + +#define FB_VMODE_NONINTERLACED 0 /* non interlaced */ +#define FB_VMODE_INTERLACED 1 /* interlaced */ +#define FB_VMODE_DOUBLE 2 /* double scan */ +#define FB_VMODE_ODD_FLD_FIRST 4 /* interlaced: top line first */ +#define FB_VMODE_MASK 255 + +#define FB_VMODE_YWRAP 256 /* ywrap instead of panning */ +#define FB_VMODE_SMOOTH_XPAN 512 /* smooth xpan possible (internally used) */ +#define FB_VMODE_CONUPDATE 512 /* don't update x/yoffset */ + +/* + * Display rotation support + */ +#define FB_ROTATE_UR 0 +#define FB_ROTATE_CW 1 +#define FB_ROTATE_UD 2 +#define FB_ROTATE_CCW 3 + +#define PICOS2KHZ(a) (1000000000UL/(a)) +#define KHZ2PICOS(a) (1000000000UL/(a)) + +struct fb_var_screeninfo { + __u32 xres; /* visible resolution */ + __u32 yres; + __u32 xres_virtual; /* virtual resolution */ + __u32 yres_virtual; + __u32 xoffset; /* offset from virtual to visible */ + __u32 yoffset; /* resolution */ + + __u32 bits_per_pixel; /* guess what */ + __u32 grayscale; /* != 0 Graylevels instead of colors */ + + struct fb_bitfield red; /* bitfield in fb mem if true color, */ + struct fb_bitfield green; /* else only length is significant */ + struct fb_bitfield blue; + struct fb_bitfield transp; /* transparency */ + + __u32 nonstd; /* != 0 Non standard pixel format */ + + __u32 activate; /* see FB_ACTIVATE_* */ + + __u32 height; /* height of picture in mm */ + __u32 width; /* width of picture in mm */ + + __u32 accel_flags; /* (OBSOLETE) see fb_info.flags */ + + /* Timing: All values in pixclocks, except pixclock (of course) */ + __u32 pixclock; /* pixel clock in ps (pico seconds) */ + __u32 left_margin; /* time from sync to picture */ + __u32 right_margin; /* time from picture to sync */ + __u32 upper_margin; /* time from sync to picture */ + __u32 lower_margin; + __u32 hsync_len; /* length of horizontal sync */ + __u32 vsync_len; /* length of vertical sync */ + __u32 sync; /* see FB_SYNC_* */ + __u32 vmode; /* see FB_VMODE_* */ + __u32 rotate; /* angle we rotate counter clockwise */ + __u32 reserved[5]; /* Reserved for future compatibility */ +}; + +struct fb_cmap { + __u32 start; /* First entry */ + __u32 len; /* Number of entries */ + __u16 *red; /* Red values */ + __u16 *green; + __u16 *blue; + __u16 *transp; /* transparency, can be NULL */ +}; + +struct fb_con2fbmap { + __u32 console; + __u32 framebuffer; +}; + +/* VESA Blanking Levels */ +#define VESA_NO_BLANKING 0 +#define VESA_VSYNC_SUSPEND 1 +#define VESA_HSYNC_SUSPEND 2 +#define VESA_POWERDOWN 3 + + +enum { + /* screen: unblanked, hsync: on, vsync: on */ + FB_BLANK_UNBLANK = VESA_NO_BLANKING, + + /* screen: blanked, hsync: on, vsync: on */ + FB_BLANK_NORMAL = VESA_NO_BLANKING + 1, + + /* screen: blanked, hsync: on, vsync: off */ + FB_BLANK_VSYNC_SUSPEND = VESA_VSYNC_SUSPEND + 1, + + /* screen: blanked, hsync: off, vsync: on */ + FB_BLANK_HSYNC_SUSPEND = VESA_HSYNC_SUSPEND + 1, + + /* screen: blanked, hsync: off, vsync: off */ + FB_BLANK_POWERDOWN = VESA_POWERDOWN + 1 +}; + +#define FB_VBLANK_VBLANKING 0x001 /* currently in a vertical blank */ +#define FB_VBLANK_HBLANKING 0x002 /* currently in a horizontal blank */ +#define FB_VBLANK_HAVE_VBLANK 0x004 /* vertical blanks can be detected */ +#define FB_VBLANK_HAVE_HBLANK 0x008 /* horizontal blanks can be detected */ +#define FB_VBLANK_HAVE_COUNT 0x010 /* global retrace counter is available */ +#define FB_VBLANK_HAVE_VCOUNT 0x020 /* the vcount field is valid */ +#define FB_VBLANK_HAVE_HCOUNT 0x040 /* the hcount field is valid */ +#define FB_VBLANK_VSYNCING 0x080 /* currently in a vsync */ +#define FB_VBLANK_HAVE_VSYNC 0x100 /* verical syncs can be detected */ + +struct fb_vblank { + __u32 flags; /* FB_VBLANK flags */ + __u32 count; /* counter of retraces since boot */ + __u32 vcount; /* current scanline position */ + __u32 hcount; /* current scandot position */ + __u32 reserved[4]; /* reserved for future compatibility */ +}; + +/* Internal HW accel */ +#define ROP_COPY 0 +#define ROP_XOR 1 + +struct fb_copyarea { + __u32 dx; + __u32 dy; + __u32 width; + __u32 height; + __u32 sx; + __u32 sy; +}; + +struct fb_fillrect { + __u32 dx; /* screen-relative */ + __u32 dy; + __u32 width; + __u32 height; + __u32 color; + __u32 rop; +}; + +struct fb_image { + __u32 dx; /* Where to place image */ + __u32 dy; + __u32 width; /* Size of image */ + __u32 height; + __u32 fg_color; /* Only used when a mono bitmap */ + __u32 bg_color; + __u8 depth; /* Depth of the image */ + const char *data; /* Pointer to image data */ + struct fb_cmap cmap; /* color map info */ +}; + +/* + * hardware cursor control + */ + +#define FB_CUR_SETIMAGE 0x01 +#define FB_CUR_SETPOS 0x02 +#define FB_CUR_SETHOT 0x04 +#define FB_CUR_SETCMAP 0x08 +#define FB_CUR_SETSHAPE 0x10 +#define FB_CUR_SETSIZE 0x20 +#define FB_CUR_SETALL 0xFF + +struct fbcurpos { + __u16 x, y; +}; + +struct fb_cursor { + __u16 set; /* what to set */ + __u16 enable; /* cursor on/off */ + __u16 rop; /* bitop operation */ + const char *mask; /* cursor mask bits */ + struct fbcurpos hot; /* cursor hot spot */ + struct fb_image image; /* Cursor image */ +}; + +#ifdef CONFIG_FB_BACKLIGHT +/* Settings for the generic backlight code */ +#define FB_BACKLIGHT_LEVELS 128 +#define FB_BACKLIGHT_MAX 0xFF +#endif + +#ifdef __KERNEL__ + +struct vm_area_struct; +struct fb_info; +struct device; +struct file; + +/* Definitions below are used in the parsed monitor specs */ +#define FB_DPMS_ACTIVE_OFF 1 +#define FB_DPMS_SUSPEND 2 +#define FB_DPMS_STANDBY 4 + +#define FB_DISP_DDI 1 +#define FB_DISP_ANA_700_300 2 +#define FB_DISP_ANA_714_286 4 +#define FB_DISP_ANA_1000_400 8 +#define FB_DISP_ANA_700_000 16 + +#define FB_DISP_MONO 32 +#define FB_DISP_RGB 64 +#define FB_DISP_MULTI 128 +#define FB_DISP_UNKNOWN 256 + +#define FB_SIGNAL_NONE 0 +#define FB_SIGNAL_BLANK_BLANK 1 +#define FB_SIGNAL_SEPARATE 2 +#define FB_SIGNAL_COMPOSITE 4 +#define FB_SIGNAL_SYNC_ON_GREEN 8 +#define FB_SIGNAL_SERRATION_ON 16 + +#define FB_MISC_PRIM_COLOR 1 +#define FB_MISC_1ST_DETAIL 2 /* First Detailed Timing is preferred */ +struct fb_chroma { + __u32 redx; /* in fraction of 1024 */ + __u32 greenx; + __u32 bluex; + __u32 whitex; + __u32 redy; + __u32 greeny; + __u32 bluey; + __u32 whitey; +}; + +struct fb_monspecs { + struct fb_chroma chroma; + struct fb_videomode *modedb; /* mode database */ + __u8 manufacturer[4]; /* Manufacturer */ + __u8 monitor[14]; /* Monitor String */ + __u8 serial_no[14]; /* Serial Number */ + __u8 ascii[14]; /* ? */ + __u32 modedb_len; /* mode database length */ + __u32 model; /* Monitor Model */ + __u32 serial; /* Serial Number - Integer */ + __u32 year; /* Year manufactured */ + __u32 week; /* Week Manufactured */ + __u32 hfmin; /* hfreq lower limit (Hz) */ + __u32 hfmax; /* hfreq upper limit (Hz) */ + __u32 dclkmin; /* pixelclock lower limit (Hz) */ + __u32 dclkmax; /* pixelclock upper limit (Hz) */ + __u16 input; /* display type - see FB_DISP_* */ + __u16 dpms; /* DPMS support - see FB_DPMS_ */ + __u16 signal; /* Signal Type - see FB_SIGNAL_* */ + __u16 vfmin; /* vfreq lower limit (Hz) */ + __u16 vfmax; /* vfreq upper limit (Hz) */ + __u16 gamma; /* Gamma - in fractions of 100 */ + __u16 gtf : 1; /* supports GTF */ + __u16 misc; /* Misc flags - see FB_MISC_* */ + __u8 version; /* EDID version... */ + __u8 revision; /* ...and revision */ + __u8 max_x; /* Maximum horizontal size (cm) */ + __u8 max_y; /* Maximum vertical size (cm) */ +}; + +struct fb_cmap_user { + __u32 start; /* First entry */ + __u32 len; /* Number of entries */ + __u16 *red; /* Red values */ + __u16 *green; + __u16 *blue; + __u16 *transp; /* transparency, can be NULL */ +}; + +struct fb_image_user { + __u32 dx; /* Where to place image */ + __u32 dy; + __u32 width; /* Size of image */ + __u32 height; + __u32 fg_color; /* Only used when a mono bitmap */ + __u32 bg_color; + __u8 depth; /* Depth of the image */ + const char *data; /* Pointer to image data */ + struct fb_cmap_user cmap; /* color map info */ +}; + +struct fb_cursor_user { + __u16 set; /* what to set */ + __u16 enable; /* cursor on/off */ + __u16 rop; /* bitop operation */ + const char *mask; /* cursor mask bits */ + struct fbcurpos hot; /* cursor hot spot */ + struct fb_image_user image; /* Cursor image */ +}; + +/* + * Register/unregister for framebuffer events + */ + +/* The resolution of the passed in fb_info about to change */ +#define FB_EVENT_MODE_CHANGE 0x01 +/* The display on this fb_info is beeing suspended, no access to the + * framebuffer is allowed any more after that call returns + */ +#define FB_EVENT_SUSPEND 0x02 +/* The display on this fb_info was resumed, you can restore the display + * if you own it + */ +#define FB_EVENT_RESUME 0x03 +/* An entry from the modelist was removed */ +#define FB_EVENT_MODE_DELETE 0x04 +/* A driver registered itself */ +#define FB_EVENT_FB_REGISTERED 0x05 +/* A driver unregistered itself */ +#define FB_EVENT_FB_UNREGISTERED 0x06 +/* CONSOLE-SPECIFIC: get console to framebuffer mapping */ +#define FB_EVENT_GET_CONSOLE_MAP 0x07 +/* CONSOLE-SPECIFIC: set console to framebuffer mapping */ +#define FB_EVENT_SET_CONSOLE_MAP 0x08 +/* A hardware display blank change occured */ +#define FB_EVENT_BLANK 0x09 +/* Private modelist is to be replaced */ +#define FB_EVENT_NEW_MODELIST 0x0A +/* The resolution of the passed in fb_info about to change and + all vc's should be changed */ +#define FB_EVENT_MODE_CHANGE_ALL 0x0B +/* A software display blank change occured */ +#define FB_EVENT_CONBLANK 0x0C +/* Get drawing requirements */ +#define FB_EVENT_GET_REQ 0x0D +/* Unbind from the console if possible */ +#define FB_EVENT_FB_UNBIND 0x0E + +struct fb_event { + struct fb_info *info; + void *data; +}; + +struct fb_blit_caps { + u32 x; + u32 y; + u32 len; + u32 flags; +}; + +/* + * Pixmap structure definition + * + * The purpose of this structure is to translate data + * from the hardware independent format of fbdev to what + * format the hardware needs. + */ + +#define FB_PIXMAP_DEFAULT 1 /* used internally by fbcon */ +#define FB_PIXMAP_SYSTEM 2 /* memory is in system RAM */ +#define FB_PIXMAP_IO 4 /* memory is iomapped */ +#define FB_PIXMAP_SYNC 256 /* set if GPU can DMA */ + +struct fb_pixmap { + u8 *addr; /* pointer to memory */ + u32 size; /* size of buffer in bytes */ + u32 offset; /* current offset to buffer */ + u32 buf_align; /* byte alignment of each bitmap */ + u32 scan_align; /* alignment per scanline */ + u32 access_align; /* alignment per read/write (bits) */ + u32 flags; /* see FB_PIXMAP_* */ + u32 blit_x; /* supported bit block dimensions (1-32)*/ + u32 blit_y; /* Format: blit_x = 1 << (width - 1) */ + /* blit_y = 1 << (height - 1) */ + /* if 0, will be set to 0xffffffff (all)*/ + /* access methods */ + void (*writeio)(struct fb_info *info, void *dst, void *src, unsigned int size); + void (*readio) (struct fb_info *info, void *dst, void *src, unsigned int size); +}; + +#ifdef CONFIG_FB_DEFERRED_IO +struct fb_deferred_io { + /* delay between mkwrite and deferred handler */ + unsigned long delay; + struct mutex lock; /* mutex that protects the page list */ + struct list_head pagelist; /* list of touched pages */ + /* callback */ + void (*deferred_io)(struct fb_info *info, struct list_head *pagelist); +}; +#endif + +/* FBINFO_* = fb_info.flags bit flags */ +#define FBINFO_MODULE 0x0001 /* Low-level driver is a module */ +#define FBINFO_HWACCEL_DISABLED 0x0002 + /* When FBINFO_HWACCEL_DISABLED is set: + * Hardware acceleration is turned off. Software implementations + * of required functions (copyarea(), fillrect(), and imageblit()) + * takes over; acceleration engine should be in a quiescent state */ + +/* hints */ +#define FBINFO_PARTIAL_PAN_OK 0x0040 /* otw use pan only for double-buffering */ +#define FBINFO_READS_FAST 0x0080 /* soft-copy faster than rendering */ + +/* + * A driver may set this flag to indicate that it does want a set_par to be + * called every time when fbcon_switch is executed. The advantage is that with + * this flag set you can really be sure that set_par is always called before + * any of the functions dependant on the correct hardware state or altering + * that state, even if you are using some broken X releases. The disadvantage + * is that it introduces unwanted delays to every console switch if set_par + * is slow. It is a good idea to try this flag in the drivers initialization + * code whenever there is a bug report related to switching between X and the + * framebuffer console. + */ +#define FBINFO_MISC_ALWAYS_SETPAR 0x40000 + +/* + * Host and GPU endianness differ. + */ +#define FBINFO_FOREIGN_ENDIAN 0x100000 +/* + * Big endian math. This is the same flags as above, but with different + * meaning, it is set by the fb subsystem depending FOREIGN_ENDIAN flag + * and host endianness. Drivers should not use this flag. + */ +#define FBINFO_BE_MATH 0x100000 + +struct fb_info { + int node; + int flags; + struct fb_var_screeninfo var; /* Current var */ + struct fb_fix_screeninfo fix; /* Current fix */ + struct fb_monspecs monspecs; /* Current Monitor specs */ + struct fb_pixmap pixmap; /* Image hardware mapper */ + struct fb_pixmap sprite; /* Cursor hardware mapper */ + struct fb_cmap cmap; /* Current cmap */ + struct list_head modelist; /* mode list */ + struct fb_videomode *mode; /* current mode */ + + char *screen_base; /* Virtual address */ + unsigned long screen_size; /* Amount of ioremapped VRAM or 0 */ + void *pseudo_palette; /* Fake palette of 16 colors */ +#define FBINFO_STATE_RUNNING 0 +#define FBINFO_STATE_SUSPENDED 1 + u32 state; /* Hardware state i.e suspend */ + void *fbcon_par; /* fbcon use-only private area */ + /* From here on everything is device dependent */ + void *par; +}; + +#define FBINFO_DEFAULT 0 + +#define FBINFO_FLAG_MODULE FBINFO_MODULE +#define FBINFO_FLAG_DEFAULT FBINFO_DEFAULT + +/* This will go away */ +#if defined(__sparc__) + +/* We map all of our framebuffers such that big-endian accesses + * are what we want, so the following is sufficient. + */ + +/* This will go away */ +#define fb_readb sbus_readb +#define fb_readw sbus_readw +#define fb_readl sbus_readl +#define fb_readq sbus_readq +#define fb_writeb sbus_writeb +#define fb_writew sbus_writew +#define fb_writel sbus_writel +#define fb_writeq sbus_writeq +#define fb_memset sbus_memset_io + +#elif defined(__i386__) || defined(__alpha__) || defined(__x86_64__) || defined(__hppa__) || defined(__sh__) || defined(__powerpc__) || defined(__avr32__) || defined(__bfin__) + +#define fb_readb __raw_readb +#define fb_readw __raw_readw +#define fb_readl __raw_readl +#define fb_readq __raw_readq +#define fb_writeb __raw_writeb +#define fb_writew __raw_writew +#define fb_writel __raw_writel +#define fb_writeq __raw_writeq +#define fb_memset memset_io + +#else + +#define fb_readb(addr) (*(volatile u8 *) (addr)) +#define fb_readw(addr) (*(volatile u16 *) (addr)) +#define fb_readl(addr) (*(volatile u32 *) (addr)) +#define fb_readq(addr) (*(volatile u64 *) (addr)) +#define fb_writeb(b,addr) (*(volatile u8 *) (addr) = (b)) +#define fb_writew(b,addr) (*(volatile u16 *) (addr) = (b)) +#define fb_writel(b,addr) (*(volatile u32 *) (addr) = (b)) +#define fb_writeq(b,addr) (*(volatile u64 *) (addr) = (b)) +#define fb_memset memset + +#endif + +#define FB_LEFT_POS(p, bpp) (fb_be_math(p) ? (32 - (bpp)) : 0) +#define FB_SHIFT_HIGH(p, val, bits) (fb_be_math(p) ? (val) >> (bits) : \ + (val) << (bits)) +#define FB_SHIFT_LOW(p, val, bits) (fb_be_math(p) ? (val) << (bits) : \ + (val) >> (bits)) +/* drivers/video/fbmon.c */ +#define FB_MAXTIMINGS 0 +#define FB_VSYNCTIMINGS 1 +#define FB_HSYNCTIMINGS 2 +#define FB_DCLKTIMINGS 3 +#define FB_IGNOREMON 0x100 + +#define FB_MODE_IS_UNKNOWN 0 +#define FB_MODE_IS_DETAILED 1 +#define FB_MODE_IS_STANDARD 2 +#define FB_MODE_IS_VESA 4 +#define FB_MODE_IS_CALCULATED 8 +#define FB_MODE_IS_FIRST 16 +#define FB_MODE_IS_FROM_VAR 32 + + +/* drivers/video/fbcmap.c */ + +extern int fb_alloc_cmap(struct fb_cmap *cmap, int len, int transp); +extern void fb_dealloc_cmap(struct fb_cmap *cmap); +extern int fb_copy_cmap(const struct fb_cmap *from, struct fb_cmap *to); +extern int fb_cmap_to_user(const struct fb_cmap *from, struct fb_cmap_user *to); +extern int fb_set_cmap(struct fb_cmap *cmap, struct fb_info *fb_info); +extern int fb_set_user_cmap(struct fb_cmap_user *cmap, struct fb_info *fb_info); +extern const struct fb_cmap *fb_default_cmap(int len); +extern void fb_invert_cmaps(void); + +struct fb_videomode { + const char *name; /* optional */ + u32 refresh; /* optional */ + u32 xres; + u32 yres; + u32 pixclock; + u32 left_margin; + u32 right_margin; + u32 upper_margin; + u32 lower_margin; + u32 hsync_len; + u32 vsync_len; + u32 sync; + u32 vmode; + u32 flag; +}; + +#endif /* __KERNEL__ */ + +#endif /* _LINUX_FB_H */ diff --git a/sps2_basement/hardware/gs/gif/gif.c b/sps2_basement/hardware/gs/gif/gif.c new file mode 100644 index 0000000..b24f304 --- /dev/null +++ b/sps2_basement/hardware/gs/gif/gif.c @@ -0,0 +1,66 @@ +#include "gif.h" +#include "../../ee/dmac/dma.h" + +#define DMA_SET_MADR(ADDR,SPR) \ + (uint32_t)(((uint32_t)ADDR) & 0x7FFFFFFF) << 0 | (uint32_t)((SPR) & 0x00000001) << 31 + +#define DMA_SET_TADR(ADDR,SPR) \ + (uint32_t)(((uint32_t)ADDR) & 0x7FFFFFFF) << 0 | (uint32_t)((SPR) & 0x00000001) << 31 + +#define DMA_SET_ASR0(ADDR,SPR) \ + (uint32_t)(((uint32_t)ADDR) & 0x7FFFFFFF) << 0 | (uint32_t)((SPR) & 0x00000001) << 31 + +#define DMA_SET_ASR1(ADDR,SPR) \ + (uint32_t)(((uint32_t)ADDR) & 0x7FFFFFFF) << 0 | (uint32_t)((SPR) & 0x00000001) << 31 + +#define DMA_SET_SADR(ADDR) (uint32_t)(((uint32_t)ADDR) & 0x00003FFF) + +#define DMA_SET_QWC(QWC) (uint32_t)((QWC) & 0x0000FFFF) + +#define DMA_SET_SIZE(A) \ +(uint32_t)(A & 0x0000FFFF) << 0 + +/** Per-dma channel registers */ +#define DMA_SET_CHCR(DIR,MODE,ASP,TTE,TIE,STR,TAG) \ + (uint32_t)((DIR) & 0x00000001) << 0 | (uint32_t)((MODE) & 0x00000003) << 2 | \ + (uint32_t)((ASP) & 0x00000003) << 4 | (uint32_t)((TTE ) & 0x00000001) << 6 | \ + (uint32_t)((TIE) & 0x00000001) << 7 | (uint32_t)((STR ) & 0x00000001) << 8 | \ + (uint32_t)((TAG) & 0x0000FFFF) << 16 + + + +int _dma_gif_init(){ + // Reset the channel registers. + *GIF_CHCR = 0x00000000; + *GIF_MADR = 0x00000000; + *GIF_SIZE = 0x00000000; + *GIF_TADR = 0x00000000; + *GIF_ASR0 = 0x00000000; + *GIF_ASR1 = 0x00000000; + *GIF_SADR = 0x00000000; + // End function. + return 0; +}; + +int _dma_gif_wait( int timeout ){ + // Wait until the channel is available. + while( ( *GIF_CHCR ) & 0x00000100 ){ + // Check for a timeout. + if( timeout-- < 1 ){ return -1; } + } + // End function. + return 0; +}; + +int _dma_gif_send(void *data, int size) { + // Wait for the DMA to be clear. + if( dma_channel_wait( DMA_CHANNEL_GIF, 100000) == -1) { return -1; } + // Flush the cache. (FlushCache(0) - Syscall 0x64) + asm("li $3, 0x64\n" "li $4, 0x00\n" "syscall\n" "nop\n"); + // Set up the transfer and send it off. + *GIF_SIZE = DMA_SET_SIZE( size ); + *GIF_MADR = DMA_SET_MADR( data, 0); + *GIF_CHCR = DMA_SET_CHCR(1, 0, 0, 0, 0, 1, 0); + // End function. + return 0; +}; diff --git a/sps2_basement/hardware/gs/gif/gif.h b/sps2_basement/hardware/gs/gif/gif.h new file mode 100644 index 0000000..d874c1a --- /dev/null +++ b/sps2_basement/hardware/gs/gif/gif.h @@ -0,0 +1,15 @@ +#ifndef __SPS2_GIF_OPERATION_HEADER__ +#define __SPS2_GIF_OPERATION_HEADER__ + +#define GIF_CHCR ((volatile uint32_t *)0x1000A000) +#define GIF_MADR ((volatile uint32_t *)0x1000A010) +#define GIF_SIZE ((volatile uint32_t *)0x1000A020) +#define GIF_TADR ((volatile uint32_t *)0x1000A030) +#define GIF_ASR0 ((volatile uint32_t *)0x1000A040) +#define GIF_ASR1 ((volatile uint32_t *)0x1000A050) +#define GIF_SADR ((volatile uint32_t *)0x1000A080) + + + + +#endif diff --git a/sps2_basement/hardware/linkfile b/sps2_basement/hardware/linkfile new file mode 100644 index 0000000..c07af94 --- /dev/null +++ b/sps2_basement/hardware/linkfile @@ -0,0 +1,52 @@ +_stack_size = 0x80000; +_heap_size = 1024*1024*10; + +ENTRY(_start); +SECTIONS { + + .text 0x400000 : { + *(.rodata) + *(.text) + } + .reginfo ALIGN(128) : { + *(.reginfo) + } + .data ALIGN(128) : { + *(.data) + } + .rdata ALIGN(128) : { + *(.rdata) + } + _gp = ALIGN(128) + 0x7ff0; + .lit4 ALIGN(128) : { + *(.lit4) + } + .lit8 ALIGN(128) : { + *(.lit8) + } + .sdata ALIGN(128) : { + *(.sdata) + } + + .sbss ALIGN(128) (NOLOAD) : { /* uninitialized data */ + _fbss = . ; + *(.scommon) + *(.sbss) + } + .bss ALIGN(128) (NOLOAD) : { /* uninitialized data */ + *(.bss) + } + .COMMON ALIGN(128) (NOLOAD) : { /* uninitialized data */ + *(COMMON) + } + _end_bss = . - 4; + _stack = .; + . += _stack_size ; + _end_stack = . - 8*5; + _end = . ; + __lc_bh = . ; + . += _heap_size ; + __lc_eh = .; + +} + diff --git a/sps2_basement/hardware/mem/Makefile b/sps2_basement/hardware/mem/Makefile new file mode 100644 index 0000000..6193d23 --- /dev/null +++ b/sps2_basement/hardware/mem/Makefile @@ -0,0 +1,12 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +SUBDIRS = alloc mtapman rmtapman padman rpadman rmman sio2man rsio2man iomanx iopmgr sbusintr siftoo sio2log + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/Rules.make diff --git a/sps2_basement/hardware/mem/alloc/Makefile b/sps2_basement/hardware/mem/alloc/Makefile new file mode 100644 index 0000000..2427ad7 --- /dev/null +++ b/sps2_basement/hardware/mem/alloc/Makefile @@ -0,0 +1,14 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_OBJS = alloc.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/mem/alloc/include/alloc.h b/sps2_basement/hardware/mem/alloc/include/alloc.h new file mode 100644 index 0000000..a750a46 --- /dev/null +++ b/sps2_basement/hardware/mem/alloc/include/alloc.h @@ -0,0 +1,45 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Basic alloc library + */ + +#ifndef __ALLOC_H__ +#define __ALLOC_H__ + +#include +#include + +void * malloc(size_t size); +void * realloc(void * ptr, size_t size); +void free(void * ptr); +void * calloc(size_t n, size_t size); +void * memalign(size_t align, size_t size); +void * __mem_walk_begin(); +void __mem_walk_read(void * token, u32 * size, void ** ptr, int * valid); +void * __mem_walk_inc(void * token); +int __mem_walk_end(void * token); + +#define alloc_IMPORTS_start DECLARE_IMPORT_TABLE(alloc, 1, 1) +#define alloc_IMPORTS_end END_IMPORT_TABLE + +#define I_malloc DECLARE_IMPORT(4, malloc) +#define I_realloc DECLARE_IMPORT(5, realloc) +#define I_free DECLARE_IMPORT(6, free) +#define I_calloc DECLARE_IMPORT(7, calloc) +#define I_memalign DECLARE_IMPORT(8, memalign) +#define I___mem_walk_begin DECLARE_IMPORT(9, __mem_walk_begin) +#define I___mem_walk_read DECLARE_IMPORT(10, __mem_walk_read) +#define I___mem_walk_inc DECLARE_IMPORT(11, __mem_walk_inc) +#define I___mem_walk_end DECLARE_IMPORT(12, __mem_walk_end) + +#endif /* __ALLOC_H__ */ diff --git a/sps2_basement/hardware/mem/alloc/src/alloc.c b/sps2_basement/hardware/mem/alloc/src/alloc.c new file mode 100644 index 0000000..d9718f1 --- /dev/null +++ b/sps2_basement/hardware/mem/alloc/src/alloc.c @@ -0,0 +1,457 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Copyright (c) 2004 adresd +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Basic alloc library + */ + +#include + +#include "types.h" +#include "defs.h" +#include "alloc.h" +#include "irx_imports.h" + + +#define MODNAME "alloc" +IRX_ID("Basic alloc library", 1, 1); + +extern struct irx_export_table _exp_alloc; + +static vs32 alloc_sema = -1; + +#define DEFAULT_HEAP_SIZE 128 * 1024 + +u32 heap_size = DEFAULT_HEAP_SIZE; +static u8 * heap_start, * heap_end, * _heap_ptr; + +static void alloc_lock() { + if (alloc_sema >= 0) { + WaitSema(alloc_sema); + } +} + +static void alloc_unlock() { + if (alloc_sema >= 0) { + SignalSema(alloc_sema); + } +} + +int _start(int argc, char **argv) +{ + iop_sema_t sem_info; + + if (RegisterLibraryEntries(&_exp_alloc) != 0) + return 1; + + // check arguments for a heap_size parameter. + if (argc > 1) { + heap_size = strtoul(argv[1], NULL, 0); + } + + if (!(heap_start = AllocSysMemory(ALLOC_FIRST, heap_size, NULL))) + return -1; + heap_end = heap_start + heap_size; + _heap_ptr = heap_start; + + sem_info.attr = 1; + sem_info.option = 1; + sem_info.initial = 1; + sem_info.max = 1; + + alloc_sema = CreateSema(&sem_info); + + return 0; +} + + +int shutdown() +{ + if (alloc_sema >= 0) { + DeleteSema(alloc_sema); + } + + FreeSysMemory(heap_start); + + return 0; +} + +/** Use this to set the default malloc() alignment. */ +#define DEFAULT_ALIGNMENT 16 + +#ifndef ALIGN +#define ALIGN(x, align) (((x)+((align)-1))&~((align)-1)) +#endif + +/* _heap_mem_block_header structure. */ +typedef struct _heap_mem_header { + void * ptr; + size_t size; + struct _heap_mem_header * prev; + struct _heap_mem_header * next; +} heap_mem_header_t; + +static void * __alloc_heap_base = NULL; +static heap_mem_header_t *__alloc_heap_head = NULL; +static heap_mem_header_t *__alloc_heap_tail = NULL; + +static void * alloc_sbrk(size_t increment) +{ + u8 *mp, *ret = (void *)-1; + + if (increment == 0) + return _heap_ptr; + + /* If the area we want to allocated is past the end of our heap, we have a problem. */ + mp = _heap_ptr + increment; + if (mp <= heap_end) { + ret = _heap_ptr; + _heap_ptr = mp; + } + + return ret; +} + +/** Find the lowest block that we can allocate AFTER, returning NULL if there are none. */ +static heap_mem_header_t * _heap_mem_fit(heap_mem_header_t *head, size_t size) +{ + heap_mem_header_t *prev_mem = head; + u32 prev_top, next_bot; + + while (prev_mem != NULL) { + if (prev_mem->next != NULL) { + prev_top = (u32)prev_mem->ptr + prev_mem->size; + next_bot = (u32)prev_mem->next - prev_top; + if (next_bot >= size) + return prev_mem; + } + + prev_mem = prev_mem->next; + } + + return prev_mem; +} + +void * malloc(size_t size) +{ + void *ptr = NULL, *mem_ptr; + heap_mem_header_t *new_mem, *prev_mem; + size_t mem_sz, heap_align_bytes; + + mem_sz = size + sizeof(heap_mem_header_t); + + if ((mem_sz & (DEFAULT_ALIGNMENT - 1)) != 0) + mem_sz = ALIGN(mem_sz, DEFAULT_ALIGNMENT); + + alloc_lock(); + + /* If we don't have any allocated blocks, reserve the first block from + the OS and initialize __alloc_heap_tail. */ + if (__alloc_heap_head == NULL) { + /* Align the bottom of the heap to our default alignment. */ + if (__alloc_heap_base == NULL) { + heap_align_bytes = (u32)alloc_sbrk(0) & (DEFAULT_ALIGNMENT - 1); + alloc_sbrk(heap_align_bytes); + __alloc_heap_base = alloc_sbrk(0); + } + + /* Allocate the physical heap and setup the head block. */ + if ((mem_ptr = alloc_sbrk(mem_sz)) == (void *)-1) + return ptr; /* NULL */ + + ptr = (void *)((u32)mem_ptr + sizeof(heap_mem_header_t)); + + __alloc_heap_head = (heap_mem_header_t *)mem_ptr; + __alloc_heap_head->ptr = ptr; + __alloc_heap_head->size = mem_sz - sizeof(heap_mem_header_t); + __alloc_heap_head->prev = NULL; + __alloc_heap_head->next = NULL; + + __alloc_heap_tail = __alloc_heap_head; + + alloc_unlock(); + return ptr; + } + + /* Check to see if there's free space at the bottom of the heap. */ + if ((__alloc_heap_base + mem_sz) < (void *)__alloc_heap_head) { + new_mem = (heap_mem_header_t *)__alloc_heap_base; + ptr = (void *)((u32)new_mem + sizeof(heap_mem_header_t)); + + new_mem->ptr = ptr; + new_mem->size = mem_sz - sizeof(heap_mem_header_t); + new_mem->prev = NULL; + new_mem->next = __alloc_heap_head; + new_mem->next->prev = new_mem; + __alloc_heap_head = new_mem; + + alloc_unlock(); + return ptr; + } + + /* See if we can allocate the block without extending the heap. */ + prev_mem = _heap_mem_fit(__alloc_heap_head, mem_sz); + if (prev_mem != NULL) { + new_mem = (heap_mem_header_t *)((u32)prev_mem->ptr + prev_mem->size); + ptr = (void *)((u32)new_mem + sizeof(heap_mem_header_t)); + + new_mem->ptr = ptr; + new_mem->size = mem_sz - sizeof(heap_mem_header_t); + new_mem->prev = prev_mem; + new_mem->next = prev_mem->next; + new_mem->next->prev = new_mem; + prev_mem->next = new_mem; + + alloc_unlock(); + return ptr; + } + + /* Extend the heap, but make certain the block is inserted in + order. */ + if ((mem_ptr = alloc_sbrk(mem_sz)) == (void *)-1) { + alloc_unlock(); + return ptr; /* NULL */ + } + + ptr = (void *)((u32)mem_ptr + sizeof(heap_mem_header_t)); + + new_mem = (heap_mem_header_t *)mem_ptr; + new_mem->ptr = ptr; + new_mem->size = mem_sz - sizeof(heap_mem_header_t); + new_mem->prev = __alloc_heap_tail; + new_mem->next = NULL; + + __alloc_heap_tail->next = new_mem; + __alloc_heap_tail = new_mem; + + alloc_unlock(); + return ptr; +} + +void * realloc(void *ptr, size_t size) +{ + heap_mem_header_t *prev_mem; + void *new_ptr = NULL; + + if (!size && ptr != NULL) { + free(ptr); + return new_ptr; + } + + if (ptr == NULL) + return malloc(size); + + if ((size & (DEFAULT_ALIGNMENT - 1)) != 0) + size = ALIGN(size, DEFAULT_ALIGNMENT); + + alloc_lock(); + prev_mem = (heap_mem_header_t *)((u32)ptr - sizeof(heap_mem_header_t)); + + + /* Don't do anything if asked for same sized block. */ + /* If the new size is shorter, let's just shorten the block. */ + if (prev_mem->size >= size) { + /* However, if this is the last block, we have to shrink the heap. */ + if (!prev_mem->next) + alloc_sbrk(ptr + size - alloc_sbrk(0)); + prev_mem->size = size; + + alloc_unlock(); + return ptr; + } + + + /* We are asked for a larger block of memory. */ + + /* Are we the last memory block ? */ + if (!prev_mem->next) { + /* Yes, let's just extend the heap then. */ + if (alloc_sbrk(size - prev_mem->size) == (void*) -1) + return NULL; + prev_mem->size = size; + + alloc_unlock(); + return ptr; + } + + /* Is the next block far enough so we can extend the current block ? */ + if ((prev_mem->next->ptr - ptr) > size) { + prev_mem->size = size; + + alloc_unlock(); + return ptr; + } + + alloc_unlock(); + + /* We got out of luck, let's allocate a new block of memory. */ + if ((new_ptr = malloc(size)) == NULL) + return new_ptr; + + /* New block is larger, we only copy the old data. */ + memcpy(new_ptr, ptr, prev_mem->size); + + free(ptr); + return new_ptr; +} + +void * calloc(size_t n, size_t size) +{ + void *ptr = NULL; + size_t sz = n * size; + + if ((ptr = malloc(sz)) == NULL) + return ptr; + + memset(ptr, 0, sz); + return ptr; +} + +void * memalign(size_t align, size_t size) +{ + heap_mem_header_t new_mem; + heap_mem_header_t *cur_mem; + heap_mem_header_t *old_mem; + void *ptr = NULL; + + if (align <= DEFAULT_ALIGNMENT) + return malloc(size); + + /* Allocate with extra alignment bytes just in case it isn't aligned + properly by malloc. */ + if ((ptr = malloc(size + align)) == NULL) + return ptr; /* NULL */ + + /* If malloc returned it aligned for us we're fine. */ + if (((u32)ptr & (align - 1)) == 0) + return ptr; + + alloc_lock(); + cur_mem = (heap_mem_header_t *)((u32)ptr - sizeof(heap_mem_header_t)); + cur_mem->size -= align; + + /* Otherwise, align the pointer and fixup our hearder accordingly. */ + ptr = (void *)ALIGN((u32)ptr, align); + + old_mem = cur_mem; + + /* Copy the heap_mem_header_t locally, before repositioning (to make + sure we don't overwrite ourselves. */ + memcpy(&new_mem, cur_mem, sizeof(heap_mem_header_t)); + cur_mem = (heap_mem_header_t *)((u32)ptr - sizeof(heap_mem_header_t)); + memcpy(cur_mem, &new_mem, sizeof(heap_mem_header_t)); + + if (cur_mem->prev) + cur_mem->prev->next = cur_mem; + if (cur_mem->next) + cur_mem->next->prev = cur_mem; + + if (__alloc_heap_head == old_mem) + __alloc_heap_head = cur_mem; + + if (__alloc_heap_tail == old_mem) + __alloc_heap_tail = cur_mem; + + cur_mem->ptr = ptr; + + alloc_unlock(); + return ptr; +} + +void free(void *ptr) +{ + heap_mem_header_t *cur; + void *heap_top; + size_t size; + + if (!ptr) + return; + + alloc_lock(); + + if (!__alloc_heap_head) { + alloc_unlock(); + return; + } + + + /* Freeing the head pointer is a special case. */ + if (ptr == __alloc_heap_head->ptr) { + size = __alloc_heap_head->size + + (size_t)(__alloc_heap_head->ptr - (void *)__alloc_heap_head); + + __alloc_heap_head = __alloc_heap_head->next; + + if (__alloc_heap_head != NULL) { + __alloc_heap_head->prev = NULL; + } else { + __alloc_heap_tail = NULL; + + alloc_sbrk(-size); + } + + alloc_unlock(); + return; + } + + cur = __alloc_heap_head; + while (ptr != cur->ptr) { + /* ptr isn't in our list */ + if (cur->next == NULL) { + alloc_unlock(); + return; + } + + cur = cur->next; + } + + /* Deallocate the block. */ + if (cur->next != NULL) { + cur->next->prev = cur->prev; + } else { + /* If this block was the last one in the list, shrink the heap. */ + __alloc_heap_tail = cur->prev; + + /* We need to free (heap top) - (prev->ptr + prev->size), or else + we'll end up with an unallocatable block of heap. */ + heap_top = alloc_sbrk(0); + size = (u32)heap_top - (u32)(cur->prev->ptr + cur->prev->size); + alloc_sbrk(-size); + } + + cur->prev->next = cur->next; + + alloc_unlock(); +} + +void * __mem_walk_begin() { + return __alloc_heap_head; +} + +void __mem_walk_read(void * token, u32 * size, void ** ptr, int * valid) { + heap_mem_header_t * cur = (heap_mem_header_t *) token; + + *valid = 1; + + *size = cur->size; + *ptr = cur->ptr; +} + +void * __mem_walk_inc(void * token) { + heap_mem_header_t * cur = (heap_mem_header_t *) token; + + return cur->next; +} + +int __mem_walk_end(void * token) { + return token == NULL; +} diff --git a/sps2_basement/hardware/mem/alloc/src/exports.tab b/sps2_basement/hardware/mem/alloc/src/exports.tab new file mode 100644 index 0000000..7be304d --- /dev/null +++ b/sps2_basement/hardware/mem/alloc/src/exports.tab @@ -0,0 +1,18 @@ +DECLARE_EXPORT_TABLE(alloc, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(shutdown) + DECLARE_EXPORT(_retonly) + + DECLARE_EXPORT(malloc) +/*05*/ DECLARE_EXPORT(realloc) + DECLARE_EXPORT(free) + DECLARE_EXPORT(calloc) + DECLARE_EXPORT(memalign) + DECLARE_EXPORT(__mem_walk_begin) +/*10*/ DECLARE_EXPORT(__mem_walk_read) + DECLARE_EXPORT(__mem_walk_inc) + DECLARE_EXPORT(__mem_walk_end) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/mem/alloc/src/imports.lst b/sps2_basement/hardware/mem/alloc/src/imports.lst new file mode 100644 index 0000000..c5d2d19 --- /dev/null +++ b/sps2_basement/hardware/mem/alloc/src/imports.lst @@ -0,0 +1,21 @@ +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end + +sysclib_IMPORTS_start +I_memcpy +I_memset +I_strtoul +sysclib_IMPORTS_end + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +sysmem_IMPORTS_end diff --git a/sps2_basement/hardware/mem/alloc/src/irx_imports.h b/sps2_basement/hardware/mem/alloc/src/irx_imports.h new file mode 100644 index 0000000..51fa919 --- /dev/null +++ b/sps2_basement/hardware/mem/alloc/src/irx_imports.h @@ -0,0 +1,24 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "loadcore.h" +#include "sysmem.h" +#include "sysclib.h" +#include "thsemap.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/mem/iomanx/Makefile b/sps2_basement/hardware/mem/iomanx/Makefile new file mode 100644 index 0000000..7cebabc --- /dev/null +++ b/sps2_basement/hardware/mem/iomanx/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN ?= iomanX.irx + +IOP_OBJS = iomanX.o ioman_sbv.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/mem/iomanx/src/exports.tab b/sps2_basement/hardware/mem/iomanx/src/exports.tab new file mode 100644 index 0000000..0dc6d0e --- /dev/null +++ b/sps2_basement/hardware/mem/iomanx/src/exports.tab @@ -0,0 +1,41 @@ + +DECLARE_EXPORT_TABLE(iomanx, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(shutdown) + DECLARE_EXPORT(GetDeviceList) + + DECLARE_EXPORT(open) +/*05*/ DECLARE_EXPORT(close) + DECLARE_EXPORT(read) + DECLARE_EXPORT(write) + DECLARE_EXPORT(lseek) + DECLARE_EXPORT(ioctl) +/*10*/ DECLARE_EXPORT(remove) + DECLARE_EXPORT(mkdir) + DECLARE_EXPORT(rmdir) + DECLARE_EXPORT(dopen) + DECLARE_EXPORT(close) /* close() handles dopen() too. */ +/*15*/ DECLARE_EXPORT(dread) + DECLARE_EXPORT(getstat) + DECLARE_EXPORT(chstat) + DECLARE_EXPORT(format) + DECLARE_EXPORT(_retonly) +/*20*/ DECLARE_EXPORT(AddDrv) + DECLARE_EXPORT(DelDrv) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) +/*25*/ DECLARE_EXPORT(rename) + DECLARE_EXPORT(chdir) + DECLARE_EXPORT(sync) + DECLARE_EXPORT(mount) + DECLARE_EXPORT(umount) +/*30*/ DECLARE_EXPORT(lseek64) + DECLARE_EXPORT(devctl) + DECLARE_EXPORT(symlink) + DECLARE_EXPORT(readlink) + DECLARE_EXPORT(ioctl2) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/mem/iomanx/src/imports.lst b/sps2_basement/hardware/mem/iomanx/src/imports.lst new file mode 100644 index 0000000..851c6dd --- /dev/null +++ b/sps2_basement/hardware/mem/iomanx/src/imports.lst @@ -0,0 +1,27 @@ +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +loadcore_IMPORTS_start +I_GetLoadcoreInternalData +I_RegisterLibraryEntries +I_QueryLibraryEntryTable +I_FlushDcache +I_FlushIcache +loadcore_IMPORTS_end + +sysclib_IMPORTS_start +I_memset +I_memcmp +I_memcpy +I_strcmp +I_index +I_strlen +I_strncpy +I_strtol +sysclib_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end diff --git a/sps2_basement/hardware/mem/iomanx/src/iomanX.c b/sps2_basement/hardware/mem/iomanx/src/iomanX.c new file mode 100644 index 0000000..6ae6929 --- /dev/null +++ b/sps2_basement/hardware/mem/iomanx/src/iomanX.c @@ -0,0 +1,645 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Copyright (c) 2004 adresd +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Advanced I/O library. + */ + +#include "types.h" +#include "defs.h" +#include "loadcore.h" +#include "iomanX.h" +#include "sysclib.h" +#include "stdarg.h" +#include "intrman.h" + +#define MODNAME "iomanx" +IRX_ID("IOX/File_Manager", 1, 1); + +#include "errno.h" + +#define MAX_DEVICES 32 +#define MAX_FILES 32 + +static iop_device_t *dev_list[MAX_DEVICES]; +iop_file_t file_table[MAX_FILES]; + +#define isnum(c) ((c) >= '0' && (c) <= '9') + +extern struct irx_export_table _exp_iomanx; + +extern int hook_ioman(); +extern int unhook_ioman(); + +iop_device_t **GetDeviceList(void) +{ + return(dev_list); +} + +int _start(int argc, char **argv) +{ + if(RegisterLibraryEntries(&_exp_iomanx) != 0) + { + return MODULE_NO_RESIDENT_END; + } + + memset(dev_list, 0, sizeof(dev_list)); + memset(file_table, 0, sizeof(file_table)); + + if(hook_ioman() != 0) + { + return MODULE_NO_RESIDENT_END; + } + + return MODULE_RESIDENT_END; +} + +int shutdown() +{ + unhook_ioman(); + return MODULE_NO_RESIDENT_END; +} + +int AddDrv(iop_device_t *device) +{ + int i, res = -1; + int oldIntr; + + CpuSuspendIntr(&oldIntr); + + for (i = 0; i < MAX_DEVICES; i++) + { + if (dev_list[i] == NULL) + break; + } + + if (i >= MAX_DEVICES) + { + CpuResumeIntr(oldIntr); + return res; + } + + dev_list[i] = device; + CpuResumeIntr(oldIntr); + + FlushIcache(); + + if ((res = device->ops->init(device)) < 0) + { + dev_list[i] = NULL; + return(-1); + } + + return(0); +} + +int DelDrv(const char *name) +{ + int i; + + for (i = 0; i < MAX_DEVICES; i++) { + if (dev_list[i] != NULL && !strcmp(name, dev_list[i]->name)) { + dev_list[i]->ops->deinit(dev_list[i]); + dev_list[i] = NULL; + return 0; + } + } + + return -1; +} + + +static char * find_iop_device(const char *dev, int *unit, iop_device_t **device) +{ + char canon[16]; + char *filename, *tail, *d = (char *)dev; + int i, len, num = 0; + + if (*d == ' ') { + while (*d == ' ') + d++; + d--; + } + + if ((tail = index(d, ':')) == NULL) + return (char *)-1; + + len = (int)(tail - d); + strncpy(canon, d, len); + canon[len] = '\0'; + + /* This is the name passed to the device op. */ + filename = d + len + 1; + + /* Search backward for the unit number. */ + if (isnum(canon[len - 1])) { + while (isnum(canon[len - 1])) + len--; + + num = strtol(canon + len, 0, 10); + } + if (unit) + *unit = num; + + /* Find the actual device. */ + canon[len] = '\0'; + for (i = 0; i < MAX_DEVICES; i++) { + if (dev_list[i] != NULL && !strcmp(canon, dev_list[i]->name)) { + if (device) + *device = dev_list[i]; + + return filename; + } + } + + return (char *)-1; +} + +iop_file_t *get_file(int fd) +{ + if (fd >= MAX_FILES) + return NULL; + + if (file_table[fd].device != NULL) + return &file_table[fd]; + + return NULL; +} + +iop_file_t *get_new_file(void) +{ + int i; + iop_file_t *fd = NULL; + int oldIntr; + + CpuSuspendIntr(&oldIntr); + + for (i = 0; i < MAX_FILES; i++) + { + if (!file_table[i].device) + { + fd = &file_table[i]; + + // fill in "device" temporarily to mark the fd as allocated. + fd->device = (iop_device_t *) 0xFFFFFFFF; + break; + } + } + + CpuResumeIntr(oldIntr); + + return fd; +} + +int open(const char *name, int flags, ...) +{ + iop_file_t *f = get_new_file(); + char *filename; + va_list alist; + int res = -ENOSYS, mode; + + va_start(alist, flags); + mode = va_arg(alist, int); + va_end(alist); + + if (!f) + { + return -EMFILE; + } + + if ((filename = find_iop_device(name, &f->unit, &f->device)) == (char *)-1) + { + f->device = NULL; + return -ENODEV; + } + + f->mode = flags; + if ((res = f->device->ops->open(f, filename, flags, mode)) >= 0) + { + res = (int)(f - file_table); + } + else + { + f->mode = 0; + f->device = NULL; + } + + return res; +} + +int close(int fd) +{ + iop_file_t *f; + int res; + + if ((f = get_file(fd)) == NULL) + { + return -EBADF; + } + + if (f->mode & 8) + { /* Directory. */ + res = f->device->ops->dclose(f); + } + else + { + res = f->device->ops->close(f); + } + + f->mode = 0; + f->device = NULL; + return res; +} + +int read(int fd, void *ptr, int size) +{ + iop_file_t *f = get_file(fd); + + if (f == NULL || !(f->mode & O_RDONLY)) + return -EBADF; + + return f->device->ops->read(f, ptr, size); +} + +int write(int fd, void *ptr, int size) +{ + iop_file_t *f = get_file(fd); + + if (f == NULL || !(f->mode & O_WRONLY)) + return -EBADF; + + return f->device->ops->write(f, ptr, size); +} + +int lseek(int fd, int offset, int whence) +{ + iop_file_t *f = get_file(fd); + + if (f == NULL) + return -EBADF; + + if (whence < SEEK_SET || whence > SEEK_END) + return -EINVAL; + + return f->device->ops->lseek(f, offset, whence); +} + +int ioctl(int fd, int cmd, void *arg) +{ + iop_file_t *f = get_file(fd); + + if (f == NULL) + return -EBADF; + + return f->device->ops->ioctl(f, cmd, arg); +} + +int remove(const char *name) +{ + iop_file_t file; + char *filename; + + if ((filename = find_iop_device(name, &file.unit, &file.device)) == (char *)-1) + return -ENODEV; + + return file.device->ops->remove(&file, filename); +} + +/* Because mkdir, rmdir, chdir, and sync have similiar arguments (each starts + with a path followed by an optional integer), we use a common routine to + handle all of them. */ +static int path_common(const char *name, int arg, int code) +{ + iop_file_t file; + iop_device_ops_t *dops; + char *filename; + + if ((filename = find_iop_device(name, &file.unit, &file.device)) == (char *)-1) + return -ENODEV; + + if (code & 0x100) + if ((file.device->type & 0xf0000000) != IOP_DT_FSEXT) + return -48; + + dops = (iop_device_ops_t *)file.device->ops; + switch (code) { + case 4: /* mkdir() */ + return dops->mkdir(&file, filename, arg); + case 5: /* rmdir() */ + return dops->rmdir(&file, filename); + case 0x103: /* chdir() */ + return dops->chdir(&file, filename); + case 0x106: + return dops->sync(&file, filename, arg); + } + + return -EINVAL; +} + +int mkdir(const char *name, int mode) +{ + return path_common(name, mode, 4); +} + +int rmdir(const char *name) +{ + return path_common(name, 0, 5); +} + +int dopen(const char *name) +{ + iop_file_t *f = get_new_file(); + char *filename; + int res; + + if (!f) + return -EMFILE; + + if ((filename = find_iop_device(name, &f->unit, &f->device)) == (char *)-1) + { + f->device = NULL; + return -ENODEV; + } + + f->mode = 8; /* Indicates a directory. */ + if ((res = f->device->ops->dopen(f, filename)) >= 0) + res = (int)(f - file_table); + else + { + f->mode = 0; + f->device = NULL; + } + + return res; +} + +int mode2modex(int mode) +{ + int modex = 0; + + if (FIO_SO_ISLNK(mode)) + modex |= FIO_S_IFLNK; + if (FIO_SO_ISREG(mode)) + modex |= FIO_S_IFREG; + if (FIO_SO_ISDIR(mode)) + modex |= FIO_S_IFDIR; + + /* Convert the file access modes. */ + if (mode & FIO_SO_IROTH) + modex |= FIO_S_IRUSR | FIO_S_IRGRP | FIO_S_IROTH; + if (mode & FIO_SO_IWOTH) + modex |= FIO_S_IWUSR | FIO_S_IWGRP | FIO_S_IWOTH; + if (mode & FIO_SO_IXOTH) + modex |= FIO_S_IXUSR | FIO_S_IXGRP | FIO_S_IXOTH; + + return modex; +} + +int modex2mode(int modex) +{ + int mode = 0; + + if (FIO_S_ISLNK(modex)) + mode |= FIO_SO_IFLNK; + if (FIO_S_ISREG(modex)) + mode |= FIO_SO_IFREG; + if (FIO_S_ISDIR(modex)) + mode |= FIO_SO_IFDIR; + + /* Convert the file access modes. */ + if (modex & (FIO_S_IRUSR | FIO_S_IRGRP | FIO_S_IROTH)) + mode |= FIO_SO_IROTH; + if (modex & (FIO_S_IWUSR | FIO_S_IWGRP | FIO_S_IWOTH)) + mode |= FIO_SO_IWOTH; + if (modex & (FIO_S_IXUSR | FIO_S_IXGRP | FIO_S_IXOTH)) + mode |= FIO_SO_IXOTH; + + return mode; +} + +int dread(int fd, iox_dirent_t *iox_dirent) +{ + iop_file_t *f = get_file(fd); + int res; + + if (f == NULL || !(f->mode & 8)) + return -EBADF; + + /* If this is a legacy device (such as mc:) then we need to convert the mode + variable of the stat structure to iomanX's extended format. */ + if ((f->device->type & 0xf0000000) != IOP_DT_FSEXT) + { + typedef int io_dread_t(iop_file_t *, io_dirent_t *); + io_dirent_t io_dirent; + io_dread_t *io_dread = (io_dread_t*) f->device->ops->dread; + res = io_dread(f, &io_dirent); + + iox_dirent->stat.mode = mode2modex(io_dirent.stat.mode); + + iox_dirent->stat.attr = io_dirent.stat.attr; + iox_dirent->stat.size = io_dirent.stat.size; + memcpy(iox_dirent->stat.ctime, io_dirent.stat.ctime, sizeof(io_dirent.stat.ctime)); + memcpy(iox_dirent->stat.atime, io_dirent.stat.atime, sizeof(io_dirent.stat.atime)); + memcpy(iox_dirent->stat.mtime, io_dirent.stat.mtime, sizeof(io_dirent.stat.mtime)); + iox_dirent->stat.hisize = io_dirent.stat.hisize; + + strncpy(iox_dirent->name, io_dirent.name, sizeof(iox_dirent->name)); + } + else + res = f->device->ops->dread(f, iox_dirent); + + return res; +} + +int getstat(const char *name, iox_stat_t *stat) +{ + iop_file_t file; + char *filename; + int res; + + if ((filename = find_iop_device(name, &file.unit, &file.device)) == (char *)-1) + return -ENODEV; + + res = file.device->ops->getstat(&file, filename, stat); + + if (res == 0) + { + /* If this is a legacy device (such as mc:) then we need to convert the mode + variable to iomanX's extended format. */ + if ((file.device->type & 0xf0000000) != IOP_DT_FSEXT) + stat->mode = mode2modex(stat->mode); + } + + return res; +} + +int chstat(const char *name, iox_stat_t *stat, unsigned int mask) +{ + iop_file_t file; + char *filename; + + if ((filename = find_iop_device(name, &file.unit, &file.device)) == (char *)-1) + return -ENODEV; + + /* If this is a legacy device (such as mc:) then we need to convert the mode + variable to iomanX's extended format. */ + if ((file.device->type & 0xf0000000) != IOP_DT_FSEXT) + stat->mode = modex2mode(stat->mode); + + return file.device->ops->chstat(&file, filename, stat, mask); +} + +int format(const char *dev, const char *blockdev, void *arg, int arglen) +{ + iop_file_t file; + char *filename; + + if ((filename = find_iop_device(dev, &file.unit, &file.device)) == (char *)-1) + return -ENODEV; + + return file.device->ops->format(&file, filename, blockdev, arg, arglen); +} + +static int link_common(const char *old, const char *new, int code) +{ + iop_file_t file; + iop_device_t *new_device; + char *filename, *new_filename = (char *)new; + int new_unit; + + if ((filename = find_iop_device(old, &file.unit, &file.device)) == (char *)-1) + return -ENODEV; + + /* Make sure the user isn't attempting to link across devices. */ + if (index(new, ':') != NULL) { + new_filename = find_iop_device(new, &new_unit, &new_device); + if ((new_filename == (char *)-1) || (new_unit != file.unit) || + (new_device != file.device)) + return -ENXIO; + } + + /* The filesystem must support these ops. */ + if ((file.device->type & 0xf0000000) != IOP_DT_FSEXT) + return -48; + + if (code == 7) /* rename() */ + return file.device->ops->rename(&file, filename, new_filename); + + return file.device->ops->symlink(&file, filename, new_filename); +} + +int rename(const char *old, const char *new) +{ + return link_common(old, new, 7); +} + +int chdir(const char *name) +{ + return path_common(name, 0, 0x103); +} + +int sync(const char *dev, int flag) +{ + return path_common(dev, flag, 0x106); +} + +int mount(const char *fsname, const char *devname, int flag, void *arg, int arglen) +{ + iop_file_t file; + char *filename; + + if ((filename = find_iop_device(fsname, &file.unit, &file.device)) == (char *)-1) + return -ENODEV; + + /* The filesystem must support these ops. */ + if ((file.device->type & 0xf0000000) != IOP_DT_FSEXT) + return -48; + + return file.device->ops->mount(&file, filename, devname, flag, arg, arglen); +} + +int umount(const char *fsname) +{ + iop_file_t file; + char *filename; + + if ((filename = find_iop_device(fsname, &file.unit, &file.device)) == (char *)-1) + return -ENODEV; + + /* The filesystem must support these ops. */ + if ((file.device->type & 0xf0000000) != IOP_DT_FSEXT) + return -48; + + return file.device->ops->umount(&file, filename); +} + +long long lseek64(int fd, long long offset, int whence) +{ + iop_file_t *f = get_file(fd); + + if (f == NULL) + return -EBADF; + + if (whence < SEEK_SET || whence > SEEK_END) + return -EINVAL; + + if ((f->device->type & 0xf0000000) != IOP_DT_FSEXT) + return -48; + + return f->device->ops->lseek64(f, offset, whence); +} + +int devctl(const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen) +{ + iop_file_t file; + char *filename; + + if ((filename = find_iop_device(name, &file.unit, &file.device)) == (char *)-1) + return -ENODEV; + + /* The filesystem must support these ops. */ + if ((file.device->type & 0xf0000000) != IOP_DT_FSEXT) + return -48; + + return file.device->ops->devctl(&file, filename, cmd, arg, arglen, buf, buflen); +} + +int symlink(const char *old, const char *new) +{ + return link_common(old, new, 8); +} + +int readlink(const char *name, char *buf, unsigned int buflen) +{ + iop_file_t file; + char *filename; + + if ((filename = find_iop_device(name, &file.unit, &file.device)) == (char *)-1) + return -ENODEV; + + /* The filesystem must support these ops. */ + if ((file.device->type & 0xf0000000) != IOP_DT_FSEXT) + return -48; + + return file.device->ops->readlink(&file, filename, buf, buflen); +} + + +int ioctl2(int fd, int command, void *arg, unsigned int arglen, void *buf, unsigned int buflen) +{ + iop_file_t *f; + + if ((f = get_file(fd)) == NULL) + return -EBADF; + + return f->device->ops->ioctl2(f, command, arg, arglen, buf, buflen); +} diff --git a/sps2_basement/hardware/mem/iomanx/src/ioman_sbv.c b/sps2_basement/hardware/mem/iomanx/src/ioman_sbv.c new file mode 100644 index 0000000..0dde61e --- /dev/null +++ b/sps2_basement/hardware/mem/iomanx/src/ioman_sbv.c @@ -0,0 +1,346 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Copyright (c) 2004 adresd +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Advanced I/O library. + */ + +#include + +#include "types.h" +#include "defs.h" +#include "loadcore.h" +#include "iomanX.h" +#include "sysclib.h" + +#include "errno.h" + +// define this to hook all IOMAN exports instead of just AddDrv and DelDrv +#define FULL_IOMAN + +#define MAX_DEVICES 32 +#define MAX_FILES 32 + +iop_device_t **dev_list; +extern iop_file_t file_table[MAX_FILES]; + +static const char *ioman_modname = "IO/File_Manager"; + +static int smod_get_next_mod(ModuleInfo_t *cur_mod, ModuleInfo_t *next_mod) +{ + void *addr; + + /* If cur_mod is 0, return the head of the list (IOP address 0x800). */ + if (!cur_mod) { + addr = GetLoadcoreInternalData()->image_info; + } else { + if (!cur_mod->next) + return 0; + else + addr = cur_mod->next; + } + + memcpy(next_mod, addr, sizeof(ModuleInfo_t)); + return next_mod->id; +} + +static int smod_get_mod_by_name(const char *name, ModuleInfo_t *info) +{ + int len = strlen(name) + 1; /* Thanks to adresd for this fix. */ + + if (!smod_get_next_mod(NULL, info)) + return 0; + + do { + if (!memcmp(info->name, name, len)) + return info->id; + } while (smod_get_next_mod(info, info) != 0); + + return 0; +} + +void fix_imports(iop_library_t *lib) +{ + struct irx_import_table *table; + struct irx_import_stub *stub; + + FlushDcache(); + + // go through each table that imports the library + for(table = lib->caller; table != NULL; table = table->next) + { + // go through each import in the table + for(stub = (struct irx_import_stub *) table->stubs; stub->jump != 0; stub++) + { + // patch the stub to jump to the address specified in the library export table for "fno" + stub->jump = 0x08000000 | (((u32) lib->exports[stub->fno] << 4) >> 6); + } + } + + FlushIcache(); +} + +static u32 *ioman_exports; + +static u32 Addr_IOMAN_open = 0; +static u32 Addr_IOMAN_close = 0; +static u32 Addr_IOMAN_read = 0; +static u32 Addr_IOMAN_write = 0; +static u32 Addr_IOMAN_lseek = 0; +static u32 Addr_IOMAN_ioctl = 0; +static u32 Addr_IOMAN_remove = 0; +static u32 Addr_IOMAN_mkdir = 0; +static u32 Addr_IOMAN_rmdir = 0; +static u32 Addr_IOMAN_dopen = 0; +static u32 Addr_IOMAN_dclose = 0; +static u32 Addr_IOMAN_dread = 0; +static u32 Addr_IOMAN_getstat = 0; +static u32 Addr_IOMAN_chstat = 0; +static u32 Addr_IOMAN_format = 0; + +static u32 Addr_IOMAN_AddDrv = 0; +static u32 Addr_IOMAN_DelDrv = 0; + +#ifndef FULL_IOMAN + +/* This is called by a module wanting to add a device to legacy ioman. */ +static int sbv_AddDrv(iop_device_t *device) +{ + int res; + + /* We get first dibs! */ + res = AddDrv(device); + + if (Addr_IOMAN_AddDrv) + return(((int (*)(iop_device_t *device)) (Addr_IOMAN_AddDrv))(device)); + + return res; +} + +/* This is called by a module wanting to delete a device from legacy ioman. */ +static int sbv_DelDrv(const char *name) +{ + int res; + + res = DelDrv(name); + + if (Addr_IOMAN_DelDrv) + return(((int (*)(const char *)) (Addr_IOMAN_DelDrv))(name)); + + return res; +} +#endif + +#ifdef FULL_IOMAN + +// legacy ioman open and mkdir calls do not specify +// the "mode" arg. use default of 0644 for open and 0755 for mkdir. + +int ioman_open(const char *name, u32 flags) +{ + return(open(name, flags, 0644)); +} + +int ioman_mkdir(const char *name) +{ + return(mkdir(name, 0755)); +} + +// legacy format only takes one arg +int ioman_format(const char *dev) +{ + return(format(dev, NULL, NULL, 0)); +} + +iop_file_t *get_file(int fd); + +int mode2modex(int mode); +int modex2mode(int mode); + +static void statx2stat(iox_stat_t *iox_stat, io_stat_t* stat) +{ + stat->mode = modex2mode(iox_stat->mode); + stat->attr = iox_stat->attr; + stat->size = iox_stat->size; + memcpy(stat->ctime, iox_stat->ctime, sizeof(iox_stat->ctime)); + memcpy(stat->atime, iox_stat->atime, sizeof(iox_stat->atime)); + memcpy(stat->mtime, iox_stat->mtime, sizeof(iox_stat->mtime)); + stat->hisize = iox_stat->hisize; +} + +static void stat2statx(io_stat_t* stat, iox_stat_t *iox_stat) +{ + iox_stat->mode = mode2modex(stat->mode); + iox_stat->attr = stat->attr; + iox_stat->size = stat->size; + memcpy(iox_stat->ctime, stat->ctime, sizeof(stat->ctime)); + memcpy(iox_stat->atime, stat->atime, sizeof(stat->atime)); + memcpy(iox_stat->mtime, stat->mtime, sizeof(stat->mtime)); + iox_stat->hisize = stat->hisize; +} + +int ioman_dread(int fd, io_dirent_t *io_dirent) +{ + iop_file_t *f = get_file(fd); + int res; + + if (f == NULL || !(f->mode & 8)) + return -EBADF; + + /* If this is a new device (such as pfs:) then we need to convert the mode + variable of the stat structure to ioman's format. */ + if ((f->device->type & 0xf0000000) == IOP_DT_FSEXT) + { + iox_dirent_t iox_dirent; + res = f->device->ops->dread(f, &iox_dirent); + + statx2stat(&iox_dirent.stat, &io_dirent->stat); + + strncpy(io_dirent->name, iox_dirent.name, sizeof(iox_dirent.name)); + } + else + { + typedef int io_dread_t(iop_file_t *, io_dirent_t *); + io_dread_t *io_dread = (io_dread_t*) f->device->ops->dread; + res = io_dread(f, io_dirent); + } + + return res; +} + +int ioman_getstat(const char *name, io_stat_t *stat) +{ + iox_stat_t iox_stat; + int res = getstat(name, &iox_stat); + if (res == 0) + statx2stat(&iox_stat, stat); + return res; +} + +int ioman_chstat(const char *name, io_stat_t *stat, unsigned int mask) +{ + iox_stat_t iox_stat; + stat2statx(stat, &iox_stat); + return chstat(name, &iox_stat, mask); +} + +#endif + +int hook_ioman(void) +{ + iop_library_t ioman_library = { NULL, NULL, 0x102, 0, "ioman\0\0" }; + ModuleInfo_t info; + + dev_list = GetDeviceList(); + + if (smod_get_mod_by_name(ioman_modname, &info)) + { + // steal the original IOMAN's 16 registered device entries + memcpy(dev_list, (void *) (info.text_start + info.text_size + info.data_size + 0x10), sizeof(iop_device_t *) * 16); + + // steal the original IOMAN's 16 file descriptors + memcpy(file_table, (void *) (info.text_start + info.text_size + info.data_size + 0x50), sizeof(iop_file_t) * 16); + } + else { return(-1); } + + // patch the IOMAN export library table to call iomanX functions + if ((ioman_exports = (u32 *)QueryLibraryEntryTable(&ioman_library)) != NULL) + { + /* Preserve ioman's library exports. */ + Addr_IOMAN_open = ioman_exports[4]; + Addr_IOMAN_close = ioman_exports[5]; + Addr_IOMAN_read = ioman_exports[6]; + Addr_IOMAN_write = ioman_exports[7]; + Addr_IOMAN_lseek = ioman_exports[8]; + Addr_IOMAN_ioctl = ioman_exports[9]; + Addr_IOMAN_remove = ioman_exports[10]; + Addr_IOMAN_mkdir = ioman_exports[11]; + Addr_IOMAN_rmdir = ioman_exports[12]; + Addr_IOMAN_dopen = ioman_exports[13]; + Addr_IOMAN_dclose = ioman_exports[14]; + Addr_IOMAN_dread = ioman_exports[15]; + Addr_IOMAN_getstat = ioman_exports[16]; + Addr_IOMAN_chstat = ioman_exports[17]; + Addr_IOMAN_format = ioman_exports[18]; + Addr_IOMAN_AddDrv = ioman_exports[20]; + Addr_IOMAN_DelDrv = ioman_exports[21]; + +#ifdef FULL_IOMAN + ioman_exports[4] = (u32) ioman_open; + ioman_exports[5] = (u32) close; + ioman_exports[6] = (u32) read; + ioman_exports[7] = (u32) write; + ioman_exports[8] = (u32) lseek; + ioman_exports[9] = (u32) ioctl; + ioman_exports[10] = (u32) remove; + ioman_exports[11] = (u32) ioman_mkdir; + ioman_exports[12] = (u32) rmdir; + ioman_exports[13] = (u32) dopen; + ioman_exports[14] = (u32) close; + ioman_exports[15] = (u32) ioman_dread; + ioman_exports[16] = (u32) ioman_getstat; + ioman_exports[17] = (u32) ioman_chstat; + ioman_exports[18] = (u32) ioman_format; + ioman_exports[20] = (u32) AddDrv; + ioman_exports[21] = (u32) DelDrv; +#else + ioman_exports[20] = (u32) sbv_AddDrv; + ioman_exports[21] = (u32) sbv_DelDrv; +#endif + + // repair all the tables that import the ioman library + fix_imports((iop_library_t *) (((u32) ioman_exports) - 0x14)); + } + else { return(-2); } + + return(0); +} + +int unhook_ioman() +{ + int i; + + dev_list = GetDeviceList(); + + /* Remove all registered devices. */ + for (i = 0; i < MAX_DEVICES; i++) { + if (dev_list[i] != NULL) { + dev_list[i]->ops->deinit(dev_list[i]); + dev_list[i] = NULL; + } + } + + /* Restore ioman's library exports. */ + ioman_exports[4] = Addr_IOMAN_open; + ioman_exports[5] = Addr_IOMAN_close; + ioman_exports[6] = Addr_IOMAN_read; + ioman_exports[7] = Addr_IOMAN_write; + ioman_exports[8] = Addr_IOMAN_lseek; + ioman_exports[9] = Addr_IOMAN_ioctl; + ioman_exports[10] = Addr_IOMAN_remove; + ioman_exports[11] = Addr_IOMAN_mkdir; + ioman_exports[12] = Addr_IOMAN_rmdir; + ioman_exports[13] = Addr_IOMAN_dopen; + ioman_exports[14] = Addr_IOMAN_dclose; + ioman_exports[15] = Addr_IOMAN_dread; + ioman_exports[16] = Addr_IOMAN_getstat; + ioman_exports[17] = Addr_IOMAN_chstat; + ioman_exports[18] = Addr_IOMAN_format; + + ioman_exports[20] = Addr_IOMAN_AddDrv; + ioman_exports[21] = Addr_IOMAN_DelDrv; + + // repair all the tables that import the ioman library + fix_imports((iop_library_t *) (((u32) ioman_exports) - 0x14)); + + return 0; +} diff --git a/sps2_basement/hardware/mem/iomanx/src/irx_imports.h b/sps2_basement/hardware/mem/iomanx/src/irx_imports.h new file mode 100644 index 0000000..f136557 --- /dev/null +++ b/sps2_basement/hardware/mem/iomanx/src/irx_imports.h @@ -0,0 +1,24 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "loadcore.h" +#include "stdio.h" +#include "sysclib.h" +#include "intrman.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/mem/iopmgr/Makefile b/sps2_basement/hardware/mem/iopmgr/Makefile new file mode 100644 index 0000000..deedf69 --- /dev/null +++ b/sps2_basement/hardware/mem/iopmgr/Makefile @@ -0,0 +1,14 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_OBJS = main.o smod.o slib.o devices.o commandline.o imports.o exports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/mem/iopmgr/README b/sps2_basement/hardware/mem/iopmgr/README new file mode 100644 index 0000000..f158d13 --- /dev/null +++ b/sps2_basement/hardware/mem/iopmgr/README @@ -0,0 +1,63 @@ +iopmgr - IOP Manager v1.1 +------------------------- +Copyright (c) 2003 Marcus R. Brown +Copyright (c) 2003,2004 adresd +Licensed under the Academic Free License version 2.0. +-- + +This includes libsmod (library for iop programs) which is based on "smod - Sub-CPU module +interface" from Marcus R. Browns's sbv-lite, adapted for native IOP use. + +This has been expanded into a general framework for a IOP Manager, handling modules, +devices and libraries. + +smod enables access to the loaded module list, which contains details of all +currently loaded IRX files, including description and version number. + +slib allows easy functions to query registered libraries (exports) and also to +unregister any loaded ones, or find exported functions. + +IOP Manager contains functions for handling access to devices and device drivers on +the IOP. Including testing if a certain filesystem driver is currently loaded and being +handled, and if it is which ioman is handling that device (ioman or iomanx). + +IOP Manager is very much a WIP, so expect it to expand. + + + +NOTES ON IOP: +It is quite important to think of IRX's consisting of two parts: + +One is the IRX as a module, and any associated threads. +The other is any exports that it registers, as they create a library entry for the mod. + +There are modules that do not export functions, so do not have a library entry. +And a module that offers exports can be loaded without the exports being registered as +a library. + +This also has implications, as the module name is not the same as the library name, and the +same goes for version numbers as well. +The library name and version is the one specified in the export list (export.lst) when building. +The module name and version come from the IRX_ID (if using ps2drv framework). + +This presumably is so the the exports can stay the same (with same library version) while +the module name and/or version changes, without affecting other modules loading those exports. + +This is one reason why the slib and smod functions are prefixed by their name, to make the +user think about it and make sure to use the right function. + +NOTES ON USAGE: + +This IRX will load and make itself resident if passed no parameters. +If passed parameters it will run in command mode. +Try the param 'help' for a list of available commands. + +OTHER COMMENTS: + +See the export list and header for supported calls, also the 'commandline.c' file is +a good example of its use. The whole code is really an example of its own use. + +ADDITIONAL CREDITS: + +Thanks go to Marcus R. Brown for the original sbv-lite library which contained the smod +module used as a base and inspiration for the one in iopmgr. diff --git a/sps2_basement/hardware/mem/iopmgr/include/iopmgr.h b/sps2_basement/hardware/mem/iopmgr/include/iopmgr.h new file mode 100644 index 0000000..bdebaba --- /dev/null +++ b/sps2_basement/hardware/mem/iopmgr/include/iopmgr.h @@ -0,0 +1,87 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * iop manager includes + */ + +#ifndef __IOPMGR_H__ +#define __IOPMGR_H__ + +#include +#include +#ifndef __IOMANX_H__ +#include +#endif +#include + +/* Module info entry. */ +typedef ModuleInfo_t smod_mod_info_t __attribute__ ((deprecated)); //For backward-compatibility with older projects. + +/* from smod.c */ +ModuleInfo_t *smod_get_next_mod(ModuleInfo_t *cur_mod); +ModuleInfo_t *smod_get_mod_by_name(const char *name); +int smod_get_modcount_by_name(const char *name); +int smod_get_modversion_by_name(const char *name); +int smod_unload_module(const char *name); + +/* from slib.c */ +iop_library_t *slib_get_lib_by_name(const char *name); +void *slib_get_exportlist_by_name(const char *name); +int slib_get_version_by_name(const char *name); +int slib_release_library(const char *name); + +/* from devices.c */ +iop_device_t *iopmgr_get_iomandev(char *device); +iop_device_t *iopmgr_get_iomanxdev(char *device); +iop_device_t *iopmgr_get_device(char *device); +int iopmgr_get_devicetype(char *device); +int iopmgr_get_devicelist(int man,int devtype,char *buffer); + +/* from modules.c */ + +/* These are the types returned by the devicetype call as return values. */ +#define IOPMGR_DEVTYPE_INVALID 0 +#define IOPMGR_DEVTYPE_IOMAN 1 +#define IOPMGR_DEVTYPE_IOMANX 2 +#define IOPMGR_DEVTYPE_ALL 0xffff + +/* iomgr module identifier */ +#define IOPMGR_MODNAME "IOP_Manager" +#define IOPMGR_LIBNAME "iopmgr" + +/* iomgr module version number, so programs can check required version is installed */ +#define IOPMGR_VERSION_HIGH 1 +#define IOPMGR_VERSION_LOW 1 + +/* defines for ioman and iomanx module identifiers , so we can locate them */ +#define IOPMGR_IOMAN_IDENT "IO/File_Manager" +#define IOPMGR_IOMANX_IDENT "IOX/File_Manager" + +#define iopmgr_IMPORTS_start DECLARE_IMPORT_TABLE(iopmgr, 1, 1) +#define iopmgr_IMPORTS_end END_IMPORT_TABLE + +#define I_smod_get_next_mod DECLARE_IMPORT(4, smod_get_next_mod) +#define I_smod_get_mod_by_name DECLARE_IMPORT(5, smod_get_mod_by_name) +#define I_smod_get_modcount_by_name DECLARE_IMPORT(6, smod_get_modcount_by_name) +#define I_smod_get_modversion_by_name DECLARE_IMPORT(7, smod_get_modversion_by_name) +#define I_smod_unload_module DECLARE_IMPORT(8, smod_unload_module) +#define I_slib_get_lib_by_name DECLARE_IMPORT(10, slib_get_lib_by_name) +#define I_slib_get_exportlist_by_name DECLARE_IMPORT(11, slib_get_exportlist_by_name) +#define I_slib_get_version_by_name DECLARE_IMPORT(12, slib_get_version_by_name) +#define I_slib_release_library DECLARE_IMPORT(13, slib_release_library) +#define I_iopmgr_get_iomandev DECLARE_IMPORT(15, iopmgr_get_iomandev) +#define I_iopmgr_get_iomanxdev DECLARE_IMPORT(16, iopmgr_get_iomanxdev) +#define I_iopmgr_get_device DECLARE_IMPORT(17, iopmgr_get_device) +#define I_iopmgr_get_devicetype DECLARE_IMPORT(18, iopmgr_get_devicetype) +#define I_iopmgr_get_devicelist DECLARE_IMPORT(19, iopmgr_get_devicelist) + +#endif /* __IOPMGR_H__ */ diff --git a/sps2_basement/hardware/mem/iopmgr/src/commandline.c b/sps2_basement/hardware/mem/iopmgr/src/commandline.c new file mode 100644 index 0000000..911c96f --- /dev/null +++ b/sps2_basement/hardware/mem/iopmgr/src/commandline.c @@ -0,0 +1,204 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * command line parser and handler for iop manager. + */ + +#include "defs.h" +#include "iomanX.h" +#include "stdio.h" +#include "sysclib.h" + +#include "iopmgr.h" + +extern int shutdown(); + +/** Prints out a list of all currently registered libraries with their name and version. + * @ingroup iopmgr + */ +void list_all_libraries() +{ + char name[9]; + iop_library_t *libptr; + + printf("Registered Libraries:\n"); + libptr = GetLoadcoreInternalData()->let_next; + while (libptr) + { + /* We only have a 8-char buffer for the name, so we need to convert it into a C + string just in case the name is 8 chars. */ + memset(name, 0, sizeof(name)); + memcpy(name, libptr->name, 8); + printf(" %-20s v%d.%d\n",name, + (libptr->version&0xff00)>>8,libptr->version&0xff); + libptr = libptr->prev; + } + printf("\n"); +} + + +/** Prints out a list of all currently loaded IRX modules with description and version number. + * @ingroup iopmgr + */ +void list_all_modules() +{ + ModuleInfo_t *info; + printf("Loaded Modules:\n"); + info = smod_get_next_mod(0); + while (info != 0) + { + printf(" %-40s v%d.%d (%d)\n",info->name, + (info->version&0xff00)>>8,(info->version&0xff),info->flags); + info = info->next; + } + printf("\n"); +} + +/** Print out all devices for ONLY ioman and shows which one they belong to. + * @ingroup iopmgr + */ +void list_devices_ioman() +{ + ModuleInfo_t *info; + iop_device_t **devinfo_table; + int i; + + if (!(info = smod_get_mod_by_name(IOPMGR_IOMAN_IDENT))) { + printf("Unable to find '%s's module info!\n",IOPMGR_IOMAN_IDENT); + return; + } + + /* Find the start of the device info array, in .bss. */ + devinfo_table = (iop_device_t **)(info->text_start + info->text_size + info->data_size + 0x0c); + + printf("Known '%s' devices:\n",IOPMGR_IOMAN_IDENT); + /* The device info table had 16 entries, but some may be empty. Just look at all of them. */ + for (i = 0; i < 16; i++) { + if (devinfo_table[i]) + printf(" %-10s: %-27s v%d.%d type:%08X\n", + devinfo_table[i]->name, devinfo_table[i]->desc, + (devinfo_table[i]->version&0xff00)>>8, + (devinfo_table[i]->version&0xff), + devinfo_table[i]->type); + } + printf("\n"); +} + +/** Print out all devices for ONLY iomanx and shows which one they belong to. + * @ingroup iopmgr + */ +void list_devices_iomanx() +{ + ModuleInfo_t *info; + iop_device_t **devinfo_table; + int i; + + if (!(info = smod_get_mod_by_name(IOPMGR_IOMANX_IDENT))) { + printf("Unable to find '%s's module info!\n",IOPMGR_IOMANX_IDENT); + return; + } + + /* Find the start of the device info array, in .bss. */ + devinfo_table = (iop_device_t **)(info->text_start + info->text_size + info->data_size + 0x00); + + printf("Known '%s' devices:\n",IOPMGR_IOMANX_IDENT); + /* The device info table had 32 entries, but some may be empty. Just look at all of them. */ + for (i = 0; i < 32; i++) { + if (devinfo_table[i]) + printf(" %-10s: %-28s v%d.%d type:%08X\n", + devinfo_table[i]->name, devinfo_table[i]->desc, + (devinfo_table[i]->version&0xff00)>>8, + (devinfo_table[i]->version&0xff), + devinfo_table[i]->type); + } + printf("\n"); +} + +/** Print out all devices for both ioman and iomanx and shows which one they belong to. + * + * @param mgrtype Device manager type search mask (IOPMGR_DEVTYPE_XXXX). + * @ingroup iopmgr + */ +void list_fs_devices(int mgrtype) +{ + int count; + int i; + char *bufptr; + char buffer[256]; + bufptr = &buffer[0]; + + count = iopmgr_get_devicelist(mgrtype,IOP_DT_FS,bufptr); + printf("filesystems found : %d\n",count); + + for (i=0;itext_start + info->text_size + info->data_size + 0x0c); + + /* The device info table had 16 entries, but some may be empty. Just look at all of them. */ + for (i = 0; i < 16; i++) { + if (devinfo_table[i]) + if (!memcmp(devinfo_table[i]->name, device, len)) + return(devinfo_table[i]); + } + return 0; +} + +/** Get a pointer to an iomanx device handler. + * @ingroup iopmgr + * + * @param device Stringname of device (eg "hdd"). + * @return Pointer to device structure. + * + * return values: + * 0 if not found. + * pointer to device structure for named driver if found. + */ +iop_device_t *iopmgr_get_iomanxdev(char *device) +{ + ModuleInfo_t *info; + iop_device_t **devinfo_table; + int i; + int len = strlen(device) + 1; + + if (!(info = smod_get_mod_by_name(IOPMGR_IOMANX_IDENT))) { + return 0; + } + + /* Find the start of the device info array, in .bss. */ + devinfo_table = (iop_device_t **)(info->text_start + info->text_size + info->data_size); + + /* The device info table had 32 entries, but some may be empty. Just look at all of them. */ + for (i = 0; i < 32; i++) { + if (devinfo_table[i]) + if (!memcmp(devinfo_table[i]->name, device, len)) + return(devinfo_table[i]); + } + return 0; +} + +/** Get a list of devices of a certain type + * @ingroup iopmgr + * + * @param man Device manager mask (IOPMGR_DEVTYPE_IOMAN or IOPMGR_DEVTYPE_IOMANX). + * @param devtype Device type mask (0x10 for filesystems). + * @return Number of devices found + * + * return values: + * 0 if no matching devices found + * device count, if found, and buffer buffer filled with ascii serial + * string of device names. + */ +int iopmgr_get_devicelist(int man,int devtype,char *buffer) +{ + ModuleInfo_t *info; + iop_device_t **devinfo_table; + int i; + char *bufptr = buffer; + int count = 0; + + /* do the ioman devices */ + if ((man & IOPMGR_DEVTYPE_IOMAN)) + if ((info = smod_get_mod_by_name(IOPMGR_IOMAN_IDENT))) + { + /* Find the start of the device info array, in .bss. */ + devinfo_table = (iop_device_t **)(info->text_start + info->text_size + info->data_size + 0x0c); + + /* The device info table had 16 entries, but some may be empty. Just look at all of them. */ + for (i = 0; i < 16; i++) + { + if (devinfo_table[i]) + if ((devinfo_table[i]->type & devtype)) + { + strcpy(bufptr,devinfo_table[i]->name); + bufptr += strlen(bufptr)+1; + count++; + } + } + } + + /* do the iomanx devices */ + if ((man & IOPMGR_DEVTYPE_IOMANX)) + if ((info = smod_get_mod_by_name(IOPMGR_IOMANX_IDENT))) + { + /* Find the start of the device info array, in .bss. */ + devinfo_table = (iop_device_t **)(info->text_start + info->text_size + info->data_size); + + /* The device info table had 32 entries, but some may be empty. Just look at all of them. */ + for (i = 0; i < 32; i++) + { + if (devinfo_table[i]) + /* only add iomanx ones here, so must have extended flag set else we get duplication with new iomanx */ + if ((devinfo_table[i]->type & IOP_DT_FSEXT) && (devinfo_table[i]->type & devtype)) + { + strcpy(bufptr,devinfo_table[i]->name); + bufptr += strlen(bufptr)+1; + count++; + } + } + } + return count; +} + +/** Get a pointer to a device of either type + * @ingroup iopmgr + * + * @param device Stringname of device (eg "host). + * @return Pointer to device structure. + * + * return values: + * 0 if not found. + * pointer to device structure for named driver if found. + */ +iop_device_t *iopmgr_get_device(char *device) +{ + iop_device_t *devptr; + devptr = iopmgr_get_iomandev(device); + if (devptr > 0) return(devptr); + devptr = iopmgr_get_iomanxdev(device); + if (devptr > 0) return(devptr); + return 0; +} + +/** Returns which i/o manager handles the given device. + * @ingroup iopmgr + * + * @param device Stringname of device (eg "host). + * @return numeric value for i/o manager. + * + * return values: + * IOPMGR_DEVTYPE_INVALID if not found, + * IOPMGR_DEVTYPE_IOMAN if found and ioman device, + * IOPMGR_DEVTYPE_IOMANX if found and iomanx device. + */ +int iopmgr_get_devicetype(char *device) +{ + if (iopmgr_get_iomandev(device) > 0) + return(IOPMGR_DEVTYPE_IOMAN); + if (iopmgr_get_iomanxdev(device) > 0) + return(IOPMGR_DEVTYPE_IOMANX); + return IOPMGR_DEVTYPE_INVALID; +} diff --git a/sps2_basement/hardware/mem/iopmgr/src/exports.tab b/sps2_basement/hardware/mem/iopmgr/src/exports.tab new file mode 100644 index 0000000..124e558 --- /dev/null +++ b/sps2_basement/hardware/mem/iopmgr/src/exports.tab @@ -0,0 +1,44 @@ + +DECLARE_EXPORT_TABLE(iopmgr, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(shutdown) + DECLARE_EXPORT(_retonly) + + /* 4 */ + DECLARE_EXPORT(smod_get_next_mod) + DECLARE_EXPORT(smod_get_mod_by_name) + DECLARE_EXPORT(smod_get_modcount_by_name) + DECLARE_EXPORT(smod_get_modversion_by_name) + + DECLARE_EXPORT(_retonly0) + DECLARE_EXPORT(_retonly0) + + /* 10 */ + DECLARE_EXPORT(slib_get_lib_by_name) + DECLARE_EXPORT(slib_get_exportlist_by_name) + DECLARE_EXPORT(slib_get_version_by_name) + DECLARE_EXPORT(slib_release_library) + DECLARE_EXPORT(_retonly0) + + /* 15 */ + DECLARE_EXPORT(iopmgr_get_iomandev) + DECLARE_EXPORT(iopmgr_get_iomanxdev) + DECLARE_EXPORT(iopmgr_get_device) + DECLARE_EXPORT(iopmgr_get_devicetype) + DECLARE_EXPORT(iopmgr_get_devicelist) + + /* 20 */ + DECLARE_EXPORT(_retonly0) + DECLARE_EXPORT(_retonly0) + DECLARE_EXPORT(_retonly0) + DECLARE_EXPORT(_retonly0) + DECLARE_EXPORT(_retonly0) + + /* 25 */ + DECLARE_EXPORT(_retonly0) + +END_EXPORT_TABLE + +void _retonly() {} +int _retonly0() {return 0;} diff --git a/sps2_basement/hardware/mem/iopmgr/src/imports.lst b/sps2_basement/hardware/mem/iopmgr/src/imports.lst new file mode 100644 index 0000000..fd6d70e --- /dev/null +++ b/sps2_basement/hardware/mem/iopmgr/src/imports.lst @@ -0,0 +1,20 @@ +sysclib_IMPORTS_start +I_memcmp +I_memcpy +I_memset +I_strlen +I_strcpy +I_strcmp +I_strncpy +sysclib_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +I_ReleaseLibraryEntries +I_GetLoadcoreInternalData +loadcore_IMPORTS_end + diff --git a/sps2_basement/hardware/mem/iopmgr/src/irx_imports.h b/sps2_basement/hardware/mem/iopmgr/src/irx_imports.h new file mode 100644 index 0000000..9354009 --- /dev/null +++ b/sps2_basement/hardware/mem/iopmgr/src/irx_imports.h @@ -0,0 +1,23 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "loadcore.h" +#include "stdio.h" +#include "sysclib.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/mem/iopmgr/src/main.c b/sps2_basement/hardware/mem/iopmgr/src/main.c new file mode 100644 index 0000000..8b09f7b --- /dev/null +++ b/sps2_basement/hardware/mem/iopmgr/src/main.c @@ -0,0 +1,109 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * init code for iop manager. + */ + +#include "types.h" +#include "defs.h" +#include "irx.h" +#include "iomanX.h" +#include "stdio.h" + +#include "iopmgr.h" + +/** @defgroup iopmgr iopmgr - IOP Manager*/ + +IRX_ID(IOPMGR_MODNAME, IOPMGR_VERSION_HIGH, IOPMGR_VERSION_LOW); + +extern struct irx_export_table _exp_iopmgr; + +extern void cmdline_handle(char *command, char *arg1); + +/** Entry point for IRX. + * @ingroup iopmgr + * + * if argc <= 1 , install as library. + * if argc > 1 , run given command in argv[1]. + * + * @param argc Number of arguments. + * @param argv Pointer to array of arguments. + * @return Module Status on Exit. + * + * return values: + * MODULE_RESIDENT_END if loaded and registered as library. + * MODULE_NO_RESIDENT_END if just exiting normally. + */ +int _start(int argc, char *argv[]) +{ + printf("%s - Version %d.%d\nCopyright (c) 2003,2004 adresd\n\n", + IOPMGR_MODNAME, IOPMGR_VERSION_HIGH, IOPMGR_VERSION_LOW); + + if (argc > 1) + { /* Execute in command line mode, so parse command */ + if(argc>2) + { + cmdline_handle(argv[1],argv[2]); + } + else + { + cmdline_handle(argv[1],NULL); + } + } + else + { /* no params, so set into resident mode */ + if (RegisterLibraryEntries(&_exp_iopmgr) == 0) + { + printf("Registered.\n"); + return MODULE_RESIDENT_END; + } + else + { + /* luckily the previously installed one will be higher up the list, so will + * be the first one found , so get the version + */ + int version = smod_get_modversion_by_name(IOPMGR_MODNAME); + printf ("Error Registering - "); + if (version >= 0) + printf("Already Registered , version : %d.%d\n", + (version&0xff00)>>8,version&0xff); + else + printf("Error : %d\n",version); + } + } + printf("\nExiting.\n"); + return MODULE_NO_RESIDENT_END; +} + +/** shutdown the IRX. + * @ingroup iopmgr + * + * This checks if the library is registered, if it is then + * it unregisters it. + * + * @return Module Status on Exit. + * + * return values: + * MODULE_RESIDENT_END if loaded and registered as library. + * MODULE_NO_RESIDENT_END if just exiting normally. + */ +int shutdown() +{ + switch(slib_release_library(IOPMGR_LIBNAME)) + { + case 0: printf("UnRegistered\n"); break; + case -1: printf("Failed to UnRegister\n"); return MODULE_RESIDENT_END; break; + case -2: printf("Library Not Present\n"); break; + } + return MODULE_NO_RESIDENT_END; +} + diff --git a/sps2_basement/hardware/mem/iopmgr/src/slib.c b/sps2_basement/hardware/mem/iopmgr/src/slib.c new file mode 100644 index 0000000..bb05c8e --- /dev/null +++ b/sps2_basement/hardware/mem/iopmgr/src/slib.c @@ -0,0 +1,111 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOP Sub-CPU library manipulation functions + */ + +#include "types.h" +#include "defs.h" +#include "irx.h" + +#include "loadcore.h" +#include "ioman.h" +#include "stdio.h" +#include "sysclib.h" + +#include "iopmgr.h" + +/** Get pointer to system library structure for named library. + * @ingroup iopmgr + * + * @param name Stringname of library (eg "ioman"). + * @return Pointer to IOP library structure. + * + * return values: + * 0 if not found. + * pointer to library structure for registered library if found. + */ +iop_library_t *slib_get_lib_by_name(const char *name) +{ + iop_library_t *libptr; + int len = strlen(name) + 1; + + libptr = GetLoadcoreInternalData()->let_next; + while ((libptr != 0)) + { + if (!memcmp(libptr->name, name, len)) + return libptr; + libptr = libptr->prev; + } + return 0; +} + +/** Get pointer to export list for named library. + * @ingroup iopmgr + * + * @param name Stringname of library (eg "ioman"). + * @return Pointer to export list. + * + * return values: + * 0 if not found. + * pointer to export list for registered library if found. + */ +void *slib_get_exportlist_by_name(const char *name) +{ + iop_library_t *libptr; + + libptr = slib_get_lib_by_name(name); + if (libptr != 0) + return libptr->exports; + return 0; +} + +/** Get version number for named library. + * @ingroup iopmgr + * + * @param name Stringname of library (eg "ioman"). + * @return version number. + * + * return values: + * 0 if not found. + * Version number for registered library if found. (0xXXYY, XX=HIGH, YY=LOW) + */ +int slib_get_version_by_name(const char *name) +{ + iop_library_t *libptr; + + libptr = slib_get_lib_by_name(name); + if (libptr != 0) + return (int)libptr->version; + return 0; +} + +/** Release (Unregister) a given named registered library. + * @ingroup iopmgr + * + * @param name Stringname of library (eg "ioman"). + * @return Status of operation. + * + * return values: + * 0 if found and sucessfully unregistered. + * -1 if found, but failed to unregister. + * -2 if library was not found. + */ +int slib_release_library(const char *name) +{ + struct irx_export_table *libptr; + + libptr = (struct irx_export_table *)slib_get_lib_by_name(name); + if (libptr != 0) + return ReleaseLibraryEntries(libptr); + return -2; +} diff --git a/sps2_basement/hardware/mem/iopmgr/src/smod.c b/sps2_basement/hardware/mem/iopmgr/src/smod.c new file mode 100644 index 0000000..93d14f5 --- /dev/null +++ b/sps2_basement/hardware/mem/iopmgr/src/smod.c @@ -0,0 +1,139 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Copyright (c) 2003, 2004 adresd +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * iop Sub-CPU module library + */ + +#include "types.h" +#include "defs.h" +#include "irx.h" + +#include "loadcore.h" +#include "ioman.h" +#include "stdio.h" +#include "sysclib.h" + +#include "iopmgr.h" + +/** Get pointer to head of module list, or next module in list. + * @ingroup iopmgr + * + * @param cur_mod Pointer to module structure, or 0 to return the head. + * @return Pointer to module structure. + * + * return values: + * 0 if end of list. + * pointer to head of module list if cur_mod=0. + * pointer to next module, if cur_mod!=0. + */ +ModuleInfo_t *smod_get_next_mod(ModuleInfo_t *cur_mod) +{ + /* If cur_mod is 0, return the head of the list. */ + if (!cur_mod) { + return GetLoadcoreInternalData()->image_info; + } else { + if (!cur_mod->next) + return 0; + else + return cur_mod->next; + } + return 0; +} + +/** Get pointer to module structure for named module. + * @ingroup iopmgr + * + * @param name Stringname of module (eg "atad_driver"). + * @return Pointer to module structure. + * + * return values: + * 0 if not found. + * pointer to module structure for loaded module if found. + */ +ModuleInfo_t *smod_get_mod_by_name(const char *name) +{ + ModuleInfo_t *modptr; + int len = strlen(name)+1; + + modptr = smod_get_next_mod(0); + while (modptr != 0) + { + if (!memcmp(modptr->name, name, len)) + return modptr; + modptr = modptr->next; + } + return 0; +} + +/** Get instance count for given module name. + * @ingroup iopmgr + * + * @param name Stringname of module (eg "atad_driver"). + * @return Number of instances loaded. + * + * NOTE: if doing this to check for own module, the run being used to check + * automatically adds one to the count.. so ret=2 means another, + * instance loaded as well as current one. + */ +int smod_get_modcount_by_name(const char *name) +{ + ModuleInfo_t *modptr = 0; + int len = strlen(name)+1; + int count = 0; + + modptr = smod_get_next_mod(0); + while (modptr != 0) + { + if (!memcmp(modptr->name, name, len)) + count++; + modptr = modptr->next; + } + + return count; +} + +/** Get version number for given module name. + * @ingroup iopmgr + * + * @param name Stringname of module (eg "atad_driver"). + * @return Version number. + * + * return values: + * 0 if not found. + * Version number for module if found. (0xXXYY, XX=HIGH, YY=LOW) + */ +int smod_get_modversion_by_name(const char *name) +{ + ModuleInfo_t *modptr = 0; + modptr = smod_get_mod_by_name(name); + if (modptr != 0) + return (int)modptr->version; + else + return -1; +} + +/** Unload the named module. + * @ingroup iopmgr + * + * @param name Stringname of module (eg "atad_driver"). + * @return Status of operation. + * + * return values: + * 0 if found and sucessfully unloaded. + * -1 if found, but failed to unload. + * -2 if module was not found. + */ +int smod_unload_module(const char *name) +{ + return -2; +} diff --git a/sps2_basement/hardware/mem/mtapman/Makefile b/sps2_basement/hardware/mem/mtapman/Makefile new file mode 100644 index 0000000..3853979 --- /dev/null +++ b/sps2_basement/hardware/mem/mtapman/Makefile @@ -0,0 +1,18 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN_ALTNAMES ?= freemtap.irx + +IOP_INCS += -I$(PS2SDKSRC)/iop/system/sio2man/include + +IOP_OBJS = freemtap.o rpcservers.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/mem/mtapman/README b/sps2_basement/hardware/mem/mtapman/README new file mode 100644 index 0000000..1a3d2d7 --- /dev/null +++ b/sps2_basement/hardware/mem/mtapman/README @@ -0,0 +1,10 @@ +freemtap is a free replacement module for XMTAPMAN. + +- Lukasz Bruun + +Changelog +------------------------------------------------------------------------------- +2007-08-29 + - lukasz, Updated the exports.tab +2007-06-25 + - lukasz, initial release diff --git a/sps2_basement/hardware/mem/mtapman/src/exports.tab b/sps2_basement/hardware/mem/mtapman/src/exports.tab new file mode 100644 index 0000000..86cfe4b --- /dev/null +++ b/sps2_basement/hardware/mem/mtapman/src/exports.tab @@ -0,0 +1,12 @@ +DECLARE_EXPORT_TABLE(mtapman, 1, 2) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(shutdown) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(mtapPortOpen) + DECLARE_EXPORT(mtapPortClose) + DECLARE_EXPORT(mtapGetSlotNumber) + DECLARE_EXPORT(mtapChangeSlot) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/mem/mtapman/src/freemtap.c b/sps2_basement/hardware/mem/mtapman/src/freemtap.c new file mode 100644 index 0000000..121e935 --- /dev/null +++ b/sps2_basement/hardware/mem/mtapman/src/freemtap.c @@ -0,0 +1,557 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP multitap driver + */ + +#include "types.h" +#include "irx.h" +#include "stdio.h" +#include "loadcore.h" +#include "thevent.h" +#include "thbase.h" +#include "xsio2man.h" +#include "freemtap.h" + +extern struct irx_export_table _exp_mtapman; + +#define BANNER "FREEMTAP %s\n" +#define VERSION "v1.0" + +#define EF_UPDATE_SLOTS 0x1 +#define EF_EXIT_THREAD 0x2 + +// TODO: last sdk 3.1.0 and sdk 3.0.3 has MTAPMAN module version 0x03,0x10 +// Check what was changed, and maybe port changes. +// Note: currently is based on the last XMTAPMAN from BOOTROM: +// 0x02,0x02 +IRX_ID("multitap_manager", 2, 2); + +static s32 event_flag; +static s32 threadid_main; + +static u32 state_open[4]; +static u32 state_getcon[4]; +static u32 state_slots[4]; +static u8 in_buffer[256]; +static u8 out_buffer[256]; +static sio2_transfer_data_t td; + +s32 read_stat6c_bit(u32 bit, sio2_transfer_data_t *tdata) +{ + switch(bit) + { + case 0: return (tdata->stat6c >> 16) & 1; + case 1: return (tdata->stat6c >> 17) & 1; + case 2: return (tdata->stat6c >> 18) & 1; + case 3: return (tdata->stat6c >> 19) & 1; + case 4: return (tdata->stat6c >> 20) & 1; + case 5: return (tdata->stat6c >> 21) & 1; + case 6: return (tdata->stat6c >> 22) & 1; + case 7: return (tdata->stat6c >> 23) & 1; + case 8: return (tdata->stat6c >> 24) & 1; + case 9: return (tdata->stat6c >> 25) & 1; + case 10: return (tdata->stat6c >> 26) & 1; + case 11: return (tdata->stat6c >> 27) & 1; + case 12: return (tdata->stat6c >> 28) & 1; + case 13: return (tdata->stat6c >> 29) & 1; + case 14: return (tdata->stat6c >> 30) & 1; + case 15: return (tdata->stat6c >> 31) & 1; + default: return 0; + } +} + +void get_slot_number_setup_td(u32 port, u32 reg) +{ + u32 p = port | 0x2; + u32 i; + + td.port_ctrl1[p] = 0xFF020505; + td.port_ctrl2[p] = 0x00030064; + + td.regdata[reg] = (p & 0x3) | 0x180640; + + for(i=0; i < 6 ; i++) td.in[td.in_size + i] = 0; + + td.in[td.in_size] = 0x21; + + if(port < 2) + td.in[td.in_size + 1] = 0x12; + else + td.in[td.in_size + 1] = 0x13; + + td.in_size += 6; + td.out_size += 6; + td.in_dma.addr = 0; + td.out_dma.addr = 0; +} + +s32 get_slot_number_check_td(u32 bit) +{ + s32 res; + u32 i; + + if(read_stat6c_bit(bit, &td) != 1) + { + if(td.out[5] == 0x66) + res = -2; + else + res = td.out[3]; + } + else + { + res = -1; + } + + for(i=0; i < 250; i++) td.out[i] = td.out[i+6]; + + td.out_size -= 6; + + return res; +} +s32 get_slot_number(u32 port, u32 retries) +{ + u32 i,j; + s32 slots = -1; + + if(port >= 4) return -3; + + if(state_open[port] == 0) return -4; + + i = 0; + + while((slots < 0) && (i <= retries)) + { + sio2_mtap_transfer_init(); + + td.in_size = 0; + td.out_size = 0; + + for(j=0; j < 16; j++) td.regdata[j] = 0; + + get_slot_number_setup_td(port, 0); + sio2_transfer2(&td); + slots = get_slot_number_check_td(0); + + sio2_transfer_reset2(); + + if((slots == -2) || (slots >= 0)) return slots; + + i++; + //M_PRINTF("get_slot_number retry %i.\n", (int)i); + } + + return -4; +} + + +void update_slot_numbers_thread() +{ + while(1) + { + u32 resbits, port; + s32 slots; + + WaitEventFlag(event_flag, EF_UPDATE_SLOTS | EF_EXIT_THREAD, 0x11, &resbits); + + if(resbits & EF_EXIT_THREAD) + { + SetEventFlag(event_flag, 0x4); + ExitThread(); + } + + for(port=0; port < 4; port++) + { + if(state_open[port] == 1) + { + if(state_getcon[port] == 0) + slots = get_slot_number(port, 10); + else + slots = get_slot_number(port, 0); + + if(slots < 0) + { + state_slots[port] = 1; + state_getcon[port] = 0; + } + else + { + state_slots[port] = slots; + state_getcon[port] = 1; + } + } + } + + + } +} + +s32 change_slot_setup_td(u32 port, s32 slot, u32 reg) +{ + u32 p = port | 0x2; + u32 i; + + td.port_ctrl1[p] = 0xFF020505; + td.port_ctrl2[p] = 0x00030064; + + td.regdata[reg] = (p & 0x3) | 0x1c0740; + + for(i=0; i < 7; i++) td.in[td.in_size + i] = 0; + + td.in[td.in_size] = 0x21; + + if(port < 2) + { + td.in[td.in_size + 1] = 0x21; + } + else + { + td.in[td.in_size + 1] = 0x22; + } + + td.in[td.in_size + 2] = (u8)slot; + + td.in_size += 7; + td.out_size += 7; + td.in_dma.addr = 0; + td.out_dma.addr = 0; + + + return 0; +} + +s32 change_slot_check_td(u32 a) +{ + u32 i; + s32 res; + + if(td.out_size >= 7) + { + if(read_stat6c_bit(a, &td) != 1) + { + if(td.out[5] == 0x66) + res = -2; + else + res = td.out[5]; + + } + else + { + res = -1; + } + } + else + { + return -99; + } + + + for(i=0; i < 249; i++) + { + td.out[i] = td.out[i+7]; + } + + td.out_size -= 7; + + + return res; +} + +int change_slot(s32 *arg) +{ + u32 loop = 0; + u32 count = 4; + u32 reg = 0; + s32 data[4]; + u32 i, port; + + while((loop < 10) && (count != 0)) + { + count = 4; + reg = 0; + + td.in_size = 0; + td.out_size = 0; + + for(i=0; i < 16; i++) td.regdata[i] = 0; + + // Setup transfer data + for(port=0; port < 4; port++) + { + data[port] = -1; + + if(arg[port] >= 0) + { + if((state_open[port] == 1) && (state_getcon[port] == 1)) + { + if(state_slots[port] > arg[port]) + { + change_slot_setup_td(port, arg[port], reg); + + data[port] = port; + reg++; + } + else + { + arg[port+4] = -1; + } + + } + else + { + if(arg[port] == 0) + arg[port+4] = 1; + else + arg[port+4] = -1; + } + } + else + { + arg[port+4] = 0; + } + + } + + // Send transfer data and check result + if(reg > 0) + { + sio2_transfer2(&td); + + for(port=0; port < 4; port++) + { + if(data[port] >= 0) + { + s32 res = change_slot_check_td(data[port]); + + if(res == -2) + { + arg[port+4] = -1; + count--; + } + else + { + if(res >= 0) + { + if(res == arg[port]) + arg[port+4] = 1; + else + arg[port+4] = -1; + + count--; + } + } + } + else + { + count--; + } + } + } + + if(count != 0) loop++; + } + + for(i=0; i < 4; i++) + { + if(arg[i+4] < 0) + return 0; + } + + return 1; + +} + +int get_slots1(int port) +{ + return state_slots[port]; +} + +int get_slots2(int port) +{ + return state_slots[port]; +} + +void update_slot_numbers() +{ + SetEventFlag(event_flag, EF_UPDATE_SLOTS); +} + +s32 _start(char **argv, int argc) +{ + iop_event_t event; + iop_thread_t thread; + u32 i; + + printf(BANNER,VERSION); + + if(RegisterLibraryEntries(&_exp_mtapman) != 0) + { + M_PRINTF("RegisterLibraryEntries failed.\n"); + return 1; + } + + if(InitRpcServers() == 0) + { + M_PRINTF("Failed to setup RPC Servers.\n"); + return 1; + } + + event.attr = 2; + event.bits = 0; + + event_flag = CreateEventFlag(&event); + + if(event_flag < 0) + { + M_PRINTF("Could not create event flag (%i)\n.", (int)event_flag); + return 1; + } + + thread.attr = TH_C; + thread.thread = update_slot_numbers_thread; + thread.stacksize = 0x800; + thread.priority = 32; + + threadid_main = CreateThread(&thread); + + if(threadid_main < 0) + { + M_PRINTF("Could not create thread (%i)\n.", (int)threadid_main); + return 1; + } + + StartThread(threadid_main, 0); + + for(i=0; i < 4; i++) + { + state_open[i] = 0; + state_getcon[i] = 0; + state_slots[i] = 0; + } + + sio2_mtap_change_slot_set(change_slot); + sio2_mtap_get_slot_max_set(get_slots1); + sio2_mtap_get_slot_max2_set(get_slots2); + sio2_mtap_update_slots_set(update_slot_numbers); + + td.in = in_buffer; + td.out = out_buffer; + + return 0; +} + + +void shutdown() +{ + u32 i; + + sio2_mtap_change_slot_set(NULL); + sio2_mtap_get_slot_max_set(NULL); + sio2_mtap_get_slot_max2_set(NULL); + sio2_mtap_update_slots_set(NULL); + + for(i=0; i < 4; i++) + { + state_open[i] = 0; + state_getcon[i] = 0; + state_slots[i] = 0; + } +} + +s32 mtapPortOpen(u32 port) +{ + if(port < 4) + { + state_open[port] = 1; + + s32 res = get_slot_number(port, 10); + + if(res < 0) + { + state_getcon[port] = 0; + state_slots[port] = 1; + return res; + } + else + { + state_getcon[port] = 1; + state_slots[port] = res; + return 1; + } + } + + return 0; +} + +s32 mtapPortClose(u32 port) +{ + state_open[port] = 0; + state_getcon[port] = 0; + + return 1; +} + +s32 mtapGetConnection(u32 port) +{ + return state_getcon[port]; +} + +s32 mtapGetSlotNumber(u32 port) +{ + s32 res; + + if(port > 4) return -1; + + if(state_open[port] == 0) return 1; + + res = get_slot_number(port, 10); + + if(res >= 0) + return res; + else + return 1; +} + +s32 mtapChangeSlot(u32 port, u32 slot) +{ + s32 data[4]; + u32 i; + + if(port > 4) return 0; + + if(state_open[port] == 0) + { + M_PRINTF("mtap manager doesn't work\n"); + return -1; + } + + for(i=0; i < 4; i++) + data[i] = -1; + + data[port] = slot; + + sio2_mtap_transfer_init(); + + change_slot(data); + + sio2_transfer_reset2(); + + if(data[port] < 0) + { + M_PRINTF("Failed to change slot.\n"); + return data[port]; + } + else + { + M_PRINTF("Change slot complete.\n"); + return 1; + } +} + + + diff --git a/sps2_basement/hardware/mem/mtapman/src/freemtap.h b/sps2_basement/hardware/mem/mtapman/src/freemtap.h new file mode 100644 index 0000000..84c0785 --- /dev/null +++ b/sps2_basement/hardware/mem/mtapman/src/freemtap.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP multitap driver + */ + +#ifndef _FREEMTAP_H_ +#define _FREEMTAP_H_ + +#define MODNAME "freemtap" +#define M_PRINTF(format, args...) printf(MODNAME ": " format, ## args) + +// rpcservers.c +s32 InitRpcServers(); + +// freemtap.c +s32 mtapPortOpen(u32 port); +s32 mtapPortClose(u32 port); +s32 mtapGetConnection(u32 port); +s32 mtapGetSlotNumber(u32 port); +s32 mtapChangeSlot(u32 port, u32 slot); + +#endif + + diff --git a/sps2_basement/hardware/mem/mtapman/src/imports.lst b/sps2_basement/hardware/mem/mtapman/src/imports.lst new file mode 100644 index 0000000..614867a --- /dev/null +++ b/sps2_basement/hardware/mem/mtapman/src/imports.lst @@ -0,0 +1,51 @@ + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_StartThread +I_ExitThread +I_GetThreadId +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_SetEventFlag +I_WaitEventFlag +thevent_IMPORTS_end + +sifman_IMPORTS_start +I_sceSifInit +I_sceSifCheckInit +sifman_IMPORTS_end + +sifcmd_IMPORTS_start +I_sceSifInitRpc +I_sceSifRegisterRpc +I_sceSifSetRpcQueue +I_sceSifRpcLoop +sifcmd_IMPORTS_end + +#ifndef SIO2MAN_V2 +xsio2man_IMPORTS_start +#else +rsio2man_IMPORTS_start +#endif +I_sio2_mtap_transfer_init +I_sio2_transfer2 +I_sio2_transfer_reset2 +I_sio2_mtap_change_slot_set +I_sio2_mtap_get_slot_max_set +I_sio2_mtap_get_slot_max2_set +I_sio2_mtap_update_slots_set +#ifndef SIO2MAN_V2 +xsio2man_IMPORTS_end +#else +rsio2man_IMPORTS_end +#endif diff --git a/sps2_basement/hardware/mem/mtapman/src/irx_imports.h b/sps2_basement/hardware/mem/mtapman/src/irx_imports.h new file mode 100644 index 0000000..a68dc61 --- /dev/null +++ b/sps2_basement/hardware/mem/mtapman/src/irx_imports.h @@ -0,0 +1,31 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include +#include +#include +#include +#include +#ifndef SIO2MAN_V2 +#include +#else +#include +#endif + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/mem/mtapman/src/rpcservers.c b/sps2_basement/hardware/mem/mtapman/src/rpcservers.c new file mode 100644 index 0000000..bd7ea8a --- /dev/null +++ b/sps2_basement/hardware/mem/mtapman/src/rpcservers.c @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP multitap driver + */ + +#include "types.h" +#include "irx.h" +#include "stdio.h" +#include "freemtap.h" +#include "sifman.h" +#include "sifcmd.h" +#include "thbase.h" + +#define MTAPSERV_PORT_OPEN 0x80000901 +#define MTAPSERV_PORT_CLOSE 0x80000902 +#define MTAPSERV_GET_CONNECTION 0x80000903 +#define MTAPSERV_GET_SLOT_NUMBER 0x800009FE +#define MTAPSERV_CHANGE_SLOT 0x800009FF + + +static u32 sb[4]; // Server buffer + +static s32 threadid_rpc1; +static SifRpcDataQueue_t qd1; +static SifRpcServerData_t sd1; + +static s32 threadid_rpc2; +static SifRpcDataQueue_t qd2; +static SifRpcServerData_t sd2; + +static s32 threadid_rpc3; +static SifRpcDataQueue_t qd3; +static SifRpcServerData_t sd3; + +static s32 threadid_rpc4; +static SifRpcDataQueue_t qd4; +static SifRpcServerData_t sd4; + +static s32 threadid_rpc5; +static SifRpcDataQueue_t qd5; +static SifRpcServerData_t sd5; + + +void* rpc_server_change_slot(s32 fno, u32 *data, s32 size) +{ + data[1] = mtapChangeSlot( data[0], data[1] ); + + return data; +} + + +void rpc_thread_change_slot() +{ + if( sceSifCheckInit() == 0) + { + M_PRINTF("Sif not initialized.\n"); + sceSifInit(); + } + + sceSifInitRpc(0); + sceSifSetRpcQueue(&qd5, GetThreadId()); + sceSifRegisterRpc(&sd5, MTAPSERV_CHANGE_SLOT, (void*)rpc_server_change_slot, sb, 0, 0, &qd5); + sceSifRpcLoop(&qd5); +} + + +void* rpc_server_get_slot_number(s32 fno, u32 *data, s32 size) +{ + data[1] = mtapGetSlotNumber( data[0] ); + + return data; +} + + +void rpc_thread_get_slot_number() +{ + if( sceSifCheckInit() == 0) + { + M_PRINTF("Sif not initialized.\n"); + sceSifInit(); + } + + sceSifInitRpc(0); + sceSifSetRpcQueue(&qd4, GetThreadId()); + sceSifRegisterRpc(&sd4, MTAPSERV_GET_SLOT_NUMBER, (void*)rpc_server_get_slot_number, sb, 0, 0, &qd4); + sceSifRpcLoop(&qd4); +} + +void* RpcServerGetConnection(s32 fno, u32 *data, s32 size) +{ + data[1] = mtapGetConnection( data[0] ); + + return data; +} + +void RpcThreadGetConnection() +{ + if( sceSifCheckInit() == 0) + { + M_PRINTF("Sif not initialized.\n"); + sceSifInit(); + } + + sceSifInitRpc(0); + sceSifSetRpcQueue(&qd3, GetThreadId()); + sceSifRegisterRpc(&sd3, MTAPSERV_GET_CONNECTION, (void*)RpcServerGetConnection, sb, 0, 0, &qd3); + sceSifRpcLoop(&qd3); +} + +void* RpcServerPortClose(s32 fno, u32 *data, s32 size) +{ + data[1] = mtapPortClose( data[0] ); + + return data; +} + +void RpcThreadPortClose() +{ + if( sceSifCheckInit() == 0) + { + M_PRINTF("Sif not initialized.\n"); + sceSifInit(); + } + + sceSifInitRpc(0); + sceSifSetRpcQueue(&qd2, GetThreadId()); + sceSifRegisterRpc(&sd2, MTAPSERV_PORT_CLOSE, (void*)RpcServerPortClose, sb, 0, 0, &qd2); + sceSifRpcLoop(&qd2); +} + +void* RpcServerPortOpen(s32 fno, u32 *data, s32 size) +{ + + data[1] = mtapPortOpen( data[0] ); + + return data; +} + +void RpcThreadPortOpen() +{ + if( sceSifCheckInit() == 0) + { + M_PRINTF("Sif not initialized.\n"); + sceSifInit(); + } + + sceSifInitRpc(0); + sceSifSetRpcQueue(&qd1, GetThreadId()); + sceSifRegisterRpc(&sd1, MTAPSERV_PORT_OPEN, (void*)RpcServerPortOpen, sb, 0, 0, &qd1); + sceSifRpcLoop(&qd1); + +} + + + + + +// You should *not* setup 1 RPC server pr. function. Unfortunatly, this +// is what XMTAPMAN does, so we have to do the same to be compatible. +s32 InitRpcServers() +{ + iop_thread_t rpc_thread; + + // mtapPortOpen RPC Server + rpc_thread.attr = TH_C; + rpc_thread.thread = RpcThreadPortOpen; + rpc_thread.stacksize = 0x2000; + rpc_thread.priority = 32; + + threadid_rpc1 = CreateThread(&rpc_thread); + + if(threadid_rpc1 == 0) return 0; + + StartThread(threadid_rpc1, 0); + + // mtapPortClose RPC Server + rpc_thread.thread = RpcThreadPortClose; + + threadid_rpc2 = CreateThread(&rpc_thread); + + if(threadid_rpc2 == 0) return 0; + + StartThread(threadid_rpc2, 0); + + // mtapGetConnection RPC Server + rpc_thread.thread = RpcThreadGetConnection; + + threadid_rpc3 = CreateThread(&rpc_thread); + + if(threadid_rpc3 == 0) return 0; + + StartThread(threadid_rpc3, 0); + + // mtapGetSlotNumber RPC Server + rpc_thread.thread = rpc_thread_get_slot_number; + + threadid_rpc4 = CreateThread(&rpc_thread); + + if(threadid_rpc4 == 0) return 0; + + StartThread(threadid_rpc4, 0); + + // mtapChangeSlot RPC Server + rpc_thread.thread = rpc_thread_change_slot; + + threadid_rpc5 = CreateThread(&rpc_thread); + + if(threadid_rpc5 == 0) return 0; + + StartThread(threadid_rpc5, 0); + + return 1; +} diff --git a/sps2_basement/hardware/mem/padman/Makefile b/sps2_basement/hardware/mem/padman/Makefile new file mode 100644 index 0000000..ac11882 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/Makefile @@ -0,0 +1,20 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN_ALTNAMES ?= freepad.irx + +# IOP_CFLAGS += -DDEBUG + +IOP_INCS += -I$(PS2SDKSRC)/iop/system/sio2man/include + +IOP_OBJS = freepad.o rpcserver.o exports.o imports.o padInit.o padPortOpen.o padMiscFuncs.o sio2Cmds.o padData.o padCmds.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/mem/padman/README b/sps2_basement/hardware/mem/padman/README new file mode 100644 index 0000000..09e67c8 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/README @@ -0,0 +1,19 @@ +freepad is a free replacement module for XPADMAN. +freepad is based off XPADMAN v3.6, which is the last known version of XPADMAN. +It was originally based on a module around v3.0. + +I'd like to thank pukko for libpad(x), Hanimar for ps2dis, [RO]man for +padspecs.txt and Marcus R. Brown for sio2log. + +You can uncomment -DDEBUG in the makefile, to build a debug version which prints +debug output to stdout. + +- Lukasz Bruun + +Changelog +------------------------------------------------------------------------------- +2017-10-14 + - SP193, full update to v3.6 and bugfixes. + +2007-08-30 + - lukasz, initial release diff --git a/sps2_basement/hardware/mem/padman/src/exports.tab b/sps2_basement/hardware/mem/padman/src/exports.tab new file mode 100644 index 0000000..2baf7e9 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/exports.tab @@ -0,0 +1,24 @@ +DECLARE_EXPORT_TABLE(padman, 1, 2) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(padInit) + DECLARE_EXPORT(padEnd) + DECLARE_EXPORT(padPortOpen) + DECLARE_EXPORT(padPortClose) + DECLARE_EXPORT(padGetInBuffer) + DECLARE_EXPORT(padSetupEEButtonData) + DECLARE_EXPORT(padGetModeConfig) + DECLARE_EXPORT(padInfoAct) + DECLARE_EXPORT(padInfoComb) + DECLARE_EXPORT(padInfoMode) + DECLARE_EXPORT(padSetMainMode) + DECLARE_EXPORT(padSetActDirect) + DECLARE_EXPORT(padSetActAlign) + DECLARE_EXPORT(padGetButtonMask) + DECLARE_EXPORT(padSetButtonInfo); + +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/mem/padman/src/freepad.c b/sps2_basement/hardware/mem/padman/src/freepad.c new file mode 100644 index 0000000..8641bf4 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/freepad.c @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#include "irx.h" +#include "types.h" +#include "ctype.h" +#include "stdio.h" +#include "loadcore.h" +#include "sysclib.h" +#include "sysmem.h" +#include "thevent.h" +#include "thbase.h" +#include "rpcserver.h" +#include "freepad.h" + +extern struct irx_export_table _exp_padman; + +// TODO: last sdk 3.1.0 and sdk 3.0.3 has PADMAN module version 0x04,0x22 +// Check what was changed, and maybe port changes. +// Note: currently is based on the last XPADMAN from BOOTROM: +// 0x03,0x06 +IRX_ID("padman", 3, 6); + +extern int padman_init; +extern int thpri_hi; +extern int thpri_lo; + +extern int vblank_end; + +static int ParseParams(int argc, char *argv[]) +{ + int i, new_thpri_hi, new_thpri_lo; + const char *param; + + new_thpri_hi = PADMAN_THPRI_HI; + new_thpri_lo = PADMAN_THPRI_LO; + + if(argc > 1) + { + argv++; + + for(i = 1; i < argc; i++,argv++) + { + if(strncmp("thpri=", *argv, 6) == 0) + { + //Parse high priority + param = &(*argv)[6]; + if(isdigit(*param)) + new_thpri_hi = strtol(param, NULL, 10); + + //Skip value for high priority + while(isdigit(*param)) + param++; + + //Valid high priority parameter + if(new_thpri_hi - 9 < 115) + { + if(*param == ',') + { + ++param; + //Parse low priority + if(isdigit(*param)) + new_thpri_lo = strtol(param, NULL, 10); + + if(new_thpri_lo - 9 >= 115) + { + M_KPRINTF("invalid priority %d\n", new_thpri_lo); + return 0; + } + } + + if(new_thpri_lo < new_thpri_hi) + M_PRINTF("high prio thread must be higher than low prio thread\n"); + } + else + { + M_KPRINTF("invalid priority %d\n", new_thpri_hi); + return 0; + } + } + } + } + + thpri_hi = new_thpri_hi; + thpri_lo = new_thpri_lo; + + return 1; +} + +int _start(int argc, char *argv[]) +{ + padman_init = 0; + vblank_end = 0; + thpri_hi = PADMAN_THPRI_HI; + thpri_lo = PADMAN_THPRI_LO; + + D_PRINTF("Debug Version\n"); + + if(argc >= 2) + ParseParams(argc, argv); + + if(thpri_hi != PADMAN_THPRI_HI || thpri_lo != PADMAN_THPRI_LO) + M_PRINTF("thread priority: high=%d, low=%d\n", thpri_hi, thpri_lo); + + if(RegisterLibraryEntries(&_exp_padman) != 0) + { + M_PRINTF("RegisterLibraryEntries failed.\n"); + return MODULE_NO_RESIDENT_END; + } + + if(InitRpcServers(thpri_lo) == 0) + { + M_PRINTF("Failed to init RPC servers.\n"); + return MODULE_NO_RESIDENT_END; + } + + printf("Pad Driver for OSD\n"); + + return MODULE_RESIDENT_END; +} + +//This may have been a drop-in replacement for WaitEventFlag, which explains the similar, but unused 3rd and 4th parameters. +void WaitClearEvent(int eventflag, u32 bits, int mode, u32 *resbits_out) +{ + u32 resbits; + + WaitEventFlag(eventflag, bits | EF_EXIT_THREAD, WEF_OR, &resbits); + + if( resbits & EF_EXIT_THREAD ) + { //Yes, it's unused. Probably leftover code. + iop_thread_info_t tinfo; + + ReferThreadStatus(TH_SELF, &tinfo); + SetEventFlag(eventflag, EF_EXIT_THREAD); + ExitThread(); + } + + ClearEventFlag(eventflag, ~bits); +} diff --git a/sps2_basement/hardware/mem/padman/src/freepad.h b/sps2_basement/hardware/mem/padman/src/freepad.h new file mode 100644 index 0000000..b9daf70 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/freepad.h @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#ifndef __FREEPAD_H__ +#define __FREEPAD_H__ + +#include "irx.h" +#include "types.h" + +#define MODNAME "freepad" +#define M_PRINTF(format, args...) printf(MODNAME ": " format, ## args) +#define M_KPRINTF(format, args...) Kprintf(MODNAME ": " format, ## args) + +#ifdef DEBUG +#define D_PRINTF(format, args...) printf(MODNAME ": " format, ## args) +#else +#define D_PRINTF(a...) (void)0 +#endif + +#define PADMAN_THPRI_LO 46 +#define PADMAN_THPRI_HI 20 + +#define SB_STAT *((volatile unsigned int*)0xBD000040) + +/* + * Pad states + */ +#define PAD_STATE_DISCONN 0x00 +#define PAD_STATE_FINDPAD 0x01 +#define PAD_STATE_FINDCTP1 0x02 +#define PAD_STATE_EXECCMD 0x05 +#define PAD_STATE_STABLE 0x06 +#define PAD_STATE_ERROR 0x07 + +/* + * Pad request states + */ +#define PAD_RSTAT_COMPLETE 0x00 +#define PAD_RSTAT_FAILED 0x01 +#define PAD_RSTAT_BUSY 0x02 + +/* + * Connected pad type + */ +#define PAD_TYPE_NEJICON 0x2 +#define PAD_TYPE_KONAMIGUN 0x3 +#define PAD_TYPE_DIGITAL 0x4 +#define PAD_TYPE_ANALOG 0x5 +#define PAD_TYPE_NAMCOGUN 0x6 +#define PAD_TYPE_DUALSHOCK 0x7 + +#define PAD_MODEL_DUALSHOCK 0x1 +#define PAD_MODEL_DUALSHOCK2 0x3 + +#define MODE_CONFIG_NO_PAD 0x0 +#define MODE_CONFIG_QUERY_PAD 0x1 +#define MODE_CONFIG_READY 0x2 + +// PAD Tasks +#define TASK_NONE 0 +#define TASK_UPDATE_PAD 1 +#define TASK_QUERY_PAD 2 +#define TASK_PORT_CLOSE 3 +#define TASK_SET_MAIN_MODE 4 +#define TASK_SET_ACT_ALIGN 5 +#define TASK_SET_BUTTON_INFO 6 +#define TASK_SET_VREF_PARAM 7 + +// Main event flags +#define EF_UPDATE_PAD 0x0001 +#define EF_QUERY_PAD 0x0002 + +#define EF_SET_MAIN_MODE 0x0008 +#define EF_SET_ACT_ALIGN 0x0010 +#define EF_SET_SET_BUTTON_INFO 0x0020 +#define EF_SET_VREF_PARAM 0x0040 +#define EF_PAD_TRANSFER_START 0x0080 +#define EF_PAD_TRANSFER_DONE 0x0100 +#define EF_TASK_DONE 0x0200 +#define EF_PORT_CLOSE 0x0400 +#define EF_EXIT_THREAD 0x1000 + +// Vblank event flags +#define EF_VB_TRANSFER 0x0001 +#define EF_VB_TRANSFER_DONE 0x0004 +#define EF_VB_WAIT_THREAD_EXIT 0x0008 + +// Global Types +typedef struct +{ + int padEnd; + int eventflag; + int init; + int stopTransfer; + int tid_1; + int tid_2; +} vblankData_t; + +typedef struct +{ + u8 data[32]; + u32 actDirData[2]; + u32 actAlignData[2]; + u32 actData[4]; + u32 combData[4]; + u32 modeTable[2]; + u32 frame; + u32 findPadRetries; + u32 length; + u8 modeConfig; + u8 modeCurId; + u8 model; + u8 buttonDataReady; + u8 nrOfModes; + u8 modeCurOffs; + u8 nrOfActuators; + u8 numActComb; + u8 val_c6; + u8 mode; + u8 lock; + u8 actDirSize; + u8 state; + u8 reqState; + u8 currentTask; + u8 runTask; + u8 stat70bit; + u8 padding[11]; +} ee_paddata_t; + +typedef struct +{ + u32 frame; + u8 state; + u8 reqState; + u8 ok; + u8 unkn7; + u8 data[32]; + u32 length; + u8 request; + /** CTP=1/no config; CTP=2/config, acts... */ + u8 CTP; + /** 1, 2 or 3 */ + u8 model; + /** the data in the buffer is already corrected */ + u8 correction; + u8 errorCount; + u8 unk49[15]; +} ee_old_paddata_t; + +typedef struct +{ + ee_paddata_t ee_pdata __attribute__((aligned(4))); + ee_old_paddata_t ee_old_pdata __attribute__((aligned(4))); + u8 modeConfig; + u8 modeCurId; + u8 model; + u8 numModes; + u8 modeCurOffs; + u8 numActuators; + u8 numActComb; + u8 disconnected; + union { + u8 data[4][4]; + u32 data32[4]; + } actData; + union { + u8 data[4][4]; + u32 data32[4]; + } combData; + union { + u16 data[4]; + u32 data32[2]; + } modeTable; + u8 buttonInfo[4]; + u8 buttonMask[4]; + u8 modeParam[12]; + u16 val_c4; // unused + u16 val_c6; + u8 inbuffer[32]; + u8 outbuffer[32]; + u8 buttonStatus[32]; + u32 buttonDataReady; + u8 mode; + u8 lock; + union { + u8 data[8]; + u32 data32[8 / sizeof(u32)]; + } ee_actDirectData; + s16 ee_actDirectSize; + union { + u8 data[8]; + u32 data32[8 / sizeof(u32)]; + } ee_actAlignData; + u16 state; + u16 reqState; + u32 frame; + u32 padarea_ee_addr; + u32 findPadRetries; + s32 updatepadTid; + s32 querypadTid; + s32 unused158; // probably unused thread id + s32 setmainmodeTid; + s32 setactalignTid; + s32 setbuttoninfoTid; + s32 setvrefparamTid; + int eventflag; + u16 port; + u16 slot; + u32 currentTask; + u32 runTask; + u32 taskTid; + u32 stat70bit; + u32 val_184; // Set, but unused +} padState_t; + +// Internal functions +void WaitClearEvent(int eventflag, u32 bits, int mode, u32 *resbits_out); +int VblankStart(void *arg); +int VblankEnd(void *arg); + +// Exported/RPC functions +s32 padInit(void * ee_addr); +s32 padEnd(void); +s32 padPortClose(s32 port, s32 slot, s32 wait); +s32 padPortOpen(s32 port, s32 slot, s32 pad_area_ee_addr, u32 *buf); +u32 padSetMainMode(u32 port, u32 slot, u32 mode, u32 lock); +u32 padSetActDirect(u32 port, u32 slot, u8 *actData); +u32 padSetActAlign(u32 port, u32 slot, u8 *actData); +u32 padGetButtonMask(u32 port, u32 slot); +u32 padSetButtonInfo(u32 port, u32 slot, u32 info); +u32 padSetVrefParam(u32 port, u32 slot, u8 *vparam); +s32 padInfoAct(u32 port, u32 slot, s32 act, u32 val); +s32 padInfoComb(u32 port, u32 slot, s32 listno, u32 offs); +s32 padInfoMode(u32 port, u32 slot, s32 term, u32 offs); +u32 padGetPortMax(void); +u32 padGetSlotMax(u32 port); +u32 padGetModVersion(void); + +#endif diff --git a/sps2_basement/hardware/mem/padman/src/imports.lst b/sps2_basement/hardware/mem/padman/src/imports.lst new file mode 100644 index 0000000..e1527d9 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/imports.lst @@ -0,0 +1,80 @@ + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +intrman_IMPORTS_start +I_CpuEnableIntr +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_DeleteThread +I_StartThread +I_ExitThread +I_GetThreadId +I_ReferThreadStatus +I_iReferThreadStatus +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_DeleteEventFlag +I_SetEventFlag +I_iSetEventFlag +I_ClearEventFlag +I_WaitEventFlag +thevent_IMPORTS_end + +sifman_IMPORTS_start +I_sceSifInit +I_sceSifSetDma +I_sceSifDmaStat +I_sceSifCheckInit +sifman_IMPORTS_end + +sifcmd_IMPORTS_start +I_sceSifInitRpc +I_sceSifRegisterRpc +I_sceSifSetRpcQueue +I_sceSifRpcLoop +sifcmd_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_look_ctype_table +I_strncmp +I_strtol +sysclib_IMPORTS_end + +vblank_IMPORTS_start +I_RegisterVblankHandler +I_ReleaseVblankHandler +vblank_IMPORTS_end + +#ifndef SIO2MAN_V2 +xsio2man_IMPORTS_start +#else +rsio2man_IMPORTS_start +#endif +I_sio2_stat70_get +I_sio2_pad_transfer_init +I_sio2_transfer2 +I_sio2_transfer_reset2 +I_sio2_mtap_change_slot +I_sio2_mtap_get_slot_max +I_sio2_mtap_update_slots +#ifndef SIO2MAN_V2 +xsio2man_IMPORTS_end +#else +rsio2man_IMPORTS_end +#endif + +sysmem_IMPORTS_start +I_Kprintf +sysmem_IMPORTS_end diff --git a/sps2_basement/hardware/mem/padman/src/irx_imports.h b/sps2_basement/hardware/mem/padman/src/irx_imports.h new file mode 100644 index 0000000..cc3bb50 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/irx_imports.h @@ -0,0 +1,34 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef SIO2MAN_V2 +#include +#else +#include +#endif +#include + +#endif diff --git a/sps2_basement/hardware/mem/padman/src/padCmds.c b/sps2_basement/hardware/mem/padman/src/padCmds.c new file mode 100644 index 0000000..c71f64d --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/padCmds.c @@ -0,0 +1,748 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#include "types.h" +#include "thevent.h" +#include "freepad.h" +#include "sio2Cmds.h" +#include "padData.h" + +static void shiftarray(u8 *buf) +{ + u8 temp[32]; + u32 i; + + for(i=0; i < 32; i++) + temp[i] = buf[i]; + + buf[0] = 0xFF; + + for(i=0; i < 31; i++) + buf[i+1] = temp[i]; +} + +u32 PadIsSupported(padState_t *pstate) +{ + u32 res; + u32 ret = 0; + + res = sio2CmdGetPortCtrl1(0, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(0, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res); + + res = pdGetRegData(0); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(0); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(0); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetReadData(0, pstate->inbuffer); + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + res = pdGetError(pstate->port, pstate->slot); + + if(res == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if(pstate->stat70bit == 1) shiftarray(pstate->outbuffer); + + if((pstate->outbuffer[1] != 0) + && (sio2cmdCheckId(pstate->outbuffer[1]) == 1)) + { //Twice? Okay... + if((pstate->outbuffer[1] != 0) + && (sio2cmdCheckId(pstate->outbuffer[1]) == 1)) + { + pstate->modeCurId = pstate->outbuffer[1]; + ret = 1; + } + } + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + return ret; +} + +u32 VrefParam(u32 val, padState_t *pstate) +{ + u32 res; + u32 ret = 0; + + res = sio2CmdGetPortCtrl1(PAD_ID_CONFIG, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(PAD_ID_CONFIG, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res), + + res = pdGetRegData(PAD_ID_CONFIG); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(PAD_ID_CONFIG); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(PAD_ID_CONFIG); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetSetVrefParam(PAD_ID_CONFIG, pstate->inbuffer); + + pstate->inbuffer[3] = val; + pstate->inbuffer[4] = pstate->modeParam[val]; + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if(pstate->stat70bit == 1) shiftarray(pstate->outbuffer); + + if(pstate->outbuffer[1] == PAD_ID_CONFIG) ret = 1; + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + return ret; +} + +u32 ReadData(padState_t *pstate) +{ + u32 res, i; + u32 ret = 0; + + res = sio2CmdGetPortCtrl1(pstate->modeCurId, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(pstate->modeCurId, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res); + + res = pdGetRegData( pstate->modeCurId ); + + pdSetRegData( pstate->port, pstate->slot, res); + + res = pdGetInSize( pstate->modeCurId ); + + pdSetInSize( pstate->port, pstate->slot, res); + + res = pdGetOutSize( pstate->modeCurId ); + + pdSetOutSize(pstate->port, pstate->slot, res); + + for(i=0; i < 32; i++) + { + pstate->inbuffer[i] = 0; + pstate->outbuffer[i] = 0; + } + + sio2CmdSetReadData(pstate->modeCurId, pstate->inbuffer); + + for(i=0; i < pstate->ee_actDirectSize; i++) + { + if(pstate->ee_actAlignData.data[i] == 0xFF) + pstate->inbuffer[i+3] = pstate->ee_actAlignData.data[i]; + else + pstate->inbuffer[i+3] = pstate->ee_actDirectData.data[i]; + } + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag( pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent( pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + res = pdGetError(pstate->port, pstate->slot); + + if(res == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + ret = 1; + + if(pstate->stat70bit == 1) shiftarray( pstate->outbuffer ); + } + + SetEventFlag( pstate->eventflag, EF_TASK_DONE); + + return ret; +} + +u32 EnterConfigMode(u8 val, padState_t *pstate) +{ + u32 res; + u32 ret = 0; + + res = sio2CmdGetPortCtrl1(val, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(val, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res); + + res = pdGetRegData(val); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(val); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(val); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetEnterConfigMode(val, pstate->inbuffer); + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if( pstate->stat70bit == 1) + { + shiftarray(pstate->outbuffer); + } + + ret = 1; + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + + return ret; +} + +u32 QueryModel(padState_t *pstate) +{ + u32 res; + u32 ret = 0; + + res = sio2CmdGetPortCtrl1(PAD_ID_CONFIG, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(PAD_ID_CONFIG, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res); + + res = pdGetRegData(PAD_ID_CONFIG); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(PAD_ID_CONFIG); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(PAD_ID_CONFIG); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetQueryModel(PAD_ID_CONFIG, pstate->inbuffer); + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if( pstate->stat70bit == 1) shiftarray( pstate->outbuffer ); + + if( pstate->outbuffer[1] == PAD_ID_CONFIG) + { + pstate->numActuators = pstate->outbuffer[6]; + pstate->model = pstate->outbuffer[3]; + pstate->numModes = pstate->outbuffer[4]; + pstate->modeCurOffs = pstate->outbuffer[5]; + pstate->numActComb = pstate->outbuffer[7]; + + if( pstate->numActuators > 4) pstate->numActuators = 4; + if( pstate->numActComb > 4 ) pstate->numActComb = 4; + if( pstate->numModes > 4) pstate->numModes = 4; + + ret = 1; + } + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + return ret; +} + +u32 SetMainMode(padState_t *pstate) +{ + u32 ret = 0; + u32 res; + + res = sio2CmdGetPortCtrl1(PAD_ID_CONFIG, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(PAD_ID_CONFIG, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res); + + res = pdGetRegData(PAD_ID_CONFIG); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(PAD_ID_CONFIG); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(PAD_ID_CONFIG); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetSetMainMode(PAD_ID_CONFIG, pstate->inbuffer); + + pstate->inbuffer[3] = pstate->mode; + pstate->inbuffer[4] = pstate->lock; + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if(pstate->stat70bit == 1) shiftarray( pstate->outbuffer); + + if(pstate->outbuffer[1] == PAD_ID_CONFIG) ret = 1; + + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + return ret; +} + +u32 QueryAct(u32 actuator, padState_t *pstate) +{ + u32 ret = 0; + u32 res; + + res = sio2CmdGetPortCtrl1(PAD_ID_CONFIG, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(PAD_ID_CONFIG, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res); + + res = pdGetRegData(PAD_ID_CONFIG); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(PAD_ID_CONFIG); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(PAD_ID_CONFIG); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetQueryAct(PAD_ID_CONFIG, pstate->inbuffer); + + pstate->inbuffer[3] = actuator; + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if(pstate->stat70bit == 1) shiftarray( pstate->outbuffer ); + + if(pstate->outbuffer[1] == PAD_ID_CONFIG) + { + u8 *actData = pstate->actData.data[actuator]; + + actData[0] = pstate->outbuffer[5]; + actData[1] = pstate->outbuffer[6]; + actData[2] = pstate->outbuffer[7]; + actData[3] = pstate->outbuffer[8]; + + ret = 1; + } + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + return ret; +} + +u32 QueryComb(u32 val, padState_t *pstate) +{ + u32 ret = 0; + u32 res; + + res = sio2CmdGetPortCtrl1(PAD_ID_CONFIG, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(PAD_ID_CONFIG, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res), + + res = pdGetRegData(PAD_ID_CONFIG); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(PAD_ID_CONFIG); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(PAD_ID_CONFIG); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetQueryComb(PAD_ID_CONFIG, pstate->inbuffer); + + pstate->inbuffer[3] = val; + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if(pstate->stat70bit == 1) shiftarray(pstate->outbuffer); + + if(pstate->outbuffer[1] == PAD_ID_CONFIG) + { + u8 *data = pstate->combData.data[val]; + + data[0] = pstate->outbuffer[5]; + data[1] = pstate->outbuffer[6]; + data[2] = pstate->outbuffer[7]; + data[3] = pstate->outbuffer[8]; + + ret = 1; + } + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + + return ret; +} + +u32 QueryMode(u32 val, padState_t *pstate) +{ + u32 res; + u32 ret = 0; + + res = sio2CmdGetPortCtrl1(PAD_ID_CONFIG, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(PAD_ID_CONFIG, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res), + + res = pdGetRegData(PAD_ID_CONFIG); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(PAD_ID_CONFIG); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(PAD_ID_CONFIG); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetQueryMode(PAD_ID_CONFIG, pstate->inbuffer); + + pstate->inbuffer[3] = val; + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if(pstate->stat70bit == 1) shiftarray(pstate->outbuffer); + + if(pstate->outbuffer[1] == PAD_ID_CONFIG) + { + u16 *modeTable = pstate->modeTable.data; + + modeTable[val] = (pstate->outbuffer[5] << 8) | pstate->outbuffer[6]; + + ret = 1; + } + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + return ret; +} + +u32 ExitConfigMode(padState_t *pstate) +{ + u32 res; + u32 ret = 0; + + res = sio2CmdGetPortCtrl1(PAD_ID_CONFIG, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(PAD_ID_CONFIG, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res), + + res = pdGetRegData(PAD_ID_CONFIG); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(PAD_ID_CONFIG); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(PAD_ID_CONFIG); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetExitConfigMode(PAD_ID_CONFIG, pstate->inbuffer); + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if(pstate->stat70bit == 1) shiftarray(pstate->outbuffer); + + ret = 1; + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + return ret; +} + +u32 SetActAlign(padState_t *pstate) +{ + u32 res, i; + u32 ret = 0; + + res = sio2CmdGetPortCtrl1(PAD_ID_CONFIG, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(PAD_ID_CONFIG, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res), + + res = pdGetRegData(PAD_ID_CONFIG); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(PAD_ID_CONFIG); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(PAD_ID_CONFIG); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetSetActAlign(PAD_ID_CONFIG, pstate->inbuffer); + + for(i=0; i < 6; i++) + pstate->inbuffer[3+i] = pstate->ee_actAlignData.data[i]; + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if(pstate->stat70bit == 1) shiftarray(pstate->outbuffer); + + if(pstate->outbuffer[1] == PAD_ID_CONFIG) ret = 1; + } + + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + return ret; +} + +u32 QueryButtonMask(padState_t *pstate) +{ + u32 res; + u32 ret = 0; + + res = sio2CmdGetPortCtrl1(PAD_ID_CONFIG, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(PAD_ID_CONFIG, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res), + + res = pdGetRegData(PAD_ID_CONFIG); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(PAD_ID_CONFIG); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(PAD_ID_CONFIG); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetQueryButtonMask(PAD_ID_CONFIG, pstate->inbuffer); + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if(pstate->stat70bit == 1) shiftarray(pstate->outbuffer); + + if(pstate->outbuffer[8] == 0x5A) + { + pstate->buttonMask[0] = pstate->outbuffer[3]; + pstate->buttonMask[1] = pstate->outbuffer[4]; + pstate->buttonMask[2] = pstate->outbuffer[5]; + pstate->buttonMask[3] = pstate->outbuffer[6]; + } + else + { + pstate->buttonMask[0] = 0; + pstate->buttonMask[1] = 0; + pstate->buttonMask[2] = 0; + pstate->buttonMask[3] = 0; + } + + ret = 1; + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + return ret; +} + +u32 SetButtonInfo(padState_t *pstate) +{ + u32 res, i; + u32 ret = 0; + + res = sio2CmdGetPortCtrl1(PAD_ID_CONFIG, pstate->stat70bit, pstate->model); + + pdSetCtrl1(pstate->port, pstate->slot, res); + + res = sio2CmdGetPortCtrl2(PAD_ID_CONFIG, pstate->stat70bit); + + pdSetCtrl2(pstate->port, pstate->slot, res), + + res = pdGetRegData(PAD_ID_CONFIG); + + pdSetRegData(pstate->port, pstate->slot, res); + + res = pdGetInSize(PAD_ID_CONFIG); + + pdSetInSize(pstate->port, pstate->slot, res); + + res = pdGetOutSize(PAD_ID_CONFIG); + + pdSetOutSize(pstate->port, pstate->slot, res); + + sio2CmdSetSetButtonInfo(PAD_ID_CONFIG, pstate->inbuffer); + + for(i=0; i < 4; i++) + pstate->inbuffer[3+i] = pstate->buttonInfo[i]; + + pdSetInBuffer(pstate->port, pstate->slot, 0, pstate->inbuffer); + + SetEventFlag(pstate->eventflag, EF_PAD_TRANSFER_START); + + WaitClearEvent(pstate->eventflag, EF_PAD_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( pdGetError(pstate->port, pstate->slot) == 0) + { + pdGetOutBuffer(pstate->port, pstate->slot, 0, pstate->outbuffer); + + if(pstate->stat70bit == 1) shiftarray(pstate->outbuffer); + + if(pstate->outbuffer[1] == PAD_ID_CONFIG) ret = 1; + } + + SetEventFlag(pstate->eventflag, EF_TASK_DONE); + + return ret; +} diff --git a/sps2_basement/hardware/mem/padman/src/padCmds.h b/sps2_basement/hardware/mem/padman/src/padCmds.h new file mode 100644 index 0000000..2c9d841 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/padCmds.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#ifndef __FREEPAD_PADCMDS_H__ +#define __FREEPAD_PADCMDS_H__ + +u32 PadIsSupported(padState_t *pstate); +u32 ReadData(padState_t *pstate); +u32 QueryModel(padState_t *pstate); +u32 SetMainMode(padState_t *pstate); +u32 QueryAct(u32 actuator, padState_t *pstate); +u32 QueryComb(u32 val, padState_t *pstate); +u32 QueryMode(u32 val, padState_t *pstate); +u32 EnterConfigMode(u8 val, padState_t *pstate); +u32 ExitConfigMode(padState_t *pstate); +u32 SetActAlign(padState_t *pstate); +u32 QueryButtonMask(padState_t *pstate); +u32 VrefParam(u32 val, padState_t *pstate); +u32 SetButtonInfo(padState_t *pstate); + +#endif + diff --git a/sps2_basement/hardware/mem/padman/src/padData.c b/sps2_basement/hardware/mem/padman/src/padData.c new file mode 100644 index 0000000..475b284 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/padData.c @@ -0,0 +1,526 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#include "irx.h" +#include "types.h" +#include "sio2man.h" +#include "xsio2man.h" +#include "sifman.h" +#include "sio2Cmds.h" +#include "padData.h" +#include "stdio.h" +#include "freepad.h" + +typedef struct +{ + u32 active; + u32 unused_4; + u32 unused_8; + u32 stat70bit; + u32 in_size; + u32 out_size; + u8 in_buffer[32]; + u8 out_buffer[32]; + u32 port_ctrl1; + u32 port_ctrl2; + u32 reg_data; + u32 error; +} padData_t; + +static padData_t padData[2][4]; + +static sio2_transfer_data_t sio2_td; +static u8 sio2_in_buffer[256]; +static u8 sio2_out_buffer[256]; +static s32 change_slot_buffer[8]; + +static int transferCount; + +u32 pdGetInSize(u8 id) +{ + if(id == 0) id = PAD_ID_DIGITAL; + + return (PAD_ID_LO(id)*2)+3; +} + +u32 pdGetOutSize(u8 id) +{ + if(id == 0) id = PAD_ID_DIGITAL; + + return (PAD_ID_LO(id)*2)+3; +} + +u32 pdGetRegData(u32 id) +{ + u32 ret1, ret2; + + ret1 = pdGetInSize((u8)id); + + ret2 = pdGetOutSize((u8)id); + + return ((ret2 & 0x1FF) << 18) | ((ret1 & 0x1FF) << 8) | 0x40; +} + +u32 pdSetRegData(u32 port, u32 slot, u32 reg_data) +{ + if(port < 2) + { + padData[port][slot].reg_data = reg_data; + return 1; + } + + return 0; + +} + +u32 setupReadData(u32 port, u32 slot, u32 val) +{ + u32 res; + u8 buf[32]; + + res = sio2CmdGetPortCtrl1(0, val, 0); + + pdSetCtrl1(port, slot, res); + + res = sio2CmdGetPortCtrl2(0, val); + + pdSetCtrl2(port, slot, res); + + + res = pdGetRegData(0); + + pdSetRegData(port, slot, res); + + + res = pdGetInSize(0); + + pdSetInSize(port, slot, res); + + res = pdGetOutSize(0); + + pdSetOutSize(port, slot, res); + + sio2CmdSetReadData(0, buf); + + pdSetInBuffer(port, slot, 0, buf); + + return 1; +} + +u32 pdSetActive(u32 port, u32 slot, u32 active) +{ + u32 res = padData[port][slot].active; + + padData[port][slot].active = active; + + return res; +} + +u32 pdIsActive(u32 port, u32 slot) +{ + return padData[port][slot].active; +} + +static u32 mtapChangeSlot(u32 slot) +{ + change_slot_buffer[0] = -1; + change_slot_buffer[1] = -1; + change_slot_buffer[2] = -1; + change_slot_buffer[3] = -1; + + if( (padData[0][slot].active == 0) && (padData[1][slot].active == 0) ) + return 0; + + if(padData[0][slot].active == 1) + change_slot_buffer[0] = slot; + + if(padData[1][slot].active == 1) + change_slot_buffer[1] = slot; + + sio2_mtap_change_slot(change_slot_buffer); + + return 1; +} + +u32 pdSetStat70bit(u32 port, u32 slot, u32 val) +{ + u32 ret = padData[port][slot].stat70bit; + + padData[port][slot].stat70bit = val; + + return ret; +} + +static u32 setupTransferData(u32 index, u32 port, u32 slot) +{ + + if(padData[port][slot].in_size > 0) + { + int i; + + for(i=0; i < padData[port][slot].in_size; i++) + { + sio2_td.in[sio2_td.in_size] = padData[port][slot].in_buffer[i]; + sio2_td.in_size++; + } + } + + sio2_td.out_size += padData[port][slot].out_size; + + sio2_td.port_ctrl1[port] = padData[port][slot].port_ctrl1; + sio2_td.port_ctrl2[port] = padData[port][slot].port_ctrl2; + sio2_td.regdata[index] = (padData[port][slot].reg_data & 0xFFFFFFFC) | (port & 0x3); + + sio2_td.regdata[index+1] = 0; + + return (index+1); +} + +u32 readStat6cBit(u32 bit, sio2_transfer_data_t *td) +{ + return( (td->stat6c & (0x00010000 << bit)) != 0); +} + +u32 readSio2OutBuffer(u32 bit, u32 port, u32 slot) +{ + if(((sio2_td.stat6c >> 13) & 0x1) == 1) + { + padData[port][slot].error = 1; + return 0; + } + else + { + if(readStat6cBit(bit, &sio2_td) == 1) + { + padData[port][slot].error = 1; + return 0; + } + else + { + padData[port][slot].error = 0; + + if( padData[port][slot].out_size > 0) + { + int i; + + for(i=0; i < padData[port][slot].out_size; i++) + { + padData[port][slot].out_buffer[i] = sio2_td.out[sio2_td.out_size]; + sio2_td.out_size++; + } + } + + return 1; + } + } +} + +u32 padTransfer(u32 slot) +{ + u32 stat70; + u32 trans_count = 0, port0_start = 0, port1_start = 0; + u32 val_port0 = 0; + u32 val_port1 = 0; + + sio2_td.in_size = 0; + sio2_td.out_size = 0; + sio2_td.in_dma.addr = 0; + sio2_td.out_dma.addr = 0; + + stat70 = sio2_stat70_get(); + + pdSetStat70bit(0, slot, (stat70 >> 4) & 1); + pdSetStat70bit(1, slot, (stat70 >> 5) & 1); + + if( padData[0][slot].active == 1 ) + { + if(change_slot_buffer[4] == 1) + { + val_port0 = 1; + port0_start = 0; + trans_count = setupTransferData(0, 0, slot); + } + } + + if( padData[1][slot].active == 1 ) + { + if(change_slot_buffer[5] == 1) + { + val_port1 = 1; + port1_start = trans_count; + trans_count = setupTransferData(trans_count, 1, slot); + } + } + + /* These two blocks of code change position before v3.6. + At v3.3 and earlier, they were within the transfer block below. At v3.0, there were no checks on change_slot_buffer. */ + if(padData[0][slot].active == 1) + { + if(change_slot_buffer[4] != 1) + padData[0][slot].error = 0xA; + } + + if(padData[1][slot].active == 1) + { + if(change_slot_buffer[5] != 1) + padData[1][slot].error = 0xA; + } + + if(trans_count != 0) + { + sio2_transfer2( &sio2_td ); + + sio2_td.out_size = 0; + + if(val_port0 == 1) + { + readSio2OutBuffer(port0_start, 0, slot); + sio2_td.out_size = padData[0][slot].out_size; + } + + if(val_port1 == 1) + { + readSio2OutBuffer(port1_start, 1, slot); + sio2_td.out_size = padData[1][slot].out_size; + } + + return 1; + } + + return 0; +} + +void pdTransfer(void) +{ + u32 slot; + + sio2_pad_transfer_init(); + + transferCount++; + + for(slot=0; slot < 4; slot++) + { + if( (padData[0][slot].active == 1) || (padData[1][slot].active == 1) ) + { + if(slot > 0) mtapChangeSlot(slot); + + padTransfer(slot); + } + } + + mtapChangeSlot(0); + + sio2_transfer_reset2(); +} + +u32 pdGetStat70bit(u32 port, u32 slot) +{ + return padData[port][slot].stat70bit; +} + +void pdReset(void) +{ + int i,j; + + for(i=0; i < 2; i++) + { + for(j=0; j < 4; j++) + { + padData[i][j].active = 0; + padData[i][j].stat70bit = 0; //This is probably more correct, compared to the original line (below) + } + + //padData[i+1][0].stat70bit = 0; //BUG: can cause buffer overrun. + } + + sio2_td.in = sio2_in_buffer; + sio2_td.out = sio2_out_buffer; +} + +//In versions before v3.6, only the slot argument was present. +static u32 SlotCheckConnection(u32 port, u32 slot) +{ + u32 stat70; + + sio2_td.in_size = 0; + sio2_td.out_size = 0; + sio2_td.out_dma.addr = 0; + sio2_td.in_dma.addr = 0; + + if(change_slot_buffer[4+port] == 1) + { //In versions before v3.6, this outer check did not exist. + stat70 = sio2_stat70_get(); + + //In versions before v3.6, stat70 is always set regardless of the slot selected. + switch(port) + { + case 0: + pdSetStat70bit(0, slot, (stat70 >> 4) & 0x1); + break; + case 1: + pdSetStat70bit(1, slot, (stat70 >> 5) & 0x1); + break; + } + + //In versions before v3.6, there used to be checks on change_slot_buffer[] and independent calls to setupTransferData, for each port (very much like padTransfer). + setupTransferData(0, port, slot); + + //As a result, there is neither a check on whether there is data to send. + sio2_transfer2( &sio2_td ); + + sio2_td.out_size = 0; + + //There used to be independent calls to readSio2OutBuffer for each port too. + readSio2OutBuffer(0, port, slot); + sio2_td.out_size = padData[port][slot].out_size; + + //This used to be per port too. + if(change_slot_buffer[4+port] != 1) + padData[port][slot].error = 0xA; + + return 1; + } + + return 0; +} + +u32 pdCheckConnection(u32 port, u32 slot) +{ + u32 res; + u32 ret = 0; + + sio2_pad_transfer_init(); + + change_slot_buffer[0] = slot; + change_slot_buffer[1] = slot; + change_slot_buffer[2] = -1; + change_slot_buffer[3] = -1; + + sio2_mtap_change_slot(change_slot_buffer); + + res = pdGetStat70bit(0, slot); + setupReadData(0, slot, res); + + res = pdGetStat70bit(1, slot); + setupReadData(1, slot, res); + + + if(SlotCheckConnection(port, slot) == 1) + { + if( padData[port][slot].error == 0 ) + ret = 1; + } + + change_slot_buffer[0] = 0; + change_slot_buffer[1] = 0; + change_slot_buffer[2] = -1; + change_slot_buffer[3] = -1; + + sio2_mtap_change_slot(change_slot_buffer); + + sio2_transfer_reset2(); + + return ret; +} + +s32 pdGetError(u32 port, u32 slot) +{ + if(port < 2) + return padData[port][slot].error; + else + return -1; +} + +u32 pdSetCtrl1(u32 port, u32 slot, u32 ctrl) +{ + if(port < 2) + { + padData[port][slot].port_ctrl1 = ctrl; + return 1; + } + + return 0; +} + +u32 pdSetCtrl2(u32 port, u32 slot, u32 ctrl) +{ + if(port < 2) + { + padData[port][slot].port_ctrl2 = ctrl; + return 1; + } + + return 0; + +} + +u32 pdSetInSize(u32 port, u32 slot, u32 size) +{ + if(port < 2) + { + padData[port][slot].in_size = size; + return size; + } + + return 0; +} + +u32 pdSetOutSize(u32 port, u32 slot, u32 size) +{ + if(port < 2) + { + padData[port][slot].out_size = size; + return size; + } + + return 0; + +} + +u32 pdSetInBuffer(u32 port, u32 slot, u32 size, const u8 *buf) +{ + if(port < 2) + { + if(size == 0) size = padData[port][slot].in_size; + + if(size > 0) + { + int i; + + for(i=0; i < size; i++) + padData[port][slot].in_buffer[i] = buf[i]; + } + + return size; + } + + return 0; +} + +u32 pdGetOutBuffer(u32 port, u32 slot, u32 size, u8 *buf) +{ + if(port < 2) + { + if(size == 0) size = padData[port][slot].out_size; + + if(size > 0) + { + int i; + + for(i=0; i < size; i++) + buf[i] = padData[port][slot].out_buffer[i]; + } + + return size; + } + + return 0; +} diff --git a/sps2_basement/hardware/mem/padman/src/padData.h b/sps2_basement/hardware/mem/padman/src/padData.h new file mode 100644 index 0000000..5f369b8 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/padData.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#ifndef __FREEPAD_PADDATA_H__ +#define __FREEPAD_PADDATA_H__ + + +void pdReset(void); +void pdTransfer(void); + +u32 pdSetCtrl1(u32 port, u32 slot, u32 ctrl); +u32 pdSetCtrl2(u32 port, u32 slot, u32 ctrl); + +u32 pdSetInBuffer(u32 port, u32 slot, u32 size, const u8 *buf); +u32 pdGetOutBuffer(u32 port, u32 slot, u32 size, u8 *buf); + +u32 pdSetInSize(u32 port, u32 slot, u32 size); +u32 pdSetOutSize(u32 port, u32 slot, u32 size); + +u32 pdGetInSize(u8 id); +u32 pdGetOutSize(u8 id); + +u32 pdSetRegData(u32 port, u32 slot, u32 reg_data); +u32 pdGetRegData(u32 id); + +u32 pdIsActive(u32 port, u32 slot); +u32 pdSetActive(u32 port, u32 slot, u32 active); + +u32 pdGetStat70bit(u32 port, u32 slot); +u32 pdSetStat70bit(u32 port, u32 slot, u32 val); + +s32 pdGetError(u32 port, u32 slot); + +u32 pdCheckConnection(u32 port, u32 slot); + + + + +#endif + diff --git a/sps2_basement/hardware/mem/padman/src/padInit.c b/sps2_basement/hardware/mem/padman/src/padInit.c new file mode 100644 index 0000000..acafd6e --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/padInit.c @@ -0,0 +1,748 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#include "types.h" +#include "freepad.h" +#include "stdio.h" +#include "thevent.h" +#include "thbase.h" +#include "intrman.h" +#include "vblank.h" +#include "xsio2man.h" +#include "sifman.h" +#include "sio2Cmds.h" +#include "sysmem.h" +#include "padData.h" + +int pad_port; +int pad_slot; +u32 mainThreadCount2; +u32 pad_portdata[2]; +/* It is very important that sif_buffer and padState are right after each other. */ +u32 sif_buffer[4] __attribute__((aligned(4))); +padState_t padState[2][4]; +u32 openSlots[2]; +vblankData_t vblankData; +int padman_init; +void *pad_ee_addr; +int thpri_hi; +int thpri_lo; +SifDmaTransfer_t sifdma_td[9]; //Original was likely 16 descriptors. + +int vblank_end = 0; +u32 frame_count = 0; +int sifdma_id = 0; +u32 vblankStartCount = 0; +s32 mainThreadCount = 0; + +static void TransferThread(void *arg) +{ + while(1) + { + WaitClearEvent(vblankData.eventflag, EF_VB_TRANSFER, WEF_AND|WEF_CLEAR, NULL); + pdTransfer(); + SetEventFlag(vblankData.eventflag, EF_VB_TRANSFER_DONE); + } +} + +u32 padSetupEEButtonData(u32 port, u32 slot, padState_t *pstate) +{ + u8 *data = pad_ee_addr ? pstate->ee_pdata.data : pstate->ee_old_pdata.data; + if(padState[port][slot].buttonDataReady == 1) + { + int i; + + data[0] = 0; + data[1] = padState[port][slot].modeCurId; + data[31] = padState[port][slot].buttonStatus[2]; + + for(i=2; i < 31; i++) + data[i] = padState[port][slot].buttonStatus[i+1]; + + if(padState[port][slot].modeCurId == 0x12) + { + data[2] = 0xFF, + data[3] = 0xFF; + data[4] = 0; + data[5] = 0; + } + + //New in v3.6 + if(padState[port][slot].modeCurId == 0x79) + { + int value; + + //Check button status & update pressure data + value = ~((data[2] << 8) | data[3]); + if(value & 0x2000) + { + if(data[8] == 0) + data[8] = 1; + } + else + { + if(data[8] != 0) + data[8] = 0; + } + + if(value & 0x8000) + { + if(data[9] == 0) + data[9] = 1; + } + else + { + if(data[9] != 0) + data[9] = 0; + } + + if(value & 0x1000) + { + if(data[10] == 0) + data[10] = 1; + } + else + { + if(data[10] != 0) + data[10] = 0; + } + + if(value & 0x4000) + { + if(data[11] == 0) + data[11] = 1; + } + else + { + if(data[11] != 0) + data[11] = 0; + } + + if(value & 0x0010) + { + if(data[12] == 0) + data[12] = 1; + } + else + { + if(data[12] != 0) + data[12] = 0; + } + + if(value & 0x0020) + { + if(data[13] == 0) + data[13] = 1; + } + else + { + if(data[13] != 0) + data[13] = 0; + } + + if(value & 0x0040) + { + if(data[14] == 0) + data[14] = 1; + } + else + { + if(data[14] != 0) + data[14] = 0; + } + + if(value & 0x0080) + { + if(data[15] == 0) + data[15] = 1; + } + else + { + if(data[15] != 0) + data[15] = 0; + } + + if(value & 0x0004) + { + if(data[16] == 0) + data[16] = 1; + } + else + { + if(data[16] != 0) + data[16] = 0; + } + + if(value & 0x0008) + { + if(data[17] == 0) + data[17] = 1; + } + else + { + if(data[17] != 0) + data[17] = 0; + } + + if(value & 0x0001) + { + if(data[18] == 0) + data[18] = 1; + } + else + { + if(data[18] != 0) + data[18] = 0; + } + + if(value & 0x0002) + { + if(data[19] == 0) + data[19] = 1; + } + else + { + if(data[19] != 0) + data[19] = 0; + } + } + + return 32; + } + else + { + int i; + + data[0] = 0xFF; + + for(i=1; i < 32; i++) + data[i] = 0; + + return 0; + } +} + + +static void DmaSendEE(void) +{ + int dma_stat; + + dma_stat = sceSifDmaStat(sifdma_id); + + if(dma_stat >= 0) + { + if( (frame_count % 240) == 0) + { + M_KPRINTF("DMA Busy ID = %08x ret = %d\n", sifdma_id, dma_stat); + M_KPRINTF(" SB_STAT = %08x\n", SB_STAT); + } + } + else + { + u32 port, slot; + u32 sifdma_count = 0; + + /* This is where the 128*2 bytes of 'garbage' gets sent to EE. + I believe that only 16 bytes should have been sent, used for checking + which ports/slots are open on the EE (padGetConnection). However + someone made a mistake and sent 128 bytes instead :-) Its the first + 112 (128-16) bytes of padState[0][0] which gets sent along with the + sif_buffer, which I think clearly indicates that sending 128 bytes + is an error. - Lukasz + */ + + sif_buffer[0]++; + sif_buffer[1] = pad_portdata[0]; + sif_buffer[2] = pad_portdata[1]; + + if (pad_ee_addr) + { + if( (sif_buffer[0] % 2) == 0) + sifdma_td[sifdma_count].dest = (void *)(((u8 *)pad_ee_addr) + 128); + else + sifdma_td[sifdma_count].dest = pad_ee_addr; + + sifdma_td[sifdma_count].src = sif_buffer; + sifdma_td[sifdma_count].size = 128; + sifdma_td[sifdma_count].attr = 0; + sifdma_count += 1; + } + + for(port=0; port < 2; port++) + { + for(slot=0; slot < 4; slot++) + { + if( (openSlots[port] >> slot) & 1 ) + { + padState_t *p = &padState[port][slot]; + + // Setup EE pad data + p->ee_pdata.frame = p->frame; + p->ee_pdata.findPadRetries = p->findPadRetries; + p->ee_pdata.modeConfig = p->modeConfig; + p->ee_pdata.modeCurId = p->modeCurId; + p->ee_pdata.model = p->model; + p->ee_pdata.buttonDataReady = p->buttonDataReady; + p->ee_pdata.nrOfModes = p->numModes; + p->ee_pdata.modeCurOffs = p->modeCurOffs; + p->ee_pdata.nrOfActuators = p->numActuators; + p->ee_pdata.numActComb = p->numActComb; + p->ee_pdata.val_c6 = p->val_c6; + p->ee_pdata.mode = p->mode; + p->ee_pdata.lock = p->lock; + p->ee_pdata.actDirSize = p->ee_actDirectSize; + p->ee_pdata.state = p->state; + p->ee_pdata.reqState = p->reqState; + p->ee_pdata.currentTask = p->currentTask; + p->ee_old_pdata.frame = p->frame; + p->ee_old_pdata.model = p->model; + p->ee_old_pdata.state = p->state; + if (p->state == PAD_STATE_ERROR && p->findPadRetries != 0) + { + p->ee_old_pdata.state = PAD_STATE_FINDPAD; + } + p->ee_old_pdata.reqState = p->reqState; + + p->frame++; + + p->ee_pdata.runTask = p->runTask; + + p->ee_pdata.actDirData[0] = p->ee_actDirectData.data32[0]; + p->ee_pdata.actDirData[1] = p->ee_actDirectData.data32[1]; + p->ee_pdata.actAlignData[0] = p->ee_actAlignData.data32[0]; + p->ee_pdata.actAlignData[1] = p->ee_actAlignData.data32[1]; + + p->ee_pdata.actData[0] = p->actData.data32[0]; + p->ee_pdata.actData[1] = p->actData.data32[1]; + p->ee_pdata.actData[2] = p->actData.data32[2]; + p->ee_pdata.actData[3] = p->actData.data32[3]; + p->ee_pdata.combData[0] = p->combData.data32[0]; + p->ee_pdata.combData[1] = p->combData.data32[1]; + p->ee_pdata.combData[2] = p->combData.data32[2]; + p->ee_pdata.combData[3] = p->combData.data32[3]; + + p->ee_pdata.modeTable[0] = p->modeTable.data32[0]; + p->ee_pdata.modeTable[1] = p->modeTable.data32[1]; + + p->ee_pdata.stat70bit = p->stat70bit; + + *((pad_ee_addr) ? &(p->ee_pdata.length) : &(p->ee_old_pdata.length)) = (p->buttonDataReady == 1) ? padSetupEEButtonData(port, slot, p) : 0; + + if( (p->frame & 1) == 0) + sifdma_td[sifdma_count].dest = (void*)p->padarea_ee_addr; + else + sifdma_td[sifdma_count].dest = (void*)(p->padarea_ee_addr + (pad_ee_addr ? 128 : 64)); + + sifdma_td[sifdma_count].src = pad_ee_addr ? (void *)&p->ee_pdata : (void *)&p->ee_old_pdata; + sifdma_td[sifdma_count].size = pad_ee_addr ? 128 : 64; + sifdma_td[sifdma_count].attr = 0; + + sifdma_count++; + } + } + } + + if(sifdma_count != 0) + { + int intr_state; + + CpuSuspendIntr(&intr_state); + + sifdma_id = sceSifSetDma( sifdma_td, sifdma_count); + + CpuResumeIntr(intr_state); + + if(sifdma_id == 0) + M_KPRINTF("sceSifSetDma failed\n"); + } + } +} + +static u32 GetThreadsStatus(padState_t *state) +{ + u32 count = 0; + iop_thread_info_t tinfo; + + if( ReferThreadStatus(state->updatepadTid, &tinfo) == 0) + { + if( (tinfo.status & THS_DORMANT) == 0) count++; + } + + if( ReferThreadStatus(state->querypadTid, &tinfo) == 0) + { + if( (tinfo.status & THS_DORMANT) == 0) count++; + } + + if( ReferThreadStatus(state->setmainmodeTid, &tinfo) == 0) + { + if( (tinfo.status & THS_DORMANT) == 0) count++; + } + + if( ReferThreadStatus(state->setactalignTid, &tinfo) == 0) + { + if( (tinfo.status & THS_DORMANT) == 0) count++; + } + + if( ReferThreadStatus(state->setbuttoninfoTid, &tinfo) == 0) + { + if( (tinfo.status & THS_DORMANT) == 0) count++; + } + + if( ReferThreadStatus(state->setvrefparamTid, &tinfo) == 0) + { + if( (tinfo.status & THS_DORMANT) == 0) count++; + } + + if(count == 0) + return 1; + else + return 0; +} + +static void DeleteThreads(padState_t *state) +{ + DeleteThread(state->updatepadTid); + DeleteThread(state->querypadTid); + DeleteThread(state->setmainmodeTid); + DeleteThread(state->setactalignTid); + DeleteThread(state->setbuttoninfoTid); + DeleteThread(state->setvrefparamTid); +} + +static void MainThread(void *arg) +{ + while(1) + { + u32 port, slot; + + mainThreadCount++; + + if( mainThreadCount % 30 == 0 ) sio2_mtap_update_slots(); + + for(port=0; port < 2; port++) + { + for(slot=0; slot < 4; slot++) + { + if( ((openSlots[port] >> slot) & 0x1) == 1) + { + pdSetActive(port, slot, 0); + + padState[port][slot].stat70bit = pdGetStat70bit(port, slot); + + if(padState[port][slot].runTask != TASK_NONE) + { + if(padState[port][slot].runTask == TASK_PORT_CLOSE) + { + padState[port][slot].currentTask = padState[port][slot].runTask; + padState[port][slot].runTask = TASK_NONE; + padState[port][slot].reqState = PAD_RSTAT_BUSY; + + SetEventFlag(padState[port][slot].eventflag, EF_EXIT_THREAD); + } + else + { + if(padState[port][slot].currentTask == TASK_UPDATE_PAD) + { + // Start Task + StartThread(padState[port][slot].taskTid, NULL); + padState[port][slot].currentTask = padState[port][slot].runTask; + padState[port][slot].runTask = TASK_NONE; + padState[port][slot].reqState = PAD_RSTAT_BUSY; + } + else + { + padState[port][slot].runTask = TASK_NONE; + padState[port][slot].reqState = PAD_RSTAT_FAILED; + } + } + } + } + + switch(padState[port][slot].currentTask) + { + case TASK_UPDATE_PAD: + { + SetEventFlag(padState[port][slot].eventflag, EF_UPDATE_PAD); + WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0); + pdSetActive(port, slot, 1); + } break; + + case TASK_QUERY_PAD: + { + padState[port][slot].buttonDataReady = 0; + + SetEventFlag(padState[port][slot].eventflag, EF_QUERY_PAD); + WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0); + pdSetActive(port, slot, 1); + } break; + + case TASK_PORT_CLOSE: + { + if(GetThreadsStatus( &padState[port][slot] ) == 1) + { + padState[port][slot].currentTask = TASK_NONE; + padState[port][slot].reqState = PAD_RSTAT_COMPLETE; + openSlots[port] ^= (1 << slot); + + DeleteThreads( &padState[port][slot] ); + SetEventFlag(padState[port][slot].eventflag, EF_PORT_CLOSE); + } + + } break; + + case TASK_SET_MAIN_MODE: + { + padState[port][slot].buttonDataReady = 0; + + SetEventFlag(padState[port][slot].eventflag, EF_SET_MAIN_MODE); + WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0); + pdSetActive(port, slot, 1); + } break; + + case TASK_SET_ACT_ALIGN: + { + padState[port][slot].buttonDataReady = 0; + + SetEventFlag(padState[port][slot].eventflag, EF_SET_ACT_ALIGN); + WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0); + pdSetActive(port, slot, 1); + } break; + + case TASK_SET_BUTTON_INFO: + { + padState[port][slot].buttonDataReady = 0; + + SetEventFlag(padState[port][slot].eventflag, EF_SET_SET_BUTTON_INFO); + WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0); + pdSetActive(port, slot, 1); + } break; + + case TASK_SET_VREF_PARAM: + { + padState[port][slot].buttonDataReady = 0; + + SetEventFlag(padState[port][slot].eventflag, EF_SET_VREF_PARAM); + WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0); + pdSetActive(port, slot, 1); + } break; + + } + } + } + + // Transfer is started in VblankStart + vblankData.stopTransfer = 0; + WaitClearEvent(vblankData.eventflag, EF_VB_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL); + + if( (openSlots[0] != 0) || (openSlots[1] != 0)) + { + for(port=0; port < 2; port++) + { + for(slot=0; slot < 4; slot++) + { + if(pdIsActive(port, slot) == 1) + { + /* Signal transfer done and wait to task (reading + sio2 data) to be done. */ + SetEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_DONE); + WaitEventFlag(padState[port][slot].eventflag, EF_TASK_DONE, 0x10, 0); + } + } + } + } + + // Send pad data to EE + DmaSendEE(); + + mainThreadCount2++; // s7 + + // Check for disconnected controllers + if(mainThreadCount2 >= 8) + { + if(mainThreadCount % 30 != 0) + { + if( pdIsActive(pad_port, pad_slot) == 1) + { + if( padState[pad_port][pad_slot].state == PAD_STATE_DISCONN) + pad_portdata[pad_port] &= ~(1 << pad_slot); // clear slot + else + pad_portdata[pad_port] |= (1 << pad_slot); // set slot + } + else + { + if( pdCheckConnection(pad_port, pad_slot) == 1) + pad_portdata[pad_port] |= (1 << pad_slot); // set slot + else + pad_portdata[pad_port] &= ~(1 << pad_slot); // clear slot + } + + //Move onto the next slot + pad_slot++; + if(pad_slot >= 4) + { + //Move onto the next port + pad_slot = 0; + pad_port++; + + if(pad_port >= 2) pad_port = 0; + } + + mainThreadCount2 = 0; + } + } + } +} + +s32 VbReferThreadStatus(vblankData_t *vData) +{ + iop_thread_info_t tinfo; + s32 ret = 0; + + if( iReferThreadStatus(vData->tid_1, &tinfo) == 0) + { + if( (tinfo.status & THS_DORMANT) == 0 ) + ret++; + } + + if( iReferThreadStatus(vData->tid_2, &tinfo) == 0) + { + if( (tinfo.status & THS_DORMANT) == 0 ) + ret++; + } + + return ret; +} + +int VblankStart(void *arg) +{ + vblankData_t *vData = arg; + + vblank_end = 0; + vblankStartCount++; + frame_count++; + + if((vData->init == 1) && (vData->stopTransfer == 0)) + { + vData->stopTransfer = 1; + iSetEventFlag(vData->eventflag, EF_VB_TRANSFER); + } + + /* Wait for threads to exit and signal event to padEnd */ + if(vData->padEnd == 1) + { + if( VbReferThreadStatus(vData) == 0 ) + iSetEventFlag(vData->eventflag, EF_VB_WAIT_THREAD_EXIT); + } + + return 1; +} + + +int VblankEnd(void *arg) +{ + vblank_end = 1; + return 1; +} + +s32 padInit(void * ee_addr) +{ + iop_thread_t thread; + int intr_state; + iop_event_t event; + + if(padman_init == 1) + { + M_PRINTF("Refresh request from EE\n."); + padEnd(); + } + + vblankData.padEnd = 0; + vblankData.init = 0; + vblankData.stopTransfer = 1; + + pad_ee_addr = ee_addr; + pad_port = 0; + pad_slot = 0; + mainThreadCount2 = 0; + pad_portdata[0] = 0; + pad_portdata[1] = 0; + sif_buffer[0] = 0; + + sio2cmdReset(); + sio2cmdInitFindPads(); + sio2cmdInitMouse(); + sio2cmdInitNegicon(); + sio2cmdInitKonamiGun(); + sio2cmdInitDigital(); + sio2cmdInitJoystick(); + sio2cmdInitNamcoGun(); + sio2cmdInitAnalog(); + sio2cmdInitJogcon(); + sio2cmdInitConfig(); + + pdReset(); + + openSlots[0] = 0; + openSlots[1] = 0; + + event.attr = EA_MULTI; + event.bits = 0; + + vblankData.eventflag = CreateEventFlag(&event); + + if( vblankData.eventflag == 0) + { + M_PRINTF("padInit: CreateEventFlag failed (%d).\n", vblankData.eventflag); + return 0; + } + + thread.attr = TH_C; + thread.thread = &TransferThread; + thread.stacksize = 0x800; + thread.priority = thpri_hi; + + vblankData.tid_2 = CreateThread(&thread); + + if(vblankData.tid_2 == 0) + { + M_PRINTF("padInit: CreateThread TransferThread failed (%d)\n.", vblankData.tid_2); + return 0; + } + + StartThread(vblankData.tid_2, NULL); + + thread.attr = TH_C; + thread.thread = MainThread; + thread.stacksize = 0x1000; + thread.priority = thpri_lo; + + vblankData.tid_1 = CreateThread(&thread); + + if(vblankData.tid_1 == 0) + { + M_PRINTF("padInit: CreateThread MainThread failed (%d)\n.", vblankData.tid_1); + return 0; + } + + StartThread(vblankData.tid_1, NULL); + + CpuSuspendIntr(&intr_state); + + RegisterVblankHandler(0, 16, &VblankStart, (void*)&vblankData); + RegisterVblankHandler(1, 16, &VblankEnd, (void*)&vblankData); + + CpuResumeIntr(intr_state); //Original BUG: was originally a call to CpuEnableIntr with intr_state as an argument + + vblankData.init = 1; + padman_init = 1; + + return 1; +} diff --git a/sps2_basement/hardware/mem/padman/src/padMiscFuncs.c b/sps2_basement/hardware/mem/padman/src/padMiscFuncs.c new file mode 100644 index 0000000..e95aa4b --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/padMiscFuncs.c @@ -0,0 +1,442 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#include "types.h" +#include "freepad.h" +#include "stdio.h" +#include "xsio2man.h" +#include "sio2Cmds.h" +#include "sysmem.h" +#include "thevent.h" +#include "thbase.h" +#include "vblank.h" +#include "irx.h" + +// Global variables +extern struct irx_id _irx_id; + +extern padState_t padState[2][4]; +extern u32 openSlots[2]; +extern vblankData_t vblankData; +extern int padman_init; +extern void *pad_ee_addr; + +void DeleteThreadsEventFlag(vblankData_t *s) +{ + DeleteThread(s->tid_1); + DeleteThread(s->tid_2); + DeleteEventFlag(s->eventflag); +} + +s32 padEnd(void) +{ + if(padman_init != 0) + { + int port,slot; + + for(port = 0; port < 2; port++) + for(slot=0; slot < 4; slot++) + { + if((openSlots[port] >> slot) & 0x1) + padPortClose(port, slot, 1); + } + + SetEventFlag(vblankData.eventflag, EF_EXIT_THREAD); + + vblankData.padEnd = 1; + + WaitEventFlag(vblankData.eventflag, EF_VB_WAIT_THREAD_EXIT, 0x11, 0); + + DeleteThreadsEventFlag( &vblankData ); + + while(ReleaseVblankHandler(0, (void*)VblankStart) != 0) + M_PRINTF("Release VB_START failed.\n"); + + while(ReleaseVblankHandler(1, VblankEnd) != 0) + M_PRINTF("Release VB_END failed.\n"); + + pad_ee_addr = NULL; + padman_init = 0; + } + + return 1; +} + +s32 padPortClose(s32 port, s32 slot, s32 wait) +{ + if(((openSlots[port] >> slot) & 1) == 0) + { + M_PRINTF("padPortClose: Port %i Slot %i is not open.\n", (int)port, (int)slot); + return 0; + } + + if(padState[port][slot].reqState == PAD_RSTAT_BUSY) + { + M_PRINTF("padPortClose: Port %i Slot %i request failed.\n", (int)port, (int)slot); + return 0; + } + + padState[port][slot].runTask = TASK_PORT_CLOSE; + padState[port][slot].taskTid = 0; + padState[port][slot].reqState = PAD_RSTAT_BUSY; + + if(wait) + { + u32 resbits; + + WaitEventFlag(padState[port][slot].eventflag, EF_PORT_CLOSE, 0x10, &resbits); + DeleteEventFlag(padState[port][slot].eventflag); + padState[port][slot].eventflag = 0; + } + + return 1; +} + +u32 padSetMainMode(u32 port, u32 slot, u32 mode, u32 lock) +{ + if( (padState[port][slot].currentTask != TASK_UPDATE_PAD) || ( padState[port][slot].modeConfig < MODE_CONFIG_READY) ) + return 0; + + if( mode >= padState[port][slot].numModes ) + return 0; + + if( padState[port][slot].reqState != PAD_RSTAT_BUSY) + { + padState[port][slot].mode = mode; + padState[port][slot].lock = lock; + padState[port][slot].runTask = TASK_SET_MAIN_MODE; + padState[port][slot].reqState = PAD_RSTAT_BUSY; + padState[port][slot].taskTid = padState[port][slot].setmainmodeTid; + + return 1; + } + + return 0; +} + +s32 padInfoAct(u32 port, u32 slot, s32 act, u32 val) +{ + if(padState[port][slot].currentTask != TASK_UPDATE_PAD) + return 0; + + if(padState[port][slot].modeConfig < MODE_CONFIG_READY) + return -1; + + if(act == -1) return padState[port][slot].numActuators; + + if( act < padState[port][slot].numActuators ) + { + u8 *actData = padState[port][slot].actData.data[act]; + + switch(val) + { + case 1: + return actData[0]; + case 2: + return actData[1]; + case 3: + return actData[2]; + case 4: + return actData[3]; + } + } + + return -1; +} + +s32 padInfoComb(u32 port, u32 slot, s32 listno, u32 offs) +{ + if(padState[port][slot].currentTask != TASK_UPDATE_PAD) + return 0; + + if(padState[port][slot].modeConfig < MODE_CONFIG_READY) + return -1; + + if(listno == -1) return padState[port][slot].numActComb; + + if( listno < padState[port][slot].numActComb) + { + u8 *combData = padState[port][slot].combData.data[listno]; + + switch(offs) + { + case -1: + return combData[0]; + case 0: + return combData[1]; + case 1: + return combData[2]; + case 2: + return combData[3]; + } + } + + return -1; +} + +s32 padInfoMode(u32 port, u32 slot, s32 term, u32 offs) +{ + if((padState[port][slot].currentTask != TASK_UPDATE_PAD) || (padState[port][slot].reqState == PAD_RSTAT_BUSY)) + return 0; + + switch(term) + { + case 2: + if(padState[port][slot].modeConfig == MODE_CONFIG_QUERY_PAD) + return 0; + else + return padState[port][slot].modeTable.data[padState[port][slot].modeCurOffs]; + case 1: + if( padState[port][slot].modeCurId != PAD_ID_CONFIG) + return (PAD_ID_HI(PAD_ID_CONFIG)); + else + return 0; + case 3: + if(padState[port][slot].modeConfig == MODE_CONFIG_QUERY_PAD) + return 0; + else + return padState[port][slot].modeCurOffs; + case 4: + if(padState[port][slot].modeConfig == MODE_CONFIG_QUERY_PAD) + return 0; + else + { + if(offs == -1) + { + return padState[port][slot].numModes; + } + else + { + u16* mode = padState[port][slot].modeTable.data; + + if(offs < padState[port][slot].numModes) + return mode[offs]; + else + return 0; + } + } + } + + return -1; +} + +u32 ActDirectTotal(u32 port, u32 slot) +{ + u32 ret = 0; + u32 p, s; + + for(p = 0; p < padGetPortMax(); p++) + { + for(s = 0; s < padGetSlotMax(port); s++) + { + if( (p == port) && (s == slot) && (((openSlots[port] >> slot) & 1) != 0)) + { + if(padState[port][slot].modeCurId != 0) + { + int i; + + for(i=0; i < padState[port][slot].ee_actDirectSize; i++) + { + if((padState[port][slot].ee_actAlignData.data[i] != 0xFF) + && (padState[port][slot].ee_actDirectData.data[i] != 0)) + { + u8 *act = padState[port][slot].actData.data[padState[port][slot].ee_actAlignData.data[i]]; + ret += act[3]; + } + } + } + } + } + } + + return ret; +} + +u32 CheckAirDirectTotal(u32 port, u32 slot, u8 *actData) +{ + int i; + u32 total = ActDirectTotal(port, slot); + + for(i=0; i < 6; i++) + { + u32 a = padState[port][slot].ee_actAlignData.data[i]; + + if(a != 0xFF) + { + if( actData[a] != 0 ) + { + u8 *act = padState[port][slot].actData.data[a]; + + total += act[3]; + + if(total >= 0x3D) + { + M_KPRINTF("Over Consumpt Max 600mA[%d][%d]\n", (int)port, (int)slot); + actData[a] = 0; + } + } + } + } + + return 1; +} + +u32 padSetActDirect(u32 port, u32 slot, u8 *actData) +{ + if(padState[port][slot].currentTask == TASK_UPDATE_PAD) + { + if( CheckAirDirectTotal(port, slot, actData) == 0) + { //This doesn't seem to be ever used. + M_KPRINTF("Over consumpt Max [%d][%d]\n", (int)port, (int)slot); + } + else + { + int i; + + for(i=0; i < 6; i++) + padState[port][slot].ee_actDirectData.data[i] = actData[i]; + + padState[port][slot].ee_actDirectSize = 6; + + return 1; + } + } + + return 0; +} + +u32 padSetActAlign(u32 port, u32 slot, u8 *actData) +{ + if( (padState[port][slot].currentTask != TASK_UPDATE_PAD) || ( padState[port][slot].modeConfig < MODE_CONFIG_READY) ) + return 0; + + if( padState[port][slot].reqState != PAD_RSTAT_BUSY) + { + int i; + + for(i=0; i < 6; i++) + padState[port][slot].ee_actAlignData.data[i] = actData[i]; + + padState[port][slot].reqState = PAD_RSTAT_BUSY; + padState[port][slot].runTask = TASK_SET_ACT_ALIGN; + padState[port][slot].taskTid = padState[port][slot].setactalignTid; + + return 1; + } + + return 0; +} + +u32 padGetButtonMask(u32 port, u32 slot) +{ + u32 ret = 0; + + if( (padState[port][slot].currentTask != TASK_UPDATE_PAD) || ( padState[port][slot].modeConfig < MODE_CONFIG_READY) ) + return ret; + + if( padState[port][slot].model < 2) + return ret; + + ret = (u32)padState[port][slot].buttonMask[0]; + ret |= (u32)padState[port][slot].buttonMask[1] << 8; + ret |= (u32)padState[port][slot].buttonMask[2] << 16; + ret |= (u32)padState[port][slot].buttonMask[3] << 24; + + return ret; +} + +u32 padSetButtonInfo(u32 port, u32 slot, u32 info) +{ + if( (padState[port][slot].currentTask != TASK_UPDATE_PAD) || ( padState[port][slot].modeConfig < MODE_CONFIG_READY) ) + return 0; + + if( padState[port][slot].model < 2) + return 0; + + if( padState[port][slot].reqState != PAD_RSTAT_BUSY) + { + int i; + + info = (info << 6) | 0x3F; + + padState[port][slot].buttonInfo[0] = (u8)(info); + padState[port][slot].buttonInfo[1] = (u8)(info >> 8); + padState[port][slot].buttonInfo[2] = (u8)(info >> 16); + padState[port][slot].buttonInfo[3] = (u8)(info >> 24); + + for(i=0; i < 11; i++) + padState[port][slot].modeParam[i] = 0x2; + + padState[port][slot].reqState = PAD_RSTAT_BUSY; + padState[port][slot].runTask = TASK_SET_BUTTON_INFO; + padState[port][slot].taskTid = padState[port][slot].setbuttoninfoTid; + + return 1; + } + + + return 0; +} + +u32 padSetVrefParam(u32 port, u32 slot, u8 *vparam) +{ + if( (padState[port][slot].currentTask != TASK_UPDATE_PAD) || ( padState[port][slot].modeConfig < MODE_CONFIG_READY) ) + return 0; + + if( padState[port][slot].model < 2) + return 0; + + if( padState[port][slot].reqState != PAD_RSTAT_BUSY) + { + int i; + + for(i=0; i < 12; i++) + padState[port][slot].modeParam[i] = vparam[i]; + + padState[port][slot].runTask = TASK_SET_VREF_PARAM; + padState[port][slot].reqState = PAD_RSTAT_BUSY; + padState[port][slot].taskTid = padState[port][slot].setvrefparamTid; + + return 1; + } + + return 0; +} + +u32 padGetPortMax(void) +{ + return 2; +} + +u32 padGetSlotMax(u32 port) +{ + return sio2_mtap_get_slot_max(port); +} + +u32 padGetModVersion(void) +{ + return _irx_id.v; +} + +u32 padGetInBuffer(u32 port, u32 slot, u8 *buf) +{ + int i; + + for(i=0; i < 32 ; i++) + buf[i] = padState[port][slot].inbuffer[i]; + + return 32; +} + +u32 padGetModeConfig(u32 port, u32 slot) +{ + return padState[port][slot].modeConfig; +} diff --git a/sps2_basement/hardware/mem/padman/src/padPortOpen.c b/sps2_basement/hardware/mem/padman/src/padPortOpen.c new file mode 100644 index 0000000..dcc7b9d --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/padPortOpen.c @@ -0,0 +1,810 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#include "types.h" +#include "freepad.h" +#include "stdio.h" +#include "thevent.h" +#include "thbase.h" +#include "sio2Cmds.h" +#include "padCmds.h" +#include "padData.h" + +// Global variables +extern padState_t padState[2][4]; +extern u32 openSlots[2]; + +extern int thpri_lo; +extern int thpri_hi; + +extern int padman_init; + +static void UpdatePadThread(void *arg) +{ + iop_thread_info_t tstatus; + padState_t *pstate; + u32 res = 0; + + ReferThreadStatus(TH_SELF, &tstatus); + pstate = (padState_t*)tstatus.option; + + while(1) + { + WaitClearEvent(pstate->eventflag, EF_UPDATE_PAD, WEF_AND|WEF_CLEAR, NULL); + + // Check if able to read button data from pad + if( ReadData(pstate) == 1) + { + res = 0; + + if( (pstate->outbuffer[2] != 0x5a) || ( pstate->outbuffer[1] != pstate->modeCurId) || (pstate->outbuffer[1] == 0xf3) ) + { + pstate->buttonDataReady = 0; + pstate->state = PAD_STATE_EXECCMD ; + pstate->currentTask = TASK_QUERY_PAD; + StartThread(pstate->querypadTid, NULL); + } + else + { + u32 i; + + for(i=0; i < 32; i++) + pstate->buttonStatus[i] = pstate->outbuffer[i]; + + pstate->buttonDataReady = 1; + + if(pstate->modeConfig == MODE_CONFIG_QUERY_PAD) + pstate->state = PAD_STATE_FINDCTP1; + else + pstate->state = PAD_STATE_STABLE ; + + if( (pstate->reqState == PAD_RSTAT_BUSY) && (pstate->runTask == TASK_NONE)) + pstate->reqState = PAD_RSTAT_COMPLETE; + } + } + else + { + pstate->buttonDataReady = 0; + pstate->state = PAD_STATE_ERROR; + pstate->findPadRetries++; + + res += pdGetError( pstate->port, pstate->slot ); + + if(res >= 10) + { + pstate->currentTask = TASK_QUERY_PAD; + StartThread(pstate->querypadTid, NULL); + } + } + } +} + +static void QueryPadThread(void *arg) +{ + iop_thread_info_t tinfo; + padState_t *pstate; + u32 i; + u8 count; + u32 res; + u32 modeCurId = 0xFF; + + ReferThreadStatus(TH_SELF, &tinfo); + + pstate = (padState_t*)tinfo.option; + + pstate->modeConfig = 0; + pstate->modeCurId = 0; + pstate->model = 0; + pstate->numModes = 0; + pstate->numActuators = 0; + pstate->numActComb = 0; + + for(i=0; i < 4; i++) + { + pstate->buttonInfo[i] = 0; + pstate->buttonMask[i] = 0; + } + + pstate->buttonDataReady = 0; + pstate->ee_actDirectSize = 0; + pstate->findPadRetries = 0; + pstate->modeCurId = 0; + + + D_PRINTF("QueryPadThread: Checking for pad (%i,%i)\n", pstate->port, pstate->slot); + + do + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + + res = PadIsSupported(pstate); + + if(res == 1) + { + if(pstate->modeCurId != 0xFF) + { + modeCurId = pstate->modeCurId; + pstate->modeCurId = 0; + pstate->state = PAD_STATE_EXECCMD; + } + else + { + pstate->state = PAD_STATE_DISCONN; + pstate->disconnected = 1; + } + } + else + { + pstate->state = PAD_STATE_DISCONN; + pstate->disconnected = 1; + } + } + while( (res != 1) || (pstate->modeCurId == 0xFF) ); + + + if(pstate->disconnected != 0) + { + for(i=0; i < 6; i++) + pstate->ee_actAlignData.data[i] = 0xFF; + } + + D_PRINTF("Found pad (%i,%i) - modeCurId: 0x%x\n", (int)pstate->port, (int)pstate->slot, (int)modeCurId); + + res = 0; + + for(i=0; (i < 10) && (res != 1); i++) + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + + res = EnterConfigMode(modeCurId, pstate); + + if(res == 1) pstate->modeConfig = MODE_CONFIG_READY; + } + + if( res != 1 ) + { + D_PRINTF("EnterConfigMode (%i, %i): Failed\n", (int)pstate->port, (int)pstate->slot); + + pstate->modeConfig = MODE_CONFIG_QUERY_PAD; + pstate->modeCurId = modeCurId; + pstate->currentTask = TASK_UPDATE_PAD; + + ExitThread(); + } + + D_PRINTF("EnterConfigMode (%i, %i): Success\n", (int)pstate->port, (int)pstate->slot); + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + res = QueryModel(pstate); + + if((res != 1) && (i >= 10)) + { + D_PRINTF("QueryModel (%i, %i): Failed\n",(int)pstate->port, (int)pstate->slot); + + pstate->modeCurId = 0; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + D_PRINTF("QueryModel (%i, %i): Success\n", (int)pstate->port, (int)pstate->slot); + + if( (pstate->disconnected == 1) && (pstate->modeCurOffs != 0)) + { + pstate->mode = 0; + pstate->lock = 0; + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + + res = SetMainMode(pstate); + + if(res == 1) + { + D_PRINTF("SetMainMode (%i,%i): Success\n", (int)pstate->port, (int)pstate->slot); + D_PRINTF("QueryPadThread: Done (%i,%i)\n", (int)pstate->port, (int)pstate->slot); + + pstate->modeCurId = 0; + pstate->currentTask = TASK_UPDATE_PAD; + pstate->disconnected = 0; + ExitThread(); + } + else + { + if(i >= 10) + { + D_PRINTF("SetMainMode (%i, %i): Failed\n", (int)pstate->port, (int)pstate->slot); + + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + } + } + + for(count=0; count < pstate->numActuators; count++) + { + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + + res = QueryAct(count, pstate); + + if((res != 1) && (i >= 10)) + { + D_PRINTF("QueryAct (%i,%i): Failed\n", (int)pstate->port, (int)pstate->slot); + + pstate->modeCurId = 0; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + } + + D_PRINTF("QueryAct (%i,%i): Success\n", (int)pstate->port, (int)pstate->slot); + + for(count=0; count < pstate->numActComb; count++) + { + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + + res = QueryComb(count, pstate); + + if((res != 1) && (i >= 10)) + { + D_PRINTF("QueryComb (%i,%i): Failed\n", (int)pstate->port, (int)pstate->slot); + + pstate->modeCurId = 0; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + } + + D_PRINTF("QueryComb (%i,%i): Success\n", (int)pstate->port, (int)pstate->slot); + + for(count=0; count < pstate->numModes; count++) + { + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + + res = QueryMode(count, pstate); + + if((res != 1) && (i >= 10)) + { + D_PRINTF("QueryMode (%i,%i): Failed\n", (int)pstate->port, (int)pstate->slot); + + pstate->modeCurId = 0; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + } + + D_PRINTF("QueryMode (%i,%i): Success\n", (int)pstate->port, (int)pstate->slot); + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + + res = SetActAlign(pstate); + + if((res != 1) && (i >= 10)) + { + D_PRINTF("SetActAlign (%i,%i): Failed\n", (int)pstate->port, (int)pstate->slot); + + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + D_PRINTF("SetActAlign (%i,%i): Success\n", (int)pstate->port, (int)pstate->slot); + + if(((pstate->modeConfig & 0xFF) == 0x02) && + ((pstate->model & 0x02) == 0x02)) + { + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + + res = QueryButtonMask(pstate); + + if((res != 1) && (i >= 10)) + { + D_PRINTF("QueryButtonMask (%i,%i): Failed\n", (int)pstate->port, (int)pstate->slot); + + pstate->modeCurId = 0; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + D_PRINTF("QueryButtonMask (%i,%i): Success\n", (int)pstate->port, (int)pstate->slot); + } + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + + res = ExitConfigMode(pstate); + + if((res != 1) && (i >= 10)) + { + D_PRINTF("ExitConfigMode (%i,%i): Failed\n", (int)pstate->port, (int)pstate->slot); + + pstate->modeCurId = 0; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + D_PRINTF("ExitConfigMode (%i,%i): Success\n", (int)pstate->port, (int)pstate->slot); + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_QUERY_PAD, WEF_AND|WEF_CLEAR, NULL); + + res = PadIsSupported(pstate); + + if((res != 1) && (i >= 10)) + { + D_PRINTF("PadIsSupported (%i,%i): Failed\n", (int)pstate->port, (int)pstate->slot); + + pstate->modeCurId = 0; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + D_PRINTF("PadIsSupported (%i,%i): Success\n", (int)pstate->port, (int)pstate->slot); + + D_PRINTF("QueryPadThread: Done (%i,%i)\n", (int)pstate->port, (int)pstate->slot); + + modeCurId = pstate->modeCurId; + pstate->state = PAD_STATE_EXECCMD; + pstate->modeCurId = 0; + pstate->currentTask = TASK_UPDATE_PAD; + pstate->disconnected = 0; + pstate->modeCurId = modeCurId; //Weird, but this was how it was done. + + ExitThread(); +} + +static void SetMainModeThread(void *arg) +{ + u32 i, res; + iop_thread_info_t tinfo; + padState_t *pstate; + + ReferThreadStatus(TH_SELF, &tinfo); + + pstate = (padState_t*)tinfo.option; + + pstate->buttonDataReady = 0; + pstate->state = PAD_STATE_EXECCMD; + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_MAIN_MODE, WEF_AND|WEF_CLEAR, NULL); + + res = EnterConfigMode(pstate->modeCurId, pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_MAIN_MODE, WEF_AND|WEF_CLEAR, NULL); + + res = SetMainMode( pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_MAIN_MODE, WEF_AND|WEF_CLEAR, NULL); + + res = ExitConfigMode(pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + +} + +void SetActAlignThread(void *arg) +{ + u32 i, res; + iop_thread_info_t tinfo; + padState_t *pstate; + + ReferThreadStatus(TH_SELF, &tinfo); + + pstate = (padState_t*)tinfo.option; + + pstate->buttonDataReady = 0; + pstate->state = PAD_STATE_EXECCMD; + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_ACT_ALIGN, WEF_AND|WEF_CLEAR, NULL); + + res = EnterConfigMode(pstate->modeCurId, pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_ACT_ALIGN, WEF_AND|WEF_CLEAR, NULL); + + res = SetActAlign(pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_ACT_ALIGN, WEF_AND|WEF_CLEAR, NULL); + + res = ExitConfigMode(pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + pstate->currentTask = TASK_UPDATE_PAD; + + ExitThread(); +} + +static void SetButtonInfoThread(void *arg) +{ + int i, res; + u32 val; + iop_thread_info_t tinfo; + padState_t *pstate; + + ReferThreadStatus(TH_SELF, &tinfo); + + pstate = (padState_t*)tinfo.option; + + pstate->buttonDataReady = 0; + pstate->state = PAD_STATE_EXECCMD; + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_SET_BUTTON_INFO, WEF_AND|WEF_CLEAR, NULL); + + res = EnterConfigMode(pstate->modeCurId, pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_SET_BUTTON_INFO, WEF_AND|WEF_CLEAR, NULL); + + res = SetButtonInfo(pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + for(val = 0; val < 12; val++) + { + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_SET_BUTTON_INFO, WEF_AND|WEF_CLEAR, NULL); + + res = VrefParam(val, pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + } + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_SET_BUTTON_INFO, WEF_AND|WEF_CLEAR, NULL); + + res = ExitConfigMode(pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + pstate->val_c6 = 1; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); +} + +static void SetVrefParamThread(void *arg) +{ + int i, res; + u32 val; + iop_thread_info_t tinfo; + padState_t *pstate; + + ReferThreadStatus(TH_SELF, &tinfo); + + pstate = (padState_t*)tinfo.option; + + pstate->buttonDataReady = 0; + pstate->state = PAD_STATE_EXECCMD; + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_VREF_PARAM, WEF_AND|WEF_CLEAR, NULL); + + res = EnterConfigMode(pstate->modeCurId, pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + for(val = 0; val < 12; val++) + { + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_VREF_PARAM, WEF_AND|WEF_CLEAR, NULL); + + res = VrefParam(val, pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + } + + for(i=0,res=0; res != 1; i++) + { + WaitClearEvent( pstate->eventflag, EF_SET_VREF_PARAM, WEF_AND|WEF_CLEAR, NULL); + + res = ExitConfigMode( pstate); + + if((res != 1) && (i >= 10)) + { + pstate->reqState = PAD_RSTAT_FAILED; + pstate->currentTask = TASK_UPDATE_PAD; + ExitThread(); + } + } + + pstate->currentTask = TASK_UPDATE_PAD; + + ExitThread(); +} + +s32 padPortOpen(s32 port, s32 slot, s32 pad_area_ee_addr, u32 *buf) +{ + iop_event_t event; + iop_thread_t thread; + + if(port > 2) + { + M_PRINTF("Invalid port number: %d\n", (int)port); + return 0; + } + + if(slot > 4) + { + M_PRINTF("Invalid slot number: %d\n", (int)port); + return 0; + } + + if (padman_init == 0) + { + padInit(NULL); + } + + if( (openSlots[port] >> slot) & 0x1) + { + M_PRINTF("The slot will be refreshed: (%d, %d)\n", (int)port, (int)slot); + padPortClose(port, slot, 1); + } + + padState[port][slot].port = port; + padState[port][slot].slot = slot; + + openSlots[port] |= 1 << slot; + + padState[port][slot].state = PAD_STATE_EXECCMD; + padState[port][slot].modeCurId = 0; + padState[port][slot].reqState = PAD_RSTAT_COMPLETE; + padState[port][slot].frame = 0; + padState[port][slot].padarea_ee_addr = pad_area_ee_addr; + padState[port][slot].buttonDataReady = 0; + padState[port][slot].ee_actDirectSize = 0; + padState[port][slot].val_c6 = 0; + padState[port][slot].currentTask = TASK_NONE; + padState[port][slot].runTask = TASK_NONE; + padState[port][slot].val_184 = 0; + + padState[port][slot].disconnected = 1; + padState[port][slot].stat70bit = 0; + + event.attr = EA_MULTI; + event.bits = 0; + + if((padState[port][slot].eventflag = CreateEventFlag(&event)) == 0) + { + M_PRINTF("Port open failed (CreateEventFlag).\n"); + return 0; + } + + + // Create UpdatePadThread + thread.attr = TH_C; + thread.option = (u32)&padState[port][slot]; + thread.thread = &UpdatePadThread; + thread.stacksize = 0x600; + thread.priority = thpri_lo; + + padState[port][slot].updatepadTid = CreateThread(&thread); + + if(padState[port][slot].updatepadTid == 0) + { + M_PRINTF("Port open failed (CreateThread UpdatePadThread).\n"); + return 0; + } + + // Create QueryPadThread + thread.attr = TH_C; + thread.option = (u32)&padState[port][slot]; + thread.thread = &QueryPadThread; + thread.stacksize = 0x600; + thread.priority = thpri_lo; + + padState[port][slot].querypadTid = CreateThread(&thread); + + if(padState[port][slot].querypadTid == 0) + { + M_PRINTF("Port open failed (CreateThread QueryPadThread).\n"); + return 0; + } + + // Create SetMainModeThread + thread.attr = TH_C; + thread.option = (u32)&padState[port][slot]; + thread.thread = &SetMainModeThread; + thread.stacksize = 0x400; + thread.priority = thpri_lo; + + padState[port][slot].setmainmodeTid = CreateThread(&thread); + + if(padState[port][slot].setmainmodeTid == 0) + { + M_PRINTF("Port open failed (CreateThread SetMainModeThread)\n."); + return 0; + } + + // Create SetActAlignThread + thread.attr = TH_C; + thread.option = (u32)&padState[port][slot]; + thread.thread = &SetActAlignThread; + thread.stacksize = 0x400; + thread.priority = thpri_lo; + + padState[port][slot].setactalignTid = CreateThread(&thread); + + if(padState[port][slot].setactalignTid == 0) + { + M_PRINTF("Port open failed (CreateThread SetActAlignThread).\n"); + return 0; + } + + // Create SetButtonInfoThread + thread.attr = TH_C; + thread.option = (u32)&padState[port][slot]; + thread.thread = &SetButtonInfoThread; + thread.stacksize = 0x400; + thread.priority = thpri_lo; + + padState[port][slot].setbuttoninfoTid = CreateThread(&thread); + + if(padState[port][slot].setbuttoninfoTid == 0) + { + M_PRINTF("Port open failed (CreateThread SetButtonInfoThread).\n"); + return 0; + } + + // Create SetVrefParamThread + thread.attr = TH_C; + thread.option = (u32)&padState[port][slot]; + thread.thread = &SetVrefParamThread; + thread.stacksize = 0x400; + thread.priority = thpri_lo; + + padState[port][slot].setvrefparamTid = CreateThread(&thread); + + if(padState[port][slot].setvrefparamTid == 0) + { + M_PRINTF("Port open failed (CreateThread SetVrefParamThread).\n"); + return 0; + } + + if(padState[port][slot].currentTask < TASK_QUERY_PAD) + { + StartThread(padState[port][slot].updatepadTid, NULL); + padState[port][slot].currentTask = TASK_UPDATE_PAD; + } + else + { + M_PRINTF("Port open failed, busy.\n"); + return 0; + } + + return 1; +} diff --git a/sps2_basement/hardware/mem/padman/src/rpcserver.c b/sps2_basement/hardware/mem/padman/src/rpcserver.c new file mode 100644 index 0000000..642d90c --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/rpcserver.c @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#include "types.h" +#include "sifcmd.h" +#include "thbase.h" +#include "stdio.h" +#include "sifman.h" +#include "sifcmd.h" +#include "freepad.h" + +#define PAD_BIND_RPC_ID1 0x80000100 +#define PAD_BIND_RPC_ID2 0x80000101 + +#define PAD_BIND_OLD_RPC_ID1 0x8000010f +#define PAD_BIND_OLD_RPC_ID2 0x8000011f + +enum PAD_RPCCMD { + PAD_RPCCMD_OPEN = 0x01, + // 0x2 undefined + PAD_RPCCMD_INFO_ACT = 0x03, + PAD_RPCCMD_INFO_COMB, + PAD_RPCCMD_INFO_MODE, + PAD_RPCCMD_SET_MMODE, + PAD_RPCCMD_SET_ACTDIR, + PAD_RPCCMD_SET_ACTALIGN, + PAD_RPCCMD_GET_BTNMASK, + PAD_RPCCMD_SET_BTNINFO, + PAD_RPCCMD_SET_VREF, + PAD_RPCCMD_GET_PORTMAX, + PAD_RPCCMD_GET_SLOTMAX, + PAD_RPCCMD_CLOSE, + PAD_RPCCMD_END, + PAD_RPCCMD_INIT, + // 0x11 undefined + PAD_RPCCMD_GET_MODVER = 0x12, + PAD_RPCCMD_13 +}; + +// RPC Server +static s32 ThreadIdRpcServer; +static SifRpcDataQueue_t qd; +static SifRpcServerData_t sd[2]; +static u32 sb[2][32]; // server buffer + +// RPC Server Extended +static s32 ThreadIdRpcServerExt; +static SifRpcDataQueue_t qdext; +static SifRpcServerData_t sdext[2]; +static u32 sbext[2][32]; // server buffer + +static void* RpcPadOpen(u32 *data) +{ + + data[3] = padPortOpen(data[1], data[2], data[4], &data[5]); + + return data; +} + +static void* RpcPadSetMainMode(u32 *data) +{ + data[5] = padSetMainMode(data[1], data[2], data[3], data[4]); + + return data; +} + +static void* RpcPadInfoAct(u32 *data) +{ + + data[5] = padInfoAct(data[1], data[2], data[3], data[4]); + + return data; +} + +static void* RpcPadInfoComb(u32 *data) +{ + data[5] = padInfoComb(data[1], data[2], data[3], data[4]); + + return data; +} + +static void* RpcPadInfoMode(u32 *data) +{ + data[5] = padInfoMode(data[1], data[2], data[3], data[4]); + + return data; +} + +static void* RpcPadSetActDirect(u32 *data) +{ + data[5] = padSetActDirect(data[1], data[2], (u8*)&data[3]); + + return data; +} + +static void* RpcPadSetActAlign(u32 *data) +{ + + data[5] = padSetActAlign(data[1], data[2], (u8*)&data[3]); + + return data; +} + +static void* RpcPadGetButtonMask(u32 *data) +{ + + data[3] = padGetButtonMask(data[1], data[2]); + + return data; +} + +static void* RpcPadSetButtonInfo(u32 *data) +{ + data[4] = padSetButtonInfo(data[1], data[2], data[3]); + + return data; +} + +static void* RpcPadSetVrefParam(u32 *data) +{ + data[7] = padSetVrefParam(data[1], data[2], (u8*)&data[3]); + + return data; +} + +static void* RpcPadGetPortMax(u32 *data) +{ + data[3] = padGetPortMax(); + + return data; +} + +static void* RpcPadGetSlotMax(u32 *data) +{ + data[3] = padGetSlotMax(data[1]); + + return data; +} + +static void* RpcPadClose(u32 *data) +{ + data[3] = padPortClose(data[1], data[2], data[4]); + + return data; +} + +static void* RpcPadEnd(u32 *data) +{ + data[3] = padEnd(); + + return data; +} + +static void* RpcPadInit(u32 *data) +{ + data[3] = padInit((void*)data[4]); + + return data; +} + +static void* RpcGetModVersion(u32 *data) +{ + data[3] = padGetModVersion(); + + return data; +} + +static void* RpcServer(int fno, void *buffer, int length) +{ + u32 *data = (u32*)buffer; + u32 command = data[0]; + + if ((0x00000100 & command) != 0) + { + if ((0x80000000 & command) != 0) + { + command &= 0xff; + command += 1; + } + else if (command == 0x00000100) + { + // Unofficial: libpad EE client from v1.3.4 has this RPC function implemented, but is not implemented within its PADMAN module. + return buffer; + } + } + + switch(command) + { + case PAD_RPCCMD_INIT: return RpcPadInit(data); + case PAD_RPCCMD_END: return RpcPadEnd(data); + case PAD_RPCCMD_GET_MODVER: return RpcGetModVersion(data); + case PAD_RPCCMD_OPEN: return RpcPadOpen(data); + case PAD_RPCCMD_CLOSE: return RpcPadClose(data); + case PAD_RPCCMD_INFO_ACT: return RpcPadInfoAct(data); + case PAD_RPCCMD_INFO_COMB: return RpcPadInfoComb(data); + case PAD_RPCCMD_INFO_MODE: return RpcPadInfoMode(data); + case PAD_RPCCMD_SET_MMODE: return RpcPadSetMainMode(data); + case PAD_RPCCMD_SET_ACTDIR: return RpcPadSetActDirect(data); + case PAD_RPCCMD_SET_ACTALIGN: return RpcPadSetActAlign(data); + case PAD_RPCCMD_GET_BTNMASK: return RpcPadGetButtonMask(data); + case PAD_RPCCMD_SET_BTNINFO: return RpcPadSetButtonInfo(data); + case PAD_RPCCMD_SET_VREF: return RpcPadSetVrefParam(data); + case PAD_RPCCMD_GET_PORTMAX: return RpcPadGetPortMax(data); + case PAD_RPCCMD_GET_SLOTMAX: return RpcPadGetSlotMax(data); + + default: + M_PRINTF("invalid function code (%03x)\n", (int)data[0]); + break; + } + + return buffer; +} + +static void* RpcServerExt(int fno, void *buffer, int length) +{ + M_PRINTF("Extend Service: This service is not supported.\n"); + + return buffer; +} + + +static void RpcThread(void *arg) +{ + if( sceSifCheckInit() == 0) + { + M_PRINTF("Sif not initialized.\n"); + sceSifInit(); + } + + sceSifInitRpc(0); + sceSifSetRpcQueue(&qd, GetThreadId()); + sceSifRegisterRpc(&sd[0], PAD_BIND_RPC_ID1, &RpcServer, sb[0], NULL, NULL, &qd); + sceSifRegisterRpc(&sd[1], PAD_BIND_OLD_RPC_ID1, &RpcServer, sb[1], NULL, NULL, &qd); + sceSifRpcLoop(&qd); +} + +static void RpcThreadExt(void *arg) +{ + if( sceSifCheckInit() == 0) + { + M_PRINTF("Sif not initialized.\n"); + sceSifInit(); + } + + sceSifInitRpc(0); + sceSifSetRpcQueue(&qdext, GetThreadId()); + sceSifRegisterRpc(&sdext[0], PAD_BIND_RPC_ID2, &RpcServerExt, sbext[0], NULL, NULL, &qdext); + sceSifRegisterRpc(&sdext[1], PAD_BIND_OLD_RPC_ID2, &RpcServerExt, sbext[1], NULL, NULL, &qdext); + sceSifRpcLoop(&qdext); +} + +int InitRpcServers(int prio) +{ + iop_thread_t rpc_thread; + + if(prio == 0) + prio = PADMAN_THPRI_LO; + + // RPC Server + rpc_thread.attr = TH_C; + rpc_thread.thread = &RpcThread; + rpc_thread.stacksize = 0x800; + rpc_thread.priority = prio; + + ThreadIdRpcServer = CreateThread(&rpc_thread); + + if(ThreadIdRpcServer == 0) return 0; + + StartThread(ThreadIdRpcServer, NULL); + + // RPC Server Extended + rpc_thread.attr = TH_C; + rpc_thread.thread = &RpcThreadExt; + rpc_thread.stacksize = 0x800; + rpc_thread.priority = prio; + + ThreadIdRpcServerExt = CreateThread(&rpc_thread); + + if(ThreadIdRpcServerExt == 0) return 0; + + StartThread(ThreadIdRpcServerExt, NULL); + + return 1; +} diff --git a/sps2_basement/hardware/mem/padman/src/rpcserver.h b/sps2_basement/hardware/mem/padman/src/rpcserver.h new file mode 100644 index 0000000..c6832b6 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/rpcserver.h @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#ifndef __FREEPAD_RPC_SERVER_H__ +#define __FREEPAD_RPC_SERVER_H__ + +int InitRpcServers(int prio); + +#endif diff --git a/sps2_basement/hardware/mem/padman/src/sio2Cmds.c b/sps2_basement/hardware/mem/padman/src/sio2Cmds.c new file mode 100644 index 0000000..59b1bab --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/sio2Cmds.c @@ -0,0 +1,1404 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#include "irx.h" +#include "types.h" +#include "sio2Cmds.h" + +typedef struct +{ + u8 id; + u8 pad[3]; + void (*readdata)(u8 *); + u32 (*getportctrl1)(u32, u32); + u32 (*getportctrl2)(u32); + u32 (*reg_data)(void); + u32 (*size1)(void); + u32 (*size2)(void); + u32 (*enterconfigmode)(u8 *); + u32 (*exitconfigmode)(u8 *); + u32 (*querymodel)(u8 *); + u32 (*queryact)(u8 *); + u32 (*querycomb)(u8 *); + u32 (*querymode)(u8 *); + u32 (*querybuttonmask)(u8 *); + u32 (*setbuttoninfo)(u8 *); + u32 (*setvrefparam)(u8 *); + u32 (*setmainmode)(u8 *); + u32 (*setactalign)(u8 *); +} sio2Cmds_t; + +static sio2Cmds_t sio2Cmds[SIO2_CMD_MAX]; +static int numControllers; + +void sio2cmdReset(void) +{ + int i; + + for(i=0; i < SIO2_CMD_MAX; i++) + sio2Cmds[i].id = 0; + + numControllers = 0; +} + +static int SetupCmds(const sio2Cmds_t *s) +{ + if( ((numControllers+1) < SIO2_CMD_MAX) && (s != NULL) ) + { + if(numControllers > 0) + { + int i = 0; + + // Check if the controller was already registered (if so, do nothing). + do + { + if(s->id == sio2Cmds[i].id) + return 0; + + i++; + } while(numControllers > i); + } + + //Register new controller + int i = numControllers; + + sio2Cmds[i].id = s->id; + sio2Cmds[i].readdata = s->readdata; + sio2Cmds[i].getportctrl1 = s->getportctrl1; + sio2Cmds[i].getportctrl2 = s->getportctrl2; + sio2Cmds[i].reg_data = s->reg_data; + sio2Cmds[i].size1 = s->size1; + sio2Cmds[i].size2 = s->size2; + sio2Cmds[i].enterconfigmode = s->enterconfigmode; + sio2Cmds[i].exitconfigmode = s->exitconfigmode; + sio2Cmds[i].querymodel = s->querymodel; + sio2Cmds[i].queryact = s->queryact; + sio2Cmds[i].querycomb = s->querycomb; + sio2Cmds[i].querymode = s->querymode; + sio2Cmds[i].querybuttonmask = s->querybuttonmask; + sio2Cmds[i].setbuttoninfo = s->setbuttoninfo; + sio2Cmds[i].setvrefparam = s->setvrefparam; + sio2Cmds[i].setmainmode = s->setmainmode; + sio2Cmds[i].setactalign = s->setactalign; + + numControllers++; + + return 1; + } + else + { + return 0; + } +} + +/******************************************************************************* + FindPads +*******************************************************************************/ + +static void FindPadsReadData(u8 *a) +{ + a[0] = 1; + a[1] = 0x42; + a[2] = 0; + a[3] = 0; + a[4] = 0; +} + +static u32 FindPadsGetPortCtrl1(u32 a, u32 b) +{ + if(a == 0) + return 0xFFC00505; + else + return 0xFF060505; +} + +static u32 FindPadsGetPortCtrl2(u32 a) +{ + if(a == 0) + return 0x2000A; + else + return 0x2012C; +} + +static u32 FindPadsGetSize1(void) +{ + return 0x5; +} + +static u32 FindPadsGetSize2(void) +{ + return 0x5; +} + +static u32 FindPadsRegData(void) +{ + u32 res1, res2; + + res1 = FindPadsGetSize1(); + + res1 = ((res1 & 0x1FF) << 8) | 0x40; + + res2 = FindPadsGetSize2(); + + res2 = (res2 & 0x1FF) << 18; + + return (res1 | res2); +} + +static u32 FindPadsEnterConfigMode(u8 *a) +{ + return 0; +} + +void sio2cmdInitFindPads(void) +{ + sio2Cmds_t s; + + s.id = PAD_ID_HI(PAD_ID_FINDPADS); + + s.readdata = &FindPadsReadData; + s.getportctrl1 = &FindPadsGetPortCtrl1; + s.getportctrl2 = &FindPadsGetPortCtrl2; + s.reg_data = &FindPadsRegData; + s.size1 = &FindPadsGetSize1; + s.size2 = &FindPadsGetSize2; + s.enterconfigmode = &FindPadsEnterConfigMode; + s.exitconfigmode = NULL; + s.querymodel = NULL; + s.queryact = NULL; + s.querycomb = NULL; + s.querymode = NULL; + s.querybuttonmask = NULL; + s.setbuttoninfo = NULL; + s.setvrefparam = NULL; + s.setmainmode = NULL; + s.setactalign = NULL; + + SetupCmds(&s); +} + +/******************************************************************************* + Mouse +*******************************************************************************/ + +static void MouseReadData(u8* a) +{ + a[0] = 1; + a[1] = 0x42; + a[2] = 0; + a[3] = 0; + a[4] = 0; + a[5] = 0; + a[6] = 0; +} + +static u32 MouseGetPortCtrl1(u32 a, u32 b) +{ + if(a == 0) + return 0xFFC00505; + else + return 0xFF060505; +} + +static u32 MouseGetPortCtrl2(u32 a) +{ + if(a == 0) + return 0x20014; + else + return 0x2012C; +} + +static u32 MouseRegData(void) +{ + return 0x1c0740; +} + +static u32 MouseSize1(void) +{ + return 0x7; +} + +static u32 MouseSize2(void) +{ + return 0x7; +} + +static u32 MouseEnterConfigMode(u8 *a) +{ + a[0] = 0x1; + a[1] = 0x43; + a[2] = 0; + a[3] = 0x1; + a[4] = 0; + a[5] = 0; + a[6] = 0; + + return 0x7; +} + +void sio2cmdInitMouse(void) +{ + sio2Cmds_t s; + + s.id = PAD_ID_HI(PAD_ID_MOUSE); + + s.readdata = &MouseReadData; + s.getportctrl1 = &MouseGetPortCtrl1; + s.getportctrl2 = &MouseGetPortCtrl2; + s.reg_data = &MouseRegData; + s.size1 = &MouseSize1; + s.size2 = &MouseSize2; + s.enterconfigmode = &MouseEnterConfigMode; + s.exitconfigmode = NULL; + s.querymodel = NULL; + s.queryact = NULL; + s.querycomb = NULL; + s.querymode = NULL; + s.querybuttonmask = NULL; + s.setbuttoninfo = NULL; + s.setvrefparam = NULL; + s.setmainmode = NULL; + s.setactalign = NULL; + + + SetupCmds(&s); +} + +/******************************************************************************* + Negicon +*******************************************************************************/ + +static void NegiconReadData(u8* a) +{ + a[0] = 1; + a[1] = 0x42; + a[2] = 0; + a[3] = 0; + a[4] = 0; + a[5] = 0; + a[6] = 0; + a[7] = 0; + a[8] = 0; +} + +static u32 NegiconGetPortCtrl1(u32 a, u32 b) +{ + if(a == 0) + return 0xFFC00505; + else + return 0xFF060505; +} + + +static u32 NegiconGetPortCtrl2(u32 a) +{ + if(a == 0) + return 0x20014; + else + return 0x2012C; +} + +static u32 NegiconRegData(void) +{ + return 0x240940; +} + +static u32 NegiconSize1(void) +{ + return 0x9; +} + +static u32 NegiconSize2(void) +{ + return 0x9; +} + +static u32 NegiconEnterConfigMode(u8 *a) +{ + a[0] = 0x1; + a[1] = 0x43; + a[2] = 0; + a[3] = 0x1; + a[4] = 0; + a[5] = 0; + a[6] = 0; + a[7] = 0; + a[8] = 0; + + return 0x9; +} + +void sio2cmdInitNegicon(void) +{ + sio2Cmds_t s; + + s.id = PAD_ID_HI(PAD_ID_NEGICON); + + s.readdata = &NegiconReadData; + s.getportctrl1 = &NegiconGetPortCtrl1; + s.getportctrl2 = &NegiconGetPortCtrl2; + s.reg_data = &NegiconRegData; + s.size1 = &NegiconSize1; + s.size2 = &NegiconSize2; + s.enterconfigmode = &NegiconEnterConfigMode; + s.exitconfigmode = NULL; + s.querymodel = NULL; + s.queryact = NULL; + s.querycomb = NULL; + s.querymode = NULL; + s.querybuttonmask = NULL; + s.setbuttoninfo = NULL; + s.setvrefparam = NULL; + s.setmainmode = NULL; + s.setactalign = NULL; + + SetupCmds(&s); +} + +/******************************************************************************* + Konami Gun +*******************************************************************************/ + +static void KonamiGunReadData(u8* a) +{ + a[0] = 1; + a[1] = 0x42; + a[2] = 0; + a[3] = 0; + a[4] = 0; +} + +static u32 KonamiGunGetPortCtrl1(u32 a, u32 b) +{ + if(a == 0) + return 0xFFC00505; + else + return 0xFF060505; +} + +static u32 KonamiGunGetPortCtrl2(u32 a) +{ + if(a == 0) + return 0x20014; + else + return 0x2012C; +} + +static u32 KonamiGunRegData(void) +{ + return 0x140540; +} + +static u32 KonamiGunSize1(void) +{ + return 0x5; +} + +static u32 KonamiGunSize2(void) +{ + return 0x5; +} + +static u32 KonamiGunEnterConfigMode(u8 *a) +{ + a[0] = 0x1; + a[1] = 0x43; + a[2] = 0; + a[3] = 0x1; + a[4] = 0; + + return 0x5; +} + +void sio2cmdInitKonamiGun(void) +{ + sio2Cmds_t s; + + s.id = PAD_ID_HI( PAD_ID_KONAMIGUN ); + + s.readdata = &KonamiGunReadData; + s.getportctrl1 = &KonamiGunGetPortCtrl1; + s.getportctrl2 = &KonamiGunGetPortCtrl2; + s.reg_data = &KonamiGunRegData; + s.size1 = &KonamiGunSize1; + s.size2 = &KonamiGunSize2; + s.enterconfigmode = &KonamiGunEnterConfigMode; + s.exitconfigmode = NULL; + s.querymodel = NULL; + s.queryact = NULL; + s.querycomb = NULL; + s.querymode = NULL; + s.querybuttonmask = NULL; + s.setbuttoninfo = NULL; + s.setvrefparam = NULL; + s.setmainmode = NULL; + s.setactalign = NULL; + + SetupCmds(&s); +} + +/******************************************************************************* + Digital +*******************************************************************************/ + +static void DigitalReadData(u8* a) +{ + a[0] = 1; + a[1] = 0x42; + a[2] = 0; + a[3] = 0; + a[4] = 0; +} + +static u32 DigitalGetPortCtrl1(u32 a, u32 b) +{ + if(a == 0) + return 0xFFC00505; + else + return 0xFF060505; +} + +static u32 DigitalGetPortCtrl2(u32 a) +{ + if(a == 0) + return 0x20014; + else + return 0x2012C; +} + +static u32 DigitalRegData(void) +{ + return 0x140540; +} + +static u32 DigitalSize1(void) +{ + return 0x5; +} + +static u32 DigitalSize2(void) +{ + return 0x5; +} + +static u32 DigitalEnterConfigMode(u8 *a) +{ + a[0] = 0x1; + a[1] = 0x43; + a[2] = 0; + a[3] = 0x1; + a[4] = 0; + + return 0x5; +} + +void sio2cmdInitDigital(void) +{ + sio2Cmds_t s; + + s.id = PAD_ID_HI(PAD_ID_DIGITAL); + + s.readdata = &DigitalReadData; + s.getportctrl1 = &DigitalGetPortCtrl1; + s.getportctrl2 = &DigitalGetPortCtrl2; + s.reg_data = &DigitalRegData; + s.size1 = &DigitalSize1; + s.size2 = &DigitalSize2; + s.enterconfigmode = &DigitalEnterConfigMode; + s.exitconfigmode = NULL; + s.querymodel = NULL; + s.queryact = NULL; + s.querycomb = NULL; + s.querymode = NULL; + s.querybuttonmask = NULL; + s.setbuttoninfo = NULL; + s.setvrefparam = NULL; + s.setmainmode = NULL; + s.setactalign = NULL; + + SetupCmds(&s); +} + +/******************************************************************************* + Joystick +*******************************************************************************/ + +static void JoystickReadData(u8* a) +{ + a[0] = 1; + a[1] = 0x42; + a[2] = 0; + a[3] = 0; + a[4] = 0; + a[5] = 0; + a[6] = 0; + a[7] = 0; + a[8] = 0; +} + +static u32 JoystickGetPortCtrl1(u32 a, u32 b) +{ + if(a == 0) + return 0xFFC00505; + else + return 0xFF060505; +} + +static u32 JoystickGetPortCtrl2(u32 a) +{ + if(a == 0) + return 0x20014; + else + return 0x2012C; +} + +static u32 JoystickRegData(void) +{ + return 0x240940; +} + +static u32 JoystickSize1(void) +{ + return 0x9; +} + +static u32 JoystickSize2(void) +{ + return 0x9; +} + +static u32 JoystickEnterConfigMode(u8 *a) +{ + a[0] = 0x1; + a[1] = 0x43; + a[2] = 0; + a[3] = 0x1; + a[4] = 0; + a[5] = 0; + a[6] = 0; + a[7] = 0; + a[8] = 0; + + return 0x9; +} + +void sio2cmdInitJoystick(void) +{ + sio2Cmds_t s; + + s.id = PAD_ID_HI( PAD_ID_JOYSTICK ); + + s.readdata = &JoystickReadData; + s.getportctrl1 = &JoystickGetPortCtrl1; + s.getportctrl2 = &JoystickGetPortCtrl2; + s.reg_data = &JoystickRegData; + s.size1 = &JoystickSize1; + s.size2 = &JoystickSize2; + s.enterconfigmode = &JoystickEnterConfigMode; + s.exitconfigmode = NULL; + s.querymodel = NULL; + s.queryact = NULL; + s.querycomb = NULL; + s.querymode = NULL; + s.querybuttonmask = NULL; + s.setbuttoninfo = NULL; + s.setvrefparam = NULL; + s.setmainmode = NULL; + s.setactalign = NULL; + + SetupCmds(&s); +} + +/******************************************************************************* + Namco Gun +*******************************************************************************/ + +static void NamcoGunReadData(u8* a) +{ + a[0] = 1; + a[1] = 0x42; + a[2] = 0; + a[3] = 0; + a[4] = 0; + a[5] = 0; + a[6] = 0; + a[7] = 0; + a[8] = 0; +} + +static u32 NamcoGunGetPortCtrl1(u32 a, u32 b) +{ + if(a == 0) + return 0xFFC00505; + else + return 0xFF060505; +} + +static u32 NamcoGunGetPortCtrl2(u32 a) +{ + if(a == 0) + return 0x20014; + else + return 0x2012C; +} + +static u32 NamcoGunRegData(void) +{ + return 0x240940; +} + +static u32 NamcoGunSize1(void) +{ + return 0x9; +} + +static u32 NamcoGunSize2(void) +{ + return 0x9; +} + +static u32 NamcoGunEnterConfigMode(u8 *a) +{ + a[0] = 0x1; + a[1] = 0x43; + a[2] = 0; + a[3] = 0x1; + a[4] = 0; + a[5] = 0; + a[6] = 0; + a[7] = 0; + a[8] = 0; + + return 0x9; +} + +void sio2cmdInitNamcoGun(void) +{ + sio2Cmds_t s; + + s.id = PAD_ID_HI(PAD_ID_NAMCOGUN); + + s.readdata = &NamcoGunReadData; + s.getportctrl1 = &NamcoGunGetPortCtrl1; + s.getportctrl2 = &NamcoGunGetPortCtrl2; + s.reg_data = &NamcoGunRegData; + s.size1 = &NamcoGunSize1; + s.size2 = &NamcoGunSize2; + s.enterconfigmode = &NamcoGunEnterConfigMode; + s.exitconfigmode = NULL; + s.querymodel = NULL; + s.queryact = NULL; + s.querycomb = NULL; + s.querymode = NULL; + s.querybuttonmask = NULL; + s.setbuttoninfo = NULL; + s.setvrefparam = NULL; + s.setmainmode = NULL; + s.setactalign = NULL; + + SetupCmds(&s); +} + +/******************************************************************************* + Analog +*******************************************************************************/ + +static void AnalogReadData(u8* a) +{ + a[0] = 1; + a[1] = 0x42; + a[2] = 0; + a[3] = 0; + a[4] = 0; + a[5] = 0; + a[6] = 0; + a[7] = 0; + a[8] = 0; + a[9] = 0; + a[10] = 0; + a[11] = 0; + a[12] = 0; + a[13] = 0; + a[14] = 0; +} + +static u32 AnalogGetPortCtrl1(u32 a, u32 b) +{ + if(a != 0) + return 0xFF060505; + else + { + u32 val1, val2, val3 ; + + if((b & 0x2) == 0) + val1 = 0x5; + else + val1 = 0xA; + + if((b & 0x2) == 0) + val2 = 0x5; + else + val2 = 0xA; + + val1 &= 0xFFFF00FF; + + val3 = val1 | ( val2 << 8); + + if((b & 0x2) == 0) + val1 = 0xC0; + else + val1 = 0x60; + + val3 &= 0xFF00FFFF; + val3 = val3 | (val1 << 16) | 0xFF000000; + + return val3; + } +} + +static u32 AnalogGetPortCtrl2(u32 a) +{ + if(a == 0) + return 0x20014; + else + return 0x2012C; +} + +static u32 AnalogEnterConfigMode(u8 *a) +{ + a[0] = 0x1; + a[1] = 0x43; + a[2] = 0; + a[3] = 0x1; + a[4] = 0; + a[5] = 0; + a[6] = 0; + a[7] = 0; + a[8] = 0; + a[9] = 0; + a[10] = 0; + a[11] = 0; + a[12] = 0; + a[13] = 0; + a[14] = 0; + + return 0x15; +} + +void sio2cmdInitAnalog(void) +{ + sio2Cmds_t s; + + s.id = PAD_ID_HI(PAD_ID_ANALOG); + + s.readdata = &AnalogReadData; + s.getportctrl1 = &AnalogGetPortCtrl1; + s.getportctrl2 = &AnalogGetPortCtrl2; + s.reg_data = NULL; + s.size1 = NULL; + s.size2 = NULL; + s.enterconfigmode = &AnalogEnterConfigMode; + s.exitconfigmode = NULL; + s.querymodel = NULL; + s.queryact = NULL; + s.querycomb = NULL; + s.querymode = NULL; + s.querybuttonmask = NULL; + s.setbuttoninfo = NULL; + s.setvrefparam = NULL; + s.setmainmode = NULL; + s.setactalign = NULL; + + SetupCmds(&s); +} + +/******************************************************************************* + Jogcon +*******************************************************************************/ + +static void JogconReadData(u8* a) +{ + a[0] = 1; + a[1] = 0x42; + a[2] = 0; + a[3] = 0; + a[4] = 0; + a[5] = 0; + a[6] = 0; + a[7] = 0; + a[8] = 0; + a[9] = 0; + a[10] = 0; + a[11] = 0; + a[12] = 0; +} + +static u32 JogconGetPortCtrl1(u32 a, u32 b) +{ + if(a == 0) + return 0xFFC00505; + else + return 0xFF060505; +} + +static u32 JogconGetPortCtrl2(u32 a) +{ + if(a == 0) + return 0x20014; + else + return 0x2012C; +} + +static u32 JogconRegData(void) +{ + return 0x340d40; +} + +static u32 JogconSize1(void) +{ + return 0xD; +} + +static u32 JogconSize2(void) +{ + return 0xD; +} + +static u32 JogconEnterConfigMode(u8 *a) +{ + a[0] = 0x1; + a[1] = 0x43; + a[2] = 0; + a[3] = 0x1; + a[4] = 0; + a[5] = 0; + a[6] = 0; + a[7] = 0; + a[8] = 0; + a[9] = 0; + a[10] = 0; + a[11] = 0; + a[12] = 0; + + return 0xD; +} + +void sio2cmdInitJogcon(void) +{ + sio2Cmds_t s; + + s.id = PAD_ID_HI(PAD_ID_JOGCON); + + s.readdata = &JogconReadData; + s.getportctrl1 = &JogconGetPortCtrl1; + s.getportctrl2 = &JogconGetPortCtrl2; + s.reg_data = &JogconRegData; + s.size1 = &JogconSize1; + s.size2 = &JogconSize2; + s.enterconfigmode = &JogconEnterConfigMode; + s.exitconfigmode = NULL; + s.querymodel = NULL; + s.queryact = NULL; + s.querycomb = NULL; + s.querymode = NULL; + s.querybuttonmask = NULL; + s.setbuttoninfo = NULL; + s.setvrefparam = NULL; + s.setmainmode = NULL; + s.setactalign = NULL; + + SetupCmds(&s); +} + +/******************************************************************************* + Config +*******************************************************************************/ + +static void ConfigReadData(u8* a) +{ + a[0] = 1; + a[1] = 0x42; + a[2] = 0; + a[3] = 0x5A; + a[4] = 0x5A; + a[5] = 0x5A; + a[6] = 0x5A; + a[7] = 0x5A; + a[8] = 0x5A; +} + +static u32 ConfigGetPortCtrl1(u32 a, u32 b) +{ + if(a == 0) + return 0xFFC00505; + else + return 0xFF060505; +} + +static u32 ConfigGetPortCtrl2(u32 a) +{ + if(a == 0) + return 0x20014; + else + return 0x2012C; +} + +static u32 ConfigRegData(void) +{ + return 0x240940; +} + +static u32 ConfigSize1(void) +{ + return 0x9; +} + +static u32 ConfigSize2(void) +{ + return 0x9; +} + +static u32 ConfigExitConfigMode(u8 *a) +{ + a[0] = 1; + a[1] = 0x43; + a[2] = 0x0; + a[3] = 0x0; + a[4] = 0x5a; + a[5] = 0x5a; + a[6] = 0x5a; + a[7] = 0x5a; + a[8] = 0x5a; + + return 9; +} + +static u32 ConfigQueryModel(u8 *a) +{ + a[0] = 1; + a[1] = 0x45; + a[2] = 0x0; + a[3] = 0x5a; + a[4] = 0x5a; + a[5] = 0x5a; + a[6] = 0x5a; + a[7] = 0x5a; + a[8] = 0x5a; + + return 9; +} + +static u32 ConfigQueryAct(u8 *a) +{ + a[0] = 1; + a[1] = 0x46; + a[2] = 0x0; + a[3] = 0x0; + a[4] = 0x5a; + a[5] = 0x5a; + a[6] = 0x5a; + a[7] = 0x5a; + a[8] = 0x5a; + + return 9; +} + +static u32 ConfigQueryComb(u8 *a) +{ + a[0] = 1; + a[1] = 0x47; + a[2] = 0x0; + a[3] = 0x0; + a[4] = 0x5a; + a[5] = 0x5a; + a[6] = 0x5a; + a[7] = 0x5a; + a[8] = 0x5a; + + return 9; +} + +static u32 ConfigQueryMode(u8 *a) +{ + a[0] = 1; + a[1] = 0x4c; + a[2] = 0x0; + a[3] = 0x0; + a[4] = 0x5a; + a[5] = 0x5a; + a[6] = 0x5a; + a[7] = 0x5a; + a[8] = 0x5a; + + return 9; +} + +static u32 ConfigQueryButtonMask(u8 *a) +{ + a[0] = 1; + a[1] = 0x41; + a[2] = 0x0; + a[3] = 0x5a; + a[4] = 0x5a; + a[5] = 0x5a; + a[6] = 0x5a; + a[7] = 0x5a; + a[8] = 0x5a; + + return 9; +} + +static u32 ConfigSetButtonInfo(u8 *a) +{ + a[0] = 1; + a[1] = 0x4F; + a[2] = 0x0; + a[3] = 0x0; + a[4] = 0x0; + a[5] = 0x0; + a[6] = 0x0; + a[7] = 0x0; + a[8] = 0x0; + + return 9; +} + +static u32 ConfigSetVrefParam(u8 *a) +{ + a[0] = 1; + a[1] = 0x40; + a[2] = 0x0; + a[3] = 0x0; + a[4] = 0x0; + a[5] = 0x0; + a[6] = 0x0; + a[7] = 0x0; + a[8] = 0x0; + + return 9; +} + +static u32 ConfigSetMainMode(u8 *a) +{ + a[0] = 1; + a[1] = 0x44; + a[2] = 0x0; + a[3] = 0x0; + a[4] = 0x0; + a[5] = 0x0; + a[6] = 0x0; + a[7] = 0x0; + a[8] = 0x0; + + return 9; +} + +static u32 ConfigSetSetActAlign(u8 *a) +{ + a[0] = 1; + a[1] = 0x4d; + a[2] = 0x0; + a[3] = 0x0; + a[4] = 0x0; + a[5] = 0x0; + a[6] = 0x0; + a[7] = 0x0; + a[8] = 0x0; + + return 9; +} + +void sio2cmdInitConfig(void) +{ + sio2Cmds_t s; + + s.id = PAD_ID_HI( PAD_ID_CONFIG ); + + s.readdata = &ConfigReadData; + s.getportctrl1 = &ConfigGetPortCtrl1; + s.getportctrl2 = &ConfigGetPortCtrl2; + s.reg_data = &ConfigRegData; + s.size1 = &ConfigSize1; + s.size2 = &ConfigSize2; + s.enterconfigmode = NULL; + s.exitconfigmode = &ConfigExitConfigMode; + s.querymodel = &ConfigQueryModel; + s.queryact = &ConfigQueryAct; + s.querycomb = &ConfigQueryComb; + s.querymode = &ConfigQueryMode; + s.querybuttonmask = &ConfigQueryButtonMask; + s.setbuttoninfo = &ConfigSetButtonInfo; + s.setvrefparam = &ConfigSetVrefParam; + s.setmainmode = &ConfigSetMainMode; + s.setactalign = &ConfigSetSetActAlign; + + SetupCmds(&s); +} + +/******************************************************************************* +*******************************************************************************/ + +u32 sio2cmdCheckId(u8 id) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + return 1; + } + + return 0; +} + + +u32 sio2CmdGetPortCtrl1(u8 id, u32 b, u8 c) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if(sio2Cmds[i].id == id) + { + if(sio2Cmds[i].getportctrl1 != NULL) + return sio2Cmds[i].getportctrl1(b, c); + } + } + + return 0; +} + +u32 sio2CmdGetPortCtrl2(u32 id, u32 b) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if(sio2Cmds[i].id == id) + { + if(sio2Cmds[i].getportctrl2 != NULL) + return sio2Cmds[i].getportctrl2(b); + } + } + + return 0; +} + +void sio2CmdSetReadData(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if(sio2Cmds[i].id == id) + { + if(sio2Cmds[i].readdata != NULL) + { + sio2Cmds[i].readdata(buf); + return; + } + } + } +} + +u32 sio2CmdSetEnterConfigMode(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if(sio2Cmds[i].id == id) + { + if(sio2Cmds[i].enterconfigmode != NULL) + return sio2Cmds[i].enterconfigmode(buf); + } + + } + + return 0; +} + +u32 sio2CmdSetQueryModel(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + { + if( sio2Cmds[i].querymodel != NULL) + return sio2Cmds[i].querymodel(buf); + } + } + + return 0; +} + +u32 sio2CmdSetSetMainMode(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + { + if( sio2Cmds[i].setmainmode != NULL) + return sio2Cmds[i].setmainmode(buf); + } + } + + return 0; +} + +u32 sio2CmdSetQueryAct(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + { + if( sio2Cmds[i].queryact != NULL) + return sio2Cmds[i].queryact(buf); + } + } + + return 0; +} + +u32 sio2CmdSetQueryComb(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + { + if( sio2Cmds[i].querycomb != NULL) + return sio2Cmds[i].querycomb(buf); + } + } + + return 0; +} + +u32 sio2CmdSetQueryMode(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + { + if( sio2Cmds[i].querymode != NULL) + return sio2Cmds[i].querymode(buf); + } + } + + return 0; +} + +u32 sio2CmdSetExitConfigMode(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + { + if( sio2Cmds[i].exitconfigmode != NULL) + return sio2Cmds[i].exitconfigmode(buf); + } + } + + return 0; +} + +u32 sio2CmdSetSetActAlign(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + { + if( sio2Cmds[i].setactalign != NULL) + return sio2Cmds[i].setactalign(buf); + } + } + + return 0; +} + +u32 sio2CmdSetQueryButtonMask(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + { + if( sio2Cmds[i].querybuttonmask != NULL) + return sio2Cmds[i].querybuttonmask(buf); + } + } + + return 0; +} + +u32 sio2CmdSetSetVrefParam(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + { + if( sio2Cmds[i].setvrefparam != NULL) + return sio2Cmds[i].setvrefparam(buf); + } + } + + return 0; + +} + +u32 sio2CmdSetSetButtonInfo(u32 id, u8 *buf) +{ + int i; + id = PAD_ID_HI(id); + + for(i=0; i < numControllers; i++) + { + if( sio2Cmds[i].id == id ) + { + if( sio2Cmds[i].setbuttoninfo != NULL) + return sio2Cmds[i].setbuttoninfo(buf); + } + } + + return 0; + +} diff --git a/sps2_basement/hardware/mem/padman/src/sio2Cmds.h b/sps2_basement/hardware/mem/padman/src/sio2Cmds.h new file mode 100644 index 0000000..bed18d2 --- /dev/null +++ b/sps2_basement/hardware/mem/padman/src/sio2Cmds.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2007 Lukasz Bruun + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/** + * @file + * IOP pad driver + */ + +#ifndef __FREEPAD_SIO2CMDS_H__ +#define __FREEPAD_SIO2CMDS_H__ + +#define SIO2_CMD_MAX 16 + +#define PAD_ID_FINDPADS 0x01 +#define PAD_ID_MOUSE 0x12 +#define PAD_ID_NEGICON 0x23 +#define PAD_ID_KONAMIGUN 0x31 +#define PAD_ID_DIGITAL 0x41 +#define PAD_ID_JOYSTICK 0x53 +#define PAD_ID_NAMCOGUN 0x63 +#define PAD_ID_ANALOG 0x73 +#define PAD_ID_ANALOG2 0x79 +#define PAD_ID_MULTITAP 0x80 +#define PAD_ID_JOGCON 0xE3 +#define PAD_ID_JOGCON2 0xE5 +#define PAD_ID_CONFIG 0xF3 + +#define PAD_ID_HI(id) ((id)>>4) +#define PAD_ID_LO(id) ((id)&0xF) + +void sio2cmdReset(void); +void sio2cmdInitFindPads(void); +void sio2cmdInitMouse(void); +void sio2cmdInitNegicon(void); +void sio2cmdInitKonamiGun(void); +void sio2cmdInitDigital(void); +void sio2cmdInitJoystick(void); +void sio2cmdInitNamcoGun(void); +void sio2cmdInitAnalog(void); +void sio2cmdInitJogcon(void); +void sio2cmdInitConfig(void); + +u32 sio2cmdCheckId(u8 id); + +void sio2CmdSetReadData(u32 id, u8 *buf); +u32 sio2CmdSetEnterConfigMode(u32 id, u8 *buf); +u32 sio2CmdSetExitConfigMode(u32 id, u8 *buf); +u32 sio2CmdSetQueryModel(u32 id, u8 *buf); +u32 sio2CmdSetQueryAct(u32 id, u8 *buf); +u32 sio2CmdSetQueryComb(u32 id, u8 *buf); +u32 sio2CmdSetQueryMode(u32 id, u8 *buf); +u32 sio2CmdSetQueryButtonMask(u32 id, u8 *buf); +u32 sio2CmdSetSetButtonInfo(u32 id, u8 *buf); +u32 sio2CmdSetSetVrefParam(u32 id, u8 *buf); +u32 sio2CmdSetSetMainMode(u32 id, u8 *buf); +u32 sio2CmdSetSetActAlign(u32 id, u8 *buf); + +u32 sio2CmdGetPortCtrl1(u8 id, u32 b, u8 c); +u32 sio2CmdGetPortCtrl2(u32 id, u32 b); + + +#endif + diff --git a/sps2_basement/hardware/mem/rmman/Makefile b/sps2_basement/hardware/mem/rmman/Makefile new file mode 100644 index 0000000..2926a51 --- /dev/null +++ b/sps2_basement/hardware/mem/rmman/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_INCS += -I$(PS2SDKSRC)/iop/system/sio2man/include/ -I$(PS2SDKSRC)/iop/system/rsio2man/include/ + +IOP_OBJS = rmman.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/mem/rmman/README b/sps2_basement/hardware/mem/rmman/README new file mode 100644 index 0000000..b326cb3 --- /dev/null +++ b/sps2_basement/hardware/mem/rmman/README @@ -0,0 +1,7 @@ +This is a compatible version of rom1:RMMAN, cloned from ROM v2.20. +This module requires a new version of SIO2MAN (export table v2.x), like rom1:SIO2MAN. + +Older consoles may have an older version of RMMAN, version v1.09. +That version has no real differences in functionality. Known differences: + 1. Does not clear the connected status, if a unrecognized response is returned within FindRemote(). + 2. The in_buf and out_buf fields of the SIO2 data structure are set to NULL within InitFindRmCmd(). diff --git a/sps2_basement/hardware/mem/rmman/include/rmman.h b/sps2_basement/hardware/mem/rmman/include/rmman.h new file mode 100644 index 0000000..b430ce9 --- /dev/null +++ b/sps2_basement/hardware/mem/rmman/include/rmman.h @@ -0,0 +1,36 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * RMMAN definitions + */ + +#ifndef __RMMAN_H__ +#define __RMMAN_H__ + +#include +#include +#include + +int rmmanInit(void); +int rmmanOpen(int port, int slot, void *buffer); +int rmmanClose(int port, int slot); +int rmmanEnd(void); + +#define rmman_IMPORTS_start DECLARE_IMPORT_TABLE(rmman, 1, 1) +#define rmman_IMPORTS_end END_IMPORT_TABLE + +#define I_rmmanInit DECLARE_IMPORT(4, rmmanInit) +#define I_rmmanOpen DECLARE_IMPORT(5, rmmanOpen) +#define I_rmmanClose DECLARE_IMPORT(6, rmmanClose) +#define I_rmmanEnd DECLARE_IMPORT(7, rmmanEnd) + +#endif /* __RMMAN_H__ */ diff --git a/sps2_basement/hardware/mem/rmman/src/exports.tab b/sps2_basement/hardware/mem/rmman/src/exports.tab new file mode 100644 index 0000000..3881a1f --- /dev/null +++ b/sps2_basement/hardware/mem/rmman/src/exports.tab @@ -0,0 +1,12 @@ +DECLARE_EXPORT_TABLE(rmman, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(rmmanInit) + DECLARE_EXPORT(rmmanOpen) + DECLARE_EXPORT(rmmanClose) + DECLARE_EXPORT(rmmanEnd) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/mem/rmman/src/imports.lst b/sps2_basement/hardware/mem/rmman/src/imports.lst new file mode 100644 index 0000000..0ce6177 --- /dev/null +++ b/sps2_basement/hardware/mem/rmman/src/imports.lst @@ -0,0 +1,52 @@ + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_DeleteThread +I_StartThread +I_ExitThread +I_GetThreadId +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_DeleteEventFlag +I_SetEventFlag +I_WaitEventFlag +I_ReferEventFlagStatus +thevent_IMPORTS_end + +sifman_IMPORTS_start +I_sceSifInit +I_sceSifCheckInit +I_sceSifSetDma +sifman_IMPORTS_end + +sifcmd_IMPORTS_start +I_sceSifInitRpc +I_sceSifRegisterRpc +I_sceSifSetRpcQueue +I_sceSifRpcLoop +sifcmd_IMPORTS_end + +rsio2man_IMPORTS_start +I_sio2_rm_transfer_init +I_sio2_transfer +I_sio2_transfer_reset +rsio2man_IMPORTS_end + +vblank_IMPORTS_start +I_WaitVblankStart +vblank_IMPORTS_end diff --git a/sps2_basement/hardware/mem/rmman/src/irx_imports.h b/sps2_basement/hardware/mem/rmman/src/irx_imports.h new file mode 100644 index 0000000..22bcdf3 --- /dev/null +++ b/sps2_basement/hardware/mem/rmman/src/irx_imports.h @@ -0,0 +1,29 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/mem/rmman/src/rmman.c b/sps2_basement/hardware/mem/rmman/src/rmman.c new file mode 100644 index 0000000..dc8a800 --- /dev/null +++ b/sps2_basement/hardware/mem/rmman/src/rmman.c @@ -0,0 +1,556 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rmman.h" + +IRX_ID("rmman", 1, 16); + +#define RM_EF_EXIT_THREAD 1 +#define RM_EF_EXIT_THREAD_DONE 2 +#define RM_EF_CLOSE_PORT 4 +#define RM_EF_CLOSE_PORT_DONE 8 + +enum RM_TASK { + RM_TASK_QUERY = 0, + RM_TASK_INIT, + RM_TASK_POLL +}; + +struct RmData{ //size = 316 + struct rmEEData eeData; //0x000 + u32 unused1; //0x030 + u8 inBuffer[32]; //0x034 + u8 outBuffer[32]; //0x054 + u32 state; //0x074 + u32 reqState; //0x078 + u32 frame; //0x07C + struct rmEEData *eeBuffer; //0x080 + s32 port; //0x084 + s32 slot; //0x088 + u32 currentTask; //0x08C + u32 counter; //0x090 + u32 powerMode; //0x094 + u32 closed; //0x098 + u32 connected; //0x09C + u32 eventFlagID; //0x0a0 + u32 unused2; //0x0a4 + sio2_transfer_data_t sio2Data; //0x0a8 +}; + +extern struct irx_export_table _exp_rmman; + +static struct RmData RmData[2][4]; +static int portStatus[2]; +static int eventFlagID; +static int MainThreadID; +static int IsInitialized; +static int RpcThreadID; +static SifRpcDataQueue_t RpcDataQueue; +static SifRpcServerData_t RpcServerData; +static struct rmRpcPacket RpcDataBuffer; + +static int CreateMainThread(void); +static void MainThread(void *arg); +static int HandleTasks(struct RmData *RmData); +static int FindRemote(struct RmData *RmData); +static int InitFindRmCmd(struct RmData *RmData); +static int PollRemote(struct RmData *RmData); +static int InitPollRmCmd(struct RmData *RmData); +static int RmExecute(struct RmData *RmData); +static int DmaSendEE(struct RmData *RmData); +static int HandleRmTaskFailed(struct RmData *RmData); +static int InitRemote(struct RmData *RmData); +static int InitInitRmCmd(struct RmData *RmData); + +int _start(int argc, char *argv[]) +{ + int result; + + if(RegisterLibraryEntries(&_exp_rmman) == 0) + { + result = CreateMainThread() <= 0 ? MODULE_NO_RESIDENT_END : MODULE_RESIDENT_END; + } + else result = MODULE_NO_RESIDENT_END; + + return result; +} + +int rmmanInit(void) +{ + iop_event_t EventFlagData; + iop_thread_t ThreadData; + int result; + + portStatus[0] = 0; + portStatus[1] = 0; + IsInitialized = 1; + EventFlagData.attr = 2; + EventFlagData.bits = 0; + if((eventFlagID = CreateEventFlag(&EventFlagData)) != 0) + { + ThreadData.attr = TH_C; + ThreadData.thread = &MainThread; + ThreadData.priority = 0x2E; + ThreadData.stacksize = 0x800; + if((MainThreadID = CreateThread(&ThreadData)) != 0) + { + StartThread(MainThreadID, NULL); + result=MainThreadID; + } + else result=0; + } + else result=0; + + return result; +} + +int rmmanOpen(int port, int slot, void *buffer) +{ + iop_event_t evf; + int result; + struct RmData *pRmData; + + if(!((portStatus[port] >> slot) & 1)) + { + pRmData = &RmData[port][slot]; + pRmData->port = port; + pRmData->slot = slot; + pRmData->state = RM_STATE_EXECCMD; + pRmData->reqState = RM_RSTATE_COMPLETE; + pRmData->eeBuffer = buffer; + pRmData->currentTask = RM_TASK_QUERY; + pRmData->counter = 0; + + evf.attr = EA_MULTI; + evf.bits = 0; + + if((pRmData->eventFlagID = CreateEventFlag(&evf)) != 0) + { + pRmData->powerMode = 0; + portStatus[port] |= (1 << slot); + result = 1; + } else + result = 0; + } else + result = 0; + + return result; +} + +int rmmanClose(int port, int slot) +{ + int result; + struct RmData *pRmData; + u32 bits; + + if((portStatus[port] >> slot) & 1) + { + pRmData = &RmData[port][slot]; + + if(pRmData->state != RM_STATE_FINDRM) + { + SetEventFlag(pRmData->eventFlagID, RM_EF_EXIT_THREAD); + WaitEventFlag(pRmData->eventFlagID, RM_EF_EXIT_THREAD_DONE, WEF_AND|WEF_CLEAR, &bits); + + if(pRmData->closed != 0) + { //Remote Control port was closed successfully. + portStatus[port] ^= (1 << slot); + result = 1; + } else { + result = 0; + } + } else { + portStatus[port] ^= (1 << slot); + result = 1; + } + } else + result = 0; + + return result; +} + +int rmmanEnd(void) +{ + u32 bits; + int port, slot, result; + + if(IsInitialized != 0) + { + for(port = 0; port < 2; port++) + { + for(slot = 0; slot < 4; slot++) + { //If port,slot is opened, close it. + if((portStatus[port] >> slot) & 1) + rmmanClose(port, slot); + } + } + + SetEventFlag(eventFlagID, RM_EF_EXIT_THREAD); + WaitEventFlag(eventFlagID, RM_EF_EXIT_THREAD_DONE, WEF_AND|WEF_CLEAR, &bits); + DeleteEventFlag(eventFlagID); + eventFlagID = 0; + if(DeleteThread(eventFlagID) == 0) + { + MainThreadID = 0; + IsInitialized = 0; + + result = 1; + } else + result = 0; + } else + result = 1; + + return result; +} + +static void MainThread(void *arg) +{ + iop_event_info_t evfInfo; + int port, slot; + + while(1) + { + WaitVblankStart(); + + ReferEventFlagStatus(eventFlagID, &evfInfo); + + if(evfInfo.currBits == RM_EF_EXIT_THREAD) + { + SetEventFlag(eventFlagID, RM_EF_EXIT_THREAD_DONE); + ExitThread(); + } + + for(port = 0; port < 2; port++) + { + for(slot = 0; slot < 4; slot++) + { + if((portStatus[port] >> slot) & 1) + { + ReferEventFlagStatus(RmData[port][slot].eventFlagID, &evfInfo); + + if(evfInfo.currBits == RM_EF_CLOSE_PORT) + { + RmData[port][slot].powerMode = 3; + if(InitRemote(&RmData[port][slot]) == 0) + RmData[port][slot].closed = 0; + else + RmData[port][slot].closed = 1; + + SetEventFlag(RmData[port][slot].eventFlagID, RM_EF_CLOSE_PORT_DONE); + } else { + HandleTasks(&RmData[port][slot]); + } + } + } + } + } +} + +static int HandleTasks(struct RmData *RmData) +{ + switch(RmData->currentTask) + { + case RM_TASK_QUERY: + if(RmData->counter == 0 && FindRemote(RmData) != 0) + { + RmData->counter = 0; + RmData->state = RM_STATE_EXECCMD; + RmData->currentTask++; + } else { + if(RmData->counter < 10) + { + RmData->counter++; + RmData->state = RM_STATE_FINDRM; + } else { + RmData->counter = 0; + } + } + break; + case RM_TASK_INIT: + if(InitRemote(RmData) != 0) + { + RmData->counter = 0; + RmData->currentTask++; + } else { + HandleRmTaskFailed(RmData); + } + break; + case RM_TASK_POLL: + RmData->state = RM_STATE_STABLE; + if(PollRemote(RmData) != 0) + { + RmData->counter = 0; + + if(RmData->reqState == RM_RSTATE_BUSY) + RmData->reqState = RM_RSTATE_COMPLETE; + } else { + if(HandleRmTaskFailed(RmData) == 0 && RmData->reqState == RM_RSTATE_BUSY) + RmData->reqState = RM_RSTATE_FAILED; + } + break; + } + + DmaSendEE(RmData); + + return 1; +} + +static int FindRemote(struct RmData *RmData) +{ + int result; + + InitFindRmCmd(RmData); + if(RmExecute(RmData) != 0) + { + if(RmData->port < 2) + { + switch(RmData->outBuffer[1]) + { + case 0x12: + result = 1; + break; + case 0x1F: + InitRemote(RmData); + result = 1; + break; + default: + RmData->connected = 0; + result = 0; + } + } else + result = 1; + } else + result = 0; + + return result; +} + +static int InitFindRmCmd(struct RmData *RmData) +{ + int i; + + //The original was setting these, byte by byte. + RmData->sio2Data.port_ctrl1[RmData->port] = 0xFFC0050F; + RmData->sio2Data.port_ctrl2[RmData->port] = 0x00060014; + + RmData->sio2Data.port_ctrl2[RmData->port] = (RmData->sio2Data.port_ctrl2[RmData->port] & ~0x03000000) | 0x01000000; + + RmData->sio2Data.in = RmData->inBuffer; + RmData->sio2Data.out = RmData->outBuffer; + RmData->inBuffer[0] = 0x61; + RmData->sio2Data.in_size = 7; + RmData->sio2Data.out_size = 7; + RmData->sio2Data.regdata[1] = 0; + RmData->inBuffer[1] = 0x0F; + + RmData->sio2Data.regdata[0] = (RmData->sio2Data.regdata[0] & ~3) | (RmData->port & 3); + RmData->sio2Data.regdata[0] = (RmData->sio2Data.regdata[0] & ~0x000000C0) | 0x40; + RmData->sio2Data.regdata[0] = (RmData->sio2Data.regdata[0] & ~0x0001FF00) | 0x00700; + RmData->sio2Data.regdata[0] = (RmData->sio2Data.regdata[0] & ~0x07FC0000) | 0x001C0000; + + for(i = 2; i < 7; i++) + RmData->inBuffer[i] = 0; + + return 1; +} + +static int PollRemote(struct RmData *RmData) +{ + InitPollRmCmd(RmData); + return(RmExecute(RmData) > 0); +} + +static int InitPollRmCmd(struct RmData *RmData) +{ + int i; + + RmData->inBuffer[0] = 0x61; + RmData->inBuffer[1] = 0x04; + for(i = 2; i < 7; i++) + RmData->inBuffer[i] = 0; + + return 1; +} + +static int RmExecute(struct RmData *RmData) +{ + int result; + + sio2_rm_transfer_init(); + sio2_transfer(&RmData->sio2Data); + sio2_transfer_reset(); + + if(((RmData->sio2Data.stat6c >> 14) & 3) == 0) + { + RmData->connected = 1; + result = 1; + } else { + RmData->connected = 0; + result = 0; + } + + return result; +} + +static int HandleRmTaskFailed(struct RmData *RmData) +{ + if(RmData->counter + 1 < 10) + { + RmData->counter++; + return RmData->counter; + } else { + RmData->currentTask = RM_TASK_QUERY; + return 0; + } +} + +static int DmaSendEE(struct RmData *RmData) +{ + SifDmaTransfer_t dmat; + int i, OldState, dmatID; + + RmData->eeData.frame = RmData->frame; + RmData->frame++; + for(i = 0; i < sizeof(RmData->eeData.data); i++) + RmData->eeData.data[i] = RmData->outBuffer[i]; + + RmData->eeData.state = RmData->state; + RmData->eeData.connected = RmData->connected; + + dmat.src = &RmData->eeData; + dmat.dest = ((RmData->frame & 1) == 0) ? (u8*)RmData->eeBuffer : (u8*)RmData->eeBuffer + 128; + dmat.size = 128; + dmat.attr = 0; + + CpuSuspendIntr(&OldState); + dmatID = sceSifSetDma(&dmat, 1); + CpuResumeIntr(OldState); + + return(dmatID > 0); +} + +static int InitRemote(struct RmData *RmData) +{ + InitInitRmCmd(RmData); + return(RmExecute(RmData) > 0); +} + +static int InitInitRmCmd(struct RmData *RmData) +{ + int i; + + RmData->inBuffer[0] = 0x61; + RmData->inBuffer[1] = 0x06; + RmData->inBuffer[2] = (u8)RmData->powerMode; + + for(i = 3; i < 7; i++) + RmData->inBuffer[i] = 0; + + return 1; +} + +static int rmmanVersion(void) +{ + return _irx_id.v; +} + +static void *RmmanRpc_init(struct rmRpcPacket *packet) +{ + packet->cmd.result = rmmanInit(); + return packet; +} + +static void *RmmanRpc_version(struct rmRpcPacket *packet) +{ + packet->cmd.result = rmmanVersion(); + return packet; +} + +static void *RmmanRpc_open(struct rmRpcPacket *packet) +{ + packet->cmd.result = rmmanOpen(packet->cmd.port, packet->cmd.slot, packet->cmd.data); + return packet; +} + +static void *RmmanRpc_end(struct rmRpcPacket *packet) +{ + packet->cmd.result = rmmanEnd(); + return packet; +} + +static void *RmmanRpc_close(struct rmRpcPacket *packet) +{ + packet->cmd.result = rmmanClose(packet->cmd.port, packet->cmd.slot); + return packet; +} + +static void *RpcHandler(int fno, void *buffer, int len) +{ + void *retBuff; + + switch(((struct rmRpcPacket *)buffer)->cmd.command) + { + case RMMAN_RPCFUNC_END: + retBuff = RmmanRpc_end((struct rmRpcPacket *)buffer); + break; + case RMMAN_RPCFUNC_INIT: + retBuff = RmmanRpc_init((struct rmRpcPacket *)buffer); + break; + case RMMAN_RPCFUNC_CLOSE: + retBuff = RmmanRpc_close((struct rmRpcPacket *)buffer); + break; + case RMMAN_RPCFUNC_OPEN: + retBuff = RmmanRpc_open((struct rmRpcPacket *)buffer); + break; + case RMMAN_RPCFUNC_VERSION: + retBuff = RmmanRpc_version((struct rmRpcPacket *)buffer); + break; + default: + printf("invalid function code (%03x)\n", (unsigned int)((struct rmRpcPacket *)buffer)->cmd.command); + retBuff = buffer; + } + + return retBuff; +} + +static void RpcThread(void *arg) +{ + if(!sceSifCheckInit()) + { + printf("yet sif hasn't been init\n"); + sceSifInit(); + } + + sceSifInitRpc(0); + + sceSifSetRpcQueue(&RpcDataQueue, GetThreadId()); + sceSifRegisterRpc(&RpcServerData, RMMAN_RPC_ID, &RpcHandler, &RpcDataBuffer, NULL, NULL, &RpcDataQueue); + sceSifRpcLoop(&RpcDataQueue); +} + +static int CreateMainThread(void) +{ + iop_thread_t ThreadData; + int result; + + ThreadData.attr=TH_C; + ThreadData.thread=&RpcThread; + ThreadData.priority=0x2E; + ThreadData.stacksize=0x800; + if((RpcThreadID=CreateThread(&ThreadData))!=0) + { + StartThread(RpcThreadID, NULL); + result = 1; + } + else result = 0; + + return result; +} diff --git a/sps2_basement/hardware/mem/rmtapman/Makefile b/sps2_basement/hardware/mem/rmtapman/Makefile new file mode 100644 index 0000000..ba276d3 --- /dev/null +++ b/sps2_basement/hardware/mem/rmtapman/Makefile @@ -0,0 +1,17 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN_ALTNAMES = + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/system/mtapman/src/ + +IOP_CFLAGS += -DSIO2MAN_V2 + +IOP_INCS += -I$(PS2SDKSRC)/iop/system/rsio2man/include/ + +include $(PS2SDKSRC)/iop/system/mtapman/Makefile diff --git a/sps2_basement/hardware/mem/rmtapman/README b/sps2_basement/hardware/mem/rmtapman/README new file mode 100644 index 0000000..d68db90 --- /dev/null +++ b/sps2_basement/hardware/mem/rmtapman/README @@ -0,0 +1 @@ +Special build to support the newer SIO2MAN module, to support RMMAN. diff --git a/sps2_basement/hardware/mem/rpadman/Makefile b/sps2_basement/hardware/mem/rpadman/Makefile new file mode 100644 index 0000000..12d88cd --- /dev/null +++ b/sps2_basement/hardware/mem/rpadman/Makefile @@ -0,0 +1,17 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN_ALTNAMES = + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/system/padman/src/ + +IOP_CFLAGS += -DSIO2MAN_V2 # -DDEBUG + +IOP_INCS += -I$(PS2SDKSRC)/iop/system/rsio2man/include + +include $(PS2SDKSRC)/iop/system/padman/Makefile diff --git a/sps2_basement/hardware/mem/rpadman/README b/sps2_basement/hardware/mem/rpadman/README new file mode 100644 index 0000000..d68db90 --- /dev/null +++ b/sps2_basement/hardware/mem/rpadman/README @@ -0,0 +1 @@ +Special build to support the newer SIO2MAN module, to support RMMAN. diff --git a/sps2_basement/hardware/mem/rsio2man/Makefile b/sps2_basement/hardware/mem/rsio2man/Makefile new file mode 100644 index 0000000..1302a38 --- /dev/null +++ b/sps2_basement/hardware/mem/rsio2man/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN_ALTNAMES = + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/system/sio2man/src/ +IOP_INC_DIR = $(PS2SDKSRC)/iop/system/sio2man/include/ + +IOP_CFLAGS += -DSIO2MAN_V2 + +include $(PS2SDKSRC)/iop/system/sio2man/Makefile diff --git a/sps2_basement/hardware/mem/rsio2man/README b/sps2_basement/hardware/mem/rsio2man/README new file mode 100644 index 0000000..6504229 --- /dev/null +++ b/sps2_basement/hardware/mem/rsio2man/README @@ -0,0 +1,6 @@ +Based on the free XSIO2MAN replacement module, freesio2. +Built from the sio2log source, without the logging feature. + +This module is meant to be a compatible version of rom1:SIO2MAN, + which is a newer version of SIO2MAN than rom0:SIO2MAN. +rom1:SIO2MAN is used by the DVD player, which is required for the remote control manager (RMMAN). diff --git a/sps2_basement/hardware/mem/rsio2man/include/rsio2man.h b/sps2_basement/hardware/mem/rsio2man/include/rsio2man.h new file mode 100644 index 0000000..3d91190 --- /dev/null +++ b/sps2_basement/hardware/mem/rsio2man/include/rsio2man.h @@ -0,0 +1,45 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * rom1:SIO2MAN module definitions + * rom1:SIO2MAN is a newer version of SIO2MAN than rom0:SIO2MAN. + */ + +#ifndef __RSIO2MAN_H__ +#define __RSIO2MAN_H__ + +#define NO_XSIO2MAN_IMPORTS +#include +#undef NO_XSIO2MAN_IMPORTS + +void sio2_rm_transfer_init(void); +void sio2_unk_transfer_init(void); + +#define rsio2man_IMPORTS_start DECLARE_IMPORT_TABLE(sio2man, 2, 3) +#define rsio2man_IMPORTS_end END_IMPORT_TABLE + +#define I_sio2_transfer_reset DECLARE_IMPORT(26, sio2_transfer_reset) +#define I_sio2_mtap_transfer_init DECLARE_IMPORT(48, sio2_mtap_transfer_init) +#define I_sio2_rm_transfer_init DECLARE_IMPORT(49, sio2_rm_transfer_init) +#define I_sio2_unk_transfer_init DECLARE_IMPORT(50, sio2_unk_transfer_init) +#define I_sio2_transfer2 DECLARE_IMPORT(51, sio2_transfer2) +#define I_sio2_transfer_reset2 DECLARE_IMPORT(52, sio2_transfer_reset2) +#define I_sio2_mtap_change_slot_set DECLARE_IMPORT(53, sio2_mtap_change_slot_set) +#define I_sio2_mtap_get_slot_max_set DECLARE_IMPORT(54, sio2_mtap_get_slot_max_set) +#define I_sio2_mtap_get_slot_max2_set DECLARE_IMPORT(55, sio2_mtap_get_slot_max2_set) +#define I_sio2_mtap_update_slots_set DECLARE_IMPORT(56, sio2_mtap_update_slots_set) +#define I_sio2_mtap_change_slot DECLARE_IMPORT(57, sio2_mtap_change_slot) +#define I_sio2_mtap_get_slot_max DECLARE_IMPORT(58, sio2_mtap_get_slot_max) +#define I_sio2_mtap_get_slot_max2 DECLARE_IMPORT(59, sio2_mtap_get_slot_max2) +#define I_sio2_mtap_update_slots DECLARE_IMPORT(60, sio2_mtap_update_slots) + +#endif /* __RSIO2MAN_H__ */ diff --git a/sps2_basement/hardware/mem/sbusintr/Makefile b/sps2_basement/hardware/mem/sbusintr/Makefile new file mode 100644 index 0000000..3368d16 --- /dev/null +++ b/sps2_basement/hardware/mem/sbusintr/Makefile @@ -0,0 +1,14 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_OBJS = sbusintr.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/mem/sbusintr/include/sbusintr.h b/sps2_basement/hardware/mem/sbusintr/include/sbusintr.h new file mode 100644 index 0000000..d367d06 --- /dev/null +++ b/sps2_basement/hardware/mem/sbusintr/include/sbusintr.h @@ -0,0 +1,53 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * SBUS interrupts. + */ + +#ifndef __SBUSINTR_H__ +#define __SBUSINTR_H__ + +#include +#include + +/* SBUS interface */ +enum sbus_errors { + SBUS_E_OK, + + /** Initialization error */ + SBUS_E_INIT = 0xd600, + /** Error with an argument */ + SBUS_E_ARG, + /** Wrong IRQ number / already in use */ + SBUS_E_IRQ, +}; + +typedef int (*sbus_intr_handler_t)(u32, void *); + +int sbus_intr_init(); +void sbus_intr_exit(); + +int sbus_intr_handler_add(u32 irq, sbus_intr_handler_t handler, void *arg); +int sbus_intr_handler_del(u32 irq); + +void sbus_intr_main_interrupt(u32 irq); + +#define sbusintr_IMPORTS_start DECLARE_IMPORT_TABLE(sbusintr, 1, 1) +#define sbusintr_IMPORTS_end END_IMPORT_TABLE + +#define I_sbus_intr_init DECLARE_IMPORT(4, sbus_intr_init) +#define I_sbus_intr_exit DECLARE_IMPORT(2, sbus_intr_exit) +#define I_sbus_intr_handler_add DECLARE_IMPORT(5, sbus_intr_handler_add) +#define I_sbus_intr_handler_del DECLARE_IMPORT(6, sbus_intr_handler_del) +#define I_sbus_intr_main_interrupt DECLARE_IMPORT(7, sbus_intr_main_interrupt) + +#endif /* __SBUSINTR_H__ */ diff --git a/sps2_basement/hardware/mem/sbusintr/src/exports.tab b/sps2_basement/hardware/mem/sbusintr/src/exports.tab new file mode 100644 index 0000000..36c8ad1 --- /dev/null +++ b/sps2_basement/hardware/mem/sbusintr/src/exports.tab @@ -0,0 +1,12 @@ +DECLARE_EXPORT_TABLE(sbusintr, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(sbus_intr_exit) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(sbus_intr_init) + DECLARE_EXPORT(sbus_intr_handler_add) + DECLARE_EXPORT(sbus_intr_handler_del) + DECLARE_EXPORT(sbus_intr_main_interrupt) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/mem/sbusintr/src/imports.lst b/sps2_basement/hardware/mem/sbusintr/src/imports.lst new file mode 100644 index 0000000..4e52be5 --- /dev/null +++ b/sps2_basement/hardware/mem/sbusintr/src/imports.lst @@ -0,0 +1,23 @@ +/* + * Imports + */ +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +intrman_IMPORTS_start +I_RegisterIntrHandler +I_ReleaseIntrHandler +I_EnableIntr +I_DisableIntr +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +sifman_IMPORTS_start +I_sceSifGetMSFlag +I_sceSifSetMSFlag +I_sceSifGetSMFlag +I_sceSifSetSMFlag +I_sceSifIntrMain +sifman_IMPORTS_end diff --git a/sps2_basement/hardware/mem/sbusintr/src/irx_imports.h b/sps2_basement/hardware/mem/sbusintr/src/irx_imports.h new file mode 100644 index 0000000..09953fe --- /dev/null +++ b/sps2_basement/hardware/mem/sbusintr/src/irx_imports.h @@ -0,0 +1,23 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "loadcore.h" +#include "intrman.h" +#include "sifman.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/mem/sbusintr/src/sbusintr.c b/sps2_basement/hardware/mem/sbusintr/src/sbusintr.c new file mode 100644 index 0000000..3358f12 --- /dev/null +++ b/sps2_basement/hardware/mem/sbusintr/src/sbusintr.c @@ -0,0 +1,146 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * SBUS interrupt handlers for IOP. + */ + +#include "types.h" +#include "defs.h" +#include "irx.h" + +#include "loadcore.h" +#include "intrman.h" +#include "sifman.h" +#include "sbusintr.h" + +IRX_ID("sbusintr", 1, 1); + +static struct { + sbus_intr_handler_t handler; + void *arg; +} sbus_handler_table[32]; + +extern struct irx_export_table _exp_sbusintr; + +int _start(int argc, const char **argv) +{ + if (RegisterLibraryEntries(&_exp_sbusintr) != 0) + return 1; + + return 0; +} + +static int sbus_dispatch(void *arg) +{ + u32 msflag, irq; + + if (!(msflag = sceSifGetMSFlag())) + return 1; + + for (irq = 0; msflag != 0 && irq < 32; irq++, msflag >>= 1) { + if (!(msflag & 1)) + continue; + + /* "Acknowledge" the interrupt */ + sceSifSetMSFlag(1 << irq); + + if (sbus_handler_table[irq].handler) + sbus_handler_table[irq].handler(irq, + sbus_handler_table[irq].arg); + } + + return 1; +} + +int sbus_intr_handler_add(u32 irq, sbus_intr_handler_t handler, void *arg) +{ + int res = irq, state = 0; + + /* I hope this correct... */ + CpuSuspendIntr(&state); + + if (irq > 31) { + res = -SBUS_E_ARG; + goto out; + } + + if (sbus_handler_table[irq].handler) { + res = -SBUS_E_IRQ; + goto out; + } + + sbus_handler_table[irq].handler = handler; + sbus_handler_table[irq].arg = arg; +out: + CpuResumeIntr(state); + return res; +} + +int sbus_intr_handler_del(u32 irq) +{ + if (irq > 31) + return -SBUS_E_ARG; + + sbus_handler_table[irq].handler = NULL; + sbus_handler_table[irq].arg = NULL; + + return irq; +} + +void sbus_intr_main_interrupt(u32 irq) +{ + u32 flag = 1 << irq; + + if (irq > 31 || (sceSifGetSMFlag() & flag)) + return; + + sceSifSetSMFlag(flag); + sceSifIntrMain(); +} + +static int initialized = 0; + +/* + * - Register SBUS handler + * - Clear handler table + */ +int sbus_intr_init() +{ + int i, state, res = 0; + + if (initialized) + return res; + + CpuSuspendIntr(&state); + + for (i = 0; i < 32; ++i) { + sbus_handler_table[i].handler = NULL; + sbus_handler_table[i].arg = NULL; + } + + if (RegisterIntrHandler(IOP_IRQ_SBUS, 1, sbus_dispatch, NULL) < 0) { + res = -SBUS_E_INIT; + goto out; + } + EnableIntr(IOP_IRQ_SBUS); + initialized = 1; +out: + CpuResumeIntr(state); + return res; +} + +void sbus_intr_exit() +{ + DisableIntr(IOP_IRQ_SBUS, NULL); + ReleaseIntrHandler(IOP_IRQ_SBUS); + initialized = 0; +} diff --git a/sps2_basement/hardware/mem/siftoo/Makefile b/sps2_basement/hardware/mem/siftoo/Makefile new file mode 100644 index 0000000..2272565 --- /dev/null +++ b/sps2_basement/hardware/mem/siftoo/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_INCS += -I$(PS2SDKSRC)/iop/system/sbusintr/include + +IOP_OBJS = siftoo.o pipe.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/mem/siftoo/include/siftoo.h b/sps2_basement/hardware/mem/siftoo/include/siftoo.h new file mode 100644 index 0000000..b2c23f1 --- /dev/null +++ b/sps2_basement/hardware/mem/siftoo/include/siftoo.h @@ -0,0 +1,60 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * SIFToo driver. + */ + +#ifndef __SIFTOO_H__ +#define __SIFTOO_H__ + +#include +#include + +enum sif2_errors { + /** No error. */ + SIF2_E_OK, + + /** Initialization error. */ + SIF2_E_INIT = 0xd700, +}; + +typedef int (*sif2_pipe_handler_t)(u32, void *, u32); + +int sif2_init(void); +int sif2_exit(void); + +int sif2_mem_read(u32 addr, void *buf, u32 size); +int sif2_mem_write(u32 addr, void *buf, u32 size); + +/* Pipe API. */ +int sif2_pipe_create(u32 id, void *buf, u32 size, u32 flags, + sif2_pipe_handler_t phandler); +int sif2_pipe_open(u32 id); +int sif2_pipe_close(int pd); + +int sif2_pipe_read(int pd, void *buf, u32 size); +int sif2_pipe_write(int pd, void *buf, u32 size); + +#define siftoo_IMPORTS_start DECLARE_IMPORT_TABLE(siftoo, 1, 1) +#define siftoo_IMPORTS_end END_IMPORT_TABLE + +#define I_sif2_init DECLARE_IMPORT(4, sif2_init) +#define I_sif2_exit DECLARE_IMPORT(5, sif2_exit) +#define I_sif2_mem_read DECLARE_IMPORT(6, sif2_mem_read) +#define I_sif2_mem_write DECLARE_IMPORT(7, sif2_mem_write) +#define I_sif2_pipe_create DECLARE_IMPORT(10, sif2_pipe_create) +#define I_sif2_pipe_open DECLARE_IMPORT(11, sif2_pipe_open) +#define I_sif2_pipe_close DECLARE_IMPORT(12, sif2_pipe_close) +#define I_sif2_pipe_read DECLARE_IMPORT(13, sif2_pipe_read) +#define I_sif2_pipe_write DECLARE_IMPORT(14, sif2_pipe_write) + +#endif /* __SIFTOO_H__ */ diff --git a/sps2_basement/hardware/mem/siftoo/src/exports.tab b/sps2_basement/hardware/mem/siftoo/src/exports.tab new file mode 100644 index 0000000..7f95966 --- /dev/null +++ b/sps2_basement/hardware/mem/siftoo/src/exports.tab @@ -0,0 +1,22 @@ +/* Version 1.1 */ +DECLARE_EXPORT_TABLE(siftoo, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(shutdown) + DECLARE_EXPORT(_retonly) + + DECLARE_EXPORT(sif2_init) + DECLARE_EXPORT(sif2_exit) + DECLARE_EXPORT(sif2_mem_read) + DECLARE_EXPORT(sif2_mem_write) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + + DECLARE_EXPORT(sif2_pipe_create) + DECLARE_EXPORT(sif2_pipe_open) + DECLARE_EXPORT(sif2_pipe_close) + DECLARE_EXPORT(sif2_pipe_read) + DECLARE_EXPORT(sif2_pipe_write) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/mem/siftoo/src/imports.lst b/sps2_basement/hardware/mem/siftoo/src/imports.lst new file mode 100644 index 0000000..1f74413 --- /dev/null +++ b/sps2_basement/hardware/mem/siftoo/src/imports.lst @@ -0,0 +1,22 @@ + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +sifman_IMPORTS_start +I_sceSifDma2Init +sifman_IMPORTS_end + +sbusintr_IMPORTS_start +I_sbus_intr_init +I_sbus_intr_handler_add +sbusintr_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end diff --git a/sps2_basement/hardware/mem/siftoo/src/irx_imports.h b/sps2_basement/hardware/mem/siftoo/src/irx_imports.h new file mode 100644 index 0000000..43a9c63 --- /dev/null +++ b/sps2_basement/hardware/mem/siftoo/src/irx_imports.h @@ -0,0 +1,25 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "loadcore.h" +#include "intrman.h" +#include "sifman.h" +#include "sbusintr.h" +#include "stdio.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/mem/siftoo/src/pipe.c b/sps2_basement/hardware/mem/siftoo/src/pipe.c new file mode 100644 index 0000000..ea1c6c8 --- /dev/null +++ b/sps2_basement/hardware/mem/siftoo/src/pipe.c @@ -0,0 +1,46 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Simple pipe API for SIFToo. + */ + +#include "types.h" +#include "defs.h" + +#include "sbusintr.h" +#include "siftoo.h" + +int sif2_pipe_create(u32 id, void *buf, u32 size, u32 flags, + sif2_pipe_handler_t phandler) +{ + return 0; +} + +int sif2_pipe_open(u32 id) +{ + return 0; +} + +int sif2_pipe_close(int pd) +{ + return 0; +} + +int sif2_pipe_read(int pd, void *buf, u32 size) +{ + return 0; +} + +int sif2_pipe_write(int pd, void *buf, u32 size) +{ + return 0; +} diff --git a/sps2_basement/hardware/mem/siftoo/src/siftoo.c b/sps2_basement/hardware/mem/siftoo/src/siftoo.c new file mode 100644 index 0000000..f2b7d34 --- /dev/null +++ b/sps2_basement/hardware/mem/siftoo/src/siftoo.c @@ -0,0 +1,105 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/* + * @file + * SIFToo low-level driver. + * + * The SBUS Interface (SIF) has 3 DMA channels, with the first 2 reserved + * for SCEI's SIF RPC interface. As far as I know, the last channel is + * only used for debugging within the EE's kernel (I haven't seen it in use + * on the IOP yet, I guess they decided to leave those modules out of the + * BIOS). So on consumer units SIF DMA channel 2 (SIF2) is unused. + * + * SIF2 is a bidirectional channel, which means data can be transferred in + * either direction on the SBUS. The SIFToo driver provides an interface + * for IOP drivers to communicate via the EE using this channel. + */ + +#include "types.h" +#include "defs.h" +#include "irx.h" + +#include "loadcore.h" +#include "intrman.h" +#include "sifman.h" +#include "sbusintr.h" +#include "siftoo.h" +#include "stdio.h" + +IRX_ID("SIFToo_driver", 1, 1); + +#define SIF2_SBUS_IRQ 0 + +int sif2_control(u32 intr, void *unused); + +extern struct irx_export_table _exp_siftoo; + +int _start(int argc, char **argv) +{ + u32 state; + + if (RegisterLibraryEntries(&_exp_siftoo) != 0) + return 1; + + /* Add our SBUS interrupt handler. */ + if (sbus_intr_init() < 0) { + printf("Unable to initialize SBUS interrupt driver, exiting.\n"); + return 1; + } + + if (sbus_intr_handler_add(SIF2_SBUS_IRQ, sif2_control, NULL) < 0) { + printf("Unable to register SIFToo Control handler, exiting.\n"); + return 1; + } + + CpuSuspendIntr((int *)&state); + sceSifDma2Init(); + CpuResumeIntr(state); + + return 0; +} + +int shutdown() +{ + return 0; +} + +int sif2_init() +{ + /* Perform the EE handshake: + * - Check if the EE was already initialized, and if so send a control + * message with our recieve buffer address. + * - If it hasn't been initialized yet, set SIF SM flag 0x80000 and + * wait for an event signaling that the EE is ready. + */ + + return 0; +} + +int sif2_exit() +{ + return 0; +} + +int sif2_control(u32 intr, void *unused) +{ + return 0; +} + +int sif2_mem_read(u32 addr, void *buf, u32 size) +{ + return 0; +} + +int sif2_mem_write(u32 addr, void *buf, u32 size) +{ + return 0; +} diff --git a/sps2_basement/hardware/mem/sio2log/Makefile b/sps2_basement/hardware/mem/sio2log/Makefile new file mode 100644 index 0000000..af67176 --- /dev/null +++ b/sps2_basement/hardware/mem/sio2log/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN_ALTNAMES = + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/system/sio2man/src/ +IOP_INC_DIR = $(PS2SDKSRC)/iop/system/sio2man/include/ + +IOP_CFLAGS += -DSIO2LOG + +include $(PS2SDKSRC)/iop/system/sio2man/Makefile diff --git a/sps2_basement/hardware/mem/sio2man/Makefile b/sps2_basement/hardware/mem/sio2man/Makefile new file mode 100644 index 0000000..25db7d3 --- /dev/null +++ b/sps2_basement/hardware/mem/sio2man/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN_ALTNAMES ?= freesio2.irx + +IOP_OBJS = sio2man.o log.o imports.o exports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/mem/sio2man/README b/sps2_basement/hardware/mem/sio2man/README new file mode 100644 index 0000000..03b7d1f --- /dev/null +++ b/sps2_basement/hardware/mem/sio2man/README @@ -0,0 +1,2 @@ +Free XSIO2MAN replacement module. +Built from the sio2log source, without the logging feature. diff --git a/sps2_basement/hardware/mem/sio2man/include/log.h b/sps2_basement/hardware/mem/sio2man/include/log.h new file mode 100644 index 0000000..f4dff6a --- /dev/null +++ b/sps2_basement/hardware/mem/sio2man/include/log.h @@ -0,0 +1,42 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * SIO2 logging. + */ + +#ifndef SIO2LOG_LOG_H +#define SIO2LOG_LOG_H + +#include + +#include "sio2man.h" + +enum _log_types { + LOG_HEADER = 0x02, LOG_PAD_READY, LOG_MC_READY, LOG_MTAP_READY, + LOG_TRS, LOG_TRS_PD, LOG_TRS_RD, LOG_TRS_DATA, LOG_TRS_DMA_IN, + LOG_TRS_DMA_OUT, + LOG_TRR, LOG_TRR_STAT, LOG_TRR_DATA, + LOG_RESET +}; + +void log_write8(u8 val); +void log_write32(u32 val); +void log_flush(int now); + +void log_default(int type); +void log_portdata(u32 *pd1, u32 *pd2); +void log_regdata(u32 *rd); +void log_data(int type, u8 *data, u32 size); +void log_dma(int type, struct _sio2_dma_arg *arg); +void log_stat(u32 stat6c, u32 stat70, u32 stat74); + +#endif /* SIO2LOG_LOG_H */ diff --git a/sps2_basement/hardware/mem/sio2man/include/sio2man.h b/sps2_basement/hardware/mem/sio2man/include/sio2man.h new file mode 100644 index 0000000..2ed3b27 --- /dev/null +++ b/sps2_basement/hardware/mem/sio2man/include/sio2man.h @@ -0,0 +1,98 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * rom0:SIO2MAN module definitions + */ + +#ifndef __SIO2MAN_H__ +#define __SIO2MAN_H__ + +#include +#include + +struct _sio2_dma_arg { // size 12 + void *addr; + int size; + int count; +}; + +typedef struct { + u32 stat6c; + + u32 port_ctrl1[4]; + u32 port_ctrl2[4]; + + u32 stat70; + + u32 regdata[16]; + + u32 stat74; + + u32 in_size; + u32 out_size; + u8 *in; + u8 *out; + + struct _sio2_dma_arg in_dma; + struct _sio2_dma_arg out_dma; +} sio2_transfer_data_t; + +void sio2_ctrl_set(u32 val); +u32 sio2_ctrl_get(void); +u32 sio2_stat6c_get(void); +void sio2_portN_ctrl1_set(int N, u32 val); +u32 sio2_portN_ctrl1_get(int N); +void sio2_portN_ctrl2_set(int N, u32 val); +u32 sio2_portN_ctrl2_get(int N); +u32 sio2_stat70_get(void); +void sio2_regN_set(int N, u32 val); +u32 sio2_regN_get(int N); +u32 sio2_stat74_get(void); +void sio2_unkn78_set(u32 val); +u32 sio2_unkn78_get(void); +void sio2_unkn7c_set(u32 val); +u32 sio2_unkn7c_get(void); +void sio2_data_out(u8 val); +u8 sio2_data_in(void); +void sio2_stat_set(u32 val); +u32 sio2_stat_get(void); +void sio2_pad_transfer_init(void); +void sio2_mc_transfer_init(void); +int sio2_transfer(sio2_transfer_data_t *td); + +#define sio2man_IMPORTS_start DECLARE_IMPORT_TABLE(sio2man, 1, 1) +#define sio2man_IMPORTS_end END_IMPORT_TABLE + +#define I_sio2_ctrl_set DECLARE_IMPORT(4, sio2_ctrl_set) +#define I_sio2_ctrl_get DECLARE_IMPORT(5, sio2_ctrl_get) +#define I_sio2_stat6c_get DECLARE_IMPORT(6, sio2_stat6c_get) +#define I_sio2_portN_ctrl1_set DECLARE_IMPORT(7, sio2_portN_ctrl1_set) +#define I_sio2_portN_ctrl1_get DECLARE_IMPORT(8, sio2_portN_ctrl1_get) +#define I_sio2_portN_ctrl2_set DECLARE_IMPORT(9, sio2_portN_ctrl2_set) +#define I_sio2_portN_ctrl2_get DECLARE_IMPORT(10, sio2_portN_ctrl2_get) +#define I_sio2_stat70_get DECLARE_IMPORT(11, sio2_stat70_get) +#define I_sio2_regN_set DECLARE_IMPORT(12, sio2_regN_set) +#define I_sio2_regN_get DECLARE_IMPORT(13, sio2_regN_get) +#define I_sio2_stat74_get DECLARE_IMPORT(14, sio2_stat74_get) +#define I_sio2_unkn78_set DECLARE_IMPORT(15, sio2_unkn78_set) +#define I_sio2_unkn78_get DECLARE_IMPORT(16, sio2_unkn78_get) +#define I_sio2_unkn7c_set DECLARE_IMPORT(17, sio2_unkn7c_set) +#define I_sio2_unkn7c_get DECLARE_IMPORT(18, sio2_unkn7c_get) +#define I_sio2_data_out DECLARE_IMPORT(19, sio2_data_out) +#define I_sio2_data_in DECLARE_IMPORT(20, sio2_data_in) +#define I_sio2_stat_set DECLARE_IMPORT(21, sio2_stat_set) +#define I_sio2_stat_get DECLARE_IMPORT(22, sio2_stat_get) +#define I_sio2_pad_transfer_init DECLARE_IMPORT(23, sio2_pad_transfer_init) +#define I_sio2_mc_transfer_init DECLARE_IMPORT(24, sio2_mc_transfer_init) +#define I_sio2_transfer DECLARE_IMPORT(25, sio2_transfer) + +#endif /* __SIO2MAN_H__ */ diff --git a/sps2_basement/hardware/mem/sio2man/src/exports.tab b/sps2_basement/hardware/mem/sio2man/src/exports.tab new file mode 100644 index 0000000..233a72e --- /dev/null +++ b/sps2_basement/hardware/mem/sio2man/src/exports.tab @@ -0,0 +1,82 @@ +#ifndef SIO2MAN_V2 +DECLARE_EXPORT_TABLE(sio2man, 1, 2) +#else +DECLARE_EXPORT_TABLE(sio2man, 2, 3) +#endif + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(shutdown) + DECLARE_EXPORT(_retonly) + + /* Register manipulation 04 - 22 */ + DECLARE_EXPORT(sio2_ctrl_set) + DECLARE_EXPORT(sio2_ctrl_get) // 5 + DECLARE_EXPORT(sio2_stat6c_get) + DECLARE_EXPORT(sio2_portN_ctrl1_set) + DECLARE_EXPORT(sio2_portN_ctrl1_get) + DECLARE_EXPORT(sio2_portN_ctrl2_set) + DECLARE_EXPORT(sio2_portN_ctrl2_get) // 10 + DECLARE_EXPORT(sio2_stat70_get) + DECLARE_EXPORT(sio2_regN_set) + DECLARE_EXPORT(sio2_regN_get) + DECLARE_EXPORT(sio2_stat74_get) + DECLARE_EXPORT(sio2_unkn78_set) // 15 + DECLARE_EXPORT(sio2_unkn78_get) + DECLARE_EXPORT(sio2_unkn7c_set) + DECLARE_EXPORT(sio2_unkn7c_get) + DECLARE_EXPORT(sio2_data_out) + DECLARE_EXPORT(sio2_data_in) // 20 + DECLARE_EXPORT(sio2_stat_set) + DECLARE_EXPORT(sio2_stat_get) + + /* Transfer events 23 - 26 */ + DECLARE_EXPORT(sio2_pad_transfer_init) + DECLARE_EXPORT(sio2_mc_transfer_init) + DECLARE_EXPORT(sio2_transfer) // 25 + DECLARE_EXPORT(sio2_transfer_reset) + + /* Repeat of register routines 27 - 45 */ + DECLARE_EXPORT(sio2_ctrl_set) + DECLARE_EXPORT(sio2_ctrl_get) + DECLARE_EXPORT(sio2_stat6c_get) + DECLARE_EXPORT(sio2_portN_ctrl1_set) + DECLARE_EXPORT(sio2_portN_ctrl1_get) + DECLARE_EXPORT(sio2_portN_ctrl2_set) + DECLARE_EXPORT(sio2_portN_ctrl2_get) + DECLARE_EXPORT(sio2_stat70_get) + DECLARE_EXPORT(sio2_regN_set) + DECLARE_EXPORT(sio2_regN_get) + DECLARE_EXPORT(sio2_stat74_get) + DECLARE_EXPORT(sio2_unkn78_set) + DECLARE_EXPORT(sio2_unkn78_get) + DECLARE_EXPORT(sio2_unkn7c_set) + DECLARE_EXPORT(sio2_unkn7c_get) + DECLARE_EXPORT(sio2_data_out) + DECLARE_EXPORT(sio2_data_in) + DECLARE_EXPORT(sio2_stat_set) + DECLARE_EXPORT(sio2_stat_get) + + /* Repeat of transfers + mtap 46 - 50 */ + DECLARE_EXPORT(sio2_pad_transfer_init) + DECLARE_EXPORT(sio2_mc_transfer_init) + DECLARE_EXPORT(sio2_mtap_transfer_init) +#ifdef SIO2MAN_V2 + DECLARE_EXPORT(sio2_rm_transfer_init) + DECLARE_EXPORT(sio2_unk_transfer_init) //50 +#endif + DECLARE_EXPORT(sio2_transfer) + DECLARE_EXPORT(sio2_transfer_reset) // 50 / 52 + + /* Callbacks 51 - 58 / 53 - 60 */ + DECLARE_EXPORT(sio2_mtap_change_slot_set) + DECLARE_EXPORT(sio2_mtap_get_slot_max_set) + DECLARE_EXPORT(sio2_mtap_get_slot_max2_set) + DECLARE_EXPORT(sio2_mtap_update_slots_set) + DECLARE_EXPORT(sio2_mtap_change_slot) // 55 / 57 + DECLARE_EXPORT(sio2_mtap_get_slot_max) + DECLARE_EXPORT(sio2_mtap_get_slot_max2) + DECLARE_EXPORT(sio2_mtap_update_slots) + +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/mem/sio2man/src/imports.lst b/sps2_basement/hardware/mem/sio2man/src/imports.lst new file mode 100644 index 0000000..f745c06 --- /dev/null +++ b/sps2_basement/hardware/mem/sio2man/src/imports.lst @@ -0,0 +1,45 @@ +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +intrman_IMPORTS_start +I_RegisterIntrHandler +I_ReleaseIntrHandler +I_EnableIntr +I_DisableIntr +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +dmacman_IMPORTS_start +I_dmac_request +I_dmac_transfer +I_dmac_ch_set_dpcr +I_dmac_enable +I_dmac_disable +dmacman_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_StartThread +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_SetEventFlag +I_iSetEventFlag +I_ClearEventFlag +I_WaitEventFlag +thevent_IMPORTS_end + +#ifdef SIO2LOG +ioman_IMPORTS_start +I_open +I_write +I_close +ioman_IMPORTS_end +#endif diff --git a/sps2_basement/hardware/mem/sio2man/src/irx_imports.h b/sps2_basement/hardware/mem/sio2man/src/irx_imports.h new file mode 100644 index 0000000..aae560c --- /dev/null +++ b/sps2_basement/hardware/mem/sio2man/src/irx_imports.h @@ -0,0 +1,30 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include +#ifdef SIO2LOG +#include +#endif +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/mem/sio2man/src/log.c b/sps2_basement/hardware/mem/sio2man/src/log.c new file mode 100644 index 0000000..1c3f502 --- /dev/null +++ b/sps2_basement/hardware/mem/sio2man/src/log.c @@ -0,0 +1,170 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Logging code used by sio2log. + */ + +#ifdef SIO2LOG + +#include +#include +#include +#include + +#include "log.h" + +#define DPRINTF(format, args...) printf("%s: " format, __FUNCTION__ , ## args) + +#define FLUSH_COUNT_MAX 4 +#define DMA_MAX 1024 + +static int init = 0; +static int logging = 1; +static int writesize = 0; +static int flushcount = 0; +static u8 log[10 * 1024]; +static int logfd = -1; + +static const char *logfile = "host0:sio2.log"; + +static int log_init(void) +{ + logging = 1; + + if ((logfd = open(logfile, O_WRONLY | O_CREAT | O_TRUNC)) < 0) + logging = 0; + + init = 1; + return 1; +} + +void log_default(int type) +{ + if (!logging) return; + + log_write8(type); +} + +void log_portdata(u32 *pd1, u32 *pd2) +{ + int i; + + if (!logging) return; + + log_default(LOG_TRS_PD); + + for (i = 0; i < 4; i++) { + log_write32(pd1[i]); + log_write32(pd2[i]); + } +} + +void log_regdata(u32 *rd) +{ + int i; + + if (!logging) return; + + log_default(LOG_TRS_RD); + + for (i = 0; i < 16; i++) + log_write32(rd[i]); +} + +void log_data(int type, u8 *data, u32 size) +{ + int i; + + if (!logging) return; + + log_default(type); + + log_write32(size); + + for (i = 0; i < size; i++) + log_write8(data[i]); +} + +void log_dma(int type, struct _sio2_dma_arg *arg) +{ + u8 *p; + int i, effective; + + if (!logging) return; + + log_default(type); + + log_write32((u32)arg->addr); + log_write32(arg->size); + log_write32(arg->count); + + effective = arg->size * 4 * arg->count; + if (effective > DMA_MAX) + effective = DMA_MAX; + + for (i = 0, p = (u8 *)arg->addr; i < effective; i++) + log_write8(p[i]); +} + +void log_stat(u32 stat6c, u32 stat70, u32 stat74) +{ + if (!logging) return; + + log_default(LOG_TRR_STAT); + + log_write32(stat6c); log_write32(stat70); log_write32(stat74); +} + +void log_write8(u8 val) +{ + if (!init && !log_init()) + return; + + log[writesize++] = val; +} + +void log_write32(u32 val) +{ + if (!init && !log_init()) + return; + + log[writesize] = val & 0xff; + log[writesize + 1] = (val >> 8) & 0xff; + log[writesize + 2] = (val >> 16) & 0xff; + log[writesize + 3] = (val >> 24) & 0xff; + writesize += 4; +} + +void log_flush(int now) +{ + if (!init && !log_init()) + return; + + if (!logging || logfd < 0) return; + + flushcount++; + + if (now || flushcount >= FLUSH_COUNT_MAX) { + write(logfd, log, writesize); + close(logfd); + logfd = open(logfile, O_WRONLY | O_APPEND); + if (logfd < 0) + logging = 0; + + writesize = 0; + } + + if (flushcount >= FLUSH_COUNT_MAX) + flushcount = 0; +} + +#endif diff --git a/sps2_basement/hardware/mem/sio2man/src/sio2man.c b/sps2_basement/hardware/mem/sio2man/src/sio2man.c new file mode 100644 index 0000000..b42658e --- /dev/null +++ b/sps2_basement/hardware/mem/sio2man/src/sio2man.c @@ -0,0 +1,464 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * SIO2 logging utility. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "xsio2man.h" + +#ifdef SIO2LOG + #include "log.h" +#endif + +// TODO: last sdk 3.1.0 and sdk 3.0.3 has SIO2MAN module version 0x03,0x11 +// Check what was changed, and maybe port changes. +// Note: currently is based on the last XPADMAN from BOOTROM: +// 0x02,0x01 (where is 0x02,0x04?) +#ifdef SIO2LOG + IRX_ID("sio2man_logger", 2, 1); +#else +#ifndef SIO2MAN_V2 + IRX_ID("sio2man", 2, 1); +#else + IRX_ID("sio2man", 2, 4); +#endif +#endif + +extern struct irx_export_table _exp_sio2man; + +#define SIO2_REG_BASE 0xbf808200 +#define SIO2_REG_PORT0_CTRL1 0xbf808240 +#define SIO2_REG_PORT0_CTRL2 0xbf808244 +#define SIO2_REG_DATA_OUT 0xbf808260 +#define SIO2_REG_DATA_IN 0xbf808264 +#define SIO2_REG_CTRL 0xbf808268 +#define SIO2_REG_STAT6C 0xbf80826c +#define SIO2_REG_STAT70 0xbf808270 +#define SIO2_REG_STAT74 0xbf808274 +#define SIO2_REG_UNKN78 0xbf808278 +#define SIO2_REG_UNKN7C 0xbf80827c +#define SIO2_REG_STAT 0xbf808280 + +/* Event flags */ +#define EF_PAD_TRANSFER_INIT 0x00000001 +#define EF_PAD_TRANSFER_READY 0x00000002 +#define EF_MC_TRANSFER_INIT 0x00000004 +#define EF_MC_TRANSFER_READY 0x00000008 +#define EF_MTAP_TRANSFER_INIT 0x00000010 +#define EF_MTAP_TRANSFER_READY 0x00000020 +#ifndef SIO2MAN_V2 + #define EF_TRANSFER_START 0x00000040 + #define EF_TRANSFER_FINISH 0x00000080 + #define EF_TRANSFER_RESET 0x00000100 + #define EF_SIO2_INTR_COMPLETE 0x00000200 +#else + #define EF_RM_TRANSFER_INIT 0x00000040 + #define EF_RM_TRANSFER_READY 0x00000080 + #define EF_UNK_TRANSFER_INIT 0x00000100 + #define EF_UNK_TRANSFER_READY 0x00000200 + #define EF_TRANSFER_START 0x00000400 + #define EF_TRANSFER_FINISH 0x00000800 + #define EF_TRANSFER_RESET 0x00001000 + #define EF_SIO2_INTR_COMPLETE 0x00002000 +#endif + +#define EPRINTF(format, args...) printf("%s: " format, _irx_id.n , ## args) + +int init = 0; +int event_flag = -1; +int thid = -1; +sio2_transfer_data_t *transfer_data = NULL; +int (*mtap_change_slot_cb)(s32 *) = NULL; +int (*mtap_get_slot_max_cb)(int) = NULL; +int (*mtap_get_slot_max2_cb)(int) = NULL; +void (*mtap_update_slots_cb)(void) = NULL; + +int sio2_intr_handler(void *arg) +{ + int ef = *(int *)arg; + + sio2_stat_set(sio2_stat_get()); + + iSetEventFlag(ef, EF_SIO2_INTR_COMPLETE); + + return 1; +} + +void send_td(sio2_transfer_data_t *td) +{ + int i; + +#ifdef SIO2LOG + log_default(LOG_TRS); +#endif + + for (i = 0; i < 4; i++) { + sio2_portN_ctrl1_set(i, td->port_ctrl1[i]); + sio2_portN_ctrl2_set(i, td->port_ctrl2[i]); + } + +#ifdef SIO2LOG + log_portdata(td->port_ctrl1, td->port_ctrl2); +#endif + + for (i = 0; i < 16; i++) + sio2_regN_set(i, td->regdata[i]); + +#ifdef SIO2LOG + log_regdata(td->regdata); +#endif + + if (td->in_size) { + for (i = 0; i < td->in_size; i++) + sio2_data_out(td->in[i]); +#ifdef SIO2LOG + log_data(LOG_TRS_DATA, td->in, td->in_size); +#endif + } + + if (td->in_dma.addr) { + dmac_request(IOP_DMAC_SIO2in, td->in_dma.addr, td->in_dma.size, + td->in_dma.count, DMAC_FROM_MEM); + dmac_transfer(IOP_DMAC_SIO2in); + +#ifdef SIO2LOG + log_dma(LOG_TRS_DMA_IN, &td->in_dma); +#endif + } + + if (td->out_dma.addr) { + dmac_request(IOP_DMAC_SIO2out, td->out_dma.addr, td->out_dma.size, + td->out_dma.count, DMAC_TO_MEM); + dmac_transfer(IOP_DMAC_SIO2out); + +#ifdef SIO2LOG + log_dma(LOG_TRS_DMA_OUT, &td->out_dma); +#endif + } +} + +void recv_td(sio2_transfer_data_t *td) +{ + int i; +#ifdef SIO2LOG + log_default(LOG_TRR); +#endif + td->stat6c = sio2_stat6c_get(); + td->stat70 = sio2_stat70_get(); + td->stat74 = sio2_stat74_get(); +#ifdef SIO2LOG + log_stat(td->stat6c, td->stat70, td->stat74); +#endif + if (td->out_size) { + for (i = 0; i < td->out_size; i++) + td->out[i] = sio2_data_in(); +#ifdef SIO2LOG + log_data(LOG_TRR_DATA, td->out, td->out_size); +#endif + } +} + +void main_thread(void *unused) +{ + u32 resbits[4]; + + while (1) { + #ifdef SIO2LOG + log_flush(0); + #endif + WaitEventFlag(event_flag, EF_PAD_TRANSFER_INIT | + EF_MC_TRANSFER_INIT | EF_MTAP_TRANSFER_INIT +#ifdef SIO2MAN_V2 + | EF_RM_TRANSFER_INIT | EF_UNK_TRANSFER_INIT +#endif + , 1, resbits); + + if (resbits[0] & EF_PAD_TRANSFER_INIT) { + ClearEventFlag(event_flag, ~EF_PAD_TRANSFER_INIT); + SetEventFlag(event_flag, EF_PAD_TRANSFER_READY); +#ifdef SIO2LOG + log_default(LOG_PAD_READY); +#endif + } else if (resbits[0] & EF_MC_TRANSFER_INIT) { + ClearEventFlag(event_flag, ~EF_MC_TRANSFER_INIT); + SetEventFlag(event_flag, EF_MC_TRANSFER_READY); +#ifdef SIO2LOG + log_default(LOG_MC_READY); +#endif + } else if (resbits[0] & EF_MTAP_TRANSFER_INIT) { + ClearEventFlag(event_flag, ~EF_MTAP_TRANSFER_INIT); + SetEventFlag(event_flag, EF_MTAP_TRANSFER_READY); +#ifdef SIO2LOG + log_default(LOG_MTAP_READY); +#endif +#ifdef SIO2MAN_V2 + } else if (resbits[0] & EF_RM_TRANSFER_INIT) { + ClearEventFlag(event_flag, ~EF_RM_TRANSFER_INIT); + SetEventFlag(event_flag, EF_RM_TRANSFER_READY); +#ifdef SIO2LOG + log_default(LOG_RM_READY); +#endif + } else if (resbits[0] & EF_UNK_TRANSFER_INIT) { + ClearEventFlag(event_flag, ~EF_UNK_TRANSFER_INIT); + SetEventFlag(event_flag, EF_UNK_TRANSFER_READY); +#ifdef SIO2LOG + log_default(LOG_UNK_READY); +#endif +#endif + } else { + EPRINTF("Unknown event %08lx. Exiting.\n", resbits[0]); + return; + } + +transfer_loop: + WaitEventFlag(event_flag, EF_TRANSFER_START | EF_TRANSFER_RESET, 1, resbits); + + if (resbits[0] & EF_TRANSFER_RESET) { + ClearEventFlag(event_flag, ~EF_TRANSFER_RESET); +#ifdef SIO2LOG + log_default(LOG_RESET); +#endif + continue; + } + + ClearEventFlag(event_flag, ~EF_TRANSFER_START); + + sio2_ctrl_set(sio2_ctrl_get() | 0xc); + send_td(transfer_data); + sio2_ctrl_set(sio2_ctrl_get() | 1); + + WaitEventFlag(event_flag, EF_SIO2_INTR_COMPLETE, 0, NULL); + ClearEventFlag(event_flag, ~EF_SIO2_INTR_COMPLETE); + + recv_td(transfer_data); + SetEventFlag(event_flag, EF_TRANSFER_FINISH); + + /* Bah... this is needed to get the initial dump from XMCMAN, + but it will kill the IOP when XPADMAN is spamming... + + TODO + I guess the correct solution is to do all logging in a + dedicated thread. */ +// log_flush(1); + + goto transfer_loop; + } +} + +int create_main_thread(void) +{ + iop_thread_t thread; + + thread.attr = 0x2000000; + thread.option = 0; + thread.thread = main_thread; + thread.stacksize = 0x8000; + thread.priority = 0x18; + return CreateThread(&thread); +} + +int create_event_flag(void) +{ + iop_event_t event; + + event.attr = 2; + event.option = 0; + event.bits = 0; + return CreateEventFlag(&event); +} + +void shutdown(void) +{ + int state; +#ifdef SIO2LOG + log_flush(1); +#endif + CpuSuspendIntr(&state); + DisableIntr(IOP_IRQ_SIO2, 0); + ReleaseIntrHandler(IOP_IRQ_SIO2); + CpuResumeIntr(state); + + dmac_disable(IOP_DMAC_SIO2in); + dmac_disable(IOP_DMAC_SIO2out); +} + +int _start(int argc, const char **argv) +{ + int state; + + shutdown(); + + if (RegisterLibraryEntries(&_exp_sio2man) != 0) + return 1; + + if (init) + return 1; + + init = 1; + + sio2_ctrl_set(0x3bc); + + mtap_change_slot_cb = NULL; mtap_get_slot_max_cb = NULL; mtap_get_slot_max2_cb = NULL; mtap_update_slots_cb = NULL; + event_flag = create_event_flag(); + thid = create_main_thread(); + + CpuSuspendIntr(&state); + RegisterIntrHandler(IOP_IRQ_SIO2, 1, sio2_intr_handler, &event_flag); + EnableIntr(IOP_IRQ_SIO2); + CpuResumeIntr(state); + + dmac_ch_set_dpcr(IOP_DMAC_SIO2in, 3); + dmac_ch_set_dpcr(IOP_DMAC_SIO2out, 3); + dmac_enable(IOP_DMAC_SIO2in); + dmac_enable(IOP_DMAC_SIO2out); + + StartThread(thid, NULL); +#ifdef SIO2LOG + EPRINTF("Logging started.\n"); +#endif + return 0; +} + +void sio2_pad_transfer_init(void) +{ + SetEventFlag(event_flag, EF_PAD_TRANSFER_INIT); + + WaitEventFlag(event_flag, EF_PAD_TRANSFER_READY, 0, NULL); + ClearEventFlag(event_flag, ~EF_PAD_TRANSFER_READY); +} + +void sio2_mc_transfer_init(void) +{ + SetEventFlag(event_flag, EF_MC_TRANSFER_INIT); + + WaitEventFlag(event_flag, EF_MC_TRANSFER_READY, 0, NULL); + ClearEventFlag(event_flag, ~EF_MC_TRANSFER_READY); +} + +void sio2_mtap_transfer_init(void) +{ + SetEventFlag(event_flag, EF_MTAP_TRANSFER_INIT); + + WaitEventFlag(event_flag, EF_MTAP_TRANSFER_READY, 0, NULL); + ClearEventFlag(event_flag, ~EF_MTAP_TRANSFER_READY); +} + +int sio2_transfer(sio2_transfer_data_t *td) +{ + transfer_data = td; + SetEventFlag(event_flag, EF_TRANSFER_START); + + WaitEventFlag(event_flag, EF_TRANSFER_FINISH, 0, NULL); + ClearEventFlag(event_flag, ~EF_TRANSFER_FINISH); + return 1; +} + +#ifdef SIO2MAN_V2 +void sio2_rm_transfer_init(void) +{ + SetEventFlag(event_flag, EF_RM_TRANSFER_INIT); + + WaitEventFlag(event_flag, EF_RM_TRANSFER_READY, 0, NULL); + ClearEventFlag(event_flag, ~EF_RM_TRANSFER_READY); +} + +void sio2_unk_transfer_init(void) +{ + SetEventFlag(event_flag, EF_UNK_TRANSFER_INIT); + + WaitEventFlag(event_flag, EF_UNK_TRANSFER_READY, 0, NULL); + ClearEventFlag(event_flag, ~EF_UNK_TRANSFER_READY); +} +#endif + +void sio2_transfer_reset(void) +{ + SetEventFlag(event_flag, EF_TRANSFER_RESET); +} + +int sio2_mtap_change_slot(s32 *status) +{ + int i, ret = 1; + + if (mtap_change_slot_cb) + return mtap_change_slot_cb(status); + + for (i = 0; i < 4; i++, status++) { + if ((*status + 1) < 2) + status[4] = 1; + else { + status[4] = 0; + ret = 0; + } + } + + return ret; +} + +int sio2_mtap_get_slot_max(int port) +{ + if (mtap_get_slot_max_cb) + return mtap_get_slot_max_cb(port); + + return 1; +} + +int sio2_mtap_get_slot_max2(int port) +{ + if (mtap_get_slot_max2_cb) + return mtap_get_slot_max2_cb(port); + + return 1; +} + +void sio2_mtap_update_slots(void) +{ + if (mtap_update_slots_cb) + mtap_update_slots_cb(); +} + +void sio2_mtap_change_slot_set(sio2_mtap_change_slot_cb_t cb) { mtap_change_slot_cb = cb; } +void sio2_mtap_get_slot_max_set(sio2_mtap_get_slot_max_cb_t cb) { mtap_get_slot_max_cb = cb; } +void sio2_mtap_get_slot_max2_set(sio2_mtap_get_slot_max2_cb_t cb) { mtap_get_slot_max2_cb = cb; } +void sio2_mtap_update_slots_set(sio2_mtap_update_slots_t cb) { mtap_update_slots_cb = cb; } + +void sio2_ctrl_set(u32 val) { _sw(val, SIO2_REG_CTRL); } +u32 sio2_ctrl_get() { return _lw(SIO2_REG_CTRL); } +u32 sio2_stat6c_get() { return _lw(SIO2_REG_STAT6C); } +void sio2_portN_ctrl1_set(int N, u32 val) { _sw(val, SIO2_REG_PORT0_CTRL1 + (N * 8)); } +u32 sio2_portN_ctrl1_get(int N) { return _lw(SIO2_REG_PORT0_CTRL1 + (N * 8)); } +void sio2_portN_ctrl2_set(int N, u32 val) { _sw(val, SIO2_REG_PORT0_CTRL2 + (N * 8)); } +u32 sio2_portN_ctrl2_get(int N) { return _lw(SIO2_REG_PORT0_CTRL2 + (N * 8)); } +u32 sio2_stat70_get() { return _lw(SIO2_REG_STAT70); } +void sio2_regN_set(int N, u32 val) { _sw(val, SIO2_REG_BASE + (N * 4)); } +u32 sio2_regN_get(int N) { return _lw(SIO2_REG_BASE + (N * 4)); } +u32 sio2_stat74_get() { return _lw(SIO2_REG_STAT74); } +void sio2_unkn78_set(u32 val) { _sw(val, SIO2_REG_UNKN78); } +u32 sio2_unkn78_get() { return _lw(SIO2_REG_UNKN78); } +void sio2_unkn7c_set(u32 val) { _sw(val, SIO2_REG_UNKN7C); } +u32 sio2_unkn7c_get() { return _lw(SIO2_REG_UNKN7C); } +void sio2_data_out(u8 val) { _sb(val, SIO2_REG_DATA_OUT); } +u8 sio2_data_in() { return _lb(SIO2_REG_DATA_IN); } +void sio2_stat_set(u32 val) { _sw(val, SIO2_REG_STAT); } +u32 sio2_stat_get() { return _lw(SIO2_REG_STAT); } diff --git a/sps2_basement/hardware/r5900/Makefile b/sps2_basement/hardware/r5900/Makefile new file mode 100644 index 0000000..b1b3dbe --- /dev/null +++ b/sps2_basement/hardware/r5900/Makefile @@ -0,0 +1,9 @@ +# +# (C) Copyright 2014 Juergen Urban +# +# SPDX-License-Identifier: GPL-2.0+ +# + +extra-y = start.o +obj-y = cache.o +obj-y += cpu.o interrupts.o time.o diff --git a/sps2_basement/hardware/r5900/cache.S b/sps2_basement/hardware/r5900/cache.S new file mode 100644 index 0000000..16f9a56 --- /dev/null +++ b/sps2_basement/hardware/r5900/cache.S @@ -0,0 +1,69 @@ +/* + * Cache-handling routined for MIPS r5900 + * + * Copyright (c) 2003 Wolfgang Denk + * Copyright (c) 2014 Juergen Urban + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include + +#ifndef CONFIG_SYS_MIPS_CACHE_MODE +#define CONFIG_SYS_MIPS_CACHE_MODE CONF_CM_CACHABLE_NONCOHERENT +#endif + +/* + * dcache_status - get cache status + * + * RETURNS: 0 - cache disabled; 1 - cache enabled + * + */ +LEAF(dcache_status) + sync + mfc0 t0, CP0_CONFIG + li t1, CONF_CM_UNCACHED + andi t0, t0, CONF_CM_CMASK + move v0, zero + beq t0, t1, 2f + li v0, 1 +2: jr ra + END(dcache_status) + +/* + * dcache_disable - disable cache + * + * RETURNS: N/A + * + */ +LEAF(dcache_disable) + sync + mfc0 t0, CP0_CONFIG + li t1, -8 + and t0, t0, t1 + ori t0, t0, CONF_CM_UNCACHED + mtc0 t0, CP0_CONFIG + sync + jr ra + END(dcache_disable) + +/* + * dcache_enable - enable cache + * + * RETURNS: N/A + * + */ +LEAF(dcache_enable) + sync + mfc0 t0, CP0_CONFIG + ori t0, CONF_CM_CMASK + xori t0, CONF_CM_CMASK + ori t0, CONFIG_SYS_MIPS_CACHE_MODE + mtc0 t0, CP0_CONFIG + sync + jr ra + END(dcache_enable) diff --git a/sps2_basement/hardware/r5900/config.mk b/sps2_basement/hardware/r5900/config.mk new file mode 100644 index 0000000..3f757c7 --- /dev/null +++ b/sps2_basement/hardware/r5900/config.mk @@ -0,0 +1,22 @@ +# +# (C) Copyright 2014 Juergen Urban +# +# SPDX-License-Identifier: GPL-2.0+ +# + +# +# Default optimization level for MIPS r5900 +# +MIPSFLAGS := -march=r5900 + +PLATFORM_CPPFLAGS += $(MIPSFLAGS) +PLATFORM_CPPFLAGS += -mabi=32 -DCONFIG_32BIT +ifdef CONFIG_SYS_BIG_ENDIAN +PLATFORM_LDFLAGS += -m elf32btsmip +else +PLATFORM_LDFLAGS += -m elf32ltsmip +endif + +CONFIG_STANDALONE_LOAD_ADDR ?= 0x80200000 -T mips.lds + +USE_PRIVATE_LIBGCC = yes diff --git a/sps2_basement/hardware/r5900/cpu.c b/sps2_basement/hardware/r5900/cpu.c new file mode 100644 index 0000000..13911c7 --- /dev/null +++ b/sps2_basement/hardware/r5900/cpu.c @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2003 Wolfgang Denk + * Copyright (c) 2014 Juergen Urban + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include + +#define dcache_op(op,addr) \ + __asm__ __volatile__( \ + " .set push \n" \ + " .set noreorder \n" \ + " .set mips3\n\t \n" \ + " sync.l \n" \ + " cache %0, %1 \n" \ + " sync.l \n" \ + " .set pop \n" \ + : \ + : "i" (op), "R" (*(unsigned char *)(addr))) + +#define icache_op(op,addr) \ + __asm__ __volatile__( \ + " .set push \n" \ + " .set noreorder \n" \ + " .set mips3\n\t \n" \ + " sync.p \n" \ + " cache %0, %1 \n" \ + " sync.p \n" \ + " .set pop \n" \ + : \ + : "i" (op), "R" (*(unsigned char *)(addr))) + +void __attribute__((weak)) _machine_restart(void) +{ +} + +int do_reset(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) +{ + _machine_restart(); + + fprintf(stderr, "*** reset failed ***\n"); + return 0; +} + +#ifdef CONFIG_SYS_CACHELINE_SIZE +static inline unsigned long icache_line_size(void) +{ + return CONFIG_SYS_CACHELINE_SIZE; +} + +static inline unsigned long dcache_line_size(void) +{ + return CONFIG_SYS_CACHELINE_SIZE; +} +#endif /* CONFIG_SYS_CACHELINE_SIZE */ + +void flush_cache(ulong start_addr, ulong size) +{ + unsigned long ilsize = icache_line_size(); + unsigned long dlsize = dcache_line_size(); + unsigned long addr, aend; + + /* aend will be miscalculated when size is zero, so we return here */ + if (size == 0) + return; + + addr = start_addr & ~(dlsize - 1); + aend = (start_addr + size - 1) & ~(dlsize - 1); + + if (ilsize == dlsize) { + /* flush I-cache & D-cache simultaneously */ + while (1) { + dcache_op(R5900_HIT_WRITEBACK_INV_D, addr); + icache_op(R5900_HIT_INVALIDATE_I, addr); + if (addr == aend) + break; + addr += dlsize; + } + return; + } + + /* flush D-cache */ + while (1) { + dcache_op(R5900_HIT_WRITEBACK_INV_D, addr); + if (addr == aend) + break; + addr += dlsize; + } + + /* flush I-cache */ + addr = start_addr & ~(ilsize - 1); + aend = (start_addr + size - 1) & ~(ilsize - 1); + while (1) { + icache_op(R5900_HIT_INVALIDATE_I, addr); + if (addr == aend) + break; + addr += ilsize; + } +} + +void flush_dcache_range(ulong start_addr, ulong stop) +{ + unsigned long lsize = dcache_line_size(); + unsigned long addr = start_addr & ~(lsize - 1); + unsigned long aend = (stop - 1) & ~(lsize - 1); + + while (1) { + dcache_op(R5900_HIT_WRITEBACK_INV_D, addr); + if (addr == aend) + break; + addr += lsize; + } +} + +void invalidate_dcache_range(ulong start_addr, ulong stop) +{ + unsigned long lsize = dcache_line_size(); + unsigned long addr = start_addr & ~(lsize - 1); + unsigned long aend = (stop - 1) & ~(lsize - 1); + + while (1) { + dcache_op(R5900_HIT_INVALIDATE_D, addr); + if (addr == aend) + break; + addr += lsize; + } +} + +int cpu_eth_init(bd_t *bis) +{ + return 0; +} diff --git a/sps2_basement/hardware/r5900/interrupts.c b/sps2_basement/hardware/r5900/interrupts.c new file mode 100644 index 0000000..bea9745 --- /dev/null +++ b/sps2_basement/hardware/r5900/interrupts.c @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2014 Juergen Urban + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +void enable_interrupts(void) +{ +} + +int disable_interrupts(void) +{ + return 0; +} diff --git a/sps2_basement/hardware/r5900/start.S b/sps2_basement/hardware/r5900/start.S new file mode 100644 index 0000000..a7c6a57 --- /dev/null +++ b/sps2_basement/hardware/r5900/start.S @@ -0,0 +1,223 @@ +/* + * Startup Code for MIPS r5900 + * + * Copyright (c) 2003 Wolfgang Denk + * Copyright (c) 2014 Juergen Urban + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include + +#ifndef CONFIG_SYS_MIPS_CACHE_MODE +#define CONFIG_SYS_MIPS_CACHE_MODE CONF_CM_CACHABLE_NONCOHERENT +#endif + + /* + * For the moment disable interrupts, mark the kernel mode and + * set ST0_KX so that the CPU does not spit fire when using + * 64-bit addresses. + */ + .macro setup_c0_status set clr + .set push + sync.p + mfc0 t0, CP0_STATUS + or t0, ST0_CU0 | \set | 0x1f | \clr + xor t0, 0x1f | \clr + mtc0 t0, CP0_STATUS + sync.p + .set noreorder + sll zero, 3 # ehb + .set pop + .endm + + .set noreorder + + .globl _start + .text +_start: + /* U-boot entry point */ + + /* Clear watch registers */ + mtc0 zero, CP0_WATCHLO + sync.p + mtc0 zero, CP0_WATCHHI + sync.p + + /* WP(Watch Pending), SW0/1 should be cleared */ + mtc0 zero, CP0_CAUSE + sync.p + + setup_c0_status 0 0 + + /* Init Timer */ + mtc0 zero, CP0_COUNT + sync.p + mtc0 zero, CP0_COMPARE + sync.p + +#ifndef CONFIG_SKIP_LOWLEVEL_INIT + /* CONFIG0 register */ + li t0, CONF_CM_UNCACHED + mtc0 t0, CP0_CONFIG + sync.p +#endif + + /* Initialize $gp */ + bal 1f + nop + .word _gp +1: + lw gp, 0(ra) + +#ifndef CONFIG_SKIP_LOWLEVEL_INIT + /* Initialize any external memory */ + la t9, lowlevel_init + jalr t9 + nop + + /* Initialize caches... */ + la t9, mips_cache_reset + jalr t9 + nop + + /* ... and enable them */ + li t0, CONFIG_SYS_MIPS_CACHE_MODE + mtc0 t0, CP0_CONFIG + sync.p +#endif + + /* Set up temporary stack */ + li sp, CONFIG_SYS_SDRAM_BASE + CONFIG_SYS_INIT_SP_OFFSET + + la t9, board_init_f + jr t9 + nop + +/* + * void relocate_code (addr_sp, gd, addr_moni) + * + * This "function" does not return, instead it continues in RAM + * after relocating the monitor code. + * + * a0 = addr_sp + * a1 = gd + * a2 = destination address + */ + .globl relocate_code + .ent relocate_code +relocate_code: + move sp, a0 # set new stack pointer + + move s0, a1 # save gd in s0 + move s2, a2 # save destination address in s2 + + li t0, CONFIG_SYS_MONITOR_BASE + sub s1, s2, t0 # s1 <-- relocation offset + + la t3, in_ram + lw t2, -12(t3) # t2 <-- __image_copy_end + move t1, a2 + + add gp, s1 # adjust gp + + /* + * t0 = source address + * t1 = target address + * t2 = source end address + */ +1: + lw t3, 0(t0) + sw t3, 0(t1) + addu t0, 4 + blt t0, t2, 1b + addu t1, 4 + + /* If caches were enabled, we would have to flush them here. */ + sub a1, t1, s2 # a1 <-- size + la t9, flush_cache + jalr t9 + move a0, s2 # a0 <-- destination address + + /* Jump to where we've relocated ourselves */ + addi t0, s2, in_ram - _start + jr t0 + nop + + .word __rel_dyn_end + .word __rel_dyn_start + .word __image_copy_end + .word _GLOBAL_OFFSET_TABLE_ + .word num_got_entries + +in_ram: + /* + * Now we want to update GOT. + * + * GOT[0] is reserved. GOT[1] is also reserved for the dynamic object + * generated by GNU ld. Skip these reserved entries from relocation. + */ + lw t3, -4(t0) # t3 <-- num_got_entries + lw t8, -8(t0) # t8 <-- _GLOBAL_OFFSET_TABLE_ + add t8, s1 # t8 now holds relocated _G_O_T_ + addi t8, t8, 8 # skipping first two entries + li t2, 2 +1: + lw t1, 0(t8) + beqz t1, 2f + add t1, s1 + sw t1, 0(t8) +2: + addi t2, 1 + blt t2, t3, 1b + addi t8, 4 + + /* Update dynamic relocations */ + lw t1, -16(t0) # t1 <-- __rel_dyn_start + lw t2, -20(t0) # t2 <-- __rel_dyn_end + + b 2f # skip first reserved entry + addi t1, 8 + +1: + lw t8, -4(t1) # t8 <-- relocation info + + li t3, 3 + bne t8, t3, 2f # skip non R_MIPS_REL32 entries + nop + + lw t3, -8(t1) # t3 <-- location to fix up in FLASH + + lw t8, 0(t3) # t8 <-- original pointer + add t8, s1 # t8 <-- adjusted pointer + + add t3, s1 # t3 <-- location to fix up in RAM + sw t8, 0(t3) + +2: + blt t1, t2, 1b + addi t1, 8 # each rel.dyn entry is 8 bytes + + /* + * Clear BSS + * + * GOT is now relocated. Thus __bss_start and __bss_end can be + * accessed directly via $gp. + */ + la t1, __bss_start # t1 <-- __bss_start + la t2, __bss_end # t2 <-- __bss_end + +1: + sw zero, 0(t1) + blt t1, t2, 1b + addi t1, 4 + + move a0, s0 # a0 <-- gd + la t9, board_init_r + jr t9 + move a1, s2 + + .end relocate_code diff --git a/sps2_basement/hardware/r5900/time.c b/sps2_basement/hardware/r5900/time.c new file mode 100644 index 0000000..0773c06 --- /dev/null +++ b/sps2_basement/hardware/r5900/time.c @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2003 Wolfgang Denk + * Copyright (c) 2014 Juergen Urban + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include + +static unsigned long timestamp; + +/* how many counter cycles in a jiffy */ +#define CYCLES_PER_JIFFY \ + (CONFIG_SYS_MIPS_TIMER_FREQ + CONFIG_SYS_HZ / 2) / CONFIG_SYS_HZ + +/* + * timer without interrupts + */ + +int timer_init(void) +{ + /* Set up the timer for the first expiration. */ + write_c0_compare(read_c0_count() + CYCLES_PER_JIFFY); + + return 0; +} + +ulong get_timer(ulong base) +{ + unsigned int count; + unsigned int expirelo = read_c0_compare(); + + /* Check to see if we have missed any timestamps. */ + count = read_c0_count(); + while ((count - expirelo) < 0x7fffffff) { + expirelo += CYCLES_PER_JIFFY; + timestamp++; + } + write_c0_compare(expirelo); + + return timestamp - base; +} + +void __udelay(unsigned long usec) +{ + unsigned int tmo; + + tmo = read_c0_count() + (usec * (CONFIG_SYS_MIPS_TIMER_FREQ / 1000000)); + while ((tmo - read_c0_count()) < 0x7fffffff) + /*NOP*/; +} + +/* + * This function is derived from PowerPC code (read timebase as long long). + * On MIPS it just returns the timer value. + */ +unsigned long long get_ticks(void) +{ + return get_timer(0); +} + +/* + * This function is derived from PowerPC code (timebase clock frequency). + * On MIPS it returns the number of timer ticks per second. + */ +ulong get_tbclk(void) +{ + return CONFIG_SYS_HZ; +} diff --git a/sps2_basement/hardware/sbios/bios.S b/sps2_basement/hardware/sbios/bios.S new file mode 100644 index 0000000..7c338fc --- /dev/null +++ b/sps2_basement/hardware/sbios/bios.S @@ -0,0 +1,1563 @@ +#include + + .text + .p2align 3 + +#define SYSCALL(name) \ + SYSCALL_SPECIAL(name, name) + +#ifdef USE_KMODE +#define SYSCALL_SPECIAL(symbol, name) \ + .set push; \ + .set noreorder; \ + .text; \ + .align 4; \ + .globl symbol; \ + .type symbol,@function; \ + .ent symbol,0; \ +symbol: j __syscall; \ + li $3, __NR_##name;\ + nop; \ + .end symbol; \ + .size symbol,.-symbol; \ + .set pop; +#else +#define SYSCALL_SPECIAL(symbol, name) \ + .set push; \ + .set noreorder; \ + .text; \ + .align 4; \ + .globl symbol; \ + .type symbol,@function; \ + .ent symbol,0; \ +symbol: li $3, __NR_##name;\ + syscall; \ + jr $31; \ + nop; \ + .end symbol; \ + .size symbol,.-symbol; \ + .set pop; +#endif + +#ifdef F___syscall +.set push +.set noreorder +.text +.align 4 +.globl __syscall +.type __syscall,@function +.ent __syscall,0 +__syscall: + mfc0 $2, $12 + andi $2, $2, 0x18 + beqz $2, _kMode + slt $2, $3, $0 + syscall + jr $31 + nop +_kMode: + subu $26, $0, $3 + movn $3, $26, $2 + sll $3, $3, 2 + lui $26, 0x8000 + lhu $2, 0x02F0($26) + sll $2, $2, 16 + lh $26, 0x02F8($26) + add $2, $26 + addu $3, $2 + lw $26, 0x00($3) + jr $26 + nop +.end __syscall +.size __syscall,.-__syscall +.set pop +#endif + +#ifdef F_ResetEE +SYSCALL(ResetEE) +#endif + +#ifdef F_SetGsCrt +SYSCALL(SetGsCrt) +#endif + +#ifdef KERNEL_NO_PATCHES + +#ifdef F_Exit +SYSCALL_SPECIAL(Exit, _Exit) +#endif + +#ifdef F_LoadExecPS2 +SYSCALL_SPECIAL(LoadExecPS2, _LoadExecPS2) +#endif + +#ifdef F_ExecPS2 +SYSCALL_SPECIAL(ExecPS2, _ExecPS2) +#endif + +#else /* KERNEL_NO_PATCHES */ + +#ifdef F__Exit +SYSCALL(_Exit) +#endif + +#ifdef F__LoadExecPS2 +SYSCALL(_LoadExecPS2) +#endif + +#ifdef F__ExecPS2 +SYSCALL(_ExecPS2) +#endif + +#endif /* KERNEL_NO_PATCHES */ + +#ifdef F_RFU009 +SYSCALL(RFU009) +#endif + +#ifdef F_AddSbusIntcHandler +SYSCALL(AddSbusIntcHandler) +#endif + +#ifdef F_RemoveSbusIntcHandler +SYSCALL(RemoveSbusIntcHandler) +#endif + +#ifdef F_Interrupt2Iop +SYSCALL(Interrupt2Iop) +#endif + +#ifdef F_SetVTLBRefillHandler +SYSCALL(SetVTLBRefillHandler) +#endif + +#ifdef F_SetVCommonHandler +SYSCALL(SetVCommonHandler) +#endif + +#ifdef F_SetVInterruptHandler +SYSCALL(SetVInterruptHandler) +#endif + +#ifdef F_AddIntcHandler +SYSCALL(AddIntcHandler) +#endif + +#ifdef F_AddIntcHandler2 +SYSCALL(AddIntcHandler2) +#endif + +#ifdef F_RemoveIntcHandler +SYSCALL(RemoveIntcHandler) +#endif + +#ifdef F_AddDmacHandler +SYSCALL(AddDmacHandler) +#endif + +#ifdef F_AddDmacHandler2 +SYSCALL(AddDmacHandler2) +#endif + +#ifdef F_RemoveDmacHandler +SYSCALL(RemoveDmacHandler) +#endif + +#ifdef F__EnableIntc +SYSCALL(_EnableIntc) +#endif + +#ifdef F__DisableIntc +SYSCALL(_DisableIntc) +#endif + +#ifdef F__EnableDmac +SYSCALL(_EnableDmac) +#endif + +#ifdef F__DisableDmac +SYSCALL(_DisableDmac) +#endif + +#ifdef F__SetAlarm +SYSCALL(_SetAlarm) +#endif + +#ifdef F_SetAlarm +#ifndef KERNEL_NO_PATCHES +SYSCALL(SetAlarm) +#endif +#endif + +#ifdef F__ReleaseAlarm +SYSCALL(_ReleaseAlarm) +#endif + +#ifndef KERNEL_NO_PATCHES +#ifdef F_ReleaseAlarm +SYSCALL(ReleaseAlarm) +#endif +#endif + +#ifdef F__iEnableIntc +SYSCALL(_iEnableIntc) +#endif + +#ifdef F__iDisableIntc +SYSCALL(_iDisableIntc) +#endif + +#ifdef F__iEnableDmac +SYSCALL(_iEnableDmac) +#endif + +#ifdef F__iDisableDmac +SYSCALL(_iDisableDmac) +#endif + +#ifdef F__iSetAlarm +SYSCALL(_iSetAlarm) +#endif + +#ifndef KERNEL_NO_PATCHES +#ifdef F_iSetAlarm +SYSCALL(iSetAlarm) +#endif +#endif + +#ifdef F__iReleaseAlarm +SYSCALL(_iReleaseAlarm) +#endif + +#ifndef KERNEL_NO_PATCHES +#ifdef F_iReleaseAlarm +SYSCALL(iReleaseAlarm) +#endif +#endif + +#ifdef F_CreateThread +SYSCALL(CreateThread) +#endif + +#ifdef F_DeleteThread +SYSCALL(DeleteThread) +#endif + +#ifdef F_StartThread +SYSCALL(StartThread) +#endif + +#ifdef F_ExitThread +SYSCALL(ExitThread) +#endif + +#ifdef F_ExitDeleteThread +SYSCALL(ExitDeleteThread) +#endif + +#ifdef F_TerminateThread +SYSCALL(TerminateThread) +#endif + +#ifdef F_iTerminateThread +SYSCALL(iTerminateThread) +#endif + +#ifdef F_DisableDispatchThread +SYSCALL(DisableDispatchThread) +#endif + +#ifdef F_EnableDispatchThread +SYSCALL(EnableDispatchThread) +#endif + +#ifdef F_ChangeThreadPriority +SYSCALL(ChangeThreadPriority) +#endif + +#ifdef F_iChangeThreadPriority +SYSCALL(iChangeThreadPriority) +#endif + +#ifdef F_RotateThreadReadyQueue +SYSCALL(RotateThreadReadyQueue) +#endif + +#ifdef KERNEL_NO_PATCHES + +#ifdef F_iRotateThreadReadyQueue +SYSCALL_SPECIAL(iRotateThreadReadyQueue, _iRotateThreadReadyQueue) +#endif + +#else /* KERNEL_NO_PATCHES */ + +#ifdef F__iRotateThreadReadyQueue +SYSCALL(_iRotateThreadReadyQueue) +#endif + +#endif /* KERNEL_NO_PATCHES */ + +#ifdef F_ReleaseWaitThread +SYSCALL(ReleaseWaitThread) +#endif + +#ifdef F_iReleaseWaitThread +SYSCALL(iReleaseWaitThread) +#endif + +#ifdef F_GetThreadId +SYSCALL(GetThreadId) +#endif + +#ifdef F__iGetThreadId +SYSCALL(_iGetThreadId) +#endif + +#ifdef F_ReferThreadStatus +SYSCALL(ReferThreadStatus) +#endif + +#ifdef F_iReferThreadStatus +SYSCALL(iReferThreadStatus) +#endif + +#ifdef F_SleepThread +SYSCALL(SleepThread) +#endif + +#ifdef F_WakeupThread +SYSCALL(WakeupThread) +#endif + +#ifdef KERNEL_NO_PATCHES + +#ifdef F_iWakeupThread +SYSCALL_SPECIAL(iWakeupThread, _iWakeupThread) +#endif + +#else /* KERNEL_NO_PATCHES */ + +#ifdef F__iWakeupThread +SYSCALL(_iWakeupThread) +#endif + +#endif /* KERNEL_NO_PATCHES */ + +#ifdef F_CancelWakeupThread +SYSCALL(CancelWakeupThread) +#endif + +#ifdef F_iCancelWakeupThread +SYSCALL(iCancelWakeupThread) +#endif + +#ifdef F_SuspendThread +SYSCALL(SuspendThread) +#endif + +#ifdef KERNEL_NO_PATCHES + +#ifdef F_iSuspendThread +SYSCALL_SPECIAL(iSuspendThread, _iSuspendThread) +#endif + +#else /* KERNEL_NO_PATCHES */ + +#ifdef F__iSuspendThread +SYSCALL(_iSuspendThread) +#endif + +#endif /* KERNEL_NO_PATCHES */ + +#ifdef F_ResumeThread +SYSCALL(ResumeThread) +#endif + +#ifdef F_iResumeThread +SYSCALL(iResumeThread) +#endif + +#ifdef F_RFU059 +SYSCALL(RFU059) +#endif + +#ifdef F_RFU060 +SYSCALL(RFU060) +#endif + +#ifdef F_SetupThread +SYSCALL(SetupThread) +#endif + +#ifdef F_RFU061 +SYSCALL(RFU061) +#endif + +#ifdef F_SetupHeap +SYSCALL(SetupHeap) +#endif + +#ifdef F_EndOfHeap +SYSCALL(EndOfHeap) +#endif + +#ifdef F_CreateSema +SYSCALL(CreateSema) +#endif + +#ifdef F_DeleteSema +SYSCALL(DeleteSema) +#endif + +#ifdef F_SignalSema +SYSCALL(SignalSema) +#endif + +#ifdef F_iSignalSema +SYSCALL(iSignalSema) +#endif + +#ifdef F_WaitSema +SYSCALL(WaitSema) +#endif + +#ifdef F_PollSema +SYSCALL(PollSema) +#endif + +#ifdef F_iPollSema +SYSCALL(iPollSema) +#endif + +#ifdef F_ReferSemaStatus +SYSCALL(ReferSemaStatus) +#endif + +#ifdef F_iReferSemaStatus +SYSCALL(iReferSemaStatus) +#endif + +#ifdef F_iDeleteSema +SYSCALL(iDeleteSema) +#endif + +#ifdef F_SetOsdConfigParam +SYSCALL(SetOsdConfigParam) +#endif + +#ifdef F_GetOsdConfigParam +SYSCALL(GetOsdConfigParam) +#endif + +#ifdef F_GetGsHParam +SYSCALL(GetGsHParam) +#endif + +#ifdef F_GetGsVParam +SYSCALL(GetGsVParam) +#endif + +#ifdef F_SetGsHParam +SYSCALL(SetGsHParam) +#endif + +#ifdef F_SetGsVParam +SYSCALL(SetGsVParam) +#endif + +#ifdef F_CreateEventFlag +SYSCALL(CreateEventFlag) +#endif + +#ifdef F_DeleteEventFlag +SYSCALL(DeleteEventFlag) +#endif + +#ifdef F_SetEventFlag +SYSCALL(SetEventFlag) +#endif + +#ifdef F_iSetEventFlag +SYSCALL(iSetEventFlag) +#endif + +#ifndef KERNEL_NO_PATCHES + +#ifdef F_PutTLBEntry +SYSCALL(PutTLBEntry) +#endif + +#ifdef F_iPutTLBEntry +SYSCALL(iPutTLBEntry) +#endif + +#ifdef F__SetTLBEntry +SYSCALL(_SetTLBEntry) +#endif + +#ifdef F_iSetTLBEntry +SYSCALL(iSetTLBEntry) +#endif + +#ifdef F_GetTLBEntry +SYSCALL(GetTLBEntry) +#endif + +#ifdef F_iGetTLBEntry +SYSCALL(iGetTLBEntry) +#endif + +#ifdef F_ProbeTLBEntry +SYSCALL(ProbeTLBEntry) +#endif + +#ifdef F_iProbeTLBEntry +SYSCALL(iProbeTLBEntry) +#endif + +#ifdef F_ExpandScratchPad +SYSCALL(ExpandScratchPad) +#endif + +#endif /* KERNEL_NO_PATCHES */ + +#ifdef F_EnableIntcHandler +SYSCALL(EnableIntcHandler) +#endif + +#ifdef F_iEnableIntcHandler +SYSCALL(iEnableIntcHandler) +#endif + +#ifdef F_DisableIntcHandler +SYSCALL(DisableIntcHandler) +#endif + +#ifdef F_iDisableIntcHandler +SYSCALL(iDisableIntcHandler) +#endif + +#ifdef F_EnableDmacHandler +SYSCALL(EnableDmacHandler) +#endif + +#ifdef F_iEnableDmacHandler +SYSCALL(iEnableDmacHandler) +#endif + +#ifdef F_DisableDmacHandler +SYSCALL(DisableDmacHandler) +#endif + +#ifdef F_iDisableDmacHandler +SYSCALL(iDisableDmacHandler) +#endif + +#ifdef F_KSeg0 +SYSCALL(KSeg0) +#endif + +#ifdef F_EnableCache +SYSCALL(EnableCache) +#endif + +#ifdef F_DisableCache +SYSCALL(DisableCache) +#endif + +#ifdef F_GetCop0 +SYSCALL(GetCop0) +#endif + +#ifdef F_FlushCache +SYSCALL(FlushCache) +#endif + +#ifdef F_CpuConfig +SYSCALL(CpuConfig) +#endif + +#ifdef F_iGetCop0 +SYSCALL(iGetCop0) +#endif + +#ifdef F_iFlushCache +SYSCALL(iFlushCache) +#endif + +#ifdef F_RFU105 +SYSCALL(RFU105) +#endif + +#ifdef F_iCpuConfig +SYSCALL(iCpuConfig) +#endif + +#ifdef F_SifStopDma +SYSCALL(SifStopDma) +#endif + +#ifdef F_SetCPUTimerHandler +SYSCALL(SetCPUTimerHandler) +#endif + +#ifdef F_SetCPUTimer +SYSCALL(SetCPUTimer) +#endif + +#ifdef F_SetOsdConfigParam2 +SYSCALL(SetOsdConfigParam2) +#endif + +#ifdef F_GetOsdConfigParam2 +SYSCALL(GetOsdConfigParam2) +#endif + +#ifdef F_GsGetIMR +SYSCALL(GsGetIMR) +#endif + +#ifdef F_iGsGetIMR +SYSCALL(iGsGetIMR) +#endif + +#ifdef F_GsPutIMR +SYSCALL(GsPutIMR) +#endif + +#ifdef F_iGsPutIMR +SYSCALL(iGsPutIMR) +#endif + +#ifdef F_SetPgifHandler +SYSCALL(SetPgifHandler) +#endif + +#ifdef F_SetVSyncFlag +SYSCALL(SetVSyncFlag) +#endif + +#ifdef F_SetSyscall +SYSCALL(SetSyscall) +#endif + +//#ifdef F_print +//SYSCALL(_print) +//#endif + +#ifdef F_SifDmaStat +SYSCALL(SifDmaStat) +#endif + +#ifdef F_iSifDmaStat +SYSCALL(iSifDmaStat) +#endif + +#ifdef F_SifSetDma +SYSCALL(SifSetDma) +#endif + +#ifdef F_iSifSetDma +SYSCALL(iSifSetDma) +#endif + +#ifdef F_SifSetDChain +SYSCALL(SifSetDChain) +#endif + +#ifdef F_iSifSetDChain +SYSCALL(iSifSetDChain) +#endif + +#ifdef F_SifSetReg +SYSCALL(SifSetReg) +#endif + +#ifdef F_SifGetReg +SYSCALL(SifGetReg) +#endif + +#ifdef KERNEL_NO_PATCHES + +#ifdef F_ExecOSD +SYSCALL_SPECIAL(ExecOSD, _ExecOSD) +#endif + +#else /* KERNEL_NO_PATCHES */ + +#ifdef F__ExecOSD +SYSCALL(_ExecOSD) +#endif + +#endif /* KERNEL_NO_PATCHES */ + +#ifdef F_Deci2Call +SYSCALL(Deci2Call) +#endif + +#ifdef F_PSMode +SYSCALL(PSMode) +#endif + +#ifdef F_MachineType +SYSCALL(MachineType) +#endif + +#ifdef F_GetMemorySize +SYSCALL(GetMemorySize) +#endif + +#ifdef F__GetGsDxDyOffset +SYSCALL(_GetGsDxDyOffset) +#endif + +#ifdef F__InitTLB +SYSCALL(_InitTLB) +#endif + +#ifdef F_SetMemoryMode +SYSCALL(SetMemoryMode) +#endif + +#ifdef F_GPfuncs + .text + .align 2 +.globl ChangeGP +.ent ChangeGP +ChangeGP: + move $v0, $gp + jr $ra + move $gp, $a0 +.end ChangeGP + +.globl SetGP +.ent SetGP +SetGP: + jr $ra + move $gp, $a0 +.end SetGP + +.globl GetGP +.ent GetGP +GetGP: + jr $ra + move $v0, $gp +.end GetGP +#endif + +#ifdef F_SifWriteBackDCache + + .globl SifWriteBackDCache + .ent SifWriteBackDCache + .set noreorder + +SifWriteBackDCache: /* DHWBIN: Data cache Hit WriteBack INvalidate. */ + + lui $25, 0xffff + ori $25, $25, 0xffc0 + blez $5, last + addu $10, $4, $5 + and $8, $4, $25 + addiu $10, $10, -1 + and $9, $10, $25 + subu $10, $9, $8 + srl $11, $10, 0x6 + addiu $11, $11, 1 + andi $9, $11, 0x7 + beqz $9, eight + srl $10, $11, 0x3 +loop1: + sync + cache 0x18, 0($8) + sync + addiu $9, $9, -1 + nop + bgtz $9, loop1 + addiu $8, $8, 64 + +eight: + beqz $10, last +loop8: + addiu $10, $10, -1 + sync + cache 0x18, 0($8) + sync + cache 0x18, 64($8) + sync + cache 0x18, 128($8) + sync + cache 0x18, 192($8) + sync + cache 0x18, 256($8) + sync + cache 0x18, 320($8) + sync + cache 0x18, 384($8) + sync + cache 0x18, 448($8) + sync + bgtz $10, loop8 + addiu $8, $8, 512 +last: + jr $31 + nop + + .end SifWriteBackDCache +#endif + +#define DXWBIN 0x14 /* Data cache: indeX WriteBack INvalidate. */ +#define DXIN 0x16 /* Data cache: indeX INvalidate. */ + +#define opDCache(name, op) \ + .set push; \ + .set noreorder; \ + .set nomacro; \ + .text; \ + .p2align 3; \ + .globl name; \ + .type name,@function; \ + .ent name, 0; \ +name: lui $7, 0xffff; \ + daddu $6, $0, $0; \ + ori $7, 0xf000; \ + nop; \ +1: sync; \ + cache 0x10, 0($6); \ + sync; \ + mfc0 $2, $28; \ + and $2, $7; \ + addu $2, $6; \ + sltu $3, $5, $2; \ + sltu $2, $4; \ + bnez $2, 2f; \ + nop; \ + bnez $3, 2f; \ + nop; \ + sync; \ + cache op, 0($6); \ + sync; \ +2: sync; \ + cache 0x10, 1($6); \ + sync; \ + mfc0 $2, $28; \ + and $2, $7; \ + addu $2, $6; \ + sltu $3, $5, $2; \ + sltu $2, $4; \ + bnez $2, 3f; \ + nop; \ + bnez $3, 3f; \ + nop; \ + sync; \ + cache op, 1($6); \ + sync; \ +3: sync; \ + addiu $6, 64; \ + slti $2, $6, 4096; \ + bnez $2, 1b; \ + nop; \ + jr $31; \ + nop; \ + .end name; \ + .size name,.-name; \ + .set pop; + +#ifdef F__SyncDCache +opDCache(_SyncDCache, DXWBIN) +#endif + +#ifdef F__InvalidDCache +opDCache(_InvalidDCache, DXIN) +#endif + +#ifdef F___errno +/* This is needed in case we are linked against libm (the math library) but + not libc. */ + .globl __errno + .ent __errno + .weak __errno + +__errno: + la $2, errno + jr $31 + nop + .end __errno +#endif + +#ifdef F_errno +/* New applications compiled against ps2lib that use errno will resolve to + this, while existing newlib applications will resolve to __errno. */ + .globl errno + .weak errno + + .data +errno: + .space 4 +#endif + +#ifdef F_strlen +/* Assembler version of strlen that uses quadword instructions. + + Jeff Johnston, Cygnus Solutions, Feb 10/1999. + + ============================================================ + Copyright (C) 1999 by Cygnus Solutions. All rights reserved. + + Permission to use, copy, modify, and distribute this + software is freely granted, provided that this notice + is preserved. + ============================================================ */ + + .text + .align 2 + .globl strlen + .text + .ent strlen + .weak strlen +strlen: + .frame $sp,0,$31 # vars= 0, regs= 0/0, args= 0, extra= 0 + .mask 0x00000000,0 + .fmask 0x00000000,0 + +#ifndef __OPTIMIZE_SIZE__ + +/* check if src is quadword aligned, doubleword aligned, or neither in which case + perform checking for null terminator one byte at a time. */ + + andi $2,$4,0x7 + .set noreorder + .set nomacro + bne $2,$0,$L15 + move $7,$4 + .set macro + .set reorder + + andi $3,$4,0xf + dli $2,0x0101010101010101 + .set noreorder + .set nomacro + bne $3,$0,$L12 + move $5,$4 + .set macro + .set reorder + +/* src is quadword aligned. Load a quadword at a time and check for null terminator. + If null terminator is found, go and find exact position by looking at each byte + of the last quadword. Otherwise, continue to next quadword and keep searching. */ + + lq $3,0($5) + pcpyld $8,$2,$2 + dli $4,0x8080808080808080 + psubb $2,$3,$8 + pnor $3,$0,$3 + pcpyld $9,$4,$4 + pand $2,$2,$3 + pand $2,$2,$9 + pcpyud $3,$2,$8 + or $6,$3,$2 + .set noreorder + .set nomacro + bnel $6,$0,$L15 + move $4,$5 + .set macro + .set reorder + + addu $5,$5,16 +$L14: + lq $2,0($5) + #nop + pnor $3,$0,$2 + psubb $2,$2,$8 + pand $2,$2,$3 + pand $4,$2,$9 + pcpyud $3,$4,$6 + or $3,$3,$4 + .set noreorder + .set nomacro + beql $3,$0,$L14 + addu $5,$5,16 + .set macro + .set reorder + + .set noreorder + .set nomacro + b $L15 + move $4,$5 + .set macro + .set reorder + +/* src is doubleword aligned. Load a doubleword at a time and check for null terminator. + If null terminator is found, go and find exact position by looking at each byte + of the last doubleword. Otherwise, continue to next doubleword and keep searching. */ + + +$L12: + ld $3,0($5) + dli $4,0x8080808080808080 + dsubu $2,$3,$2 + nor $3,$0,$3 + and $2,$2,$3 + and $2,$2,$4 + .set noreorder + .set nomacro + bnel $2,$0,$L15 + move $4,$5 + .set macro + .set reorder + + dli $6,0x0101010101010101 + addu $5,$5,8 +$L16: + ld $2,0($5) + #nop + nor $3,$0,$2 + dsubu $2,$2,$6 + and $2,$2,$3 + and $2,$2,$4 + .set noreorder + .set nomacro + beql $2,$0,$L16 + addu $5,$5,8 + .set macro + .set reorder + + move $4,$5 + +#else /* __OPTIMIZE_SIZE__ */ + + move $7,$4 + +#endif /* __OPTIMIZE_SIZE__ */ + +/* search a byte at a time for null terminator and then calculate length by subtracting + original string address from null terminator address. */ + +$L9: +$L15: + .set noreorder + .set nomacro + + lb $2,0($4) + #nop + beq $2,$0,1f + addu $4,$4,1 + + lb $2,0($4) + #nop + bne $2,$0,$L9 + addu $4,$4,1 +1: + subu $4,$4,1 + + .set macro + .set reorder + + .set noreorder + .set nomacro + j $31 + subu $2,$4,$7 + .set macro + .set reorder + + .end strlen +#endif + +#ifdef F_strncpy +/* Assembler version of strncpy using quadword instructions + + Jeff Johnston, Cygnus Solutions, Feb 10/1999. + + ============================================================ + Copyright (C) 1999 by Cygnus Solutions. All rights reserved. + + Permission to use, copy, modify, and distribute this + software is freely granted, provided that this notice + is preserved. + ============================================================ */ + + .text + .p2align 3 + .globl strncpy + .text + .ent strncpy + .weak strncpy +strncpy: + .frame $sp,0,$31 # vars= 0, regs= 0/0, args= 0, extra= 0 + .mask 0x00000000,0 + .fmask 0x00000000,0 + + move $8,$4 + +#ifndef __OPTIMIZE_SIZE__ + +/* check if src and dest are doubleword aligned, quadword aligned, or neither in which + case copy byte by byte */ + + or $7,$5,$4 + li $10,0x10 + andi $2,$7,0x7 + li $9,0x8 + .set noreorder + .set nomacro + bne $2,$0,$L9 + andi $2,$7,0xf + .set macro + .set reorder + movz $9,$10,$2 + .set noreorder + .set nomacro + bne $2,$0,$L17 + sltu $2,$6,$9 + .set macro + .set reorder + +/* src and dest are quadword aligned. Check a quadword at a time looking for a + null terminator or until the nth byte is reached. Otherwise, copy the + quadword to dest and continue looping checking quadwords. Once a null + terminator is found or n is < 16 go copy a byte at a time. */ + +$L31: + bne $2,$0,$L9 + dli $7,0x0101010101010101 + lq $3,0($5) + pcpyld $9,$7,$7 + pnor $3,$0,$3 + dli $7,0x8080808080808080 + psubb $2,$3,$9 + pcpyld $10,$7,$7 + pand $2,$2,$3 + pand $2,$2,$10 + pcpyud $3,$2,$4 + or $3,$2,$3 + .set noreorder + .set nomacro + bne $3,$0,$L5 + move $7,$8 + .set macro + .set reorder + lq $3,0($5) + .p2align 3 +$L39: + addu $6,$6,-16 + addu $5,$5,16 + sltu $2,$6,16 + sq $3,0($7) + .set noreorder + .set nomacro + bne $2,$0,$L5 + addu $7,$7,16 + .set macro + .set reorder + + lq $2,0($5) + #nop + pnor $3,$0,$2 + psubb $2,$2,$9 + pand $2,$2,$3 + pand $2,$2,$10 + pcpyud $3,$2,$4 + or $2,$2,$3 + .set noreorder + .set nomacro + beql $2,$0,$L19 + lq $3,0($5) + b $L9 + move $4,$7 + .set macro + .set reorder + +/* src and dest are quadword aligned. Check a quadword at a time looking for a + null terminator or until the nth byte is reached. Otherwise, copy the + quadword to dest and continue looping checking quadwords. Once a null + terminator is found or n is < 16 go copy a byte at a time. */ + +$L17: + bne $2,$0,$L9 + ld $3,0($5) + dli $9,0x0101010101010101 + dli $10,0x8080808080808080 + dsubu $2,$3,$9 + nor $3,$0,$3 + and $2,$2,$3 + and $2,$2,$10 + .set noreorder + .set nomacro + bne $2,$0,$L5 + move $7,$8 + .set macro + .set reorder + ld $3,0($5) + .p2align 3 +$L19: + addu $6,$6,-8 + addu $5,$5,8 + sltu $2,$6,8 + sd $3,0($7) + .set noreorder + .set nomacro + bne $2,$0,$L5 + addu $7,$7,8 + .set macro + .set reorder + + ld $2,0($5) + #nop + nor $3,$0,$2 + dsubu $2,$2,$9 + and $2,$2,$3 + and $2,$2,$10 + .set noreorder + .set nomacro + beql $2,$0,$L19 + ld $3,0($5) + .set macro + .set reorder + +$L5: + move $4,$7 + +#endif /* !__OPTIMIZE_SIZE__ */ + +/* check a byte at a time looking for either the null terminator or until n bytes are + copied. If the null terminator is found and n is not reached yet, copy null + bytes until n is reached. */ + + .p2align 3 +$L9: + .set noreorder + .set nomacro + beq $6,$0,$L18 + move $2,$6 + .set macro + .set reorder + + lbu $2,0($5) + addu $6,$6,-1 + addu $5,$5,1 + sb $2,0($4) + sll $2,$2,24 + .set noreorder + .set nomacro + bne $2,$0,$L9 + addu $4,$4,1 + .set macro + .set reorder + + move $2,$6 +$L20: + .set noreorder + .set nomacro + beq $2,$0,$L18 + addu $6,$6,-1 + .set macro + .set reorder + + .p2align 3 +$L16: + sb $0,0($4) + move $2,$6 + addu $4,$4,1 + .set noreorder + .set nomacro + nop + nop + bne $2,$0,$L16 + addu $6,$6,-1 + .set macro + .set reorder + +$L18: + .set noreorder + .set nomacro + j $31 + move $2,$8 + .set macro + .set reorder + + .end strncpy +#endif + +#ifdef F_memcpy +/* Assembler version of memcpy using quadword instructions. + + Jeff Johnston, Cygnus Solutions, Feb 10/1999. + + ============================================================ + Copyright (C) 1999 by Cygnus Solutions. All rights reserved. + + Permission to use, copy, modify, and distribute this + software is freely granted, provided that this notice + is preserved. + ============================================================ */ + + .text + .align 2 + .globl memcpy + .text + .ent memcpy + .weak memcpy +memcpy: + .frame $sp,0,$31 # vars= 0, regs= 0/0, args= 0, extra= 0 + .mask 0x00000000,0 + .fmask 0x00000000,0 + move $8,$4 + +#ifndef __OPTIMIZE_SIZE__ + +/* if bytes to move are < 32 or src or dest are not quadword aligned, jump to + code that moves one byte at a time */ + + sltu $2,$6,32 + .set noreorder + .set nomacro + bne $2,$0,$L2 + move $3,$8 + .set macro + .set reorder + + or $2,$5,$8 + andi $2,$2,0xF + .set noreorder + .set nomacro + bnel $2,$0,$L20 + addu $6,$6,-1 + .set macro + .set reorder + + move $7,$8 + +/* while remainder to move is >= 32 bytes, use LQ/SQ quadword instructions + to move data */ + +$L5: + lq $3,0($5) + addu $6,$6,-32 + addu $5,$5,16 + sltu $4,$6,32 + sq $3,0($7) + addu $7,$7,16 + lq $2,0($5) + addu $5,$5,16 + sq $2,0($7) + .set noreorder + .set nomacro + beq $4,$0,$L5 + addu $7,$7,16 + .set macro + .set reorder + + sltu $2,$6,8 + .set noreorder + .set nomacro + bne $2,$0,$L2 + move $3,$7 + .set macro + .set reorder + +/* while remainder to move is >= 8 bytes, use LD/SD doubleword instructions + to move data */ + +$L9: + ld $3,0($5) + addu $6,$6,-8 + addu $5,$5,8 + sltu $2,$6,8 + sd $3,0($7) + .set noreorder + .set nomacro + beq $2,$0,$L9 + addu $7,$7,8 + .set macro + .set reorder + + move $3,$7 + +#else /* __OPTIMIZE_SIZE__ */ + + move $3,$8 + +#endif /* !__OPTIMIZE_SIZE__ */ + +/* Move any remaining bytes one at a time */ + +$L2: + addu $6,$6,-1 +$L20: + li $2,-1 # 0xffffffffffffffff + .set noreorder + .set nomacro + beq $6,$2,$L12 + move $4,$2 + .set macro + .set reorder + +$L13: + lbu $2,0($5) + addu $6,$6,-1 + addu $5,$5,1 + sb $2,0($3) + .set noreorder + .set nomacro + nop + bne $6,$4,$L13 + addu $3,$3,1 + .set macro + .set reorder + +$L12: + .set noreorder + .set nomacro + j $31 + move $2,$8 + .set macro + .set reorder + + .end memcpy +#endif + +#ifdef F_memset +/* Assembler version of memset using quadword instructions. + + Jeff Johnston, Cygnus Solutions, Feb 10/1999. + + ============================================================ + Copyright (C) 1999 by Cygnus Solutions. All rights reserved. + + Permission to use, copy, modify, and distribute this + software is freely granted, provided that this notice + is preserved. + ============================================================ */ + + .text + .align 2 + .globl memset + .text + .ent memset + .weak memset +memset: + .frame $sp,0,$31 # vars= 0, regs= 0/0, args= 0, extra= 0 + .mask 0x00000000,0 + .fmask 0x00000000,0 + +#ifndef __OPTIMIZE_SIZE__ + +/* if not setting a double word or more, go and set one byte at a time */ + + sltu $2,$6,8 + .set noreorder + .set nomacro + bne $2,$0,$L2 + move $3,$4 + .set macro + .set reorder + +/* if not aligned on a quadword boundary, set one byte at a time */ + + andi $2,$4,0xf + .set noreorder + .set nomacro + bne $2,$0,$L2 + move $7,$4 + .set macro + .set reorder + +/* otherwise, build a double word containing the bytes to set */ + + andi $9,$5,0xff + sltu $10,$6,32 + move $8,$9 + dsll $3,$8,8 + or $8,$3,$9 + pcpyh $3,$8 + .set noreorder + .set nomacro + +/* check if setting 32 bytes or more, otherwise set 8 bytes at a time */ + + bne $10,$0,$L31 + sltu $2,$6,8 + .set macro + .set reorder + +/* take double word built from the byte to set and make a quadword */ + + pcpyld $8,$3,$3 + +/* loop while bytes to set >=32 and use quadword stores */ + +$L12: + sq $8,0($7) + addu $6,$6,-32 + addu $7,$7,16 + sltu $2,$6,32 + sq $8,0($7) + .set noreorder + .set nomacro + beq $2,$0,$L12 + addu $7,$7,16 + .set macro + .set reorder + + .set noreorder + .set nomacro + b $L31 + sltu $2,$6,8 + .set macro + .set reorder + +$L16: + addu $6,$6,-8 + addu $7,$7,8 + sltu $2,$6,8 +$L31: + .set noreorder + .set nomacro + nop + nop + beql $2,$0,$L16 + sd $3,0($7) + .set macro + .set reorder + + move $3,$7 + +#else /* __OPTIMIZE_SIZE__ */ + + move $3,$4 + +#endif /* __OPTIMIZE_SIZE__ */ + +/* loop while bytes left to set and set one byte at a time */ + +$L2: + li $2,4294901760 # 0xffff0000 + addu $6,$6,-1 + ori $2,$2,0xffff + beq $6,$2,$L19 + li $2,4294901760 # 0xffff0000 + ori $2,$2,0xffff + +$L20: + sb $5,0($3) + addu $6,$6,-1 + .set noreorder + .set nomacro + nop + nop + nop + bne $6,$2,$L20 + addu $3,$3,1 + .set macro + .set reorder + +$L19: + .set noreorder + .set nomacro + j $31 + move $2,$4 + .set macro + .set reorder + + .end memset +#endif + diff --git a/sps2_basement/hardware/sbios/bios.c b/sps2_basement/hardware/sbios/bios.c new file mode 100644 index 0000000..a2445a4 --- /dev/null +++ b/sps2_basement/hardware/sbios/bios.c @@ -0,0 +1,102 @@ +#include "bios.h" +#include "../../core/base/basicTypes.h" +#include "syscallnr.h" + +#define sps2_bios_sc_in0_out0( CALL ) __asm__ __volatile__( "li $3, " ZSTR(CALL) " \nsyscall \nnop \n" ) +#define sps2_bios_sc_in1_out0( CALL, ARG0 ) __asm__ __volatile__( "li $3, " ZSTR(CALL) " \nori $4, %0, 0 \nsyscall \nnop \n" :: "r" (ARG0) ) +#define sps2_bios_sc_in2_out0( CALL, ARG0, ARG1 ) __asm__ __volatile__( "li $3, " ZSTR(CALL) " \nori $4, %0, 0 \nori $5, %0, 0 \nsyscall \nnop \n" :: "r" (ARG0), "r" (ARG1) ) +#define sps2_bios_sc_in3_out0( CALL, ARG0, ARG1, ARG2 ) __asm__ __volatile__( "li $3, " ZSTR(CALL) " \nori $4, %0, 0 \nori $5, %1, 0 \nori $6, %2, 0 \nsyscall \nnop \n" :: "r" (ARG0), "r" (ARG1), "r" (ARG2) ) +#define sps2_bios_sc_in4_out0( CALL, ARG0, ARG1, ARG2, ARG2 ) __asm__ __volatile__( "li $3, " ZSTR(CALL) " \nori $4, %0, 0 \nori $5, %1, 0 \nori $6, %2, 0 \nori $7, %3, 0 \nsyscall \nnop \n" :: "r" (ARG0), "r" (ARG1), "r" (ARG2), "r" (ARG3) ) + +#define sps2_bios_sc_in0_out1( CALL, RVAL0 ) __asm__ __volatile__( "li $3, " ZSTR(CALL) " \nsyscall \nnop \n" : "r=" (ARG0) ) + +#define ZSTR( X ) #X + +void sps2_ee_reset( uint32_t init_bitfield ){ + sps2_bios_sc_in1_out0( __NR_ResetEE, init_bitfield ); +}; + +void sps2_gs_set_mode( uint32_t interlace, uint32_t mode, uint32_t field ){ + sps2_bios_sc_in3_out0( __NR_SetGsCrt, interlace, mode, field ); +}; + +void sps2_exit( void ){ + sps2_bios_sc_in0_out0( __NR__Exit ); +}; + +void sps2_load_exec( const char *fileName, uint32_t argc, char **argv ){ + sps2_bios_sc_in3_out0( __NR__LoadExecPS2, fileName, argc, argv ); +}; + +void sps2_mem_exec( void *ptr, uint32_t gp_paramu, int32_t argc, char **argv ){ + sps2_bios_sc_in4_out0( __NR__ExecPS2, address, gp_paramu, argc, argv ); +}; + +void sps2_set_sbus_int_handler( uint32_t int_id, (*handler)(unsigned int int_id) ){ + sps2_bios_sc_in2_out0( __NR_AddIntcHandler, int_id, handler ); +}; + +void sps2_del_sbus_int_handler( uint32_t int_id ){ + sps2_bios_sc_in1_out0( __NR_RemoveSbusIntcHandler, int_id ); +}; + +//Returns int ?? what purpose ? +void sps2_trig_iop_int( uint32_t int_id ){ + sps2_bios_sc_in1_out0( __NR_Interrupt2Iop, int_id ); +}; + + +// Info obtained from: +// - Gustavo Scotti (gustavo@scotti.com) +// - Marcus R. Brown (mrbrown@0xd6.org) +// - Herben (?) - Video mode information. +// - Loser (?) - More video mode information. +// - Hiryu (?) - Even more video mode information. +/* +void gs_setmode(int interlace, int mode, int field) { + __asm__ __volatile__( + "li $3, 0x02 \n" // Specify the syscall. (reg 3) + "add $4, $0, %0 \n" // Specify the arguments. (regs 4 - 11) + "add $5, $0, %1 \n" // + "add $6, $0, %2 \n" // + "syscall \n" // Perform the syscall. + "nop \n" // + : + : "r" (interlace), "r" (mode), "r" (field) + ); +}; +*/ +__asm__ ( + ".set push\n" + ".set noreorder\n" + ".text\n" + ".align 4\n" + ".globl __syscall\n" + ".type __syscall,@function\n" + ".ent __syscall,0\n" + "__syscall:\n" + "\tmfc0 $2, $12\n\t" // Move From System Control Coprocessor GPR[$2] <- CPR[0,$12] + "andi $2, $2, 0x18\n\t" // AND IMIDIATE GRP[$2] = 0x18 & GPR[$2] + "beqz $2, _kMode\n\t" // if GPR[$2] == 0 -> _KMode + "slt $2, $3, $0\n\t" // if ( GPR[$3] < GPR[$0] ) GPR[$2] = 1 else GPR[$2] = 0 + "syscall\n\t" // real syscal + "jr $31\n\t" // sets GPR[$31] tp a PC .... goto address in GPR[$31] + "nop\n" + "_kMode:\n\t" + "subu $26, $0, $3\n\t" + "movn $3, $26, $2\n\t" + "sll $3, $3, 2\n\t" + "lui $26, 0x8000\n\t" + "lhu $2, 0x02F0($26)\n\t" + "sll $2, $2, 16\n\t" + "lh $26, 0x02F8($26)\n\t" + "add $2, $26\n\t" + "addu $3, $2\n\t" + "lw $26, 0x00($3)\n\t" + "jr $26\n\t" + "nop\n" + ".end __syscall\n" + ".size __syscall,.-__syscall\n" + ".set pop\n" +); + diff --git a/sps2_basement/hardware/sbios/bios.h b/sps2_basement/hardware/sbios/bios.h new file mode 100644 index 0000000..d32edf6 --- /dev/null +++ b/sps2_basement/hardware/sbios/bios.h @@ -0,0 +1,498 @@ +#ifndef __SPS2_BASIC_SYSTEM_HEADER__ +#define __SPS2_BASIC_SYSTEM_HEADER__ + +#include "../../core/base/basicTypes.h" +#include "sifdma.h" + +#define DI DIntr +#define EI EIntr + +// Workaround for EE kernel bug: call this immediately before returning from any interrupt handler. +#define ExitHandler() asm volatile("sync\nei\n") + +// note: 'sync' is the same as 'sync.l' +#define EE_SYNC() __asm__ volatile ("sync") +#define EE_SYNCL() __asm__ volatile ("sync.l") +#define EE_SYNCP() __asm__ volatile ("sync.p") + +#define UNCACHED_SEG(x) \ + ((void *)(((uint32_t)(x)) | 0x20000000)) + +#define IS_UNCACHED_SEG(x) \ + (((uint32_t)(x)) & 0x20000000) + +#define UCAB_SEG(x) \ + ((void *)(((uint32_t)(x)) | 0x30000000)) + +#define PUSHDATA( t, x, v, l) \ + *(t *)(x) = (v); (l) = sizeof(t) + +#define POPDATA( t, x, v, l) \ + (v) = *(t *)(x); (l) = sizeof(t) + +#define ALIGNED(x) __attribute__((aligned((x)))) + +// GP functions +void * ChangeGP(void *gp); +void SetGP(void *gp); +void * GetGP(void); + +extern void *_gp; +#define SetModuleGP() ChangeGP(&_gp) + +/** Special thread ID for referring to the running thread. + Unlike the IOP kernel, this is only supported by ReferThreadStatus() and ChangeThreadPriority(). + It can also be used by the iWakeupThread() _syscall_. + But because the libkernel patch may call WakeupThread() to avoid the defect within iWakeupThread() that prevents the running thread from being woken up, + THS_SELF should not be used with iWakeupThread(). */ +#define TH_SELF 0 + +/** Limits */ +#define MAX_THREADS 256 //A few will be used for the kernel patches. Thread 0 is always the idle thread. +#define MAX_SEMAPHORES 256 //A few will be used for the kernel patches. +#define MAX_PRIORITY 128 +#define MAX_HANDLERS 128 +#define MAX_ALARMS 64 + +/** Modes for FlushCache */ +#define WRITEBACK_DCACHE 0 +#define INVALIDATE_DCACHE 1 +#define INVALIDATE_ICACHE 2 +#define INVALIDATE_CACHE 3 //Invalidate both data & instruction caches. + +/** EE Interrupt Controller (INTC) interrupt numbers */ +typedef enum e_initc_irq { + INTC_GS = 0, + INTC_SBUS = 1, + INTC_VBLANK_S = 2, + INTC_VBLANK_E = 3, + INTC_VIF0 = 4, + INTC_VIF1 = 5, + INTC_VU0 = 6, + INTC_VU1 = 7, + INTC_IPU = 8, + INTC_TIM0 = 9, + INTC_TIM1 = 10, + INTC_TIM2 = 11, + INTC_TIM3 = 12, //Reserved by the EE kernel for alarms (do not use) + INTC_SFIFO = 13, //Error encountered during SFIFO transfer + INTC_VU0WD = 14 //VU0 WatchDog; ForceBreak is sent to VU0 if left in RUN state for extended periods of time. +}initc_irq_t; + +//For backward-compatibility +#define kINTC_GS INTC_GS +#define kINTC_SBUS INTC_SBUS +#define kINTC_VBLANK_START INTC_VBLANK_S +#define kINTC_VBLANK_END INTC_VBLANK_E +#define kINTC_VIF0 INTC_VIF0 +#define kINTC_VIF1 INTC_VIF1 +#define kINTC_VU0 INTC_VU0 +#define kINTC_VU1 INTC_VU1 +#define kINTC_IPU INTC_IPU +#define kINTC_TIMER0 INTC_TIM0 +#define kINTC_TIMER1 INTC_TIM1 + +/** EE Direct Memory Access Controller (DMAC) interrupt numbers */ +typedef enum e_dmac_irq { + DMAC_VIF0 = 0, + DMAC_VIF1 = 1, + DMAC_GIF = 3, + DMAC_FROM_IPU = 4, + DMAC_TO_IPU = 5, + DMAC_SIF0 = 6, + DMAC_SIF1 = 7, + DMAC_SIF2 = 8, + DMAC_FROM_SPR = 9, + DMAC_TO_SPR = 10, + + DMAC_CIS = 13, //Channel interrupt + DMAC_MEIS = 14, //MemFIFO empty interrupt + DMAC_BEIS = 15, //Bus error interrupt +} dmac_irq_t; + +/** ResetEE argument bits */ +#define INIT_DMAC 0x01 +#define INIT_VU1 0x02 +#define INIT_VIF1 0x04 +#define INIT_GIF 0x08 +#define INIT_VU0 0x10 +#define INIT_VIF0 0x20 +#define INIT_IPU 0x40 + +static inline void nopdelay(void){ + uint32_t i = 0xfffff; + do{ __asm__ ("nop\nnop\nnop\nnop\nnop\n"); } while( i-- ); +}; + +static inline uint32_t ee_get_opmode(void) { + uint32_t status; + __asm__ volatile ( + ".set\tpush\n\t" \ + ".set\tnoreorder\n\t" \ + "mfc0\t%0, $12\n\t" \ + ".set\tpop\n\t" : "=r" (status)); + return (status >> 3) & 3; +}; + +static inline uint32_t ee_set_opmode( uint32_t opmode ){ + uint32_t status, mask; + __asm__ volatile ( + ".set\tpush\n\t" \ + ".set\tnoreorder\n\t" \ + "mfc0\t%0, $12\n\t" \ + "li\t%1, 0xffffffe7\n\t" \ + "and\t%0, %1\n\t" \ + "or\t%0, %2\n\t" \ + "mtc0\t%0, $12\n\t" \ + "sync.p\n\t" + ".set\tpop\n\t" : "=r" (status), "=r" (mask) : "r" (opmode)); + + return (status >> 3) & 3; +}; + +static inline uint32_t ee_kmode_enter(){ + uint32_t status, mask; + + __asm__ volatile ( + ".set\tpush\n\t" \ + ".set\tnoreorder\n\t" \ + "mfc0\t%0, $12\n\t" \ + "li\t%1, 0xffffffe7\n\t" \ + "and\t%0, %1\n\t" \ + "mtc0\t%0, $12\n\t" \ + "sync.p\n\t" + ".set\tpop\n\t" : "=r" (status), "=r" (mask)); + + return status; +}; + +static inline uint32_t ee_kmode_exit(){ + uint32_t status; + + __asm__ volatile ( + ".set\tpush\n\t" \ + ".set\tnoreorder\n\t" \ + "mfc0\t%0, $12\n\t" \ + "ori\t%0, 0x10\n\t" \ + "mtc0\t%0, $12\n\t" \ + "sync.p\n\t" \ + ".set\tpop\n\t" : "=r" (status)); + + return status; +}; + +typedef struct s_ee_sema{ + uint32_t count, + max_count, + init_count, + wait_threads; + uint32_t attr, + option; +} ee_sema_t; + +typedef struct s_ee_thread { + uint32_t status; // 0x00 + void * func; // 0x04 + void * stack; // 0x08 + uint32_t stack_size; // 0x0C + void * gp_reg; // 0x10 + uint32_t initial_priority; // 0x14 + uint32_t current_priority; // 0x18 + uint32_t attr; // 0x1C + uint32_t option; // 0x20 Do not use - officially documented to not work. +} ee_thread_t; + +/** Thread status */ +#define THS_RUN 0x01 +#define THS_READY 0x02 +#define THS_WAIT 0x04 +#define THS_SUSPEND 0x08 +#define THS_WAITSUSPEND 0x0c +#define THS_DORMANT 0x10 + +/** Thread WAIT Status */ +#define TSW_NONE 0 //Thread is not in WAIT state +#define TSW_SLEEP 1 +#define TSW_SEMA 2 + +// sizeof() == 0x30 +typedef struct s_ee_thread_status{ + uint32_t status; // 0x00 + void * func; // 0x04 + void * stack; // 0x08 + uint32_t stack_size; // 0x0C + void * gp_reg; // 0x10 + uint32_t initial_priority; // 0x14 + uint32_t current_priority; // 0x18 + uint32_t attr; // 0x1C + uint32_t option; // 0x20 + uint32_t waitType; // 0x24 + uint32_t waitId; // 0x28 + uint32_t wakeupCount; // 0x2C +} ee_thread_status_t; + +/** CpuConfig options */ +enum CPU_CONFIG { + CPU_CONFIG_ENABLE_DIE = 0, //Enable Dual Issue + CPU_CONFIG_ENABLE_ICE, //Enable Instruction Cache + CPU_CONFIG_ENABLE_DCE, //Enable Data Cache + CPU_CONFIG_DISBLE_DIE, //Disable Dual Issue + CPU_CONFIG_DISBLE_ICE, //Disable Instruction Cache + CPU_CONFIG_DISBLE_DCE //Disable Data Cache +}; + +/** EnableCache & DisableCache options (multiple options may be specified) */ +#define CPU_DATA_CACHE 1 +#define CPU_INSTRUCTION_CACHE 2 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Initialization/deinitialization routines. */ +void _InitSys(void); //Run by crt0 + +void TerminateLibrary(void); //Run by crt0 + +/* Thread update functions */ +int InitThread(void); //Run by _InitSys + +int32_t iWakeupThread(int32_t thread_id ); +int32_t iRotateThreadReadyQueue(int32_t priority); +int32_t iSuspendThread(int32_t thread_id); + +/* TLB update functions */ +void InitTLBFunctions(void); //Run by _InitSys + +void InitTLB(void); +void Exit(int32_t exit_code) __attribute__((noreturn)); +int32_t ExecPS2(void *entry, void *gp, int num_args, char *args[]); +void LoadExecPS2(const char *filename, int32_t num_args, char *args[]) __attribute__((noreturn)); +void ExecOSD(int num_args, char *args[]) __attribute__((noreturn)); + +/* Alarm update functions */ +void InitAlarm(void); //Run by _InitSys + +/* libosd update functions */ +void InitExecPS2(void); //ExecPS2 patch only. Run by _InitSys, Exit, LoadExecPS2, ExecPS2 and ExecOSD +void InitOsd(void); //ExecPS2 + System Configuration patches. Please refer to the comments within libosd_full.c + +int PatchIsNeeded(void); //Indicates whether the patch is required. + +/* Glue routines. */ +int DIntr(void); +int EIntr(void); + +int EnableIntc(int intc); +int DisableIntc(int intc); +int EnableDmac(int dmac); +int DisableDmac(int dmac); + +int iEnableIntc(int intc); +int iDisableIntc(int intc); +int iEnableDmac(int dmac); +int iDisableDmac(int dmac); + +void SyncDCache(void *start, void *end); +void iSyncDCache(void *start, void *end); +void InvalidDCache(void *start, void *end); +void iInvalidDCache(void *start, void *end); + +/* System call prototypes */ +void ResetEE( uint32_t init_bitfield ); +void SetGsCrt(int16_t interlace, int16_t pal_ntsc, int16_t field); +void _Exit(int32_t exit_code) __attribute__((noreturn)); +void _LoadExecPS2(const char *filename, int32_t num_args, char *args[]) __attribute__((noreturn)); +int32_t _ExecPS2(void *entry, void *gp, int num_args, char *args[]); +void RFU009(uint32_t arg0, uint32_t arg1); +int32_t AddSbusIntcHandler(int32_t cause, void (*handler)(int call)); +int32_t RemoveSbusIntcHandler(int32_t cause); +int32_t Interrupt2Iop(int32_t cause); +void SetVTLBRefillHandler(int32_t handler_num, void* handler_func); +void SetVCommonHandler(int32_t handler_num, void* handler_func); +void SetVInterruptHandler(int32_t handler_num, void* handler_func); +int32_t AddIntcHandler(int32_t cause, int32_t(*handler_func)(int32_t cause), int32_t next); +int32_t AddIntcHandler2(int32_t cause, int32_t(*handler_func)(int32_t cause, void* arg, void* addr), int32_t next, void* arg); +int32_t RemoveIntcHandler(int32_t cause, int32_t handler_id); +int32_t AddDmacHandler(int32_t channel, int32_t (*handler)(int32_t channel), int32_t next); +int32_t AddDmacHandler2(int32_t channel, int32_t (*handler)(int32_t channel, void *arg, void *addr), int32_t next, void* arg); +int32_t RemoveDmacHandler(int32_t channel, int32_t handler_id); +int32_t _EnableIntc(int32_t cause); +int32_t _DisableIntc(int32_t cause); +int32_t _EnableDmac(int32_t channel); +int32_t _DisableDmac(int32_t channel); + +//Alarm value is in H-SYNC ticks. +int32_t SetAlarm(uint16_t time, void (*callback)(int32_t alarm_id, uint16_t time, void *common), void *common); +int32_t _SetAlarm(uint16_t time, void (*callback)(int32_t alarm_id, uint16_t time, void *common), void *common); +int32_t ReleaseAlarm(int32_t alarm_id); +int32_t _ReleaseAlarm(int32_t alarm_id); + +int32_t _iEnableIntc(int32_t cause); +int32_t _iDisableIntc(int32_t cause); +int32_t _iEnableDmac(int32_t channel); +int32_t _iDisableDmac(int32_t channel); + +int32_t iSetAlarm(uint16_t time, void (*callback)(int32_t alarm_id, uint16_t time, void *common), void *common); +int32_t _iSetAlarm(uint16_t time, void (*callback)(int32_t alarm_id, uint16_t time, void *common), void *common); +int32_t iReleaseAlarm(int32_t alarm_id); +int32_t _iReleaseAlarm(int32_t alarm_id); + +int32_t CreateThread(ee_thread_t *thread); +int32_t DeleteThread(int32_t thread_id); +int32_t StartThread(int32_t thread_id, void *args); +void ExitThread(void); +void ExitDeleteThread(void); +int32_t TerminateThread(int32_t thread_id); +int32_t iTerminateThread(int32_t thread_id); +// void DisableDispatchThread(void); // not supported +// void EnableDispatchThread(void); // not supported +int32_t ChangeThreadPriority(int32_t thread_id, int32_t priority); +int32_t iChangeThreadPriority(int32_t thread_id, int32_t priority); +int32_t RotateThreadReadyQueue(int32_t priority); +int32_t _iRotateThreadReadyQueue(int32_t priority); +int32_t ReleaseWaitThread(int32_t thread_id); +int32_t iReleaseWaitThread(int32_t thread_id); +int32_t GetThreadId(void); +int32_t _iGetThreadId(void); //This is actually GetThreadId(), used for a hack by SCE to work around the iWakeupThread design flaw. +int32_t ReferThreadStatus(int32_t thread_id, ee_thread_status_t *info); +int32_t iReferThreadStatus(int32_t thread_id, ee_thread_status_t *info); +int32_t SleepThread(void); +int32_t WakeupThread(int32_t thread_id); +int32_t _iWakeupThread(int32_t thread_id); +int32_t CancelWakeupThread(int32_t thread_id); +int32_t iCancelWakeupThread(int32_t thread_id); +int32_t SuspendThread(int32_t thread_id); +int32_t _iSuspendThread(int32_t thread_id); +int32_t ResumeThread(int32_t thread_id); +int32_t iResumeThread(int32_t thread_id); + +uint8_t RFU059(void); + +void * SetupThread(void * gp, void * stack, int32_t stack_size, void * args, void * root_func); +void SetupHeap(void * heap_start, int32_t heap_size); +void *EndOfHeap(void); + +int32_t CreateSema(ee_sema_t *sema); +int32_t DeleteSema(int32_t sema_id); +int32_t SignalSema(int32_t sema_id); +int32_t iSignalSema(int32_t sema_id); +int32_t WaitSema(int32_t sema_id); +int32_t PollSema(int32_t sema_id); +int32_t iPollSema(int32_t sema_id); +int32_t ReferSemaStatus(int32_t sema_id, ee_sema_t *sema); +int32_t iReferSemaStatus(int32_t sema_id, ee_sema_t *sema); +int32_t iDeleteSema(int32_t sema_id); +void SetOsdConfigParam(void* addr); +void GetOsdConfigParam(void* addr); +void GetGsHParam(void* addr1, void* addr2, void* addr3); +int32_t GetGsVParam(void); +void SetGsHParam(void* addr1, void* addr2, void* addr3, void* addr4); +void SetGsVParam(int32_t arg1); + +//TLB functions are only available if InitTLBFunctions() is run (Normally run by crt0). +int PutTLBEntry(unsigned int PageMask, unsigned int EntryHi, unsigned int EntryLo0, unsigned int EntryLo1); +int iPutTLBEntry(unsigned int PageMask, unsigned int EntryHi, unsigned int EntryLo0, unsigned int EntryLo1); +int _SetTLBEntry(unsigned int index, unsigned int PageMask, unsigned int EntryHi, unsigned int EntryLo0, unsigned int EntryLo1); +int iSetTLBEntry(unsigned int index, unsigned int PageMask, unsigned int EntryHi, unsigned int EntryLo0, unsigned int EntryLo1); +int GetTLBEntry(unsigned int index, unsigned int *PageMask, unsigned int *EntryHi, unsigned int *EntryLo0, unsigned int *EntryLo1); +int iGetTLBEntry(unsigned int index, unsigned int *PageMask, unsigned int *EntryHi, unsigned int *EntryLo0, unsigned int *EntryLo1); +int ProbeTLBEntry(unsigned int EntryHi, unsigned int *PageMask, unsigned int *EntryLo0, unsigned int *EntryLo1); +int iProbeTLBEntry(unsigned int EntryHi, unsigned int *PageMask, unsigned int *EntryLo0, unsigned int *EntryLo1); +int ExpandScratchPad(unsigned int page); + +void EnableIntcHandler(uint32_t cause); +void iEnableIntcHandler(uint32_t cause); +void DisableIntcHandler(uint32_t cause); +void iDisableIntcHandler(uint32_t cause); +void EnableDmacHandler(uint32_t channel); +void iEnableDmacHandler(uint32_t channel); +void DisableDmacHandler(uint32_t channel); +void iDisableDmacHandler(uint32_t channel); +void KSeg0(int32_t arg1); +int32_t EnableCache(int32_t cache); +int32_t DisableCache(int32_t cache); +uint32_t GetCop0(int32_t reg_id); +void FlushCache(int32_t operation); +uint32_t CpuConfig(uint32_t config); +uint32_t iGetCop0(int32_t reg_id); +void iFlushCache(int32_t operation); +uint32_t iCpuConfig(uint32_t config); +void SetCPUTimerHandler(void (*handler)(void)); +void SetCPUTimer(int32_t compval); + +//These two are not available in the unpatched Protokernel (Unpatched SCPH-10000 and SCPH-15000 kernels). +void SetOsdConfigParam2(void* config, int32_t size, int32_t offset); +void GetOsdConfigParam2(void* config, int32_t size, int32_t offset); + +uint64_t GsGetIMR(void); +uint64_t iGsGetIMR(void); +uint64_t GsPutIMR(uint64_t imr); +uint64_t iGsPutIMR(uint64_t imr); +void SetPgifHandler(void* handler); +void SetVSyncFlag(uint32_t *, uint64_t *); +void SetSyscall(int32_t syscall_num, void* handler); +//void _print(const char *fmt, ...); // null function + +void SifStopDma(void); //Disables SIF0 (IOP -> EE). + +uint32_t SifDmaStat( uint32_t id ); +uint32_t iSifDmaStat( uint32_t id ); +uint32_t SifSetDma( sif_dma_transfer_t *sdd, uint32_t len); +uint32_t iSifSetDma( sif_dma_transfer_t *sdd, uint32_t len); + +//Enables SIF0 (IOP -> EE). Sets channel 5 CHCR to 0x184 (CHAIN, TIE and STR). +void SifSetDChain(void); +void iSifSetDChain(void); + +//Sets/gets SIF register values (Refer to sifdma.h for a register list). +int SifSetReg(uint32_t register_num, int register_value); +int SifGetReg(uint32_t register_num); + +void _ExecOSD(int num_args, char *args[]) __attribute__((noreturn)); +int32_t Deci2Call(int32_t , uint32_t *); +void PSMode(void); +int32_t MachineType(void); +int32_t GetMemorySize(void); + +//Internal function for getting board-specific offsets, only present in later kernels (ROMVER > 20010608). +void _GetGsDxDyOffset(int mode, int *dx, int *dy, int *dw, int *dh); + +//Internal function for reinitializing the TLB, only present in later kernels. Please use InitTLB() instead to initialize the TLB with all kernels. +int _InitTLB(void); +/* (PSX only) Sets the memory size. 0 = 64MB mode, 1 = 32MB mode. The mode is only binding when either _InitTLB() or the PSX ExecPS2() syscall is called. + The stack pointer must remain in range of usable memory, or a TLB exception will occur. */ +int SetMemoryMode(int mode); //Arbitrarily named. + +void _SyncDCache(void *start, void *end); +void _InvalidDCache(void *start, void *end); + +/* stdlib - program termination */ +void abort(void) __attribute__((noreturn)); +void exit(int retval) __attribute__((noreturn)); +void _exit(int retval) __attribute__((noreturn)); + +/* errno.h */ +#ifndef errno +extern int errno __attribute__((section("data"))); +int *__errno(void); +#endif + +void *GetSyscallHandler(int syscall_no); +void *GetExceptionHandler(int except_no); +void *GetInterruptHandler(int intr_no); + +/* Helper functions for kernel patching */ +int kCopy(void *dest, const void *src, int size); +int kCopyBytes(void *dest, const void *src, int size); +int Copy(void *dest, const void *src, int size); +void setup(int syscall_num, void* handler); //alias of "SetSyscall" +void *GetEntryAddress(int syscall); + +#ifdef __cplusplus +} +#endif + +__externC uint32_t *sps2_syscall( uint32_t syscall_no, ... ); + +#endif /* __KERNEL_H__ */ diff --git a/sps2_basement/hardware/sbios/bootinfo.h b/sps2_basement/hardware/sbios/bootinfo.h new file mode 100644 index 0000000..d0fc680 --- /dev/null +++ b/sps2_basement/hardware/sbios/bootinfo.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2000 Sony Computer Entertainment Inc. + * Copyright (c) 2014 Juergen Urban + * + * SPDX-License-Identifier: GPL-2.0 + */ + +#ifndef __ASM_PS2_BOOTINFO_H +#define __ASM_PS2_BOOTINFO_H + +#include "sysconf.h" + +#define PS2_BOOTINFO_MAGIC 0x50324c42 /* "P2LB" */ +#define PS2_BOOTINFO_OLDADDR 0x01fff000 +#define PS2_BOOTINFO_MACHTYPE_PS2 0 +#define PS2_BOOTINFO_MACHTYPE_T10K 1 + +struct ps2_rtc { + uint8_t padding_1; + uint8_t sec; + uint8_t min; + uint8_t hour; + uint8_t padding_2; + uint8_t day; + uint8_t mon; + uint8_t year; +}; + +struct ps2_bootinfo { + uint32_t pccard_type; + char *opt_string; + uint32_t reserved0; + uint32_t reserved1; + struct ps2_rtc boot_time; + uint32_t mach_type; + uint32_t pcic_type; + struct ps2_sysconf sysconf; + uint32_t magic; + uint32_t size; + uint32_t sbios_base; + uint32_t maxmem; + uint32_t stringsize; + char *stringdata; + char *ver_vm; + char *ver_rb; + char *ver_model; + char *ver_ps1drv_rom; + char *ver_ps1drv_hdd; + char *ver_ps1drv_path; + char *ver_dvd_id; + char *ver_dvd_rom; + char *ver_dvd_hdd; + char *ver_dvd_path; + /* Special defines, not used anymore. */ + uint32_t initrd_start; + uint32_t initrd_size; +}; + +#define PS2_BOOTINFO_OLDSIZE ((int)(&((struct ps2_bootinfo*)0)->magic)) + +#endif /* __ASM_PS2_BOOTINFO_H */ diff --git a/sps2_basement/hardware/sbios/crt0.s b/sps2_basement/hardware/sbios/crt0.s new file mode 100644 index 0000000..ed9c325 --- /dev/null +++ b/sps2_basement/hardware/sbios/crt0.s @@ -0,0 +1,149 @@ +.set noat +.set noreorder +.global _start + +.global FlushCache +.global Exit +.global SignalSema +.global _start +.global _exit + +.text + nop + nop +FlushCache: + li $3,100 + syscall + jr $31 + nop +Exit: + li $3,4 + syscall + jr $31 + nop +SignalSema: + li $3,66 + syscall + jr $31 + nop + + nop + nop +_start: + lui $2,%hi(_args_ptr) + addiu $2,$2, %lo(_args_ptr) + sw $4,($2) +# Clear bss +zerobss: + lui $2,%hi(_fbss) + lui $3,%hi(_end) + addiu $2,$2,%lo(_fbss) + addiu $3,$3,%lo(_end) +loop: + nop + nop + sq $0,($2) + sltu $1,$2,$3 + bne $1,$0,loop + addiu $2,$2,16 + +# Thread + lui $4,%hi(_gp) + addiu $4,$4,%lo(_gp) + lui $5,%hi(_stack) + addiu $5,$5,%lo(_stack) + lui $6,%hi(_stack_size) + addiu $6,$6,%lo(_stack_size) + lui $7,%hi(_args) + addiu $7,$7,%lo(_args) + lui $8,%hi(_root) + addiu $8,$8,%lo(_root) + move $28,$4 + addiu $3,$0,60 + syscall + move $29, $2 + +# Heap + addiu $3,$0,61 + lui $4,%hi(_end) + addiu $4,$4,%lo(_end) + lui $5,%hi(_heap_size) + addiu $5,$5,%lo(_heap_size) + syscall + nop + +# Cache + jal FlushCache + move $4,$0 + +# Jump main + ei + + lui $2,%hi(_args_ptr) + addiu $2,$2,%lo(_args_ptr) + lw $3,($2) + lui $2,%hi(_args) + addiu $2,$2,%lo(_args) + + lw $4, ($2) + jal main + addiu $5, $2, 4 +_root: +_exit: +# ??? + lui $2,%hi(_args_ptr) + addiu $2,$2,%lo(_args_ptr) + lw $3,($2) + jal SignalSema + lw $4,($3) +# Exit + addiu $3,$0,35 + syscall + nop + +# The following is take from 3stars by Duke: + + .globl Init_GS + .align 4 + +Init_GS: + lui $2,0x1fc8 + lb $2,-0xae($2) + li $3,'E' + li $6,2 # 2=NTSC, 3=PAL + beql $2,$3,pal_mode + addiu $6,1 +pal_mode: + li $5,1 # 0=NON, 1=INTERLACE + li $7,0 # 1=frame, 2=field + + + addu $17,$5,$0 + addu $18,$6,$0 + addu $19,$7,$0 + li $3,0x12001000 + li $2,0x00000200 + sd $2,0($3) # write 0x200 to 0x12001000 (=GS reset) + li $4,0x0000FF00 + ld $2,0($3) + dsrl $2,16 + andi $2,0xFF + li $3,0x71 # PutIMR(kernel) + syscall + nop + andi $4,$17,1 + andi $5,$18,0xFF + andi $6,$19,1 + li $3,2 # SetGsCrt(kernel) + syscall + jr $31 + nop + + + .bss + .align 6 +_args: .space 256+16*4+4 + + .data +_args_ptr: + .space 4 diff --git a/sps2_basement/hardware/sbios/fileio.h b/sps2_basement/hardware/sbios/fileio.h new file mode 100644 index 0000000..e106ad8 --- /dev/null +++ b/sps2_basement/hardware/sbios/fileio.h @@ -0,0 +1,73 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (C)2001, Gustavo Scotti (gustavo@scotti.com) +# (c) 2003 Marcus R. Brown (mrbrown@0xd6.org) +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * EE FILE IO handling + */ + +#ifndef __FILEIO_H__ +#define __FILEIO_H__ + +#include + +#ifndef NEWLIB_PORT_AWARE +#error "Using fio/fileXio functions directly in the newlib port will lead to problems." +#error "Use posix function calls instead." +#endif + +#define FIO_PATH_MAX 256 + +#define FIO_WAIT 0 +#define FIO_NOWAIT 1 + +#define FIO_COMPLETE 1 +#define FIO_INCOMPLETE 0 + +#define EOF (-1) + +#ifdef __cplusplus +extern "C" { +#endif + +int fioInit(void); +void fioExit(void); +int fioOpen(const char *fname, int mode); +int fioClose( int fd); +int fioRead( int fd, void *buff, int buff_size); +int fioWrite( int fd, const void *buff, int buff_size); +int fioLseek( int fd, int offset, int whence); +int fioMkdir(const char* dirname); +int fioPutc(int fd,int c); +int fioGetc(int fd); +int fioGets(int fd, char* buff, int n); +void fioSetBlockMode(int blocking); +int fioSync(int mode, int *retVal); +int fioIoctl(int fd, int request, void *data); +int fioDopen(const char *name); +int fioDclose(int fd); +int fioDread(int fd, io_dirent_t *buf); //Warning! (*) +int fioGetstat(const char *name, io_stat_t *buf); //Warning! (*) +int fioChstat(const char *name, io_stat_t *buf, unsigned int cbit); +int fioRemove(const char *name); //Warning! (**) +int fioFormat(const char *name); +int fioRmdir(const char* dirname); + +/* * Function is unstable; does not suspend interrupts prior to performing DMA transfers on the IOP side. + ** Function is broken; falls through to the next case (mkdir) upon completion. + + Patches are available to fix these issues. Otherwise, please use fileXio instead. */ + +#ifdef __cplusplus +} +#endif + +#endif /* __FILEIO_H__ */ diff --git a/sps2_basement/hardware/sbios/iopcontrol.h b/sps2_basement/hardware/sbios/iopcontrol.h new file mode 100644 index 0000000..3d4ea45 --- /dev/null +++ b/sps2_basement/hardware/sbios/iopcontrol.h @@ -0,0 +1,48 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (c) 2003 Marcus R. Brown (mrbrown@0xd6.org) +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOP reset and status routines. + */ + +#ifndef __IOPCONTROL_H__ +#define __IOPCONTROL_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/** Resets IOP + * This is a high level wrapper for SifIopReset + * @param arg a const character pointer for path to module that will be loaded afterwards or an empty string. NULL must not be specified. + * @return 1 for success or 0 for failure. + */ +int SifIopReboot(const char *arg); +/** Resets IOP + * @param arg a const character pointer for path to module that will be loaded afterwards or a blank. NULL is not officially supported, but is supported for backward-compatibility with old homebrew projects. + * @param mode Bitmask for optional settings. 0x80000000 for verbose messages and 0x100 for magicgate. + * @return 1 for success or 0 for failure. + */ +int SifIopReset(const char *arg, int mode); +/** + * @return 1 for SIF initialized or 0 for not initialized. + */ +int SifIopIsAlive(void); +/** + * @return 1 for bootup complete or 0 for incomplete. + */ +int SifIopSync(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __IOPCONTROL_H__ */ diff --git a/sps2_basement/hardware/sbios/iopheap.h b/sps2_basement/hardware/sbios/iopheap.h new file mode 100644 index 0000000..5cdedf7 --- /dev/null +++ b/sps2_basement/hardware/sbios/iopheap.h @@ -0,0 +1,35 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOP heap handling prototypes + */ + +#ifndef __IOPHEAP_H__ +#define __IOPHEAP_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +int SifInitIopHeap(void); +void SifExitIopHeap(void); + +void * SifAllocIopHeap(int size); +int SifFreeIopHeap(void *addr); + +int SifLoadIopHeap(const char *path, void *addr); + +#ifdef __cplusplus +} +#endif + +#endif /* __IOPHEAP_H__ */ diff --git a/sps2_basement/hardware/sbios/linkfile b/sps2_basement/hardware/sbios/linkfile new file mode 100644 index 0000000..c07af94 --- /dev/null +++ b/sps2_basement/hardware/sbios/linkfile @@ -0,0 +1,52 @@ +_stack_size = 0x80000; +_heap_size = 1024*1024*10; + +ENTRY(_start); +SECTIONS { + + .text 0x400000 : { + *(.rodata) + *(.text) + } + .reginfo ALIGN(128) : { + *(.reginfo) + } + .data ALIGN(128) : { + *(.data) + } + .rdata ALIGN(128) : { + *(.rdata) + } + _gp = ALIGN(128) + 0x7ff0; + .lit4 ALIGN(128) : { + *(.lit4) + } + .lit8 ALIGN(128) : { + *(.lit8) + } + .sdata ALIGN(128) : { + *(.sdata) + } + + .sbss ALIGN(128) (NOLOAD) : { /* uninitialized data */ + _fbss = . ; + *(.scommon) + *(.sbss) + } + .bss ALIGN(128) (NOLOAD) : { /* uninitialized data */ + *(.bss) + } + .COMMON ALIGN(128) (NOLOAD) : { /* uninitialized data */ + *(COMMON) + } + _end_bss = . - 4; + _stack = .; + . += _stack_size ; + _end_stack = . - 8*5; + _end = . ; + __lc_bh = . ; + . += _heap_size ; + __lc_eh = .; + +} + diff --git a/sps2_basement/hardware/sbios/loadfile.h b/sps2_basement/hardware/sbios/loadfile.h new file mode 100644 index 0000000..3390ac9 --- /dev/null +++ b/sps2_basement/hardware/sbios/loadfile.h @@ -0,0 +1,343 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (c) 2003 Marcus R. Brown (mrbrown@0xd6.org) +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOP executable file loader. + */ + +#ifndef __LOADFILE_H__ +#define __LOADFILE_H__ + +#include + +#define LF_PATH_MAX 252 +#define LF_ARG_MAX 252 + +enum _lf_val_types { + LF_VAL_BYTE = 0, + LF_VAL_SHORT, + LF_VAL_LONG +}; + +enum _lf_functions { + LF_F_MOD_LOAD = 0, + LF_F_ELF_LOAD, + + LF_F_SET_ADDR, + LF_F_GET_ADDR, + + LF_F_MG_MOD_LOAD, + LF_F_MG_ELF_LOAD, + + LF_F_MOD_BUF_LOAD, + + LF_F_MOD_STOP, + LF_F_MOD_UNLOAD, + + LF_F_SEARCH_MOD_BY_NAME, + LF_F_SEARCH_MOD_BY_ADDRESS, +}; + +typedef struct +{ + u32 epc; + u32 gp; + u32 sp; + u32 dummy; +} t_ExecData; + +/* Extended error codes */ +/** Could not bind with RPC server */ +#define SCE_EBINDMISS 0x10000 +/** Could not call the RPC function */ +#define SCE_ECALLMISS 0x10001 +/** ELF/Module load failed */ +#define SCE_ELOADMISS 0x10003 + +#ifdef __cplusplus +extern "C" { +#endif + +/** Initialize the LOADFILE library. + * @ingroup loadfile + * + * @returns 0 on success, E_SIF_RPC_BIND if unable to connect to the server. + * + * Initializes the LOADFILE API and binds to the remote LOADFILE RPC server. + */ +int SifLoadFileInit(void); +/** Reset the LOADFILE library. + * @ingroup loadfile + * + * Deinitializes the LOADFILE library in preparation of an IOP reset. + */ +void SifLoadFileExit(void); + +/** Load and execute an IRX module. + * @ingroup loadfile + * + * @param path Path to an IRX module + * @param arg_len Length, in bytes, of the argument list + * @param args List of arguments to pass to the IRX on startup + * + * @returns The ID of the loaded module on success, or an error if the module + * couldn't be loaded. + * + * Loads an IRX module from the specified path, and executes it. The args + * parameter specifies a list of arguments that are passed to the loaded module + * as the argv[] array. Each argument string in args must be seperated by NUL ('\\0'). + * Pass the length of the entire args list, including the NUL seperators in the args_len + * parameter. + * + * @note By default, modules cannot be loaded directly from the memory card. If you need to + * load modules from the memory card, you should use ::SifExecModuleFile or link with the + * sbv-lite library (http://www.0xd6.org). + * + * @see SifExecModuleFile + */ +int SifLoadModule(const char *path, int arg_len, const char *args); +/** Load and execute and IRX module, and retrieve the module's load status. + * @ingroup loadfile + * + * @param path Path to an IRX module + * @param arg_len Length, in bytes, of the argument list + * @param args List of arguments to pass to the IRX on startup + * @param mod_res Pointer to a variable that will store the return value from the IRX's _start() function + * + * @returns The ID of the loaded module on success, or an error if the module + * couldn't be loaded. + * + * Loads an IRX module from the specified path, and executes it. See ::SifLoadModule for + * details on the arg_len and args parameters. If mod_res is non-NULL, the result code from + * the module's _start() function is stored here. + * + * @see SifLoadModule + */ +int SifLoadStartModule(const char *path, int arg_len, const char *args, int *mod_res); + +/** Load and execute an IRX module encrypted with MagicGate. + * @ingroup loadfile + * + * @param path Path to an IRX module + * @param arg_len Length, in bytes, of the argument list + * @param args List of arguments to pass to the IRX on startup + * + * @returns The ID of the loaded module on success, or an error if the module + * couldn't be loaded. + * + * There is no real use for this function; it is only included in ps2lib for completeness. + * + * @see SifLoadModule + */ +int SifLoadModuleEncrypted(const char *path, int arg_len, const char *args); + +/** Load and execute an IRX module from a buffer in IOP RAM. + * @ingroup loadfile + * + * @param ptr Pointer to a buffer in IOP RAM where the IRX module will be loaded from + * @param arg_len Length, in bytes, of the argument list + * @param args List of arguments to pass to the IRX on startup + * + * @returns The ID of the loaded module on success, or an error if the module couldn't + * be loaded. + * + * Loads an IRX module from a buffer located in IOP RAM. See ::SifLoadModule for details on + * the arg_len and args parameters. + * + * @note If you need to load an IRX module onto the IOP directly from a buffer in EE RAM, then + * use ::SifExecModuleBuffer. + * + * @see SifLoadModule, SifExecModuleBuffer + */ +int SifLoadModuleBuffer(void *ptr, int arg_len, const char *args); +/** Load and execute an IRX module from a buffer in IOP RAM, and retrieve the module's load status. + * @ingroup loadfile + * + * @param ptr Pointer to a buffer in IOP RAM where the IRX module will be loaded from + * @param arg_len Length, in bytes, of the argument list + * @param args List of arguments to pass to the IRX on startup + * @param mod_res Pointer to a variable that will store the return value from the IRX's _start() function + * + * @returns The ID of the loaded module on success, or an error if the module + * couldn't be loaded. + * + * Loads an IRX module from a buffer located in IOP RAM. See ::SifLoadModule for details on + * the arg_len and args parameters. If mod_res is non-NULL, the result code from the module's + * _start() function is stored here. + * + * @note If you need to load an IRX module onto the IOP directly from a buffer in EE RAM, then + * use ::SifExecModuleBuffer. + * + * @see SifLoadModule, SifExecModuleBuffer + */ +int SifLoadStartModuleBuffer(void *ptr, int arg_len, const char *args, int *mod_res); + +int SifStopModule(int id, int arg_len, const char *args, int *mod_res); +int SifUnloadModule(int id); +int SifSearchModuleByName(const char *name); +int SifSearchModuleByAddress(const void *ptr); + +/** Load the specified section of an ELF executable into EE RAM. + * @ingroup loadfile + * + * @param path Path to an ELF executable + * @param secname The name of a single section to load from the ELF, or "all" to load all sections + * @param data Pointer to a variable that will store information about the loaded executable + * + * @returns 0 on success, or an error code if an error occurred. + * + * Loads the section secname from the ELF file specified by path into EE RAM. + * + * data points to a t_ExecData structure where information about the loaded + * section will be returned. + * + * @warning Don't ever use this function, it does not work as intended. + */ +int SifLoadElfPart(const char *path, const char *secname, t_ExecData *data); +/** Load an ELF executable into EE RAM. + * @ingroup loadfile + * + * @param path Path to an ELF executable + * @param data Pointer to a variable that will store information about the loaded executable + * + * @returns 0 on success, or an error code if an error occurred. + * + * Loads the ELF executable specified by path into EE RAM. data points to a + * t_ExecData structure where information about the loaded executable will be returned. + * + * @warning It's possible to overwrite your program if the ELF that you're trying to + * load overlaps your program's memory space. Always ensure that the target ELF will + * load before or after your program's code and data addresses. + */ +int SifLoadElf(const char *path, t_ExecData *data); +/** Load a MagicGate-encrypted ELF executable into EE RAM. + * @ingroup loadfile + * + * @param path Path to an ELF executable + * @param data Pointer to a variable that will store information about the loaded executable + * + * @returns 0 on success, or an error code if an error occurred. + * + * There is no real use for this function; it is only included in ps2lib for completeness. + * + * @see SifLoadElf + */ +int SifLoadElfEncrypted(const char *path, t_ExecData *data); + +/** Write a value to an address within the IOP's memory space. + * @ingroup loadfile + * + * @param iop_addr Address to modify in the IOP's address space + * @param val Data to write at iop_addr + * @param type A type describing the size of the val argument + * + * @returns Previous value at iop_addr on success (?), or an error code if an + * error occurred. + * + * Writes the data passed in val to the IOP address specified by iop_addr. Use + * the following types specify the size of data write: + * - ::LF_VAL_BYTE to write an 8-bit value + * - ::LF_VAL_SHORT to write a 16-bit value + * - ::LF_VAL_LONG to write a 32-bit value + * + * @note Because iop_addr can be any address within the IOP's address space, it's + * possible to modify IOP hardware registers. However, in most cases the EE can + * modify the IOP's hardware registers directly so there is little use for this function. + * + * @see SifIopGetVal + */ +int SifIopSetVal(u32 iop_addr, int val, int type); +/** Read a value from an address within the IOP's memory space. + * @ingroup loadfile + * + * @param iop_addr Address within the IOP's address space to read from + * @param val Pointer to a variable that stores the value read + * @param type A type describing the size of the data to read + * + * @returns 0 on success, or an error code if an error occurred. + * + * Reads data of the size specified by type from the IOP address specified by + * iop_addr. Use the following types to specify the size of the data to read: + * - ::LF_VAL_BYTE to write an 8-bit value + * - ::LF_VAL_SHORT to write a 16-bit value + * - ::LF_VAL_LONG to write a 32-bit value + * + * @note Because iop_addr can be any address within the IOP's address space, it's + * possible to read from IOP hardware registers. However, in most cases the EE can + * read the IOP's hardware registers directly so there is little use for this function. + * @see SifIopSetVal + */ +int SifIopGetVal(u32 iop_addr, void *val, int type); + +/** Transfer an IRX module from EE RAM to IOP RAM and execute it. + * @ingroup loadfile + * + * @param ptr Pointer to a buffer in EE RAM where the IRX module will be loaded from + * @param size Size of the buffer in EE RAM that contains the IRX module + * @param arg_len Length, in bytes, of the argument list + * @param args List of arguments to pass to the IRX on startup + * @param mod_res Pointer to a variable that will store the return value from the IRX's _start() function + * + * @returns The ID of the loaded module on success, or an error if the module couldn't + * be loaded. + * + * Transfers an IRX module stored in a buffer in EE RAM to the IOP, and calls ::SifLoadModuleBuffer to + * load and execute the module. See ::SifLoadModule for details on the arg_len and args parameters. + * If mod_res is non-NULL, the result code from the module's _start() function is stored here. + * + * @see SifLoadModule, SifLoadModuleBuffer + */ +int SifExecModuleBuffer(void *ptr, u32 size, u32 arg_len, const char *args, int *mod_res); +/** Read an IRX module from a file into IOP RAM and execute it. + * @ingroup loadfile + * + * @param path Path to an IRX module + * @param arg_len Length, in bytes, of the argument list + * @param args List of arguments to pass to the IRX on startup + * @param mod_res Pointer to a variable that will store the return value from the IRX's _start() function + * + * @returns The ID of the loaded module on success, or an error if the module + * couldn't be loaded. + * + * Loads an IRX module from the specified path into a buffer on the IOP, then calls ::SifLoadModuleBuffer + * to load and execute the module. See ::SifLoadModule for details on the arg_len and args parameters. + * This function is useful if you need to load an IRX module from a prohibited device, such as the memory card. + * + * @see SifLoadModule, SifLoadModuleBuffer + */ +int SifExecModuleFile(const char *path, u32 arg_len, const char *args, int *mod_res); + + +/** Low-level function for loading and executing an IRX module. + * @ingroup loadfile + * + * @param path Path to an IRX module + * @param arg_len Length, in bytes, of the argument list + * @param args List of arguments to pass to the IRX on startup + * @param *modres Pointer to a variable that will store the return value from the IRX's _start() function + * @param fno Function number of function to execute. + * @param dontwait Whether to wait for the module's _start function to finish executing. + * + * @returns The ID of the loaded module on success, or an error if the module + * couldn't be loaded. + * + * Unless required, use the higher-level functions instead. + * + * @see SifLoadModule, SifLoadModuleBuffer, SifLoadModuleEncrypted + */ +int _SifLoadModule(const char *path, int arg_len, const char *args, + int *modres, int fno, int dontwait); + +#ifdef __cplusplus +} +#endif + +#endif /* __LOADFILE_H__ */ diff --git a/sps2_basement/hardware/sbios/osd_config.h b/sps2_basement/hardware/sbios/osd_config.h new file mode 100644 index 0000000..36f7c13 --- /dev/null +++ b/sps2_basement/hardware/sbios/osd_config.h @@ -0,0 +1,217 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * PS2 Configuration settings + * Note: the 'set' methods are only valid till the ps2 gets + * turned off or reset! + * + * Note 2: Early Japanese consoles (The SCPH-10000 and SCPH-15000) have kernels based on older specifications. + * The SCPH-18000 has the same kernel as the first expansion bay model (SCPH-30000). + * The early kernels can be modernized if patched. + * Newer games will automatically patch ExecPS2 of such a kernel when they detect one, + * although only HDDOSDs will fully patch kernel completely (causes the kernel to appear as a newer kernel to everything). + */ + +#ifndef __OSD_CONFIG_H__ +#define __OSD_CONFIG_H__ + +#include +#ifndef OSD_CONFIG_NO_LIBCDVD +#include +#endif + +/** language values returned and used by: configGetLanguage() and configSetLanguage() */ +enum OSD_LANGUAGES{ + LANGUAGE_JAPANESE = 0, + LANGUAGE_ENGLISH, + LANGUAGE_FRENCH, + LANGUAGE_SPANISH, + LANGUAGE_GERMAN, + LANGUAGE_ITALIAN, + LANGUAGE_DUTCH, + LANGUAGE_PORTUGUESE, + /* Language values after here are not officially documented. + Are supported by neither this library nor the original Sony libscf library, + but can be found in the MECHACON's NVRAM and are used exclusively by the OSDs of consoles that support these languages. + However, these consoles will always specify English within ConfigParam. + + When ConfigParam.version is 2, the true language can be found in Config2Param.language. */ + LANGUAGE_RUSSIAN, + LANGUAGE_KOREAN, + LANGUAGE_TRAD_CHINESE, + LANGUAGE_SIMPL_CHINESE +}; + +/** tv screen values returned by: int getTvScreenType(void) */ +enum TV_SCREEN_TYPES{ + TV_SCREEN_43 = 0, + TV_SCREEN_FULL, + TV_SCREEN_169 +}; + +/** Video output type values */ +enum VIDEO_OUTPUT_TYPES{ + VIDEO_OUTPUT_RGB = 0, + VIDEO_OUTPUT_COMPONENT +}; + +/** date format values returned by: int getDateFormat(void) */ +enum DATE_FORMAT_TYPES{ + DATE_YYYYMMDD = 0, + DATE_MMDDYYYY, + DATE_DDMMYYYY +}; + +/** Time format values returned by: int getTimeFormat(void) */ +enum TIME_FORMAT_TYPES{ + TIME_24H = 0, + TIME_12H, +}; + +/** parameter struct as used by GetOsdConfigParam/SetOsdConfigParam */ +typedef struct { + /** 0=enabled, 1=disabled */ +/*00*/u32 spdifMode:1; + /** 0=4:3, 1=fullscreen, 2=16:9 */ +/*01*/u32 screenType:2; + /** 0=rgb(scart), 1=component */ +/*03*/u32 videoOutput:1; + /** 0=japanese, 1=english(non-japanese) */ +/*04*/u32 japLanguage:1; + /** Playstation driver settings. */ +/*05*/u32 ps1drvConfig:8; + /** 0 = early Japanese OSD, 1 = OSD2, 2 = OSD2 with extended languages. Early kernels cannot retain the value set in this field (Hence always 0). */ +/*13*/u32 version:3; + /** LANGUAGE_??? value */ +/*16*/u32 language:5; + /** timezone minutes offset from gmt */ +/*21*/u32 timezoneOffset:11; +} ConfigParam; + +/** parameter struct as used by GetOsdConfigParam2/SetOsdConfigParam2 + * (Not supported by unpatched, early kernels. Do NOT invoke GetOsdConfigParam2 or SetOsdConfigParam2 on one!) + */ +typedef struct { +/*00*/u8 format; + +/*00*/u8 reserved:4; + /** 0=standard(winter), 1=daylight savings(summer) */ +/*04*/u8 daylightSaving:1; + /** 0=24 hour, 1=12 hour */ +/*05*/u8 timeFormat:1; + /** 0=YYYYMMDD, 1=MMDDYYYY, 2=DDMMYYYY */ +/*06*/u8 dateFormat:2; + +//Only used if ConfigParam.version = 2 + /** Set to 2 */ +/*00*/u8 version; + /** The true language, unlike the one from ConfigParam */ +/*00*/u8 language; +} Config2Param; + +#ifdef __cplusplus +extern "C" { +#endif + +/** get the language the ps2 is currently set to + * @return Language value (See OSD_LANGUAGES above) + */ +int configGetLanguage(void); +/** sets the default language of the ps2 + * @param language Language value (See OSD_LANGUAGES above) + */ +void configSetLanguage(int language); + + +/** get the tv screen type the ps2 is setup for + * @return 0 = 4:3; 1 = fullscreen; 2 = 16:9 + */ +int configGetTvScreenType(void); +/** set the tv screen type + * @param screenType 0 = 4:3; 1 = fullscreen; 2 = 16:9 + */ +void configSetTvScreenType(int screenType); + + +/** gets the date display format + * @return 0 = yyyy/mm/dd; 1 = mm/dd/yyyy; 2 = dd/mm/yyyy + */ +int configGetDateFormat(void); +/** sets the date display format + * @param dateFormat 0 = yyyy/mm/dd; 1 = mm/dd/yyyy; 2 = dd/mm/yyyy + */ +void configSetDateFormat(int dateFormat); + + +/** gets the time display format + * (whether 24hour time or not) + * @return 0 = 24hour; 1 = 12hour + */ +int configGetTimeFormat(void); +/** sets the time display format + * (whether 24hour time or not) + * @param timeFormat 0 = 24hour; 1 = 12hour + */ +void configSetTimeFormat(int timeFormat); + +/** get timezone + * @return offset in minutes from GMT + */ +int configGetTimezone(void); +/** set timezone +* @param offset offset in minutes from GMT + */ +void configSetTimezone(int offset); + +/** checks whether the spdif is enabled or not + * @return 1 = on; 0 = off + */ +int configIsSpdifEnabled(void); +/** sets whether the spdif is enabled or not + * @param enabled 1 = on; 0 = off + */ +void configSetSpdifEnabled(int enabled); + +/** checks whether daylight saving is currently set + * @return 1 = on; 0 = off + */ +int configIsDaylightSavingEnabled(void); +/** sets daylight saving + * @param enabled 1 = on; 0 = off + */ +void configSetDaylightSavingEnabled(int enabled); + +#ifndef OSD_CONFIG_NO_LIBCDVD +/** converts the time returned from the ps2's clock into GMT time + * (ps2 clock is in JST time) + */ +void configConvertToGmtTime(sceCdCLOCK* time); + +/** converts the time returned from the ps2's clock into LOCAL time + * (ps2 clock is in JST time) + */ +void configConvertToLocalTime(sceCdCLOCK* time); +#endif + +// Internal functions. +/** check if ps2 has a 'Protokernel' (Really early Japanese models) + * + * @param config unsigned int config value from GetOsdConfigParam() syscall + * @return 1 if early jap model; 0 if not + */ +int IsEarlyJap(ConfigParam config); + +#ifdef __cplusplus +} +#endif + +#endif /* __OSD_CONFIG_H__ */ diff --git a/sps2_basement/hardware/sbios/ps2.c b/sps2_basement/hardware/sbios/ps2.c new file mode 100644 index 0000000..4fad422 --- /dev/null +++ b/sps2_basement/hardware/sbios/ps2.c @@ -0,0 +1,391 @@ +/* + * Copyright (C) 2014 Juergen Urban + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "bootinfo.h" +#include "sbios.h" + +/* EE SIO registers */ +#define EE_SIO_BASE 0x1000f100 +#define EE_SIO_SIZE 0x100 + +#define EE_SIO_LCR 0x1000f100 /* Line Control Register */ +#define LCR_UMODE_8BIT 0x00 +#define LCR_UMODE_7BIT 0x01 +#define LCR_USBL_1BIT 0x00 /* UART Stop Bit Length */ +#define LCR_USBL_2BITS 0x04 +#define LCR_UPEN_OFF 0x00 /* UART Parity Enable */ +#define LCR_UPEN_ON 0x08 +#define LCR_UEPS_ODD 0x00 /* UART Even Parity Select */ +#define LCR_UEPS_EVEN 0x10 +#define LCR_SCS_VAL 0x20 /* Baud rate generator output that divided CPUCLK */ + +#define EE_SIO_LSR 0x1000f110 /* Line Status Register */ +#define LSR_OE 0x02 /* Overrun error */ +#define LSR_PE 0x04 /* Parity error */ +#define LSR_FE 0x08 /* Framing error */ + +#define EE_SIO_IER 0x1000f120 /* Interrupt Enable Register */ +#define IER_RX_DATA 0x0001 +#define IER_TX_EMPTY 0x0002 +#define IER_BI 0x0004 /* Break signal */ + +#define EE_SIO_ISR 0x1000f130 /* Interrupt Status Register */ +#define ISR_RX_DATA 0x0001 +#define ISR_TX_EMPTY 0x0002 +#define ISR_BI 0x0004 /* Break signal */ +#define ISR_TXFIFO_MASK 0xf000 +#define ISR_TXFIFO_FULL 0x8000 +#define ISR_RXFIFO_MASK 0x0f00 + +#define EE_SIO_FCR 0x1000f140 /* FIFO Control Register */ +#define FCR_FRSTE 0x01 /* FIFO Reset Enable */ +#define FCR_RFRST 0x02 /* RX FIFO Reset */ +#define SIO_FCR_TFRST 0x04 /* TX FIFO Reset */ + +#define SIO_BGR 0x1000f150 /* Baud Rate Control Register */ + +#define EE_SIO_TXFIFO 0x1000f180 +#define EE_SIO_RXFIFO 0x1000f1c0 + +#define EE_DMAC_SIF0_CHCR 0x1000c000 +#define CHCR_STR 0x0100 + +#define SBIOS_BASE 0x80001000 +#define SBIOS_MAGIC 0x80001004 +#define SBIOS_MAGICVAL 0x62325350 + +/* Base address for IOP memory. */ +#define PS2_IOP_HEAP_BASE 0x1c000000 +#define PS2_IOP_HEAP_END 0x20000000 + +DECLARE_GLOBAL_DATA_PTR; + +int sbios(int func, void *arg) +{ + extern int sbios_call(int, void *, void *); + + if (gd->arch._sbios == NULL) { + error("SBIOS not found\n"); + return -1; + } + return sbios_call(func, arg, gd->arch._sbios); +} + +phys_size_t initdram(int board_type) +{ + return CONFIG_SYS_MEM_SIZE; +} + +static void check_sif_irq(void) +{ + if (inl(EE_DMAC_SIF0_CHCR) & CHCR_STR) { + /* DMA not finished, no interrupt. */ + return; + } + + /* Emulate interrupt. */ + sbios(SB_SIFCMDINTRHDLR, NULL); +} + +static void rpc_wakeup(void *p, int result) +{ + volatile int *woken; + + woken = (int *) p; + *woken = 1; +} + +static int sbios_rpc(int func, void *arg, int *result) +{ + int ret; + struct sbr_common_arg carg; + volatile int woken = 0; + + carg.arg = arg; + carg.func = rpc_wakeup; + carg.para = (void *) &woken; + carg.result = -1; + + do { + debug("Call SBIOS %d\n", func); + ret = sbios(func, &carg); + debug("ret = %d\n", ret); + switch (ret) { + case 0: + break; + case -SIF_RPCE_SENDP: + /* resource temporarily unavailable */ + + /* Time to check for interrupts. */ + check_sif_irq(); + break; + default: + *result = ret; + error("sbios_rpc: RPC failed, func=%d result=%d\n", func, ret); + return ret; + } + } while (ret < 0); + + while(woken == 0) { + debug("check_sif_irq\n"); + + /* Time to check for interrupts. */ + check_sif_irq(); + } + debug("carg.result %d\n", carg.result); + + *result = carg.result; + + return 0; +} + +static void driver_init(void) +{ + int rv; + int result; + + rv = sbios(SB_SIFINIT, NULL); + if (rv < 0) { + error("SB_SIFINIT failed rv = %d\n", rv); + return; + } + + rv = sbios(SB_SIFINITCMD, NULL); + if (rv < 0) { + error("SB_SIFINITCMD failed rv = %d\n", rv); + return; + } + + rv = sbios(SB_SIFINITRPC, NULL); + if (rv < 0) { + error("SB_SIFINITRPC failed rv = %d\n", rv); + return; + } + + for (;;) { + debug("Call SBR_IOPH_INIT\n"); + rv = sbios_rpc(SBR_IOPH_INIT, NULL, &result); + debug("rv = %d\n", rv); + if (rv < 0) { + error("SBR_IOPH_INIT failed rv = %d\n", rv); + return; + } + debug("result = %d\n", result); + if (result == 0) { + /* Success */ + break; + } + } + debug("SBIOS drivers successfully initialized.\n"); +} + +int checkboard(void) +{ + struct ps2_bootinfo *info = (void *) CKSEG0ADDR(PS2_BOOTINFO_OLDADDR); + uint32_t size; + volatile uint32_t *sbios_magic; + int sbversion = 0; + struct ps2_bootinfo bootinfo; + + puts("Board: Sony Playstation 2 MIPS r5900\n"); + memset(&bootinfo, 0, sizeof(bootinfo)); + size = info->size; + if (size > sizeof(bootinfo)) { + size = sizeof(bootinfo); + } + memcpy(&bootinfo, info, size); + + sbios_magic = (uint32_t *) SBIOS_MAGIC; + if (*sbios_magic == SBIOS_MAGICVAL) { + gd->arch._sbios = *(int (**)(int, void *))(SBIOS_BASE); + } + else + gd->arch._sbios = NULL; + + sbversion = sbios(SB_GETVER, NULL); + printf("SBIOS Version 0x%08x\n", sbversion); + + driver_init(); + return 0; +} + +int board_eth_init(bd_t *bis) +{ + /* TBD */ + return 0; +} + +void _machine_restart(void) +{ + struct sb_halt_arg arg; + + arg.mode = SB_HALT_MODE_PWROFF; + sbios(SB_HALT, &arg); +} + +int board_early_init_f(void) +{ + return 0; +} + +int sio_start(void) +{ + return 0; +} + +int sio_stop(void) +{ + return 0; +} + +void sio_setbrg(void) +{ + /* TBD: Configure baudrate */ +} + +int sio_getc(void) +{ + uint32_t isr; + uint8_t ch; + + while((((isr = inl(EE_SIO_ISR)) & ISR_RXFIFO_MASK) >> 8) == 0) { + /* Wait for input */ + } + ch = inb(EE_SIO_RXFIFO); + return ch; +} + +int sio_tstc(void) +{ + /* Return number of characters in RX FIFO. */ + return (((inl(EE_SIO_ISR)) & ISR_RXFIFO_MASK) >> 8); +} + +void sio_putc(const char c) +{ + if (c == '\n') + sio_putc('\r'); + while ((inl(EE_SIO_ISR) & ISR_TXFIFO_MASK) == ISR_TXFIFO_FULL) { + /* Wait until data can be send. */ + }; + outb(c, EE_SIO_TXFIFO); +} + +void sio_puts(const char *s) +{ + while(*s != 0) { + sio_putc(*s); + s++; + } +} + +struct serial_device sio_device = { + .name = "PS2SIO", + .start = sio_start, + .stop = sio_stop, + .setbrg = sio_setbrg, + .getc = sio_getc, + .tstc = sio_tstc, + .putc = sio_putc, + .puts = sio_puts, +}; + +struct serial_device *default_serial_console(void) +{ + set_io_port_base(CKSEG1ADDR(0)); + return &sio_device; +} + +void rtc_reset (void) +{ + /* TBD */ + return; +} + +int rtc_get (struct rtc_time *tmp) +{ + /* TBD */ + return 0; +} + +int rtc_set (struct rtc_time *tmp) +{ + /* TBD */ + return 0; +} + +/** Allocate bus address. Returns 0 on error. */ +uint32_t ps2sif_allociopheap(int size) +{ + struct sbr_ioph_alloc_arg arg; + int result; + int err; + + arg.size = size; + err = sbios_rpc(SBR_IOPH_ALLOC, &arg, &result); + + if (err < 0) { + return 0; + } + return result; +} + +int ps2sif_freeiopheap(uint32_t busaddr) +{ + struct sbr_ioph_free_arg arg; + int result; + int err; + + arg.addr = busaddr; + err = sbios_rpc(SBR_IOPH_FREE, &arg, &result); + + if (err < 0) { + return -1; + } + return result; +} + +uint32_t ps2sif_phystobus(uint32_t physaddr) +{ + if (physaddr <= PS2_IOP_HEAP_BASE) { + error("Bad physical address 0x%08x used\n", + physaddr); + } + if (physaddr >= PS2_IOP_HEAP_END) { + error("Bad physical address 0x%08x used\n", + physaddr); + } + return (physaddr - PS2_IOP_HEAP_BASE); +} + +/** Converts iopheap bus addr to phys addr for use with inl() and outl(). */ +uint32_t ps2sif_bustophys(uint32_t busaddr) +{ + uint32_t physaddr; + + assert(busaddr != 0); + + physaddr = busaddr + PS2_IOP_HEAP_BASE; + if (physaddr < PS2_IOP_HEAP_BASE) { + error("Bad bus address 0x%08x used\n", + busaddr); + } + if (physaddr >= PS2_IOP_HEAP_END) { + error("Bad bus address 0x%08x used\n", + busaddr); + } + return physaddr; +} diff --git a/sps2_basement/hardware/sbios/rom0_info.h b/sps2_basement/hardware/sbios/rom0_info.h new file mode 100644 index 0000000..009f442 --- /dev/null +++ b/sps2_basement/hardware/sbios/rom0_info.h @@ -0,0 +1,48 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * PS2 ROM0 Info. + * Some useful method for extracting info from ROM0 + */ + +#ifndef __ROM0_INFO_H__ +#define __ROM0_INFO_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/** check whether the PlayStation 2 is actually a DESR-XXXX machine + * + * @return 1 if DESR-XXXX machine; 0 if not + */ +int IsDESRMachine(void); + +/** check whether the PlayStation 2 is actually a TOOL DTL-T10000(H) + * + * @return 1 if DTL-T10000(H); 0 if not + */ +int IsT10K(void); + +/** gets the romname from the current ps2 + * 14 chars - doesnt set a null terminator + * + * @param romname buffer to hold romname (14 chars long) + * @return pointer to buffer containing romname + */ +char *GetRomName(char *romname); + +#ifdef __cplusplus +} +#endif + +#endif /* __ROM_INFO_H__ */ diff --git a/sps2_basement/hardware/sbios/sbios.S b/sps2_basement/hardware/sbios/sbios.S new file mode 100644 index 0000000..7f3e805 --- /dev/null +++ b/sps2_basement/hardware/sbios/sbios.S @@ -0,0 +1,36 @@ +/* + * SBIOS interface for MIPS r5900 + * + * Copyright (c) 2014 Juergen Urban + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +.text +.global sbios_call + +/* + * extern int sbios_call(int func, void *arg, void *sbiosfunc); + * a0 = func + * a1 = arg + * a2 = sbiosfunc + * + * Calls sbiosfunc with 16 Byte aligned stack and a0 + a1 as + * parameter. + * Returns v0 return value of SBIOS call. + */ +sbios_call: + move $t0, $sp + addiu $sp,$sp,-32 + + # Align stack to 16 Bytes: + li $t1,-16 + and $sp,$sp,$t1 + + sw $ra,28($sp) + sw $t0,24($sp) + move $t9, $a2 + jalr $t9 + lw $ra,28($sp) + lw $sp,24($sp) + jr $ra diff --git a/sps2_basement/hardware/sbios/sbios.h b/sps2_basement/hardware/sbios/sbios.h new file mode 100644 index 0000000..1c126c5 --- /dev/null +++ b/sps2_basement/hardware/sbios/sbios.h @@ -0,0 +1,714 @@ +/* + * PlayStation 2 SBIOS interface + * + * Copyright (c) 2000 Sony Computer Entertainment Inc. + * Copyright (c) 2014 Juergen Urban + * + * SPDX-License-Identifier: GPL-2.0 + */ + +/* + * Change history: + * + * Version 2.57 Mar 13, 2003 + * added: + * SB_SETRGBYC + * Version 2.56 Nov 26, 2002 + * added: + * SBR_REMOCON2_INIT + * SBR_REMOCON2_END + * SBR_REMOCON2_PORTOPEN + * SBR_REMOCON2_PORTCLOSE + * SBR_REMOCON2_FEATURE + * SBR_REMOCON2_IGNORE + * SB_REMOCON2_READ + * Version 2.55 Jan 09, 2002 + * added SBR_SOUND_REMOTE command definitions + * Version 2.54 Jan 08, 2002 + * deleted: + * SBR_SOUND_VOICE_TRANS + * SBR_SOUND_VOICE_TRANSSTAT + * Version 2.53 Dec 19, 2001 + * added: + * SBR_SOUND_REMOTE + * Version 2.52 Dec 04, 2001 + * added: + * SBR_CDVD_OPENCONFIG + * SBR_CDVD_CLOSECONFIG + * SBR_CDVD_READCONFIG + * SBR_CDVD_WRITECONFIG + * Version 2.51 Nov 19, 2001 + * added: + * SBR_REMOCON_INIT + * SBR_REMOCON_END + * SBR_REMOCON_PORTOPEN + * SBR_REMOCON_PORTCLOSE + * SB_REMOCON_READ + * Version 6.66 2010 + * added: + * SBIOS provided by kernelloader + * SB_SET_PRINTS_CALLBACK + * + */ + +#ifndef __SPS2_SBIOS_HEADER__ +#define __SPS2_SBIOS_HEADER__ + +#ifdef CONFIG_64BIT + /** Kernel uses 64-Bit pointers, but SBIOS expects 32-Bit pointers. */ + typedef uint32_t ps2_addr_t; + typedef uint32_t ps2_const_addr_t; +#else + typedef void * ps2_addr_t; + typedef const void * ps2_const_addr_t; +#endif + +int sbios(int sbcall, void *arg); + +#define SBIOS_VERSION 0x0257 + +#define SIF_RPCE_GETP 1 /* failed to get packet data. */ +#define SIF_RPCE_SENDP 2 /* failed to send dma packet. */ +#define E_SIF_PKT_ALLOC 0xd610 /* Can't allocate SIF packet. */ + +#define SB_GETVER 0 +#define SB_HALT 1 + +#define SB_HALT_MODE_PWROFF 0 +#define SB_HALT_MODE_HALT 1 +#define SB_HALT_MODE_RESTART 2 +struct sb_halt_arg { + int mode; +}; + +#define SB_SETDVE 2 +struct sb_setdve_arg { + int mode; +}; + +#define SB_PUTCHAR 3 +struct sb_putchar_arg { + char c; +}; + +#define SB_GETCHAR 4 +#define SB_SETGSCRT 5 +struct sb_setgscrt_arg { + int inter; + int omode; + int ffmode; + ps2_addr_t dx1, dy1, dx2, dy2; +}; + +#define SB_SETRGBYC 6 +struct sb_setrgbyc_arg { + int rgbyc; +}; + +/** Debug output in TGE (not supported by RTE). */ +#define SB_SET_PRINTS_CALLBACK 15 + +/* + * SIF DMA services + */ + +#define SB_SIFINIT 16 +#define SB_SIFEXIT 17 +#define SB_SIFSETDMA 18 +struct sb_sifsetdma_arg { + ps2_addr_t sdd; + int len; +}; + +#define SB_SIFDMASTAT 19 +struct sb_sifdmastat_arg { + int id; +}; +#define SB_SIFSETDCHAIN 20 +#define SB_SIFSETREG 21 +enum _sif_regs { + SIF_REG_MAINADDR = 1, + SIF_REG_SUBADDR, + SIF_REG_MSFLAG, + SIF_REG_SMFLAG +}; + +typedef struct sb_sifsetreg { + u_int reg; + u_int val; +}; +#define SB_SIFGETREG 22 +struct sb_sifgetreg { + u_int reg; +}; +#define SB_SIFSTOPDMA 23 + +/* + * SIF CMD services + */ + +#define SB_SIFINITCMD 32 +#define SB_SIFEXITCMD 33 +#define SB_SIFSENDCMD 34 +struct sb_sifsendcmd_arg { + u_int fid; + ps2_addr_t pp; + int ps; + ps2_addr_t src; + ps2_addr_t dest; + int size; +}; +#define SB_SIFCMDINTRHDLR 35 +#define SB_SIFADDCMDHANDLER 36 +struct sb_sifaddcmdhandler_arg { + u_int fid; + ps2_addr_t func; + ps2_addr_t data; +}; +#define SB_SIFREMOVECMDHANDLER 37 +struct sb_sifremovecmdhandler_arg { + u_int fid; +}; +#define SB_SIFSETCMDBUFFER 38 +struct sb_sifsetcmdbuffer_arg { + ps2_addr_t db; + int size; +}; +/* 39-42: reserved */ + +/* + * SIF RPC services + */ + +#define SB_SIFINITRPC 48 +#define SB_SIFEXITRPC 49 +#define SB_SIFGETOTHERDATA 50 +struct sb_sifgetotherdata_arg { + ps2_addr_t rd; + ps2_addr_t src; + ps2_addr_t dest; + int size; + u_int mode; + ps2_addr_t func; + ps2_addr_t para; +}; +#define SB_SIFBINDRPC 51 +struct sb_sifbindrpc_arg { + ps2_addr_t bd; + u_int command; + u_int mode; + ps2_addr_t func; + ps2_addr_t para; +}; +#define SB_SIFCALLRPC 52 +struct sb_sifcallrpc_arg { + ps2_addr_t bd; + u_int fno; + u_int mode; + ps2_addr_t send; + int ssize; + ps2_addr_t receive; + int rsize; + ps2_addr_t func; + ps2_addr_t para; +}; +#define SB_SIFCHECKSTATRPC 53 +struct sb_sifcheckstatrpc_arg { + ps2_addr_t cd; +}; +#define SB_SIFSETRPCQUEUE 54 +struct sb_sifsetrpcqueue_arg { + ps2_addr_t pSrqd; + ps2_addr_t callback; + ps2_addr_t arg; +}; +#define SB_SIFREGISTERRPC 55 +struct sb_sifregisterrpc_arg { + ps2_addr_t pr; + u_int command; + ps2_addr_t func; + ps2_addr_t buff; + ps2_addr_t cfunc; + ps2_addr_t cbuff; + ps2_addr_t pq; +}; +#define SB_SIFREMOVERPC 56 +struct sb_sifremoverpc_arg { + ps2_addr_t pr; + ps2_addr_t pq; +}; +#define SB_SIFREMOVERPCQUEUE 57 +struct sb_sifremoverpcqueue_arg { + ps2_addr_t pSrqd; +}; +#define SB_SIFGETNEXTREQUEST 58 +struct sb_sifgetnextrequest_arg { + ps2_addr_t qd; +}; +#define SB_SIFEXECREQUEST 59 +struct sb_sifexecrequest_arg { + ps2_addr_t rdp; +}; + +/* + * device services + */ + +/* RPC common argument */ + +struct sbr_common_arg { + int result; + ps2_addr_t arg; + /* void (*func)(void *, int); */ + ps2_addr_t func; + ps2_addr_t para; +}; + +/* IOP heap */ + +#define SBR_IOPH_INIT 64 +#define SBR_IOPH_ALLOC 65 +struct sbr_ioph_alloc_arg { + int size; +}; +#define SBR_IOPH_FREE 66 +struct sbr_ioph_free_arg { + uint32_t addr; +}; + +/* pad device */ + +#define SBR_PAD_INIT 80 +struct sbr_pad_init_arg { + int mode; +}; +#define SBR_PAD_END 81 +#define SBR_PAD_PORTOPEN 82 +struct sbr_pad_portopen_arg { + int port; + int slot; + ps2_addr_t addr; +}; +#define SBR_PAD_PORTCLOSE 83 +struct sbr_pad_portclose_arg { + int port; + int slot; +}; +#define SBR_PAD_SETMAINMODE 84 +struct sbr_pad_setmainmode_arg { + int port; + int slot; + int offs; + int lock; +}; +#define SBR_PAD_SETACTDIRECT 85 +struct sbr_pad_setactdirect_arg { + int port; + int slot; + /* const unsigned char *data */ + ps2_const_addr_t data; +}; +#define SBR_PAD_SETACTALIGN 86 +struct sbr_pad_setactalign_arg { + int port; + int slot; + /* const unsigned char *data */ + ps2_const_addr_t data; +}; +#define SBR_PAD_INFOPRESSMODE 87 +struct sbr_pad_pressmode_arg { + int port; + int slot; +}; +#define SBR_PAD_ENTERPRESSMODE 88 +#define SBR_PAD_EXITPRESSMODE 89 + + +#define SB_PAD_READ 90 +struct sb_pad_read_arg { + int port; + int slot; + /* unsigned char *rdata; */ + ps2_addr_t rdata; +}; +#define SB_PAD_GETSTATE 91 +struct sb_pad_getstate_arg { + int port; + int slot; +}; +#define SB_PAD_GETREQSTATE 92 +struct sb_pad_getreqstate_arg { + int port; + int slot; +}; +#define SB_PAD_INFOACT 93 +struct sb_pad_infoact_arg { + int port; + int slot; + int actno; + int term; +}; +#define SB_PAD_INFOCOMB 94 +struct sb_pad_infocomb_arg { + int port; + int slot; + int listno; + int offs; +}; +#define SB_PAD_INFOMODE 95 +struct sb_pad_infomode_arg { + int port; + int slot; + int term; + int offs; +}; + +/* sound */ + +#define SBR_SOUND_INIT 112 +struct sbr_sound_init_arg { +#define SB_SOUND_INIT_COLD 0 +#define SB_SOUND_INIT_HOT 1 + int flag; +}; +#define SBR_SOUND_END 113 +#define SB_SOUND_GREG 114 +#define SB_SOUND_SREG 115 +struct sb_sound_reg_arg { + u_int idx; +#define SB_SOUND_REG_MADR(core) (0 + (core)) +#define SB_SOUND_REG_BCR(core) (2 + (core)) +#define SB_SOUND_REG_BTCR(core) (4 + (core)) +#define SB_SOUND_REG_CHCR(core) (6 + (core)) + +#define SB_SOUND_REG_MMIX(core) (8 + (core)) +#define SB_SOUND_REG_DMAMOD(core) (10 + (core)) +#define SB_SOUND_REG_MVOLL(core) (12 + (core)) +#define SB_SOUND_REG_MVOLR(core) (14 + (core)) +#define SB_SOUND_REG_EVOLL(core) (16 + (core)) +#define SB_SOUND_REG_EVOLR(core) (18 + (core)) +#define SB_SOUND_REG_AVOLL(core) (20 + (core)) +#define SB_SOUND_REG_AVOLR(core) (22 + (core)) +#define SB_SOUND_REG_BVOLL(core) (24 + (core)) +#define SB_SOUND_REG_BVOLR(core) (26 + (core)) + u_int data; +}; +#define SBR_SOUND_GCOREATTR 116 +#define SBR_SOUND_SCOREATTR 117 +struct sbr_sound_coreattr_arg { + u_int idx; +#define SB_SOUND_CA_EFFECT_ENABLE (1<<1) +#define SB_SOUND_CA_IRQ_ENABLE (2<<1) +#define SB_SOUND_CA_MUTE_ENABLE (3<<1) +#define SB_SOUND_CA_NOISE_CLK (4<<1) +#define SB_SOUND_CA_SPDIF_MODE (5<<1) + u_int data; +}; +#define SBR_SOUND_TRANS 118 +struct sbr_sound_trans_arg { + int channel; + u_int mode; +#define SB_SOUND_TRANS_MODE_WRITE 0 +#define SB_SOUND_TRANS_MODE_READ 1 +#define SB_SOUND_TRANS_MODE_STOP 2 +#define SB_SOUND_TRANS_MODE_DMA (0<<3) +#define SB_SOUND_TRANS_MODE_PIO (1<<3) +#define SB_SOUND_TRANS_MODE_ONCE (0<<4) +#define SB_SOUND_TRANS_MODE_LOOP (1<<4) + u_int addr; + u_int size; + u_int start_addr; +}; +#define SBR_SOUND_TRANSSTAT 119 +struct sbr_sound_trans_stat_arg { + int channel; +#define SB_SOUND_TRANSSTAT_WAIT 1 +#define SB_SOUND_TRANSSTAT_CHECK 0 + int flag; +}; +#define SBR_SOUND_TRANSCALLBACK 120 +struct sbr_sound_trans_callback_arg { + int channel; + /* int (*func)(void*, int); */ + ps2_addr_t func; + ps2_addr_t data; + /* int (*oldfunc)(void*, int); */ + ps2_addr_t oldfunc; + ps2_addr_t olddata; +}; +#define SBR_SOUND_REMOTE 123 +/* + * struct sbr_sound_remote_arg in asm/mips/ps2/sbcall.h and + * struct ps2sd_command must have common members and alignments. + * double check if you change this structure. + */ +struct sbr_sound_remote_arg { + int command; +#define PS2SDCTL_COMMAND_QUIT 0x1020 +#define PS2SDCTL_COMMAND_QUIT2 0x010000d0 +#define PS2SDCTL_COMMAND_OPEN1 0x1030 +#define PS2SDCTL_COMMAND_OPEN2 0x1040 +#define PS2SDCTL_COMMAND_OPEN3 0x1050 +#define PS2SDCTL_COMMAND_OPEN4 0x01009050 +#define PS2SDCTL_COMMAND_WRITE 0x1060 +#define PS2SDCTL_COMMAND_WRITE2 0x01000070 +#define PS2SDCTL_COMMAND_WRITE3 0x01000040 +#define PS2SDCTL_COMMAND_READ 0x1070 + int args[126]; +}; + +/* memory card */ + +#define SBR_MC_INIT 144 +#define SBR_MC_OPEN 145 +struct sbr_mc_open_arg { + int port; + int slot; + /* const char *name; */ + ps2_const_addr_t name; + int mode; +}; +#define SBR_MC_MKDIR 146 +struct sbr_mc_mkdir_arg { + int port; + int slot; + /* const char *name; */ + ps2_const_addr_t name; +}; +#define SBR_MC_CLOSE 147 +struct sbr_mc_close_arg { + int fd; +}; +#define SBR_MC_SEEK 148 +struct sbr_mc_seek_arg { + int fd; + int offset; + int mode; +}; +#define SBR_MC_READ 149 +struct sbr_mc_read_arg { + int fd; + ps2_addr_t buff; + int size; +}; +#define SBR_MC_WRITE 150 +struct sbr_mc_write_arg { + int fd; + ps2_const_addr_t buff; + int size; +}; +#define SBR_MC_GETINFO 151 +struct sbr_mc_getinfo_arg { + int port; + int slot; + /* int *type; */ + ps2_addr_t type; + /* int *free; */ + ps2_addr_t free; + /* int *format; */ + ps2_addr_t format; +}; +#define SBR_MC_GETDIR 152 +struct sbr_mc_getdir_arg { + int port; + int slot; + /* const char *name; */ + ps2_const_addr_t name; + unsigned int mode; + int maxent; + ps2_addr_t table; +}; +#define SBR_MC_FORMAT 153 +struct sbr_mc_format_arg { + int port; + int slot; +}; +#define SBR_MC_DELETE 154 +struct sbr_mc_delete_arg { + int port; + int slot; + /* const char *name; */ + ps2_const_addr_t name; +}; +#define SBR_MC_FLUSH 155 +struct sbr_mc_flush_arg { + int fd; +}; +#define SBR_MC_SETFILEINFO 156 +struct sbr_mc_setfileinfo_arg { + int port; + int slot; + /* const char *name; */ + ps2_const_addr_t name; + /* const char *info; */ + ps2_const_addr_t info; + unsigned int valid; +}; +#define SBR_MC_RENAME 157 +struct sbr_mc_rename_arg { + int port; + int slot; + /* const char *org; */ + ps2_const_addr_t orgname; + /* const char *new; */ + ps2_const_addr_t newname; +}; +#define SBR_MC_UNFORMAT 158 +struct sbr_mc_unformat_arg { + int port; + int slot; +}; +#define SBR_MC_GETENTSPACE 159 +struct sbr_mc_getentspace_arg { + int port; + int slot; + /* const char *path; */ + ps2_const_addr_t path; +}; +#define SBR_MC_CALL 160 + +/* + * CD/DVD + */ +#define SBR_CDVD_INIT 176 +#define SBR_CDVD_RESET 177 +#define SBR_CDVD_READY 178 +struct sbr_cdvd_ready_arg { + int mode; +}; + +#define SBR_CDVD_READ 179 +struct sbr_cdvd_read_arg { + u_int lbn; + u_int sectors; + ps2_addr_t buf; + /* struct sceCdRMode *rmode; */ + ps2_addr_t rmode; +}; + +#define SBR_CDVD_STOP 180 +#define SBR_CDVD_GETTOC 181 +struct sbr_cdvd_gettoc_arg { + /* u_char *buf; */ + ps2_addr_t buf; + int len; + int media; +}; + +#define SBR_CDVD_READRTC 182 +#define SBR_CDVD_WRITERTC 183 +struct sbr_cdvd_rtc_arg { + u_char stat; /* status */ + u_char second; /* second */ + u_char minute; /* minute */ + u_char hour; /* hour */ + + u_char pad; /* pad */ + u_char day; /* day */ + u_char month; /* 1900 or 2000 and month */ + u_char year; /* year */ +}; +#define SBR_CDVD_MMODE 184 +struct sbr_cdvd_mmode_arg { + int media; +}; + +#define SBR_CDVD_GETERROR 185 +#define SBR_CDVD_GETTYPE 186 +#define SBR_CDVD_TRAYREQ 187 +struct sbr_cdvd_trayreq_arg { + int req; + int traycount; +}; + +#define SB_CDVD_POWERHOOK 188 +struct sb_cdvd_powerhook_arg { + /* void (*func)(void *); */ + ps2_addr_t func; + ps2_addr_t arg; +}; + +#define SBR_CDVD_DASTREAM 189 +struct sbr_cdvd_dastream_arg { + u_int command; + u_int lbn; + int size; + ps2_addr_t buf; + /* struct sceCdRMode *rmode; */ + ps2_addr_t rmode; +}; + +#define SBR_CDVD_READSUBQ 190 +struct sbr_cdvd_readsubq_arg { + int stat; + u_char data[10]; + u_char reserved[2]; +}; + +#define SBR_CDVD_OPENCONFIG 191 +#define SBR_CDVD_CLOSECONFIG 192 +#define SBR_CDVD_READCONFIG 193 +#define SBR_CDVD_WRITECONFIG 194 +struct sbr_cdvd_config_arg { + int dev; +#define SB_CDVD_CFG_OSD 0x01 /* OSD */ + int mode; +#define SB_CDVD_CFG_READ 0x00 /* READ */ +#define SB_CDVD_CFG_WRITE 0x01 /* WRITE */ + int blk; +#define SB_CDVD_CFG_BLKSIZE 15 + /* u_char *data; */ + ps2_addr_t data; + int stat; +#define SB_CDVD_CFG_STAT_CMDERR (1<<7) +#define SB_CDVD_CFG_STAT_BUSY (1<<0) +}; + +#define SBR_CDVD_RCBYCTL 195 +struct sbr_cdvd_rcbyctl_arg { + int param; + int stat; +}; + +/* Uses sbr_cdvd_read_arg */ +#define SBR_CDVD_READ_DVD 196 + +/* + * Remote Controller + */ +#define SBR_REMOCON_INIT 208 +struct sbr_remocon_init_arg { + int mode; +#define SBR_REMOCON_INIT_MODE 0 +}; + +#define SBR_REMOCON_END 209 +#define SBR_REMOCON_PORTOPEN 210 +#define SBR_REMOCON_PORTCLOSE 211 +struct sbr_remocon_portopen_arg { + int port; + int slot; +}; + +#define SB_REMOCON_READ 212 +struct sb_remocon_read_arg { + int port; + int slot; + int len; +#define SB_REMOCON_MAXDATASIZE 64 + /* unsigned char *buf; */ + ps2_addr_t buf; +}; + +#define SBR_REMOCON2_INIT 213 +#define SBR_REMOCON2_END 214 +#define SBR_REMOCON2_PORTOPEN 215 +#define SBR_REMOCON2_PORTCLOSE 216 +#define SB_REMOCON2_READ 217 + +#define SBR_REMOCON2_IRFEATURE 218 +struct sbr_remocon2_feature_arg { + unsigned char feature; +}; + +#endif diff --git a/sps2_basement/hardware/sbios/sifcmd.h b/sps2_basement/hardware/sbios/sifcmd.h new file mode 100644 index 0000000..4a93d64 --- /dev/null +++ b/sps2_basement/hardware/sbios/sifcmd.h @@ -0,0 +1,108 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (C)2001, Gustavo Scotti (gustavo@scotti.com) +# (c) 2003 Marcus R. Brown (mrbrown@0xd6.org) +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * EE SIF commands prototypes + */ + +#ifndef __SIFCMD_H__ +#define __SIFCMD_H__ + +#include + +typedef struct t_SifCmdHeader +{ + /** Packet size. Min: 1x16 (header only), max: 7*16 */ + u32 psize:8; + /** Payload size */ + u32 dsize:24; + /** Destination address for payload. Can be NULL if there is no payload. */ + void *dest; + /** Function number of function to call. */ + int cid; + /** Can be freely used. */ + u32 opt; +} SifCmdHeader_t; + +/** System functions */ +#define SIF_CMD_ID_SYSTEM 0x80000000 + +#define SIF_CMD_CHANGE_SADDR (SIF_CMD_ID_SYSTEM | 0) +#define SIF_CMD_SET_SREG (SIF_CMD_ID_SYSTEM | 1) +#define SIF_CMD_INIT_CMD (SIF_CMD_ID_SYSTEM | 2) +#define SIF_CMD_RESET_CMD (SIF_CMD_ID_SYSTEM | 3) +#define SIF_CMD_RPC_END (SIF_CMD_ID_SYSTEM | 8) +#define SIF_CMD_RPC_BIND (SIF_CMD_ID_SYSTEM | 9) +#define SIF_CMD_RPC_CALL (SIF_CMD_ID_SYSTEM | 10) +#define SIF_CMD_RPC_RDATA (SIF_CMD_ID_SYSTEM | 12) + +/** System SREG */ +#define SIF_SREG_RPCINIT 0 + +/** Structure for remotely (over the SIF) changing the value of a software register (SREG). + * There are 32 software registers (0 - 31). Registers 0-7 are used by the system. + */ +typedef struct t_SifCmdSRegData { + SifCmdHeader_t header; + int index; + unsigned int value; +} SifCmdSRegData_t; + +#ifdef __cplusplus +extern "C" +#endif +typedef void (*SifCmdHandler_t)(void *data, void *harg); + +typedef struct t_SifCmdHandlerData +{ + SifCmdHandler_t handler; + void *harg; +} SifCmdHandlerData_t; + +/** Triggers an IOP reboot */ +#define RESET_ARG_MAX 79 + +typedef struct _iop_reset_pkt { + struct t_SifCmdHeader header; + int arglen; + int mode; + char arg[RESET_ARG_MAX + 1]; +} SifCmdResetData_t; + +#ifdef __cplusplus +extern "C" { +#endif + +unsigned int SifSendCmd(int cmd, void *packet, int packet_size, void *src_extra, + void *dest_extra, int size_extra); +unsigned int iSifSendCmd(int cmd, void *packet, int packet_size, void *src_extra, + void *dest_extra, int size_extra); +void SifAddCmdHandler(int pos, SifCmdHandler_t handler, void *harg); +void SifRemoveCmdHandler(int pos); +void SifInitCmd(void); +void SifExitCmd(void); +SifCmdHandlerData_t *SifSetCmdBuffer(SifCmdHandlerData_t *db, int size); +int SifGetSreg(int index); + +void SifWriteBackDCache(void *ptr, int size); //EE only + +//Send mode bits +/** Called within an interrupt context */ +#define SIF_CMD_M_INTR 0x01 +/** Write back D-cache for extended data */ +#define SIF_CMD_M_WBDC 0x04 + +#ifdef __cplusplus +} +#endif + +#endif /* __SIFCMD_H__ */ diff --git a/sps2_basement/hardware/sbios/sifdma.h b/sps2_basement/hardware/sbios/sifdma.h new file mode 100644 index 0000000..a8f9f38 --- /dev/null +++ b/sps2_basement/hardware/sbios/sifdma.h @@ -0,0 +1,57 @@ +#ifndef __SPS2_SIF_DMA_HEADERS__ +#define __SPS2_SIF_DMA_HEADERS__ + +#include "../../core/base/basicTypes.h" + +#define SIF_DMA_INT_I 0x2 +#define SIF_DMA_INT_O 0x4 + +#define SIF_DMA_ERT 0x40 + +#define SIF_REG_ID_SYSTEM 0x80000000 + +typedef enum e_sif_regs { + /** Main -> sub-CPU command buffer (MSCOM) */ + SIF_REG_MAINADDR = 1, + /** Sub -> main-CPU command buffer (SMCOM) */ + SIF_REG_SUBADDR, + /** Main -> sub-CPU flag (MSFLAG) */ + SIF_REG_MSFLAG, + /** Sub -> main-CPU flag (SMFLAG) */ + SIF_REG_SMFLAG, + + //Used with the EE kernel. Not actually physical registers like the above, but are implemented in software. + SIF_SYSREG_SUBADDR = SIF_REG_ID_SYSTEM|0, + SIF_SYSREG_MAINADDR, + SIF_SYSREG_RPCINIT +} sif_regs_t; + +//Status bits for the SM and MS SIF registers +/** SIF initialized */ +#define SIF_STAT_SIFINIT 0x10000 +/** SIFCMD initialized */ +#define SIF_STAT_CMDINIT 0x20000 +/** Bootup completed */ +#define SIF_STAT_BOOTEND 0x40000 + +typedef struct s_sif_dma_transfer{ + void * src, + * dest; + uint32_t size; + uint32_t attr; +} sif_dma_transfer_t; + +typedef sif_dma_transfer_t SifDmaTransfer_t; + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t SifSetDma( sif_dma_transfer_t *sdd, uint32_t len ); +uint32_t SifDmaStat( uint32_t id ); + +#ifdef __cplusplus +} +#endif + +#endif /* __SIFDMA_H__ */ diff --git a/sps2_basement/hardware/sbios/sifrpc.h b/sps2_basement/hardware/sbios/sifrpc.h new file mode 100644 index 0000000..3dcb33d --- /dev/null +++ b/sps2_basement/hardware/sbios/sifrpc.h @@ -0,0 +1,203 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (C)2001, Gustavo Scotti (gustavo@scotti.com) +# (c) Marcus R. Brown (mrbrown@0xd6.org) +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * EE SIF RPC commands prototypes + */ + +#ifndef __SIFRPC_H__ +#define __SIFRPC_H__ + +#include + +/* Modes for bind() and call() */ +/** Don't wait for end function */ +#define SIF_RPC_M_NOWAIT 0x01 +/** Don't write back the D cache */ +#define SIF_RPC_M_NOWBDC 0x02 + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void * (*SifRpcFunc_t)(int fno, void *buffer, int length); +typedef void (*SifRpcEndFunc_t)(void *end_param); + +#ifdef __cplusplus +} +#endif + +typedef struct t_SifRpcPktHeader { + struct t_SifCmdHeader sifcmd; + int rec_id; + void *pkt_addr; + int rpc_id; +} SifRpcPktHeader_t; + +typedef struct t_SifRpcRendPkt +{ + struct t_SifCmdHeader sifcmd; + int rec_id; /* 04 */ + void *pkt_addr; /* 05 */ + int rpc_id; /* 06 */ + + struct t_SifRpcClientData *client; /* 7 */ + u32 cid; /* 8 */ + struct t_SifRpcServerData *server; /* 9 */ + void *buff, /* 10 */ + *cbuff; /* 11 */ +} SifRpcRendPkt_t; + +typedef struct t_SifRpcOtherDataPkt +{ + struct t_SifCmdHeader sifcmd; + int rec_id; /* 04 */ + void *pkt_addr; /* 05 */ + int rpc_id; /* 06 */ + + struct t_SifRpcReceiveData *receive; /* 07 */ + void *src; /* 08 */ + void *dest; /* 09 */ + int size; /* 10 */ +} SifRpcOtherDataPkt_t; + +typedef struct t_SifRpcBindPkt +{ + struct t_SifCmdHeader sifcmd; + int rec_id; /* 04 */ + void *pkt_addr; /* 05 */ + int rpc_id; /* 06 */ + struct t_SifRpcClientData *client; /* 07 */ + int sid; /* 08 */ +} SifRpcBindPkt_t; + +typedef struct t_SifRpcCallPkt +{ + struct t_SifCmdHeader sifcmd; + int rec_id; /* 04 */ + void *pkt_addr; /* 05 */ + int rpc_id; /* 06 */ + struct t_SifRpcClientData *client; /* 07 */ + int rpc_number; /* 08 */ + int send_size; /* 09 */ + void *receive; /* 10 */ + int recv_size; /* 11 */ + int rmode; /* 12 */ + struct t_SifRpcServerData *server; /* 13 */ +} SifRpcCallPkt_t; + +typedef struct t_SifRpcServerData +{ + int sid; /* 04 00 */ + + SifRpcFunc_t func; /* 05 01 */ + void *buff; /* 06 02 */ + int size; /* 07 03 */ + + SifRpcFunc_t cfunc; /* 08 04 */ + void *cbuff; /* 09 05 */ + int size2; /* 10 06 */ + + struct t_SifRpcClientData *client; /* 11 07 */ + void *pkt_addr; /* 12 08 */ + int rpc_number; /* 13 09 */ + + void *receive; /* 14 10 */ + int rsize; /* 15 11 */ + int rmode; /* 16 12 */ + int rid; /* 17 13 */ + + struct t_SifRpcServerData *link; /* 18 14 */ + struct t_SifRpcServerData *next; /* 19 15 */ + struct t_SifRpcDataQueue *base; /* 20 16 */ +} SifRpcServerData_t; + + +typedef struct t_SifRpcHeader +{ + void *pkt_addr; /* 04 00 */ + u32 rpc_id; /* 05 01 */ + int sema_id; /* 06 02 */ + u32 mode; /* 07 03 */ +} SifRpcHeader_t; + + +typedef struct t_SifRpcClientData +{ + struct t_SifRpcHeader hdr; + u32 command; /* 04 08 */ + void *buff, /* 05 09 */ + *cbuff; /* 06 10 */ + SifRpcEndFunc_t end_function; /* 07 11 */ + void *end_param; /* 08 12*/ + struct t_SifRpcServerData *server; /* 09 13 */ +} SifRpcClientData_t; + +typedef struct t_SifRpcReceiveData +{ + struct t_SifRpcHeader hdr; + void *src, /* 04 */ + *dest; /* 05 */ + int size; /* 06 */ +} SifRpcReceiveData_t; + +typedef struct t_SifRpcDataQueue +{ + int thread_id, /* 00 */ + active; /* 01 */ + struct t_SifRpcServerData *link, /* 02 */ + *start, /* 03 */ + *end; /* 04 */ + struct t_SifRpcDataQueue *next; /* 05 */ +} SifRpcDataQueue_t; + +#ifdef __cplusplus +extern "C" { +#endif + +void SifInitRpc(int mode); +void SifExitRpc(void); + +/* SIF RPC client API */ +int SifBindRpc(SifRpcClientData_t *client, int rpc_number, int mode); +int SifCallRpc(SifRpcClientData_t *client, int rpc_number, int mode, + void *send, int ssize, void *receive, int rsize, + SifRpcEndFunc_t end_function, void *end_param); +int SifRpcGetOtherData(SifRpcReceiveData_t *rd, void *src, void *dest, + int size, int mode); + +int SifCheckStatRpc(SifRpcClientData_t *cd); + +/* SIF RPC server API */ +SifRpcDataQueue_t * +SifSetRpcQueue(SifRpcDataQueue_t *q, int thread_id); +SifRpcDataQueue_t * +SifRemoveRpcQueue(SifRpcDataQueue_t *qd); + +SifRpcServerData_t * +SifRegisterRpc(SifRpcServerData_t *srv, + int sid, SifRpcFunc_t func, void *buff, SifRpcFunc_t cfunc, + void *cbuff, SifRpcDataQueue_t *qd); +SifRpcServerData_t * +SifRemoveRpc(SifRpcServerData_t *sd, SifRpcDataQueue_t *queue); + +SifRpcServerData_t * +SifGetNextRequest(SifRpcDataQueue_t *qd); + +void SifExecRequest(SifRpcServerData_t *srv); +void SifRpcLoop(SifRpcDataQueue_t *q); + +#ifdef __cplusplus +} +#endif + +#endif /* __SIFRPC_H__ */ diff --git a/sps2_basement/hardware/sbios/sio.h b/sps2_basement/hardware/sbios/sio.h new file mode 100644 index 0000000..32ccc30 --- /dev/null +++ b/sps2_basement/hardware/sbios/sio.h @@ -0,0 +1,125 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * EE Serial I/O + */ + +#ifndef __SIO_H__ +#define __SIO_H__ + +#include +#include + +/* SIO Registers. */ +/* Most of these are based off of Toshiba documentation for the TX49 and the + TX79 companion chip. However, looking at the kernel SIOP (Debug) exception + handler, it looks like some registers are borrowed from the TX7901 UART + (0x1000f110 or LSR, in particular). I'm still trying to find the correct + register names and values. */ +/** Line Control Register. */ +#define SIO_LCR 0x1000f100 +/** UART Mode. */ +#define SIO_LCR_UMODE_8BIT 0x00 +#define SIO_LCR_UMODE_7BIT 0x01 +/** UART Stop Bit Length. */ +#define SIO_LCR_USBL_1BIT 0x00 +#define SIO_LCR_USBL_2BITS 0x01 +/** UART Parity Enable. */ +#define SIO_LCR_UPEN_OFF 0x00 +#define SIO_LCR_UPEN_ON 0x01 +/** UART Even Parity Select. */ +#define SIO_LCR_UEPS_ODD 0x00 +#define SIO_LCR_UEPS_EVEN 0x01 + +/** Line Status Register. */ +#define SIO_LSR 0x1000f110 +/** Data Ready. (Not tested) */ +#define SIO_LSR_DR 0x01 +/** Overrun Error. */ +#define SIO_LSR_OE 0x02 +/** Parity Error. */ +#define SIO_LSR_PE 0x04 +/** Framing Error. */ +#define SIO_LSR_FE 0x08 + +/** Interrupt Enable Register. */ +#define SIO_IER 0x1000f120 +/** Enable Received Data Available Interrupt */ +#define SIO_IER_ERDAI 0x01 +/** Enable Line Status Interrupt. */ +#define SIO_IER_ELSI 0x04 + +/** Interrupt Status Register (?). */ +#define SIO_ISR 0x1000f130 +#define SIO_ISR_RX_DATA 0x01 +#define SIO_ISR_TX_EMPTY 0x02 +#define SIO_ISR_RX_ERROR 0x04 + +/** FIFO Control Register. */ +#define SIO_FCR 0x1000f140 +/** FIFO Reset Enable. */ +#define SIO_FCR_FRSTE 0x01 +/** RX FIFO Reset. */ +#define SIO_FCR_RFRST 0x02 +/** TX FIFO Reset. */ +#define SIO_FCR_TFRST 0x04 + +/** Baud Rate Control Register. */ +#define SIO_BGR 0x1000f150 + +/** Transmit FIFO. */ +#define SIO_TXFIFO 0x1000f180 +/** Receive FIFO. */ +#define SIO_RXFIFO 0x1000f1c0 + +/** The bit in the EE cause register which indicates an SIO exception */ +#define SIO_CAUSE_BIT (1 << 12) + +#ifdef __cplusplus +extern "C" { +#endif + +/* Initialize the SIO. + * The lcr_* parameters are passed as is, so you'll need to use the SIO_LCR_* register values. + * You can pass 0 for all of the lcr_* params to get the standard 8N1 setting (8 data bits, no parity checking, 1 stop bit). + * Note: Unlike the BIOS sio_init() routine, we always base the baud rate on the CPU clock. + */ +void sio_init(u32 baudrate, u8 lcr_ueps, u8 lcr_upen, u8 lcr_usbl, u8 lcr_umode); + +int sio_putc(int c); +int sio_getc(void); +/** Same as sio_getc, but blocking. + * Note that getc should be blocking by default. Ho well. + */ +int sio_getc_block(void); + +/** Not really much to do in the way of error-handling. sio_putc() already + * checks to see if there's room in the TX FIFO, and my cable doesn't support + * hardware flow control. + */ +size_t sio_write(void *buf, size_t size); +/** This will read from the serial port until size characters have been read or EOF (RX FIFO is empty). */ +size_t sio_read(void *buf, size_t size); + +int sio_puts(const char *str); +int sio_putsn(const char *str); // no newline for this one +/** Will block until it recieves \n or \r. */ +char *sio_gets(char *str); + +/** Flushes the input buffer. */ +void sio_flush(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __SIO_H__ */ diff --git a/sps2_basement/hardware/sbios/syscallnr.h b/sps2_basement/hardware/sbios/syscallnr.h new file mode 100644 index 0000000..f456ab3 --- /dev/null +++ b/sps2_basement/hardware/sbios/syscallnr.h @@ -0,0 +1,156 @@ +/** + * @file + * This file contains the system call numbers, similar to asm/unistd.h on Linux. + */ + +#ifndef __SPS2_SYSCALL_NUMBERS_HEADER__ +#define __SPS2_SYSCALL_NUMBERS_HEADER__ + +#define __NR_ResetEE 1 +#define __NR_SetGsCrt 2 +#define __NR__Exit 4 +#define __NR_ResumeIntrDispatch 5 //Arbitrarily named +#define __NR__LoadExecPS2 6 +#define __NR__ExecPS2 7 +#define __NR_ResumeT3IntrDispatch 8 //Arbitrarily named (used by alarm update) +#define __NR_RFU009 9 +#define __NR_AddSbusIntcHandler 0xa +#define __NR_RemoveSbusIntcHandler 0xb +#define __NR_Interrupt2Iop 0xc +#define __NR_SetVTLBRefillHandler 0xd +#define __NR_SetVCommonHandler 0xe +#define __NR_SetVInterruptHandler 0xf +#define __NR_AddIntcHandler 0x10 +#define __NR_AddIntcHandler2 __NR_AddIntcHandler +#define __NR_RemoveIntcHandler 0x11 +#define __NR_AddDmacHandler 0x12 +#define __NR_AddDmacHandler2 __NR_AddDmacHandler +#define __NR_RemoveDmacHandler 0x13 +#define __NR__EnableIntc 0x14 +#define __NR__DisableIntc 0x15 +#define __NR__EnableDmac 0x16 +#define __NR__DisableDmac 0x17 +#define __NR__SetAlarm 0x18 +#define __NR__ReleaseAlarm 0x19 +#define __NR_SetAlarm 0xfc +#define __NR_ReleaseAlarm 0xfe +#define __NR__iEnableIntc (-0x1a) +#define __NR__iDisableIntc (-0x1b) +#define __NR__iEnableDmac (-0x1c) +#define __NR__iDisableDmac (-0x1d) +#define __NR__iSetAlarm (-0x1e) +#define __NR__iReleaseAlarm (-0x1f) +#define __NR_iSetAlarm (-0xfd) +#define __NR_iReleaseAlarm (-0xff) +#define __NR_CreateThread 0x20 +#define __NR_DeleteThread 0x21 +#define __NR_StartThread 0x22 +#define __NR_ExitThread 0x23 +#define __NR_ExitDeleteThread 0x24 +#define __NR_TerminateThread 0x25 +#define __NR_iTerminateThread (-0x26) +#define __NR_DisableDispatchThread 0x27 +#define __NR_EnableDispatchThread 0x28 +#define __NR_ChangeThreadPriority 0x29 +#define __NR_iChangeThreadPriority (-0x2a) +#define __NR_RotateThreadReadyQueue 0x2b +#define __NR__iRotateThreadReadyQueue (-0x2c) +#define __NR_ReleaseWaitThread 0x2d +#define __NR_iReleaseWaitThread (-0x2e) +#define __NR_GetThreadId 0x2f +#define __NR__iGetThreadId (-0x2f) //Used for a hack by SCE to workaround iWakeupThread +#define __NR_ReferThreadStatus 0x30 +#define __NR_iReferThreadStatus (-0x31) +#define __NR_SleepThread 0x32 +#define __NR_WakeupThread 0x33 +#define __NR__iWakeupThread (-0x34) +#define __NR_CancelWakeupThread 0x35 +#define __NR_iCancelWakeupThread (-0x36) +#define __NR_SuspendThread 0x37 +#define __NR__iSuspendThread (-0x38) +#define __NR_ResumeThread 0x39 +#define __NR_iResumeThread (-0x3a) +#define __NR_RFU059 0x3b +#define __NR_RFU060 0x3c +#define __NR_SetupThread __NR_RFU060 +#define __NR_RFU061 0x3d +#define __NR_SetupHeap __NR_RFU061 +#define __NR_EndOfHeap 0x3e +#define __NR_CreateSema 0x40 +#define __NR_DeleteSema 0x41 +#define __NR_SignalSema 0x42 +#define __NR_iSignalSema (-0x43) +#define __NR_WaitSema 0x44 +#define __NR_PollSema 0x45 +#define __NR_iPollSema (-0x46) +#define __NR_ReferSemaStatus 0x47 +#define __NR_iReferSemaStatus (-0x48) +#define __NR_iDeleteSema (-0x49) +#define __NR_SetOsdConfigParam 0x4a +#define __NR_GetOsdConfigParam 0x4b +#define __NR_GetGsHParam 0x4c +#define __NR_GetGsVParam 0x4d +#define __NR_SetGsHParam 0x4e +#define __NR_SetGsVParam 0x4f +#define __NR_CreateEventFlag 0x50 +#define __NR_DeleteEventFlag 0x51 +#define __NR_SetEventFlag 0x52 +#define __NR_iSetEventFlag 0x53 +#define __NR_PutTLBEntry 0x55 +#define __NR_iPutTLBEntry (-0x55) +#define __NR__SetTLBEntry 0x56 +#define __NR_iSetTLBEntry (-0x56) +#define __NR_GetTLBEntry 0x57 +#define __NR_iGetTLBEntry (-0x57) +#define __NR_ProbeTLBEntry 0x58 +#define __NR_iProbeTLBEntry (-0x58) +#define __NR_ExpandScratchPad 0x59 +#define __NR_EnableIntcHandler 0x5C +#define __NR_iEnableIntcHandler (-0x5C) +#define __NR_DisableIntcHandler 0x5D +#define __NR_iDisableIntcHandler (-0x5D) +#define __NR_EnableDmacHandler 0x5E +#define __NR_iEnableDmacHandler (-0x5E) +#define __NR_DisableDmacHandler 0x5F +#define __NR_iDisableDmacHandler (-0x5F) +#define __NR_KSeg0 0x60 +#define __NR_EnableCache 0x61 +#define __NR_DisableCache 0x62 +#define __NR_GetCop0 0x63 +#define __NR_FlushCache 0x64 +#define __NR_CpuConfig 0x66 +#define __NR_iGetCop0 (-0x67) +#define __NR_iFlushCache (-0x68) +#define __NR_RFU105 0x69 +#define __NR_iCpuConfig (-0x6a) +#define __NR_SifStopDma 0x6b +#define __NR_SetCPUTimerHandler 0x6c +#define __NR_SetCPUTimer 0x6d +#define __NR_SetOsdConfigParam2 0x6e +#define __NR_GetOsdConfigParam2 0x6f +#define __NR_GsGetIMR 0x70 +#define __NR_iGsGetIMR (-0x70) +#define __NR_GsPutIMR 0x71 +#define __NR_iGsPutIMR (-0x71) +#define __NR_SetPgifHandler 0x72 +#define __NR_SetVSyncFlag 0x73 +#define __NR_SetSyscall 0x74 +#define __NR__print 0x75 +#define __NR_SifDmaStat 0x76 +#define __NR_iSifDmaStat (-0x76) +#define __NR_SifSetDma 0x77 +#define __NR_iSifSetDma (-0x77) +#define __NR_SifSetDChain 0x78 +#define __NR_iSifSetDChain (-0x78) +#define __NR_SifSetReg 0x79 +#define __NR_SifGetReg 0x7a +#define __NR__ExecOSD 0x7b +#define __NR_Deci2Call 0x7c +#define __NR_PSMode 0x7d +#define __NR_MachineType 0x7e +#define __NR_GetMemorySize 0x7f +#define __NR__GetGsDxDyOffset 0x80 +#define __NR__InitTLB 0x82 +#define __NR_SetMemoryMode 0x85 + +#endif /* __SYSCALLNR_H__ */ diff --git a/sps2_basement/hardware/sbios/sysconf.h b/sps2_basement/hardware/sbios/sysconf.h new file mode 100644 index 0000000..e78ef58 --- /dev/null +++ b/sps2_basement/hardware/sbios/sysconf.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2000 Sony Computer Entertainment Inc. + * Copyright (c) 2014 Juergen Urban + * + * SPDX-License-Identifier: GPL-2.0 + */ + +#ifndef __ASM_PS2_SYSCONF_H +#define __ASM_PS2_SYSCONF_H + +struct ps2_sysconf { + short timezone; + uint8_t aspect; + uint8_t datenotation; + uint8_t language; + uint8_t spdif; + uint8_t summertime; + uint8_t timenotation; + uint8_t video; +}; + +#endif /* __ASM_PS2_SYSCONF_H */ diff --git a/sps2_basement/hardware/sbios/system_map.c b/sps2_basement/hardware/sbios/system_map.c new file mode 100644 index 0000000..8307293 --- /dev/null +++ b/sps2_basement/hardware/sbios/system_map.c @@ -0,0 +1,8 @@ +/* + * The builtin symbol table for use with kallsyms + * + * Copyright (c) 2008-2009 Analog Devices Inc. + * Licensed under the GPL-2 or later. + */ + +const char const system_map[] = SYSTEM_MAP; diff --git a/sps2_basement/hardware/sbios/timer.h b/sps2_basement/hardware/sbios/timer.h new file mode 100644 index 0000000..f090412 --- /dev/null +++ b/sps2_basement/hardware/sbios/timer.h @@ -0,0 +1,68 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Timer prototypes + */ + +#ifndef __TIMER_H__ +#define __TIMER_H__ + +#include + +// EE Timers +#define T0_COUNT ((volatile unsigned int*)0x10000000) +#define T0_MODE ((volatile unsigned int*)0x10000010) +#define T0_COMP ((volatile unsigned int*)0x10000020) +#define T0_HOLD ((volatile unsigned int*)0x10000030) + +#define T1_COUNT ((volatile unsigned int*)0x10000800) +#define T1_MODE ((volatile unsigned int*)0x10000810) +#define T1_COMP ((volatile unsigned int*)0x10000820) +#define T1_HOLD ((volatile unsigned int*)0x10000830) + +// Note! T2 and T3 don't have a Tn_HOLD register! +// ---------------------------------------------- +#define T2_COUNT ((volatile unsigned int*)0x10001000) +#define T2_MODE ((volatile unsigned int*)0x10001010) +#define T2_COMP ((volatile unsigned int*)0x10001020) + +#define T3_COUNT ((volatile unsigned int*)0x10001800) +#define T3_MODE ((volatile unsigned int*)0x10001810) +#define T3_COMP ((volatile unsigned int*)0x10001820) + +#define Tn_MODE(CLKS,GATE,GATS,GATM,ZRET,CUE,CMPE,OVFE,EQUF,OVFF) \ + (u32)((u32)(CLKS) | ((u32)(GATE) << 2) | \ + ((u32)(GATS) << 3) | ((u32)(GATM) << 4) | \ + ((u32)(ZRET) << 6) | ((u32)(CUE) << 7) | \ + ((u32)(CMPE) << 8) | ((u32)(OVFE) << 9) | \ + ((u32)(EQUF) << 10) | ((u32)(OVFF) << 11)) + +// Available rates +#define kBUSCLK (147456000) +#define kBUSCLKBY16 (kBUSCLK / 16) +#define kBUSCLKBY256 (kBUSCLK / 256) +#define kHBLNK_NTSC (15734) +#define kHBLNK_PAL (15625) +#define kHBLNK_DTV480p (31469) +#define kHBLNK_DTV1080i (33750) + +#ifdef __cplusplus +extern "C" { +#endif + +u32 cpu_ticks(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __TIMER_H__ */ diff --git a/sps2_basement/hardware/sbus/ee_low.S b/sps2_basement/hardware/sbus/ee_low.S new file mode 100644 index 0000000..36ed14b --- /dev/null +++ b/sps2_basement/hardware/sbus/ee_low.S @@ -0,0 +1,54 @@ +.global WriteBackDCache +.ent WriteBackDCache +WriteBackDCache: + + lui $25, 0xffff + ori $25, $25, 0xffc0 + blez $5, last + addu $10, $4, $5 + and $8, $4, $25 + addiu $10, $10, -1 + and $9, $10, $25 + subu $10, $9, $8 + srl $11, $10, 0x6 + addiu $11, $11, 1 + andi $9, $11, 0x7 + beqz $9, eight + srl $10, $11, 0x3 +loop1: + sync + cache 0x18, 0($8) + sync + addiu $9, $9, -1 + nop + bgtz $9, loop1 + addiu $8, $8, 64 + +eight: + beqz $10, last +loop8: + addiu $10, $10, -1 + sync + cache 0x18, 0($8) + sync + cache 0x18, 64($8) + sync + cache 0x18, 128($8) + sync + cache 0x18, 192($8) + sync + cache 0x18, 256($8) + sync + cache 0x18, 320($8) + sync + cache 0x18, 384($8) + sync + cache 0x18, 448($8) + sync + bgtz $10, loop8 + addiu $8, $8, 512 +last: + jr $31 + nop + +.end WriteBackDCache diff --git a/sps2_basement/hardware/sbus/ee_sbus.c b/sps2_basement/hardware/sbus/ee_sbus.c new file mode 100644 index 0000000..5754c97 --- /dev/null +++ b/sps2_basement/hardware/sbus/ee_sbus.c @@ -0,0 +1,89 @@ +/* + +EE-specific code for PS2 SBUS library. + +This file contains the glue, etc needed for an SBUS library on EE. + +*/ + +#include "sbus.h" +#include "../sbios/bios.h" +extern int __local_sbus_irq_handler(void); + +void SBUS_check_intr(void){ + if(*R_EE_I_STAT & EE_I_STAT_SBUS){ + __local_sbus_irq_handler(); + *R_EE_I_STAT |= EE_I_STAT_SBUS; + }; +}; + +#if 0 + +int SBUS_interrupt_remote(int irq) +{ + int oldi; + + M_SuspendIntr(&oldi); + + // wait for remote to clear "irq" bit + while(SBUS_get_reg(PS2_SBUS_LR_FLAG) & (1 << irq)); + + // if clk is high, bring it low + if(SBUS_get_reg(PS2_SBUS_REG4) & 0x00000100) { SBUS_set_reg(PS2_SBUS_REG4, 0x00000100); } + + // set the "irq" bit for the SBUS interrupt. + SBUS_set_reg(PS2_SBUS_LR_FLAG, (1 << irq)); + + // cause the actual SBUS interrupt on remote CPU + + // clk high + *R_EE_SBUS(4) = 0x00000100; + // clk low + *R_EE_SBUS(4) = 0x00000100; + // clk high + *R_EE_SBUS(4) = 0x00000100; + // clk low + *R_EE_SBUS(4) = 0x00000100; + // clk high + *R_EE_SBUS(4) = 0x00000100; + // clk low + *R_EE_SBUS(4) = 0x00000100; + // clk high + *R_EE_SBUS(4) = 0x00000100; + // clk low + *R_EE_SBUS(4) = 0x00000100; + // clk high + *R_EE_SBUS(4) = 0x00000100; + // clk low, intr high + *R_EE_SBUS(4) = 0x00040100; + + M_ResumeIntr(oldi); + + return(irq); +} +#else +int8_t SBUS_interrupt_remote( int8_t irq ){ + int oldi; + if( irq >= 32 ) return -1; + M_SuspendIntr( &oldi ); + // wait for remote to clear irq bit + while( SBUS_get_reg( PS2_SBUS_MS_FLAG ) & ( 1 << irq ) ); + // set the "irq" bit for the SBUS interrupt. + SBUS_set_reg( PS2_SBUS_MS_FLAG, ( 1 << irq )); + SBUS_set_reg( PS2_SBUS_REG4, 0x00040100); + SBUS_set_reg( PS2_SBUS_REG4, 0x00000100); + M_ResumeIntr( oldi ); + return irq; +} + +#endif + +// this is a hack but the address of the function that sets the actual low-level interrupt handler pointer. +void _SetIntcHandler( uint8_t irq, void *handler ){ + int i_state, u_state; + i_state = DI(); + u_state = (ee_kmode_enter() >> 3) & 3; + ((void (*)(int, void *)) (0x80000700))( irq, handler ); + if( u_state ) ee_kmode_exit(); + if( i_state ) EI(); +}; diff --git a/sps2_basement/hardware/sbus/iop/io_common.h b/sps2_basement/hardware/sbus/iop/io_common.h new file mode 100644 index 0000000..252a536 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/io_common.h @@ -0,0 +1,63 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Shared IO structures and definitions + */ + +#ifndef __IO_COMMON_H__ +#define __IO_COMMON_H__ + +#include +#include + +#ifdef _EE +#ifndef NEWLIB_PORT_AWARE +#error "Using fio/fileXio functions directly in the newlib port will lead to problems." +#error "Use posix function calls instead." +#endif +#endif + +#define FIO_O_RDONLY 0x0001 +#define FIO_O_WRONLY 0x0002 +#define FIO_O_RDWR 0x0003 +#define FIO_O_DIROPEN 0x0008 // Internal use for dopen +#define FIO_O_NBLOCK 0x0010 +#define FIO_O_APPEND 0x0100 +#define FIO_O_CREAT 0x0200 +#define FIO_O_TRUNC 0x0400 +#define FIO_O_EXCL 0x0800 +#define FIO_O_NOWAIT 0x8000 + +#define FIO_MT_RDWR 0x00 +#define FIO_MT_RDONLY 0x01 + +#define FIO_SEEK_SET 0 +#define FIO_SEEK_CUR 1 +#define FIO_SEEK_END 2 + +typedef struct { + unsigned int mode; + unsigned int attr; + unsigned int size; + unsigned char ctime[8]; + unsigned char atime[8]; + unsigned char mtime[8]; + unsigned int hisize; +} io_stat_t; + +typedef struct { + io_stat_t stat; + char name[256]; + unsigned int unknown; +} io_dirent_t; + +#endif /* __IO_COMMON_H__ */ diff --git a/sps2_basement/hardware/sbus/iop/iop_cop0_defs.h b/sps2_basement/hardware/sbus/iop/iop_cop0_defs.h new file mode 100644 index 0000000..ee2eb17 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/iop_cop0_defs.h @@ -0,0 +1,73 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 PS2DEV.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOP Co-processor 0(COP0) register definitions. + */ + +#ifndef __IOP_COP0_DEFS_H__ +#define __IOP_COP0_DEFS_H__ + +#define M_IOP_GET_CAUSE_EXCODE(__cause) (((__cause) >> 2) & 0x1F) + +// IOP COP0 register names +#define IOP_COP0_BPC $3 +#define IOP_COP0_BDA $5 +#define IOP_COP0_DCIC $7 +#define IOP_COP0_BADVADDR $8 +#define IOP_COP0_BDAM $9 +#define IOP_COP0_BPCM $11 +#define IOP_COP0_STATUS $12 + +// IOP COP0 DCIC Register +/** Trap enable */ +#define IOP_DCIC_TR 0x80000000 +/** User debug enable */ +#define IOP_DCIC_UD 0x40000000 +/** Kernel debug enable */ +#define IOP_DCIC_KD 0x20000000 +/** Trace enable */ +#define IOP_DCIC_TE 0x10000000 +/** Enable data breakpoints on write */ +#define IOP_DCIC_DW 0x08000000 +/** Enable data breakpoints on read */ +#define IOP_DCIC_DR 0x04000000 +/** Enable data addresss breakpoints */ +#define IOP_DCIC_DAE 0x02000000 +/** Enable instruction breakpoints */ +#define IOP_DCIC_PCE 0x01000000 +/** Debug enable */ +#define IOP_DCIC_DE 0x00800000 +/** Data cache line invalidate */ +#define IOP_DCIC_DL 0x00008000 +/** Instruction cache line invalidate */ +#define IOP_DCIC_IL 0x00004000 +/** Data cache invalidate enable */ +#define IOP_DCIC_D 0x00002000 +/** Instr. cache invalidate enable */ +#define IOP_DCIC_I 0x00001000 +/** Trace, set by CPU */ +#define IOP_DCIC_T 0x00000020 +/** Write reference, set by CPU */ +#define IOP_DCIC_W 0x00000010 +/** Read reference, set by CPU */ +#define IOP_DCIC_R 0x00000008 +/** Data address, set by CPU */ +#define IOP_DCIC_DA 0x00000004 +/** Program counter, set by CPU */ +#define IOP_DCIC_PC 0x00000002 +/** Debug, set by CPU */ +#define IOP_DCIC_DB 0x00000001 + +// IOP COP0 Cause Register +#define IOP_CAUSE_BD (1 << 31) + +#endif /* __IOP_COP0_DEFS_H__ */ diff --git a/sps2_basement/hardware/sbus/iop/iop_regs.h b/sps2_basement/hardware/sbus/iop/iop_regs.h new file mode 100644 index 0000000..0dbab68 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/iop_regs.h @@ -0,0 +1,433 @@ +#ifndef __IOP_REGS_H__ +#define __IOP_REGS_H__ + +#include "../../../core/base/basicTypes.h" + +#define A_IOP_SIF0_HANDLER ((pvuint32_t) (0x000003C0)) +#define A_IOP_SIF1_HANDLER ((pvuint32_t) (0x000003D0)) +#define A_IOP_SIF2_HANDLER ((pvuint32_t) (0x000003E0)) + +#define M_reg8(___base, ___reg_num) ((pvuint8_t *) (___base + (___reg_num))) + +/** N_CMD is written to supply the command number for a CDVD "N" command. */ +#define R_CDVD_N_CMD M_reg8(A_CDVD_REG_BASE, 0x04) + +/** CDVD Register 0x05 is written to add a byte to N-command param FIFO + * and read to determine N-command status. + * Command status: + * bit explaination + * --- ------------ + * 0 Unknown + * 1 Unknown + * 2 Unknown + * 3 Unknown + * 4 Unknown + * 5 Unknown + * 6 result FIFO empty(0 = result in FIFO, 1 = result FIFO is empty) + * 7 busy(1 if currently processing a N-command) + */ +#define R_CDVD_N_CMD_STATUS M_reg8(A_CDVD_REG_BASE, 0x05) +#define R_CDVD_N_CMD_PARAM_FIFO M_reg8(A_CDVD_REG_BASE, 0x05) + +#define R_CDVD_LAST_ERROR M_reg8(A_CDVD_REG_BASE, 0x06) + +// 0x01 is written to this register to cause a "break" to occur, along with an interrupt. +#define R_CDVD_REG07 M_reg8(A_CDVD_REG_BASE, 0x07) + +/* TRAY_STAT is read to get the status of the drive tray. + * Tray status: + * bit explaination + * --- ------------ + * 0 Tray Open(1 if tray is open, 0 if closed) + * 1-7 Unknown + */ +#define R_CDVD_TRAY_STATUS M_reg8(A_CDVD_REG_BASE, 0x0A) + +/** bits for CDVD_TRAY_STAT register */ +#define CDVD_TRAY_STAT_OPEN (1 << 0) + +#define R_CDVD_DISK_TYPE M_reg8(A_CDVD_REG_BASE, 0x0F) + +/** CDVD Register "S_CMD" : 0x16 + * write 8-bit "S" command number after parameters. + * read: unknown + */ +#define R_CDVD_S_CMD M_reg8(A_CDVD_REG_BASE, 0x16) + +/* CDVD Register 0x17 is written to add a parameter to the S-command param FIFO + * and read to determine command status. + * Command status: + * bit explaination + * --- ------------ + * 0 Unknown + * 1 Unknown + * 2 Unknown + * 3 Unknown + * 4 Unknown + * 5 Unknown + * 6 result FIFO empty(0 = result in FIFO, 1 = result FIFO is empty) + * 7 busy(1 if currently processing a command) + */ +#define R_CDVD_S_STATUS M_reg8(A_CDVD_REG_BASE, 0x17) +#define R_CDVD_S_PARAM_FIFO M_reg8(A_CDVD_REG_BASE, 0x17) + +#define CDVD_S_STAT_RFIFO_EMPTY (1 << 6) +#define CDVD_S_STAT_BUSY (1 << 7) + +/** S_RES_FIFO is read to get a byte from the S-command result FIFO. */ +#define R_CDVD_S_RES_FIFO M_reg8(A_CDVD_REG_BASE, 0x18) + +#define R_CDVD_KEY_DATA0 M_reg8(A_CDVD_REG_BASE, 0x20) +#define R_CDVD_KEY_DATA1 M_reg8(A_CDVD_REG_BASE, 0x21) +#define R_CDVD_KEY_DATA2 M_reg8(A_CDVD_REG_BASE, 0x22) +#define R_CDVD_KEY_DATA3 M_reg8(A_CDVD_REG_BASE, 0x23) +#define R_CDVD_KEY_DATA4 M_reg8(A_CDVD_REG_BASE, 0x24) + +#define R_CDVD_KEY_DATA5 M_reg8(A_CDVD_REG_BASE, 0x28) +#define R_CDVD_KEY_DATA6 M_reg8(A_CDVD_REG_BASE, 0x29) +#define R_CDVD_KEY_DATA7 M_reg8(A_CDVD_REG_BASE, 0x2A) +#define R_CDVD_KEY_DATA8 M_reg8(A_CDVD_REG_BASE, 0x2B) +#define R_CDVD_KEY_DATA9 M_reg8(A_CDVD_REG_BASE, 0x2C) + +#define R_CDVD_KEY_DATAA M_reg8(A_CDVD_REG_BASE, 0x30) +#define R_CDVD_KEY_DATAB M_reg8(A_CDVD_REG_BASE, 0x31) +#define R_CDVD_KEY_DATAC M_reg8(A_CDVD_REG_BASE, 0x32) +#define R_CDVD_KEY_DATAD M_reg8(A_CDVD_REG_BASE, 0x33) +#define R_CDVD_KEY_DATAE M_reg8(A_CDVD_REG_BASE, 0x34) + +/** Flags indicating the format of the key data. + * Bits 0-2 set indicate that the corresponding 5-byte key data block is valid. + * Bits 3-7 are unknown, but may be used to determine additional encryption measures used for DSP<->mechacon communication. + */ +#define R_CDVD_KEY_FLAGS M_reg8(A_CDVD_REG_BASE, 0x38) + +/** Key Data Block XOR key + * XOR'd with each byte of each valid Key Data Block to decrypt their values. + */ +#define R_CDVD_KEY_XOR M_reg8(A_CDVD_REG_BASE, 0x39) + +/** Decryption control, enable/disable decryption algorithms on data being read from disc using 5th byte of current + * key as the XOR key. + * Bit 0 is Data XOR enable, this causes data being read from the disc to be XOR'd with the value of the CDVD_KEY_DATA4 + * register. + * Bit 1 is Rotate Left enable, this causes data being read to be rotated left by a specified number of bits(see Bits 4-6). + * Bit 2 doesn't seem to do anything.. + * Bit 3 is Swap Nibble enable, this causes data being read to have the the high and low nibbles of each byte + * to be swapped. + * Bits 4-7 is the number of bits the data being read will be shifted left byte, if enabled. + */ +#define R_CDVD_DEC_CTRL M_reg8(A_CDVD_REG_BASE, 0x3A) + +// bits for CDVD_DEC_CTRL(bits 4-7 are "rotate left number") +#define CDVD_DEC_XOR_EN (1 << 0) +#define CDVD_DEC_ROTL_EN (1 << 1) +#define CDVD_DEC_UNK_EN (1 << 2) +#define CDVD_DEC_SWAP_EN (1 << 3) + + +#define A_IOP_IRQ_CTRL 0xBF801450 +#define A_IOP_REG_1454 0xBF801454 + +/** unknown, related to CD? 32-bit */ +#define A_PS1_1F801018 0x1F801018 + +/** unknown, related to CD? 32-bit */ +#define A_PS1_1F801020 0x1F801020 + + +#define A_PS1_SIO0_DATA 0x1F801040 +#define A_PS1_SIO0_STAT 0x1F801044 +#define A_PS1_SIO0_MODE 0x1F801048 +#define A_PS1_SIO0_CTRL 0x1F80104A +#define A_PS1_SIO0_BAUD 0x1F80104E + +#define A_PS1_SIO1_DATA 0x1F801050 +#define A_PS1_SIO1_STAT 0x1F801054 +#define A_PS1_SIO1_MODE 0x1F801058 +#define A_PS1_SIO1_CTRL 0x1F80105A +#define A_PS1_SIO1_BAUD 0x1F80105E + +#define A_PS1_RAM_SIZE 0x1F801060 + +#define A_IOP_I_STAT 0xBF801070 +#define A_IOP_I_MASK 0xBF801074 + +#define A_IOP_IREG_1078 0xBF801078 +#define A_IOP_IREG_107C 0xBF80107C + +#define A_IOP_D0_MADR 0xBF801080 +#define A_IOP_D0_BCR 0xBF801084 +#define A_IOP_D0_CHCR 0xBF801088 + +#define A_IOP_D1_MADR 0xBF801090 +#define A_IOP_D1_BCR 0xBF801094 +#define A_IOP_D1_CHCR 0xBF801098 + +#define A_IOP_D2_MADR 0xBF8010A0 +#define A_IOP_D2_BCR 0xBF8010A4 +#define A_IOP_D2_CHCR 0xBF8010A8 + +#define A_IOP_D3_MADR 0xBF8010B0 +#define A_IOP_D3_BCR 0xBF8010B4 +#define A_IOP_D3_CHCR 0xBF8010B8 + +#define A_IOP_D4_MADR 0xBF8010C0 +#define A_IOP_D4_BCR 0xBF8010C4 +#define A_IOP_D4_CHCR 0xBF8010C8 +#define A_IOP_D4_TADR 0xBF8010CC + +#define A_IOP_D5_MADR 0xBF8010D0 +#define A_IOP_D5_BCR 0xBF8010D4 +#define A_IOP_D5_CHCR 0xBF8010D8 + +#define A_IOP_D6_MADR 0xBF8010E0 +#define A_IOP_D6_BCR 0xBF8010E4 +#define A_IOP_D6_CHCR 0xBF8010E8 + +#define A_IOP_SIF_1450 0xBF801450 +#define A_IOP_SIF_1454 0xBF801454 + +#define A_IOP_BF80146E 0xBF80146E +#define A_IOP_BF801470 0xBF801470 +#define A_IOP_BF801472 0xBF801472 + +#define A_IOP_D7_MADR 0xBF801500 +#define A_IOP_D7_BCR 0xBF801504 +#define A_IOP_D7_CHCR 0xBF801508 + +#define A_IOP_D8_MADR 0xBF801510 +#define A_IOP_D8_BCR 0xBF801514 +#define A_IOP_D8_CHCR 0xBF801518 + +#define A_IOP_D9_MADR 0xBF801520 +#define A_IOP_D9_BCR 0xBF801524 +#define A_IOP_D9_CHCR 0xBF801528 +#define A_IOP_D9_TADR 0xBF80152C + +#define A_IOP_D10_MADR 0xBF801530 +#define A_IOP_D10_BCR 0xBF801534 +#define A_IOP_D10_CHCR 0xBF801538 + +#define A_IOP_D11_MADR 0xBF801540 +#define A_IOP_D11_BCR 0xBF801544 +#define A_IOP_D11_CHCR 0xBF801548 + +#define A_IOP_D12_MADR 0xBF801550 +#define A_IOP_D12_BCR 0xBF801554 +#define A_IOP_D12_CHCR 0xBF801558 + +#define A_IOP_DMAC_1560 0xBF801560 +#define A_IOP_DMAC_1564 0xBF801564 +#define A_IOP_DMAC_1568 0xBF801568 + +#define A_IOP_DPCR 0xBF8010F0 +#define A_IOP_DPCR2 0xBF801570 +#define A_IOP_DPCR3 0xBF8015F0 + +#define A_IOP_DICR 0xBF8010F4 +#define A_IOP_DICR2 0xBF801574 +#define A_IOP_DICR3 0xBF80157C + +#define A_IOP_DMAC_1578 0xBF801578 + +#define A_PS1_CD_REG0 0x1F801800 +#define A_PS1_CD_REG1 0x1F801801 +#define A_PS1_CD_REG2 0x1F801802 +#define A_PS1_CD_REG3 0x1F801803 + +#define A_IOP_GPU_DATA 0x1F801810 +#define A_IOP_GPU_CTRL 0x1F801814 + +// $1f801c00-$1f801dff +#define A_IOP_SPU1_BASE 0x1F801C00 + +#define A_IOP_UNK_2070 0xBF802070 + +#define A_IOP_BF803200 0xBF803200 +#define A_IOP_BF803204 0xBF803204 +#define A_IOP_BF803218 0xBF803218 +#define A_IOP_BF808400 0xBF808400 +#define A_IOP_BF808414 0xBF808414 +#define A_IOP_BF80844C 0xBF80844C +#define A_IOP_BF808420 0xBF808420 +#define A_IOP_BF808428 0xBF808428 +#define A_IOP_BF808430 0xBF808430 +#define A_IOP_BF80847C 0xBF80847C + +#define A_IOP_SBUS_REG_BASE 0xBD000000 + +// Register pointer definitions + +// IOP/EE IRQ control? +#define R_IOP_IRQ_CTRL ((pvuint32_t) (A_IOP_IRQ_CTRL)) + +// ??? related to IOP/EE communication? +#define R_IOP_REG_1454 ((pvuint32_t) (A_IOP_REG_1454)) + +// PS1 SIO0(pad/card slots) All 16-bit? +#define R_PS1_SIO0_DATA ((pvuint16_t) (A_PS1_SIO0_DATA)) +#define R_PS1_SIO0_STAT ((pvuint16_t) (A_PS1_SIO0_STAT)) +#define R_PS1_SIO0_MODE ((pvuint16_t) (A_PS1_SIO0_MODE)) +#define R_PS1_SIO0_CTRL ((pvuint16_t) (A_PS1_SIO0_CTRL)) +#define R_PS1_SIO0_BAUD ((pvuint16_t) (A_PS1_SIO0_BAUD)) + +// PS1 SIO1(serial port) All 16-bit? +// note: these are just duplicated from SIO0 infos! +#define R_PS1_SIO1_DATA ((pvuint16_t) (A_PS1_SIO1_DATA)) +#define R_PS1_SIO1_STAT ((pvuint16_t) (A_PS1_SIO1_STAT)) +#define R_PS1_SIO1_MODE ((pvuint16_t) (A_PS1_SIO1_MODE)) +#define R_PS1_SIO1_CTRL ((pvuint16_t) (A_PS1_SIO1_CTRL)) +#define R_PS1_SIO1_BAUD ((pvuint16_t) (A_PS1_SIO1_BAUD)) + +// ?? +#define R_PS1_RAM_SIZE ((pvuint32_t) (A_PS1_RAM_SIZE)) + +#define R_IOP_I_STAT ((pvuint32_t) (A_IOP_I_STAT)) +#define R_IOP_I_MASK ((pvuint32_t) (A_IOP_I_MASK)) + +// unknown functions, likely interrupt/dma related. +#define R_IOP_IREG_1078 ((pvuint32_t) (A_IOP_IREG_1078)) +#define R_IOP_IREG_107C ((pvuint32_t) (A_IOP_IREG_107C)) + +// IOP DMAC Registers +#define R_IOP_D0_MADR ((pvuint32_t) (A_IOP_D0_MADR)) +#define R_IOP_D0_BCR ((pvuint32_t) (A_IOP_D0_BCR)) +#define R_IOP_D0_CHCR ((pvuint32_t) (A_IOP_D0_CHCR)) + +#define R_IOP_D1_MADR ((pvuint32_t) (A_IOP_D1_MADR)) +#define R_IOP_D1_BCR ((pvuint32_t) (A_IOP_D1_BCR)) +#define R_IOP_D1_CHCR ((pvuint32_t) (A_IOP_D1_CHCR)) + +#define R_IOP_D2_MADR ((pvuint32_t) (A_IOP_D2_MADR)) +#define R_IOP_D2_BCR ((pvuint32_t) (A_IOP_D2_BCR)) +#define R_IOP_D2_BCR_BS ((pvuint16_t) (A_IOP_D2_BCR + 0x00)) +#define R_IOP_D2_BCR_BC ((pvuint16_t) (A_IOP_D2_BCR + 0x02)) +#define R_IOP_D2_CHCR ((pvuint32_t) (A_IOP_D2_CHCR)) + +#define R_IOP_D3_MADR ((pvuint32_t) (A_IOP_D3_MADR)) +#define R_IOP_D3_BCR ((pvuint32_t) (A_IOP_D3_BCR)) +#define R_IOP_D3_CHCR ((pvuint32_t) (A_IOP_D3_CHCR)) + +#define R_IOP_D4_MADR ((pvuint32_t) (A_IOP_D4_MADR)) +#define R_IOP_D4_BCR ((pvuint32_t) (A_IOP_D4_BCR)) +#define R_IOP_D4_CHCR ((pvuint32_t) (A_IOP_D4_CHCR)) +#define R_IOP_D4_TADR ((pvuint32_t) (A_IOP_D4_TADR)) + +#define R_IOP_D5_MADR ((pvuint32_t) (A_IOP_D5_MADR)) +#define R_IOP_D5_BCR ((pvuint32_t) (A_IOP_D5_BCR)) +#define R_IOP_D5_CHCR ((pvuint32_t) (A_IOP_D5_CHCR)) + +#define R_IOP_D6_MADR ((pvuint32_t) (A_IOP_D6_MADR)) +#define R_IOP_D6_BCR ((pvuint32_t) (A_IOP_D6_BCR)) +#define R_IOP_D6_CHCR ((pvuint32_t) (A_IOP_D6_CHCR)) + +#define R_IOP_D7_MADR ((pvuint32_t) (A_IOP_D7_MADR)) +#define R_IOP_D7_BCR ((pvuint32_t) (A_IOP_D7_BCR)) +#define R_IOP_D7_CHCR ((pvuint32_t) (A_IOP_D7_CHCR)) + +#define R_IOP_D8_MADR ((pvuint32_t) (A_IOP_D8_MADR)) +#define R_IOP_D8_BCR ((pvuint32_t) (A_IOP_D8_BCR)) +#define R_IOP_D8_CHCR ((pvuint32_t) (A_IOP_D8_CHCR)) + +#define R_IOP_D9_MADR ((pvuint32_t) (A_IOP_D9_MADR)) +#define R_IOP_D9_BCR ((pvuint32_t) (A_IOP_D9_BCR)) +#define R_IOP_D9_CHCR ((pvuint32_t) (A_IOP_D9_CHCR)) +#define R_IOP_D9_TADR ((pvuint32_t) (A_IOP_D9_TADR)) + +#define R_IOP_D10_MADR ((pvuint32_t) (A_IOP_D10_MADR)) +#define R_IOP_D10_BCR ((pvuint32_t) (A_IOP_D10_BCR)) +#define R_IOP_D10_CHCR ((pvuint32_t) (A_IOP_D10_CHCR)) + +#define R_IOP_D11_MADR ((pvuint32_t) (A_IOP_D11_MADR)) +#define R_IOP_D11_BCR ((pvuint32_t) (A_IOP_D11_BCR)) +#define R_IOP_D11_CHCR ((pvuint32_t) (A_IOP_D11_CHCR)) + +#define R_IOP_D12_MADR ((pvuint32_t) (A_IOP_D12_MADR)) +#define R_IOP_D12_BCR ((pvuint32_t) (A_IOP_D12_BCR)) +#define R_IOP_D12_CHCR ((pvuint32_t) (A_IOP_D12_CHCR)) + +// These are some type of extended DMA control/address +// Reg 1560 is for SIF0(CH9), 1564 is for SIF1(CH10) and 1568 is for "SPU"(CH4) though "SPU" seems odd, perhaps SIF2?? +#define R_IOP_DMAC_1560 ((pvuint32_t) (A_IOP_DMAC_1560)) +#define R_IOP_DMAC_1564 ((pvuint32_t) (A_IOP_DMAC_1564)) +#define R_IOP_DMAC_1568 ((pvuint32_t) (A_IOP_DMAC_1568)) + +#define R_IOP_DPCR ((pvuint32_t) (A_IOP_DPCR)) +#define R_IOP_DPCR2 ((pvuint32_t) (A_IOP_DPCR2)) +#define R_IOP_DPCR3 ((pvuint32_t) (A_IOP_DPCR3)) + +#define R_IOP_DICR ((pvuint32_t) (A_IOP_DICR)) +#define R_IOP_DICR2 ((pvuint32_t) (A_IOP_DICR2)) +#define R_IOP_DICR3 ((pvuint32_t) (A_IOP_DICR3)) + +/** ??? Set to 1 by DMACMAN when DMAC is initilized, set to 0 by DMACMAN when shut down. */ +#define R_IOP_DMAC_1578 ((pvuint32_t) (A_IOP_DMAC_1578)) + +// SIF/SBUS + +#define R_IOP_SIF_1450 ((pvuint32_t) (A_IOP_SIF_1450)) +#define R_IOP_SIF_1454 ((pvuint32_t) (A_IOP_SIF_1454)) + + + +#define R_PS1_CD_REG0 ((pvuint8_t) (A_PS1_CD_REG0)) +#define R_PS1_CD_REG1 ((pvuint8_t) (A_PS1_CD_REG1)) +#define R_PS1_CD_REG2 ((pvuint8_t) (A_PS1_CD_REG2)) +#define R_PS1_CD_REG3 ((pvuint8_t) (A_PS1_CD_REG3)) + +#define R_IOP_GPU_DATA ((pvuint32_t) (A_IOP_GPU_DATA)) +#define R_IOP_GPU_CTRL ((pvuint32_t) (A_IOP_GPU_CTRL)) + +#define R_IOP_UNK_2070 ((pvuint32_t) (A_IOP_UNK_2070)) + +/** IOP SBUS Registers(add PS2_SBUS_xxx to this to get register address) */ +#define R_IOP_SBUS_REG_BASE ((pvuint32_t) (A_IOP_SBUS_REG_BASE)) + +// Accessed by EECONF.IRX: + +// accessed as 8-bit +#define R_IOP_BF80146E ((pvuint8_t) (A_IOP_BF80146E)) + +// accessed as 16-bit +#define R_IOP_BF801470 ((pvuint16_t) (A_IOP_BF801470)) +#define R_IOP_BF801472 ((pvuint16_t) (A_IOP_BF801472)) + +// accessed as 8-bit +#define R_IOP_BF803200 ((pvuint8_t) (A_IOP_BF803200)) +#define R_IOP_BF803204 ((pvuint8_t) (A_IOP_BF803204)) +#define R_IOP_BF803218 ((pvuint8_t) (A_IOP_BF803218)) + +// 32-bit?? +#define R_IOP_BF808400 ((pvuint32_t) (A_IOP_BF808400)) +#define R_IOP_BF808414 ((pvuint32_t) (A_IOP_BF808414)) +#define R_IOP_BF80844C ((pvuint32_t) (A_IOP_BF80844C)) +#define R_IOP_BF808420 ((pvuint32_t) (A_IOP_BF808420)) +#define R_IOP_BF808428 ((pvuint32_t) (A_IOP_BF808428)) +#define R_IOP_BF808430 ((pvuint32_t) (A_IOP_BF808430)) +#define R_IOP_BF80847C ((pvuint32_t) (A_IOP_BF80847C)) + +/** Unknown, seems to be related to SIF2? */ +#define IOP_CHCR_30 (1<<30) + +/** Transfer(used to kick a transfer and determine if a transfer is in progress). */ +#define IOP_CHCR_TR (1<<24) + +/** Linked List(DMA tags), valid for GPU(SIF2?), SPU and SIF0 */ +#define IOP_CHCR_LI (1<<10) + +/** Continuous transfer, TR is not cleared when transfer has completed. */ +#define IOP_CHCR_CO (1<<9) + +// Unknown +#define IOP_CHCR_08 (1<<8) + +/** Direction: 0 = "to RAM", 1 = "from RAM" */ +#define IOP_CHCR_DR (1<<0) + +#define IOP_TO_MEM 0 +#define IOP_FROM_MEM 1 + +#define IOP_I_STAT_VB (1 << 0) +#define IOP_I_STAT_SBUS (1 << 1) + +#endif /* __IOP_REGS_H__ */ diff --git a/sps2_basement/hardware/sbus/iop/iox_stat.h b/sps2_basement/hardware/sbus/iop/iox_stat.h new file mode 100644 index 0000000..8fb3c98 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/iox_stat.h @@ -0,0 +1,140 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * File attributes and directory entries. + */ + +#ifndef __SYS_IOX_STAT_H__ +#define __SYS_IOX_STAT_H__ + +#include + +#ifdef _EE +#ifndef NEWLIB_PORT_AWARE +#error "Using fio/fileXio functions directly in the newlib port will lead to problems." +#error "Use posix function calls instead." +#endif +#endif + +// Flags for chstat 'statmask' +#define FIO_CST_MODE 0x0001 +#define FIO_CST_ATTR 0x0002 +#define FIO_CST_SIZE 0x0004 +#define FIO_CST_CT 0x0008 +#define FIO_CST_AT 0x0010 +#define FIO_CST_MT 0x0020 +#define FIO_CST_PRVT 0x0040 + +// File mode flags +/** Format mask */ +#define FIO_S_IFMT 0xF000 +/** Symbolic link */ +#define FIO_S_IFLNK 0x4000 +/** Regular file */ +#define FIO_S_IFREG 0x2000 +/** Directory */ +#define FIO_S_IFDIR 0x1000 + +// Access rights +/** SUID */ +#define FIO_S_ISUID 0x0800 +/** SGID */ +#define FIO_S_ISGID 0x0400 +/** Sticky bit */ +#define FIO_S_ISVTX 0x0200 + +/** User access rights mask */ +#define FIO_S_IRWXU 0x01C0 +/** read */ +#define FIO_S_IRUSR 0x0100 +/** write */ +#define FIO_S_IWUSR 0x0080 +/** execute */ +#define FIO_S_IXUSR 0x0040 + +/** Group access rights mask */ +#define FIO_S_IRWXG 0x0038 +/** read */ +#define FIO_S_IRGRP 0x0020 +/** write */ +#define FIO_S_IWGRP 0x0010 +/** execute */ +#define FIO_S_IXGRP 0x0008 + +/** Others access rights mask */ +#define FIO_S_IRWXO 0x0007 +/** read */ +#define FIO_S_IROTH 0x0004 +/** write */ +#define FIO_S_IWOTH 0x0002 +/** execute */ +#define FIO_S_IXOTH 0x0001 + +// File mode checking macros +#define FIO_S_ISLNK(m) (((m) & FIO_S_IFMT) == FIO_S_IFLNK) +#define FIO_S_ISREG(m) (((m) & FIO_S_IFMT) == FIO_S_IFREG) +#define FIO_S_ISDIR(m) (((m) & FIO_S_IFMT) == FIO_S_IFDIR) + +/* File attributes that are retrieved using the getstat and dread calls, and + set using chstat. */ + +/* The following structures are only supported by iomanX. */ + +typedef struct { + unsigned int mode; + unsigned int attr; + unsigned int size; + unsigned char ctime[8]; + unsigned char atime[8]; + unsigned char mtime[8]; + unsigned int hisize; + /** Number of subs (main) / subpart number (sub) */ + unsigned int private_0; + unsigned int private_1; + unsigned int private_2; + unsigned int private_3; + unsigned int private_4; + /** Sector start. */ + unsigned int private_5; +} iox_stat_t; + +typedef struct { + iox_stat_t stat; + char name[256]; + unsigned int unknown; +} iox_dirent_t; + +/* The following defines are only supported by ioman. */ + +// File mode flags (for mode in io_stat_t) +/** Format mask */ +#define FIO_SO_IFMT 0x0038 +/** Symbolic link */ +#define FIO_SO_IFLNK 0x0008 +/** Regular file */ +#define FIO_SO_IFREG 0x0010 +/** Directory */ +#define FIO_SO_IFDIR 0x0020 + +/** read */ +#define FIO_SO_IROTH 0x0004 +/** write */ +#define FIO_SO_IWOTH 0x0002 +/** execute */ +#define FIO_SO_IXOTH 0x0001 + +// File mode checking macros +#define FIO_SO_ISLNK(m) (((m) & FIO_SO_IFMT) == FIO_SO_IFLNK) +#define FIO_SO_ISREG(m) (((m) & FIO_SO_IFMT) == FIO_SO_IFREG) +#define FIO_SO_ISDIR(m) (((m) & FIO_SO_IFMT) == FIO_SO_IFDIR) + +#endif /* __SYS_IOX_STAT_H__ */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/cdvd/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/Makefile new file mode 100644 index 0000000..a1e1090 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/Makefile @@ -0,0 +1,12 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +SUBDIRS = cdfs + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/Rules.make diff --git a/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/Makefile new file mode 100644 index 0000000..d7d05e4 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +# IOP_CFLAGS += -DSIO_DEBUG -DDEBUG + +IOP_OBJS = main.o cdfs_iop.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/cdfs_iop.c b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/cdfs_iop.c new file mode 100644 index 0000000..30ce054 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/cdfs_iop.c @@ -0,0 +1,1104 @@ +#include +#include +#include +#include + +#include "cdfs_iop.h" + +#define TRUE 1 +#define FALSE 0 + +// Macros for READ Data pattan +#define CdSecS2048 0 // sector size 2048 +#define CdSecS2328 1 // sector size 2328 +#define CdSecS2340 2 // sector size 2340 + +// Macros for Spindle control +#define CdSpinMax 0 +#define CdSpinNom 1 // Starts reading data at maximum rotational velocity and if a read error occurs, the rotational velocity is reduced. +#define CdSpinStm 0 // Recommended stream rotation speed. + +#define MAX_DIR_CACHE_SECTORS 32 + +struct DirTocEntry +{ + short length; + unsigned int fileLBA; + unsigned int fileLBA_bigend; + unsigned int fileSize; + unsigned int fileSize_bigend; + unsigned char dateStamp[6]; + unsigned char reserved1; + unsigned char fileProperties; + unsigned char reserved2[6]; + unsigned char filenameLength; + char filename[128]; +} __attribute__((packed)); // This is the internal format on the CD +// a file with a single character filename will have a 34byte toc entry +// (max 60 entries per sector)6 + +// TocEntry structure contains only the important stuff needed for export +// + +struct CacheInfoDir +{ + char pathname[1024]; // The pathname of the cached directory + unsigned int valid; // TRUE if cache data is valid, FALSE if not + + unsigned int path_depth; // The path depth of the cached directory (0 = root) + + unsigned int sector_start; // The start sector (LBA) of the cached directory + unsigned int sector_num; // The total size of the directory (in sectors) + unsigned int cache_offset; // The offset from sector_start of the cached area + unsigned int cache_size; // The size of the cached directory area (in sectors) + + u8 *cache; // The actual cached data +}; + +struct RootDirTocHeader +{ + u16 length; + u32 tocLBA; + u32 tocLBA_bigend; + u32 tocSize; + u32 tocSize_bigend; + u8 dateStamp[8]; + u8 reserved[6]; + u8 reserved2; + u8 reserved3; +} __attribute__((packed)); + +struct ASCIIDate +{ + char year[4]; + char month[2]; + char day[2]; + char hours[2]; + char minutes[2]; + char seconds[2]; + char hundreths[2]; + char terminator[1]; +} __attribute__((packed)); + +struct CDVolDesc +{ + u8 filesystemType; // 0x01 = ISO9660, 0x02 = Joliet, 0xFF = NULL + u8 volID[5]; // "CD001" + u8 reserved2; + u8 reserved3; + u8 sysIdName[32]; + u8 volName[32]; // The ISO9660 Volume Name + u8 reserved5[8]; + u32 volSize; // Volume Size + u32 volSizeBig; // Volume Size Big-Endian + u8 reserved6[32]; + u32 unknown1; + u32 unknown1_bigend; + u16 volDescSize; + u16 volDescSize_bigend; + u32 unknown3; + u32 unknown3_bigend; + u32 priDirTableLBA; // LBA of Primary Dir Table + u32 reserved7; + u32 secDirTableLBA; // LBA of Secondary Dir Table + u32 reserved8; + struct RootDirTocHeader rootToc; + u8 volSetName[128]; + u8 publisherName[128]; + u8 preparerName[128]; + u8 applicationName[128]; + u8 copyrightFileName[37]; + u8 abstractFileName[37]; + u8 bibliographyFileName[37]; + struct ASCIIDate creationDate; + struct ASCIIDate modificationDate; + struct ASCIIDate effectiveDate; + struct ASCIIDate expirationDate; + u8 reserved10; + u8 reserved11[1166]; +} __attribute__((packed)); + +enum Cache_getMode { + CACHE_START = 0, + CACHE_NEXT = 1 +}; + +enum PathMatch { + NOT_MATCH = 0, + MATCH, + SUBDIR +}; + +static struct CacheInfoDir cacheInfoDir; +static struct CDVolDesc cdVolDesc; +static sceCdRMode cdReadMode; +static u8 dvdvBuffer[2064]; + +static int cdvdChangedMagic = 0; +static int cdvdChangedMagicLast[CHANGED_MAX] = {-1}; + +/*********************************************** +* * +* PRIVATE FUNCTIONS * +* * +***********************************************/ + +// Used in findfile +static int strcasecmp(const char *s1, const char *s2) { + while (*s1 != '\0' && tolower(*s1) == tolower(*s2)) { + s1++; + s2++; + } + + return tolower(*(unsigned char *)s1) - tolower(*(unsigned char *)s2); +} + +/*********************************************** +* Determines if there is a valid disc inserted * +***********************************************/ +static int isValidDisc(void) { + int result; + + switch (sceCdGetDiskType()) { + case SCECdPSCD: + case SCECdPSCDDA: + case SCECdPS2CD: + case SCECdPS2CDDA: + case SCECdPS2DVD: + case SCECdDVDV: + result = 1; + break; + default: + result = 0; + } + + return result; +} + +// Copy a TOC Entry from the CD native format to our tidier format +static void copyToTocEntry(struct TocEntry *tocEntry, struct DirTocEntry *internalTocEntry) { + int i; + int filenamelen; + + DPRINTF("copyToTocEntry: from=%p, to=%p\n\n", tocEntry, internalTocEntry); + DPRINTF("copyToTocEntry: DirTocEntry=%i\n", internalTocEntry); + DPRINTF(" length......... %i\n", internalTocEntry->length); + DPRINTF(" fileLBA........ %i\n", internalTocEntry->fileLBA); + DPRINTF(" fileLBA_bigend. %i\n", internalTocEntry->fileLBA_bigend); + DPRINTF(" fileSize....... %i\n", internalTocEntry->fileSize); + DPRINTF(" fileSize_bigend %i\n", internalTocEntry->fileSize_bigend); + DPRINTF(" dateStamp...... %s\n", internalTocEntry->dateStamp); + DPRINTF(" reserved1...... %i\n", internalTocEntry->reserved1); + DPRINTF(" fileProperties. %i\n", internalTocEntry->fileProperties); + DPRINTF(" reserved2...... %s\n", internalTocEntry->reserved2); + DPRINTF(" filenameLength. %i\n", internalTocEntry->filenameLength); + DPRINTF(" filename....... %s\n", internalTocEntry->filename); + + tocEntry->fileSize = internalTocEntry->fileSize; + tocEntry->fileLBA = internalTocEntry->fileLBA; + tocEntry->fileProperties = internalTocEntry->fileProperties; + + if (cdVolDesc.filesystemType == 2) { + // This is a Joliet Filesystem, so use Unicode to ISO string copy + filenamelen = internalTocEntry->filenameLength / 2; + + for (i = 0; i < filenamelen; i++) + tocEntry->filename[i] = internalTocEntry->filename[(i << 1) + 1]; + } else { + filenamelen = internalTocEntry->filenameLength; + + // use normal string copy + strncpy(tocEntry->filename, internalTocEntry->filename, 128); + } + + tocEntry->filename[filenamelen] = 0; + + if (!(tocEntry->fileProperties & 0x02)) { + // strip the ;1 from the filename (if it's there) + strtok(tocEntry->filename, ";"); + } + + DPRINTF("copyToTocEntry: tocEntry=%i\n\n", tocEntry); + DPRINTF(" fileLBA........ %i\n\n", tocEntry->fileLBA); + DPRINTF(" fileSize....... %i\n\n", tocEntry->fileSize); + DPRINTF(" filename....... %s\n\n", tocEntry->filename); + DPRINTF(" fileProperties. %i\n\n", tocEntry->fileProperties); +} + + +// findPath should use the current directory cache to start it's search (in this case the root) +// and should change cacheInfoDir.pathname, to the path of the dir it finds +// it should also cache the first chunk of directory sectors, +// and fill the contents of the other elements of cacheInfoDir appropriately + +static int findPath(char *pathname) { + char *dirname; + char *seperator; + + int dir_entry; + int found_dir; + + struct DirTocEntry *tocEntryPointer; + struct TocEntry localTocEntry; + + dirname = strtok(pathname, "\\/"); + DPRINTF("findPath: trying to find directory %s\n\n", pathname); + + if (!isValidDisc()) + return FALSE; + + sceCdDiskReady(0); + + while (dirname != NULL) { + found_dir = FALSE; + + tocEntryPointer = (struct DirTocEntry *)cacheInfoDir.cache; + + // Always skip the first entry (self-refencing entry) + tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length); + + dir_entry = 0; + + for (; tocEntryPointer < (struct DirTocEntry *)(cacheInfoDir.cache + (cacheInfoDir.cache_size * 2048)); tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length)) { + // If we have a null toc entry, then we've either reached the end of the dir, or have reached a sector boundary + if (tocEntryPointer->length == 0) { + DPRINTF("Got a null pointer entry, so either reached end of dir, or end of sector\n\n"); + tocEntryPointer = (struct DirTocEntry *)(cacheInfoDir.cache + (((((u8 *)tocEntryPointer - cacheInfoDir.cache) / 2048) + 1) * 2048)); + } + + if (tocEntryPointer >= (struct DirTocEntry *)(cacheInfoDir.cache + (cacheInfoDir.cache_size * 2048))) { + // If we've gone past the end of the cache + // then check if there are more sectors to load into the cache + + if ((cacheInfoDir.cache_offset + cacheInfoDir.cache_size) < cacheInfoDir.sector_num) { + // If there are more sectors to load, then load them + cacheInfoDir.cache_offset += cacheInfoDir.cache_size; + cacheInfoDir.cache_size = cacheInfoDir.sector_num - cacheInfoDir.cache_offset; + + if (cacheInfoDir.cache_size > MAX_DIR_CACHE_SECTORS) + cacheInfoDir.cache_size = MAX_DIR_CACHE_SECTORS; + + if (!cdfs_readSect(cacheInfoDir.sector_start + cacheInfoDir.cache_offset, cacheInfoDir.cache_size, cacheInfoDir.cache)) { + DPRINTF("Couldn't Read from CD !\n\n"); + cacheInfoDir.valid = FALSE; // should we completely invalidate just because we couldnt read time? + return FALSE; + } + + tocEntryPointer = (struct DirTocEntry *)cacheInfoDir.cache; + } else { + cacheInfoDir.valid = FALSE; + return FALSE; + } + } + + // If the toc Entry is a directory ... + if (tocEntryPointer->fileProperties & 0x02) { + // Convert to our format (inc ascii name), for the check + copyToTocEntry(&localTocEntry, tocEntryPointer); + + // If it's the link to the parent directory, then give it the name ".." + if (dir_entry == 0) { + if (cacheInfoDir.path_depth != 0) { + DPRINTF("First directory entry in dir, so name it '..'\n\n"); + strcpy(localTocEntry.filename, ".."); + } + } + + // Check if this is the directory that we are looking for + if (strcasecmp(dirname, localTocEntry.filename) == 0) { + DPRINTF("Found the matching sub-directory\n\n"); + found_dir = TRUE; + + if (dir_entry == 0) { + // We've matched with the parent directory + // so truncate the pathname by one level + + if (cacheInfoDir.path_depth > 0) + cacheInfoDir.path_depth--; + + if (cacheInfoDir.path_depth == 0) { + // If at root then just clear the path to root + // (simpler than finding the colon seperator etc) + cacheInfoDir.pathname[0] = 0; + } else { + seperator = strrchr(cacheInfoDir.pathname, '/'); + + if (seperator != NULL) + *seperator = 0; + } + } else { + // otherwise append a seperator, and the matched directory + // to the pathname + strcat(cacheInfoDir.pathname, "/"); + DPRINTF("Adding '%s' to cached pathname - path depth = %d\n\n", dirname, cacheInfoDir.path_depth); + strcat(cacheInfoDir.pathname, dirname); + cacheInfoDir.path_depth++; + } + + // Exit out of the search loop + // (and find the next sub-directory, if there is one) + break; + } else { + DPRINTF("Found a directory, but it doesn't match\n\n"); + } + } + + dir_entry++; + + } // end of cache block search loop + + + // if we've reached here, without finding the directory, then it's not there + if (!found_dir) { + cacheInfoDir.valid = FALSE; + return FALSE; + } + + // find name of next dir + dirname = strtok(NULL, "\\/"); + + cacheInfoDir.sector_start = localTocEntry.fileLBA; + cacheInfoDir.sector_num = (localTocEntry.fileSize >> 11) + ((cdVolDesc.rootToc.tocSize & 2047) != 0); + + // Cache the start of the found directory + // (used in searching if this isn't the last dir, + // or used by whatever requested the cache in the first place if it is the last dir) + cacheInfoDir.cache_offset = 0; + cacheInfoDir.cache_size = cacheInfoDir.sector_num; + + if (cacheInfoDir.cache_size > MAX_DIR_CACHE_SECTORS) + cacheInfoDir.cache_size = MAX_DIR_CACHE_SECTORS; + + if (!cdfs_readSect(cacheInfoDir.sector_start + cacheInfoDir.cache_offset, cacheInfoDir.cache_size, cacheInfoDir.cache)) { + DPRINTF("Couldn't Read from CD, trying to read %d sectors, starting at sector %d !\n\n", + cacheInfoDir.cache_size, cacheInfoDir.sector_start + cacheInfoDir.cache_offset); + cacheInfoDir.valid = FALSE; // should we completely invalidate just because we couldnt read time? + return FALSE; + } + } + +// If we've got here then we found the requested directory + DPRINTF("findPath found the path\n\n"); + cacheInfoDir.valid = TRUE; + return TRUE; +} + +static int cdfs_getVolumeDescriptor(void) { + // Read until we find the last valid Volume Descriptor + int volDescSector; + static struct CDVolDesc localVolDesc; + DPRINTF("cdfs_getVolumeDescriptor called\n\n"); + + for (volDescSector = 16; volDescSector < 20; volDescSector++) { + cdfs_readSect(volDescSector, 1, (u8*)&localVolDesc); + + // If this is still a volume Descriptor + if (memcmp(localVolDesc.volID, "CD001", 5) == 0) { + if ((localVolDesc.filesystemType == 1) || + (localVolDesc.filesystemType == 2)) { + memcpy(&cdVolDesc, &localVolDesc, sizeof(struct CDVolDesc)); + } + } else + break; + } + +#ifdef DEBUG + switch (cdVolDesc.filesystemType) { + case 1: + DPRINTF("CD FileSystem is ISO9660\n\n"); + break; + case 2: + DPRINTF("CD FileSystem is Joliet\n\n"); + break; + default: + DPRINTF("CD FileSystem is unknown type\n\n"); + break; + } +#endif + // sceCdStop(); + return TRUE; +} + +static enum PathMatch comparePath(const char *path) { + int length; + int i; + + length = strlen(cacheInfoDir.pathname); + + for (i = 0; i < length; i++) { + // check if character matches + if (path[i] != cacheInfoDir.pathname[i]) { + // if not, then is it just because of different path seperator ? + if ((path[i] == '/') || (path[i] == '\\')) { + if ((cacheInfoDir.pathname[i] == '/') || (cacheInfoDir.pathname[i] == '\\')) { + continue; + } + } + + // if the characters don't match for any other reason then report a failure + return NOT_MATCH; + } + } + + // Reached the end of the Cached pathname + // if requested path is same length, then report exact match + if (path[length] == 0) + return MATCH; + + // if requested path is longer, and next char is a dir seperator + // then report sub-dir match + if ((path[length] == '/') || (path[length] == '\\')) + return SUBDIR; + else + return NOT_MATCH; +} + +// Check if a TOC Entry matches our extension list +static int compareTocEntry(char *filename, const char *extensions) { + static char ext_list[129]; + + char *token; + + char *ext_point; + + strncpy(ext_list, extensions, 128); + ext_list[128] = 0; + + token = strtok(ext_list, " ,"); + while (token != NULL) { + // if 'token' matches extension of 'filename' + // then return a match + ext_point = strrchr(filename, '.'); + + if (strcasecmp(ext_point, token) == 0) + return TRUE; + + /* Get next token: */ + token = strtok(NULL, " ,"); + } + + // If not match found then return FALSE + return FALSE; +} + +// Find, and cache, the requested directory, for use by GetDir or (and thus open) +// provide an optional offset variable, for use when caching dirs of greater than 500 files + +// returns TRUE if all TOC entries have been retrieved, or +// returns FALSE if there are more TOC entries to be retrieved +static int cdfs_cacheDir(const char *pathname, enum Cache_getMode getMode) { + // macke sure that the requested pathname is not directly modified + static char dirname[1024]; + + int path_len; + DPRINTF("Attempting to find, and cache, directory: %s\n", pathname); + + // Invalidate table of contents cache if disk changed + if (cdfs_checkDiskChanged(CHANGED_TOC)) { + cacheInfoDir.valid = FALSE; + } + + // only take any notice of the existing cache, if it's valid + if (cacheInfoDir.valid) { + // Check if the requested path is already cached + // if (strcasecmp(pathname,cacheInfoDir.pathname)==0) + if (comparePath(pathname) == MATCH) { + DPRINTF("CacheDir: The requested path is already cached\n"); + // If so, is the request ot cache the start of the directory, or to resume the next block ? + if (getMode == CACHE_START) { + DPRINTF(" and requested cache from start of dir\n"); + + if (cacheInfoDir.cache_offset == 0) { +// requested cache of start of the directory, and thats what's already cached +// so sit back and do nothing + DPRINTF(" and start of dir is already cached so nothing to do :o)\n"); + + cacheInfoDir.valid = TRUE; + return TRUE; + } else { +// Requested cache of start of the directory, but thats not what's cached +// so re-cache the start of the directory + DPRINTF(" but dir isn't cached from start, so re-cache existing dir from start\n"); + + // reset cache data to start of existing directory + cacheInfoDir.cache_offset = 0; + cacheInfoDir.cache_size = cacheInfoDir.sector_num; + + if (cacheInfoDir.cache_size > MAX_DIR_CACHE_SECTORS) + cacheInfoDir.cache_size = MAX_DIR_CACHE_SECTORS; + + // Now fill the cache with the specified sectors + if (!cdfs_readSect(cacheInfoDir.sector_start + cacheInfoDir.cache_offset, cacheInfoDir.cache_size, cacheInfoDir.cache)) { + DPRINTF("Couldn't Read from CD !\n"); + + cacheInfoDir.valid = FALSE; // should we completely invalidate just because we couldnt read first time? + return FALSE; + } + + cacheInfoDir.valid = TRUE; + return TRUE; + } + } else { + // getMode == CACHE_NEXT + // So get the next block of the existing directory + cacheInfoDir.cache_offset += cacheInfoDir.cache_size; + cacheInfoDir.cache_size = cacheInfoDir.sector_num - cacheInfoDir.cache_offset; + + if (cacheInfoDir.cache_size > MAX_DIR_CACHE_SECTORS) + cacheInfoDir.cache_size = MAX_DIR_CACHE_SECTORS; + + // Now fill the cache with the specified sectors + if (!cdfs_readSect(cacheInfoDir.sector_start + cacheInfoDir.cache_offset, cacheInfoDir.cache_size, cacheInfoDir.cache)) { + DPRINTF("Couldn't Read from CD !\n"); + + cacheInfoDir.valid = FALSE; // should we completely invalidate just because we couldnt read first time? + return FALSE; + } + + cacheInfoDir.valid = TRUE; + return TRUE; + } + } else { + // requested directory is not the cached directory (but cache is still valid) + DPRINTF("Cache is valid, but cached directory, is not the requested one\n" + "so check if the requested directory is a sub-dir of the cached one\n"); + DPRINTF("Requested Path = %s , Cached Path = %s\n", pathname, cacheInfoDir.pathname); + + if (comparePath(pathname) == SUBDIR) { +// If so then we can start our search for the path, from the currently cached directory + DPRINTF("Requested dir is a sub-dir of the cached directory,\n" + "so start search from current cached dir\n"); + // if the cached chunk, is not the start of the dir, + // then we will need to re-load it before starting search + if (cacheInfoDir.cache_offset != 0) { + cacheInfoDir.cache_offset = 0; + cacheInfoDir.cache_size = cacheInfoDir.sector_num; + if (cacheInfoDir.cache_size > MAX_DIR_CACHE_SECTORS) + cacheInfoDir.cache_size = MAX_DIR_CACHE_SECTORS; + + // Now fill the cache with the specified sectors + if (!cdfs_readSect(cacheInfoDir.sector_start + cacheInfoDir.cache_offset, cacheInfoDir.cache_size, cacheInfoDir.cache)) { + DPRINTF("Couldn't Read from CD !\n"); + cacheInfoDir.valid = FALSE; // should we completely invalidate just because we couldnt read time? + return FALSE; + } + } + + // start the search, with the path after the current directory + path_len = strlen(cacheInfoDir.pathname); + strcpy(dirname, pathname + path_len); + + // findPath should use the current directory cache to start it's search + // and should change cacheInfoDir.pathname, to the path of the dir it finds + // it should also cache the first chunk of directory sectors, + // and fill the contents of the other elements of cacheInfoDir appropriately + + return (findPath(dirname)); + } + } + } + +// If we've got here, then either the cache was not valid to start with +// or the requested path is not a subdirectory of the currently cached directory +// so lets start again + DPRINTF("The cache is not valid, or the requested directory is not a sub-dir of the cached one\n\n"); + + if (!isValidDisc()) { + DPRINTF("No supported disc inserted.\n"); + return -1; + } + + sceCdDiskReady(0); + + // Read the main volume descriptor + if (!cdfs_getVolumeDescriptor()) { + DPRINTF("Could not read the CD/DVD Volume Descriptor\n"); + return -1; + } + + DPRINTF("Read the CD Volume Descriptor\n\n"); + + cacheInfoDir.path_depth = 0; + strcpy(cacheInfoDir.pathname, ""); + + // Setup the lba and sector size, for retrieving the root toc + cacheInfoDir.cache_offset = 0; + cacheInfoDir.sector_start = cdVolDesc.rootToc.tocLBA; + cacheInfoDir.sector_num = (cdVolDesc.rootToc.tocSize >> 11) + ((cdVolDesc.rootToc.tocSize & 2047) != 0); + cacheInfoDir.cache_size = cacheInfoDir.sector_num; + + if (cacheInfoDir.cache_size > MAX_DIR_CACHE_SECTORS) + cacheInfoDir.cache_size = MAX_DIR_CACHE_SECTORS; + + // Now fill the cache with the specified sectors + if (!cdfs_readSect(cacheInfoDir.sector_start + cacheInfoDir.cache_offset, cacheInfoDir.cache_size, cacheInfoDir.cache)) { + DPRINTF("Couldn't Read from CD !\n"); + cacheInfoDir.valid = FALSE; // should we completely invalidate just because we couldnt read time? + return FALSE; + } + + DPRINTF("Read the first block from the root directory\n"); + DPRINTF("Calling findPath\n"); + strcpy(dirname, pathname); + + return (findPath(dirname)); +} + +static void splitPath(const char *constpath, char *dir, char *fname) { + // 255 char max path-length is an ISO9660 restriction + // we must change this for Joliet or relaxed iso restriction support + static char pathcopy[1024 + 1]; + char *slash; + + strncpy(pathcopy, constpath, 1024); + slash = strrchr(pathcopy, '/'); + + // if the path doesn't contain a '/' then look for a '\' + if (!slash) + slash = strrchr(pathcopy, (int)'\\'); + + // if a slash was found + if (slash != NULL) { + // null terminate the path + slash[0] = 0; + // and copy the path into 'dir' + strncpy(dir, pathcopy, 1024); + dir[255] = 0; + + // copy the filename into 'fname' + strncpy(fname, slash + 1, 128); + fname[128] = 0; + } else { + dir[0] = 0; + + strncpy(fname, pathcopy, 128); + fname[128] = 0; + } +} + +/*********************************************** +* * +* CDFS FUNCTIONS * +* * +***********************************************/ + +int cdfs_prepare(void) { + + // Initialise the directory cache + strcpy(cacheInfoDir.pathname, ""); // The pathname of the cached directory + cacheInfoDir.valid = FALSE; // Cache is not valid + cacheInfoDir.path_depth = 0; // 0 = root) + cacheInfoDir.sector_start = 0; // The start sector (LBA) of the cached directory + cacheInfoDir.sector_num = 0; // The total size of the directory (in sectors) + cacheInfoDir.cache_offset = 0; // The offset from sector_start of the cached area + cacheInfoDir.cache_size = 0; // The size of the cached directory area (in sectors) + + if (cacheInfoDir.cache == NULL) + cacheInfoDir.cache = (u8 *)AllocSysMemory(0, MAX_DIR_CACHE_SECTORS * 2048, NULL); + + // setup the cdReadMode structure + cdReadMode.trycount = 0; + cdReadMode.spindlctrl = SCECdSpinStm; + cdReadMode.datapattern = SCECdSecS2048; + + return 0; +} + +int cdfs_start(void) { + return sceCdInit(SCECdINoD); +} + +int cdfs_finish(void) { + if (cacheInfoDir.cache) + FreeSysMemory(cacheInfoDir.cache); + + return 0; +} + +int cdfs_findfile(const char *fname, struct TocEntry *tocEntry) { + static char filename[128 + 1]; + static char pathname[1024 + 1]; + + struct DirTocEntry *tocEntryPointer; + + DPRINTF("cdfs_findfile called\n\n"); + + splitPath(fname, pathname, filename); + DPRINTF("Trying to find file: %s in directory: %s\n", filename, pathname); + + // Invalidate table of contents cache if disk changed + if (cdfs_checkDiskChanged(CHANGED_TOC)) { + cacheInfoDir.valid = FALSE; + } + + if ((cacheInfoDir.valid) && (comparePath(pathname) == MATCH)) { + // the directory is already cached, so check through the currently + // cached chunk of the directory first + + tocEntryPointer = (struct DirTocEntry *)cacheInfoDir.cache; + + for (; tocEntryPointer < (struct DirTocEntry *)(cacheInfoDir.cache + (cacheInfoDir.cache_size * 2048)); tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length)) { + if (tocEntryPointer->length == 0) { + DPRINTF("Got a null pointer entry, so either reached end of dir, or end of sector\n"); + tocEntryPointer = (struct DirTocEntry *)(cacheInfoDir.cache + (((((u8 *)tocEntryPointer - cacheInfoDir.cache) / 2048) + 1) * 2048)); + } + + if (tocEntryPointer >= (struct DirTocEntry *)(cacheInfoDir.cache + (cacheInfoDir.cache_size * 2048))) { + // reached the end of the cache block + break; + } + + copyToTocEntry(tocEntry, tocEntryPointer); + + if (strcasecmp(tocEntry->filename, filename) == 0) { + // and it matches !! + return TRUE; + } + } // end of for loop + + // If that was the only dir block, and we havent found it, then fail + if (cacheInfoDir.cache_size == cacheInfoDir.sector_num) + return FALSE; + + // Otherwise there is more dir to check + if (cacheInfoDir.cache_offset == 0) { + // If that was the first block then continue with the next block + if (!cdfs_cacheDir(pathname, CACHE_NEXT)) + return FALSE; + } else { + // otherwise (if that wasnt the first block) then start checking from the start + if (!cdfs_cacheDir(pathname, CACHE_START)) + return FALSE; + } + } else { + DPRINTF("Trying to cache directory\n\n"); + // The wanted directory wasnt already cached, so cache it now + if (!cdfs_cacheDir(pathname, CACHE_START)) { + DPRINTF("Failed to cache directory\n\n"); + return FALSE; + } + } + + // If we've got here, then we have a block of the directory cached, and want to check + // from this point, to the end of the dir + DPRINTF("cache_size = %d\n", cacheInfoDir.cache_size); + while (cacheInfoDir.cache_size > 0) { + tocEntryPointer = (struct DirTocEntry *)cacheInfoDir.cache; + + if (cacheInfoDir.cache_offset == 0) + tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length); + + for (; tocEntryPointer < (struct DirTocEntry *)(cacheInfoDir.cache + (cacheInfoDir.cache_size * 2048)); tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length)) { + if (tocEntryPointer->length == 0) { + DPRINTF("Got a null pointer entry, so either reached end of dir, or end of sector\n"); + DPRINTF("Offset into cache = %d bytes\n", (u8 *)tocEntryPointer - cacheInfoDir.cache); + tocEntryPointer = (struct DirTocEntry *)(cacheInfoDir.cache + (((((u8 *)tocEntryPointer - cacheInfoDir.cache) / 2048) + 1) * 2048)); + } + + if (tocEntryPointer >= (struct DirTocEntry *)(cacheInfoDir.cache + (cacheInfoDir.cache_size * 2048))) { + // reached the end of the cache block + break; + } + + copyToTocEntry(tocEntry, tocEntryPointer); + + if (strcasecmp(tocEntry->filename, filename) == 0) { + DPRINTF("Found a matching file\n\n"); + // and it matches !! + return TRUE; + } + + DPRINTF("Non-matching file - looking for %s , found %s\n", filename, tocEntry->filename); + } // end of for loop + + DPRINTF("Reached end of cache block\n"); + // cache the next block + cdfs_cacheDir(pathname, CACHE_NEXT); + } + + // we've run out of dir blocks to cache, and still not found it, so fail + DPRINTF("cdfs_findfile: could not find file\n"); + return FALSE; +} + +/******************** +* Optimised CD Read * +********************/ + +int cdfs_readSect(u32 lsn, u32 sectors, u8 *buf) { + u32 i; + u32 consecutive_sectors = (sectors > 2) ? (sectors * 2048) / 2064 : 0; + int retry; + int result = 0; + cdReadMode.trycount = 32; + + for (retry = 0; retry < 32; retry++) { // 32 retries + if (retry <= 8) + cdReadMode.spindlctrl = 1; // Try fast reads for first 8 tries + else + cdReadMode.spindlctrl = 0; // Then try slow reads + + if (!isValidDisc()) + return FALSE; + + sceCdDiskReady(0); + + if (sceCdGetDiskType() == SCECdDVDV) + { + if (consecutive_sectors > 0) + { + result = !sceCdReadDVDV(lsn, consecutive_sectors, buf, &cdReadMode); + if (result == 0) + { + sceCdSync(0); + result = sceCdGetError(); + } + if (result != 0) + { + continue; + } + } + for (i = 0; i < consecutive_sectors; i += 1) + { + memmove(buf + (2048 * i), buf + (2064 * i) + 12, 2048); + } + for (i = consecutive_sectors; i < sectors; i += 1) + { + result = !sceCdReadDVDV(lsn + i, 1, dvdvBuffer, &cdReadMode); + if (result == 0) + { + sceCdSync(0); + result = sceCdGetError(); + } + if (result != 0) + { + break; + } + memcpy(buf + (2048 * i), dvdvBuffer + 12, 2048); + } + } + else + { + result = !sceCdRead(lsn, sectors, buf, &cdReadMode); + if (result == 0) + { + sceCdSync(0); + result = sceCdGetError(); + } + } + + if (result == 0) + break; + } + + cdReadMode.trycount = 32; + cdReadMode.spindlctrl = 1; + + if (result == 0) + return TRUE; + + memset(buf, 0, (sectors << 11)); + + return FALSE; // error +} + +int cdfs_getDir(const char *pathname, const char *extensions, enum CDFS_getMode getMode, struct TocEntry tocEntry[], unsigned int req_entries) { + int matched_entries; + int dir_entry; + + struct TocEntry localTocEntry; + struct DirTocEntry *tocEntryPointer; + + DPRINTF("cdfs_getDir Request\n\n"); + + matched_entries = 0; + + // pre-cache the dir (and get the new pathname - in-case selected "..") + if (!cdfs_cacheDir(pathname, CACHE_START)) { + DPRINTF("cdfs_getDir - Call of cdfs_cacheDir failed\n\n"); + return -1; + } + + DPRINTF("requested directory is %d sectors\n", cacheInfoDir.sector_num); + + if ((getMode == CDFS_GET_DIRS_ONLY) || (getMode == CDFS_GET_FILES_AND_DIRS)) { + // Cache the start of the requested directory + if (!cdfs_cacheDir(cacheInfoDir.pathname, CACHE_START)) { + DPRINTF("cdfs_getDir - Call of cdfs_cacheDir failed\n\n"); + return -1; + } + + tocEntryPointer = (struct DirTocEntry *)cacheInfoDir.cache; + // skip the first self-referencing entry + tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length); + + // skip the parent entry if this is the root + if (cacheInfoDir.path_depth == 0) + tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length); + + dir_entry = 0; + + while (1) { + DPRINTF("cdfs_getDir - inside while-loop\n\n"); + + // parse the current cache block + for (; tocEntryPointer < (struct DirTocEntry *)(cacheInfoDir.cache + (cacheInfoDir.cache_size * 2048)); tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length)) { + if (tocEntryPointer->length == 0) { + // if we have a toc entry length of zero, + // then we've either reached the end of the sector, or the end of the dir + // so point to next sector (if there is one - will be checked by next condition) + + tocEntryPointer = (struct DirTocEntry *)(cacheInfoDir.cache + (((((u8 *)tocEntryPointer - cacheInfoDir.cache) / 2048) + 1) * 2048)); + } + + if (tocEntryPointer >= (struct DirTocEntry *)(cacheInfoDir.cache + (cacheInfoDir.cache_size * 2048))) { + // we've reached the end of the current cache block (which may be end of entire dir + // so just break the loop + break; + } + + // Check if the current entry is a dir or a file + if (tocEntryPointer->fileProperties & 0x02) { + DPRINTF("We found a dir, and we want all dirs\n\n"); + copyToTocEntry(&localTocEntry, tocEntryPointer); + + if (dir_entry == 0) { + if (cacheInfoDir.path_depth != 0) { + DPRINTF("It's the first directory entry, so name it '..'\n\n"); + strcpy(localTocEntry.filename, ".."); + } + } + + // Copy from localTocEntry + tocEntry[matched_entries] = localTocEntry; + matched_entries++; + } else { // it must be a file + DPRINTF("We found a file, but we dont want files (at least not yet)\n\n"); + } + + dir_entry++; + + if (matched_entries >= req_entries) // if we've filled the requested buffer + return (matched_entries); // then just return + + } // end of the current cache block + + // if there is more dir to load, then load next chunk, else finish + if ((cacheInfoDir.cache_offset + cacheInfoDir.cache_size) < cacheInfoDir.sector_num) { + if (!cdfs_cacheDir(cacheInfoDir.pathname, CACHE_NEXT)) { + // failed to cache next block (should return TRUE even if + // there is no more directory, as long as a CD read didnt fail + return -1; + } + } else + break; + + tocEntryPointer = (struct DirTocEntry *)cacheInfoDir.cache; + } + } + + // Next do files + if ((getMode == CDFS_GET_FILES_ONLY) || (getMode == CDFS_GET_FILES_AND_DIRS)) { + // Cache the start of the requested directory + if (!cdfs_cacheDir(cacheInfoDir.pathname, CACHE_START)) { + DPRINTF("cdfs_getDir - Call of cdfs_cacheDir failed\n\n"); + return -1; + } + + tocEntryPointer = (struct DirTocEntry *)cacheInfoDir.cache; + + // skip the first self-referencing entry + tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length); + + // skip the parent entry if this is the root + if (cacheInfoDir.path_depth == 0) + tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length); + + dir_entry = 0; + + while (1) { + DPRINTF("cdfs_getDir - inside while-loop\n\n"); + + // parse the current cache block + for (; tocEntryPointer < (struct DirTocEntry *)(cacheInfoDir.cache + (cacheInfoDir.cache_size * 2048)); tocEntryPointer = (struct DirTocEntry *)((u8 *)tocEntryPointer + tocEntryPointer->length)) { + if (tocEntryPointer->length == 0) { + // if we have a toc entry length of zero, + // then we've either reached the end of the sector, or the end of the dir + // so point to next sector (if there is one - will be checked by next condition) + + tocEntryPointer = (struct DirTocEntry *)(cacheInfoDir.cache + (((((u8 *)tocEntryPointer - cacheInfoDir.cache) / 2048) + 1) * 2048)); + } + + if (tocEntryPointer >= (struct DirTocEntry *)(cacheInfoDir.cache + (cacheInfoDir.cache_size * 2048))) { + // we've reached the end of the current cache block (which may be end of entire dir + // so just break the loop + break; + } + + // Check if the current entry is a dir or a file + if (tocEntryPointer->fileProperties & 0x02) { + DPRINTF("We don't want files now\n\n"); + } else { // it must be a file + copyToTocEntry(&localTocEntry, tocEntryPointer); + + if (strlen(extensions) > 0) { + // check if the file matches the extension list + if (compareTocEntry(localTocEntry.filename, extensions)) { + DPRINTF("We found a file that matches the requested extension list\n\n"); + // Copy from localTocEntry + tocEntry[matched_entries] = localTocEntry; + matched_entries++; + } else { + DPRINTF("We found a file, but it didnt match the requested extension list\n\n"); + } + } else { // no extension list to match against + DPRINTF("We found a file, and there is not extension list to match against\n\n"); + + // Copy from localTocEntry + tocEntry[matched_entries] = localTocEntry; + matched_entries++; + } + } + + dir_entry++; + + if (matched_entries >= req_entries) // if we've filled the requested buffer + return (matched_entries); // then just return + + } // end of the current cache block + + + // if there is more dir to load, then load next chunk, else finish + if ((cacheInfoDir.cache_offset + cacheInfoDir.cache_size) < cacheInfoDir.sector_num) { + if (!cdfs_cacheDir(cacheInfoDir.pathname, CACHE_NEXT)) { + // failed to cache next block (should return TRUE even if + // there is no more directory, as long as a CD read didnt fail + return -1; + } + } else + break; + + tocEntryPointer = (struct DirTocEntry *)cacheInfoDir.cache; + } + } + // reached the end of the dir, before filling up the requested entries + + return (matched_entries); +} + +// This function uses sceCdTrayReq to check if the disc in the disc drive has changed. +// Once sceCdTrayReq is called it will reset the flag inside CDVDMAN. +// Avoid using sceCdTrayReq with SCECdTrayCheck as arguemnt in other code if possible. + +int cdfs_checkDiskChanged(enum Cdvd_Changed_Index index) { + u32 res = 0; + sceCdTrayReq(SCECdTrayCheck, &res); + if (res) { + cdvdChangedMagic += 1; + } + if (cdvdChangedMagic != cdvdChangedMagicLast[index]) { + cdvdChangedMagicLast[index] = cdvdChangedMagic; + return TRUE; + } + return FALSE; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/cdfs_iop.h b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/cdfs_iop.h new file mode 100644 index 0000000..1f4c465 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/cdfs_iop.h @@ -0,0 +1,40 @@ +#ifndef _CDFS_IOP_H +#define _CDFS_IOP_H + +#ifdef DEBUG +#define DPRINTF(args...) printf(args) +#else +#define DPRINTF(args...) do { } while(0) +#endif + +#define CDFS_FILEPROPERTY_DIR 0x02 + +struct TocEntry { + u32 fileLBA; + u32 fileSize; + u8 fileProperties; + unsigned char dateStamp[8]; + char filename[128 + 1]; +} __attribute__((packed)); + +enum CDFS_getMode { + CDFS_GET_FILES_ONLY = 1, + CDFS_GET_DIRS_ONLY = 2, + CDFS_GET_FILES_AND_DIRS = 3 +}; + +enum Cdvd_Changed_Index { + CHANGED_TOC = 0, + CHANGED_FIO = 1, + CHANGED_MAX +}; + +int cdfs_prepare(void); +int cdfs_start(void); +int cdfs_finish(void); +int cdfs_findfile(const char *fname, struct TocEntry *tocEntry); +int cdfs_readSect(u32 lsn, u32 sectors, u8 *buf); +int cdfs_getDir(const char *pathname, const char *extensions, enum CDFS_getMode getMode, struct TocEntry tocEntry[], unsigned int req_entries); +int cdfs_checkDiskChanged(enum Cdvd_Changed_Index index); + +#endif // _CDFS_H diff --git a/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/imports.lst new file mode 100644 index 0000000..ebbbf50 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/imports.lst @@ -0,0 +1,41 @@ +cdvdman_IMPORTS_start +I_sceCdInit +I_sceCdGetError +I_sceCdRead +I_sceCdReadDVDV +I_sceCdStop +I_sceCdSync +I_sceCdDiskReady +I_sceCdGetDiskType +I_sceCdTrayReq +cdvdman_IMPORTS_end + +ioman_IMPORTS_start +I_AddDrv +I_DelDrv +ioman_IMPORTS_end + +sysclib_IMPORTS_start +I_tolower +I_strcpy +I_strncpy +I_strncmp +I_strtok +I_strrchr +I_strcat +I_strlen +I_memset +I_memcmp +I_memcpy +I_memmove +sysclib_IMPORTS_end + +stdio_IMPORTS_start +I_printf +I_sprintf +stdio_IMPORTS_end + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +sysmem_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/irx_imports.h new file mode 100644 index 0000000..9399fd1 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/irx_imports.h @@ -0,0 +1,35 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ + +#include +#include +#include +#include +#include +#ifdef SIO_DEBUG +#include +#endif +#include +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/main.c b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/main.c new file mode 100644 index 0000000..d6004e0 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/cdvd/cdfs/src/main.c @@ -0,0 +1,455 @@ +#include +#include +#include +#include + +#include "cdfs_iop.h" + +// 16 sectors worth of toc entry +#define MAX_FILES_PER_FOLDER 256 +#define MAX_FILES_OPENED 16 +#define MAX_FOLDERS_OPENED 16 +#define MAX_BYTES_READ 16384 + +#define DRIVER_UNIT_NAME "cdfs" +#define DRIVER_UNIT_VERSION 2 + +struct fdtable +{ + iop_file_t *fd; + int fileSize; + int LBA; + int filePos; +}; + +struct fodtable +{ + iop_file_t *fd; + int files; + int filesIndex; + struct TocEntry entries[MAX_FILES_PER_FOLDER]; +}; + +// File Descriptors +static struct fdtable fd_table[MAX_FILES_OPENED]; +static int fd_used[MAX_FILES_OPENED]; + +// Folder Descriptors +static struct fodtable fod_table[MAX_FOLDERS_OPENED]; +static int fod_used[MAX_FOLDERS_OPENED]; + +// global variables +static int lastsector = -1; +static int last_bk = 0; + +/*********************************************** +* * +* DRIVER FUNCTIONS * +* * +***********************************************/ + +static int fio_init(iop_device_t *driver) +{ + printf("%s\n", driver->desc); + printf("Re-edited by fjtrujy\n"); + printf("Original implementation\n"); + printf("by A.Lee (aka Hiryu) & Nicholas Van Veen (aka Sjeep)\n"); + printf("CDFS: Initializing '%s' file driver.\n", driver->name); + + cdfs_start(); + return 0; +} + +static int fio_deinit(iop_device_t *f) +{ + DPRINTF("CDFS: fio_deinit called.\n"); + DPRINTF(" kernel_fd.. %p\n", f); + return cdfs_finish(); +} + +static int fio_open(iop_file_t *f, const char *name, int mode) +{ + int j; + static struct TocEntry tocEntry; + + DPRINTF("CDFS: fio_open called.\n"); + DPRINTF(" kernel_fd.. %p\n", f); + DPRINTF(" name....... %s %x\n", name, (int)name); + DPRINTF(" mode....... %d\n\n", mode); + + // Invalidate last sector cache if disk changed + if (cdfs_checkDiskChanged(CHANGED_FIO)) { + lastsector = -1; + last_bk = 0; + } + + // check if the file exists + if (!cdfs_findfile(name, &tocEntry)) { + printf("***** FILE %s CAN NOT FOUND ******\n\n", name); + return -1; + } + + if (mode != O_RDONLY) { + printf("mode is different than O_RDONLY, expected %i, received %i\n\n", O_RDONLY, mode); + return -2; + } + + DPRINTF("CDFS: fio_open TocEntry info\n"); + DPRINTF(" TocEntry....... %p\n", &tocEntry); + DPRINTF(" fileLBA........ %i\n", tocEntry.fileLBA); + DPRINTF(" fileSize....... %i\n", tocEntry.fileSize); + DPRINTF(" fileProperties. %i\n", tocEntry.fileProperties); + DPRINTF(" dateStamp...... %s\n", tocEntry.dateStamp); + DPRINTF(" filename....... %s\n", tocEntry.filename); + + // set up a new file descriptor + for (j = 0; j < MAX_FILES_OPENED; j++) { + if (fd_used[j] == 0) + break; + } + + if (j >= MAX_FILES_OPENED) { + printf("File descriptor overflow!!\n\n"); + return -3; + } + + fd_used[j] = 1; + fd_table[j].fd = f; + fd_table[j].fileSize = tocEntry.fileSize; + fd_table[j].LBA = tocEntry.fileLBA; + fd_table[j].filePos = 0; + + f->privdata = (void *)j; + + return j; +} + +static int fio_close(iop_file_t *f) +{ + int i; + + DPRINTF("CDFS: fio_close called.\n"); + DPRINTF(" kernel fd.. %p\n\n", f); + + i = (int)f->privdata; + + if (i >= MAX_FILES_OPENED) { + printf("fio_close: ERROR: File does not appear to be open!\n"); + return -1; + } + + fd_used[i] = 0; + + return 0; +} + +static int fio_read(iop_file_t *f, void *buffer, int size) +{ + int i; + + int start_sector; + int off_sector; + int num_sectors; + + int read = 0; + static u8 local_buffer[9 * 2048]; + + DPRINTF("CDFS: fio_read called\n\n"); + DPRINTF(" kernel_fd... %p\n", f); + DPRINTF(" buffer...... 0x%X\n", (int)buffer); + DPRINTF(" size........ %d\n\n", size); + + i = (int)f->privdata; + + if (i >= MAX_FILES_OPENED) { + printf("fio_read: ERROR: File does not appear to be open!\n"); + return -1; + } + + // A few sanity checks + if (fd_table[i].filePos > fd_table[i].fileSize) { + // We cant start reading from past the beginning of the file + return 0; // File exists but we couldnt read anything from it + } + + if ((fd_table[i].filePos + size) > fd_table[i].fileSize) + size = fd_table[i].fileSize - fd_table[i].filePos; + + if (size <= 0) + return 0; + + if (size > MAX_BYTES_READ) + size = MAX_BYTES_READ; + + // Now work out where we want to start reading from + start_sector = fd_table[i].LBA + (fd_table[i].filePos >> 11); + off_sector = (fd_table[i].filePos & 0x7FF); + + num_sectors = (off_sector + size); + num_sectors = (num_sectors >> 11) + ((num_sectors & 2047) != 0); + + DPRINTF("fio_read: read sectors %d to %d\n", start_sector, start_sector + num_sectors); + + // Skip a Sector for equal (use the last sector in buffer) + if (start_sector == lastsector) { + read = 1; + if (last_bk > 0) + memcpy(local_buffer, local_buffer + 2048 * (last_bk), 2048); + last_bk = 0; + } + + lastsector = start_sector + num_sectors - 1; + // Read the data (we only ever get 16KB max request at once) + + if (read == 0 || (read == 1 && num_sectors > 1)) { + if (!cdfs_readSect(start_sector + read, num_sectors - read, local_buffer + ((read) << 11))) { + DPRINTF("Couldn't Read from file for some reason\n"); + } + + last_bk = num_sectors - 1; + } + + memcpy(buffer, local_buffer + off_sector, size); + fd_table[i].filePos += size; + + return (size); +} + +static int fio_write(iop_file_t *f, void *buffer, int size) +{ + if (size == 0) + return 0; + else { + printf("CDFS: dummy fio_write function called, this is not a re-writer xD"); + return -1; + } +} + +static int fio_lseek(iop_file_t *f, int offset, int whence) +{ + int i; + + DPRINTF("CDFS: fio_lseek called.\n"); + DPRINTF(" kernel_fd... %p\n", f); + DPRINTF(" offset...... %d\n", offset); + DPRINTF(" whence...... %d\n\n", whence); + + i = (int) f->privdata; + + if (i >= 16) { + DPRINTF("fio_lseek: ERROR: File does not appear to be open!\n"); + return -1; + } + + switch (whence) { + case SEEK_SET: + fd_table[i].filePos = offset; + break; + + case SEEK_CUR: + fd_table[i].filePos += offset; + break; + + case SEEK_END: + fd_table[i].filePos = fd_table[i].fileSize + offset; + break; + + default: + return -1; + } + + if (fd_table[i].filePos < 0) + fd_table[i].filePos = 0; + + if (fd_table[i].filePos > fd_table[i].fileSize) + fd_table[i].filePos = fd_table[i].fileSize; + + return fd_table[i].filePos; +} + +static int fio_openDir(iop_file_t *f, const char *path) { + int j; + + DPRINTF("CDFS: fio_openDir called.\n"); + DPRINTF(" kernel_fd.. %p\n", f); + DPRINTF(" name....... %s\n", f->device->name); + DPRINTF(" mode....... %d\n\n", f->mode); + DPRINTF(" path....... %s\n\n", path); + + // set up a new file descriptor + for (j = 0; j < MAX_FOLDERS_OPENED; j++) { + if (fod_used[j] == 0) + break; + } + + if (j >= MAX_FOLDERS_OPENED) + return -3; + + fod_table[j].files = cdfs_getDir(path, NULL, CDFS_GET_FILES_AND_DIRS, fod_table[j].entries, MAX_FILES_PER_FOLDER); + if (fod_table[j].files < 0) { + printf("The path doesn't exist\n\n"); + return -2; + } + + fod_table[j].filesIndex = 0; + fod_table[j].fd = f; + fod_used[j] = 1; + + DPRINTF("ITEMS %i\n\n", fod_table[j].files); +#ifdef DEBUG + int index = 0; + for (index=0; index < fod_table[j].files; index++) { + struct TocEntry tocEntry = fod_table[j].entries[index]; + + DPRINTF("CDFS: fio_openDir index=%d TocEntry info\n", index); + DPRINTF(" TocEntry....... %p\n", &tocEntry); + DPRINTF(" fileLBA........ %i\n", tocEntry.fileLBA); + DPRINTF(" fileSize....... %i\n", tocEntry.fileSize); + DPRINTF(" fileProperties. %i\n", tocEntry.fileProperties); + DPRINTF(" dateStamp....... %s\n", tocEntry.dateStamp); + DPRINTF(" filename....... %s\n", tocEntry.filename); + } +#endif + + f->privdata = (void *)j; + + return j; +} + +static int fio_closeDir(iop_file_t *fd) +{ + int i; + + DPRINTF("CDFS: fio_closeDir called.\n"); + DPRINTF(" kernel_fd.. %p\n", fd); + + i = (int)fd->privdata; + + if (i >= MAX_FOLDERS_OPENED) { + printf("fio_close: ERROR: File does not appear to be open!\n"); + return -1; + } + + fod_used[i] = 0; + return 0; +} + +static int fio_dread(iop_file_t *fd, io_dirent_t *dirent) +{ + int i; + int filesIndex; + struct TocEntry entry; + + DPRINTF("CDFS: fio_dread called.\n"); + DPRINTF(" kernel_fd.. %p\n", fd); + DPRINTF(" mode....... %p\n\n", dirent); + + i = (int)fd->privdata; + + if (i >= MAX_FOLDERS_OPENED) { + printf("fio_dread: ERROR: Folder does not appear to be open!\n\n"); + return -1; + } + + filesIndex = fod_table[i].filesIndex; + if (filesIndex >= fod_table[i].files) { + printf("fio_dread: No more items pending to read!\n\n"); + return -1; + } + + entry = fod_table[i].entries[filesIndex]; + + DPRINTF("fio_dread: fod_table index=%i, fileIndex=%i\n\n", i, filesIndex); + DPRINTF("fio_dread: entries=%i\n\n", fod_table[i].files); + DPRINTF("fio_dread: reading entry\n\n"); + DPRINTF(" entry.. %p\n", entry); + DPRINTF(" filesize....... %i\n\n", entry.fileSize); + DPRINTF(" filename....... %s\n\n", entry.filename); + DPRINTF(" fileproperties.. %i\n\n", entry.fileProperties); + + dirent->stat.mode = (entry.fileProperties == CDFS_FILEPROPERTY_DIR) ? FIO_SO_IFDIR : FIO_SO_IFREG; + dirent->stat.attr = entry.fileProperties; + dirent->stat.size = entry.fileSize; + memcpy(dirent->stat.ctime, entry.dateStamp, 8); + memcpy(dirent->stat.atime, entry.dateStamp, 8); + memcpy(dirent->stat.mtime, entry.dateStamp, 8); + strncpy(dirent->name, entry.filename, 128); + dirent->unknown = 0; + + fod_table[i].filesIndex++; + return fod_table[i].filesIndex; +} + +static int fio_getstat(iop_file_t *fd, const char *name, io_stat_t *stat) +{ + struct TocEntry entry; + int ret = -1; + + DPRINTF("CDFS: fio_getstat called.\n"); + DPRINTF(" kernel_fd.. %p\n", fd); + DPRINTF(" name....... %s\n\n", name); + + ret = cdfs_findfile(name, &entry); + + DPRINTF(" entry.. %p\n", entry); + DPRINTF(" filesize....... %i\n\n", entry.fileSize); + DPRINTF(" filename....... %s\n\n", entry.filename); + DPRINTF(" fileproperties.. %i\n\n", entry.fileProperties); + + stat->mode = (entry.fileProperties == CDFS_FILEPROPERTY_DIR) ? FIO_SO_IFDIR : FIO_SO_IFREG; + stat->attr = entry.fileProperties; + stat->size = entry.fileSize; + memcpy(stat->ctime, entry.dateStamp, 8); + memcpy(stat->atime, entry.dateStamp, 8); + memcpy(stat->mtime, entry.dateStamp, 8); + + return ret; +} + +static int cdfs_dummy() { + DPRINTF("CDFS: dummy function called\n\n"); + return -5; +} + +static iop_device_ops_t fio_ops = { + fio_init, + fio_deinit, + cdfs_dummy, + fio_open, + fio_close, + fio_read, + fio_write, + fio_lseek, + cdfs_dummy, + cdfs_dummy, + cdfs_dummy, + cdfs_dummy, + fio_openDir, + fio_closeDir, + fio_dread, + fio_getstat, + cdfs_dummy +}; + +int _start(int argc, char **argv) +{ + static iop_device_t fio_driver; + + // Prepare cache and read mode + cdfs_prepare(); + + char driverDesc[50]; + sprintf(driverDesc, "%s Filedriver v%i", DRIVER_UNIT_NAME, DRIVER_UNIT_VERSION); + + // setup the fio_driver structure + fio_driver.name = DRIVER_UNIT_NAME; + fio_driver.type = IOP_DT_FS; + fio_driver.version = DRIVER_UNIT_VERSION; + fio_driver.desc = driverDesc; + fio_driver.ops = &fio_ops; + + DelDrv(DRIVER_UNIT_NAME); + if(AddDrv(&fio_driver) != 0) { return(-1); } + + return(0); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/fs/Makefile new file mode 100644 index 0000000..e95c6da --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/Makefile @@ -0,0 +1,12 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +SUBDIRS = bdm bdmfs_vfat devfs fakehost filexio http netfs + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/Rules.make diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/Makefile new file mode 100644 index 0000000..a72567d --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +# IOP_CFLAGS += -DDEBUG + +IOP_OBJS = main.o bdm.o part_driver.o imports.o exports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/include/bdm.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/include/bdm.h new file mode 100644 index 0000000..bb32b5e --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/include/bdm.h @@ -0,0 +1,75 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOP BDM (Block Device Manager) definitions. + */ + +#ifndef __BDM_H__ +#define __BDM_H__ + +#include +#include + +struct block_device { + // Private driver data + void* priv; + + // Device name + number + partition number + // Can be used to create device names like: + // - mass0p1 + char* name; + unsigned int devNr; + unsigned int parNr; + unsigned char parId; + + unsigned int sectorSize; + unsigned int sectorOffset; + unsigned int sectorCount; + + int (*read)(struct block_device* bd, u32 sector, void* buffer, u16 count); + int (*write)(struct block_device* bd, u32 sector, const void* buffer, u16 count); + void (*flush)(struct block_device* bd); + int (*stop)(struct block_device* bd); +}; + +struct file_system { + // Private driver data + void* priv; + + // Filesystem (/partition) name + char* name; + + // mount / umount block device + int (*connect_bd)(struct block_device* bd); + void (*disconnect_bd)(struct block_device* bd); +}; + +typedef void (*bdm_cb)(int event); + +// Exported functions +void bdm_connect_bd(struct block_device* bd); +void bdm_disconnect_bd(struct block_device* bd); +void bdm_connect_fs(struct file_system* fs); +void bdm_disconnect_fs(struct file_system* fs); +void bdm_get_bd(struct block_device** pbd, unsigned int count); +void bdm_RegisterCallback(bdm_cb cb); + +#define bdm_IMPORTS_start DECLARE_IMPORT_TABLE(bdm, 1, 1) +#define bdm_IMPORTS_end END_IMPORT_TABLE + +#define I_bdm_connect_bd DECLARE_IMPORT(4, bdm_connect_bd) +#define I_bdm_disconnect_bd DECLARE_IMPORT(5, bdm_disconnect_bd) +#define I_bdm_connect_fs DECLARE_IMPORT(6, bdm_connect_fs) +#define I_bdm_disconnect_fs DECLARE_IMPORT(7, bdm_disconnect_fs) +#define I_bdm_get_bd DECLARE_IMPORT(8, bdm_get_bd) +#define I_bdm_RegisterCallback DECLARE_IMPORT(9, bdm_RegisterCallback) + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/bdm.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/bdm.c new file mode 100644 index 0000000..1ee5493 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/bdm.c @@ -0,0 +1,227 @@ +#include +#include +#include +#include + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +struct bdm_mounts { + struct block_device* bd; + struct file_system* fs; +}; + +#define MAX_CONNECTIONS 20 +static struct bdm_mounts g_mount[MAX_CONNECTIONS]; +static struct file_system* g_fs[MAX_CONNECTIONS]; +static bdm_cb g_cb = NULL; +static int bdm_event = -1; +static int bdm_thread_id = -1; + +/* Event flag bits */ +#define BDM_EVENT_CB_MOUNT 0x01 +#define BDM_EVENT_CB_UMOUNT 0x02 +#define BDM_EVENT_MOUNT 0x04 + +void bdm_RegisterCallback(bdm_cb cb) +{ + int i; + + M_DEBUG("%s\n", __func__); + + g_cb = cb; + + if (g_cb == NULL) + return; + + // Trigger a mount callback if we already have mounts + for (i = 0; i < MAX_CONNECTIONS; ++i) { + if ((g_mount[i].bd != NULL) && (g_mount[i].fs != NULL)) { + SetEventFlag(bdm_event, BDM_EVENT_CB_MOUNT); + break; + } + } +} + +void bdm_connect_bd(struct block_device* bd) +{ + int i; + + M_PRINTF("connecting device %s%dp%d id=0x%x\n", bd->name, bd->devNr, bd->parNr, bd->parId); + + for (i = 0; i < MAX_CONNECTIONS; ++i) { + if (g_mount[i].bd == NULL) { + g_mount[i].bd = bd; + // New block device, try to mount it to a filesystem + SetEventFlag(bdm_event, BDM_EVENT_MOUNT); + break; + } + } +} + +void bdm_disconnect_bd(struct block_device* bd) +{ + int i; + + M_PRINTF("disconnecting device %s%dp%d id=0x%x\n", bd->name, bd->devNr, bd->parNr, bd->parId); + + for (i = 0; i < MAX_CONNECTIONS; ++i) { + if (g_mount[i].bd == bd) { + g_mount[i].fs->disconnect_bd(bd); + M_PRINTF("%s%dp%d unmounted from %s\n", bd->name, bd->devNr, bd->parNr, g_mount[i].fs->name); + g_mount[i].bd = NULL; + g_mount[i].fs = NULL; + if (g_cb != NULL) + SetEventFlag(bdm_event, BDM_EVENT_CB_UMOUNT); + } + } +} + +void bdm_connect_fs(struct file_system* fs) +{ + int i; + + M_PRINTF("connecting fs %s\n", fs->name); + + for (i = 0; i < MAX_CONNECTIONS; ++i) { + if (g_fs[i] == NULL) { + g_fs[i] = fs; + break; + } + } + + // New filesystem, try to mount it to the block devices + SetEventFlag(bdm_event, BDM_EVENT_MOUNT); +} + +void bdm_disconnect_fs(struct file_system* fs) +{ + int i; + + M_PRINTF("disconnecting fs %s\n", fs->name); + + // Unmount fs from block devices + for (i = 0; i < MAX_CONNECTIONS; ++i) { + if (g_mount[i].fs == fs) { + g_mount[i].fs = NULL; + if (g_cb != NULL) + SetEventFlag(bdm_event, BDM_EVENT_CB_UMOUNT); + } + } + + // Remove fs from list + for (i = 0; i < MAX_CONNECTIONS; ++i) { + if (g_fs[i] == fs) { + g_fs[i] = NULL; + break; + } + } +} + +void bdm_get_bd(struct block_device** pbd, unsigned int count) +{ + int i; + + M_DEBUG("%s\n", __func__); + + // Fill pointer array with block device pointers + for (i = 0; i < count && i < MAX_CONNECTIONS; i++) + pbd[i] = g_mount[i].bd; +} + +static void bdm_try_mount(struct bdm_mounts* mount) +{ + int i; + + M_DEBUG("%s(%s%dp%d)\n", __func__, mount->bd->name, mount->bd->devNr, mount->bd->parNr); + + for (i = 0; i < MAX_CONNECTIONS; ++i) { + if (g_fs[i] != NULL) { + if (g_fs[i]->connect_bd(mount->bd) == 0) { + M_PRINTF("%s%dp%d mounted to %s\n", mount->bd->name, mount->bd->devNr, mount->bd->parNr, g_fs[i]->name); + mount->fs = g_fs[i]; + if (g_cb != NULL) + SetEventFlag(bdm_event, BDM_EVENT_CB_MOUNT); + break; + } + } + } +} + +static void bdm_thread(void* arg) +{ + u32 EFBits; + int i; + + M_PRINTF("BDM event thread running\n"); + + while (1) { + WaitEventFlag(bdm_event, BDM_EVENT_CB_MOUNT | BDM_EVENT_CB_UMOUNT | BDM_EVENT_MOUNT, WEF_OR | WEF_CLEAR, &EFBits); + + if (EFBits & BDM_EVENT_MOUNT) { + // Try to mount any unmounted block devices + for (i = 0; i < MAX_CONNECTIONS; ++i) { + if ((g_mount[i].bd != NULL) && (g_mount[i].fs == NULL)) + bdm_try_mount(&g_mount[i]); + } + } + + if (EFBits & BDM_EVENT_CB_MOUNT) { + // Notify callback about changes + if (g_cb != NULL) + g_cb(1); + } + + if (EFBits & BDM_EVENT_CB_UMOUNT) { + // Notify callback about changes + if (g_cb != NULL) + g_cb(0); + } + } +} + +int bdm_init() +{ + int i, result; + iop_event_t EventFlagData; + iop_thread_t ThreadData; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < MAX_CONNECTIONS; ++i) { + g_mount[i].bd = NULL; + g_mount[i].fs = NULL; + g_fs[i] = NULL; + } + + EventFlagData.attr = 0; + EventFlagData.option = 0; + EventFlagData.bits = 0; + result = bdm_event = CreateEventFlag(&EventFlagData); + if (result < 0) { + M_DEBUG("ERROR: CreateEventFlag %d\n", result); + return result; + } + + ThreadData.attr = TH_C; + ThreadData.thread = bdm_thread; + ThreadData.option = 0; + ThreadData.priority = 0x30; // Low priority + ThreadData.stacksize = 0x1000; // 4KiB + result = bdm_thread_id = CreateThread(&ThreadData); + if (result < 0) { + M_DEBUG("ERROR: CreateThread %d\n", result); + DeleteEventFlag(bdm_event); + return result; + } + + result = StartThread(bdm_thread_id, NULL); + if (result < 0) { + M_DEBUG("ERROR: StartThread %d\n", result); + DeleteThread(bdm_thread_id); + DeleteEventFlag(bdm_event); + return result; + } + + return 0; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/exports.tab b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/exports.tab new file mode 100644 index 0000000..b84dd8f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/exports.tab @@ -0,0 +1,16 @@ +/**/ + +DECLARE_EXPORT_TABLE(bdm, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(bdm_connect_bd) + DECLARE_EXPORT(bdm_disconnect_bd) + DECLARE_EXPORT(bdm_connect_fs) + DECLARE_EXPORT(bdm_disconnect_fs) + DECLARE_EXPORT(bdm_get_bd) + DECLARE_EXPORT(bdm_RegisterCallback) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/imports.lst new file mode 100644 index 0000000..c848cbc --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/imports.lst @@ -0,0 +1,20 @@ +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_StartThread +I_DeleteThread +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_WaitEventFlag +I_SetEventFlag +I_DeleteEventFlag +thevent_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/include/module_debug.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/include/module_debug.h new file mode 100644 index 0000000..bd20629 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/include/module_debug.h @@ -0,0 +1,18 @@ +#ifndef _MODULE_DEBUG_H +#define _MODULE_DEBUG_H + +//#define MINI_DRIVER + +#ifndef MINI_DRIVER +#define M_PRINTF(format, args...) printf("BDM: " format, ##args) +#else +#define M_PRINTF(format, args...) +#endif + +#ifdef DEBUG +#define M_DEBUG M_PRINTF +#else +#define M_DEBUG(format, args...) +#endif + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/irx_imports.h new file mode 100644 index 0000000..945dc77 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/irx_imports.h @@ -0,0 +1,25 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/main.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/main.c new file mode 100644 index 0000000..e156b81 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/main.c @@ -0,0 +1,38 @@ +#include +#include +#include +#include + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +#define MAJOR_VER 1 +#define MINOR_VER 1 + +IRX_ID("bdm", MAJOR_VER, MINOR_VER); + +extern struct irx_export_table _exp_bdm; +extern int bdm_init(); +extern void part_init(); + +int _start(int argc, char* argv[]) +{ + printf("Block Device Manager (BDM) v%d.%d\n", MAJOR_VER, MINOR_VER); + + if (RegisterLibraryEntries(&_exp_bdm) != 0) { + M_PRINTF("ERROR: Already registered!\n"); + return MODULE_NO_RESIDENT_END; + } + + // initialize the block device manager + if (bdm_init() < 0) { + M_PRINTF("ERROR: BDM init failed!\n"); + return MODULE_NO_RESIDENT_END; + } + + // initialize the partition driver + part_init(); + + // return resident + return MODULE_RESIDENT_END; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/part_driver.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/part_driver.c new file mode 100644 index 0000000..a93090b --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdm/src/part_driver.c @@ -0,0 +1,241 @@ +#include +#include + +#include + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +#define getUI32(buf) ((unsigned int)(((u8 *)(buf))[0] + \ + (((u8 *)(buf))[1] << 8) + \ + (((u8 *)(buf))[2] << 16) + \ + (((u8 *)(buf))[3] << 24))) + +typedef struct _part_record { + unsigned char sid; //system id- 4=16bit FAT (16bit sector numbers) + // 5=extended partition + // 6=16bit FAT (32bit sector numbers) + unsigned int start; // start sector of the partition + unsigned int count; // length of the partititon (total number of sectors) +} part_record; + +typedef struct _part_table { + part_record record[4]; //maximum of 4 primary partitions +} part_table; + +typedef struct _part_raw_record { + unsigned char active; //Set to 80h if this partition is active / bootable + unsigned char startH; //Partition's starting head. + unsigned char startST[2]; //Partition's starting sector and track. + unsigned char sid; //Partition's system ID number. + unsigned char endH; //Partition's ending head. + unsigned char endST[2]; //Partition's ending sector and track. + unsigned char startLBA[4]; //Starting LBA (sector) + unsigned char size[4]; //Partition size in sectors. +} part_raw_record; + +struct partition { + struct block_device* bd; +}; + +#define MAX_PARTITIONS 10 +static struct partition g_part[MAX_PARTITIONS]; +static struct block_device g_part_bd[MAX_PARTITIONS]; +static struct file_system g_part_fs; + +//--------------------------------------------------------------------------- +static int part_getPartitionRecord(struct block_device* bd, part_raw_record* raw, part_record* rec) +{ + M_DEBUG("%s\n", __func__); + + rec->sid = raw->sid; + rec->start = getUI32(raw->startLBA); + rec->count = getUI32(raw->size); + + if (rec->sid != 0x00) { /* Windows appears to check if the start LBA is not 0 and whether the start LBA is within the disk. + There may be checks against the size, but I didn't manage to identify a pattern. + If the disk has no partition table (i.e. disks with "removable" media), then this check is also one safeguard. */ + if ((rec->start == 0) || (rec->start >= bd->sectorCount)) + return 1; + } + + return 0; +} + +//--------------------------------------------------------------------------- +// FIXME: use malloc/free +static unsigned char sbuf[512]; +static int part_getPartitionTable(struct block_device* bd, part_table* part) +{ + part_raw_record* part_raw; + int ret; + unsigned int i; + + M_DEBUG("%s\n", __func__); + + ret = bd->read(bd, bd->sectorOffset, sbuf, 1); // read sector 0 - Disk MBR or boot sector + if (ret < 0) { + M_DEBUG("ERROR: part_getPartitionTable read failed %d!\n", ret); + return -EIO; + } + + M_DEBUG("boot signature %X %X\n", sbuf[0x1FE], sbuf[0x1FF]); + if (sbuf[0x1FE] == 0x55 && sbuf[0x1FF] == 0xAA) { + for (i = 0; i < 4; i++) { + part_raw = (part_raw_record*)(sbuf + 0x01BE + (i * 16)); + if (part_getPartitionRecord(bd, part_raw, &part->record[i]) != 0) + return 0; //Invalid record encountered, so the table is probably invalid. + } + return 4; + } else { + for (i = 0; i < 4; i++) { + part->record[i].sid = 0; + } + return 0; + } +} + +//--------------------------------------------------------------------------- +void part_create(struct block_device* bd, part_record* rec, unsigned int parNr) +{ + int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < MAX_PARTITIONS; ++i) { + if (g_part[i].bd == NULL) { + g_part[i].bd = bd; + g_part_bd[i].name = bd->name; + g_part_bd[i].devNr = bd->devNr; + g_part_bd[i].parNr = parNr + 1; + g_part_bd[i].parId = rec->sid; + g_part_bd[i].sectorSize = bd->sectorSize; + g_part_bd[i].sectorOffset = bd->sectorOffset + rec->start; + g_part_bd[i].sectorCount = rec->count; + bdm_connect_bd(&g_part_bd[i]); + break; + } + } +} + +//--------------------------------------------------------------------------- +int part_connect(struct block_device* bd) +{ + part_table partTable; + unsigned int i; + int parts; + int rval = -1; + + M_DEBUG("%s\n", __func__); + + // Filter for supported partition IDs: + // - First sector of disk can be MBR partition + // - 0x05 = extended MBR partition with CHS addressing + // - 0x0f = extended MBR partition with LBA addressing + if (bd->sectorOffset != 0 && + bd->parId != 0x05 && + bd->parId != 0x0f) + return rval; + + if ((parts = part_getPartitionTable(bd, &partTable)) <= 0) + return rval; + + for (i = 0; i < parts; i++) { + if (partTable.record[i].sid != 0x00) { + M_DEBUG("mount partition %d id %02x\n", i, partTable.record[i].sid); + part_create(bd, &partTable.record[i], i); + rval = 0; + } + } + + return rval; +} + +//--------------------------------------------------------------------------- +void part_disconnect(struct block_device* bd) +{ + int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < MAX_PARTITIONS; ++i) { + if (g_part[i].bd == bd) { + bdm_disconnect_bd(&g_part_bd[i]); + g_part[i].bd = NULL; + } + } +} + +// +// Block device interface +// +static int part_read(struct block_device* bd, u32 sector, void* buffer, u16 count) +{ + struct partition* part = (struct partition*)bd->priv; + + M_DEBUG("%s\n", __func__); + + if ((part == NULL) || (part->bd == NULL)) + return -1; + + return part->bd->read(part->bd, sector, buffer, count); +} + +static int part_write(struct block_device* bd, u32 sector, const void* buffer, u16 count) +{ + struct partition* part = (struct partition*)bd->priv; + + M_DEBUG("%s\n", __func__); + + if ((part == NULL) || (part->bd == NULL)) + return -1; + + return part->bd->write(part->bd, sector, buffer, count); +} + +static void part_flush(struct block_device* bd) +{ + struct partition* part = (struct partition*)bd->priv; + + M_DEBUG("%s\n", __func__); + + if ((part == NULL) || (part->bd == NULL)) + return; + + return part->bd->flush(part->bd); +} + +static int part_stop(struct block_device* bd) +{ + struct partition* part = (struct partition*)bd->priv; + + M_DEBUG("%s\n", __func__); + + if ((part == NULL) || (part->bd == NULL)) + return -1; + + return part->bd->stop(part->bd); +} + +void part_init() +{ + int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < MAX_PARTITIONS; ++i) { + g_part[i].bd = NULL; + + g_part_bd[i].priv = &g_part[i]; + g_part_bd[i].read = part_read; + g_part_bd[i].write = part_write; + g_part_bd[i].flush = part_flush; + g_part_bd[i].stop = part_stop; + } + + g_part_fs.priv = NULL; + g_part_fs.name = "MBR"; + g_part_fs.connect_bd = part_connect; + g_part_fs.disconnect_bd = part_disconnect; + bdm_connect_fs(&g_part_fs); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/Makefile new file mode 100644 index 0000000..0c32573 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/Makefile @@ -0,0 +1,18 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +# IOP_CFLAGS += -DDEBUG -DDEBUG_EXTREME + +IOP_INCS += -I$(PS2SDKSRC)/iop/fs/bdm/include + +IOP_OBJS = fs_driver.o fat_driver.o fat_write.o scache.o main.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/fat_driver.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/fat_driver.c new file mode 100644 index 0000000..f55dc35 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/fat_driver.c @@ -0,0 +1,1100 @@ +#include +#include +#include + +#include +//#include +#include "common.h" +#include "fat.h" +#include "fat_driver.h" +#include "scache.h" +#include +#include + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +#define READ_SECTOR(d, a, b) scache_readSector((d)->cache, (a), (void**)&b) + +#define NUM_DRIVES 10 +static fat_driver* g_fatd[NUM_DRIVES]; + +//--------------------------------------------------------------------------- +int InitFAT(void) +{ + int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < NUM_DRIVES; ++i) + g_fatd[i] = NULL; + + return 0; +} + +//--------------------------------------------------------------------------- +int strEqual(const char* s1, const char* s2) +{ + char u1, u2; + + M_DEBUG("%s\n", __func__); + + for (;;) { + u1 = *s1++; + u2 = *s2++; + if (u1 > 64 && u1 < 91) + u1 += 32; + if (u2 > 64 && u2 < 91) + u2 += 32; + + if (u1 != u2) { + return -1; + } + if (u1 == '\0') { + return 0; + } + } +} + +/* + + 0x321, 0xABC + + byte| byte| byte| + +--+--+--+--+--+--+ + |2 |1 |C |3 |A |B | + +--+--+--+--+--+--+ + +*/ + +//--------------------------------------------------------------------------- +unsigned int fat_getClusterRecord12(unsigned char* buf, int type) +{ + M_DEBUG("%s\n", __func__); + + if (type) { //1 + return ((buf[1] << 4) + (buf[0] >> 4)); + } else { // 0 + return (((buf[1] & 0x0F) << 8) + buf[0]); + } +} + +//--------------------------------------------------------------------------- +// Get Cluster chain into buffer +// returns: +// 0 :if buf is full (bufSize entries) and more chain entries exist +// 1-n :number of filled entries of the buf +// -1 :error +//--------------------------------------------------------------------------- +//for fat12 +/* fat12 cluster records can overlap the edge of the sector so we need to detect and maintain + these cases +*/ +static int fat_getClusterChain12(fat_driver* fatd, unsigned int cluster, unsigned int* buf, unsigned int bufSize, int startFlag) +{ + int ret; + unsigned int i, recordOffset, fatSector, lastFatSector; + unsigned char xbuf[4], sectorSpan, cont; + unsigned char* sbuf = NULL; //sector buffer + + M_DEBUG("%s\n", __func__); + + cont = 1; + lastFatSector = -1; + i = 0; + if (startFlag) { + buf[i] = cluster; //store first cluster + i++; + } + while (i < bufSize && cont) { + recordOffset = (cluster * 3) / 2; //offset of the cluster record (in bytes) from the FAT start + fatSector = recordOffset / fatd->partBpb.sectorSize; + sectorSpan = 0; + if ((recordOffset % fatd->partBpb.sectorSize) == (fatd->partBpb.sectorSize - 1)) { + sectorSpan = 1; + } + if (lastFatSector != fatSector || sectorSpan) { + ret = READ_SECTOR(fatd, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector, sbuf); + if (ret < 0) { + M_DEBUG("Read fat12 sector failed! sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector); + return -EIO; + } + lastFatSector = fatSector; + + if (sectorSpan) { + xbuf[0] = sbuf[fatd->partBpb.sectorSize - 2]; + xbuf[1] = sbuf[fatd->partBpb.sectorSize - 1]; + ret = READ_SECTOR(fatd, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector + 1, sbuf); + if (ret < 0) { + M_DEBUG("Read fat12 sector failed sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector + 1); + return -EIO; + } + xbuf[2] = sbuf[0]; + xbuf[3] = sbuf[1]; + } + } + if (sectorSpan) { // use xbuf as source buffer + cluster = fat_getClusterRecord12(xbuf + (recordOffset % fatd->partBpb.sectorSize) - (fatd->partBpb.sectorSize - 2), cluster % 2); + } else { // use sector buffer as source buffer + cluster = fat_getClusterRecord12(sbuf + (recordOffset % fatd->partBpb.sectorSize), cluster % 2); + } + + if ((cluster & 0xFFF) >= 0xFF8) { + cont = 0; //continue = false + } else { + buf[i] = cluster & 0xFFF; + i++; + } + } + return i; +} + +//--------------------------------------------------------------------------- +//for fat16 +static int fat_getClusterChain16(fat_driver* fatd, unsigned int cluster, unsigned int* buf, unsigned int bufSize, int startFlag) +{ + int ret; + unsigned int i, indexCount, fatSector, lastFatSector; + unsigned char cont; + unsigned char* sbuf = NULL; //sector buffer + + M_DEBUG("%s\n", __func__); + + cont = 1; + indexCount = fatd->partBpb.sectorSize / 2; //FAT16->2, FAT32->4 + lastFatSector = -1; + i = 0; + if (startFlag) { + buf[i] = cluster; //store first cluster + i++; + } + while (i < bufSize && cont) { + fatSector = cluster / indexCount; + if (lastFatSector != fatSector) { + ret = READ_SECTOR(fatd, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector, sbuf); + if (ret < 0) { + M_DEBUG("Read fat16 sector failed! sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector); + return -EIO; + } + + lastFatSector = fatSector; + } + cluster = getUI16(sbuf + ((cluster % indexCount) * 2)); + if ((cluster & 0xFFFF) >= 0xFFF8) { + cont = 0; //continue = false + } else { + buf[i] = cluster & 0xFFFF; + i++; + } + } + return i; +} + +//--------------------------------------------------------------------------- +//for fat32 +static int fat_getClusterChain32(fat_driver* fatd, unsigned int cluster, unsigned int* buf, unsigned int bufSize, int startFlag) +{ + int ret; + unsigned int i, indexCount, fatSector, lastFatSector; + unsigned char cont; + unsigned char* sbuf = NULL; //sector buffer + + M_DEBUG("%s\n", __func__); + + cont = 1; + indexCount = fatd->partBpb.sectorSize / 4; //FAT16->2, FAT32->4 + lastFatSector = -1; + i = 0; + if (startFlag) { + buf[i] = cluster; //store first cluster + i++; + } + while (i < bufSize && cont) { + fatSector = cluster / indexCount; + if (lastFatSector != fatSector) { + ret = READ_SECTOR(fatd, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector, sbuf); + if (ret < 0) { + M_DEBUG("Read fat32 sector failed sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector); + return -EIO; + } + + lastFatSector = fatSector; + } + cluster = getUI32(sbuf + ((cluster % indexCount) * 4)); + if ((cluster & 0xFFFFFFF) >= 0xFFFFFF8) { + cont = 0; //continue = false + } else { + buf[i] = cluster & 0xFFFFFFF; + i++; + } + } + return i; +} + +//--------------------------------------------------------------------------- +int fat_getClusterChain(fat_driver* fatd, unsigned int cluster, unsigned int* buf, unsigned int bufSize, int startFlag) +{ + M_DEBUG("%s\n", __func__); + + if (cluster == fatd->lastChainCluster) { + return fatd->lastChainResult; + } + + switch (fatd->partBpb.fatType) { + case FAT12: + fatd->lastChainResult = fat_getClusterChain12(fatd, cluster, buf, bufSize, startFlag); + break; + case FAT16: + fatd->lastChainResult = fat_getClusterChain16(fatd, cluster, buf, bufSize, startFlag); + break; + case FAT32: + fatd->lastChainResult = fat_getClusterChain32(fatd, cluster, buf, bufSize, startFlag); + break; + } + fatd->lastChainCluster = cluster; + return fatd->lastChainResult; +} + +//--------------------------------------------------------------------------- +int fat_CheckChain(fat_driver* fatd, unsigned int cluster) +{ + int i, chainSize, nextChain = 1; + int clusterChainStart = 1; + + if (cluster < 2) + return 0; + + while (nextChain) { + chainSize = fat_getClusterChain(fatd, cluster, fatd->cbuf, MAX_DIR_CLUSTER, clusterChainStart); + clusterChainStart = 0; + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + cluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + } else { //chain fits in the chain buffer completely - no next chain needed + nextChain = 0; + } + + //process the cluster chain (fatd->cbuf) and skip leading clusters if needed + for (i = 0; i < (chainSize - 1); i++) { + if ((fatd->cbuf[i] + 1) != fatd->cbuf[i + 1]) + return 0; + } + } + + return 1; +} + +//--------------------------------------------------------------------------- +void fat_invalidateLastChainResult(fat_driver* fatd) +{ + fatd->lastChainCluster = 0; +} + +//--------------------------------------------------------------------------- +static void fat_determineFatType(fat_bpb* partBpb) +{ + unsigned int sector, clusterCount; + + M_DEBUG("%s\n", __func__); + + //get sector of cluster 0 + sector = fat_cluster2sector(partBpb, 0); + //remove partition start sector to get BR+FAT+ROOT_DIR sector count + sector -= partBpb->partStart; + sector = partBpb->sectorCount - sector; + clusterCount = sector / partBpb->clusterSize; + //M_DEBUG("Data cluster count = %u \n", clusterCount); + + if (clusterCount < 4085) { + partBpb->fatType = FAT12; + } else if (clusterCount < 65525) { + partBpb->fatType = FAT16; + } else { + partBpb->fatType = FAT32; + } +} + +//--------------------------------------------------------------------------- +static int fat_getPartitionBootSector(struct block_device* bd, unsigned int sector, fat_bpb* partBpb) +{ + fat_raw_bpb* bpb_raw; //fat16, fat12 + fat32_raw_bpb* bpb32_raw; //fat32 + int ret; + unsigned char* sbuf = malloc(bd->sectorSize); //sector buffer + + M_DEBUG("%s\n", __func__); + + ret = bd->read(bd, sector, sbuf, 1); //read partition boot sector (first sector on partition) + if (ret < 0) { + M_DEBUG("Read partition boot sector failed sector=%u! \n", sector); + free(sbuf); + return -EIO; + } + + bpb_raw = (fat_raw_bpb*)sbuf; + bpb32_raw = (fat32_raw_bpb*)sbuf; + + if ((bpb32_raw->bootSignature[0] != 0x55) || (bpb32_raw->bootSignature[1] != 0xAA)) { + M_DEBUG("Invalid bootSignature (0x%x - 0x%x)\n", bpb32_raw->bootSignature[0], bpb32_raw->bootSignature[1]); + free(sbuf); + return -EIO; + } + + //set fat common properties + partBpb->sectorSize = getUI16(bpb_raw->sectorSize); + partBpb->clusterSize = bpb_raw->clusterSize; + partBpb->resSectors = getUI16(bpb_raw->resSectors); + partBpb->fatCount = bpb_raw->fatCount; + partBpb->rootSize = getUI16(bpb_raw->rootSize); + partBpb->fatSize = getUI16(bpb_raw->fatSize); + partBpb->trackSize = getUI16(bpb_raw->trackSize); + partBpb->headCount = getUI16(bpb_raw->headCount); + partBpb->sectorCount = getUI16(bpb_raw->sectorCountO); + if (partBpb->sectorCount == 0) { + partBpb->sectorCount = getUI32(bpb_raw->sectorCount); // large partition + } + partBpb->partStart = sector; + partBpb->rootDirStart = partBpb->partStart + (partBpb->fatCount * partBpb->fatSize) + partBpb->resSectors; + for (ret = 0; ret < 8; ret++) { + partBpb->fatId[ret] = bpb_raw->fatId[ret]; + } + partBpb->fatId[ret] = 0; + partBpb->rootDirCluster = 0; + partBpb->dataStart = partBpb->rootDirStart + (partBpb->rootSize / (partBpb->sectorSize >> 5)); + + fat_determineFatType(partBpb); + + //fat32 specific info + if (partBpb->fatType == FAT32 && partBpb->fatSize == 0) { + partBpb->fatSize = getUI32(bpb32_raw->fatSize32); + partBpb->activeFat = getUI16(bpb32_raw->fatStatus); + if (partBpb->activeFat & 0x80) { //fat not synced + partBpb->activeFat = (partBpb->activeFat & 0xF); + } else { + partBpb->activeFat = 0; + } + partBpb->rootDirStart = partBpb->partStart + (partBpb->fatCount * partBpb->fatSize) + partBpb->resSectors; + partBpb->rootDirCluster = getUI32(bpb32_raw->rootDirCluster); + for (ret = 0; ret < 8; ret++) { + partBpb->fatId[ret] = bpb32_raw->fatId[ret]; + } + partBpb->fatId[ret] = 0; + partBpb->dataStart = partBpb->rootDirStart; + } + + M_PRINTF("Fat type %u Id %s \n", partBpb->fatType, partBpb->fatId); + free(sbuf); + return 1; +} + +//--------------------------------------------------------------------------- +/* + returns: + 0 - no more dir entries + 1 - short name dir entry found + 2 - long name dir entry found + 3 - deleted dir entry found +*/ +int fat_getDirentry(unsigned char fatType, fat_direntry* dir_entry, fat_direntry_summary* dir) +{ + int i, j; + unsigned int offset; + unsigned char cont; + u16 character; + + M_DEBUG("%s\n", __func__); + + //detect last entry - all zeros (slight modification by radad) + if (dir_entry->sfn.name[0] == 0) { + return 0; + } + //detect deleted entry - it will be ignored + if (dir_entry->sfn.name[0] == 0xE5) { + return 3; + } + + //detect long filename + if (dir_entry->lfn.rshv == 0x0F && dir_entry->lfn.reserved1 == 0x00 && dir_entry->lfn.reserved2[0] == 0x00) { + //long filename - almost whole direntry is unicode string - extract it + offset = dir_entry->lfn.entrySeq & 0x3f; + offset--; + offset = offset * 13; + //name - 1st part + cont = 1; + for (i = 0; i < 10 && cont; i += 2) { + character = dir_entry->lfn.name1[i] | (dir_entry->lfn.name1[i + 1] << 8); + + if (character == 0 || offset >= (FAT_MAX_NAME - 1)) { + dir->name[offset] = 0; //terminate + cont = 0; //stop + } else { + // Handle characters that we don't support. + dir->name[offset] = character <= UCHAR_MAX ? dir_entry->lfn.name1[i] : '?'; + offset++; + } + } + //name - 2nd part + for (i = 0; i < 12 && cont; i += 2) { + character = dir_entry->lfn.name2[i] | (dir_entry->lfn.name2[i + 1] << 8); + + if (character == 0 || offset >= (FAT_MAX_NAME - 1)) { + dir->name[offset] = 0; //terminate + cont = 0; //stop + } else { + // Handle characters that we don't support. + dir->name[offset] = character <= UCHAR_MAX ? dir_entry->lfn.name2[i] : '?'; + offset++; + } + } + //name - 3rd part + for (i = 0; i < 4 && cont; i += 2) { + character = dir_entry->lfn.name3[i] | (dir_entry->lfn.name3[i + 1] << 8); + + if (character == 0 || offset >= (FAT_MAX_NAME - 1)) { + dir->name[offset] = 0; //terminate + cont = 0; //stop + } else { + // Handle characters that we don't support. + dir->name[offset] = character <= UCHAR_MAX ? dir_entry->lfn.name3[i] : '?'; + offset++; + } + } + if ((dir_entry->lfn.entrySeq & 0x40)) { //terminate string flag + dir->name[offset] = 0; + } + return 2; + } else { + //short filename + //copy name + for (i = 0; i < 8 && dir_entry->sfn.name[i] != ' '; i++) { + dir->sname[i] = dir_entry->sfn.name[i]; + // Adaption for LaunchELF + if (dir_entry->sfn.reservedNT & 0x08 && dir->sname[i] >= 'A' && dir->sname[i] <= 'Z') { + dir->sname[i] += 0x20; //Force standard letters in name to lower case + } + } + for (j = 0; j < 3 && dir_entry->sfn.ext[j] != ' '; j++) { + if (j == 0) { + dir->sname[i] = '.'; + i++; + } + dir->sname[i + j] = dir_entry->sfn.ext[j]; + // Adaption for LaunchELF + if (dir_entry->sfn.reservedNT & 0x10 && dir->sname[i + j] >= 'A' && dir->sname[i + j] <= 'Z') { + dir->sname[i + j] += 0x20; //Force standard letters in ext to lower case + } + } + dir->sname[i + j] = 0; //terminate + if (dir->name[0] == 0) { //long name desn't exit + for (i = 0; dir->sname[i] != 0; i++) + dir->name[i] = dir->sname[i]; + dir->name[i] = 0; + } + dir->attr = dir_entry->sfn.attr; + dir->size = getUI32(dir_entry->sfn.size); + dir->cluster = (fatType == FAT32) ? getUI32_2(dir_entry->sfn.clusterL, dir_entry->sfn.clusterH) : getUI16(dir_entry->sfn.clusterL); + + return 1; + } +} + +//--------------------------------------------------------------------------- +//Set chain info (cluster/offset) cache +void fat_setFatDirChain(fat_driver* fatd, fat_dir* fatDir) +{ + int i, j; + unsigned int index, clusterChainStart, fileCluster, fileSize, blockSize; + unsigned char nextChain; + int chainSize; + + M_DEBUG("%s\n", __func__); + + fileCluster = fatDir->chain[0].cluster; + + if (fileCluster < 2) { + M_DEBUG("early exit...\n"); + return; + } + + fileSize = fatDir->size; + blockSize = fileSize / DIR_CHAIN_SIZE; + + nextChain = 1; + clusterChainStart = 0; + j = 1; + fileSize = 0; + index = 0; + + while (nextChain) { + if ((chainSize = fat_getClusterChain(fatd, fileCluster, fatd->cbuf, MAX_DIR_CLUSTER, 1)) >= 0) { + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + fileCluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + } else { //chain fits in the chain buffer completely - no next chain exist + nextChain = 0; + } + } else { + M_DEBUG("fat_setFatDirChain(): fat_getClusterChain() failed: %d\n", chainSize); + return; + } + + //process the cluster chain (fatd->cbuf) + for (i = clusterChainStart; i < chainSize; i++) { + fileSize += (fatd->partBpb.clusterSize * fatd->partBpb.sectorSize); + while (fileSize >= (j * blockSize) && j < DIR_CHAIN_SIZE) { + fatDir->chain[j].cluster = fatd->cbuf[i]; + fatDir->chain[j].index = index; + j++; + } //ends "while" + index++; + } //ends "for" + clusterChainStart = 1; + } //ends "while" + fatDir->lastCluster = fatd->cbuf[i - 1]; + +#ifdef DEBUG_EXTREME //dlanor: I patched this because this bloat hid important stuff + //debug + M_DEBUG("SEEK CLUSTER CHAIN CACHE fileSize=%u blockSize=%u \n", fatDir->size, blockSize); + for (i = 0; i < DIR_CHAIN_SIZE; i++) { + M_DEBUG("index=%u cluster=%u offset= %u - %u start=%u \n", + fatDir->chain[i].index, fatDir->chain[i].cluster, + fatDir->chain[i].index * fatd->partBpb.clusterSize * fatd->partBpb.sectorSize, + (fatDir->chain[i].index + 1) * fatd->partBpb.clusterSize * fatd->partBpb.sectorSize, + i * blockSize); + } +#endif /* debug */ + M_DEBUG("read cluster chain done!\n"); +} + +//--------------------------------------------------------------------------- +/* Set base attributes of direntry */ +static void fat_setFatDir(fat_driver* fatd, fat_dir* fatDir, unsigned int parentDirCluster, fat_direntry_sfn* dsfn, fat_direntry_summary* dir, int getClusterInfo) +{ + unsigned int i; + char* srcName; + + M_DEBUG("%s\n", __func__); + + srcName = dir->sname; + if (dir->name[0] != 0) { //long filename not empty + srcName = dir->name; + } + //copy name + for (i = 0; srcName[i] != 0; i++) + fatDir->name[i] = srcName[i]; + fatDir->name[i] = 0; //terminate + + fatDir->attr = dir->attr; + fatDir->size = dir->size; + + //created Date: Day, Month, Year-low, Year-high + fatDir->cdate[0] = (dsfn->dateCreate[0] & 0x1F); + fatDir->cdate[1] = (dsfn->dateCreate[0] >> 5) + ((dsfn->dateCreate[1] & 0x01) << 3); + i = 1980 + (dsfn->dateCreate[1] >> 1); + fatDir->cdate[2] = (i & 0xFF); + fatDir->cdate[3] = ((i & 0xFF00) >> 8); + + //created Time: Hours, Minutes, Seconds + fatDir->ctime[0] = ((dsfn->timeCreate[1] & 0xF8) >> 3); + fatDir->ctime[1] = ((dsfn->timeCreate[1] & 0x07) << 3) + ((dsfn->timeCreate[0] & 0xE0) >> 5); + fatDir->ctime[2] = ((dsfn->timeCreate[0] & 0x1F) << 1); + + //accessed Date: Day, Month, Year-low, Year-high + fatDir->adate[0] = (dsfn->dateAccess[0] & 0x1F); + fatDir->adate[1] = (dsfn->dateAccess[0] >> 5) + ((dsfn->dateAccess[1] & 0x01) << 3); + i = 1980 + (dsfn->dateAccess[1] >> 1); + fatDir->adate[2] = (i & 0xFF); + fatDir->adate[3] = ((i & 0xFF00) >> 8); + + //modified Date: Day, Month, Year-low, Year-high + fatDir->mdate[0] = (dsfn->dateWrite[0] & 0x1F); + fatDir->mdate[1] = (dsfn->dateWrite[0] >> 5) + ((dsfn->dateWrite[1] & 0x01) << 3); + i = 1980 + (dsfn->dateWrite[1] >> 1); + fatDir->mdate[2] = (i & 0xFF); + fatDir->mdate[3] = ((i & 0xFF00) >> 8); + + //modified Time: Hours, Minutes, Seconds + fatDir->mtime[0] = ((dsfn->timeWrite[1] & 0xF8) >> 3); + fatDir->mtime[1] = ((dsfn->timeWrite[1] & 0x07) << 3) + ((dsfn->timeWrite[0] & 0xE0) >> 5); + fatDir->mtime[2] = ((dsfn->timeWrite[0] & 0x1F) << 1); + + fatDir->chain[0].cluster = dir->cluster; + fatDir->chain[0].index = 0; + if (getClusterInfo) { + fat_setFatDirChain(fatd, fatDir); + } + + fatDir->parentDirCluster = parentDirCluster; + fatDir->startCluster = dir->cluster; +} + +//--------------------------------------------------------------------------- +int fat_getDirentrySectorData(fat_driver* fatd, unsigned int* startCluster, unsigned int* startSector, unsigned int* dirSector) +{ + unsigned int chainSize; + + M_DEBUG("%s\n", __func__); + + if (*startCluster == 0 && fatd->partBpb.fatType < FAT32) { //Root directory + *startSector = fatd->partBpb.rootDirStart; + *dirSector = fatd->partBpb.rootSize / (fatd->partBpb.sectorSize / 32); + return 0; + } + //other directory or fat 32 + if (*startCluster == 0 && fatd->partBpb.fatType == FAT32) { + *startCluster = fatd->partBpb.rootDirCluster; + } + *startSector = fat_cluster2sector(&fatd->partBpb, *startCluster); + chainSize = fat_getClusterChain(fatd, *startCluster, fatd->cbuf, MAX_DIR_CLUSTER, 1); + if (chainSize >= MAX_DIR_CLUSTER) { + M_DEBUG("Chain too large\n"); + return -EFAULT; + } else if (chainSize > 0) { + *dirSector = chainSize * fatd->partBpb.clusterSize; + } else { + M_DEBUG("Error getting cluster chain! startCluster=%u \n", *startCluster); + return -EFAULT; + } + + return chainSize; +} + +//--------------------------------------------------------------------------- +static int fat_getDirentryStartCluster(fat_driver* fatd, char* dirName, unsigned int* startCluster, fat_dir* fatDir) +{ + static fat_direntry_summary dir; // TOO BIG FOR STACK! + unsigned int i, dirSector, startSector, dirPos; + unsigned char cont; + int ret; + + M_DEBUG("%s(%s)\n", __func__, dirName); + + cont = 1; + //clear name strings + dir.sname[0] = 0; + dir.name[0] = 0; + + ret = fat_getDirentrySectorData(fatd, startCluster, &startSector, &dirSector); + if (ret < 0) + return ret; + + M_DEBUG("dirCluster=%u startSector=%u (%u) dirSector=%u \n", *startCluster, startSector, startSector * fatd->bd->sectorSize, dirSector); + + //go through first directory sector till the max number of directory sectors + //or stop when no more direntries detected + for (i = 0; i < dirSector && cont; i++) { + unsigned char* sbuf = NULL; //sector buffer + + //At cluster borders, get correct sector from cluster chain buffer + if ((*startCluster != 0) && (i % fatd->partBpb.clusterSize == 0)) { + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[(i / fatd->partBpb.clusterSize)]) - i; + } + + ret = READ_SECTOR(fatd, startSector + i, sbuf); + if (ret < 0) { + M_DEBUG("read directory sector failed ! sector=%u\n", startSector + i); + return -EIO; + } + M_DEBUG("read sector ok, scanning sector for direntries...\n"); + dirPos = 0; + + // go through start of the sector till the end of sector + while (cont && dirPos < fatd->partBpb.sectorSize) { + fat_direntry* dir_entry = (fat_direntry*)(sbuf + dirPos); + cont = fat_getDirentry(fatd->partBpb.fatType, dir_entry, &dir); //get single directory entry from sector buffer + if (cont == 1) { //when short file name entry detected + if (!(dir.attr & FAT_ATTR_VOLUME_LABEL)) { //not volume label + if ((strEqual(dir.sname, dirName) == 0) || (strEqual(dir.name, dirName) == 0)) { + M_DEBUG("found! %s\n", dir.name); + if (fatDir != NULL) { //fill the directory properties + fat_setFatDir(fatd, fatDir, *startCluster, &dir_entry->sfn, &dir, 1); + } + *startCluster = dir.cluster; + M_DEBUG("direntry %s found at cluster: %u\n", dirName, dir.cluster); + return dir.attr; //returns file or directory attr + } + } //ends "if(!(dir.attr & FAT_ATTR_VOLUME_LABEL))" + //clear name strings + dir.sname[0] = 0; + dir.name[0] = 0; + } //ends "if (cont == 1)" + dirPos += sizeof(fat_direntry); + } //ends "while" + } //ends "for" + M_DEBUG("direntry %s not found!\n", dirName); + return -ENOENT; +} + +//--------------------------------------------------------------------------- +// start cluster should be 0 - if we want to search from root directory +// otherwise the start cluster should be correct cluster of directory +// to search directory - set fatDir as NULL +int fat_getFileStartCluster(fat_driver* fatd, const char* fname, unsigned int* startCluster, fat_dir* fatDir) +{ + static char tmpName[FAT_MAX_NAME + 1]; // TOO BIG FOR STACK! + unsigned int i, offset; + int ret; + + M_DEBUG("%s\n", __func__); + + offset = 0; + i = 0; + + *startCluster = 0; + if (fatDir != NULL) { + memset(fatDir, 0, sizeof(fat_dir)); + fatDir->attr = FAT_ATTR_DIRECTORY; + } + if (fname[i] == '/') { + i++; + } + + for (; fname[i] != 0; i++) { + if (fname[i] == '/') { //directory separator + tmpName[offset] = 0; //terminate string + ret = fat_getDirentryStartCluster(fatd, tmpName, startCluster, fatDir); + if (ret < 0) { + return -ENOENT; + } + offset = 0; + } else { + tmpName[offset] = fname[i]; + offset++; + } + } //ends "for" + //and the final file + tmpName[offset] = 0; //terminate string + M_DEBUG("Ready to get cluster for file \"%s\"\n", tmpName); + if (fatDir != NULL) { + //if the last char of the name was slash - the name was already found -exit + if (offset == 0) { + M_DEBUG("Exiting from fat_getFileStartCluster with a folder\n"); + return 2; + } + ret = fat_getDirentryStartCluster(fatd, tmpName, startCluster, fatDir); + if (ret < 0) { + M_DEBUG("Exiting from fat_getFileStartCluster with error %i\n", ret); + return ret; + } + M_DEBUG("file's startCluster found. Name=%s, cluster=%u \n", fname, *startCluster); + } + M_DEBUG("Exiting from fat_getFileStartCluster with no error.\n"); + return 1; +} + +//--------------------------------------------------------------------------- +void fat_getClusterAtFilePos(fat_driver* fatd, fat_dir* fatDir, unsigned int filePos, unsigned int* cluster, unsigned int* clusterPos) +{ + unsigned int i, j, blockSize; + + M_DEBUG("%s\n", __func__); + + blockSize = fatd->partBpb.clusterSize * fatd->partBpb.sectorSize; + + for (i = 0, j = (DIR_CHAIN_SIZE - 1); i < (DIR_CHAIN_SIZE - 1); i++) { + if (fatDir->chain[i].index * blockSize <= filePos && fatDir->chain[i + 1].index * blockSize > filePos) { + j = i; + break; + } + } + *cluster = fatDir->chain[j].cluster; + *clusterPos = (fatDir->chain[j].index * blockSize); +} + +//--------------------------------------------------------------------------- +int fat_readFile(fat_driver* fatd, fat_dir* fatDir, unsigned int filePos, unsigned char* buffer, unsigned int size) +{ + int ret, chainSize; + unsigned int i, j, startSector, clusterChainStart, bufSize, sectorSkip, clusterSkip, dataSkip; + unsigned char nextChain; + + unsigned int bufferPos, fileCluster, clusterPos; + + M_DEBUG("%s\n", __func__); + + fat_getClusterAtFilePos(fatd, fatDir, filePos, &fileCluster, &clusterPos); + sectorSkip = (filePos - clusterPos) / fatd->partBpb.sectorSize; + clusterSkip = sectorSkip / fatd->partBpb.clusterSize; + sectorSkip %= fatd->partBpb.clusterSize; + dataSkip = filePos % fatd->partBpb.sectorSize; + bufferPos = 0; + + M_DEBUG("fileCluster = %u, clusterPos= %u clusterSkip=%u, sectorSkip=%u dataSkip=%u \n", + fileCluster, clusterPos, clusterSkip, sectorSkip, dataSkip); + + if (fileCluster < 2) { + return 0; + } + + bufSize = fatd->bd->sectorSize; + nextChain = 1; + clusterChainStart = 1; + + while (nextChain && size > 0) { + if ((chainSize = fat_getClusterChain(fatd, fileCluster, fatd->cbuf, MAX_DIR_CLUSTER, clusterChainStart)) < 0) { + return chainSize; + } + + clusterChainStart = 0; + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + fileCluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + } else { //chain fits in the chain buffer completely - no next chain needed + nextChain = 0; + } + while (clusterSkip >= MAX_DIR_CLUSTER) { + chainSize = fat_getClusterChain(fatd, fileCluster, fatd->cbuf, MAX_DIR_CLUSTER, clusterChainStart); + clusterChainStart = 0; + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + fileCluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + } else { //chain fits in the chain buffer completely - no next chain needed + nextChain = 0; + } + clusterSkip -= MAX_DIR_CLUSTER; + } + + //process the cluster chain (fatd->cbuf) and skip leading clusters if needed + for (i = 0 + clusterSkip; i < chainSize && size > 0; i++) { + //read cluster and save cluster content + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[i]); + //process all sectors of the cluster (and skip leading sectors if needed) + for (j = 0 + sectorSkip; j < fatd->partBpb.clusterSize && size > 0; j++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = READ_SECTOR(fatd, startSector + j, sbuf); + if (ret < 0) { + M_DEBUG("Read sector failed ! sector=%u\n", startSector + j); + return bufferPos; + } + + //compute exact size of transfered bytes + if (size < bufSize) { + bufSize = size + dataSkip; + } + if (bufSize > fatd->bd->sectorSize) { + bufSize = fatd->bd->sectorSize; + } + M_DEBUG("memcopy dst=%u, src=%u, size=%u bufSize=%u \n", bufferPos, dataSkip, bufSize - dataSkip, bufSize); + memcpy(buffer + bufferPos, sbuf + dataSkip, bufSize - dataSkip); + size -= (bufSize - dataSkip); + bufferPos += (bufSize - dataSkip); + dataSkip = 0; + bufSize = fatd->bd->sectorSize; + } + sectorSkip = 0; + } + clusterSkip = 0; + } + return bufferPos; +} + +//--------------------------------------------------------------------------- +int fat_getNextDirentry(fat_driver* fatd, fat_dir_list* fatdlist, fat_dir* fatDir) +{ + static fat_direntry_summary dir; // TOO BIG FOR STACK! + int i, ret; + unsigned int startSector, dirSector, dirPos, dirCluster; + unsigned char cont, new_entry; + + M_DEBUG("%s\n", __func__); + + //the getFirst function was not called + if (fatdlist->direntryCluster == 0xFFFFFFFF || fatDir == NULL) { + return -EFAULT; + } + + dirCluster = fatdlist->direntryCluster; + + //clear name strings + dir.sname[0] = 0; + dir.name[0] = 0; + + ret = fat_getDirentrySectorData(fatd, &dirCluster, &startSector, &dirSector); + if (ret < 0) + return ret; + + M_DEBUG("dirCluster=%u startSector=%u (%u) dirSector=%u \n", dirCluster, startSector, startSector * fatd->bd->sectorSize, dirSector); + + //go through first directory sector till the max number of directory sectors + //or stop when no more direntries detected + //dlanor: but avoid rescanning same areas redundantly (if possible) + cont = 1; + new_entry = 1; + dirPos = (fatdlist->direntryIndex * 32) % fatd->partBpb.sectorSize; + for (i = ((fatdlist->direntryIndex * 32) / fatd->partBpb.sectorSize); (i < dirSector) && cont; i++) { + unsigned char* sbuf = NULL; //sector buffer + + //At cluster borders, get correct sector from cluster chain buffer + if ((dirCluster != 0) && (new_entry || (i % fatd->partBpb.clusterSize == 0))) { + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[(i / fatd->partBpb.clusterSize)]) + - i + (i % fatd->partBpb.clusterSize); + new_entry = 0; + } + ret = READ_SECTOR(fatd, startSector + i, sbuf); + if (ret < 0) { + M_DEBUG("Read directory sector failed ! sector=%u\n", startSector + i); + return -EIO; + } + + // go through sector from current pos till its end + while (cont && (dirPos < fatd->partBpb.sectorSize)) { + fat_direntry* dir_entry = (fat_direntry*)(sbuf + dirPos); + cont = fat_getDirentry(fatd->partBpb.fatType, dir_entry, &dir); //get a directory entry from sector + fatdlist->direntryIndex++; //Note current entry processed + if (cont == 1) { //when short file name entry detected + fat_setFatDir(fatd, fatDir, dirCluster, &dir_entry->sfn, &dir, 0); +#if 0 + M_DEBUG("fat_getNextDirentry %c%c%c%c%c%c %x %s %s\n", + (dir.attr & FAT_ATTR_VOLUME_LABEL) ? 'v' : '-', + (dir.attr & FAT_ATTR_DIRECTORY) ? 'd' : '-', + (dir.attr & FAT_ATTR_READONLY) ? 'r' : '-', + (dir.attr & FAT_ATTR_ARCHIVE) ? 'a' : '-', + (dir.attr & FAT_ATTR_SYSTEM) ? 's' : '-', + (dir.attr & FAT_ATTR_HIDDEN) ? 'h' : '-', + dir.attr, + dir.sname, + dir.name); +#endif + return 1; + } + dirPos += sizeof(fat_direntry); + } //ends "while" + dirPos = 0; + } //ends "for" + // when we get this far - reset the direntry cluster + fatdlist->direntryCluster = 0xFFFFFFFF; //no more files + return 0; //indicate that no direntry is avalable +} + +//--------------------------------------------------------------------------- +int fat_getFirstDirentry(fat_driver* fatd, const char* dirName, fat_dir_list* fatdlist, fat_dir* fatDir_host, fat_dir* fatDir) +{ + int ret; + unsigned int startCluster = 0; + + M_DEBUG("%s\n", __func__); + + ret = fat_getFileStartCluster(fatd, dirName, &startCluster, fatDir_host); + if (ret < 0) { //dir name not found + return -ENOENT; + } + //check that direntry is directory + if (!(fatDir_host->attr & FAT_ATTR_DIRECTORY)) { + return -ENOTDIR; //it's a file - exit + } + fatdlist->direntryCluster = startCluster; + fatdlist->direntryIndex = 0; + return fat_getNextDirentry(fatd, fatdlist, fatDir); +} + +//--------------------------------------------------------------------------- +int fat_mount(struct block_device* bd) +{ + fat_driver* fatd = NULL; + unsigned int i; + + M_DEBUG("%s\n", __func__); + + // Filter for supported partition IDs: + // - 0x0b = FAT32 with CHS addressing + // - 0x0c = FAT32 with LBA addressing + if (bd->parId != 0x0b && bd->parId != 0x0c) + return -1; + + for (i = 0; i < NUM_DRIVES && fatd == NULL; ++i) { + if (g_fatd[i] == NULL) { + M_DEBUG("allocate fat_driver %d!\n", sizeof(fat_driver)); + g_fatd[i] = malloc(sizeof(fat_driver)); + if (g_fatd[i] != NULL) { + g_fatd[i]->bd = NULL; + g_fatd[i]->cache = NULL; + } + fatd = g_fatd[i]; + } else if (g_fatd[i]->bd == NULL) { + fatd = g_fatd[i]; + } + } + + if (fatd == NULL) { + M_PRINTF("unable to allocate drive!\n"); + return -1; + } + + if (fatd->bd != NULL) { + M_PRINTF("mount ERROR: alread mounted\n"); + fat_forceUnmount(fatd->bd); + } + + if (fatd->cache != NULL) { + M_PRINTF("ERROR: cache already created\n"); + scache_kill(fatd->cache); + fatd->cache = NULL; + } + + if (fat_getPartitionBootSector(bd, bd->sectorOffset, &fatd->partBpb) < 0) + return -1; + + fatd->cache = scache_init(bd); + if (fatd->cache == NULL) { + M_PRINTF("Error - scache_init failed\n"); + return -1; + } + + fatd->bd = bd; + fatd->deIdx = 0; + fatd->clStackIndex = 0; + fatd->clStackLast = 0; + fatd->lastChainCluster = 0xFFFFFFFF; + fatd->lastChainResult = -1; + return 0; +} + +//--------------------------------------------------------------------------- +void fat_forceUnmount(struct block_device* bd) +{ + unsigned int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < NUM_DRIVES; ++i) { + if (g_fatd[i] != NULL && g_fatd[i]->bd == bd) { + scache_kill(g_fatd[i]->cache); + free(g_fatd[i]); + g_fatd[i] = NULL; + } + } +} + +//--------------------------------------------------------------------------- +fat_driver* fat_getData(int device) +{ + M_DEBUG("%s(%d)\n", __func__, device); + + if (device >= NUM_DRIVES) + return NULL; + + if (g_fatd[device] == NULL || g_fatd[device]->bd == NULL) + return NULL; + + return g_fatd[device]; +} + +//--------------------------------------------------------------------------- +int fat_stopUnit(int device) +{ + fat_driver *fatd; + + fatd = fat_getData(device); + return (fatd != NULL) ? fatd->bd->stop(fatd->bd) : -ENODEV; +} + +void fat_stopAll(void) +{ + fat_driver *fatd; + int i; + + for (i = 0; i < NUM_DRIVES; i++) + { + fatd = fat_getData(i); + if (fatd != NULL) + fatd->bd->stop(fatd->bd); + } +} + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/fat_write.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/fat_write.c new file mode 100644 index 0000000..675252c --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/fat_write.c @@ -0,0 +1,2295 @@ +/* + * fat_driver.c - USB Mass storage driver for PS2 + * + * (C) 2005, Marek Olejnik (ole00@post.cz) + * + * FAT filesystem layer - write functions + * + * See the file LICENSE included with this distribution for licensing terms. + */ +//--------------------------------------------------------------------------- +#include "common.h" +#include "fat.h" +#include "fat_driver.h" +#include "scache.h" +#include +#include +#include +#include + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +#define DATE_CREATE 1 +#define DATE_MODIFY 2 + +#define READ_SECTOR(d, a, b) scache_readSector((d)->cache, (a), (void**)&b) +#define ALLOC_SECTOR(d, a, b) scache_readSector((d)->cache, (a), (void **)&b) //Cannot allocate a block as the cluster might not necessarily be aligned with the cache block; may result in corruption of the adjacent cluster. +#define WRITE_SECTOR(d, a) scache_writeSector((d)->cache, (a)) +#define FLUSH_SECTORS(d) scache_flushSectors((d)->cache) + +//--------------------------------------------------------------------------- +/* + reorder (swap) the cluster stack records +*/ +static void swapClStack(fat_driver* fatd, int startIndex, int endIndex) +{ + int i; + int size; + int offset1, offset2; + unsigned int tmp; + + size = endIndex - startIndex; + if (size < 2) { + return; + } + + size /= 2; + for (i = 0; i < size; i++) { + offset1 = startIndex + i; + offset2 = endIndex - 1 - i; + tmp = fatd->clStack[offset1]; + fatd->clStack[offset1] = fatd->clStack[offset2]; + fatd->clStack[offset2] = tmp; + } +} + +//--------------------------------------------------------------------------- +/* + scan FAT12 for free clusters and store them to the cluster stack +*/ + +static int fat_readEmptyClusters12(fat_driver* fatd) +{ + int ret; + int recordOffset; + int sectorSpan; + int fatSector; + int lastFatSector; + unsigned int cluster; + unsigned int clusterValue; + unsigned char xbuf[4]; + int oldClStackIndex; + unsigned char* sbuf = NULL; //sector buffer + + oldClStackIndex = fatd->clStackIndex; + + lastFatSector = -1; + cluster = fatd->clStackLast; + + while (fatd->clStackIndex < MAX_CLUSTER_STACK) { + recordOffset = (cluster * 3) / 2; //offset of the cluster record (in bytes) from the FAT start + fatSector = recordOffset / fatd->partBpb.sectorSize; + sectorSpan = 0; + if ((recordOffset % fatd->partBpb.sectorSize) == (fatd->partBpb.sectorSize - 1)) { + sectorSpan = 1; + } + if (lastFatSector != fatSector || sectorSpan) { + ret = READ_SECTOR(fatd, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector, sbuf); + if (ret < 0) { + M_DEBUG("Read fat12 sector failed! sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector); + return -EIO; + } + lastFatSector = fatSector; + + if (sectorSpan) { + xbuf[0] = sbuf[fatd->partBpb.sectorSize - 2]; + xbuf[1] = sbuf[fatd->partBpb.sectorSize - 1]; + ret = READ_SECTOR(fatd, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector + 1, sbuf); + if (ret < 0) { + M_DEBUG("Read fat12 sector failed sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector + 1); + return -EIO; + } + xbuf[2] = sbuf[0]; + xbuf[3] = sbuf[1]; + } + } + if (sectorSpan) { // use xbuf as source buffer + clusterValue = fat_getClusterRecord12(xbuf + (recordOffset % fatd->partBpb.sectorSize) - (fatd->partBpb.sectorSize - 2), cluster % 2); + } else { // use sector buffer as source buffer + clusterValue = fat_getClusterRecord12(sbuf + (recordOffset % fatd->partBpb.sectorSize), cluster % 2); + } + if (clusterValue == 0) { + fatd->clStackLast = cluster; + fatd->clStack[fatd->clStackIndex] = cluster; + fatd->clStackIndex++; + } + cluster++; //read next cluster record in the sequence + } + //the stack operates as LIFO but we put in the clusters as FIFO + //we should reverse the cluster order - not necessary + //but it will retain the natural (increasing) order of + //the cluster chain + swapClStack(fatd, oldClStackIndex, fatd->clStackIndex); + return fatd->clStackIndex; +} + +//--------------------------------------------------------------------------- +/* + scan FAT32 for free clusters and store them to the cluster stack +*/ +static int fat_readEmptyClusters32(fat_driver* fatd) +{ + unsigned int i, j; + int ret; + unsigned int indexCount; + unsigned int fatStartSector; + unsigned int cluster; + unsigned int clusterValue; + int oldClStackIndex; + int sectorSkip; + int recordSkip; + + oldClStackIndex = fatd->clStackIndex; + + //indexCount = numer of cluster indices per sector + indexCount = fatd->partBpb.sectorSize / 4; //FAT16->2, FAT32->4 + //skip areas we have already searched through + sectorSkip = fatd->clStackLast / indexCount; + recordSkip = fatd->clStackLast % indexCount; + + fatStartSector = fatd->partBpb.partStart + fatd->partBpb.resSectors; + + for (i = sectorSkip; i < fatd->partBpb.fatSize && fatd->clStackIndex < MAX_CLUSTER_STACK; i++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = READ_SECTOR(fatd, fatStartSector + i, sbuf); + if (ret < 0) { + M_DEBUG("Read fat32 sector failed! sector=%u! \n", fatStartSector + i); + return -EIO; + } + for (j = recordSkip; j < indexCount && fatd->clStackIndex < MAX_CLUSTER_STACK; j++) { + cluster = getUI32(sbuf + (j * 4)); + if (cluster == 0) { //the cluster is free + clusterValue = (i * indexCount) + j; + if (clusterValue < 0xFFFFFF7) { + fatd->clStackLast = clusterValue; + fatd->clStack[fatd->clStackIndex] = clusterValue; + fatd->clStackIndex++; + } + } + } + recordSkip = 0; + } + //the stack operates as LIFO but we put in the clusters as FIFO + //we should reverse the cluster order - not necessary + //but it will retain the natural (increasing) order of + //the cluster chain + swapClStack(fatd, oldClStackIndex, fatd->clStackIndex); + return fatd->clStackIndex; +} + +//--------------------------------------------------------------------------- +/* + scan FAT16 for free clusters and store them to the cluster stack +*/ +static int fat_readEmptyClusters16(fat_driver* fatd) +{ + unsigned int i, j; + int ret; + unsigned int indexCount; + unsigned int fatStartSector; + unsigned int cluster; + int oldClStackIndex; + int sectorSkip; + int recordSkip; + + oldClStackIndex = fatd->clStackIndex; + //M_DEBUG("#### Read empty clusters16: clStackIndex=%d MAX=%d\n", clStackIndex, MAX_CLUSTER_STACK); + + //indexCount = numer of cluster indices per sector + indexCount = fatd->partBpb.sectorSize / 2; //FAT16->2, FAT32->4 + + //skip areas we have already searched through + sectorSkip = fatd->clStackLast / indexCount; + recordSkip = fatd->clStackLast % indexCount; + + fatStartSector = fatd->partBpb.partStart + fatd->partBpb.resSectors; + + for (i = sectorSkip; i < fatd->partBpb.fatSize && fatd->clStackIndex < MAX_CLUSTER_STACK; i++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = READ_SECTOR(fatd, fatStartSector + i, sbuf); + if (ret < 0) { + M_DEBUG("Read fat16 sector failed! sector=%u! \n", fatStartSector + i); + return -EIO; + } + for (j = recordSkip; j < indexCount && fatd->clStackIndex < MAX_CLUSTER_STACK; j++) { + cluster = getUI16(sbuf + (j * 2)); + if (cluster == 0) { //the cluster is free + fatd->clStackLast = (i * indexCount) + j; + fatd->clStack[fatd->clStackIndex] = fatd->clStackLast; + M_DEBUG("%u ", fatd->clStack[fatd->clStackIndex]); + fatd->clStackIndex++; + } + } + recordSkip = 0; + } + M_DEBUG("\n"); + //the stack operates as LIFO but we put in the clusters as FIFO + //we should reverse the cluster order - not necessary + //but it will retain the natural (increasing) order of + //the cluster chain + swapClStack(fatd, oldClStackIndex, fatd->clStackIndex); + return fatd->clStackIndex; +} + +//--------------------------------------------------------------------------- +/* + scan FAT for free clusters and store them to the cluster stack +*/ +static int fat_readEmptyClusters(fat_driver* fatd) +{ + switch (fatd->partBpb.fatType) { + case FAT12: + return fat_readEmptyClusters12(fatd); + case FAT16: + return fat_readEmptyClusters16(fatd); + case FAT32: + return fat_readEmptyClusters32(fatd); + } + + return (-1); +} + +//--------------------------------------------------------------------------- +/* + set sinlge cluster record (FAT12)into buffer + + 0x321, 0xABC + + byte0|byte1|byte2| + +--+--+--+--+--+--+ + |2 |1 |C |3 |A |B | + +--+--+--+--+--+--+ + +*/ +static void fat_setClusterRecord12(unsigned char* buf, unsigned int cluster, int type) +{ + + if (type) { //type 1 + buf[0] = (buf[0] & 0x0F) + ((cluster & 0x0F) << 4); + buf[1] = (cluster & 0xFF0) >> 4; + } else { // type 0 + buf[0] = (cluster & 0xFF); + buf[1] = (buf[1] & 0xF0) + ((cluster & 0xF00) >> 8); + } +} + +//--------------------------------------------------------------------------- +static void fat_setClusterRecord12part1(unsigned char* buf, unsigned int cluster, int type) +{ + if (type) { //type 1 + buf[0] = (buf[0] & 0x0F) + ((cluster & 0x0F) << 4); + } else { // type 0 + buf[0] = (cluster & 0xFF); + } +} + +//--------------------------------------------------------------------------- +static void fat_setClusterRecord12part2(unsigned char* buf, unsigned int cluster, int type) +{ + if (type) { //type 1 + buf[0] = (cluster & 0xFF0) >> 4; + } else { // type 0 + buf[0] = (buf[0] & 0xF0) + ((cluster & 0xF00) >> 8); + } +} + +//--------------------------------------------------------------------------- +/* + save value at the cluster record in FAT 12 +*/ +static int fat_saveClusterRecord12(fat_driver* fatd, unsigned int currentCluster, unsigned int value) +{ + int ret; + int sectorSpan; + int recordOffset; + int recordType; + int fatNumber; + unsigned int fatSector; + + ret = -1; + //recordOffset is byte offset of the record from the start of the fat table + recordOffset = (currentCluster * 3) / 2; + + //save both fat tables + for (fatNumber = 0; fatNumber < fatd->partBpb.fatCount; fatNumber++) { + unsigned char* sbuf = NULL; //sector buffer + + fatSector = fatd->partBpb.partStart + fatd->partBpb.resSectors + (fatNumber * fatd->partBpb.fatSize); + fatSector += recordOffset / fatd->partBpb.sectorSize; + sectorSpan = fatd->partBpb.sectorSize - (recordOffset % fatd->partBpb.sectorSize); + if (sectorSpan > 1) { + sectorSpan = 0; + } + recordType = currentCluster % 2; + + ret = READ_SECTOR(fatd, fatSector, sbuf); + if (ret < 0) { + M_DEBUG("Read fat16 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + if (!sectorSpan) { // not sector span - the record is copmact and fits in single sector + fat_setClusterRecord12(sbuf + (recordOffset % fatd->partBpb.sectorSize), value, recordType); + ret = WRITE_SECTOR(fatd, fatSector); + if (ret < 0) { + M_DEBUG("Write fat12 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + } else { // sector span - the record is broken in 2 pieces - each one on different sector + //modify one last byte of the sector buffer + fat_setClusterRecord12part1(sbuf + (recordOffset % fatd->partBpb.sectorSize), value, recordType); + //save current sector + ret = WRITE_SECTOR(fatd, fatSector); + if (ret < 0) { + M_DEBUG("Write fat12 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + //read next sector from the fat + fatSector++; + ret = READ_SECTOR(fatd, fatSector, sbuf); + if (ret < 0) { + M_DEBUG("Read fat16 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + //modify first byte of the sector buffer + fat_setClusterRecord12part2(sbuf, value, recordType); + //save current sector + ret = WRITE_SECTOR(fatd, fatSector); + if (ret < 0) { + M_DEBUG("Write fat12 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + } + } //end for + return ret; +} + +//--------------------------------------------------------------------------- +/* + save value at the cluster record in FAT 32 +*/ +static int fat_saveClusterRecord16(fat_driver* fatd, unsigned int currentCluster, unsigned int value) +{ + int i; + int ret; + int indexCount; + int fatNumber; + unsigned int fatSector; + + ret = -1; + //indexCount is numer of cluster indices per sector + indexCount = fatd->partBpb.sectorSize / 2; //FAT16->2, FAT32->4 + + //save both fat tables + for (fatNumber = 0; fatNumber < fatd->partBpb.fatCount; fatNumber++) { + unsigned char* sbuf = NULL; //sector buffer + + fatSector = fatd->partBpb.partStart + fatd->partBpb.resSectors + (fatNumber * fatd->partBpb.fatSize); + fatSector += currentCluster / indexCount; + + ret = READ_SECTOR(fatd, fatSector, sbuf); + if (ret < 0) { + M_DEBUG("Read fat16 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + i = currentCluster % indexCount; + i *= 2; //fat16 + sbuf[i++] = value & 0xFF; + sbuf[i] = ((value & 0xFF00) >> 8); + ret = WRITE_SECTOR(fatd, fatSector); + if (ret < 0) { + M_DEBUG("Write fat16 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + } + return ret; +} + +//--------------------------------------------------------------------------- +/* + save value at the cluster record in FAT 16 +*/ +static int fat_saveClusterRecord32(fat_driver* fatd, unsigned int currentCluster, unsigned int value) +{ + int i; + int ret; + int indexCount; + int fatNumber; + unsigned int fatSector; + + ret = -1; + //indexCount is numer of cluster indices per sector + indexCount = fatd->partBpb.sectorSize / 4; //FAT16->2, FAT32->4 + + //save both fat tables + for (fatNumber = 0; fatNumber < fatd->partBpb.fatCount; fatNumber++) { + unsigned char* sbuf = NULL; //sector buffer + + fatSector = fatd->partBpb.partStart + fatd->partBpb.resSectors + (fatNumber * fatd->partBpb.fatSize); + fatSector += currentCluster / indexCount; + + ret = READ_SECTOR(fatd, fatSector, sbuf); + if (ret < 0) { + M_DEBUG("Read fat32 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + i = currentCluster % indexCount; + i *= 4; //fat32 + sbuf[i++] = value & 0xFF; + sbuf[i++] = ((value & 0xFF00) >> 8); + sbuf[i++] = ((value & 0xFF0000) >> 16); + sbuf[i] = (sbuf[i] & 0xF0) + ((value >> 24) & 0x0F); //preserve the highest nibble intact + + ret = WRITE_SECTOR(fatd, fatSector); + if (ret < 0) { + M_DEBUG("Write fat32 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + } + return ret; +} + +//--------------------------------------------------------------------------- +/* + Append (and write) cluster chain to the FAT table. + + currentCluster - current end cluster record. + endCluster - new end cluster record. + + Note: there is no checking wether the currentCluster holds the EOF marker! + + Example + current FAT: + + index 09 10 11 12 + +-----+-----+-----+-----+ + value + 10 | EOF | 0 | 0 | + +-----+-----+-----+-----+ + + + currentcluster = 10, endcluster = 12 + updated FAT (after the function ends): + + index 09 10 11 12 + +-----+-----+-----+-----+ + value + 10 | 12 | 0 | EOF | + +-----+-----+-----+-----+ + +*/ +//--------------------------------------------------------------------------- +static int fat_appendClusterChain(fat_driver* fatd, unsigned int currentCluster, unsigned int endCluster) +{ + int ret; + ret = -1; + switch (fatd->partBpb.fatType) { + case FAT12: + ret = fat_saveClusterRecord12(fatd, currentCluster, endCluster); + if (ret < 0) + return ret; + ret = fat_saveClusterRecord12(fatd, endCluster, 0xFFF); + break; + + case FAT16: + ret = fat_saveClusterRecord16(fatd, currentCluster, endCluster); + if (ret < 0) + return ret; + ret = fat_saveClusterRecord16(fatd, endCluster, 0xFFFF); + break; + + case FAT32: + ret = fat_saveClusterRecord32(fatd, currentCluster, endCluster); + if (ret < 0) + return ret; + ret = fat_saveClusterRecord32(fatd, endCluster, 0xFFFFFFF); + break; + } + return ret; +} + +//--------------------------------------------------------------------------- +/* + create new cluster chain (of size 1 cluster) at the cluster index +*/ +static int fat_createClusterChain(fat_driver* fatd, unsigned int cluster) +{ + switch (fatd->partBpb.fatType) { + case FAT12: + return fat_saveClusterRecord12(fatd, cluster, 0xFFF); + case FAT16: + return fat_saveClusterRecord16(fatd, cluster, 0xFFFF); + case FAT32: + return fat_saveClusterRecord32(fatd, cluster, 0xFFFFFFF); + } + return -EFAULT; +} + +//--------------------------------------------------------------------------- +/* + modify the cluster (in FAT table) at the cluster index +*/ +static int fat_modifyClusterChain(fat_driver* fatd, unsigned int cluster, unsigned int value) +{ + switch (fatd->partBpb.fatType) { + case FAT12: + return fat_saveClusterRecord12(fatd, cluster, value); + case FAT16: + return fat_saveClusterRecord16(fatd, cluster, value); + case FAT32: + return fat_saveClusterRecord32(fatd, cluster, value); + } + return -EFAULT; +} + +//--------------------------------------------------------------------------- +/* + delete cluster chain starting at cluster +*/ +static int fat_deleteClusterChain(fat_driver* fatd, unsigned int cluster) +{ + int ret; + int size; + int cont; + int end; + int i; + + if (cluster < 2) { + return -EFAULT; + } + M_DEBUG("I: delete cluster chain starting at cluster=%u\n", cluster); + + cont = 1; + + while (cont) { + size = fat_getClusterChain(fatd, cluster, fatd->cbuf, MAX_DIR_CLUSTER, 1); + + end = size - 1; //do not delete last cluster in the chain buffer + + for (i = 0; i < end; i++) { + ret = fat_modifyClusterChain(fatd, fatd->cbuf[i], 0); + if (ret < 0) { + return ret; + } + } + //the cluster chain continues + if (size == MAX_DIR_CLUSTER) { + cluster = fatd->cbuf[end]; + } else { + //no more cluster entries - delete the last cluster entry + ret = fat_modifyClusterChain(fatd, fatd->cbuf[end], 0); + if (ret < 0) { + return ret; + } + cont = 0; + } + fat_invalidateLastChainResult(fatd); //prevent to misuse current (now deleted) fatd->cbuf + } + return 1; +} + +//--------------------------------------------------------------------------- +/* + Get single empty cluster from the clusterStack (cS is small cache of free clusters) + Passed currentCluster is updated in the FAT and the new returned cluster index is + appended at the end of fat chain! +*/ +static unsigned int fat_getFreeCluster(fat_driver* fatd, unsigned int currentCluster) +{ + + int ret; + unsigned int result; + + //cluster stack is empty - find and fill the cS + if (fatd->clStackIndex <= 0) { + fatd->clStackIndex = 0; + ret = fat_readEmptyClusters(fatd); + if (ret <= 0) + return 0; + fatd->clStackIndex = ret; + } + //pop from cluster stack + fatd->clStackIndex--; + result = fatd->clStack[fatd->clStackIndex]; + //append the cluster chain + if (currentCluster) { + ret = fat_appendClusterChain(fatd, currentCluster, result); + } else { //create new cluster chain + ret = fat_createClusterChain(fatd, result); + } + if (ret < 0) + return 0; + return result; +} + +//--------------------------------------------------------------------------- +/* +returns number of direntry positions that the name takes +//dlanor: Note that this only includes the long_name entries +*/ +static int getDirentrySize(const char* lname) +{ + int len; + int result; + len = strlen(lname); + result = len / 13; + if (len % 13 > 0) + result++; + return result; +} + +//--------------------------------------------------------------------------- +/* +compute checksum of the short filename +*/ +static unsigned char computeNameChecksum(const char* sname) +{ + unsigned char result; + int i; + + result = 0; + for (i = 0; i < 11; i++) { + result = (0x80 * (0x01 & result)) + (result >> 1); //ROR 1 + result += sname[i]; + } + return result; +} + +//--------------------------------------------------------------------------- +/* + fill the LFN (long filename) direntry +*/ +static void setLfnEntry(const char* lname, int nameSize, unsigned char chsum, fat_direntry_lfn* dlfn, int part, int maxPart) +{ + int i, j; + unsigned char name[26]; //unicode name buffer = 13 characters per 2 bytes + int nameStart; + + nameStart = 13 * (part - 1); + j = nameSize - nameStart; + if (j > 13) { + j = 13; + } + + //fake unicode conversion + for (i = 0; i < j; i++) { + name[i * 2] = (unsigned char)lname[nameStart + i]; + name[i * 2 + 1] = 0; + } + + //rest of the name is zero terminated and padded with 0xFF + for (i = j; i < 13; i++) { + if (i == j) { + name[i * 2] = 0; + name[i * 2 + 1] = 0; + } else { + name[i * 2] = 0xFF; + name[i * 2 + 1] = 0xFF; + } + } + + dlfn->entrySeq = part; + if (maxPart == part) + dlfn->entrySeq |= 0x40; + dlfn->checksum = chsum; + //1st part of the name + for (i = 0; i < 10; i++) + dlfn->name1[i] = name[i]; + //2nd part of the name + for (i = 0; i < 12; i++) + dlfn->name2[i] = name[i + 10]; + //3rd part of the name + for (i = 0; i < 4; i++) + dlfn->name3[i] = name[i + 22]; + dlfn->rshv = 0x0f; + dlfn->reserved1 = 0; + dlfn->reserved2[0] = 0; + dlfn->reserved2[1] = 0; +} + +//--------------------------------------------------------------------------- +/* + update the SFN (long filename) direntry - DATE and TIME +*/ +static void setSfnDate(fat_direntry_sfn* dsfn, int mode) +{ + int year, month, day, hour, minute, sec; + unsigned char tmpClk[4]; + +#ifdef WIN32 + year = 0; + month = 0; + day = 0; + hour = 0; + minute = 0; + sec = 0; +#else + //ps2 specific routine to get time and date + sceCdCLOCK cdtime; + + if (sceCdReadClock(&cdtime) != 0 && cdtime.stat == 0) { + sec = btoi(cdtime.second); + minute = btoi(cdtime.minute); + hour = btoi(cdtime.hour); + day = btoi(cdtime.day); + month = btoi(cdtime.month & 0x7F); //Ignore century bit (when an old CDVDMAN is used). + year = btoi(cdtime.year) + 2000; + } else { + year = 2005; + month = 1; + day = 6; + hour = 14; + minute = 12; + sec = 10; + } +#endif + + if (dsfn == NULL || mode == 0) { + return; + } + + tmpClk[0] = (sec / 2) & 0x1F; //seconds + tmpClk[0] += (minute & 0x07) << 5; // minute + tmpClk[1] = (minute & 0x38) >> 3; // minute + tmpClk[1] += (hour & 0x1F) << 3; // hour + + tmpClk[2] = (day & 0x1F); //day + tmpClk[2] += (month & 0x07) << 5; // month + tmpClk[3] = (month & 0x08) >> 3; // month + tmpClk[3] += ((year - 1980) & 0x7F) << 1; //year + + M_DEBUG("year=%d, month=%d, day=%d h=%d m=%d s=%d \n", year, month, day, hour, minute, sec); + //set date & time of creation + if (mode & DATE_CREATE) { + dsfn->timeCreate[0] = tmpClk[0]; + dsfn->timeCreate[1] = tmpClk[1]; + dsfn->dateCreate[0] = tmpClk[2]; + dsfn->dateCreate[1] = tmpClk[3]; + dsfn->dateAccess[0] = tmpClk[2]; + dsfn->dateAccess[1] = tmpClk[3]; + } + //set date & time of modification + if (mode & DATE_MODIFY) { + dsfn->timeWrite[0] = tmpClk[0]; + dsfn->timeWrite[1] = tmpClk[1]; + dsfn->dateWrite[0] = tmpClk[2]; + dsfn->dateWrite[1] = tmpClk[3]; + } +} + +//--------------------------------------------------------------------------- +/* + fill the SFN (short filename) direntry +*/ +static void setSfnEntry(const char* shortName, char directory, fat_direntry_sfn* dsfn, unsigned int cluster) +{ + int i; + + //name + ext + for (i = 0; i < 8; i++) + dsfn->name[i] = shortName[i]; + for (i = 0; i < 3; i++) + dsfn->ext[i] = shortName[i + 8]; + + if (directory > 0) { + dsfn->attr = FAT_ATTR_DIRECTORY; + } else { + dsfn->attr = FAT_ATTR_ARCHIVE; + } + dsfn->reservedNT = 0; + dsfn->clusterH[0] = (cluster & 0xFF0000) >> 16; + dsfn->clusterH[1] = (cluster & 0xFF000000) >> 24; + dsfn->clusterL[0] = (cluster & 0x00FF); + dsfn->clusterL[1] = (cluster & 0xFF00) >> 8; + + //size is zero - because we don't know the filesize yet + for (i = 0; i < 4; i++) + dsfn->size[i] = 0; + + setSfnDate(dsfn, DATE_CREATE | DATE_MODIFY); +} + +static void setSfnEntryFromOld(const char* shortName, fat_direntry_sfn* dsfn, const fat_direntry_sfn* orig_dsfn) +{ + int i; + + memcpy(dsfn, orig_dsfn, sizeof(fat_direntry_sfn)); + + //name + ext + for (i = 0; i < 8; i++) + dsfn->name[i] = shortName[i]; + for (i = 0; i < 3; i++) + dsfn->ext[i] = shortName[i + 8]; +} + +//--------------------------------------------------------------------------- +/* + Create short name by squeezing long name into the 8.3 name boundaries + lname - existing long name + sname - buffer where to store short name + + returns: 0 if longname completely fits into the 8.3 boundaries + 1 if long name have to be truncated (ie. INFORM~1.TXT) + <0 if invalid long name detected +*/ +static int createShortNameMask(char* lname, char* sname) +{ + int i; + int size; + int j; + int fit; + + if ((lname[0] == '.') + && ((lname[1] == 0) + || ((lname[1] == '.') + && (lname[2] == 0)))) { + return -EINVAL; + } + + fit = 0; + //clean short name by putting space + for (i = 0; i < 11; i++) + sname[i] = ' '; + M_DEBUG("Clear short name ='%s'\n", sname); + + //detect number of dots and space characters in the long name + j = 0; + for (i = 0; lname[i] != 0; i++) { + if (lname[i] == '.') + j++; + else if (lname[i] == ' ') + j += 2; + } + //long name contains no dot or one dot and no space char + if (j <= 1) + fit++; + //M_DEBUG("fit1=%d j=%d\n", fit, j); + + //store name + for (i = 0; lname[i] != 0 && lname[i] != '.' && i < 8; i++) { + sname[i] = toupper(lname[i]); + //short name must not contain spaces - replace space by underscore + if (sname[i] == ' ') + sname[i] = '_'; + } + //check wether last char is '.' and the name is shorter than 8 + if (lname[i] == '.' || lname[i] == 0) { + fit++; + } + //M_DEBUG("fit2=%d\n", fit); + + //find the last dot "." - filename extension + size = strlen(lname); + size--; + + for (i = size; i > 0 && lname[i] != '.'; i--) + ; + if (lname[i] == '.') { + i++; + for (j = 0; lname[i] != 0 && j < 3; i++, j++) { + sname[j + 8] = toupper(lname[i]); + } + //no more than 3 characters of the extension + if (lname[i] == 0) + fit++; + } else { + //no dot detected in the long filename + fit++; + } + // M_DEBUG("fit3=%d\n", fit); + // M_DEBUG("Long name=%s Short name=%s \n", lname, sname); + + //all 3 checks passed - the long name fits in the short name without restrictions + if (fit == 3) { + M_DEBUG("Short name is loseles!\n"); + return 0; + } + + //one of the check failed - the short name have to be 'sequenced' + //do not allow spaces in the short name + for (i = 0; i < 8; i++) { + if (sname[i] == ' ') + sname[i] = '_'; + } + return 1; +} + +//--------------------------------------------------------------------------- +/* + separate path and filename + fname - the source (merged) string (input) + path - separated path (output) + name - separated filename (output) +*/ +static int separatePathAndName(const char* fname, char* path, char* name) +{ + int path_len; + const char *sp, *np; + + if (!(sp = strrchr(fname, '/'))) //if last path separator missing ? + np = fname; // name starts at start of fname string + else //else last path separator found + np = sp + 1; // name starts after separator + if (strlen(np) >= FAT_MAX_NAME) //if name is too long + return -ENAMETOOLONG; // return error code + strcpy(name, np); //copy name from correct part of fname string + if ((path_len = (np - fname)) >= FAT_MAX_PATH) //if path is too long + return -ENAMETOOLONG; // return error code + strncpy(path, fname, path_len); //copy path from start of fname string + path[path_len] = 0; //terminate path + return 1; +} + +//--------------------------------------------------------------------------- +/* + get the sequence number from existing direntry name +*/ +static int getShortNameSequence(char* name, char* ext, const char* sname) +{ + int i, j; + const char* tmp; + char buf[8]; + + //at first: compare extensions + //if extensions differ then filenames are diffrerent and seq is 0 + tmp = sname + 8; + for (i = 0; i < 3; i++) { + if (ext[i] != tmp[i]) + return 0; + } + + //at second: find tilde '~' character (search backward from the end) + for (i = 7; i > 0 && name[i] != '~'; i--) + ; + + if (i == 0) + return 0; // tilde char was not found or is at first character + + //now compare the names - up to '~' position + //if names differ then filenames are different; + for (j = 0; j < i; j++) { + if (name[j] != sname[j]) + return 0; + } + + //if we get to this point we know that extension and name match + //now get the sequence number behind the '~' + for (j = i + 1; j < 8; j++) + buf[j - i - 1] = name[j]; + buf[j - i - 1] = 0; //terminate + + M_DEBUG("found short name sequence number='%s' \n", buf); + return strtol(buf, NULL, 10); +} + +//--------------------------------------------------------------------------- +/* + set the short name sequence number +*/ +static int setShortNameSequence(fat_driver* fatd, char* sname) +{ + char number[8]; + char* buf; + int i, j; + int seq; + unsigned char mask; + + //dlanor: The code below was bugged in several ways, as it treated the high seq + //values stored in long_name records as separate seqs, and also failed to accept + //any valid seq value whose low part (stored in short_name record) was zero. + //I'm now replacing this garbage with a bit-mask oriented scheme + + seq = SEQ_MASK_SIZE; + for (i = 0; (i < (SEQ_MASK_SIZE >> 3)); i++) { //for each mask byte + if ((mask = fatd->seq_mask[i]) != 0xFF) { //if mask byte has any bit free + for (j = 0; j < 8; j++, mask >>= 1) { //for each bit in byte + if ((mask & 1) == 0) { //if free bit found + seq = (i << 3) + j; //set seq value + break; //break bit loop + } //ends "if free bit found" + } //ends "for each bit in byte" + break; //break byte loop + } //ends "if mask byte has any bit free" + } //ends "for each mask byte" + + memset(number, 0, 8); + sprintf(number, "%d", seq); + j = strlen(number); + + buf = sname + 7 - j; + buf[0] = '~'; + buf++; + for (i = 0; i < j; i++) + buf[i] = number[i]; + + return 0; +} + +//--------------------------------------------------------------------------- +/* + find space where to put the direntry +*/ +static int getDirentryStoreOffset(fat_driver* fatd, int entryCount, int direntrySize) +{ + int i; + int tightIndex; + int looseIndex; + int cont; + int id; + int slotStart; + int slotSize; + int mask_ix, mask_sh; + + //we search for sequence of deleted or empty entries (cleared bits in dir_used_mask) + //1) search the tight slot (that fits completely. ex: size = 3, and slot space is 3 ) + //2) search the suitable (loose) slot (ex: size = 3, slot space is 5) + + slotStart = -1; + slotSize = 0; + tightIndex = -1; + looseIndex = -1; + cont = 1; + //search the entries for entry types + for (i = 0; i < entryCount && cont; i++) { + mask_ix = i >> 3; + mask_sh = i & 7; + id = fatd->dir_used_mask[mask_ix] & (1 << mask_sh); + if (id == 0) { //empty entry + if (slotStart >= 0) { + slotSize++; + } else { + slotStart = i; + slotSize = 1; + M_DEBUG("*Start slot at index=%d ", slotStart); + } + } else { //occupied entry + if (tightIndex < 0 && slotSize == direntrySize) { + tightIndex = slotStart; + M_DEBUG("!Set tight index= %d\n", tightIndex); + } + if (looseIndex < 0 && slotSize > direntrySize) { + looseIndex = slotStart + slotSize - direntrySize; + M_DEBUG("!Set loose index= %d\n", looseIndex); + } + if (tightIndex >= 0 && looseIndex >= 0) { + cont = 0; + } + slotStart = -1; + slotSize = 0; + } + } + M_DEBUG("\n"); + + // tight index - smaller fragmentation of space, the larger blocks + // are left for larger filenames. + // loose index - more fragmentation of direntry space, but the direntry + // name has space for future enlargement (of the name). + // i.e. no need to reposition the direntry and / or + // to allocate additional fat cluster for direntry space. + + // we prefere tight slot if available, othervise we use the loose slot. + // if there are no tight and no loose slot then we position new direntry + // at the end of current direntry space + if (tightIndex >= 0) { + return tightIndex; + } + if (looseIndex >= 0) { + return looseIndex; + } + //last entry is (most likely) empty - and if so, use it + mask_ix = (entryCount - 1) >> 3; + mask_sh = (entryCount - 1) & 7; + id = fatd->dir_used_mask[mask_ix] & (1 << mask_sh); + if (id == 0) { + return entryCount - 1; + } + + return entryCount; +} + +//--------------------------------------------------------------------------- +/* + scans current directory entries and fills the info records + + lname - long filename (to test wether existing entry match the long name) (input) + sname - short filename ( ditto ^^ ) (input) + startCluster - valid start cluster of the directory or 0 if we scan the root directory (input), first cluster of dirent (output). + directory - Entry type to check against. 0 = file, >0 = directory, <0 = ignore type. + + if file/directory already exist (return code 0) then: + retSector - contains sector number of the direntry (output) + retOffset - contains byte offse of the SFN direntry from start of the sector (output) + the reason is to speed up modification of the SFN (size of the file) +//dlanor: This function has been rewritten to use global bitmask arrays for output +*/ +static int fat_fillDirentryInfo(fat_driver* fatd, const char* lname, const char* sname, + char directory, unsigned int* startCluster, + unsigned int* retSector, int* retOffset) +{ + fat_direntry_summary dir; + int i, j; + unsigned int startSector, dirSector, theSector; + int cont; + int ret; + unsigned int dirPos; + int seq; + int mask_ix, mask_sh; + + memset(fatd->dir_used_mask, 0, DIR_MASK_SIZE / 8); + memset(fatd->seq_mask, 0, SEQ_MASK_SIZE / 8); + + cont = 1; + //clear name strings + dir.sname[0] = 0; + dir.name[0] = 0; + + j = 0; + if (directory > 0) + directory = FAT_ATTR_DIRECTORY; + + fat_getDirentrySectorData(fatd, startCluster, &startSector, &dirSector); + + M_DEBUG("dirCluster=%u startSector=%u (%u) dirSector=%u \n", *startCluster, startSector, startSector * fatd->bd->sectorSize, dirSector); + + //go through first directory sector till the max number of directory sectors + //or stop when no more direntries detected + for (i = 0; i < dirSector && cont; i++) { + unsigned char* sbuf = NULL; //sector buffer + + //At cluster borders, get correct sector from cluster chain buffer + if ((*startCluster != 0) && (i % fatd->partBpb.clusterSize == 0)) { + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[(i / fatd->partBpb.clusterSize)]) - i; + } + theSector = startSector + i; + ret = READ_SECTOR(fatd, theSector, sbuf); + if (ret < 0) { + M_DEBUG("read directory sector failed ! sector=%u\n", theSector); + return -EIO; + } + M_DEBUG("read sector ok, scanning sector for direntries...\n"); + dirPos = 0; + + // go through start of the sector till the end of sector + while (cont && (dirPos < fatd->partBpb.sectorSize) && (j < DIR_MASK_SIZE)) { + fat_direntry* dir_entry = (fat_direntry*)(sbuf + dirPos); + cont = fat_getDirentry(fatd->partBpb.fatType, dir_entry, &dir); //get single directory entry from sector buffer + mask_ix = j >> 3; + mask_sh = j & 7; + switch (cont) { + case 1: //short name + fatd->dir_used_mask[mask_ix] |= (1 << mask_sh); + if (!(dir.attr & FAT_ATTR_VOLUME_LABEL)) { //not volume label + if ((strEqual(dir.sname, lname) == 0) || (strEqual(dir.name, lname) == 0)) { + //file we want to create already exist - return the cluster of the file + if ((directory >= 0) && ((dir.attr & FAT_ATTR_DIRECTORY) != directory)) { + //found directory but requested is file (and vice veresa) + if (directory) + return -ENOTDIR; + return -EISDIR; + } //ends "if" clause for mismatched file/folder state + M_DEBUG("I: entry found! %s, %s = %s\n", dir.name, dir.sname, lname); + *retSector = theSector; + *retOffset = dirPos; + *startCluster = dir.cluster; + fatd->deSec[fatd->deIdx] = theSector; + fatd->deOfs[fatd->deIdx] = dirPos; + fatd->deIdx++; + return 0; + } //ends "if" clause for matching name + seq = getShortNameSequence((char*)dir_entry->sfn.name, (char*)dir_entry->sfn.ext, sname); + if (seq < SEQ_MASK_SIZE) + fatd->seq_mask[seq >> 3] |= (1 << (seq & 7)); + fatd->deIdx = 0; + //clear name strings + dir.sname[0] = 0; + dir.name[0] = 0; + } //ends "if(!(dir.attr & FAT_ATTR_VOLUME_LABEL))" + else { //dlanor: Volume label + fatd->deIdx = 0; + } + break; + case 2: //long name + fatd->dir_used_mask[mask_ix] |= (1 << mask_sh); + fatd->deSec[fatd->deIdx] = theSector; + fatd->deOfs[fatd->deIdx] = dirPos; + fatd->deIdx++; + break; + case 3: //empty + fatd->deIdx = 0; + break; + } //ends "switch" + dirPos += sizeof(fat_direntry); + j++; + } + } + //indicate inconsistency + if (j >= DIR_MASK_SIZE) { + j++; + } + return j; +} + +//--------------------------------------------------------------------------- +/* + check wether the new direntries (note: one file have at least 2 direntries for 1 SFN and 1..n LFN) + fit into the current directory space. + Enlarges the directory space if needed and possible (note: root dirspace can't be enlarged for fat12 and fat16) + + startCluster - valid start cluster of dirpace or 0 for the root directory + entryCount - number of direntries of the filename (at least 2) + entryIndex - index where to store new direntries + direntrySize - number of all direntries in the directory +*/ + +static int enlargeDirentryClusterSpace(fat_driver* fatd, unsigned int startCluster, int entryCount, int entryIndex, int direntrySize) +{ + int ret; + unsigned int startSector, dirSector; + int i; + int maxSector; + int entriesPerSector; + int chainSize; + unsigned int currentCluster; + unsigned int newCluster; + + i = entryIndex + direntrySize; + M_DEBUG("cur=%d ecount=%d \n", i, entryCount); + //we don't need to enlarge directory cluster space + if (i <= entryCount) + return 0; //direntry fits into current space + + entriesPerSector = fatd->partBpb.sectorSize / 32; + maxSector = i / entriesPerSector; + if (i % entriesPerSector) { + maxSector++; + } + + chainSize = fat_getDirentrySectorData(fatd, &startCluster, &startSector, &dirSector); + + M_DEBUG("maxSector=%u dirSector=%u\n", maxSector, dirSector); + + if (maxSector <= dirSector) + return 0; + + //Root directory of FAT12 or FAT16 - space can't be enlarged! + if (startCluster == 0 && fatd->partBpb.fatType < FAT32) { + return -EMLINK; //too many direntries in the root directory + } + + //in the fatd->cbuf we have the cluster chain + + //get last cluster of the cluster chain + currentCluster = fatd->cbuf[chainSize - 1]; + M_DEBUG("current (last) cluster=%u \n", currentCluster); + + //get 1 cluster from cluster stack and append the chain + newCluster = fat_getFreeCluster(fatd, currentCluster); + M_DEBUG("new cluster=%u \n", newCluster); + fat_invalidateLastChainResult(fatd); //prevent to misuse current (now updated) fatd->cbuf + //if new cluster cannot be allocated + if (newCluster == 0) { + return -ENOSPC; + } + + // now clean the directory space + startSector = fat_cluster2sector(&fatd->partBpb, newCluster); + for (i = 0; i < fatd->partBpb.clusterSize; i++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = ALLOC_SECTOR(fatd, startSector + i, sbuf); + memset(sbuf, 0, fatd->partBpb.sectorSize); //fill whole sector with zeros + ret = WRITE_SECTOR(fatd, startSector + i); + if (ret < 0) + return -EIO; + } + return 1; // 1 cluster allocated +} + +//--------------------------------------------------------------------------- +/* + Create empty directory space with two SFN direntries: + 1) current directory "." + 2) parent directory ".." + +*/ +static int createDirectorySpace(fat_driver* fatd, unsigned int dirCluster, unsigned int parentDirCluster) +{ + int i, j; + int ret; + unsigned int startSector; + + //we do not mess with root directory + if (dirCluster < 2) { + return -EFAULT; + } + + //we create directory space inside one cluster. No need to worry about + //large dir space spread on multiple clusters + startSector = fat_cluster2sector(&fatd->partBpb, dirCluster); + M_DEBUG("I: create dir space: cluster=%u sector=%u (%u) \n", dirCluster, startSector, startSector * fatd->partBpb.sectorSize); + + //go through all sectors of the cluster + for (i = 0; i < fatd->partBpb.clusterSize; i++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = ALLOC_SECTOR(fatd, startSector + i, sbuf); + if (ret < 0) { + M_DEBUG("alloc directory sector failed ! sector=%u\n", startSector + i); + return -EIO; + } + memset(sbuf, 0, fatd->partBpb.sectorSize); //clean the sector + if (i == 0) { + fat_direntry_sfn* dsfn = (fat_direntry_sfn*)sbuf; + char name[11]; + for (j = 1; j < 11; j++) + name[j] = ' '; + name[0] = '.'; + setSfnEntry(name, 1, dsfn + 0, dirCluster); + name[1] = '.'; + setSfnEntry(name, 1, dsfn + 1, parentDirCluster); + } + ret = WRITE_SECTOR(fatd, startSector + i); + if (ret < 0) { + M_DEBUG("write directory sector failed ! sector=%u\n", startSector + i); + return -EIO; + } + } + + return (0); +} + +/* + Update the parent directory ("..") entry cluster number of the specified SFN direntry. +*/ +static int updateDirectoryParent(fat_driver* fatd, unsigned int dirCluster, unsigned int parentDirCluster) +{ + int i, j; + int ret; + unsigned int startSector; + + //we do not mess with root directory + if (dirCluster < 2) { + return -EFAULT; + } + + //The basic directory space should be within one cluster. No need to worry about + //large dir space spread on multiple clusters + startSector = fat_cluster2sector(&fatd->partBpb, dirCluster); + M_DEBUG("I: update dir parent: cluster=%u sector=%u (%u) \n", dirCluster, startSector, startSector * fatd->partBpb.sectorSize); + + //go through all sectors of the cluster + for (i = 0; i < fatd->partBpb.clusterSize; i++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = READ_SECTOR(fatd, startSector + i, sbuf); + if (ret < 0) { + M_DEBUG("read directory sector failed ! sector=%u\n", startSector + i); + return -EIO; + } + fat_direntry_sfn* dsfn = (fat_direntry_sfn*)sbuf; + for (j = 0; j < fatd->partBpb.sectorSize; j += sizeof(fat_direntry_sfn), dsfn++) { + if (memcmp(dsfn->name, ".. ", sizeof(dsfn->name)) == 0) { + dsfn->clusterH[0] = (parentDirCluster & 0xFF0000) >> 16; + dsfn->clusterH[1] = (parentDirCluster & 0xFF000000) >> 24; + dsfn->clusterL[0] = (parentDirCluster & 0x00FF); + dsfn->clusterL[1] = (parentDirCluster & 0xFF00) >> 8; + + ret = WRITE_SECTOR(fatd, startSector + i); + if (ret < 0) { + M_DEBUG("write directory sector failed ! sector=%u\n", startSector + i); + return -EIO; + } + + return 0; + } + } + } + + return -1; +} + +//--------------------------------------------------------------------------- +/* + Save direntries of the long and short filename to the directory space on the disk + + startCluster - start cluster of the directory space + lname : long name + sname : short name + directory : 0-file, 1-directory + cluster : start cluster of the file/directory + + entrySize - number of direntries to store + entryIndex - index of the direntry start in the directory space + + retSector - contains sector number of the direntry (output) + retOffset - contains byte offse of the SFN direntry from start of the sector (output) + the reason is to speed up modification of the SFN (size of the file) + + note: the filesize set in the direntry is 0 (for both directory and file) +*/ +static int saveDirentry(fat_driver* fatd, unsigned int startCluster, + const char* lname, const char* sname, char directory, unsigned int cluster, + int entrySize, int entryIndex, unsigned int* retSector, int* retOffset, const fat_direntry_sfn* orig_dsfn) +{ + int i, j; + unsigned int dirSector; + unsigned int startSector; + unsigned int theSector; + int cont; + int ret; + unsigned int dirPos; + int entryEndIndex; + int writeFlag; + int part = entrySize - 1; + int nameSize; + unsigned char chsum; + + chsum = computeNameChecksum(sname); + nameSize = strlen(lname); + + cont = 1; + //clear name strings + entryEndIndex = entryIndex + entrySize; + + j = 0; + + fat_getDirentrySectorData(fatd, &startCluster, &startSector, &dirSector); + + M_DEBUG("dirCluster=%u startSector=%u (%u) dirSector=%u \n", startCluster, startSector, startSector * fatd->bd->sectorSize, dirSector); + + //go through first directory sector till the max number of directory sectors + //or stop when no more direntries detected + for (i = 0; i < dirSector && cont; i++) { + unsigned char* sbuf = NULL; //sector buffer + + //At cluster borders, get correct sector from cluster chain buffer + if ((startCluster != 0) && (i % fatd->partBpb.clusterSize == 0)) { + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[(i / fatd->partBpb.clusterSize)]) - i; + } + theSector = startSector + i; + ret = READ_SECTOR(fatd, theSector, sbuf); + if (ret < 0) { + M_DEBUG("read directory sector failed ! sector=%u\n", theSector); + return -EIO; + } + M_DEBUG("read sector ok, scanning sector for direntries...\n"); + dirPos = 0; + writeFlag = 0; + // go through start of the sector till the end of sector + while (dirPos < fatd->partBpb.sectorSize) { + if (j >= entryIndex && j < entryEndIndex) { + fat_direntry* dir_entry = (fat_direntry*)(sbuf + dirPos); + if (part == 0) { + if (orig_dsfn == NULL) + setSfnEntry(sname, directory, &dir_entry->sfn, cluster); + else + setSfnEntryFromOld(sname, &dir_entry->sfn, orig_dsfn); + } else + setLfnEntry(lname, nameSize, chsum, &dir_entry->lfn, part, entrySize - 1); + part--; + writeFlag++; + //SFN is stored + if (j == entryEndIndex - 1) { + *retSector = theSector; + *retOffset = dirPos; + } + } + //sbuf + dirPos + dirPos += sizeof(fat_direntry); + j++; + } //ends "while" + //store modified sector + if (writeFlag) { + ret = WRITE_SECTOR(fatd, theSector); + if (ret < 0) { + M_DEBUG("write directory sector failed ! sector=%u\n", theSector); + return -EIO; + } + } + if (j >= entryEndIndex) { + cont = 0; //do not continue + } + } + return j; +} + +//--------------------------------------------------------------------------- +/* + - create/convert long name to short name + - analyse directory space + - enlarge directory space + - save direntries + + lname - long name + directory - 0-> create file 1->create directory + escapeNoExist - 0->allways create file 1->early exit if file doesn't exist + startCluster - directory space start cluster (set to zero for root directory) (input), first cluster of dirent (output) + retSector - SFN sector - sector of the SFN direntry (output) + retOffset - byte offset of the SFN direntry counting from the start of the sector (output) + orig_dsfn - Dirent SFN entry, to use as the new dirent. +*/ + +static int fat_modifyDirSpace(fat_driver* fatd, char* lname, char directory, char escapeNotExist, unsigned int *startCluster, unsigned int* retSector, int* retOffset, const fat_direntry_sfn *orig_dsfn) +{ + char sname[12]; //short name 8+3 + terminator + unsigned int newCluster, parentDirCluster; + int ret, entryCount, compressShortName, entryIndex, direntrySize; + + //dlanor: Since each filename may need up to 11 directory entries (MAX_FAT_NAME==128) + //dlanor: I've rewritten the methods of this function to use global bitmasks as this + //dlanor: allows more effective entry handling than most other methods + // + //memo buffer for each direntry - up to 1024 entries in directory + // 7 6 5 4 3 2 | 1 0 + // ------------+----- + // SEQ HI/LO | ID + // ------------------ + // ID : 0 - entry is empty or deleted + // 1 - sfn entry + // 2 - lfn entry + // 3 - other entry (volume label etc.) + // SEQ: sequence number of the short filename. + // if our long filename is "Quitelongname.txt" then + // seq for existing entry: + // ABCD.TXT seq = 0 (no sequence number in name and name doesn't match) + // ABCDEF~1.TXT seq = 0 (because the short names doesn't match) + // QUITELON.TXT seq = 0 (again the short name doesn't match) + // QUITEL~1.JPG seq = 0 (name match but extension desn't match) + // QUITEL~1.TXT seq = 1 (both name and extension match - sequence number 1) + // QUITE~85.TXT seq = 85 ( dtto. ^^^^) + + // If the sfn has sequence it means the filename should be long + // and preceeding entry should be lfn. In this case the preceeding (lfn) + // entry seq holds the high 6 bites of the whole sequence. If preceding + // entry is another sfn direntry then we report error (even if it might be + // (in some rare occasions) correct directory structure). + + sname[11] = 0; + + //create short name from long name + ret = createShortNameMask(lname, sname); + if (ret < 0) { + M_DEBUG("E: short name invalid!\n"); + return ret; + } + compressShortName = ret; + + //get information about existing direntries (palcement of the empty/reusable direntries) + //and sequence numbers of the short filenames + parentDirCluster = *startCluster; + ret = fat_fillDirentryInfo(fatd, lname, sname, directory, + startCluster, retSector, retOffset); + if (ret < 0) { + M_DEBUG("E: direntry data invalid!\n"); + return ret; + } + //ret 0 means that exact filename/directory already exist + if (ret == 0) { + return ret; + } + + //exact filename not exist and we want to report it + if (escapeNotExist) { + return -ENOENT; + } + + if (ret > DIR_MASK_SIZE) { + M_DEBUG("W: Direntry count is larger than number of records!\n"); + ret = DIR_MASK_SIZE; + } + entryCount = ret; + M_DEBUG("I: direntry count=%d\n", entryCount); + + if (compressShortName) { + setShortNameSequence(fatd, sname); + } + M_DEBUG("I: new short name='%s' \n", sname); + + //direntry size for long name + 1 additional direntry for short name + direntrySize = getDirentrySize(lname) + 1; + M_DEBUG("Direntry size=%d\n", direntrySize); + + //find the offset (index) of the direntry space where to put this direntry + entryIndex = getDirentryStoreOffset(fatd, entryCount, direntrySize); + M_DEBUG("I: direntry store offset=%d\n", entryIndex); + + //if the direntry offset excede current space of directory clusters + //we have to add one cluster to directory space + ret = enlargeDirentryClusterSpace(fatd, parentDirCluster, entryCount, entryIndex, direntrySize); + M_DEBUG("I: enlarge direntry cluster space ret=%d\n", ret); + if (ret < 0) { + return ret; + } + + if (orig_dsfn == NULL) { + //get new cluster for file/directory + newCluster = fat_getFreeCluster(fatd, 0); + if (newCluster == 0) { + return -ENOSPC; + } + M_DEBUG("I: new file/dir cluster=%u\n", newCluster); + *startCluster = newCluster; + } else { + newCluster = 0; + *startCluster = (fatd->partBpb.fatType == FAT32) ? getUI32_2(orig_dsfn->clusterL, orig_dsfn->clusterH) : getUI16(orig_dsfn->clusterL); + } + + //now store direntries into the directory space + ret = saveDirentry(fatd, parentDirCluster, lname, sname, directory, newCluster, direntrySize, entryIndex, retSector, retOffset, orig_dsfn); + M_DEBUG("I: save direntry ret=%d\n", ret); + if (ret < 0) { + return ret; + } + + //create empty directory structure + if ((orig_dsfn == NULL) && directory) { + ret = createDirectorySpace(fatd, newCluster, parentDirCluster); + M_DEBUG("I: create directory space ret=%d\n", ret); + if (ret < 0) { + return ret; + } + } + + return 1; +} + +//--------------------------------------------------------------------------- +/* + Check whether directory space contain any file or directory + + startCluster - start cluster of the directory space + + returns: 0 - false - directory space contains files or directories (except '.' and '..') + 1 - true - directory space is empty or contains deleted entries + -X - error +*/ +static int checkDirspaceEmpty(fat_driver* fatd, unsigned int startCluster) +{ + int ret; + int i; + char sname[12]; //short name 8+3 + terminator + int entryCount; + + unsigned int retSector; + int retOffset; + + M_DEBUG("I: checkDirspaceEmpty directory cluster=%u \n", startCluster); + if (startCluster < 2) { // do not check root directory! + return -EFAULT; + } + + sname[0] = 0; + + ret = fat_fillDirentryInfo(fatd, sname, sname, 1, + &startCluster, &retSector, &retOffset); + if (ret > DIR_MASK_SIZE) { + M_DEBUG("W: Direntry count is larger than number of records! directory space cluster =%u maxRecords=%u\n", startCluster, DIR_MASK_SIZE); + ret = DIR_MASK_SIZE; + } + entryCount = ret; + //first two records should be '.' & '..', which don't count as real content + if ((fatd->dir_used_mask[0] & 0xFC) != 0) + goto non_empty; + for (i = 1; i < (entryCount / 8); i++) { + if (fatd->dir_used_mask[i] != 0) { + non_empty: + M_DEBUG("I: directory not empty!\n"); + return 0; + } //ends "if" + } //ends "for" + M_DEBUG("I: directory is empty.\n"); + return 1; +} + +//--------------------------------------------------------------------------- +static int fat_wipeDirEntries(fat_driver* fatd) +{ + int ret; + unsigned int i, theSector; + unsigned char* sbuf = NULL; + + //now mark direntries as deleted + theSector = 0; + ret = 0; + for (i = 0; i < fatd->deIdx; i++) { + if (fatd->deSec[i] != theSector) { + if (theSector > 0) { + ret = WRITE_SECTOR(fatd, theSector); + if (ret < 0) { + M_DEBUG("write directory sector failed ! sector=%u\n", theSector); + ret = -EIO; + break; + } + } + theSector = fatd->deSec[i]; + ret = READ_SECTOR(fatd, theSector, sbuf); + if (ret < 0) { + M_DEBUG("read directory sector failed ! sector=%u\n", theSector); + ret = -EIO; + break; + } + } + sbuf[fatd->deOfs[i]] = 0xE5; //delete marker + } + if (theSector > 0) { + ret = WRITE_SECTOR(fatd, theSector); + if (ret < 0) { + M_DEBUG("write directory sector failed ! sector=%u\n", theSector); + ret = -EIO; + } + } + + return ret; +} + +/* + Remove the name (direntries of the file or directory) from the directory space. + + lname - long name (without the path) + directory - 0->delete file 1-delete directory + startCluster - start cluster of the directory space +*/ + +static int fat_clearDirSpace(fat_driver* fatd, char* lname, char directory, unsigned int* startCluster) +{ + int ret; + char sname[12]; //short name 8+3 + terminator + unsigned int dirCluster; + unsigned int sfnSector; + int sfnOffset; + + sname[0] = 0; + + dirCluster = *startCluster; + //get information about existing direntries (palcement of the empty/reusable direntries) + //and find the lname in the directory + //also fill up the dsSec and dsOfs information + ret = fat_fillDirentryInfo(fatd, lname, sname, directory, + startCluster, &sfnSector, &sfnOffset); + if (ret != 0) { + M_DEBUG("E: direntry not found!\n"); + return -ENOENT; + } + M_DEBUG("clear dir space: dir found at cluster=%u \n ", *startCluster); + + //Check wether any file or directory exist in te target directory space. + //We should not delete the directory if files/directories exist + //because just clearing the dir doesn't free the fat clusters + //occupied by files. + if (directory) { + //check wether sub-directory is empty + //startCluster now points to subdirectory start cluster + ret = checkDirspaceEmpty(fatd, *startCluster); + if (ret == 0) { //directorty contains some files + return -ENOTEMPTY; + } + //read the direntry info again, because we lost it during subdir check + *startCluster = dirCluster; + + ret = fat_fillDirentryInfo(fatd, lname, sname, directory, + startCluster, &sfnSector, &sfnOffset); + if (ret != 0) { + M_DEBUG("E: direntry not found!\n"); + return -ENOENT; + } + } + + //now mark direntries as deleted + ret = fat_wipeDirEntries(fatd); + if (ret < 0) { + M_DEBUG("E: wipe direntries failed!\n"); + return ret; + } + + //now delete whole cluster chain starting at the file's first cluster + ret = fat_deleteClusterChain(fatd, *startCluster); + if (ret < 0) { + M_DEBUG("E: delete cluster chain failed!\n"); + return ret; + } + return 1; +} + +/* ===================================================================== */ + +/* + cluster - start cluster of the file + sfnSector - short filename entry sector + sfnOffset - short filename entry offset from the sector start +*/ +int fat_truncateFile(fat_driver* fatd, unsigned int cluster, unsigned int sfnSector, int sfnOffset) +{ + int ret; + fat_direntry_sfn* dsfn; + unsigned char* sbuf = NULL; //sector buffer + + if (cluster == 0 || sfnSector == 0) { + return -EFAULT; + } + + //now delete whole cluster chain starting at the file's first cluster + ret = fat_deleteClusterChain(fatd, cluster); + if (ret < 0) { + M_DEBUG("E: delete cluster chain failed!\n"); + return ret; + } + + //terminate cluster + ret = fat_createClusterChain(fatd, cluster); + if (ret < 0) { + M_DEBUG("E: truncate cluster chain failed!\n"); + return ret; + } + + ret = READ_SECTOR(fatd, sfnSector, sbuf); + if (ret < 0) { + M_DEBUG("read direntry sector failed ! sector=%u\n", sfnSector); + return -EIO; + } + dsfn = (fat_direntry_sfn*)(sbuf + sfnOffset); + dsfn->size[0] = 0; + dsfn->size[1] = 0; + dsfn->size[2] = 0; + dsfn->size[3] = 0; + + ret = WRITE_SECTOR(fatd, sfnSector); + if (ret < 0) { + M_DEBUG("write directory sector failed ! sector=%u\n", sfnSector); + return -EIO; + } + return 1; +} + +//--------------------------------------------------------------------------- +/* + Update size of the SFN entry + + cluster - start cluster of the file + sfnSector - short filename entry sector + sfnOffset - short filename entry offset from the sector start +*/ +int fat_updateSfn(fat_driver* fatd, int size, unsigned int sfnSector, int sfnOffset) +{ + int ret; + fat_direntry_sfn* dsfn; + unsigned char* sbuf = NULL; //sector buffer + + if (sfnSector == 0) { + return -EFAULT; + } + + ret = READ_SECTOR(fatd, sfnSector, sbuf); + if (ret < 0) { + M_DEBUG("read direntry sector failed ! sector=%u\n", sfnSector); + return -EIO; + } + dsfn = (fat_direntry_sfn*)(sbuf + sfnOffset); + dsfn->size[0] = size & 0xFF; + dsfn->size[1] = (size & 0xFF00) >> 8; + dsfn->size[2] = (size & 0xFF0000) >> 16; + dsfn->size[3] = (size & 0xFF000000) >> 24; + + setSfnDate(dsfn, DATE_MODIFY); + + ret = WRITE_SECTOR(fatd, sfnSector); + if (ret < 0) { + M_DEBUG("write directory sector failed ! sector=%u\n", sfnSector); + return -EIO; + } + M_DEBUG("I: sfn updated, file size=%d \n", size); + return 1; +} + +//--------------------------------------------------------------------------- +/* + create file or directory + + fname - path and filename + directory - set to 0 to create file, 1 to create directory + escapeNotExist - set to 1 if you want to report error if file not exist. + Otherwise set to 0 and file/dir will be created. + cluster - start cluster of the directory space - default is 0 -> root directory (input), first cluster of dirent (output). + sfnSector - sector of the SFN entry (output) - helps to modify direntry (size, date, time) + sfnOffset - offset (in bytes) of the SFN entry (output) +*/ + +int fat_createFile(fat_driver* fatd, const char* fname, char directory, char escapeNotExist, unsigned int* cluster, unsigned int* sfnSector, int* sfnOffset) +{ + int ret; + unsigned int startCluster; + unsigned int directoryCluster; + char lname[FAT_MAX_NAME], pathToDirent[FAT_MAX_PATH]; + fat_dir fatdir; + + ret = separatePathAndName(fname, pathToDirent, lname); + if ((ret < 0) //if name invalid to separation routine + || ((lname[0] == 0) //or name is empty string + || ((lname[0] == '.') + && ((lname[1] == 0) //or name is single period + || ((lname[1] == '.') + && (lname[2] == 0) //or name is two periods + ))))) { + M_DEBUG("E: file name not exist or not valid!"); + return -ENOENT; + } + + M_DEBUG("Calling fat_getFileStartCluster from fat_createFile\n"); + //get start cluster of the last sub-directory of the path + startCluster = 0; + ret = fat_getFileStartCluster(fatd, pathToDirent, &startCluster, &fatdir); + if (ret < 0) { + M_DEBUG("E: directory not found! \n"); + return ret; + } + + if (!(fatdir.attr & FAT_ATTR_DIRECTORY)) { + M_DEBUG("E: directory not found! \n"); + return -ENOENT; + } + + M_DEBUG("directory=%s name=%s cluster=%u \n", pathToDirent, lname, startCluster); + + if (fatdir.attr & FAT_ATTR_READONLY) + return -EACCES; + + //modify directory space of the path (cread direntries) + //and/or create new (empty) directory space if directory creation requested + directoryCluster = startCluster; + ret = fat_modifyDirSpace(fatd, lname, directory, escapeNotExist, &startCluster, sfnSector, sfnOffset, NULL); + if (ret < 0) { + M_DEBUG("E: modifyDirSpace failed!\n"); + return ret; + } + M_DEBUG("I: SFN info: sector=%u (%u) offset=%u (%u) startCluster=%u\n", *sfnSector, *sfnSector * fatd->partBpb.sectorSize, *sfnOffset, *sfnOffset + (*sfnSector * fatd->partBpb.sectorSize), startCluster); + *cluster = startCluster; + //dlanor: I've repatched the stuff below to improve functionality + //The simple test below was bugged for the case of creating a folder in root + //if (startCluster != directoryCluster) { + //That test (on the line above) fails in root because created folders never + //get a startCluster of 0. That is reserved for root only. + //The test below replaces this with a more complex test that takes all of this + //stuff into proper account, but behaves like the old test for other cases. + //That's mainly because I can't tell how consistent name conflict flagging is + //for those other cases, and it's not really worth the trouble of finding out :) + if ((ret == 0) //if we have a directly flagged name conflict + || ((directoryCluster || !directory) //OR working in non_root, or making a file + && (startCluster != directoryCluster) //AND we get an unexpected startCluster + )) { + M_DEBUG("I: file already exists at cluster=%u\n", startCluster); + return EEXIST; + } + return 0; +} + +//--------------------------------------------------------------------------- +int fat_deleteFile(fat_driver* fatd, const char* fname, char directory) +{ + int ret; + unsigned int startCluster; + unsigned int directoryCluster; + char lname[FAT_MAX_NAME], pathToDirent[FAT_MAX_PATH]; + fat_dir fatdir; + + ret = separatePathAndName(fname, pathToDirent, lname); + if ((ret < 0) //if name invalid to separation routine + || ((lname[0] == 0) //or name is empty string + || ((lname[0] == '.') + && ((lname[1] == 0) //or name is single period + || ((lname[1] == '.') + && (lname[2] == 0) //or name is two periods + ))))) { + M_DEBUG("E: file name not exist or not valid!"); + return -ENOENT; + } + + M_DEBUG("Calling fat_getFileStartCluster from fat_deleteFile\n"); + //get start cluster of the last sub-directory of the path + startCluster = 0; + ret = fat_getFileStartCluster(fatd, pathToDirent, &startCluster, &fatdir); + if (ret < 0) { + M_DEBUG("E: directory not found! \n"); + return ret; + } + + if (!(fatdir.attr & FAT_ATTR_DIRECTORY)) { + M_DEBUG("E: directory not found! \n"); + return -ENOENT; + } + + M_DEBUG("directory=%s name=%s cluster=%u \n", pathToDirent, lname, startCluster); + + if (fatdir.attr & FAT_ATTR_READONLY) { + M_DEBUG("E: directory read only! \n"); + return -EACCES; + } + + //delete direntries and modify fat + directoryCluster = startCluster; + ret = fat_clearDirSpace(fatd, lname, directory, &startCluster); + if (ret < 0) { + M_DEBUG("E: cleanDirSpace failed!\n"); + return ret; + } + if (startCluster != directoryCluster) { + M_DEBUG("I: file/dir removed from cluster=%u\n", startCluster); + } + return 0; +} + +//--------------------------------------------------------------------------- +//Create a new record that points to the file/directory, before deleting the original one. + +int fat_renameFile(fat_driver* fatd, fat_dir* fatdir, const char* fname) +{ + int ret; + unsigned int sDirCluster; + unsigned int dDirCluster, dParentDirCluster; + char lname[FAT_MAX_NAME], pathToDirent[FAT_MAX_PATH]; + unsigned int sfnSector, new_sfnSector, startCluster; + int sfnOffset, new_sfnOffset; + char sname[12]; //short name 8+3 + terminator + unsigned char* sbuf = NULL; + unsigned char srcIsDirectory; + fat_direntry_sfn OriginalSFN; + + ret = separatePathAndName(fname, pathToDirent, lname); + if ((ret < 0) //if name invalid to separation routine + || ((lname[0] == 0) //or name is empty string + || ((lname[0] == '.') + && ((lname[1] == 0) //or name is single period + || ((lname[1] == '.') + && (lname[2] == 0) //or name is two periods + ))))) { + M_DEBUG("E: destination file name not exist or not valid!"); + return -ENOENT; + } + + //Check if the source file exists, and that the new filename is not in use. + sDirCluster = fatdir->parentDirCluster; + dDirCluster = 0; + M_DEBUG("Calling fat_getFileStartCluster from fat_renameFile\n"); + + ret = fat_getFileStartCluster(fatd, pathToDirent, &dDirCluster, NULL); + if (ret < 0) { + M_DEBUG("E: destination directory not found! \n"); + return ret; + } + dParentDirCluster = dDirCluster; //Backup dDirCluster, as every call to fat_filleDirentryInfo will update it to point to the scanned file's first cluster. + + //Get the SFN sector number and offset, so that the SFN record can be read. + sname[0] = 0; + ret = fat_fillDirentryInfo(fatd, fatdir->name, sname, -1, &sDirCluster, &sfnSector, &sfnOffset); + if (ret != 0) { + M_DEBUG("E: direntry not found! %d\n", ret); + return -ENOENT; + } + + M_DEBUG("fat_renameFile: dir found at cluster=%u \n ", sDirCluster); + + //Preserve the original SFN entry. + if ((ret = READ_SECTOR(fatd, sfnSector, sbuf)) < 0) { + M_DEBUG("E: I/O error! %d\n", ret); + return ret; + } + memcpy(&OriginalSFN, (fat_direntry_sfn*)(sbuf + sfnOffset), sizeof(fat_direntry_sfn)); + srcIsDirectory = ((fat_direntry_sfn*)(sbuf + sfnOffset))->attr & FAT_ATTR_DIRECTORY; + + ret = fat_fillDirentryInfo(fatd, lname, sname, srcIsDirectory, &dDirCluster, &new_sfnSector, &new_sfnOffset); + if (ret == 0) { + //Entry is found and the type is the same as the original (both are either directories or files). + if (srcIsDirectory) { + //If directory, the rename can still take place if the directory can be deleted (is empty). + dDirCluster = dParentDirCluster; + if ((ret = fat_clearDirSpace(fatd, lname, 1, &dDirCluster)) < 0) + return ret; + } else { + //Do not allow a file to be renamed to an existing file. + return -EEXIST; + } + } + + //Insert a new record. + startCluster = dParentDirCluster; + if ((ret = fat_modifyDirSpace(fatd, lname, srcIsDirectory, 0, &startCluster, &sfnSector, &sfnOffset, &OriginalSFN)) < 0) { + M_DEBUG("E: fat_modifyDirSpace failed! %d\n", ret); + return ret; + } + + //If it is a directory, update the parent directory record. + if (srcIsDirectory) { + dDirCluster = (fatd->partBpb.fatType == FAT32) ? getUI32_2(OriginalSFN.clusterL, OriginalSFN.clusterH) : getUI16(OriginalSFN.clusterL); + if ((ret = updateDirectoryParent(fatd, dDirCluster, dParentDirCluster)) != 0) { + M_DEBUG("E: could not update \"..\" entry! %d\n", ret); + return ret; + } + } + + //Wipe the original entry. + //Fill fatd with a list of the original directory entry records, which can be deleted. + sDirCluster = fatdir->parentDirCluster; + ret = fat_fillDirentryInfo(fatd, fatdir->name, sname, -1, &sDirCluster, &sfnSector, &sfnOffset); + if (ret != 0) { + M_DEBUG("E: direntry not found! %d\n", ret); + return -ENOENT; + } + + //now mark the original direntries as deleted + ret = fat_wipeDirEntries(fatd); + if (ret < 0) { + M_DEBUG("E: wipe direntries failed!\n"); + return ret; + } + + fatdir->parentDirCluster = dParentDirCluster; + strcpy(fatdir->name, lname); + + return 0; +} //ends fat_renameFile + +//--------------------------------------------------------------------------- +int fat_writeFile(fat_driver* fatd, fat_dir* fatDir, int* updateClusterIndices, unsigned int filePos, unsigned char* buffer, unsigned int size) +{ + int ret; + int i, j; + int chainSize; + int nextChain; + int startSector; + unsigned int bufSize; + int sectorSkip; + int clusterSkip; + int dataSkip; + + unsigned int bufferPos; + unsigned int fileCluster; + unsigned int clusterPos; + unsigned int endPosFile; + unsigned int endPosCluster; + unsigned int lastCluster; + + int clusterChainStart; + + //check wether we have enough clusters allocated + i = fatd->partBpb.clusterSize * fatd->partBpb.sectorSize; //the size (in bytes) of the one cluster + j = fatDir->size / i; + if (fatDir->size % i) { + j++; + } + if (j == 0) + j = 1; //the file have allways at least one cluster allocated + + endPosCluster = j * i; + endPosFile = filePos + size; + + *updateClusterIndices = 0; + + //allocate additional cluster(s) + if (endPosFile > endPosCluster) { + ret = endPosFile - endPosCluster; //additional space needed in bytes + j = ret / i; //additional space needed (given in number of clusters) + if (ret % i) { + j++; + } + lastCluster = fatDir->lastCluster; + M_DEBUG("I: writeFile: last cluster= %u \n", lastCluster); + + if (lastCluster == 0) + return -ENOSPC; // no more free clusters or data invalid + for (i = 0; i < j; i++) { + lastCluster = fat_getFreeCluster(fatd, lastCluster); + if (lastCluster == 0) + return -ENOSPC; // no more free clusters + } + fatDir->lastCluster = lastCluster; + *updateClusterIndices = j; + fat_invalidateLastChainResult(fatd); //prevent to misuse current (now deleted) fatd->cbuf + + M_DEBUG("I: writeFile: new clusters allocated = %u new lastCluster=%u \n", j, lastCluster); + } + M_DEBUG("I: write file: filePos=%d dataSize=%d \n", filePos, size); + + fat_getClusterAtFilePos(fatd, fatDir, filePos, &fileCluster, &clusterPos); + sectorSkip = (filePos - clusterPos) / fatd->partBpb.sectorSize; + clusterSkip = sectorSkip / fatd->partBpb.clusterSize; + sectorSkip %= fatd->partBpb.clusterSize; + dataSkip = filePos % fatd->partBpb.sectorSize; + bufferPos = 0; + + M_DEBUG("fileCluster = %u, clusterPos= %u clusterSkip=%u, sectorSkip=%u dataSkip=%u \n", + fileCluster, clusterPos, clusterSkip, sectorSkip, dataSkip); + + if (fileCluster < 2) { + return -EFAULT; + } + + bufSize = fatd->bd->sectorSize; + nextChain = 1; + clusterChainStart = 1; + + while (nextChain && size > 0) { + chainSize = fat_getClusterChain(fatd, fileCluster, fatd->cbuf, MAX_DIR_CLUSTER, clusterChainStart); + clusterChainStart = 0; + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + fileCluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + } else { //chain fits in the chain buffer completely - no next chain needed + nextChain = 0; + } + while (clusterSkip >= MAX_DIR_CLUSTER) { + chainSize = fat_getClusterChain(fatd, fileCluster, fatd->cbuf, MAX_DIR_CLUSTER, clusterChainStart); + clusterChainStart = 0; + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + fileCluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + } else { //chain fits in the chain buffer completely - no next chain needed + nextChain = 0; + } + clusterSkip -= MAX_DIR_CLUSTER; + } + + //process the cluster chain (fatd->cbuf) and skip leading clusters if needed + for (i = 0 + clusterSkip; i < chainSize && size > 0; i++) { + //read cluster and save cluster content + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[i]); + //process all sectors of the cluster (and skip leading sectors if needed) + for (j = 0 + sectorSkip; j < fatd->partBpb.clusterSize && size > 0; j++) { + unsigned char* sbuf = NULL; //sector buffer + + //compute exact size of transfered bytes + if (size < bufSize) { + bufSize = size + dataSkip; + } + if (bufSize > fatd->bd->sectorSize) { + bufSize = fatd->bd->sectorSize; + } + + ret = READ_SECTOR(fatd, startSector + j, sbuf); + if (ret < 0) { + M_DEBUG("Read sector failed ! sector=%u\n", startSector + j); + return bufferPos; //return number of bytes already written + } + + M_DEBUG("memcopy dst=%u, src=%u, size=%u bufSize=%u \n", dataSkip, bufferPos, bufSize - dataSkip, bufSize); + memcpy(sbuf + dataSkip, buffer + bufferPos, bufSize - dataSkip); + ret = WRITE_SECTOR(fatd, startSector + j); + if (ret < 0) { + M_DEBUG("Write sector failed ! sector=%u\n", startSector + j); + return bufferPos; //return number of bytes already written + } + + size -= (bufSize - dataSkip); + bufferPos += (bufSize - dataSkip); + dataSkip = 0; + bufSize = fatd->bd->sectorSize; + } + sectorSkip = 0; + } + clusterSkip = 0; + } + + return bufferPos; //return number of bytes already written +} + +//--------------------------------------------------------------------------- +int fat_flushSectors(fat_driver* fatd) +{ + FLUSH_SECTORS(fatd); + return (0); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/fs_driver.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/fs_driver.c new file mode 100644 index 0000000..94069d1 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/fs_driver.c @@ -0,0 +1,915 @@ +/* + * fat_driver.c - USB Mass storage driver for PS2 + * + * (C) 2004, Marek Olejnik (ole00@post.cz) + * (C) 2004 Hermes (support for sector sizes from 512 to 4096 bytes) + * (C) 2004 raipsu (fs_dopen, fs_dclose, fs_dread, fs_getstat implementation) + * + * FAT filesystem layer + * + * See the file LICENSE included with this distribution for licensing terms. + */ +//--------------------------------------------------------------------------- +#include +#include +#include + +#include +#include +#include +#include + +#include "common.h" +#include "fat.h" +#include "fat_driver.h" +#include "fat_write.h" +#include + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +#define FLUSH_SECTORS fat_flushSectors + +enum FS_FILE_FLAG { + FS_FILE_FLAG_FOLDER = 0, + FS_FILE_FLAG_FILE +}; + +struct fs_dirent { //Common structure for both directories and regular files. + //This flag is always 1 for a file, and always 0 for a folder (different typedef) + //Routines that handle both must test it, and then typecast the privdata pointer + //to the type that is appropriate for the given case. (see also fs_dir typedef) + short int file_flag; + short int sizeChange; //flag, used for regular files. Otherwise padding. + fat_dir fatdir; +}; + +typedef struct _fs_rec { + struct fs_dirent dirent; + short int sizeChange; //flag + unsigned int filePos; + int mode; //file open mode + unsigned int sfnSector; //short filename sector - write support + int sfnOffset; //short filename offset - write support +} fs_rec; + +typedef struct _fs_dir { + struct fs_dirent dirent; + int status; + fat_dir_list fatdlist; + fat_dir current_fatdir; +} fs_dir; + +#define MAX_FILES 16 +static fs_rec fsRec[MAX_FILES]; //file info record + +static void fillStat(iox_stat_t* stat, const fat_dir* fatdir) +{ + stat->mode = FIO_S_IROTH | FIO_S_IXOTH; + if (fatdir->attr & FAT_ATTR_DIRECTORY) { + stat->mode |= FIO_S_IFDIR; + } else { + stat->mode |= FIO_S_IFREG; + } + if (!(fatdir->attr & FAT_ATTR_READONLY)) { + stat->mode |= FIO_S_IWOTH; + } + + stat->size = fatdir->size; + + //set created Date: Day, Month, Year + stat->ctime[4] = fatdir->cdate[0]; + stat->ctime[5] = fatdir->cdate[1]; + stat->ctime[6] = fatdir->cdate[2]; + stat->ctime[7] = fatdir->cdate[3]; + + //set created Time: Hours, Minutes, Seconds + stat->ctime[3] = fatdir->ctime[0]; + stat->ctime[2] = fatdir->ctime[1]; + stat->ctime[1] = fatdir->ctime[2]; + + //set accessed Date: Day, Month, Year + stat->atime[4] = fatdir->adate[0]; + stat->atime[5] = fatdir->adate[1]; + stat->atime[6] = fatdir->adate[2]; + stat->atime[7] = fatdir->adate[3]; + + //set modified Date: Day, Month, Year + stat->mtime[4] = fatdir->mdate[0]; + stat->mtime[5] = fatdir->mdate[1]; + stat->mtime[6] = fatdir->mdate[2]; + stat->mtime[7] = fatdir->mdate[3]; + + //set modified Time: Hours, Minutes, Seconds + stat->mtime[3] = fatdir->mtime[0]; + stat->mtime[2] = fatdir->mtime[1]; + stat->mtime[1] = fatdir->mtime[2]; +} + +/*************************************************************************************/ +/* File IO functions */ +/*************************************************************************************/ + +//--------------------------------------------------------------------------- +static fs_rec* fs_findFreeFileSlot(void) +{ + int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < MAX_FILES; i++) { + if (fsRec[i].dirent.file_flag < 0) { + return &fsRec[i]; + break; + } + } + return NULL; +} + +//--------------------------------------------------------------------------- +static fs_rec* fs_findFileSlotByCluster(unsigned int startCluster) +{ + int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < MAX_FILES; i++) { + if (fsRec[i].dirent.file_flag >= 0 && fsRec[i].dirent.fatdir.startCluster == startCluster) { + return &fsRec[i]; + } + } + return NULL; +} + +//--------------------------------------------------------------------------- +static int _lock_sema_id = -1; + +//--------------------------------------------------------------------------- +static int _fs_init_lock(void) +{ + iop_sema_t sp; + + M_DEBUG("%s\n", __func__); + + sp.initial = 1; + sp.max = 1; + sp.option = 0; + sp.attr = 0; + if ((_lock_sema_id = CreateSema(&sp)) < 0) { + return (-1); + } + + return (0); +} + +//--------------------------------------------------------------------------- +static void _fs_lock(void) +{ + M_DEBUG("%s\n", __func__); + + WaitSema(_lock_sema_id); +} + +//--------------------------------------------------------------------------- +static void _fs_unlock(void) +{ + M_DEBUG("%s\n", __func__); + + SignalSema(_lock_sema_id); +} + +//--------------------------------------------------------------------------- +static void fs_reset(void) +{ + int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < MAX_FILES; i++) + fsRec[i].dirent.file_flag = -1; + + if (_lock_sema_id >= 0) + DeleteSema(_lock_sema_id); + + _fs_init_lock(); +} + +//--------------------------------------------------------------------------- +static int fs_inited = 0; + +//--------------------------------------------------------------------------- +static int fs_dummy(void) +{ + M_DEBUG("%s\n", __func__); + + return -5; +} + +//--------------------------------------------------------------------------- +static int fs_init(iop_device_t* driver) +{ + M_DEBUG("%s\n", __func__); + + if (!fs_inited) { + fs_reset(); + fs_inited = 1; + } + + return 1; +} + +//--------------------------------------------------------------------------- +static int fs_open(iop_file_t* fd, const char* name, int flags, int mode) +{ + fat_driver* fatd; + fs_rec *rec, *rec2; + int ret; + unsigned int cluster; + char escapeNotExist; + + M_DEBUG("%s: %s flags=%X mode=%X\n", __func__, name, flags, mode); + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + //check if the slot is free + rec = fs_findFreeFileSlot(); + if (rec == NULL) { + _fs_unlock(); + return -EMFILE; + } + + //find the file + cluster = 0; //allways start from root + M_DEBUG("Calling fat_getFileStartCluster from fs_open\n"); + ret = fat_getFileStartCluster(fatd, name, &cluster, &rec->dirent.fatdir); + if (ret < 0 && ret != -ENOENT) { + _fs_unlock(); + return ret; + } else { + //File exists. Check if the file is already open + rec2 = fs_findFileSlotByCluster(rec->dirent.fatdir.startCluster); + if (rec2 != NULL) { + if ((flags & O_WRONLY) || //current file is opened for write + (rec2->mode & O_WRONLY)) { //other file is opened for write + _fs_unlock(); + return -EACCES; + } + } + } + + if (flags & O_WRONLY) { //dlanor: corrected bad test condition + cluster = 0; //start from root + + escapeNotExist = 1; + if (flags & O_CREAT) { + M_DEBUG("FAT I: O_CREAT detected!\n"); + escapeNotExist = 0; + } + + rec->sfnSector = 0; + rec->sfnOffset = 0; + ret = fat_createFile(fatd, name, 0, escapeNotExist, &cluster, &rec->sfnSector, &rec->sfnOffset); + if (ret < 0) { + FLUSH_SECTORS(fatd); + _fs_unlock(); + return ret; + } + //the file already exist but flags is set to truncate + if (ret == EEXIST && (flags & O_TRUNC)) { + M_DEBUG("FAT I: O_TRUNC detected!\n"); + ret = fat_truncateFile(fatd, cluster, rec->sfnSector, rec->sfnOffset); + if (ret < 0) { + FLUSH_SECTORS(fatd); + M_DEBUG("FAT E: failed to truncate!\n"); + _fs_unlock(); + return ret; + } + } + + //find the file + cluster = 0; //allways start from root + M_DEBUG("Calling fat_getFileStartCluster from fs_open after file creation\n"); + ret = fat_getFileStartCluster(fatd, name, &cluster, &rec->dirent.fatdir); + } + + if (ret < 0) { //At this point, the file should be locatable without any errors. + _fs_unlock(); + return ret; + } + + if ((rec->dirent.fatdir.attr & FAT_ATTR_DIRECTORY) == FAT_ATTR_DIRECTORY) { + // Can't open a directory with open + _fs_unlock(); + return -EISDIR; + } + + rec->dirent.file_flag = FS_FILE_FLAG_FILE; + rec->mode = flags; + rec->filePos = 0; + rec->sizeChange = 0; + + if ((flags & O_APPEND) && (flags & O_WRONLY)) { + M_DEBUG("FAT I: O_APPEND detected!\n"); + rec->filePos = rec->dirent.fatdir.size; + } + + //store the slot to user parameters + fd->privdata = rec; + + _fs_unlock(); + return 1; +} + +//--------------------------------------------------------------------------- +static int fs_close(iop_file_t* fd) +{ + fat_driver* fatd; + fs_rec* rec = (fs_rec*)fd->privdata; + + M_DEBUG("%s\n", __func__); + + if (rec == NULL) + return -EBADF; + + _fs_lock(); + + if (rec->dirent.file_flag != FS_FILE_FLAG_FILE) { + _fs_unlock(); + return -EISDIR; + } + + rec->dirent.file_flag = -1; + fd->privdata = NULL; + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + if ((rec->mode & O_WRONLY)) { + //update direntry size and time + if (rec->sizeChange) { + fat_updateSfn(fatd, rec->dirent.fatdir.size, rec->sfnSector, rec->sfnOffset); + } + + FLUSH_SECTORS(fatd); + } + + _fs_unlock(); + return 0; +} + +//--------------------------------------------------------------------------- +static int fs_lseek(iop_file_t* fd, int offset, int whence) +{ + fat_driver* fatd; + fs_rec* rec = (fs_rec*)fd->privdata; + + M_DEBUG("%s\n", __func__); + + if (rec == NULL) + return -EBADF; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + if (rec->dirent.file_flag != FS_FILE_FLAG_FILE) { + _fs_unlock(); + return -EISDIR; + } + + switch (whence) { + case SEEK_SET: + rec->filePos = offset; + break; + case SEEK_CUR: + rec->filePos += offset; + break; + case SEEK_END: + rec->filePos = rec->dirent.fatdir.size + offset; + break; + default: + _fs_unlock(); + return -1; + } + if (rec->filePos < 0) { + rec->filePos = 0; + } + if (rec->filePos > rec->dirent.fatdir.size) { + rec->filePos = rec->dirent.fatdir.size; + } + + _fs_unlock(); + return rec->filePos; +} + +//--------------------------------------------------------------------------- +static int fs_write(iop_file_t* fd, void* buffer, int size) +{ + fat_driver* fatd; + fs_rec* rec = (fs_rec*)fd->privdata; + int result; + int updateClusterIndices = 0; + + M_DEBUG("%s\n", __func__); + + if (rec == NULL) + return -EBADF; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + if (rec->dirent.file_flag != FS_FILE_FLAG_FILE) { + _fs_unlock(); + return -EISDIR; + } + + if (!(rec->mode & O_WRONLY)) { + _fs_unlock(); + return -EACCES; + } + + if (size <= 0) { + _fs_unlock(); + return 0; + } + + result = fat_writeFile(fatd, &rec->dirent.fatdir, &updateClusterIndices, rec->filePos, (unsigned char*)buffer, size); + if (result > 0) { //write succesful + rec->filePos += result; + if (rec->filePos > rec->dirent.fatdir.size) { + rec->dirent.fatdir.size = rec->filePos; + rec->sizeChange = 1; + //if new clusters allocated - then update file cluster indices + if (updateClusterIndices) { + fat_setFatDirChain(fatd, &rec->dirent.fatdir); + } + } + } + + _fs_unlock(); + return result; +} + +//--------------------------------------------------------------------------- +static int fs_read(iop_file_t* fd, void* buffer, int size) +{ + fat_driver* fatd; + fs_rec* rec = (fs_rec*)fd->privdata; + int result; + + M_DEBUG("%s\n", __func__); + + if (rec == NULL) + return -EBADF; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + if (rec->dirent.file_flag != FS_FILE_FLAG_FILE) { + _fs_unlock(); + return -EISDIR; + } + + if (!(rec->mode & O_RDONLY)) { + _fs_unlock(); + return -EACCES; + } + + if (size <= 0) { + _fs_unlock(); + return 0; + } + + if ((rec->filePos + size) > rec->dirent.fatdir.size) { + size = rec->dirent.fatdir.size - rec->filePos; + } + + result = fat_readFile(fatd, &rec->dirent.fatdir, rec->filePos, (unsigned char*)buffer, size); + if (result > 0) { //read succesful + rec->filePos += result; + } + + _fs_unlock(); + return result; +} + +//--------------------------------------------------------------------------- +static int fs_remove(iop_file_t* fd, const char* name) +{ + fat_driver* fatd; + fs_rec* rec; + int result; + unsigned int cluster; + fat_dir fatdir; + + M_DEBUG("%s\n", __func__); + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + result = -ENODEV; + _fs_unlock(); + return result; + } + + cluster = 0; //allways start from root + M_DEBUG("Calling fat_getFileStartCluster from fs_remove\n"); + result = fat_getFileStartCluster(fatd, name, &cluster, &fatdir); + if (result < 0) { + _fs_unlock(); + return result; + } + + rec = fs_findFileSlotByCluster(fatdir.startCluster); + + //file is opened - can't delete the file + if (rec != NULL) { + result = -EINVAL; + _fs_unlock(); + return result; + } + + result = fat_deleteFile(fatd, name, 0); + FLUSH_SECTORS(fatd); + + _fs_unlock(); + return result; +} + +//--------------------------------------------------------------------------- +static int fs_mkdir(iop_file_t* fd, const char* name, int mode) +{ + fat_driver* fatd; + int ret; + int sfnOffset; + unsigned int sfnSector; + unsigned int cluster; + + M_DEBUG("%s\n", __func__); + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + M_DEBUG("fs_mkdir: name=%s \n", name); + ret = fat_createFile(fatd, name, 1, 0, &cluster, &sfnSector, &sfnOffset); + + //directory of the same name already exist + if (ret == 2) { + ret = -EEXIST; + } + FLUSH_SECTORS(fatd); + + _fs_unlock(); + return ret; +} + +//--------------------------------------------------------------------------- +static int fs_rmdir(iop_file_t* fd, const char* name) +{ + fat_driver* fatd; + int ret; + + M_DEBUG("%s\n", __func__); + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + ret = fat_deleteFile(fatd, name, 1); + FLUSH_SECTORS(fatd); + _fs_unlock(); + return ret; +} + +//--------------------------------------------------------------------------- +static int fs_dopen(iop_file_t* fd, const char* name) +{ + fat_driver* fatd; + int is_root = 0; + fs_dir* rec; + + M_DEBUG("%s: unit %d name %s\n", __func__, fd->unit, name); + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + if (((name[0] == '/') && (name[1] == '\0')) + || ((name[0] == '/') && (name[1] == '.') && (name[2] == '\0'))) { + name = "/"; + is_root = 1; + } + + fd->privdata = malloc(sizeof(fs_dir)); + memset(fd->privdata, 0, sizeof(fs_dir)); //NB: also implies "file_flag = FS_FILE_FLAG_FOLDER;" + rec = (fs_dir*)fd->privdata; + + rec->status = fat_getFirstDirentry(fatd, name, &rec->fatdlist, &rec->dirent.fatdir, &rec->current_fatdir); + + // root directory may have no entries, nothing else may. + if (rec->status == 0 && !is_root) + rec->status = -EFAULT; + + if (rec->status < 0) + free(fd->privdata); + + _fs_unlock(); + return rec->status; +} + +//--------------------------------------------------------------------------- +static int fs_dclose(iop_file_t* fd) +{ + fs_dir* rec = (fs_dir*)fd->privdata; + + M_DEBUG("%s\n", __func__); + + if (fd->privdata == NULL) + return -EBADF; + + _fs_lock(); + M_DEBUG("fs_dclose called: unit %d\n", fd->unit); + if (rec->dirent.file_flag != FS_FILE_FLAG_FOLDER) { + _fs_unlock(); + return -ENOTDIR; + } + + free(fd->privdata); + fd->privdata = NULL; + _fs_unlock(); + return 0; +} + +//--------------------------------------------------------------------------- +static int fs_dread(iop_file_t* fd, iox_dirent_t* buffer) +{ + fat_driver* fatd; + int ret; + fs_dir* rec = (fs_dir*)fd->privdata; + + M_DEBUG("%s\n", __func__); + + if (rec == NULL) + return -EBADF; + + _fs_lock(); + + M_DEBUG("fs_dread called: unit %d\n", fd->unit); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + if (rec->dirent.file_flag != FS_FILE_FLAG_FOLDER) { + _fs_unlock(); + return -ENOTDIR; + } + + while (rec->status > 0 + && (rec->current_fatdir.attr & FAT_ATTR_VOLUME_LABEL + || ((rec->current_fatdir.attr & (FAT_ATTR_HIDDEN | FAT_ATTR_SYSTEM)) == (FAT_ATTR_HIDDEN | FAT_ATTR_SYSTEM)))) + rec->status = fat_getNextDirentry(fatd, &rec->fatdlist, &rec->current_fatdir); + + ret = rec->status; + if (rec->status >= 0) { + memset(buffer, 0, sizeof(iox_dirent_t)); + fillStat(&buffer->stat, &rec->current_fatdir); + strcpy(buffer->name, (const char*)rec->current_fatdir.name); + } + + if (rec->status > 0) + rec->status = fat_getNextDirentry(fatd, &rec->fatdlist, &rec->current_fatdir); + + _fs_unlock(); + return ret; +} + +//--------------------------------------------------------------------------- +static int fs_getstat(iop_file_t* fd, const char* name, iox_stat_t* stat) +{ + fat_driver* fatd; + int ret; + unsigned int cluster = 0; + fat_dir fatdir; + + M_DEBUG("%s: unit %d name %s\n", __func__, fd->unit, name); + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + M_DEBUG("Calling fat_getFileStartCluster from fs_getstat\n"); + ret = fat_getFileStartCluster(fatd, name, &cluster, &fatdir); + if (ret < 0) { + _fs_unlock(); + return ret; + } + + memset(stat, 0, sizeof(iox_stat_t)); + fillStat(stat, &fatdir); + + _fs_unlock(); + return 0; +} + +//--------------------------------------------------------------------------- +int fs_ioctl(iop_file_t* fd, int cmd, void* data) +{ + fat_driver* fatd; + struct fs_dirent* dirent = (struct fs_dirent*)fd->privdata; //Remember to re-cast this to the right structure (either fs_rec or fs_dir)! + int ret; + + M_DEBUG("%s\n", __func__); + + if (dirent == NULL) + return -EBADF; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + switch (cmd) { + case USBMASS_IOCTL_RENAME: + ret = fat_renameFile(fatd, &dirent->fatdir, data); //No need to re-cast since this inner structure is a common one. + FLUSH_SECTORS(fatd); + break; + case USBMASS_IOCTL_GET_CLUSTER: + ret = ((fs_rec*)fd->privdata)->dirent.fatdir.startCluster; + break; + case USBMASS_IOCTL_GET_LBA: + ret = fat_cluster2sector(&fatd->partBpb, ((fs_rec*)fd->privdata)->dirent.fatdir.startCluster); + break; + case USBMASS_IOCTL_GET_DRIVERNAME: + ret = *(int*)fatd->bd->name; + break; + case USBMASS_IOCTL_CHECK_CHAIN: + ret = fat_CheckChain(fatd, ((fs_rec*)fd->privdata)->dirent.fatdir.startCluster); + break; + default: + ret = fs_dummy(); + } + + _fs_unlock(); + return ret; +} + +int fs_rename(iop_file_t *fd, const char *path, const char *newpath) +{ + fat_dir fatdir; + fat_driver *fatd; + fs_rec *rec = NULL; + unsigned int cluster; + struct fs_dirent *dirent = (struct fs_dirent *)fd->privdata; + int ret; + + if (dirent == NULL) + return -EBADF; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + //find the file + cluster = 0; //allways start from root + M_DEBUG("Calling fat_getFileStartCluster from fs_rename\n"); + ret = fat_getFileStartCluster(fatd, path, &cluster, &fatdir); + if (ret < 0 && ret != -ENOENT) { + _fs_unlock(); + return ret; + } else { + //File exists. Check if the file is already open + rec = fs_findFileSlotByCluster(fatdir.startCluster); + if (rec != NULL) { + _fs_unlock(); + return -EACCES; + } + } + + ret = fat_renameFile(fatd, &fatdir, newpath); + FLUSH_SECTORS(fatd); + + _fs_unlock(); + return ret; +} + +static int fs_devctl(iop_file_t *fd, const char *name, int cmd, void *arg, unsigned int arglen, void *buf, unsigned int buflen) +{ + int ret; + + _fs_lock(); + + switch(cmd) + { + case USBMASS_DEVCTL_STOP_UNIT: + ret = fat_stopUnit(fd->unit); + break; + case USBMASS_DEVCTL_STOP_ALL: + fat_stopAll(); + ret = 0; + break; + default: + ret = -ENXIO; + } + + _fs_unlock(); + + return ret; +} + +static iop_device_ops_t fs_functarray = { + &fs_init, + (void*)&fs_dummy, + (void*)&fs_dummy, + &fs_open, + &fs_close, + &fs_read, + &fs_write, + &fs_lseek, + &fs_ioctl, + &fs_remove, + &fs_mkdir, + &fs_rmdir, + &fs_dopen, + &fs_dclose, + &fs_dread, + &fs_getstat, + (void*)&fs_dummy, + &fs_rename, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, + &fs_devctl, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, +}; +static iop_device_t fs_driver = { + "mass", + IOP_DT_FS | IOP_DT_FSEXT, + 2, + "VFAT driver", + &fs_functarray +}; + +/* init file system driver */ +int InitFS(void) +{ + M_DEBUG("%s\n", __func__); + + DelDrv("mass"); + return (AddDrv(&fs_driver) == 0 ? 0 : -1); +} + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/imports.lst new file mode 100644 index 0000000..ecbcd2c --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/imports.lst @@ -0,0 +1,47 @@ +bdm_IMPORTS_start +I_bdm_connect_fs +I_bdm_disconnect_fs +bdm_IMPORTS_end + +cdvdman_IMPORTS_start +I_sceCdReadClock +cdvdman_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +ioman_IMPORTS_start +I_AddDrv +I_DelDrv +ioman_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_toupper +I_memset +I_memcmp +I_memcpy +I_strlen +I_strcpy +I_strncpy +I_strtol +I_strrchr +I_sprintf +sysclib_IMPORTS_end + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +sysmem_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_SignalSema +I_WaitSema +I_DeleteSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/common.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/common.h new file mode 100644 index 0000000..4c28d19 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/common.h @@ -0,0 +1,24 @@ +#ifndef _USBHD_COMMON_H +#define _USBHD_COMMON_H + +#ifdef WIN32 +#define USBHD_INLINE +typedef unsigned char u8; +#else +#define USBHD_INLINE inline +void *malloc(int size); +void free(void *ptr); +#endif + +//--------------------------------------------------------------------------- +#define getUI32(buf) ((unsigned int)(((u8 *)(buf))[0] + \ + (((u8 *)(buf))[1] << 8) + \ + (((u8 *)(buf))[2] << 16) + \ + (((u8 *)(buf))[3] << 24))) +#define getUI32_2(buf1, buf2) ((unsigned int)(((u8 *)(buf1))[0] + \ + (((u8 *)(buf1))[1] << 8) + \ + (((u8 *)(buf2))[0] << 16) + \ + (((u8 *)(buf2))[1] << 24))) +#define getUI16(buf) ((unsigned int)(((u8 *)(buf))[0] + (((u8 *)(buf))[1] << 8))) + +#endif // _USBHD_COMMON_H diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/fat.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/fat.h new file mode 100644 index 0000000..4040026 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/fat.h @@ -0,0 +1,156 @@ +/* + * fat.h - USB Mass storage driver for PS2 + * + * (C) 2004, Marek Olejnik (ole00@post.cz) + * + * FAT helper structures + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/* + FAT References: http://www.igd.fhg.de/~aschaefe/fips/distrib/techinfo.txt + : http://home.freeuk.net/foxy2k/disk/disk1.htm +*/ + +#ifndef _FAT_H +#define _FAT_H + +#include "fat_driver.h" + +#define FAT12 0x0C +#define FAT16 0x10 +#define FAT32 0x20 + +#define FAT_MAX_PATH 260 + +/* bios parameter block - bpb - fat12, fat16 */ +typedef struct _fat_raw_bpb { + unsigned char jump[3]; //jump instruction ('eb xx 90' or 'e9 xx xx') + unsigned char oem[8]; //OEM name and version - e.g. MSDOS5.0 + unsigned char sectorSize[2]; //bytes per sector - should be 512 + unsigned char clusterSize; //sectors per cluster - power of two + unsigned char resSectors[2]; //reserved sectors - typically 1 (boot sector) + unsigned char fatCount; //number of FATs - must be 2 + unsigned char rootSize[2]; //number of rootdirectory entries - typically 512 + unsigned char sectorCountO[2]; //number of sectors (short) - 0, if BIGDOS partition + unsigned char mediaDesc; //media descriptor - typically f8h + unsigned char fatSize[2]; //sectors per FAT - varies + unsigned char trackSize[2]; //sectors per track + unsigned char headCount[2]; //number of heads + unsigned char hiddenCountL[2]; //number of hidden sectors (low) + + unsigned char hiddenCountH[2]; //number of hidden sectors (high) + unsigned char sectorCount[4]; //number of sectors + + /* extended BPB since DOS 4.0 */ + unsigned char driveNumber; //physical drive number - 80h or 81h + unsigned char reserved; //Current head (not used for this but WinNT stores two flags here). + unsigned char signature; //Signature (must be 28h or 29h to be recognised by NT). + unsigned char serialNumber[4]; //The serial number, the serial number is stored in reverse + //order and is the hex representation of the bytes stored here + unsigned char volumeLabel[11]; //Volume label + unsigned char fatId[8]; //File system ID. "FAT12", "FAT16" or "FAT " +} fat_raw_bpb; + +/* bios parameter block - bpb - fat32 */ +typedef struct _fat32_raw_bpb { + unsigned char jump[3]; //jump instruction ('eb xx 90' or 'e9 xx xx') + unsigned char oem[8]; //OEM name and version - e.g. MSDOS5.0 + unsigned char sectorSize[2]; //bytes per sector - should be 512 + unsigned char clusterSize; //sectors per cluster - power of two + unsigned char resSectors[2]; //reserved sectors - typically 1 (boot sector) + unsigned char fatCount; //number of FATs - must be 2 + unsigned char rootSize[2]; //number of rootdirectory entries - typically 512 + unsigned char sectorCountO[2]; //number of sectors (short) - 0, if BIGDOS partition + unsigned char mediaDesc; //media descriptor - typically f8h + unsigned char fatSize[2]; //sectors per FAT - varies + unsigned char trackSize[2]; //sectors per track + unsigned char headCount[2]; //number of heads + unsigned char hiddenCountL[2]; //number of hidden sectors (low) + + unsigned char hiddenCountH[2]; //number of hidden sectors (high) + unsigned char sectorCount[4]; //number of sectors + + /* fat32 specific */ + unsigned char fatSize32[4]; //FAT32 sectors per FAT + unsigned char fatStatus[2]; //If bit 7 is clear then all FAT's are updated other wise bits 0-3 + //give the current active FAT, all other bits are reserved. + unsigned char revision[2]; //High byte is major revision number, low byte is minor revision number, currently both are 0 + unsigned char rootDirCluster[4]; //Root directory starting cluster + unsigned char fsInfoSector[2]; //File system information sector. + unsigned char bootSectorCopy[2]; //If non-zero this gives the sector which holds a copy of the boot record, usually 6 + unsigned char reserved1[12]; //Reserved, set to 0. + unsigned char pdn; //Physical drive number (BIOS system ie 80h is first HDD, 00h is first FDD) + unsigned char reserved2; //Reserved + unsigned char signature; //Signature (must be 28h or 29h to be recognised by NT) + unsigned char serialNumber[4]; //The serial number, the serial number is stored in reverse + //order and is the hex representation of the bytes stored here + unsigned char volumeLabel[11]; //Volume label + unsigned char fatId[8]; //File system ID. "FAT12", "FAT16" or "FAT " + unsigned char machineCode[420]; //Machine code + unsigned char bootSignature[2]; //Boot Signature AA55h. +} fat32_raw_bpb; + +/* directory entry of the short file name */ +typedef struct _fat_direntry_sfn { + unsigned char name[8]; //Filename padded with spaces if required. + unsigned char ext[3]; //Filename extension padded with spaces if required. + unsigned char attr; //File Attribute Byte. + + unsigned char reservedNT; //Reserved for use by Windows NT. + unsigned char seconds; //Tenths of a second at time of file creation, 0-199 is valid. + unsigned char timeCreate[2]; //Time when file was created. + unsigned char dateCreate[2]; //Date when file was created. + unsigned char dateAccess[2]; //Date when file was last accessed. + unsigned char clusterH[2]; //High word of cluster number (EA index for FAT12 and FAT16). + + unsigned char timeWrite[2]; //Time of last write to file (last modified or when created). + unsigned char dateWrite[2]; //Date of last write to file (last modified or when created). + unsigned char clusterL[2]; //Starting cluster (Low word). + unsigned char size[4]; //File size (set to zero if a directory). +} fat_direntry_sfn; + +/* directory entry of the long file name + + Each LFN directory entry holds 13 characters of the complete LFN using 16-bit Unicode characters. +*/ +typedef struct _fat_direntry_lfn { + unsigned char entrySeq; //Bits 0-5 give the LFN part number, bit 6 is set if this is the last entry for the file. + unsigned char name1[10]; //1st 5 letters of LFN entry. + unsigned char rshv; //?? 0Fh (RSHV attributes set) + + unsigned char reserved1; //Reserved set to 0. + unsigned char checksum; //Checksum generated from SFN. + unsigned char name2[12]; //Next 6 letters of LFN entry. + + unsigned char reserved2[2]; //Reserved set to 0. + unsigned char name3[4]; //Last 2 letters of LFN entry. +} fat_direntry_lfn; + +typedef union _fat_direntry { + fat_direntry_sfn sfn; + fat_direntry_lfn lfn; +} fat_direntry; + +typedef struct _fat_direntry_summary { + unsigned char attr; //Attributes (bits:5-Archive 4-Directory 3-Volume Label 2-System 1-Hidden 0-Read Only) + char name[FAT_MAX_NAME]; //Long name (zero terminated) + char sname[13]; //Short name (zero terminated) + unsigned int size; //file size, 0 for directory + unsigned int cluster; //file start cluster +} fat_direntry_summary; + +//--------------------------------------------------------------------------- +static USBHD_INLINE unsigned int fat_cluster2sector(fat_bpb* partBpb, unsigned int cluster) +{ + return partBpb->dataStart + (partBpb->clusterSize * (cluster - 2)); +} + +unsigned int fat_getClusterRecord12(unsigned char* buf, int type); +int fat_getDirentry(unsigned char fatType, fat_direntry* dir_entry, fat_direntry_summary* dir); +int fat_getDirentrySectorData(fat_driver* fatd, unsigned int* startCluster, unsigned int* startSector, unsigned int* dirSector); +void fat_invalidateLastChainResult(fat_driver* fatd); +void fat_getClusterAtFilePos(fat_driver* fatd, fat_dir* fatDir, unsigned int filePos, unsigned int* cluster, unsigned int* clusterPos); + +#endif /* _FAT_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/fat_driver.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/fat_driver.h new file mode 100644 index 0000000..d931347 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/fat_driver.h @@ -0,0 +1,111 @@ +#ifndef _FAT_DRIVER_H +#define _FAT_DRIVER_H + +#include "scache.h" +#include + +#define DIR_CHAIN_SIZE 32 + +#define FAT_MAX_NAME 256 + +//attributes (bits:5-Archive 4-Directory 3-Volume Label 2-System 1-Hidden 0-Read Only) +#define FAT_ATTR_READONLY 0x01 +#define FAT_ATTR_HIDDEN 0x02 +#define FAT_ATTR_SYSTEM 0x04 +#define FAT_ATTR_VOLUME_LABEL 0x08 +#define FAT_ATTR_DIRECTORY 0x10 +#define FAT_ATTR_ARCHIVE 0x20 + +typedef struct _fat_dir_list { + unsigned int direntryCluster; //the directory cluster requested by getFirstDirentry + int direntryIndex; //index of the directory children +} fat_dir_list; + +typedef struct _fat_dir_chain_record { + unsigned int cluster; + unsigned int index; +} fat_dir_chain_record; + +typedef struct _fat_dir { + unsigned char attr; //attributes (bits:5-Archive 4-Directory 3-Volume Label 2-System 1-Hidden 0-Read Only) + char name[FAT_MAX_NAME]; + unsigned char cdate[4]; //D:M:Yl:Yh + unsigned char ctime[3]; //H:M:S + unsigned char adate[4]; //D:M:Yl:Yh + unsigned char atime[3]; //H:M:S + unsigned char mdate[4]; //D:M:Yl:Yh + unsigned char mtime[3]; //H:M:S + unsigned int size; //file size, 0 for directory + unsigned int parentDirCluster; //The cluster number of the parent directory. + unsigned int startCluster; + //Stuff here are used for caching and might not be filled. + unsigned int lastCluster; + fat_dir_chain_record chain[DIR_CHAIN_SIZE]; //cluser/offset cache - for seeking purpose +} fat_dir; + +typedef struct _fat_bpb { + unsigned int sectorSize; //bytes per sector - should be 512 + unsigned char clusterSize; //sectors per cluster - power of two + unsigned int resSectors; //reserved sectors - typically 1 (boot sector) + unsigned char fatCount; //number of FATs - must be 2 + unsigned int rootSize; //number of rootdirectory entries - typically 512 + unsigned int fatSize; //sectors per FAT - varies + unsigned int trackSize; //sectors per track + unsigned int headCount; //number of heads + unsigned int sectorCount; //number of sectors + unsigned int partStart; //sector where partition starts (boot sector) + unsigned int rootDirStart; //sector where root directory starts + unsigned int rootDirCluster; //fat32 - cluster of the root directory + unsigned int activeFat; //fat32 - current active fat number + unsigned char fatType; //12-FAT16, 16-FAT16, 32-FAT32 + unsigned char fatId[9]; //File system ID. "FAT12", "FAT16" or "FAT " - for debug only + unsigned int dataStart; //sector where data starts +} fat_bpb; + +typedef struct _fat_driver { + struct block_device* bd; + cache_set* cache; + fat_bpb partBpb; //partition bios parameter block + + // modified by Hermes +#define MAX_DIR_CLUSTER 512 + unsigned int cbuf[MAX_DIR_CLUSTER]; //cluster index buffer // 2048 by Hermes + + unsigned int lastChainCluster; + int lastChainResult; + +/* enough for long filename of length 260 characters (20*13) and one short filename */ +#define MAX_DE_STACK 21 + unsigned int deSec[MAX_DE_STACK]; //direntry sector + int deOfs[MAX_DE_STACK]; //direntry offset + int deIdx; //direntry index + +#define SEQ_MASK_SIZE 2048 //Allow 2K files per directory + u8 seq_mask[SEQ_MASK_SIZE / 8]; //bitmask for consumed seq numbers +#define DIR_MASK_SIZE 2048 * 11 //Allow 2K maxed fullnames per directory + u8 dir_used_mask[DIR_MASK_SIZE / 8]; //bitmask for used directory entries + +#define MAX_CLUSTER_STACK 128 + unsigned int clStack[MAX_CLUSTER_STACK]; //cluster allocation stack + int clStackIndex; + unsigned int clStackLast; // last free cluster of the fat table +} fat_driver; + +int strEqual(const char* s1, const char* s2); + +int fat_mount(struct block_device* bd); +void fat_forceUnmount(struct block_device* bd); +void fat_setFatDirChain(fat_driver* fatd, fat_dir* fatDir); +int fat_readFile(fat_driver* fatd, fat_dir* fatDir, unsigned int filePos, unsigned char* buffer, unsigned int size); +int fat_getFirstDirentry(fat_driver* fatd, const char* dirName, fat_dir_list* fatdlist, fat_dir* fatDir_host, fat_dir* fatDir); +int fat_getNextDirentry(fat_driver* fatd, fat_dir_list* fatdlist, fat_dir* fatDir); + +fat_driver* fat_getData(int device); +int fat_getFileStartCluster(fat_driver* fatd, const char* fname, unsigned int* startCluster, fat_dir* fatDir); +int fat_getClusterChain(fat_driver* fatd, unsigned int cluster, unsigned int* buf, unsigned int bufSize, int startFlag); +int fat_CheckChain(fat_driver* fatd, unsigned int cluster); + +int fat_stopUnit(int device); +void fat_stopAll(void); + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/fat_write.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/fat_write.h new file mode 100644 index 0000000..e3bf111 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/fat_write.h @@ -0,0 +1,14 @@ +#ifndef _FAT_WRITE_H +#define _FAT_WRITE_H 1 + +int fat_createFile(fat_driver* fatd, const char* fname, char directory, char escapeNotExist, unsigned int* cluster, unsigned int* sfnSector, int* sfnOffset); +int fat_deleteFile(fat_driver* fatd, const char* fname, char directory); +int fat_truncateFile(fat_driver* fatd, unsigned int cluster, unsigned int sfnSector, int sfnOffset); +int fat_renameFile(fat_driver* fatd, fat_dir* fatdir, const char* fname); +int fat_writeFile(fat_driver* fatd, fat_dir* fatDir, int* updateClusterIndices, unsigned int filePos, unsigned char* buffer, int size); +int fat_updateSfn(fat_driver* fatd, int size, unsigned int sfnSector, int sfnOffset); + +int fat_allocSector(fat_driver* fatd, unsigned int sector, unsigned char** buf); +int fat_writeSector(fat_driver* fatd, unsigned int sector); +int fat_flushSectors(fat_driver* fatd); +#endif /* _FAT_WRITE_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/module_debug.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/module_debug.h new file mode 100644 index 0000000..365b913 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/module_debug.h @@ -0,0 +1,18 @@ +#ifndef _MODULE_DEBUG_H +#define _MODULE_DEBUG_H + +//#define MINI_DRIVER + +#ifndef MINI_DRIVER +#define M_PRINTF(format, args...) printf("VFAT: " format, ##args) +#else +#define M_PRINTF(format, args...) +#endif + +#ifdef DEBUG +#define M_DEBUG M_PRINTF +#else +#define M_DEBUG(format, args...) +#endif + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/scache.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/scache.h new file mode 100644 index 0000000..a4326cd --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/include/scache.h @@ -0,0 +1,40 @@ +#ifndef _SCACHE_H +#define _SCACHE_H + +#include + +//number of cache slots (1 slot = block) +#define CACHE_SIZE 32 + +typedef struct _cache_record { + unsigned int sector; + int tax; + char writeDirty; +} cache_record; + +typedef struct _cache_set { + struct block_device* bd; + unsigned int sectorSize; + unsigned int indexLimit; + unsigned char* sectorBuf; // = NULL; //sector content - the cache buffer + cache_record rec[CACHE_SIZE]; //cache info record + +#ifdef SCACHE_RECORD_STATS + //statistical information + unsigned int cacheAccess; + unsigned int cacheHits; +#endif + unsigned int writeFlag; +} cache_set; + +cache_set* scache_init(struct block_device* bd); +void scache_close(cache_set* cache); +void scache_kill(cache_set* cache); //dlanor: added for disconnection events (flush impossible) +//int scache_allocSector(cache_set* cache, unsigned int sector, void** buf); +int scache_readSector(cache_set* cache, unsigned int sector, void** buf); +int scache_writeSector(cache_set* cache, unsigned int sector); +int scache_flushSectors(cache_set* cache); + +void scache_getStat(cache_set* cache, unsigned int* access, unsigned int* hits); + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/irx_imports.h new file mode 100644 index 0000000..61af16d --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/irx_imports.h @@ -0,0 +1,28 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include +#include +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/main.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/main.c new file mode 100644 index 0000000..aba38bb --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/main.c @@ -0,0 +1,70 @@ +#include +#include +#include +#include +#include +#include + +#include "fat_driver.h" + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +#define MAJOR_VER 1 +#define MINOR_VER 1 + +IRX_ID("bdmvfat", MAJOR_VER, MINOR_VER); + +extern int InitFAT(void); +extern int InitFS(void); + +static struct file_system g_fs = { + .priv = NULL, + .name = "vfat", + .connect_bd = fat_mount, + .disconnect_bd = fat_forceUnmount, +}; + +int _start(int argc, char* argv[]) +{ + printf("BDM VFAT driver (FAT12/16/32) v%d.%d\n", MAJOR_VER, MINOR_VER); + + // initialize the FAT driver + if (InitFAT() != 0) { + M_DEBUG("Error initializing FAT driver!\n"); + return MODULE_NO_RESIDENT_END; + } + + // initialize the file system driver + if (InitFS() != 0) { + M_DEBUG("Error initializing FS driver!\n"); + return MODULE_NO_RESIDENT_END; + } + + // Connect to block device manager + bdm_connect_fs(&g_fs); + + // return resident + return MODULE_RESIDENT_END; +} + +void* malloc(int size) +{ + void* result; + int OldState; + + CpuSuspendIntr(&OldState); + result = AllocSysMemory(ALLOC_FIRST, size, NULL); + CpuResumeIntr(OldState); + + return result; +} + +void free(void* ptr) +{ + int OldState; + + CpuSuspendIntr(&OldState); + FreeSysMemory(ptr); + CpuResumeIntr(OldState); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/scache.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/scache.c new file mode 100644 index 0000000..dbf7002 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/bdmfs_vfat/src/scache.c @@ -0,0 +1,335 @@ +/* + * scache.c - USB Mass storage driver for PS2 + * + * (C) 2004, Marek Olejnik (ole00@post.cz) + * (C) 2004 Hermes (support for sector sizes from 512 to 4096 bytes) + * + * Sector cache + * + * See the file LICENSE included with this distribution for licensing terms. + */ +//--------------------------------------------------------------------------- +#include + +#ifdef WIN32 +#include +#include +#include +#include +#else +#include +#include +#endif + +//#define SCACHE_RECORD_STATS 1 + +#include "common.h" +#include "scache.h" + +//--------------------------------------------------------------------------- +#define READ_SECTOR(d, s, a, c) (d)->bd->read((d)->bd, s, a, c) +#define WRITE_SECTOR(d, s, a, c) (d)->bd->write((d)->bd, s, a, c) + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +#define BLOCK_SIZE (4 * 1024) + +//when the flushCounter reaches FLUSH_TRIGGER then flushSectors is called +//#define FLUSH_TRIGGER 16 + +//--------------------------------------------------------------------------- +static void initRecords(cache_set* cache) +{ + unsigned int i; + + for (i = 0; i < CACHE_SIZE; i++) { + cache->rec[i].sector = 0xFFFFFFF0; + cache->rec[i].tax = 0; + cache->rec[i].writeDirty = 0; + } + + cache->writeFlag = 0; +} + +//--------------------------------------------------------------------------- +/* search cache records for the sector number stored in cache + returns cache record (slot) number + */ +static int getSlot(cache_set* cache, unsigned int sector) +{ + int i; + + for (i = 0; i < CACHE_SIZE; i++) { + if (sector >= cache->rec[i].sector && sector < (cache->rec[i].sector + cache->indexLimit)) { + return i; + } + } + return -1; +} + +//--------------------------------------------------------------------------- +/* search cache records for the sector number stored in cache */ +static int getIndexRead(cache_set* cache, unsigned int sector) +{ + unsigned int i; + int index = -1; + + for (i = 0; i < CACHE_SIZE; i++) { + if (sector >= cache->rec[i].sector && sector < (cache->rec[i].sector + cache->indexLimit)) { + if (cache->rec[i].tax < 0) + cache->rec[i].tax = 0; + cache->rec[i].tax += 2; + index = i; + } + if (cache->rec[i].tax > 1) + cache->rec[i].tax--; //apply tax penalty + } + if (index < 0) + return index; + else + return ((index * cache->indexLimit) + (sector - cache->rec[index].sector)); +} + +//--------------------------------------------------------------------------- +/* select the best record where to store new sector */ +static int getIndexWrite(cache_set* cache, unsigned int sector) +{ + int ret; + int minTax = 0x0FFFFFFF; + unsigned int i, index = 0; + + for (i = 0; i < CACHE_SIZE; i++) { + if (cache->rec[i].tax < minTax) { + index = i; + minTax = cache->rec[i].tax; + } + } + + //this sector is dirty - we need to flush it first + if (cache->rec[index].writeDirty) { + M_DEBUG("scache: getIndexWrite: sector is dirty : %u index=%d \n", cache->rec[index].sector, index); + ret = WRITE_SECTOR(cache, cache->rec[index].sector, cache->sectorBuf + (index * BLOCK_SIZE), BLOCK_SIZE / cache->sectorSize); + if (ret < 0) { + M_PRINTF("scache: ERROR writing sector to disk! sector=%u\n", sector); + return ret; + } + + cache->rec[index].writeDirty = 0; + } + cache->rec[index].tax += 2; + cache->rec[index].sector = sector; + + return index * cache->indexLimit; +} + +//--------------------------------------------------------------------------- +/* + flush dirty sectors + */ +int scache_flushSectors(cache_set* cache) +{ + unsigned int i; + int counter = 0, ret; + + M_DEBUG("scache: flushSectors devId = %i \n", cache->bd->devNr); + + M_DEBUG("scache: flushSectors writeFlag=%d\n", cache->writeFlag); + //no write operation occured since last flush + if (cache->writeFlag == 0) { + return 0; + } + + for (i = 0; i < CACHE_SIZE; i++) { + if (cache->rec[i].writeDirty) { + M_DEBUG("scache: flushSectors dirty index=%d sector=%u \n", i, cache->rec[i].sector); + ret = WRITE_SECTOR(cache, cache->rec[i].sector, cache->sectorBuf + (i * BLOCK_SIZE), BLOCK_SIZE / cache->sectorSize); + if (ret < 0) { + M_PRINTF("scache: ERROR writing sector to disk! sector=%u\n", cache->rec[i].sector); + return ret; + } + + cache->rec[i].writeDirty = 0; + counter++; + } + } + cache->writeFlag = 0; + return counter; +} + +//--------------------------------------------------------------------------- +int scache_readSector(cache_set* cache, unsigned int sector, void** buf) +{ + int index; //index is given in single sectors not octal sectors + int ret; + unsigned int alignedSector; + + M_DEBUG("scache: readSector devId = %i %p sector = %u \n", cache->bd->devNr, cache, sector); + if (cache == NULL) { + M_PRINTF("scache: devId cache not created = %i \n", cache->bd->devNr); + return -1; + } + +#ifdef SCACHE_RECORD_STATS + cache->cacheAccess++; +#endif + index = getIndexRead(cache, sector); + M_DEBUG("scache: indexRead=%i \n", index); + if (index >= 0) { //sector found in cache +#ifdef SCACHE_RECORD_STATS + cache->cacheHits++; +#endif + *buf = cache->sectorBuf + (index * cache->sectorSize); + M_DEBUG("scache: hit and done reading sector \n"); + + return cache->sectorSize; + } + + //compute alignedSector - to prevent storage of duplicit sectors in slots + alignedSector = (sector / cache->indexLimit) * cache->indexLimit; + index = getIndexWrite(cache, alignedSector); + M_DEBUG("scache: indexWrite=%i slot=%d alignedSector=%u\n", index, index / cache->indexLimit, alignedSector); + ret = READ_SECTOR(cache, alignedSector, cache->sectorBuf + (index * cache->sectorSize), BLOCK_SIZE / cache->sectorSize); + + if (ret < 0) { + M_PRINTF("scache: ERROR reading sector from disk! sector=%u\n", alignedSector); + return ret; + } + *buf = cache->sectorBuf + (index * cache->sectorSize) + ((sector % cache->indexLimit) * cache->sectorSize); + M_DEBUG("scache: done reading physical sector \n"); + + //write precaution + //cache->flushCounter++; + //if (cache->flushCounter == FLUSH_TRIGGER) { + //scache_flushSectors(cache); + //} + + return cache->sectorSize; +} + +//--------------------------------------------------------------------------- +/* SP193: this function is dangerous if not used correctly. + As scache's blocks are aligned to the start of the disk, the clusters of the partition + must also be aligned to a multiple of the scache block size. + Otherwise, it is possible to cause the adjacent cluster to lose data, if the block spans across more than one cluster. +*/ +#if 0 +int scache_allocSector(cache_set* cache, unsigned int sector, void** buf) +{ + int index; //index is given in single sectors not octal sectors + //int ret; + unsigned int alignedSector; + + M_DEBUG("scache: allocSector devId = %i sector = %u \n", cache->bd->devNr, sector); + + index = getIndexRead(cache, sector); + M_DEBUG("scache: indexRead=%i \n", index); + if (index >= 0) { //sector found in cache + *buf = cache->sectorBuf + (index * cache->sectorSize); + M_DEBUG("scache: hit and done allocating sector \n"); + return cache->sectorSize; + } + + //compute alignedSector - to prevent storage of duplicit sectors in slots + alignedSector = (sector / cache->indexLimit) * cache->indexLimit; + index = getIndexWrite(cache, alignedSector); + M_DEBUG("scache: indexWrite=%i \n", index); + *buf = cache->sectorBuf + (index * cache->sectorSize) + ((sector % cache->indexLimit) * cache->sectorSize); + M_DEBUG("scache: done allocating sector\n"); + return cache->sectorSize; +} +#endif + +//--------------------------------------------------------------------------- +int scache_writeSector(cache_set* cache, unsigned int sector) +{ + int index; //index is given in single sectors not octal sectors + //int ret; + + M_DEBUG("scache: writeSector devId = %i sector = %u \n", cache->bd->devNr, sector); + + index = getSlot(cache, sector); + if (index < 0) { //sector not found in cache + M_PRINTF("scache: writeSector: ERROR! the sector is not allocated! \n"); + return -1; + } + M_DEBUG("scache: slotFound=%i \n", index); + + //prefere written sectors to stay in cache longer than read sectors + cache->rec[index].tax += 2; + + //set dirty status + cache->rec[index].writeDirty = 1; + cache->writeFlag++; + + M_DEBUG("scache: done soft writing sector \n"); + + //write precaution + //cache->flushCounter++; + //if (cache->flushCounter == FLUSH_TRIGGER) { + //scache_flushSectors(devId); + //} + + return cache->sectorSize; +} + +//--------------------------------------------------------------------------- +cache_set* scache_init(struct block_device* bd) +{ + cache_set* cache; + M_DEBUG("scache: init devId = %i sectorSize = %u \n", bd->devNr, bd->sectorSize); + + cache = malloc(sizeof(cache_set)); + if (cache == NULL) { + M_PRINTF("scache init! Sector cache: can't alloate cache!\n"); + return NULL; + } + + M_DEBUG("scache init!\n"); + cache->bd = bd; + + cache->sectorBuf = (unsigned char*)malloc(BLOCK_SIZE * CACHE_SIZE); + if (cache->sectorBuf == NULL) { + M_PRINTF("scache: can't alloate memory of size:%d \n", BLOCK_SIZE * CACHE_SIZE); + free(cache); + return NULL; + } + M_DEBUG("scache: allocated memory at:%p of size:%d \n", cache->sectorBuf, BLOCK_SIZE * CACHE_SIZE); + + //added by Hermes + cache->sectorSize = bd->sectorSize; + cache->indexLimit = BLOCK_SIZE / cache->sectorSize; //number of sectors per 1 cache slot +#ifdef SCACHE_RECORD_STATS + cache->cacheAccess = 0; + cache->cacheHits = 0; +#endif + initRecords(cache); + return cache; +} + +#ifdef SCACHE_RECORD_STATS +//--------------------------------------------------------------------------- +void scache_getStat(cache_set* cache, unsigned int* access, unsigned int* hits) +{ + *access = cache->cacheAccess; + *hits = cache->cacheHits; +} +#endif + +//--------------------------------------------------------------------------- +void scache_kill(cache_set* cache) //dlanor: added for disconnection events (flush impossible) +{ + M_DEBUG("scache: kill devId = %i \n", cache->bd->devNr); + if (cache->sectorBuf != NULL) { + free(cache->sectorBuf); + cache->sectorBuf = NULL; + } + free(cache); +} +//--------------------------------------------------------------------------- +void scache_close(cache_set* cache) +{ + M_DEBUG("scache: close devId = %i \n", cache->bd->devNr); + scache_flushSectors(cache); + scache_kill(cache); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/Makefile new file mode 100644 index 0000000..9e58bba --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/Makefile @@ -0,0 +1,14 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_OBJS = devfs.o exports.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/README b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/README new file mode 100644 index 0000000..e6c3533 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/README @@ -0,0 +1,70 @@ +PS2 Device Filing System for IOP v1.0 +Copyright (c) 2004 James Forshaw (TyRaNiD) +Licensed under the Academic Free License version 2.0. +-- + +This file describes the PS2 Device Filing System (devfs) for use on the IOP. + +What is it? +-- + +The module provided works with ioman/X to provide a consistent interface for +exporting device orientated files for access on the IOP or EE. It is analogous +to a *nix style /dev heirarchy where each device can be read or written to and +commands passed using the ioctl functions. + +Why? +-- + +The first question you will probably ask is, why with ioman/iomanX providing +similar functionality is there a need for something else. Well what devfs +provides (in no particular order) is: + +- Easy configuration for devices without going having to add a complete ioman +driver. +- Trivial listing of available devices accessible by the system. To list the +currently available devices you can use the standard dopen, dread, dclose +functions. Listing top level ioman devices is decidedly less trivial. +- Reduction in effort, a driver only has to provide at most 3 access functions +. You could provide none at all but that would be kind of pointless. +- ioman can only handle 16 top level devices, iomanX 32. It is theoretically +possible to require many more device nodes than this. By comparison devfs can +provide theoretically unlimited top level devices (up to limits of IOP ram) and +up to 16 sub devices in a standard build. +- All devices accessible under a common heirarchy. + +Of course there are counter reasons for devfs including, +- Replication in some part of ioman/X functionality +- You still need ioman/X for it to operate +- Might run out of ram before enough devices are in use to make it worthwhile. + +Usage +-- + +Well if you are still with me, how to use it. + +The devfs.irx should have been built along with the rest of ps2drv, to use it +just load the irx and then access the functions via the exported interface. + +A quick run down of how the file system is structured. + +The ioman fs is under the devfs: device. A device consists of a root node and +a number of sub devices. The root node itself is not represented in the fs +but any sub devices are. The name you provide when registering the devices +will be suffixed with the sub device number i.e. if you register the device +'test' and add sub device 0 then you will see a 'test0' file in the fs. + +The root device holds references to a read, write and ioctl handler. If one or +more are set to NULL then they will be ignored. Device seeking is done by devfs +itself, the current location being passed to the handler functions. + +A sub device can be assigned an extent (which is its size to the seek code). It +can also be assigned certain access rights such as read/write or exclusive mode +(where only one file can be opened on the device). + +For an example of use see the devfs sample. + +-- + +Thanks go to the various members of PS2 deving, especially those involved with +the creation of so much infrastructure such as ps2lib and ps2drv. diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/include/devfs.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/include/devfs.h new file mode 100644 index 0000000..31aef8b --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/include/devfs.h @@ -0,0 +1,164 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * DevFS header file + * @defgroup devfs devfs: PS2 Device Filing System + * @addtogroup devfs + * @{ + */ + +#ifndef __DEVFS_H__ +#define __DEVFS_H__ + +#include +#include + +/** Type to hold a handle to a device */ +typedef s32 HDEV; +/** Maximum number of sub devices per device */ +#define DEVFS_MAX_SUBDEVS 16 +/** Maximum size of a device name */ +#define DEVFS_MAX_DEVNAME_LENGTH 32 +/** Maximum length of a description string */ +#define DEVFS_MAX_DESC_LENGTH 256 + +/** Enumeration of sub device access modes */ +enum devfs_subdev_modes +{ + /** Indicates a sub device can only be opened by one application at a time */ + DEVFS_MODE_EX = (1 << 0), + /** Indicates a sub device can be opened for reading */ + DEVFS_MODE_W = (1 << 1), + /** Indicates a sub device can be opened for writing */ + DEVFS_MODE_R = (1 << 2), + /** Indicates a sub device can be opened for reading and writing */ + DEVFS_MODE_RW = (DEVFS_MODE_R | DEVFS_MODE_W) +}; + +/** Enumeration of device type. + * @note These are currently not used + */ +enum devfs_devtypes +{ + /** Indicates a device is character device */ + DEVFS_DEVTYPE_CHAR = 1, + /** Indicates a device is a block device */ + DEVFS_DEVTYPE_BLOCK = 2, + /** Indicates a device is a stream device (no seek) */ + DEVFS_DEVTYPE_STREAM = 3 +}; + +/** Specifies ioctl was called. No return value and the lengths are invalid */ +#define DEVFS_IOCTL_TYPE_1 1 +/** ioctl2 was called. Parameters should all be valid */ +#define DEVFS_IOCTL_TYPE_2 2 + +/** ioctl command to return the description associated with a device */ +#define DEVFS_IOCTL_GETDESC 0 + +/** A union to make it easy to access the 32bit elements of a 64bit integer */ +typedef union + +{ + /** Array of two 32bit values */ + u32 loc32[2]; + /** The 64bit integer */ + u64 loc64; +} devfs_loc_t; + +/** Structure passed to the application when an event occurs */ +typedef struct + +{ + /** The sub devices data pointer as set by DevFSAddSubDevice */ + void *data; + /** The sub device number */ + s32 subdev; + /** The open mode. + * @note This is actually the posix mode bit fields as passed to open + */ + u32 mode; + /** The current seek location */ + devfs_loc_t loc; +} devfs_info_t; + +/** Typedef of the read event handler */ +typedef s32 (*read_handler)(const devfs_info_t *dev, u8 *buf, s32 len); +/** Typedef of the write event handler */ +typedef s32 (*write_handler)(const devfs_info_t *dev, u8 *buf, s32 len); +/** Typedef of the ioctl handler */ +typedef s32 (*ioctl_handler)(const devfs_info_t *dev, int ioctl_type, int cmd, void *arg, + size_t arglen, void *buf, size_t buflen); + +/** Structure defining a device node for passing to DevFSAddDevice() */ +typedef struct +{ + /** Name of the device */ + char *name; + /** A textual description */ + char *desc; + /** The type of device, possible values in ::devfs_devtypes */ + s32 devtype; + /** The block size of the device. Not currently used */ + u32 blocksize; + /** Pointer to a read handler. Can be NULL */ + read_handler read; + /** Pointer to a write handler. Can be NULL */ + write_handler write; + /** Pointer to a ioctl handler. Can be NULL */ + ioctl_handler ioctl; +} devfs_node_t; + +/** Adds a new device to the filing system + * @param node: Pointer to a ::devfs_node_t structure + * @returns A device handle is returned if the device was added. + * On error INVALID_HDEV is returned + */ +HDEV DevFSAddDevice(const devfs_node_t *node); +/** Define to add DevFSAddDevice to the imports list */ + +/** Deletes an previously opened device. + * @param hDev: Handle to the device to delete + * @returns 0 if device deleted, -1 on error + */ +int DevFSDelDevice(HDEV hDev); + +/** Adds a sub device to a previously opened device + * @param hDev: Handle to an opened device + * @param subdev_no: The number of the subdevice. Can be 0 to DEVFS_MAX_SUBDEVS + * @param extent: A 64bit extent which reflects the size of the underlying device + * @param data: Pointer to some private data to associate with this sub device + * @returns 0 if sub device added, else -1 + */ +int DevFSAddSubDevice(HDEV hDev, u32 subdev_no, s32 mode, devfs_loc_t extent, void *data); + +/** Deletes a sub device. + * @param hDev: Handle to an opened device. + * @param subdev_no: The number of the subdevice to delete. + * @returns 0 if device deleted. -1 on error. + */ +int DevFSDelSubDevice(HDEV hDev, u32 subdev_no); + +/** Defines an invalid HDEV value */ +#define INVALID_HDEV -1 + +#define devfs_IMPORTS_start DECLARE_IMPORT_TABLE(devfs, 1, 1) +#define devfs_IMPORTS_end END_IMPORT_TABLE + +#define I_DevFSAddDevice DECLARE_IMPORT(4, DevFSAddDevice) +#define I_DevFSDelDevice DECLARE_IMPORT(5, DevFSDelDevice) +#define I_DevFSAddSubDevice DECLARE_IMPORT(6, DevFSAddSubDevice) +#define I_DevFSDelSubDevice DECLARE_IMPORT(7, DevFSDelSubDevice) + +#endif /* __DEVFS_H__ */ + +/** @} */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/devfs.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/devfs.c new file mode 100644 index 0000000..3a60840 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/devfs.c @@ -0,0 +1,1298 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * DevFS source file + */ + +#include "types.h" +#include "defs.h" +#include "irx.h" +#include "loadcore.h" +#include "thbase.h" +#include "thevent.h" +#include "thsemap.h" +#include "intrman.h" +#include "stdio.h" +#include "sysclib.h" +#include "devfs.h" +#include "sysmem.h" +#include "stdio.h" + +#ifdef USE_IOMAN +#include "ioman.h" +#else +#include "iomanX.h" +#endif + +#define MODNAME "devfs" +IRX_ID(MODNAME, 1, 1); + +#define M_PRINTF(format, args...) printf(MODNAME ": " format, ## args) + +#define BANNER "DEVFS %s\n" +#define VERSION "v0.1" +#define MAX_OPENFILES 32 +#define MAX_OPEN_DIRFILES 16 + +extern struct irx_export_table _exp_devfs; + +iop_device_t devfs_device; +iop_device_ops_t devfs_ops; +typedef int (*dummy_func)(void); + +typedef struct + +{ + void *data; + s32 valid; + u32 mode; + u32 open_refcount; + devfs_loc_t extent; + struct _ioman_data *open_files[MAX_OPENFILES]; +} subdev_t; + +typedef struct _devfs_device +{ + /** Pointers to the next device in the chain */ + struct _devfs_device *forw, *back; + HDEV hDev; + devfs_node_t node; + subdev_t subdevs[DEVFS_MAX_SUBDEVS]; + u32 subdev_count; + u32 open_refcount; +} devfs_device_t; + +typedef struct _ioman_data +{ + HDEV hDev; + /** Pointer to the main device, set to NULL if device closed */ + devfs_device_t *dev; + int subdev; + u32 mode; + devfs_loc_t loc; +} ioman_data_t; + +/** Pointer to the root device */ +devfs_device_t *root_device; +HDEV dev_count; + +typedef struct _directory_file + +{ + /** Should always be set to -1 */ + HDEV hDev; + /** The number of the file being listed */ + u32 devno; + /** If this directory file is in an opened state */ + u32 opened; +} directory_file_t; + +directory_file_t open_dirfiles[MAX_OPEN_DIRFILES]; + +/** Simple function to convert a number to a string + * @param subdev: The number to convert. + * @returns A constant string containing the number. Returns an + * empty string if not possible to convert. + */ +const char *devfs_subdev_to_str(int subdev) + +{ + static char name[4]; /* Supports up to 999 subdevices */ + int loop; + + if((subdev > 999) || (subdev < 0)) + { + name[0] = 0; + } + else + { + loop = 0; + name[loop++] = ((subdev / 100) % 10) + '0'; + name[loop++] = ((subdev / 10) % 10) + '0'; + name[loop++] = (subdev % 10) + '0'; + name[loop++] = 0; + } + + loop = 0; + if(name[0] == '0') loop = 1; + if((name[0] == '0') && (name[1] == '0')) loop = 2; + + return &name[loop]; +} + +/** Scans the device list and fills in the corresponding directory entry + * + * @param dirent: Pointer to a ::iox_dirent_t structure. + * @param devno: The sequential device number to read + * + * @returns Always 0 + */ + +int devfs_fill_dirent(iox_dirent_t *dirent, int devno) + +{ + devfs_device_t *dev_scan; + int curr_no = 0; + u32 subdev_loop; + + dev_scan = root_device; + + while(dev_scan != NULL) + { + if((curr_no + dev_scan->subdev_count) > devno) + { + for(subdev_loop = 0; subdev_loop < DEVFS_MAX_SUBDEVS; subdev_loop++) + { + if(dev_scan->subdevs[subdev_loop].valid) + { + if(curr_no == devno) + { + break; + } + curr_no++; + } + } + + if(subdev_loop < DEVFS_MAX_SUBDEVS) + { + memset(dirent, 0, sizeof(iox_dirent_t)); + dirent->stat.size = dev_scan->subdevs[subdev_loop].extent.loc32[0]; + dirent->stat.hisize = dev_scan->subdevs[subdev_loop].extent.loc32[1]; + dirent->stat.mode = FIO_S_IFREG; + if(dev_scan->subdevs[subdev_loop].mode & DEVFS_MODE_R) + { + dirent->stat.mode |= FIO_S_IRUSR; + } + if(dev_scan->subdevs[subdev_loop].mode & DEVFS_MODE_W) + { + dirent->stat.mode |= FIO_S_IWUSR; + } + dirent->name[0] = 0; + strcpy(dirent->name, dev_scan->node.name); + strcat(dirent->name, devfs_subdev_to_str(subdev_loop)); + + return strlen(dirent->name); + } + } + + curr_no += dev_scan->subdev_count; + + dev_scan = dev_scan->forw; + } + + return 0; +} + +/** Creates a new device based on the node data supplied + * + * @param node: Pointer to a ::devfs_node_t structure + * + * @returns A new device structure or NULL on error. + */ +devfs_device_t *devfs_create_device(const devfs_node_t *node) + +{ + devfs_device_t *dev; + + if((node == NULL) || (node->name == NULL)) + { + return NULL; + } + + dev = AllocSysMemory(ALLOC_FIRST, sizeof(devfs_device_t), NULL); + if(dev == NULL) + { + printf("create_device: Alloc Failed\n"); + return NULL; + } + + memset(dev, 0, sizeof(devfs_device_t)); + memcpy(&dev->node, node, sizeof(devfs_node_t)); + if(dev->node.name != NULL) + { + dev->node.name = AllocSysMemory(ALLOC_FIRST, strlen(node->name) + 1, NULL); + if(dev->node.name == NULL) + { + FreeSysMemory(dev); + return NULL; + } + memcpy(dev->node.name, node->name, strlen(node->name) + 1); + } + + if(dev->node.desc != NULL) + { + dev->node.desc = AllocSysMemory(ALLOC_FIRST, strlen(node->desc) + 1, NULL); + if(dev->node.name == NULL) + { + FreeSysMemory(dev->node.name); + FreeSysMemory(dev); + return NULL; + } + memcpy(dev->node.desc, node->desc, strlen(node->desc) + 1); + } + + return dev; +} + +/** Deletes a device + * @param dev: Pointer to a previously allocated device structure + * @returns Always 0 + */ + +int devfs_delete_device(devfs_device_t *dev) + +{ + if(dev != NULL) + { + if(dev->node.name) + { + FreeSysMemory(dev->node.name); + } + + if(dev->node.desc) + { + FreeSysMemory(dev->node.desc); + } + + FreeSysMemory(dev); + } + + return 0; +} + +/** Trys to find a device with a matching name. + * + * The name can be a full device name with subdev on the end, the function should + * still find the device. + * @param name: The name of the device to find + * @returns A pointer to the device, if not found returns NULL + */ +devfs_device_t *devfs_find_devicename(const char *name) + +{ + devfs_device_t *dev_scan; + + if(name == NULL) + { + return NULL; + } + + dev_scan = root_device; + + while(dev_scan != NULL) + { + /* Ensure name is at least less than or equal to the one we want to find */ + if(strlen(dev_scan->node.name) <= strlen(name)) + { + if(strncmp(dev_scan->node.name, name, strlen(dev_scan->node.name)) == 0) + { + return dev_scan; + } + } + dev_scan = dev_scan->forw; + } + + return NULL; +} + +/** Finds a device from its device handle. + * + * @param hDev: Handle to the device. + * @returns A pointer to the device, if not found returns NULL + */ +devfs_device_t *devfs_find_deviceid(HDEV hDev) + +{ + devfs_device_t *dev_scan; + + dev_scan = root_device; + + while(dev_scan != NULL) + { + if(dev_scan->hDev == hDev) + { + return dev_scan; + } + dev_scan = dev_scan->forw; + } + + return NULL; +} + +/** Dummy ioman handler + * @returns Always returns -1 + */ +int devfs_dummy(void) + +{ + printf("devfs_dummy\n"); + return -1; +} + +/** ioman init handler + * @returns Always returns 0 + */ +int devfs_init(iop_device_t *dev) + +{ + printf("devfs_init dev=%p\n", dev); + return 0; +} + +/** ioman deinit handler + * @returns Always returns 0 + */ +int devfs_deinit(iop_device_t *dev) + +{ + printf("devfs_deinit dev=%p\n", dev); + return 0; +} + +/** ioman open handler + * @oaram file: Pointer to the ioman file structure + * @param name: Name of file to open + * @param mode: Open file mode settings + * @returns 0 if success, -1 on error +*/ +#ifdef USE_IOMAN +int devfs_open(iop_file_t *file, const char *name, int mode) +#else +int devfs_open(iop_file_t *file, const char *name, int mode, int unused) +#endif +{ + devfs_device_t *dev; + int loop; + int fn_offset = 0; + + //printf("devfs_open file=%p name=%s mode=%d\n", file, name, mode); + if(name == NULL) + { + M_PRINTF("open: Name is NULL\n"); + return -1; + } + + if((name[0] == '\\') || (name[0] == '/')) + { + fn_offset = 1; + } + + dev = devfs_find_devicename(name + fn_offset); + + if(dev != NULL) + { + char *endp; + int subdev; + int name_len; + + name_len = strlen(dev->node.name); + + if(name_len == strlen(name)) /* If this is has not got a subnumber */ + { + M_PRINTF("open: No subdevice number in filename %s\n", name); + return -1; + } + + subdev = strtoul(&name[name_len + fn_offset], &endp, 10); + if(((subdev == 0) && (name[name_len + fn_offset] != '0')) + || (subdev >= DEVFS_MAX_SUBDEVS)) + /* Invalid number */ + { + M_PRINTF("open: Invalid subdev number %d\n", subdev); + return -1; + } + + if(*endp) + /* Extra charactes after filename */ + { + M_PRINTF("open: Invalid filename\n"); + return -1; + } + + if(!dev->subdevs[subdev].valid) + /* No subdev */ + { + M_PRINTF("open: No subdev registered\n"); + return -1; + } + + if((dev->subdevs[subdev].mode & DEVFS_MODE_EX) + && (dev->subdevs[subdev].open_refcount > 0)) + /* Already opened in exclusive mode */ + { + M_PRINTF("open: Exclusive subdevice already opened\n"); + return -1; + } + + if(dev->subdevs[subdev].open_refcount == MAX_OPENFILES) + { + M_PRINTF("open: Reached open file limit for sub device\n"); + } + + /* Tried to open read but not allowed */ + if(((mode & O_RDONLY) || ((mode & O_RDWR) == O_RDWR)) + && !(dev->subdevs[subdev].mode & DEVFS_MODE_R)) + { + M_PRINTF("open: Read mode requested but not permitted\n"); + return -1; + } + + if(((mode & O_WRONLY) || ((mode & O_RDWR) == O_RDWR)) + && !(dev->subdevs[subdev].mode & DEVFS_MODE_W)) + { + M_PRINTF("open: Write mode requested but not permitted\n"); + return -1; + } + + file->privdata = AllocSysMemory(ALLOC_FIRST, sizeof(ioman_data_t), NULL); + if(file->privdata == NULL) + { + M_PRINTF("open: Allocation failure\n"); + return -1; + } + + ((ioman_data_t *) file->privdata)->hDev = dev->hDev; + ((ioman_data_t *) file->privdata)->subdev = subdev; + ((ioman_data_t *) file->privdata)->loc.loc64 = 0; + ((ioman_data_t *) file->privdata)->dev = dev; + ((ioman_data_t *) file->privdata)->mode = mode; + + dev->subdevs[subdev].open_refcount++; + loop = 0; + while((loop < MAX_OPENFILES) && (dev->subdevs[subdev].open_files[loop])) + { + loop++; + } + if(loop == MAX_OPENFILES) + { + FreeSysMemory(file->privdata); + M_PRINTF("open: Inconsistency between number of open files and available slot\n"); + return -1; + } + + dev->subdevs[subdev].open_files[loop] = file->privdata; + dev->open_refcount++; + M_PRINTF("open: Opened device %s subdev %d\n", dev->node.name, subdev); + } + else + { + M_PRINTF("open: Couldn't find the device\n"); + return -1; + } + + return 0; +} + +/** ioman close handler + * + * @param file: Pointer to an ioman file structure + * @returns 0 on success, else -1 + */ +int devfs_close(iop_file_t *file) + +{ + devfs_device_t *dev; + ioman_data_t *data = (ioman_data_t *) file->privdata; + int loop; + + if((data) && (data->hDev != INVALID_HDEV)) /* Invalid HDEV is a dir listing */ + { + dev = data->dev; + + if(dev != NULL) + { + if(dev->subdevs[data->subdev].open_refcount > 0) + { + dev->subdevs[data->subdev].open_refcount--; + } + if(dev->open_refcount > 0) + { + dev->open_refcount--; + } + + loop = 0; + while((loop < MAX_OPENFILES) + && (dev->subdevs[data->subdev].open_files[loop] != data)) + { + loop++; + } + + if(loop != MAX_OPENFILES) + { + dev->subdevs[data->subdev].open_files[loop] = NULL; + } + else + { + M_PRINTF("close: Could not find opened file\n"); + } + + M_PRINTF("close: Closing device %s subdev %d\n", dev->node.name, data->subdev); + FreeSysMemory(data); + } + else + { + FreeSysMemory(data); + file->privdata = NULL; + return -1; + } + } + else + { + return -1; + } + + return 0; +} + +/** ioman ioctl handler + * @param file: Pointer to an ioman file structure + * @param cmd: ioctl command number + * @param args: Pointer to a buffer containing any arguments + * @returns >= 0 Defined by the type of command, -1 on error + */ +int devfs_ioctl(iop_file_t *file, int cmd, void *args) + +{ + devfs_device_t *dev; + ioman_data_t *data = (ioman_data_t *) file->privdata; + + if(cmd == DEVFS_IOCTL_GETDESC) + { + return -1; /* ioctl cannot support this call */ + } + + data = file->privdata; + if((data) && (data->hDev != INVALID_HDEV)) + { + dev = data->dev; + if(dev == NULL) /* Device has been closed from under us */ + { + /* Delete data to try and prevent a memory leak */ + FreeSysMemory(data); + file->privdata = NULL; + return -1; + } + + if(dev->node.ioctl != NULL) + { + devfs_info_t dev_info; + + dev_info.data = dev->subdevs[data->subdev].data; + dev_info.subdev = data->subdev; + dev_info.mode = data->mode; + dev_info.loc = data->loc; + return dev->node.ioctl(&dev_info, DEVFS_IOCTL_TYPE_1, cmd, args, 0, NULL, 0); + } + + } + + return -1; +} + +/** ioman ioctl2 handler + * @param file: Pointer to an ioman file structure + * @param cmd: ioctl command number + * @param args: Pointer a buffer containing command arguments + * @param arglen: Length of args buffer + * @param buf: Pointer to a return buffer + * @param buflen: Length of buf + * @returns >= 0 Depends on command, -1 on error + */ +int devfs_ioctl2(iop_file_t *file, int cmd, void *args, unsigned int arglen, void *buf, unsigned int buflen) + +{ + devfs_device_t *dev; + ioman_data_t *data = (ioman_data_t *) file->privdata; + + data = file->privdata; + if((data) && (data->hDev != INVALID_HDEV)) + { + dev = data->dev; + if(dev == NULL) /* Device has been closed from under us */ + { + /* Delete data to try and prevent a memory leak */ + FreeSysMemory(data); + file->privdata = NULL; + return -1; + } + + if((cmd == DEVFS_IOCTL_GETDESC) && (buf) && (buflen >= DEVFS_MAX_DESC_LENGTH)) + { + if(dev->node.desc) + { + strncpy(buf, dev->node.desc, buflen-1); + *((u8 *) (buf + buflen)) = 0; + return strlen(buf); + } + + return 0; + } + + if(dev->node.ioctl != NULL) + { + devfs_info_t dev_info; + + dev_info.data = dev->subdevs[data->subdev].data; + dev_info.subdev = data->subdev; + dev_info.mode = data->mode; + dev_info.loc = data->loc; + return dev->node.ioctl(&dev_info, DEVFS_IOCTL_TYPE_2, cmd, args, arglen, buf, buflen); + } + + } + + return -1; +} + +/** ioman read handler + * @param file: Pointer to an ioman file structure + * @param buf: Buffer to read data to + * @param len: Length of data to read + * @returns Length of data read. 0 on eof or file pointer out of range. -1 on error. + */ +int devfs_read(iop_file_t *file, void *buf, int len) + +{ + devfs_device_t *dev; + ioman_data_t *data = (ioman_data_t *) file->privdata; + + //printf("devfs_read file=%p buf=%p len=%d\n", file, buf, len); + + data = file->privdata; + if((data) && (data->hDev != INVALID_HDEV)) + { + dev = data->dev; + if(dev == NULL) /* Device has been closed from under us */ + { + /* Delete data to try and prevent a memory leak */ + FreeSysMemory(data); + file->privdata = NULL; + return -1; + } + + if((dev->node.read != NULL) + && (dev->subdevs[data->subdev].mode & DEVFS_MODE_R)) + { + devfs_info_t dev_info; + int bytes_read; + + dev_info.data = dev->subdevs[data->subdev].data; + dev_info.subdev = data->subdev; + dev_info.mode = data->mode; + dev_info.loc = data->loc; + bytes_read = dev->node.read(&dev_info, buf, len); + if(bytes_read > 0) + { + data->loc.loc64 += (u64) bytes_read; + } + return bytes_read; + } + } + + return -1; +} + +/** ioman write handler + * @param file: Pointer to an ioman file structure + * @param buf: Pointer to the buffer to write + * @param len: Length of data to write + * @returns Number of bytes written, 0 on eof or -1 on error + */ +int devfs_write(iop_file_t *file, void *buf, int len) + +{ + devfs_device_t *dev; + ioman_data_t *data = (ioman_data_t *) file->privdata; + + //printf("devfs_write file=%p buf=%p len=%d\n", file, buf, len); + data = file->privdata; + if((data) && (data->hDev != INVALID_HDEV)) + { + dev = data->dev; + if(dev == NULL) /* Device has been closed from under us */ + { + /* Delete data to try and prevent a memory leak */ + FreeSysMemory(data); + file->privdata = NULL; + return -1; + } + + if((dev->node.write != NULL) + && (dev->subdevs[data->subdev].mode & DEVFS_MODE_W)) + { + devfs_info_t dev_info; + int bytes_written; + + dev_info.data = dev->subdevs[data->subdev].data; + dev_info.subdev = data->subdev; + dev_info.mode = data->mode; + dev_info.loc = data->loc; + bytes_written = dev->node.write(&dev_info, buf, len); + if(bytes_written > 0) + { + data->loc.loc64 += (u64) bytes_written; + } + return bytes_written; + } + } + + return -1; +} + +/** ioman lseek handler + * @param file: Pointer to a ioman file structure + * @param loc: Location to seek to + * @param whence: Seek base. + * @returns location seeked to, -1 on error. + */ +int devfs_lseek(iop_file_t *file, long loc, int whence) +{ + devfs_device_t *dev; + ioman_data_t *data = (ioman_data_t *) file->privdata; + + //printf("devfs_lseek file=%p loc=%ld whence=%d\n", file, loc, whence); + data = file->privdata; + if((data) && (data->hDev != INVALID_HDEV)) + { + dev = data->dev; + if(dev == NULL) /* Device has been closed from under us */ + { + /* Delete data to try and prevent a memory leak */ + FreeSysMemory(data); + file->privdata = NULL; + return -1; + } + + switch(whence) + { + case SEEK_SET: if(loc > 0) + data->loc.loc64 = (u64) loc; + break; + case SEEK_CUR: if(loc > 0) + data->loc.loc64 += (u64) loc; + else if(((s64) -loc) < data->loc.loc64) + data->loc.loc64 += (s64) loc; + break; + case SEEK_END: if((loc > 0) + && (dev->subdevs[data->subdev].extent.loc64 >= (u64) loc)) + data->loc.loc64 = dev->subdevs[data->subdev].extent.loc64 - (u64) loc; + break; + default: return -1; + } + } + else + { + return -1; + } + + return data->loc.loc32[0]; +} + +/** ioman lseek64 handler + * @param file: Pointer to an ioman file structure + * @param loc: 64bit seek location + * @param whence: Seek base + */ +int devfs_lseek64(iop_file_t *file, long long loc, int whence) +{ + devfs_device_t *dev; + ioman_data_t *data = (ioman_data_t *) file->privdata; + + //printf("devfs_lseek64 file=%p loc= whence=%d\n", file, whence); + data = file->privdata; + if((data) && (data->hDev != INVALID_HDEV)) + { + dev = data->dev; + if(dev == NULL) /* Device has been closed from under us */ + { + /* Delete data to try and prevent a memory leak */ + FreeSysMemory(data); + file->privdata = NULL; + return -1; + } + + switch(whence) + { + case SEEK_SET: if(loc > 0) + data->loc.loc64 = (u64) loc; + break; + case SEEK_CUR: if(loc > 0) + data->loc.loc64 += (u64) loc; + else if(((s64) -loc) < data->loc.loc64) + data->loc.loc64 += (s64) loc; + break; + case SEEK_END: if((loc > 0) && (dev->subdevs[data->subdev].extent.loc64 >= (u64) loc)) + data->loc.loc64 = dev->subdevs[data->subdev].extent.loc64 - (u64) loc; + break; + default: return -1; + } + + } + else + { + return -1; + } + + return data->loc.loc32[0]; +} + +/** ioman dopen handler + * @param file: Pointer to an ioman file structure + * @param name: Name of directory to open + * @returns 0 if success, -1 on error + */ +int devfs_dopen(iop_file_t *file, const char *name) +{ + int dir_loop; + + if((name == NULL) && (name[0] != '\\') && (name[0] != '/')) + { + M_PRINTF("dopen: Not a valid directory name\n"); + return -1; + } + + //M_PRINTF("dopen: file=%p name=%s\n", file, name); + for(dir_loop = 0; dir_loop < MAX_OPEN_DIRFILES; dir_loop++) + { + if(!open_dirfiles[dir_loop].opened) + { + open_dirfiles[dir_loop].devno = 0; + open_dirfiles[dir_loop].hDev = INVALID_HDEV; + file->privdata = &open_dirfiles[dir_loop]; + return 0; + } + } + + return -1; +} + +/** ioman dclose handler + * @param file: Pointer to an ioman file structure + * @returns Always returns 0 + */ +int devfs_dclose(iop_file_t *file) +{ + directory_file_t *dir; + + //M_PRINTF("dclose: file=%p\n", file); + dir = (directory_file_t *) file->privdata; + + if((dir) && (dir->hDev == INVALID_HDEV)) + { + dir->opened = 0; + file->privdata = NULL; + } + + return 0; +} + +#ifdef USE_IOMAN +int devfs_dread(iop_file_t *file, fio_dirent_t *buf) +#else +int devfs_dread(iop_file_t *file, iox_dirent_t *buf) +#endif +{ + directory_file_t *dir; + int ret = 0; + + //M_PRINTF("dread: file=%p buf=%p\n", file, buf); + dir = (directory_file_t *) file->privdata; + if((dir) && (dir->hDev == INVALID_HDEV) && (buf)) + { + ret = devfs_fill_dirent(buf, dir->devno); + if(ret) + { + dir->devno++; + } + } + + return ret; +} + +/** ioman getstat handler + * @param file: Pointer to an ioman file structure + * @param name: Name of the file to stat + * @param stat: Buffer to receive the stat + * @returns 0 on success, -1 on error + */ +#ifdef USE_IOMAN +int devfs_getstat(iop_file_t *file, const char *name, fio_stat_t *stat) +#else +int devfs_getstat(iop_file_t *file, const char *name, iox_stat_t *stat) +#endif +{ + devfs_device_t *dev; + int fn_offset = 0; + + if(name == NULL) + { + return -1; + } + + if((name[0] == '\\') || (name[0] == '/')) + { + fn_offset = 1; + } + + if(stat == NULL) + { + return -1; + } + + dev = devfs_find_devicename(name + fn_offset); + + if(dev != NULL) + { + char *endp; + int subdev; + int name_len; + + name_len = strlen(dev->node.name); + + if(name_len == strlen(name)) /* If this is has not got a subnumber */ + { + M_PRINTF("getstat: No subdevice number in filename %s\n", name); + return -1; + } + + subdev = strtoul(&name[name_len + fn_offset], &endp, 10); + if(((subdev == 0) && (name[name_len + fn_offset] != '0')) + || (subdev >= DEVFS_MAX_SUBDEVS)) + /* Invalid number */ + { + M_PRINTF("getstat: Invalid subdev number %d\n", subdev); + return -1; + } + + if(*endp) + /* Extra charactes after filename */ + { + M_PRINTF("getstat: Invalid filename\n"); + return -1; + } + + if(!dev->subdevs[subdev].valid) + { + M_PRINTF("getstat: No subdev registered\n"); + return -1; + } + +#ifdef USE_IOMAN + memset(stat, 0, sizeof(fio_stat_t)); +#else + memset(stat, 0, sizeof(iox_stat_t)); +#endif + stat->size = dev->subdevs[subdev].extent.loc32[0]; + stat->hisize = dev->subdevs[subdev].extent.loc32[1]; + stat->mode = FIO_S_IFREG; + if(dev->subdevs[subdev].mode & DEVFS_MODE_R) + { + stat->mode |= FIO_S_IRUSR; + } + if(dev->subdevs[subdev].mode & DEVFS_MODE_W) + { + stat->mode |= FIO_S_IWUSR; + } + } + + return 0; +} + +/** DevFS initialise function + * @returns >= 0 on success, -1 on error + */ +int init_devfs(void) + +{ + int dummy_loop; + dummy_func *dummy; + + root_device = NULL; + dev_count = 0; + + /* Set all io handlers to dummy values */ + dummy = (dummy_func *) &devfs_ops; + for(dummy_loop = 0; dummy_loop < (sizeof(iop_device_ops_t) / sizeof(dummy)); dummy_loop++) + { + dummy[dummy_loop] = devfs_dummy; + } + memset(open_dirfiles, 0, sizeof(directory_file_t) * MAX_OPEN_DIRFILES); + + devfs_device.name = "devfs"; + devfs_device.type = IOP_DT_FS | IOP_DT_FSEXT; + devfs_device.version = 0x100; + devfs_device.desc = "PS2 Device FS Driver"; + devfs_device.ops = &devfs_ops; + devfs_ops.init = devfs_init; + devfs_ops.deinit = devfs_deinit; + devfs_ops.open = devfs_open; + devfs_ops.read = devfs_read; + devfs_ops.close = devfs_close; + devfs_ops.dopen = devfs_dopen; + devfs_ops.dclose = devfs_dclose; + devfs_ops.dread = devfs_dread; + devfs_ops.ioctl = devfs_ioctl; + devfs_ops.ioctl2 = devfs_ioctl2; + devfs_ops.getstat = devfs_getstat; + DelDrv("devfs"); + + return AddDrv(&devfs_device); +} + +/** Main start function of the module + * @param argc: Unused + * @param argv: Unused + * @returns 0 on success, -1 on error + */ +int _start(int argc, char **argv) +{ + int res = 1; + + printf(BANNER, VERSION); + + if ((res = RegisterLibraryEntries(&_exp_devfs)) != 0) { + M_PRINTF("Library is already registered, exiting.\n"); + printf("res=%d\n", res); + } + else + { + res = init_devfs(); + } + + M_PRINTF("devfs_device_t size=%d\n", sizeof(devfs_device_t)); + M_PRINTF("Driver loaded.\n"); + + return res; +} + +/** Function to check a device name only contains alphabetic characters + * @param name: The name to check. + * @returns 0 if the name is invalid, else 1 + */ +int devfs_check_devname(const char *name) +/* Valid device name uses alphabetic characters only */ + +{ + int str_loop; + + if((name == NULL) || (name[0] == 0)) + { + return 0; + } + + if(strlen(name) > DEVFS_MAX_DEVNAME_LENGTH) + { + return 0; + } + + str_loop = 0; + + while(name[str_loop]) + { + char ch; + + ch = name[str_loop]; + if(((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z'))) + { + str_loop++; + } + else + { + return 0; + } + } + + return 1; +} + +HDEV DevFSAddDevice(const devfs_node_t *node) + +{ + devfs_device_t *dev = NULL; + devfs_device_t *dev_scan; + + //printf("AddDevice node=%p\n", node); + if(node == NULL) + { + M_PRINTF("AddDevice: node == NULL\n"); + return INVALID_HDEV; + } + + if(!devfs_check_devname(node->name)) + { + M_PRINTF("AddDevice: node name invalid\n"); + return INVALID_HDEV; + } + + if(devfs_find_devicename(node->name)) + { + M_PRINTF("AddDevice: cannot add new device. Already exists\n"); + return INVALID_HDEV; + } + + dev = devfs_create_device(node); + if(dev == NULL) + { + M_PRINTF("AddDevice: failed to allocate device structure\n"); + return INVALID_HDEV; + } + if(root_device == NULL) + { + root_device = dev; + } + else + { + dev_scan = root_device; + while(dev_scan->forw) /* Scan the device linked list */ + { + dev_scan = dev_scan->forw; + } + dev_scan->forw = dev; + dev->back = dev_scan; + } + + dev->hDev = dev_count++; + if(dev_count == INVALID_HDEV) dev_count++; + M_PRINTF("AddDevice: Registered device (%s)\n", node->name); + + return dev->hDev; +} + +int DevFSDelDevice(HDEV hDev) + +{ + devfs_device_t *dev; + int ret = -1; + devfs_device_t *forw, *back; + + //printf("DelDevice hDev=%d\n", hDev); + dev = devfs_find_deviceid(hDev); + if(dev) + { + int subdev_loop; + int openfile_loop; + + forw = dev->forw; + back = dev->back; + + /* Delete the device even if open files */ + for(subdev_loop = 0; subdev_loop < DEVFS_MAX_SUBDEVS; subdev_loop++) + { + for(openfile_loop = 0; openfile_loop < MAX_OPENFILES; openfile_loop++) + { + if(dev->subdevs[subdev_loop].open_files[openfile_loop]) + { + dev->subdevs[subdev_loop].open_files[openfile_loop]->dev = NULL; + /* Set the device reference to NULL */ + } + } + } + devfs_delete_device(dev); + + if(back) + { + back->forw = forw; + } + else + { + root_device = NULL; + } + + if(forw) + { + forw->back = back; + } + + ret = 0; + } + + return ret; +} + +int DevFSAddSubDevice(HDEV hDev, u32 subdev_no, s32 mode, devfs_loc_t extent, void *data) + +{ + devfs_device_t *dev; + + //M_PRINTF("AddSubDevice hDev=%d subdev_no=%d data=%p\n", hDev, subdev_no, data); + dev = devfs_find_deviceid(hDev); + if(dev != NULL) + { + if(subdev_no >= DEVFS_MAX_SUBDEVS) + { + M_PRINTF("AddSubDevice: Sub device number too big\n"); + return -1; + } + + if(dev->subdevs[subdev_no].valid) + { + M_PRINTF("AddSubDevice: Sub device already created\n"); + return -1; + } + + dev->subdevs[subdev_no].data = data; + dev->subdevs[subdev_no].valid = 1; + dev->subdevs[subdev_no].mode = mode; + dev->subdevs[subdev_no].open_refcount = 0; + dev->subdevs[subdev_no].extent = extent; + memset(dev->subdevs[subdev_no].open_files, 0, sizeof(ioman_data_t *) * MAX_OPENFILES); + dev->subdev_count++; + } + else + { + M_PRINTF("AddSubDevice: Couldn't find device ID\n"); + return -1; + } + + return 0; +} + +int DevFSDelSubDevice(HDEV hDev, u32 subdev_no) + +{ + devfs_device_t *dev; + int openfile_loop; + + //printf("DelSubDevice hDev=%d subdev_no=%d\n", hDev, subdev_no); + dev = devfs_find_deviceid(hDev); + if(dev != NULL) + { + if(subdev_no >= DEVFS_MAX_SUBDEVS) + { + M_PRINTF("DelSubDevice: Sub device number too big\n"); + return -1; + } + + if(!dev->subdevs[subdev_no].valid) + { + M_PRINTF("DelSubDevice: Sub device not created\n"); + return -1; + } + + dev->subdevs[subdev_no].data = NULL; + dev->subdevs[subdev_no].valid = 0; + dev->subdevs[subdev_no].mode = 0; + dev->subdevs[subdev_no].open_refcount = 0; + dev->subdevs[subdev_no].extent.loc64= 0; + for(openfile_loop = 0; openfile_loop < MAX_OPENFILES; openfile_loop++) + { + if(dev->subdevs[subdev_no].open_files[openfile_loop]) + { + dev->subdevs[subdev_no].open_files[openfile_loop]->dev = NULL; + dev->subdevs[subdev_no].open_files[openfile_loop] = NULL; + } + } + dev->subdev_count--; + } + + return 0; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/exports.tab b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/exports.tab new file mode 100644 index 0000000..e3f1388 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/exports.tab @@ -0,0 +1,14 @@ +/**/ + +DECLARE_EXPORT_TABLE(devfs, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(_retonly) + DECLARE_EXPORT(DevFSAddDevice) + DECLARE_EXPORT(DevFSDelDevice) + DECLARE_EXPORT(DevFSAddSubDevice) + DECLARE_EXPORT(DevFSDelSubDevice) +END_EXPORT_TABLE + +void _retonly() {} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/imports.lst new file mode 100644 index 0000000..41e1f32 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/imports.lst @@ -0,0 +1,37 @@ + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +loadcore_IMPORTS_end + +stdio_IMPORTS_start +I_printf +I_sprintf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memcpy +I_memset +I_strlen +I_strncmp +I_strtoul +I_strcpy +I_strcat +I_strncpy +sysclib_IMPORTS_end + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +sysmem_IMPORTS_end + +#ifdef USE_IOMAN +ioman_IMPORTS_start +I_AddDrv +I_DelDrv +ioman_IMPORTS_end +#else +iomanX_IMPORTS_start +I_AddDrv +I_DelDrv +iomanX_IMPORTS_end +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/irx_imports.h new file mode 100644 index 0000000..24a36f0 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/devfs/src/irx_imports.h @@ -0,0 +1,25 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "iomanX.h" +#include "loadcore.h" +#include "stdio.h" +#include "sysclib.h" +#include "sysmem.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/Makefile new file mode 100644 index 0000000..31e88c0 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/Makefile @@ -0,0 +1,14 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_OBJS = fakehost.o nprintf.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/README b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/README new file mode 100644 index 0000000..bfa724d --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/README @@ -0,0 +1,40 @@ +fakehost v1.0 +Copyright (c) 2004 adresd +Licensed under the Academic Free License version 2.0. +-- + +fakehost is a filesystem driver for the IOP processor. + +It accepts one parameter, this parameter is a path to an iomanx filesystem, for example pfs0:/ +When run, it will install a filesystem driver to redirect the host: device to the given device's directory. +It also installs a naplink style rpc interface, for programs that +require that to run. +This together with the host drive is sufficient to allow most programs +designed to run from one of the loader utilities to function in this +environment. + +Usage is: fakehost.irx pfs0:/dir/ + +Example: from ps2link, make sure the needed support modules are loaded and a partition mounted. +Then do, from pksh: execiop host:fakehost.irx pfs0:/dir + +OR alternatively call it with the parameters from EE via loadmodule. + + +NOTES: +This does not handle any mounting of partitions, it is designed to accept +a pfs device as the parameter. The calling program must do any +required setup first. + +This module relies upon: +iomanx and fileXio IOP modules. + +It is also advised that you load: +ps2dev9, ps2atad,ps2hdd and ps2fs +for hdd access. + + +Credits: +Tord Lindstrom for the Naplink RPC Handler +David Ryan (david@livemedia.com.au) for the basic HOST redirection handler (ioman ver) + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/fakehost.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/fakehost.c new file mode 100644 index 0000000..5df5c4a --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/fakehost.c @@ -0,0 +1,273 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOP filesystem driver v1.0 + * This redirects an iomanx device (eg a pfs mount point) the ioman device called 'host' + * it also installs a naplink RPC driver. + * This basically sets up ready to run programs as though they were run from naplink or + * pukklink, regarding host and naplink printf. + */ + +//#define DEBUG + +#include "types.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "intrman.h" +#include "sysmem.h" +#include "sifman.h" +#include "sifcmd.h" + +#include "iomanX.h" +#include "ioman_mod.h" + +#define TRUE 1 +#define FALSE 0 + +/** @defgroup fakehost fakehost - host: to hdd driver */ + +#define MODNAME "fakehost" + +// This is the filesystem to replace +#define FS_REPNAME "host" + +IRX_ID(MODNAME, 1, 1); + +#define M_PRINTF(format, args...) \ + printf(MODNAME ": " format, ##args) + +#ifdef DEBUG +#define M_DEBUG M_PRINTF +#else +#define M_DEBUG(format, args...) +#endif + +// Host base location +static char base[100]; + +// FileIO structure. +static iop_io_device_t driver; + +// Function array for fileio structure. +static iop_io_device_ops_t functions; + +static int fd_global; + +extern int ttyMount(void); +extern int naplinkRpcInit(void); + +/** Make a full pathname string, adding base on. + * @ingroup fakehost + * + * @param buffer buffer to hold result. + * @param name name to add base to. + * @return Pointer to buffer. + * + * This function takes the name param and adds it to the basename + * for replacement, returning the destination full pathname. + */ +char * fd_name( char * buffer, const char * name ) +{ + strcpy( buffer, base ); + strcat( buffer, name ); + return buffer; +} + +/** Store filedescriptor and get client filedescriptor. + * @ingroup fakehost + * + * @param fd filedescriptor to store. + * @param f io_file pointer to store fd in . + * @return client filedescriptor. + */ +int fd_save( int fd, iop_io_file_t *f ) +{ + f->unit = ++fd_global; + f->privdata = (void *) fd; + return f->unit; +} + +/** Get real filedescriptor. + * @ingroup fakehost + * + * @param f io_file pointer to get fd from. + * @return real filedescriptor. + */ +int realfd( iop_io_file_t *f ) +{ + return (int) f->privdata; +} + +/** Dummy function, for where needed. + * @ingroup fakehost + */ +int dummy() +{ + M_DEBUG("dummy function called\n"); + return -5; +} + +/** Initialise fs driver. + * @ingroup fakehost + * + * @param driver io_device pointer to device + * @return Status (0=successful). + */ +int fd_initialize( iop_io_device_t *driver) +{ + M_PRINTF( "initializing '%s' file driver.\n", driver->name ); + return 0; +} + +/** Handle open request. + * @ingroup fakehost + * + * @param f Pointer to io_device structure. + * @param name pathname. + * @param mode open mode. + * @return Status (as for fileio open). + */ +int fd_open( iop_io_file_t *f, const char *name, int mode) +{ + char nameBuffer[ 250 ]; + int fd; + + M_DEBUG("open %i %s %s\n", f->unit, name ,base); + fd = open( fd_name( nameBuffer, name), mode, 0 ); + if ( fd < 0 ) return fd; + + return fd_save( fd, f ); +} + +/** Handle close request. + * @ingroup fakehost + * + * @param f Pointer to io_device structure. + * @return Status (as for fileio close). + */ +int fd_close( iop_io_file_t *f ) +{ + return close( realfd(f) ); +} + +/** Handle read request. + * @ingroup fakehost + * + * @param f Pointer to io_device structure. + * @param buffer Pointer to read buffer. + * @param size Size of buffer. + * @return Status (as for fileio read). + */ +int fd_read( iop_io_file_t *f, void * buffer, int size ) +{ + return read( realfd(f), buffer, size ); +} + +/** Handle write request. + * @ingroup fakehost + * + * @param f Pointer to io_device structure. + * @param buffer Pointer to read buffer. + * @param size Size of buffer. + * @return Status (as for fileio write). + */ +int fd_write( iop_io_file_t *fd, void *buffer, int size ) +{ + return write( realfd(fd), buffer, size ); +} + +/** Handle lseek request. + * @ingroup fakehost + * + * @param f Pointer to io_device structure. + * @param offset Offset for seek. + * @param whence Base for seek. + * @return Status (as for fileio lseek). + */ +int fd_lseek( iop_io_file_t *fd, int offset, int whence) +{ + return lseek( realfd(fd), offset, whence ); +} + +/** Entry point for IRX. + * @ingroup fakehost + * + * if argc != 2 , quit, as it needs parameter + * if argc == 2 , use arv[1] as basename. + * + * @param argc Number of arguments. + * @param argv Pointer to array of arguments. + * @return Module Status on Exit. + * + * This initialises the fakehost driver, setting up the 'host:' fs driver + * basename redirection, and naplink compatible rpc hander. + * + * return values: + * MODULE_RESIDENT_END if loaded and registered as library. + * MODULE_NO_RESIDENT_END if just exiting normally. + */ +int _start( int argc, char **argv ) +{ + M_PRINTF( "Copyright (c) 2004 adresd\n" ); + + if ( argc != 2 ) + { + M_PRINTF( "HOST requires based argument\n" ); + return -1; + } + else + { + // Copy the base location. + strncpy( base, argv[1] ,sizeof(base) - 1); + base[sizeof(base) - 1] = '\0'; + + M_PRINTF( "redirecting '%s:' to '%s'\n",FS_REPNAME,base); + fd_global = 1; + + driver.name = FS_REPNAME; + driver.type = 16; + driver.version = 1; + driver.desc = "host redirection driver"; + driver.ops = &functions; + + functions.io_init = fd_initialize; + functions.io_deinit = dummy; + functions.io_format = dummy; + functions.io_open = fd_open; + functions.io_close = fd_close; + functions.io_read = fd_read; + functions.io_write = dummy; + functions.io_lseek = fd_lseek; + functions.io_ioctl = dummy; + functions.io_remove = dummy; + functions.io_mkdir = dummy; + functions.io_rmdir = dummy; + functions.io_dopen = dummy; + functions.io_dclose = dummy; + functions.io_dread = dummy; + functions.io_getstat = dummy; + functions.io_chstat = dummy; + + M_PRINTF( "HOST final step, bye\n" ); + + // Install naplink RPC handler + naplinkRpcInit(); + + // now install the fileio driver + io_DelDrv( FS_REPNAME ); + io_AddDrv( &driver ); + } + return 0; +} + + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/imports.lst new file mode 100644 index 0000000..ae8b455 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/imports.lst @@ -0,0 +1,45 @@ + +#include "ioman_mod.h" + +sysclib_IMPORTS_start +I_strncpy +I_strcpy +I_strcat +sysclib_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_StartThread +I_SleepThread +I_GetThreadId +I_DeleteThread +I_ExitDeleteThread +thbase_IMPORTS_end + +iomanX_IMPORTS_start +I_open +I_close +I_read +I_write +I_lseek +I_AddDrv +I_DelDrv +iomanX_IMPORTS_end + +ioman_mod_IMPORTS_start +I_io_AddDrv +I_io_DelDrv +I_io_open +I_io_close +ioman_mod_IMPORTS_end + +sifcmd_IMPORTS_start +I_sceSifInitRpc +I_sceSifSetRpcQueue +I_sceSifRegisterRpc +I_sceSifRpcLoop +sifcmd_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/irx_imports.h new file mode 100644 index 0000000..acd386c --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/irx_imports.h @@ -0,0 +1,28 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "iomanX.h" +#include "ioman_mod.h" +#include "loadcore.h" +#include "sifcmd.h" +#include "stdio.h" +#include "sysclib.h" +#include "sysmem.h" +#include "thbase.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/nprintf.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/nprintf.c new file mode 100644 index 0000000..7b0768b --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/fakehost/src/nprintf.c @@ -0,0 +1,100 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * IOP naplink RPC server v1.0 + * This installs a naplink compatible RPC handler, to service the nprintf functions + * given via naplink for printing from ee. + */ + +#include "types.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "intrman.h" +#include "sysmem.h" +#include "sifman.h" +#include "sifcmd.h" + +//////////////////////////////////////////////////////////////////////// +#define NPM_PUTS 0x01 +#define RPC_NPM_USER 0x014d704e + +/** RPC handler function. + * @ingroup fakehost + * + * @param cmd Command. + * @param buffer Pointer to buffer. + * @param size Size of buffer. + */ +static void *naplinkRpcHandler(int cmd, void *buffer, int size) +{ + return buffer; +} + +//////////////////////////////////////////////////////////////////////// +static SifRpcServerData_t server __attribute((aligned(16))); +static SifRpcDataQueue_t queue __attribute((aligned(16))); +static unsigned char rpc_buffer[512] __attribute((aligned(16))); + +/** naplink compatbile RPC handler thread. + * @ingroup fakehost + * + * @param arg Startup parameters. + */ +static void napThread(void *arg) +{ + int pid; + + SifInitRpc(0); + pid = GetThreadId(); + SifSetRpcQueue(&queue, pid); + SifRegisterRpc(&server, RPC_NPM_USER, naplinkRpcHandler, + rpc_buffer, 0, 0, &queue); + SifRpcLoop(&queue); // Never exits + ExitDeleteThread(); +} + +/** Setup naplink compatible RPC handler. + * @ingroup fakehost + * + * @return Status. + * + * return values: + * 0 on success. + * -1 on error. + */ +int naplinkRpcInit(void) +{ + iop_thread_t th_attr; + int ret; + int pid; + + th_attr.attr = 0x02000000; + th_attr.option = 0; + th_attr.thread = napThread; + th_attr.stacksize = 0x800; + th_attr.priority = 0x4f; + + pid = CreateThread(&th_attr); + if (pid < 0) { + printf("IOP: napRpc createThread failed %d\n", pid); + return -1; + } + + ret = StartThread(pid, 0); + if (ret < 0) { + printf("IOP: napRpc startThread failed %d\n", ret); + DeleteThread(pid); + return -1; + } + return 0; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/Makefile new file mode 100644 index 0000000..945a4d1 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN ?= fileXio.irx + +IOP_OBJS = fileXio_iop.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/src/fileXio_iop.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/src/fileXio_iop.c new file mode 100644 index 0000000..f2368c3 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/src/fileXio_iop.c @@ -0,0 +1,1097 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * fileXio RPC Server + * This module provides an RPC interface to the EE for all the functions + * of ioman/fileio. + */ + +//#define DEBUG + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MODNAME "IOX/File_Manager_Rpc" +IRX_ID(MODNAME, 1, 2); + +#define M_PRINTF(format, args...) \ + printf(MODNAME ": " format, ##args) + +#ifdef DEBUG +#define M_DEBUG M_PRINTF +#else +#define M_DEBUG(format, args...) +#endif + +#define TRUE 1 +#define FALSE 0 + +#define MIN(a, b) (((a)<(b))?(a):(b)) +#define RDOWN_64(a) ((unsigned int)(a)&~0x3F) + +#define DEFAULT_RWSIZE 16384 +static void *rwbuf = NULL; +static unsigned int RWBufferSize=DEFAULT_RWSIZE; + +// 0x4800 bytes for DirEntry structures +// 0x400 bytes for the filename string +static unsigned char fileXio_rpc_buffer[0x4C00]; // RPC send/receive buffer +struct t_SifRpcDataQueue qd; +struct t_SifRpcServerData sd0; + +static rests_pkt rests; + +/* RPC exported functions */ +static int fileXio_GetDeviceList_RPC(struct fileXioDevice* ee_devices, int eecount); +static int fileXio_CopyFile_RPC(const char *src, const char *dest, int mode); +static int fileXio_Read_RPC(int infd, char *read_buf, int read_size, void *intr_data); +static int fileXio_Write_RPC(int outfd, const char *write_buf, int write_size, int mis,u8 *misbuf); +static int fileXio_GetDir_RPC(const char* pathname, struct fileXioDirEntry dirEntry[], unsigned int req_entries); +static int fileXio_Mount_RPC(const char* mountstring, const char* mountpoint, int flag); +static int fileXio_chstat_RPC(char *filename, void* eeptr, int mask); +static int fileXio_getstat_RPC(char *filename, void* eeptr); +static int fileXio_dread_RPC(int fd, void* eeptr); + +// Functions called by the RPC server +static void* fileXioRpc_Stop(); +static void* fileXioRpc_GetDeviceList(unsigned int* sbuff); +static void* fileXioRpc_Getdir(unsigned int* sbuff); +static void* fileXioRpc_Mount(unsigned int* sbuff); +static void* fileXioRpc_uMount(unsigned int* sbuff); +static void* fileXioRpc_CopyFile(unsigned int* sbuff); +static void* fileXioRpc_MkDir(unsigned int* sbuff); +static void* fileXioRpc_RmDir(unsigned int* sbuff); +static void* fileXioRpc_Remove(unsigned int* sbuff); +static void* fileXioRpc_Rename(unsigned int* sbuff); +static void* fileXioRpc_SymLink(unsigned int* sbuff); +static void* fileXioRpc_ReadLink(unsigned int* sbuff); +static void* fileXioRpc_ChDir(unsigned int* sbuff); +static void* fileXioRpc_Open(unsigned int* sbuff); +static void* fileXioRpc_Close(unsigned int* sbuff); +static void* fileXioRpc_Read(unsigned int* sbuff); +static void* fileXioRpc_Write(unsigned int* sbuff); +static void* fileXioRpc_Lseek(unsigned int* sbuff); +static void* fileXioRpc_Lseek64(unsigned int* sbuff); +static void* fileXioRpc_ChStat(unsigned int* sbuff); +static void* fileXioRpc_GetStat(unsigned int* sbuff); +static void* fileXioRpc_Format(unsigned int* sbuff); +static void* fileXioRpc_AddDrv(unsigned int* sbuff); +static void* fileXioRpc_DelDrv(unsigned int* sbuff); +static void* fileXioRpc_Sync(unsigned int* sbuff); +static void* fileXioRpc_Devctl(unsigned int* sbuff); +static void* fileXioRpc_Ioctl(unsigned int* sbuff); +static void* fileXioRpc_Ioctl2(unsigned int* sbuff); +static void* fileXioRpc_Dopen(unsigned int* sbuff); +static void* fileXioRpc_Dread(unsigned int* sbuff); +static void* fileXioRpc_Dclose(unsigned int* sbuff); +static void* filexioRpc_SetRWBufferSize(void *sbuff); +static void* fileXioRpc_Getdir(unsigned int* sbuff); +static void DirEntryCopy(struct fileXioDirEntry* dirEntry, iox_dirent_t* internalDirEntry); + +// RPC server +static void* fileXio_rpc_server(int fno, void *data, int size); +static void fileXio_Thread(void* param); + +int _start( int argc, char **argv) +{ + struct _iop_thread param; + int th, result; + + param.attr = TH_C; + param.thread = (void*)fileXio_Thread; + param.priority = 40; + param.stacksize = 0x8000; + param.option = 0; + + th = CreateThread(¶m); + + if (th > 0) + { + StartThread(th, NULL); + result=MODULE_RESIDENT_END; + } + else result=MODULE_NO_RESIDENT_END; + + return result; +} + +static int fileXio_GetDeviceList_RPC(struct fileXioDevice* ee_devices, int eecount) +{ + int device_count = 0; + iop_device_t **devices = GetDeviceList(); + struct fileXioDevice local_devices[FILEXIO_MAX_DEVICES]; + while (devices[device_count] && device_count < eecount) + { + iop_device_t *device = devices[device_count]; + strncpy(local_devices[device_count].name, device->name, 128); + local_devices[device_count].name[15] = '\0'; + local_devices[device_count].type = device->type; + local_devices[device_count].version = device->version; + strncpy(local_devices[device_count].desc, device->desc, 128); + local_devices[device_count].desc[127] = '\0'; + ++device_count; + } + if (device_count) + { + struct t_SifDmaTransfer dmaStruct; + int intStatus; // interrupt status - for dis/en-abling interrupts + + dmaStruct.src = local_devices; + dmaStruct.dest = ee_devices; + dmaStruct.size = sizeof(struct fileXioDevice) * device_count; + dmaStruct.attr = 0; + + // Do the DMA transfer + CpuSuspendIntr(&intStatus); + SifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + } + return device_count; +} + +static int fileXio_CopyFile_RPC(const char *src, const char *dest, int mode) +{ + iox_stat_t stat; + int infd, outfd, size, remain, i, retval = 0; + + if ((infd = open(src, O_RDONLY, 0666)) < 0) { + return infd; + } + if ((outfd = open(dest, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0) { + close(infd); + return outfd; + } + size = lseek(infd, 0, SEEK_END); + lseek(infd, 0, SEEK_SET); + if (!size) + return retval; + + remain = size % RWBufferSize; + for (i = 0; i < (size / RWBufferSize); i++) { + read(infd, rwbuf, RWBufferSize); + write(outfd, rwbuf, RWBufferSize); + } + read(infd, rwbuf, remain); + write(outfd, rwbuf, remain); + close(infd); + close(outfd); + + stat.mode = mode; + chstat(dest, &stat, 1); + + return size; +} + +static int fileXio_Read_RPC(int infd, char *read_buf, int read_size, void *intr_data) +{ + int srest; + int erest; + int asize; + int abuffer; + int rlen; + int total; + int readlen; + int status; + struct t_SifDmaTransfer dmaStruct; + void *buffer; + void *aebuffer; + int intStatus; // interrupt status - for dis/en-abling interrupts + int read_buf2 = (int)read_buf; + + total = 0; + + if(read_size < 64) + { + srest = read_size; + erest = asize = abuffer = 0; + buffer = read_buf; + aebuffer = 0; + }else{ + if ((read_buf2 & 0x3F) == 0) + srest=0; + else + srest=(int)RDOWN_64(read_buf2) - read_buf2 + 64; + buffer = read_buf; + abuffer = read_buf2 + srest; + aebuffer=(void *)RDOWN_64(read_buf2 + read_size); + asize = (int)aebuffer - (int)abuffer; + erest = (read_buf2 + read_size) - (int)aebuffer; + } + if (srest>0) + { + if (srest!=(rlen=read(infd, rests.sbuffer, srest))) + { + total += srest = (rlen>0 ? rlen:0); + goto EXIT; + } + else + total += srest; + } + + status=0; + while (asize>0) + { + readlen=MIN(RWBufferSize, asize); + + while(SifDmaStat(status)>=0); + + rlen=read(infd, rwbuf, readlen); + if (readlen!=rlen){ + if (rlen<=0)goto EXIT; + dmaStruct.dest=(void *)abuffer; + dmaStruct.size=rlen; + dmaStruct.attr=0; + dmaStruct.src =rwbuf; + CpuSuspendIntr(&intStatus); + SifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + total +=rlen; + goto EXIT; + }else{ //read ok + total += rlen; + asize -=rlen; + dmaStruct.dest=(void *)abuffer; + abuffer +=rlen; + dmaStruct.size=rlen; + dmaStruct.attr=0; + dmaStruct.src =rwbuf; + CpuSuspendIntr(&intStatus); + status=SifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + } + } + if (erest>0) + { + rlen = read(infd, rests.ebuffer, erest); + total += (rlen>0 ? rlen : 0); + } +EXIT: + rests.ssize=srest; + rests.esize=erest; + rests.sbuf =buffer; + rests.ebuf =aebuffer; + dmaStruct.src =&rests; + dmaStruct.size=sizeof(rests_pkt); + dmaStruct.attr=0; + dmaStruct.dest=intr_data; + CpuSuspendIntr(&intStatus); + SifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + return (total); +} + +static int fileXio_Write_RPC(int outfd, const char *write_buf, int write_size, int mis,u8 *misbuf) +{ + SifRpcReceiveData_t rdata; + int left; + int wlen; + int writelen; + int pos; + int total; + + left = write_size; + total = 0; + if (mis > 0) + { + wlen=write(outfd, misbuf, mis); + if (wlen != mis) + { + if (wlen > 0) + total += wlen; + return (total); + } + total += wlen; + } + + left-=mis; + pos=(int)write_buf+mis; + while(left){ + writelen = MIN(RWBufferSize, left); + SifRpcGetOtherData(&rdata, (void *)pos, rwbuf, writelen, 0); + wlen=write(outfd, rwbuf, writelen); + if (wlen != writelen){ + if (wlen>0) + total+=wlen; + return (total); + } + left -=writelen; + pos +=writelen; + total+=writelen; + } + return (total); +} + + +// This is the getdir for use by the EE RPC client +// It DMA's entries to the specified buffer in EE memory +static int fileXio_GetDir_RPC(const char* pathname, struct fileXioDirEntry dirEntry[], unsigned int req_entries) +{ + int matched_entries; + int fd, res; + iox_dirent_t dirbuf; + struct fileXioDirEntry localDirEntry; + int intStatus; // interrupt status - for dis/en-abling interrupts + struct t_SifDmaTransfer dmaStruct; + int dmaID; + + dmaID = 0; + + M_DEBUG("GetDir Request\n"); + M_DEBUG("dirname: %s\n",pathname); + + matched_entries = 0; + + fd = dopen(pathname); + if (fd <= 0) + { + return fd; + } + { + + res = 1; + while (res > 0) + { + memset(&dirbuf, 0, sizeof(dirbuf)); + res = dread(fd, &dirbuf); + if (res > 0) + { + // check for too many entries + if (matched_entries == req_entries) + { + close(fd); + return (matched_entries); + } + // wait for any previous DMA to complete + // before over-writing localDirEntry + while(SifDmaStat(dmaID)>=0); + DirEntryCopy(&localDirEntry, &dirbuf); + // DMA localDirEntry to the address specified by dirEntry[matched_entries] + // setup the dma struct + dmaStruct.src = &localDirEntry; + dmaStruct.dest = &dirEntry[matched_entries]; + dmaStruct.size = sizeof(struct fileXioDirEntry); + dmaStruct.attr = 0; + // Do the DMA transfer + CpuSuspendIntr(&intStatus); + dmaID = SifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + matched_entries++; + } // if res + } // while + + } // if dirs and files + + // cleanup and return # of entries + close(fd); + return (matched_entries); +} + +// This is the mount for use by the EE RPC client +static int fileXio_Mount_RPC(const char* mountstring, const char* mountpoint, int flag) +{ + int res=0; + M_DEBUG("Mount Request\n"); + M_DEBUG("mountpoint: %s - %s - %d\n",mountpoint,mountstring,flag); + res = mount(mountpoint, mountstring, flag, NULL, 0); + return(res); +} + +static int fileXio_chstat_RPC(char *filename, void* eeptr, int mask) +{ + int res=0; + iox_stat_t localStat; + SifRpcReceiveData_t rdata; + + SifRpcGetOtherData(&rdata, (void *)eeptr, &localStat, 64, 0); + + res = chstat(filename, &localStat, mask); + return(res); +} + +static int fileXio_getstat_RPC(char *filename, void* eeptr) +{ + iox_stat_t localStat; + int res = 0; + struct t_SifDmaTransfer dmaStruct; + int intStatus; // interrupt status - for dis/en-abling interrupts + + res = getstat(filename, &localStat); + + if(res >= 0) + { + // DMA localStat to the address specified by eeptr + // setup the dma struct + dmaStruct.src = &localStat; + dmaStruct.dest = eeptr; + dmaStruct.size = sizeof(iox_stat_t); + dmaStruct.attr = 0; + // Do the DMA transfer + CpuSuspendIntr(&intStatus); + SifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + } + + return(res); +} + +static int fileXio_dread_RPC(int fd, void* eeptr) +{ + int res=0; + iox_dirent_t localDir; + struct t_SifDmaTransfer dmaStruct; + int intStatus; // interrupt status - for dis/en-abling interrupts + + res = dread(fd, &localDir); + if (res > 0) + { + // DMA localStat to the address specified by eeptr + // setup the dma struct + dmaStruct.src = &localDir; + dmaStruct.dest = eeptr; + dmaStruct.size = 64+256; + dmaStruct.attr = 0; + // Do the DMA transfer + CpuSuspendIntr(&intStatus); + SifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + } + + return(res); +} + +static void* fileXioRpc_Stop(void) +{ + M_DEBUG("Stop Request\n"); + return NULL; +} + +// Send: Offset 0 = pointer to array of fileXioDevice structures in EE mem +// Send: Offset 4 = requested number of entries +// Return: Offset 0 = ret val (number of entries). Size = int +static void* fileXioRpc_GetDeviceList(unsigned int* sbuff) +{ + int ret; + struct fxio_devlist_packet *packet=(struct fxio_devlist_packet*)sbuff; + + ret=fileXio_GetDeviceList_RPC( + packet->deviceEntry, + packet->reqEntries + ); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = filename string (512 bytes) +// Send: Offset 512 = pointer to array of DirEntry structures in EE mem +// Send: Offset 516 = requested number of entries +// Return: Offset 0 = ret val (number of matched entries). Size = int +static void* fileXioRpc_Getdir(unsigned int* sbuff) +{ + int ret; + struct fxio_getdir_packet *packet=(struct fxio_getdir_packet*)sbuff; + + ret=fileXio_GetDir_RPC( + packet->pathname, + packet->dirEntry, + packet->reqEntries + ); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = mount format string (512 bytes) +// Send: Offset 512 = mount point (512 bytes) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_Mount(unsigned int* sbuff) +{ + struct fxio_mount_packet *packet=(struct fxio_mount_packet*)sbuff; + int ret; + + M_DEBUG("Mount Request\n"); + ret=fileXio_Mount_RPC( + packet->blockdevice, // mount format string + packet->mountpoint, // mount point + packet->flags // flag (normal,readonly,robust) + ); + + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = mount format string (512 bytes) +// Send: Offset 512 = mount point (512 bytes) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_uMount(unsigned int* sbuff) +{ + int ret; + struct fxio_unmount_packet *packet=(struct fxio_unmount_packet*)sbuff; + + M_DEBUG("uMount Request\n"); + ret=umount(packet->mountpoint); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = source filename (512 bytes) +// Send: Offset 512 = destination filename (512 bytes) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_CopyFile(unsigned int* sbuff) +{ + int ret; + struct fxio_copyfile_packet *packet=(struct fxio_copyfile_packet*)sbuff; + + ret=fileXio_CopyFile_RPC( + packet->source, // source filename + packet->dest, // dest filename + packet->mode // mode + ); + + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = filenames (512 bytes) +// Send: Offset 512 = mode (int) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_MkDir(unsigned int* sbuff) +{ + int ret; + struct fxio_mkdir_packet *packet=(struct fxio_mkdir_packet*)sbuff; + + M_DEBUG("MkDir Request\n"); + ret=mkdir(packet->pathname, packet->mode); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = filenames (512 bytes) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_RmDir(unsigned int* sbuff) +{ + int ret; + struct fxio_pathsel_packet *packet=(struct fxio_pathsel_packet*)sbuff; + + M_DEBUG("RmDir Request\n"); + ret=rmdir(packet->pathname); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = filenames (512 bytes) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_Remove(unsigned int* sbuff) +{ + int ret; + struct fxio_pathsel_packet *packet=(struct fxio_pathsel_packet*)sbuff; + + M_DEBUG("Remove Request\n"); + ret=remove(packet->pathname); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = source filename (512 bytes) +// Send: Offset 512 = destination filename (512 bytes) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_Rename(unsigned int* sbuff) +{ + int ret; + struct fxio_rename_packet *packet=(struct fxio_rename_packet*)sbuff; + + M_DEBUG("Rename Request\n"); + ret=rename(packet->source, packet->dest); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = source filename (512 bytes) +// Send: Offset 512 = destination filename (512 bytes) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_SymLink(unsigned int* sbuff) +{ + int ret; + struct fxio_rename_packet *packet=(struct fxio_rename_packet*)sbuff; + + M_DEBUG("SymLink Request\n"); + ret=symlink(packet->source, packet->dest); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = source filename (512 bytes) +// Send: Offset 512 = buffer (512 bytes) +// Send: Offset 1024 = buflen (int) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_ReadLink(unsigned int* sbuff) +{ + int ret; + struct fxio_readlink_packet *packet=(struct fxio_readlink_packet*)sbuff; + + M_DEBUG("ReadLink Request\n"); + ret=readlink(packet->source, packet->buffer, packet->buflen); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = filename (512 bytes) +// Return: Offset 0 = return status (int) +void* fileXioRpc_ChDir(unsigned int* sbuff) +{ + int ret; + M_DEBUG("ChDir Request\n"); + ret=chdir((char*)sbuff); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = source filename (512 bytes) +// Send: Offset 512 = flags (int) +// Send: Offset 516 = modes (int) +// Return: Offset 0 = return status (int) / fd +static void* fileXioRpc_Open(unsigned int* sbuff) +{ + int ret; + struct fxio_open_packet *packet=(struct fxio_open_packet*)sbuff; + + M_DEBUG("Open Request\n"); + ret=open(packet->pathname, packet->flags, packet->mode); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = fd (int) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_Close(unsigned int* sbuff) +{ + int ret; + struct fxio_close_packet *packet=(struct fxio_close_packet*)sbuff; + + M_DEBUG("Close Request\n"); + ret=close(packet->fd); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = fd (int) +// Send: Offset 4 = pointer to buffer in EE mem +// Send: Offset 8 = buffer size (int) +// Send: Offset 12 = pointer to intr_data in EE mem +static void* fileXioRpc_Read(unsigned int* sbuff) +{ + int ret; + struct fxio_read_packet *packet=(struct fxio_read_packet*)sbuff; + + M_DEBUG("Read Request\n"); + ret=fileXio_Read_RPC(packet->fd, packet->buffer, packet->size, packet->intrData); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = fd (int) +// Send: Offset 4 = pointer to buffer in EE mem +// Send: Offset 8 = buffer size (int) +// Send: Offset 12 = misaligned buffer size (int) +// Send: Offset 16 = misaligned buffer (16) +static void* fileXioRpc_Write(unsigned int* sbuff) +{ + int ret; + struct fxio_write_packet *packet=(struct fxio_write_packet*)sbuff; + + M_DEBUG("Write Request\n"); + ret=fileXio_Write_RPC(packet->fd, packet->buffer, packet->size, + packet->unalignedDataLen, packet->unalignedData); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = fd (int) +// Send: Offset 4 = offset (long) +// Send: Offset 8 = whence (int) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_Lseek(unsigned int* sbuff) +{ + int ret; + struct fxio_lseek_packet *packet=(struct fxio_lseek_packet*)sbuff; + + M_DEBUG("Lseek Request\n"); + ret=lseek(packet->fd, (long int)packet->offset, packet->whence); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = fd (int) +// Send: Offset 4 = offset (long long) +// Send: Offset 12 = whence (int) +// Return: Offset 0 = return status (long long) +static void* fileXioRpc_Lseek64(unsigned int* sbuff) +{ + long long ret; + struct fxio_lseek64_packet *packet=(struct fxio_lseek64_packet*)sbuff; + struct fxio_lseek64_return_pkt *ret_packet=(struct fxio_lseek64_return_pkt*)sbuff; + + M_DEBUG("Lseek64 Request\n"); + + long long offsetHI = packet->offset_hi; + offsetHI = offsetHI << 32; + long long offset = offsetHI | packet->offset_lo; + + ret=lseek64(packet->fd, offset, packet->whence); + ret_packet->pos_lo = (u32)(ret & 0xffffffff); + ret_packet->pos_hi = (u32)((ret >> 32) & 0xffffffff); + + return sbuff; +} + +// Send: Offset 0 = filename (int) +// Send: Offset 512 = pointer to EE mem +// Send: Offset 516 = mask (int) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_ChStat(unsigned int* sbuff) +{ + int ret=-1; + struct fxio_chstat_packet *packet=(struct fxio_chstat_packet*)sbuff; + + M_DEBUG("ChStat Request\n"); + ret=fileXio_chstat_RPC(packet->pathname, packet->stat, packet->mask); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = filename +// Send: Offset 512 = pointer to EE mem +// Return: Offset 0 = return status (int) +static void* fileXioRpc_GetStat(unsigned int* sbuff) +{ + int ret=-1; + struct fxio_getstat_packet *packet=(struct fxio_getstat_packet*)sbuff; + + M_DEBUG("GetStat Request\n"); + ret=fileXio_getstat_RPC(packet->pathname, packet->stat); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = device +// Send: Offset 128 = blockdevice +// Send: Offset 640 = args +// Send: Offset 1152 = arglen (int) +// Return: Offset 0 = return status +static void* fileXioRpc_Format(unsigned int* sbuff) +{ + int ret; + struct fxio_format_packet *packet=(struct fxio_format_packet*)sbuff; + + M_DEBUG("Format Request\n"); + ret=format(packet->device, packet->blockDevice, packet->args, packet->arglen); + sbuff[0] = ret; + return sbuff; +} + +//int io_AddDrv(iop_device_t *device); +static void* fileXioRpc_AddDrv(unsigned int* sbuff) +{ + int ret=-1; + M_DEBUG("AddDrv Request\n"); + // BODY + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = fsname +// Return: Offset 0 = return status (int) +static void* fileXioRpc_DelDrv(unsigned int* sbuff) +{ + int ret=-1; + M_DEBUG("DelDrv Request\n"); +// ret=deldrv((char *)&sbuff[0/4]); + sbuff[0] = ret; + return sbuff; +} + +// Send: Offset 0 = devname +// Send: Offset 512 = flag (int) +// Return: Offset 0 = return status (int) +static void* fileXioRpc_Sync(unsigned int* sbuff) +{ + int ret; + struct fxio_sync_packet *packet=(struct fxio_sync_packet*)sbuff; + + M_DEBUG("Sync Request\n"); + ret=sync(packet->device, packet->flags); + sbuff[0] = ret; + return sbuff; +} + +//int io_devctl(const char *name, int cmd, void *arg, unsigned int arglen, void *bufp, +// unsigned int buflen); +static void* fileXioRpc_Devctl(unsigned int* sbuff) +{ + struct fxio_devctl_packet *packet = (struct fxio_devctl_packet *)sbuff; + struct fxio_ctl_return_pkt *ret_buf = (struct fxio_ctl_return_pkt *)rwbuf; + SifDmaTransfer_t dmatrans; + int intStatus; + int ret; + + M_DEBUG("Devctl Request\n"); + + ret = devctl(packet->name, packet->cmd, packet->arg, packet->arglen, ret_buf->buf, packet->buflen); + + // Transfer buffer back to EE + if(packet->buflen != 0) + { + dmatrans.src = ret_buf; + dmatrans.dest = packet->intr_data; + dmatrans.attr = 0; + dmatrans.size = sizeof(struct fxio_ctl_return_pkt); + + ret_buf->dest = packet->buf; + + // EE is expecting data.. on error, simply use size of 0 so no data is copied. + if(ret >= 0) + ret_buf->len = packet->buflen; + else + ret_buf->len = 0; + + CpuSuspendIntr(&intStatus); + SifSetDma(&dmatrans, 1); + CpuResumeIntr(intStatus); + } + + sbuff[0] = ret; + return sbuff; +} + +//int io_ioctl(int fd, int cmd, void *arg); +static void* fileXioRpc_Ioctl(unsigned int* sbuff) +{ + struct fxio_ioctl_packet *packet = (struct fxio_ioctl_packet *)sbuff; + int ret; + + M_DEBUG("Ioctl Request\n"); + + // BODY + ret=ioctl(packet->fd, packet->cmd, packet->arg); + sbuff[0] = ret; + return sbuff; +} +//int io_ioctl2(int fd, int cmd, void *arg, unsigned int arglen, void *bufp, +// unsigned int buflen); +static void* fileXioRpc_Ioctl2(unsigned int* sbuff) +{ + struct fxio_ioctl2_packet *packet = (struct fxio_ioctl2_packet *)sbuff; + struct fxio_ctl_return_pkt *ret_buf = (struct fxio_ctl_return_pkt *)rwbuf; + SifDmaTransfer_t dmatrans; + int intStatus; + int ret; + + M_DEBUG("ioctl2 Request\n"); + + ret = ioctl2(packet->fd, packet->cmd, packet->arg, packet->arglen, ret_buf->buf, packet->buflen); + + // Transfer buffer back to EE + if(packet->buflen != 0) + { + dmatrans.src = ret_buf; + dmatrans.dest = packet->intr_data; + dmatrans.attr = 0; + dmatrans.size = sizeof(struct fxio_ctl_return_pkt); + + ret_buf->dest = packet->buf; + + // EE is expecting data.. on error, simply use size of 0 so no data is copied. + if(ret >= 0) + ret_buf->len = packet->buflen; + else + ret_buf->len = 0; + + CpuSuspendIntr(&intStatus); + SifSetDma(&dmatrans, 1); + CpuResumeIntr(intStatus); + } + + sbuff[0] = ret; + return sbuff; +} + +static void* fileXioRpc_Dopen(unsigned int* sbuff) +{ + int ret; + struct fxio_pathsel_packet *packet=(struct fxio_pathsel_packet*)sbuff; + + M_DEBUG("Dopen Request\n"); + ret=dopen(packet->pathname); + sbuff[0] = ret; + return sbuff; +} + +static void* fileXioRpc_Dread(unsigned int* sbuff) +{ + int ret=-1; + struct fxio_dread_packet *packet=(struct fxio_dread_packet*)sbuff; + + M_DEBUG("Dread Request\n"); + ret=fileXio_dread_RPC(packet->fd, packet->dirent); + sbuff[0] = ret; + return sbuff; +} + +static void* fileXioRpc_Dclose(unsigned int* sbuff) +{ + int ret; + struct fxio_close_packet *packet=(struct fxio_close_packet*)sbuff; + + M_DEBUG("Dclose Request\n"); + ret=dclose(packet->fd); + sbuff[0] = ret; + return sbuff; +} + +/************************************************* +* The functions below are for internal use only, * +* and are not to be exported * +*************************************************/ + +static void fileXio_Thread(void* param) +{ + int OldState; + + M_PRINTF("fileXio: fileXio RPC Server v1.00\nCopyright (c) 2003 adresd\n"); + M_DEBUG("fileXio: RPC Initialize\n"); + + SifInitRpc(0); + + RWBufferSize=DEFAULT_RWSIZE; + CpuSuspendIntr(&OldState); + rwbuf = AllocSysMemory(ALLOC_FIRST, RWBufferSize, NULL); + CpuResumeIntr(OldState); + if (rwbuf == NULL) + { + M_DEBUG("Failed to allocate memory for RW buffer!\n"); + + SleepThread(); + } + + SifSetRpcQueue(&qd, GetThreadId()); + SifRegisterRpc(&sd0, FILEXIO_IRX, &fileXio_rpc_server, fileXio_rpc_buffer, NULL, NULL, &qd); + SifRpcLoop(&qd); +} + +static void* filexioRpc_SetRWBufferSize(void *sbuff) +{ + int OldState; + + if(rwbuf!=NULL){ + CpuSuspendIntr(&OldState); + FreeSysMemory(rwbuf); + CpuResumeIntr(OldState); + } + + RWBufferSize=((struct fxio_rwbuff*)sbuff)->size; + CpuSuspendIntr(&OldState); + rwbuf=AllocSysMemory(ALLOC_FIRST, RWBufferSize, NULL); + CpuResumeIntr(OldState); + + ((int*)sbuff)[0] = rwbuf!=NULL?0:-ENOMEM; + return sbuff; +} + +static void* fileXio_rpc_server(int fno, void *data, int size) +{ + + switch(fno) { + case FILEXIO_DOPEN: + return fileXioRpc_Dopen((unsigned*)data); + case FILEXIO_DREAD: + return fileXioRpc_Dread((unsigned*)data); + case FILEXIO_DCLOSE: + return fileXioRpc_Dclose((unsigned*)data); + case FILEXIO_MOUNT: + return fileXioRpc_Mount((unsigned*)data); + case FILEXIO_UMOUNT: + return fileXioRpc_uMount((unsigned*)data); + case FILEXIO_GETDIR: + return fileXioRpc_Getdir((unsigned*)data); + case FILEXIO_COPYFILE: + return fileXioRpc_CopyFile((unsigned*)data); + case FILEXIO_STOP: + return fileXioRpc_Stop(); + case FILEXIO_CHDIR: + return fileXioRpc_ChDir((unsigned*)data); + case FILEXIO_RENAME: + return fileXioRpc_Rename((unsigned*)data); + case FILEXIO_MKDIR: + return fileXioRpc_MkDir((unsigned*)data); + case FILEXIO_RMDIR: + return fileXioRpc_RmDir((unsigned*)data); + case FILEXIO_REMOVE: + return fileXioRpc_Remove((unsigned*)data); + case FILEXIO_OPEN: + return fileXioRpc_Open((unsigned*)data); + case FILEXIO_CLOSE: + return fileXioRpc_Close((unsigned*)data); + case FILEXIO_READ: + return fileXioRpc_Read((unsigned*)data); + case FILEXIO_WRITE: + return fileXioRpc_Write((unsigned*)data); + case FILEXIO_LSEEK: + return fileXioRpc_Lseek((unsigned*)data); + case FILEXIO_IOCTL: + return fileXioRpc_Ioctl((unsigned*)data); + case FILEXIO_GETSTAT: + return fileXioRpc_GetStat((unsigned*)data); + case FILEXIO_CHSTAT: + return fileXioRpc_ChStat((unsigned*)data); + case FILEXIO_FORMAT: + return fileXioRpc_Format((unsigned*)data); + case FILEXIO_ADDDRV: + return fileXioRpc_AddDrv((unsigned*)data); + case FILEXIO_DELDRV: + return fileXioRpc_DelDrv((unsigned*)data); + case FILEXIO_SYNC: + return fileXioRpc_Sync((unsigned*)data); + case FILEXIO_DEVCTL: + return fileXioRpc_Devctl((unsigned*)data); + case FILEXIO_SYMLINK: + return fileXioRpc_SymLink((unsigned*)data); + case FILEXIO_READLINK: + return fileXioRpc_ReadLink((unsigned*)data); + case FILEXIO_IOCTL2: + return fileXioRpc_Ioctl2((unsigned*)data); + case FILEXIO_LSEEK64: + return fileXioRpc_Lseek64((unsigned*)data); + case FILEXIO_GETDEVICELIST: + return fileXioRpc_GetDeviceList((unsigned*)data); + case FILEXIO_SETRWBUFFSIZE: + return filexioRpc_SetRWBufferSize(data); + } + return NULL; +} + + +// Copy a DIR Entry from the native format to our format +static void DirEntryCopy(struct fileXioDirEntry* dirEntry, iox_dirent_t* internalDirEntry) +{ + dirEntry->fileSize = internalDirEntry->stat.size; + dirEntry->fileProperties = internalDirEntry->stat.attr; + strncpy(dirEntry->filename,internalDirEntry->name,127); + dirEntry->filename[127] = '\0'; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/src/imports.lst new file mode 100644 index 0000000..11f5233 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/src/imports.lst @@ -0,0 +1,71 @@ + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +sysmem_IMPORTS_end + +sysclib_IMPORTS_start +I_memset +I_strncpy +sysclib_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_StartThread +I_SleepThread +I_GetThreadId +thbase_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +iomanX_IMPORTS_start +I_GetDeviceList +I_format +I_open +I_close +I_read +I_write +I_lseek +I_ioctl +I_ioctl2 +I_remove +I_mkdir +I_rmdir +I_dopen +I_dclose +I_dread +I_getstat +I_chstat +I_rename +I_chdir +I_sync +I_mount +I_umount +I_lseek64 +I_devctl +I_AddDrv +I_DelDrv +I_symlink +I_readlink +iomanX_IMPORTS_end + +sifman_IMPORTS_start +I_sceSifInit +I_sceSifSetDma +I_sceSifDmaStat +sifman_IMPORTS_end + +sifcmd_IMPORTS_start +I_sceSifInitRpc +I_sceSifGetOtherData +I_sceSifSetRpcQueue +I_sceSifRegisterRpc +I_sceSifRpcLoop +sifcmd_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/src/irx_imports.h new file mode 100644 index 0000000..c86fb1f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/filexio/src/irx_imports.h @@ -0,0 +1,28 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include +#include +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/http/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/fs/http/Makefile new file mode 100644 index 0000000..52c6f96 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/http/Makefile @@ -0,0 +1,18 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN ?= ps2http.irx + +IOP_INCS += -I$(PS2SDKSRC)/iop/tcpip/tcpip/include -I$(PS2SDKSRC)/iop/tcpip/dns/include + +IOP_OBJS = ps2http.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/http/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/fs/http/src/imports.lst new file mode 100644 index 0000000..381b251 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/http/src/imports.lst @@ -0,0 +1,36 @@ + +sysclib_IMPORTS_start +I_strncpy +I_strstr +I_strtol +I_strlen +I_strcat +I_strcpy +I_strncmp +I_memset +I_toupper +sysclib_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +ps2ip_IMPORTS_start +I_lwip_recv +I_lwip_socket +I_lwip_connect +I_lwip_send +I_lwip_close +I_lwip_gethostbyname +I_inet_addr +ps2ip_IMPORTS_end + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +sysmem_IMPORTS_end + +ioman_mod_IMPORTS_start +I_io_AddDrv +I_io_DelDrv +ioman_mod_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/http/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/http/src/irx_imports.h new file mode 100644 index 0000000..29dee30 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/http/src/irx_imports.h @@ -0,0 +1,30 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "intrman.h" +#include "iomanX.h" +#include "ps2ip.h" +#include "sifcmd.h" +#include "sifman.h" +#include "stdio.h" +#include "sysclib.h" +#include "sysmem.h" +#include "thbase.h" +#include "ioman_mod.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/http/src/ps2http.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/http/src/ps2http.c new file mode 100644 index 0000000..da7c1df --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/http/src/ps2http.c @@ -0,0 +1,509 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/* + * @file + * HTTP CLIENT FILE SYSTEM DRIVER. + * The HTTP file io driver is a read only driver that slots into the PS2 + * IO subsystem and provides access to HTTP. + * + * For each open request a file handle is allocated and any read request + * is directed to the socket. After close has been called the file + * handle slot is free'd for the next request. + * + * No header information normally returned from a HTTP request is returned. + * The client must know the content of the data stream and how to deal with it. + * + * lseek is currently only supported in order to get the size of a file. With + * the current implimentation, it is not possible to seek to different positions + * in a file. + * + * With the current implimentation, hostnames may only be specified as an IP + * address. This will change once we get a DNS resolver up & running with lwip. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "ps2ip.h" + +//#define DEBUG + +#define M_PRINTF(format, args...) \ + printf("PS2HTTP: " format, ##args) + +#ifdef DEBUG +#define M_DEBUG M_PRINTF +#else +#define M_DEBUG(format, args...) +#endif + +typedef struct +{ + int sockFd; + int fileSize; + int filePos; +} t_fioPrivData; + + +// example of basic HTTP 1.0 protocol request. +char strTest[] = "GET /blah HTTP/1.0\n\n"; + +char HTTPGET[] = "GET "; +char HTTPHOST[] = "Host: "; +char HTTPGETEND[] = " HTTP/1.0\r\n"; +char HTTPUSERAGENT[] = "User-Agent: PS2IP HTTP Client\r\n"; +char HTTPENDHEADER[] = "\r\n"; + +/** + * This function will parse the Content-Length header line and return the file size + */ +int parseContentLength(char *mimeBuffer) +{ + char *line; + + line = strstr(mimeBuffer, "CONTENT-LENGTH:"); + line += strlen("CONTENT-LENGTH:"); + + // Advance past any whitepace characters + while((*line == ' ') || (*line == '\t')) line++; + + return (int)strtol(line,NULL, 10); +} + +/** + * This function will parse the initial response header line and return 0 for a "200 OK", + * or return the error code in the event of an error (such as 404 - not found) + */ +int isErrorHeader(char *mimeBuffer) +{ + char *line; + int i; + int code; + + line = strstr(mimeBuffer, "HTTP/1."); + line += strlen("HTTP/1."); + + // Advance past minor protocol version number + line++; + + // Advance past any whitespace characters + while((*line == ' ') || (*line == '\t')) line++; + + // Terminate string after status code + for(i = 0; ((line[i] != ' ') && (line[i] != '\t')); i++); + line[i] = '\0'; + + code = (int)strtol(line,NULL, 10); + if( code == 200 ) + return 0; + else + return code; +} + +/** + * When a request has been sent, we can expect mime headers to be + * before the data. We need to read exactly to the end of the headers + * and no more data. This readline reads a single char at a time. + */ +int readLine( int socket, char * buffer, int size ) +{ + char * ptr = buffer; + int count = 0; + int rc; + + // Keep reading until we fill the buffer. + + while ( count < size ) + { + rc = recv( socket, ptr, 1, 0 ); + + if ( rc <= 0 ) return rc; + + if ( (*ptr == '\n') ) break; + + // increment after check for cr. Don't want to count the cr. + count++; + ptr++; + } + + // Terminate string + *ptr = '\0'; + + // return how many bytes read. + return count; +} + + +/** + * This is the main HTTP client connect work. Makes the connection + * and handles the protocol and reads the return headers. Needs + * to leave the stream at the start of the real data. + */ +int httpConnect( struct sockaddr_in * server, char *hostAddr, const char * url, t_fioPrivData *pHandle ) +{ + int sockHandle; + int peerHandle; + int rc; + char mimeBuffer[100]; + + M_DEBUG( "create socket\n" ); + + if((sockHandle = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP )) < 0) + { + M_PRINTF( "SOCKET FAILED\n" ); + return -1; + } + + M_DEBUG( "connect\n" ); + + rc = connect( sockHandle, (struct sockaddr *) server, sizeof(*server)); + if ( rc < 0 ) + { + M_PRINTF( "CONNECT FAILED %i\n", sockHandle ); + return -1; + } + peerHandle = sockHandle; + + M_DEBUG( "send\n" ); + + // Needs more error checking here..... + rc = send( peerHandle, HTTPGET, sizeof( HTTPGET ) - 1, 0 ); + rc = send( peerHandle, (void*) url, strlen( url ), 0 ); + rc = send( peerHandle, HTTPGETEND, sizeof( HTTPGETEND ) - 1, 0 ); + + rc = send( peerHandle, HTTPHOST, sizeof( HTTPHOST ) - 1, 0 ); + rc = send( peerHandle, hostAddr, strlen( hostAddr ), 0 ); + rc = send( peerHandle, HTTPENDHEADER, sizeof( HTTPENDHEADER ) - 1, 0 ); // "\r\n" + + rc = send( peerHandle, HTTPUSERAGENT, sizeof( HTTPUSERAGENT ) - 1, 0 ); + rc = send( peerHandle, HTTPENDHEADER, sizeof( HTTPENDHEADER ) - 1, 0 ); + + // We now need to read the header information + while ( 1 ) + { + int i; + + // read a line from the header information. + rc = readLine( peerHandle, mimeBuffer, 100 ); + + M_DEBUG(">> %s", mimeBuffer); + + if ( rc < 0 ) return rc; + + // End of headers is a blank line. exit. + if ( rc == 0 ) break; + if ( (rc == 1) && (mimeBuffer[0] == '\r') ) break; + + // Convert mimeBuffer to upper case, so we can do string comps + for(i = 0; i < strlen(mimeBuffer); i++) + mimeBuffer[i] = toupper(mimeBuffer[i]); + + if(strstr(mimeBuffer, "HTTP/1.")) // First line of header, contains status code. Check for an error code + if((rc = isErrorHeader(mimeBuffer))) { + M_PRINTF("status code = %d!\n", rc); + return -rc; + } + + if(strstr(mimeBuffer, "CONTENT-LENGTH:")) + { + pHandle->fileSize = parseContentLength(mimeBuffer); + M_DEBUG("fileSize = %d\n", pHandle->fileSize); + } + } + + // We've sent the request, and read the headers. SockHandle is + // now at the start of the main data read for a file io read. + return peerHandle; +} + +char *strnchr(char *str, char ch, int max) { + int i; + + for(i = 0; (i < max) && (str[i] != '\0'); i++) + if(str[i] == ch) + return(&str[i]); + + return(NULL); +} + +static int _ResolveHostname(const char *hostname , struct in_addr* ip) +{ + struct hostent *HostEntry; + struct in_addr **addr_list; + + if((HostEntry = gethostbyname(hostname)) == NULL) + return 1; + + for(addr_list = (struct in_addr **) HostEntry->h_addr_list; addr_list != NULL; addr_list++) + { + ip->s_addr = (*addr_list)->s_addr; + return 0; + } + + return 1; +} + +/** + * Before we can connect we need to parse the server address and optional + * port from the url provided. the format of "url" as passed to this function + * is "//192.168.0.1:8080/blah.elf" where "192.168.0.1" can be either an IP + * or a domain name and ":8080" is the optional port to connect to, default + * port is 80. + * + * This function will return a filename string for use in GET + * requests, and fill the structure pointed to by *server with the + * correct values. + */ +const char *resolveAddress( struct sockaddr_in *server, const char * url, char *hostAddr ) +{ + unsigned char w; + const char *char_ptr; + char addr[128]; + char port[6] = "80"; // default port of 80(HTTP) + int i = 0, rv; + int isDomain = 0; + + // eg url= //192.168.0.1/fred.elf (the http: is already stripped) + + // NOTE: Need more error checking in parsing code + + // URL must start with double forward slashes. + while(url[0] == '/') { + url++; + } + + for(i = 0; ((url[i] != '\0') && (url[i] != '/')) && (i < 127); i++) + if((((addr[i] = url[i]) < '0') || (url[i] > '9')) && (url[i] != '.')) { + + if(url[i] == ':') {// allow specification of port in URL like http://www.server.net:8080/ + for(w = 0; ((w + i + 1) < 127) && (w < 5) && (url[w + i + 1] != '/') && (url[w + i + 1] != '\0'); w++) + port[w] = url[w + i + 1]; + port[w] = '\0'; + + M_DEBUG("using port %s for connection\n", port); + break; + } + else // it's a domain name if a non-numeric char is contained in the "server" part of the URL. + isDomain = 1; + } + addr[i] = '\0'; // overwrite last char copied(should be '/', '\0' or ':') with a '\0' + strcpy(hostAddr, addr); + + if(isDomain) { + // resolve the host name. + rv = _ResolveHostname(addr, &server->sin_addr); + if(rv != 0) { + M_PRINTF("failed to resolve domain '%s'\n", addr); + return NULL; + } + } + else { + server->sin_addr.s_addr = inet_addr(addr); + } + + i = (int) strtol(port, NULL, 10); // set the port + server->sin_port = htons(i); + + server->sin_family = AF_INET; + +#if 1 + char_ptr = url; + while(*char_ptr != '/') char_ptr++; + + return char_ptr; +#else + return url; +#endif +} + +/** + * Any calls we don't implement calls dummy. + */ +int httpDummy() +{ + M_PRINTF("dummy function called\n"); + return -5; +} + +int httpInitialize(iop_io_device_t *driver) +{ + M_PRINTF("filesystem driver initialized\n"); + + return 0; +} + +/** + * Open has the most work to do in the file driver. It must: + * + * 1. Find a free file Handle. + * 2. Check we have a valid IP address and URL. + * 3. Try and connect to the remote server. + * 4. Send a GET request to the server + * 5. Parse the GET response header from the server + */ +int httpOpen(iop_io_file_t *f, const char *name, int mode) +{ + int peerHandle = 0; + struct sockaddr_in server; + const char *getName; + t_fioPrivData *privData; + char hostAddr[100]; + + M_DEBUG("httpOpen(-, %s, %d)\n", name, mode); + + if((privData = AllocSysMemory(ALLOC_FIRST, sizeof(t_fioPrivData), NULL)) == NULL) + return -1; + + f->privdata = privData; + + privData->fileSize = 0; + privData->filePos = 0; + + memset(&server, 0, sizeof(server)); + // Check valid IP address and URL + if((getName = resolveAddress( &server, name, hostAddr )) == NULL) + { + FreeSysMemory(privData); + return -2; + } + + // Now we connect and initiate the transfer by sending a + // request header to the server, and receiving the response header + if((peerHandle = httpConnect( &server, hostAddr, getName, privData )) < 0) + { + M_PRINTF("failed to connect to '%s'!\n", hostAddr); + FreeSysMemory(privData); + return peerHandle; + } + + // http connect returns valid socket. Save in handle list. + privData->sockFd = peerHandle; + + // return success. We got it all ready. :) + return 0; +} + + +/** + * Read is simple. It simply needs to find the socket no + * based on the file handle and call recv. + */ +int httpRead(iop_io_file_t *f, void *buffer, int size) +{ + int bytesRead = 0; + t_fioPrivData *privData = (t_fioPrivData *)f->privdata; + int left = size; + int totalRead = 0; + + M_DEBUG("httpRead(-, 0x%X, %d)\n", (int)buffer, size); + + // Read until: there is an error, we've read "size" bytes or the remote + // side has closed the connection. + do { + + bytesRead = recv( privData->sockFd, buffer + totalRead, left, 0 ); + +// M_DEBUG("bytesRead = %d\n", bytesRead); + + if(bytesRead <= 0) break; + + left -= bytesRead; + totalRead += bytesRead; + + } while(left); + + return totalRead; +} + + +/** + * Close finds the correct handle and + * calls disconnect. + */ +int httpClose(iop_io_file_t *f) +{ + t_fioPrivData *privData = (t_fioPrivData *)f->privdata; + + M_DEBUG("httpClose(-)\n"); + + lwip_close(privData->sockFd); + FreeSysMemory(privData); + + return 0; +} + +/** + * lseek is only supported in order to get the size of a file. Allough the function + * does modify the filePos member, this does not have any effect on the read position + * of the file in the current implimentation. + */ +int httpLseek(iop_io_file_t *f, int offset, int mode) +{ + t_fioPrivData *privData = (t_fioPrivData *)f->privdata; + + M_DEBUG("httpLseek(-, %d, %d)\n", (int)offset, mode); + + switch(mode) + { + case SEEK_SET: + privData->filePos = offset; + break; + + case SEEK_CUR: + privData->filePos += offset; + break; + + case SEEK_END: + privData->filePos = privData->fileSize + offset; + break; + + default: + return -1; + } + + return privData->filePos; +} + + +iop_io_device_ops_t ps2httpOps = { + httpInitialize, httpDummy, httpDummy, httpOpen, httpClose, httpRead, httpDummy, httpLseek, + httpDummy, httpDummy, httpDummy, httpDummy, httpDummy, httpDummy, httpDummy, httpDummy, + httpDummy +}; + +iop_io_device_t ps2httpDev = { + "http", + IOP_DT_FS, + 1, + "HTTP client file driver", + &ps2httpOps +}; + + +/** + * Main.. registers the File driver. + */ +int _start( int argc, char **argv) +{ + M_PRINTF("Module Loaded\n"); + + M_PRINTF("Adding 'http' driver into io system\n"); + io_DelDrv( "http"); + io_AddDrv(&ps2httpDev); + + return 0; +} + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/Makefile new file mode 100644 index 0000000..085faa3 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/Makefile @@ -0,0 +1,18 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_BIN ?= ps2netfs.irx + +IOP_INCS += -I$(PS2SDKSRC)/iop/system/iopmgr/include -I$(PS2SDKSRC)/iop/tcpip/tcpip/include + +IOP_OBJS = ps2netfs.o ps2_fio.o devscan.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/byteorder.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/byteorder.h new file mode 100644 index 0000000..c1fe3a6 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/byteorder.h @@ -0,0 +1,64 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Lame header. + */ + +#ifndef BYTEORDER_H +#define BYTEORDER_H + +#include + +#ifdef BIG_ENDIAN +inline uint64_t ntohll(x) { return x; } +inline uint32_t ntohl(x) { return x; } +inline uint16_t ntohs(x) { return x; } +#else +// LITTLE_ENDIAN +#ifndef htonll +inline uint64_t +htonll(uint64_t x) +{ + return ((x & 0x00000000000000ffull) << 56) | + ((x & 0x000000000000ff00ull) << 40) | + ((x & 0x0000000000ff0000ull) << 24) | + ((x & 0x00000000ff000000ull) << 8) | + ((x & 0x000000ff00000000ull) >> 8) | + ((x & 0x0000ff0000000000ull) >> 24) | + ((x & 0x00ff000000000000ull) >> 40) | + ((x & 0xff00000000000000ull) >> 56); +} +#endif + +#ifndef htonl +inline uint32_t +htonl(uint32_t x) +{ + return ((x & 0x000000ff) << 24) | + ((x & 0x0000ff00) << 8) | + ((x & 0x00ff0000) >> 8) | + ((x & 0xff000000) >> 24); +} +#endif + +#ifndef htons +inline uint16_t +htons(uint16_t x) +{ + return ((x & 0x00ff) << 8) | + ((x & 0xff00) >> 8); +} +#endif + +#endif + +#endif /* BYTEORDER_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/devscan.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/devscan.c new file mode 100644 index 0000000..8257459 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/devscan.c @@ -0,0 +1,188 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * device driver scanner and handler + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "devscan.h" + +//#define DEBUG +#ifdef DEBUG +#define dbgprintf(args...) printf(args) +#else +#define dbgprintf(args...) do { } while(0) +#endif + +/** Device type structure. + * @ingroup ps2netfs + */ +static dev_table_t dev_info_list[DEVSCAN_MAX+1]; /* one for padding */ + +/** Get pointer to module structure for named module. + * @ingroup ps2netfs + * + * @param name Stringname of module (eg "atad_driver"). + * @return Pointer to module structure. + * + * return values: + * 0 if not found. + * pointer to module structure for loaded module if found. + */ +ModuleInfo_t *devscan_getmodule(const char *name) +{ + ModuleInfo_t *modptr; + int len = strlen(name)+1; + + modptr = GetLoadcoreInternalData()->image_info; + while (modptr != 0) + { + if (!memcmp(modptr->name, name, len)) + return modptr; + modptr = modptr->next; + } + return 0; +} + +/** Initialise the devices table + * @ingroup ps2netfs + * + * @param devtype Mask for device types to return (0x10 = FS drivers). + * @return Number of devices found. + * + * This scans ioman and iomanx for devices, then adds them to the + * internal list, with basename and the handler type. + * + * Also used to re-init the devices table + */ +int devscan_setup(int devtype) +{ + ModuleInfo_t *info; + iop_device_t **devinfo_table; + int i; + int count = 0; + + dbgprintf("devscan: setup\n"); + // clear device list + memset(&dev_info_list,0,sizeof(dev_info_list)); + + /* do the ioman devices */ + if ((info = devscan_getmodule(IOPMGR_IOMAN_IDENT))) + { + /* Find the start of the device info array, in .bss. */ + devinfo_table = (iop_device_t **)(info->text_start + info->text_size + info->data_size + 0x0c); + + /* The device info table had 16 entries, but some may be empty. Just look at all of them. */ + for (i = 0; i < DEVSCAN_IOMAX; i++) + { + if (devinfo_table[i]) + if ((devinfo_table[i]->type & devtype)) + { + dev_info_list[count].devtype = IOPMGR_DEVTYPE_IOMAN; + strncpy(dev_info_list[count].name,devinfo_table[i]->name,255); + dev_info_list[count].name[255] = '\0'; + dev_info_list[count].len = strlen(dev_info_list[count].name); + dbgprintf("devscan: ioman '%s'\n",dev_info_list[count].name); + count++; + } + } + } + + /* do the iomanx devices */ + if ((info = devscan_getmodule(IOPMGR_IOMANX_IDENT))) + { + /* Find the start of the device info array, in .bss. */ + devinfo_table = (iop_device_t **)(info->text_start + info->text_size + info->data_size); + + /* The device info table had 32 entries, but some may be empty. Just look at all of them. */ + for (i = 0; i < DEVSCAN_IOXMAX; i++) + { + if (devinfo_table[i]) + /* only add iomanx ones here, so must have extended flag set else we get duplication with new iomanx */ + if ((devinfo_table[i]->type & IOP_DT_FSEXT) && (devinfo_table[i]->type & devtype)) + { + dev_info_list[count].devtype = IOPMGR_DEVTYPE_IOMANX; + strncpy(dev_info_list[count].name,devinfo_table[i]->name,255); + dev_info_list[count].name[255] = '\0'; + dev_info_list[count].len = strlen(dev_info_list[count].name); + dbgprintf("devscan: iomanx '%s'\n",dev_info_list[count].name); + count++; + } + } + } + return count; +} + +/** Get device handler type for path. + * @ingroup ps2netfs + * + * @param name Full pathname to check. + * @return Device handler type. + * + * return values: + * MODULE_RESIDENT_END if loaded and registered as library. + * MODULE_NO_RESIDENT_END if just exiting normally. + */ +int devscan_gettype(char *name) +{ + int count = 0; + int ret = 0; + dbgprintf("devscan: gettype '%s'\n",name); + while (dev_info_list[count].name[0] != 0) + { + ret = strncmp(dev_info_list[count].name,name,dev_info_list[count].len ); + dbgprintf("'%s'",dev_info_list[count].name); + if (!ret) + return dev_info_list[count].devtype; + count++; + } + return IOPMGR_DEVTYPE_INVALID; +} + +/** Get device list. + * @ingroup ps2netfs + * + * @param buffer Pointer to dest buffer + * @return number of devices returned. + */ +int devscan_getdevlist(char *buffer) +{ + int count; + int i; + char *bufptr = buffer; + + dbgprintf("devscan: getdevlist\n"); + /* rescan for devices, before returning list */ + count = devscan_setup(DEVSCAN_MASK); + + /* now convert this list into the right format */ + for (i=0;i +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + + +/* Please keep these in alphabetical order! */ +#include "ioman_mod.h" +#include "iomanX.h" +#include "loadcore.h" +#include "ps2ip.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thsemap.h" + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2_fio.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2_fio.c new file mode 100644 index 0000000..4976315 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2_fio.c @@ -0,0 +1,2106 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * iop tcp fs driver. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ps2_fio.h" +#include "ps2fs.h" +#include "byteorder.h" +#include "devscan.h" + +//#define DEBUG +//#define DEBUG +#ifdef DEBUG +#define dbgprintf(args...) printf(args) +#else +#define dbgprintf(args...) do { } while(0) +#endif + +////////////////////////////////////////////////////////////////////////// +// How about a header file?.. +extern int fsysUnmount(void); + +////////////////////////////////////////////////////////////////////////// +#define PACKET_MAXSIZE 4096 + +static char ps2netfs_send_packet[PACKET_MAXSIZE] __attribute__((aligned(16))); +static char ps2netfs_recv_packet[PACKET_MAXSIZE] __attribute__((aligned(16))); + +static int ps2netfs_sock = -1; +static int ps2netfs_active = 0; + +static int ps2netfs_sema; +static int ps2netfs_pid = 0; + +#define FIOTRAN_MAXSIZE 65535 +static char ps2netfs_fiobuffer[FIOTRAN_MAXSIZE+1]; + +////////////////////////////////////////////////////////////////////////// + +/** File Descriptor Handler functions + * @ingroup ps2netfs + * + * Handles upto FDH_MAXFD open files concurrently. + */ +typedef struct { + int used; + int realfd; + int devtype; +} fd_table_t; + +#define FDH_MAX 50 +static fd_table_t fd_info_list[FDH_MAX+1]; /* one for padding */ + +/** Initialise the file descriptor table. + * @ingroup ps2netfs + * + * This initialises the file descriptor table that we + * use to translate to numbers passed to client, and to + * enable quick lookups on handler type. + */ +static inline void fdh_setup() +{ + memset(&fd_info_list,0,sizeof(fd_info_list)); +} + +/** Get file descriptor for client. + * @ingroup ps2netfs + * + * @param devtype Device Manager type. + * @param fd PS2 file descriptor. + * @return FD to send to client. + * + * return values: + * -1 if no space in list. + * FD if returning valid entry. + */ +static inline int fdh_getfd(int devtype,int fd) +{ + int count = 1; + while ((count < FDH_MAX)) + { + if (fd_info_list[count].used == 0) + { + fd_info_list[count].used = 1; + fd_info_list[count].realfd = fd; + fd_info_list[count].devtype = devtype; + return count; + } + count++; + } + return -1; +} + +/** Free file descriptor from client table. + * @ingroup ps2netfs + * + * @param fd client file descriptor. + */ +static inline void fdh_freefd(int fd) +{ + if (fd < FDH_MAX) + { + fd_info_list[fd].used = 0; + fd_info_list[fd].realfd = 0; + fd_info_list[fd].devtype = 0; + } +} + +/** Get fd list entry. */ +#define fdh_get(a) (&fd_info_list[a]) +/** Get fd list entry used value. */ +#define fdh_getused(a) (fd_info_list[a].used) +/** Get fd list entry type value. */ +#define fdh_getfdtype(a) (fd_info_list[a].devtype) +/** Get fd list entry ps2 file descriptor value. */ +#define fdh_getrealfd(a) (fd_info_list[a].realfd) + + +/** changes mode from ioman to iomanx format + * @ingroup ps2netfs + */ +static inline int convmode_to_iomanx(int stat) +{ + int mode = 0; + + if FIO_SO_ISLNK(stat) mode |= FIO_S_IFLNK; // Symbolic link + if FIO_SO_ISREG(stat) mode |= FIO_S_IFREG; // regular file + if FIO_SO_ISDIR(stat) mode |= FIO_S_IFDIR; // directory + + if (((stat) & FIO_SO_IROTH) == FIO_SO_IROTH) // read + mode |= FIO_S_IRUSR | FIO_S_IRGRP | FIO_S_IROTH; + if (((stat) & FIO_SO_IWOTH) == FIO_SO_IWOTH) // write + mode |= FIO_S_IWUSR | FIO_S_IWGRP | FIO_S_IWOTH; + if (((stat) & FIO_SO_IXOTH) == FIO_SO_IXOTH) // execute + mode |= FIO_S_IXUSR | FIO_S_IXGRP | FIO_S_IXOTH; + + return mode; +} + +/** changes mode from iomanx to ioman format + * @ingroup ps2netfs + */ +static inline int convmode_from_iomanx(int stat) +{ + return stat; +} + +/** Shortcut to close the socket and cleanup. + * @ingroup ps2netfs + * + * @return disconnect return value. + */ +int ps2netfs_close_socket(void) +{ + int ret; + + ret = disconnect(ps2netfs_sock); + if (ret < 0) + printf("ps2netfs: disconnect returned error %d\n", ret); + ps2netfs_sock = -1; + return ret; +} + +/** Shortcut to close the socket forcibly and set to exit (active=0). + * @ingroup ps2netfs + * + * This will close down the socket, and cause the server thread to exit. + * + * @return disconnect return value. + */ +void ps2netfs_close_fsys(void) +{ + if (ps2netfs_sock > 0) + disconnect(ps2netfs_sock); + ps2netfs_active = 0; + return; +} + +//---------------------------------------------------------------------- +// XXX: Hm, this func should behave sorta like pko_recv_bytes imho.. +// i.e. check if it was able to send just a part of the packet etc.. +static inline int ps2netfs_lwip_send(int sock, void *buf, int len, int flag) +{ + int ret; + ret = send(sock, buf, len, flag); + if (ret < 0) + { + dbgprintf("ps2netfs: lwip_send() error %d\n", ret); + ps2netfs_close_socket(); + return -1; + } + else if (len == 0) + { // send is blocking, so 0 means error + dbgprintf("ps2netfs: lwip_send() - disconnected\n"); + return -2; + } + else return ret; +} + +/** Do repetetive recv() calls until 'bytes' bytes are received or error returned */ +int ps2netfs_recv_bytes(int sock, char *buf, int bytes) +{ + int left; + int len; + + left = bytes; + + while (left > 0) { + len = recv(sock, &buf[bytes - left], left, 0); + if (len < 0) { + dbgprintf("ps2netfs: recv_bytes error!! (%d)\n",len); + return -1; + } + if (len == 0) + { // recv is blocking, so 0 means error + dbgprintf("ps2netfs: recv_bytes - disconnected\n"); + return -2; + } + left -= len; + } + return bytes; +} + +/** Receive a 'packet' of unknown type, max size 4096 bytes */ +int ps2netfs_accept_pktunknown(int sock, char *buf) +{ + int length; + ps2netfs_pkt_hdr *hdr; +#ifdef DEBUG + unsigned int hcmd; +#endif + unsigned short hlen; + + dbgprintf("ps2netfs: accept_pkt\n"); + length = ps2netfs_recv_bytes(sock, buf, sizeof(ps2netfs_pkt_hdr)); + if (length == 0) return 0; + if (length < 0) { + dbgprintf("ps2netfs: accept_pkt recv error\n"); + return -1; + } + + if (length < sizeof(ps2netfs_pkt_hdr)) { + dbgprintf("ps2netfs: XXX: did not receive a full header!!!! " + "Fix this! (%d)\n", length); + return -1; + } + + hdr = (ps2netfs_pkt_hdr *)buf; +#ifdef DEBUG + hcmd = ntohl(hdr->cmd); +#endif + hlen = ntohs(hdr->len); + + dbgprintf("ps2netfs: accept_pkt: got 0x%x , hlen: %d, length: %d\n", hcmd,hlen,length); + + if ((length > PACKET_MAXSIZE) || (hlen > PACKET_MAXSIZE)) + { + dbgprintf("ps2netfs: accept_pkt: hlen is too large!! " + "(%d,%d can only receive %d)\n", length,hlen, PACKET_MAXSIZE); + return -1; + } + + // get the actual packet data + length = ps2netfs_recv_bytes(sock, buf + sizeof(ps2netfs_pkt_hdr), + hlen - sizeof(ps2netfs_pkt_hdr)); + + if (length < 0) { + dbgprintf("ps2netfs: accept recv2 error!!\n"); + return -1; + } + + if (length < (hlen - sizeof(ps2netfs_pkt_hdr))) { + dbgprintf("ps2netfs: Did not receive full packet!!! " + "Fix this! (%d)\n", length); + } + + return hlen; +} + +/** Handles a PS2NETFS_INFO_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -1 if error. + * 0 if handled ok. + */ +static int ps2netfs_op_info(char *buf, int len) +{ +// ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_info_rly *inforly; + int count; + +// cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: info\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + inforly = (ps2netfs_pkt_info_rly *)&ps2netfs_send_packet[0]; + + // do the stuff here + count = 0; + + // now build the response + + // Build packet + inforly->cmd = htonl(PS2NETFS_INFO_RLY); + inforly->len = htons((unsigned short)sizeof(ps2netfs_pkt_info_rly)); + inforly->retval = htonl(count); + inforly->count = htonl(count); + + if (ps2netfs_lwip_send(ps2netfs_sock, inforly, sizeof(ps2netfs_pkt_info_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_FSTYPE_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -1 if error. + * 0 if handled ok. + */ +static int ps2netfs_op_fstype(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_file_rly *openrly; + int devtype = -1; + + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: fstype\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + // do the stuff here + devtype = devscan_gettype(cmd->path); + + // now build the response + openrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + openrly->cmd = htonl(PS2NETFS_OPEN_RLY); + openrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + openrly->retval = htonl(devtype); + + if (ps2netfs_lwip_send(ps2netfs_sock, openrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_DEVLIST_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -1 if error. + * 0 if handled ok. + */ +static int ps2netfs_op_devlist(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_devlist_rly *devlistrly; + int count; + + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: devlist\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + devlistrly = (ps2netfs_pkt_devlist_rly *)&ps2netfs_send_packet[0]; + + // do the stuff here + count = devscan_getdevlist(devlistrly->list); + + // first char of the path passed in is the delimiter + { // so fudge in the delimiters + int cnt; char *ptr = &devlistrly->list[0]; int len; + for(cnt=0;cnt<(count-1);cnt++) + { + len = strlen(ptr); + // ok, got a string, so replace the final 0, with delimiter + // move onto next string + *(ptr+len) = cmd->path[0]; + ptr += len + 1; + } + } + + // now build the response + + // Build packet + devlistrly->cmd = htonl(PS2NETFS_DEVLIST_RLY); + devlistrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_devlist_rly)); + devlistrly->retval = htonl(count); + devlistrly->count = htonl(count); + + if (ps2netfs_lwip_send(ps2netfs_sock, devlistrly, sizeof(ps2netfs_pkt_devlist_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + + +/** Handles a PS2NETFS_OPEN_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int open(const char *name, int flags, ...); +static int ps2netfs_op_open(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_file_rly *openrly; + int retval = -ENODEV; + int devtype = 0; + + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: open\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + // do the stuff here + devtype = devscan_gettype(cmd->path); + if (devtype != IOPMGR_DEVTYPE_INVALID) + { + if (devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_open(cmd->path,ntohl(cmd->flags)); + else if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = open(cmd->path,ntohl(cmd->flags),0644); + if (retval > 0) + retval = fdh_getfd(devtype,retval); + } + + // now build the response + openrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + openrly->cmd = htonl(PS2NETFS_OPEN_RLY); + openrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + openrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, openrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_CLOSE_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * >=0 if handled ok. + * -X if error. + */ +// int close(int fd); +static int ps2netfs_op_close(char *buf, int len) +{ + ps2netfs_pkt_close_req *cmd; + ps2netfs_pkt_file_rly *closerly; + int retval = -1; + fd_table_t *fdptr; + cmd = (ps2netfs_pkt_close_req *)buf; + + dbgprintf("ps2netfs: close\n"); + + if (len != sizeof(ps2netfs_pkt_close_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // do the stuff here + fdptr = fdh_get(ntohl(cmd->fd)); + if (fdptr != 0) + { + if (fdptr->devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_close(fdptr->realfd); + else if (fdptr->devtype == IOPMGR_DEVTYPE_IOMANX) + retval = close(fdptr->realfd); + fdh_freefd(ntohl(cmd->fd)); + } + + // now build the response + closerly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + closerly->cmd = htonl(PS2NETFS_CLOSE_RLY); + closerly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + closerly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, closerly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_READ_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * >=0 if handled ok , bytes read. + * -X if error. + */ +// int read(int fd, void *ptr, size_t size); +static int ps2netfs_op_read(char *buf, int len) +{ + ps2netfs_pkt_read_req *cmd; + ps2netfs_pkt_read_rly *readrly; + int retval = -1; + int nbytes; + fd_table_t *fdptr; + cmd = (ps2netfs_pkt_read_req *)buf; + + dbgprintf("ps2netfs: read\n"); + + if (len != sizeof(ps2netfs_pkt_read_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + // limit read request to 64k + nbytes = ntohl(cmd->nbytes); + if (nbytes > FIOTRAN_MAXSIZE) nbytes = FIOTRAN_MAXSIZE; + + // do the stuff here + fdptr = fdh_get(ntohl(cmd->fd)); + if (fdptr != 0) + { + if (fdptr->devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_read(fdptr->realfd,ps2netfs_fiobuffer,nbytes); + else if (fdptr->devtype == IOPMGR_DEVTYPE_IOMANX) + retval = read(fdptr->realfd,ps2netfs_fiobuffer,nbytes); + } + + // now build the response + readrly = (ps2netfs_pkt_read_rly *)&ps2netfs_send_packet[0]; + + // Build packet + readrly->cmd = htonl(PS2NETFS_READ_RLY); + readrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_read_rly)); + readrly->retval = htonl(retval); + readrly->nbytes = readrly->retval; + + // send the response + if (ps2netfs_lwip_send(ps2netfs_sock, readrly, sizeof(ps2netfs_pkt_read_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + // now send the data + if (retval > 0) + if (ps2netfs_lwip_send(ps2netfs_sock, ps2netfs_fiobuffer, ntohl(readrly->retval), 0) < 0) + { + dbgprintf("ps2netfs: error sending data!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_WRITE_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * >=0 if handled ok , bytes written. + * -X if error. + */ +// int write(int fd, void *ptr, size_t size); +static int ps2netfs_op_write(char *buf, int len) +{ + ps2netfs_pkt_write_req *cmd; + ps2netfs_pkt_file_rly *writerly; + int retval = -1; + fd_table_t *fdptr; + cmd = (ps2netfs_pkt_write_req *)buf; + + dbgprintf("ps2netfs: write\n"); + + // do the stuff here + fdptr = fdh_get(ntohl(cmd->fd)); + if (fdptr != 0) + { + int left = ntohl(cmd->nbytes); + int towrite, written; + written = retval = 0; + while ((retval >= 0) && (left > 0)) + { + towrite = left; if (towrite > FIOTRAN_MAXSIZE) towrite = FIOTRAN_MAXSIZE; + if (ps2netfs_recv_bytes(ps2netfs_sock, ps2netfs_fiobuffer, towrite) <=0 ) + { + dbgprintf("ps2netfs: error reading data!\n"); + return -1; + } + + if (fdptr->devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_write(fdptr->realfd,ps2netfs_fiobuffer,towrite); + else if (fdptr->devtype == IOPMGR_DEVTYPE_IOMANX) + retval = write(fdptr->realfd,ps2netfs_fiobuffer,towrite); + + if (retval > 0) { written += retval; left -= retval; } + } + if (retval > 0) + retval = written; + } + + // now build the response + writerly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + writerly->cmd = htonl(PS2NETFS_WRITE_RLY); + writerly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + writerly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, writerly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_LSEEK_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * >=0 if handled ok , position. + * -X if error. + */ +// int lseek(int fd, int offset, int mode); +static int ps2netfs_op_lseek(char *buf, int len) +{ + ps2netfs_pkt_lseek_req *cmd; + ps2netfs_pkt_file_rly *lseekrly; + fd_table_t *fdptr; + int retval = -ENODEV; + cmd = (ps2netfs_pkt_lseek_req *)buf; + + dbgprintf("ps2netfs: lseek\n"); + + if (len != sizeof(ps2netfs_pkt_lseek_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + // do the stuff here + fdptr = fdh_get(ntohl(cmd->fd)); + if (fdptr != 0) + { + if (fdptr->devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_lseek(fdptr->realfd,ntohl(cmd->offset),ntohl(cmd->whence)); + else if (fdptr->devtype == IOPMGR_DEVTYPE_IOMANX) + retval = lseek(fdptr->realfd,ntohl(cmd->offset),ntohl(cmd->whence)); + } + + // now build the response + lseekrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + lseekrly->cmd = htonl(PS2NETFS_LSEEK_RLY); + lseekrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + lseekrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, lseekrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_IOCTL_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * >=0 if handled ok. + * -X if error. + */ +// int ioctl(int fd, unsigned long cmd, void *param); +static int ps2netfs_op_ioctl(char *buf, int len) +{ + ps2netfs_pkt_ioctl_req *cmd; + ps2netfs_pkt_ioctl_rly *ioctlrly; + fd_table_t *fdptr; + int retval = -ENODEV; + cmd = (ps2netfs_pkt_ioctl_req *)buf; + + dbgprintf("ps2netfs: ioctl\n"); + + if (len != sizeof(ps2netfs_pkt_ioctl_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + // now build the response + ioctlrly = (ps2netfs_pkt_ioctl_rly *)&ps2netfs_send_packet[0]; + + // do the stuff here + fdptr = fdh_get(ntohl(cmd->fd)); + if (fdptr != 0) + { + if (fdptr->devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_ioctl(fdptr->realfd,ntohl(cmd->command),(void *)ioctlrly->buf); + else if (fdptr->devtype == IOPMGR_DEVTYPE_IOMANX) + retval = ioctl(fdptr->realfd,ntohl(cmd->command),(void *)ioctlrly->buf); + } + + // Build packet + ioctlrly->cmd = htonl(PS2NETFS_IOCTL_RLY); + ioctlrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_ioctl_rly)); + ioctlrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, ioctlrly, sizeof(ps2netfs_pkt_ioctl_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_REMOVE_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * >=0 if handled ok. + * -X if error. + */ +// int remove(const char *name); +static int ps2netfs_op_remove(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_file_rly *removerly; + int retval = -ENODEV; + int devtype; + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: remove\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // do the stuff here + devtype = devscan_gettype(cmd->path); + if (devtype != IOPMGR_DEVTYPE_INVALID) + { + if (devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_remove(cmd->path); + else if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = remove(cmd->path); + } + + // now build the response + removerly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + removerly->cmd = htonl(PS2NETFS_REMOVE_RLY); + removerly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + removerly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, removerly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_MKDIR_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * >=0 if handled ok. + * -X if error. + */ +// int mkdir(const char *path, ...); +static int ps2netfs_op_mkdir(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_file_rly *mkdirrly; + int retval = -19; + int devtype; + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: mkdir\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // do the stuff here + devtype = devscan_gettype(cmd->path); + if (devtype != IOPMGR_DEVTYPE_INVALID) + { + if (devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_mkdir(cmd->path); + else if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = mkdir(cmd->path,0644); + } + + // now build the response + mkdirrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + mkdirrly->cmd = htonl(PS2NETFS_MKDIR_RLY); + mkdirrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + mkdirrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, mkdirrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_RMDIR_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * >=0 if handled ok. + * -X if error. + */ +// int rmdir(const char *path); +static int ps2netfs_op_rmdir(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_file_rly *rmdirrly; + int retval = -ENODEV; + int devtype; + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: remove\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // do the stuff here + devtype = devscan_gettype(cmd->path); + if (devtype != IOPMGR_DEVTYPE_INVALID) + { + if (devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_rmdir(cmd->path); + else if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = rmdir(cmd->path); + } + + // now build the response + rmdirrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + rmdirrly->cmd = htonl(PS2NETFS_RMDIR_RLY); + rmdirrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + rmdirrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, rmdirrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_DOPEN_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int dopen(const char *path); +static int ps2netfs_op_dopen(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_file_rly *dopenrly; + int retval = -ENODEV; + int devtype; + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: dopen\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // do the stuff here + devtype = devscan_gettype(cmd->path); + if (devtype != IOPMGR_DEVTYPE_INVALID) + { + if (devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_dopen(cmd->path,0); + else if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = dopen(cmd->path); + if (retval > 0) + retval = fdh_getfd(devtype,retval); + } + + // now build the response + dopenrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + dopenrly->cmd = htonl(PS2NETFS_DOPEN_RLY); + dopenrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + dopenrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, dopenrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_DCLOSE_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * >=0 if handled ok. + * -X if error. + */ +// int dclose(int fd); +static int ps2netfs_op_dclose(char *buf, int len) +{ + ps2netfs_pkt_close_req *cmd; + ps2netfs_pkt_file_rly *closerly; + fd_table_t *fdptr; + int retval = -ENODEV; + cmd = (ps2netfs_pkt_close_req *)buf; + + dbgprintf("ps2netfs: dclose\n"); + + if (len != sizeof(ps2netfs_pkt_close_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // do the stuff here + fdptr = fdh_get(ntohl(cmd->fd)); + if (fdptr != 0) + { + if (fdptr->devtype == IOPMGR_DEVTYPE_IOMAN) + retval = io_dclose(fdptr->realfd); + else if (fdptr->devtype == IOPMGR_DEVTYPE_IOMANX) + retval = dclose(fdptr->realfd); + if (retval == 0) fdh_freefd(ntohl(cmd->fd)); + } + + // now build the response + closerly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + closerly->cmd = htonl(PS2NETFS_DCLOSE_RLY); + closerly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + closerly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, closerly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_DREAD_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * >=0 if handled ok. + * -X if error. + */ +// int dread(int fd, void *buf); +static int ps2netfs_op_dread(char *buf, int len) +{ + ps2netfs_pkt_dread_req *cmd; + ps2netfs_pkt_dread_rly *dreadrly; + fd_table_t *fdptr; + int retval = -ENODEV; + cmd = (ps2netfs_pkt_dread_req *)buf; + + dbgprintf("ps2netfs: dread\n"); + + if (len != sizeof(ps2netfs_pkt_dread_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // get response structure ready for filling + dreadrly = (ps2netfs_pkt_dread_rly *)&ps2netfs_send_packet[0]; + memset(dreadrly,0,sizeof(ps2netfs_pkt_dread_rly)); + + // do the stuff here + fdptr = fdh_get(ntohl(cmd->fd)); + if (fdptr != 0) + { + if (fdptr->devtype == IOPMGR_DEVTYPE_IOMAN) + { + io_dirent_t dirent; + retval = io_dread(fdptr->realfd,&dirent); + if (retval > 0) + { + dreadrly->mode = htonl(convmode_to_iomanx(dirent.stat.mode)); + dreadrly->attr = htonl(dirent.stat.attr); + dreadrly->size = htonl(dirent.stat.size); + dreadrly->hisize = htonl(0); + memcpy(dreadrly->ctime,dirent.stat.ctime,8*3); + strncpy(dreadrly->name,dirent.name,255); + dreadrly->name[255] = '\0'; + } + } + else if (fdptr->devtype == IOPMGR_DEVTYPE_IOMANX) + { + iox_dirent_t dirent; + retval = dread(fdptr->realfd,&dirent); + if (retval > 0) + { + dreadrly->mode = htonl(dirent.stat.mode); + dreadrly->attr = htonl(dirent.stat.attr); + dreadrly->size = htonl(dirent.stat.size); + dreadrly->hisize = htonl(0); + memcpy(dreadrly->ctime,dirent.stat.ctime,8*3); + strncpy(dreadrly->name,dirent.name,255); + dreadrly->name[255] = '\0'; + } + } + } + dbgprintf("ps2netfs: dread '%s' %d\n",dreadrly->name,dreadrly->size); + // Build packet + dreadrly->cmd = htonl(PS2NETFS_DREAD_RLY); + dreadrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_dread_rly)); + dreadrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, dreadrly, sizeof(ps2netfs_pkt_dread_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_GETSTAT_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int getstat(const char *name, void *stat); +static int ps2netfs_op_getstat(char *buf, int len) +{ + return -1; +} + +/** Handles a PS2NETFS_CHSTAT_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int chstat(const char *name, void *stat, unsigned int statmask); +static int ps2netfs_op_chstat(char *buf, int len) +{ + return -1; +} + +/** Handles a PS2NETFS_FORMAT_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int format(const char *dev, const char *blockdev, void *arg, size_t arglen); +// #define PFS_ZONE_SIZE 8192 +// #define PFS_FRAGMENT 0x00000000 +// int Arg[3] = { PFS_ZONE_SIZE, 0x2d66, PFS_FRAGMENT }; +// retVal = fileXioFormat("pfs:", "hdd0:partition", (const char*)&Arg, sizeof(Arg)); + +#define PFS_ZONE_SIZE 8192 +#define PFS_FRAGMENT 0x00000000 +static int ps2netfs_op_format(char *buf, int len) +{ + ps2netfs_pkt_format_req *cmd; + ps2netfs_pkt_file_rly *formatrly; + int retval = -ENODEV; + int devtype = 0; + + cmd = (ps2netfs_pkt_format_req *)buf; + + dbgprintf("ps2netfs: format\n"); + + if (len != sizeof(ps2netfs_pkt_format_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + // do the stuff here + devtype = devscan_gettype(cmd->dev); + if (devtype == IOPMGR_DEVTYPE_IOMANX) + { // if other end has not set args, add some standard ones (hdd use only for mo) + if (ntohl(cmd->arglen) == 0) + { + int Arg[3] = { PFS_ZONE_SIZE, 0x2d66, PFS_FRAGMENT }; + retval = format(cmd->dev,cmd->blockdev,(char*)&Arg,sizeof(Arg)); + } + else retval = format(cmd->dev,cmd->blockdev,cmd->arg,ntohl(cmd->arglen)); + } + + // now build the response + formatrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + formatrly->cmd = htonl(PS2NETFS_FORMAT_RLY); + formatrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + formatrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, formatrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +// EXTENDED CALLS FROM HERE ON IN + +/** Handles a PS2NETFS_RENAME_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int rename(const char *old, const char *new); +static int ps2netfs_op_rename(char *buf, int len) +{ + ps2netfs_pkt_symlink_req *cmd; + ps2netfs_pkt_file_rly *renamerly; + int retval = -ENODEV; + int devtype; + cmd = (ps2netfs_pkt_symlink_req *)buf; + + dbgprintf("ps2netfs: rename\n"); + + if (len != sizeof(ps2netfs_pkt_symlink_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // check that both are iomanx devices + devtype = devscan_gettype(cmd->oldpath); + if (devtype == IOPMGR_DEVTYPE_IOMANX) + { + devtype = devscan_gettype(cmd->newpath); + if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = rename(cmd->oldpath,cmd->newpath); + else retval = -1; + } + // now build the response + renamerly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + renamerly->cmd = htonl(PS2NETFS_SYMLINK_RLY); + renamerly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + renamerly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, renamerly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1 ; + } + return 0; +} + +/** Handles a PS2NETFS_CHDIR_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int chdir(const char *name); +static int ps2netfs_op_chdir(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_file_rly *chdirrly; + int retval = -ENODEV; + int devtype; + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: chdir\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // do the stuff here + devtype = devscan_gettype(cmd->path); + if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = chdir(cmd->path); + + // now build the response + chdirrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + chdirrly->cmd = htonl(PS2NETFS_CHDIR_RLY); + chdirrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + chdirrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, chdirrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_SYNC_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int sync(const char *dev, int flag); +static int ps2netfs_op_sync(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_file_rly *syncrly; + int retval = -ENODEV; + int devtype; + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: sync\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // do the stuff here + devtype = devscan_gettype(cmd->path); + if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = sync(cmd->path,ntohl(cmd->flags)); + + // now build the response + syncrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + syncrly->cmd = htonl(PS2NETFS_SYNC_RLY); + syncrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + syncrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, syncrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1; + } + return 0; +} + +/** Handles a PS2NETFS_MOUNT_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int mount(const char *fsname, const char *devname, int flag, void *arg, size_t arglen); +static int ps2netfs_op_mount(char *buf, int len) +{ + ps2netfs_pkt_mount_req *cmd; + ps2netfs_pkt_file_rly *mountrly; + int retval = -ENODEV; + int devtype; + cmd = (ps2netfs_pkt_mount_req *)buf; + + dbgprintf("ps2netfs: mount\n"); + + if (len != sizeof(ps2netfs_pkt_mount_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // do the stuff here + devtype = devscan_gettype(cmd->fsname); + if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = mount(cmd->fsname,cmd->devname,ntohl(cmd->flag),cmd->arg,ntohl(cmd->arglen)); + + // now build the response + mountrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + mountrly->cmd = htonl(PS2NETFS_MOUNT_RLY); + mountrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + mountrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, mountrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1 ; + } + return 0; +} + +/** Handles a PS2NETFS_UMOUNT_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int umount(const char *fsname); +static int ps2netfs_op_umount(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_file_rly *umountrly; + int retval = -ENODEV; + int devtype; + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: umount\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // do the stuff here + devtype = devscan_gettype(cmd->path); + if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = umount(cmd->path); + + // now build the response + umountrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + umountrly->cmd = htonl(PS2NETFS_UMOUNT_RLY); + umountrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + umountrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, umountrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1 ; + } + return 0; +} + +/** Handles a PS2NETFS_LSEEK64_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int lseek64(int fd, long long offset, int whence); +static int ps2netfs_op_lseek64(char *buf, int len) +{ + return -1; +} + +/** Handles a PS2NETFS_DEVCTL_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int devctl(const char *name, int cmd, void *arg, size_t arglen, void *buf, size_t buflen); +static int ps2netfs_op_devctl(char *buf, int len) +{ + return -1; +} + +/** Handles a PS2NETFS_SYMLINK_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int symlink(const char *old, const char *new); +static int ps2netfs_op_symlink(char *buf, int len) +{ + ps2netfs_pkt_symlink_req *cmd; + ps2netfs_pkt_file_rly *symlinkrly; + int retval = -ENODEV; + int devtype; + cmd = (ps2netfs_pkt_symlink_req *)buf; + + dbgprintf("ps2netfs: symlink\n"); + + if (len != sizeof(ps2netfs_pkt_symlink_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // check that both are iomanx devices + devtype = devscan_gettype(cmd->oldpath); + if (devtype == IOPMGR_DEVTYPE_IOMANX) + { + devtype = devscan_gettype(cmd->newpath); + if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = symlink(cmd->oldpath,cmd->newpath); + else retval = -1; + } + // now build the response + symlinkrly = (ps2netfs_pkt_file_rly *)&ps2netfs_send_packet[0]; + + // Build packet + symlinkrly->cmd = htonl(PS2NETFS_SYMLINK_RLY); + symlinkrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_file_rly)); + symlinkrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, symlinkrly, sizeof(ps2netfs_pkt_file_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1 ; + } + return 0; +} + +/** Handles a PS2NETFS_READLINK_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int readlink(const char *path, char *buf, size_t buflen); +static int ps2netfs_op_readlink(char *buf, int len) +{ + ps2netfs_pkt_open_req *cmd; + ps2netfs_pkt_readlink_rly *readlinkrly; + int retval = -ENODEV; + int devtype; + cmd = (ps2netfs_pkt_open_req *)buf; + + dbgprintf("ps2netfs: readlink\n"); + + if (len != sizeof(ps2netfs_pkt_open_req)) + { + dbgprintf("ps2netfs: got a broken packet (%d)!\n", len); + return -1; + } + + // now build the response + readlinkrly = (ps2netfs_pkt_readlink_rly *)&ps2netfs_send_packet[0]; + + // do the stuff here + devtype = devscan_gettype(cmd->path); + if (devtype == IOPMGR_DEVTYPE_IOMANX) + retval = readlink(cmd->path,readlinkrly->path,cmd->flags); + + + // Build packet + readlinkrly->cmd = htonl(PS2NETFS_READLINK_RLY); + readlinkrly->len = htons((unsigned short)sizeof(ps2netfs_pkt_readlink_rly)); + readlinkrly->retval = htonl(retval); + + if (ps2netfs_lwip_send(ps2netfs_sock, readlinkrly, sizeof(ps2netfs_pkt_readlink_rly), 0) < 0) + { + dbgprintf("ps2netfs: error sending reply!\n"); + return -1 ; + } + return 0; +} + +/** Handles a PS2NETFS_IOCTL2_CMD request. + * @ingroup ps2netfs + * + * @param buf Pointer to packet data. + * @param len Length of packet. + * @return Status. + * + * status returns: + * 0 if all request and response handled ok. + * -X if error. + * + * return values for client: + * -19 (ENODEV) if device not found + * +X if handled ok, valid FD returned. + * -X if error. + */ +// int ioctl2(int fd, int cmd, void *arg, size_t arglen, void *buf, size_t buflen); +static int ps2netfs_op_ioctl2(char *buf, int len) +{ + return -1; +} + + +/** Listen for packets and handle them. + * @ingroup ps2netfs + * + * @param sock Socket to receive on. + * + * This function listens on the given socket for command packets. + * It loops until a socket error, or protocol error is found, then + * exits to the calling function, which should clean the socket up. + */ +static void ps2netfs_Listener(int sock) +{ + int done; + int len; + unsigned int cmd; + ps2netfs_pkt_hdr *header; + int retval; + + done = 0; + + while(!done) { + len = ps2netfs_accept_pktunknown(sock, &ps2netfs_recv_packet[0]); + + if (len > 0) + dbgprintf("ps2netfs: received packet (%d)\n", len); + + if (len < 0) { + dbgprintf("ps2netfs_Listener: recvfrom error (%d)\n", len); + return; + } + if (len >= sizeof(ps2netfs_pkt_hdr)) + { + header = (ps2netfs_pkt_hdr *)ps2netfs_recv_packet; + cmd = ntohl(header->cmd); + switch (cmd) + { + case PS2NETFS_OPEN_CMD: + retval = ps2netfs_op_open(ps2netfs_recv_packet, len); + break; + case PS2NETFS_CLOSE_CMD: + retval = ps2netfs_op_close(ps2netfs_recv_packet, len); + break; + case PS2NETFS_READ_CMD: + retval = ps2netfs_op_read(ps2netfs_recv_packet, len); + break; + case PS2NETFS_WRITE_CMD: + retval = ps2netfs_op_write(ps2netfs_recv_packet, len); + break; + case PS2NETFS_LSEEK_CMD: + retval = ps2netfs_op_lseek(ps2netfs_recv_packet, len); + break; + case PS2NETFS_IOCTL_CMD: + retval = ps2netfs_op_ioctl(ps2netfs_recv_packet, len); + break; + case PS2NETFS_REMOVE_CMD: + retval = ps2netfs_op_remove(ps2netfs_recv_packet, len); + break; + case PS2NETFS_MKDIR_CMD: + retval = ps2netfs_op_mkdir(ps2netfs_recv_packet, len); + break; + case PS2NETFS_RMDIR_CMD: + retval = ps2netfs_op_rmdir(ps2netfs_recv_packet, len); + break; + case PS2NETFS_DOPEN_CMD: + retval = ps2netfs_op_dopen(ps2netfs_recv_packet, len); + break; + case PS2NETFS_DCLOSE_CMD: + retval = ps2netfs_op_dclose(ps2netfs_recv_packet, len); + break; + case PS2NETFS_DREAD_CMD: + retval = ps2netfs_op_dread(ps2netfs_recv_packet, len); + break; + case PS2NETFS_GETSTAT_CMD: + retval = ps2netfs_op_getstat(ps2netfs_recv_packet, len); + break; + case PS2NETFS_CHSTAT_CMD: + retval = ps2netfs_op_chstat(ps2netfs_recv_packet, len); + break; + case PS2NETFS_FORMAT_CMD: + retval = ps2netfs_op_format(ps2netfs_recv_packet, len); + break; + case PS2NETFS_RENAME_CMD: + retval = ps2netfs_op_rename(ps2netfs_recv_packet, len); + break; + case PS2NETFS_CHDIR_CMD: + retval = ps2netfs_op_chdir(ps2netfs_recv_packet, len); + break; + case PS2NETFS_SYNC_CMD: + retval = ps2netfs_op_sync(ps2netfs_recv_packet, len); + break; + case PS2NETFS_MOUNT_CMD: + retval = ps2netfs_op_mount(ps2netfs_recv_packet, len); + break; + case PS2NETFS_UMOUNT_CMD: + retval = ps2netfs_op_umount(ps2netfs_recv_packet, len); + break; + case PS2NETFS_LSEEK64_CMD: + retval = ps2netfs_op_lseek64(ps2netfs_recv_packet, len); + break; + case PS2NETFS_DEVCTL_CMD: + retval = ps2netfs_op_devctl(ps2netfs_recv_packet, len); + break; + case PS2NETFS_SYMLINK_CMD: + retval = ps2netfs_op_symlink(ps2netfs_recv_packet, len); + break; + case PS2NETFS_READLINK_CMD: + retval = ps2netfs_op_readlink(ps2netfs_recv_packet, len); + break; + case PS2NETFS_IOCTL2_CMD: + retval = ps2netfs_op_ioctl2(ps2netfs_recv_packet, len); + break; + + case PS2NETFS_INFO_CMD: + retval = ps2netfs_op_info(ps2netfs_recv_packet, len); + break; + case PS2NETFS_FSTYPE_CMD: + retval = ps2netfs_op_fstype(ps2netfs_recv_packet, len); + break; + case PS2NETFS_DEVLIST_CMD: + retval = ps2netfs_op_devlist(ps2netfs_recv_packet, len); + break; + + default: + dbgprintf("ps2netfs: Unknown cmd received\n"); + retval = 0; + break; + } + if (retval == -1) + return; + } + else + { + dbgprintf("ps2netfs: packet too small (%d)\n", len); + return; + } + dbgprintf("ps2netfs: waiting for next pkt\n"); + } +} + +/** Main ps2netfs Thread. + * @ingroup ps2netfs + * + * @param argv Parameters to thread. + * @return Status. + * + * This is the main thread function for ps2netfs. It runs until + * 'ps2netfs_active' is set to 0. + * Handles accepting connections and passing them onto the listener + * function to handle them. + * + * status returns: + * 0 if exiting and finished. + * -1 if error starting thread. + */ +int +ps2netfs_serv(void *argv) +{ + struct sockaddr_in server_addr; + struct sockaddr_in client_addr; + int sock; + int client_sock; + int client_len; + int ret; + + dbgprintf(" - ps2netfs TCP Server -\n"); + + devscan_setup(DEVSCAN_MASK); + fdh_setup(); + + memset((void *)&server_addr, 0, sizeof(server_addr)); + // Should perhaps specify PC side ip.. + server_addr.sin_family = AF_INET; + server_addr.sin_addr.s_addr = htonl(INADDR_ANY); + server_addr.sin_port = htons(PS2NETFS_LISTEN_PORT); + + while ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + dbgprintf("ps2netfs: socket creation error (%d)\n", sock); + return -1; + } + + ret = bind(sock, (struct sockaddr *)&server_addr, + sizeof(server_addr)); + if (ret < 0) + { + dbgprintf("ps2netfs: bind error (%d)\n", ret); + ps2netfs_close_socket(); + return -1; + } + + ret = listen(sock, 5); + + if (ret < 0) + { + dbgprintf("ps2netfs: listen error (%d)\n", ret); + disconnect(sock); + return -1; + } + + // Active flag kinda sux, cause it wont be checked until a new client has + // connected.. But it's better than nothing and good for now at least + ps2netfs_active = 1; + + // Connection loop + while(ps2netfs_active) + { + dbgprintf("ps2netfs: Waiting for connection\n"); + + client_len = sizeof(client_addr); + client_sock = accept(sock, (struct sockaddr *)&client_addr, + &client_len); + if (client_sock < 0) + { + dbgprintf("ps2netfs: accept error (%d)", client_sock); + continue; + } + + dbgprintf("Client connected from %x\n", + client_addr.sin_addr.s_addr); + + if (ps2netfs_sock > 0) + { + dbgprintf("ps2netfs: Client reconnected\n"); + ret = ps2netfs_close_socket(); + dbgprintf("ps2netfs: close ret %d\n", ret); + continue; + } + ps2netfs_sock = client_sock; + + if (ps2netfs_sock > 0) + { + ps2netfs_Listener(ps2netfs_sock); + ret = ps2netfs_close_socket(); + dbgprintf("ps2netfs: close2 ret %d\n", ret); + continue; + } + } + + if (ps2netfs_sock > 0) + disconnect(ps2netfs_sock); + + disconnect(sock); + + ExitDeleteThread(); + return 0; +} + +/** Init ps2netfs. + * @ingroup ps2netfs + * + * @return Status (0=success, -1 = failure). + * + * This handles setting up the Thread, and starting it running. + */ +int ps2netfs_Init(void) +{ + iop_thread_t mythread; + int pid; + int i; + + dbgprintf("initializing ps2netfs\n"); + + // Start socket server thread + + mythread.attr = 0x02000000; // attr + mythread.option = 0; // option + mythread.thread = (void *)ps2netfs_serv; // entry + mythread.stacksize = 0x800; + mythread.priority = 0x43; // just above ps2link + + pid = CreateThread(&mythread); + + if (pid > 0) + { + if ((i=StartThread(pid, NULL)) < 0) + { + printf("StartThread failed (%d)\n", i); + return -1; + } + } + else + { + printf("ps2netfs: CreateThread failed (%d)\n", pid); + return -1; + } + + ps2netfs_pid = pid; + dbgprintf("ps2netfs: Thread id: %x\n", pid); + return 0; +} + +/** Shutdown ps2netfs. + * @ingroup ps2netfs + * + * This handles Stopping the thread and disconnecting. All shutdown + * for ps2netfs. + */ +int ps2fs_Destroy(void) +{ + WaitSema(ps2netfs_sema); + // ExitDeleteThread(ps2netfs_pid); + SignalSema(ps2netfs_sema); + DeleteSema(ps2netfs_sema); + return 0; +} + + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2_fio.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2_fio.h new file mode 100644 index 0000000..b7c7ebb --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2_fio.h @@ -0,0 +1,25 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Lame header. + */ + +#ifndef _PS2FIO_H_ +#define _PS2FIO_H_ + +// set this to enable it +#define PS2FIOINC + +int ps2netfs_Init( ); +int ps2netfs_Destroy(void); + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2fs.h b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2fs.h new file mode 100644 index 0000000..4592b10 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2fs.h @@ -0,0 +1,268 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Protocol and packet definitions for ps2netfs. + */ + +/** @defgroup ps2netfs ps2netfs - TCP fs driver */ + +#ifndef _PS2FS_H_ +#define _PS2FS_H_ + +#define PS2NETFS_LISTEN_PORT 0x4713 + +//from iomanx, all operations +// open +#define PS2NETFS_OPEN_CMD 0xbeef8011 +#define PS2NETFS_OPEN_RLY 0xbeef8012 +// close +#define PS2NETFS_CLOSE_CMD 0xbeef8021 +#define PS2NETFS_CLOSE_RLY 0xbeef8022 +// read +#define PS2NETFS_READ_CMD 0xbeef8031 +#define PS2NETFS_READ_RLY 0xbeef8032 +// write +#define PS2NETFS_WRITE_CMD 0xbeef8041 +#define PS2NETFS_WRITE_RLY 0xbeef8042 +// lseek +#define PS2NETFS_LSEEK_CMD 0xbeef8051 +#define PS2NETFS_LSEEK_RLY 0xbeef8052 +// ioctl +#define PS2NETFS_IOCTL_CMD 0xbeef8061 +#define PS2NETFS_IOCTL_RLY 0xbeef8062 +// remove +#define PS2NETFS_REMOVE_CMD 0xbeef8071 +#define PS2NETFS_REMOVE_RLY 0xbeef8072 +// mkdir +#define PS2NETFS_MKDIR_CMD 0xbeef8081 +#define PS2NETFS_MKDIR_RLY 0xbeef8082 +// rmdir +#define PS2NETFS_RMDIR_CMD 0xbeef8091 +#define PS2NETFS_RMDIR_RLY 0xbeef8092 +// dopen +#define PS2NETFS_DOPEN_CMD 0xbeef80A1 +#define PS2NETFS_DOPEN_RLY 0xbeef80A2 +// dclose +#define PS2NETFS_DCLOSE_CMD 0xbeef80B1 +#define PS2NETFS_DCLOSE_RLY 0xbeef80B2 +// dread +#define PS2NETFS_DREAD_CMD 0xbeef80C1 +#define PS2NETFS_DREAD_RLY 0xbeef80C2 +// getstat +#define PS2NETFS_GETSTAT_CMD 0xbeef80D1 +#define PS2NETFS_GETSTAT_RLY 0xbeef80D2 +// chstat +#define PS2NETFS_CHSTAT_CMD 0xbeef80E1 +#define PS2NETFS_CHSTAT_RLY 0xbeef80E2 +// format +#define PS2NETFS_FORMAT_CMD 0xbeef80F1 +#define PS2NETFS_FORMAT_RLY 0xbeef80F2 +// extended commands +// rename +#define PS2NETFS_RENAME_CMD 0xbeef8111 +#define PS2NETFS_RENAME_RLY 0xbeef8112 +// chdir +#define PS2NETFS_CHDIR_CMD 0xbeef8121 +#define PS2NETFS_CHDIR_RLY 0xbeef8122 +// sync +#define PS2NETFS_SYNC_CMD 0xbeef8131 +#define PS2NETFS_SYNC_RLY 0xbeef8132 +// mount +#define PS2NETFS_MOUNT_CMD 0xbeef8141 +#define PS2NETFS_MOUNT_RLY 0xbeef8142 +// umount +#define PS2NETFS_UMOUNT_CMD 0xbeef8151 +#define PS2NETFS_UMOUNT_RLY 0xbeef8152 +// lseek64 +#define PS2NETFS_LSEEK64_CMD 0xbeef8161 +#define PS2NETFS_LSEEK64_RLY 0xbeef8162 +// devctl +#define PS2NETFS_DEVCTL_CMD 0xbeef8171 +#define PS2NETFS_DEVCTL_RLY 0xbeef8172 +// symlink +#define PS2NETFS_SYMLINK_CMD 0xbeef8181 +#define PS2NETFS_SYMLINK_RLY 0xbeef8182 +// readlink +#define PS2NETFS_READLINK_CMD 0xbeef8191 +#define PS2NETFS_READLINK_RLY 0xbeef8192 +// ioctl2 +#define PS2NETFS_IOCTL2_CMD 0xbeef81A1 +#define PS2NETFS_IOCTL2_RLY 0xbeef81A2 +// added on +// info/status +#define PS2NETFS_INFO_CMD 0xbeef8F01 +#define PS2NETFS_INFO_RLY 0xbeef8F02 +// fstype +#define PS2NETFS_FSTYPE_CMD 0xbeef8F11 +#define PS2NETFS_FSTYPE_RLY 0xbeef8F12 +// devlist +#define PS2NETFS_DEVLIST_CMD 0xbeef8F21 +#define PS2NETFS_DEVLIST_RLY 0xbeef8F22 + +#define PS2NETFS_MAX_PATH 256 + +typedef struct +{ + unsigned int cmd; + unsigned short len; +} __attribute__((packed)) ps2netfs_pkt_hdr; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + unsigned int retval; +} __attribute__((packed)) ps2netfs_pkt_file_rly; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int flags; + char path[PS2NETFS_MAX_PATH]; +} __attribute__((packed)) ps2netfs_pkt_open_req; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int fd; +} __attribute__((packed)) ps2netfs_pkt_close_req; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int fd; + int nbytes; +} __attribute__((packed)) ps2netfs_pkt_read_req; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int retval; + int nbytes; +} __attribute__((packed)) ps2netfs_pkt_read_rly; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int fd; + int nbytes; +} __attribute__((packed)) ps2netfs_pkt_write_req; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int fd; + int offset; + int whence; +} __attribute__((packed)) ps2netfs_pkt_lseek_req; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int fd; + int command; +} __attribute__((packed)) ps2netfs_pkt_ioctl_req; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int retval; + char buf[PS2NETFS_MAX_PATH]; +} __attribute__((packed)) ps2netfs_pkt_ioctl_rly; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int fd; +} __attribute__((packed)) ps2netfs_pkt_dread_req; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int retval; + unsigned int mode; + unsigned int attr; + unsigned int size; + unsigned char ctime[8]; + unsigned char atime[8]; + unsigned char mtime[8]; + unsigned int hisize; + char name[PS2NETFS_MAX_PATH]; +} __attribute__((packed)) ps2netfs_pkt_dread_rly; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int retval; + int count; + char list[PS2NETFS_MAX_PATH]; +} __attribute__((packed)) ps2netfs_pkt_info_rly; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int retval; + int count; + char list[PS2NETFS_MAX_PATH]; +} __attribute__((packed)) ps2netfs_pkt_devlist_rly; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + char fsname[PS2NETFS_MAX_PATH]; + char devname[PS2NETFS_MAX_PATH]; + int flag; + char arg[PS2NETFS_MAX_PATH]; + int arglen; +} __attribute__((packed)) ps2netfs_pkt_mount_req; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int arglen; + char dev[PS2NETFS_MAX_PATH]; + char blockdev[PS2NETFS_MAX_PATH]; + char arg[PS2NETFS_MAX_PATH]; +} __attribute__((packed)) ps2netfs_pkt_format_req; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int flags; + char oldpath[PS2NETFS_MAX_PATH]; + char newpath[PS2NETFS_MAX_PATH]; +} __attribute__((packed)) ps2netfs_pkt_symlink_req; + +typedef struct +{ + unsigned int cmd; + unsigned short len; + int retval; + char path[PS2NETFS_MAX_PATH]; +} __attribute__((packed)) ps2netfs_pkt_readlink_rly; + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2netfs.c b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2netfs.c new file mode 100644 index 0000000..7723fcb --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/fs/netfs/src/ps2netfs.c @@ -0,0 +1,71 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * iop tcp fs driver. + */ + +#include +#include +#include + +#include +#include +#include +#include + +#include "ps2_fio.h" +#include "devscan.h" + +#define PS2NETFS_MODNAME "PS2_TcpFileDriver" +#define PS2NETFS_VERSION_HIGH 1 +#define PS2NETFS_VERSION_LOW 0 + +IRX_ID(PS2NETFS_MODNAME, PS2NETFS_VERSION_HIGH, PS2NETFS_VERSION_LOW); + +/** Entry point for IRX. + * @ingroup ps2netfs + * + * argc and argv make no difference to runstate. + * + * @param argc Number of arguments. + * @param argv Pointer to array of arguments. + * @return Module Status on Exit. + * + * return values: + * MODULE_RESIDENT_END if loaded and registered as library. + * MODULE_NO_RESIDENT_END if just exiting normally. + */ +int _start(int argc, char *argv[]) +{ + printf("%s - v%d.%d - Copyright (c) 2004 adresd\n", + PS2NETFS_MODNAME,PS2NETFS_VERSION_HIGH,PS2NETFS_VERSION_LOW); + + if (!devscan_getmodule(IOPMGR_IOMAN_IDENT)) + { + printf("ioman not found\n"); + return MODULE_NO_RESIDENT_END; + } + if (!devscan_getmodule(IOPMGR_IOMANX_IDENT)) + { + printf("iomanx not found\n"); + return MODULE_NO_RESIDENT_END; + } + + if (ps2netfs_Init() == 0) + { + printf("\nServer Started\n"); + return MODULE_RESIDENT_END; + } + + printf("\nExiting.\n"); + return MODULE_NO_RESIDENT_END; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/hdd/Makefile new file mode 100644 index 0000000..e6efff6 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/Makefile @@ -0,0 +1,12 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +SUBDIRS = apa apa-gpt apa-osd apa-xosd pfs pfs-osd pfs-xosd + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/Rules.make diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa-gpt/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa-gpt/Makefile new file mode 100644 index 0000000..9eae47a --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa-gpt/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/hdd/apa/src/ + +IOP_BIN ?= ps2hdd-gpt.irx + +IOP_CFLAGS += -DAPA_SUPPORT_GPT + +include $(PS2SDKSRC)/iop/hdd/apa/Makefile diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa-osd/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa-osd/Makefile new file mode 100644 index 0000000..b7a5bdf --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa-osd/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/hdd/apa/src/ + +IOP_BIN ?= ps2hdd-osd.irx + +IOP_CFLAGS += -DAPA_OSD_VER + +include $(PS2SDKSRC)/iop/hdd/apa/Makefile diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa-xosd/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa-xosd/Makefile new file mode 100644 index 0000000..b970466 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa-xosd/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/hdd/apa/src/ + +IOP_BIN ?= ps2hdd-xosd.irx + +IOP_CFLAGS += -DAPA_XOSD_VER + +include $(PS2SDKSRC)/iop/hdd/apa/Makefile diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/Makefile new file mode 100644 index 0000000..4ca9879 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/Makefile @@ -0,0 +1,26 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +LIBAPA_PATH = $(PS2SDKSRC)/iop/hdd/libapa/ + +LIBAPA_SRC_DIR = $(LIBAPA_PATH)src/ + +IOP_BIN ?= ps2hdd.irx + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/poweroff/include -I$(PS2SDKSRC)/iop/dev9/dev9/include -I$(PS2SDKSRC)/iop/dev9/atad/include -I$(LIBAPA_PATH)include + +APA_OBJS = password.o misc.o cache.o apa.o journal.o free.o +IOP_OBJS = hdd_fio.o hdd.o imports.o $(APA_OBJS) + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release + +$(IOP_OBJS_DIR)%.o: $(LIBAPA_SRC_DIR)%.c + $(IOP_CC) $(IOP_CFLAGS) -c $< -o $@ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/apa-opt.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/apa-opt.h new file mode 100644 index 0000000..c4be709 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/apa-opt.h @@ -0,0 +1,32 @@ +#ifndef _APA_OPT_H +#define _APA_OPT_H + +#define APA_PRINTF(format, ...) printf(format, ##__VA_ARGS__) +#define APA_DRV_NAME "hdd" + +/* Define APA_OSD_VER in your Makefile to build an OSD version, which will: + 1. (currently disabled) When formatting, do not create any partitions other than __mbr. + 2. __mbr will be formatted with its password. + 3. All partitions can be accessed, even without the right password. + 4. The starting LBA of the partition will be returned in + the private_5 field of the stat structure (returned by getstat and dread). */ + +#ifdef APA_XOSD_VER +#define APA_OSD_VER +#define APA_SUPPORT_BHDD +#endif + +#ifdef APA_OSD_VER +#define APA_STAT_RETURN_PART_LBA 1 +#define APA_FORMAT_LOCK_MBR 1 +#define APA_FORMAT_MAKE_PARTITIONS 1 // For now, define this because I don't think we're ready (and want to) deal with the official passwords. +#else +#define APA_ENABLE_PASSWORDS 1 +#define APA_FORMAT_MAKE_PARTITIONS 1 +#endif + +// Module version +#define APA_MODVER_MAJOR 2 +#define APA_MODVER_MINOR 5 + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd.c new file mode 100644 index 0000000..5a58aae --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd.c @@ -0,0 +1,341 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Start Up routines +*/ + +#include +#ifdef _IOP +#include +#include +#else +#include +#include +#endif +#include +#include +#include +#include +#include +#include + +#include "apa-opt.h" +#include +#include "hdd.h" +#include "hdd_fio.h" + +#ifdef _IOP +IRX_ID("hdd_driver", APA_MODVER_MAJOR, APA_MODVER_MINOR); +#endif + +static iop_device_ops_t hddOps={ + hddInit, + hddDeinit, + hddFormat, + hddOpen, + hddClose, + hddRead, + hddWrite, + hddLseek, + (void*)hddUnsupported, + hddRemove, + (void*)hddUnsupported, + (void*)hddUnsupported, + hddDopen, + hddClose, + hddDread, + hddGetStat, + (void*)hddUnsupported, + hddReName, + (void*)hddUnsupported, + (void*)hddUnsupported, + (void*)hddUnsupported, + (void*)hddUnsupported, + (void*)hddUnsupported, + hddDevctl, + (void*)hddUnsupported, + (void*)hddUnsupported, + hddIoctl2, +}; +static iop_device_t hddFioDev={ + "hdd", + IOP_DT_BLOCK | IOP_DT_FSEXT, + 1, + "HDD", + (struct _iop_device_ops *)&hddOps, +}; +#ifdef APA_SUPPORT_BHDD +static iop_device_t bhddFioDev={ + "bhdd", + IOP_DT_BLOCK | IOP_DT_FSEXT, + 1, + "HDD", + (struct _iop_device_ops *)&hddOps, +}; +#endif + +apa_device_t hddDevices[2]={ + {0, 0, 0, 3}, + {0, 0, 0, 3} +}; + +extern int apaMaxOpen; +extern hdd_file_slot_t *hddFileSlots; + +static int inputError(char *input); +static int unlockDrive(s32 device); +static void hddShutdownCb(void); +static int hddInitError(void); + +int hddCheckPartitionMax(s32 device, u32 size) +{ + return (hddDevices[device].partitionMaxSize >= size) ? 0 : -EINVAL; +} + +apa_cache_t *hddAddPartitionHere(s32 device, const apa_params_t *params, u32 *emptyBlocks, + u32 sector, int *err) +{ + apa_cache_t *clink_this; + apa_cache_t *clink_next; + apa_cache_t *clink_new; + apa_header_t *header; + u32 i; + u32 tmp, some_size, part_end; + u32 tempSize; + + // walk empty blocks in case can use one :) + for(i=0;i< 32;i++) + { + if((u32)(1 << i) >= params->size && emptyBlocks[i]!=0) + return apaInsertPartition(device, params, emptyBlocks[i], err); + } + clink_this=apaCacheGetHeader(device, sector, APA_IO_MODE_READ, err); + header=clink_this->header; + part_end=header->start+header->length; + some_size=(part_end%params->size); + tmp = some_size ? params->size - some_size : 0; + + if(hddDevices[device].totalLBA < (part_end + params->size + tmp) + //Non-SONY: when dealing with large disks, this check may overflow (therefore, check for overflows!). + || (part_end < sector)) + { + *err=-ENOSPC; + apaCacheFree(clink_this); + return NULL; + } + + if((clink_next=apaCacheGetHeader(device, 0, APA_IO_MODE_READ, err))==NULL) + { + apaCacheFree(clink_this); + return NULL; + } + + tempSize=params->size; + while(part_end%params->size) + { + tempSize=params->size>>1; + while(0x3FFFFheader->start, tempSize); + clink_this->header->next=part_end; + clink_this->flags|=APA_CACHE_FLAG_DIRTY; + clink_next->header->prev=clink_new->header->start; + part_end+=tempSize; + clink_next->flags|=APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(device); + apaCacheFree(clink_this); + clink_this=clink_new; + break; + } + tempSize>>=1; + } + } + if((clink_new=apaFillHeader(device, params, part_end, 0, clink_this->header->start, + params->size, err))!=NULL) + { + clink_this->header->next=part_end; + clink_this->flags|=APA_CACHE_FLAG_DIRTY; + clink_next->header->prev=clink_new->header->start; + clink_next->flags|=APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(device); + } + apaCacheFree(clink_this); + apaCacheFree(clink_next); + return clink_new; +} + +static int inputError(char *input) +{ + APA_PRINTF(APA_DRV_NAME": Error: Usage: %s [-o ] [-n ]\n", input); + return MODULE_NO_RESIDENT_END; +} + +static void printStartup(void) +{ + APA_PRINTF(APA_DRV_NAME": PS2 APA Driver v%d.%d (c) 2003 Vector\n", APA_MODVER_MAJOR, APA_MODVER_MINOR); + return; +} + +static int unlockDrive(s32 device) +{ + u8 id[32]; + int rv; + if((rv=apaGetIlinkID(id))==0) + return ata_device_sce_sec_unlock(device, id); + return rv; +} + +int _start(int argc, char **argv) +{ + int i, ret; + char *input; + int cacheSize=3; + apa_ps2time_t tm; + ata_devinfo_t *hddInfo; + + printStartup(); + + if((input=strrchr(argv[0], '/'))) + input++; + else + input=argv[0]; + + argc--; argv++; + while(argc) + { + if(argv[0][0] != '-') + break; + if(strcmp("-o", argv[0])==0) + { + argc--; argv++; + if(!argc) + return inputError(input); + i=strtol(argv[0], 0, 10); + if(i-1<32) + apaMaxOpen=i; + } + else if(strcmp("-n", argv[0])==0) + { + argc--; argv++; + if(!argc) + return inputError(input); + i=strtol(*argv, 0, 10); + if(cacheSizeexists!=0 && hddInfo->has_packet==0) + { + hddDevices[i].status--; + hddDevices[i].totalLBA=hddInfo->total_sectors; + hddDevices[i].partitionMaxSize=apaGetPartitionMax(hddInfo->total_sectors); + if(unlockDrive(i)==0) + hddDevices[i].status--; + APA_PRINTF(APA_DRV_NAME": disk%d: 0x%08lx sectors, max 0x%08lx\n", i, + hddDevices[i].totalLBA, hddDevices[i].partitionMaxSize); + } + } + hddFileSlots=apaAllocMem(apaMaxOpen*sizeof(hdd_file_slot_t)); + ret = (hddFileSlots == NULL) ? -ENOMEM : 0; + if(ret != 0) + { + APA_PRINTF(APA_DRV_NAME": error: file descriptor initialization failed.\n"); + return hddInitError(); + } + + memset(hddFileSlots, 0, apaMaxOpen*sizeof(hdd_file_slot_t)); + + if(apaCacheInit(cacheSize) != 0) + { + APA_PRINTF(APA_DRV_NAME": error: cache buffer initialization failed.\n"); + return hddInitError(); + } + + for(i=0;i < 2;i++) + { + if(hddDevices[i].status<2) + { + if(apaJournalRestore(i) != 0) + { + APA_PRINTF(APA_DRV_NAME": error: log check failed.\n"); + return hddInitError(); + } + if(apaGetFormat(i, &hddDevices[i].format)) + hddDevices[i].status--; + APA_PRINTF(APA_DRV_NAME": drive status %d, format version %08x\n", + hddDevices[i].status, hddDevices[i].format); + } + } + DelDrv("hdd"); + if(AddDrv(&hddFioDev) == 0) + { +#ifdef APA_SUPPORT_BHDD + DelDrv("bhdd"); + if(AddDrv(&bhddFioDev) == 0) +#endif + { +#if defined(APA_XOSD_VER) + APA_PRINTF(APA_DRV_NAME": version %04x driver start. This is XOSD LBA48 VERSION !!!!!!!!!!!\n", IRX_VER(APA_MODVER_MAJOR, APA_MODVER_MINOR)); +#elif defined(APA_OSD_VER) + APA_PRINTF(APA_DRV_NAME": version %04x driver start. This is OSD version!\n", IRX_VER(APA_MODVER_MAJOR, APA_MODVER_MINOR)); +#else + APA_PRINTF(APA_DRV_NAME": version %04x driver start.\n", IRX_VER(APA_MODVER_MAJOR, APA_MODVER_MINOR)); +#endif + return MODULE_RESIDENT_END; + } + } + { + APA_PRINTF(APA_DRV_NAME": error: add device failed.\n"); + return hddInitError(); + } +} + +static void hddShutdownCb(void) +{ + int i; + + for(i = 0; i < 2; i++) + { + if(hddDevices[i].status == 0) + ata_device_smart_save_attr(i); + } +} + +static int hddInitError(void) +{ + dev9RegisterShutdownCb(0, NULL); + return MODULE_NO_RESIDENT_END; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd.h new file mode 100644 index 0000000..e41db41 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd.h @@ -0,0 +1,31 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# HDD.IRX APA Header file +*/ + +#ifndef _HDD_H +#define _HDD_H + +typedef struct +{ + iop_file_t *f; // used to see if open... + u32 post; // offset/post.... + u16 nsub; + u16 type; + char id[APA_IDMAX]; + apa_sub_t parts[APA_MAXSUB+1]; // Partition data (0 = main partition, 1+ = sub-partition) +} hdd_file_slot_t; + +/////////////////////////////////////////////////////////////////////////////// +// Function declarations +int hddCheckPartitionMax(s32 device, u32 size); +apa_cache_t *hddAddPartitionHere(s32 device, const apa_params_t *params, u32 *EmptyBlocks, u32 sector, int *err); + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd_fio.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd_fio.c new file mode 100644 index 0000000..c12e0de --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd_fio.c @@ -0,0 +1,1071 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# APA File System routines +*/ + +#include +#ifdef _IOP +#include +#include +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include + +#include "apa-opt.h" +#include +#include "hdd.h" +#include "hdd_fio.h" + +hdd_file_slot_t *hddFileSlots; +int fioSema; +int apaMaxOpen = 1; + +extern const char apaMBRMagic[]; +extern apa_device_t hddDevices[]; + +#ifdef APA_FORMAT_MAKE_PARTITIONS +static const char *formatPartList[] = { + "__net", "__system", "__sysconf", "__common", NULL}; +#endif + +#define APA_NUMBER_OF_SIZES 9 +static const char *sizeList[APA_NUMBER_OF_SIZES] = { + "128M", "256M", "512M", "1G", "2G", "4G", "8G", "16G", "32G"}; + +/////////////////////////////////////////////////////////////////////////////// +// Function declarations +static int fioPartitionSizeLookUp(char *str); +static int fioInputBreaker(char const **arg, char *outBuf, int maxout); +static int fioDataTransfer(iop_file_t *f, void *buf, int size, int mode); +static int getFileSlot(apa_params_t *params, hdd_file_slot_t **fileSlot); +static int ioctl2Transfer(s32 device, hdd_file_slot_t *fileSlot, hddIoctl2Transfer_t *arg); +static void fioGetStatFiller(apa_cache_t *clink1, iox_stat_t *stat); +static int ioctl2AddSub(hdd_file_slot_t *fileSlot, char *argp); +static int ioctl2DeleteLastSub(hdd_file_slot_t *fileSlot); +static int devctlSwapTemp(s32 device, char *argp); + +static int fioPartitionSizeLookUp(char *str) +{ + int i; + + for (i = 0; i < APA_NUMBER_OF_SIZES; i++) { + if (strcmp(str, sizeList[i]) == 0) + return (256 * 1024) << i; + } + APA_PRINTF(APA_DRV_NAME ": Error: Invalid partition size, %s.\n", str); + return -EINVAL; +} + +static int fioInputBreaker(char const **arg, char *outBuf, int maxout) +{ + int len; + char *p; + + if ((p = strchr(arg[0], ','))) { + if (maxout < (len = p - arg[0])) + return -EINVAL; + memcpy(outBuf, arg[0], len); + arg[0] = p + 1; + while (arg[0][0] == ' ') + arg[0] += 1; + return 0; + } // else + if (maxout < (len = strlen(arg[0]))) + return -EINVAL; + memcpy(outBuf, arg[0], len); + arg[0] += len; + return 0; +} + +struct apaFsType +{ + const char *desc; + u16 type; +}; + +static int fioGetInput(const char *arg, apa_params_t *params) +{ + char argBuf[32]; + int rv = 0; + static const struct apaFsType fsTypes[] = { + {"EXT2SWAP", APA_TYPE_EXT2SWAP}, + {"EXT2", APA_TYPE_EXT2}, + {"REISER", APA_TYPE_REISER}, + {"PFS", APA_TYPE_PFS}, + {"CFS", APA_TYPE_CFS}, + }; + + if (params == NULL) + return -EINVAL; + memset(params, 0, sizeof(apa_params_t)); + + while (arg[0] == ' ') + arg++; + + if (arg[0] == 0 || arg[0] == ',') + return -EINVAL; + if ((rv = fioInputBreaker(&arg, params->id, APA_IDMAX)) != 0) + return rv; + if (arg[0] == '\0') // Return if there are no further parameters. + return 0; + + if ((rv = fioInputBreaker(&arg, params->fpwd, APA_PASSMAX)) != 0) + return rv; + + if (params->fpwd[0] != '\0') + apaEncryptPassword(params->id, params->fpwd, params->fpwd); + + if (arg[0] == '\0') // Return if there are no further parameters. + return 0; + + if ((rv = fioInputBreaker(&arg, params->rpwd, APA_PASSMAX)) != 0) + return rv; + + if (params->rpwd[0] != '\0') + apaEncryptPassword(params->id, params->rpwd, params->rpwd); + + if (arg[0] == '\0') // Return if there are no further parameters. + return 0; + + memset(argBuf, 0, sizeof(argBuf)); + if ((rv = fioInputBreaker(&arg, argBuf, sizeof(argBuf))) != 0) + return rv; + + if ((rv = fioPartitionSizeLookUp(argBuf)) < 0) + return rv; + params->size = rv; + + memset(argBuf, 0, sizeof(argBuf)); + if ((rv = fioInputBreaker(&arg, argBuf, sizeof(argBuf))) != 0) + return rv; + + // scan through fstypes if found none - error + for (int i = 0; i < 6; i++) { + if (i == 5) { + APA_PRINTF(APA_DRV_NAME ": error: Invalid fstype, %s.\n", argBuf); + return -EINVAL; + } else if (!strcmp(argBuf, fsTypes[i].desc)) { + params->type = fsTypes[i].type; + break; + } + } + + return rv; +} + +static int getFileSlot(apa_params_t *params, hdd_file_slot_t **fileSlot) +{ + int i; + + for (i = 0; i < apaMaxOpen; i++) { + if (hddFileSlots[i].f) + if (memcmp(hddFileSlots[i].id, ¶ms->id, APA_IDMAX) == 0) + return -EBUSY; // file is open + } + for (i = 0; i < apaMaxOpen; i++) { + if (!hddFileSlots[i].f) { + *fileSlot = &hddFileSlots[i]; + return 0; + } + } + return -EMFILE; // no file slots free :( +} + +static int fioDataTransfer(iop_file_t *f, void *buf, int size, int mode) +{ + hdd_file_slot_t *fileSlot = (hdd_file_slot_t *)f->privdata; + + if ((size & 0x1FF)) + return -EINVAL; + size >>= 9; // size/512 + + if (fileSlot->post + size >= 0x1FF9) // no over reading + size = 0x1FF8 - fileSlot->post; + + if (size != 0) { + int rv = 0; + + WaitSema(fioSema); + if (ata_device_sector_io(f->unit, buf, fileSlot->post + fileSlot->parts[0].start + 8, size, mode)) + rv = -EIO; + SignalSema(fioSema); + if (rv == 0) { + fileSlot->post += size; + return size << 9; + } + + return rv; + } + return 0; +} + +static int ioctl2Transfer(s32 device, hdd_file_slot_t *fileSlot, hddIoctl2Transfer_t *arg) +{ + if (fileSlot->nsub < arg->sub) + return -ENODEV; + + // main partitions can only be read starting from the 4MB offset. + if (arg->sub == 0 && (arg->sector < 0x2000)) + return -EINVAL; + // sub-partitions can only be read starting from after the header. + if (arg->sub != 0 && (arg->sector < 2)) + return -EINVAL; + + if (fileSlot->parts[arg->sub].length < arg->sector + arg->size) + return -ENXIO; + + if (ata_device_sector_io(device, arg->buffer, + fileSlot->parts[arg->sub].start + arg->sector, arg->size, arg->mode)) + return -EIO; + + return 0; +} + +int hddInit(iop_device_t *f) +{ + iop_sema_t sema; + + sema.attr = 1; + sema.initial = 1; + sema.max = 1; + sema.option = 0; + fioSema = CreateSema(&sema); + + return 0; +} + +int hddDeinit(iop_device_t *f) +{ + DeleteSema(fioSema); + return 0; +} + +int hddFormat(iop_file_t *f, const char *dev, const char *blockdev, void *arg, int arglen) +{ + int rv = 0; + apa_cache_t *clink; + u32 i; +#ifdef APA_FORMAT_MAKE_PARTITIONS + apa_params_t params; + u32 emptyBlocks[32]; +#endif + +#ifdef APA_SUPPORT_BHDD + if (strcmp(f->device->name, "bhdd") == 0) + return -ENODEV; +#endif + + if (f->unit >= 2) + return -ENXIO; + + // clear all errors on hdd + clink = apaCacheAlloc(); + memset(clink->header, 0, sizeof(apa_header_t)); + if (ata_device_sector_io(f->unit, clink->header, APA_SECTOR_SECTOR_ERROR, 1, ATA_DIR_WRITE)) { + apaCacheFree(clink); + return -EIO; + } + if (ata_device_sector_io(f->unit, clink->header, APA_SECTOR_PART_ERROR, 1, ATA_DIR_WRITE)) { + apaCacheFree(clink); + return -EIO; + } + // clear apa headers + for (i = 1024 * 8; i < hddDevices[f->unit].totalLBA; i += (1024 * 256)) { + ata_device_sector_io(f->unit, clink->header, i, sizeof(apa_header_t) / 512, + ATA_DIR_WRITE); + } + apaCacheFree(clink); + if ((rv = apaJournalReset(f->unit)) != 0) + return rv; + + // set up mbr :) + if ((clink = apaCacheGetHeader(f->unit, 0, APA_IO_MODE_WRITE, &rv))) { + apa_header_t *header = clink->header; + memset(header, 0, sizeof(apa_header_t)); + header->magic = APA_MAGIC; + header->length = (1024 * 256); // 128MB + header->type = APA_TYPE_MBR; + strcpy(header->id, "__mbr"); +#ifdef APA_FORMAT_LOCK_MBR + apaEncryptPassword(header->id, header->fpwd, "sce_mbr"); + apaEncryptPassword(header->id, header->rpwd, "sce_mbr"); +#endif + memcpy(header->mbr.magic, apaMBRMagic, sizeof(header->mbr.magic)); + + header->mbr.version = APA_MBR_VERSION; + header->mbr.nsector = 0; + apaGetTime(&header->created); + apaGetTime(&header->mbr.created); + +#ifdef APA_SUPPORT_GPT + header->mbr.protective_mbr.UniqueMbrSignature = 0; + header->mbr.protective_mbr.Unknown = 0; + header->mbr.protective_mbr.partition_record1.BootIndicator = 0; + header->mbr.protective_mbr.partition_record1.StartHead = 0; + header->mbr.protective_mbr.partition_record1.StartSector = 2; + header->mbr.protective_mbr.partition_record1.StartTrack = 0; + header->mbr.protective_mbr.partition_record1.OSIndicator = 0xEE; + header->mbr.protective_mbr.partition_record1.EndHead = 0xFF; + header->mbr.protective_mbr.partition_record1.EndSector = 0xFF; + header->mbr.protective_mbr.partition_record1.EndTrack = 0xFF; + header->mbr.protective_mbr.partition_record1.StartingLBA = 1; + header->mbr.protective_mbr.partition_record1.SizeInLBA = hddDevices[f->unit].totalLBA - header->mbr.protective_mbr.partition_record1.StartingLBA; + header->mbr.protective_mbr.Signature = 0xAA55; +#endif + + header->checksum = apaCheckSum(header, 1); + clink->flags |= APA_CACHE_FLAG_DIRTY; + apaCacheFlushDirty(clink); + ata_device_flush_cache(f->unit); + apaCacheFree(clink); + hddDevices[f->unit].status = 0; + hddDevices[f->unit].format = APA_MBR_VERSION; + } +#ifdef APA_FORMAT_MAKE_PARTITIONS + memset(&emptyBlocks, 0, sizeof(emptyBlocks)); + memset(¶ms, 0, sizeof(apa_params_t)); + params.size = (1024 * 256); + params.type = APA_TYPE_PFS; + + // add __net, __system.... + for (i = 0; formatPartList[i]; i++) { + memset(params.id, 0, APA_IDMAX); + strcpy(params.id, formatPartList[i]); + if (!(clink = hddAddPartitionHere(f->unit, ¶ms, emptyBlocks, i ? clink->sector : 0, &rv))) + return rv; + apaCacheFree(clink); + + params.size <<= 1; + if (hddDevices[f->unit].partitionMaxSize < params.size) + params.size = hddDevices[f->unit].partitionMaxSize; + } +#endif + return rv; +} + +static int apaOpen(s32 device, hdd_file_slot_t *fileSlot, apa_params_t *params, int mode) +{ + int rv = 0; + u32 emptyBlocks[32]; + apa_cache_t *clink; + apa_cache_t *clink2; + u32 sector = 0; + +#ifdef APA_SUPPORT_BHDD + if (strcmp(params->id, "__xcontents") == 0 || strcmp(params->id, "__extend") == 0 || strcmp(params->id, "__xdata") == 0) + sector = hddDevices[device].totalLBA; +#endif + + // walk all looking for any empty blocks & look for partition + clink = apaCacheGetHeader(device, sector, APA_IO_MODE_READ, &rv); + memset(&emptyBlocks, 0, sizeof(emptyBlocks)); + while (clink) { + sector = clink->sector; + if (!(clink->header->flags & APA_FLAG_SUB)) { + if (memcmp(clink->header->id, params->id, APA_IDMAX) == 0) + break; // found :) + } + apaAddEmptyBlock(clink->header, emptyBlocks); + clink = apaGetNextHeader(clink, &rv); + } + + if (rv != 0) + return rv; + rv = -ENOENT; + + if (clink == NULL && (mode & O_CREAT)) { + if ((rv = hddCheckPartitionMax(device, params->size)) >= 0) { + if ((clink = hddAddPartitionHere(device, params, emptyBlocks, sector, &rv)) != NULL) { + sector = clink->header->start; + clink2 = apaCacheAlloc(); + memset(clink2->header, 0, sizeof(apa_header_t)); + ata_device_sector_io(device, clink2->header, sector + 8, 2, ATA_DIR_WRITE); + ata_device_sector_io(device, clink2->header, sector + 0x2000, 2, ATA_DIR_WRITE); + apaCacheFree(clink2); + } + } + } + if (clink == NULL) + return rv; + fileSlot->parts[0].start = clink->header->start; + fileSlot->parts[0].length = clink->header->length; + memcpy(&fileSlot->parts[1], &clink->header->subs, APA_MAXSUB * sizeof(apa_sub_t)); + fileSlot->type = clink->header->type; + fileSlot->nsub = clink->header->nsub; + memcpy(&fileSlot->id, &clink->header->id, APA_IDMAX); + apaCacheFree(clink); + if (apaPassCmp(clink->header->fpwd, params->fpwd) != 0) { + rv = (!(mode & O_WRONLY)) ? apaPassCmp(clink->header->rpwd, params->rpwd) : -EACCES; + } else + rv = 0; + + return rv; +} + +static int apaRemove(s32 device, const char *id, const char *fpwd) +{ + u32 nsub; + apa_cache_t *clink; + apa_cache_t *clink2; + int rv, i; + + for (i = 0; i < apaMaxOpen; i++) // look to see if open + { + if (hddFileSlots[i].f != 0) { + if (memcmp(hddFileSlots[i].id, id, APA_IDMAX) == 0) + return -EBUSY; + } + } + if (id[0] == '_' && id[1] == '_') + return -EACCES; + if ((clink = apaFindPartition(device, id, &rv)) == NULL) + return rv; + if (apaPassCmp(clink->header->fpwd, fpwd)) { + apaCacheFree(clink); + return -EACCES; + } + // remove all subs first... + nsub = clink->header->nsub; + clink->header->nsub = 0; + clink->flags |= APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(device); + for (i = nsub - 1; i != -1; i--) { + if ((clink2 = apaCacheGetHeader(device, clink->header->subs[i].start, APA_IO_MODE_READ, &rv))) { + if ((rv = apaDelete(clink2))) { + apaCacheFree(clink); + return rv; + } + } + } + if (rv == 0) + return apaDelete(clink); + + apaCacheFree(clink); + return rv; +} + +// Unofficial helper for renaming APA partitions. +static int apaRename(s32 device, const apa_params_t *oldParams, const apa_params_t *newParams) +{ + apa_cache_t *clink; + int i, rv; + + // look to see if can make(newname) or not... + if ((clink = apaFindPartition(device, newParams->id, &rv)) != NULL) { + apaCacheFree(clink); + SignalSema(fioSema); + return -EEXIST; // File exists + } + + // look to see if open(oldname) + for (i = 0; i < apaMaxOpen; i++) { + if (hddFileSlots[i].f != NULL) { + if (memcmp(hddFileSlots[i].id, oldParams->id, APA_IDMAX) == 0) { + SignalSema(fioSema); + return -EBUSY; + } + } + } + + // Do not allow system partitions (__*) to be renamed. + if (oldParams->id[0] == '_' && oldParams->id[1] == '_') + return -EACCES; + + // find :) + if ((clink = apaFindPartition(device, oldParams->id, &rv)) == NULL) { + SignalSema(fioSema); + return rv; + } + + // Check for access rights. + if (apaPassCmp(clink->header->fpwd, oldParams->fpwd) != 0) { + apaCacheFree(clink); + return -EACCES; + } + + // do the renaming :) note: subs have no names!! + memcpy(clink->header->id, newParams->id, APA_IDMAX); + + // Update passwords + memcpy(clink->header->rpwd, newParams->rpwd, APA_PASSMAX); + memcpy(clink->header->fpwd, newParams->fpwd, APA_PASSMAX); + + clink->flags |= APA_CACHE_FLAG_DIRTY; + + apaCacheFlushAllDirty(device); + apaCacheFree(clink); + + return 0; +} + +int hddRemove(iop_file_t *f, const char *name) +{ + int rv; + apa_params_t params; + + if ((rv = fioGetInput(name, ¶ms)) < 0) + return rv; +#ifdef APA_SUPPORT_BHDD + if (strcmp(f->device->name, "bhdd") == 0) + return -EACCES; +#endif + WaitSema(fioSema); + rv = apaRemove(f->unit, params.id, params.fpwd); + SignalSema(fioSema); + + return rv; +} + +int hddOpen(iop_file_t *f, const char *name, int flags, int mode) +{ + int rv; + apa_params_t params; + hdd_file_slot_t *fileSlot; + + if (f->unit >= 2 || hddDevices[f->unit].status != 0) + return -ENODEV; + +#ifdef APA_SUPPORT_BHDD + if (strcmp(f->device->name, "bhdd") == 0) + if ((flags & O_CREAT) != 0) + return -EACCES; +#endif + + if (!(f->mode & O_DIROPEN)) + if ((rv = fioGetInput(name, ¶ms)) < 0) + return rv; + + WaitSema(fioSema); + if ((rv = getFileSlot(¶ms, &fileSlot)) == 0) { + if (!(f->mode & O_DIROPEN)) { + if ((rv = apaOpen(f->unit, fileSlot, ¶ms, flags)) == 0) { + fileSlot->f = f; + f->privdata = fileSlot; + } + } else { +#ifdef APA_SUPPORT_BHDD + if (strcmp(f->device->name, "bhdd") == 0) { + fileSlot->parts[0].start = hddDevices[f->unit].totalLBA; + } else { + fileSlot->parts[0].start = 0; + } +#endif + fileSlot->f = f; + f->privdata = fileSlot; + } + } + SignalSema(fioSema); + return rv; +} + +int hddClose(iop_file_t *f) +{ + WaitSema(fioSema); + memset(f->privdata, 0, sizeof(hdd_file_slot_t)); + SignalSema(fioSema); + return 0; +} + +int hddRead(iop_file_t *f, void *buf, int size) +{ + return fioDataTransfer(f, buf, size, ATA_DIR_READ); +} + +int hddWrite(iop_file_t *f, void *buf, int size) +{ + if (!(f->mode & O_WRONLY)) + return -EACCES; +#ifdef APA_SUPPORT_BHDD + if (strcmp(f->device->name, "bhdd") == 0) + return -EACCES; +#endif + return fioDataTransfer(f, buf, size, ATA_DIR_WRITE); +} + +int hddLseek(iop_file_t *f, int post, int whence) +{ + int rv = 0; + hdd_file_slot_t *fileSlot; + + // test input( no seeking to end point less :P ) + if (whence == SEEK_END) + return -EINVAL; + if ((post & 0x1FF)) + return -EINVAL; + + post >>= 9; // post/512 + + WaitSema(fioSema); + fileSlot = f->privdata; + if (whence == SEEK_CUR) { + if ((fileSlot->post + post) < 0 || (fileSlot->post + post) >= 0x1FF9) + rv = -EINVAL; + else { + fileSlot->post += post; + rv = fileSlot->post << 9; + } + } else if (whence == SEEK_SET) { + if (post < 0 || post >= 0x1FF9) + rv = -EINVAL; + else { + fileSlot->post = post; + rv = fileSlot->post << 9; + } + } + SignalSema(fioSema); + return rv; +} + +static void fioGetStatFiller(apa_cache_t *clink, iox_stat_t *stat) +{ + stat->mode = clink->header->type; + stat->attr = clink->header->flags; + stat->hisize = 0; + stat->size = clink->header->length; + memcpy(&stat->ctime, &clink->header->created, sizeof(apa_ps2time_t)); + memcpy(&stat->atime, &clink->header->created, sizeof(apa_ps2time_t)); + memcpy(&stat->mtime, &clink->header->created, sizeof(apa_ps2time_t)); + if (clink->header->flags & APA_FLAG_SUB) + stat->private_0 = clink->header->number; + else + stat->private_0 = clink->header->nsub; + stat->private_1 = 0; + stat->private_2 = 0; + stat->private_3 = 0; + stat->private_4 = 0; +#ifndef APA_STAT_RETURN_PART_LBA + stat->private_5 = 0; // game ver +#else + stat->private_5 = clink->header->start; // SONY ver (return start LBA of the partition) +#endif +} + +int hddGetStat(iop_file_t *f, const char *name, iox_stat_t *stat) +{ + apa_cache_t *clink; + apa_params_t params; + int rv; + + if ((rv = fioGetInput(name, ¶ms)) < 0) + return rv; + + WaitSema(fioSema); + if ((clink = apaFindPartition(f->unit, params.id, &rv))) { + if ((rv = apaPassCmp(clink->header->fpwd, params.fpwd)) == 0 || (rv = apaPassCmp(clink->header->rpwd, params.rpwd)) == 0) + fioGetStatFiller(clink, stat); + apaCacheFree(clink); + } + SignalSema(fioSema); + return rv; +} + +int hddDopen(iop_file_t *f, const char *name) +{ + return hddOpen(f, name, 0, 0); +} + +int hddDread(iop_file_t *f, iox_dirent_t *dirent) +{ + int rv; + hdd_file_slot_t *fileSlot = f->privdata; + apa_cache_t *clink; + + if (!(f->mode & O_DIROPEN)) + return -ENOTDIR; + + if (fileSlot->parts[0].start == -1) + return 0; // end :) + + WaitSema(fioSema); + if ((clink = apaCacheGetHeader(f->unit, fileSlot->parts[0].start, APA_IO_MODE_READ, &rv)) && + clink->header->length) { + if (clink->header->flags & APA_FLAG_SUB) { + // if sub get id from main header... + apa_cache_t *cmain = apaCacheGetHeader(f->unit, clink->header->main, APA_IO_MODE_READ, &rv); + if (cmain != NULL) { + /* This was the SONY original, which didn't do bounds-checking: + rv=strlen(cmain->header->id); + strcpy(dirent->name, cmain->header->id); */ + strncpy(dirent->name, cmain->header->id, APA_IDMAX); + dirent->name[APA_IDMAX] = '\0'; + rv = strlen(dirent->name); + + apaCacheFree(cmain); + } + } else { + /* This was the SONY original, which didn't do bounds-checking: + rv=strlen(clink->header->id); + strcpy(dirent->name, clink->header->id); */ + strncpy(dirent->name, clink->header->id, APA_IDMAX); + dirent->name[APA_IDMAX] = '\0'; + rv = strlen(dirent->name); + } + fioGetStatFiller(clink, &dirent->stat); + if (clink->header->next == 0) + fileSlot->parts[0].start = -1; // mark end + else + fileSlot->parts[0].start = clink->header->next; // set next + apaCacheFree(clink); + } + SignalSema(fioSema); + return rv; +} + +/* Originally, SONY provided no function for renaming partitions. + Syntax: rename , , + + The full-access password (fpwd) is required. + System partitions (__*) cannot be renamed. */ +int hddReName(iop_file_t *f, const char *oldname, const char *newname) +{ + apa_params_t oldParams; + apa_params_t newParams; + int rv; + + if ((rv = fioGetInput(oldname, &oldParams)) < 0) + return rv; + if ((rv = fioGetInput(newname, &newParams)) < 0) + return rv; + + WaitSema(fioSema); + rv = apaRename(f->unit, &oldParams, &newParams); + SignalSema(fioSema); + + return rv; +} + +static int ioctl2AddSub(hdd_file_slot_t *fileSlot, char *argp) +{ + int rv; + u32 device = fileSlot->f->unit; + apa_params_t params; + u32 emptyBlocks[32]; + apa_cache_t *clink; + u32 sector = 0; + u32 length; + + if (!(fileSlot->f->mode & O_WRONLY)) + return -EACCES; + + if (!(fileSlot->nsub < APA_MAXSUB)) + return -EFBIG; + + memset(¶ms, 0, sizeof(apa_params_t)); + + if ((rv = fioPartitionSizeLookUp(argp)) < 0) + return rv; + + params.size = rv; + params.flags = APA_FLAG_SUB; + params.type = fileSlot->type; + params.main = fileSlot->parts[0].start; + params.number = fileSlot->nsub + 1; + if ((rv = hddCheckPartitionMax(device, params.size)) < 0) + return rv; + + // walk all looking for any empty blocks + memset(&emptyBlocks, 0, sizeof(emptyBlocks)); + clink = apaCacheGetHeader(device, 0, APA_IO_MODE_READ, &rv); + while (clink) { + sector = clink->sector; + apaAddEmptyBlock(clink->header, emptyBlocks); + clink = apaGetNextHeader(clink, &rv); + } + if (rv != 0) + return rv; + + if (!(clink = hddAddPartitionHere(device, ¶ms, emptyBlocks, sector, &rv))) + return rv; + + sector = clink->header->start; + length = clink->header->length; + apaCacheFree(clink); + if (!(clink = apaCacheGetHeader(device, fileSlot->parts[0].start, APA_IO_MODE_READ, &rv))) + return rv; + + clink->header->subs[clink->header->nsub].start = sector; + clink->header->subs[clink->header->nsub].length = length; + clink->header->nsub++; + fileSlot->nsub++; + fileSlot->parts[fileSlot->nsub].start = sector; + fileSlot->parts[fileSlot->nsub].length = length; + clink->flags |= APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(device); + apaCacheFree(clink); + return rv; +} + +static int ioctl2DeleteLastSub(hdd_file_slot_t *fileSlot) +{ + int rv; + u32 device = fileSlot->f->unit; + apa_cache_t *mainPart; + apa_cache_t *subPart; + + if (!(fileSlot->f->mode & O_WRONLY)) + return -EACCES; + + if (fileSlot->nsub == 0) + return -ENOENT; + + if (!(mainPart = apaCacheGetHeader(device, fileSlot->parts[0].start, APA_IO_MODE_READ, &rv))) + return rv; + + if ((subPart = apaCacheGetHeader(device, + mainPart->header->subs[mainPart->header->nsub - 1].start, APA_IO_MODE_READ, &rv))) { + fileSlot->nsub--; + mainPart->header->nsub--; + mainPart->flags |= APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(device); + rv = apaDelete(subPart); + } + apaCacheFree(mainPart); + return rv; +} + +int hddIoctl2(iop_file_t *f, int req, void *argp, unsigned int arglen, + void *bufp, unsigned int buflen) +{ + u32 rv = 0, err_lba; + hdd_file_slot_t *fileSlot = f->privdata; + +#ifdef APA_SUPPORT_BHDD + if (strcmp(f->device->name, "bhdd") == 0) { + switch (req) { + case HIOCADDSUB: + case HIOCDELSUB: + case HIOCFLUSH: + case HIOCSETPARTERROR: + case HIOCGETPARTERROR: + return -EACCES; + default: + break; + } + } +#endif + WaitSema(fioSema); + switch (req) { + // cmd set 1 + case HIOCADDSUB: + rv = ioctl2AddSub(fileSlot, (char *)argp); + break; + + case HIOCDELSUB: + rv = ioctl2DeleteLastSub(fileSlot); + break; + + case HIOCNSUB: + rv = fileSlot->nsub; + break; + + case HIOCFLUSH: + ata_device_flush_cache(f->unit); + break; + + // cmd set 2 + case HIOCTRANSFER: + rv = ioctl2Transfer(f->unit, fileSlot, argp); + break; + + case HIOCGETSIZE: + rv = fileSlot->parts[*(u32 *)argp].length; + break; + + case HIOCSETPARTERROR: + apaSetPartErrorSector(f->unit, fileSlot->parts[0].start); + rv = 0; + break; + + case HIOCGETPARTERROR: + if ((rv = apaGetPartErrorSector(f->unit, APA_SECTOR_PART_ERROR, &err_lba)) > 0) { + if (err_lba == fileSlot->parts[0].start) { + rv = 0; + apaSetPartErrorSector(f->unit, 0); // clear last error :) + } + } + break; + + default: + rv = -EINVAL; + break; + } + SignalSema(fioSema); + return rv; +} + +static int devctlSwapTemp(s32 device, char *argp) +{ + int rv; + apa_params_t params; + char szBuf[APA_IDMAX]; + apa_cache_t *partTemp; + apa_cache_t *partNew; + + + if ((rv = fioGetInput(argp, ¶ms)) < 0) + return rv; + + if (params.id[0] == '_' && params.id[1] == '_') // test for '__' system partition + return -EINVAL; + + memset(szBuf, 0, APA_IDMAX); + strcpy(szBuf, "_tmp"); + if (!(partTemp = apaFindPartition(device, szBuf, &rv))) + return rv; + + if ((partNew = apaFindPartition(device, params.id, &rv))) { + if ((rv = apaPassCmp(partNew->header->fpwd, params.fpwd)) == 0) { + memcpy(partTemp->header->id, partNew->header->id, APA_IDMAX); + memcpy(partTemp->header->rpwd, partNew->header->rpwd, APA_PASSMAX); + memcpy(partTemp->header->fpwd, partNew->header->fpwd, APA_PASSMAX); + // memset(partNew->header->id, 0, 8);// BUG! can make it so can not open!! + memset(partNew->header->id, 0, APA_IDMAX); + strcpy(partNew->header->id, "_tmp"); + memset(partNew->header->rpwd, 0, APA_PASSMAX); + memset(partNew->header->fpwd, 0, APA_PASSMAX); + partTemp->flags |= APA_CACHE_FLAG_DIRTY; + partNew->flags |= APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(device); + } + apaCacheFree(partNew); + } + apaCacheFree(partTemp); + return rv; +} + +static int devctlSetOsdMBR(s32 device, hddSetOsdMBR_t *mbrInfo) +{ + int rv; + apa_cache_t *clink; + + if (!(clink = apaCacheGetHeader(device, APA_SECTOR_MBR, APA_IO_MODE_READ, &rv))) + return rv; + + APA_PRINTF(APA_DRV_NAME ": mbr start: %ld\n" APA_DRV_NAME ": mbr size : %ld\n", mbrInfo->start, mbrInfo->size); + // osdStart should not overwrite APA journal + if (mbrInfo->start < APA_SECTOR_MIN_OSDSTART) + return -EINVAL; + else + clink->header->mbr.osdStart = mbrInfo->start; + clink->header->mbr.osdSize = mbrInfo->size; + clink->flags |= APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(device); + apaCacheFree(clink); + return rv; +} + +int hddDevctl(iop_file_t *f, const char *devname, int cmd, void *arg, + unsigned int arglen, void *bufp, unsigned int buflen) +{ + int rv = 0; + +#ifdef APA_SUPPORT_BHDD + if (strcmp(f->device->name, "bhdd") == 0) + return -ENODEV; +#endif + + WaitSema(fioSema); + switch (cmd) { + // Command set 1 ('H') + case HDIOC_DEV9OFF: + // Early versions called ata_device_smart_save_attr() here, when their old dev9 versions did not support the pre-shutdown callback. + dev9Shutdown(); + break; + + case HDIOC_IDLE: + rv = ata_device_idle(f->unit, *(char *)arg); + break; + + case HDIOC_MAXSECTOR: + rv = hddDevices[f->unit].partitionMaxSize; + break; + + case HDIOC_TOTALSECTOR: + rv = hddDevices[f->unit].totalLBA; + break; + + case HDIOC_FLUSH: + if (ata_device_flush_cache(f->unit)) + rv = -EIO; + break; + + case HDIOC_SWAPTMP: + rv = devctlSwapTemp(f->unit, (char *)arg); + break; + + case HDIOC_SMARTSTAT: + rv = ata_device_smart_get_status(f->unit); + break; + + case HDIOC_STATUS: + rv = hddDevices[f->unit].status; + break; + + case HDIOC_FORMATVER: + rv = hddDevices[f->unit].format; + break; + + case HDIOC_FREESECTOR: + rv = apaGetFreeSectors(f->unit, bufp, hddDevices); + break; + + case HDIOC_IDLEIMM: + rv = ata_device_idle_immediate(f->unit); + break; + + // Command set 2 ('h') + case HDIOC_GETTIME: + rv = apaGetTime((apa_ps2time_t *)bufp); + break; + + case HDIOC_SETOSDMBR: + rv = devctlSetOsdMBR(f->unit, (hddSetOsdMBR_t *)arg); + break; + + case HDIOC_GETSECTORERROR: + rv = apaGetPartErrorSector(f->unit, APA_SECTOR_SECTOR_ERROR, 0); + break; + + case HDIOC_GETERRORPARTNAME: + rv = apaGetPartErrorName(f->unit, (char *)bufp); + break; + + case HDIOC_READSECTOR: + rv = ata_device_sector_io(f->unit, (void *)bufp, ((hddAtaTransfer_t *)arg)->lba, + ((hddAtaTransfer_t *)arg)->size, ATA_DIR_READ); + break; + + case HDIOC_WRITESECTOR: + rv = ata_device_sector_io(f->unit, ((hddAtaTransfer_t *)arg)->data, + ((hddAtaTransfer_t *)arg)->lba, ((hddAtaTransfer_t *)arg)->size, + ATA_DIR_WRITE); + break; + + case HDIOC_SCEIDENTIFY: + rv = ata_device_sce_identify_drive(f->unit, (u16 *)bufp); + break; + + default: + rv = -EINVAL; + break; + } + SignalSema(fioSema); + + return rv; +} + +int hddUnsupported(iop_file_t *f) { return -1; } diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd_fio.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd_fio.h new file mode 100644 index 0000000..e15d9ef --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/hdd_fio.h @@ -0,0 +1,33 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef _HDD_FIO_H +#define _HDD_FIO_H + +// I/O functions +int hddInit(iop_device_t *f); +int hddDeinit(iop_device_t *f); +int hddFormat(iop_file_t *f, const char *dev, const char *blockdev, void *arg, int arglen); +int hddOpen(iop_file_t *f, const char *name, int flags, int mode); +int hddClose(iop_file_t *f); +int hddRead(iop_file_t *f, void *buf, int size); +int hddWrite(iop_file_t *f, void *buf, int size); +int hddLseek(iop_file_t *f, int post, int whence); +int hddIoctl2(iop_file_t *f, int request, void *argp, unsigned int arglen, void *bufp, unsigned intbuflen); +int hddRemove(iop_file_t *f, const char *name); +int hddDopen(iop_file_t *f, const char *name); +int hddDread(iop_file_t *f, iox_dirent_t *dirent); +int hddGetStat(iop_file_t *f, const char *name, iox_stat_t *stat); +int hddReName(iop_file_t *f, const char *oldname, const char *newname); +int hddDevctl(iop_file_t *f, const char *devname, int cmd, void *arg, unsigned int arglen, void *bufp, unsigned int buflen); + +int hddUnsupported(iop_file_t *f); + +#endif /* _HDD_FIO_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/imports.lst new file mode 100644 index 0000000..2b1a07e --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/imports.lst @@ -0,0 +1,66 @@ + +atad_IMPORTS_start +I_ata_get_devinfo +I_ata_device_sector_io +I_ata_device_sce_sec_unlock +I_ata_device_idle +I_ata_device_sce_identify_drive +I_ata_device_smart_get_status +I_ata_device_smart_save_attr +I_ata_device_flush_cache +I_ata_device_idle_immediate +atad_IMPORTS_end + +cdvdman_IMPORTS_start +I_sceCdReadClock +I_sceCdRI +cdvdman_IMPORTS_end + +dev9_IMPORTS_start +I_dev9Shutdown +I_dev9RegisterShutdownCb +dev9_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +iomanX_IMPORTS_start +I_AddDrv +I_DelDrv +iomanX_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memcmp +I_memcpy +I_memset +I_strchr +I_strcmp +I_strcpy +I_strlen +I_strncmp +I_strncpy +I_strrchr +I_strtol +sysclib_IMPORTS_end + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +sysmem_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/irx_imports.h new file mode 100644 index 0000000..166e3c8 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/apa/src/irx_imports.h @@ -0,0 +1,30 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/include/libapa.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/include/libapa.h new file mode 100644 index 0000000..1e82ff1 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/include/libapa.h @@ -0,0 +1,207 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef __LIBAPA_H__ +#define __LIBAPA_H__ + +#include +#include + +// Sectors for this and that ;) +#define APA_SECTOR_MBR 0 +#ifdef APA_SUPPORT_GPT +#define APA_SECTOR_SECTOR_ERROR 34 // 6 use for last sector that had a error... +#else +#define APA_SECTOR_SECTOR_ERROR 6 // 6 use for last sector that had a error... +#endif +#define APA_SECTOR_PART_ERROR APA_SECTOR_SECTOR_ERROR + 1 // 7 use for last partition that had a error... +#define APA_SECTOR_APAL APA_SECTOR_PART_ERROR + 1 // 8 +#define APA_SECTOR_APAL_HEADERS APA_SECTOR_APAL + 2 // 10-262 +#define APA_SECTOR_MIN_OSDSTART APA_SECTOR_APAL_HEADERS + 252 + 1 // OSD program cannot overlap the journal + +// APA Partition +#define APA_MAGIC 0x00415041 // 'APA\0' +#define APA_MBR_VERSION 2 + +#define APA_MODVER ((APA_MODVER_MAJOR << 8) | APA_MODVER_MINOR) + +typedef struct +{ + u8 unused; + u8 sec; + u8 min; + u8 hour; + u8 day; + u8 month; + u16 year; +} apa_ps2time_t; + +// +// MAIN APA defines/struct +// +typedef struct +{ + u32 start; // Sector address + u32 length; // Sector count +} apa_sub_t; + +typedef struct +{ + u32 checksum; + u32 magic; // APA_MAGIC + u32 next; + u32 prev; + char id[APA_IDMAX]; + char rpwd[APA_PASSMAX]; + char fpwd[APA_PASSMAX]; + u32 start; + u32 length; + u16 type; + u16 flags; + u32 nsub; + apa_ps2time_t created; + u32 main; + u32 number; + u32 modver; + u32 pading1[7]; + char pading2[128]; + struct + { + char magic[32]; + u32 version; + u32 nsector; + apa_ps2time_t created; + u32 osdStart; + u32 osdSize; + char pading3[128]; // 200 + struct + { + u32 UniqueMbrSignature; + u16 Unknown; + struct + { + u8 BootIndicator; + u8 StartHead; + u8 StartSector; + u8 StartTrack; + u8 OSIndicator; + u8 EndHead; + u8 EndSector; + u8 EndTrack; + u32 StartingLBA; + u32 SizeInLBA; + } partition_record1; + u8 partition_record234[48]; + u16 Signature; + } protective_mbr; + } mbr; + apa_sub_t subs[APA_MAXSUB]; +} apa_header_t; + +#define APA_CACHE_FLAG_DIRTY 0x01 +typedef struct sapa_cache +{ + struct sapa_cache *next; + struct sapa_cache *tail; + u16 flags; + u16 nused; + s32 device; + u32 sector; + union + { + apa_header_t *header; + u32 *error_lba; + }; +} apa_cache_t; + +typedef struct +{ + char id[APA_IDMAX]; + char fpwd[APA_PASSMAX]; + char rpwd[APA_PASSMAX]; + u32 size; + u16 type; + u16 flags; + u32 main; + u32 number; +} apa_params_t; + +void apaSaveError(s32 device, void *buffer, u32 lba, u32 err_lba); +void apaSetPartErrorSector(s32 device, u32 lba); +int apaGetPartErrorSector(s32 device, u32 lba, u32 *lba_out); +int apaGetPartErrorName(s32 device, char *name); + +apa_cache_t *apaFillHeader(s32 device, const apa_params_t *params, u32 start, u32 next, u32 prev, u32 length, int *err); +apa_cache_t *apaInsertPartition(s32 device, const apa_params_t *params, u32 sector, int *err); +apa_cache_t *apaFindPartition(s32 device, const char *id, int *err); +void apaAddEmptyBlock(apa_header_t *header, u32 *emptyBlocks); +apa_cache_t *apaRemovePartition(s32 device, u32 start, u32 next, u32 prev, u32 length); +void apaMakeEmpty(apa_cache_t *clink); +apa_cache_t *apaDeleteFixPrev(apa_cache_t *clink1, int *err); +apa_cache_t *apaDeleteFixNext(apa_cache_t *clink, int *err); +int apaDelete(apa_cache_t *clink); +int apaCheckSum(apa_header_t *header, int fullcheck); +int apaReadHeader(s32 device, apa_header_t *header, u32 lba); +int apaWriteHeader(s32 device, apa_header_t *header, u32 lba); +int apaGetFormat(s32 device, int *format); +u32 apaGetPartitionMax(u32 totalLBA); +apa_cache_t *apaGetNextHeader(apa_cache_t *clink, int *err); + +/////////////////////////////////////////////////////////////////////////////// + +int apaCacheInit(u32 size); +void apaCacheLink(apa_cache_t *clink, apa_cache_t *cnew); +apa_cache_t *apaCacheUnLink(apa_cache_t *clink); +int apaCacheTransfer(apa_cache_t *clink, int type); +void apaCacheFlushDirty(apa_cache_t *clink); +int apaCacheFlushAllDirty(s32 device); +apa_cache_t *apaCacheGetHeader(s32 device, u32 sector, u32 mode, int *err); +void apaCacheFree(apa_cache_t *clink); +apa_cache_t *apaCacheAlloc(void); + +/////////////////////////////////////////////////////////////////////////////// + +#define APAL_MAGIC 0x4150414C // 'APAL' +typedef struct +{ + u32 magic; // APAL_MAGIC + s32 num; + u32 sectors[126]; +} apa_journal_t; + +#define journalCheckSum(header) apaCheckSum((apa_header_t *)header, 1) +int apaJournalReset(s32 device); +int apaJournalFlush(s32 device); +int apaJournalWrite(apa_cache_t *clink); +int apaJournalRestore(s32 device); + +/////////////////////////////////////////////////////////////////////////////// + +void *apaAllocMem(int size); +void apaFreeMem(void *ptr); +int apaGetTime(apa_ps2time_t *tm); +int apaGetIlinkID(u8 *idbuf); + +/////////////////////////////////////////////////////////////////////////////// +int apaPassCmp(const char *password1, const char *password2); +void apaEncryptPassword(const char *id, char *password_out, const char *password_in); + +/////////////////////////////////////////////////////////////////////////////// +typedef struct +{ + u32 totalLBA; + u32 partitionMaxSize; + int format; + int status; +} apa_device_t; + +int apaGetFreeSectors(s32 device, u32 *free, apa_device_t *deviceinfo); + +#endif /* __LIBAPA_H__ */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/apa.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/apa.c new file mode 100644 index 0000000..3f81a53 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/apa.c @@ -0,0 +1,488 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Main APA related routines +*/ + +#include +#include +#ifdef _IOP +#include +#else +#include +#endif +#include +#include +#include + +#include "apa-opt.h" +#include "libapa.h" + +#ifdef APA_SUPPORT_BHDD +extern apa_device_t hddDevices[]; +#endif + +const char apaMBRMagic[] = "Sony Computer Entertainment Inc."; + +void apaSaveError(s32 device, void *buffer, u32 lba, u32 err_lba) +{ + memset(buffer, 0, 512); + *(u32 *)buffer = err_lba; + ata_device_sector_io(device, buffer, lba, 1, ATA_DIR_WRITE); + ata_device_flush_cache(device); +} + +void apaSetPartErrorSector(s32 device, u32 lba) +{ // used to set the lba of a partition that has a error... + apa_cache_t *clink; + clink = apaCacheAlloc(); + apaSaveError(device, clink->header, APA_SECTOR_PART_ERROR, lba); + apaCacheFree(clink); +} + +int apaGetPartErrorSector(s32 device, u32 lba, u32 *lba_out) +{ + apa_cache_t *clink; + int rv = 0; + + if (!(clink = apaCacheAlloc())) + return -ENOMEM; + + if (ata_device_sector_io(device, clink->header, lba, 1, ATA_DIR_READ)) + return -EIO; + + if (lba_out) + *lba_out = *clink->error_lba; + if (*clink->error_lba) + rv = 1; // error is set ;) + apaCacheFree(clink); + return rv; +} + +int apaGetPartErrorName(s32 device, char *name) +{ + u32 lba; + int rv = 0; + apa_cache_t *clink; + + if ((rv = apaGetPartErrorSector(device, APA_SECTOR_PART_ERROR, &lba)) <= 0) + return rv; + if (!(clink = apaCacheGetHeader(device, 0, APA_IO_MODE_READ, &rv))) + return rv; + + while (clink) { + if (clink->header->type != APA_TYPE_FREE && + !(clink->header->flags & APA_CACHE_FLAG_DIRTY) && + clink->header->start == lba) { + if (name) { + strncpy(name, clink->header->id, APA_IDMAX - 1); + name[APA_IDMAX - 1] = '\0'; + } + apaCacheFree(clink); + return 1; + } + clink = apaGetNextHeader(clink, &rv); + } + + // clear error if no errors and partitions was not found... + if (rv == 0) + apaSetPartErrorSector(device, 0); + return rv; +} + +apa_cache_t *apaFillHeader(s32 device, const apa_params_t *params, u32 start, u32 next, + u32 prev, u32 length, int *err) +{ // used for making a new partition + apa_cache_t *clink; + + if (!(clink = apaCacheGetHeader(device, start, APA_IO_MODE_WRITE, err))) + return NULL; + memset(clink->header, 0, sizeof(apa_header_t)); + clink->header->magic = APA_MAGIC; + clink->header->start = start; + clink->header->next = next; + clink->header->prev = prev; + clink->header->length = length; + clink->header->type = params->type; + clink->header->flags = params->flags; + clink->header->modver = APA_MODVER; + memcpy(clink->header->id, params->id, APA_IDMAX); + if (params->flags & APA_FLAG_SUB) { + clink->header->main = params->main; + clink->header->number = params->number; + } else { + if (strncmp(clink->header->id, "_tmp", APA_IDMAX) != 0) { + memcpy(clink->header->rpwd, params->rpwd, APA_PASSMAX); + memcpy(clink->header->fpwd, params->fpwd, APA_PASSMAX); + } + } + apaGetTime(&clink->header->created); + clink->flags |= APA_CACHE_FLAG_DIRTY; + return clink; +} + +apa_cache_t *apaInsertPartition(s32 device, const apa_params_t *params, u32 sector, int *err) +{ // Adds a new partition using an empty block. + apa_cache_t *clink_empty; + apa_cache_t *clink_this; + apa_cache_t *clink_next; + + if ((clink_this = apaCacheGetHeader(device, sector, APA_IO_MODE_READ, err)) == 0) + return 0; + + while (clink_this->header->length != params->size) { + if ((clink_next = apaCacheGetHeader(device, clink_this->header->next, APA_IO_MODE_READ, err)) == NULL) { // Get next partition + apaCacheFree(clink_this); + return 0; + } + clink_this->header->length >>= 1; + clink_empty = apaRemovePartition(device, (clink_this->header->start + clink_this->header->length), + clink_this->header->next, clink_this->header->start, clink_this->header->length); + clink_this->header->next = clink_empty->header->start; + clink_this->flags |= APA_CACHE_FLAG_DIRTY; + clink_next->header->prev = clink_empty->header->start; + clink_next->flags |= APA_CACHE_FLAG_DIRTY; + + apaCacheFlushAllDirty(device); + apaCacheFree(clink_empty); + apaCacheFree(clink_next); + } + apaCacheFree(clink_this); + clink_this = apaFillHeader(device, params, clink_this->header->start, clink_this->header->next, + clink_this->header->prev, params->size, err); + apaCacheFlushAllDirty(device); + return clink_this; +} + +apa_cache_t *apaFindPartition(s32 device, const char *id, int *err) +{ + apa_cache_t *clink; + u32 sector = 0; + +#ifdef APA_SUPPORT_BHDD + if (strcmp(id, "__xcontents") == 0 || strcmp(id, "__extend") == 0 || strcmp(id, "__xdata") == 0) + sector = hddDevices[device].totalLBA; +#endif + + clink = apaCacheGetHeader(device, sector, APA_IO_MODE_READ, err); + while (clink) { + if (!(clink->header->flags & APA_FLAG_SUB)) { + if (memcmp(clink->header->id, id, APA_IDMAX) == 0) + return clink; // found + } + clink = apaGetNextHeader(clink, (int *)err); + } + if (*err == 0) { + *err = -ENOENT; + return NULL; + // return (apa_cache_t *)-ENOENT; // <-- BUG code tests for NULL only + } + *err = 0; + return NULL; +} + +void apaAddEmptyBlock(apa_header_t *header, u32 *emptyBlocks) +{ // small helper.... to track empty blocks.. + u32 i; + + if (header->type == APA_TYPE_FREE) { + for (i = 0; i < 32; i++) { + if (header->length == (1 << i)) { + if (emptyBlocks[i] == APA_TYPE_FREE) { + emptyBlocks[i] = header->start; + return; + } + } + } + } +} + +apa_cache_t *apaRemovePartition(s32 device, u32 start, u32 next, u32 prev, + u32 length) +{ + apa_cache_t *clink; + int err; + + if ((clink = apaCacheGetHeader(device, start, APA_IO_MODE_WRITE, &err)) == NULL) + return NULL; + memset(clink->header, 0, sizeof(apa_header_t)); + clink->header->magic = APA_MAGIC; + clink->header->start = start; + clink->header->next = next; + clink->header->prev = prev; + clink->header->length = length; + strcpy(clink->header->id, "__empty"); + apaGetTime(&clink->header->created); + clink->flags |= APA_CACHE_FLAG_DIRTY; + return clink; +} + +void apaMakeEmpty(apa_cache_t *clink) +{ + u32 saved_start; + u32 saved_next; + u32 saved_prev; + u32 saved_length; + + saved_start = clink->header->start; + saved_next = clink->header->next; + saved_prev = clink->header->prev; + saved_length = clink->header->length; + memset(clink->header, 0, sizeof(apa_header_t)); + clink->header->magic = APA_MAGIC; + clink->header->start = saved_start; + clink->header->next = saved_next; + clink->header->prev = saved_prev; + clink->header->length = saved_length; + apaGetTime(&clink->header->created); + strcpy(clink->header->id, "__empty"); + clink->flags |= APA_CACHE_FLAG_DIRTY; +} + +apa_cache_t *apaDeleteFixPrev(apa_cache_t *clink, int *err) +{ + apa_cache_t *clink2 = clink; + apa_header_t *header = clink2->header; + u32 device = clink->device; + u32 length = clink->header->length; + u32 saved_next = clink->header->next; + u32 saved_length = clink->header->length; + u32 tmp; + + while (header->start) { + if (!(clink2 = apaCacheGetHeader(device, header->prev, APA_IO_MODE_READ, err))) { + apaCacheFree(clink); + return NULL; + } + header = clink2->header; + tmp = header->length + length; + if (header->type != 0) { + apaCacheFree(clink2); + break; + } + if ((header->start % tmp) || (tmp & (tmp - 1))) { + apaCacheFree(clink2); + break; + } + length = tmp; + apaCacheFree(clink); + clink = clink2; + } + if (length != saved_length) { + if (!(clink2 = apaCacheGetHeader(device, saved_next, APA_IO_MODE_READ, err))) { + apaCacheFree(clink); + return NULL; + } + clink->header->length = length; + clink->header->next = clink->header->start + length; + clink2->header->prev = clink->header->start; + clink2->flags |= APA_CACHE_FLAG_DIRTY; + clink->flags |= APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(device); + apaCacheFree(clink2); + } + return clink; +} + + +apa_cache_t *apaDeleteFixNext(apa_cache_t *clink, int *err) +{ + apa_header_t *header = clink->header; + u32 length = header->length; + u32 saved_length = header->length; + u32 lnext = header->next; + apa_cache_t *clink1; + apa_cache_t *clink2; + u32 device = clink->device; + u32 tmp; + + while (lnext != 0) { + if (!(clink1 = apaCacheGetHeader(device, lnext, APA_IO_MODE_READ, err))) { + apaCacheFree(clink); + return 0; + } + header = clink1->header; + tmp = header->length + length; + if (header->type != 0) { + apaCacheFree(clink1); + break; + } + if ((clink->header->start % tmp) != 0 || ((tmp - 1) & tmp)) { + apaCacheFree(clink1); + break; + } + length = tmp; + apaCacheFree(clink1); + lnext = header->next; + } + if (length != saved_length) { + if (!(clink2 = apaCacheGetHeader(device, lnext, APA_IO_MODE_READ, err))) { + apaCacheFree(clink); + return NULL; + } + clink->header->length = length; + clink->header->next = lnext; + apaMakeEmpty(clink); + clink2->header->prev = clink->header->start; + clink2->flags |= APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(device); + apaCacheFree(clink2); + } + return clink; +} + + +int apaDelete(apa_cache_t *clink) +{ + int rv = 0; + apa_cache_t *clink_mbr; + u32 device = clink->device; + u32 start = clink->header->start; + int i; + + if (!start) { + apaCacheFree(clink); + return -EACCES; + } + + if (clink->header->next == 0) { + if ((clink_mbr = apaCacheGetHeader(device, 0, APA_IO_MODE_READ, &rv)) == NULL) { + apaCacheFree(clink); + return rv; + } + do { + apaCacheFree(clink); + if ((clink = apaCacheGetHeader(clink->device, clink->header->prev, APA_IO_MODE_READ, &rv)) == NULL) + return 0; + clink->header->next = 0; + clink->flags |= APA_CACHE_FLAG_DIRTY; + clink_mbr->header->prev = clink->header->start; + clink_mbr->flags |= APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(device); + } while (clink->header->type == 0); + apaCacheFree(clink_mbr); + } else { + u32 length = clink->header->length; + + for (i = 0; i < 2; i++) { + if ((clink = apaDeleteFixPrev(clink, &rv)) == NULL) + return 0; + if ((clink = apaDeleteFixNext(clink, &rv)) == NULL) + return 0; + } + if (clink->header->start == start && clink->header->length == length) { + apaMakeEmpty(clink); + apaCacheFlushAllDirty(clink->device); + } + } + apaCacheFree(clink); + return rv; +} + +int apaCheckSum(apa_header_t *header, int fullcheck) +{ + u32 *ptr = (u32 *)header; + u32 sum, i; + + for (sum = 0, i = 1; i < 256; i++) // sizeof(header)/4 = 256, start at offset +4 to omit the checksum field. + sum += ptr[i]; +#ifdef APA_SUPPORT_GPT + if (!(fullcheck)) + for (sum = 0, i = 1; i < 128; i++) // recalculate checksum only for first sector. + sum += ptr[i]; +#endif + return sum; +} + +int apaReadHeader(s32 device, apa_header_t *header, u32 lba) +{ + if (ata_device_sector_io(device, header, lba, 2, ATA_DIR_READ) != 0) + return -EIO; + if (header->magic != APA_MAGIC) + return -EIO; + if (apaCheckSum(header, 1) != header->checksum) + if (lba == APA_SECTOR_MBR) + if (apaCheckSum(header, 0) != header->checksum) + return -EIO; + + if (lba == APA_SECTOR_MBR) { + if (strncmp(header->mbr.magic, apaMBRMagic, sizeof(header->mbr.magic)) == 0) + return 0; + APA_PRINTF(APA_DRV_NAME ": error: invalid partition table or version newer than I know.\n"); + return -EIO; + } + return 0; +} + +int apaWriteHeader(s32 device, apa_header_t *header, u32 lba) +{ + if (ata_device_sector_io(device, header, lba, 2, ATA_DIR_WRITE)) + return -EIO; + return 0; +} + +int apaGetFormat(s32 device, int *format) +{ + apa_cache_t *clink; + int rv = 0; + u32 *pDW, i; + + clink = apaCacheAlloc(); + *format = 0; + if ((rv = apaReadHeader(device, clink->header, 0)) == 0) { + *format = clink->header->mbr.version; + if (ata_device_sector_io(device, clink->header, APA_SECTOR_SECTOR_ERROR, 2, ATA_DIR_READ)) + rv = -EIO; // return -EIO; + if (rv == 0) { + pDW = (u32 *)clink->header; + for (i = 0; i < 256; i++) { + if ((i & 0x7F) && pDW[i] != 0) + rv = 1; + } + } + } + apaCacheFree(clink); + return rv == 0; +} + +u32 apaGetPartitionMax(u32 totalLBA) +{ + u32 i, size; + + totalLBA >>= 6; // totalLBA/64 + size = (1 << 0x1F); + for (i = 31; i != 0; i--) { + size = 1 << i; + if (size & totalLBA) + break; + } + if (size < totalLBA) + i++; + return (1 << i); +} + +apa_cache_t *apaGetNextHeader(apa_cache_t *clink, int *err) +{ + u32 start = clink->header->start; + + apaCacheFree(clink); + if (!clink->header->next) + return NULL; + + if (!(clink = apaCacheGetHeader(clink->device, clink->header->next, APA_IO_MODE_READ, err))) + return NULL; + + if (start != clink->header->prev) { + APA_PRINTF(APA_DRV_NAME ": Warning: Invalid partition information. start != prev\n"); + clink->header->prev = start; + clink->flags |= APA_CACHE_FLAG_DIRTY; + apaCacheFlushAllDirty(clink->device); + } + return clink; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/cache.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/cache.c new file mode 100644 index 0000000..dc986d6 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/cache.c @@ -0,0 +1,199 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# APA cache manipulation routines +*/ + +#include +#include +#ifdef _IOP +#include +#else +#include +#endif +#include +#include + +#include "apa-opt.h" +#include "libapa.h" + +// Globals +static apa_cache_t *cacheBuf; +static int cacheSize; + +int apaCacheInit(u32 size) +{ + apa_header_t *header; + unsigned int i; + + cacheSize=size; // save size ;) + if((header=(apa_header_t *)apaAllocMem(size*sizeof(apa_header_t)))){ + cacheBuf=apaAllocMem((size+1)*sizeof(apa_cache_t)); + if(cacheBuf==NULL) + return -ENOMEM; + } + else + return -ENOMEM; + // setup cache header... + memset(cacheBuf, 0, (size+1)*sizeof(apa_cache_t)); + cacheBuf->next=cacheBuf; + cacheBuf->tail=cacheBuf; + for(i=1; itail, &cacheBuf[i]); + } + return 0; +} + +void apaCacheLink(apa_cache_t *clink, apa_cache_t *cnew) +{ + cnew->tail=clink; + cnew->next=clink->next; + clink->next->tail=cnew; + clink->next=cnew; +} + +apa_cache_t *apaCacheUnLink(apa_cache_t *clink) +{ + clink->tail->next=clink->next; + clink->next->tail=clink->tail; + return clink; +} + +int apaCacheTransfer(apa_cache_t *clink, int type) +{ + int err; + if(type) + err=apaWriteHeader(clink->device, clink->header, clink->sector); + else// 0 + err=apaReadHeader(clink->device, clink->header, clink->sector); + + if(err) + { + APA_PRINTF(APA_DRV_NAME": error: disk err %d on device %ld, sector %ld, type %d\n", + err, clink->device, clink->sector, type); + if(type==0)// save any read error's.. + apaSaveError(clink->device, clink->header, APA_SECTOR_SECTOR_ERROR, clink->sector); + } + clink->flags&=~APA_CACHE_FLAG_DIRTY; + return err; +} + +void apaCacheFlushDirty(apa_cache_t *clink) +{ + if(clink->flags&APA_CACHE_FLAG_DIRTY) + apaCacheTransfer(clink, APA_IO_MODE_WRITE); +} + +int apaCacheFlushAllDirty(s32 device) +{ + int i; + // flush apal + for(i=1;inused==0) + clink=apaCacheUnLink(clink); + clink->nused++; + return clink; + } + if((cacheBuf->tail==cacheBuf) && + (cacheBuf->tail==cacheBuf->tail->next)){ + APA_PRINTF(APA_DRV_NAME": error: free buffer empty\n"); + } + else + { + clink=cacheBuf->next; + if(clink->flags & APA_CACHE_FLAG_DIRTY) + APA_PRINTF(APA_DRV_NAME": error: dirty buffer allocated\n"); + clink->flags=0; + clink->nused=1; + clink->device=device; + clink->sector=sector; + clink=apaCacheUnLink(clink); + } + if(clink==NULL) + { + *result=-ENOMEM; + return NULL; + } + if(!mode) + { + if((*result=apaCacheTransfer(clink, APA_IO_MODE_READ))<0){ + clink->nused=0; + clink->device=-1; + apaCacheLink(cacheBuf, clink); + clink=NULL; + } + } + return clink; +} + +void apaCacheFree(apa_cache_t *clink) +{ + if(clink==NULL){ + APA_PRINTF(APA_DRV_NAME": error: null buffer returned\n"); + return; + } + if(clink->nused==0){ + APA_PRINTF(APA_DRV_NAME": error: unused cache returned\n"); + return; + } + if(clink->flags & APA_CACHE_FLAG_DIRTY) + APA_PRINTF(APA_DRV_NAME": error: dirty buffer returned\n"); + clink->nused--; + if(clink->nused==0) + apaCacheLink(cacheBuf->tail, clink); + return; +} + +apa_cache_t *apaCacheAlloc(void) +{ + apa_cache_t *cnext; + + if((cacheBuf->tail==cacheBuf) && + (cacheBuf->tail==cacheBuf->tail->next)){ + APA_PRINTF(APA_DRV_NAME": error: free buffer empty\n"); + return NULL; + } + cnext=cacheBuf->next; + if(cnext->flags & APA_CACHE_FLAG_DIRTY) + APA_PRINTF(APA_DRV_NAME": error: dirty buffer allocated\n"); + cnext->nused=1; + cnext->flags=0; + cnext->device=-1; + cnext->sector=-1; + return apaCacheUnLink(cnext); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/free.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/free.c new file mode 100644 index 0000000..7b9bfcc --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/free.c @@ -0,0 +1,85 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Free space calculation routines +*/ + +#include +#include +#ifdef _IOP +#include +#else +#include +#endif +#include +#include +#include + +#include "apa-opt.h" +#include "libapa.h" + +static void apaCalculateFreeSpace(u32 *free, u32 sectors) +{ + if(0x1FFFFF < sectors) + { + *free += sectors; + return; + } + + if((*free & sectors) == 0) + { + *free |= sectors; + return; + } + + for(sectors /= 2; 0x3FFFF < sectors; sectors /= 2) + *free |= sectors; +} + +int apaGetFreeSectors(s32 device, u32 *free, apa_device_t *deviceinfo) +{ + u32 sectors, partMax; + int rv; + apa_cache_t *clink; + + sectors = 0; + *free = 0; + if((clink = apaCacheGetHeader(device, 0, APA_IO_MODE_READ, &rv)) != NULL) + { + do{ + if(clink->header->type == 0) + apaCalculateFreeSpace(free, clink->header->length); + sectors += clink->header->length; + }while((clink = apaGetNextHeader(clink, &rv)) != NULL); + } + + if(rv == 0) + { + for(partMax = deviceinfo[device].partitionMaxSize; 0x0003FFFF < partMax; partMax = deviceinfo[device].partitionMaxSize) + { //As weird as it looks, this was how it was done in the original HDD.IRX. + for( ; 0x0003FFFF < partMax; partMax /= 2) + { + //Non-SONY: Perform 64-bit arithmetic here to avoid overflows when dealing with large disks. + if((sectors % partMax == 0) && ((u64)sectors + partMax < deviceinfo[device].totalLBA)) + { + apaCalculateFreeSpace(free, partMax); + sectors += partMax; + break; + } + } + + if(0x0003FFFF >= partMax) + break; + } + + APA_PRINTF(APA_DRV_NAME": total = %08lx sectors, installable = %08lx sectors.\n", sectors, *free); + } + + return rv; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/journal.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/journal.c new file mode 100644 index 0000000..069412d --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/journal.c @@ -0,0 +1,87 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# APA journal related routines +*/ + +#include +#include +#include +#ifdef _IOP +#include +#else +#include +#endif +#include +#include + +#include "apa-opt.h" +#include "libapa.h" + +// Globals +static apa_journal_t journalBuf; + +int apaJournalFlush(s32 device) +{// this write any thing that in are journal buffer :) + if(ata_device_flush_cache(device)) + return -EIO; + if(ata_device_sector_io(device, &journalBuf, APA_SECTOR_APAL, 1, ATA_DIR_WRITE)) + return -EIO; + if(ata_device_flush_cache(device)) + return -EIO; + return 0; +} + +int apaJournalReset(s32 device) +{ + memset(&journalBuf, 0, sizeof(apa_journal_t)); + journalBuf.magic=APAL_MAGIC; + return apaJournalFlush(device); +} + +int apaJournalWrite(apa_cache_t *clink) +{ + clink->header->checksum=journalCheckSum(clink->header); + if(ata_device_sector_io(clink->device, clink->header, + (journalBuf.num << 1)+APA_SECTOR_APAL_HEADERS, 2, ATA_DIR_WRITE)) + return -EIO; + journalBuf.sectors[journalBuf.num]=clink->sector; + journalBuf.num++; + return 0; +} + +int apaJournalRestore(s32 device) +{ // copies the journal from the HDD and erases the original. + int i, ret; + u32 sector; + apa_cache_t *clink; + + APA_PRINTF(APA_DRV_NAME": checking log...\n"); + ret = ata_device_sector_io(device, &journalBuf, APA_SECTOR_APAL, sizeof(apa_journal_t)/512, ATA_DIR_READ) == 0 ? 0 : -EIO; + if((ret == 0) && (journalBuf.magic == APAL_MAGIC)) + { + if(journalBuf.num == 0) + return 0; + + clink=apaCacheAlloc(); + for(i=0, sector=APA_SECTOR_APAL_HEADERS;iheader, sector, 2, ATA_DIR_READ) == 0) ? 0 : -EIO; + if(ret != 0) + break; + + ret = (ata_device_sector_io(device, clink->header, journalBuf.sectors[i], 2, ATA_DIR_WRITE) == 0) ? 0 : -EIO; + if(ret != 0) + break; + } + apaCacheFree(clink); + } + + return apaJournalReset(device); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/misc.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/misc.c new file mode 100644 index 0000000..90b3195 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/misc.c @@ -0,0 +1,140 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Miscellaneous routines +*/ + +#include +#ifdef _IOP +#include +#include +#include +#include +#include +#else +#include +#include +#include +#endif +#include +#include +#include + +#include "apa-opt.h" +#include "libapa.h" + +void *apaAllocMem(int size) +{ +#ifdef _IOP + int intrStat; + void *mem; + + CpuSuspendIntr(&intrStat); + mem = AllocSysMemory(ALLOC_FIRST, size, NULL); + if(mem == NULL) + APA_PRINTF(APA_DRV_NAME": error: out of memory\n"); + CpuResumeIntr(intrStat); + + return mem; +#else + return malloc(size); +#endif +} + +void apaFreeMem(void *ptr) +{ +#ifdef _IOP + int intrStat; + + CpuSuspendIntr(&intrStat); + FreeSysMemory(ptr); + CpuResumeIntr(intrStat); +#else + free(ptr); +#endif +} + +int apaGetTime(apa_ps2time_t *tm) +{ +#ifdef _IOP + int ret, i; + sceCdCLOCK cdtime; + static apa_ps2time_t timeBuf={ + 0, 7, 6, 5, 4, 3, 2000 // used if can not get time... + }; + + for(i = 0; i < 20; i++) + { + ret = sceCdReadClock(&cdtime); + + if(ret!=0 && cdtime.stat==0) + { + timeBuf.sec=btoi(cdtime.second); + timeBuf.min=btoi(cdtime.minute); + timeBuf.hour=btoi(cdtime.hour); + timeBuf.day=btoi(cdtime.day); + timeBuf.month=btoi(cdtime.month & 0x7F); //The old CDVDMAN sceCdReadClock() function does not automatically file off the highest bit. + timeBuf.year=btoi(cdtime.year) + 2000; + break; + } else { + if(!(cdtime.stat & 0x80)) + break; + } + + DelayThread(100000); + } + + memcpy(tm, &timeBuf, sizeof(apa_ps2time_t)); +#else + time_t rawtime; + struct tm timeinfo; + time(&rawtime); + // Convert to JST + rawtime += (-9 * 60 * 60); + gmtime_r(&rawtime, &timeinfo); + + tm->sec = timeinfo.tm_sec; + tm->min = timeinfo.tm_min; + tm->hour = timeinfo.tm_hour; + tm->day = timeinfo.tm_mday; + tm->month = timeinfo.tm_mon + 1; + tm->year = timeinfo.tm_year + 1900; +#endif + + return 0; +} + +int apaGetIlinkID(u8 *idbuf) +{ +#ifdef _IOP + u32 stat; + int i; + + for(i = 0; ; i++) + { + stat=0; + memset(idbuf, 0, 32); + if((sceCdRI(idbuf, &stat) != 0) && (stat == 0)) + { + return 0; + } + + if(i >= 20) + break; + + DelayThread(100000); + } + + APA_PRINTF(APA_DRV_NAME": Error: cannot get id\n"); + return -EIO; +#else + memset(idbuf, 0, 32); + return 0; +#endif +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/password.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/password.c new file mode 100644 index 0000000..46b6a90 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libapa/src/password.c @@ -0,0 +1,522 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Password-handling routines +*/ + +#include +#include +#include +#ifdef _IOP +#include +#else +#include +#endif +#include +#include + +#include "apa-opt.h" +#include "libapa.h" + +int apaPassCmp(const char *pw1, const char *pw2) +{ +#ifdef APA_ENABLE_PASSWORDS + return memcmp(pw1, pw2, APA_PASSMAX) ? -EACCES : 0; +#else + //Passwords are not supported, hence this check should always pass. + return 0; +#endif +} + +static void DESEncryptPassword(u32 id_lo, u32 id_hi, char *password_out, const char *password); + +void apaEncryptPassword(const char *id, char *password_out, const char *password_in) +{ + char password[APA_PASSMAX]; + memcpy(password, password_in, APA_PASSMAX); + DESEncryptPassword(*(u32*)(id), *(u32*)(id + 4), password_out, password); +} + +struct KeyPair{ + u32 lo, hi; +}; + +//This is a standard DES-ECB implementation. It encrypts the partition ID with the password. +static void DESEncryptPassword(u32 id_lo, u32 id_hi, char *password_out, const char *password) +{ + //Left + static const u8 PC1[]={ 0x39, 0x31, 0x29, 0x21, 0x19, 0x11, 0x09, + 0x01, 0x3a, 0x32, 0x2a, 0x22, 0x1a, 0x12, + 0x0a, 0x02, 0x3b, 0x33, 0x2b, 0x23, 0x1b, + 0x13, 0x0b, 0x03, 0x3c, 0x34, 0x2c, 0x24, + //Right + 0x3f, 0x37, 0x2f, 0x27, 0x1f, 0x17, 0x0f, + 0x07, 0x3e, 0x36, 0x2e, 0x26, 0x1e, 0x16, + 0x0e, 0x06, 0x3d, 0x35, 0x2d, 0x25, 0x1d, + 0x15, 0x0d, 0x05, 0x1c, 0x14, 0x0c, 0x04 }; + static const u8 Rotations[]={ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; + static const u8 PC2[]={ 0x0e, 0x11, 0x0b, 0x18, 0x01, 0x05, + 0x03, 0x1c, 0x0f, 0x06, 0x15, 0x0a, + 0x17, 0x13, 0x0c, 0x04, 0x1a, 0x08, + 0x10, 0x07, 0x1b, 0x14, 0x0d, 0x02, + 0x29, 0x34, 0x1f, 0x25, 0x2f, 0x37, + 0x1e, 0x28, 0x33, 0x2d, 0x21, 0x30, + 0x2c, 0x31, 0x27, 0x38, 0x22, 0x35, + 0x2e, 0x2a, 0x32, 0x24, 0x1d, 0x20 }; + static const u8 IP[]={ 0x3a, 0x32, 0x2a, 0x22, 0x1a, 0x12, 0x0a, 0x02, 0x3c, 0x34, 0x2c, 0x24, 0x1c, 0x14, 0x0c, 0x04, + 0x3e, 0x36, 0x2e, 0x26, 0x1e, 0x16, 0x0e, 0x06, 0x40, 0x38, 0x30, 0x28, 0x20, 0x18, 0x10, 0x08, + + 0x39, 0x31, 0x29, 0x21, 0x19, 0x11, 0x09, 0x01, 0x3b, 0x33, 0x2b, 0x23, 0x1b, 0x13, 0x0b, 0x03, + 0x3d, 0x35, 0x2d, 0x25, 0x1d, 0x15, 0x0d, 0x05, 0x3f, 0x37, 0x2f, 0x27, 0x1f, 0x17, 0x0f, 0x07 }; + static const u8 Expansion[]={ 0x20, 0x01, 0x02, 0x03, 0x04, 0x05, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x08, 0x09, 0x0a, 0x0b, + 0x0c, 0x0d, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x01 }; + static const u8 sbox[][64]={ { 0x0e, 0x04, 0x0d, 0x01, 0x02, 0x0f, 0x0b, 0x08, 0x03, 0x0a, 0x06, 0x0c, 0x05, 0x09, 0x00, 0x07, + 0x00, 0x0f, 0x07, 0x04, 0x0e, 0x02, 0x0d, 0x01, 0x0a, 0x06, 0x0c, 0x0b, 0x09, 0x05, 0x03, 0x08, + 0x04, 0x01, 0x0e, 0x08, 0x0d, 0x06, 0x02, 0x0b, 0x0f, 0x0c, 0x09, 0x07, 0x03, 0x0a, 0x05, 0x00, + 0x0f, 0x0c, 0x08, 0x02, 0x04, 0x09, 0x01, 0x07, 0x05, 0x0b, 0x03, 0x0e, 0x0a, 0x00, 0x06, 0x0d }, + { 0x0f, 0x01, 0x08, 0x0e, 0x06, 0x0b, 0x03, 0x04, 0x09, 0x07, 0x02, 0x0d, 0x0c, 0x00, 0x05, 0x0a, + 0x03, 0x0d, 0x04, 0x07, 0x0f, 0x02, 0x08, 0x0e, 0x0c, 0x00, 0x01, 0x0a, 0x06, 0x09, 0x0b, 0x05, + 0x00, 0x0e, 0x07, 0x0b, 0x0a, 0x04, 0x0d, 0x01, 0x05, 0x08, 0x0c, 0x06, 0x09, 0x03, 0x02, 0x0f, + 0x0d, 0x08, 0x0a, 0x01, 0x03, 0x0f, 0x04, 0x02, 0x0b, 0x06, 0x07, 0x0c, 0x00, 0x05, 0x0e, 0x09 }, + { 0x0a, 0x00, 0x09, 0x0e, 0x06, 0x03, 0x0f, 0x05, 0x01, 0x0d, 0x0c, 0x07, 0x0b, 0x04, 0x02, 0x08, + 0x0d, 0x07, 0x00, 0x09, 0x03, 0x04, 0x06, 0x0a, 0x02, 0x08, 0x05, 0x0e, 0x0c, 0x0b, 0x0f, 0x01, + 0x0d, 0x06, 0x04, 0x09, 0x08, 0x0f, 0x03, 0x00, 0x0b, 0x01, 0x02, 0x0c, 0x05, 0x0a, 0x0e, 0x07, + 0x01, 0x0a, 0x0d, 0x00, 0x06, 0x09, 0x08, 0x07, 0x04, 0x0f, 0x0e, 0x03, 0x0b, 0x05, 0x02, 0x0c }, + { 0x07, 0x0d, 0x0e, 0x03, 0x00, 0x06, 0x09, 0x0a, 0x01, 0x02, 0x08, 0x05, 0x0b, 0x0c, 0x04, 0x0f, + 0x0d, 0x08, 0x0b, 0x05, 0x06, 0x0f, 0x00, 0x03, 0x04, 0x07, 0x02, 0x0c, 0x01, 0x0a, 0x0e, 0x09, + 0x0a, 0x06, 0x09, 0x00, 0x0c, 0x0b, 0x07, 0x0d, 0x0f, 0x01, 0x03, 0x0e, 0x05, 0x02, 0x08, 0x04, + 0x03, 0x0f, 0x00, 0x06, 0x0a, 0x01, 0x0d, 0x08, 0x09, 0x04, 0x05, 0x0b, 0x0c, 0x07, 0x02, 0x0e }, + { 0x02, 0x0c, 0x04, 0x01, 0x07, 0x0a, 0x0b, 0x06, 0x08, 0x05, 0x03, 0x0f, 0x0d, 0x00, 0x0e, 0x09, + 0x0e, 0x0b, 0x02, 0x0c, 0x04, 0x07, 0x0d, 0x01, 0x05, 0x00, 0x0f, 0x0a, 0x03, 0x09, 0x08, 0x06, + 0x04, 0x02, 0x01, 0x0b, 0x0a, 0x0d, 0x07, 0x08, 0x0f, 0x09, 0x0c, 0x05, 0x06, 0x03, 0x00, 0x0e, + 0x0b, 0x08, 0x0c, 0x07, 0x01, 0x0e, 0x02, 0x0d, 0x06, 0x0f, 0x00, 0x09, 0x0a, 0x04, 0x05, 0x03 }, + { 0x0c, 0x01, 0x0a, 0x0f, 0x09, 0x02, 0x06, 0x08, 0x00, 0x0d, 0x03, 0x04, 0x0e, 0x07, 0x05, 0x0b, + 0x0a, 0x0f, 0x04, 0x02, 0x07, 0x0c, 0x09, 0x05, 0x06, 0x01, 0x0d, 0x0e, 0x00, 0x0b, 0x03, 0x08, + 0x09, 0x0e, 0x0f, 0x05, 0x02, 0x08, 0x0c, 0x03, 0x07, 0x00, 0x04, 0x0a, 0x01, 0x0d, 0x0b, 0x06, + 0x04, 0x03, 0x02, 0x0c, 0x09, 0x05, 0x0f, 0x0a, 0x0b, 0x0e, 0x01, 0x07, 0x06, 0x00, 0x08, 0x0d }, + { 0x04, 0x0b, 0x02, 0x0e, 0x0f, 0x00, 0x08, 0x0d, 0x03, 0x0c, 0x09, 0x07, 0x05, 0x0a, 0x06, 0x01, + 0x0d, 0x00, 0x0b, 0x07, 0x04, 0x09, 0x01, 0x0a, 0x0e, 0x03, 0x05, 0x0c, 0x02, 0x0f, 0x08, 0x06, + 0x01, 0x04, 0x0b, 0x0d, 0x0c, 0x03, 0x07, 0x0e, 0x0a, 0x0f, 0x06, 0x08, 0x00, 0x05, 0x09, 0x02, + 0x06, 0x0b, 0x0d, 0x08, 0x01, 0x04, 0x0a, 0x07, 0x09, 0x05, 0x00, 0x0f, 0x0e, 0x02, 0x03, 0x0c }, + { 0x0d, 0x02, 0x08, 0x04, 0x06, 0x0f, 0x0b, 0x01, 0x0a, 0x09, 0x03, 0x0e, 0x05, 0x00, 0x0c, 0x07, + 0x01, 0x0f, 0x0d, 0x08, 0x0a, 0x03, 0x07, 0x04, 0x0c, 0x05, 0x06, 0x0b, 0x00, 0x0e, 0x09, 0x02, + 0x07, 0x0b, 0x04, 0x01, 0x09, 0x0c, 0x0e, 0x02, 0x00, 0x06, 0x0a, 0x0d, 0x0f, 0x03, 0x05, 0x08, + 0x02, 0x01, 0x0e, 0x07, 0x04, 0x0a, 0x08, 0x0d, 0x0f, 0x0c, 0x09, 0x00, 0x03, 0x05, 0x06, 0x0b }}; + static const u8 Permutation[]={ 0x10, 0x07, 0x14, 0x15, 0x1d, 0x0c, 0x1c, 0x11, 0x01, 0x0f, 0x17, 0x1a, 0x05, 0x12, 0x1f, 0x0a, + 0x02, 0x08, 0x18, 0x0e, 0x20, 0x1b, 0x03, 0x09, 0x13, 0x0d, 0x1e, 0x06, 0x16, 0x0b, 0x04, 0x19 }; + static const u8 FP[]={ 0x28, 0x08, 0x30, 0x10, 0x38, 0x18, 0x40, 0x20, 0x27, 0x07, 0x2f, 0x0f, 0x37, 0x17, 0x3f, 0x1f, + 0x26, 0x06, 0x2e, 0x0e, 0x36, 0x16, 0x3e, 0x1e, 0x25, 0x05, 0x2d, 0x0d, 0x35, 0x15, 0x3d, 0x1d, + 0x24, 0x04, 0x2c, 0x0c, 0x34, 0x14, 0x3c, 0x1c, 0x23, 0x03, 0x2b, 0x0b, 0x33, 0x13, 0x3b, 0x1b, + 0x22, 0x02, 0x2a, 0x0a, 0x32, 0x12, 0x3a, 0x1a, 0x21, 0x01, 0x29, 0x09, 0x31, 0x11, 0x39, 0x19 }; + u32 BitMask_hi, BitMask_lo; + u32 PermutedKeyMask_lo, PermutedKeyMask_hi, Rot2Mask_lo, Rot1Mask_lo, Rot2Mask_hi, Rot1Mask_hi; + u32 BitPerm_lo, BitPerm_hi; + u32 password_lo, password_hi; + u32 key1, key2, key3, key4, input_lo, input_hi; + u32 PermutedKey_lo, PermutedKey_hi, kVal_lo, kVal_hi, PermutedInput_lo, PermutedInput_hi, eVal_lo, eVal_hi, sVal_lo, sVal_hi, pVal_lo, pVal_hi, output_lo, output_hi; + struct KeyPair pairC[17], pairD[17], pairK[17], pairL[17], pairR[17]; + struct KeyPair *pPairC, *pPairD, *pPairK, *pPairL, *pPairR; + unsigned int i, j, k; + int shift; + + //Phase 1 (Permute KEY with Permuted Choice 1) + PermutedKey_lo = 0; + PermutedKey_hi = 0; + BitMask_lo = 0; + BitMask_hi = 0x80000000; + BitPerm_lo = 0; + BitPerm_hi = 0x80000000; + + password_lo = *(const u32*)password; + password_hi = *(const u32*)(password + 4); + + for(i = 0; i < 56; i++) + { + shift = PC1[i] - 1; + + if((shift << 26) >= 0) + { //0 to 31-bit shift + if((shift << 26) > 0) //Shift all bits left by shift (hi,lo >> shift) + key1 = (BitMask_lo >> shift) | (BitMask_hi << (-shift)); + else //0-bit shift, which should not happen. + key1 = BitMask_lo >> shift; + + key2 = BitMask_hi >> shift; + } else { //>31-bit shift + key2 = 0; + key1 = BitMask_hi >> shift; + } + + //If bit (shift) is set, set the current bit. + if(((password_lo & key1) | (password_hi & key2)) != 0) + { + PermutedKey_lo |= BitPerm_lo; + PermutedKey_hi |= BitPerm_hi; + } + + //Shift all bits left by 1 (hi,lo >> 1) + BitPerm_lo = (BitPerm_lo >> 1) | (BitPerm_hi << 31); + BitPerm_hi >>= 1; + } + + //Phase 2 (Key Schedule Calculation) + //This mask is used to extract the lower 28-bits of a key. + PermutedKeyMask_lo = 0x0FFFFFFF; + PermutedKeyMask_hi = 0x00000000; + + Rot2Mask_lo = 3; + Rot2Mask_hi = 0x00000000; + Rot1Mask_lo = 1; + Rot1Mask_hi = 0x00000000; + + //C-bits, upper 28-bits of Permuted Key + pairC[0].lo = PermutedKey_hi >> 4; + pairC[0].hi = 0; + + //D-bits, lower 28-bits of Permuted Key + pairD[0].lo = ((PermutedKey_lo >> 8) | (PermutedKey_hi << 24)) & PermutedKeyMask_lo; + pairD[0].hi = ((PermutedKey_hi >> 8) & PermutedKeyMask_hi); + + //Calculate all Cn and Dn. + for(i = 0; i < 16; i++) + { + if(Rotations[i] != 1) + { //Rotate left twice + //hi 26:0 | lo 31:26 + key1 = ((pairC[i].hi << 6) | (pairC[i].lo >> 26)) & Rot2Mask_lo; + //lo 29:0 + //key1|key 4 results in: LLLLLLLLLLLLLLLLLLLLLLLLLLLLLXX, where X is from key1 + key4 = pairC[i].lo << 2; + //hi 31:26 + //This part is discarded. + key2 = (pairC[i].hi >> 26) & Rot2Mask_hi; + //hi 29:2 | lo 31:30 + //key2|key3 results in: HHHHHHHHHHHHHHHHHHHHHHHHHHHHHLL + key3 = (pairC[i].hi << 2) | (pairC[i].lo >> 30); + } else { //Rotate left once + //hi 27:0 | lo 31:27 + key1 = ((pairC[i].hi << 5) | (pairC[i].lo >> 27)) & Rot1Mask_lo; + //lo 30:0 + //key1|key4 results in: LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLX, where X is from key1 + key4 = pairC[i].lo << 1; + //hi 31:27 + //This part is discarded. + key2 = (pairC[i].hi >> 27) & Rot1Mask_hi; + //hi 30:0 | lo 31:31 + //key2:key3 results in: HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHL + key3 = (pairC[i].hi << 1) | (pairC[i].lo >> 31); + } + + //Merge the two rotated parts together, for the hi and low pair. + //Note: hi contains nothing. + pairC[i + 1].lo = (key1 | key4) & PermutedKeyMask_lo; + pairC[i + 1].hi = (key2 | key3) & PermutedKeyMask_hi; + + if(Rotations[i] != 1) + { //Rotate left twice + //hi 26:0 | lo 31:26 + key1 = ((pairD[i].hi << 6) | (pairD[i].lo >> 26)) & Rot2Mask_lo; + //lo 29:0 + //key1|key 4 results in: LLLLLLLLLLLLLLLLLLLLLLLLLLLLLXX, where X is from key1 + key4 = pairD[i].lo << 2; + //hi 31:26 + //This part is discarded. + key2 = (pairD[i].hi >> 26) & Rot2Mask_hi; + //hi 29:2 | lo 31:30 + //key2|key3 results in: HHHHHHHHHHHHHHHHHHHHHHHHHHHHHLL + key3 = (pairD[i].hi << 2) | (pairD[i].lo >> 30); + } else { //Rotate left once + //hi 27:0 | lo 31:27 + key1 = ((pairD[i].hi << 5) | (pairD[i].lo >> 27)) & Rot1Mask_lo; + //lo 30:0 + //key1|key4 results in: LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLX, where X is from key1 + key4 = pairD[i].lo << 1; + //hi 31:27 + //This part is discarded. + key2 = (pairD[i].hi >> 27) & Rot1Mask_hi; + //hi 30:0 | lo 31:31 + //key2:key3 results in: HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHL + key3 = (pairD[i].hi << 1) | (pairD[i].lo >> 31); + } + + //Merge the two rotated parts together, for the hi and low pair. + //Note: hi contains nothing. + pairD[i + 1].lo = (key1 | key4) & PermutedKeyMask_lo; + pairD[i + 1].hi = (key2 | key3) & PermutedKeyMask_hi; + } + + //Phase 3 + BitMask_lo = 0x00000000; + BitMask_hi = 0x80000000; + + // Determine all K, through the Permutation of CnDn by PC-2 + for(pPairC = &pairC[1],pPairD = &pairD[1],pPairK = &pairK[1]; pPairK < &pairK[17]; pPairC++,pPairD++,pPairK++) + { + kVal_lo = 0; + kVal_hi = 0; + BitPerm_lo = 0x00000000; + BitPerm_hi = 0x80000000; + + /* Calculate CnDn: + Note: hi of both Cn and Dn are assumed to, and actually contain nothing. + lo: (D lo 23:0) | (0 7:0) + D lo 23:0 LLLLLLLLLLLLLLLLLLLLLLLL00000000 + 0 7:0 00000000000000000000000000000000 + hi: (C hi 27:0) | (D hi 23:0) | (D lo 31:24) + C lo 27:0 llllllllllllllllllllllllllll0000 + D hi 23:0 HHHHHHHHHHHHHHHHHHHHHHHH00000000 All zero + D lo 31:24 000000000000000000000000XXXXLLLL + + l = C lo L = D lo + h = C hi H = D hi X = unused bits (28/32-bit value) */ + input_lo = 0 | (pPairD->lo << 8); + input_hi = (pPairC->lo << 4) | (pPairD->hi << 8) | (pPairD->lo >> 24); + + for(i = 0; i < 48; i++) + { + shift = PC2[i] - 1; + + if((shift << 26) >= 0) + { //0 to 31-bit shift + if((shift << 26) > 0) //Shift all bits left by shift (hi,lo >> shift) + key1 = (BitMask_lo >> shift) | (BitMask_hi << (-shift)); + else //0-bit shift, which should not happen. + key1 = BitMask_lo >> shift; + + key2 = BitMask_hi >> shift; + } else { //>31-bit shift + key2 = 0; + key1 = BitMask_hi >> shift; + } + + //If bit (shift) is set, set the current bit. + if(((input_lo & key1) | (input_hi & key2)) != 0) + { + kVal_lo |= BitPerm_lo; + kVal_hi |= BitPerm_hi; + } + + //Shift all bits left by 1 (hi,lo >> 1) + BitPerm_lo = (BitPerm_hi << 31) | (BitPerm_lo >> 1); + BitPerm_hi >>= 1; + } + + pPairK->lo = kVal_lo; + pPairK->hi = kVal_hi; + } + + //Phase 4 (Enciphering) + BitMask_lo = 0x00000000; + BitMask_hi = 0x80000000; + BitPerm_lo = 0x00000000; + BitPerm_hi = 0x80000000; + PermutedInput_lo = 0; + PermutedInput_hi = 0; + + //Initial Permutation (IP) + for(i = 0; i < 64; i++) + { + shift = IP[i] - 1; + + if((shift << 26) >= 0) + { //0 to 31-bit shift + if((shift << 26) > 0) //Shift all bits left by shift (hi,lo >> shift) + key1 = (BitMask_lo >> shift) | (BitMask_hi << (-shift)); + else //0-bit shift, which should not happen. + key1 = BitMask_lo >> shift; + + key2 = BitMask_hi >> shift; + } else { //>31-bit shift + key2 = 0; + key1 = BitMask_hi >> shift; + } + + //If bit (shift) is set, set the current bit. + if(((id_lo & key1) | (id_hi & key2)) != 0) + { + PermutedInput_lo |= BitPerm_lo; + PermutedInput_hi |= BitPerm_hi; + } + + //Shift all bits left by 1 (hi,lo >> 1) + BitPerm_lo = (BitPerm_lo >> 1) | (BitPerm_hi << 31); + BitPerm_hi >>= 1; + } + + //Phase 5 (Key-dependent Computation) + BitMask_lo = 0x00000000; + BitMask_hi = 0x80000000; + + //L0 and R0 make up the permuted input block. + //The lo values are not used. + pairL[0].lo = PermutedInput_lo & 0x00000000; + pairL[0].hi = PermutedInput_hi & 0xFFFFFFFF; + pairR[0].lo = 0x00000000; + pairR[0].hi = PermutedInput_lo << 0; + + for (j = 0, k = 1, pPairL = &pairL[1], pPairR = &pairR[1]; pPairR < &pairR[17]; j++, k++, pPairR++, pPairL++) + { + eVal_lo = 0; + eVal_hi = 0; + BitPerm_lo = 0x00000000; + BitPerm_hi = 0x80000000; + + //Ln' = Rn + pPairL->lo = input_lo = pairR[j].lo; + pPairL->hi = input_hi = pairR[j].hi; + + //Calculate E(Rn) + for(i = 0; i < 48; i++) + { + shift = Expansion[i] - 1; + if((shift << 26) >= 0) + { //0 to 31-bit shift + if((shift << 26) > 0) //Shift all bits left by shift (hi,lo >> shift) + key1 = (BitMask_lo >> shift) | (BitMask_hi << (-shift)); + else //0-bit shift, which should not happen. + key1 = BitMask_lo >> shift; + + key2 = BitMask_hi >> shift; + } else { //>31-bit shift + key2 = 0; + key1 = BitMask_hi >> shift; + } + + //If bit (shift) is set, set the current bit. + if(((input_lo & key1) | (input_hi & key2)) != 0) + { + eVal_lo |= BitPerm_lo; + eVal_hi |= BitPerm_hi; + } + + //Shift all bits left by 1 (hi,lo >> 1) + BitPerm_lo = (BitPerm_hi << 31) | (BitPerm_lo >> 1); + BitPerm_hi >>= 1; + } + + //Phase 6 (Substitution Boxes) + sVal_lo = 0; + sVal_hi = 0; + //Calculate Bn = Kn ^ E(Rn) + //Also, shift the 48-bit Expansion value forward towards position 0. + eVal_lo = (eVal_lo ^ pairK[k].lo) >> 16; + eVal_hi = eVal_hi ^ pairK[k].hi; + eVal_lo |= (eVal_hi << 16); + eVal_hi >>= 16; + + //Calculate Sn(Bn), which is stored in the upper 32-bits of the result. + for(i = 0, shift = 32; i < 8; i++, shift += 4) + { + input_lo = sbox[7 - i][((eVal_lo & 0x20) | ((eVal_lo & 0x3F) >> 1 & 0xF) | ((eVal_lo & 0x3F) << 4 & 0x10))]; + //Shift to the next 6-bit B-block + eVal_lo = (eVal_lo >> 6) | (eVal_hi << 26); + eVal_hi >>= 6; + + input_hi = 0; + if((shift << 26) >= 0) + { //0 to 31-bit shift + if((shift << 26) > 0) //Shift all bits right by shift (hi,lo >> shift) + key3 = (input_hi << shift) | (input_lo >> (-shift)); + else //0-bit shift, which should not happen. + key3 = input_hi << shift; + + key4 = input_lo << shift; + } else { //>31-bit shift + key3 = input_lo << shift; + key4 = 0; + } + + sVal_lo |= key4; + sVal_hi |= key3; + } + + //Phase 7 (Permutation with function P) + pVal_lo = 0; + pVal_hi = 0; + BitPerm_lo = 0x00000000; + BitPerm_hi = 0x80000000; + + //Calculate P(Sn(K ^ E(Rn))) + for(i = 0; i < 32; i++) + { + shift = Permutation[i] - 1; + if((shift << 26) >= 0) + { //0 to 31-bit shift + if((shift << 26) > 0) //Shift all bits left by shift (hi,lo >> shift) + key1 = (BitMask_lo >> shift) | (BitMask_hi << (-shift)); + else //0-bit shift, which should not happen. + key1 = BitMask_lo >> shift; + + key2 = BitMask_hi >> shift; + } else { //>31-bit shift + key1 = BitMask_hi >> shift; + key2 = 0; + } + + //If bit (shift) is set, set the current bit. + if(((sVal_lo & key1) | (sVal_hi & key2)) != 0) + { + pVal_lo |= BitPerm_lo; + pVal_hi |= BitPerm_hi; + } + + //Shift all bits left by 1 (hi,lo >> 1) + BitPerm_lo = (BitPerm_lo >> 1) | (BitPerm_hi << 31); + BitPerm_hi >>= 1; + } + + //0x00003bc4 - Rn' = Ln ^ f(Rn,Kn) + pPairR->lo = pairL[j].lo ^ pVal_lo; + pPairR->hi = pairL[j].hi ^ pVal_hi; + } + + //Phase 8 (Final Permutation) + output_lo = 0; + output_hi = 0; + BitMask_lo = BitPerm_lo = 0x00000000; + BitMask_hi = BitPerm_hi = 0x80000000; + //Retrieve preoutput blocks + //Ln and Rn lo do not contain anything, hence they are discarded. + input_lo = pairR[16].lo | (pairL[16].hi >> 0); + input_hi = pairR[16].hi | 0; + + //Subject the preoutput to the Final Permutation + for(i = 0; i < 64; i++) + { + shift = FP[i] - 1; + if((shift << 26) >= 0) + { //0 to 31-bit shift + if((shift << 26) > 0) //Shift all bits left by shift (hi,lo >> shift) + key1 = (BitMask_lo >> shift) | (BitMask_hi << (-shift)); + else //0-bit shift, which should not happen. + key1 = BitMask_lo >> shift; + + key2 = BitMask_hi >> shift; + } else { //>31-bit shift + key1 = BitMask_hi >> shift; + key2 = 0; + } + + //If bit (shift) is set, set the current bit. + if(((input_lo & key1) | (input_hi & key2)) != 0) + { + output_lo |= BitPerm_lo; + output_hi |= BitPerm_hi; + } + + //Shift all bits left by 1 (hi,lo >> 1) + BitPerm_lo = (BitPerm_lo >> 1) | (BitPerm_hi << 31); + BitPerm_hi >>= 1; + } + + //Encrypted output + *(u32*)password_out = output_lo; + *(u32*)(password_out + 4) = output_hi; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/include/libpfs.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/include/libpfs.h new file mode 100644 index 0000000..1813289 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/include/libpfs.h @@ -0,0 +1,346 @@ + +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef __LIBPFS_H__ +#define __LIBPFS_H__ + +#include + +// General constants +#define PFS_BLOCKSIZE 0x2000 +#define PFS_SUPER_MAGIC 0x50465300 // "PFS\0" aka Playstation Filesystem +#define PFS_JOUNRNAL_MAGIC 0x5046534C // "PFSL" aka PFS Log +#define PFS_SEGD_MAGIC 0x53454744 // "SEGD" aka segment descriptor direct +#define PFS_SEGI_MAGIC 0x53454749 // "SEGI" aka segment descriptor indirect +#define PFS_MAX_SUBPARTS 64 +#define PFS_NAME_LEN 255 +#define PFS_FORMAT_VERSION 3 +#define PFS_INODE_MAX_BLOCKS 114 + +// attribute flags +#define PFS_FIO_ATTR_READABLE 0x0001 +#define PFS_FIO_ATTR_WRITEABLE 0x0002 +#define PFS_FIO_ATTR_EXECUTABLE 0x0004 +#define PFS_FIO_ATTR_COPYPROTECT 0x0008 +#define PFS_FIO_ATTR_UNK0010 0x0010 +#define PFS_FIO_ATTR_SUBDIR 0x0020 +#define PFS_FIO_ATTR_UNK0040 0x0040 +#define PFS_FIO_ATTR_CLOSED 0x0080 +#define PFS_FIO_ATTR_UNK0100 0x0100 +#define PFS_FIO_ATTR_UNK0200 0x0200 +#define PFS_FIO_ATTR_UNK0400 0x0400 +#define PFS_FIO_ATTR_PDA 0x0800 +#define PFS_FIO_ATTR_PSX 0x1000 +#define PFS_FIO_ATTR_UNK2000 0x2000 +#define PFS_FIO_ATTR_HIDDEN 0x4000 + +// cache flags (status) +#define PFS_CACHE_FLAG_DIRTY 0x01 +#define PFS_CACHE_FLAG_NOLOAD 0x02 +#define PFS_CACHE_FLAG_MASKSTATUS 0x0F + +// cache flags (types) +#define PFS_CACHE_FLAG_NOTHING 0x00 +#define PFS_CACHE_FLAG_SEGD 0x10 +#define PFS_CACHE_FLAG_SEGI 0x20 +#define PFS_CACHE_FLAG_BITMAP 0x40 +#define PFS_CACHE_FLAG_MASKTYPE 0xF0 + +// fsck stats +#define PFS_FSCK_STAT_OK 0x00 +#define PFS_FSCK_STAT_WRITE_ERROR 0x01 +#define PFS_FSCK_STAT_ERRORS_FIXED 0x02 + +// odd and end +#define PFS_MODE_SET_FLAG 0x00 +#define PFS_MODE_REMOVE_FLAG 0x01 +#define PFS_MODE_CHECK_FLAG 0x02 + +// UID and GID +/* UID and GID are fixed with constants. + Files (and directories) created by the system have UID and GID set to 0, + as they were made with an older library. + + As of release v2.3, the UID and GID were changed to 0xFFFF. + The HDD Browser probably changes the UID and GID to 0xFFFF with chstat, + although I have not verified that. + + If the UID and GID are not set to 0xFFFF, then the software may ignore the entry. */ +#define PFS_UID 0xFFFF +#define PFS_GID 0xFFFF + +// journal/log +typedef struct { + u32 magic; // =PFS_JOUNRNAL_MAGIC + u16 num; // + u16 checksum; // + struct{ + u32 sector; // block/sector for partition + u16 sub; // main(0)/sub(+1) partition + u16 logSector; // block/sector offset in journal area + } log[127]; +} pfs_journal_t; + +// Attribute Entry +typedef struct{ + u8 kLen; // key len/used for offset in to str for value + u8 vLen; // value len + u16 aLen; // allocated length == ((kLen+vLen+7) & ~3) + char str[3]; // size = 3 so sizeof pfs_aentry_t=7 :P +} pfs_aentry_t; + +// Directory Entry +typedef struct { + u32 inode; + u8 sub; + u8 pLen; // path length + u16 aLen; // allocated length == ((pLen+8+3) & ~3) + char path[512-8]; +} pfs_dentry_t; + +// Block number/count pair (used in inodes) +typedef struct { + u32 number; // + u16 subpart; // + u16 count; // +} pfs_blockinfo_t; + +// Date/time descriptor +typedef struct { + u8 unused; // + u8 sec; // + u8 min; // + u8 hour; // + u8 day; // + u8 month; // + u16 year; // +} pfs_datetime_t; + +// Superblock structure +typedef struct { + u32 magic; // + u32 version; // + u32 modver; // + u32 pfsFsckStat; // + u32 zone_size; // + u32 num_subs; // number of subs attached to filesystem + pfs_blockinfo_t log; // block info for metadata log + pfs_blockinfo_t root; // block info for root directory +} pfs_super_block_t; + +// Inode structure +typedef struct { + u32 checksum; // Sum of all other words in the inode + u32 magic; // + pfs_blockinfo_t inode_block; // start block of inode + pfs_blockinfo_t next_segment; // next segment descriptor inode + pfs_blockinfo_t last_segment; // last segment descriptor inode + pfs_blockinfo_t unused; // + pfs_blockinfo_t data[PFS_INODE_MAX_BLOCKS]; // + u16 mode; // file mode + u16 attr; // file attributes + u16 uid; // + u16 gid; // + pfs_datetime_t atime; // + pfs_datetime_t ctime; // + pfs_datetime_t mtime; // + u64 size; // + u32 number_blocks; // number of blocks/zones used by file + u32 number_data; // number of used entries in data array + u32 number_segdesg; // number of "indirect blocks"/next segment descriptor's + u32 subpart; // subpart of inode + u32 reserved[4]; // +} pfs_inode_t; + +typedef struct { + char *devName; + int (*transfer)(int fd, void *buffer, /*u16*/u32 sub, u32 sector, u32 size, u32 mode); + u32 (*getSubNumber)(int fd); + u32 (*getSize)(int fd, /*u16*/u32 sub/*0=main 1+=subs*/); + void (*setPartitionError)(int fd); // set open partition as having an error + int (*flushCache)(int fd); +} pfs_block_device_t; + +typedef struct { + pfs_block_device_t *blockDev; // call table for hdd(hddCallTable) + int fd; // + u32 flags; // rename to attr ones checked + u32 total_zones; // number of zones in the filesystem + u32 zfree; // zone free + u32 sector_scale; // Number of sectors within a zone + u32 inode_scale; // Number of inodes within a zone + u32 zsize; // zone size + u32 num_subs; // number of sub partitions in the filesystem + pfs_blockinfo_t root_dir; // block info for root directory + pfs_blockinfo_t log; // block info for the log + pfs_blockinfo_t current_dir; // block info for current directory + u32 lastError; // 0 if no error :) + u32 free_zone[65]; // free zones in each partition (1 main + 64 possible subs) +} pfs_mount_t; + +typedef struct pfs_cache_s { + struct pfs_cache_s *next; // + struct pfs_cache_s *prev; // + u16 flags; // + u16 nused; // + pfs_mount_t *pfsMount; // + u32 sub; // main(0)/sub(+1) partition + u32 block; // block within for partition + union{ // + void *data; + pfs_inode_t *inode; + pfs_aentry_t *aentry; + pfs_dentry_t *dentry; + pfs_super_block_t *superblock; + u32 *bitmap; + } u; +} pfs_cache_t; + +typedef struct +{ + pfs_cache_t *inode; + u32 block_segment; // index into data array in inode structure for current zone segment + u32 block_offset; // block offset from start of current zone segment + u32 byte_offset; // byte offset into current zone +} pfs_blockpos_t; + +/////////////////////////////////////////////////////////////////////////////// +// Super Block functions + +#define PFS_SUPER_SECTOR 8192 +#define PFS_SUPER_BACKUP_SECTOR 8193 + +int pfsCheckZoneSize(u32 zone_size); +#ifdef PFS_SUPPORT_BHDD +int pfsCheckExtendedZoneSize(u32 zone_size); +#endif +u32 pfsGetBitmapSizeSectors(int zoneScale, u32 partSize); +u32 pfsGetBitmapSizeBlocks(int scale, u32 mainsize); +int pfsFormatSub(pfs_block_device_t *blockDev, int fd, u32 sub, u32 reserved, u32 scale, u32 fragment); +int pfsFormat(pfs_block_device_t *blockDev, int fd, int zonesize, int fragment); +int pfsUpdateSuperBlock(pfs_mount_t *pfsMount, pfs_super_block_t *superblock, u32 sub); +int pfsMountSuperBlock(pfs_mount_t *pfsMount); + +/////////////////////////////////////////////////////////////////////////////// +// Cache functions + +void pfsCacheFree(pfs_cache_t *clink); +void pfsCacheLink(pfs_cache_t *clink, pfs_cache_t *cnew); +pfs_cache_t *pfsCacheUnLink(pfs_cache_t *clink); +pfs_cache_t *pfsCacheUsedAdd(pfs_cache_t *clink); +int pfsCacheTransfer(pfs_cache_t* clink, int mode); +void pfsCacheFlushAllDirty(pfs_mount_t *pfsMount); +pfs_cache_t *pfsCacheAlloc(pfs_mount_t *pfsMount, u16 sub, u32 block, int flags, int *result); +pfs_cache_t *pfsCacheGetData(pfs_mount_t *pfsMount, u16 sub, u32 block, int flags, int *result); +pfs_cache_t *pfsCacheAllocClean(int *result); +int pfsCacheIsFull(void); +int pfsCacheInit(u32 numBuf, u32 bufSize); +void pfsCacheClose(pfs_mount_t *pfsMount); +void pfsCacheMarkClean(pfs_mount_t *pfsMount, u32 subpart, u32 blockStart, u32 blockEnd); + +/////////////////////////////////////////////////////////////////////////////// +// Bitmap functions + +#define PFS_BITMAP_ALLOC 0 +#define PFS_BITMAP_FREE 1 + +typedef struct +{ + u32 chunk; + u32 index; + u32 bit; + u32 partitionChunks; + u32 partitionRemainder; +} pfs_bitmapInfo_t; + +void pfsBitmapSetupInfo(pfs_mount_t *pfsMount, pfs_bitmapInfo_t *info, u32 subpart, u32 number); +void pfsBitmapAllocFree(pfs_cache_t *clink, u32 operation, u32 subpart, u32 chunk, u32 index, u32 _bit, u32 count); +int pfsBitmapAllocateAdditionalZones(pfs_mount_t *pfsMount, pfs_blockinfo_t *bi, u32 count); +int pfsBitmapAllocZones(pfs_mount_t *pfsMount, pfs_blockinfo_t *bi, u32 amount); +int pfsBitmapSearchFreeZone(pfs_mount_t *pfsMount, pfs_blockinfo_t *bi, u32 max_count); +void pfsBitmapFreeBlockSegment(pfs_mount_t *pfsMount, pfs_blockinfo_t *bi); +int pfsBitmapCalcFreeZones(pfs_mount_t *pfsMount, int sub); +void pfsBitmapShow(pfs_mount_t *pfsMount); +void pfsBitmapFreeInodeBlocks(pfs_cache_t *clink); + +/////////////////////////////////////////////////////////////////////////////// +// Block functions + +int pfsBlockSeekNextSegment(pfs_cache_t *clink, pfs_blockpos_t *blockpos); +u32 pfsBlockSyncPos(pfs_blockpos_t *blockpos, u64 size); +int pfsBlockInitPos(pfs_cache_t *clink, pfs_blockpos_t *blockpos, u64 position); +int pfsBlockExpandSegment(pfs_cache_t *clink, pfs_blockpos_t *blockpos, u32 count); +int pfsBlockAllocNewSegment(pfs_cache_t *clink, pfs_blockpos_t *blockpos, u32 blocks); +pfs_blockinfo_t* pfsBlockGetCurrent(pfs_blockpos_t *blockpos); +pfs_cache_t *pfsBlockGetNextSegment(pfs_cache_t *clink, int *result); +pfs_cache_t *pfsBlockGetLastSegmentDescriptorInode(pfs_cache_t *clink, int *result); + +/////////////////////////////////////////////////////////////////////////////// +// Directory-Entry (DEntry) inode functions + +pfs_cache_t *pfsGetDentry(pfs_cache_t *clink, char *path, pfs_dentry_t **dentry, u32 *size, int option); +int pfsGetNextDentry(pfs_cache_t *clink, pfs_blockpos_t *blockpos, u32 *position, char *name, pfs_blockinfo_t *bi); +pfs_cache_t *pfsFillDentry(pfs_cache_t *clink, pfs_dentry_t *dentry, char *path1, pfs_blockinfo_t *bi, u32 len, u16 mode); +pfs_cache_t *pfsDirAddEntry(pfs_cache_t *dir, char *filename, pfs_blockinfo_t *bi, u16 mode, int *result); +pfs_cache_t *pfsDirRemoveEntry(pfs_cache_t *clink, char *path); +int pfsCheckDirForFiles(pfs_cache_t *clink); +void pfsFillSelfAndParentDentries(pfs_cache_t *clink, pfs_blockinfo_t *self, pfs_blockinfo_t *parent); +pfs_cache_t* pfsSetDentryParent(pfs_cache_t *clink, pfs_blockinfo_t *bi, int *result); +pfs_cache_t *pfsInodeGetFileInDir(pfs_cache_t *dirInode, char *path, int *result); +pfs_cache_t *pfsInodeGetFile(pfs_mount_t *pfsMount, pfs_cache_t *clink, const char *name, int *result); +void pfsInodeFill(pfs_cache_t *ci, pfs_blockinfo_t *bi, u16 mode, u16 uid, u16 gid); +int pfsInodeRemove(pfs_cache_t *parent, pfs_cache_t *inode, char *path); +pfs_cache_t *pfsInodeGetParent(pfs_mount_t *pfsMount, pfs_cache_t *clink, const char *filename, char *path, int *result); +pfs_cache_t *pfsInodeCreate(pfs_cache_t *clink, u16 mode, u16 uid, u16 gid, int *result); +int pfsCheckAccess(pfs_cache_t *clink, int flags); +char* pfsSplitPath(char *filename, char *path, int *result); +u16 pfsGetMaxIndex(pfs_mount_t *pfsMount); + +int pfsAllocZones(pfs_cache_t *clink, int msize, int mode); +void pfsFreeZones(pfs_cache_t *pfree); + +/////////////////////////////////////////////////////////////////////////////// +// Inode functions + +void pfsInodePrint(pfs_inode_t *inode); +int pfsInodeCheckSum(pfs_inode_t *inode); +void pfsInodeSetTime(pfs_cache_t *clink); +void pfsInodeSetTimeParent(pfs_cache_t *parent, pfs_cache_t *self); +pfs_cache_t *pfsInodeGetData(pfs_mount_t *pfsMount, u16 sub, u32 inode, int *result); +int pfsInodeSync(pfs_blockpos_t *blockpos, u64 size, u32 used_segments); +pfs_cache_t *pfsGetDentriesChunk(pfs_blockpos_t *position, int *result); +pfs_cache_t *pfsGetDentriesAtPos(pfs_cache_t *clink, u64 position, int *offset, int *result); + +/////////////////////////////////////////////////////////////////////////////// +// Journal functions + +int pfsJournalChecksum(void *header); +void pfsJournalWrite(pfs_mount_t *pfsMount, pfs_cache_t *clink, u32 pfsCacheNumBuffers); +int pfsJournalReset(pfs_mount_t *pfsMount); +int pfsJournalFlush(pfs_mount_t *pfsMount); +int pfsJournalRestore(pfs_mount_t *pfsMount); +int pfsJournalResetThis(pfs_block_device_t *blockDev, int fd, u32 sector); + +/////////////////////////////////////////////////////////////////////////////// +// Function declerations + +int pfsFsckStat(pfs_mount_t *pfsMount, pfs_super_block_t *superblock, u32 stat, int mode); + +void *pfsAllocMem(int size); +void pfsFreeMem(void *buffer); +int pfsGetTime(pfs_datetime_t *tm); +void pfsPrintBitmap(const u32 *bitmap); + +pfs_block_device_t *pfsGetBlockDeviceTable(const char *name); +u32 pfsGetScale(u32 num, u32 size); +u32 pfsFixIndex(u32 index); + +#endif /* _LIBPFS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/bitmap.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/bitmap.c new file mode 100644 index 0000000..aed0144 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/bitmap.c @@ -0,0 +1,385 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS bitmap manipulation routines +*/ + +#include +#include +#include + +#include "pfs-opt.h" +#include "libpfs.h" + +extern u32 pfsMetaSize; +extern u32 pfsBlockSize; + +u32 pfsBitsPerBitmapChunk = 8192; // number of bitmap bits in each bitmap data chunk (1024 bytes) + +void pfsBitmapSetupInfo(pfs_mount_t *pfsMount, pfs_bitmapInfo_t *info, u32 subpart, u32 number) +{ + u32 size; + + size = pfsMount->blockDev->getSize(pfsMount->fd, subpart) >> pfsMount->sector_scale; + + info->chunk = number / pfsBitsPerBitmapChunk; + info->bit = number & 31; + info->index = (number % pfsBitsPerBitmapChunk) / 32; + info->partitionChunks = size / pfsBitsPerBitmapChunk; + info->partitionRemainder = size % pfsBitsPerBitmapChunk; +} + +// Allocates or frees (depending on operation) the bitmap area starting at chunk/index/bit, of size count +void pfsBitmapAllocFree(pfs_cache_t *clink, u32 operation, u32 subpart, u32 chunk, u32 index, u32 _bit, u32 count) +{ + int result; + u32 sector, bit; + u32 *bitmapWord, *bitmapEnd; + + while (clink) + { + bitmapEnd = (u32*)&((u8*)clink->u.bitmap)[pfsMetaSize]; + for (bitmapWord = &clink->u.bitmap[index]; (bitmapWord < bitmapEnd) && count; bitmapWord++, _bit = 0) + { + for (bit = _bit; bit < 32 && count; bit++, count--) + { + if(operation == PFS_BITMAP_ALLOC) + { + if (*bitmapWord & (1 << bit)) + PFS_PRINTF(PFS_DRV_NAME": Error: Tried to allocate used block!\n"); + + *bitmapWord |= (1 << bit); + } + else + { + if ((*bitmapWord & (1 << bit))==0) + PFS_PRINTF(PFS_DRV_NAME": Error: Tried to free unused block!\n"); + + *bitmapWord &= ~(1 << bit); + } + } + } + + index = 0; + clink->flags |= PFS_CACHE_FLAG_DIRTY; + pfsCacheFree(clink); + + if (count==0) + break; + + chunk++; + + sector = (1 << clink->pfsMount->inode_scale) + chunk; + if(subpart==0) + sector += 0x2000 >> pfsBlockSize; + + clink = pfsCacheGetData(clink->pfsMount, subpart, sector, PFS_CACHE_FLAG_BITMAP, &result); + } +} + +// Attempts to allocate 'count' more continuous zones for 'bi' +int pfsBitmapAllocateAdditionalZones(pfs_mount_t *pfsMount, pfs_blockinfo_t *bi, u32 count) +{ + int result; + pfs_bitmapInfo_t info; + pfs_cache_t *c; + int res=0; + u32 bitmapMax; + u32 *bitmapWord, *bitmapEnd; + + pfsBitmapSetupInfo(pfsMount, &info, bi->subpart, bi->number+bi->count); + + // Make sure we're not trying to allocate more than is possible + if ((u32)USHRT_MAX - bi->count < count) + count = USHRT_MAX - bi->count; + + // Loop over each bitmap chunk (each is 1024 bytes in size) until either we have allocated + // the requested amount of blocks, or until we have run out of space on the current partition + while ((((info.partitionRemainder==0) && (info.chunk < info.partitionChunks )) || + ((info.partitionRemainder!=0) && (info.chunk < info.partitionChunks+1))) && count) + { + u32 sector=(1<inode_scale) + info.chunk; + + // if main partition, add offset (in units of blocks) + if (bi->subpart==0) + sector += 0x2000 >> pfsBlockSize; + + // Read the bitmap chunk from the hdd + c=pfsCacheGetData(pfsMount, bi->subpart, sector, PFS_CACHE_FLAG_BITMAP, &result); + if (c==NULL)break; + + // Loop over each 32-bit word in the current bitmap chunk until + // we find a used zone or we've allocated all the zones we need + bitmapMax = info.chunk==info.partitionChunks ? info.partitionRemainder / 8 : pfsMetaSize; + bitmapEnd = (u32*)&((u8*)c->u.bitmap)[bitmapMax]; + for (bitmapWord=&c->u.bitmap[info.index]; (bitmapWord < bitmapEnd) && count; bitmapWord++, info.bit=0) + { + // Loop over each of the 32 bits in the current word from the current bitmap chunk, + // trying to allocate the requested number of zones + for ( ; (info.bit < 32) && count; count--) + { + // We only want to allocate a continuous area, so if we come + // accross a used zone bail + if (*bitmapWord & (1<flags |= PFS_CACHE_FLAG_DIRTY; + } + } + pfsCacheFree(c); + info.index=0; + info.chunk++; + } +exit: + + // Adjust global free zone counts + pfsMount->free_zone[bi->subpart]-=res; + pfsMount->zfree-=res; + return res; +} + +// Searches for 'amount' free zones, starting from the position specified in 'bi'. +// Returns 1 if allocation was successful, otherwise 0. +int pfsBitmapAllocZones(pfs_mount_t *pfsMount, pfs_blockinfo_t *bi, u32 amount) +{ + pfs_bitmapInfo_t info; + int result; + u32 startBit = 0, startPos = 0, startChunk = 0, count = 0; + u32 sector; + pfs_cache_t *bitmap; + u32 *bitmapWord, *bitmapEnd; + u32 i, bitmapMax; + + pfsBitmapSetupInfo(pfsMount, &info, bi->subpart, bi->number); + + for ( ; ((info.partitionRemainder==0) && (info.chunk < info.partitionChunks))|| + ((info.partitionRemainder!=0) && (info.chunk < info.partitionChunks+1)); info.chunk++){ + + sector = info.chunk + (1 << pfsMount->inode_scale); + if(bi->subpart==0) + sector += 0x2000 >> pfsBlockSize; + + // read in the bitmap chunk + bitmap = pfsCacheGetData(pfsMount, bi->subpart, sector, PFS_CACHE_FLAG_BITMAP, &result); + if(bitmap==0) + return 0; + + bitmapMax = info.chunk == info.partitionChunks ? info.partitionRemainder / 8 : pfsMetaSize; + bitmapEnd = (u32*)&((u8*)bitmap->u.bitmap)[bitmapMax]; + for (bitmapWord=&bitmap->u.bitmap[info.index]; bitmapWord < bitmapEnd; info.bit=0, bitmapWord++) + { + for (i=info.bit; i < 32; i++) + { + // if this bit is marked as free.. + if (((*bitmapWord >> i) & 1)==0) + { + if (count==0) + { + startBit = i; + startChunk = info.chunk; + startPos = bitmapWord - bitmap->u.bitmap; + } + if (++count == amount) + { + bi->number = (startPos * 32) + (startChunk * pfsBitsPerBitmapChunk) + startBit; + if (count < bi->count) + bi->count=count; + + if (bitmap->block != (startChunk + (1 << pfsMount->inode_scale))) + { + pfsCacheFree(bitmap); + sector = (1 << pfsMount->inode_scale) + startChunk; + if(bi->subpart==0) + sector += 0x2000 >> pfsBlockSize; + + bitmap = pfsCacheGetData(pfsMount, bi->subpart, sector, PFS_CACHE_FLAG_BITMAP, &result); + } + + pfsBitmapAllocFree(bitmap, PFS_BITMAP_ALLOC, bi->subpart, startChunk, startPos, startBit, bi->count); + return 1; + } + } + else + count=0; + } + } + pfsCacheFree(bitmap); + info.index=0; + } + return 0; +} + +// Searches for 'max_count' free zones over all the partitions, and +// allocates them. Returns 0 on success, -ENOSPC if the zones could +// not be allocated. +int pfsBitmapSearchFreeZone(pfs_mount_t *pfsMount, pfs_blockinfo_t *bi, u32 max_count) +{ + u32 num, count, n; + + num = pfsMount->num_subs + 1; + + if (bi->subpart >= num) + bi->subpart = 0; + if (bi->number) + num = pfsMount->num_subs + 2; + + count = max_count < 33 ? max_count : 32; //min(max_count, 32) + if(count < bi->count) + count = bi->count; //max(count, bi->count) + // => count = bound(bi->count, 32); + for(--num; num >= 0; num--) + { + for (n = count; n; n /= 2) + { + if ((pfsMount->free_zone[bi->subpart] >= n) && + pfsBitmapAllocZones(pfsMount, bi, n)) + { + pfsMount->free_zone[bi->subpart] -= bi->count; + pfsMount->zfree -= bi->count; + return 0; // the good exit ;) + } + } + + bi->number=0; + bi->subpart++; + + if(bi->subpart == pfsMount->num_subs + 1) + bi->subpart=0; + } + return -ENOSPC; +} + +// De-allocates the block segment 'bi' in the bitmaps +void pfsBitmapFreeBlockSegment(pfs_mount_t *pfsMount, pfs_blockinfo_t *bi) +{ + pfs_bitmapInfo_t info; + pfs_cache_t *clink; + u32 sector; + int rv; + + pfsBitmapSetupInfo(pfsMount, &info, bi->subpart, bi->number); + + sector = (1 << pfsMount->inode_scale) + info.chunk; + if(bi->subpart==0) + sector += 0x2000 >> pfsBlockSize; + + if((clink=pfsCacheGetData(pfsMount, (u16)bi->subpart, sector, PFS_CACHE_FLAG_BITMAP, &rv)) != NULL) + { + pfsBitmapAllocFree(clink, PFS_BITMAP_FREE, bi->subpart, info.chunk, info.index, info.bit, bi->count); + pfsMount->free_zone[(u16)bi->subpart]+=bi->count; + pfsMount->zfree+=bi->count; + } +} + +// Returns the number of free zones for the partition 'sub' +int pfsBitmapCalcFreeZones(pfs_mount_t *pfsMount, int sub) +{ + // "Free zone" map. Used to get number of free zone in bitmap, 4-bits at a time + u32 pfsFreeZoneBitmap[16]={4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0}; + int result; + pfs_bitmapInfo_t info; + pfs_cache_t *clink; + u32 i, bitmapSize, zoneFree=0, sector; + + pfsBitmapSetupInfo(pfsMount, &info, sub, 0); + + while (((info.partitionRemainder!=0) && (info.chunkinode_scale) + info.chunk; + if (sub==0) + sector +=0x2000>>pfsBlockSize; + + if ((clink=pfsCacheGetData(pfsMount, sub, sector, PFS_CACHE_FLAG_BITMAP, &result))) + { + for (i=0; iu.bitmap)[i] & 0xF] + +pfsFreeZoneBitmap[((u8*)clink->u.bitmap)[i] >> 4]; + } + + pfsCacheFree(clink); + } + info.chunk++; + } + + return zoneFree; +} + +// Debugging function, prints bitmap information +void pfsBitmapShow(pfs_mount_t *pfsMount) +{ + int result; + pfs_bitmapInfo_t info; + u32 pn, bitcnt; + + for (pn=0; pn < pfsMount->num_subs+1; pn++) + { + bitcnt=pfsBitsPerBitmapChunk; + pfsBitmapSetupInfo(pfsMount, &info, pn, 0); + + while (((info.partitionRemainder!=0) && (info.chunkinode_scale) + info.chunk; + u32 i; + + if(pn==0) + sector += 0x2000 >> pfsBlockSize; + clink=pfsCacheGetData(pfsMount, pn, sector, PFS_CACHE_FLAG_BITMAP, &result); + + if (info.chunk == info.partitionChunks) + bitcnt=info.partitionRemainder; + + PFS_PRINTF(PFS_DRV_NAME": Zone show: pn %ld, bn %ld, bitcnt %ld\n", pn, info.chunk, bitcnt); + + for(i=0; (i < (u32)(1<u.bitmap+128*i); + + pfsCacheFree(clink); + info.chunk++; + } + } +} + +// Free's all blocks allocated to an inode +void pfsBitmapFreeInodeBlocks(pfs_cache_t *clink) +{ + pfs_mount_t *pfsMount=clink->pfsMount; + u32 i; + + pfsCacheUsedAdd(clink); + for(i=0;i < clink->u.inode->number_data; i++) + { + u32 index = pfsFixIndex(i); + pfs_blockinfo_t *bi=&clink->u.inode->data[index]; + int err; + + if(i!=0) { + if(index==0) + if((clink = pfsBlockGetNextSegment(clink, &err))==NULL) + return; + } + + pfsBitmapFreeBlockSegment(pfsMount, bi); + pfsCacheMarkClean(pfsMount, (u16)bi->subpart, bi->number << pfsMount->inode_scale, + (bi->number + bi->count) << pfsMount->inode_scale); + } + pfsCacheFree(clink); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/block.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/block.c new file mode 100644 index 0000000..d1fbe4b --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/block.c @@ -0,0 +1,99 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS block/zone related routines +*/ + +#include +#include +#ifdef _IOP +#include +#else +#include +#endif + +#include "pfs-opt.h" +#include "libpfs.h" + +// Returns the next block descriptor inode +pfs_cache_t *pfsBlockGetNextSegment(pfs_cache_t *clink, int *result) +{ + pfsCacheFree(clink); + + if (clink->u.inode->next_segment.number) + return pfsCacheGetData(clink->pfsMount, + clink->u.inode->next_segment.subpart, + clink->u.inode->next_segment.number << clink->pfsMount->inode_scale, + PFS_CACHE_FLAG_SEGI, result); + + PFS_PRINTF(PFS_DRV_NAME": Error: There is no next segment descriptor\n"); + *result=-EINVAL; + return NULL; +} + +// Sets 'blockpos' to point to the next block segment for the inode (and moves onto the +// next block descriptor inode if necessary) +int pfsBlockSeekNextSegment(pfs_cache_t *clink, pfs_blockpos_t *blockpos) +{ + pfs_cache_t *nextSegment; + int result=0; + + if (blockpos->byte_offset) + { + PFS_PRINTF(PFS_DRV_NAME": Panic: This is a bug!\n"); + return -1; + } + + // If we're at the end of the block descriptor array for the current + // inode, then move onto the next inode + if (pfsFixIndex(blockpos->block_segment+1)==0) + { + if ((nextSegment=pfsBlockGetNextSegment(pfsCacheUsedAdd(blockpos->inode), &result)) == NULL) + return result; + pfsCacheFree(blockpos->inode); + blockpos->inode=nextSegment; + if (clink->u.inode->number_data-1 == ++blockpos->block_segment) + return -EINVAL; + } + + blockpos->block_offset=0; + blockpos->block_segment++; + return result; +} + +u32 pfsBlockSyncPos(pfs_blockpos_t *blockpos, u64 size) +{ + u32 i; + + i = (u32)(size / blockpos->inode->pfsMount->zsize); + blockpos->byte_offset += size % blockpos->inode->pfsMount->zsize; + + if (blockpos->byte_offset >= blockpos->inode->pfsMount->zsize) + { + blockpos->byte_offset -= blockpos->inode->pfsMount->zsize; + i++; + } + return i; +} + +int pfsBlockInitPos(pfs_cache_t *clink, pfs_blockpos_t *blockpos, u64 position) +{ + blockpos->inode=pfsCacheUsedAdd(clink); + blockpos->byte_offset=0; + + if (clink->u.inode->size) + { + blockpos->block_segment=1; + blockpos->block_offset=0; + }else{ + blockpos->block_segment=0; + blockpos->block_offset=1; + } + return pfsInodeSync(blockpos, position, clink->u.inode->number_data); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/blockWrite.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/blockWrite.c new file mode 100644 index 0000000..37e8eaa --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/blockWrite.c @@ -0,0 +1,146 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS block/zone (write) related routines +*/ + +#include +#include +#ifdef _IOP +#include +#else +#include +#endif + +#include "pfs-opt.h" +#include "libpfs.h" + +// Attempt to expand the block segment 'blockpos' by 'count' blocks +int pfsBlockExpandSegment(pfs_cache_t *clink, pfs_blockpos_t *blockpos, u32 count) +{ + int ret; + pfs_blockinfo_t *bi; + + if(pfsFixIndex(blockpos->block_segment)==0) + return 0; + + bi = &blockpos->inode->u.inode->data[pfsFixIndex(blockpos->block_segment)]; + + if ((ret = pfsBitmapAllocateAdditionalZones(clink->pfsMount, bi, count))) + { + bi->count+=ret; + clink->u.inode->number_blocks+=ret; + blockpos->inode->flags |= PFS_CACHE_FLAG_DIRTY; + clink->flags |= PFS_CACHE_FLAG_DIRTY; + } + + return ret; +} + +// Attempts to allocate 'blocks' new blocks for an inode +int pfsBlockAllocNewSegment(pfs_cache_t *clink, pfs_blockpos_t *blockpos, u32 blocks) +{ + pfs_blockinfo_t bi, *bi2; + int result=0; + pfs_mount_t *pfsMount=clink->pfsMount; + u32 i, old_blocks = blocks; + + if (pfsCacheIsFull()) + return -ENOMEM; + + // create "indirect segment descriptor" if necessary + if (pfsFixIndex(clink->u.inode->number_data) == 0) + { + pfs_cache_t *clink2; + + bi2 = &blockpos->inode->u.inode->data[pfsFixIndex(blockpos->block_segment)]; + bi.subpart=bi2->subpart; + bi.count=1; + bi.number=bi2->number+bi2->count; + result=pfsBitmapSearchFreeZone(pfsMount, &bi, clink->u.inode->number_blocks); + if (result<0) + { + PFS_PRINTF(PFS_DRV_NAME": Error: Couldnt allocate zone! (1)\n"); + return result; + } + + clink2=pfsCacheGetData(pfsMount, bi.subpart, bi.number << pfsMount->inode_scale, + PFS_CACHE_FLAG_SEGI | PFS_CACHE_FLAG_NOLOAD, &result); + memset(clink2->u.inode, 0, sizeof(pfs_inode_t)); + clink2->u.inode->magic=PFS_SEGI_MAGIC; + + memcpy(&clink2->u.inode->inode_block, &clink->u.inode->inode_block, sizeof(pfs_blockinfo_t)); + memcpy(&clink2->u.inode->last_segment, &blockpos->inode->u.inode->data[0], sizeof(pfs_blockinfo_t)); + memcpy(&clink2->u.inode->data[0], &bi, sizeof(pfs_blockinfo_t)); + + clink2->flags |= PFS_CACHE_FLAG_DIRTY; + + clink->u.inode->number_blocks+=bi.count; + clink->u.inode->number_data++; + + memcpy(&clink->u.inode->last_segment, &bi, sizeof(pfs_blockinfo_t)); + + clink->u.inode->number_segdesg++; + + clink->flags |= PFS_CACHE_FLAG_DIRTY; + blockpos->block_segment++; + blockpos->block_offset=0; + + memcpy(&blockpos->inode->u.inode->next_segment, &bi, sizeof(pfs_blockinfo_t)); + + blockpos->inode->flags |= PFS_CACHE_FLAG_DIRTY; + pfsCacheFree(blockpos->inode); + blockpos->inode=clink2; + } + + bi2 = &blockpos->inode->u.inode->data[pfsFixIndex(blockpos->block_segment)]; + bi.subpart = bi2->subpart; + bi.count = blocks; + bi.number = bi2->number + bi2->count; + + result = pfsBitmapSearchFreeZone(pfsMount, &bi, clink->u.inode->number_blocks); + if(result < 0) + { + PFS_PRINTF(PFS_DRV_NAME": Error: Couldnt allocate zone! (2)\n"); + return result; + } + + clink->u.inode->number_blocks += bi.count; + clink->u.inode->number_data++; + clink->flags |= PFS_CACHE_FLAG_DIRTY; + blockpos->block_offset=0; + blockpos->block_segment++; + + i = pfsFixIndex(clink->u.inode->number_data-1); + memcpy(&blockpos->inode->u.inode->data[i], &bi, sizeof(pfs_blockinfo_t)); + + blockpos->inode->flags |= PFS_CACHE_FLAG_DIRTY; + blocks -= bi.count; + if (blocks) + blocks -= pfsBlockExpandSegment(clink, blockpos, blocks); + + return old_blocks - blocks; +} + +// Returns the block info for the block segment corresponding to the +// files current position. +pfs_blockinfo_t* pfsBlockGetCurrent(pfs_blockpos_t *blockpos) +{ + return &blockpos->inode->u.inode->data[pfsFixIndex(blockpos->block_segment)]; +} + +pfs_cache_t *pfsBlockGetLastSegmentDescriptorInode(pfs_cache_t *clink, int *result) +{ + return pfsCacheGetData(clink->pfsMount, clink->u.inode->last_segment.subpart, + clink->u.inode->last_segment.number<pfsMount->inode_scale, + (clink->u.inode->last_segment.subpart== + clink->u.inode->inode_block.subpart)&& + (clink->u.inode->last_segment.number== + clink->u.inode->inode_block.number) ? 16 : 32, result); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/cache.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/cache.c new file mode 100644 index 0000000..e29bf35 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/cache.c @@ -0,0 +1,261 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS metadata cache manipulation routines +*/ + +#include +#include +#ifdef _IOP +#include +#else +#include +#endif +#include + +#include "pfs-opt.h" +#include "libpfs.h" + +extern u32 pfsBlockSize; + +pfs_cache_t *pfsCacheBuf; +u32 pfsCacheNumBuffers; + +void pfsCacheFree(pfs_cache_t *clink) +{ + if(clink==NULL) { + PFS_PRINTF(PFS_DRV_NAME": Warning: NULL buffer returned\n"); + return; + } + + if(clink->nused==0){ + PFS_PRINTF(PFS_DRV_NAME": Error: Unused cache returned\n"); + return; + } + + clink->nused--; + if(clink->pfsMount!=NULL) { + if(clink->nused!=0) + return; + pfsCacheLink(pfsCacheBuf->prev, clink); + return; + } + if(clink->nused!=0) { + PFS_PRINTF(PFS_DRV_NAME": Warning: Invalidated buffer is in use\n"); + return; + } + pfsCacheLink(pfsCacheBuf, clink); +} + +void pfsCacheLink(pfs_cache_t *clink, pfs_cache_t *cnew) +{ + cnew->prev=clink; + cnew->next=clink->next; + clink->next->prev=cnew; + clink->next=cnew; +} + +pfs_cache_t *pfsCacheUnLink(pfs_cache_t *clink) +{ + clink->prev->next=clink->next; + clink->next->prev=clink->prev; + return clink; +} + +pfs_cache_t *pfsCacheUsedAdd(pfs_cache_t *clink) +{ + clink->nused++; + return clink; +} + +int pfsCacheTransfer(pfs_cache_t* clink, int mode) +{ + pfs_mount_t *pfsMount=clink->pfsMount; + int err; + + if(pfsMount->lastError == 0) { // no error + if((err=pfsMount->blockDev->transfer(pfsMount->fd, clink->u.data, clink->sub, + clink->block << pfsBlockSize, 1 << pfsBlockSize, mode))==0) { + if(mode==PFS_IO_MODE_READ) { + if(clink->flags & PFS_CACHE_FLAG_SEGD && ((pfs_inode_t *)clink->u.inode)->magic!=PFS_SEGD_MAGIC) + err=-EIO; + if(clink->flags & PFS_CACHE_FLAG_SEGI && ((pfs_inode_t *)clink->u.inode)->magic!=PFS_SEGI_MAGIC) + err=-EIO; + if(clink->flags & (PFS_CACHE_FLAG_SEGD|PFS_CACHE_FLAG_SEGI)) { + if(((pfs_inode_t *)clink->u.inode)->checksum!=pfsInodeCheckSum(clink->u.inode)) + err=-EIO; + } + } + } + if(err!=0) { + PFS_PRINTF(PFS_DRV_NAME": Error: Disk error partition %ld, block %ld, err %d\n", + clink->sub, clink->block, err); +#ifndef PFS_NO_WRITE_ERROR_STAT + pfsMount->blockDev->setPartitionError(pfsMount->fd); + pfsFsckStat(pfsMount, clink->u.superblock, PFS_FSCK_STAT_WRITE_ERROR, PFS_MODE_SET_FLAG); + pfsMount->lastError=err; +#endif + } + } + clink->flags&=~PFS_CACHE_FLAG_DIRTY; // clear dirty :) + return pfsMount->lastError; +} + +void pfsCacheFlushAllDirty(pfs_mount_t *pfsMount) +{ + u32 i; + int found=0; + + for(i=1;iprev==pfsCacheBuf && pfsCacheBuf->prev->next==pfsCacheBuf->prev) { + PFS_PRINTF(PFS_DRV_NAME": Error: Free buffer list is empty\n"); + *result=-ENOMEM; + return NULL; + } + allocated=pfsCacheBuf->next; + if (pfsCacheBuf->next==NULL) + PFS_PRINTF(PFS_DRV_NAME": Panic: Null pointer allocated\n"); + if (allocated->pfsMount && (allocated->flags & PFS_CACHE_FLAG_DIRTY)) + pfsCacheFlushAllDirty(allocated->pfsMount); + allocated->flags = flags & PFS_CACHE_FLAG_MASKTYPE; + allocated->pfsMount = pfsMount; + allocated->sub = sub; + allocated->block = block; + allocated->nused = 1; + return pfsCacheUnLink(allocated); +} + +pfs_cache_t *pfsCacheGetData(pfs_mount_t *pfsMount, u16 sub, u32 block, + int flags, int *result) +{ + u32 i; + pfs_cache_t *clink; + + *result=0; + + for (i=1; i < pfsCacheNumBuffers + 1; i++) + if ( pfsCacheBuf[i].pfsMount && + (pfsCacheBuf[i].pfsMount==pfsMount) && + (pfsCacheBuf[i].block == block)) + if (pfsCacheBuf[i].sub==sub){ + pfsCacheBuf[i].flags &= PFS_CACHE_FLAG_MASKSTATUS; + pfsCacheBuf[i].flags |= flags & PFS_CACHE_FLAG_MASKTYPE; + if (pfsCacheBuf[i].nused == 0) + pfsCacheUnLink(&pfsCacheBuf[i]); + pfsCacheBuf[i].nused++; + return &pfsCacheBuf[i]; + } + + clink=pfsCacheAlloc(pfsMount, sub, block, flags, result); + + if (clink){ + if (flags & PFS_CACHE_FLAG_NOLOAD) + return clink; + + if ((*result=pfsCacheTransfer(clink, PFS_IO_MODE_READ))>=0) + return clink; + + clink->pfsMount=NULL; + pfsCacheFree(clink); + } + return NULL; +} + +pfs_cache_t *pfsCacheAllocClean(int *result) +{ + *result = 0; + return pfsCacheAlloc(NULL, 0, 0, 0, result); +} + +// checks if the pfsCacheBuf list has some room +int pfsCacheIsFull(void) +{ + if (pfsCacheBuf->prev != pfsCacheBuf) return 0; + return pfsCacheBuf->prev->next == pfsCacheBuf->prev; +} + +int pfsCacheInit(u32 numBuf, u32 bufSize) +{ + char *cacheData; + u32 i; + + if(numBuf > 127) { + PFS_PRINTF(PFS_DRV_NAME": Error: Number of buffers larger than 127.\n"); + return -EINVAL; + } + + cacheData = pfsAllocMem(numBuf * bufSize); + + if(!cacheData || !(pfsCacheBuf = pfsAllocMem((numBuf + 1) * sizeof(pfs_cache_t)))) + return -ENOMEM; + + pfsCacheNumBuffers = numBuf; + memset(pfsCacheBuf, 0, (numBuf + 1) * sizeof(pfs_cache_t)); + + pfsCacheBuf->next = pfsCacheBuf; + pfsCacheBuf->prev = pfsCacheBuf; + + for(i = 1; i < numBuf + 1; i++) + { + pfsCacheBuf[i].u.data = cacheData; + pfsCacheLink(pfsCacheBuf->prev, &pfsCacheBuf[i]); + cacheData += bufSize; + } + + return 0; +} + +void pfsCacheClose(pfs_mount_t *pfsMount) +{ + unsigned int i; + +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") != 0) +#endif + { + pfsCacheFlushAllDirty(pfsMount); + } + for(i=1; i < pfsCacheNumBuffers+1;i++){ + if(pfsCacheBuf[i].pfsMount==pfsMount) + pfsCacheBuf[i].pfsMount=NULL; + } +} + +void pfsCacheMarkClean(pfs_mount_t *pfsMount, u32 subpart, u32 blockStart, u32 blockEnd) +{ + u32 i; + + for(i=1; i< pfsCacheNumBuffers+1;i++){ + if(pfsCacheBuf[i].pfsMount==pfsMount && pfsCacheBuf[i].sub==subpart) { + if(pfsCacheBuf[i].block >= blockStart && pfsCacheBuf[i].block < blockEnd) + pfsCacheBuf[i].flags&=~PFS_CACHE_FLAG_DIRTY; + } + } +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/dir.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/dir.c new file mode 100644 index 0000000..2f92107 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/dir.c @@ -0,0 +1,718 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS directory parsing routines +*/ + +#include +#include +#ifdef _IOP +#include +#else +#include +#endif +#include + +#include "pfs-opt.h" +#include "libpfs.h" + +extern u32 pfsMetaSize; + +// Gets a dir entry from the inode specified by clink +pfs_cache_t *pfsGetDentry(pfs_cache_t *clink, char *path, pfs_dentry_t **dentry, u32 *size, int option) +{ + pfs_blockpos_t block_pos; + pfs_dentry_t *d; + u16 aLen; + pfs_dentry_t *d2; + pfs_cache_t *dentCache; + u32 new_dentryLen=0,dentryLen; + int len=0, result; + + if (path) + { + len = strlen(path); + new_dentryLen = (len+8+3) &~3; + } + *size = 0; + + block_pos.inode = pfsCacheUsedAdd(clink); + block_pos.block_segment = 1; + block_pos.block_offset = 0; + block_pos.byte_offset = 0; + dentCache = pfsGetDentriesChunk(&block_pos, &result); + + if (dentCache != NULL) + { + d2=d=dentCache->u.dentry; + while(*size < clink->u.inode->size) + { + // Read another dentry chunk if we need to + if (d2 >= (pfs_dentry_t*)((u8*)dentCache->u.inode + pfsMetaSize)) + { + if (pfsInodeSync(&block_pos, pfsMetaSize, clink->u.inode->number_data)) + break; + pfsCacheFree(dentCache); + + if ((dentCache=pfsGetDentriesChunk(&block_pos, &result)) == NULL) + break; + d=dentCache->u.dentry; + } + + // Scan through the sector. + for (d2=(pfs_dentry_t*)((u8*)d+512); d < d2; d=(pfs_dentry_t *)((u8*)d + aLen)) + { + aLen=(d->aLen & 0xFFF); + + if (aLen & 3){ + PFS_PRINTF(PFS_DRV_NAME": Error: dentry allocated length/4 != 0\n"); + goto _exit; + } + dentryLen = (d->pLen + 8 + 3) & 0x1FC; + if (aLen < dentryLen){ + PFS_PRINTF(PFS_DRV_NAME": Error: dentry is too small\n"); + goto _exit; + } + if (d2 < (pfs_dentry_t*)((u8*)d + aLen)){ + PFS_PRINTF(PFS_DRV_NAME": Error: dentry across sectors\n"); + goto _exit; + } + + // decide if the current dentry meets the required criteria, based on 'option' + switch(option) + { + case 0: // result = 1 when paths are equal + result = (len==d->pLen) && (memcmp(path, d->path, d->pLen)==0); + break; + case 1: // result = 1 when either there is no inode or if there is enough space remaining in the inode. + result = ((d->inode) || (aLen < new_dentryLen)) ? (aLen - dentryLen + >= new_dentryLen) : 1; + break; + case 2: // result = 1 when dir path is not empty, "." or ".." + result = d->pLen && strcmp(d->path, ".") && strcmp(d->path, ".."); + break; + default: + goto _exit; + } + + if (result) + { + *dentry=d; + pfsCacheFree(block_pos.inode); + return dentCache; + } + *size+=aLen; + } + } +_exit: pfsCacheFree(dentCache); + } + pfsCacheFree(block_pos.inode); + return NULL; +} + +int pfsGetNextDentry(pfs_cache_t *clink, pfs_blockpos_t *blockpos, u32 *position, char *name, pfs_blockinfo_t *bi) +{ + int result; + pfs_cache_t *dcache; + pfs_dentry_t *dentry; + u32 len=0; + + // loop until a non-empty entry is found or until the end of the dentry chunk is reached + while((len == 0) && (*position < clink->u.inode->size)) + { + + if (!(dcache=pfsGetDentriesChunk(blockpos, &result))) + { + PFS_PRINTF(PFS_DRV_NAME": couldnt get dentries chunk for dread!\n"); + break; + } + + dentry = (pfs_dentry_t*)((u8*)dcache->u.data + (blockpos->byte_offset % pfsMetaSize)); + + len = dentry->pLen; + memcpy(name, dentry->path, len); + name[len] = '\0'; + + bi->subpart = dentry->sub; + bi->number = dentry->inode; + pfsCacheFree(dcache); + + *position += dentry->aLen & 0xFFF; + + // update blockpos + if (pfsInodeSync(blockpos, dentry->aLen & 0xFFF, clink->u.inode->number_data)) + break; + } + + return len; +} + +pfs_cache_t *pfsFillDentry(pfs_cache_t *clink, pfs_dentry_t *dentry, char *path1, pfs_blockinfo_t *bi, u32 len, u16 mode) +{ + dentry->inode=bi->number; + dentry->sub=(u8)bi->subpart; + dentry->pLen=strlen(path1); + dentry->aLen=len | (mode & FIO_S_IFMT); + memcpy(dentry->path, path1, dentry->pLen & 0xFF); + + return clink; +} + +pfs_cache_t *pfsDirAddEntry(pfs_cache_t *dir, char *filename, pfs_blockinfo_t *bi, u16 mode, int *result) +{ + pfs_dentry_t *dentry; + u32 size; + u32 len; + pfs_cache_t *dcache; + + dcache=pfsGetDentry(dir, filename, &dentry, &size, 1); + if (dcache != NULL){ + len=dentry->aLen & 0xFFF; + if (dentry->pLen) + len-=(dentry->pLen + 11) & 0x1FC; + dentry->aLen=(dentry->aLen & FIO_S_IFMT) | ((dentry->aLen & 0xFFF) - len); + dentry=(pfs_dentry_t *)((u8*)dentry + (dentry->aLen & 0xFFF)); + }else{ + int offset; + + if ((*result=pfsAllocZones(dir, sizeof(pfs_dentry_t), 0))<0) + return NULL; + dcache=pfsGetDentriesAtPos(dir, dir->u.inode->size, &offset, result); + if (dcache==NULL) + return NULL; + + dir->u.inode->size += sizeof(pfs_dentry_t); + + dentry=(pfs_dentry_t*)((u8*)dcache->u.dentry+offset); + len=sizeof(pfs_dentry_t); + } + return pfsFillDentry(dcache, dentry, filename, bi, len, mode); +} + +pfs_cache_t *pfsDirRemoveEntry(pfs_cache_t *clink, char *path) +{ + pfs_dentry_t *dentry; + u32 size; + u16 aLen; + int i=0, val; + pfs_dentry_t *dlast=NULL, *dnext; + pfs_cache_t *c; + + if ((c=pfsGetDentry(clink, path, &dentry, &size, 0)) != NULL){ + val=(int)dentry-(int)c->u.dentry; + if (val<0) val +=511; + val /=512; + val *=512; + + dnext=(pfs_dentry_t*)((u8*)c->u.dentry+val); + do{ + aLen = dnext->aLen & 0xFFF; + + if (dnext==dentry){ + if (dlast) + dlast->aLen=(dlast->aLen & FIO_S_IFMT) | ((dlast->aLen & 0xFFF) + aLen); + else{ + dnext->inode=0; + dnext->pLen=0; + + if (size+aLen >= clink->u.inode->size) + clink->u.inode->size -= aLen; + } + return c; + } + i+=aLen; + dlast=dnext; + dnext=(pfs_dentry_t *)((u8*)dnext + aLen); + }while (i<512); + } + return NULL; +} + +int pfsCheckDirForFiles(pfs_cache_t *clink) +{ + pfs_dentry_t *dentry; + pfs_cache_t *dcache; + u32 size; + + if((dcache=pfsGetDentry(clink, NULL, &dentry, &size, 2))){ + pfsCacheFree(dcache); + return 0; + } + return 1; +} + +void pfsFillSelfAndParentDentries(pfs_cache_t *clink, pfs_blockinfo_t *self, pfs_blockinfo_t *parent) +{ + pfs_dentry_t *dentry=clink->u.dentry; + + memset(dentry, 0, pfsMetaSize); + dentry->inode=self->number; + dentry->path[0]='.'; + dentry->path[1]='\0'; + dentry->sub=(u8)self->subpart; + dentry->pLen=1; + dentry->aLen=12 | FIO_S_IFDIR; + + dentry=(pfs_dentry_t *)((u8*)dentry + 12); + + dentry->inode=parent->number; + dentry->path[0]='.'; + dentry->path[1]='.'; + dentry->path[2]='\0'; + dentry->sub=(u8)parent->subpart; + dentry->pLen=2; + dentry->aLen=500 | FIO_S_IFDIR; +} + +pfs_cache_t* pfsSetDentryParent(pfs_cache_t *clink, pfs_blockinfo_t *bi, int *result) +{ + int offset; + pfs_cache_t *dcache; + + dcache=pfsGetDentriesAtPos(clink, 0, &offset, result); + if (dcache){ + pfs_dentry_t *d=(pfs_dentry_t*)(12+(u8*)dcache->u.data); + d->inode=bi->number; + d->sub =(u8)bi->subpart; + } + return dcache; +} + +// Returns the cached inode for the file (dir) in the directory pointed +// to by the dir inode. +pfs_cache_t *pfsInodeGetFileInDir(pfs_cache_t *dirInode, char *path, int *result) +{ + pfs_dentry_t *dentry; + u32 size; + pfs_cache_t *clink; + + if (path[0]==0) + return pfsCacheUsedAdd(dirInode); + + // If we're in the root dir, don't do anything for ".." + if ((dirInode->block == + dirInode->pfsMount->root_dir.number << dirInode->pfsMount->inode_scale) && + (dirInode->sub == dirInode->pfsMount->root_dir.subpart) && + (strcmp(path, "..") == 0)) + return pfsCacheUsedAdd(dirInode); + + if ((*result=pfsCheckAccess(dirInode, 1)) < 0) + return NULL; + + // Get dentry of file/dir specified by path from the dir pointed to + // by the inode (dirInode). Then return the cached inode for that dentry. + if ((clink=pfsGetDentry(dirInode, path, &dentry, &size, 0))){ + pfsCacheFree(clink); + return pfsInodeGetData(dirInode->pfsMount, + dentry->sub, dentry->inode, result); + } + + *result=-ENOENT; + return NULL; +} + +pfs_cache_t *pfsInodeGetFile(pfs_mount_t *pfsMount, pfs_cache_t *clink, + const char *name, int *result) { + char path[256]; + pfs_cache_t *c,*fileInode; + + c=pfsInodeGetParent(pfsMount, clink, name, path, result); + if (c){ + fileInode=pfsInodeGetFileInDir(c, path, result); + pfsCacheFree(c); + return fileInode; + } + return NULL; +} + +void pfsInodeFill(pfs_cache_t *ci, pfs_blockinfo_t *bi, u16 mode, u16 uid, u16 gid) +{ + u32 val; + + memset(ci->u.inode, 0, pfsMetaSize); + + ci->u.inode->magic=PFS_SEGD_MAGIC; + + ci->u.inode->inode_block.number=bi->number; + ci->u.inode->inode_block.subpart=bi->subpart; + ci->u.inode->inode_block.count=bi->count; + + ci->u.inode->last_segment.number=bi->number; + ci->u.inode->last_segment.subpart=bi->subpart; + ci->u.inode->last_segment.count=bi->count; + + ci->u.inode->mode=mode; + ci->u.inode->uid=uid; + ci->u.inode->gid=gid; + + if ((mode & FIO_S_IFMT) == FIO_S_IFDIR){ + ci->u.inode->attr=0xA0; + ci->u.inode->size=sizeof(pfs_dentry_t); + val=2; + }else{ + ci->u.inode->size=0; + val=1; + } + ci->u.inode->number_data=val; + ci->u.inode->number_blocks=val; + + pfsGetTime(&ci->u.inode->ctime); + memcpy(&ci->u.inode->atime, &ci->u.inode->ctime, sizeof(pfs_datetime_t)); + memcpy(&ci->u.inode->mtime, &ci->u.inode->ctime, sizeof(pfs_datetime_t)); + + ci->u.inode->number_segdesg=1; + ci->u.inode->data[0].number =bi->number; + ci->u.inode->data[0].subpart=bi->subpart; + ci->u.inode->data[0].count =bi->count; + + ci->u.inode->subpart=bi->subpart; + + ci->flags |= PFS_CACHE_FLAG_DIRTY; +} + + +// Given a path, this function will return the inode for the directory which holds +// the file (dir) specified by the filename. +// +// ie: if filename = /usr/local/ps2/games then it will return the inode for /usr/local/ps2 +pfs_cache_t* pfsInodeGetParent(pfs_mount_t *pfsMount, pfs_cache_t *clink, const char *filename, + char *path, int *result) +{ + static int pfsSymbolicLinks = 0; + pfs_cache_t *link, *inode; + char *filename2=(char*)filename; + + if (filename2[0]==0) + { + *result=-ENOENT; + if (clink) pfsCacheFree(clink); + return NULL; + } + + if (filename2[0] == '/') + { + + // Get inode for root dir + + if (clink) pfsCacheFree(clink); + if ((clink=pfsInodeGetData(pfsMount, pfsMount->root_dir.subpart, + pfsMount->root_dir.number, result))==0) + return NULL; + } + else if (clink==NULL) + { + + // Otherwise if relative path, get inode for current dir + + if ((clink=pfsInodeGetData(pfsMount, pfsMount->current_dir.subpart, + pfsMount->current_dir.number, result))==0) + return NULL; + } + + do + { + filename2=pfsSplitPath(filename2, path, result); + if (filename2==NULL) return NULL; + + // If we've reached the end of the path, then we want to return + // the cached inode for the directory which holds the file/dir in path + if (filename2[0]==0) + { + if ((clink->u.inode->mode & FIO_S_IFMT) == FIO_S_IFDIR) + return clink; + + pfsCacheFree(clink); + *result=-ENOTDIR; // not a directory + return NULL; + } + + inode=pfsInodeGetFileInDir(clink, path, result); + + if (inode && ((inode->u.inode->mode & FIO_S_IFMT) == FIO_S_IFLNK)) + { + if (pfsSymbolicLinks >= 4) + { + *result=-ELOOP; // too many symbolic links + pfsCacheFree(clink); + pfsCacheFree(inode); + return NULL; + } + + pfsSymbolicLinks++; + link=pfsInodeGetFile(pfsMount, clink, (char*)&inode->u.inode->data[1], result); + pfsSymbolicLinks--; + + clink=inode; + if (link==0) + { + pfsCacheFree(inode); + return NULL; + } + inode=link; + } + pfsCacheFree(clink); + clink=inode; + + } while (inode); + + return NULL; +} + +int pfsInodeRemove(pfs_cache_t *parent, pfs_cache_t *inode, char *path) +{ + pfs_cache_t *entry; + int rv=0; + + if((entry=pfsDirRemoveEntry(parent, path))!=NULL) + { + pfsInodeSetTimeParent(parent, entry); + pfsCacheFree(entry); + } + else + rv=-ENOENT; + + pfsCacheFree(parent); + if(rv==0) + { + inode->flags&=~PFS_CACHE_FLAG_DIRTY; + pfsBitmapFreeInodeBlocks(inode); + //if(parent->pfsMount->flags & PFS_FIO_ATTR_WRITEABLE) //Not checked for in late versions of PFS. + pfsCacheFlushAllDirty(parent->pfsMount); + } + + pfsCacheFree(inode); + return rv; +} + +pfs_cache_t *pfsInodeCreate(pfs_cache_t *clink, u16 mode, u16 uid, u16 gid, int *result) +{ + pfs_blockinfo_t a, b; + + pfs_mount_t *pfsMount=clink->pfsMount; + u32 j; + u32 i; + pfs_cache_t *inode; + + if ((mode & FIO_S_IFMT) == FIO_S_IFDIR) + { + if (pfsMount->num_subs > clink->u.inode->subpart) + clink->u.inode->subpart++; + else + clink->u.inode->subpart=0; + a.number =0; + a.subpart=clink->u.inode->subpart; + j= (pfsMount->zfree * (u64)100) / pfsMount->total_zones; + i= (pfsMount->free_zone[a.subpart] * (u64)100) / + (pfsMount->blockDev->getSize(pfsMount->fd, a.subpart) >> pfsMount->sector_scale); + if ((i < j) && ((j-i) >= 11)) + a.subpart=pfsGetMaxIndex(pfsMount); + }else{ + a.number=clink->u.inode->inode_block.number; + a.subpart=clink->u.inode->inode_block.subpart; + a.count=clink->u.inode->inode_block.count; + } + a.count=1; + + // Search for a free zone, starting from parent dir inode block + *result=pfsBitmapSearchFreeZone(pfsMount, &a, 2); + if (*result<0) return 0; + inode=pfsCacheGetData(pfsMount, a.subpart, a.number << pfsMount->inode_scale, + PFS_CACHE_FLAG_SEGD | PFS_CACHE_FLAG_NOLOAD, result); + if (inode == NULL) + return NULL; + + // Initialise the inode (which has been allocate blocks specified by a) + pfsInodeFill(inode, (pfs_blockinfo_t*)&a, mode, uid, gid); + if ((mode & FIO_S_IFMT) != FIO_S_IFDIR) + return inode; + + b.number=a.number; + b.subpart=a.subpart; + b.count=a.count; + + *result=pfsBitmapSearchFreeZone(pfsMount, (pfs_blockinfo_t*)&a, 0); + if (*result<0){ + pfsCacheFree(inode); + pfsBitmapFreeBlockSegment(pfsMount, (pfs_blockinfo_t*)&b); + return NULL; + } + + inode->u.inode->data[1].number=a.number; + inode->u.inode->data[1].subpart=a.subpart; + inode->u.inode->data[1].count =a.count; + + return inode; +} + +int pfsCheckAccess(pfs_cache_t *clink, int flags) +{ + int mode; + + // Bail if trying to write to read-only mount + if ((clink->pfsMount->flags & FIO_MT_RDONLY) && (flags & O_WRONLY)) + return -EROFS; + + if (((clink->u.inode->mode & FIO_S_IFMT) != FIO_S_IFDIR) && + ((clink->u.inode->mode & 0111) == 0)) + mode=6; + else + mode=7; + return ((mode & flags) & 7) == flags ? 0 : -EACCES; +} + +char* pfsSplitPath(char *filename, char *path, int *result) +{ + int i=0; + int j=0; + + for (i=0; filename[i] == '/'; i++) + ; + + for (; i<1024 && filename[i] != '/'; i++){ + if (filename[i] == 0) break; + if (j < 255) + path[j++] = filename[i]; + } + + if (j<256) + path[j]=0; + + while (filename[i] == '/') + if (i<1024) + i++; + else + break; + if (i<1024) + return &filename[i]; + + *result=-ENAMETOOLONG; + return 0; +} + +u16 pfsGetMaxIndex(pfs_mount_t *pfsMount) +{ + u32 max=0, maxI=0, i, v; + + for (i=0; i < pfsMount->num_subs + 1; i++) //enumerate all subs + { + v = (pfsMount->free_zone[i] * (u64)100) / + (pfsMount->blockDev->getSize(pfsMount->fd, i) >> pfsMount->sector_scale); + if (max < v) + { + max=v; + maxI=i; + } + } + return maxI; +} + +int pfsAllocZones(pfs_cache_t *clink, int msize, int mode) +{ + pfs_blockpos_t blockpos; + int result=0; + u32 val; + int zsize; + + zsize=clink->pfsMount->zsize; + val=((msize-1 + zsize) & (-zsize)) / zsize; + + if(mode==0) + if (((clink->u.inode->number_blocks-clink->u.inode->number_segdesg) *(u64)zsize) + >= (clink->u.inode->size + msize)) + return 0; + + if((blockpos.inode = pfsBlockGetLastSegmentDescriptorInode(clink, &result))) + { + blockpos.block_offset=blockpos.byte_offset=0; + blockpos.block_segment=clink->u.inode->number_data-1; + val-=pfsBlockExpandSegment(clink, &blockpos, val); + while (val && ((result=pfsBlockAllocNewSegment(clink, &blockpos, val))>=0)){ + val-=result; + result=0; + } + pfsCacheFree(blockpos.inode); + } + return result; +} + +void pfsFreeZones(pfs_cache_t *pfree) +{ + pfs_blockinfo_t b; + int result; + pfs_mount_t *pfsMount = pfree->pfsMount; + pfs_inode_t *inode = pfree->u.inode; + u32 nextsegdesc = 1, limit = inode->number_data, i, j = 0, zones; + pfs_blockinfo_t *bi; + pfs_cache_t *clink; + + zones = (u32)(inode->size / pfsMount->zsize); + if(inode->size % pfsMount->zsize) + zones++; + if(inode->number_segdesg + zones == inode->number_blocks) + return; + + j = zones; + b.number = 0; + clink = pfsCacheUsedAdd(pfree); + + // iterate through each of the block segments used by the inode + for (i = 1; i < limit && j; i++) + { + if(pfsFixIndex(i) == 0) + { + if ((clink = pfsBlockGetNextSegment(clink, &result)) == 0) + return; + + nextsegdesc++; + } + else + { + bi = &clink->u.inode->data[pfsFixIndex(i)]; + + if(j < bi->count) + { + bi->count -= j; + b.subpart = bi->subpart; + b.count = j; + b.number = bi->number + + bi->count; + j = 0; + clink->flags |= PFS_CACHE_FLAG_DIRTY; + } + else + j -= bi->count; + } + } + + pfree->u.inode->number_data = i; + pfree->u.inode->number_blocks = zones + nextsegdesc; + pfree->u.inode->number_segdesg = nextsegdesc; + pfree->u.inode->last_segment.number = clink->u.inode->data[0].number; + pfree->u.inode->last_segment.subpart= clink->u.inode->data[0].subpart; + pfree->u.inode->last_segment.count = clink->u.inode->data[0].count; + pfree->flags |= PFS_CACHE_FLAG_DIRTY; + + if (b.number) + pfsBitmapFreeBlockSegment(pfsMount, &b); + + for( ; i < limit; i++) + { + if (pfsFixIndex(i) == 0) + { + if((clink = pfsBlockGetNextSegment(clink, &result)) == 0) + return; + } + bi = &clink->u.inode->data[pfsFixIndex(i)]; + pfsBitmapFreeBlockSegment(pfsMount, bi); + pfsCacheMarkClean(pfsMount, bi->subpart, bi->number<inode_scale, + (bi->number+bi->count)<inode_scale); + } + + pfsCacheFree(clink); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/inode.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/inode.c new file mode 100644 index 0000000..1d217c5 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/inode.c @@ -0,0 +1,135 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS low-level inode manipulation routines +*/ + +#include +#include +#ifdef _IOP +#include +#else +#include +#endif + +#include "pfs-opt.h" +#include "libpfs.h" + +extern u32 pfsMetaSize; + +/////////////////////////////////////////////////////////////////////////////// +// Function definitions + +void pfsInodePrint(pfs_inode_t *inode) +{ + PFS_PRINTF(PFS_DRV_NAME": pfsInodePrint: Checksum = 0x%lX, Magic = 0x%lX\n", inode->checksum, inode->magic); + PFS_PRINTF(PFS_DRV_NAME": Mode = 0x%X, attr = 0x%X\n", inode->mode, inode->attr); + PFS_PRINTF(PFS_DRV_NAME": size = 0x%08lX%08lX\n", (u32)(inode->size >> 32), (u32)(inode->size)); +} + +int pfsInodeCheckSum(pfs_inode_t *inode) +{ + u32 *ptr=(u32 *)inode; + u32 sum=0; + int i; + + for(i=1; i < 256; i++) + sum+=ptr[i]; + return sum; +} + +pfs_cache_t *pfsInodeGetData(pfs_mount_t *pfsMount, u16 sub, u32 inode, int *result) +{ + return pfsCacheGetData(pfsMount, sub, inode << pfsMount->inode_scale, + PFS_CACHE_FLAG_SEGD, result); +} + +void pfsInodeSetTime(pfs_cache_t *clink) +{ // set the inode time's in cache + pfsGetTime(&clink->u.inode->mtime); + memcpy(&clink->u.inode->ctime, &clink->u.inode->mtime, sizeof(pfs_datetime_t)); + memcpy(&clink->u.inode->atime, &clink->u.inode->mtime, sizeof(pfs_datetime_t)); + clink->flags|=PFS_CACHE_FLAG_DIRTY; +} + +void pfsInodeSetTimeParent(pfs_cache_t *parent, pfs_cache_t *self) +{ // set the inode time's in cache + pfsInodeSetTime(parent); + self->flags|=PFS_CACHE_FLAG_DIRTY; +} + +int pfsInodeSync(pfs_blockpos_t *blockpos, u64 size, u32 used_segments) +{ + int result=0; + u32 i; + u16 count; + + for(i=pfsBlockSyncPos(blockpos, size); i; ) + { + count=blockpos->inode->u.inode->data[pfsFixIndex(blockpos->block_segment)].count; + + i+=blockpos->block_offset; + + if (i < count){ + blockpos->block_offset=i; + break; + } + + i-=count; + + if (blockpos->block_segment + 1 == used_segments) + { + blockpos->block_offset=count; + if (i || blockpos->byte_offset){ + PFS_PRINTF(PFS_DRV_NAME": panic: fp exceeds file.\n"); + return -EINVAL; + } + }else{ + blockpos->block_offset=0; + blockpos->block_segment++; + } + + if (pfsFixIndex(blockpos->block_segment)) + continue; + + if ((blockpos->inode = pfsBlockGetNextSegment(blockpos->inode, &result)) == 0) + break; + + i++; + } + + return result; +} + +pfs_cache_t *pfsGetDentriesChunk(pfs_blockpos_t *position, int *result) +{ + pfs_blockinfo_t *bi; + pfs_mount_t *pfsMount=position->inode->pfsMount; + + bi = &position->inode->u.inode->data[pfsFixIndex(position->block_segment)]; + + return pfsCacheGetData(pfsMount, bi->subpart, + ((bi->number + position->block_offset) << pfsMount->inode_scale) + + position->byte_offset / pfsMetaSize, PFS_CACHE_FLAG_NOTHING, result); +} + +pfs_cache_t *pfsGetDentriesAtPos(pfs_cache_t *clink, u64 position, int *offset, int *result) +{ + pfs_blockpos_t blockpos; + pfs_cache_t *r; + *result=pfsBlockInitPos(clink, &blockpos, position); + if (*result) return 0; + + *offset=blockpos.byte_offset % pfsMetaSize; + + r=pfsGetDentriesChunk(&blockpos, result); + pfsCacheFree(blockpos.inode); + + return r; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/journal.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/journal.c new file mode 100644 index 0000000..a5a46d3 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/journal.c @@ -0,0 +1,170 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS metadata journal related routines +*/ + +#include +#ifdef _IOP +#include +#else +#include +#endif +#include + +#include "pfs-opt.h" +#include "libpfs.h" + +extern u32 pfsBlockSize; + +/////////////////////////////////////////////////////////////////////////////// +// Globals + +pfs_journal_t pfsJournalBuf; + +/////////////////////////////////////////////////////////////////////////////// +// Function defenitions + +int pfsJournalChecksum(void *header) +{ + u32 *ptr=(u32 *)header; + u32 sum=0; + int i; + for(i=2; i < 256; i++) + sum+=ptr[i]; + return sum & 0xFFFF; +} + +void pfsJournalWrite(pfs_mount_t *pfsMount, pfs_cache_t *clink, u32 pfsCacheNumBuffers) +{ + u32 i=0; + u32 logSector=2; + +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + return; +#endif + + for(i=0; i checksum=pfsInodeCheckSum(clink[i].u.inode); + pfsJournalBuf.log[pfsJournalBuf.num].sector = clink[i].block << pfsBlockSize; + pfsJournalBuf.log[pfsJournalBuf.num].sub = clink[i].sub; + pfsJournalBuf.log[pfsJournalBuf.num].logSector = logSector; + pfsJournalBuf.num+=1; + } + logSector+=2; + } + + if(pfsMount->blockDev->transfer(pfsMount->fd, clink->u.inode, 0, + (pfsMount->log.number << pfsMount->sector_scale) + 2, pfsCacheNumBuffers*2, + PFS_IO_MODE_WRITE)>=0) + pfsJournalFlush(pfsMount); +} + +int pfsJournalReset(pfs_mount_t *pfsMount) +{ + int rv; + +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + return 0; +#endif + + memset(&pfsJournalBuf, 0, sizeof(pfs_journal_t)); + pfsJournalBuf.magic=PFS_JOUNRNAL_MAGIC; + + pfsMount->blockDev->flushCache(pfsMount->fd); + + rv = pfsMount->blockDev->transfer(pfsMount->fd, &pfsJournalBuf, 0, + (pfsMount->log.number << pfsMount->sector_scale), 2, PFS_IO_MODE_WRITE); + + pfsMount->blockDev->flushCache(pfsMount->fd); + return rv; +} + +int pfsJournalResetThis(pfs_block_device_t *blockDev, int fd, u32 sector) +{ + memset(&pfsJournalBuf, 0, sizeof(pfs_journal_t)); + pfsJournalBuf.magic=PFS_JOUNRNAL_MAGIC; + return blockDev->transfer(fd, &pfsJournalBuf, 0, sector, 2, 1); +} + +int pfsJournalFlush(pfs_mount_t *pfsMount) +{// this write any thing that in are journal buffer :) + int rv; + +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + return 0; +#endif + + pfsMount->blockDev->flushCache(pfsMount->fd); + + pfsJournalBuf.checksum=pfsJournalChecksum(&pfsJournalBuf); + + rv=pfsMount->blockDev->transfer(pfsMount->fd, &pfsJournalBuf, 0, + (pfsMount->log.number << pfsMount->sector_scale), 2, PFS_IO_MODE_WRITE); + + pfsMount->blockDev->flushCache(pfsMount->fd); + return rv; +} + +int pfsJournalRestore(pfs_mount_t *pfsMount) +{ + int rv; + int result; + pfs_cache_t *clink; + u32 i; + +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + return 0; +#endif + + // Read journal buffer from disk + rv = pfsMount->blockDev->transfer(pfsMount->fd, &pfsJournalBuf, 0, + (pfsMount->log.number << pfsMount->sector_scale), 2, PFS_IO_MODE_READ); + + if(rv || (pfsJournalBuf.magic != PFS_JOUNRNAL_MAGIC) || + (pfsJournalBuf.checksum != (u16)pfsJournalChecksum(&pfsJournalBuf))) + { + PFS_PRINTF(PFS_DRV_NAME": Error: cannot read log/invalid log\n"); + return pfsJournalReset(pfsMount); + } + + if(pfsJournalBuf.num == 0) + { + return pfsJournalReset(pfsMount); + } + + clink = pfsCacheAllocClean(&result); + if(!clink) + return result; + + for(i = 0; i < pfsJournalBuf.num; i++) + { + PFS_PRINTF(PFS_DRV_NAME": Log overwrite %d:%08lx\n", pfsJournalBuf.log[i].sub, pfsJournalBuf.log[i].sector); + + // Read data in from log section on disk into cache buffer + rv = pfsMount->blockDev->transfer(pfsMount->fd, clink->u.data, 0, + (pfsMount->log.number << pfsMount->sector_scale) + pfsJournalBuf.log[i].logSector, 2, + PFS_IO_MODE_READ); + + // Write from cache buffer into destination location on disk + if(!rv) + pfsMount->blockDev->transfer(pfsMount->fd, clink->u.data, pfsJournalBuf.log[i].sub, + pfsJournalBuf.log[i].sector, 2, PFS_IO_MODE_WRITE); + } + + pfsCacheFree(clink); + return pfsJournalReset(pfsMount); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/misc.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/misc.c new file mode 100644 index 0000000..9e5c656 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/misc.c @@ -0,0 +1,279 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Miscellaneous routines +*/ + +#include +#include +#include +#ifdef _IOP +#include +#include +#include +#include +#include +#else +#include +#include +#include +#endif +#include +#include + +#include "pfs-opt.h" +#include "libpfs.h" + +/////////////////////////////////////////////////////////////////////////////// +// Function definitions + +void *pfsAllocMem(int size) +{ +#ifdef _IOP + int intrStat; + void *mem; + + CpuSuspendIntr(&intrStat); + mem = AllocSysMemory(ALLOC_FIRST, size, NULL); + CpuResumeIntr(intrStat); + + return mem; +#else + return malloc(size); +#endif +} + +void pfsFreeMem(void *buffer) +{ +#ifdef _IOP + int OldState; + + CpuSuspendIntr(&OldState); + FreeSysMemory(buffer); + CpuResumeIntr(OldState); +#else + free(buffer); +#endif +} + +int pfsGetTime(pfs_datetime_t *tm) +{ +#ifdef _IOP + int ret, i; + sceCdCLOCK cdtime; + static pfs_datetime_t timeBuf={ + 0, 7, 6, 5, 4, 3, 2000 // used if can not get time... + }; + + for(i = 0; i < 20; i++) + { + ret = sceCdReadClock(&cdtime); + + if(ret!=0 && cdtime.stat==0) + { + timeBuf.sec=btoi(cdtime.second); + timeBuf.min=btoi(cdtime.minute); + timeBuf.hour=btoi(cdtime.hour); + timeBuf.day=btoi(cdtime.day); + timeBuf.month=btoi(cdtime.month & 0x7F); //The old CDVDMAN sceCdReadClock() function does not automatically file off the highest bit. + timeBuf.year=btoi(cdtime.year) + 2000; + break; + } else { + if(!(cdtime.stat & 0x80)) + break; + } + + DelayThread(100000); + } + memcpy(tm, &timeBuf, sizeof(pfs_datetime_t)); +#else + time_t rawtime; + struct tm timeinfo; + time(&rawtime); + // Convert to JST + rawtime += (-9 * 60 * 60); + gmtime_r(&rawtime, &timeinfo); + + tm->sec = timeinfo.tm_sec; + tm->min = timeinfo.tm_min; + tm->hour = timeinfo.tm_hour; + tm->day = timeinfo.tm_mday; + tm->month = timeinfo.tm_mon + 1; + tm->year = timeinfo.tm_year + 1900; +#endif + + return 0; +} + +int pfsFsckStat(pfs_mount_t *pfsMount, pfs_super_block_t *superblock, + u32 stat, int mode) +{ // mode 0=set flag, 1=remove flag, else check stat + + if(pfsMount->blockDev->transfer(pfsMount->fd, superblock, 0, PFS_SUPER_SECTOR, 1, + PFS_IO_MODE_READ)==0) + { + switch(mode) + { + case PFS_MODE_SET_FLAG: + superblock->pfsFsckStat|=stat; + break; + case PFS_MODE_REMOVE_FLAG: + superblock->pfsFsckStat&=~stat; + break; + default/*PFS_MODE_CHECK_FLAG*/: + return 0 < (superblock->pfsFsckStat & stat); + } + pfsMount->blockDev->transfer(pfsMount->fd, superblock, 0, PFS_SUPER_SECTOR, 1, + PFS_IO_MODE_WRITE); + pfsMount->blockDev->flushCache(pfsMount->fd); + } + return 0; +} + +void pfsPrintBitmap(const u32 *bitmap) { + u32 i, j; + char a[48+1], b[16+1]; + + b[16]=0; + for (i=0; i < 32; i++){ + memset(a, 0, 49); + for (j=0; j < 16; j++){ + const char *c=(const char*)bitmap+j+i*16; + + sprintf(a+j*3, "%02x ", *c); + b[j] = ((*c>=0) && (isgraph(*c))) ? + *c : '.'; + } + PFS_PRINTF("%s%s\n", a, b); + } +} + +u32 pfsGetScale(u32 num, u32 size) +{ + u32 scale = 0; + + while((size << scale) != num) + scale++; + + return scale; +} + +u32 pfsFixIndex(u32 index) +{ + if(index < PFS_INODE_MAX_BLOCKS) + return index; + + index -= PFS_INODE_MAX_BLOCKS; + return index % 123; +} + +/////////////////////////////////////////////////////////////////////////////// +// Functions to work with hdd.irx + +static int pfsHddTransfer(int fd, void *buffer, u32 sub/*0=main 1+=subs*/, u32 sector, + u32 size/* in sectors*/, u32 mode); +static u32 pfsHddGetSubCount(int fd); +static u32 pfsHddGetPartSize(int fd, u32 sub/*0=main 1+=subs*/); +static void pfsHddSetPartError(int fd); +static int pfsHddFlushCache(int fd); + +#ifdef PFS_SUPPORT_BHDD +#define NUM_SUPPORTED_DEVICES 2 +#else +#define NUM_SUPPORTED_DEVICES 1 +#endif +pfs_block_device_t pfsBlockDeviceCallTable[NUM_SUPPORTED_DEVICES] = { + { + "hdd", + &pfsHddTransfer, + &pfsHddGetSubCount, + &pfsHddGetPartSize, + &pfsHddSetPartError, + &pfsHddFlushCache, + }, +#ifdef PFS_SUPPORT_BHDD + { + "bhdd", + &pfsHddTransfer, + &pfsHddGetSubCount, + &pfsHddGetPartSize, + &pfsHddSetPartError, + &pfsHddFlushCache, + }, +#endif +}; + +pfs_block_device_t *pfsGetBlockDeviceTable(const char *name) +{ + char *end; + char devname[32]; + char *tmp; + u32 len; + int i; + + while(name[0] == ' ') + name++; + + end = strchr(name, ':'); + if(!end) { + PFS_PRINTF(PFS_DRV_NAME": Error: Unknown block device '%s'\n", name); + return NULL; + } + + len = (u32)end - (u32)name; + strncpy(devname, name, len); + devname[len] = '\0'; + + // Loop until digit is found, then terminate string at that digit. + // Should then have just the device name left, minus any front spaces or trailing digits. + tmp = devname; + while(!(isdigit(tmp[0]))) + tmp++; + tmp[0] = '\0'; + + for(i = 0; i < NUM_SUPPORTED_DEVICES; i++) + if(!strcmp(pfsBlockDeviceCallTable[i].devName, devname)) + return &pfsBlockDeviceCallTable[i]; + + return NULL; +} + +static int pfsHddTransfer(int fd, void *buffer, u32 sub/*0=main 1+=subs*/, u32 sector, + u32 size/* in sectors*/, u32 mode) +{ + hddIoctl2Transfer_t t; + + t.sub=sub; + t.sector=sector; + t.size=size; + t.mode=mode; + t.buffer=buffer; + + return ioctl2(fd, HIOCTRANSFER, &t, 0, NULL, 0); +} + +static u32 pfsHddGetSubCount(int fd) +{ + return ioctl2(fd, HIOCNSUB, NULL, 0, NULL, 0); +} + +static u32 pfsHddGetPartSize(int fd, u32 sub/*0=main 1+=subs*/) +{ // of a partition + return ioctl2(fd, HIOCGETSIZE, &sub, 0, NULL, 0); +} + +static void pfsHddSetPartError(int fd) +{ + ioctl2(fd, HIOCSETPARTERROR, NULL, 0, NULL, 0); +} + +static int pfsHddFlushCache(int fd) +{ + return ioctl2(fd,HIOCFLUSH, NULL, 0, NULL, 0); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/super.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/super.c new file mode 100644 index 0000000..6e7b89f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/super.c @@ -0,0 +1,70 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS superblock manipulation routines +*/ + +#include +#include +#ifdef _IOP +#include +#else +#include +#endif +#include + +#include "pfs-opt.h" +#include "libpfs.h" + +u32 pfsBlockSize = 1;// block size scale in sectors (512). Note that 0 = 1x +u32 pfsMetaSize = 1024; // size of each metadata structure + +int pfsCheckZoneSize(u32 zone_size) +{ + if((zone_size & (zone_size - 1)) || (zone_size < (2 * 1024)) || (zone_size > (128 * 1024))) + { + PFS_PRINTF(PFS_DRV_NAME": Error: Invalid zone size\n"); + return 0; + } + + return 1; +} + +#ifdef PFS_SUPPORT_BHDD +int pfsCheckExtendedZoneSize(u32 zone_size) +{ + if ((zone_size & (zone_size - 1)) || (zone_size < (2 * 1024)) || (zone_size > (128 * 8192))) + { + PFS_PRINTF(PFS_DRV_NAME": error: invalid extended zone size %d,%d\n", (zone_size & (zone_size - 1)) == 0, zone_size); + return 0; + } + + return 1; +} +#endif + +// Returns the number of sectors (512 byte units) which will be used +// for bitmaps, given the zone size and partition size +u32 pfsGetBitmapSizeSectors(int zoneScale, u32 partSize) +{ + int w, zones = partSize / (1 << zoneScale); + + w = (zones & 7); + zones = zones / 8 + w; + + w = (zones & 511); + return zones / 512 + w; +} + +// Returns the number of blocks/zones which will be used for bitmaps +u32 pfsGetBitmapSizeBlocks(int scale, u32 mainsize) +{ + u32 a=pfsGetBitmapSizeSectors(scale, mainsize); + return a / (1<0); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/superWrite.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/superWrite.c new file mode 100644 index 0000000..781a281 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/libpfs/src/superWrite.c @@ -0,0 +1,265 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS superblock (write) manipulation routines +*/ + +#include +#include +#ifdef _IOP +#include +#else +#include +#endif +#include + +#include "pfs-opt.h" +#include "libpfs.h" + +extern u32 pfsBlockSize; +extern u32 pfsMetaSize; + +// Formats a partition (main or sub) by filling with fragment pattern and setting the bitmap accordingly +int pfsFormatSub(pfs_block_device_t *blockDev, int fd, u32 sub, u32 reserved, u32 scale, u32 fragment) +{ + pfs_cache_t *cache; + int i; + unsigned int j; + u32 sector, count, size, *b; + int result = 0; + + size = blockDev->getSize(fd, sub); + sector = 1 << scale; + count = pfsGetBitmapSizeSectors(scale, size); + if (reserved>=2) + sector+=0x2000; + reserved += pfsGetBitmapSizeBlocks(scale, size); + + if((cache = pfsCacheAllocClean(&result))) + { + // fill with fragment pattern + for (i=127; i>=0; i--) + cache->u.bitmap[i]=fragment; + + // set as allocated the sectors up to reserved, for the first part of the bitmap + // this will mark the area the bitmaps themselves occupy as used + for (j=0, b=cache->u.bitmap; jtransfer(fd, cache->u.bitmap, sub, sector++, 1, 1))>=0)) + for (i=127; i>=0; i--) + cache->u.bitmap[i]=fragment; + + PFS_PRINTF("sector end = %ld\n", sector - 1); + + pfsCacheFree(cache); + } + return result; +} + +// Formats a partition and all sub-partitions with PFS +int pfsFormat(pfs_block_device_t *blockDev, int fd, int zonesize, int fragment) +{ + int result, result2; + pfs_cache_t *clink, *cache; + pfs_super_block_t *sb; + int scale; + u32 i, mainsize, subnumber = blockDev->getSubNumber(fd); + + mainsize=blockDev->getSize(fd, 0); + if(pfsCheckZoneSize(zonesize) == 0) + return -EINVAL; + + scale = pfsGetScale(zonesize, 512); + + if((clink=pfsCacheAllocClean(&result))) + { + sb = clink->u.superblock; + memset(sb, 0, pfsMetaSize); + sb->magic = PFS_SUPER_MAGIC; + sb->version = PFS_FORMAT_VERSION; + sb->modver = ((PFS_MAJOR << 8) | PFS_MINOR); + sb->zone_size = zonesize; + sb->num_subs = subnumber; + sb->log.number = pfsGetBitmapSizeBlocks(scale, mainsize) + (0x2000 >> scale) + 1; + sb->log.count = 0x20000 / zonesize ? 0x20000 / zonesize : 1; + + PFS_PRINTF(PFS_DRV_NAME": Format: log.number = %ld, log.count = %d\n", sb->log.number << scale, sb->log.count); + + sb->root.count = 1; + sb->root.number = sb->log.number + sb->log.count; + if((result = pfsJournalResetThis(blockDev, fd, sb->log.number<= 0) + { + if((cache = pfsCacheAllocClean(&result2))) + { + pfsFillSelfAndParentDentries(cache, &sb->root, &sb->root); + result2 = blockDev->transfer(fd, cache->u.dentry, 0, (sb->root.number+1) << scale, + 1 << pfsBlockSize, 1); + if(result2 == 0) + { + // setup root directory + pfsInodeFill(cache, &sb->root, 0x11FF, 0, 0); + cache->u.inode->data[1].subpart = 0; + cache->u.inode->data[1].number = sb->root.number + 1; + cache->u.inode->data[1].count = 1; + cache->u.inode->checksum = pfsInodeCheckSum(cache->u.inode); + + result2=blockDev->transfer(fd, cache->u.inode, 0, sb->root.number << scale, + 1 << pfsBlockSize, 1); + } + + pfsCacheFree(cache); + } + + if((result = result2) >= 0) + { + for (i=0; i < subnumber+1; i++) + if((result=pfsFormatSub(blockDev, fd, i, i ? 1 : (0x2000 >> scale) + + sb->log.count + 3, scale, fragment))<0) + break; + + if((result == 0) && ((result = blockDev->transfer(fd, sb, 0, PFS_SUPER_BACKUP_SECTOR, 1, 1))==0)) + result = blockDev->transfer(fd, sb, 0, PFS_SUPER_SECTOR, 1, 1); + } + } + + pfsCacheFree(clink); + blockDev->flushCache(fd); + } + return result; +} + +// Formats sub partitions which are added to the main partition after it is initially +// formatted with PFS +int pfsUpdateSuperBlock(pfs_mount_t *pfsMount, pfs_super_block_t *superblock, u32 sub) +{ + u32 scale; + u32 i; + int rv; + + scale = pfsGetScale(superblock->zone_size, 512); + + for(i = superblock->num_subs + 1; i < sub + 1; i++) + { + rv = pfsFormatSub(pfsMount->blockDev, pfsMount->fd, i, 1, scale, 0); + if(rv < 0) + return rv; + } + + superblock->num_subs = sub; + + // Write superblock, then write backup + rv = pfsMount->blockDev->transfer(pfsMount->fd, superblock, 0, PFS_SUPER_SECTOR, 1, PFS_IO_MODE_WRITE); + if(!rv) + rv = pfsMount->blockDev->transfer(pfsMount->fd, superblock, 0, PFS_SUPER_BACKUP_SECTOR, 1, PFS_IO_MODE_WRITE); + + pfsMount->blockDev->flushCache(pfsMount->fd); + + return rv; +} + +int pfsMountSuperBlock(pfs_mount_t *pfsMount) +{ + int result; + pfs_cache_t *clink; + pfs_super_block_t *superblock; + u32 sub; + u32 i; + + + // Get number of sub partitions attached to the main partition + sub = pfsMount->blockDev->getSubNumber(pfsMount->fd); + + // Allocate a cache entry for the superblock + clink = pfsCacheAllocClean(&result); + if(!clink) + return result; + + superblock = clink->u.superblock; + + // Read the suprerblock from the main partition + result = pfsMount->blockDev->transfer(pfsMount->fd, superblock, 0, PFS_SUPER_SECTOR, 1, PFS_IO_MODE_READ); + if(result) goto error; + + if((superblock->magic != PFS_SUPER_MAGIC) || (superblock->version > PFS_FORMAT_VERSION)) + { + PFS_PRINTF(PFS_DRV_NAME": Error: Invalid magic/version\n"); + pfsCacheFree(clink); + return -EIO; + } + + +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + { + if(!pfsCheckExtendedZoneSize(superblock->zone_size)) + result = -EIO; + } + else +#endif + { + if(!pfsCheckZoneSize(superblock->zone_size)) + result = -EIO; + } + + if((superblock->pfsFsckStat & PFS_FSCK_STAT_WRITE_ERROR) && (pfsMount->flags & PFS_FIO_ATTR_EXECUTABLE)) + result = -EIO; + + if(sub < superblock->num_subs) + { + PFS_PRINTF(PFS_DRV_NAME": Error: Filesystem larger than partition\n"); + result = -EIO; + } + + if(result) goto error; + + // If new subs have been added, update filesystem + if(superblock->num_subs < sub) + { + PFS_PRINTF(PFS_DRV_NAME": New subs added, updating filesystem..\n"); + result = pfsUpdateSuperBlock(pfsMount, superblock, sub); + } + + if(result) goto error; + + pfsMount->zsize = superblock->zone_size; + pfsMount->sector_scale = pfsGetScale(pfsMount->zsize, 512); + pfsMount->inode_scale = pfsGetScale(pfsMount->zsize, pfsMetaSize); + pfsMount->num_subs = superblock->num_subs; + memcpy(&pfsMount->root_dir, &superblock->root, sizeof(pfs_blockinfo_t)); + memcpy(&pfsMount->log, &superblock->log, sizeof(pfs_blockinfo_t)); + memcpy(&pfsMount->current_dir, &superblock->root, sizeof(pfs_blockinfo_t)); + pfsMount->total_zones = 0; + + // Do a journal restore (in case of un-clean unmount) + pfsJournalRestore(pfsMount); + + // Calculate free space and total size + for(i = 0; i < (pfsMount->num_subs + 1); i++) + { + int free; + + pfsMount->total_zones += pfsMount->blockDev->getSize(pfsMount->fd, i) >> pfsMount->sector_scale; + + free = pfsBitmapCalcFreeZones(pfsMount, i); + pfsMount->free_zone[i] = free; + pfsMount->zfree += free; + } + +error: + pfsCacheFree(clink); + return result; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs-osd/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs-osd/Makefile new file mode 100644 index 0000000..cada159 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs-osd/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/hdd/pfs/src/ + +IOP_BIN ?= ps2fs-osd.irx + +IOP_CFLAGS += -DPFS_OSD_VER + +include $(PS2SDKSRC)/iop/hdd/pfs/Makefile diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs-xosd/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs-xosd/Makefile new file mode 100644 index 0000000..541cb1e --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs-xosd/Makefile @@ -0,0 +1,15 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/hdd/pfs/src/ + +IOP_BIN ?= ps2fs-xosd.irx + +IOP_CFLAGS += -DPFS_XOSD_VER + +include $(PS2SDKSRC)/iop/hdd/pfs/Makefile diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/Makefile new file mode 100644 index 0000000..5d1cb4b --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/Makefile @@ -0,0 +1,28 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +LIBPFS_PATH = $(PS2SDKSRC)/iop/hdd/libpfs/ + +LIBPFS_SRC_DIR = $(LIBPFS_PATH)src/ + +IOP_BIN ?= ps2fs.irx + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/atad/include -I$(PS2SDKSRC)/iop/dev9/poweroff/include -I$(LIBPFS_PATH)include + +IOP_LIBS += -lgcc + +PFS_OBJS = bitmap.o dir.o inode.o journal.o misc.o super.o superWrite.o cache.o block.o blockWrite.o +IOP_OBJS = pfs.o pfs_fio.o pfs_fioctl.o imports.o $(PFS_OBJS) + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release + +$(IOP_OBJS_DIR)%.o: $(LIBPFS_SRC_DIR)%.c + $(IOP_CC) $(IOP_CFLAGS) -c $< -o $@ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/imports.lst new file mode 100644 index 0000000..c1a0614 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/imports.lst @@ -0,0 +1,53 @@ + +cdvdman_IMPORTS_start +I_sceCdReadClock +cdvdman_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +iomanX_IMPORTS_start +I_open +I_close +I_ioctl2 +I_AddDrv +I_DelDrv +iomanX_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memcpy +I_memset +I_strncpy +I_sprintf +I_strlen +I_strcpy +I_memcmp +I_strncmp +I_strrchr +I_strcmp +I_strtol +I_strchr +I_look_ctype_table +sysclib_IMPORTS_end + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +sysmem_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/irx_imports.h new file mode 100644 index 0000000..e822f82 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/irx_imports.h @@ -0,0 +1,28 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2003 Marcus R. Brown +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include +#include +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs-opt.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs-opt.h new file mode 100644 index 0000000..9007377 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs-opt.h @@ -0,0 +1,27 @@ +#ifndef _PFS_OPT_H +#define _PFS_OPT_H + +#define PFS_PRINTF(format,...) printf(format, ##__VA_ARGS__) +#define PFS_DRV_NAME "pfs" + +// TODO: last sdk 3.1.0 has PFS module with significant changes. +// Check what was changed, and maybe port changes. +// Note: PFS version the same: 2.2 +// CRC32: 98E62276 +#define PFS_MAJOR 2 +#define PFS_MINOR 2 + +#ifdef PFS_XOSD_VER +#define PFS_OSD_VER 1 +#define PFS_SUPPORT_BHDD 1 +#endif + +/* Define PFS_OSD_VER in your Makefile to build an OSD version, which will: + 1. Enable the PIOCINVINODE IOCTL2 function. + 2. (Unofficial) Return the LBA of the inode in private_5 and sub number in private_4 fields of the stat structure (returned by getstat and dread). */ +#ifdef PFS_OSD_VER +#define PFS_IOCTL2_INC_CHECKSUM 1 +#define PFS_STAT_RETURN_INODE_LBA 1 +#endif + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs.c new file mode 100644 index 0000000..bca2b71 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs.c @@ -0,0 +1,240 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS startup and misc code +*/ + +#include +#ifdef _IOP +#include +#include +#else +#include +#include +#endif +#include +#include +#include +#include + +#include "pfs-opt.h" +#include "libpfs.h" +#include "pfs.h" +#include "pfs_fio.h" +#include "pfs_fioctl.h" + +#ifdef _IOP +IRX_ID("pfs_driver", PFS_MAJOR, PFS_MINOR); +#endif + +/////////////////////////////////////////////////////////////////////////////// +// Globals + +iop_device_ops_t pfsOps = { + pfsFioInit, + pfsFioDeinit, + pfsFioFormat, + pfsFioOpen, + pfsFioClose, + pfsFioRead, + pfsFioWrite, + pfsFioLseek, + pfsFioIoctl, + pfsFioRemove, + pfsFioMkdir, + pfsFioRmdir, + pfsFioDopen, + pfsFioClose, + pfsFioDread, + pfsFioGetstat, + pfsFioChstat, + pfsFioRename, + pfsFioChdir, + pfsFioSync, + pfsFioMount, + pfsFioUmount, + pfsFioLseek64, + pfsFioDevctl, + pfsFioSymlink, + pfsFioReadlink, + pfsFioIoctl2 +}; + +iop_device_t pfsFioDev = { + "pfs", + (IOP_DT_FS | IOP_DT_FSEXT), + 1, + "PFS", + &pfsOps +}; + +pfs_config_t pfsConfig = { 1, 2 }; +pfs_mount_t *pfsMountBuf; +char *pfsFilename = NULL; + +extern u32 pfsMetaSize; +extern pfs_file_slot_t *pfsFileSlots; +extern pfs_config_t pfsConfig; + +/////////////////////////////////////////////////////////////////////////////// +// Local function declerations + +static int printPfsArgError(void); +static int allocateMountBuffer(int size); + +/////////////////////////////////////////////////////////////////////////////// +// Function defenitions + +static int printPfsArgError(void) +{ + PFS_PRINTF(PFS_DRV_NAME" ERROR: Usage: %s [-m ] [-o ] [-n ]\n", pfsFilename); + + return MODULE_NO_RESIDENT_END; +} + +static int allocateMountBuffer(int size) +{ + int tsize = size * sizeof(pfs_mount_t); + + pfsMountBuf = pfsAllocMem(tsize); + if(!pfsMountBuf) + return -ENOMEM; + + memset(pfsMountBuf, 0, tsize); + + return 0; +} + +void pfsClearMount(pfs_mount_t *pfsMount) +{ + memset(pfsMount, 0, sizeof(pfs_mount_t)); +} + +pfs_mount_t *pfsGetMountedUnit(s32 unit) +{ // get mounted unit + if(unit>=pfsConfig.maxMount) + return NULL; + + if(!(pfsMountBuf[unit].flags & PFS_MOUNT_BUSY)) + return NULL; + + return &pfsMountBuf[unit]; +} + +int _start(int argc, char *argv[]) +{ + char *filename; + int number; + int numBuf = 8; + int reqBuf; + int size, ret; + + PFS_PRINTF(PFS_DRV_NAME" Playstation Filesystem Driver v%d.%d\nps2fs: (c) 2003 Sjeep, Vector and Florin Sasu\n", PFS_MAJOR, PFS_MINOR); + + // Get filename of IRX + filename = strrchr(argv[0], '/'); + if(filename++) + pfsFilename = filename; + else + pfsFilename = argv[0]; + + argc--; + argv++; + + // Parse arguments + while(argc > 0) + { + if(argv[0][0] != '-') + break; + + if(!strcmp(argv[0], "-m")) + { + if(--argc <= 0) + return printPfsArgError(); + argv++; + + number = strtol(argv[0], 0, 10); + + if(number <= 32) + pfsConfig.maxMount = number; + } + else if(!strcmp(argv[0], "-o")) + { + if(--argc <= 0) + return printPfsArgError(); + argv++; + + number = strtol(argv[0], NULL, 10); + + if(number <= 32) + pfsConfig.maxOpen = number; + } + else if(!strcmp(argv[0], "-n")) + { + if(--argc <= 0) + return printPfsArgError(); + argv++; + + number = strtol(argv[0], NULL, 10); + + if(number > numBuf) + numBuf = number; + + if(numBuf > 127) { + PFS_PRINTF(PFS_DRV_NAME" ERROR: Number of buffers is larger than 127!\n"); + return -EINVAL; + } + } + else + return printPfsArgError(); + + argc--; + argv++; + } + + PFS_PRINTF(PFS_DRV_NAME" Max mount: %ld, Max open: %ld, Number of buffers: %d\n", pfsConfig.maxMount, + pfsConfig.maxOpen, numBuf); + + // Do we have enough buffers ? + reqBuf = (pfsConfig.maxOpen * 2) + 8; + if(numBuf < reqBuf) + PFS_PRINTF(PFS_DRV_NAME" Warning: %d buffers may be needed, but only %d buffers are allocated\n", reqBuf, numBuf); + + if(allocateMountBuffer(pfsConfig.maxMount) < 0) + return MODULE_NO_RESIDENT_END; + + // Allocate and zero memory for file slots + size = pfsConfig.maxOpen * sizeof(pfs_file_slot_t); + pfsFileSlots = pfsAllocMem(size); + ret = (pfsFileSlots == NULL) ? -ENOMEM : 0; + if(ret != 0) + { //Official PFS module does not print an error message here. + PFS_PRINTF(PFS_DRV_NAME" Error: Failed to allocate memory for file descriptors!\n"); + return MODULE_NO_RESIDENT_END; + } + + memset(pfsFileSlots, 0, size); + + if(pfsCacheInit(numBuf, pfsMetaSize) < 0) + return MODULE_NO_RESIDENT_END; + + DelDrv("pfs"); + if(AddDrv(&pfsFioDev) == 0) { +#if defined(PFS_XOSD_VER) + PFS_PRINTF(PFS_DRV_NAME" version %04x driver start. This is OSD LBA48 VERSION !!!!!!!!!!!\n", IRX_VER(PFS_MAJOR, PFS_MINOR)); +#elif defined(PFS_OSD_VER) + PFS_PRINTF(PFS_DRV_NAME" version %04x driver start. This is OSD version!\n", IRX_VER(PFS_MAJOR, PFS_MINOR)); +#else + PFS_PRINTF(PFS_DRV_NAME" version %04x driver start.\n", IRX_VER(PFS_MAJOR, PFS_MINOR)); +#endif + return MODULE_RESIDENT_END; + } + + return MODULE_NO_RESIDENT_END; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs.h new file mode 100644 index 0000000..f7585ed --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs.h @@ -0,0 +1,64 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef _PFS_H +#define _PFS_H + +#ifndef min +#define min(a, b) ((a) < (b) ? (a) : (b)) +#endif + +/////////////////////////////////////////////////////////////////////////////// +// Global types + +typedef struct +{ + u16 dirty; // Whether the buffer is dirty or not. + u16 sub; // Sub/main partition + u32 sector; // Sector + u8 buffer[512]; // used for reading mis-aligned/remainder data +} pfs_unaligned_io_t; + +#define PFS_AENTRY_KEY_MAX 256 +#define PFS_AENTRY_VALUE_MAX 256 + +typedef struct +{ + char key[PFS_AENTRY_KEY_MAX]; + char value[PFS_AENTRY_VALUE_MAX]; +} pfs_ioctl2attr_t; + +typedef struct { + iop_file_t *fd; // + pfs_cache_t *clink; // + u32 aentryOffset; // used for read offset + u64 position; // + pfs_blockpos_t block_pos; // current position into file + pfs_unaligned_io_t unaligned; // Contains unaligned data (data can only be read from the HDD in units of 512) +} pfs_file_slot_t; + +typedef struct { + u32 maxMount; + u32 maxOpen; +} pfs_config_t; + +/////////////////////////////////////////////////////////////////////////////// +// Global defines + +// mount flags +#define PFS_MOUNT_BUSY 0x8000 + +/////////////////////////////////////////////////////////////////////////////// +// Function declarations + +pfs_mount_t *pfsGetMountedUnit(s32 unit); +void pfsClearMount(pfs_mount_t *pfsMount); + +#endif /* _PFS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fio.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fio.c new file mode 100644 index 0000000..47b21d7 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fio.c @@ -0,0 +1,1360 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS I/O manager related routines +*/ + +#include +#ifdef _IOP +#include +#else +#include +#endif +#include +#include +#include +#include + +#include "pfs-opt.h" +#include "libpfs.h" +#include "pfs.h" +#include "pfs_fio.h" +#include "pfs_fioctl.h" + +/////////////////////////////////////////////////////////////////////////////// +// Globals + +static const u8 openFlagArray[] = { 0, 4, 2, 6, 0, 0, 0, 0 }; +int pfsFioSema = 0; +pfs_file_slot_t *pfsFileSlots; + +extern pfs_config_t pfsConfig; +extern pfs_cache_t *pfsCacheBuf; +extern u32 pfsCacheNumBuffers; +extern pfs_mount_t *pfsMountBuf; + +#ifdef PFS_STAT_RETURN_INODE_LBA +extern u32 pfsBlockSize; +#endif + +/////////////////////////////////////////////////////////////////////////////// +// Function declarations + +static int openFile(pfs_mount_t *pfsMount, pfs_file_slot_t *freeSlot, const char *filename, int openFlags, int mode); +static int fileTransferRemainder(pfs_file_slot_t *fileSlot, void *buf, int size, int operation); +static int fileTransfer(pfs_file_slot_t *fileSlot, u8 *buf, int size, int operation); +static void fioStatFiller(pfs_cache_t *clink, iox_stat_t *stat); +static s64 _seek(pfs_file_slot_t *fileSlot, s64 offset, int whence, int mode); +static int _remove(pfs_mount_t *pfsMount, const char *path, int mode); +static int mountDevice(pfs_block_device_t *blockDev, int fd, int unit, int flag); +static void _sync(void); + +/////////////////////////////////////////////////////////////////////////////// +// Function definitions + +int pfsFioCheckForLastError(pfs_mount_t *pfsMount, int rv) +{ + return pfsMount->lastError ? pfsMount->lastError : rv; +} + +int pfsFioCheckFileSlot(pfs_file_slot_t *fileSlot) +{ + WaitSema(pfsFioSema); + + if(fileSlot->clink==NULL) + { + SignalSema(pfsFioSema); + return -EBADF; + } + + return 0; +} + +void pfsFioCloseFileSlot(pfs_file_slot_t *fileSlot) +{ + pfs_mount_t *pfsMount=fileSlot->clink->pfsMount; + + if(fileSlot->fd->mode & O_WRONLY) + { + if(fileSlot->unaligned.dirty!=0) + { + pfsMount->blockDev->transfer(pfsMount->fd, fileSlot->unaligned.buffer, + fileSlot->unaligned.sub, fileSlot->unaligned.sector, 1, PFS_IO_MODE_WRITE); + } + pfsInodeSetTime(fileSlot->clink); // set time :P + fileSlot->clink->u.inode->attr|=PFS_FIO_ATTR_CLOSED; + if(pfsMount->flags & PFS_FIO_ATTR_WRITEABLE) + pfsCacheFlushAllDirty(pfsMount); + } + pfsCacheFree(fileSlot->block_pos.inode); + pfsCacheFree(fileSlot->clink); + memset(fileSlot, 0, sizeof(pfs_file_slot_t)); +} + +pfs_mount_t *pfsFioGetMountedUnit(int unit) +{ + pfs_mount_t *pfsMount; + + WaitSema(pfsFioSema); + if((pfsMount=pfsGetMountedUnit(unit))==NULL) + SignalSema(pfsFioSema); + return pfsMount; +} + +static int mountDevice(pfs_block_device_t *blockDev, int fd, int unit, int flag) +{ + s32 i; + int rv; + + if(unit >= pfsConfig.maxMount) + return -EMFILE; + + if(pfsMountBuf[unit].flags & PFS_MOUNT_BUSY) + return -EBUSY; + + for(i = 0; i < pfsConfig.maxMount; i++) + if((pfsMountBuf[i].flags & PFS_MOUNT_BUSY) && + (blockDev == pfsMountBuf[i].blockDev) && + (fd == pfsMountBuf[i].fd)) // Cant mount the same partition more than once + return -EBUSY; + + pfsMountBuf[unit].blockDev = blockDev; + pfsMountBuf[unit].fd = fd; + pfsMountBuf[unit].flags = flag; + + rv = pfsMountSuperBlock(&pfsMountBuf[unit]); + if(rv < 0) + return rv; + + pfsMountBuf[unit].flags |= PFS_MOUNT_BUSY; + + return 0; +} + +static int openFile(pfs_mount_t *pfsMount, pfs_file_slot_t *freeSlot, const char *filename, int openFlags, int mode) +{ + char file[256]; + int result, result2, result3, result4; + pfs_cache_t *parentInode, *fileInode, *cached; + + + result = 0; //no error +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + if (openFlags & O_CREAT) + return -EACCES; +#endif + // Get the inode for the directory which contains the file (dir) in filename + // After this call, 'file' will contain the name of the file we're operating on. + if ((parentInode=pfsInodeGetParent(pfsMount, NULL, filename, file, &result))==0) + { + return result; + } + + // Get the inode for the actual file/directory contained in the parent dir + fileInode=pfsInodeGetFileInDir(parentInode, file, &result); + + // If file already exists.. + if (fileInode) + { + u32 flags; + u32 count; + + // Setup flags + flags=openFlagArray[openFlags & O_RDWR]; + if (openFlags & O_TRUNC) flags |= 2; + if (openFlags & PFS_FDIRO) flags |= 4; + if ((mode & 0x10000) || + ((openFlags & (O_CREAT|O_EXCL)) == (O_CREAT|O_EXCL))){ + result=-EEXIST; + } + else + { + count = 0; + + // Resolve actual file from a symlink + while ((fileInode->u.inode->mode & FIO_S_IFMT) == FIO_S_IFLNK) + { + if (count++>=4) + { + result=-ELOOP; + goto label; + } + + parentInode=pfsInodeGetParent(pfsMount, parentInode, (char*)&fileInode->u.inode->data[1], + file, &result); + pfsCacheFree(fileInode); + if ((parentInode==0) || + ((fileInode=pfsInodeGetFileInDir(parentInode, file, &result))==0)) + goto label; + } + + // Make sure that if a file is being opened, then inode does not point + // to a directory, and vice versa. + if ((openFlags & PFS_FDIRO) == 0) + { + if ((fileInode->u.inode->mode & FIO_S_IFMT) == FIO_S_IFDIR) + result=-EISDIR; + }else{ + if ((fileInode->u.inode->mode & FIO_S_IFMT) != FIO_S_IFDIR) + result=-ENOTDIR; + } + + // Truncate file if required + if ((result==0) && + ((result=pfsCheckAccess(fileInode, flags & 0xFFFF))==0) && + (openFlags & O_TRUNC)) + { + cached=pfsCacheGetData(fileInode->pfsMount, fileInode->sub, fileInode->block+1, PFS_CACHE_FLAG_NOLOAD | PFS_CACHE_FLAG_NOTHING, &result2); + if (cached) + { + memset(cached->u.aentry, 0, sizeof(pfs_inode_t)); //1024 + cached->u.aentry->aLen=sizeof(pfs_inode_t); + cached->flags |= PFS_CACHE_FLAG_DIRTY; + pfsCacheFree(cached); + } + if (result2 == 0) + { + fileInode->u.inode->size = 0; + fileInode->u.inode->attr &= ~PFS_FIO_ATTR_CLOSED; //~0x80==0xFF7F + fileInode->flags |= PFS_CACHE_FLAG_DIRTY; + pfsFreeZones(fileInode); + } + } + } + + // Otherwise, if file doesnt already exist.. + }else{ + if ((openFlags & O_CREAT) && (result==-ENOENT) && + ((result=pfsCheckAccess(parentInode, 2))==0) && + (fileInode=pfsInodeCreate(parentInode, mode, PFS_UID, + PFS_GID, &result))) + { + if ((mode & FIO_S_IFMT) == FIO_S_IFLNK) + { + strcpy((char*)&fileInode->u.inode->data[1], (char*)freeSlot); + freeSlot=NULL; + } + + // If new file is a directory, the fill self and parent entries + if ((mode & FIO_S_IFMT) == FIO_S_IFDIR) + { + cached=pfsCacheGetData(fileInode->pfsMount, fileInode->u.inode->data[1].subpart, + fileInode->u.inode->data[1].number << fileInode->pfsMount->inode_scale, + PFS_CACHE_FLAG_NOLOAD | PFS_CACHE_FLAG_NOTHING, &result3); + if (cached) + { + pfsFillSelfAndParentDentries(cached, + &fileInode->u.inode->inode_block, + &parentInode->u.inode->inode_block); + cached->flags |= PFS_CACHE_FLAG_DIRTY; + pfsCacheFree(cached); + } + result=result3; + // Otherwise if its just a regular file, just zero its attribute entry + }else{ + cached=pfsCacheGetData(fileInode->pfsMount, fileInode->sub, fileInode->block+1, + PFS_CACHE_FLAG_NOLOAD | PFS_CACHE_FLAG_NOTHING, &result4); + if (cached) + { + memset(cached->u.aentry, 0, sizeof(pfs_inode_t)); + cached->u.aentry->aLen=sizeof(pfs_inode_t); + cached->flags |= PFS_CACHE_FLAG_DIRTY; + pfsCacheFree(cached); + } + result=result4; + } + + // Link new file with parent directory + if ((result==0) && (cached=pfsDirAddEntry(parentInode, file, &fileInode->u.inode->inode_block, + mode, &result))) + { + pfsInodeSetTimeParent(parentInode, cached); + pfsCacheFree(cached); + } + } + } +label: + pfsCacheFree(parentInode); + if ((result==0) && freeSlot && fileInode) + { + freeSlot->clink=fileInode; + if (openFlags & O_APPEND) + freeSlot->position = fileInode->u.inode->size; + else + freeSlot->position = 0; + + result=pfsBlockInitPos(freeSlot->clink, &freeSlot->block_pos, freeSlot->position); + if (result==0) + { + if ((openFlags & O_WRONLY) && + (fileInode->u.inode->attr & PFS_FIO_ATTR_CLOSED)){ + fileInode->u.inode->attr &= ~PFS_FIO_ATTR_CLOSED; + fileInode->flags |= PFS_CACHE_FLAG_DIRTY; + if (pfsMount->flags & PFS_FIO_ATTR_WRITEABLE) + pfsCacheFlushAllDirty(pfsMount); + } + if ((result=pfsFioCheckForLastError(pfsMount, result))==0) + return 0; + } + freeSlot->clink=NULL; + } + + if(fileInode) pfsCacheFree(fileInode); + + return pfsFioCheckForLastError(pfsMount, result); +} + +static int fileTransferRemainder(pfs_file_slot_t *fileSlot, void *buf, int size, int operation) +{ + u32 sector, pos; + s32 i; + int result; + pfs_blockpos_t *blockpos = &fileSlot->block_pos; + pfs_mount_t *pfsMount = fileSlot->clink->pfsMount; + pfs_unaligned_io_t *unaligned = &fileSlot->unaligned; + pfs_unaligned_io_t *unaligned2 = NULL; + pfs_blockinfo_t *bi = pfsBlockGetCurrent(blockpos); + + sector = ((bi->number+blockpos->block_offset) << pfsMount->sector_scale) + + (blockpos->byte_offset >> 9); + pos = blockpos->byte_offset & 0x1FF; + + if(operation == 0) + { //If READ, copy latest data from the buffer of any FD that was opened for writing. + for(i = 0; i < pfsConfig.maxOpen; i++) + { + if((pfsFileSlots[i].clink != NULL) + && (pfsFileSlots[i].clink->pfsMount == pfsMount) + && (pfsFileSlots[i].unaligned.dirty) + && (pfsFileSlots[i].unaligned.sub == bi->subpart) + && (pfsFileSlots[i].unaligned.sector == sector)) + { + unaligned2 = &pfsFileSlots[i].unaligned; + if(unaligned != unaligned2) + memcpy(unaligned->buffer, unaligned2->buffer, sizeof(unaligned->buffer)); + else + unaligned2 = NULL; //Nothing to update. + break; + } + } + } + + if(unaligned2 == NULL) + { //If the latest version is likely in disk. + if((unaligned->sector != sector) || (unaligned->sub!=bi->subpart)) + { + if (unaligned->dirty) + { + result=pfsMount->blockDev->transfer(pfsMount->fd, unaligned->buffer, unaligned->sub, unaligned->sector, 1, PFS_IO_MODE_WRITE); + if(result) + return result; + unaligned->dirty=0; + } + + unaligned->sub=bi->subpart; + unaligned->sector=sector; + + if(pos || (fileSlot->position != fileSlot->clink->u.inode->size)) + { + result = pfsMount->blockDev->transfer(pfsMount->fd, unaligned->buffer, unaligned->sub, unaligned->sector, 1, PFS_IO_MODE_READ); + if(result) + return result | 0x10000; + } + } + } + + if (operation==0) + memcpy(buf, &unaligned->buffer[pos], size=min(size, (int)sizeof(unaligned->buffer)-(int)pos)); + else + memcpy(&unaligned->buffer[pos], buf, size=min(size, (int)sizeof(unaligned->buffer)-(int)pos)); + + if (operation == 1) + { + if (pfsMount->flags & PFS_FIO_ATTR_WRITEABLE) + { + if ((result=pfsMount->blockDev->transfer(pfsMount->fd, unaligned->buffer, unaligned->sub, + unaligned->sector, operation, operation))) + return result; + + //In late modules, sync data with all other FDs that were opened for reading. + for(i = 0; i < pfsConfig.maxOpen; i++) + { + if((pfsFileSlots[i].clink != NULL) + && (pfsFileSlots[i].clink->pfsMount == pfsMount) + && (pfsFileSlots[i].unaligned.sub == fileSlot->unaligned.sub) + && (pfsFileSlots[i].unaligned.sector == fileSlot->unaligned.sector)) + { + if(!pfsFileSlots[i].unaligned.dirty) + memcpy(pfsFileSlots[i].unaligned.buffer, unaligned->buffer, sizeof(pfsFileSlots[i].unaligned.buffer)); + } + } + } + else + unaligned->dirty=operation; + } + return size; +} + +// Does actual read/write of data from file +static int fileTransfer(pfs_file_slot_t *fileSlot, u8 *buf, int size, int operation) +{ + int result=0; + pfs_blockpos_t *blockpos=&fileSlot->block_pos; + pfs_mount_t *pfsMount=fileSlot->clink->pfsMount; + u64 bytes_remain; + int total = size; + + // If we're writing and there is less free space in the last allocated block segment + // than can hold the data being written, then try and expand the block segment + if ((operation==1) && + (fileSlot->clink->u.inode->number_data - 1 == blockpos->block_segment)) + { + bytes_remain = (pfsBlockGetCurrent(blockpos)->count - blockpos->block_offset) * pfsMount->zsize - blockpos->byte_offset; + + if (bytes_remain < (u32)size) + { + pfsBlockExpandSegment(fileSlot->clink, blockpos, + ((size-bytes_remain+pfsMount->zsize-1) & (~(pfsMount->zsize-1))) / pfsMount->zsize); + } + } + + while (size) + { + pfs_blockinfo_t *bi; + u32 sectors; + + // Get block info for current file position + bi=pfsBlockGetCurrent(blockpos); + + // Get amount of remaining data in current block + bytes_remain=(bi->count - blockpos->block_offset) * pfsMount->zsize - blockpos->byte_offset; + + // If there is no space/data left in the current block segment, then we need to move onto the next + if (bytes_remain==0) + { + // If we're at the end of allocated block segments, then allocate a new block segment + if (blockpos->block_segment == fileSlot->clink->u.inode->number_data-1){ + if (operation==0){ + PFS_PRINTF(PFS_DRV_NAME" Panic: This is a bug!\n"); + return 0; + } + + result = pfsBlockAllocNewSegment(fileSlot->clink, blockpos, + (size - 1 + pfsMount->zsize) / pfsMount->zsize); + if(result<0) + break; + + // Otherwise, move to the next block segment + }else + if ((result=pfsBlockSeekNextSegment(fileSlot->clink, blockpos))) + { + return result; + } + + bi=pfsBlockGetCurrent(blockpos); + bytes_remain=(bi->count - blockpos->block_offset) * pfsMount->zsize - blockpos->byte_offset; + } + + if (bytes_remain==0) + { + PFS_PRINTF(PFS_DRV_NAME" Panic: There is no zone.\n"); + return 0; + } + + if(fileSlot->unaligned.dirty) + { //If there is going to be a partial transfer, write the dirty data to disk first. + u32 sector = ((bi->number + fileSlot->block_pos.block_offset) << pfsMount->sector_scale) + (fileSlot->block_pos.byte_offset / 512); + if((fileSlot->unaligned.sector == sector) && + (fileSlot->unaligned.sub == bi->subpart) + && (size < 512)) + { + if((result = pfsMount->blockDev->transfer(pfsMount->fd, fileSlot->unaligned.buffer, fileSlot->unaligned.sub, fileSlot->unaligned.sector, 1, PFS_IO_MODE_WRITE)) != 0) + return result; + + fileSlot->unaligned.dirty = 0; + } + } + + // If we are transferring size not a multiple of 512, under 512, or to + // an unaligned buffer we need to use a special function rather than + // just doing a ATA sector transfer. + if ((blockpos->byte_offset & 0x1FF) || (size < 512) || ((u32)buf & 3)) + { + if ((result=fileTransferRemainder(fileSlot, buf, size, operation)) < 0) + break; + } + else + { + sectors = (u32)(bytes_remain / 512); + if ((u32)(size / 512) < sectors) sectors = size / 512; //sectors=min(size/512, sectors) + + // Do the ATA sector transfer + result=pfsMount->blockDev->transfer(pfsMount->fd, buf, bi->subpart, + ((bi->number + blockpos->block_offset) << pfsMount->sector_scale)+(blockpos->byte_offset / 512), + sectors, operation); + if (result < 0) + { + result |= 0x10000; // TODO: EIO define + break; + } + result = sectors * 512; + } + + size -= result; + fileSlot->position += result; + buf += result; + + // If file has grown, need to mark inode as dirty + if(fileSlot->clink->u.inode->size < fileSlot->position) + { + fileSlot->clink->u.inode->size = fileSlot->position; + fileSlot->clink->flags |= PFS_CACHE_FLAG_DIRTY; + } + + blockpos->block_offset+=pfsBlockSyncPos(blockpos, result); + } + return result < 0 ? result : total; +} + +int pfsFioInit(iop_device_t *f) +{ + iop_sema_t sema; + + sema.attr = 1; + sema.option = 0; + sema.initial = 1; + sema.max = 1; + + pfsFioSema = CreateSema(&sema); + + return 0; +} + +int pfsFioDeinit(iop_device_t *f) +{ + pfsFioDevctlCloseAll(); + + DeleteSema(pfsFioSema); + + return 0; +} + +int pfsFioFormat(iop_file_t *t, const char *dev, const char *blockdev, void *args, int arglen) +{ + int *arg = (int *)args; + int fragment = 0; + int fd; + pfs_block_device_t *blockDev; + int rv; + + // Has a fragment bit pattern been specified ? + if((arglen == (3 * sizeof(int))) && (arg[1] == 0x2D66)) //arg[1] == "-f" + fragment = arg[2]; + + if((blockDev = pfsGetBlockDeviceTable(blockdev)) == 0) + return -ENXIO; + +#ifdef PFS_SUPPORT_BHDD + if (strcmp(blockDev->devName, "bhdd") == 0) + return -EACCES; +#endif + + WaitSema(pfsFioSema); + + fd = open(blockdev, O_RDWR); + + if(fd < 0) + rv = fd; + else { + rv = pfsFormat(blockDev, fd, arg[0], fragment); + close(fd); + } + + SignalSema(pfsFioSema); + + return rv; +} + +int pfsFioOpen(iop_file_t *f, const char *name, int flags, int mode) +{ + int rv = 0; + s32 i; + pfs_file_slot_t *freeSlot; + pfs_mount_t *pfsMount; + + if(!name) + return -ENOENT; + + if(!(pfsMount = pfsFioGetMountedUnit(f->unit))) + { + return -ENODEV; + } + + // Find free file slot + for(i = 0; i < pfsConfig.maxOpen; i++) + { + if(!pfsFileSlots[i].fd) { + freeSlot = &pfsFileSlots[i]; + goto pfsOpen_slotFound; + } + } + + PFS_PRINTF(PFS_DRV_NAME" Error: There are no free file slots!\n"); + freeSlot = NULL; + +pfsOpen_slotFound: + + if(!freeSlot) { + rv = -EMFILE; + goto pfsOpen_end; + } + + // Do actual open + if((rv = openFile(pfsMount, freeSlot, name, f->mode, (mode & 0xfff) | FIO_S_IFREG))) + goto pfsOpen_end; + + freeSlot->fd = f; + f->privdata = freeSlot; + +pfsOpen_end: + + SignalSema(pfsFioSema); + + return rv; +} + +int pfsFioClose(iop_file_t *f) +{ + pfs_file_slot_t *fileSlot = (pfs_file_slot_t *)f->privdata; + int rv; + + rv = pfsFioCheckFileSlot(fileSlot); + if(rv) + return rv; + + pfsFioCloseFileSlot(fileSlot); + + SignalSema(pfsFioSema); + + return rv; +} + +int pfsFioRead(iop_file_t *f, void *buf, int size) +{ + pfs_file_slot_t *fileSlot = (pfs_file_slot_t*)f->privdata; + int result = pfsFioCheckFileSlot(fileSlot); + + if (result) + { + return result; + } + + // Check bounds, adjust size if necessary + if(fileSlot->clink->u.inode->size < (fileSlot->position + size)) + size = (int)(fileSlot->clink->u.inode->size - fileSlot->position); + + result = size ? fileTransfer(fileSlot, buf, size, 0) : 0; + result = pfsFioCheckForLastError(fileSlot->clink->pfsMount, result); + + SignalSema(pfsFioSema); + return result; +} + +int pfsFioWrite(iop_file_t *f, void *buf, int size) +{ + pfs_mount_t *pfsMount; + pfs_file_slot_t *fileSlot = (pfs_file_slot_t*)f->privdata; + int result = pfsFioCheckFileSlot(fileSlot); + + if(result) + return result; + + pfsMount = fileSlot->clink->pfsMount; + + if(fileSlot->position + (unsigned int)size < fileSlot->position) + result = -EINVAL; + else + { +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + return -EBADF; + else +#endif + { + result = fileTransfer(fileSlot, buf, size, 1); + } + } + + if (pfsMount->flags & PFS_FIO_ATTR_WRITEABLE) + pfsCacheFlushAllDirty(pfsMount); + + result = pfsFioCheckForLastError(pfsMount, result); + SignalSema(pfsFioSema); + return result; +} + +static s64 _seek(pfs_file_slot_t *fileSlot, s64 offset, int whence, int mode) +{ + int rv; + s64 startPos, newPos; + + if (mode & O_DIROPEN) + { + return -EISDIR; + } + + switch (whence) + { + case SEEK_SET: + startPos = 0; + break; + case SEEK_CUR: + startPos= fileSlot->position; + break; + case SEEK_END: + startPos = fileSlot->clink->u.inode->size; + break; + default: + return -EINVAL; + } + newPos = startPos + offset; + + if (((offset < 0) && (startPos < newPos)) || + ((offset > 0) && (startPos > newPos)) || + (fileSlot->clink->u.inode->size < (u64)newPos)) + { + return -EINVAL; + } + + pfsCacheFree(fileSlot->block_pos.inode); + rv=pfsBlockInitPos(fileSlot->clink, &fileSlot->block_pos, newPos); + if (rv==0) + fileSlot->position = newPos; + else { + fileSlot->position = 0; + pfsBlockInitPos(fileSlot->clink, &fileSlot->block_pos, 0); + } + + if (rv) + { + return rv; + } + + return newPos; +} + +int pfsFioLseek(iop_file_t *f, int pos, int whence) +{ + pfs_file_slot_t *fileSlot = (pfs_file_slot_t*)f->privdata; + int result = pfsFioCheckFileSlot(fileSlot); + + if (result) + return result; + + result = (u32)_seek(fileSlot, (s64)pos, whence, f->mode); + + SignalSema(pfsFioSema); + return result; +} + +s64 pfsFioLseek64(iop_file_t *f, s64 offset, int whence) +{ + pfs_file_slot_t *fileSlot = (pfs_file_slot_t *)f->privdata; + u64 rv; + + rv=pfsFioCheckFileSlot(fileSlot); + if(!rv) + { + rv=_seek(fileSlot, offset, whence, f->mode); + SignalSema(pfsFioSema); + } + return rv; +} + +static int _remove(pfs_mount_t *pfsMount, const char *path, int mode) +{ + char szPath[256]; + int rv=0; + pfs_cache_t *parent; + pfs_cache_t *file; + +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + return -EACCES; +#endif + + if((parent=pfsInodeGetParent(pfsMount, NULL, path, szPath, &rv))==NULL) + return rv; + + if((file=pfsInodeGetFileInDir(parent, szPath, &rv))!=NULL) + { + if(mode!=0) + {// remove dir + if((file->u.inode->mode & FIO_S_IFMT) != FIO_S_IFDIR) + rv=-ENOTDIR; + else if(pfsCheckDirForFiles(file)==0) + rv=-ENOTEMPTY; + else if(((u16)file->u.inode->inode_block.number==pfsMount->root_dir.number) && + ((u16)file->u.inode->inode_block.subpart==pfsMount->root_dir.subpart)) + rv=-EBUSY; + else if(((u16)file->u.inode->inode_block.number==pfsMount->current_dir.number) && + ((u16)file->u.inode->inode_block.subpart==pfsMount->current_dir.subpart)) + rv=-EBUSY; + } + else// just a file + if((file->u.inode->mode & FIO_S_IFMT)==FIO_S_IFDIR) + rv=-EISDIR; + + if(rv==0) + { + if(file->u.inode->uid!=0) + rv=pfsCheckAccess(file, 2); + if(file->nused>=2) + rv=-EBUSY; + if(rv==0) + return pfsInodeRemove(parent, file, szPath); + } + pfsCacheFree(file); + } + pfsCacheFree(parent); + return pfsFioCheckForLastError(pfsMount, rv); +} + +int pfsFioRemove(iop_file_t *f, const char *name) +{ + pfs_mount_t *pfsMount; + int rv; + + if(!(pfsMount = pfsFioGetMountedUnit(f->unit))) + return -ENODEV; + + rv = _remove(pfsMount, name, 0); + + SignalSema(pfsFioSema); + + return rv; +} + +int pfsFioMkdir(iop_file_t *f, const char *path, int mode) +{ + pfs_mount_t *pfsMount; + int rv; + + mode = (mode & 0xfff) | 0x10000 | FIO_S_IFDIR; // TODO: change to some constant/macro + + if(!(pfsMount = pfsFioGetMountedUnit(f->unit))) + return -ENODEV; + + rv = openFile(pfsMount, NULL, path, O_CREAT | O_WRONLY, mode); + + SignalSema(pfsFioSema); + + return rv; +} + +int pfsFioRmdir(iop_file_t *f, const char *path) +{ + pfs_mount_t *pfsMount; + const char *temp; + int rv; + + temp = path + strlen(path); + if(*temp == '.') + return -EINVAL; + + if(!(pfsMount = pfsFioGetMountedUnit(f->unit))) + return -ENODEV; + + rv = _remove(pfsMount, path, 0x01); // TODO: constant for 0x01 ? + + SignalSema(pfsFioSema); + + return rv; +} + +int pfsFioDopen(iop_file_t *f, const char *name) +{ + return pfsFioOpen(f, name, 0, 0); +} + +int pfsFioDread(iop_file_t *f, iox_dirent_t *dirent) +{ + pfs_file_slot_t *fileSlot = (pfs_file_slot_t *)f->privdata; + pfs_mount_t *pfsMount; + pfs_cache_t *clink; + pfs_blockinfo_t bi; + int result; + int rv; + + rv = pfsFioCheckFileSlot(fileSlot); + if(rv < 0) + return rv; + + pfsMount = fileSlot->clink->pfsMount; + + if((fileSlot->clink->u.inode->mode & FIO_S_IFMT) != FIO_S_IFDIR) + { + rv = -ENOTDIR; + } + else + { + if((rv = pfsGetNextDentry(fileSlot->clink, &fileSlot->block_pos, (u32 *)&fileSlot->position, + dirent->name, &bi)) > 0) + { + + clink = pfsInodeGetData(pfsMount, bi.subpart, bi.number, &result); + if(clink != NULL) + { + fioStatFiller(clink, &dirent->stat); + pfsCacheFree(clink); + } + + if(result) + rv = result; + } + } + + rv = pfsFioCheckForLastError(pfsMount, rv); + SignalSema(pfsFioSema); + + return rv; +} + +static void fioStatFiller(pfs_cache_t *clink, iox_stat_t *stat) +{ + stat->mode = clink->u.inode->mode; + stat->attr = clink->u.inode->attr; + stat->size = (u32)clink->u.inode->size; + stat->hisize = (u32)(clink->u.inode->size >> 32); + memcpy(&stat->ctime, &clink->u.inode->ctime, sizeof(pfs_datetime_t)); + memcpy(&stat->atime, &clink->u.inode->atime, sizeof(pfs_datetime_t)); + memcpy(&stat->mtime, &clink->u.inode->mtime, sizeof(pfs_datetime_t)); + stat->private_0 = clink->u.inode->uid; + stat->private_1 = clink->u.inode->gid; + stat->private_2 = clink->u.inode->number_blocks; + stat->private_3 = clink->u.inode->number_data; +#ifndef PFS_STAT_RETURN_INODE_LBA + stat->private_4 = 0; + stat->private_5 = 0; +#else + stat->private_4 = clink->sub; + stat->private_5 = clink->block << pfsBlockSize; +#endif +} + +int pfsFioGetstat(iop_file_t *f, const char *name, iox_stat_t *stat) +{ + pfs_mount_t *pfsMount; + pfs_cache_t *clink; + int rv=0; + + if(!(pfsMount = pfsFioGetMountedUnit(f->unit))) + return -ENODEV; + + clink=pfsInodeGetFile(pfsMount, NULL, name, &rv); + if(clink!=NULL) + { + fioStatFiller(clink, stat); + pfsCacheFree(clink); + } + + SignalSema(pfsFioSema); + return pfsFioCheckForLastError(pfsMount, rv); +} + +int pfsFioChstat(iop_file_t *f, const char *name, iox_stat_t *stat, unsigned int statmask) +{ + pfs_mount_t *pfsMount; + pfs_cache_t *clink; + int rv = 0; + + if(!(pfsMount = pfsFioGetMountedUnit(f->unit))) + return -ENODEV; +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + { + SignalSema(pfsFioSema); + return -EBADF; + } +#endif + clink = pfsInodeGetFile(pfsMount, NULL, name, &rv); + if(clink != NULL) { + + rv = pfsCheckAccess(clink, 0x02); + if(rv == 0) { + + clink->flags |= PFS_CACHE_FLAG_DIRTY; + + if((statmask & FIO_CST_MODE) && ((clink->u.inode->mode & FIO_S_IFMT) != FIO_S_IFLNK)) + clink->u.inode->mode = (clink->u.inode->mode & FIO_S_IFMT) | (stat->mode & 0xfff); + if(statmask & FIO_CST_ATTR) + clink->u.inode->attr = (clink->u.inode->attr & 0xA0) | (stat->attr & 0xFF5F); + if(statmask & FIO_CST_SIZE) + rv = -EACCES; + if(statmask & FIO_CST_CT) + memcpy(&clink->u.inode->ctime, stat->ctime, sizeof(pfs_datetime_t)); + if(statmask & FIO_CST_AT) + memcpy(&clink->u.inode->atime, stat->atime, sizeof(pfs_datetime_t)); + if(statmask & FIO_CST_MT) + memcpy(&clink->u.inode->mtime, stat->mtime, sizeof(pfs_datetime_t)); +/* //By PFS v2.2, changing UID and GID was no longer allowed. + if(statmask & FIO_CST_PRVT) { + clink->u.inode->uid = stat->private_0; + clink->u.inode->gid = stat->private_1; + } */ + + if(pfsMount->flags & PFS_FIO_ATTR_WRITEABLE) + pfsCacheFlushAllDirty(pfsMount); + } + + pfsCacheFree(clink); + + } + + SignalSema(pfsFioSema); + return pfsFioCheckForLastError(pfsMount, rv); +} + +int pfsFioRename(iop_file_t *ff, const char *old, const char *new) +{ + char path1[256], path2[256]; + int result=0; + pfs_mount_t *pfsMount; + int f, sameParent; + pfs_cache_t *parentOld=NULL, *parentNew=NULL; + pfs_cache_t *removeOld=NULL, *removeNew=NULL; + pfs_cache_t *iFileOld=NULL, *iFileNew=NULL; + pfs_cache_t *newParent=NULL,*addNew=NULL; + + pfsMount=pfsFioGetMountedUnit(ff->unit); + if (pfsMount==0) return -ENODEV; +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + { + SignalSema(pfsFioSema); + return -EACCES; + } +#endif + parentOld=pfsInodeGetParent(pfsMount, NULL, old, path1, &result); + if (parentOld){ + u32 nused=parentOld->nused; + + if (nused != 1){ + result=-EBUSY; + goto exit; + } + + if ((iFileOld=pfsInodeGetFileInDir(parentOld, path1, &result))==NULL) goto exit; + + if ((parentNew=pfsInodeGetParent(pfsMount, NULL, new, path2, &result))==NULL) goto exit; + + f=(iFileOld->u.inode->mode & FIO_S_IFMT) == FIO_S_IFDIR; + + sameParent = parentOld == parentNew; + + if ((parentNew->nused != nused) && ((!sameParent) || (parentNew->nused!=2))){ + result=-EBUSY; + goto exit; + } + + iFileNew=pfsInodeGetFileInDir(parentNew, path2, &result); + if (iFileNew){ + if (f){ + if ((iFileNew->u.inode->mode & FIO_S_IFMT) != FIO_S_IFDIR) + result=-ENOTDIR; + else + if (pfsCheckDirForFiles(iFileNew)){ + if (iFileNew->nused >= 2) + result=-EBUSY; + else{ + if (iFileOld==iFileNew) + goto exit; + } + }else + result=-ENOTEMPTY; + }else + if ((iFileNew->u.inode->mode & FIO_S_IFMT) == FIO_S_IFDIR) + result=-EISDIR; + else + if (iFileNew->nused >= 2) + result=-EBUSY; + else{ + if (iFileOld==iFileNew) + goto exit; + } + }else + if (result==-ENOENT) + result=0; + + if (result) goto exit; + + if (f && (!sameParent)){ + pfs_cache_t *parent; + + parent=pfsCacheUsedAdd(parentNew); + do{ + pfs_cache_t *tmp; + + if (parent==iFileOld){ + result=-EINVAL; + break; + } + tmp=pfsInodeGetFileInDir(parent, "..", &result); + pfsCacheFree(parent); + if (tmp==parent)break; + parent=tmp; + }while(parent); + pfsCacheFree(parent); + } + + if (result==0){ + if (strcmp(path1, ".") && strcmp(path1, "..") && + strcmp(path2, ".") && strcmp(path2, "..")){ + result=pfsCheckAccess(parentOld, 3); + if (result==0) + result=pfsCheckAccess(parentNew, 3); + }else + result=-EINVAL; + + if (result==0){ + if (iFileNew && ((removeNew=pfsDirRemoveEntry(parentNew, path2))==NULL)) + result=-ENOENT; + else{ + removeOld=pfsDirRemoveEntry(parentOld, path1); + if (removeOld==0) + result=-ENOENT; + else{ + addNew=pfsDirAddEntry(parentNew, path2, &iFileOld->u.inode->inode_block, iFileOld->u.inode->mode, &result); + if (addNew && f && (!sameParent)) + newParent=pfsSetDentryParent(iFileOld, &parentNew->u.inode->inode_block, &result); + } + } + } + } + + if (result){ + if (removeNew) removeNew->pfsMount=NULL; + if (removeOld) removeOld->pfsMount=NULL; + if (addNew) addNew->pfsMount=NULL; + if (iFileNew) iFileNew->pfsMount=NULL; + parentOld->pfsMount=NULL; + parentNew->pfsMount=NULL; + }else{ + if (sameParent){ + if (removeOld!=addNew) + removeOld->flags |= PFS_CACHE_FLAG_DIRTY; + }else + { + pfsInodeSetTimeParent(parentOld, removeOld); + } + pfsInodeSetTimeParent(parentNew, addNew); + + if (newParent != NULL){ + pfsInodeSetTimeParent(iFileOld, newParent); + pfsCacheFree(newParent); + } + + if (iFileNew != NULL){ + iFileNew->flags &= ~PFS_CACHE_FLAG_DIRTY; + pfsBitmapFreeInodeBlocks(iFileNew); + } + + //if (pfsMount->flags & PFS_FIO_ATTR_WRITEABLE) No check for this in late versions of PFS. + pfsCacheFlushAllDirty(pfsMount); + } + if (removeOld) pfsCacheFree(removeOld); + if (addNew) pfsCacheFree(addNew); + if (removeNew) pfsCacheFree(removeNew); +exit: + if (iFileNew) pfsCacheFree(iFileNew); + pfsCacheFree(iFileOld); + pfsCacheFree(parentOld); + pfsCacheFree(parentNew); + } + SignalSema(pfsFioSema); + return pfsFioCheckForLastError(pfsMount, result); +} + +int pfsFioChdir(iop_file_t *f, const char *name) +{ + pfs_mount_t *pfsMount; + pfs_cache_t *clink; + int result = 0; + + if(!(pfsMount = pfsFioGetMountedUnit(f->unit))) + return -ENODEV; + + clink = pfsInodeGetFile(pfsMount, 0, name, &result); + if(clink != NULL) { + if((clink->u.inode->mode & FIO_S_IFMT) != FIO_S_IFDIR) + result = -ENOTDIR; + else { + + result = pfsCheckAccess(clink, 0x01); + + if(result == 0) + memcpy(&pfsMount->current_dir, &clink->u.inode->inode_block, sizeof(pfs_blockinfo_t)); + } + + pfsCacheFree(clink); + } + + SignalSema(pfsFioSema); + return pfsFioCheckForLastError(pfsMount, result); +} + +static void _sync(void) +{ + s32 i, j; + + for(i=0;idirty) { + pfs_mount_t *pfsMount=pfsFileSlots[i].clink->pfsMount; + pfsMount->blockDev->transfer(pfsMount->fd, unaligned->buffer, + unaligned->sub, unaligned->sector, 1, PFS_IO_MODE_WRITE); + + //In late modules, sync data with all other FDs that were opened for reading. + for(j = 0; j < pfsConfig.maxOpen; j++) + { + if((pfsFileSlots[j].clink != NULL) + && (pfsFileSlots[i].clink->pfsMount == pfsFileSlots[j].clink->pfsMount) + && (pfsFileSlots[i].unaligned.sub == pfsFileSlots[j].unaligned.sub) + && (pfsFileSlots[i].unaligned.sector == pfsFileSlots[j].unaligned.sector)) + { + if(!pfsFileSlots[j].unaligned.dirty) + memcpy(pfsFileSlots[j].unaligned.buffer, pfsFileSlots[i].unaligned.buffer, sizeof(pfsFileSlots[j].unaligned.buffer)); + } + } + + unaligned->dirty=0; + } + } +} + +int pfsFioSync(iop_file_t *f, const char *dev, int flag) +{ + pfs_mount_t *pfsMount; + + if(!(pfsMount = pfsFioGetMountedUnit(f->unit))) + return -ENODEV; +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + { + SignalSema(pfsFioSema); + return -ENODEV; + } +#endif + _sync(); + pfsCacheFlushAllDirty(pfsMount); + + SignalSema(pfsFioSema); + return pfsFioCheckForLastError(pfsMount, 0); +} + +int pfsFioMount(iop_file_t *f, const char *fsname, const char *devname, int flag, void *arg, int arglen) +{ + int rv; + int fd; + pfs_block_device_t *blockDev; + + if(!(blockDev = pfsGetBlockDeviceTable(devname))) + return -ENXIO; + + WaitSema(pfsFioSema); + + fd = open(devname, (flag & FIO_MT_RDONLY) ? O_RDONLY : O_RDWR); // ps2hdd.irx fd + if(fd < 0) + rv = fd; + else { + if((rv=mountDevice(blockDev, fd, f->unit, flag)) < 0) + close(fd); + } + SignalSema(pfsFioSema); + return rv; +} + +int pfsFioUmount(iop_file_t *f, const char *fsname) +{ + s32 i; + int rv=0; + int busy_flag=0; + pfs_mount_t *pfsMount; + + if((pfsMount = pfsFioGetMountedUnit(f->unit))==NULL) + return -ENODEV; + + for(i = 0; i < pfsConfig.maxOpen; i++) + { + if((pfsFileSlots[i].clink!=NULL) && (pfsFileSlots[i].clink->pfsMount==pfsMount)) + { + busy_flag=1; + break; + } + } + if(busy_flag==0) + { + pfsCacheClose(pfsMount); + close(pfsMount->fd); + pfsClearMount(pfsMount); + } + else + rv=-EBUSY; // Mount device busy + + SignalSema(pfsFioSema); + return rv; +} + +int pfsFioSymlink(iop_file_t *f, const char *old, const char *new) +{ + int rv; + pfs_mount_t *pfsMount; + int mode = 0x10000 | FIO_S_IFLNK | 0x1FF; + + if(old==NULL || new==NULL) + return -ENOENT; + + if(!(pfsMount=pfsFioGetMountedUnit(f->unit))) + return -ENODEV; + + rv = openFile(pfsMount, (pfs_file_slot_t *)old, (const char *)new, O_CREAT|O_WRONLY, mode); + SignalSema(pfsFioSema); + return rv; +} + +int pfsFioReadlink(iop_file_t *f, const char *path, char *buf, unsigned int buflen) +{ + int rv=0; + pfs_mount_t *pfsMount; + pfs_cache_t *clink; + + if(buflen < 0) + return -EINVAL; + if(!(pfsMount=pfsFioGetMountedUnit(f->unit))) + return -ENODEV; + + if((clink=pfsInodeGetFile(pfsMount, NULL, path, &rv))!=NULL) + { + if(!FIO_S_ISLNK(clink->u.inode->mode)) + rv=-EINVAL; + else + { + rv=strlen((char *)&clink->u.inode->data[1]); + if(buflen < (unsigned int)rv) + rv=(int)buflen; + memcpy(buf, &clink->u.inode->data[1], rv); + } + pfsCacheFree(clink); + } + SignalSema(pfsFioSema); + + return pfsFioCheckForLastError(pfsMount, rv); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fio.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fio.h new file mode 100644 index 0000000..76a96bd --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fio.h @@ -0,0 +1,52 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef _PFS_FIO_H +#define _PFS_FIO_H + +#define PFS_FDIRO (0x0008) /* internal use for dopen */ + +/////////////////////////////////////////////////////////////////////////////// +// Function declarations + +int pfsFioCheckForLastError(pfs_mount_t *pfsMount, int rv); +int pfsFioCheckFileSlot(pfs_file_slot_t *fileSlot); +pfs_mount_t *pfsFioGetMountedUnit(int unit); +void pfsFioCloseFileSlot(pfs_file_slot_t *fileSlot); + +/////////////////////////////////////////////////////////////////////////////// +// I/O functions + +int pfsFioInit(iop_device_t *f); +int pfsFioDeinit(iop_device_t *f); +int pfsFioFormat(iop_file_t *, const char *dev, const char *blockdev, void *arg, int arglen); +int pfsFioOpen(iop_file_t *f, const char *name, int flags, int mode); +int pfsFioClose(iop_file_t *f); +int pfsFioRead(iop_file_t *f, void *buf, int size); +int pfsFioWrite(iop_file_t *f, void *buf, int size); +int pfsFioLseek(iop_file_t *f, int pos, int whence); +int pfsFioRemove(iop_file_t *f, const char *name); +int pfsFioMkdir(iop_file_t *f, const char *path, int mode); +int pfsFioRmdir(iop_file_t *f, const char *path); +int pfsFioDopen(iop_file_t *f, const char *name); +int pfsFioDclose(iop_file_t *f); +int pfsFioDread(iop_file_t *f, iox_dirent_t *buf); +int pfsFioGetstat(iop_file_t *f, const char *name, iox_stat_t *stat); +int pfsFioChstat(iop_file_t *f, const char *name, iox_stat_t *stat, unsigned int statmask); +int pfsFioRename(iop_file_t *f, const char *old, const char *new); +int pfsFioChdir(iop_file_t *f, const char *name); +int pfsFioSync(iop_file_t *f, const char *dev, int flag); +int pfsFioMount(iop_file_t *f, const char *fsname, const char *devname, int flag, void *arg, int arglen); +int pfsFioUmount(iop_file_t *f, const char *fsname); +s64 pfsFioLseek64(iop_file_t *f, s64 offset, int whence); +int pfsFioSymlink(iop_file_t *f, const char *old, const char *new); +int pfsFioReadlink(iop_file_t *f, const char *path, char *buf, unsigned int buflen); + +#endif /* _PFS_FIO_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fioctl.c b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fioctl.c new file mode 100644 index 0000000..1ea2fb7 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fioctl.c @@ -0,0 +1,392 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# PFS ioctl and devctl related routines +*/ + +#include +#ifdef _IOP +#include +#else +#include +#endif +#include +#include +#include +#include + +#include "pfs-opt.h" +#include "libpfs.h" +#include "pfs.h" +#include "pfs_fio.h" +#include "pfs_fioctl.h" + +extern pfs_config_t pfsConfig; +extern int pfsFioSema; +extern pfs_file_slot_t *pfsFileSlots; + +#ifdef PFS_IOCTL2_INC_CHECKSUM +extern u32 pfsBlockSize; +#endif + +enum PFS_AENTRY_MODE { + PFS_AENTRY_MODE_LOOKUP = 0, + PFS_AENTRY_MODE_ADD, + PFS_AENTRY_MODE_DELETE +}; + +/////////////////////////////////////////////////////////////////////////////// +// Function declarations + +static int devctlFsckStat(pfs_mount_t *pfsMount, int mode); + +#ifdef PFS_IOCTL2_INC_CHECKSUM +static int ioctl2InvalidateInode(pfs_cache_t *clink); +#endif +static int ioctl2Attr(pfs_cache_t *clink, int cmd, void *arg, void *outbuf, u32 *offset); +static pfs_aentry_t *getAentry(pfs_cache_t *clink, char *key, char *value, int mode); +static int ioctl2AttrAdd(pfs_cache_t *clink, pfs_ioctl2attr_t *attr); +static int ioctl2AttrDelete(pfs_cache_t *clink, void *arg); +static int ioctl2AttrLookUp(pfs_cache_t *clink, char *key, char *value); +static int ioctl2AttrRead(pfs_cache_t *clink, pfs_ioctl2attr_t *attr, u32 *unkbuf); + +int pfsFioIoctl(iop_file_t *f, int cmd, void *param) +{ + return -1; +} + +int pfsFioDevctl(iop_file_t *f, const char *name, int cmd, void *arg, size_t arglen, void *buf, size_t buflen) +{ + pfs_mount_t *pfsMount; + int rv=0; + + if(!(pfsMount=pfsFioGetMountedUnit(f->unit))) + return -ENODEV; +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + { + SignalSema(pfsFioSema); + return -ENODEV; + } +#endif + switch(cmd) + { + case PDIOC_ZONESZ: + rv=pfsMount->zsize; + break; + + case PDIOC_ZONEFREE: + rv=pfsMount->zfree; + break; + + case PDIOC_CLOSEALL: + pfsFioDevctlCloseAll(); + break; + + case PDIOC_CLRFSCKSTAT: + rv=devctlFsckStat(pfsMount, PFS_MODE_REMOVE_FLAG); + break; + + case PDIOC_GETFSCKSTAT: + rv=devctlFsckStat(pfsMount, PFS_MODE_CHECK_FLAG); + break; + + case PDIOC_SHOWBITMAP: + pfsBitmapShow(pfsMount); + break; + + default: + rv=-EINVAL; + break; + + } + SignalSema(pfsFioSema); + + return rv; +} + +#ifdef PFS_IOCTL2_INC_CHECKSUM +static int ioctl2InvalidateInode(pfs_cache_t *clink) +{ + clink->u.inode->checksum++; + return clink->pfsMount->blockDev->transfer(clink->pfsMount->fd, clink->u.inode, clink->sub, clink->block << pfsBlockSize, 1 << pfsBlockSize, PFS_IO_MODE_WRITE); +} +#endif + +int pfsFioIoctl2(iop_file_t *f, int cmd, void *arg, size_t arglen, void *buf, size_t buflen) +{ + int rv; + pfs_file_slot_t *fileSlot = (pfs_file_slot_t *)f->privdata; + pfs_mount_t *pfsMount; + + if(f->mode & O_DIROPEN) + if(cmd==PIOCATTRREAD) + return -EISDIR; + + if(!(f->mode & O_WRONLY)) + { + switch(cmd) + { + case PIOCATTRLOOKUP: + case PIOCATTRREAD: + case PIOCINVINODE: + break; + default: + return -EACCES; + } + } + if((rv=pfsFioCheckFileSlot(fileSlot))<0) + return rv; + pfsMount=fileSlot->clink->pfsMount; +#ifdef PFS_SUPPORT_BHDD + if (strcmp(pfsMount->blockDev->devName, "bhdd") == 0) + return -EBADF; +#endif + switch(cmd) + { + case PIOCALLOC: + rv=pfsAllocZones(fileSlot->clink, *(int *)(arg), 1); + break; + + case PIOCFREE: + pfsFreeZones(fileSlot->clink); + break; + + case PIOCATTRADD: + case PIOCATTRDEL: + case PIOCATTRLOOKUP: + case PIOCATTRREAD: + rv=ioctl2Attr(fileSlot->clink, cmd, arg, buf, &fileSlot->aentryOffset); + break; + +#ifdef PFS_IOCTL2_INC_CHECKSUM + case PIOCINVINODE: + rv=ioctl2InvalidateInode(fileSlot->clink); + break; +#endif + + default: + rv=-EINVAL; + break; + } + + if(pfsMount->flags & PFS_FIO_ATTR_WRITEABLE) + pfsCacheFlushAllDirty(pfsMount); + rv=pfsFioCheckForLastError(pfsMount, rv); + SignalSema(pfsFioSema); + + return rv; +} + +static int ioctl2Attr(pfs_cache_t *clink, int cmd, void *arg, void *outbuf, u32 *offset) +{ // attr set, attr delete, attr lookup, attr read cmds + int rv; + pfs_cache_t *flink; + + if((flink=pfsCacheGetData(clink->pfsMount, clink->sub, clink->block+1 + ,PFS_CACHE_FLAG_NOTHING, &rv))==NULL) + return rv; + + switch(cmd) + { + case PIOCATTRADD: + rv=ioctl2AttrAdd(flink, arg); + break; + + case PIOCATTRDEL: + rv=ioctl2AttrDelete(flink, arg); + break; + + case PIOCATTRLOOKUP: + rv=ioctl2AttrLookUp(flink, arg, outbuf); + break; + + case PIOCATTRREAD: + rv=ioctl2AttrRead(flink, outbuf, offset); + break; + + } + pfsCacheFree(flink); + + return rv; +} + +void pfsFioDevctlCloseAll(void) +{ + s32 i; + + for(i=0;i < pfsConfig.maxOpen;i++) + { + if(pfsFileSlots[i].fd) + pfsFioCloseFileSlot(&pfsFileSlots[i]); + } + for(i=0;i < pfsConfig.maxOpen;i++) + { + pfs_mount_t *pfsMount; + if((pfsMount=pfsGetMountedUnit(i))!=NULL) + pfsCacheFlushAllDirty(pfsMount); + + } +} + +static int devctlFsckStat(pfs_mount_t *pfsMount, int mode) +{ + int rv; + pfs_cache_t *clink; + + if((clink=pfsCacheAllocClean(&rv))!=NULL){ + rv=pfsFsckStat(pfsMount, clink->u.superblock, PFS_FSCK_STAT_ERRORS_FIXED, mode); + pfsCacheFree(clink); + } + return rv; +} + +static pfs_aentry_t *getAentry(pfs_cache_t *clink, char *key, char *value, int mode) +{ + int kLen, fullsize; + pfs_aentry_t *aentry=clink->u.aentry; + pfs_aentry_t *aentryLast=NULL; + pfs_aentry_t *end; + + kLen=strlen(key); + fullsize=(kLen+strlen(value)+7) & ~3; + for(end=(pfs_aentry_t *)((u8*)aentry+1024);aentry < end; aentry=(pfs_aentry_t *)((u8*)aentry+aentry->aLen)) + { //Other than critical errors, do nothing about the filesystem errors. + if(aentry->aLen & 3) + PFS_PRINTF(PFS_DRV_NAME" Error: aentry allocated length/4 != 0\n"); + if(aentry->aLen < ((aentry->kLen+aentry->vLen+7) & ~3)) + { + PFS_PRINTF(PFS_DRV_NAME" Panic: aentry is too small\n"); + return NULL; + } + if(end < (pfs_aentry_t*)((u8*)aentry+aentry->aLen)) + PFS_PRINTF(PFS_DRV_NAME" Error: aentry too big\n"); + + switch(mode) + { + case PFS_AENTRY_MODE_LOOKUP: + if(kLen==aentry->kLen) + if(memcmp(key, aentry->str, kLen)==0) + return aentry; + break; + + case PFS_AENTRY_MODE_ADD: + if(aentry->kLen==0) + { + if(aentry->aLen>=fullsize) + return aentry; + } + if(aentry->aLen - ((aentry->kLen+aentry->vLen+7) & ~3) < fullsize) + continue; + return aentry; + + case PFS_AENTRY_MODE_DELETE: + default: + if(kLen==aentry->kLen) + { + if(memcmp(key, aentry->str, kLen)==0) + { + if(aentryLast!=NULL) + { + aentryLast->aLen+=aentry->aLen; + return aentry; + } + // delete it :P + aentry->kLen=0; + aentry->vLen=0; + return aentry; + } + } + aentryLast=aentry; + break; + + } + } + return NULL; +} + +static int ioctl2AttrAdd(pfs_cache_t *clink, pfs_ioctl2attr_t *attr) +{ + u32 kLen, vLen; + pfs_aentry_t *aentry; + u32 tmp; + + // input check + kLen=strlen(attr->key); + vLen=strlen(attr->value); + if(kLen>=PFS_AENTRY_KEY_MAX || vLen>=PFS_AENTRY_VALUE_MAX) // max size bounds check + return -EINVAL; + + if(kLen==0 || vLen==0) // no input check + return -EINVAL; + + if(getAentry(clink, attr->key, NULL, PFS_AENTRY_MODE_LOOKUP)) + return -EEXIST; + if((aentry=getAentry(clink, attr->key, attr->value, PFS_AENTRY_MODE_ADD)) == NULL) + return -ENOSPC; + + if(aentry->kLen==0) + tmp=aentry->aLen; + else + tmp=aentry->aLen-((aentry->kLen+(aentry->vLen + 7)) & 0x3FC); //The only case that uses 0x3FC within the whole PFS driver. + + aentry->aLen-=tmp; + aentry = (pfs_aentry_t*)((u8 *)aentry + aentry->aLen); + aentry->kLen=kLen; + aentry->vLen=vLen; + aentry->aLen=tmp; + memcpy(&aentry->str[0], attr->key, aentry->kLen); + memcpy(&aentry->str[aentry->kLen], attr->value, aentry->vLen); + clink->flags|=PFS_CACHE_FLAG_DIRTY; + + return 0; +} + +static int ioctl2AttrDelete(pfs_cache_t *clink, void *arg) +{ + pfs_aentry_t *aentry; + + if((aentry=getAentry(clink, arg, NULL, PFS_AENTRY_MODE_DELETE)) == NULL) + return -ENOENT; + clink->flags|=PFS_CACHE_FLAG_DIRTY; + return 0; +} + +static int ioctl2AttrLookUp(pfs_cache_t *clink, char *key, char *value) +{ + pfs_aentry_t *aentry; + + if((aentry=getAentry(clink, key, NULL, PFS_AENTRY_MODE_LOOKUP)) != NULL) + { + memcpy(value, &aentry->str[aentry->kLen], aentry->vLen); + value[aentry->vLen]=0; + return aentry->vLen; + } + return -ENOENT; +} + +static int ioctl2AttrRead(pfs_cache_t *clink, pfs_ioctl2attr_t *attr, u32 *offset) +{ + pfs_aentry_t *aentry; + + if(*offset >= 1024) + return 0; + do { + aentry=(pfs_aentry_t *)((u8*)clink->u.inode+*offset); + memcpy(attr->key, &aentry->str[0], aentry->kLen); + attr->key[aentry->kLen]=0; + memcpy(attr->value, &aentry->str[aentry->kLen], aentry->vLen); + attr->value[aentry->vLen]=0; + *offset+=aentry->aLen; // next + if(aentry->kLen!=0) + break; + } while(*offset < 1024); + + return aentry->kLen; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fioctl.h b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fioctl.h new file mode 100644 index 0000000..8455ce1 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/hdd/pfs/src/pfs_fioctl.h @@ -0,0 +1,23 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef _PFS_FIOCTL_H +#define _PFS_FIOCTL_H + +/////////////////////////////////////////////////////////////////////////////// +// Function declarations + +int pfsFioIoctl(iop_file_t *f, int cmd, void *param); +int pfsFioIoctl2(iop_file_t *f, int cmd, void *arg, size_t arglen, void *buf, size_t buflen); +int pfsFioDevctl(iop_file_t *f, const char *name, int cmd, void *arg, size_t arglen, void *buf, size_t buflen); + +void pfsFioDevctlCloseAll(void); + +#endif /* _PFS_FIOCTL_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/Makefile new file mode 100644 index 0000000..9f5d02b --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/Makefile @@ -0,0 +1,21 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +# IOP_CFLAGS += -DDEBUG + +IOP_CFLAGS += -mno-check-zero-division # -DSIF_CALLBACKS_12_13 + +IOP_INCS += -I$(PS2SDKSRC)/iop/iLink/iLinkman/include +IOP_INCS += -I$(PS2SDKSRC)/iop/fs/bdm/include + +IOP_OBJS = sbp2_driver.o imports.o main.o scsi.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/imports.lst new file mode 100644 index 0000000..c431857 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/imports.lst @@ -0,0 +1,65 @@ +bdm_IMPORTS_start +I_bdm_connect_bd +I_bdm_disconnect_bd +bdm_IMPORTS_end + +iLinkman_IMPORTS_start +I_iLinkEnableSBus +I_iLinkResetSBus +I_iLinkSetNodeCapabilities +I_iLinkSetTrCallbackHandler +I_iLinkGetGenerationNumber +I_iLinkGetLocalNodeID +I_iLinkGetNodeCount +I_iLinkTrAlloc +I_iLinkTrFree +I_iLinkTrWrite +I_iLinkTrRead +I_iLinkGetNodeMaxSpeed +I_iLinkGetNodeTrSpeed +I_iLinkSetNodeTrSpeed +I_iLinkFindUnit +I_iLinkReadCROM +iLinkman_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +#ifndef MINI_DRIVER +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end +#endif + +sysclib_IMPORTS_start +I_memset +sysclib_IMPORTS_end + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +sysmem_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_StartThread +I_DelayThread +I_GetSystemTime +I_SysClock2USec +I_USec2SysClock +I_SetAlarm +I_CancelAlarm +I_TerminateThread +I_DeleteThread +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_ClearEventFlag +I_SetEventFlag +I_iSetEventFlag +I_WaitEventFlag +I_DeleteEventFlag +thevent_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/include/module_debug.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/include/module_debug.h new file mode 100644 index 0000000..d58b2ae --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/include/module_debug.h @@ -0,0 +1,16 @@ +#ifndef _MODULE_DEBUG_H +#define _MODULE_DEBUG_H + +#ifndef MINI_DRIVER +#define M_PRINTF(format, args...) printf("SBP2: " format, ##args) +#else +#define M_PRINTF(format, args...) +#endif + +#ifdef DEBUG +#define M_DEBUG M_PRINTF +#else +#define M_DEBUG(format, args...) +#endif + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/include/sbp2_disk.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/include/sbp2_disk.h new file mode 100644 index 0000000..c1fcb12 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/include/sbp2_disk.h @@ -0,0 +1,153 @@ +#ifndef _SPB2_DISK_H_ +#define _SPB2_DISK_H_ + + +#include +#include "scsi.h" + + +#define XFER_BLOCK_SIZE 65024 /* 65536-512. It seems like my Oxford 934 is capable of maximum transfers of less than 65536 bytes. + NOTE: I reduced the maximum block size here by 512, since transfers are done in (smallest) groups of 512 bytes! + */ + +#define READ_TRANSACTION 0 +#define WRITE_TRANSACTION 1 + +/* Some macros */ +#define CDB_PAGE_SIZE(v) ((v) << 16) /* Not in use. */ +#define CDB_PAGE_TABLE_PRESENT(v) ((v) << 19) /* Not in use. */ +#define CDB_MAX_PAYLOAD(v) ((v) << 20) +#define CDB_SPEED(v) ((v) << 24) +#define CDB_DIRECTION(v) ((v) << 27) +#define CDB_DATA_SIZE(v) ((v)) + +/* Event flag bits. */ +#define WRITE_REQ_INCOMING 1 +#define READ_REQ_INCOMING 2 +#define BUS_RESET_COMPLETE 4 +#define ERROR_TIME_OUT 8 + +/* Management ORB opcodes */ +#define SBP2_LOGIN_REQUEST 0x0 +#define SBP2_QUERY_LOGINS_REQUEST 0x1 +#define SBP2_RECONNECT_REQUEST 0x3 +#define SBP2_SET_PASSWORD_REQUEST 0x4 +#define SBP2_LOGOUT_REQUEST 0x7 +#define SBP2_ABORT_TASK_REQUEST 0xb +#define SBP2_ABORT_TASK_SET 0xc +#define SBP2_LOGICAL_UNIT_RESET 0xe +#define SBP2_TARGET_RESET_REQUEST 0xf + +/* Configuration ROM keys */ +#define IEEE1394_CROM_LOGICAL_UNIT_NUM 0x14 +#define IEEE1394_CROM_UNIT_CHARA 0x3A +#define IEEE1394_CROM_CSR_OFFSET 0x54 +#define IEEE1394_CROM_UNIT_DIRECTORY 0xD1 + +/* Some macros. */ +#define MANAGEMENT_ORB_LOGINID(v) ((v)) +#define MANAGEMENT_ORB_LUN(v) ((v)) +#define MANAGEMENT_ORB_FUNCTION(v) ((v) << 16) +#define MANAGEMENT_ORB_RECONNECT(v) ((v) << 20) +#define MANAGEMENT_ORB_EXCLUSIVE(v) ((v) ? 1 << 28 : 0) + +#define ORB_REQUEST_FORMAT(v) ((v) << 29) +#define ORB_NOTIFY ((1) << 31) + +#define MANAGEMENT_ORB_RESPONSE_LENGTH(v) ((v)&0x0000FFFF) +#define MANAGEMENT_ORB_PASSWORD_LENGTH(v) ((v) << 16) + +#define NULL_POINTER (1<<15) + +#define RESP_SBP_STATUS(v) (((v)>>16)&0xFF) +#define RESP_LEN(v) (((v)>>24)&0x07) +#define RESP_DEAD(v) (((v)>>27)&0x01) +#define RESP_RESP(v) (((v)>>28)&0x03) +#define RESP_SRC(v) (((v)>>30)&0x03) + +struct sbp2_status{ + u32 status; + u32 ORB_low; + u8 data[24]; +}__attribute__((packed)); + +struct sbp2_pointer{ + u16 high; /* Big endian. */ + u16 NodeID; /* Big endian. */ + u32 low; /* Big endian. */ +}__attribute__((packed)); + +struct sbp2_ORB_pointer{ + u16 high; /* Big endian. */ + u16 reserved; /* Big endian. */ + u32 low; /* Big endian. */ +}__attribute__((packed)); + +struct sbp2_login_response { + u16 login_ID; /* Big endian. */ + u16 length; /* Big endian. */ + + struct sbp2_pointer command_block_agent; + u32 reconnect_hold; /* Big endian. */ +}__attribute__((packed)); + +struct management_ORB{ + union { + u32 function_data[4]; + struct { + struct sbp2_pointer password; + struct sbp2_pointer response; + } login; + }; + u32 flags; + union { + u32 function_data2; + u32 length; + }; + struct sbp2_pointer status_FIFO; +}__attribute__((packed)); + +struct CommandDescriptorBlock{ + struct sbp2_ORB_pointer NextOrb; + struct sbp2_pointer DataDescriptor; + + u32 misc; + unsigned char CDBs[12]; +}__attribute__((packed)); + +struct SBP2Device +{ + int trContext; + unsigned short int nodeID; + unsigned short int InitiatorNodeID; + unsigned short int max_payload; + unsigned short int LUN; + + unsigned short int loginID; /* Stored in big endian. */ + + unsigned char IsConnected; + unsigned char mgt_ORB_timeout; + unsigned char ORB_size; + unsigned char speed; + + unsigned long int ManagementAgent_high; + unsigned long int ManagementAgent_low; + + unsigned long int CommandBlockAgent_high; + unsigned long int CommandBlockAgent_low; + + unsigned long int sectorSize; + unsigned long int maxLBA; + void *cache; + + struct scsi_interface scsi; +}; + +/* Function prototypes. */ +void init_ieee1394DiskDriver(void); +int ieee1394_SendCommandBlockORB(struct SBP2Device *dev, struct CommandDescriptorBlock *firstCDB); +int ieee1394_Sync(void); +void DeinitIEEE1394(void); + + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/include/scsi.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/include/scsi.h new file mode 100644 index 0000000..8ef394e --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/include/scsi.h @@ -0,0 +1,17 @@ +#ifndef _SCSI_H +#define _SCSI_H + +struct scsi_interface { + void* priv; + char* name; + unsigned int max_sectors; + + int (*get_max_lun)(struct scsi_interface* scsi); + int (*queue_cmd)(struct scsi_interface* scsi, const unsigned char* cmd, unsigned int cmd_len, unsigned char* data, unsigned int data_len, unsigned int data_wr); +}; + +int scsi_init(void); +void scsi_connect(struct scsi_interface* scsi); +void scsi_disconnect(struct scsi_interface* scsi); + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/irx_imports.h new file mode 100644 index 0000000..0cce6d0 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/irx_imports.h @@ -0,0 +1,35 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include "iLinkman.h" +#include +#include +#include +#include +#include +#ifdef SIF_CALLBACKS_12_13 +#include +#endif +#include +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/main.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/main.c new file mode 100644 index 0000000..4be6f12 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/main.c @@ -0,0 +1,29 @@ +#define MAJOR_VER 1 +#define MINOR_VER 1 +#define MODNAME "IEEE1394_bd" + +#include "sbp2_disk.h" +#include "scsi.h" +#include +#include +#include + +#include "module_debug.h" + +IRX_ID(MODNAME, MAJOR_VER, MINOR_VER); + +int _start(int argc, char** argv) +{ + M_PRINTF("IEEE1394 Driver v%d.%d\n", MAJOR_VER, MINOR_VER); + + // initialize the SCSI driver + if (scsi_init() != 0) { + M_PRINTF("ERROR: initializing SCSI driver!\n"); + return MODULE_NO_RESIDENT_END; + } + + // initialize the IEEE1394 driver + init_ieee1394DiskDriver(); + + return MODULE_RESIDENT_END; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/sbp2_driver.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/sbp2_driver.c new file mode 100644 index 0000000..064a2e5 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/sbp2_driver.c @@ -0,0 +1,669 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "iLinkman.h" +#include "sbp2_disk.h" +#include "scsi.h" +#include "usbhdfsd-common.h" + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +#define MAX_DEVICES 5 +static struct SBP2Device SBP2Devices[MAX_DEVICES]; +static u8 *writeBuffer = NULL; + +/* Thread creation data. */ +static iop_thread_t threadData = { + TH_C, /* attr */ + 0, /* option */ + NULL, /* thread */ + 0x1000, /* stacksize */ + 0x30 /* priority */ +}; + +//static unsigned long int iLinkBufferOffset, iLinkTransferSize; +static int sbp2_event_flag; + +static void ieee1394_callback(int reason, unsigned long int offset, unsigned long int size); +static void iLinkIntrCBHandlingThread(void* arg); +static int ieee1394_SendManagementORB(int mode, struct SBP2Device* dev); +static int ieee1394_InitializeFetchAgent(struct SBP2Device* dev); +static inline int ieee1394_Sync_withTimeout(u32 n500mSecUnits); +void free(void* buffer); +void* malloc(int NumBytes); + +static volatile union { + struct sbp2_status status; + unsigned char buffer[32]; /* Maximum 32 bytes. */ +} statusFIFO; + +static void ieee1394_callback(int reason, unsigned long int offset, unsigned long int size) +{ +#if 0 + iLinkBufferOffset=offset; + iLinkTransferSize=size; + + if(reason==iLink_CB_WRITE_REQUEST){ + u32 statusFIFO_result; + +// M_DEBUG("Write request: Offset: 0x%08lx; size: 0x%08lx.\n", iLinkBufferOffset, iLinkTransferSize); + + if(iLinkBufferOffset==(u32)&statusFIFO){ /* Check to be sure that we don't signal ieee1394_Sync() too early; Some transactions are transactions involving multiple ORBs. */ + statusFIFO_result=statusFIFO.status.status; + if(RESP_SRC(statusFIFO_result)!=0) SetEventFlag(sbp2_event_flag, WRITE_REQ_INCOMING); /* Signal ieee1394_Sync() only after the last ORB was read. */ + } + } + else +#endif + if (reason == iLink_CB_BUS_RESET) { + SetEventFlag(sbp2_event_flag, BUS_RESET_COMPLETE); + } +#if 0 + else{ + //M_DEBUG("Read request: Offset: 0x%08lx; size: 0x%08lx;\n", iLinkBufferOffset, iLinkTransferSize); + } +#endif +} + +/* Event flag creation data. */ +static iop_event_t evfp = { + 2, /* evfp.attr=EA_MULTI */ + 0, /* evfp.option */ + 0 /* evfp.bits */ +}; + +int iLinkIntrCBThreadID; +static int sbp2_get_max_lun(struct scsi_interface* scsi); +static int sbp2_queue_cmd(struct scsi_interface* scsi, const unsigned char* cmd, unsigned int cmd_len, unsigned char* data, unsigned int data_len, unsigned int data_wr); + +void init_ieee1394DiskDriver(void) +{ + int i; + + for (i = 0; i < MAX_DEVICES; i++) { + SBP2Devices[i].IsConnected = 0; + SBP2Devices[i].nodeID = 0; + SBP2Devices[i].trContext = (-1); + + SBP2Devices[i].scsi.priv = &SBP2Devices[i]; + SBP2Devices[i].scsi.name = "sd"; + SBP2Devices[i].scsi.max_sectors = XFER_BLOCK_SIZE / 512; + SBP2Devices[i].scsi.get_max_lun = sbp2_get_max_lun; + SBP2Devices[i].scsi.queue_cmd = sbp2_queue_cmd; + } + + writeBuffer = malloc(XFER_BLOCK_SIZE); + + sbp2_event_flag = CreateEventFlag(&evfp); + + M_DEBUG("Starting threads..\n"); + + threadData.thread = &iLinkIntrCBHandlingThread; + iLinkIntrCBThreadID = CreateThread(&threadData); + StartThread(iLinkIntrCBThreadID, NULL); + + iLinkSetTrCallbackHandler(&ieee1394_callback); + + M_DEBUG("Threads created and started.\n"); + + iLinkEnableSBus(); +} + +static int initConfigureSBP2Device(struct SBP2Device* dev) +{ + unsigned char retries; + + // Try 5 x 200ms to login (same as Linux: drivers/firewire/sbp2.c) + retries = 5; + while (1) { + if (ieee1394_SendManagementORB(SBP2_LOGIN_REQUEST, dev) >= 0) + break; + + retries--; + if (retries == 0) + break; + + DelayThread(200 * 1000); // 200ms + } + + if (retries == 0) { + M_DEBUG("Failed to log into the SBP-2 device.\n"); + return -1; + } + + if (ieee1394_InitializeFetchAgent(dev) < 0) { + M_DEBUG("Error initializing the SBP-2 device's Fetch Agent.\n"); + return -2; + } + + scsi_connect(&dev->scsi); + + M_DEBUG("Completed device initialization.\n"); + + return 0; +} + +static inline int initSBP2Disk(struct SBP2Device* dev) +{ + void* managementAgentAddr = NULL; + unsigned int ConfigurationROMOffset, DirectorySize, i, LeafData, UnitDirectoryOffset; + int result; + + UnitDirectoryOffset = 0; + + /* !! NOTE !! sce1394CrRead() reads data starting from the start of the target device's configuration ROM (0x400), + and the offset and data to be read is specified in quadlets (Groups of 4 bytes)!!!!! */ + + M_DEBUG("Reading configuration ROM for the unit directory offset of node 0x%08x\n", dev->nodeID); + + /* Offset in quadlets: 0x14 / 4 = 5 */ + ConfigurationROMOffset = 5; + + if ((result = iLinkReadCROM(dev->nodeID, ConfigurationROMOffset, 1, &LeafData)) < 0) { + M_DEBUG("Error reading the configuration ROM. Error %d.\n", result); + return (result); + } + + ConfigurationROMOffset++; + + /* Get the Unit Directory's offset from the root directory. */ + DirectorySize = LeafData >> 16; + for (i = 0; i < DirectorySize; i++) { + if ((result = iLinkReadCROM(dev->nodeID, ConfigurationROMOffset, 1, &LeafData)) < 0) { + M_DEBUG("Error reading the configuration ROM. Error %d.\n", result); + return (result); + } + + if ((LeafData >> 24) == IEEE1394_CROM_UNIT_DIRECTORY) { + UnitDirectoryOffset = ConfigurationROMOffset + (LeafData & 0x00FFFFFF); + break; + } + + ConfigurationROMOffset++; + } + if (i == DirectorySize) + return -1; + + if ((result = iLinkReadCROM(dev->nodeID, UnitDirectoryOffset, 1, &LeafData)) < 0) { + M_DEBUG("Error reading the configuration ROM. Error %d.\n", result); + return (result); + } + + DirectorySize = LeafData >> 16; + for (i = 0; i < DirectorySize; i++) { + /* Get the offset in the configuration ROM of the unit record. */ + if ((result = iLinkReadCROM(dev->nodeID, UnitDirectoryOffset + 1 + i, 1, &LeafData)) < 0) { + M_DEBUG("Error reading the configuration ROM. Error %d.\n", result); + return (result); + } + + switch (LeafData >> 24) { + /* Now get the address of the Management Agent CSR. */ + case IEEE1394_CROM_CSR_OFFSET: + managementAgentAddr = (void*)(LeafData & 0x00FFFFFF); /* Mask off the bits that represent the Management Agent key. */ + M_DEBUG("managementAgentAddr=0x%08lx.\n", (u32)managementAgentAddr * 4); + + dev->ManagementAgent_low = (u32)managementAgentAddr * 4 + 0xf0000000; + dev->ManagementAgent_high = 0x0000ffff; + break; + case IEEE1394_CROM_UNIT_CHARA: + dev->mgt_ORB_timeout = (LeafData & 0x0000FF00) >> 8; + dev->ORB_size = LeafData & 0x000000FF; + M_DEBUG("mgt_ORB_timeout=%u; ORB_size=%u.\n", dev->mgt_ORB_timeout, dev->ORB_size); + break; + case IEEE1394_CROM_LOGICAL_UNIT_NUM: + dev->LUN = LeafData & 0x0000FFFF; + M_DEBUG("LUN=0x%08x.\n", dev->LUN); + break; + } + } + + return 1; +} + +/* Hardware event handling threads. */ +static void iLinkIntrCBHandlingThread(void* arg) +{ + int nNodes, i, targetDeviceID, nodeID, result; + static const unsigned char PayloadSizeLookupTable[] = { + 7, /* S100; 2^(7+2)=512 */ + 8, /* S200; 2^(8+2)=1024 */ + 9, /* S400; 2^(9+2)=2048 */ + }; + + while (1) { + WaitEventFlag(sbp2_event_flag, BUS_RESET_COMPLETE, WEF_AND | WEF_CLEAR, NULL); + + /* Disconnect all currently connected nodes. */ + for (i = 0; i < MAX_DEVICES; i++) { + if (SBP2Devices[i].trContext >= 0) { + scsi_disconnect(&SBP2Devices[i].scsi); + + iLinkTrFree(SBP2Devices[i].trContext); + SBP2Devices[i].trContext = -1; + } + } + + if ((nNodes = iLinkGetNodeCount()) < 0) + M_DEBUG("Critical error: Failure getting the number of nodes!\n"); /* Error. */ + + M_PRINTF("BUS RESET DETECTED. Nodes: %d\n", nNodes); + M_PRINTF("Local Node: 0x%08x.\n", iLinkGetLocalNodeID()); + + //DelayThread(500000); /* Give the devices on the bus some time to initialize themselves (The SBP-2 standard states that a maximum of 5 seconds may be given). */ + + targetDeviceID = 0; + + for (i = 0; i < nNodes; i++) { + if (targetDeviceID >= MAX_DEVICES) { + M_DEBUG("Warning! There are more devices that what can be connected to.\n"); + break; + } + + M_PRINTF("Attempting to initialize unit %d...\n", i); + + /* 16-bit node ID = BUS NUMBER (Upper 10 bits) followed by the NODE ID (Lower 6 bits). */ + if ((nodeID = iLinkFindUnit(i, 0x0609e, 0x010483)) < 0) { + M_DEBUG("Error: Unit %d is not a valid SBP-2 device. Code: %d.\n", i, nodeID); + continue; + } + + M_PRINTF("Detected SBP-2 device.\n"); + + SBP2Devices[targetDeviceID].InitiatorNodeID = iLinkGetLocalNodeID(); + + M_PRINTF("Local Node: 0x%08x.\n", SBP2Devices[targetDeviceID].InitiatorNodeID); + +#if 0 + if(SBP2Devices[targetDeviceID].IsConnected){ /* Already connected to the device. */ + if(SBP2Devices[targetDeviceID].nodeID==nodeID){ /* Make sure that we're attempting to re-connect to the same device. */ + if(ieee1394_SendManagementORB(SBP2_RECONNECT_REQUEST, &SBP2Devices[i])<0){ + M_DEBUG("Error reconnecting to the SBP-2 device %u.\n", nodeID); + } + else{ + M_DEBUG("Successfully reconnected to SBP-2 device %u.", nodeID); + targetDeviceID++; + continue; + } + } + else SBP2Devices[targetDeviceID].IsConnected=0; + } +#endif + + SBP2Devices[targetDeviceID].IsConnected = 0; + + /* Attempt a login into the device. */ + SBP2Devices[targetDeviceID].nodeID = nodeID; + if ((result = initSBP2Disk(&SBP2Devices[targetDeviceID])) < 0) { + M_DEBUG("Error initializing the device. Code: %d.\n", result); + continue; + } + + SBP2Devices[targetDeviceID].trContext = iLinkTrAlloc(nodeID, iLinkGetNodeMaxSpeed(nodeID)); + + if (SBP2Devices[targetDeviceID].trContext >= 0) { + M_PRINTF("Connected device as node 0x%08x.\n", SBP2Devices[targetDeviceID].nodeID); + M_PRINTF("Generation number: %d.\n", iLinkGetGenerationNumber()); + + SBP2Devices[targetDeviceID].speed = iLinkGetNodeTrSpeed(SBP2Devices[targetDeviceID].trContext); + M_PRINTF("Current speed: %d.\n", SBP2Devices[targetDeviceID].speed); + + SBP2Devices[targetDeviceID].max_payload = PayloadSizeLookupTable[SBP2Devices[targetDeviceID].speed]; + + if (initConfigureSBP2Device(&SBP2Devices[targetDeviceID]) >= 0) { + SBP2Devices[targetDeviceID].IsConnected = 1; + targetDeviceID++; + } + } else + M_DEBUG("Error allocating a transaction.\n"); + } + + for (; targetDeviceID < MAX_DEVICES; targetDeviceID++) + SBP2Devices[targetDeviceID].IsConnected = 0; /* Mark the unused device slots as being unused. */ + } +} + +static void ieee1394_ResetFetchAgent(struct SBP2Device* dev) +{ + unsigned long int dummy; + int result; + + /* Reset the Fetch Agent. */ + if ((result = iLinkTrWrite(dev->trContext, dev->CommandBlockAgent_high, dev->CommandBlockAgent_low + 0x04, &dummy, 4)) < 0) { + M_DEBUG("Error writing to the Fetch Agent's AGENT_RESET register @ 0x%08lx %08lx. Code: %d.\n", dev->CommandBlockAgent_high, dev->CommandBlockAgent_low + 0x04, result); + } +} + +static int ieee1394_GetFetchAgentState(struct SBP2Device* dev) +{ + unsigned long int FetchAgentState; + int result; + + if ((result = iLinkTrRead(dev->trContext, dev->CommandBlockAgent_high, dev->CommandBlockAgent_low, &FetchAgentState, 4)) < 0) { + M_DEBUG("Error reading the Fetch Agent's AGENT_STATE register @ 0x%08lx %08lx. Code: %d.\n", dev->CommandBlockAgent_high, dev->CommandBlockAgent_low, result); + return -1; + } else { + FetchAgentState = BSWAP32(FetchAgentState); + M_DEBUG("Fetch Agent state: %lu.\n", FetchAgentState); + return FetchAgentState; + } +} + +static int ieee1394_InitializeFetchAgent(struct SBP2Device* dev) +{ + int result, retries; + void* dummy_ORB; + struct sbp2_pointer address; + + M_DEBUG("Initializing fetch agent..."); + + dummy_ORB = malloc(dev->ORB_size * 4); + memset(dummy_ORB, 0, dev->ORB_size * 4); + + ieee1394_ResetFetchAgent(dev); + + /* Write the address of the dummy ORB to the fetch agent's ORB_POINTER register. */ + address.low = (u32)dummy_ORB; + address.NodeID = dev->InitiatorNodeID; + address.high = 0; + + ((struct sbp2_ORB_pointer*)dummy_ORB)->reserved = NULL_POINTER; + ((struct sbp2_ORB_pointer*)dummy_ORB)->high = ((struct sbp2_ORB_pointer*)dummy_ORB)->low = 0; + ((struct management_ORB*)dummy_ORB)->flags = (u32)(ORB_NOTIFY | ORB_REQUEST_FORMAT(3)); + + retries = 0; + while ((result = iLinkTrWrite(dev->trContext, dev->CommandBlockAgent_high, dev->CommandBlockAgent_low + 0x08, &address, 8)) < 0) { + M_DEBUG("Error writing to the Fetch Agent's ORB_POINTER register @ 0x%08lx %08lx. Code: %d.\n", dev->CommandBlockAgent_high, dev->CommandBlockAgent_low + 0x08, result); + ieee1394_ResetFetchAgent(dev); + + retries++; + if (retries > 3) + return (-1); + } + + result = ieee1394_Sync(); + ieee1394_GetFetchAgentState(dev); + + free(dummy_ORB); + + M_DEBUG("done!\n"); + + return 1; +} + +static int ieee1394_SendManagementORB(int mode, struct SBP2Device* dev) +{ + int result; + struct sbp2_pointer address; + + struct sbp2_login_response login_result; + struct management_ORB new_management_ORB; + + memset((void*)&statusFIFO, 0, sizeof(statusFIFO)); + memset(&login_result, 0, sizeof(struct sbp2_login_response)); + memset(&new_management_ORB, 0, sizeof(struct management_ORB)); + + new_management_ORB.status_FIFO.low = (u32)&statusFIFO; + new_management_ORB.flags = (u32)(ORB_NOTIFY | ORB_REQUEST_FORMAT(0) | MANAGEMENT_ORB_FUNCTION(mode)); + + switch (mode) { + case SBP2_LOGIN_REQUEST: /* Login. */ + /* The reconnect timeout is now set to 0, since the mechanism that determines whether the initiator was already logged into the target or not was not accurate. */ + new_management_ORB.flags |= (u32)(MANAGEMENT_ORB_RECONNECT(0) | MANAGEMENT_ORB_EXCLUSIVE(1) | MANAGEMENT_ORB_LUN(dev->LUN)); + + new_management_ORB.login.response.low = (u32)&login_result; + new_management_ORB.length = (MANAGEMENT_ORB_RESPONSE_LENGTH(sizeof(struct sbp2_login_response)) | MANAGEMENT_ORB_PASSWORD_LENGTH(0)); + break; +#if 0 + case SBP2_RECONNECT_REQUEST: /* Reconnect. */ + new_management_ORB.flags|=(u32)(MANAGEMENT_ORB_RECONNECT(4) | MANAGEMENT_ORB_LOGINID(dev->loginID)); /* loginID was stored as a big endian number, so it has to be converted into little endian first. :( */ + break; +#endif + default: + M_DEBUG("Warning! Unsupported management ORB type!\n"); + } + + address.NodeID = dev->InitiatorNodeID; + address.high = 0; + address.low = (u32)&new_management_ORB; + + M_DEBUG("Management ORB: %p. size=%d.\n", &new_management_ORB, sizeof(struct management_ORB)); + M_DEBUG("Address pointer: %p\n", &address); + + if ((result = iLinkTrWrite(dev->trContext, dev->ManagementAgent_high, dev->ManagementAgent_low, &address, 8)) < 0) { /* Write the Login ORB address to the target's Management Agent CSR. */ + M_DEBUG("Error writing to the Management Agent CSR @ 0x%08lx %08lx. Code: %d.\n", dev->ManagementAgent_high, dev->ManagementAgent_low, result); + return (result); + } + + M_DEBUG("Waiting for ILINK...\n"); + + result = ieee1394_Sync_withTimeout(dev->mgt_ORB_timeout); + + M_DEBUG("statusFIFO= %p; [0]=%u.\n", &statusFIFO, statusFIFO.buffer[0]); + if (result >= 0) { + switch (mode) { + case SBP2_LOGIN_REQUEST: /* Login. */ + M_DEBUG("Done. command_block_agent= 0x%08x %08lx.\n", login_result.command_block_agent.high, login_result.command_block_agent.low); + + /* Store the address to the target's command block agent. */ + + dev->CommandBlockAgent_high = login_result.command_block_agent.high; + dev->CommandBlockAgent_low = login_result.command_block_agent.low; + + dev->loginID = login_result.login_ID; /* Store the login ID. */ + + M_DEBUG("Login response size: %u.", login_result.length); + M_DEBUG("Signed into SBP-2 device node 0x%08x. Login ID: %u\n", dev->nodeID, dev->loginID); + break; +#if 0 + case SBP2_RECONNECT_REQUEST: /* Reconnect. */ + /* Just return the result from ieee1394_Sync(). */ + break; +#endif + default: + M_DEBUG("Warning! Unsupported management ORB type!\n"); + } + + /* Validate the fetch agent's CSR address. */ + if ((dev->CommandBlockAgent_low < 0xF0010000) || ((dev->CommandBlockAgent_high & 0xFFFF) != 0x0000FFFF)) + result = (-1); + } + + return result; +} + +int ieee1394_SendCommandBlockORB(struct SBP2Device* dev, struct CommandDescriptorBlock* firstCDB) +{ + int result, retries; + struct sbp2_pointer address; + + memset((void*)&statusFIFO, 0, sizeof(statusFIFO)); + + address.low = (u32)firstCDB; + address.NodeID = dev->InitiatorNodeID; + address.high = 0; + + retries = 0; + + /* Write the pointer to the first ORB in the fetch agent's NEXT_ORB register. */ + while ((result = iLinkTrWrite(dev->trContext, dev->CommandBlockAgent_high, dev->CommandBlockAgent_low + 0x08, &address, 8)) < 0) { + M_DEBUG("Error writing to the Fetch Agent's ORB_POINTER register @ 0x%08lx %08lx. Code: %d.\n", dev->CommandBlockAgent_high, dev->CommandBlockAgent_low + 0x08, result); + + DelayThread(200000); + ieee1394_ResetFetchAgent(dev); + + retries++; + if (retries > 3) + return (-1); + } + +#if 0 + /* Write a value to the fetch agent's DOORBELL register. */ + result=1; + if((result=iLinkTrWrite(dev->trContext, dev->CommandBlockAgent_high, dev->CommandBlockAgent_low+0x10, &result, 4))<0){ + M_DEBUG("Error writing to the Fetch Agent's DOORBELL register @ 0x%08lx %08lx. Code: %d.\n", dev->CommandBlockAgent_high, dev->CommandBlockAgent_low+0x10, result); + return -2; + } +#endif + + return 1; +} + +static int sbp2_get_max_lun(struct scsi_interface* scsi) +{ + return 0; +} + +static int sbp2_queue_cmd(struct scsi_interface* scsi, const unsigned char* cmd, unsigned int cmd_len, unsigned char* data, unsigned int data_len, unsigned int data_wr) +{ + struct SBP2Device* dev = (struct SBP2Device*)scsi->priv; + int i; + int ret; + struct CommandDescriptorBlock cdb; + + M_DEBUG("sbp2_queue_cmd(0x%02x)\n", cmd[0]); + + cdb.misc = ORB_NOTIFY | ORB_REQUEST_FORMAT(0) | CDB_MAX_PAYLOAD(dev->max_payload) | CDB_SPEED(dev->speed); + cdb.misc |= data_wr ? CDB_DIRECTION(WRITE_TRANSACTION) : CDB_DIRECTION(READ_TRANSACTION); + if (data_len > 0) + cdb.misc |= CDB_DATA_SIZE(data_len); + + cdb.DataDescriptor.low = data_wr ? (u32)writeBuffer : (u32)data; + cdb.DataDescriptor.high = 0; + cdb.DataDescriptor.NodeID = dev->InitiatorNodeID; + + cdb.NextOrb.high = 0; + cdb.NextOrb.low = 0; + cdb.NextOrb.reserved = NULL_POINTER; + + // Copy and BSWAP32 the SCSI command + for (i = 0; i < cmd_len / 4; i++) + ((unsigned int*)cdb.CDBs)[i] = BSWAP32(((unsigned int*)cmd)[i]); + + if ((data_len > 0) && (data_wr == 1)) { + // BSWAP32 all data we write + for (i = 0; i < data_len / 4; i++) + ((unsigned int*)writeBuffer)[i] = BSWAP32(((unsigned int*)data)[i]); + } + + ieee1394_SendCommandBlockORB(dev, &cdb); + ret = ieee1394_Sync(); + + if (ret != 0) { + M_DEBUG("sbp2_queue_cmd error %d\n", ret); + } else if ((data_len > 0) && (data_wr == 0)) { + // BSWAP32 all data we read + for (i = 0; i < data_len / 4; i++) + ((unsigned int*)data)[i] = BSWAP32(((unsigned int*)data)[i]); + } + + return ret; +} + +/* static unsigned int alarm_cb(void *arg){ + iSetEventFlag(sbp2_event_flag, ERROR_TIME_OUT); + return 0; +} */ + +static int ProcessStatus(void) +{ + u32 statusFIFO_result; + unsigned char status, resp, dead, sense, len; + int result; + + statusFIFO_result = statusFIFO.status.status; + status = RESP_SBP_STATUS(statusFIFO_result); + resp = RESP_RESP(statusFIFO_result); + dead = RESP_DEAD(statusFIFO_result); + len = RESP_LEN(statusFIFO_result); + sense = ((statusFIFO.status.data[0]) >> 16) & 0xF; + + M_DEBUG("result: 0x%08lx; status: 0x%02x; RESP: 0x%02x; Dead: %u; len: 0x%02x; sense: 0x%02x.\n", statusFIFO_result, status, resp, dead, len, sense); + if (sense == 0) + sense = 1; /* Workaround for faulty firmwares: The sense code is 0 or was not sent when it's supposed to be sent. */ + + result = (((status == 0) || (status == 0x0B)) && (resp == 0) && (!dead) && (len == 1)) ? 0 : -sense; + + if (result < 0) { + M_PRINTF("result: 0x%08lx; status: 0x%02x; RESP: 0x%02x; Dead: %u; len: 0x%02x; sense: 0x%02x.\n", statusFIFO_result, status, resp, dead, len, sense); + } + + return result; +} + +/* This is declared as inline as there is only one call to it. */ +static inline int ieee1394_Sync_withTimeout(u32 n500mSecUnits) +{ + /* iop_sys_clock_t timeout_clk; + u32 ef_result; + + USec2SysClock(n500mSecUnits*500000, &timeout_clk); + + SetAlarm(&timeout_clk, &alarm_cb, NULL); + WaitEventFlag(sbp2_event_flag, WRITE_REQ_INCOMING|ERROR_TIME_OUT, WEF_OR|WEF_CLEAR, &ef_result); + + if(ef_result&ERROR_TIME_OUT){ + M_DEBUG("-=Time out=-\n"); + return(-1); + } + else CancelAlarm(&alarm_cb, NULL); */ + + unsigned int i = 0; + + while (RESP_SRC(statusFIFO.status.status) == 0) { + if (i > n500mSecUnits * 10000) { + M_DEBUG("-=Time out=-\n"); + return (-1); + } + + DelayThread(50); + i++; + }; + + return (ProcessStatus()); +} + +int ieee1394_Sync(void) +{ + // WaitEventFlag(sbp2_event_flag, WRITE_REQ_INCOMING, WEF_AND|WEF_CLEAR, NULL); + + while (RESP_SRC(statusFIFO.status.status) == 0) { + DelayThread(50); + }; + + return (ProcessStatus()); +} + +void DeinitIEEE1394(void) +{ + TerminateThread(iLinkIntrCBThreadID); + DeleteThread(iLinkIntrCBThreadID); + DeleteEventFlag(sbp2_event_flag); +} + +void* malloc(int NumBytes) +{ + int OldState; + void* buffer; + + CpuSuspendIntr(&OldState); + buffer = AllocSysMemory(ALLOC_FIRST, NumBytes, NULL); + CpuResumeIntr(OldState); + + return buffer; +} + +void free(void* buffer) +{ + int OldState; + + CpuSuspendIntr(&OldState); + FreeSysMemory(buffer); + CpuResumeIntr(OldState); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/scsi.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/scsi.c new file mode 100644 index 0000000..236b1f6 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd/src/scsi.c @@ -0,0 +1,308 @@ +#include +#include +#include +#include + +#include "scsi.h" +#include + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +#define getBI32(__buf) ((((u8*)(__buf))[3] << 0) | (((u8*)(__buf))[2] << 8) | (((u8*)(__buf))[1] << 16) | (((u8*)(__buf))[0] << 24)) +#define SCSI_MAX_RETRIES 16 + +typedef struct _inquiry_data { + u8 peripheral_device_type; // 00h - Direct access (Floppy), 1Fh none (no FDD connected) + u8 removable_media; // 80h - removeable + u8 iso_ecma_ansi; + u8 response_data_format; + u8 additional_length; + u8 res[3]; + u8 vendor[8]; + u8 product[16]; + u8 revision[4]; +} inquiry_data; + +typedef struct _sense_data { + u8 error_code; + u8 res1; + u8 sense_key; + u8 information[4]; + u8 add_sense_len; + u8 res3[4]; + u8 add_sense_code; + u8 add_sense_qual; + u8 res4[4]; +} sense_data; + +typedef struct _read_capacity_data { + u8 last_lba[4]; + u8 block_length[4]; +} read_capacity_data; + +#define NUM_DEVICES 2 +static struct block_device g_scsi_bd[NUM_DEVICES]; + +// +// Private Low level SCSI commands +// +static int scsi_cmd(struct block_device* bd, unsigned char cmd, void* buffer, int buf_size, int cmd_size) +{ + unsigned char comData[12] = { 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + struct scsi_interface* scsi = (struct scsi_interface*)bd->priv; + + //M_DEBUG("%s\n", __func__); + + comData[0] = cmd; + comData[4] = cmd_size; + + return scsi->queue_cmd(scsi, comData, 12, buffer, buf_size, 0); +} + +static inline int scsi_cmd_test_unit_ready(struct block_device* bd) +{ + M_DEBUG("%s\n", __func__); + + return scsi_cmd(bd, 0x00, NULL, 0, 0); +} + +static inline int scsi_cmd_request_sense(struct block_device* bd, void* buffer, int size) +{ + M_DEBUG("%s\n", __func__); + + return scsi_cmd(bd, 0x03, buffer, size, size); +} + +static inline int scsi_cmd_inquiry(struct block_device* bd, void* buffer, int size) +{ + M_DEBUG("%s\n", __func__); + + return scsi_cmd(bd, 0x12, buffer, size, size); +} + +static int scsi_cmd_start_stop_unit(struct block_device* bd, u8 param) +{ + M_DEBUG("%s\n", __func__); + + return scsi_cmd(bd, 0x1b, NULL, 0, param); +} + +static inline int scsi_cmd_read_capacity(struct block_device* bd, void* buffer, int size) +{ + M_DEBUG("%s\n", __func__); + + return scsi_cmd(bd, 0x25, buffer, size, 0); +} + +static int scsi_cmd_rw_sector(struct block_device* bd, unsigned int lba, const void* buffer, unsigned short int sectorCount, unsigned int write) +{ + unsigned char comData[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + struct scsi_interface* scsi = (struct scsi_interface*)bd->priv; + + M_DEBUG("scsi_cmd_rw_sector - 0x%08x %p 0x%04x\n", lba, buffer, sectorCount); + + comData[0] = write ? 0x2a : 0x28; + comData[2] = (lba & 0xFF000000) >> 24; //lba 1 (MSB) + comData[3] = (lba & 0xFF0000) >> 16; //lba 2 + comData[4] = (lba & 0xFF00) >> 8; //lba 3 + comData[5] = (lba & 0xFF); //lba 4 (LSB) + comData[7] = (sectorCount & 0xFF00) >> 8; //Transfer length MSB + comData[8] = (sectorCount & 0xFF); //Transfer length LSB + return scsi->queue_cmd(scsi, comData, 12, (void*)buffer, bd->sectorSize * sectorCount, write); +} + +// +// Private +// +static int scsi_warmup(struct block_device* bd) +{ + struct scsi_interface* scsi = (struct scsi_interface*)bd->priv; + inquiry_data id; + sense_data sd; + read_capacity_data rcd; + int stat; + + M_DEBUG("%s\n", __func__); + + stat = scsi->get_max_lun(scsi); + M_DEBUG("scsi->get_max_lun %d\n", stat); + + memset(&id, 0, sizeof(inquiry_data)); + if ((stat = scsi_cmd_inquiry(bd, &id, sizeof(inquiry_data))) < 0) { + M_PRINTF("ERROR: scsi_cmd_inquiry %d\n", stat); + return -1; + } + + M_PRINTF("Vendor: %.8s\n", id.vendor); + M_PRINTF("Product: %.16s\n", id.product); + M_PRINTF("Revision: %.4s\n", id.revision); + + while ((stat = scsi_cmd_test_unit_ready(bd)) != 0) { + M_PRINTF("ERROR: scsi_cmd_test_unit_ready %d\n", stat); + + stat = scsi_cmd_request_sense(bd, &sd, sizeof(sense_data)); + if (stat != 0) + M_PRINTF("ERROR: scsi_cmd_request_sense %d\n", stat); + + if ((sd.error_code == 0x70) && (sd.sense_key != 0x00)) { + M_PRINTF("Sense Data key: %02X code: %02X qual: %02X\n", sd.sense_key, sd.add_sense_code, sd.add_sense_qual); + + if ((sd.sense_key == 0x02) && (sd.add_sense_code == 0x04) && (sd.add_sense_qual == 0x02)) { + M_PRINTF("ERROR: Additional initalization is required for this device!\n"); + if ((stat = scsi_cmd_start_stop_unit(bd, 1)) != 0) { + M_PRINTF("ERROR: scsi_cmd_start_stop_unit %d\n", stat); + return -1; + } + } + } + } + + if ((stat = scsi_cmd_read_capacity(bd, &rcd, sizeof(read_capacity_data))) != 0) { + M_PRINTF("ERROR: scsi_cmd_read_capacity %d\n", stat); + return -1; + } + + bd->sectorSize = getBI32(&rcd.block_length); + bd->sectorOffset = 0; + bd->sectorCount = getBI32(&rcd.last_lba); + M_PRINTF("%u %u-byte logical blocks: (%uMB / %uMiB)\n", bd->sectorCount, bd->sectorSize, bd->sectorCount / ((1000 * 1000) / bd->sectorSize), bd->sectorCount / ((1024 * 1024) / bd->sectorSize)); + + return 0; +} + +// +// Block device interface +// +static int scsi_read(struct block_device* bd, u32 sector, void* buffer, u16 count) +{ + struct scsi_interface* scsi = (struct scsi_interface*)bd->priv; + u16 sc_remaining = count; + int retries; + + M_DEBUG("%s: sector=%d, count=%d\n", __func__, (int)sector, count); + + while (sc_remaining > 0) { + u16 sc = sc_remaining > scsi->max_sectors ? scsi->max_sectors : sc_remaining; + + for (retries = SCSI_MAX_RETRIES; retries > 0; retries--) { + if (scsi_cmd_rw_sector(bd, sector, buffer, sc, 0) == 0) + break; + } + + if (retries == 0) + return -EIO; + + sc_remaining -= sc; + sector += sc; + buffer = (u8*)buffer + (sc * bd->sectorSize); + } + + return count; +} + +static int scsi_write(struct block_device* bd, u32 sector, const void* buffer, u16 count) +{ + struct scsi_interface* scsi = (struct scsi_interface*)bd->priv; + u16 sc_remaining = count; + int retries; + + M_DEBUG("%s: sector=%d, count=%d\n", __func__, (int)sector, count); + + while (sc_remaining > 0) { + u16 sc = sc_remaining > scsi->max_sectors ? scsi->max_sectors : sc_remaining; + + for (retries = SCSI_MAX_RETRIES; retries > 0; retries--) { + if (scsi_cmd_rw_sector(bd, sector, buffer, sc, 1) == 0) + break; + } + + if (retries == 0) + return -EIO; + + sc_remaining -= sc; + sector += sc; + buffer = (u8*)buffer + (sc * bd->sectorSize); + } + + return count; +} + +static void scsi_flush(struct block_device* bd) +{ + M_DEBUG("%s\n", __func__); + + // Dummy function +} + +static int scsi_stop(struct block_device* bd) +{ + int stat; + + M_DEBUG("%s\n", __func__); + + if ((stat = scsi_cmd_start_stop_unit(bd, 0)) != 0) { + M_PRINTF("ERROR: scsi_cmd_start_stop_unit %d\n", stat); + } + + return stat; +} + +// +// Public functions +// +void scsi_connect(struct scsi_interface* scsi) +{ + int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < NUM_DEVICES; ++i) { + if (g_scsi_bd[i].priv == NULL) { + struct block_device* bd = &g_scsi_bd[i]; + + bd->priv = scsi; + bd->name = scsi->name; + scsi_warmup(bd); + bdm_connect_bd(bd); + break; + } + } +} + +void scsi_disconnect(struct scsi_interface* scsi) +{ + int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < NUM_DEVICES; ++i) { + if (g_scsi_bd[i].priv == scsi) { + struct block_device* bd = &g_scsi_bd[i]; + bdm_disconnect_bd(bd); + bd->priv = NULL; + break; + } + } +} + +int scsi_init(void) +{ + int i; + + M_DEBUG("%s\n", __func__); + + for (i = 0; i < NUM_DEVICES; ++i) { + g_scsi_bd[i].devNr = i; + g_scsi_bd[i].parNr = 0; + g_scsi_bd[i].parId = 0x00; + + g_scsi_bd[i].priv = NULL; + g_scsi_bd[i].read = scsi_read; + g_scsi_bd[i].write = scsi_write; + g_scsi_bd[i].flush = scsi_flush; + g_scsi_bd[i].stop = scsi_stop; + } + + return 0; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd_mini/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd_mini/Makefile new file mode 100644 index 0000000..a93c2ba --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_bd_mini/Makefile @@ -0,0 +1,13 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/iLink/IEEE1394_bd/src/ + +IOP_CFLAGS += -DMINI_DRIVER + +include $(PS2SDKSRC)/iop/iLink/IEEE1394_bd/Makefile diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/Makefile new file mode 100644 index 0000000..182327c --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/Makefile @@ -0,0 +1,20 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +# IOP_CFLAGS += -DDEBUG -DDEBUG_EXTREME + +IOP_CFLAGS += -mno-check-zero-division # -DSIF_CALLBACKS_12_13 + +IOP_INCS += -I$(PS2SDKSRC)/iop/iLink/iLinkman/include + +IOP_OBJS = sbp2_driver.o imports.o main.o scsi.o fat_write.o fs_driver.o scache.o fat_driver.o part_driver.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/README b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/README new file mode 100644 index 0000000..7aa2dec --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/README @@ -0,0 +1,37 @@ +IEEE1394_disk v1.06E README file - 2012/02/29 +============================================= + +IEEE1394_disk is an SBP-2 over IEEE1394 device software driver. +It's designed to be used with iLinkman v0.98H and later. + +It was based on USBHDFSD, and hence shares the features of USBHDFSD. +It supports the FAT12, FAT16 and FAT32 filesystems, and has experimental (Untested) write support. +Caution should be exercised when attempting to write data with this driver as anything can go wrong, possibly causing the existing data on your disk to be damaged. + +Hardware tested on: +=================== +Consoles: + *SCPH-39006 (With an unknown modchip installed, possibly a M2 chip) + *SCPH-10000 + +IEEE1394 enclosure: + *SmartDrive IEEE1394 + USB 2.0 combo HDD enclosure. + Chipset: Oxford Semiconductor OXUF934SSA-LQAG + +Additional notes: +================= +*IEEE1394 enclosures with the Prolific PL-3507 chip do not work with IEEE1394_disk. + I am not sure whether the Initio INIC-1430 and that certain Genesys chip which I had mentioned in the iLinkman README file are incompatible with IEEE1394_disk. + +Credits: +======== +USBHDFSD project developers. + +Special thanks go to: + *EEUG, for providing a partially completed SBP-2 device driver for the PS2. + *Mark K., for volunteering to be a beta tester for the early IEEE1394_disk versions. + +A short note for programmers: +============================= +In order to work on IEEE1394_disk properly, knowledge on the SBP-2 protocol is required. +The T10 Project 1155D document that is titled "Information technology - Serial Bus Protocol 2 (SBP-2)" (Revision 4; Dated May 19, 1998) was what I used, and was found through a Google search (In February 2011). diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/Changelog.txt b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/Changelog.txt new file mode 100644 index 0000000..3de607f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/Changelog.txt @@ -0,0 +1,88 @@ +NOTE! The entry at the top is the oldest, and the entry at the bottom is the newest! +------------------------------------------------------------------------------------ + +2011/03/17 - v1.00 +================================= +-Initial release that supported iLinkman v0.91A and later. + +2011/03/20 - v1.01 +================================= +-Cleaned up ieee1394_Sync() to remove a redundant loop. +-Added code to automatically retry logging in into the SBP-2 device in the event the first attempt at logging in was to fail. + +2011/04/15 - v1.02 +================================ +-Added ieee1394_Sync_withTimeout(). It's a wrapper function to ieee1394_Sync(), and accepts a value that will be used as a timeout. +-Modified ieee1394_SendManagementORB() to use ieee1394_Sync_withTimeout() instead of ieee1394_Sync(), to prevent freezing up the console if the target device was to not respond. + +2011/05/01 - v1.03 +================================ +-Updated the driver to work with iLinkman v0.95. + +2011/05/07 - v1.04 +================================ +-Updated the driver to work with iLinkman v0.96. +-Some of the event flag manipulation functions are using the wrong defines for waiting on/setting/clearing event flag bits. +-Some redundant code was removed. +-Calls to ClearEventFlag() were replaced by setting the event flag mode to include WEF_CLEAR for calls to WaitEventFlag(). + +2011/05/17 - v1.05 +================================ +-Fixed sense code and response code handling. +-Removed some of the unused structures from scsi.h. +-Removed the volatile keyword from variables that have it, but their values are in no way adjusted by hardware. + +2011/05/25 - v1.06 +================================ +-Fixed sense code and response code handling yet again. +-Shifted the READ CAPACITY command to immediately after the INQUIRY command. This is to prevent some devices with a Prolific chipset from malfunctioning. +-Removed calls to READ SENSE. RBC enclosures might DIE after receiving such a command since they might not support it and were not well programmed to handle unimplemented commands. :( +-Corrected the capacity calculation code and related structures to use UNSIGNED LONG integers instead of SIGNED integers. + +2011/05/27 - v1.06 +================================ +-Corrected the formatting of one of the debug messages (Line 505 of sbp2_driver.c). +-Corrected yet again the sense and response code handling code, so that errors that occur during READ SECTOR operations would no longer go unnoticed. + +2011/05/29 - v1.06A +================================ +-Fixed the max_payload field of all ORBs. Previously, all transactions will have a max_payload size of 9, which might not be a good thing for S100 and S200 transactions. +-Fixed a bug in the code that parses the configuration ROM of the SBP-2 devices. If the Unit Directory offset was not the first entry within the Root Directory, there was quite a good chance that the offsets will be miscalculated. +-The waiting time between the bus reset and initialization of all devices on the bus was reduced from 600000 usec to 500000 usec. + +2011/06/28 - v1.06B +================================ +-The WRITE sector SCSI command function has been fixed, but is still untested. + +2011/08/11 - v1.06C +================================ +-Removed old testing code in sbp2_driver.c: The payload size was always that of the S100 transfer mode. +-Declaration the device name in main.c as const. +-Edited main.c to make it neater. + +2011/08/12 - v1.06C1 +================================ +-Block size reduced to 65535 bytes - the maximum value that appears to be supported by my Oxford 934-based enclosure. + +2011/09/29 - v1.06D +================================ +-Consolidated all calls to AllocSysMemory() and FreeSysMemory() to internal versions of malloc() and free() respectively. Within the malloc() and free() functions, AllocSysMemory() and FreeSysMemory() are called respectively after suspending interrupts and thread cycling. + This is to observe the requirements of AllocSysMemory() and FreeSysMemory(). +-Commented out the delay at line 262 of sbp2_driver.c. A delay is actually not required, but some devices just need it. Anyway, those devices should reset the bus again once they become ready. +-ORBs are no longer allocated with AllocSysMemory(), but are now allocated from a fixed ORB buffer. + This is for performance, since AllocSysMemory() is slow. +-Support for the reconnection ORB has been withdrawn. The system that determines whether the host was already logged into the target was not accurate at all. +-The Makefile has been edited to use the default level of optimization as specified by the development environment, + and to only delete the object files and compiled binary whenever a "make clean" command is invoked. +-Added code to fail device initialization if ConfigureSBP2Device() fails. + +2012/02/29 - v1.06E +================================ +-Updated the driver to support the new DMA-enabled iLinkman module (v0.98H). + Hence, older versions of iLinkman are not supported as they do not use threads! +-Block size reduced to 65024 bytes (65536-512). It seems like my Oxford 934 is capable of maximum transfers of less than 65536 bytes. + NOTE: I reduced the maximum block size here by 512, since transfers are done in (smallest) groups of 512 bytes! + +2012/04/06 - v1.06E1 +================================ +-Data read in will be byte-swapped asynchronously, as other requests are being executed. diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/KnownBugs.txt b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/KnownBugs.txt new file mode 100644 index 0000000..73c3dd1 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/KnownBugs.txt @@ -0,0 +1,3 @@ +-Some enclosures are not working properly with the driver, mostly due to bugs in the enclosures' firmwares. :( + +Last updated: 2011/05/25 diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/TODO.txt b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/TODO.txt new file mode 100644 index 0000000..9e40a5d --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/TODO.txt @@ -0,0 +1,4 @@ +-Add reconnection support. +-Add code to detect and determine the maximum block size for the SBP-2 device. Right now, it is fixed to 65024 bytes. + +Last updated: 2012/02/29 \ No newline at end of file diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/USBHDFSD/usb_mass/README b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/USBHDFSD/usb_mass/README new file mode 100644 index 0000000..c574185 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/doc/USBHDFSD/usb_mass/README @@ -0,0 +1,125 @@ +----------------------------------------------------------------------------- + USB_MASS - the usb mass storage driver for ps2 + ver. 0.31 +----------------------------------------------------------------------------- + +This is the driver for ps2 that supports usb flash drives and other usb +mass storage devices plugged in the 'black box'. +The basic idea is to plug the usb bar flash disk into ps2 usb port and +be able to access stored files from within the homebrew ps2 programs. + +Supported hardware: + - bulk only devices with scsi command set (I hope that most of the recent + flash disks will work) + Tested with: + * Seitec Usb Bar (1022_128M sticker) - working + * SWEEX (FX300010) 6 In 1 multi pannel - first CF slot working + * ViPowER usb to ide cable (VP-9208 + VP-9054V HDD enclosure) - working + * Ne Way MP3 player 256MB + * MSI Mega Stick 511 (128MB, MP3 player) - working + * iMex-A2U2 external HDD enclosure - working (in case the disk/driver + behaves inreliably - use supplied power cable) + +Supported features: + - fat12, fat16, fat32. First suitable partition is used. + - basic support for long filenames (128 chars in the filename). + - read and write access. + Note: write access is experimental - use at your own risks! + +Missing features: + - multi partition acces + - real unicode decoding and conversion for long filenames + - only one mass device connected is currently supported + - file system error detection - if you plug in disk with corrupted + filesystem then the resluts are unspecified + - and much more :-) Driver is still in development so you may + encounter many bugs. + + +How to use: +The usb_mass driver requires that usbd.irx is loaded. You can use either +usbd.irx that can be found on some games and demo disks or you can use +npm_usbd.irx that is part of the naplink ps2 server side. Then load +the mass_usb.irx and you are ready to acces the "mass:" device by calling +open("mass:xxx/yyy.txt", O_RDONLY), read etc. When you plug in +the flash disk (the supported one) you should see the message on the +console ("usb_mass: connect ok!") which means that device is recognised +and ready to use. There is an example in the ee directory that lists +directory content of the disk's root directory. + +Performance: +My tests show that file transfer speed is about 500kbytes per second. +If large non fragmented files are accesed (several megabytes) then the +speed jumps at 550kbytes/s. It's not much but when compared to maximum +usb 1.1 tranfer speed it's not that bad (max is about 700kb/s). + +Compilation: +Copy the content to ps2sdk/samples/usb_mass directory and run make +in ee and/or iop subdirectory to get example elf and driver irx. + + +Change log: + +ver 0.32 (EEUG) +-------- +- Handle devices without partition table (floppy-like) + +ver 0.31 +-------- +- Compatibility improvement in warmup stage by BraveDog + +ver 0.30 +-------- +- Write support for fat12, fat16 and fat32 file systems. + The write support is disabled by default because I did'n run + extensive tests, so there is a risk of loosing your data. + If you want to enable it then modify the makefile inside the + iop directory, uncomment the 'WRITE_SUPPORT' variable and recompile. + + !!!! Don't forget to BACKUP YOUR DATA first !!!! + + note: - fioRmdir requires device number in the name (use 'mass0:\xx..'). + - fioRemove bug (calling fioMkdir afterwards) was hack-patched. + + +ver 0.24 +-------- +- bugfix - scsi inquiry command asked more data than required +- removed device reset during configuration of the device (caused freeze for + some devices, other devices were able to survive the reset ) + +ver 0.23 +-------- +- dopen dclose dread getstat implementation by raipsu + +ver 0.22 +-------- +Hermes Notes: +-Added support for different sizes of sector (512 to 4096) +-Modified scache control and reader to read blocks of 4096 bytes. It use the same memory and run well. +-Some changes necessary in fat_driver +-Tested in a 128MB Pendrive with FAT16 and 512bytes per sector (4 sector per cluster) +-Tested in a Ne Way MP3 player 256MB with FAT16 & FAT32, 2048 bytes per sector (2 sector per cluster) + +ver 0.21 +-------- +- ps2sdk compatible + +ver 0.2 +------- +- support for the fat32 filesystem + +ver 0.1 +------- +-initial version + + +Credits: (alphabetical order :) +BraveDog,Jonathan Fox (FAT system guide), Hermes, mrbrown, ole, oobles, +Gustvo Scotti, raipsu, TyRaNiD, and the ps2dev scene. + +Thanks: +to all folks who helped me with testing. + +License: +See the file LICENSE included with this distribution for licensing terms. diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/fat_driver.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/fat_driver.c new file mode 100644 index 0000000..354336f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/fat_driver.c @@ -0,0 +1,990 @@ +//--------------------------------------------------------------------------- +//File name: fat_driver.c +//--------------------------------------------------------------------------- +#include +#include + +#ifdef WIN32 +#include +#include +#include +#else +#include +//#include + +#include +#include +#endif + +#include "usbhd_common.h" +#include "scache.h" +#include "fat_driver.h" +#include "fat.h" +#include "sbp2_disk.h" +#include "scsi.h" + +//#define DEBUG //comment out this line when not debugging + +#include "mass_debug.h" + +#define READ_SECTOR(d, a, b) scache_readSector((d)->cache, (a), (void **)&b) + +#define NUM_DRIVES 10 +static fat_driver* g_fatd[NUM_DRIVES]; + +//--------------------------------------------------------------------------- +int InitFAT(void) +{ + int i; + + for (i = 0; i < NUM_DRIVES; ++i) + g_fatd[i] = NULL; + + return 0; +} + +//--------------------------------------------------------------------------- +int strEqual(const char *s1, const char* s2) { + char u1, u2; + for (;;) { + u1 = *s1++; + u2 = *s2++; + if (u1 >64 && u1 < 91) u1+=32; + if (u2 >64 && u2 < 91) u2+=32; + + if (u1 != u2) { + return -1; + } + if (u1 == '\0') { + return 0; + } + } +} + +/* + + 0x321, 0xABC + + byte| byte| byte| + +--+--+--+--+--+--+ + |2 |1 |C |3 |A |B | + +--+--+--+--+--+--+ + +*/ + +//--------------------------------------------------------------------------- +unsigned int fat_getClusterRecord12(unsigned char* buf, int type) { + if (type) { //1 + return ((buf[1]<< 4) + (buf[0] >>4)); + } else { // 0 + return (((buf[1] & 0x0F) << 8) + buf[0]); + } +} + +//--------------------------------------------------------------------------- +// Get Cluster chain into buffer +// returns: +// 0 :if buf is full (bufSize entries) and more chain entries exist +// 1-n :number of filled entries of the buf +// -1 :error +//--------------------------------------------------------------------------- +//for fat12 +/* fat12 cluster records can overlap the edge of the sector so we need to detect and maintain + these cases +*/ +static int fat_getClusterChain12(fat_driver* fatd, unsigned int cluster, unsigned int* buf, unsigned int bufSize, int startFlag) { + int ret; + unsigned int i, recordOffset, fatSector, lastFatSector; + unsigned char xbuf[4], sectorSpan, cont; + unsigned char* sbuf = NULL; //sector buffer + + cont = 1; + lastFatSector = -1; + i = 0; + if (startFlag) { + buf[i] = cluster; //store first cluster + i++; + } + while(i < bufSize && cont) { + recordOffset = (cluster * 3) / 2; //offset of the cluster record (in bytes) from the FAT start + fatSector = recordOffset / fatd->partBpb.sectorSize; + sectorSpan = 0; + if ((recordOffset % fatd->partBpb.sectorSize) == (fatd->partBpb.sectorSize - 1)) { + sectorSpan = 1; + } + if (lastFatSector != fatSector || sectorSpan) { + ret = READ_SECTOR(fatd->dev, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat12 sector failed! sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector ); + return -EIO; + } + lastFatSector = fatSector; + + if (sectorSpan) { + xbuf[0] = sbuf[fatd->partBpb.sectorSize - 2]; + xbuf[1] = sbuf[fatd->partBpb.sectorSize - 1]; + ret = READ_SECTOR(fatd->dev, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector + 1, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat12 sector failed sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector + 1); + return -EIO; + } + xbuf[2] = sbuf[0]; + xbuf[3] = sbuf[1]; + } + } + if (sectorSpan) { // use xbuf as source buffer + cluster = fat_getClusterRecord12(xbuf + (recordOffset % fatd->partBpb.sectorSize) - (fatd->partBpb.sectorSize-2), cluster % 2); + } else { // use sector buffer as source buffer + cluster = fat_getClusterRecord12(sbuf + (recordOffset % fatd->partBpb.sectorSize), cluster % 2); + } + + if ((cluster & 0xFFF) >= 0xFF8) { + cont = 0; //continue = false + } else { + buf[i] = cluster & 0xFFF; + i++; + } + } + return i; +} + + +//--------------------------------------------------------------------------- +//for fat16 +static int fat_getClusterChain16(fat_driver* fatd, unsigned int cluster, unsigned int* buf, unsigned int bufSize, int startFlag) { + int ret; + unsigned int i, indexCount, fatSector, lastFatSector; + unsigned char cont; + unsigned char* sbuf = NULL; //sector buffer + + cont = 1; + indexCount = fatd->partBpb.sectorSize / 2; //FAT16->2, FAT32->4 + lastFatSector = -1; + i = 0; + if (startFlag) { + buf[i] = cluster; //store first cluster + i++; + } + while(i < bufSize && cont) { + fatSector = cluster / indexCount; + if (lastFatSector != fatSector) { + ret = READ_SECTOR(fatd->dev, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat16 sector failed! sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector ); + return -EIO; + } + + lastFatSector = fatSector; + } + cluster = getUI16(sbuf + ((cluster % indexCount) * 2)); + if ((cluster & 0xFFFF) >= 0xFFF8) { + cont = 0; //continue = false + } else { + buf[i] = cluster & 0xFFFF; + i++; + } + } + return i; +} + +//--------------------------------------------------------------------------- +//for fat32 +static int fat_getClusterChain32(fat_driver* fatd, unsigned int cluster, unsigned int* buf, unsigned int bufSize, int startFlag) { + int ret; + unsigned int i, indexCount, fatSector, lastFatSector; + unsigned char cont; + unsigned char* sbuf = NULL; //sector buffer + + cont = 1; + indexCount = fatd->partBpb.sectorSize / 4; //FAT16->2, FAT32->4 + lastFatSector = -1; + i = 0; + if (startFlag) { + buf[i] = cluster; //store first cluster + i++; + } + while(i < bufSize && cont) { + fatSector = cluster / indexCount; + if (lastFatSector != fatSector) { + ret = READ_SECTOR(fatd->dev, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat32 sector failed sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector ); + return -EIO; + } + + lastFatSector = fatSector; + } + cluster = getUI32(sbuf + ((cluster % indexCount) * 4)); + if ((cluster & 0xFFFFFFF) >= 0xFFFFFF8) { + cont = 0; //continue = false + } else { + buf[i] = cluster & 0xFFFFFFF; + i++; + } + } + return i; +} + +//--------------------------------------------------------------------------- +int fat_getClusterChain(fat_driver* fatd, unsigned int cluster, unsigned int* buf, unsigned int bufSize, int startFlag) { + + if (cluster == fatd->lastChainCluster) { + return fatd->lastChainResult; + } + + switch (fatd->partBpb.fatType) { + case FAT12: fatd->lastChainResult = fat_getClusterChain12(fatd, cluster, buf, bufSize, startFlag); break; + case FAT16: fatd->lastChainResult = fat_getClusterChain16(fatd, cluster, buf, bufSize, startFlag); break; + case FAT32: fatd->lastChainResult = fat_getClusterChain32(fatd, cluster, buf, bufSize, startFlag); break; + } + fatd->lastChainCluster = cluster; + return fatd->lastChainResult; +} + +//--------------------------------------------------------------------------- +void fat_invalidateLastChainResult(fat_driver* fatd) +{ + fatd->lastChainCluster = 0; +} + +//--------------------------------------------------------------------------- +static void fat_determineFatType(fat_bpb* partBpb) { + unsigned int sector, clusterCount; + + //get sector of cluster 0 + sector = fat_cluster2sector(partBpb, 0); + //remove partition start sector to get BR+FAT+ROOT_DIR sector count + sector -= partBpb->partStart; + sector = partBpb->sectorCount - sector; + clusterCount = sector / partBpb->clusterSize; + //XPRINTF("USBHDFSD: Data cluster count = %u \n", clusterCount); + + if (clusterCount < 4085) { + partBpb->fatType = FAT12; + } else + if (clusterCount < 65525) { + partBpb->fatType = FAT16; + } else { + partBpb->fatType = FAT32; + } +} + +//--------------------------------------------------------------------------- +static int fat_getPartitionBootSector(struct SBP2Device* dev, unsigned int sector, fat_bpb* partBpb) { + fat_raw_bpb* bpb_raw; //fat16, fat12 + fat32_raw_bpb* bpb32_raw; //fat32 + int ret; + unsigned char* sbuf = NULL; //sector buffer + + ret = READ_SECTOR(dev, sector, sbuf); //read partition boot sector (first sector on partition) + if (ret < 0) { + XPRINTF("USBHDFSD: Read partition boot sector failed sector=%u! \n", sector); + return -EIO; + } + + bpb_raw = (fat_raw_bpb*) sbuf; + bpb32_raw = (fat32_raw_bpb*) sbuf; + + //set fat common properties + partBpb->sectorSize = getUI16(bpb_raw->sectorSize); + partBpb->clusterSize = bpb_raw->clusterSize; + partBpb->resSectors = getUI16(bpb_raw->resSectors); + partBpb->fatCount = bpb_raw->fatCount; + partBpb->rootSize = getUI16(bpb_raw->rootSize); + partBpb->fatSize = getUI16(bpb_raw->fatSize); + partBpb->trackSize = getUI16(bpb_raw->trackSize); + partBpb->headCount = getUI16(bpb_raw->headCount); + partBpb->sectorCount = getUI16(bpb_raw->sectorCountO); + if (partBpb->sectorCount == 0) { + partBpb->sectorCount = getUI32(bpb_raw->sectorCount); // large partition + } + partBpb->partStart = sector; + partBpb->rootDirStart = partBpb->partStart + (partBpb->fatCount * partBpb->fatSize) + partBpb->resSectors; + for (ret = 0; ret < 8; ret++) { + partBpb->fatId[ret] = bpb_raw->fatId[ret]; + } + partBpb->fatId[ret] = 0; + partBpb->rootDirCluster = 0; + partBpb->dataStart = partBpb->rootDirStart + (partBpb->rootSize / (partBpb->sectorSize >> 5)); + + fat_determineFatType(partBpb); + + //fat32 specific info + if (partBpb->fatType == FAT32 && partBpb->fatSize == 0) { + partBpb->fatSize = getUI32(bpb32_raw->fatSize32); + partBpb->activeFat = getUI16(bpb32_raw->fatStatus); + if (partBpb->activeFat & 0x80) { //fat not synced + partBpb->activeFat = (partBpb->activeFat & 0xF); + } else { + partBpb->activeFat = 0; + } + partBpb->rootDirStart = partBpb->partStart + (partBpb->fatCount * partBpb->fatSize) + partBpb->resSectors; + partBpb->rootDirCluster = getUI32(bpb32_raw->rootDirCluster); + for (ret = 0; ret < 8; ret++) { + partBpb->fatId[ret] = bpb32_raw->fatId[ret]; + } + partBpb->fatId[ret] = 0; + partBpb->dataStart = partBpb->rootDirStart; + } + + printf("USBHDFSD: Fat type %u Id %s \n", partBpb->fatType, partBpb->fatId); + return 1; +} + +//--------------------------------------------------------------------------- +/* + returns: + 0 - no more dir entries + 1 - short name dir entry found + 2 - long name dir entry found + 3 - deleted dir entry found +*/ +int fat_getDirentry(unsigned char fatType, fat_direntry* dir_entry, fat_direntry_summary* dir ) { + int i, j; + unsigned int offset; + unsigned char cont; + u16 character; + + //detect last entry - all zeros (slight modification by radad) + if (dir_entry->sfn.name[0] == 0) { + return 0; + } + //detect deleted entry - it will be ignored + if (dir_entry->sfn.name[0] == 0xE5) { + return 3; + } + + //detect long filename + if (dir_entry->lfn.rshv == 0x0F && dir_entry->lfn.reserved1 == 0x00 && dir_entry->lfn.reserved2[0] == 0x00) { + //long filename - almost whole direntry is unicode string - extract it + offset = dir_entry->lfn.entrySeq & 0x3f; + offset--; + offset = offset * 13; + //name - 1st part + cont = 1; + for (i = 0; i < 10 && cont; i+=2) { + character = dir_entry->lfn.name1[i] | (dir_entry->lfn.name1[i+1] << 8); + + if (character == 0 || offset >= FAT_MAX_NAME) { + dir->name[offset] = 0; //terminate + cont = 0; //stop + } else { + // Handle non-ASCII characters + dir->name[offset] = character < 128 ? dir_entry->lfn.name1[i] : '?'; + offset++; + } + } + //name - 2nd part + for (i = 0; i < 12 && cont; i+=2) { + character = dir_entry->lfn.name2[i] | (dir_entry->lfn.name2[i+1] << 8); + + if (character == 0 || offset >= FAT_MAX_NAME) { + dir->name[offset] = 0; //terminate + cont = 0; //stop + } else { + // Handle non-ASCII characters + dir->name[offset] = character < 128 ? dir_entry->lfn.name2[i] : '?'; + offset++; + } + } + //name - 3rd part + for (i = 0; i < 4 && cont; i+=2) { + character = dir_entry->lfn.name3[i] | (dir_entry->lfn.name3[i+1] << 8); + + if (character == 0 || offset >= FAT_MAX_NAME) { + dir->name[offset] = 0; //terminate + cont = 0; //stop + } else { + // Handle non-ASCII characters + dir->name[offset] = character < 128 ? dir_entry->lfn.name3[i] : '?'; + offset++; + } + } + if ((dir_entry->lfn.entrySeq & 0x40)) { //terminate string flag + dir->name[offset] = 0; + } + return 2; + } else { + //short filename + //copy name + for (i = 0; i < 8 && dir_entry->sfn.name[i]!= ' '; i++) { + dir->sname[i] = dir_entry->sfn.name[i]; + // NT-adaption for LaunchELF + if (dir_entry->sfn.reservedNT & 0x08 && + dir->sname[i] >= 'A' && dir->sname[i] <= 'Z') { + dir->sname[i] += 0x20; //Force standard letters in name to lower case + } + } + for (j=0; j < 3 && dir_entry->sfn.ext[j] != ' '; j++) { + if (j == 0) { + dir->sname[i] = '.'; + i++; + } + dir->sname[i+j] = dir_entry->sfn.ext[j]; + // NT-adaption for LaunchELF + if (dir_entry->sfn.reservedNT & 0x10 && + dir->sname[i+j] >= 'A' && dir->sname[i+j] <= 'Z') { + dir->sname[i+j] += 0x20; //Force standard letters in ext to lower case + } + } + dir->sname[i+j] = 0; //terminate + if (dir->name[0] == 0) { //long name desn't exit + for (i =0 ; dir->sname[i] !=0; i++) dir->name[i] = dir->sname[i]; + dir->name[i] = 0; + } + dir->attr = dir_entry->sfn.attr; + dir->size = getUI32(dir_entry->sfn.size); + dir->cluster = (fatType == FAT32) ? getUI32_2(dir_entry->sfn.clusterL, dir_entry->sfn.clusterH) : getUI16(dir_entry->sfn.clusterL); + + return 1; + } +} + +//--------------------------------------------------------------------------- +//Set chain info (cluster/offset) cache +void fat_setFatDirChain(fat_driver* fatd, fat_dir* fatDir) { + int i,j; + unsigned int index, clusterChainStart, fileCluster, fileSize, blockSize; + unsigned char nextChain; + int chainSize; + + XPRINTF("USBHDFSD: reading cluster chain \n"); + fileCluster = fatDir->chain[0].cluster; + + if (fileCluster < 2) { + XPRINTF("USBHDFSD: early exit... \n"); + return; + } + + fileSize = fatDir->size; + blockSize = fileSize / DIR_CHAIN_SIZE; + + nextChain = 1; + clusterChainStart = 0; + j = 1; + fileSize = 0; + index = 0; + + while (nextChain) { + if((chainSize = fat_getClusterChain(fatd, fileCluster, fatd->cbuf, MAX_DIR_CLUSTER, 1)) >=0){ + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + fileCluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + }else { //chain fits in the chain buffer completely - no next chain exist + nextChain = 0; + } + }else{ + XPRINTF("USBHDFSD: fat_setFatDirChain(): fat_getClusterChain() failed: %d\n", chainSize); + return; + } + + //process the cluster chain (fatd->cbuf) + for (i = clusterChainStart; i < chainSize; i++) { + fileSize += (fatd->partBpb.clusterSize * fatd->partBpb.sectorSize); + while (fileSize >= (j * blockSize) && j < DIR_CHAIN_SIZE) { + fatDir->chain[j].cluster = fatd->cbuf[i]; + fatDir->chain[j].index = index; + j++; + }//ends "while" + index++; + }//ends "for" + clusterChainStart = 1; + }//ends "while" + fatDir->lastCluster = fatd->cbuf[i-1]; + +#ifdef DEBUG_EXTREME //dlanor: I patched this because this bloat hid important stuff + //debug + XPRINTF("USBHDFSD: SEEK CLUSTER CHAIN CACHE fileSize=%u blockSize=%u \n", fatDir->size, blockSize); + for (i = 0; i < DIR_CHAIN_SIZE; i++) { + XPRINTF("USBHDFSD: index=%u cluster=%u offset= %u - %u start=%u \n", + fatDir->chain[i].index, fatDir->chain[i].cluster, + fatDir->chain[i].index * fatd->partBpb.clusterSize * fatd->partBpb.sectorSize, + (fatDir->chain[i].index+1) * fatd->partBpb.clusterSize * fatd->partBpb.sectorSize, + i * blockSize); + } +#endif /* debug */ + XPRINTF("USBHDFSD: read cluster chain done!\n"); +} + +//--------------------------------------------------------------------------- +/* Set base attributes of direntry */ +static void fat_setFatDir(fat_driver* fatd, fat_dir* fatDir, unsigned int parentDirCluster, fat_direntry_sfn* dsfn, fat_direntry_summary* dir, int getClusterInfo ) { + unsigned int i; + char* srcName; + + XPRINTF("USBHDFSD: setting fat dir...\n"); + srcName = dir->sname; + if (dir->name[0] != 0) { //long filename not empty + srcName = dir->name; + } + //copy name + for (i = 0; srcName[i] != 0; i++) fatDir->name[i] = srcName[i]; + fatDir->name[i] = 0; //terminate + + fatDir->attr = dir->attr; + fatDir->size = dir->size; + + //created Date: Day, Month, Year-low, Year-high + fatDir->cdate[0] = (dsfn->dateCreate[0] & 0x1F); + fatDir->cdate[1] = (dsfn->dateCreate[0] >> 5) + ((dsfn->dateCreate[1] & 0x01) << 3 ); + i = 1980 + (dsfn->dateCreate[1] >> 1); + fatDir->cdate[2] = (i & 0xFF); + fatDir->cdate[3] = ((i & 0xFF00)>> 8); + + //created Time: Hours, Minutes, Seconds + fatDir->ctime[0] = ((dsfn->timeCreate[1] & 0xF8) >> 3); + fatDir->ctime[1] = ((dsfn->timeCreate[1] & 0x07) << 3) + ((dsfn->timeCreate[0] & 0xE0) >> 5); + fatDir->ctime[2] = ((dsfn->timeCreate[0] & 0x1F) << 1); + + //accessed Date: Day, Month, Year-low, Year-high + fatDir->adate[0] = (dsfn->dateAccess[0] & 0x1F); + fatDir->adate[1] = (dsfn->dateAccess[0] >> 5) + ((dsfn->dateAccess[1] & 0x01) << 3 ); + i = 1980 + (dsfn->dateAccess[1] >> 1); + fatDir->adate[2] = (i & 0xFF); + fatDir->adate[3] = ((i & 0xFF00)>> 8); + + //modified Date: Day, Month, Year-low, Year-high + fatDir->mdate[0] = (dsfn->dateWrite[0] & 0x1F); + fatDir->mdate[1] = (dsfn->dateWrite[0] >> 5) + ((dsfn->dateWrite[1] & 0x01) << 3 ); + i = 1980 + (dsfn->dateWrite[1] >> 1); + fatDir->mdate[2] = (i & 0xFF); + fatDir->mdate[3] = ((i & 0xFF00)>> 8); + + //modified Time: Hours, Minutes, Seconds + fatDir->mtime[0] = ((dsfn->timeWrite[1] & 0xF8) >> 3); + fatDir->mtime[1] = ((dsfn->timeWrite[1] & 0x07) << 3) + ((dsfn->timeWrite[0] & 0xE0) >> 5); + fatDir->mtime[2] = ((dsfn->timeWrite[0] & 0x1F) << 1); + + fatDir->chain[0].cluster = dir->cluster; + fatDir->chain[0].index = 0; + if (getClusterInfo) { + fat_setFatDirChain(fatd, fatDir); + } + + fatDir->parentDirCluster = parentDirCluster; + fatDir->startCluster = dir->cluster; +} + +//--------------------------------------------------------------------------- +int fat_getDirentrySectorData(fat_driver* fatd, unsigned int* startCluster, unsigned int* startSector, unsigned int* dirSector) { + unsigned int chainSize; + + if (*startCluster == 0 && fatd->partBpb.fatType < FAT32) { //Root directory + *startSector = fatd->partBpb.rootDirStart; + *dirSector = fatd->partBpb.rootSize / (fatd->partBpb.sectorSize / 32); + return 0; + } + //other directory or fat 32 + if (*startCluster == 0 && fatd->partBpb.fatType == FAT32) { + *startCluster = fatd->partBpb.rootDirCluster; + } + *startSector = fat_cluster2sector(&fatd->partBpb, *startCluster); + chainSize = fat_getClusterChain(fatd, *startCluster, fatd->cbuf, MAX_DIR_CLUSTER, 1); + if (chainSize >= MAX_DIR_CLUSTER) { + XPRINTF("USBHDFSD: Chain too large\n"); + return -EFAULT; + } else if (chainSize > 0) { + *dirSector = chainSize * fatd->partBpb.clusterSize; + } else { + XPRINTF("USBHDFSD: Error getting cluster chain! startCluster=%u \n", *startCluster); + return -EFAULT; + } + + return chainSize; +} + +//--------------------------------------------------------------------------- +static int fat_getDirentryStartCluster(fat_driver* fatd, char* dirName, unsigned int* startCluster, fat_dir* fatDir) { + fat_direntry_summary dir; + unsigned int i, dirSector, startSector, dirPos; + unsigned char cont; + int ret; +#ifdef DEBUG + struct SBP2Device* mass_device = fatd->dev; +#endif + + cont = 1; + XPRINTF("USBHDFSD: getting cluster for dir entry: %s \n", dirName); + //clear name strings + dir.sname[0] = 0; + dir.name[0] = 0; + + ret = fat_getDirentrySectorData(fatd, startCluster, &startSector, &dirSector); + if (ret < 0) + return ret; + + XPRINTF("USBHDFSD: dirCluster=%u startSector=%u (%u) dirSector=%u \n", *startCluster, startSector, startSector * mass_device->sectorSize, dirSector); + + //go through first directory sector till the max number of directory sectors + //or stop when no more direntries detected + for (i = 0; i < dirSector && cont; i++) { + unsigned char* sbuf = NULL; //sector buffer + + //At cluster borders, get correct sector from cluster chain buffer + if ((*startCluster != 0) && (i % fatd->partBpb.clusterSize == 0)) { + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[(i / fatd->partBpb.clusterSize)]) -i; + } + + ret = READ_SECTOR(fatd->dev, startSector + i, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: read directory sector failed ! sector=%u\n", startSector + i); + return -EIO; + } + XPRINTF("USBHDFSD: read sector ok, scanning sector for direntries...\n"); + dirPos = 0; + + // go through start of the sector till the end of sector + while (cont && dirPos < fatd->partBpb.sectorSize) { + fat_direntry* dir_entry = (fat_direntry*) (sbuf + dirPos); + cont = fat_getDirentry(fatd->partBpb.fatType, dir_entry, &dir); //get single directory entry from sector buffer + if (cont == 1) { //when short file name entry detected + if (!(dir.attr & FAT_ATTR_VOLUME_LABEL)) { //not volume label + if ((strEqual(dir.sname, dirName) == 0) || + (strEqual(dir.name, dirName) == 0) ) { + XPRINTF("USBHDFSD: found! %s\n", dir.name); + if (fatDir != NULL) { //fill the directory properties + fat_setFatDir(fatd, fatDir, *startCluster, &dir_entry->sfn, &dir, 1); + } + *startCluster = dir.cluster; + XPRINTF("USBHDFSD: direntry %s found at cluster: %u \n", dirName, dir.cluster); + return dir.attr; //returns file or directory attr + } + }//ends "if(!(dir.attr & FAT_ATTR_VOLUME_LABEL))" + //clear name strings + dir.sname[0] = 0; + dir.name[0] = 0; + }//ends "if (cont == 1)" + dirPos += sizeof(fat_direntry); + }//ends "while" + }//ends "for" + XPRINTF("USBHDFSD: direntry %s not found! \n", dirName); + return -ENOENT; +} + +//--------------------------------------------------------------------------- +// start cluster should be 0 - if we want to search from root directory +// otherwise the start cluster should be correct cluster of directory +// to search directory - set fatDir as NULL +int fat_getFileStartCluster(fat_driver* fatd, const char* fname, unsigned int* startCluster, fat_dir* fatDir) { + char tmpName[FAT_MAX_NAME+1]; + unsigned int i, offset; + int ret; + + XPRINTF("USBHDFSD: Entering fat_getFileStartCluster\n"); + + offset = 0; + i=0; + + *startCluster = 0; + if (fatDir != NULL) { + memset(fatDir, 0, sizeof(fat_dir)); + fatDir->attr = FAT_ATTR_DIRECTORY; + } + if (fname[i] == '/') { + i++; + } + + for ( ; fname[i] !=0; i++) { + if (fname[i] == '/') { //directory separator + tmpName[offset] = 0; //terminate string + ret = fat_getDirentryStartCluster(fatd, tmpName, startCluster, fatDir); + if (ret < 0) { + return -ENOENT; + } + offset = 0; + } else{ + tmpName[offset] = fname[i]; + offset++; + } + }//ends "for" + //and the final file + tmpName[offset] = 0; //terminate string + XPRINTF("USBHDFSD: Ready to get cluster for file \"%s\"\n", tmpName); + if (fatDir != NULL) { + //if the last char of the name was slash - the name was already found -exit + if (offset == 0) { + XPRINTF("USBHDFSD: Exiting from fat_getFileStartCluster with a folder\n"); + return 2; + } + ret = fat_getDirentryStartCluster(fatd, tmpName, startCluster, fatDir); + if (ret < 0) { + XPRINTF("USBHDFSD: Exiting from fat_getFileStartCluster with error %i\n", ret); + return ret; + } + XPRINTF("USBHDFSD: file's startCluster found. Name=%s, cluster=%u \n", fname, *startCluster); + } + XPRINTF("USBHDFSD: Exiting from fat_getFileStartCluster with no error.\n"); + return 1; +} + +//--------------------------------------------------------------------------- +void fat_getClusterAtFilePos(fat_driver* fatd, fat_dir* fatDir, unsigned int filePos, unsigned int* cluster, unsigned int* clusterPos) { + unsigned int i, j, blockSize; + + blockSize = fatd->partBpb.clusterSize * fatd->partBpb.sectorSize; + + for (i = 0, j = (DIR_CHAIN_SIZE-1); i < (DIR_CHAIN_SIZE-1); i++) { + if (fatDir->chain[i].index * blockSize <= filePos && + fatDir->chain[i+1].index * blockSize > filePos) { + j = i; + break; + } + } + *cluster = fatDir->chain[j].cluster; + *clusterPos = (fatDir->chain[j].index * blockSize); +} + +//--------------------------------------------------------------------------- +int fat_readFile(fat_driver* fatd, fat_dir* fatDir, unsigned int filePos, unsigned char* buffer, unsigned int size) { + int ret, chainSize; + unsigned int i, j, startSector, clusterChainStart, bufSize, sectorSkip, clusterSkip, dataSkip; + unsigned char nextChain; + struct SBP2Device* mass_device = fatd->dev; + + unsigned int bufferPos, fileCluster, clusterPos; + + fat_getClusterAtFilePos(fatd, fatDir, filePos, &fileCluster, &clusterPos); + sectorSkip = (filePos - clusterPos) / fatd->partBpb.sectorSize; + clusterSkip = sectorSkip / fatd->partBpb.clusterSize; + sectorSkip %= fatd->partBpb.clusterSize; + dataSkip = filePos % fatd->partBpb.sectorSize; + bufferPos = 0; + + XPRINTF("USBHDFSD: fileCluster = %u, clusterPos= %u clusterSkip=%u, sectorSkip=%u dataSkip=%u \n", + fileCluster, clusterPos, clusterSkip, sectorSkip, dataSkip); + + if (fileCluster < 2) { + return 0; + } + + bufSize = mass_device->sectorSize; + nextChain = 1; + clusterChainStart = 1; + + while (nextChain && size > 0 ) { + if((chainSize = fat_getClusterChain(fatd, fileCluster, fatd->cbuf, MAX_DIR_CLUSTER, clusterChainStart))<0){ + return chainSize; + } + + clusterChainStart = 0; + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + fileCluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + }else { //chain fits in the chain buffer completely - no next chain needed + nextChain = 0; + } + while (clusterSkip >= MAX_DIR_CLUSTER) { + chainSize = fat_getClusterChain(fatd, fileCluster, fatd->cbuf, MAX_DIR_CLUSTER, clusterChainStart); + clusterChainStart = 0; + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + fileCluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + }else { //chain fits in the chain buffer completely - no next chain needed + nextChain = 0; + } + clusterSkip -= MAX_DIR_CLUSTER; + } + + //process the cluster chain (fatd->cbuf) and skip leading clusters if needed + for (i = 0 + clusterSkip; i < chainSize && size > 0; i++) { + //read cluster and save cluster content + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[i]); + //process all sectors of the cluster (and skip leading sectors if needed) + for (j = 0 + sectorSkip; j < fatd->partBpb.clusterSize && size > 0; j++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = READ_SECTOR(fatd->dev, startSector + j, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read sector failed ! sector=%u\n", startSector + j); + return bufferPos; + } + + //compute exact size of transfered bytes + if (size < bufSize) { + bufSize = size + dataSkip; + } + if (bufSize > mass_device->sectorSize) { + bufSize = mass_device->sectorSize; + } + XPRINTF("USBHDFSD: memcopy dst=%u, src=%u, size=%u bufSize=%u \n", bufferPos, dataSkip, bufSize-dataSkip, bufSize); + memcpy(buffer+bufferPos, sbuf + dataSkip, bufSize - dataSkip); + size-= (bufSize - dataSkip); + bufferPos += (bufSize - dataSkip); + dataSkip = 0; + bufSize = mass_device->sectorSize; + } + sectorSkip = 0; + } + clusterSkip = 0; + } + return bufferPos; +} + +//--------------------------------------------------------------------------- +int fat_getNextDirentry(fat_driver* fatd, fat_dir_list* fatdlist, fat_dir* fatDir) { + fat_direntry_summary dir; + int i, ret; + unsigned int startSector, dirSector, dirPos, dirCluster; + unsigned char cont, new_entry; +#ifdef DEBUG + struct SBP2Device* mass_device = fatd->dev; +#endif + + //the getFirst function was not called + if (fatdlist->direntryCluster == 0xFFFFFFFF || fatDir == NULL) { + return -EFAULT; + } + + dirCluster = fatdlist->direntryCluster; + + //clear name strings + dir.sname[0] = 0; + dir.name[0] = 0; + + ret = fat_getDirentrySectorData(fatd, &dirCluster, &startSector, &dirSector); + if (ret < 0) + return ret; + + XPRINTF("USBHDFSD: dirCluster=%u startSector=%u (%u) dirSector=%u \n", dirCluster, startSector, startSector * mass_device->sectorSize, dirSector); + + //go through first directory sector till the max number of directory sectors + //or stop when no more direntries detected + //dlanor: but avoid rescanning same areas redundantly (if possible) + cont = 1; + new_entry = 1; + dirPos = (fatdlist->direntryIndex*32) % fatd->partBpb.sectorSize; + for (i = ((fatdlist->direntryIndex*32) / fatd->partBpb.sectorSize); (i < dirSector) && cont; i++) { + unsigned char* sbuf = NULL; //sector buffer + + //At cluster borders, get correct sector from cluster chain buffer + if ((dirCluster != 0) && (new_entry || (i % fatd->partBpb.clusterSize == 0))) { + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[(i / fatd->partBpb.clusterSize)]) + -i + (i % fatd->partBpb.clusterSize); + new_entry = 0; + } + ret = READ_SECTOR(fatd->dev, startSector + i, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read directory sector failed ! sector=%u\n", startSector + i); + return -EIO; + } + + // go through sector from current pos till its end + while (cont && (dirPos < fatd->partBpb.sectorSize)) { + fat_direntry* dir_entry = (fat_direntry*) (sbuf + dirPos); + cont = fat_getDirentry(fatd->partBpb.fatType, dir_entry, &dir); //get a directory entry from sector + fatdlist->direntryIndex++; //Note current entry processed + if (cont == 1) { //when short file name entry detected + fat_setFatDir(fatd, fatDir, dirCluster, &dir_entry->sfn, &dir, 0); +#if 0 + XPRINTF("USBHDFSD: fat_getNextDirentry %c%c%c%c%c%c %x %s %s\n", + (dir.attr & FAT_ATTR_VOLUME_LABEL) ? 'v' : '-', + (dir.attr & FAT_ATTR_DIRECTORY) ? 'd' : '-', + (dir.attr & FAT_ATTR_READONLY) ? 'r' : '-', + (dir.attr & FAT_ATTR_ARCHIVE) ? 'a' : '-', + (dir.attr & FAT_ATTR_SYSTEM) ? 's' : '-', + (dir.attr & FAT_ATTR_HIDDEN) ? 'h' : '-', + dir.attr, + dir.sname, + dir.name); +#endif + return 1; + } + dirPos += sizeof(fat_direntry); + }//ends "while" + dirPos = 0; + }//ends "for" + // when we get this far - reset the direntry cluster + fatdlist->direntryCluster = 0xFFFFFFFF; //no more files + return 0; //indicate that no direntry is avalable +} + +//--------------------------------------------------------------------------- +int fat_getFirstDirentry(fat_driver* fatd, const char* dirName, fat_dir_list* fatdlist, fat_dir *fatDir_host, fat_dir* fatDir) { + int ret; + unsigned int startCluster = 0; + + ret = fat_getFileStartCluster(fatd, dirName, &startCluster, fatDir_host); + if (ret < 0) { //dir name not found + return -ENOENT; + } + //check that direntry is directory + if (!(fatDir_host->attr & FAT_ATTR_DIRECTORY)) { + return -ENOTDIR; //it's a file - exit + } + fatdlist->direntryCluster = startCluster; + fatdlist->direntryIndex = 0; + return fat_getNextDirentry(fatd, fatdlist, fatDir); +} + +//--------------------------------------------------------------------------- +int fat_mount(struct SBP2Device* dev, unsigned int start, unsigned int count) +{ + fat_driver* fatd = NULL; + unsigned int i; + for (i = 0; i < NUM_DRIVES && fatd == NULL; ++i) + { + if (g_fatd[i] == NULL) + { + XPRINTF("USBHDFSD: usb fat: allocate fat_driver %d!\n", sizeof(fat_driver)); + g_fatd[i] = malloc(sizeof(fat_driver)); + if (g_fatd[i] != NULL) + { + g_fatd[i]->dev = NULL; + } + fatd = g_fatd[i]; + } + else if(g_fatd[i]->dev == NULL) + { + fatd = g_fatd[i]; + } + } + + if (fatd == NULL) + { + printf("USBHDFSD: usb fat: unable to allocate drive!\n"); + return -1; + } + + if (fatd->dev != NULL) + { + printf("USBHDFSD: usb fat: mount ERROR: alread mounted\n"); + fat_forceUnmount(fatd->dev); + } + + if (fat_getPartitionBootSector(dev, start, &fatd->partBpb) < 0) + return -1; + + fatd->dev = dev; + fatd->deIdx = 0; + fatd->clStackIndex = 0; + fatd->clStackLast = 0; + fatd->lastChainCluster = 0xFFFFFFFF; + fatd->lastChainResult = -1; + return 0; +} + +//--------------------------------------------------------------------------- +void fat_forceUnmount(struct SBP2Device* dev) +{ + unsigned int i; + XPRINTF("USBHDFSD: usb fat: forceUnmount devId %i \n", dev->nodeID); + + for (i = 0; i < NUM_DRIVES; ++i) + { + if (g_fatd[i] != NULL && g_fatd[i]->dev == dev) + g_fatd[i] = NULL; + } +} + +//--------------------------------------------------------------------------- +fat_driver * fat_getData(int device) +{ + if (device >= NUM_DRIVES) + return NULL; + + if (g_fatd[device] == NULL || g_fatd[device]->dev == NULL) + return NULL; + else + return g_fatd[device]; +} + +//--------------------------------------------------------------------------- +//End of file: fat_driver.c +//--------------------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/fat_write.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/fat_write.c new file mode 100644 index 0000000..c71eb0d --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/fat_write.c @@ -0,0 +1,2209 @@ +//--------------------------------------------------------------------------- +//File name: fat_write.c +//--------------------------------------------------------------------------- +/* + * fat_driver.c - USB Mass storage driver for PS2 + * + * (C) 2005, Marek Olejnik (ole00@post.cz) + * + * FAT filesystem layer - write functions + * + * See the file LICENSE included with this distribution for licensing terms. + */ +//--------------------------------------------------------------------------- +#include +#include + +#ifdef WIN32 +#include +#include +#include +#include +#else +#include +#include +#endif + +#include +#include "usbhd_common.h" +#include "fat_driver.h" +#include "fat.h" +#include "scache.h" +#include "sbp2_disk.h" + +//#define DEBUG //comment out this line when not debugging + +#include "mass_debug.h" + +#define DATE_CREATE 1 +#define DATE_MODIFY 2 + +#define READ_SECTOR(d, a, b) scache_readSector((d)->cache, (a), (void **)&b) +#define ALLOC_SECTOR(d, a, b) scache_allocSector((d)->cache, (a), (void **)&b) +#define WRITE_SECTOR(d, a) scache_writeSector((d)->cache, (a)) +#define FLUSH_SECTORS(d) scache_flushSectors((d)->cache) + +//--------------------------------------------------------------------------- +/* + reorder (swap) the cluster stack records +*/ +static void swapClStack(fat_driver* fatd, int startIndex, int endIndex) { + int i; + int size; + int offset1, offset2; + unsigned int tmp; + + size = endIndex-startIndex; + if (size < 2) { + return; + } + + size/=2; + for (i = 0; i < size; i++) { + offset1 = startIndex + i; + offset2 = endIndex - 1 - i; + tmp = fatd->clStack[offset1]; + fatd->clStack[offset1] = fatd->clStack[offset2]; + fatd->clStack[offset2] = tmp; + } +} + +//--------------------------------------------------------------------------- +/* + scan FAT12 for free clusters and store them to the cluster stack +*/ + +static int fat_readEmptyClusters12(fat_driver* fatd) { + int ret; + int recordOffset; + int sectorSpan; + int fatSector; + int lastFatSector; + unsigned int cluster; + unsigned int clusterValue; + unsigned char xbuf[4]; + int oldClStackIndex; + unsigned char* sbuf = NULL; //sector buffer + + oldClStackIndex = fatd->clStackIndex; + + lastFatSector = -1; + cluster = fatd->clStackLast; + + while(fatd->clStackIndex < MAX_CLUSTER_STACK ) { + recordOffset = (cluster * 3) / 2; //offset of the cluster record (in bytes) from the FAT start + fatSector = recordOffset / fatd->partBpb.sectorSize; + sectorSpan = 0; + if ((recordOffset % fatd->partBpb.sectorSize) == (fatd->partBpb.sectorSize - 1)) { + sectorSpan = 1; + } + if (lastFatSector != fatSector || sectorSpan) { + ret = READ_SECTOR(fatd->dev, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat12 sector failed! sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector ); + return -EIO; + } + lastFatSector = fatSector; + + if (sectorSpan) { + xbuf[0] = sbuf[fatd->partBpb.sectorSize - 2]; + xbuf[1] = sbuf[fatd->partBpb.sectorSize - 1]; + ret = READ_SECTOR(fatd->dev, fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector + 1, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat12 sector failed sector=%u! \n", fatd->partBpb.partStart + fatd->partBpb.resSectors + fatSector + 1); + return -EIO; + } + xbuf[2] = sbuf[0]; + xbuf[3] = sbuf[1]; + } + } + if (sectorSpan) { // use xbuf as source buffer + clusterValue = fat_getClusterRecord12(xbuf + (recordOffset % fatd->partBpb.sectorSize) - (fatd->partBpb.sectorSize-2), cluster % 2); + } else { // use sector buffer as source buffer + clusterValue = fat_getClusterRecord12(sbuf + (recordOffset % fatd->partBpb.sectorSize), cluster % 2); + } + if (clusterValue == 0) { + fatd->clStackLast = cluster; + fatd->clStack[fatd->clStackIndex] = cluster; + fatd->clStackIndex++; + + } + cluster++; //read next cluster record in the sequence + } + //the stack operates as LIFO but we put in the clusters as FIFO + //we should reverse the cluster order - not necessary + //but it will retain the natural (increasing) order of + //the cluster chain + swapClStack(fatd, oldClStackIndex, fatd->clStackIndex); + return fatd->clStackIndex; +} + + +//--------------------------------------------------------------------------- +/* + scan FAT32 for free clusters and store them to the cluster stack +*/ +static int fat_readEmptyClusters32(fat_driver* fatd) { + unsigned int i,j; + int ret; + unsigned int indexCount; + unsigned int fatStartSector; + unsigned int cluster; + unsigned int clusterValue; + int oldClStackIndex; + int sectorSkip; + int recordSkip; + + oldClStackIndex = fatd->clStackIndex; + + //indexCount = numer of cluster indices per sector + indexCount = fatd->partBpb.sectorSize / 4; //FAT16->2, FAT32->4 + //skip areas we have already searched through + sectorSkip = fatd->clStackLast / indexCount; + recordSkip = fatd->clStackLast % indexCount; + + fatStartSector = fatd->partBpb.partStart + fatd->partBpb.resSectors; + + for (i = sectorSkip; i < fatd->partBpb.fatSize && fatd->clStackIndex < MAX_CLUSTER_STACK ; i++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = READ_SECTOR(fatd->dev, fatStartSector + i, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat32 sector failed! sector=%u! \n", fatStartSector + i); + return -EIO; + } + for (j = recordSkip; j < indexCount && fatd->clStackIndex < MAX_CLUSTER_STACK ; j++) { + cluster = getUI32(sbuf + (j * 4)); + if (cluster == 0) { //the cluster is free + clusterValue = (i * indexCount) + j; + if (clusterValue < 0xFFFFFF7) { + fatd->clStackLast = clusterValue; + fatd->clStack[fatd->clStackIndex] = clusterValue; + fatd->clStackIndex++; + } + } + } + recordSkip = 0; + } + //the stack operates as LIFO but we put in the clusters as FIFO + //we should reverse the cluster order - not necessary + //but it will retain the natural (increasing) order of + //the cluster chain + swapClStack(fatd, oldClStackIndex, fatd->clStackIndex); + return fatd->clStackIndex; +} + +//--------------------------------------------------------------------------- +/* + scan FAT16 for free clusters and store them to the cluster stack +*/ +static int fat_readEmptyClusters16(fat_driver* fatd) { + unsigned int i,j; + int ret; + unsigned int indexCount; + unsigned int fatStartSector; + unsigned int cluster; + int oldClStackIndex; + int sectorSkip; + int recordSkip; + + oldClStackIndex = fatd->clStackIndex; + //XPRINTF("USBHDFSD: #### Read empty clusters16: clStackIndex=%d MAX=%d\n", clStackIndex, MAX_CLUSTER_STACK); + + //indexCount = numer of cluster indices per sector + indexCount = fatd->partBpb.sectorSize / 2; //FAT16->2, FAT32->4 + + //skip areas we have already searched through + sectorSkip = fatd->clStackLast / indexCount; + recordSkip = fatd->clStackLast % indexCount; + + fatStartSector = fatd->partBpb.partStart + fatd->partBpb.resSectors; + + for (i = sectorSkip; i < fatd->partBpb.fatSize && fatd->clStackIndex < MAX_CLUSTER_STACK ; i++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = READ_SECTOR(fatd->dev, fatStartSector + i, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat16 sector failed! sector=%u! \n", fatStartSector + i); + return -EIO; + } + for (j = recordSkip; j < indexCount && fatd->clStackIndex < MAX_CLUSTER_STACK ; j++) { + cluster = getUI16(sbuf + (j * 2)); + if (cluster == 0) { //the cluster is free + fatd->clStackLast = (i * indexCount) + j; + fatd->clStack[fatd->clStackIndex] = fatd->clStackLast; + XPRINTF("USBHDFSD: %u ", fatd->clStack[fatd->clStackIndex]); + fatd->clStackIndex++; + } + } + recordSkip = 0; + } + XPRINTF("USBHDFSD: \n"); + //the stack operates as LIFO but we put in the clusters as FIFO + //we should reverse the cluster order - not necessary + //but it will retain the natural (increasing) order of + //the cluster chain + swapClStack(fatd, oldClStackIndex, fatd->clStackIndex); + return fatd->clStackIndex; +} + +//--------------------------------------------------------------------------- +/* + scan FAT for free clusters and store them to the cluster stack +*/ +static int fat_readEmptyClusters(fat_driver* fatd) { + switch (fatd->partBpb.fatType) + { + case FAT12: return fat_readEmptyClusters12(fatd); + case FAT16: return fat_readEmptyClusters16(fatd); + case FAT32: return fat_readEmptyClusters32(fatd); + } + + return(-1); +} + + +//--------------------------------------------------------------------------- +/* + set sinlge cluster record (FAT12)into buffer + + 0x321, 0xABC + + byte0|byte1|byte2| + +--+--+--+--+--+--+ + |2 |1 |C |3 |A |B | + +--+--+--+--+--+--+ + +*/ +static void fat_setClusterRecord12(unsigned char* buf, unsigned int cluster, int type) { + + if (type) { //type 1 + buf[0] = (buf[0] & 0x0F) + ((cluster & 0x0F)<<4) ; + buf[1] = (cluster & 0xFF0) >> 4; + } else { // type 0 + buf[0] = (cluster & 0xFF); + buf[1] = (buf[1] & 0xF0) + ((cluster & 0xF00) >> 8); + } + +} + +//--------------------------------------------------------------------------- +static void fat_setClusterRecord12part1(unsigned char* buf, unsigned int cluster, int type) { + if (type) { //type 1 + buf[0] = (buf[0] & 0x0F) + ((cluster & 0x0F)<<4); + } else { // type 0 + buf[0] = (cluster & 0xFF); + } +} + +//--------------------------------------------------------------------------- +static void fat_setClusterRecord12part2(unsigned char* buf, unsigned int cluster, int type) { + if (type) { //type 1 + buf[0] = (cluster & 0xFF0) >> 4; + } else { // type 0 + buf[0] = (buf[0] & 0xF0) + ((cluster & 0xF00) >> 8); + } +} + +//--------------------------------------------------------------------------- +/* + save value at the cluster record in FAT 12 +*/ +static int fat_saveClusterRecord12(fat_driver* fatd, unsigned int currentCluster, unsigned int value) +{ + int ret; + int sectorSpan; + int recordOffset; + int recordType; + int fatNumber; + unsigned int fatSector; + + ret = -1; + //recordOffset is byte offset of the record from the start of the fat table + recordOffset = (currentCluster * 3) / 2; + + //save both fat tables + for (fatNumber = 0; fatNumber < fatd->partBpb.fatCount; fatNumber++) { + unsigned char* sbuf = NULL; //sector buffer + + fatSector = fatd->partBpb.partStart + fatd->partBpb.resSectors + (fatNumber * fatd->partBpb.fatSize); + fatSector += recordOffset / fatd->partBpb.sectorSize; + sectorSpan = fatd->partBpb.sectorSize - (recordOffset % fatd->partBpb.sectorSize); + if (sectorSpan > 1) { + sectorSpan = 0; + } + recordType = currentCluster % 2; + + ret = READ_SECTOR(fatd->dev, fatSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat16 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + if (!sectorSpan) { // not sector span - the record is copmact and fits in single sector + fat_setClusterRecord12(sbuf + (recordOffset % fatd->partBpb.sectorSize), value, recordType); + ret = WRITE_SECTOR(fatd->dev, fatSector); + if (ret < 0) { + XPRINTF("USBHDFSD: Write fat12 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + } else { // sector span - the record is broken in 2 pieces - each one on different sector + //modify one last byte of the sector buffer + fat_setClusterRecord12part1(sbuf + (recordOffset % fatd->partBpb.sectorSize), value, recordType); + //save current sector + ret = WRITE_SECTOR(fatd->dev, fatSector); + if (ret < 0) { + XPRINTF("USBHDFSD: Write fat12 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + //read next sector from the fat + fatSector++; + ret = READ_SECTOR(fatd->dev, fatSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat16 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + //modify first byte of the sector buffer + fat_setClusterRecord12part2(sbuf, value, recordType); + //save current sector + ret = WRITE_SECTOR(fatd->dev, fatSector); + if (ret < 0) { + XPRINTF("USBHDFSD: Write fat12 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + } + } //end for + return ret; +} + +//--------------------------------------------------------------------------- +/* + save value at the cluster record in FAT 32 +*/ +static int fat_saveClusterRecord16(fat_driver* fatd, unsigned int currentCluster, unsigned int value) { + int i; + int ret; + int indexCount; + int fatNumber; + unsigned int fatSector; + + ret = -1; + //indexCount is numer of cluster indices per sector + indexCount = fatd->partBpb.sectorSize / 2; //FAT16->2, FAT32->4 + + //save both fat tables + for (fatNumber = 0; fatNumber < fatd->partBpb.fatCount; fatNumber++) { + unsigned char* sbuf = NULL; //sector buffer + + fatSector = fatd->partBpb.partStart + fatd->partBpb.resSectors + (fatNumber * fatd->partBpb.fatSize); + fatSector += currentCluster / indexCount; + + ret = READ_SECTOR(fatd->dev, fatSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat16 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + i = currentCluster % indexCount; + i*=2; //fat16 + sbuf[i++] = value & 0xFF; + sbuf[i] = ((value & 0xFF00) >> 8); + ret = WRITE_SECTOR(fatd->dev, fatSector); + if (ret < 0) { + XPRINTF("USBHDFSD: Write fat16 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + } + return ret; +} + +//--------------------------------------------------------------------------- +/* + save value at the cluster record in FAT 16 +*/ +static int fat_saveClusterRecord32(fat_driver* fatd, unsigned int currentCluster, unsigned int value) { + int i; + int ret; + int indexCount; + int fatNumber; + unsigned int fatSector; + + ret = -1; + //indexCount is numer of cluster indices per sector + indexCount = fatd->partBpb.sectorSize / 4; //FAT16->2, FAT32->4 + + //save both fat tables + for (fatNumber = 0; fatNumber < fatd->partBpb.fatCount; fatNumber++) { + unsigned char* sbuf = NULL; //sector buffer + + fatSector = fatd->partBpb.partStart + fatd->partBpb.resSectors + (fatNumber * fatd->partBpb.fatSize); + fatSector += currentCluster / indexCount; + + ret = READ_SECTOR(fatd->dev, fatSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read fat32 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + i = currentCluster % indexCount; + i*=4; //fat32 + sbuf[i++] = value & 0xFF; + sbuf[i++] = ((value & 0xFF00) >> 8); + sbuf[i++] = ((value & 0xFF0000) >> 16); + sbuf[i] = (sbuf[i] &0xF0) + ((value >> 24) & 0x0F); //preserve the highest nibble intact + + ret = WRITE_SECTOR(fatd->dev, fatSector); + if (ret < 0) { + XPRINTF("USBHDFSD: Write fat32 sector failed! sector=%u! \n", fatSector); + return -EIO; + } + } + return ret; +} + + +//--------------------------------------------------------------------------- +/* + Append (and write) cluster chain to the FAT table. + + currentCluster - current end cluster record. + endCluster - new end cluster record. + + Note: there is no checking wether the currentCluster holds the EOF marker! + + Example + current FAT: + + index 09 10 11 12 + +-----+-----+-----+-----+ + value + 10 | EOF | 0 | 0 | + +-----+-----+-----+-----+ + + + currentcluster = 10, endcluster = 12 + updated FAT (after the function ends): + + index 09 10 11 12 + +-----+-----+-----+-----+ + value + 10 | 12 | 0 | EOF | + +-----+-----+-----+-----+ + +*/ +//--------------------------------------------------------------------------- +static int fat_appendClusterChain(fat_driver* fatd, unsigned int currentCluster, unsigned int endCluster) { + int ret; + ret = -1; + switch (fatd->partBpb.fatType) { + case FAT12: + ret = fat_saveClusterRecord12(fatd, currentCluster, endCluster); + if (ret < 0) return ret; + ret = fat_saveClusterRecord12(fatd, endCluster, 0xFFF); + break; + + case FAT16: + XPRINTF("USBHDFSD: I: appending cluster chain : current=%u end=%u \n", currentCluster, endCluster); + ret = fat_saveClusterRecord16(fatd, currentCluster, endCluster); + if (ret < 0) return ret; + ret = fat_saveClusterRecord16(fatd, endCluster, 0xFFFF); + break; + + case FAT32: + ret = fat_saveClusterRecord32(fatd, currentCluster, endCluster); + if (ret < 0) return ret; + ret = fat_saveClusterRecord32(fatd, endCluster, 0xFFFFFFF); + break; + } + return ret; +} + +//--------------------------------------------------------------------------- +/* + create new cluster chain (of size 1 cluster) at the cluster index +*/ +static int fat_createClusterChain(fat_driver* fatd, unsigned int cluster) { + switch (fatd->partBpb.fatType) { + case FAT12: return fat_saveClusterRecord12(fatd, cluster, 0xFFF); + case FAT16: return fat_saveClusterRecord16(fatd, cluster, 0xFFFF); + case FAT32: return fat_saveClusterRecord32(fatd, cluster, 0xFFFFFFF); + } + return -EFAULT; +} + +//--------------------------------------------------------------------------- +/* + modify the cluster (in FAT table) at the cluster index +*/ +static int fat_modifyClusterChain(fat_driver* fatd, unsigned int cluster, unsigned int value) { + switch (fatd->partBpb.fatType) { + case FAT12: return fat_saveClusterRecord12(fatd, cluster, value); + case FAT16: return fat_saveClusterRecord16(fatd, cluster, value); + case FAT32: return fat_saveClusterRecord32(fatd, cluster, value); + } + return -EFAULT; +} + +//--------------------------------------------------------------------------- +/* + delete cluster chain starting at cluster +*/ +static int fat_deleteClusterChain(fat_driver* fatd, unsigned int cluster) { + int ret; + int size; + int cont; + int end; + int i; + + if (cluster < 2) { + return -EFAULT; + } + XPRINTF("USBHDFSD: I: delete cluster chain starting at cluster=%u\n", cluster); + + cont = 1; + + while (cont) { + size = fat_getClusterChain(fatd, cluster, fatd->cbuf, MAX_DIR_CLUSTER, 1); + + end = size-1; //do not delete last cluster in the chain buffer + + for (i = 0 ; i < end; i++) { + ret = fat_modifyClusterChain(fatd, fatd->cbuf[i], 0); + if (ret < 0) { + return ret; + } + } + //the cluster chain continues + if (size == MAX_DIR_CLUSTER) { + cluster = fatd->cbuf[end]; + } else { + //no more cluster entries - delete the last cluster entry + ret = fat_modifyClusterChain(fatd, fatd->cbuf[end], 0); + if (ret < 0) { + return ret; + } + cont = 0; + } + fat_invalidateLastChainResult(fatd); //prevent to misuse current (now deleted) fatd->cbuf + } + return 1; +} + +//--------------------------------------------------------------------------- +/* + Get single empty cluster from the clusterStack (cS is small cache of free clusters) + Passed currentCluster is updated in the FAT and the new returned cluster index is + appended at the end of fat chain! +*/ +static unsigned int fat_getFreeCluster(fat_driver* fatd, unsigned int currentCluster) { + + int ret; + unsigned int result; + + //cluster stack is empty - find and fill the cS + if (fatd->clStackIndex <= 0) { + fatd->clStackIndex = 0; + ret = fat_readEmptyClusters(fatd); + if (ret <= 0) return 0; + fatd->clStackIndex = ret; + + } + //pop from cluster stack + fatd->clStackIndex--; + result = fatd->clStack[fatd->clStackIndex]; + //append the cluster chain + if (currentCluster) { + ret = fat_appendClusterChain(fatd, currentCluster, result); + } else { //create new cluster chain + ret = fat_createClusterChain(fatd, result); + } + if (ret < 0) return 0; + return result; +} + +//--------------------------------------------------------------------------- +/* +returns number of direntry positions that the name takes +//dlanor: Note that this only includes the long_name entries +*/ +static int getDirentrySize(const char* lname) { + int len; + int result; + len = strlen(lname); + result = len / 13; + if (len % 13 > 0) result++; + return result; +} + +//--------------------------------------------------------------------------- +/* +compute checksum of the short filename +*/ +static unsigned char computeNameChecksum(const char* sname) { + unsigned char result; + int i; + + result = 0; + for (i = 0; i < 11; i++) { + result = (0x80 * (0x01 & result)) + (result >> 1); //ROR 1 + result += sname[i]; + } + return result; +} + +//--------------------------------------------------------------------------- +/* + fill the LFN (long filename) direntry +*/ +static void setLfnEntry(const char* lname, int nameSize, unsigned char chsum, fat_direntry_lfn* dlfn, int part, int maxPart){ + int i,j; + unsigned char name[26]; //unicode name buffer = 13 characters per 2 bytes + int nameStart; + + nameStart = 13 * (part - 1); + j = nameSize - nameStart; + if (j > 13) { + j = 13; + } + + //fake unicode conversion + for (i = 0; i < j; i++) { + name[i*2] = (unsigned char)lname[nameStart + i]; + name[i*2+1] = 0; + } + + //rest of the name is zero terminated and padded with 0xFF + for (i = j; i < 13; i++) { + if (i == j) { + name[i*2] = 0; + name[i*2+1] = 0; + } else { + name[i*2] = 0xFF; + name[i*2+1] = 0xFF; + } + } + + dlfn->entrySeq = part; + if (maxPart == part) + dlfn->entrySeq |= 0x40; + dlfn->checksum = chsum; + //1st part of the name + for (i = 0; i < 10; i++) dlfn->name1[i] = name[i]; + //2nd part of the name + for (i = 0; i < 12; i++) dlfn->name2[i] = name[i+10]; + //3rd part of the name + for (i = 0; i < 4; i++) dlfn->name3[i] = name[i+22]; + dlfn->rshv = 0x0f; + dlfn->reserved1 = 0; + dlfn->reserved2[0] = 0; + dlfn->reserved2[1] = 0; +} + +//--------------------------------------------------------------------------- +/* + update the SFN (long filename) direntry - DATE and TIME +*/ +static void setSfnDate(fat_direntry_sfn* dsfn, int mode) { + int year, month, day, hour, minute, sec; + unsigned char tmpClk[4]; + +#ifdef WIN32 + year = 0; + month = 0; + day = 0; + hour = 0; + minute = 0; + sec = 0; +#else + //ps2 specific routine to get time and date + sceCdCLOCK cdtime; + + if(sceCdReadClock(&cdtime)!=0 && cdtime.stat==0) + { + sec = btoi(cdtime.second); + minute = btoi(cdtime.minute); + hour = btoi(cdtime.hour); + day = btoi(cdtime.day); + month = btoi(cdtime.month & 0x7F); //Ignore century bit (when an old CDVDMAN is used). + year = btoi(cdtime.year) + 2000; + } else { + year = 2005; month = 1; day = 6; + hour = 14; minute = 12; sec = 10; + } +#endif + + if (dsfn == NULL || mode == 0) { + return; + } + + tmpClk[0] = (sec / 2) & 0x1F; //seconds + tmpClk[0] += (minute & 0x07) << 5; // minute + tmpClk[1] = (minute & 0x38) >> 3; // minute + tmpClk[1] += (hour & 0x1F) << 3; // hour + + tmpClk[2] = (day & 0x1F); //day + tmpClk[2] += (month & 0x07) << 5; // month + tmpClk[3] = (month & 0x08) >> 3; // month + tmpClk[3] += ((year-1980) & 0x7F) << 1; //year + + XPRINTF("USBHDFSD: year=%d, month=%d, day=%d h=%d m=%d s=%d \n", year, month, day, hour, minute, sec); + //set date & time of creation + if (mode & DATE_CREATE) { + dsfn->timeCreate[0] = tmpClk[0]; + dsfn->timeCreate[1] = tmpClk[1]; + dsfn->dateCreate[0] = tmpClk[2]; + dsfn->dateCreate[1] = tmpClk[3]; + dsfn->dateAccess[0] = tmpClk[2]; + dsfn->dateAccess[1] = tmpClk[3]; + } + //set date & time of modification + if (mode & DATE_MODIFY) { + dsfn->timeWrite[0] = tmpClk[0]; + dsfn->timeWrite[1] = tmpClk[1]; + dsfn->dateWrite[0] = tmpClk[2]; + dsfn->dateWrite[1] = tmpClk[3]; + } +} + +//--------------------------------------------------------------------------- +/* + fill the SFN (short filename) direntry +*/ +static void setSfnEntry(const char* shortName, char directory, fat_direntry_sfn* dsfn, unsigned int cluster) { + int i; + + //name + ext + for (i = 0; i < 8; i++) dsfn->name[i] = shortName[i]; + for (i = 0; i < 3; i++) dsfn->ext[i] = shortName[i+8]; + + if (directory > 0) { + dsfn->attr = FAT_ATTR_DIRECTORY; + } else { + dsfn->attr = FAT_ATTR_ARCHIVE; + } + dsfn->reservedNT = 0; + dsfn->clusterH[0] = (cluster & 0xFF0000) >> 16; + dsfn->clusterH[1] = (cluster & 0xFF000000) >> 24; + dsfn->clusterL[0] = (cluster & 0x00FF); + dsfn->clusterL[1] = (cluster & 0xFF00) >> 8; + + //size is zero - because we don't know the filesize yet + for (i = 0; i < 4; i++) dsfn->size[i] = 0; + + setSfnDate(dsfn, DATE_CREATE | DATE_MODIFY); +} + +static void setSfnEntryFromOld(const char* shortName, fat_direntry_sfn* dsfn, const fat_direntry_sfn* orig_dsfn) { + int i; + + memcpy(dsfn, orig_dsfn, sizeof(fat_direntry_sfn)); + + //name + ext + for (i = 0; i < 8; i++) dsfn->name[i] = shortName[i]; + for (i = 0; i < 3; i++) dsfn->ext[i] = shortName[i+8]; +} + +//--------------------------------------------------------------------------- +/* + Create short name by squeezing long name into the 8.3 name boundaries + lname - existing long name + sname - buffer where to store short name + + returns: 0 if longname completely fits into the 8.3 boundaries + 1 if long name have to be truncated (ie. INFORM~1.TXT) + <0 if invalid long name detected +*/ +static int createShortNameMask(char* lname, char* sname) { + int i; + int size; + int j; + int fit; + + if( (lname[0] == '.') + &&( (lname[1] == 0) + ||( (lname[1] == '.') + &&(lname[2] == 0)) + ) + ) + { + return -EINVAL; + } + + fit = 0; + //clean short name by putting space + for (i = 0; i < 11; i++) sname[i] = ' '; + XPRINTF("USBHDFSD: Clear short name ='%s'\n", sname); + + //detect number of dots and space characters in the long name + j = 0; + for (i = 0; lname[i] != 0; i++) { + if (lname[i] == '.') j++; else + if (lname[i] == ' ' ) j+=2; + } + //long name contains no dot or one dot and no space char + if (j <= 1) fit++; + //XPRINTF("USBHDFSD: fit1=%d j=%d\n", fit, j); + + //store name + for (i = 0; lname[i] !=0 && lname[i] != '.' && i < 8; i++) { + sname[i] = toupper(lname[i]); + //short name must not contain spaces - replace space by underscore + if (sname[i] == ' ') sname[i]='_'; + } + //check wether last char is '.' and the name is shorter than 8 + if (lname[i] == '.' || lname[i] == 0) { + fit++; + } + //XPRINTF("USBHDFSD: fit2=%d\n", fit); + + //find the last dot "." - filename extension + size = strlen(lname); + size--; + + for (i = size; i > 0 && lname[i] !='.'; i--); + if (lname[i] == '.') { + i++; + for (j=0; lname[i] != 0 && j < 3; i++, j++) { + sname[j+8] = toupper(lname[i]); + } + //no more than 3 characters of the extension + if (lname[i] == 0) fit++; + } else { + //no dot detected in the long filename + fit++; + } +// XPRINTF("USBHDFSD: fit3=%d\n", fit); +// XPRINTF("USBHDFSD: Long name=%s Short name=%s \n", lname, sname); + + //all 3 checks passed - the long name fits in the short name without restrictions + if (fit == 3) { + XPRINTF("USBHDFSD: Short name is loseles!\n"); + return 0; + } + + //one of the check failed - the short name have to be 'sequenced' + //do not allow spaces in the short name + for (i = 0; i < 8;i++) { + if (sname[i] == ' ') sname[i] = '_'; + } + return 1; +} + +//--------------------------------------------------------------------------- +/* + separate path and filename + fname - the source (merged) string (input) + path - separated path (output) + name - separated filename (output) +*/ +static int separatePathAndName(const char* fname, char* path, char* name) { + int path_len; + const char *np; + char *sp; + + if(!(sp=strrchr(fname, '/'))) //if last path separator missing ? + np = fname; // name starts at start of fname string + else //else last path separator found + np = sp+1; // name starts after separator + if(strlen(np) >= FAT_MAX_NAME) //if name is too long + return -ENAMETOOLONG; // return error code + strcpy(name, np); //copy name from correct part of fname string + if((path_len = (np - fname)) >= FAT_MAX_PATH) //if path is too long + return -ENAMETOOLONG; // return error code + strncpy(path, fname, path_len); //copy path from start of fname string + path[path_len] = 0; //terminate path + return 1; +} + +//--------------------------------------------------------------------------- +/* + get the sequence number from existing direntry name +*/ +static int getShortNameSequence(char* name, char* ext, const char* sname) { + int i,j; + const char* tmp; + char buf[8]; + + //at first: compare extensions + //if extensions differ then filenames are diffrerent and seq is 0 + tmp = sname+8; + for (i = 0; i < 3; i++) { + if (ext[i] != tmp[i]) return 0; + } + + //at second: find tilde '~' character (search backward from the end) + for (i = 7; i > 0 && name[i] !='~'; i--); + + if (i == 0) return 0; // tilde char was not found or is at first character + + //now compare the names - up to '~' position + //if names differ then filenames are different; + for (j=0; j < i;j++) { + if (name[j] != sname[j]) return 0; + } + + //if we get to this point we know that extension and name match + //now get the sequence number behind the '~' + for (j = i+1; j<8; j++) buf[j-i-1] = name[j]; + buf[j-i-1] = 0; //terminate + + XPRINTF("USBHDFSD: found short name sequence number='%s' \n", buf); + return strtol(buf, NULL, 10); +} + +//--------------------------------------------------------------------------- +/* + set the short name sequence number +*/ +static int setShortNameSequence(fat_driver* fatd, char* sname) { + char number[8]; + char *buf; + int i,j; + int seq; + unsigned char mask; + + //dlanor: The code below was bugged in several ways, as it treated the high seq + //values stored in long_name records as separate seqs, and also failed to accept + //any valid seq value whose low part (stored in short_name record) was zero. + //I'm now replacing this garbage with a bit-mask oriented scheme + + seq = SEQ_MASK_SIZE; + for(i=0; (i < (SEQ_MASK_SIZE>>3)); i++) { //for each mask byte + if((mask = fatd->seq_mask[i]) != 0xFF) { //if mask byte has any bit free + for(j=0; j<8; j++, mask>>=1) { //for each bit in byte + if((mask & 1)==0) { //if free bit found + seq = (i<<3)+j; //set seq value + break; //break bit loop + }//ends "if free bit found" + }//ends "for each bit in byte" + break; //break byte loop + }//ends "if mask byte has any bit free" + }//ends "for each mask byte" + + memset(number, 0, 8); + sprintf(number, "%d", seq); + j = strlen(number); + + buf = sname + 7 - j; + buf[0] = '~'; + buf++; + for (i = 0; i < j; i++) buf[i] = number[i]; + + return 0; +} + +//--------------------------------------------------------------------------- +/* + find space where to put the direntry +*/ +static int getDirentryStoreOffset(fat_driver* fatd, int entryCount, int direntrySize ) { + int i; + int tightIndex; + int looseIndex; + int cont; + int id; + int slotStart; + int slotSize; + int mask_ix, mask_sh; + + + //we search for sequence of deleted or empty entries (cleared bits in dir_used_mask) + //1) search the tight slot (that fits completely. ex: size = 3, and slot space is 3 ) + //2) search the suitable (loose) slot (ex: size = 3, slot space is 5) + + slotStart = -1; + slotSize = 0; + tightIndex = -1; + looseIndex = -1; + cont = 1; + //search the entries for entry types + for (i = 0; i < entryCount && cont; i++) { + mask_ix = i>>3; + mask_sh = i&7; + id = fatd->dir_used_mask[mask_ix] & (1<= 0) { + slotSize++; + } else { + slotStart = i; + slotSize = 1; + XPRINTF("USBHDFSD: *Start slot at index=%d ",slotStart); + } + } else { //occupied entry + if (tightIndex < 0 && slotSize == direntrySize) { + tightIndex = slotStart; + XPRINTF("USBHDFSD: !Set tight index= %d\n", tightIndex); + } + if (looseIndex < 0 && slotSize > direntrySize) { + looseIndex = slotStart + slotSize - direntrySize; + XPRINTF("USBHDFSD: !Set loose index= %d\n", looseIndex); + } + if (tightIndex >= 0 && looseIndex >= 0) { + cont = 0; + } + slotStart = -1; + slotSize = 0; + } + } + XPRINTF("USBHDFSD: \n"); + + // tight index - smaller fragmentation of space, the larger blocks + // are left for larger filenames. + // loose index - more fragmentation of direntry space, but the direntry + // name has space for future enlargement (of the name). + // i.e. no need to reposition the direntry and / or + // to allocate additional fat cluster for direntry space. + + // we prefere tight slot if available, othervise we use the loose slot. + // if there are no tight and no loose slot then we position new direntry + // at the end of current direntry space + if (tightIndex >=0) { + return tightIndex; + } + if (looseIndex >=0) { + return looseIndex; + } + //last entry is (most likely) empty - and if so, use it + mask_ix = (entryCount-1)>>3; + mask_sh = (entryCount-1)&7; + id = fatd->dir_used_mask[mask_ix] & (1<dev; +#endif + + memset(fatd->dir_used_mask, 0, DIR_MASK_SIZE/8); + memset(fatd->seq_mask, 0, SEQ_MASK_SIZE/8); + + cont = 1; + //clear name strings + dir.sname[0] = 0; + dir.name[0] = 0; + + j = 0; + if (directory>0) directory = FAT_ATTR_DIRECTORY; + + fat_getDirentrySectorData(fatd, startCluster, &startSector, &dirSector); + + XPRINTF("USBHDFSD: dirCluster=%u startSector=%u (%u) dirSector=%u \n", *startCluster, startSector, startSector * mass_device->sectorSize, dirSector); + + //go through first directory sector till the max number of directory sectors + //or stop when no more direntries detected + for (i = 0; i < dirSector && cont; i++) { + unsigned char* sbuf = NULL; //sector buffer + + //At cluster borders, get correct sector from cluster chain buffer + if ((*startCluster != 0) && (i % fatd->partBpb.clusterSize == 0)) { + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[(i / fatd->partBpb.clusterSize)]) -i; + } + theSector = startSector + i; + ret = READ_SECTOR(fatd->dev, theSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: read directory sector failed ! sector=%u\n", theSector); + return -EIO; + } + XPRINTF("USBHDFSD: read sector ok, scanning sector for direntries...\n"); + dirPos = 0; + + // go through start of the sector till the end of sector + while (cont && (dirPos < fatd->partBpb.sectorSize) && (j < DIR_MASK_SIZE)) { + fat_direntry* dir_entry = (fat_direntry*) (sbuf + dirPos); + cont = fat_getDirentry(fatd->partBpb.fatType, dir_entry, &dir); //get single directory entry from sector buffer + mask_ix = j>>3; + mask_sh = j&7; + switch (cont) { + case 1: //short name + fatd->dir_used_mask[mask_ix] |= (1< 0) && ((dir.attr & FAT_ATTR_DIRECTORY) != directory)) { + //found directory but requested is file (and vice veresa) + if (directory) return -ENOTDIR; + return -EISDIR; + }//ends "if" clause for mismatched file/folder state + XPRINTF("USBHDFSD: I: entry found! %s, %s = %s\n", dir.name, dir.sname, lname); + *retSector = theSector; + *retOffset = dirPos; + *startCluster = dir.cluster; + fatd->deSec[fatd->deIdx] = theSector; + fatd->deOfs[fatd->deIdx] = dirPos; + fatd->deIdx++; + return 0; + }//ends "if" clause for matching name + seq = getShortNameSequence((char*)dir_entry->sfn.name, (char*)dir_entry->sfn.ext, sname); + if(seq < SEQ_MASK_SIZE) + fatd->seq_mask[seq>>3] |= (1<<(seq & 7)); + fatd->deIdx = 0; + //clear name strings + dir.sname[0] = 0; + dir.name[0] = 0; + }//ends "if(!(dir.attr & FAT_ATTR_VOLUME_LABEL))" + else { //dlanor: Volume label + fatd->deIdx = 0; + } + break; + case 2: //long name + fatd->dir_used_mask[mask_ix] |= (1<deSec[fatd->deIdx] = theSector; + fatd->deOfs[fatd->deIdx] = dirPos; + fatd->deIdx++; + break; + case 3: //empty + fatd->deIdx = 0; + break; + }//ends "switch" + dirPos += sizeof(fat_direntry); + j++; + } + } + //indicate inconsistency + if (j >= DIR_MASK_SIZE) { + j++; + } + return j; +} + +//--------------------------------------------------------------------------- +/* + check wether the new direntries (note: one file have at least 2 direntries for 1 SFN and 1..n LFN) + fit into the current directory space. + Enlarges the directory space if needed and possible (note: root dirspace can't be enlarged for fat12 and fat16) + + startCluster - valid start cluster of dirpace or 0 for the root directory + entryCount - number of direntries of the filename (at least 2) + entryIndex - index where to store new direntries + direntrySize - number of all direntries in the directory +*/ + +static int enlargeDirentryClusterSpace(fat_driver* fatd, unsigned int startCluster, int entryCount, int entryIndex, int direntrySize) +{ + int ret; + unsigned int startSector, dirSector; + int i; + int maxSector; + int entriesPerSector; + int chainSize; + unsigned int currentCluster; + unsigned int newCluster; + + i = entryIndex + direntrySize; + XPRINTF("USBHDFSD: cur=%d ecount=%d \n", i, entryCount); + //we don't need to enlarge directory cluster space + if (i <= entryCount) return 0; //direntry fits into current space + + entriesPerSector = fatd->partBpb.sectorSize / 32; + maxSector = i / entriesPerSector; + if (i%entriesPerSector) { + maxSector++; + } + + chainSize = fat_getDirentrySectorData(fatd, &startCluster, &startSector, &dirSector); + + XPRINTF("USBHDFSD: maxSector=%u dirSector=%u\n", maxSector, dirSector); + + if (maxSector<=dirSector) return 0; + + //Root directory of FAT12 or FAT16 - space can't be enlarged! + if (startCluster == 0 && fatd->partBpb.fatType < FAT32) { + return -EMLINK; //too many direntries in the root directory + } + + //in the fatd->cbuf we have the cluster chain + + //get last cluster of the cluster chain + currentCluster = fatd->cbuf[chainSize-1]; + XPRINTF("USBHDFSD: current (last) cluster=%u \n", currentCluster); + + //get 1 cluster from cluster stack and append the chain + newCluster = fat_getFreeCluster(fatd, currentCluster); + XPRINTF("USBHDFSD: new cluster=%u \n", newCluster); + fat_invalidateLastChainResult(fatd); //prevent to misuse current (now updated) fatd->cbuf + //if new cluster cannot be allocated + if (newCluster == 0) { + return -ENOSPC; + } + + // now clean the directory space + startSector = fat_cluster2sector(&fatd->partBpb, newCluster); + for (i = 0; i < fatd->partBpb.clusterSize; i++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = ALLOC_SECTOR(fatd->dev, startSector + i, sbuf); + memset(sbuf, 0 , fatd->partBpb.sectorSize); //fill whole sector with zeros + ret = WRITE_SECTOR(fatd->dev, startSector + i); + if (ret < 0) return -EIO; + } + return 1; // 1 cluster allocated +} + +//--------------------------------------------------------------------------- +/* + Create empty directory space with two SFN direntries: + 1) current directory "." + 2) parent directory ".." + +*/ +static int createDirectorySpace(fat_driver* fatd, unsigned int dirCluster, unsigned int parentDirCluster) { + int i, j; + int ret; + unsigned int startSector; + + //we do not mess with root directory + if (dirCluster < 2) { + return -EFAULT; + } + + //we create directory space inside one cluster. No need to worry about + //large dir space spread on multiple clusters + startSector = fat_cluster2sector(&fatd->partBpb, dirCluster); + XPRINTF("USBHDFSD: I: create dir space: cluster=%u sector=%u (%u) \n", dirCluster, startSector, startSector * fatd->partBpb.sectorSize); + + //go through all sectors of the cluster + for (i = 0; i < fatd->partBpb.clusterSize; i++) { + unsigned char* sbuf = NULL; //sector buffer + + ret = ALLOC_SECTOR(fatd->dev, startSector + i, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: alloc directory sector failed ! sector=%u\n", startSector + i); + return -EIO; + } + memset(sbuf, 0, fatd->partBpb.sectorSize); //clean the sector + if (i == 0) { + fat_direntry_sfn* dsfn = (fat_direntry_sfn*) sbuf; + char name[11]; + for (j = 1; j< 11; j++) name[j] = ' '; + name[0] = '.'; + setSfnEntry(name, 1, dsfn + 0, dirCluster); + name[1] = '.'; + setSfnEntry(name, 1, dsfn + 1, parentDirCluster); + } + ret = WRITE_SECTOR(fatd->dev, startSector + i); + if (ret < 0) { + XPRINTF("USBHDFSD: write directory sector failed ! sector=%u\n", startSector + i); + return -EIO; + } + } + + return(0); +} + + +//--------------------------------------------------------------------------- +/* + Save direntries of the long and short filename to the directory space on the disk + + startCluster - start cluster of the directory space + lname : long name + sname : short name + directory : 0-file, 1-directory + cluster : start cluster of the file/directory + + entrySize - number of direntries to store + entryIndex - index of the direntry start in the directory space + + retSector - contains sector number of the direntry (output) + retOffset - contains byte offse of the SFN direntry from start of the sector (output) + the reason is to speed up modification of the SFN (size of the file) + + note: the filesize set in the direntry is 0 (for both directory and file) +*/ +static int saveDirentry(fat_driver* fatd, unsigned int startCluster, + const char* lname, const char* sname, char directory, unsigned int cluster, + int entrySize, int entryIndex, unsigned int* retSector, int* retOffset, const fat_direntry_sfn *orig_dsfn) { + int i, j; + unsigned int startSector, dirSector, theSector; + int cont; + int ret; + unsigned int dirPos; + int entryEndIndex; + int writeFlag; +#ifdef DEBUG + struct SBP2Device* mass_device = fatd->dev; +#endif + int part = entrySize - 1; + int nameSize; + unsigned char chsum; + + chsum = computeNameChecksum(sname); + nameSize = strlen(lname); + + cont = 1; + //clear name strings + entryEndIndex = entryIndex + entrySize; + + j = 0; + + fat_getDirentrySectorData(fatd, &startCluster, &startSector, &dirSector); + + XPRINTF("USBHDFSD: dirCluster=%u startSector=%u (%u) dirSector=%u \n", startCluster, startSector, startSector * mass_device->sectorSize, dirSector); + + //go through first directory sector till the max number of directory sectors + //or stop when no more direntries detected + for (i = 0; i < dirSector && cont; i++) { + unsigned char* sbuf = NULL; //sector buffer + + //At cluster borders, get correct sector from cluster chain buffer + if ((startCluster != 0) && (i % fatd->partBpb.clusterSize == 0)) { + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[(i / fatd->partBpb.clusterSize)]) -i; + } + theSector = startSector + i; + ret = READ_SECTOR(fatd->dev, theSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: read directory sector failed ! sector=%u\n", theSector); + return -EIO; + } + XPRINTF("USBHDFSD: read sector ok, scanning sector for direntries...\n"); + dirPos = 0; + writeFlag = 0; + // go through start of the sector till the end of sector + while (dirPos < fatd->partBpb.sectorSize) { + if (j >=entryIndex && j < entryEndIndex) { + fat_direntry* dir_entry = (fat_direntry*) (sbuf + dirPos); + if (part == 0) { + if(orig_dsfn == NULL) + setSfnEntry(sname, directory, &dir_entry->sfn, cluster); + else + setSfnEntryFromOld(sname, &dir_entry->sfn, orig_dsfn); + }else + setLfnEntry(lname, nameSize, chsum, &dir_entry->lfn, part, entrySize - 1); + part--; + writeFlag++; + //SFN is stored + if (j == entryEndIndex-1) { + *retSector = theSector; + *retOffset = dirPos; + } + } + //sbuf + dirPos + dirPos += sizeof(fat_direntry); + j++; + }//ends "while" + //store modified sector + if (writeFlag) { + ret = WRITE_SECTOR(fatd->dev, theSector); + if (ret < 0) { + XPRINTF("USBHDFSD: write directory sector failed ! sector=%u\n", theSector); + return -EIO; + } + } + if (j >= entryEndIndex) { + cont = 0; //do not continue + } + } + return j; +} + +//--------------------------------------------------------------------------- +/* + - create/convert long name to short name + - analyse directory space + - enlarge directory space + - save direntries + + lname - long name + directory - 0-> create file 1->create directory + escapeNoExist - 0->allways create file 1->early exit if file doesn't exist + startCluster - directory space start cluster (set to zero for root directory) + retSector - SFN sector - sector of the SFN direntry (output) + retOffset - byte offset of the SFN direntry counting from the start of the sector (output) +*/ + +static int fat_modifyDirSpace(fat_driver* fatd, char* lname, char directory, char escapeNotExist, unsigned int* startCluster, unsigned int* retSector, int* retOffset, const fat_direntry_sfn *orig_dsfn) { + char sname[12]; //short name 8+3 + terminator + unsigned int newCluster, parentDirCluster_tmp; + int ret, entryCount, compressShortName, entryIndex, direntrySize; + + //dlanor: Since each filename may need up to 11 directory entries (MAX_FAT_NAME==128) + //dlanor: I've rewritten the methods of this function to use global bitmasks as this + //dlanor: allows more effective entry handling than most other methods + // + //memo buffer for each direntry - up to 1024 entries in directory + // 7 6 5 4 3 2 | 1 0 + // ------------+----- + // SEQ HI/LO | ID + // ------------------ + // ID : 0 - entry is empty or deleted + // 1 - sfn entry + // 2 - lfn entry + // 3 - other entry (volume label etc.) + // SEQ: sequence number of the short filename. + // if our long filename is "Quitelongname.txt" then + // seq for existing entry: + // ABCD.TXT seq = 0 (no sequence number in name and name doesn't match) + // ABCDEF~1.TXT seq = 0 (because the short names doesn't match) + // QUITELON.TXT seq = 0 (again the short name doesn't match) + // QUITEL~1.JPG seq = 0 (name match but extension desn't match) + // QUITEL~1.TXT seq = 1 (both name and extension match - sequence number 1) + // QUITE~85.TXT seq = 85 ( dtto. ^^^^) + + // If the sfn has sequence it means the filename should be long + // and preceeding entry should be lfn. In this case the preceeding (lfn) + // entry seq holds the high 6 bites of the whole sequence. If preceding + // entry is another sfn direntry then we report error (even if it might be + // (in some rare occasions) correct directory structure). + + + sname[11] = 0; + + //create short name from long name + ret = createShortNameMask(lname,sname); + if (ret < 0) { + XPRINTF("USBHDFSD: E: short name invalid!\n"); + return ret; + } + compressShortName = ret; + + //get information about existing direntries (palcement of the empty/reusable direntries) + //and sequence numbers of the short filenames + parentDirCluster_tmp = *startCluster; + ret = fat_fillDirentryInfo(fatd, lname, sname, directory, + &parentDirCluster_tmp, retSector, retOffset); + if (ret < 0) { + XPRINTF("USBHDFSD: E: direntry data invalid!\n"); + return ret; + } + //ret 0 means that exact filename/directory already exist + if (ret == 0) { + return ret; + } + + //exact filename not exist and we want to report it + if (escapeNotExist) { + return -ENOENT; + } + + + if (ret > DIR_MASK_SIZE) { + XPRINTF("USBHDFSD: W: Direntry count is larger than number of records!\n"); + ret = DIR_MASK_SIZE; + } + entryCount = ret; + XPRINTF("USBHDFSD: I: direntry count=%d\n", entryCount); + + if (compressShortName) { + setShortNameSequence(fatd, sname); + } + XPRINTF("USBHDFSD: I: new short name='%s' \n", sname); + + //direntry size for long name + 1 additional direntry for short name + direntrySize = getDirentrySize(lname) + 1; + XPRINTF("USBHDFSD: Direntry size=%d\n", direntrySize); + + //find the offset (index) of the direntry space where to put this direntry + entryIndex = getDirentryStoreOffset(fatd, entryCount, direntrySize); + XPRINTF("USBHDFSD: I: direntry store offset=%d\n", entryIndex); + + //if the direntry offset excede current space of directory clusters + //we have to add one cluster to directory space + ret = enlargeDirentryClusterSpace(fatd, *startCluster, entryCount, entryIndex, direntrySize); + XPRINTF("USBHDFSD: I: enlarge direntry cluster space ret=%d\n", ret); + if (ret < 0) { + return ret; + } + + if(orig_dsfn == NULL){ + //get new cluster for file/directory + newCluster = fat_getFreeCluster(fatd, 0); + if (newCluster == 0) { + return -ENOSPC; + } + XPRINTF("USBHDFSD: I: new file/dir cluster=%u\n", newCluster); + }else{ + newCluster = 0; + } + + //now store direntries into the directory space + ret = saveDirentry(fatd, *startCluster, lname, sname, directory, newCluster, direntrySize, entryIndex, retSector, retOffset, orig_dsfn); + XPRINTF("USBHDFSD: I: save direntry ret=%d\n", ret); + if (ret < 0) { + return ret; + } + + //create empty directory structure + if ((orig_dsfn == NULL) && directory) { + ret = createDirectorySpace(fatd, newCluster, *startCluster); + XPRINTF("USBHDFSD: I: create directory space ret=%d\n", ret); + if (ret < 0) { + return ret; + } + } + + return 1; +} + +//--------------------------------------------------------------------------- +/* + Check whether directory space contain any file or directory + + startCluster - start cluster of the directory space + + returns: 0 - false - directory space contains files or directories (except '.' and '..') + 1 - true - directory space is empty or contains deleted entries + -X - error +*/ +static int checkDirspaceEmpty(fat_driver* fatd, unsigned int startCluster) { + int ret; + int i; + char sname[12]; //short name 8+3 + terminator + int entryCount; + + unsigned int retSector; + int retOffset; + + XPRINTF("USBHDFSD: I: checkDirspaceEmpty directory cluster=%u \n", startCluster); + if (startCluster < 2) { // do not check root directory! + return -EFAULT; + } + + sname[0] = 0; + + + ret = fat_fillDirentryInfo(fatd, sname, sname, 1, + &startCluster, &retSector, &retOffset); + if (ret > DIR_MASK_SIZE) { + XPRINTF("USBHDFSD: W: Direntry count is larger than number of records! directory space cluster =%u maxRecords=%u\n", startCluster, DIR_MASK_SIZE); + ret = DIR_MASK_SIZE; + } + entryCount = ret; + //first two records should be '.' & '..', which don't count as real content + if((fatd->dir_used_mask[0] & 0xFC) != 0) + goto non_empty; + for (i=1; i < (entryCount/8); i++) { + if(fatd->dir_used_mask[i] != 0) { +non_empty: + XPRINTF("USBHDFSD: I: directory not empty!\n"); + return 0; + }//ends "if" + }//ends "for" + XPRINTF("USBHDFSD: I: directory is empty.\n"); + return 1; +} + +//--------------------------------------------------------------------------- +static int fat_wipeDirEntries(fat_driver *fatd){ + int ret; + unsigned int i, theSector; + unsigned char* sbuf = NULL; + + //now mark direntries as deleted + theSector = 0; + ret = 0; + for (i = 0; i < fatd->deIdx; i++) { + if (fatd->deSec[i] != theSector) { + if (theSector > 0) { + ret = WRITE_SECTOR(fatd->dev, theSector); + if (ret < 0) { + XPRINTF("USBHDFSD: write directory sector failed ! sector=%u\n", theSector); + ret = -EIO; + break; + } + } + theSector = fatd->deSec[i]; + ret = READ_SECTOR(fatd->dev, theSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: read directory sector failed ! sector=%u\n", theSector); + ret = -EIO; + break; + } + } + sbuf[fatd->deOfs[i]] = 0xE5; //delete marker + } + if (theSector > 0) { + ret = WRITE_SECTOR(fatd->dev, theSector); + if (ret < 0) { + XPRINTF("USBHDFSD: write directory sector failed ! sector=%u\n", theSector); + ret = -EIO; + } + } + + return ret; +} + + +/* + Remove the name (direntries of the file or directory) from the directory space. + + lname - long name (without the path) + directory - 0->delete file 1-delete directory + startCluster - start cluster of the directory space +*/ + +static int fat_clearDirSpace(fat_driver* fatd, char* lname, char directory, unsigned int* startCluster) { + int ret; + char sname[12]; //short name 8+3 + terminator + unsigned int dirCluster; + unsigned int sfnSector; + int sfnOffset; + + sname[0] = 0; + + + dirCluster = *startCluster; + //get information about existing direntries (palcement of the empty/reusable direntries) + //and find the lname in the directory + //also fill up the dsSec and dsOfs information + ret = fat_fillDirentryInfo(fatd, lname, sname, directory, + startCluster, &sfnSector, &sfnOffset); + if (ret != 0) { + XPRINTF("USBHDFSD: E: direntry not found!\n"); + return -ENOENT; + } + XPRINTF("USBHDFSD: clear dir space: dir found at cluster=%u \n ", *startCluster); + + //Check wether any file or directory exist in te target directory space. + //We should not delete the directory if files/directories exist + //because just clearing the dir doesn't free the fat clusters + //occupied by files. + if (directory) { + //check wether sub-directory is empty + //startCluster now points to subdirectory start cluster + ret = checkDirspaceEmpty(fatd, *startCluster); + if (ret == 0) { //directorty contains some files + return -ENOTEMPTY; + } + //read the direntry info again, because we lost it during subdir check + *startCluster = dirCluster; + + ret = fat_fillDirentryInfo(fatd, lname, sname, directory, + startCluster, &sfnSector, &sfnOffset); + if (ret != 0) { + XPRINTF("USBHDFSD: E: direntry not found!\n"); + return -ENOENT; + } + } + + //now mark direntries as deleted + ret = fat_wipeDirEntries(fatd); + if (ret < 0) { + XPRINTF("USBHDFSD: E: wipe direntries failed!\n"); + return ret; + } + + //now delete whole cluster chain starting at the file's first cluster + ret = fat_deleteClusterChain(fatd, *startCluster); + if (ret < 0) { + XPRINTF("USBHDFSD: E: delete cluster chain failed!\n"); + return ret; + } + return 1; +} + + + + +/* ===================================================================== */ + +/* + cluster - start cluster of the file + sfnSector - short filename entry sector + sfnOffset - short filename entry offset from the sector start +*/ +int fat_truncateFile(fat_driver* fatd, unsigned int cluster, unsigned int sfnSector, int sfnOffset ) { + int ret; + fat_direntry_sfn* dsfn; + unsigned char* sbuf = NULL; //sector buffer + + if (cluster == 0 || sfnSector == 0) { + return -EFAULT; + } + + + //now delete whole cluster chain starting at the file's first cluster + ret = fat_deleteClusterChain(fatd, cluster); + if (ret < 0) { + XPRINTF("USBHDFSD: E: delete cluster chain failed!\n"); + return ret; + } + + //terminate cluster + ret = fat_createClusterChain(fatd, cluster); + if (ret < 0) { + XPRINTF("USBHDFSD: E: truncate cluster chain failed!\n"); + return ret; + } + + ret = READ_SECTOR(fatd->dev, sfnSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: read direntry sector failed ! sector=%u\n", sfnSector); + return -EIO; + } + dsfn = (fat_direntry_sfn*) (sbuf + sfnOffset); + dsfn->size[0] = 0; + dsfn->size[1] = 0; + dsfn->size[2] = 0; + dsfn->size[3] = 0; + + ret = WRITE_SECTOR(fatd->dev, sfnSector); + if (ret < 0) { + XPRINTF("USBHDFSD: write directory sector failed ! sector=%u\n", sfnSector); + return -EIO; + } + return 1; +} + + +//--------------------------------------------------------------------------- +/* + Update size of the SFN entry + + cluster - start cluster of the file + sfnSector - short filename entry sector + sfnOffset - short filename entry offset from the sector start +*/ +int fat_updateSfn(fat_driver* fatd, int size, unsigned int sfnSector, int sfnOffset ) { + int ret; + fat_direntry_sfn* dsfn; + unsigned char* sbuf = NULL; //sector buffer + + if (sfnSector == 0) { + return -EFAULT; + } + + + ret = READ_SECTOR(fatd->dev, sfnSector, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: read direntry sector failed ! sector=%u\n", sfnSector); + return -EIO; + } + dsfn = (fat_direntry_sfn*) (sbuf + sfnOffset); + dsfn->size[0] = size & 0xFF; + dsfn->size[1] = (size & 0xFF00) >> 8; + dsfn->size[2] = (size & 0xFF0000) >> 16; + dsfn->size[3] = (size & 0xFF000000) >> 24; + + setSfnDate(dsfn, DATE_MODIFY); + + ret = WRITE_SECTOR(fatd->dev, sfnSector); + if (ret < 0) { + XPRINTF("USBHDFSD: write directory sector failed ! sector=%u\n", sfnSector); + return -EIO; + } + XPRINTF("USBHDFSD: I: sfn updated, file size=%d \n", size); + return 1; +} + + +//--------------------------------------------------------------------------- +/* + create file or directory + + fname - path and filename + directory - set to 0 to create file, 1 to create directory + escapeNotExist - set to 1 if you want to report error if file not exist. + Otherwise set to 0 and file/dir will be created. + cluster - start cluster of the directory space - default is 0 -> root directory + sfnSector - sector of the SFN entry (output) - helps to modify direntry (size, date, time) + sfnOffset - offset (in bytes) of the SFN entry (output) +*/ + +int fat_createFile(fat_driver* fatd, const char* fname, char directory, char escapeNotExist, unsigned int* cluster, unsigned int* sfnSector, int* sfnOffset) { + int ret; + unsigned int startCluster; + unsigned int directoryCluster; + char lname[FAT_MAX_NAME], pathToDirent[FAT_MAX_PATH]; + fat_dir fatdir; + + ret = separatePathAndName(fname, pathToDirent, lname); + if( (ret < 0) //if name invalid to separation routine + ||( (lname[0] == 0) //or name is empty string + ||( (lname[0]=='.') + &&( (lname[1]==0) //or name is single period + ||( (lname[1]=='.') + &&(lname[2]==0) //or name is two periods + ) + ) + ) + ) + ) + { + XPRINTF("USBHDFSD: E: file name not exist or not valid!"); + return -ENOENT; + } + + XPRINTF("USBHDFSD: Calling fat_getFileStartCluster from fat_createFile\n"); + //get start cluster of the last sub-directory of the path + startCluster = 0; + ret = fat_getFileStartCluster(fatd, pathToDirent, &startCluster, &fatdir); + if (ret < 0) { + XPRINTF("USBHDFSD: E: directory not found! \n"); + return ret; + } + + if (!(fatdir.attr & FAT_ATTR_DIRECTORY)) { + XPRINTF("USBHDFSD: E: directory not found! \n"); + return -ENOENT; + } + + XPRINTF("USBHDFSD: directory=%s name=%s cluster=%u \n", pathToDirent, lname, startCluster); + + if (fatdir.attr & FAT_ATTR_READONLY) + return -EACCES; + + //modify directory space of the path (cread direntries) + //and/or create new (empty) directory space if directory creation requested + directoryCluster = startCluster; + ret = fat_modifyDirSpace(fatd, lname, directory, escapeNotExist, &startCluster, sfnSector, sfnOffset, NULL); + if (ret < 0) { + XPRINTF("USBHDFSD: E: modifyDirSpace failed!\n"); + return ret; + } + XPRINTF("USBHDFSD: I: SFN info: sector=%u (%u) offset=%u (%u) startCluster=%u\n", *sfnSector, *sfnSector * fatd->partBpb.sectorSize, *sfnOffset, *sfnOffset + (*sfnSector * fatd->partBpb.sectorSize), startCluster); + *cluster = startCluster; + //dlanor: I've repatched the stuff below to improve functionality + //The simple test below was bugged for the case of creating a folder in root + //if (startCluster != directoryCluster) { + //That test (on the line above) fails in root because created folders never + //get a startCluster of 0. That is reserved for root only. + //The test below replaces this with a more complex test that takes all of this + //stuff into proper account, but behaves like the old test for other cases. + //That's mainly because I can't tell how consistent name conflict flagging is + //for those other cases, and it's not really worth the trouble of finding out :) + if( (ret == 0) //if we have a directly flagged name conflict + ||( (directoryCluster || !directory) //OR working in non_root, or making a file + &&(startCluster != directoryCluster) //AND we get an unexpected startCluster + ) + ) { + XPRINTF("USBHDFSD: I: file already exists at cluster=%u\n", startCluster); + return 2; + } + return 0; +} + + +//--------------------------------------------------------------------------- +int fat_deleteFile(fat_driver* fatd, const char* fname, char directory) { + int ret; + unsigned int startCluster; + unsigned int directoryCluster; + char lname[FAT_MAX_NAME], pathToDirent[FAT_MAX_PATH]; + fat_dir fatdir; + + ret = separatePathAndName(fname, pathToDirent, lname); + if( (ret < 0) //if name invalid to separation routine + ||( (lname[0] == 0) //or name is empty string + ||( (lname[0]=='.') + &&( (lname[1]==0) //or name is single period + ||( (lname[1]=='.') + &&(lname[2]==0) //or name is two periods + ) + ) + ) + ) + ) + { + XPRINTF("USBHDFSD: E: file name not exist or not valid!"); + return -ENOENT; + } + + XPRINTF("USBHDFSD: Calling fat_getFileStartCluster from fat_deleteFile\n"); + //get start cluster of the last sub-directory of the path + startCluster = 0; + ret = fat_getFileStartCluster(fatd, pathToDirent, &startCluster, &fatdir); + if (ret < 0) { + XPRINTF("USBHDFSD: E: directory not found! \n"); + return ret; + } + + if (!(fatdir.attr & FAT_ATTR_DIRECTORY)) { + XPRINTF("USBHDFSD: E: directory not found! \n"); + return -ENOENT; + } + + XPRINTF("USBHDFSD: directory=%s name=%s cluster=%u \n", pathToDirent, lname, startCluster); + + if (fatdir.attr & FAT_ATTR_READONLY) { + XPRINTF("USBHDFSD: E: directory read only! \n"); + return -EACCES; + } + + //delete direntries and modify fat + directoryCluster = startCluster; + ret = fat_clearDirSpace(fatd, lname, directory, &startCluster); + if (ret < 0) { + XPRINTF("USBHDFSD: E: cleanDirSpace failed!\n"); + return ret; + } + if (startCluster != directoryCluster) { + XPRINTF("USBHDFSD: I: file/dir removed from cluster=%u\n", startCluster); + } + return 0; +} + +//--------------------------------------------------------------------------- +//Create a new record that points to the file/directory, before deleting the original one. + +int fat_renameFile(fat_driver* fatd, fat_dir *fatdir, const char* fname) { + int ret; + unsigned int sDirCluster; + unsigned int dDirCluster, dParentDirCluster; + char lname[FAT_MAX_NAME], pathToDirent[FAT_MAX_PATH]; + unsigned int sfnSector, new_sfnSector; + int directory, sfnOffset, new_sfnOffset; + char sname[12]; //short name 8+3 + terminator + unsigned char* sbuf = NULL; + fat_direntry_sfn OriginalSFN; + + ret = separatePathAndName(fname, pathToDirent, lname); + if( (ret < 0) //if name invalid to separation routine + ||( (lname[0] == 0) //or name is empty string + ||( (lname[0]=='.') + &&( (lname[1]==0) //or name is single period + ||( (lname[1]=='.') + &&(lname[2]==0) //or name is two periods + ) + ) + ) + ) + ) + { + XPRINTF("USBHDFSD: E: destination file name not exist or not valid!"); + return -ENOENT; + } + + //Check if the source file exists, and that the new filename is not in use. + sDirCluster = fatdir->parentDirCluster; + dDirCluster = 0; + XPRINTF("USBHDFSD: Calling fat_getFileStartCluster from fat_renameFile\n"); + + ret = fat_getFileStartCluster(fatd, pathToDirent, &dDirCluster, NULL); + if (ret < 0) { + XPRINTF("USBHDFSD: E: destination directory not found! \n"); + return ret; + } + dParentDirCluster = dDirCluster; //Backup dDirCluster, as every call to fat_filleDirentryInfo will update it to point to the scanned file's first cluster. + + sname[0] = 0; + ret = fat_fillDirentryInfo(fatd, lname, sname, -1, &dDirCluster, &new_sfnSector, &new_sfnOffset); + if (ret == 0) { + XPRINTF("USBHDFSD: E: file already exists!\n"); + return -EEXIST; + } + + //Get the SFN sector number and offset, so that the SFN record can be read. + ret = fat_fillDirentryInfo(fatd, fatdir->name, sname, -1, &sDirCluster, &sfnSector, &sfnOffset); + if (ret != 0) { + XPRINTF("USBHDFSD: E: direntry not found! %d\n", ret); + return -ENOENT; + } + + XPRINTF("USBHDFSD: fat_renameFile: dir found at cluster=%u \n ", sDirCluster); + + //Preserve the original SFN entry. + if((ret = READ_SECTOR(fatd->dev, sfnSector, sbuf))<0){ + XPRINTF("USBHDFSD: E: I/O error! %d\n", ret); + return ret; + } + memcpy(&OriginalSFN, (fat_direntry_sfn*) (sbuf + sfnOffset), sizeof(fat_direntry_sfn)); + directory = ((fat_direntry_sfn*) (sbuf + sfnOffset))->attr & FAT_ATTR_DIRECTORY; + + //Insert a new record. + if((ret = fat_modifyDirSpace(fatd, lname, directory, 0, &dDirCluster, &sfnSector, &sfnOffset, &OriginalSFN)) < 0){ + XPRINTF("USBHDFSD: E: fat_modifyDirSpace failed! %d\n", ret); + return ret; + } + + //Wipe the original entry. + //Fill fatd with a list of the original directory entry records, which can be deleted. + sDirCluster = fatdir->parentDirCluster; + ret = fat_fillDirentryInfo(fatd, fatdir->name, sname, -1, &sDirCluster, &sfnSector, &sfnOffset); + if (ret != 0) { + XPRINTF("USBHDFSD: E: direntry not found! %d\n", ret); + return -ENOENT; + } + + //now mark the original direntries as deleted + ret = fat_wipeDirEntries(fatd); + if (ret < 0) { + XPRINTF("USBHDFSD: E: wipe direntries failed!\n"); + return ret; + } + + fatdir->parentDirCluster = dParentDirCluster; + strcpy(fatdir->name, lname); + + return 0; +} //ends fat_renameFile + +//--------------------------------------------------------------------------- +int fat_writeFile(fat_driver* fatd, fat_dir* fatDir, int* updateClusterIndices, unsigned int filePos, unsigned char* buffer, unsigned int size) { + int ret; + int i,j; + int chainSize; + int nextChain; + int startSector; + unsigned int bufSize; + int sectorSkip; + int clusterSkip; + int dataSkip; + + unsigned int bufferPos; + unsigned int fileCluster; + unsigned int clusterPos; + unsigned int endPosFile; + unsigned int endPosCluster; + unsigned int lastCluster; + + int clusterChainStart; + + struct SBP2Device* mass_device = fatd->dev; + + //check wether we have enough clusters allocated + i = fatd->partBpb.clusterSize * fatd->partBpb.sectorSize; //the size (in bytes) of the one cluster + j = fatDir->size / i; + if (fatDir->size % i) { + j++; + } + if (j == 0) j = 1; //the file have allways at least one cluster allocated + + endPosCluster = j * i; + endPosFile = filePos + size; + + *updateClusterIndices = 0; + + //allocate additional cluster(s) + if (endPosFile > endPosCluster) { + ret = endPosFile - endPosCluster; //additional space needed in bytes + j = ret / i; //additional space needed (given in number of clusters) + if (ret % i) { + j++; + } + lastCluster = fatDir->lastCluster; + XPRINTF("USBHDFSD: I: writeFile: last cluster= %u \n", lastCluster); + + if (lastCluster == 0) return -ENOSPC; // no more free clusters or data invalid + for (i = 0; i < j; i++) { + lastCluster = fat_getFreeCluster(fatd, lastCluster); + if (lastCluster == 0) return -ENOSPC; // no more free clusters + } + fatDir->lastCluster = lastCluster; + *updateClusterIndices = j; + fat_invalidateLastChainResult(fatd); //prevent to misuse current (now deleted) fatd->cbuf + + XPRINTF("USBHDFSD: I: writeFile: new clusters allocated = %u new lastCluster=%u \n", j, lastCluster); + } + XPRINTF("USBHDFSD: I: write file: filePos=%d dataSize=%d \n", filePos, size); + + + fat_getClusterAtFilePos(fatd, fatDir, filePos, &fileCluster, &clusterPos); + sectorSkip = (filePos - clusterPos) / fatd->partBpb.sectorSize; + clusterSkip = sectorSkip / fatd->partBpb.clusterSize; + sectorSkip %= fatd->partBpb.clusterSize; + dataSkip = filePos % fatd->partBpb.sectorSize; + bufferPos = 0; + + + XPRINTF("USBHDFSD: fileCluster = %u, clusterPos= %u clusterSkip=%u, sectorSkip=%u dataSkip=%u \n", + fileCluster, clusterPos, clusterSkip, sectorSkip, dataSkip); + + if (fileCluster < 2) { + return -EFAULT; + } + + bufSize = mass_device->sectorSize; + nextChain = 1; + clusterChainStart = 1; + + while (nextChain && size > 0 ) { + chainSize = fat_getClusterChain(fatd, fileCluster, fatd->cbuf, MAX_DIR_CLUSTER, clusterChainStart); + clusterChainStart = 0; + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + fileCluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + }else { //chain fits in the chain buffer completely - no next chain needed + nextChain = 0; + } + while (clusterSkip >= MAX_DIR_CLUSTER) { + chainSize = fat_getClusterChain(fatd, fileCluster, fatd->cbuf, MAX_DIR_CLUSTER, clusterChainStart); + clusterChainStart = 0; + if (chainSize >= MAX_DIR_CLUSTER) { //the chain is full, but more chain parts exist + fileCluster = fatd->cbuf[MAX_DIR_CLUSTER - 1]; + }else { //chain fits in the chain buffer completely - no next chain needed + nextChain = 0; + } + clusterSkip -= MAX_DIR_CLUSTER; + } + + //process the cluster chain (fatd->cbuf) and skip leading clusters if needed + for (i = 0 + clusterSkip; i < chainSize && size > 0; i++) { + //read cluster and save cluster content + startSector = fat_cluster2sector(&fatd->partBpb, fatd->cbuf[i]); + //process all sectors of the cluster (and skip leading sectors if needed) + for (j = 0 + sectorSkip; j < fatd->partBpb.clusterSize && size > 0; j++) { + unsigned char* sbuf = NULL; //sector buffer + + //compute exact size of transfered bytes + if (size < bufSize) { + bufSize = size + dataSkip; + } + if (bufSize > mass_device->sectorSize) { + bufSize = mass_device->sectorSize; + } + + /* SP193: By right, the sector's content should be retained if it has already been allocated and is going to be partially written-to. + Since this function wasn't designed to be able to tell allocated sectors from unallocated sectors, assume that all partial writes are to allocated sectors. */ + if((bufSize - dataSkip) != mass_device->sectorSize) + ret = READ_SECTOR(fatd->dev, startSector + j, sbuf); + else + ret = ALLOC_SECTOR(fatd->dev, startSector + j, sbuf); + if (ret < 0) { + XPRINTF("USBHDFSD: Read sector failed ! sector=%u\n", startSector + j); + return bufferPos; //return number of bytes already written + } + + XPRINTF("USBHDFSD: memcopy dst=%u, src=%u, size=%u bufSize=%u \n", dataSkip, bufferPos,bufSize-dataSkip, bufSize); + memcpy(sbuf + dataSkip, buffer+bufferPos, bufSize - dataSkip); + ret = WRITE_SECTOR(fatd->dev, startSector + j); + if (ret < 0) { + XPRINTF("USBHDFSD: Write sector failed ! sector=%u\n", startSector + j); + return bufferPos; //return number of bytes already written + } + + size-= (bufSize - dataSkip); + bufferPos += (bufSize - dataSkip); + dataSkip = 0; + bufSize = mass_device->sectorSize; + } + sectorSkip = 0; + } + clusterSkip = 0; + } + + return bufferPos; //return number of bytes already written +} + +//--------------------------------------------------------------------------- +int fat_flushSectors(fat_driver* fatd) +{ + FLUSH_SECTORS(fatd->dev); + return(0); +} +//--------------------------------------------------------------------------- +//End of file: fat_write.c +//--------------------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/fs_driver.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/fs_driver.c new file mode 100644 index 0000000..34f88f6 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/fs_driver.c @@ -0,0 +1,806 @@ +//--------------------------------------------------------------------------- +//File name: fs_driver.c +//--------------------------------------------------------------------------- +/* + * fat_driver.c - USB Mass storage driver for PS2 + * + * (C) 2004, Marek Olejnik (ole00@post.cz) + * (C) 2004 Hermes (support for sector sizes from 512 to 4096 bytes) + * (C) 2004 raipsu (fs_dopen, fs_dclose, fs_dread, fs_getstat implementation) + * + * FAT filesystem layer + * + * See the file LICENSE included with this distribution for licensing terms. + */ +//--------------------------------------------------------------------------- +#include +#include +#include + +#ifdef WIN32 +#include +#include +#include +#include +#else +#include +#include +#include +#include +#endif + +#include +#include "usbhd_common.h" +#include "fat_driver.h" +#include "fat_write.h" +#include "fat.h" +#include "sbp2_disk.h" + +//#define DEBUG //comment out this line when not debugging + +#include "mass_debug.h" + +#define FLUSH_SECTORS fat_flushSectors + +enum FS_FILE_FLAG{ + FS_FILE_FLAG_FOLDER = 0, + FS_FILE_FLAG_FILE +}; + +struct fs_dirent{ //Common structure for both directories and regular files. + //This flag is always 1 for a file, and always 0 for a folder (different typedef) + //Routines that handle both must test it, and then typecast the privdata pointer + //to the type that is appropriate for the given case. (see also fs_dir typedef) + short int file_flag; + short int sizeChange; //flag, used for regular files. Otherwise padding. + fat_dir fatdir; +}; + +typedef struct _fs_rec { + struct fs_dirent dirent; + short int sizeChange; //flag + unsigned int filePos; + int mode; //file open mode + unsigned int sfnSector; //short filename sector - write support + int sfnOffset; //short filename offset - write support +} fs_rec; + +typedef struct _fs_dir { + struct fs_dirent dirent; + int status; + fat_dir_list fatdlist; + fat_dir current_fatdir; +} fs_dir; + +#define MAX_FILES 16 +static fs_rec fsRec[MAX_FILES]; //file info record + +static void fillStat(iox_stat_t *stat, const fat_dir *fatdir) +{ + stat->mode = FIO_S_IROTH | FIO_S_IXOTH; + if (fatdir->attr & FAT_ATTR_DIRECTORY) { + stat->mode |= FIO_S_IFDIR; + } else { + stat->mode |= FIO_S_IFREG; + } + if (!(fatdir->attr & FAT_ATTR_READONLY)) { + stat->mode |= FIO_S_IWOTH; + } + + stat->size = fatdir->size; + + //set created Date: Day, Month, Year + stat->ctime[4] = fatdir->cdate[0]; + stat->ctime[5] = fatdir->cdate[1]; + stat->ctime[6] = fatdir->cdate[2]; + stat->ctime[7] = fatdir->cdate[3]; + + //set created Time: Hours, Minutes, Seconds + stat->ctime[3] = fatdir->ctime[0]; + stat->ctime[2] = fatdir->ctime[1]; + stat->ctime[1] = fatdir->ctime[2]; + + //set accessed Date: Day, Month, Year + stat->atime[4] = fatdir->adate[0]; + stat->atime[5] = fatdir->adate[1]; + stat->atime[6] = fatdir->adate[2]; + stat->atime[7] = fatdir->adate[3]; + + //set modified Date: Day, Month, Year + stat->mtime[4] = fatdir->mdate[0]; + stat->mtime[5] = fatdir->mdate[1]; + stat->mtime[6] = fatdir->mdate[2]; + stat->mtime[7] = fatdir->mdate[3]; + + //set modified Time: Hours, Minutes, Seconds + stat->mtime[3] = fatdir->mtime[0]; + stat->mtime[2] = fatdir->mtime[1]; + stat->mtime[1] = fatdir->mtime[2]; +} + +/*************************************************************************************/ +/* File IO functions */ +/*************************************************************************************/ + +//--------------------------------------------------------------------------- +static fs_rec* fs_findFreeFileSlot(void) { + int i; + for (i = 0; i < MAX_FILES; i++) { + if (fsRec[i].dirent.file_flag < 0) { + return &fsRec[i]; + break; + } + } + return NULL; +} + +//--------------------------------------------------------------------------- +static fs_rec* fs_findFileSlotByCluster(unsigned int startCluster) { + int i; + + for (i = 0; i < MAX_FILES; i++) { + if (fsRec[i].dirent.file_flag >= 0 && fsRec[i].dirent.fatdir.startCluster == startCluster) { + return &fsRec[i]; + } + } + return NULL; +} + +//--------------------------------------------------------------------------- +static int _lock_sema_id = -1; + +//--------------------------------------------------------------------------- +static int _fs_init_lock(void) +{ +#ifndef WIN32 + iop_sema_t sp; + + sp.initial = 1; + sp.max = 1; + sp.option = 0; + sp.attr = 0; + if((_lock_sema_id = CreateSema(&sp)) < 0) { return(-1); } +#endif + + return(0); +} + +//--------------------------------------------------------------------------- +static void _fs_lock(void) +{ +#ifndef WIN32 + WaitSema(_lock_sema_id); +#endif +} + +//--------------------------------------------------------------------------- +static void _fs_unlock(void) +{ +#ifndef WIN32 + SignalSema(_lock_sema_id); +#endif +} + +//--------------------------------------------------------------------------- +static void fs_reset(void) +{ + int i; + for (i = 0; i < MAX_FILES; i++) { fsRec[i].dirent.file_flag = -1; } +#ifndef WIN32 + if(_lock_sema_id >= 0) { DeleteSema(_lock_sema_id); } +#endif + _fs_init_lock(); +} + +//--------------------------------------------------------------------------- +static int fs_inited = 0; + +//--------------------------------------------------------------------------- +static int fs_dummy(void) +{ + return -5; +} + +//--------------------------------------------------------------------------- +static int fs_init(iop_device_t *driver) +{ + if(!fs_inited) { + fs_reset(); + fs_inited = 1; + } + + return 1; +} + +//--------------------------------------------------------------------------- +static int fs_open(iop_file_t* fd, const char *name, int flags, int mode) { + fat_driver* fatd; + fs_rec* rec, *rec2; + int ret; + unsigned int cluster; + char escapeNotExist; + + _fs_lock(); + + XPRINTF("USBHDFSD: fs_open called: %s flags=%X mode=%X \n", name, flags, mode) ; + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + //check if the slot is free + rec = fs_findFreeFileSlot(); + if (rec == NULL) { _fs_unlock(); return -EMFILE; } + + //find the file + cluster = 0; //allways start from root + XPRINTF("USBHDFSD: Calling fat_getFileStartCluster from fs_open\n"); + ret = fat_getFileStartCluster(fatd, name, &cluster, &rec->dirent.fatdir); + if (ret < 0 && ret != -ENOENT) { + _fs_unlock(); + return ret; + }else{ + //File exists. Check if the file is already open + rec2 = fs_findFileSlotByCluster(rec->dirent.fatdir.startCluster); + if (rec2 != NULL) { + if ((flags & O_WRONLY) || //current file is opened for write + (rec2->mode & O_WRONLY) ) {//other file is opened for write + _fs_unlock(); + return -EACCES; + } + } + } + + if(flags & O_WRONLY) { //dlanor: corrected bad test condition + cluster = 0; //start from root + + escapeNotExist = 1; + if (flags & O_CREAT) { + XPRINTF("USBHDFSD: FAT I: O_CREAT detected!\n"); + escapeNotExist = 0; + } + + rec->sfnSector = 0; + rec->sfnOffset = 0; + ret = fat_createFile(fatd, name, 0, escapeNotExist, &cluster, &rec->sfnSector, &rec->sfnOffset); + if (ret < 0) { + _fs_unlock(); + return ret; + } + //the file already exist but flags is set to truncate + if (ret == 2 && (flags & O_TRUNC)) { + XPRINTF("USBHDFSD: FAT I: O_TRUNC detected!\n"); + fat_truncateFile(fatd, cluster, rec->sfnSector, rec->sfnOffset); + } + + //find the file + cluster = 0; //allways start from root + XPRINTF("USBHDFSD: Calling fat_getFileStartCluster from fs_open after file creation\n"); + ret = fat_getFileStartCluster(fatd, name, &cluster, &rec->dirent.fatdir); + } + + if (ret < 0) { //At this point, the file should be locatable without any errors. + _fs_unlock(); + return ret; + } + + if ((rec->dirent.fatdir.attr & FAT_ATTR_DIRECTORY) == FAT_ATTR_DIRECTORY) { + // Can't open a directory with open + _fs_unlock(); + return -EISDIR; + } + + rec->dirent.file_flag = FS_FILE_FLAG_FILE; + rec->mode = flags; + rec->filePos = 0; + rec->sizeChange = 0; + + if ((flags & O_APPEND) && (flags & O_WRONLY)) { + XPRINTF("USBHDFSD: FAT I: O_APPEND detected!\n"); + rec->filePos = rec->dirent.fatdir.size; + } + + //store the slot to user parameters + fd->privdata = rec; + + _fs_unlock(); + return 1; +} + +//--------------------------------------------------------------------------- +static int fs_close(iop_file_t* fd) { + fat_driver* fatd; + fs_rec* rec = (fs_rec*)fd->privdata; + + if (rec == NULL) + return -EBADF; + + _fs_lock(); + + if (rec->dirent.file_flag != FS_FILE_FLAG_FILE) { + _fs_unlock(); + return -EISDIR; + } + + rec->dirent.file_flag = -1; + fd->privdata = NULL; + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + if ((rec->mode & O_WRONLY)) { + //update direntry size and time + if (rec->sizeChange) { + fat_updateSfn(fatd, rec->dirent.fatdir.size, rec->sfnSector, rec->sfnOffset); + } + + FLUSH_SECTORS(fatd); + } + + _fs_unlock(); + return 0; +} + +//--------------------------------------------------------------------------- +static int fs_lseek(iop_file_t* fd, int offset, int whence) { + fat_driver* fatd; + fs_rec* rec = (fs_rec*)fd->privdata; + + if (rec == NULL) + return -EBADF; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + if (rec->dirent.file_flag != FS_FILE_FLAG_FILE) { + _fs_unlock(); + return -EISDIR; + } + + switch(whence) { + case SEEK_SET: + rec->filePos = offset; + break; + case SEEK_CUR: + rec->filePos += offset; + break; + case SEEK_END: + rec->filePos = rec->dirent.fatdir.size + offset; + break; + default: + _fs_unlock(); + return -1; + } + if (rec->filePos < 0) { + rec->filePos = 0; + } + if (rec->filePos > rec->dirent.fatdir.size) { + rec->filePos = rec->dirent.fatdir.size; + } + + _fs_unlock(); + return rec->filePos; +} + +//--------------------------------------------------------------------------- +static int fs_write(iop_file_t* fd, void * buffer, int size ) +{ + fat_driver* fatd; + fs_rec* rec = (fs_rec*)fd->privdata; + int result; + int updateClusterIndices = 0; + + if (rec == NULL) + return -EBADF; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + if (rec->dirent.file_flag != FS_FILE_FLAG_FILE) { + _fs_unlock(); + return -EISDIR; + } + + if (!(rec->mode & O_WRONLY)) { + _fs_unlock(); + return -EACCES; + } + + if (size <= 0) { _fs_unlock(); return 0; } + + result = fat_writeFile(fatd, &rec->dirent.fatdir, &updateClusterIndices, rec->filePos, buffer, size); + if (result > 0) { //write succesful + rec->filePos += result; + if (rec->filePos > rec->dirent.fatdir.size) { + rec->dirent.fatdir.size = rec->filePos; + rec->sizeChange = 1; + //if new clusters allocated - then update file cluster indices + if (updateClusterIndices) { + fat_setFatDirChain(fatd, &rec->dirent.fatdir); + } + } + } + + _fs_unlock(); + return result; +} + +//--------------------------------------------------------------------------- +static int fs_read(iop_file_t* fd, void * buffer, int size ) { + fat_driver* fatd; + fs_rec* rec = (fs_rec*)fd->privdata; + int result; + + if (rec == NULL) + return -EBADF; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + if (rec->dirent.file_flag != FS_FILE_FLAG_FILE) { + _fs_unlock(); + return -EISDIR; + } + + if (!(rec->mode & O_RDONLY)) { + _fs_unlock(); + return -EACCES; + } + + if (size<=0) { + _fs_unlock(); + return 0; + } + + if ((rec->filePos+size) > rec->dirent.fatdir.size) { + size = rec->dirent.fatdir.size - rec->filePos; + } + + result = fat_readFile(fatd, &rec->dirent.fatdir, rec->filePos, buffer, size); + if (result > 0) { //read succesful + rec->filePos += result; + } + + _fs_unlock(); + return result; +} + +//--------------------------------------------------------------------------- +static int fs_remove(iop_file_t *fd, const char *name) { + fat_driver* fatd; + fs_rec* rec; + int result; + unsigned int cluster; + fat_dir fatdir; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) + { + result = -ENODEV; + _fs_unlock(); + return result; + } + + cluster = 0; //allways start from root + XPRINTF("USBHDFSD: Calling fat_getFileStartCluster from fs_remove\n"); + result = fat_getFileStartCluster(fatd, name, &cluster, &fatdir); + if (result < 0) { + _fs_unlock(); + return result; + } + + rec = fs_findFileSlotByCluster(fatdir.startCluster); + + //file is opened - can't delete the file + if (rec != NULL) { + result = -EINVAL; + _fs_unlock(); + return result; + } + + result = fat_deleteFile(fatd, name, 0); + FLUSH_SECTORS(fatd); + + _fs_unlock(); + return result; +} + +//--------------------------------------------------------------------------- +static int fs_mkdir(iop_file_t *fd, const char *name, int mode) { + fat_driver* fatd; + int ret; + int sfnOffset; + unsigned int sfnSector; + unsigned int cluster; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + XPRINTF("USBHDFSD: fs_mkdir: name=%s \n",name); + ret = fat_createFile(fatd, name, 1, 0, &cluster, &sfnSector, &sfnOffset); + + //directory of the same name already exist + if (ret == 2) { + ret = -EEXIST; + } + FLUSH_SECTORS(fatd); + + _fs_unlock(); + return ret; +} + +//--------------------------------------------------------------------------- +static int fs_rmdir(iop_file_t *fd, const char *name) { + fat_driver* fatd; + int ret; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + ret = fat_deleteFile(fatd, name, 1); + FLUSH_SECTORS(fatd); + _fs_unlock(); + return ret; +} + +//--------------------------------------------------------------------------- +static int fs_dopen(iop_file_t *fd, const char *name) +{ + fat_driver* fatd; + int is_root = 0; + fs_dir* rec; + + _fs_lock(); + + XPRINTF("USBHDFSD: fs_dopen called: unit %d name %s\n", fd->unit, name); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + if( ((name[0] == '/') && (name[1] == '\0')) + ||((name[0] == '/') && (name[1] == '.') && (name[2] == '\0'))) + { + name = "/"; + is_root = 1; + } + + fd->privdata = malloc(sizeof(fs_dir)); + memset(fd->privdata, 0, sizeof(fs_dir)); //NB: also implies "file_flag = FS_FILE_FLAG_FOLDER;" + rec = (fs_dir *) fd->privdata; + + rec->status = fat_getFirstDirentry(fatd, name, &rec->fatdlist, &rec->dirent.fatdir, &rec->current_fatdir); + + // root directory may have no entries, nothing else may. + if(rec->status == 0 && !is_root) + rec->status = -EFAULT; + + if (rec->status < 0) + free(fd->privdata); + + _fs_unlock(); + return rec->status; +} + +//--------------------------------------------------------------------------- +static int fs_dclose(iop_file_t *fd) +{ + fs_dir *rec = (fs_dir*)fd->privdata; + + if (fd->privdata == NULL) + return -EBADF; + + _fs_lock(); + XPRINTF("USBHDFSD: fs_dclose called: unit %d\n", fd->unit); + if (rec->dirent.file_flag != FS_FILE_FLAG_FOLDER) { + _fs_unlock(); + return -ENOTDIR; + } + + free(fd->privdata); + fd->privdata = NULL; + _fs_unlock(); + return 0; +} + +//--------------------------------------------------------------------------- +static int fs_dread(iop_file_t *fd, iox_dirent_t *buffer) +{ + fat_driver* fatd; + int ret; + fs_dir* rec = (fs_dir *) fd->privdata; + + if (rec == NULL) + return -EBADF; + + _fs_lock(); + + XPRINTF("USBHDFSD: fs_dread called: unit %d\n", fd->unit); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + if (rec->dirent.file_flag != FS_FILE_FLAG_FOLDER) { + _fs_unlock(); + return -ENOTDIR; + } + + while (rec->status > 0 + && (rec->current_fatdir.attr & FAT_ATTR_VOLUME_LABEL + || ((rec->current_fatdir.attr & (FAT_ATTR_HIDDEN | FAT_ATTR_SYSTEM)) == (FAT_ATTR_HIDDEN | FAT_ATTR_SYSTEM)))) + rec->status = fat_getNextDirentry(fatd, &rec->fatdlist, &rec->current_fatdir); + + ret = rec->status; + if (rec->status >= 0) + { + memset(buffer, 0, sizeof(iox_dirent_t)); + fillStat(&buffer->stat, &rec->current_fatdir); + strcpy(buffer->name, (const char*)rec->current_fatdir.name); + } + + if (rec->status > 0) + rec->status = fat_getNextDirentry(fatd, &rec->fatdlist, &rec->current_fatdir); + + _fs_unlock(); + return ret; +} + +//--------------------------------------------------------------------------- +static int fs_getstat(iop_file_t *fd, const char *name, iox_stat_t *stat) +{ + fat_driver* fatd; + int ret; + unsigned int cluster = 0; + fat_dir fatdir; + + _fs_lock(); + + XPRINTF("USBHDFSD: fs_getstat called: unit %d name %s\n", fd->unit, name); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + XPRINTF("USBHDFSD: Calling fat_getFileStartCluster from fs_getstat\n"); + ret = fat_getFileStartCluster(fatd, name, &cluster, &fatdir); + if (ret < 0) { + _fs_unlock(); + return ret; + } + + memset(stat, 0, sizeof(iox_stat_t)); + fillStat(stat, &fatdir); + + _fs_unlock(); + return 0; +} + +//--------------------------------------------------------------------------- +int fs_ioctl(iop_file_t *fd, int cmd, void *data) +{ + fat_driver* fatd; + struct fs_dirent* dirent = (struct fs_dirent *) fd->privdata; //Remember to re-cast this to the right structure (either fs_rec or fs_dir)! + int ret; + + if (dirent == NULL) + return -EBADF; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { _fs_unlock(); return -ENODEV; } + + switch (cmd) { + case USBMASS_IOCTL_RENAME: + ret = fat_renameFile(fatd, &dirent->fatdir, data); //No need to re-cast since this inner structure is a common one. + FLUSH_SECTORS(fatd); + break; + default: + ret = fs_dummy(); + } + + _fs_unlock(); + return ret; +} + +int fs_rename(iop_file_t *fd, const char *path, const char *newpath) +{ + fat_dir fatdir; + fat_driver *fatd; + fs_rec *rec = NULL; + unsigned int cluster; + struct fs_dirent *dirent = (struct fs_dirent *)fd->privdata; + int ret; + + if (dirent == NULL) + return -EBADF; + + _fs_lock(); + + fatd = fat_getData(fd->unit); + if (fatd == NULL) { + _fs_unlock(); + return -ENODEV; + } + + //find the file + cluster = 0; //allways start from root + XPRINTF("USBHDFSD: Calling fat_getFileStartCluster from fs_rename\n"); + ret = fat_getFileStartCluster(fatd, path, &cluster, &fatdir); + if (ret < 0 && ret != -ENOENT) { + _fs_unlock(); + return ret; + } else { + //File exists. Check if the file is already open + rec = fs_findFileSlotByCluster(fatdir.startCluster); + if (rec != NULL) { + _fs_unlock(); + return -EACCES; + } + } + + ret = fat_renameFile(fatd, &fatdir, newpath); + FLUSH_SECTORS(fatd); + + _fs_unlock(); + return ret; +} + +#ifndef WIN32 +static iop_device_ops_t fs_functarray={ + &fs_init, + (void*)&fs_dummy, + (void*)&fs_dummy, + &fs_open, + &fs_close, + &fs_read, + &fs_write, + &fs_lseek, + &fs_ioctl, + &fs_remove, + &fs_mkdir, + &fs_rmdir, + &fs_dopen, + &fs_dclose, + &fs_dread, + &fs_getstat, + (void*)&fs_dummy, + &fs_rename, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, + (void*)&fs_dummy, +}; +static iop_device_t fs_driver={ + "sd", + IOP_DT_FS | IOP_DT_FSEXT, + 2, + "IEEE1394_disk", + &fs_functarray +}; + +/* init file system driver */ +int InitFS(void) +{ + DelDrv("sd"); + return(AddDrv(&fs_driver) == 0 ? 0 : -1); +} +#endif + +//--------------------------------------------------------------------------- +//End of file: fs_driver.c +//--------------------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/imports.lst new file mode 100644 index 0000000..f8546c2 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/imports.lst @@ -0,0 +1,88 @@ +cdvdman_IMPORTS_start +I_sceCdReadClock +cdvdman_IMPORTS_end + +iLinkman_IMPORTS_start +I_iLinkEnableSBus +I_iLinkResetSBus +I_iLinkSetNodeCapabilities +I_iLinkSetTrCallbackHandler +I_iLinkGetGenerationNumber +I_iLinkGetLocalNodeID +I_iLinkGetNodeCount +I_iLinkTrAlloc +I_iLinkTrFree +I_iLinkTrWrite +I_iLinkTrRead +I_iLinkGetNodeMaxSpeed +I_iLinkGetNodeTrSpeed +I_iLinkSetNodeTrSpeed +I_iLinkFindUnit +I_iLinkReadCROM +iLinkman_IMPORTS_end + +ioman_IMPORTS_start +I_open +I_close +I_read +I_lseek +I_AddDrv +I_DelDrv +ioman_IMPORTS_end + +intrman_IMPORTS_start +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_toupper +I_memset +I_memcmp +I_memcpy +I_strlen +I_strcpy +I_strncpy +I_strtol +I_strrchr +I_sprintf +sysclib_IMPORTS_end + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +I_Kprintf +sysmem_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_StartThread +I_DelayThread +I_GetSystemTime +I_SysClock2USec +I_USec2SysClock +I_SetAlarm +I_CancelAlarm +I_TerminateThread +I_DeleteThread +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_ClearEventFlag +I_SetEventFlag +I_iSetEventFlag +I_WaitEventFlag +I_DeleteEventFlag +thevent_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_WaitSema +I_SignalSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/fat.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/fat.h new file mode 100644 index 0000000..c24e9e5 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/fat.h @@ -0,0 +1,154 @@ +/* + * fat.h - USB Mass storage driver for PS2 + * + * (C) 2004, Marek Olejnik (ole00@post.cz) + * + * FAT helper structures + * + * See the file LICENSE included with this distribution for licensing terms. + */ + +/* + FAT References: http://www.igd.fhg.de/~aschaefe/fips/distrib/techinfo.txt + : http://home.freeuk.net/foxy2k/disk/disk1.htm +*/ + +#ifndef _FAT_H +#define _FAT_H 1 + +#define FAT12 0x0C +#define FAT16 0x10 +#define FAT32 0x20 + +#define FAT_MAX_PATH 260 + +/* bios parameter block - bpb - fat12, fat16 */ +typedef struct _fat_raw_bpb { + unsigned char jump[3]; //jump instruction ('eb xx 90' or 'e9 xx xx') + unsigned char oem[8]; //OEM name and version - e.g. MSDOS5.0 + unsigned char sectorSize[2]; //bytes per sector - should be 512 + unsigned char clusterSize; //sectors per cluster - power of two + unsigned char resSectors[2]; //reserved sectors - typically 1 (boot sector) + unsigned char fatCount; //number of FATs - must be 2 + unsigned char rootSize[2]; //number of rootdirectory entries - typically 512 + unsigned char sectorCountO[2]; //number of sectors (short) - 0, if BIGDOS partition + unsigned char mediaDesc; //media descriptor - typically f8h + unsigned char fatSize[2]; //sectors per FAT - varies + unsigned char trackSize[2]; //sectors per track + unsigned char headCount[2]; //number of heads + unsigned char hiddenCountL[2]; //number of hidden sectors (low) + + unsigned char hiddenCountH[2]; //number of hidden sectors (high) + unsigned char sectorCount[4]; //number of sectors + + /* extended BPB since DOS 4.0 */ + unsigned char driveNumber; //physical drive number - 80h or 81h + unsigned char reserved; //Current head (not used for this but WinNT stores two flags here). + unsigned char signature; //Signature (must be 28h or 29h to be recognised by NT). + unsigned char serialNumber[4]; //The serial number, the serial number is stored in reverse + //order and is the hex representation of the bytes stored here + unsigned char volumeLabel[11]; //Volume label + unsigned char fatId[8]; //File system ID. "FAT12", "FAT16" or "FAT " +} fat_raw_bpb; + +/* bios parameter block - bpb - fat32 */ +typedef struct _fat32_raw_bpb { + unsigned char jump[3]; //jump instruction ('eb xx 90' or 'e9 xx xx') + unsigned char oem[8]; //OEM name and version - e.g. MSDOS5.0 + unsigned char sectorSize[2]; //bytes per sector - should be 512 + unsigned char clusterSize; //sectors per cluster - power of two + unsigned char resSectors[2]; //reserved sectors - typically 1 (boot sector) + unsigned char fatCount; //number of FATs - must be 2 + unsigned char rootSize[2]; //number of rootdirectory entries - typically 512 + unsigned char sectorCountO[2]; //number of sectors (short) - 0, if BIGDOS partition + unsigned char mediaDesc; //media descriptor - typically f8h + unsigned char fatSize[2]; //sectors per FAT - varies + unsigned char trackSize[2]; //sectors per track + unsigned char headCount[2]; //number of heads + unsigned char hiddenCountL[2]; //number of hidden sectors (low) + + unsigned char hiddenCountH[2]; //number of hidden sectors (high) + unsigned char sectorCount[4]; //number of sectors + + /* fat32 specific */ + unsigned char fatSize32[4]; //FAT32 sectors per FAT + unsigned char fatStatus[2]; //If bit 7 is clear then all FAT's are updated other wise bits 0-3 + //give the current active FAT, all other bits are reserved. + unsigned char revision[2]; //High byte is major revision number, low byte is minor revision number, currently both are 0 + unsigned char rootDirCluster[4];//Root directory starting cluster + unsigned char fsInfoSector[2]; //File system information sector. + unsigned char bootSectorCopy[2];//If non-zero this gives the sector which holds a copy of the boot record, usually 6 + unsigned char reserved1[12]; //Reserved, set to 0. + unsigned char pdn; //Physical drive number (BIOS system ie 80h is first HDD, 00h is first FDD) + unsigned char reserved2; //Reserved + unsigned char signature; //Signature (must be 28h or 29h to be recognised by NT) + unsigned char serialNumber[4]; //The serial number, the serial number is stored in reverse + //order and is the hex representation of the bytes stored here + unsigned char volumeLabel[11]; //Volume label + unsigned char fatId[8]; //File system ID. "FAT12", "FAT16" or "FAT " + unsigned char machineCode[8]; //Machine code + unsigned char bootSignature[2]; //Boot Signature AA55h. +} fat32_raw_bpb; + +/* directory entry of the short file name */ +typedef struct _fat_direntry_sfn { + unsigned char name[8]; //Filename padded with spaces if required. + unsigned char ext[3]; //Filename extension padded with spaces if required. + unsigned char attr; //File Attribute Byte. + + unsigned char reservedNT; //Reserved for use by Windows NT. + unsigned char seconds; //Tenths of a second at time of file creation, 0-199 is valid. + unsigned char timeCreate[2]; //Time when file was created. + unsigned char dateCreate[2]; //Date when file was created. + unsigned char dateAccess[2]; //Date when file was last accessed. + unsigned char clusterH[2]; //High word of cluster number (EA index for FAT12 and FAT16). + + unsigned char timeWrite[2]; //Time of last write to file (last modified or when created). + unsigned char dateWrite[2]; //Date of last write to file (last modified or when created). + unsigned char clusterL[2]; //Starting cluster (Low word). + unsigned char size[4]; //File size (set to zero if a directory). +} fat_direntry_sfn; + +/* directory entry of the long file name + + Each LFN directory entry holds 13 characters of the complete LFN using 16-bit Unicode characters. +*/ +typedef struct _fat_direntry_lfn { + unsigned char entrySeq; //Bits 0-5 give the LFN part number, bit 6 is set if this is the last entry for the file. + unsigned char name1[10]; //1st 5 letters of LFN entry. + unsigned char rshv; //?? 0Fh (RSHV attributes set) + + unsigned char reserved1; //Reserved set to 0. + unsigned char checksum; //Checksum generated from SFN. + unsigned char name2[12]; //Next 6 letters of LFN entry. + + unsigned char reserved2[2]; //Reserved set to 0. + unsigned char name3[4]; //Last 2 letters of LFN entry. +} fat_direntry_lfn; + +typedef union _fat_direntry { + fat_direntry_sfn sfn; + fat_direntry_lfn lfn; +} fat_direntry; + +typedef struct _fat_direntry_summary { + unsigned char attr; //Attributes (bits:5-Archive 4-Directory 3-Volume Label 2-System 1-Hidden 0-Read Only) + char name[FAT_MAX_NAME]; //Long name (zero terminated) + char sname[13]; //Short name (zero terminated) + unsigned int size; //file size, 0 for directory + unsigned int cluster; //file start cluster +} fat_direntry_summary; + +//--------------------------------------------------------------------------- +static USBHD_INLINE unsigned int fat_cluster2sector(fat_bpb* partBpb, unsigned int cluster) +{ + return partBpb->dataStart + (partBpb->clusterSize * (cluster-2)); +} + +unsigned int fat_getClusterRecord12(unsigned char* buf, int type); +int fat_getDirentry(unsigned char fatType, fat_direntry* dir_entry, fat_direntry_summary* dir ); +int fat_getDirentrySectorData(fat_driver* fatd, unsigned int* startCluster, unsigned int* startSector, unsigned int* dirSector); +void fat_invalidateLastChainResult(fat_driver* fatd); +void fat_getClusterAtFilePos(fat_driver* fatd, fat_dir* fatDir, unsigned int filePos, unsigned int* cluster, unsigned int* clusterPos); + +#endif /* _FAT_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/fat_driver.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/fat_driver.h new file mode 100644 index 0000000..110dc78 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/fat_driver.h @@ -0,0 +1,105 @@ +#ifndef _FAT_DRIVER_H +#define _FAT_DRIVER_H 1 + +#define DIR_CHAIN_SIZE 32 + +#define FAT_MAX_NAME 256 + +//attributes (bits:5-Archive 4-Directory 3-Volume Label 2-System 1-Hidden 0-Read Only) +#define FAT_ATTR_READONLY 0x01 +#define FAT_ATTR_HIDDEN 0x02 +#define FAT_ATTR_SYSTEM 0x04 +#define FAT_ATTR_VOLUME_LABEL 0x08 +#define FAT_ATTR_DIRECTORY 0x10 +#define FAT_ATTR_ARCHIVE 0x20 + +typedef struct _fat_bpb { + unsigned int sectorSize; //bytes per sector - should be 512 + unsigned char clusterSize; //sectors per cluster - power of two + unsigned int resSectors; //reserved sectors - typically 1 (boot sector) + unsigned char fatCount; //number of FATs - must be 2 + unsigned int rootSize; //number of rootdirectory entries - typically 512 + unsigned int fatSize; //sectors per FAT - varies + unsigned int trackSize; //sectors per track + unsigned int headCount; //number of heads + unsigned int sectorCount; //number of sectors + unsigned int partStart; //sector where partition starts (boot sector) + unsigned int rootDirStart; //sector where root directory starts + unsigned int rootDirCluster; //fat32 - cluster of the root directory + unsigned int activeFat; //fat32 - current active fat number + unsigned char fatType; //12-FAT16, 16-FAT16, 32-FAT32 + unsigned char fatId[9]; //File system ID. "FAT12", "FAT16" or "FAT " - for debug only + unsigned int dataStart; //sector where data starts +} fat_bpb; + +typedef struct _fat_driver { + struct SBP2Device* dev; + fat_bpb partBpb; //partition bios parameter block + + // modified by Hermes +#define MAX_DIR_CLUSTER 512 + unsigned int cbuf[MAX_DIR_CLUSTER]; //cluster index buffer // 2048 by Hermes + + unsigned int lastChainCluster; + int lastChainResult; + +/* enough for long filename of length 260 characters (20*13) and one short filename */ +#define MAX_DE_STACK 21 + unsigned int deSec[MAX_DE_STACK]; //direntry sector + int deOfs[MAX_DE_STACK]; //direntry offset + int deIdx; //direntry index + +#define SEQ_MASK_SIZE 2048 //Allow 2K files per directory + u8 seq_mask[SEQ_MASK_SIZE/8]; //bitmask for consumed seq numbers +#define DIR_MASK_SIZE 2048*11 //Allow 2K maxed fullnames per directory + u8 dir_used_mask[DIR_MASK_SIZE/8]; //bitmask for used directory entries + +#define MAX_CLUSTER_STACK 128 + unsigned int clStack[MAX_CLUSTER_STACK]; //cluster allocation stack + int clStackIndex; + unsigned int clStackLast; // last free cluster of the fat table +} fat_driver; + +typedef struct _fat_dir_list { + unsigned int direntryCluster; //the directory cluster requested by getFirstDirentry + int direntryIndex; //index of the directory children +} fat_dir_list; + +typedef struct _fat_dir_chain_record { + unsigned int cluster; + unsigned int index; +} fat_dir_chain_record; + +typedef struct _fat_dir { + unsigned char attr; //attributes (bits:5-Archive 4-Directory 3-Volume Label 2-System 1-Hidden 0-Read Only) + char name[FAT_MAX_NAME]; + unsigned char cdate[4]; //D:M:Yl:Yh + unsigned char ctime[3]; //H:M:S + unsigned char adate[4]; //D:M:Yl:Yh + unsigned char atime[3]; //H:M:S + unsigned char mdate[4]; //D:M:Yl:Yh + unsigned char mtime[3]; //H:M:S + unsigned int size; //file size, 0 for directory + unsigned int parentDirCluster; //The cluster number of the parent directory. + unsigned int startCluster; + //Stuff here are used for caching and might not be filled. + unsigned int lastCluster; + fat_dir_chain_record chain[DIR_CHAIN_SIZE]; //cluser/offset cache - for seeking purpose +} fat_dir; + +int InitFAT(void); +int strEqual(const char *s1, const char* s2); + +int fat_mount(struct SBP2Device* dev, unsigned int start, unsigned int count); +void fat_forceUnmount(struct SBP2Device* dev); +void fat_setFatDirChain(fat_driver* fatd, fat_dir* fatDir); +int fat_readFile(fat_driver* fatd, fat_dir* fatDir, unsigned int filePos, unsigned char* buffer, unsigned int size); +int fat_getFirstDirentry(fat_driver* fatd, const char* dirName, fat_dir_list* fatdlist, fat_dir *fatDir_host, fat_dir* fatDir); +int fat_getNextDirentry(fat_driver* fatd, fat_dir_list* fatdlist, fat_dir* fatDir); + +fat_driver * fat_getData(int device); +int fat_getFileStartCluster(fat_driver* fatd, const char* fname, unsigned int* startCluster, fat_dir* fatDir); +int fat_getClusterChain(fat_driver* fatd, unsigned int cluster, unsigned int* buf, unsigned int bufSize, int startFlag); + +#endif + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/fat_write.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/fat_write.h new file mode 100644 index 0000000..f75ee39 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/fat_write.h @@ -0,0 +1,14 @@ +#ifndef _FAT_WRITE_H +#define _FAT_WRITE_H 1 + +int fat_createFile(fat_driver* fatd, const char* fname, char directory, char escapeNotExist, unsigned int* cluster, unsigned int* sfnSector, int* sfnOffset); +int fat_deleteFile(fat_driver* fatd, const char* fname, char directory); +int fat_truncateFile(fat_driver* fatd, unsigned int cluster, unsigned int sfnSector, int sfnOffset); +int fat_renameFile(fat_driver* fatd, fat_dir *fatdir, const char* fname); +int fat_writeFile(fat_driver* fatd, fat_dir* fatDir, int* updateClusterIndices, unsigned int filePos, unsigned char* buffer, int size) ; +int fat_updateSfn(fat_driver* fatd, int size, unsigned int sfnSector, int sfnOffset); + +int fat_allocSector(fat_driver* fatd, unsigned int sector, unsigned char** buf); +int fat_writeSector(fat_driver* fatd, unsigned int sector); +int fat_flushSectors(fat_driver* fatd); +#endif /* _FAT_WRITE_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/mass_debug.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/mass_debug.h new file mode 100644 index 0000000..dd9808c --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/mass_debug.h @@ -0,0 +1,12 @@ +#ifndef _MASS_DEBUG_H +#define _MASS_DEBUG_H 1 + +#ifdef DEBUG +#define XPRINTF(args...) printf(args) +#define iXPRINTF(args...) Kprintf(args) +#else +#define XPRINTF(args...) +#define iXPRINTF(args...) +#endif + +#endif /* _MASS_DEBUG_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/part_driver.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/part_driver.h new file mode 100644 index 0000000..1b37403 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/part_driver.h @@ -0,0 +1,8 @@ +#ifndef _PART_DRIVER_H +#define _PART_DRIVER_H 1 + +int part_connect(struct SBP2Device* dev); +void part_disconnect(struct SBP2Device* dev); + +#endif + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/sbp2_disk.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/sbp2_disk.h new file mode 100644 index 0000000..3f7ecc5 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/sbp2_disk.h @@ -0,0 +1,125 @@ +/* Event flag bits. */ +#define WRITE_REQ_INCOMING 1 +#define READ_REQ_INCOMING 2 +#define BUS_RESET_COMPLETE 4 +#define ERROR_TIME_OUT 8 + +/* Management ORB opcodes */ +#define SBP2_LOGIN_REQUEST 0x0 +#define SBP2_QUERY_LOGINS_REQUEST 0x1 +#define SBP2_RECONNECT_REQUEST 0x3 +#define SBP2_SET_PASSWORD_REQUEST 0x4 +#define SBP2_LOGOUT_REQUEST 0x7 +#define SBP2_ABORT_TASK_REQUEST 0xb +#define SBP2_ABORT_TASK_SET 0xc +#define SBP2_LOGICAL_UNIT_RESET 0xe +#define SBP2_TARGET_RESET_REQUEST 0xf + +/* Configuration ROM keys */ +#define IEEE1394_CROM_LOGICAL_UNIT_NUM 0x14 +#define IEEE1394_CROM_UNIT_CHARA 0x3A +#define IEEE1394_CROM_CSR_OFFSET 0x54 +#define IEEE1394_CROM_UNIT_DIRECTORY 0xD1 + +/* Some macros. */ +#define MANAGEMENT_ORB_LOGINID(v) ((v)) +#define MANAGEMENT_ORB_LUN(v) ((v)) +#define MANAGEMENT_ORB_FUNCTION(v) ((v) << 16) +#define MANAGEMENT_ORB_RECONNECT(v) ((v) << 20) +#define MANAGEMENT_ORB_EXCLUSIVE(v) ((v) ? 1 << 28 : 0) + +#define ORB_REQUEST_FORMAT(v) ((v) << 29) +#define ORB_NOTIFY ((1) << 31) + +#define MANAGEMENT_ORB_RESPONSE_LENGTH(v) ((v)&0x0000FFFF) +#define MANAGEMENT_ORB_PASSWORD_LENGTH(v) ((v) << 16) + +#define NULL_POINTER (1<<15) + +#define RESP_SBP_STATUS(v) (((v)>>16)&0xFF) +#define RESP_LEN(v) (((v)>>24)&0x07) +#define RESP_DEAD(v) (((v)>>27)&0x01) +#define RESP_RESP(v) (((v)>>28)&0x03) +#define RESP_SRC(v) (((v)>>30)&0x03) + +struct sbp2_status{ + u32 status; + u32 ORB_low; + u8 data[24]; +}__attribute__((packed)); + +struct sbp2_pointer{ + u16 high; /* Big endian. */ + u16 NodeID; /* Big endian. */ + u32 low; /* Big endian. */ +}__attribute__((packed)); + +struct sbp2_ORB_pointer{ + u16 high; /* Big endian. */ + u16 reserved; /* Big endian. */ + u32 low; /* Big endian. */ +}__attribute__((packed)); + +struct sbp2_login_response { + u16 login_ID; /* Big endian. */ + u16 length; /* Big endian. */ + + struct sbp2_pointer command_block_agent; + u32 reconnect_hold; /* Big endian. */ +}__attribute__((packed)); + +struct management_ORB{ + union { + u32 function_data[4]; + struct { + struct sbp2_pointer password; + struct sbp2_pointer response; + } login; + }; + u32 flags; + union { + u32 function_data2; + u32 length; + }; + struct sbp2_pointer status_FIFO; +}__attribute__((packed)); + +struct CommandDescriptorBlock{ + struct sbp2_ORB_pointer NextOrb; + struct sbp2_pointer DataDescriptor; + + u32 misc; + unsigned char CDBs[12]; +}__attribute__((packed)); + +struct SBP2Device +{ + int trContext; + unsigned short int nodeID; + unsigned short int InitiatorNodeID; + unsigned short int max_payload; + unsigned short int LUN; + + unsigned short int loginID; /* Stored in big endian. */ + + unsigned char IsConnected; + unsigned char mgt_ORB_timeout; + unsigned char ORB_size; + unsigned char speed; + + unsigned long int ManagementAgent_high; + unsigned long int ManagementAgent_low; + + unsigned long int CommandBlockAgent_high; + unsigned long int CommandBlockAgent_low; + + unsigned long int sectorSize; + unsigned long int maxLBA; + void *cache; +}; + +/* Function prototypes. */ +void init_ieee1394DiskDriver(void); +int ieee1394_SendCommandBlockORB(struct SBP2Device *dev, struct CommandDescriptorBlock *firstCDB); +int ieee1394_Sync(void); +void DeinitIEEE1394(void); diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/scache.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/scache.h new file mode 100644 index 0000000..0972246 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/scache.h @@ -0,0 +1,46 @@ +#ifndef _SCACHE_H +#define _SCACHE_H 1 + +#define BLOCK_SIZE 16384 + +//number of cache slots (1 slot = block) +#define CACHE_SIZE 32 + +//when the flushCounter reaches FLUSH_TRIGGER then flushSectors is called +//#define FLUSH_TRIGGER 16 + +typedef struct _cache_record +{ + unsigned int sector; + int tax; + char writeDirty; +} cache_record; + +struct _cache_set +{ + struct SBP2Device* dev; + int sectorSize; + int indexLimit; + unsigned char* sectorBuf; // = NULL; //sector content - the cache buffer + cache_record rec[CACHE_SIZE]; //cache info record + + //statistical infos + unsigned int cacheAccess; + unsigned int cacheHits; + unsigned int writeFlag; + //unsigned int flushCounter; + + //unsigned int cacheDumpCounter = 0; +}; + +cache_set* scache_init(struct SBP2Device* dev, int sectorSize); +void scache_close(cache_set* cache); +void scache_kill(cache_set* cache); //dlanor: added for disconnection events (flush impossible) +int scache_allocSector(cache_set* cache, unsigned int sector, void** buf); +int scache_readSector(cache_set* cache, unsigned int sector, void** buf); +int scache_writeSector(cache_set* cache, unsigned int sector); +int scache_flushSectors(cache_set* cache); + +void scache_getStat(cache_set* cache, unsigned int* access, unsigned int* hits); + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/scsi.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/scsi.h new file mode 100644 index 0000000..d74e3cc --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/scsi.h @@ -0,0 +1,49 @@ +#define XFER_BLOCK_SIZE 65024 /* 65536-512. It seems like my Oxford 934 is capable of maximum transfers of less than 65536 bytes. + NOTE: I reduced the maximum block size here by 512, since transfers are done in (smallest) groups of 512 bytes! + */ + +#define READ_TRANSACTION 0 +#define WRITE_TRANSACTION 1 + +/* Some macros */ +#define CDB_PAGE_SIZE(v) ((v) << 16) /* Not in use. */ +#define CDB_PAGE_TABLE_PRESENT(v) ((v) << 19) /* Not in use. */ +#define CDB_MAX_PAYLOAD(v) ((v) << 20) +#define CDB_SPEED(v) ((v) << 24) +#define CDB_DIRECTION(v) ((v) << 27) +#define CDB_DATA_SIZE(v) ((v)) + +typedef struct _inquiry_data { + u8 peripheral_device_type; // 00h - Direct access (Floppy), 1Fh none (no FDD connected) + u8 removable_media; // 80h - removeable + u8 iso_ecma_ansi; + u8 repsonse_data_format; + u8 additional_length; + u8 res[3]; + u8 vendor[8]; + u8 product[16]; + u8 revision[4]; +} inquiry_data; + +typedef struct _sense_data { + u8 error_code; + u8 res1; + u8 sense_key; + u8 information[4]; + u8 add_sense_len; + u8 res3[4]; + u8 add_sense_code; + u8 add_sense_qual; + u8 res4[4]; +} sense_data; + +typedef struct _read_capacity_data { + u32 last_lba; /* Big endian data. */ + u32 block_length; /* Big endian data. */ +} read_capacity_data; + +/* Function prototypes. */ +int scsiReadSector(struct SBP2Device *dev, unsigned long int lba, void *buffer, int sectorCount); +int scsiWriteSector(struct SBP2Device *dev, unsigned long int lba, void* buffer, int sectorCount); +void releaseSBP2Device(struct SBP2Device *dev); +int ConfigureSBP2Device(struct SBP2Device *dev); diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/usbhd_common.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/usbhd_common.h new file mode 100644 index 0000000..6597ceb --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/include/usbhd_common.h @@ -0,0 +1,27 @@ +#ifndef _USBHD_COMMON_H +#define _USBHD_COMMON_H + +#ifdef WIN32 +#define USBHD_INLINE +typedef unsigned char u8; +#else +#define USBHD_INLINE inline +void *malloc(int size); +void free(void *ptr); +#endif + +struct _cache_set; +typedef struct _cache_set cache_set; + +//--------------------------------------------------------------------------- +#define getUI32(buf) ((unsigned int)(((u8 *)(buf))[0] + \ + (((u8 *)(buf))[1] << 8) + \ + (((u8 *)(buf))[2] << 16) + \ + (((u8 *)(buf))[3] << 24))) +#define getUI32_2(buf1, buf2) ((unsigned int)(((u8 *)(buf1))[0] + \ + (((u8 *)(buf1))[1] << 8) + \ + (((u8 *)(buf2))[0] << 16) + \ + (((u8 *)(buf2))[1] << 24))) +#define getUI16(buf) ((unsigned int)(((u8 *)(buf))[0] + (((u8 *)(buf))[1] << 8))) + +#endif // _USBHD_COMMON_H diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/irx_imports.h new file mode 100644 index 0000000..32ea44f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/irx_imports.h @@ -0,0 +1,34 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include "iLinkman.h" +#include +#include +#include +#ifdef SIF_CALLBACKS_12_13 +#include +#endif +#include +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/main.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/main.c new file mode 100644 index 0000000..7add41b --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/main.c @@ -0,0 +1,26 @@ +#include +#include +#include +#include + +#include "sbp2_disk.h" +#include "fat_driver.h" + +#define MODNAME "IEEE1394_disk" +IRX_ID(MODNAME, 0x01, 0x07); + +int InitFS(void); + +int _start(int argc, char** argv) +{ + if(InitFAT() != 0) + { + printf("Error initializing FAT driver!\n"); + return MODULE_NO_RESIDENT_END; + } + + init_ieee1394DiskDriver(); + InitFS(); + + return MODULE_RESIDENT_END; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/part_driver.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/part_driver.c new file mode 100644 index 0000000..1257efe --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/part_driver.c @@ -0,0 +1,131 @@ +//--------------------------------------------------------------------------- +//File name: part_driver.c +//--------------------------------------------------------------------------- +#include + +#include "usbhd_common.h" +#include "scache.h" +#include "part_driver.h" +#include "sbp2_disk.h" +#include "fat_driver.h" + +//#define DEBUG //comment out this line when not debugging + +#include "mass_debug.h" + +#define READ_SECTOR(d, a, b) scache_readSector((d)->cache, (a), (void **)&b) + +typedef struct _part_record { + unsigned char sid; //system id - 4=16bit FAT (16bit sector numbers) + // 5=extended partition + // 6=16bit FAT (32bit sector numbers) + unsigned int start; // start sector of the partition + unsigned int count; // length of the partititon (total number of sectors) +} part_record; + +typedef struct _part_table { + part_record record[4]; //maximum of 4 primary partitions +} part_table; + +typedef struct _part_raw_record { + unsigned char active; //Set to 80h if this partition is active / bootable + unsigned char startH; //Partition's starting head. + unsigned char startST[2]; //Partition's starting sector and track. + unsigned char sid; //Partition's system ID number. + unsigned char endH; //Partition's ending head. + unsigned char endST[2]; //Partition's ending sector and track. + unsigned char startLBA[4]; //Starting LBA (sector) + unsigned char size[4]; //Partition size in sectors. +} part_raw_record; + +//--------------------------------------------------------------------------- +static void part_getPartitionRecord(part_raw_record* raw, part_record* rec) +{ + rec->sid = raw->sid; + rec->start = getUI32(raw->startLBA); + rec->count = getUI32(raw->size); +} + +//--------------------------------------------------------------------------- +int part_getPartitionTable(struct SBP2Device* dev, part_table* part) +{ + part_raw_record* part_raw; + int i; + int ret; + unsigned char* sbuf; + + ret = READ_SECTOR(dev, 0, sbuf); // read sector 0 - Disk MBR or boot sector + if ( ret < 0 ) + { + printf("USBHDFSD: part_getPartitionTable read failed %d!\n", ret); + return -1; + } + + printf("USBHDFSD: boot signature %X %X\n", sbuf[0x1FE], sbuf[0x1FF]); + if (sbuf[0x1FE] == 0x55 && sbuf[0x1FF] == 0xAA) + { + for ( i = 0; i < 4; i++) + { + part_raw = ( part_raw_record* )( sbuf + 0x01BE + ( i * 16 ) ); + part_getPartitionRecord(part_raw, &part->record[i]); + } + return 4; + } + else + { + for ( i = 0; i < 4; i++) + { + part->record[i].sid = 0;; + } + return 0; + } +} + +//--------------------------------------------------------------------------- +int part_connect(struct SBP2Device* dev) +{ + part_table partTable; + int count = 0; + int i; + XPRINTF("USBHDFSD: part_connect devId %i \n", dev->nodeID); + + if (part_getPartitionTable(dev, &partTable) < 0) + return -1; + + for ( i = 0; i < 4; i++) + { + if( + partTable.record[ i ].sid == 6 || + partTable.record[ i ].sid == 4 || + partTable.record[ i ].sid == 1 || // fat 16, fat 12 + partTable.record[ i ].sid == 0x0B || + partTable.record[ i ].sid == 0x0C || // fat 32 + partTable.record[ i ].sid == 0x0E) // fat 16 LBA + { + XPRINTF("USBHDFSD: mount partition %d\n", i); + if (fat_mount(dev, partTable.record[i].start, partTable.record[i].count) >= 0) + count++; + } + } + + if ( count == 0 ) + { // no partition table detected + // try to use "floppy" option + printf("USBHDFSD: mount drive\n"); + if (fat_mount(dev, 0, dev->maxLBA) < 0) + return -1; + } + + return 0; +} + +//--------------------------------------------------------------------------- +void part_disconnect(struct SBP2Device* dev) +{ + printf("USBHDFSD: part_disconnect devId %i \n", dev->nodeID); + fat_forceUnmount(dev); +} + +//--------------------------------------------------------------------------- +//End of file: part_driver.c +//--------------------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/sbp2_driver.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/sbp2_driver.c new file mode 100644 index 0000000..05a0224 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/sbp2_driver.c @@ -0,0 +1,613 @@ +#include +#include +#include +#include +#include +#include +#include + +//#define DEBUG + +#include "iLinkman.h" +#include "sbp2_disk.h" +#include "scsi.h" +#include "mass_debug.h" +#include "usbhd_common.h" + +#define MAX_DEVICES 5 +static struct SBP2Device SBP2Devices[MAX_DEVICES]; + +/* Thread creation data. */ +static iop_thread_t threadData={ + TH_C, /* attr */ + 0, /* option */ + NULL, /* thread */ + 0x420, /* stacksize */ + 0x30 /* priority */ +}; + +//static unsigned long int iLinkBufferOffset, iLinkTransferSize; +static int sbp2_event_flag; + +static void ieee1394_callback(int reason, unsigned long int offset, unsigned long int size); +static void iLinkIntrCBHandlingThread(void *arg); +static int ieee1394_SendManagementORB(int mode, struct SBP2Device *dev); +static int ieee1394_InitializeFetchAgent(struct SBP2Device *dev); +static inline int ieee1394_Sync_withTimeout(u32 n500mSecUnits); + +static volatile union{ + struct sbp2_status status; + unsigned char buffer[32]; /* Maximum 32 bytes. */ +} statusFIFO; + +static void ieee1394_callback(int reason, unsigned long int offset, unsigned long int size){ +#if 0 + iLinkBufferOffset=offset; + iLinkTransferSize=size; + + if(reason==iLink_CB_WRITE_REQUEST){ + u32 statusFIFO_result; + +// XPRINTF("Write request: Offset: 0x%08lx; size: 0x%08lx.\n", iLinkBufferOffset, iLinkTransferSize); + + if(iLinkBufferOffset==(u32)&statusFIFO){ /* Check to be sure that we don't signal ieee1394_Sync() too early; Some transactions are transactions involving multiple ORBs. */ + statusFIFO_result=statusFIFO.status.status; + if(RESP_SRC(statusFIFO_result)!=0) SetEventFlag(sbp2_event_flag, WRITE_REQ_INCOMING); /* Signal ieee1394_Sync() only after the last ORB was read. */ + } + } + else +#endif + if(reason==iLink_CB_BUS_RESET){ + SetEventFlag(sbp2_event_flag, BUS_RESET_COMPLETE); + } +#if 0 + else{ + //XPRINTF("Read request: Offset: 0x%08lx; size: 0x%08lx;\n", iLinkBufferOffset, iLinkTransferSize); + } +#endif +} + +/* Event flag creation data. */ +static iop_event_t evfp={ + 2, /* evfp.attr=EA_MULTI */ + 0, /* evfp.option */ + 0 /* evfp.bits */ +}; + +int iLinkIntrCBThreadID; + +void init_ieee1394DiskDriver(void){ + int i; + + for(i=0; i0); + if(retries==0){ + XPRINTF("Failed to log into the SBP-2 device.\n"); + return -1; + } + + if(ieee1394_InitializeFetchAgent(dev)<0){ + XPRINTF("Error initializing the SBP-2 device's Fetch Agent.\n"); + return -2; + } + + if(ConfigureSBP2Device(dev)<0) return -3; + + XPRINTF("Completed device initialization.\n"); + + /****** !!!FOR TESTING ONLY!!! ******/ +#if 0 + iop_sys_clock_t lTime; + u32 lSecStart, lUSecStart; + u32 lSecEnd, lUSecEnd, nbytes, i, rounds; + void *buffer; + int result; + + nbytes=1048576; + rounds=64; + if((buffer=malloc(nbytes))==NULL) printf("Unable to allocate memory. :(\n"); + printf("Read test: %p.\n", buffer); + printf("Start reading data...\n" ); + + GetSystemTime ( &lTime ); + SysClock2USec ( &lTime, &lSecStart, &lUSecStart ); + + for(i=0; inodeID); + + /* Offset in quadlets: 0x14 / 4 = 5 */ + ConfigurationROMOffset=5; + + if((result=iLinkReadCROM(dev->nodeID, ConfigurationROMOffset, 1, &LeafData))<0){ + XPRINTF("Error reading the configuration ROM. Error %d.\n", result); + return(result); + } + + ConfigurationROMOffset++; + + /* Get the Unit Directory's offset from the root directory. */ + DirectorySize=LeafData>>16; + for(i=0; inodeID, ConfigurationROMOffset, 1, &LeafData))<0){ + XPRINTF("Error reading the configuration ROM. Error %d.\n", result); + return(result); + } + + if((LeafData>>24)==IEEE1394_CROM_UNIT_DIRECTORY){ + UnitDirectoryOffset=ConfigurationROMOffset+(LeafData&0x00FFFFFF); + break; + } + + ConfigurationROMOffset++; + } + if(i==DirectorySize) return -1; + + if((result=iLinkReadCROM(dev->nodeID, UnitDirectoryOffset, 1, &LeafData))<0){ + XPRINTF("Error reading the configuration ROM. Error %d.\n", result); + return(result); + } + + DirectorySize=LeafData>>16; + for(i=0; inodeID, UnitDirectoryOffset+1+i, 1, &LeafData))<0){ + XPRINTF("Error reading the configuration ROM. Error %d.\n", result); + return(result); + } + + switch(LeafData>>24){ + /* Now get the address of the Management Agent CSR. */ + case IEEE1394_CROM_CSR_OFFSET: + managementAgentAddr=(void*)(LeafData&0x00FFFFFF); /* Mask off the bits that represent the Management Agent key. */ + XPRINTF("managementAgentAddr=0x%08lx.\n", (u32)managementAgentAddr*4); + + dev->ManagementAgent_low=(u32)managementAgentAddr*4+0xf0000000; + dev->ManagementAgent_high=0x0000ffff; + break; + case IEEE1394_CROM_UNIT_CHARA: + dev->mgt_ORB_timeout=(LeafData&0x0000FF00)>>8; + dev->ORB_size=LeafData&0x000000FF; + XPRINTF("mgt_ORB_timeout=%u; ORB_size=%u.\n", dev->mgt_ORB_timeout, dev->ORB_size); + break; + case IEEE1394_CROM_LOGICAL_UNIT_NUM: + dev->LUN=LeafData&0x0000FFFF; + XPRINTF("LUN=0x%08x.\n", dev->LUN); + break; + } + } + + return 1; +} + +/* Hardware event handling threads. */ +static void iLinkIntrCBHandlingThread(void *arg){ + int nNodes, i, targetDeviceID, nodeID, result; + static const unsigned char PayloadSizeLookupTable[]={ + 7, /* S100; 2^(7+2)=512 */ + 8, /* S200; 2^(8+2)=1024 */ + 9, /* S400; 2^(9+2)=2048 */ + }; + + while(1){ + WaitEventFlag(sbp2_event_flag, BUS_RESET_COMPLETE, WEF_AND|WEF_CLEAR, NULL); + + /* Disconnect all currently connected nodes. */ + for(i=0; i=0){ + releaseSBP2Device(&SBP2Devices[i]); + + iLinkTrFree(SBP2Devices[i].trContext); + SBP2Devices[i].trContext = -1; + } + } + + if((nNodes=iLinkGetNodeCount())<0) XPRINTF("Critical error: Failure getting the number of nodes!\n"); /* Error. */ + + XPRINTF("BUS RESET DETECTED. Nodes: %d\n", nNodes); + XPRINTF("Local Node: 0x%08x.\n", iLinkGetLocalNodeID()); + + //DelayThread(500000); /* Give the devices on the bus some time to initialize themselves (The SBP-2 standard states that a maximum of 5 seconds may be given). */ + + targetDeviceID=0; + + for(i=0; i=MAX_DEVICES){ + XPRINTF("Warning! There are more devices that what can be connected to.\n"); + break; + } + + XPRINTF("Attempting to initialize unit %d...\n", i); + + /* 16-bit node ID = BUS NUMBER (Upper 10 bits) followed by the NODE ID (Lower 6 bits). */ + if((nodeID=iLinkFindUnit(i, 0x0609e, 0x010483))<0){ + XPRINTF("Error: Unit %d is not a valid SBP-2 device. Code: %d.\n", i, nodeID); + continue; + } + + XPRINTF("Detected SBP-2 device.\n"); + + SBP2Devices[targetDeviceID].InitiatorNodeID=iLinkGetLocalNodeID(); + + XPRINTF("Local Node: 0x%08x.\n", SBP2Devices[targetDeviceID].InitiatorNodeID); + +#if 0 + if(SBP2Devices[targetDeviceID].IsConnected){ /* Already connected to the device. */ + if(SBP2Devices[targetDeviceID].nodeID==nodeID){ /* Make sure that we're attempting to re-connect to the same device. */ + if(ieee1394_SendManagementORB(SBP2_RECONNECT_REQUEST, &SBP2Devices[i])<0){ + XPRINTF("Error reconnecting to the SBP-2 device %u.\n", nodeID); + } + else{ + XPRINTF("Successfully reconnected to SBP-2 device %u.", nodeID); + targetDeviceID++; + continue; + } + } + else SBP2Devices[targetDeviceID].IsConnected=0; + } +#endif + + SBP2Devices[targetDeviceID].IsConnected=0; + + /* Attempt a login into the device. */ + SBP2Devices[targetDeviceID].nodeID=nodeID; + if((result=initSBP2Disk(&SBP2Devices[targetDeviceID]))<0){ + XPRINTF("Error initializing the device. Code: %d.\n", result); + continue; + } + + SBP2Devices[targetDeviceID].trContext=iLinkTrAlloc(nodeID, iLinkGetNodeMaxSpeed(nodeID)); + + if(SBP2Devices[targetDeviceID].trContext>=0){ + XPRINTF("Connected device as node 0x%08x.\n", SBP2Devices[targetDeviceID].nodeID); + XPRINTF("Generation number: %d.\n", iLinkGetGenerationNumber()); + + SBP2Devices[targetDeviceID].speed=iLinkGetNodeTrSpeed(SBP2Devices[targetDeviceID].trContext); + XPRINTF("Current speed: %d.\n", SBP2Devices[targetDeviceID].speed); + + SBP2Devices[targetDeviceID].max_payload=PayloadSizeLookupTable[SBP2Devices[targetDeviceID].speed]; + + if(initConfigureSBP2Device(&SBP2Devices[targetDeviceID])>=0){ + SBP2Devices[targetDeviceID].IsConnected=1; + targetDeviceID++; + } + } + else XPRINTF("Error allocating a transaction.\n"); + } + + for(; targetDeviceIDtrContext, dev->CommandBlockAgent_high, dev->CommandBlockAgent_low+0x04, &dummy, 4))<0){ + XPRINTF("Error writing to the Fetch Agent's AGENT_RESET register @ 0x%08lx %08lx. Code: %d.\n", dev->CommandBlockAgent_high, dev->CommandBlockAgent_low+0x04, result); + } +} + +static int ieee1394_GetFetchAgentState(struct SBP2Device *dev){ + unsigned long int FetchAgentState; + int result; + + if((result=iLinkTrRead(dev->trContext, dev->CommandBlockAgent_high, dev->CommandBlockAgent_low, &FetchAgentState, 4))<0){ + XPRINTF("Error reading the Fetch Agent's AGENT_STATE register @ 0x%08lx %08lx. Code: %d.\n", dev->CommandBlockAgent_high, dev->CommandBlockAgent_low, result); + return -1; + } + else{ + FetchAgentState=BSWAP32(FetchAgentState); + XPRINTF("Fetch Agent state: %lu.\n", FetchAgentState); + return FetchAgentState; + } +} + +static int ieee1394_InitializeFetchAgent(struct SBP2Device *dev){ + int result, retries; + void *dummy_ORB; + struct sbp2_pointer address; + + XPRINTF("Initializing fetch agent..."); + + dummy_ORB=malloc(dev->ORB_size*4); + memset(dummy_ORB, 0, dev->ORB_size*4); + + ieee1394_ResetFetchAgent(dev); + + /* Write the address of the dummy ORB to the fetch agent's ORB_POINTER register. */ + address.low=(u32)dummy_ORB; + address.NodeID=dev->InitiatorNodeID; + address.high=0; + + ((struct sbp2_ORB_pointer *)dummy_ORB)->reserved=NULL_POINTER; + ((struct sbp2_ORB_pointer *)dummy_ORB)->high=((struct sbp2_ORB_pointer *)dummy_ORB)->low=0; + ((struct management_ORB *)dummy_ORB)->flags=(u32)(ORB_NOTIFY|ORB_REQUEST_FORMAT(3)); + + retries=0; + while((result=iLinkTrWrite(dev->trContext, dev->CommandBlockAgent_high, dev->CommandBlockAgent_low+0x08, &address, 8))<0){ + XPRINTF("Error writing to the Fetch Agent's ORB_POINTER register @ 0x%08lx %08lx. Code: %d.\n", dev->CommandBlockAgent_high, dev->CommandBlockAgent_low+0x08, result); + ieee1394_ResetFetchAgent(dev); + + retries++; + if(retries>3) return(-1); + } + + result=ieee1394_Sync(); + ieee1394_GetFetchAgentState(dev); + + free(dummy_ORB); + + XPRINTF("done!\n"); + + return 1; +} + +static int ieee1394_SendManagementORB(int mode, struct SBP2Device *dev){ + int result; + struct sbp2_pointer address; + + struct sbp2_login_response login_result; + struct management_ORB new_management_ORB; + + memset((void*)&statusFIFO, 0, sizeof(statusFIFO)); + memset(&login_result, 0, sizeof(struct sbp2_login_response)); + memset(&new_management_ORB, 0, sizeof(struct management_ORB)); + + new_management_ORB.status_FIFO.low=(u32)&statusFIFO; + new_management_ORB.flags=(u32)(ORB_NOTIFY | ORB_REQUEST_FORMAT(0) |MANAGEMENT_ORB_FUNCTION(mode)); + + switch(mode){ + case SBP2_LOGIN_REQUEST: /* Login. */ + /* The reconnect timeout is now set to 0, since the mechanism that determines whether the initiator was already logged into the target or not was not accurate. */ + new_management_ORB.flags|=(u32)(MANAGEMENT_ORB_RECONNECT(0) | MANAGEMENT_ORB_EXCLUSIVE(1) | MANAGEMENT_ORB_LUN(dev->LUN)); + + new_management_ORB.login.response.low=(u32)&login_result; + new_management_ORB.length=(MANAGEMENT_ORB_RESPONSE_LENGTH(sizeof(struct sbp2_login_response))|MANAGEMENT_ORB_PASSWORD_LENGTH(0)); + break; +#if 0 + case SBP2_RECONNECT_REQUEST: /* Reconnect. */ + new_management_ORB.flags|=(u32)(MANAGEMENT_ORB_RECONNECT(4) | MANAGEMENT_ORB_LOGINID(dev->loginID)); /* loginID was stored as a big endian number, so it has to be converted into little endian first. :( */ + break; +#endif + default: + XPRINTF("Warning! Unsupported management ORB type!\n"); + } + + address.NodeID=dev->InitiatorNodeID; + address.high=0; + address.low=(u32)&new_management_ORB; + + XPRINTF("Management ORB: %p. size=%d.\n", &new_management_ORB, sizeof(struct management_ORB)); + XPRINTF("Address pointer: %p\n", &address); + + if((result=iLinkTrWrite(dev->trContext, dev->ManagementAgent_high, dev->ManagementAgent_low, &address, 8))<0){ /* Write the Login ORB address to the target's Management Agent CSR. */ + XPRINTF("Error writing to the Management Agent CSR @ 0x%08lx %08lx. Code: %d.\n", dev->ManagementAgent_high, dev->ManagementAgent_low, result); + return(result); + } + + XPRINTF("Waiting for ILINK...\n"); + + result=ieee1394_Sync_withTimeout(dev->mgt_ORB_timeout); + + XPRINTF("statusFIFO= %p; [0]=%u.\n", &statusFIFO, statusFIFO.buffer[0]); + if(result>=0){ + switch(mode){ + case SBP2_LOGIN_REQUEST: /* Login. */ + XPRINTF("Done. command_block_agent= 0x%08x %08lx.\n", login_result.command_block_agent.high, login_result.command_block_agent.low); + + /* Store the address to the target's command block agent. */ + + dev->CommandBlockAgent_high=login_result.command_block_agent.high; + dev->CommandBlockAgent_low=login_result.command_block_agent.low; + + dev->loginID=login_result.login_ID; /* Store the login ID. */ + + XPRINTF("Login response size: %u.", login_result.length); + XPRINTF("Signed into SBP-2 device node 0x%08x. Login ID: %u\n", dev->nodeID, dev->loginID); + break; +#if 0 + case SBP2_RECONNECT_REQUEST: /* Reconnect. */ + /* Just return the result from ieee1394_Sync(). */ + break; +#endif + default: + XPRINTF("Warning! Unsupported management ORB type!\n"); + } + + /* Validate the fetch agent's CSR address. */ + if((dev->CommandBlockAgent_low<0xF0010000)||((dev->CommandBlockAgent_high&0xFFFF)!=0x0000FFFF)) result=(-1); + } + + return result; +} + +int ieee1394_SendCommandBlockORB(struct SBP2Device *dev, struct CommandDescriptorBlock *firstCDB){ + int result, retries; + struct sbp2_pointer address; + + memset((void*)&statusFIFO, 0, sizeof(statusFIFO)); + + address.low=(u32)firstCDB; + address.NodeID=dev->InitiatorNodeID; + address.high=0; + + retries=0; + + /* Write the pointer to the first ORB in the fetch agent's NEXT_ORB register. */ + while((result=iLinkTrWrite(dev->trContext, dev->CommandBlockAgent_high, dev->CommandBlockAgent_low+0x08, &address, 8))<0){ + XPRINTF("Error writing to the Fetch Agent's ORB_POINTER register @ 0x%08lx %08lx. Code: %d.\n", dev->CommandBlockAgent_high, dev->CommandBlockAgent_low+0x08, result); + + DelayThread(200000); + ieee1394_ResetFetchAgent(dev); + + retries++; + if(retries>3) return(-1); + } + +#if 0 + /* Write a value to the fetch agent's DOORBELL register. */ + result=1; + if((result=iLinkTrWrite(dev->trContext, dev->CommandBlockAgent_high, dev->CommandBlockAgent_low+0x10, &result, 4))<0){ + XPRINTF("Error writing to the Fetch Agent's DOORBELL register @ 0x%08lx %08lx. Code: %d.\n", dev->CommandBlockAgent_high, dev->CommandBlockAgent_low+0x10, result); + return -2; + } +#endif + + return 1; +} + +/* static unsigned int alarm_cb(void *arg){ + iSetEventFlag(sbp2_event_flag, ERROR_TIME_OUT); + return 0; +} */ + +static int ProcessStatus(void){ + u32 statusFIFO_result; + unsigned char status, resp, dead, sense, len; + int result; + + statusFIFO_result=statusFIFO.status.status; + status=RESP_SBP_STATUS(statusFIFO_result); + resp=RESP_RESP(statusFIFO_result); + dead=RESP_DEAD(statusFIFO_result); + len=RESP_LEN(statusFIFO_result); + sense=((statusFIFO.status.data[0])>>16)&0xF; + + XPRINTF("result: 0x%08lx; status: 0x%02x; RESP: 0x%02x; Dead: %u; len: 0x%02x; sense: 0x%02x.\n", statusFIFO_result, status, resp, dead, len, sense); + if(sense==0) sense=1; /* Workaround for faulty firmwares: The sense code is 0 or was not sent when it's supposed to be sent. */ + + result=(((status==0)||(status==0x0B))&&(resp==0)&&(!dead)&&(len==1))?0:-sense; + + if(result<0){ + printf("result: 0x%08lx; status: 0x%02x; RESP: 0x%02x; Dead: %u; len: 0x%02x; sense: 0x%02x.\n", statusFIFO_result, status, resp, dead, len, sense); + } + + return result; +} + +/* This is declared as inline as there is only one call to it. */ +static inline int ieee1394_Sync_withTimeout(u32 n500mSecUnits){ +/* iop_sys_clock_t timeout_clk; + u32 ef_result; + + USec2SysClock(n500mSecUnits*500000, &timeout_clk); + + SetAlarm(&timeout_clk, &alarm_cb, NULL); + WaitEventFlag(sbp2_event_flag, WRITE_REQ_INCOMING|ERROR_TIME_OUT, WEF_OR|WEF_CLEAR, &ef_result); + + if(ef_result&ERROR_TIME_OUT){ + XPRINTF("-=Time out=-\n"); + return(-1); + } + else CancelAlarm(&alarm_cb, NULL); */ + + unsigned int i=0; + + while(RESP_SRC(statusFIFO.status.status)==0){ + if(i>n500mSecUnits*10000){ + XPRINTF("-=Time out=-\n"); + return(-1); + } + + DelayThread(50); + i++; + }; + + return(ProcessStatus()); +} + +int ieee1394_Sync(void){ +// WaitEventFlag(sbp2_event_flag, WRITE_REQ_INCOMING, WEF_AND|WEF_CLEAR, NULL); + + while(RESP_SRC(statusFIFO.status.status)==0){ + DelayThread(50); + }; + + return(ProcessStatus()); +} + +void DeinitIEEE1394(void){ + TerminateThread(iLinkIntrCBThreadID); + DeleteThread(iLinkIntrCBThreadID); + DeleteEventFlag(sbp2_event_flag); +} + +void *malloc(int NumBytes){ + int OldState; + void *buffer; + + CpuSuspendIntr(&OldState); + buffer=AllocSysMemory(ALLOC_FIRST, NumBytes, NULL); + CpuResumeIntr(OldState); + + return buffer; +} + +void free(void *buffer){ + int OldState; + + CpuSuspendIntr(&OldState); + FreeSysMemory(buffer); + CpuResumeIntr(OldState); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/scache.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/scache.c new file mode 100644 index 0000000..8da019f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/scache.c @@ -0,0 +1,316 @@ +//--------------------------------------------------------------------------- +//File name: scache.c +//--------------------------------------------------------------------------- +/* + * scache.c - USB Mass storage driver for PS2 + * + * (C) 2004, Marek Olejnik (ole00@post.cz) + * (C) 2004 Hermes (support for sector sizes from 512 to 4096 bytes) + * + * Sector cache + * + * See the file LICENSE included with this distribution for licensing terms. + */ +//--------------------------------------------------------------------------- +#include + +#include +#include + +#include "usbhd_common.h" +#include "sbp2_disk.h" +#include "scsi.h" +#include "scache.h" + +//--------------------------------------------------------------------------- +#define READ_SECTOR scsiReadSector +#define WRITE_SECTOR scsiWriteSector + +//#define DEBUG //comment out this line when not debugging + +#include "mass_debug.h" + +//--------------------------------------------------------------------------- +void initRecords(cache_set* cache) +{ + int i; + + for (i = 0; i < CACHE_SIZE; i++) + { + cache->rec[i].sector = 0xFFFFFFF0; + cache->rec[i].tax = 0; + cache->rec[i].writeDirty = 0; + } + + cache->writeFlag = 0; + //cache->flushCounter = 0; +} + +//--------------------------------------------------------------------------- +/* search cache records for the sector number stored in cache + returns cache record (slot) number + */ +int getSlot(cache_set* cache, unsigned int sector) { + int i; + + for (i = 0; i < CACHE_SIZE; i++) { + if (sector >= cache->rec[i].sector && sector < (cache->rec[i].sector + cache->indexLimit)) { + return i; + } + } + return -1; +} + + +//--------------------------------------------------------------------------- +/* search cache records for the sector number stored in cache */ +int getIndexRead(cache_set* cache, unsigned int sector) { + int i; + int index =-1; + + for (i = 0; i < CACHE_SIZE; i++) { + if (sector >= cache->rec[i].sector && sector < (cache->rec[i].sector + cache->indexLimit)) { + if (cache->rec[i].tax < 0) cache->rec[i].tax = 0; + cache->rec[i].tax +=2; + index = i; + } + cache->rec[i].tax--; //apply tax penalty + } + if (index < 0) + return index; + else + return ((index * cache->indexLimit) + (sector - cache->rec[index].sector)); +} + +//--------------------------------------------------------------------------- +/* select the best record where to store new sector */ +int getIndexWrite(cache_set* cache, unsigned int sector) { + int i, ret; + int minTax = 0x0FFFFFFF; + int index = 0; + + for (i = 0; i < CACHE_SIZE; i++) { + if (cache->rec[i].tax < minTax) { + index = i; + minTax = cache->rec[i].tax; + } + } + + //this sector is dirty - we need to flush it first + if (cache->rec[index].writeDirty) { + XPRINTF("scache: getIndexWrite: sector is dirty : %d index=%d \n", cache->rec[index].sector, index); + ret = WRITE_SECTOR(cache->dev, cache->rec[index].sector, cache->sectorBuf + (index * BLOCK_SIZE), BLOCK_SIZE/cache->dev->sectorSize); + cache->rec[index].writeDirty = 0; + //TODO - error handling + if (ret < 0) { + printf("scache: ERROR writing sector to disk! sector=%d\n", sector); + } + + } + cache->rec[index].tax +=2; + cache->rec[index].sector = sector; + + return index * cache->indexLimit; +} + + + +//--------------------------------------------------------------------------- +/* + flush dirty sectors + */ +int scache_flushSectors(cache_set* cache) { + int i,ret; + int counter = 0; + + XPRINTF("cache: flushSectors devId = %i \n", cache->dev->nodeID); + + //cache->flushCounter = 0; + + XPRINTF("scache: flushSectors writeFlag=%d\n", cache->writeFlag); + //no write operation occured since last flush + if (cache->writeFlag==0) { + return 0; + } + + for (i = 0; i < CACHE_SIZE; i++) { + if (cache->rec[i].writeDirty) { + XPRINTF("scache: flushSectors dirty index=%d sector=%d \n", i, cache->rec[i].sector); + ret = WRITE_SECTOR(cache->dev, cache->rec[i].sector, cache->sectorBuf + (i * BLOCK_SIZE), BLOCK_SIZE); + cache->rec[i].writeDirty = 0; + //TODO - error handling + if (ret < 0) { + printf("scache: ERROR writing sector to disk! sector=%d\n", cache->rec[i].sector); + return ret; + } + counter ++; + } + } + cache->writeFlag = 0; + return counter; +} + +//--------------------------------------------------------------------------- +int scache_readSector(cache_set* cache, unsigned int sector, void** buf) { + int index; //index is given in single sectors not octal sectors + int ret; + unsigned int alignedSector; + + XPRINTF("cache: readSector devId = %i %X sector = %i \n", cache->dev->nodeID, (int) cache, sector); + if (cache == NULL) { + printf("cache: devId cache not created = %i \n", cache->dev->nodeID); + return -1; + } + + cache->cacheAccess ++; + index = getIndexRead(cache, sector); + XPRINTF("cache: indexRead=%i \n", index); + if (index >= 0) { //sector found in cache + cache->cacheHits ++; + *buf = cache->sectorBuf + (index * cache->sectorSize); + XPRINTF("cache: hit and done reading sector \n"); + + return cache->sectorSize; + } + + //compute alignedSector - to prevent storage of duplicit sectors in slots + alignedSector = (sector/cache->indexLimit)*cache->indexLimit; + index = getIndexWrite(cache, alignedSector); + XPRINTF("cache: indexWrite=%i slot=%d alignedSector=%i\n", index, index / cache->indexLimit, alignedSector); + ret = READ_SECTOR(cache->dev, alignedSector, cache->sectorBuf + (index * cache->sectorSize), BLOCK_SIZE/cache->dev->sectorSize); + + if (ret < 0) { + printf("scache: ERROR reading sector from disk! sector=%d\n", alignedSector); + return ret; + } + *buf = cache->sectorBuf + (index * cache->sectorSize) + ((sector%cache->indexLimit) * cache->sectorSize); + XPRINTF("cache: done reading physical sector \n"); + + //write precaution + //cache->flushCounter++; + //if (cache->flushCounter == FLUSH_TRIGGER) { + //scache_flushSectors(cache); + //} + + return cache->sectorSize; +} + + +//--------------------------------------------------------------------------- +int scache_allocSector(cache_set* cache, unsigned int sector, void** buf) { + int index; //index is given in single sectors not octal sectors + //int ret; + unsigned int alignedSector; + + XPRINTF("cache: allocSector devId = %i sector = %i \n", cache->dev->nodeID, sector); + + index = getIndexRead(cache, sector); + XPRINTF("cache: indexRead=%i \n", index); + if (index >= 0) { //sector found in cache + *buf = cache->sectorBuf + (index * cache->sectorSize); + XPRINTF("cache: hit and done allocating sector \n"); + return cache->sectorSize; + } + + //compute alignedSector - to prevent storage of duplicit sectors in slots + alignedSector = (sector/cache->indexLimit)*cache->indexLimit; + index = getIndexWrite(cache, alignedSector); + XPRINTF("cache: indexWrite=%i \n", index); + *buf = cache->sectorBuf + (index * cache->sectorSize) + ((sector%cache->indexLimit) * cache->sectorSize); + XPRINTF("cache: done allocating sector\n"); + return cache->sectorSize; +} + + +//--------------------------------------------------------------------------- +int scache_writeSector(cache_set* cache, unsigned int sector) { + int index; //index is given in single sectors not octal sectors + //int ret; + + XPRINTF("cache: writeSector devId = %i sector = %i \n", cache->dev->nodeID, sector); + + index = getSlot(cache, sector); + if (index < 0) { //sector not found in cache + printf("cache: writeSector: ERROR! the sector is not allocated! \n"); + return -1; + } + XPRINTF("cache: slotFound=%i \n", index); + + //prefere written sectors to stay in cache longer than read sectors + cache->rec[index].tax += 2; + + //set dirty status + cache->rec[index].writeDirty = 1; + cache->writeFlag++; + + XPRINTF("cache: done soft writing sector \n"); + + //write precaution + //cache->flushCounter++; + //if (cache->flushCounter == FLUSH_TRIGGER) { + //scache_flushSectors(devId); + //} + + return cache->sectorSize; +} + +//--------------------------------------------------------------------------- +cache_set* scache_init(struct SBP2Device* dev, int sectSize) +{ + cache_set* cache; + XPRINTF("cache: init devId = %i sectSize = %i \n", dev->nodeID, sectSize); + + cache = malloc(sizeof(cache_set)); + if (cache == NULL) { + printf("scache init! Sector cache: can't alloate cache!\n"); + return NULL; + } + + XPRINTF("scache init! \n"); + cache->dev = dev; + + XPRINTF("sectorSize: 0x%x\n", cache->sectorSize); + cache->sectorBuf = (unsigned char*) malloc(BLOCK_SIZE * CACHE_SIZE); + if (cache->sectorBuf == NULL) { + printf("Sector cache: can't alloate memory of size:%d \n", BLOCK_SIZE * CACHE_SIZE); + free(cache); + return NULL; + } + XPRINTF("Sector cache: allocated memory at:%p of size:%d \n", cache->sectorBuf, BLOCK_SIZE * CACHE_SIZE); + + //added by Hermes + cache->sectorSize = sectSize; + cache->indexLimit = BLOCK_SIZE/cache->sectorSize; //number of sectors per 1 cache slot + cache->cacheAccess = 0; + cache->cacheHits = 0; + initRecords(cache); + return cache; +} + +//--------------------------------------------------------------------------- +void scache_getStat(cache_set* cache, unsigned int* access, unsigned int* hits) { + *access = cache->cacheAccess; + *hits = cache->cacheHits; +} + +//--------------------------------------------------------------------------- +void scache_kill(cache_set* cache) //dlanor: added for disconnection events (flush impossible) +{ + XPRINTF("cache: kill devId = %i \n", cache->dev->nodeID); + if(cache->sectorBuf != NULL) + { + free(cache->sectorBuf); + cache->sectorBuf = NULL; + } + free(cache); +} +//--------------------------------------------------------------------------- +void scache_close(cache_set* cache) +{ + XPRINTF("cache: close devId = %i \n", cache->dev->nodeID); + scache_flushSectors(cache); + scache_kill(cache); +} +//--------------------------------------------------------------------------- +//End of file: scache.c +//--------------------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/scsi.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/scsi.c new file mode 100644 index 0000000..4ae7b5f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/IEEE1394_disk/src/scsi.c @@ -0,0 +1,428 @@ +#include +#include +#include +#include +#include + +//#define DEBUG + +#include "iLinkman.h" +#include "sbp2_disk.h" +#include "scsi.h" + +#include "usbhd_common.h" +#include "scache.h" +#include "part_driver.h" +#include "mass_debug.h" + +/* Function prototypes */ +static int scsiTestUnitReady(struct SBP2Device* dev); +static int scsiInquiry(struct SBP2Device* dev, void *buffer, int size); +static int scsiRequestSense(struct SBP2Device* dev, void *buffer, int size); +static int scsiStartStopUnit(struct SBP2Device* dev); +static int scsiReadCapacity(struct SBP2Device* dev, void *buffer, int size); + +static int scsiTestUnitReady(struct SBP2Device* dev){ + struct CommandDescriptorBlock cdb; + + XPRINTF("IEEE1394_disk: scsiTestUnitReady.\n"); + + cdb.misc=(u32)(ORB_NOTIFY | ORB_REQUEST_FORMAT(0) | CDB_MAX_PAYLOAD(dev->max_payload) | CDB_DIRECTION(WRITE_TRANSACTION) | CDB_SPEED(dev->speed)); + + cdb.DataDescriptor.low=cdb.DataDescriptor.high=0; + cdb.DataDescriptor.NodeID=dev->InitiatorNodeID; + + cdb.NextOrb.high=cdb.NextOrb.low=0; + cdb.NextOrb.reserved=NULL_POINTER; + + //scsi command packet + cdb.CDBs[3] = 0x00; //test unit ready operation code + cdb.CDBs[2] = 0; //reserved + cdb.CDBs[1] = 0; //reserved + cdb.CDBs[0] = 0; //reserved + cdb.CDBs[7] = 0; //reserved + cdb.CDBs[6] = 0; //reserved + cdb.CDBs[5] = 0; //reserved + cdb.CDBs[4] = 0; //reserved + cdb.CDBs[11] = 0; //reserved + cdb.CDBs[10] = 0; //reserved + cdb.CDBs[9] = 0; //reserved + cdb.CDBs[8] = 0; //reserved + + ieee1394_SendCommandBlockORB(dev, &cdb); + return(ieee1394_Sync()); +} + +static int scsiRequestSense(struct SBP2Device* dev, void *buffer, int size) +{ + int ret; + struct CommandDescriptorBlock cdb; + + XPRINTF("IEEE1394_disk: scsiRequestSense.\n"); + + cdb.misc=(ORB_NOTIFY | ORB_REQUEST_FORMAT(0) | CDB_MAX_PAYLOAD(dev->max_payload) | CDB_DIRECTION(WRITE_TRANSACTION) | CDB_SPEED(dev->speed) | CDB_DATA_SIZE(size)); + + cdb.DataDescriptor.low=(u32)buffer; + cdb.DataDescriptor.high=0; + cdb.DataDescriptor.NodeID=dev->InitiatorNodeID; + + cdb.NextOrb.high=cdb.NextOrb.low=0; + cdb.NextOrb.reserved=NULL_POINTER; + + //scsi command packet + cdb.CDBs[3] = 0x03; //request sense operation code + cdb.CDBs[2] = 0; //reserved + cdb.CDBs[1] = 0; //reserved + cdb.CDBs[0] = 0; //reserved + cdb.CDBs[7] = size; //allocation length + cdb.CDBs[6] = 0; //reserved + cdb.CDBs[5] = 0; //reserved + cdb.CDBs[4] = 0; //reserved + cdb.CDBs[11] = 0; //reserved + cdb.CDBs[10] = 0; //reserved + cdb.CDBs[9] = 0; //reserved + cdb.CDBs[8] = 0; //reserved + + ieee1394_SendCommandBlockORB(dev, &cdb); + ret=ieee1394_Sync(); + + if(ret!=0) XPRINTF("IEEE1394_disk: scsiRequestSense error: %d\n", ret); + + return ret; +} + +static int scsiInquiry(struct SBP2Device* dev, void *buffer, int size) +{ + int ret; + struct CommandDescriptorBlock cdb; + unsigned int i; + + XPRINTF("IEEE1394_disk: scsiInquiry. buffer: %p\n", buffer); + + cdb.misc=(ORB_NOTIFY | ORB_REQUEST_FORMAT(0) | CDB_MAX_PAYLOAD(dev->max_payload) | CDB_DIRECTION(WRITE_TRANSACTION) | CDB_SPEED(dev->speed) | CDB_DATA_SIZE(size)); + + cdb.DataDescriptor.low=(u32)buffer; + cdb.DataDescriptor.high=0; + cdb.DataDescriptor.NodeID=dev->InitiatorNodeID; + + cdb.NextOrb.high=cdb.NextOrb.low=0; + cdb.NextOrb.reserved=NULL_POINTER; + + //scsi command packet + cdb.CDBs[3] = 0x12; //inquiry operation code + cdb.CDBs[2] = 0; //reserved + cdb.CDBs[1] = 0; //page code + cdb.CDBs[0] = 0; //reserved + cdb.CDBs[7] = size; //inquiry reply length + cdb.CDBs[6] = 0; //reserved + cdb.CDBs[5] = 0; //reserved + cdb.CDBs[4] = 0; //reserved + cdb.CDBs[11] = 0; //reserved + cdb.CDBs[10] = 0; //reserved + cdb.CDBs[9] = 0; //reserved + cdb.CDBs[8] = 0; //reserved + + ieee1394_SendCommandBlockORB(dev, &cdb); + ret=ieee1394_Sync(); + + if(ret != 0) XPRINTF("IEEE1394_disk: scsiInquiry error %d\n", ret); + else{ + for(i=0; imax_payload) | CDB_DIRECTION(WRITE_TRANSACTION) | CDB_SPEED(dev->speed)); + + cdb.DataDescriptor.low=cdb.DataDescriptor.high=0; + cdb.DataDescriptor.NodeID=dev->InitiatorNodeID; + + cdb.NextOrb.high=cdb.NextOrb.low=0; + cdb.NextOrb.reserved=NULL_POINTER; + + //scsi command packet + cdb.CDBs[3] = 0x1B; //start stop unit operation code + cdb.CDBs[2] = 1; //reserved/immed + cdb.CDBs[1] = 0; //reserved + cdb.CDBs[0] = 0; //reserved + cdb.CDBs[7] = 1; //POWER CONDITIONS/reserved/LoEj/Start "Start the media and acquire the format type" + cdb.CDBs[6] = 0; //reserved + cdb.CDBs[5] = 0; //reserved + cdb.CDBs[4] = 0; //reserved + cdb.CDBs[11] = 0; //reserved + cdb.CDBs[10] = 0; //reserved + cdb.CDBs[9] = 0; //reserved + cdb.CDBs[8] = 0; //reserved + + ieee1394_SendCommandBlockORB(dev, &cdb); + return(ieee1394_Sync()); +} + +static int scsiReadCapacity(struct SBP2Device* dev, void *buffer, int size) +{ + struct CommandDescriptorBlock cdb; + + XPRINTF("IEEE1394_disk: scsiReadCapacity.\n"); + + cdb.misc=(ORB_NOTIFY | ORB_REQUEST_FORMAT(0) | CDB_MAX_PAYLOAD(dev->max_payload) | CDB_DIRECTION(WRITE_TRANSACTION) | CDB_SPEED(dev->speed) | CDB_DATA_SIZE(size)); + + cdb.DataDescriptor.low=(u32)buffer; + cdb.DataDescriptor.high=0; + cdb.DataDescriptor.NodeID=dev->InitiatorNodeID; + + cdb.NextOrb.high=cdb.NextOrb.low=0; + cdb.NextOrb.reserved=NULL_POINTER; + + //scsi command packet + cdb.CDBs[3] = 0x25; //read capacity operation code + cdb.CDBs[2] = 0; //reserved + cdb.CDBs[1] = 0; //LBA 1 + cdb.CDBs[0] = 0; //LBA 2 + cdb.CDBs[7] = 0; //LBA 3 + cdb.CDBs[6] = 0; //LBA 4 + cdb.CDBs[5] = 0; //Reserved + cdb.CDBs[4] = 0; //Reserved + cdb.CDBs[11] = 0; //Reserved + cdb.CDBs[10] = 0; //reserved + cdb.CDBs[9] = 0; //reserved + cdb.CDBs[8] = 0; //reserved + + ieee1394_SendCommandBlockORB(dev, &cdb); + return(ieee1394_Sync()); +} + +#define MAX_ORBS 256 + +static struct CommandDescriptorBlock cdb[MAX_ORBS]; + +int scsiReadSector(struct SBP2Device *dev, unsigned long int lba, void *buffer, int sectorCount) +{ + unsigned int nOrbs, OrbsRemaining, i, sectorsToRead, sectorsRemaining, SectorsPerBlock, BlockNum; + unsigned long int startingLBA; + void *bufferPtr, *PreviousReqBufferPtr; + int result; + + XPRINTF("IEEE1394_disk: scsiReadSector. buffer: %p, lba: 0x%08lx, numsectors: %d.\n", buffer, lba, sectorCount); + SectorsPerBlock=XFER_BLOCK_SIZE/dev->sectorSize; + OrbsRemaining=sectorCount/SectorsPerBlock; + if((sectorCount%SectorsPerBlock)!=0) OrbsRemaining++; + + XPRINTF("NumOrbs=%d cdb: %p.\n", OrbsRemaining, cdb); + + startingLBA=lba; + sectorsRemaining=sectorCount; + bufferPtr=buffer; + + result=0; + for(PreviousReqBufferPtr=NULL, BlockNum=0, sectorsToRead=0; (OrbsRemaining>0) && (result==0); OrbsRemaining-=nOrbs, BlockNum++){ + nOrbs=(OrbsRemaining>MAX_ORBS)?MAX_ORBS:OrbsRemaining; + + if(BlockNum>0){ /* While waiting for the read request that was just sent to be processed, byte-swap the previously read in data. */ + for(i=0; iSectorsPerBlock)?SectorsPerBlock:sectorsRemaining; + + cdb[i].misc=(ORB_NOTIFY | ORB_REQUEST_FORMAT(0) | CDB_MAX_PAYLOAD(dev->max_payload) | CDB_DIRECTION(WRITE_TRANSACTION) | CDB_SPEED(dev->speed) | CDB_DATA_SIZE((dev->sectorSize * sectorsToRead))); + + cdb[i].DataDescriptor.low=(u32)bufferPtr; + cdb[i].DataDescriptor.high=0; + cdb[i].DataDescriptor.NodeID=dev->InitiatorNodeID; + + if(i>0){ + cdb[i-1].NextOrb.high=0; + cdb[i-1].NextOrb.low=(u32)&cdb[i]; + cdb[i-1].NextOrb.reserved=0; + } + + //scsi command packet + cdb[i].CDBs[3] = 0x28; //read operation code + cdb[i].CDBs[2] = 0; //Reserved + cdb[i].CDBs[1] = (startingLBA & 0xFF000000) >> 24; //lba 1 (MSB) + cdb[i].CDBs[0] = (startingLBA & 0xFF0000) >> 16; //lba 2 + cdb[i].CDBs[7] = (startingLBA & 0xFF00) >> 8; //lba 3 + cdb[i].CDBs[6] = (startingLBA & 0xFF); //lba 4 (LSB) + cdb[i].CDBs[5] = 0; //Reserved + cdb[i].CDBs[4] = (sectorsToRead & 0xFF00) >> 8; //Transfer length MSB + cdb[i].CDBs[11] = (sectorsToRead & 0xFF); //Transfer length LSB + cdb[i].CDBs[10] = 0; //reserved + cdb[i].CDBs[9] = 0; //reserved + cdb[i].CDBs[8] = 0; //reserved + + startingLBA+=sectorsToRead; + sectorsRemaining-=sectorsToRead; + bufferPtr+=dev->sectorSize * sectorsToRead; + } + + /* NULL terminate the last ORB. */ + cdb[i-1].NextOrb.high=cdb[i-1].NextOrb.low=0; + cdb[i-1].NextOrb.reserved=NULL_POINTER; + + ieee1394_SendCommandBlockORB(dev, cdb); + } + + /* Sync and byte-swap the last block. */ + result=ieee1394_Sync(); + for(i=0; isectorSize; + OrbsRemaining=sectorCount/SectorsPerBlock; + if((sectorCount%SectorsPerBlock)!=0) OrbsRemaining++; + + startingLBA=lba; + sectorsRemaining=sectorCount; + bufferPtr=buffer; + max_payload=(dev->max_payload>7)?7:dev->max_payload; /* Do not allow the maximum payload to exceed 512 bytes (Actually, is this necessary?). */ + + result=0; + for(; (OrbsRemaining>0) && (result==0); OrbsRemaining-=nOrbs){ + nOrbs=(OrbsRemaining>MAX_ORBS)?MAX_ORBS:OrbsRemaining; + + for(i=0; iSectorsPerBlock)?SectorsPerBlock:sectorsRemaining; + + cdb[i].misc=(ORB_NOTIFY | ORB_REQUEST_FORMAT(0) | CDB_MAX_PAYLOAD(max_payload) | CDB_DIRECTION(READ_TRANSACTION) | CDB_SPEED(dev->speed) | CDB_DATA_SIZE((dev->sectorSize * sectorsToRead))); + + cdb[i].DataDescriptor.low=(u32)bufferPtr; + cdb[i].DataDescriptor.high=0; + cdb[i].DataDescriptor.NodeID=dev->InitiatorNodeID; + + if(i>0){ + cdb[i-1].NextOrb.high=0; + cdb[i-1].NextOrb.low=(u32)&cdb[i]; + cdb[i-1].NextOrb.reserved=0; + } + + //scsi command packet + cdb[i].CDBs[3] = 0x2A; //write operation code + cdb[i].CDBs[2] = 0; //Reserved + cdb[i].CDBs[1] = (startingLBA & 0xFF000000) >> 24; //lba 1 (MSB) + cdb[i].CDBs[0] = (startingLBA & 0xFF0000) >> 16; //lba 2 + cdb[i].CDBs[7] = (startingLBA & 0xFF00) >> 8; //lba 3 + cdb[i].CDBs[6] = (startingLBA & 0xFF); //lba 4 (LSB) + cdb[i].CDBs[5] = 0; //Reserved + cdb[i].CDBs[4] = (sectorsToRead & 0xFF00) >> 8; //Transfer length MSB + cdb[i].CDBs[11] = (sectorsToRead & 0xFF); //Transfer length LSB + cdb[i].CDBs[10] = 0; //reserved + cdb[i].CDBs[9] = 0; //reserved + cdb[i].CDBs[8] = 0; //reserved + + startingLBA+=sectorsToRead; + sectorsRemaining-=sectorsToRead; + bufferPtr+=dev->sectorSize * sectorsToRead; + } + + /* NULL terminate the last ORB. */ + cdb[i-1].NextOrb.high=cdb[i-1].NextOrb.low=0; + cdb[i-1].NextOrb.reserved=NULL_POINTER; + + ieee1394_SendCommandBlockORB(dev, cdb); + result=ieee1394_Sync(); + } + + return result; +} + +static inline int InitializeSCSIDevice(struct SBP2Device *dev) { + inquiry_data id; + sense_data sd; + read_capacity_data rcd; + int stat; + + XPRINTF("IEEE1394_disk: InitializeSCSIDevice.\n"); + + memset(&id, 0, sizeof(inquiry_data)); + if ((stat = scsiInquiry(dev, &id, sizeof(inquiry_data))) < 0) { + XPRINTF("IEEE1394_disk: Error - scsiInquiry returned %d.\n", stat); + return -1; + } + + printf("IEEE1394_disk: Vendor: %.8s\n", id.vendor); + printf("IEEE1394_disk: Product: %.16s\n", id.product); + printf("IEEE1394_disk: Revision: %.4s\n", id.revision); + + if((stat = scsiReadCapacity(dev, &rcd, sizeof(read_capacity_data))) != 0) { + XPRINTF("IEEE1394_disk: Error - scsiReadCapacity %d\n", stat); + return -1; + } + + dev->sectorSize = rcd.block_length; + dev->maxLBA = rcd.last_lba; + + printf("IEEE1394_disk: sectorSize %lu maxLBA %lu\n", dev->sectorSize, dev->maxLBA); + + while((stat = scsiTestUnitReady(dev)) != 0) + { + XPRINTF("IEEE1394_disk: Error - scsiTestUnitReady %d\n", stat); + + stat = scsiRequestSense(dev, &sd, sizeof(sense_data)); + if (stat != 0) + XPRINTF("IEEE1394_disk: Error - scsiRequestSense %d\n", stat); + + if ((sd.error_code == 0x70) && (sd.sense_key != 0x00)) + { + XPRINTF("IEEE1394_disk: Sense Data key: %02X code: %02X qual: %02X\n", sd.sense_key, sd.add_sense_code, sd.add_sense_qual); + + if ((sd.sense_key == 0x02) && (sd.add_sense_code == 0x04) && (sd.add_sense_qual == 0x02)) + { + XPRINTF("IEEE1394_disk: Error - Additional initalization is required for this device!\n"); + if ((stat = scsiStartStopUnit(dev)) != 0) { + XPRINTF("IEEE1394_disk: Error - scsiStartStopUnit %d\n", stat); + return -1; + } + } + } + } + + return 0; +} + +void releaseSBP2Device(struct SBP2Device *dev){ + part_disconnect(dev); + scache_kill(dev->cache); +} + +int ConfigureSBP2Device(struct SBP2Device *dev) +{ + int ret; + + if((ret = InitializeSCSIDevice(dev))<0) + { + XPRINTF("IEEE1394_disk: Error - failed to warmup device 0x%08x\n", dev->nodeID); + return ret; + } + + if((dev->cache = scache_init(dev, dev->sectorSize))==NULL){ + XPRINTF("IEEE1394_disk: Error - scache_init failed \n" ); + return ret; + } + + return(part_connect(dev)); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/iLink/Makefile new file mode 100644 index 0000000..9893bc6 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/Makefile @@ -0,0 +1,12 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +SUBDIRS = iLinkman IEEE1394_disk IEEE1394_bd IEEE1394_bd_mini + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/Rules.make diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/Makefile new file mode 100644 index 0000000..5ebc093 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/Makefile @@ -0,0 +1,16 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_CFLAGS += -mno-check-zero-division + +IOP_OBJS = imports.o exports.o iLink.o iLink_PHY.o iLink_internal.o iLink_crom.o iLink_intr.o iLink_TxRx.o iLink_DMA.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/README b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/README new file mode 100644 index 0000000..4981c5d --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/README @@ -0,0 +1,64 @@ +iLinkman v0.98H README file - 2012/02/29 +============================================ + +iLinkman is a software driver for the Playstation 2's iLink port. + +Yes, DMA support has been added. Performance isn't really up to my original expectations, however. +The i.Link hardware doesn't seem to have any mechanisms to handle byte-swapping, and the IOP is left to swap the endianness of the data on it's own. D: + +On the up side, I got roughly around 7MB/s during my tests. +Not to mention that the iLink might even outperform the PS2's ethernet hardware, as the iLink hardware seems to be easier and simpler to configure and prepare for transmitting/receiving data. +Performance should still be better than the Sony iLink driver though, as less memcpy() calls are required to transfer data. + +Hardware tested on: +=================== +Consoles: + *SCPH-39006 (With an unknown modchip installed, possibly a M-Chip M2 chip) + *SCPH-10000 + +IEEE1394 enclosure: + *SmartDrive IEEE1394 + USB 2.0 combo HDD enclosure. + Chipset: Oxford Semiconductor OXUF934SSA-LQAG + +Additional notes: +================= +*IEEE1394 enclosures with a Prolific PL-3507, Initio INIC-1430 and a certain Genesys chip do not work with iLinkman. + +Credits: +======== +Special thanks go to: + *EEUG, for providing a partially completed IEEE1394/iLink driver for the PS2. + *Mark K., for volunteering to be a beta tester for the early iLinkman versions. + Silverbull, for contributing information regarding the DMAC belonging to the i.Link hardware. + +A short note for developers: +============================ +Most of the functions are similar to the functions available in Sony's ilink.irx module, and they are not multithread-safe. +That means that care should be taken to prevent multiple threads from calling any function from the library at the same time. +Check the header file "iLinkman.h" to see a list of exported functions. +I'll try to create a documentation for the functions soon. Meanwhile, feel free to ask me questions. + +I had several resources to aid me when I was building iLinkman. +The most important ones were the LSI technical manuals titled "1394 Node Controller Core" and "1394 Physical Layer (PHY) Core". + +They should be available on the Internet. +After all, I could still find them through a Google search (As of May 2011). + +There are three *critical* issues with the iLink hardware of some consoles: + 1. When the console is the root node, it seems like it cannot operate at higher speeds than S100. @_@ + Such behaviour can be observed with the Sony iLink driver too - when the console is the root node, the speed will always be S100 (And it seems to rarely be able to operate at full speed; S400). + When made to go faster, it seems like packets won't get sent (Or received by the receiver) at all. @_@ + The ideal solution to the issue will probably be to manually detect the maximum supported speed, but I think that the maximum speed will then always be S100 whenever the console is the root node lol. + (So it such a complicated system required? Just locking the speed to S100 mode whenever the console is the root node is a simpler solution). :X @_@ + + Well, if somebody can prove me wrong about this chip bug (And that there IS a correct way to control the iLink hardware), I'll be glad to be corrected. + I had spent a LONG time trying to fix this, and have came to this conclusion after monitoring the behaviour of the Sony iLink driver. + 2. Enabling the UTD interrupt (INTR1 register) seems to cause something to crash on the IOP. It's because the IOP is too slow and the iLink hardware killed the IOP by spamming interrupts. + ->Note: The UTD interrupt works fine if the IOP doesn't remain within the interrupt context for long periods of time. During my tests, the Multi-Threaded variant of iLinkman uses the UTD interrupt just fine, as the FIFOs are handled by individual threads (And not within the interrupt context). + 3. Sometimes, the receival of packets in the DBUF FIFOs will go unannounced. D: + ** UPDATE ** This problem does exist, but the LSI documents seem to recommend another method of receiving the SELF-ID packets. + By waiting for the SubActGap interrupt event to occur after detecting a bus reset, SELF-ID packets can be read from the DBUF FIFO without the problem of missing any of them. + + ** UPDATE 2 ** The problem here is related to the issue with the usage of the UTD interrupt event: The IOP is too slow and might miss some interrupt assertions. D: + The problem begins when the IOP is running an interrupt handler and the i.Link hardware asserts the BUS RESET interrupt event. The IOP misses that interrupt assertion and does not know about SELF-ID data in the UBUF/DBUF. + While the UBUF/DBUF contains SELF-ID packets, the i.Link hardware won't assert further interrupts regarding bus resets at all. D: diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/Changelog.txt b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/Changelog.txt new file mode 100644 index 0000000..7bc710b --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/Changelog.txt @@ -0,0 +1,196 @@ +NOTE! The entry at the top is the oldest, and the entry at the bottom is the newest! +------------------------------------------------------------------------------------ + +2011/03/14 - v0.90 +================================= +-Initial prototype version + +2011/03/17 - v0.91 +================================= +-Variout fixes were made, first functional version that could be used with PS2ESDL. + +2011/03/17 - v0.91A +================================= +-Changed the way IEEE1394 read and write responses and requests were handled. They are now handled from within the hardware interrupt itself. + This reduces the amount of random freezes, and improves performance slightly. + +2011/03/20 - v0.92 +================================= +-Re-written the read request handler, to reduce the amount of code. +-Solved the problem where block read requests seem to be in big endian. + It was caused by iLinkWritePHTReq() not byte-swapping the data before it's sent. + Actually, it's a design fault in the IEEE1394 write request function that use the PHT. +-Cleaned up the outstanding TODOs and FIXMEs. +-Added synchronization code to the end of the functions used for sending responses to IEEE1394 read/write requests. + +2011/03/20 - v0.93 +================================= +-Fixed iLinkReadCROM(), since it seemed to return some bogus value. +-Modified iLinkTrRead() and iLinkTrWrite() to return -1 for all requests to the local node. + IEEE1394 read/write functionality to the local node has not been implemented yet. +-Modified iLinkIntrHandler() to also check the level of DBUF Rx FIFO, as sometimes data that is received would go announced (And the hardware will still await a software acknowledgement). + As a result of the above, hotplugging of devices is now working. :) + +2011/04/15 - v0.94 +================================= +-Modified the initialization code in iLink_intr.c, to use defined values instead of hardcoded values. +-The above file was also modified to include initialization code that is slightly more stable. This will hopefully solve issues with my SCPH-10000 console. +-Modified iLinkIntrHandler() to also check the level of DBUF 01's Rx FIFO, as sometimes data that is received would go announced (And the hardware will still await a software acknowledgement). + As a result of the above, it seems like iLinkman is now working on my SCPH-10000 console. :) +-DBUF data handling code (In interrupt handler) had redundant code removed. +-Removed iLink_DMA.c, as it was proven that the DMA Controller (DMAC) was not connected to the iLink hardware. + Hence the iLink hardware is incapable of DMA transfers. + +2011/05/01 - v0.95 +================================= +-iLinkReadCROM() was changed to not keep allocating a new transaction context per call. This is for efficiency, given that most drivers that parse the configuration ROM of nodes won't be done after a handful of read requests. +-Due to the change above, iLinkReadCROM() will now take in a transaction context descriptor instead of a node ID as the first argument. +-Some of the configuration ROM manipulation functions that used to allocate a transaction context with the S100 speed as the starting speed have been modified to read data from the nodes at maximum speed. + There seems to be some issue with changing the speed on my SCPH-10000 console. :( + Once data was read from the device at S100 speed, it seems to be "reluctant" to work at a higher rate. + +2011/05/07 - v0.96 +================================= +-iLink_PHT.c was modified so that the driver won't cause a freeze by waiting for the misbehaving hardware of some consoles to acknowledge that data was transmitted sucessfully. + Currently, it causes a bus reset to reset the serial bus. + However, that is not the best solution as that is slow and seems to cause some occasional instability. + + At least the failure rate has dipped significantly. + +-iLink.c was also modified to include an approxmiately 5 seconds of delay before returning. + The delay seems to be necessary in order to give the serial bus time to stablize. + Otherwise, some node on the bus might cause a bus reset. :( +-All configuration ROM access functions have been hard-coded to run at S100 speed only. + This is for stability. +-Undid the change to iLinkReadCROM() as the old system was actually simpler to use and meant less code in the calling program. +-iLinkPHTSendData() in iLink_PHT.c now uses interrupts again. +-LocalCachedIntr0Register is no longer declared as volatile. +-The driver should now be compiled with optimization turned of. Otherwise, corruption/freezing might occur. :( + +2011/05/25 - v0.97 +================================= +-Sorted out the IEEE1394 Node Core initialization procedure. + Resorted to use normal (long) bus resets in place of the short bus resets, in case some older PS2 does not support short bus resets properly. D: +-The PHY and LINK are now cold-booted after being shut-down during the initialization of iLinkman. + This seems to be required to ensure proper operation of the iLink hardware, and seems to get rid of the timeout issues on my SCPH-10000. + In other words, the PHT request timeout workaround is no longer needed! Yay! :D + +2011/05/27 - v0.97A +================================= +-Reverted back to using short bus resets, since Sony was doing it and the node controller cores are supposed to be IEEE1394A compliant. +-The PHT request timeout was added back, as it seems like the issue with the PHT not responding on my SCPH-10000 was still there. + However, the 5-second data transfer time limit limitation is no longer present, as this new timeout mechanism only resets the iLink hardware if it detected the the PHT 01 had become stuck (PStk). +-Fixed a bug in iLinkReadCROM() that caused garbage to be read when more than one quadlet was requested at a time. +-iLinkReadCROM() will now automatically retry to read the target's configuration ROM after a failure, up to 5 retries. +-Adjusted iLinkFindUnit() to use iLinkReadCROM() instead of reading data from the target's configuration ROM directly. +-Fixed the way interrupts were acknowledged (Shifted to the front of the interrupt handler). + Some interrupt events need to be acknowledged as soon as possible or they will prevent the hardware from working properly. +-Enabled compiler optimization for all files, as the fault with random freezes under load stems from the above fault. +-Code in the interrupt handler was reduced. + +2011/05/29 - v0.97B +================================= +-Adjusted the speed lookup table in iLink.c to be constants. +-Corrected the max_rec size to 10 (2^(10+1)=2048 bytes). +-Corrected a bug in ParseUnitCROM() that might have resulted in incorrect address calculation (Shifted the increament of CROMOffset to the bottom of the loop at line 123). + +2011/06/01 - v0.97C +================================= +-Fixed several bugs in iLink_crom.c: + *Retries of read requests of the configuration ROM by iLinkReadCROM() will now stop once a read succeeds. + *iLinkGetNodeMaxSpeed() now returns the correct maximum supported speed for each node. +-Implemented handling of PHY packets. +-Fixed (yet again!) the receiving of SELF ID packets. This has got to be one of the most irritating parts of this driver. :( + +2011/06/26 - v0.98 +================================= +-Discontinued the useage of the PHTs as it seems like some older consoles have some rather nasty issues with them. :( +-Due to the above, the UBUFs will now see more usage. +-Thankfully, it seems like the functionality of the PHTs not only extend to the packets/transactions that were issued by them, but to any incoming IEEE1394 transaction packets that fall into the range of DMAR. + (No wonder Sony didn't have any issues with the PHTs locking up and were yet able to use the DBUF FIFOs). +-The Cycle Master bit of the CTRL0 register will now only be set after the SELF-ID phase. +-The bus will be reset until the console is not the root node. It seems like block writes won't work properly when the console is the root node. @_@ +-PHY register reading and writing code (And other functions that poll interrupts) has been improved. Now interrupt registers will have the interrupts acknowledged (Despite these interrupts being disabled). + +2011/06/28 - v0.98A +================================= +-I've KILLED the bug that cases packets to not get transmitted (Or received by the receiver). :D :D :D + Apparently, there is a chip bug in the iLink hardware of most consoles (Read the README file for more details). +-To accomplish the above, iLinkSetNodeTrSpeed() now locks the maximum data transfer rate to S100 whenever the console is the root node. +-Since the matter on packets not being sent correctly has been resolved, iLinkReadCROM() can now read data from the configuration ROMs at full speed. :D +-Cleaned up interrupts (Removed interrupt handling code and disable interrupts related to PHT control and status monitoring). +-Cleaned up code (Removed some leftover code that were used to control and initialize part of PHT 01; E.g. the code that configures the STO register). + +2011/07/XX to 2011/07/XX - v0.98B/C/D/E/F +========================================= +-Various fixes and experiments were made (I think that all relevant fixes were carried over into future builds that remained practical for usage). + +2011/07/XX - v0.98F +================================= +-DBUF 00 is now used to transmit data. + +2011/07/18 - v0.98D1 +================================= +-Multi-threaded version is now working. Probably the closest varient to the official Sony iLink driver. + +2011/07/20 - v0.98F1 +================================= +-Code that sends a response with the PHT has been removed. It was never used, and I don't think that it will ever work (Was the PHT even capable of sending responses via the application interface without DMA transfers enabled?). :/ + +2011/07/20 - v0.98A2 +================================= +-UBUF-only Tx varient of iLinkman. +-DBUF levels can now be read correctly. Previously, a logical right-shift of 18 followed by a logical AND of 0x1FFF was used to get the number of quads in the DBUF. However, that is not really correct as that might cause those reserved bits to affect the result. + The solution is the perform a logical AND with 0x7FF instead of 0x1FFF. +-Some unused code was removed (E.g. Calls to CpuSuspendIntr() in iLinkSendData()). +-iLink interrupt events will now be re-enabled only after the final call to iSetEventFlag() in iLink_intr(). + +2011/07/31-2011/08/11 - v0.98F2/v0.98A3/v0.98E1 +=============================================== +-That "hack" that involved acknowledging the "missing" DBUF and UBUF packet interrupt events is now obsolete. +-SELF-ID packets are only received after the Arbitration Reset Gap interrupt event occurs. The LSI document states that SELF-ID packets can be received after waiting for the ArbRstGap interrupt event after detecting a bus reset. + Hence, there is no way for SELF-ID packets to get lost by the driver once they have been received by the hardware. +-Code has been cleaned up, adding the REQ_CHECK_MEM_BOUNDARIES option to configure the driver to have (or not to have) memory address checks for incoming requests. + +2011/08/13 - v0.98F3 +================================= +-Reverted back to the old system of acknowledging interrupt events immediately when the interrupt was asserted, since the new method seems to cause instability under certain conditions. + The new system only seems to work properly with the MT version of iLinkman. + +2011/09/29 - v0.98F4 +================================= +-Consolidated all calls to AllocSysMemory() and FreeSysMemory() to internal versions of malloc() and free() respectively. Within the malloc() and free() functions, AllocSysMemory() and FreeSysMemory() are called respectively after suspending interrupts and thread cycling. + This is to observe the requirements of AllocSysMemory() and FreeSysMemory(). +-Added a timeout to the code that waits for the arbitration reset gap before checking the FIFO for SELF-ID packets in iLink_intr.c, since the IOP is sooo slow that it might miss the one and only Arbitration reset gap if the PS2 is the only node on the network. + Anyway, is it even normal for there to be only one arbitration reset gap?! Of course, that is assuming that there is only one node present on the network at that time. +-Cleaned up, shortened and simplified code here and there. +-Replaced all "volatile unsigned long int" datatypes with "volatile unsigned int" of variables that refer to hardware registers, since registers are meant to be as long as a single word of the processor. +-Shifted all literations of the code that denies transactions to the local node into iLinkTrAlloc(), since all transactions have to be allocated first. +-Code that polls registers in loops within iLink_PHY.c now loop with calls to DelayThread(), so as to not hog the IOP. +-Code that polls the PHY Access register of the iLink hardware have now been consolidated into the synchronization function within iLink_PHY.c. +-The Makefile has been edited to use the default level of optimization as specified by the development environment. + +2011/11/20 and 2011/11/21 - v0.98G +================================== +-Added working DMA support. + +2012/02/21-2012/02/29 - v0.98H +================================= +-Large-scale system overhaul. Redesigned to have better reliability and to not suck the life force out of the IOP. + *The UBUF is now managed with a thread, which I suppose is what Sony would have intended. + *Interrupts are also handled with a thread, hence all callbacks will not be within an interrupt context. + *Transmissions made with the UBUF are now done with the UTD interrupt event and have a split-timeout mechanism. +-Added iLinkGetLocalNodeEUI64(), which returns the EUI of the console. +-The calls to the dmac_ch_get_dpcr() and dmac_ch_set_dpcr() functions used for enabling and disabling DMA channels have been replaced by calls to dmac_enable() and dmac_disable(). +-The CHCR register of DMA channels are now cleared before the channels are disabled. This is to prevent crashes that might occur when the channels are re-enabled. +-Hardware interrupt events are now disabled before the i.Link hardware is reset. +-Removed code from ResetHW() that was intended to be used to detect consoles that do not have functional i.Link controllers, since I've just discovered that my SCPH-77006 seems to have some chip logic that emulates a real i.Link controller... so those lines of code never works as intended. +-Fixed a bug caused by all event flag bits being cleared by the call to ClearEventFlag() within the UBUF data handling thread in iLink_internal.c. +-Added the REQ_CHECK_CONSOLE_VERSION option, which controls a version check on the console. Newer consoles that lack a physical i.Link port will cause a crash when anything related to DMAC #3 is accessed. + Although Sony seems to have included the iLink controller in my SCPH-77006 console, it seems like DMAC #3 is missing from it's usual spot, and rom0:DMACMAN doesn't even know about the change. + Doing anything with DMAC #3 resulted in bus errors. Strangely, DMAC #3 can be disabled at the startup of rom0:DMACMAN... I wonder why. Maybe I'm wrong, and DMACMAN doesn't disable the channels of DMAC #3 on my SCPH-77006 at bootup. + +2012/04/06 - v0.98H1 +================================= +-Fixed UBUF split timeout handling. Previously, iLinkSync() did not check for the iLinkEventError bit properly and the split timeout was too short (Incorrectly calculated). iLinkSync() did not return an error whenever a split timeout occurred. +-Changed the argument that specified which registers INTRMAN should preserve prior to calling the interrupt handler (Changed from 2 to 1), since it seems like all other interrupt handlers in other drivers use 1 anyway... and is it necessary to preserve the extra registers that will be saved with mode 2, compared to mode 1? diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/KnownIssues.txt b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/KnownIssues.txt new file mode 100644 index 0000000..61b60fd --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/KnownIssues.txt @@ -0,0 +1,6 @@ +-Some Firewire/IEEE1394 IDE/SATA to IEE1394/Firewire chipsets are not compatible. +-iLinkman will cause bus errors on newer consoles that lack a physical i.Link port as DMAC #3 doesn't seem to exist on those consoles. + Even the DMACMAN module on those consoles do not seem to be aware of a lack of DMAC #3, and bus errors can occur within the DMACMAN module too. + **UPDATE: I've added a console version check that will cause iLinkman to not load if the console has a BIOS newer than v1.60. + +Last Updated: 2012/02/29 diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/Notes.txt b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/Notes.txt new file mode 100644 index 0000000..eaf2869 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/Notes.txt @@ -0,0 +1,8 @@ +There are some oddities when it comes to data transfers. +Maybe it was already covered in the full, official documentation (Which I didn't have), but these were what I had noticed: + +1. When a write request is received, the data seems to be in little endian (For both quadlet and block write requests). +2. When a read request is received, the data sent must be converted into little Endian if the request was a block read request. + >>Quadlet read requests seem to be fine when the payload of the response is sent in little endian. (!) +3. When a read request is made, the data returned in the response seems to be in Big Endian format if it was a block read request. + >> If it was a quadlet read request that was made, the data returned seems to already be in little endian. (!!) diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/TODO.txt b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/TODO.txt new file mode 100644 index 0000000..8caa053 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/doc/TODO.txt @@ -0,0 +1,11 @@ +-Add lock transaction support (?). +-Add isochronous transaction support (?). +-Write a API compatibility module to make this module compatible with SCE's functions (?). +-Add multi-transaction label support(?) +-Verify and fix compatibility with post v8 consoles (Consoles lacking the i.Link hardware). +-Verify the validity of the configuration ROM. +-Come up with a feasible system to determine whether the console contains a valid i.Link port or not. + It appears that consoles that do not have physical i.Link ports still contain sufficient chip logic to emulate a functional i.Link controller. +-Discover and use the DMAC #3 interrupt entry in INTRMAN. + +Last updated: 2012/02/29 \ No newline at end of file diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/include/iLinkman.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/include/iLinkman.h new file mode 100644 index 0000000..f45a957 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/include/iLinkman.h @@ -0,0 +1,88 @@ +/* iLinkman.h + * Purpose: Main header file containing function prototypes, structure declaration and other declarations. + * + * Last Updated: 2012/02/28 + * Programmer: SP193 + */ + +#ifndef __ILINKMAN_H__ +#define __ILINKMAN_H__ + +#include +#include + +#define BSWAP32(x) ((x<<24)|((x&0xff00)<<8)|((x&0xff0000)>>8)|(x>>24)) +#define BSWAP16(x) ((((unsigned short int)x)<<8)|(x>>8)) + +/* IEEE1394 speeds */ +#define S100 0 +#define S200 1 +#define S400 2 + +#define iLink_NODE_IRMC 0x10 +#define iLink_NODE_CMC 0x08 +#define iLink_NODE_ISC 0x04 +#define iLink_NODE_BMC 0x02 +#define iLink_NODE_PMC 0x01 + +#define iLink_CB_WRITE_REQUEST 0x01 +#define iLink_CB_READ_REQUEST 0x02 +#define iLink_CB_LOCK_REQUEST 0x04 +#define iLink_CB_BUS_RESET 0x08 + +void iLinkEnableSBus(void); +void iLinkDisableSBus(void); +void iLinkResetSBus(void); +unsigned int iLinkSetNodeCapabilities(unsigned int capabilities); +void *iLinkSetTrCallbackHandler(void *function); +int iLinkGetGenerationNumber(void); + +int iLinkGetLocalNodeID(void); +int iLinkGetNodeCount(void); + +int iLinkTrAlloc(unsigned short int NodeID, unsigned char speed); +void iLinkTrFree(int trContext); +int iLinkTrWrite(int trContext, unsigned short int offset_high, unsigned int offset_low, void *buffer, unsigned int nBytes); +int iLinkTrRead(int trContext, unsigned short int offset_high, unsigned int offset_low, void *buffer, unsigned int nBytes); + +unsigned short int iLinkCalculateCRC16(void *data, unsigned int nQuads); +int iLinkAddCROMUnit(unsigned int *data, unsigned int nQuads); +void iLinkDeleteCROMUnit(unsigned int id); +int iLinkGetNodeCapabilities(unsigned short NodeID); +int iLinkGetNodeMaxSpeed(unsigned short int NodeID); + +int iLinkGetNodeTrSpeed(int trContext); +int iLinkSetNodeTrSpeed(int trContext, unsigned char speed); + +int iLinkFindUnit(int UnitInList, unsigned int UnitSpec, unsigned int UnitSW_Version); +int iLinkReadCROM(unsigned short int NodeID, unsigned int Offset, unsigned int nQuads, unsigned int *buffer); + +u64 iLinkGetLocalNodeEUI64(void); + +#define iLinkman_IMPORTS_start DECLARE_IMPORT_TABLE(iLinkman, 1, 1) +#define iLinkman_IMPORTS_end END_IMPORT_TABLE + +#define I_iLinkEnableSBus DECLARE_IMPORT(4, iLinkEnableSBus) +#define I_iLinkDisableSBus DECLARE_IMPORT(5, iLinkDisableSBus) +#define I_iLinkResetSBus DECLARE_IMPORT(6, iLinkResetSBus) +#define I_iLinkSetNodeCapabilities DECLARE_IMPORT(7, iLinkSetNodeCapabilities) +#define I_iLinkSetTrCallbackHandler DECLARE_IMPORT(8, iLinkSetTrCallbackHandler) +#define I_iLinkGetGenerationNumber DECLARE_IMPORT(9, iLinkGetGenerationNumber) +#define I_iLinkGetLocalNodeID DECLARE_IMPORT(10, iLinkGetLocalNodeID) +#define I_iLinkGetNodeCount DECLARE_IMPORT(11, iLinkGetNodeCount) +#define I_iLinkTrAlloc DECLARE_IMPORT(12, iLinkTrAlloc) +#define I_iLinkTrFree DECLARE_IMPORT(13, iLinkTrFree) +#define I_iLinkTrWrite DECLARE_IMPORT(14, iLinkTrWrite) +#define I_iLinkTrRead DECLARE_IMPORT(15, iLinkTrRead) +#define I_iLinkCalculateCRC16 DECLARE_IMPORT(16, iLinkCalculateCRC16) +#define I_iLinkAddCROMUnit DECLARE_IMPORT(17, iLinkAddCROMUnit) +#define I_iLinkDeleteCROMUnit DECLARE_IMPORT(18, iLinkDeleteCROMUnit) +#define I_iLinkGetNodeCapabilities DECLARE_IMPORT(19, iLinkGetNodeCapabilities) +#define I_iLinkGetNodeMaxSpeed DECLARE_IMPORT(20, iLinkGetNodeMaxSpeed) +#define I_iLinkGetNodeTrSpeed DECLARE_IMPORT(21, iLinkGetNodeTrSpeed) +#define I_iLinkSetNodeTrSpeed DECLARE_IMPORT(22, iLinkSetNodeTrSpeed) +#define I_iLinkFindUnit DECLARE_IMPORT(23, iLinkFindUnit) +#define I_iLinkReadCROM DECLARE_IMPORT(24, iLinkReadCROM) +#define I_iLinkGetLocalNodeEUI64 DECLARE_IMPORT(12, iLinkGetLocalNodeEUI64) + +#endif /* __ILINKMAN_H__ */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/exports.tab b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/exports.tab new file mode 100644 index 0000000..38a91f7 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/exports.tab @@ -0,0 +1,30 @@ +void _funcret(){}; + +DECLARE_EXPORT_TABLE(iLinkman, 1, 1) + DECLARE_EXPORT(_start) /* 000 */ + DECLARE_EXPORT(_funcret) + DECLARE_EXPORT(_exit) /* 002 */ + DECLARE_EXPORT(_funcret) /* 003 */ + DECLARE_EXPORT(iLinkEnableSBus) /* 004 */ + DECLARE_EXPORT(iLinkDisableSBus) /* 005 */ + DECLARE_EXPORT(iLinkResetSBus) /* 006 */ + DECLARE_EXPORT(iLinkSetNodeCapabilities) /* 007 */ + DECLARE_EXPORT(iLinkSetTrCallbackHandler) /* 008 */ + DECLARE_EXPORT(iLinkGetGenerationNumber) /* 009 */ + DECLARE_EXPORT(iLinkGetLocalNodeID) /* 010 */ + DECLARE_EXPORT(iLinkGetNodeCount) /* 011 */ + DECLARE_EXPORT(iLinkTrAlloc) /* 012 */ + DECLARE_EXPORT(iLinkTrFree) /* 013 */ + DECLARE_EXPORT(iLinkTrWrite) /* 014 */ + DECLARE_EXPORT(iLinkTrRead) /* 015 */ + DECLARE_EXPORT(iLinkCalculateCRC16) /* 016 */ + DECLARE_EXPORT(iLinkAddCROMUnit) /* 017 */ + DECLARE_EXPORT(iLinkDeleteCROMUnit) /* 018 */ + DECLARE_EXPORT(iLinkGetNodeCapabilities) /* 019 */ + DECLARE_EXPORT(iLinkGetNodeMaxSpeed) /* 020 */ + DECLARE_EXPORT(iLinkGetNodeTrSpeed) /* 021 */ + DECLARE_EXPORT(iLinkSetNodeTrSpeed) /* 022 */ + DECLARE_EXPORT(iLinkFindUnit) /* 023 */ + DECLARE_EXPORT(iLinkReadCROM) /* 024 */ + DECLARE_EXPORT(iLinkGetLocalNodeEUI64) /* 025 */ +END_EXPORT_TABLE diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink.c new file mode 100644 index 0000000..751793b --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink.c @@ -0,0 +1,268 @@ +/* iLink.c + * Purpose: Contains the main functions of the iLinkman driver. + * It contains functions that are exported for use by other modules, and contains the entry point function. + * + * Last Updated: 2012/02/29 + * Programmer: SP193 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "iLinkman.h" +#include "iLink_internal.h" + +#define MODNAME "iLINK_HW_Manager" +IRX_ID(MODNAME, 0x00, 0x98); + +/* Global variables. */ +extern struct irx_export_table _exp_iLinkman; + +struct ILINKMemMap *ILINKRegisterBase=(struct ILINKMemMap *)ILINK_REGISTER_BASE; +extern struct TransactionContextData TransactionContexts[MAX_CONCURRENT_TRANSACTIONS]; +extern unsigned int *ConfigurationROM; +void (*CallBackFunction)(int reason, unsigned int offset, unsigned int size); + +u64 ConsoleGUID; +char ConsoleModelName[32]; + +unsigned short int LocalNodeID; + +extern int GenerationNumber; +extern int nNodes; +extern int NodeCapabilities; + +int IntrEventFlag, UBUFTxSema, UBUFThreadID; + +extern unsigned char IsBusRoot; + +static iop_event_t EventFlagData={ + 2, /* evfp.attr=EA_MULTI */ + 0, /* evfp.option */ + 0 /* evfp.bits */ +}; + +/* SP193: Get the console's BIOS version, and refuse to load if the console is a iLink-free console. + Although Sony seems to have included the iLink controller in my SCPH-77006 console, it seems like DMAC #3 is missing from it's usual spot, and rom0:DMACMAN doesn't even know about the change. + Doing anything with DMAC #3 resulted in bus errors. Strangely, DMAC #3 can be disabled at the startup of rom0:DMACMAN... I wonder why. Maybe I'm wrong, and DMACMAN doesn't disable the channels of DMAC #3 on my SCPH-77006 at bootup. +*/ +#ifdef REQ_CHECK_CONSOLE_VERSION +static inline unsigned int GetBIOSVersion(void){ + char romver_str[5]; + int fd; + + fd=open("rom0:ROMVER", O_RDONLY); + read(fd, romver_str, 4); + close(fd); + + romver_str[4]='\0'; + return strtoul(romver_str, NULL, 16); +} +#endif + +int _start(int argc, char **argv){ + int i, result; + iop_thread_t ThreadData; + + DEBUG_PRINTF("iLink driver version 0.98H\n"); + +#ifdef REQ_CHECK_CONSOLE_VERSION + if(GetBIOSVersion()>0x160){ + printf("Unsupported console detected. Not loading.\n"); + return MODULE_NO_RESIDENT_END; + } +#endif + + iLinkDisableIntr(); + + if((result=iLinkResetHW())<0){ + DEBUG_PRINTF("Error occurred while resetting i.Link hardware. Code: %d\n", result); + return MODULE_NO_RESIDENT_END; + } + + iLinkHWInitialize(); + + DEBUG_PRINTF("Initializing Configuration ROM...\n"); + + memset(ConsoleModelName, 0, sizeof(ConsoleModelName)); + ConsoleGUID=0; + GetConsoleIDs(&ConsoleGUID, ConsoleModelName); + DEBUG_PRINTF("Console GUID: 0x%08lx %08lx, ModelName: %s.\n", (u32)(ConsoleGUID>>32), (u32)ConsoleGUID, ConsoleModelName); + + InitializeConfigurationROM(); + + CallBackFunction=NULL; + IntrEventFlag=CreateEventFlag(&EventFlagData); + UBUFTxSema=CreateMutex(IOP_MUTEX_UNLOCKED); + + ThreadData.attr=TH_C; + ThreadData.option=0; + ThreadData.thread=&UBUFThread; + ThreadData.stacksize=0x350; + ThreadData.priority=0x60; + + StartThread(UBUFThreadID=CreateThread(&ThreadData), NULL); + + RegisterIntrHandler(IOP_IRQ_ILINK, 1, &iLinkIntrHandler, NULL); + EnableIntr(IOP_IRQ_ILINK); + + for(i=0; ictrl0&=~(iLink_CTRL0_RxEn|iLink_CTRL0_TxEn); /* CTL0: ~(TxEn | RxEn) */ +} + +void iLinkResetSBus(void){ + ClearEventFlag(IntrEventFlag, ~(iLinkEventBusReady|iLinkEventGotSELFIDs)); + + DEBUG_PRINTF("-=Reseting bus=-\n"); + + iLinkPHYBusReset(); + + DEBUG_PRINTF("-=Waiting for the serial bus to be ready=-\n"); + WaitEventFlag(IntrEventFlag, iLinkEventBusReady|iLinkEventGotSELFIDs, WEF_AND, NULL); /* Wait for the bus to be completely reset. */ + DEBUG_PRINTF("-=Bus reset and ready=-\n"); +} + +void *iLinkSetTrCallbackHandler(void *function){ + void *cb_function; + + cb_function=CallBackFunction; + CallBackFunction=function; + + return cb_function; +} + +static const unsigned char speeds[3]={ + 0, /* S100 */ + 2, /* S200 */ + 4 /* S400 */ +}; + +int iLinkGetNodeTrSpeed(int trContext){ + int CurrentSpeed, i; + + CurrentSpeed=-1; + for(i=0; i<3; i++){ + if(speeds[i]==TransactionContexts[trContext].speed){ + CurrentSpeed=i; + break; + } + } + + return CurrentSpeed; +} + +int iLinkSetNodeTrSpeed(int trContext, unsigned char speed){ + int result; + + result=iLinkGetNodeTrSpeed(trContext); + + /* !!HACK!! Due to a chip bug (?) in the iLink hardware of most consoles, limit the speed to S100 mode whenever the console is the root node + (Read the README file for more details on this bug). */ + if(IsBusRoot) speed=S100; + + /* Assign the specified speed to the specified transaction. Assign the maxium allowed speed if the specified speed is above the maximum value. */ + TransactionContexts[trContext].speed=(speed>(sizeof(speeds)-1))?speeds[sizeof(speeds)-1]:speeds[speed]; + + return result; +} + +u64 iLinkGetLocalNodeEUI64(void){ + return ConsoleGUID; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_DMA.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_DMA.c new file mode 100644 index 0000000..27763a0 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_DMA.c @@ -0,0 +1,114 @@ +/* iLink_PHT.c + * Purpose: Contains the functions related to IEEE1394 read/write requests that are to be generated by PHT 00, and functions related to initializing both PHTs and DMAC #3. + * Only block reads and writes are supported by functions in this files. + * + * Last Updated: 2012/02/22 + * Programmer: SP193 + */ + +#include +#include +#include +#include +#include + +#include "iLinkman.h" +#include "iLink_internal.h" + +extern unsigned short int LocalNodeID; +extern int IntrEventFlag; + +extern int GenerationNumber; + +extern struct ILINKMemMap *ILINKRegisterBase; +extern unsigned int *TargetBuffer; +extern unsigned int LocalCachedIntr0Register; + +struct DMAChannelRegBlock *iLinkDMACRegs=(struct DMAChannelRegBlock *)ILINK_DMAC_REGISTER_BASE; +struct DMARRegBlock *iLinkDMARRegs=(struct DMARRegBlock *)ILINK_DMAC_DMAR_CTRL_BASE; + +static int iLinkPHTSendData(struct TransactionContextData *trContext, unsigned char tCode, unsigned short int offset_high, unsigned int offset_low, unsigned int *payload, unsigned int nBytes, char ByteSwap); + +void iLinkInitPHT(void){ + /* Stop all DMA-related activities */ + iLinkDMACRegs[0].chcr=iLinkDMACRegs[2].chcr=0; + + ILINKRegisterBase->PHT_ctrl_ST_R0=PHT_CTRL_ST_PHTRst; /* Reset PHT 00 */ + ILINKRegisterBase->PHT_ctrl_ST_R1=PHT_CTRL_ST_PHTRst; /* Reset PHT 01 */ + + while((ILINKRegisterBase->PHT_ctrl_ST_R0&PHT_CTRL_ST_PHTRst) || (ILINKRegisterBase->PHT_ctrl_ST_R1&PHT_CTRL_ST_PHTRst)){}; + + ILINKRegisterBase->dmar=0x00000020; /* DMA space is within the 2MB of IOP memory. */ + ILINKRegisterBase->PHT_ctrl_ST_R1=PHT_CTRL_ST_EnDMAS|PHT_CTRL_ST_IHdr; /* EnDMAS | IHdr */ + ILINKRegisterBase->PHT_ctrl_ST_R0=0; + + ILINKRegisterBase->STRxNIDSel0_R1=ILINKRegisterBase->STRxNIDSel1_R1=0xFFFFFFFF; /* Accept DMA transfers from all nodes. */ + ILINKRegisterBase->STRxNIDSel0_R0=ILINKRegisterBase->STRxNIDSel1_R0=0; /* Reject DMA transfers from all nodes. */ + + iLinkDMACRegs[0].slice=iLinkDMACRegs[2].slice=0x400; + iLinkDMACRegs[2].chcr=DMAC_CHCR_AR|DMAC_CHCR_CO; + + iLinkDMACRegs[0].DmarReadStart=iLinkDMACRegs[2].DmarReadStart=iLinkDMARRegs->DmarWriteStart=0x00000800; + iLinkDMACRegs[0].DmarReadEnd=iLinkDMACRegs[2].DmarReadEnd=iLinkDMARRegs->DmarWriteEnd=0x00200000; + + ILINKRegisterBase->dmaTransTRSH0=0x03FF0000; + ILINKRegisterBase->dmaTransTRSH1=0x000F03FF; + ILINKRegisterBase->dmaCtrlSR0=ILINKRegisterBase->dmaCtrlSR1=iLinkDMA_CTRL_SR_LFirst|iLinkDMA_CTRL_SR_DWidth(2)|iLinkDMA_CTRL_SR_DEn|iLinkDMA_CTRL_SR_RActl; + + ILINKRegisterBase->PHT_split_TO_R1=ILINKRegisterBase->PHT_split_TO_R0=0x00000800; /* STO: 0x800 */ +} + +static int iLinkPHTSendData(struct TransactionContextData *trContext, unsigned char tCode, unsigned short int offset_high, unsigned int offset_low, unsigned int *payload, unsigned int nBytes, char ByteSwap){ + unsigned char tLabel; + unsigned int PHT_ctrl_ST_R0_flags; + + if(trContext->GenerationNumber!=GenerationNumber) return(-1021); + + ClearEventFlag(IntrEventFlag, ~(iLinkEventDMATransEnd|iLinkEventError)); + + ByteSwap=0; + + PHT_ctrl_ST_R0_flags=(tCode==IEEE1394_TCODE_WRITEB)?PHT_CTRL_ST_EPCNT|PHT_CTRL_ST_EWREQ:PHT_CTRL_ST_EPCNT|PHT_CTRL_ST_ERREQ; /* EWReq and EPCnt, OR ERReq and EPCnt. */ + tLabel=0x3F; /* PHT 00 */ + + ILINKRegisterBase->PHT_ReqResHdr0_R0=(((unsigned int)trContext->NodeID)<<16) | offset_high; + ILINKRegisterBase->PHT_ReqResHdr1_R0=offset_low; + ILINKRegisterBase->PHT_ReqResHdr2_R0=(((unsigned int)tLabel)<<19) | (((unsigned int)trContext->speed)<<16) | nBytes; + + ILINKRegisterBase->DTransCTRL0=1; /* Only 1 packet. */ + ILINKRegisterBase->PHT_ctrl_ST_R0|=PHT_ctrl_ST_R0_flags; + + iLinkDMACRegs[0].madr=(unsigned int)payload; + iLinkDMACRegs[0].dlen=nBytes; + iLinkDMACRegs[0].chcr=DMAC_CHCR_TR|DMAC_CHCR_CO; + + DEBUG_PRINTF("Waiting for interrupt...\n"); + WaitEventFlag(IntrEventFlag, iLinkEventDMATransEnd|iLinkEventError, WEF_OR, NULL); + + ILINKRegisterBase->PHT_ctrl_ST_R0&=(~PHT_ctrl_ST_R0_flags); + + DEBUG_PRINTF("Processing results...\n"); + + if(LocalCachedIntr0Register&iLink_INTR0_InvAck) return(-1023); + if(LocalCachedIntr0Register&iLink_INTR0_STO) return(-1024); + if(LocalCachedIntr0Register&iLink_INTR0_AckMiss) return(-1025); + if(LocalCachedIntr0Register&iLink_INTR0_RetEx) return(-1026); + + return nBytes; +} + +/* !!! NOTE !!! This function only supports issuing BLOCK read requests! Quadlet read requests should be issued with the equilvalent function that uses the UBUF. */ +int iLinkReadPHTReq(struct TransactionContextData *trContext, unsigned short int offset_high, unsigned int offset_low, void *buffer, unsigned int nBytes){ + DEBUG_PRINTF("iLinkReadPHTReq() 0x%08x 0x%08x; nbytes: 0x%08x. Node: 0x%04x.\n", offset_high, offset_low, nBytes, trContext->NodeID); + + TargetBuffer=buffer; + + return(iLinkPHTSendData(trContext, IEEE1394_TCODE_READB, offset_high, offset_low, NULL, nBytes, 0)); +} + +/* !!! NOTE !!! This function only supports issuing BLOCK write requests! Quadlet write requests should be issued with the equilvalent function that uses the UBUF. */ +int iLinkWritePHTReq(struct TransactionContextData *trContext, unsigned short int offset_high, unsigned int offset_low, void *buffer, unsigned int nBytes){ + DEBUG_PRINTF("iLinkWritePHTReq() 0x%08x 0x%08x; nbytes: 0x%08x. Node: 0x%04x.\n", offset_high, offset_low, nBytes, trContext->NodeID); + + return(iLinkPHTSendData(trContext, IEEE1394_TCODE_WRITEB, offset_high, offset_low, buffer, nBytes, 1)); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_PHY.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_PHY.c new file mode 100644 index 0000000..cd30b2e --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_PHY.c @@ -0,0 +1,63 @@ +/* iLink_PHY.c + * Purpose: Contains the functions that are used for writing/reading values from the PHY. + * + * Last Updated: 2012/02/20 + * Programmer: SP193 + */ + +#include + +#include "iLinkman.h" +#include "iLink_internal.h" + +extern struct ILINKMemMap *ILINKRegisterBase; + +#define RdPhy 0x80000000 +#define WrPhy 0x40000000 + +static void iLinkPhySync(void){ + while(ILINKRegisterBase->PHYAccess&(RdPhy|WrPhy)){}; +} + +unsigned char iLinkReadPhy(unsigned char address){ + ILINKRegisterBase->PHYAccess=(((unsigned int)address)<<24)|RdPhy; + iLinkPhySync(); + + while(!(ILINKRegisterBase->intr0&iLink_INTR0_PhyRRx)){}; + ILINKRegisterBase->intr0=iLink_INTR0_PhyRRx; + + return(ILINKRegisterBase->PHYAccess&0xFF); +} + +void iLinkWritePhy(unsigned char address, unsigned char data){ + ILINKRegisterBase->PHYAccess=(((unsigned int)address)<<24)|(((unsigned int)data)<<16)|WrPhy; + iLinkPhySync(); +} + +void iLinkPHY_SetRootBit(int isRoot){ + unsigned short int Register01value; + + Register01value=iLinkReadPhy(1); + if(isRoot) Register01value|=REG01_RHB; + else Register01value&=(~REG01_RHB); + + iLinkWritePhy(1, Register01value); +} + +void iLinkPHY_SetGapCount(unsigned char GapCount){ + iLinkWritePhy(1, (iLinkReadPhy(1)&0xC0)|GapCount); +} + +void iLinkPHY_SetLCTRL(int LCTRL_status){ + unsigned short int Register04value; + + Register04value=iLinkReadPhy(4); + if(LCTRL_status) Register04value|=REG04_LCTRL; + else Register04value&=(~REG04_LCTRL); + + iLinkWritePhy(4, Register04value); +} + +void iLinkPHYBusReset(void){ + iLinkWritePhy(5, iLinkReadPhy(5)|REG05_ISBR); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_TxRx.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_TxRx.c new file mode 100644 index 0000000..98ebfe4 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_TxRx.c @@ -0,0 +1,175 @@ +/* iLink_TxRx.c + * Purpose: Contains the functions that are used to transmit IEEE1394 response and request packets via the UBUF. + * Only quadlet reads and writes are supported by functions in this files. + * + * Last Updated: 2012/02/21 + * Programmer: SP193 + */ + +#include +#include +#include +#include +#include +#include + +#include "iLinkman.h" +#include "iLink_internal.h" + +extern unsigned short int LocalNodeID; +extern int GenerationNumber; +extern int IntrEventFlag; + +extern struct ILINKMemMap *ILINKRegisterBase; +extern struct DMAChannelRegBlock *iLinkDMACRegs; +extern unsigned *TargetBuffer; +extern unsigned int LocalCachedIntr0Register; +extern int UBUFTxSema; + +static int iLinkSendData(struct TransactionContextData *trContext, unsigned int *header, unsigned int HeaderLength, unsigned int *payload, unsigned int PayloadLength); + +static int iLinkSendData(struct TransactionContextData *trContext, unsigned int *header, unsigned int HeaderLength, unsigned int *payload, unsigned int PayloadLength){ + unsigned int i, *data; + u32 FlagBits; + + WaitSema(UBUFTxSema); + ClearEventFlag(IntrEventFlag, ~(iLinkEventDataSent|iLinkEventDataReceived|iLinkEventError)); + + ILINKRegisterBase->ubufTransmitClear=0; + data=header; + + /* Transmit the header... */ + for(i=0; iGenerationNumber!=GenerationNumber)) return(-1021); + + ILINKRegisterBase->ubufTransmitNext=*data; + data++; + } + + /* Now transmit the payload. */ + if(PayloadLength>0){ + data=payload; + for(i=0; iGenerationNumber!=GenerationNumber)) return(-1021); + ILINKRegisterBase->ubufTransmitNext=*data; + data++; + } + } + + ILINKRegisterBase->ubufTransmitLast=*(data-1); + + DEBUG_PRINTF("Transmitting payload...\n"); + WaitEventFlag(IntrEventFlag, iLinkEventDataSent|iLinkEventError, WEF_OR, &FlagBits); + + if(FlagBits&iLinkEventError){ + DEBUG_PRINTF("iLinkman: TX Error.\n"); + } + + SignalSema(UBUFTxSema); + + return((FlagBits&iLinkEventError)?-1:PayloadLength); +} + +void SendResponse(unsigned short int NodeID, unsigned short RcvdBusID, unsigned char rCode, unsigned char tLabel, unsigned char tCode, unsigned char speed, unsigned int *buffer, unsigned int nQuads){ + struct ieee1394_TrResponsePacketHdr ResponseHeader; + unsigned int ResponseHeaderLength; + + ResponseHeaderLength=(tCode==IEEE1394_TCODE_READB_RESPONSE)?4:3; + + DEBUG_PRINTF("Sending response to: 0x%04x, RcvdBusID: 0x%04x, rcode: %d, Header length: %u, speed: 0x%04x. Payload length: 0x%08x.\n", NodeID, RcvdBusID, rCode, ResponseHeaderLength, speed, nQuads); + DEBUG_PRINTF("tCode: 0x%02x\n", tCode); + + ResponseHeader.header=(((unsigned int)RcvdBusID)<<22) | (((unsigned int)speed)<<16) | (((unsigned int)tLabel)<<10) | (1<<8) | (((unsigned int)tCode)<<4); + ResponseHeader.header2=(((unsigned int)NodeID)<<16) | (((unsigned int)rCode)<<12); + ResponseHeader.reserved=0; + ResponseHeader.LastField=nQuads<<18; + + iLinkSendData(NULL, (unsigned int *)&ResponseHeader, ResponseHeaderLength, buffer, nQuads); +} + +static iop_sys_clock_t Timeout={ + 0x8E9400, /* 0x800*125us / (1/36.5MHz) */ + 0 +}; + +static unsigned int TimeoutCallbackFunction(void *argv){ + iSetEventFlag(IntrEventFlag, iLinkEventError); + return 0; +} + +static int iLinkSync(unsigned int PayloadLength){ + u32 FlagBits; + + DEBUG_PRINTF("Payload transmitted. Now awaiting response...\n"); + + SetAlarm(&Timeout, &TimeoutCallbackFunction, NULL); + WaitEventFlag(IntrEventFlag, iLinkEventDataReceived|iLinkEventError, WEF_OR, &FlagBits); + + if(!(FlagBits&iLinkEventError)){ + CancelAlarm(&TimeoutCallbackFunction, NULL); + } + else{ + DEBUG_PRINTF("iLinkman: Split timeout.\n"); + LocalCachedIntr0Register|=iLink_INTR0_STO; + } + + DEBUG_PRINTF("Processing results...\n"); + + if(LocalCachedIntr0Register&iLink_INTR0_InvAck) return(-1023); + if(LocalCachedIntr0Register&iLink_INTR0_STO) return(-1024); + if(LocalCachedIntr0Register&iLink_INTR0_AckMiss) return(-1025); + if(LocalCachedIntr0Register&iLink_INTR0_RetEx) return(-1026); + /* if(!(LocalCachedIntr0Register&iLink_INTR0_AckRcvd)) return(-1); *//* Don't test for an acknowledge, as this somehow doesn't work right. :/ */ + + return PayloadLength; +} + +int iLinkReadReq(struct TransactionContextData *trContext, unsigned short int offset_high, unsigned int offset_low, void *buffer, unsigned int nBytes){ + unsigned int nBytesToTransfer; + struct ieee1394_TrPacketHdr TxHeader; + int result; + unsigned char tlabel, tCode; + + DEBUG_PRINTF("iLinkTrRead() 0x%08x %08x; nbytes: 0x%08x. Node: 0x%04x.\n", offset_high, offset_low, nBytes, trContext->NodeID); + + TargetBuffer=buffer; + + tlabel=1; /* Note: As the tlabel is the same, multiple simultaneous transactions will probably not be possible. */ + tCode=IEEE1394_TCODE_READQ; + TxHeader.header= (((unsigned int)trContext->speed)<<16) | (((unsigned int)tlabel) << 10) | (1<<8) | (((unsigned int)tCode) << 4 ); + TxHeader.offset_high=(((unsigned int)trContext->NodeID)<<16)|offset_high; + TxHeader.offset_low=offset_low; + TxHeader.misc=nBytes<<16; + + nBytesToTransfer=sizeof(struct ieee1394_TrPacketHdr)-4; /* Quadlet reads do not have the data length field. */ + + if((result=iLinkSendData(trContext, (unsigned int *)&TxHeader, nBytesToTransfer>>2, NULL, 0))>=0){ + result=iLinkSync(nBytesToTransfer); + } + + return result; +} + +int iLinkWriteReq(struct TransactionContextData *trContext, unsigned short int offset_high, unsigned int offset_low, void *buffer, unsigned int nBytes){ + unsigned int nBytesToTransfer; + struct ieee1394_TrPacketHdr TxHeader; + int result; + unsigned char tlabel, tCode; + + DEBUG_PRINTF("iLinkTrWrite() 0x%08x %08x; nbytes: 0x%08x. Node: 0x%04x.\n", offset_high, offset_low, nBytes, trContext->NodeID); + + tlabel=1; /* Note: As the tlabel is the same, multiple simultaneous transactions will probably not be possible. */ + tCode=IEEE1394_TCODE_WRITEQ; + TxHeader.header=(((unsigned int)trContext->speed)<<16) | (((unsigned int)tlabel) << 10) | (1<<8) | (((unsigned int)tCode) << 4 ); + TxHeader.offset_high=(((unsigned int)trContext->NodeID)<<16)|offset_high; + TxHeader.offset_low=offset_low; + TxHeader.misc=nBytes<<16; + + nBytesToTransfer=sizeof(struct ieee1394_TrPacketHdr)-4; /* Quadlet writes do not have the data length field. */ + + if((result=iLinkSendData(trContext, (unsigned int *)&TxHeader, nBytesToTransfer>>2, buffer, nBytes>>2))>=0){ + result=iLinkSync(nBytesToTransfer); + } + + return result; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_crom.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_crom.c new file mode 100644 index 0000000..9cc0bb1 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_crom.c @@ -0,0 +1,368 @@ +/* iLink_crom.c + * Purpose: Contains the functions related to configuration ROM access/management. + * !!!NOTE!!! All data accessible by external IEEE1394 nodes are usually in Big-Endian!!! + * + * Last Updated: 2011/11/21 + * Programmer: SP193 + */ + +#include +#include +#include +#include + +#include "iLinkman.h" +#include "iLink_CROM.h" +#include "iLink_internal.h" + +extern u64 ConsoleGUID; +extern char ConsoleModelName[32]; +extern unsigned short int LocalNodeID; +extern int nNodes; + +static void *ExtraCROMUnits[16]; +static unsigned int ExtraCROMUnitsSize[16]; +static unsigned int nExtraCROMUnits; +unsigned int *ConfigurationROM; +unsigned int ConfigurationROMSize; +static unsigned char LinkSpeed, CycleClkAcc, Max_Rec; + +extern int NodeCapabilities; +extern unsigned int NodeData[63]; + +/* Function prototypes. */ +static void ieee1394Swab32(void *dest, void *src, unsigned int nQuads); +static void BuildConfigurationROM(void); + +static void ieee1394Swab32(void *dest, void *src, unsigned int nQuads){ + register unsigned int i; + + for(i=0; i= 0; lShift -= 4 ) { + lSum = ( ( lCRC >> 12 ) ^ ( lData >> lShift ) ) & 15; + lCRC = ( lCRC << 4 ) ^ ( lSum << 12 ) ^ ( lSum << 5 ) ^ lSum; + } /* end for */ + lCRC &= 0xFFFF; + } /* end for */ + + return lCRC; +} + +int iLinkAddCROMUnit(unsigned int *data, unsigned int nQuads){ + unsigned int i, CROM_EntrySizeInBytes; + int result; + + result = -1002; + for(i=0; i<16; i++){ + if(ExtraCROMUnits[i]==NULL){ + CROM_EntrySizeInBytes=nQuads*4; + if((ExtraCROMUnits[i]=malloc(CROM_EntrySizeInBytes))!=NULL){ + ExtraCROMUnitsSize[i]=CROM_EntrySizeInBytes; + + ieee1394Swab32(ExtraCROMUnits[i], data, nQuads); + nExtraCROMUnits++; + + BuildConfigurationROM(); + + result = i; + } + + break; + } + } + + return result; +} + +void iLinkDeleteCROMUnit(unsigned int id){ + free(ExtraCROMUnits[id]); + ExtraCROMUnits[id]=NULL; + BuildConfigurationROM(); + + nExtraCROMUnits--; +} + +int iLinkGetNodeCapabilities(unsigned short NodeID){ + int result; + unsigned int data; + + if(NodeID==LocalNodeID) return NodeCapabilities; + + result=iLinkReadCROM(NodeID, 8, 1, &data); + result=(result<0)?(-1):(int)(data>>27); + + return result; +} + +int iLinkGetNodeMaxSpeed(unsigned short int NodeID){ + unsigned int i; + int result; + + result=-1; + for(i=0; i>2; + UnitDirectoryOffset=0; + + /* Search the root directory for the unit directory key. */ + if((result=iLinkReadCROM(NodeID, CROMOffset, 1, &data))<0) return(result); + DirectoryLength=(unsigned short int)(data>>16); + + CROMOffset++; + + for(i=0; i>24)==IEEE1394_CROM_UNIT_DIRECTORY){ + UnitDirectoryOffset=data&0x00FFFFFF; + break; + } + + CROMOffset++; + } + if(i==DirectoryLength) return -1; + + CROMOffset+=UnitDirectoryOffset; + DEBUG_PRINTF("CROMOffset=0x%08x.\n", CROMOffset); + + /* Search the unit directory for the unit spec and unit SW keys. */ + if((result=iLinkReadCROM(NodeID, CROMOffset, 1, &data))<0) return result; + DirectoryLength=(unsigned short int)(data>>16); + + CROMOffset++; + + for(i=0; i>24)==IEEE1394_CROM_UNIT_SPEC){ + *UnitSpec=data&0x00FFFFFF; + } + else if((data>>24)==IEEE1394_CROM_UNIT_SW_VERSION){ + *UnitSW_Version=data&0x00FFFFFF; + } + + if((*UnitSpec!=0)&&(*UnitSW_Version!=0)) return 1; + } + + return -1; +} + +int iLinkFindUnit(int UnitInList, unsigned int UnitSpec, unsigned int UnitSW_Version){ + int result; + unsigned int CurrentUnitSW_Version, CurrentUnitSpec; + unsigned short int NodeID; + + DEBUG_PRINTF("iLinkFindUnit() %d UnitSpec: 0x%08x; UnitSW Version: 0x%08x.\n", UnitInList, UnitSpec, UnitSW_Version); + + result=-1; + if(UnitInList=0){ + result=((CurrentUnitSW_Version==UnitSW_Version)&&(CurrentUnitSpec==UnitSpec))?NodeID:(-1); + } + } + + return result; +} + +int iLinkReadCROM(unsigned short int NodeID, unsigned int Offset, unsigned int nQuads, unsigned int *buffer){ + unsigned int i; + int result, trContext, retries; + + DEBUG_PRINTF("Reading CROM of node 0x%04x, offset: %u, nquads: %u.\n", NodeID, Offset, nQuads); + + result=-1; + if((trContext=iLinkTrAlloc(NodeID, S100))<0) return trContext; + + for(i=0; i=0){ + *buffer=BSWAP32(*buffer); + buffer++; + Offset++; + } + else{ + DelayThread(100000); + retries--; + } + }while((result<0)&&(retries>0)); + if(retries==0) break; + } + + iLinkTrFree(trContext); + + return result; +} + +void InitializeConfigurationROM(void){ + register unsigned int i; + + for(i=0; i<16; i++) ExtraCROMUnits[i]=NULL; + nExtraCROMUnits=0; + ConfigurationROM=NULL; + + LinkSpeed=4; + CycleClkAcc=~0; + Max_Rec=10; + + BuildConfigurationROM(); +} + +static void BuildConfigurationROM(void){ + unsigned char *CROM_Buffer; + unsigned int CROMSize, CurrentOffset; + + struct BusInformationBlock *BusInfoBlk; + struct Root_Directory *RootDirectory; + struct Module_Vendor_Id *ModuleVendorID; + struct DirectoryHeader *DirectoryHeader; + struct Module_Vendor_ID_Texual_Descriptor *ModuleTexualDescriptor; + struct Node_Unique_Id *NodeUniqueID; + struct ModelID_Textual_Descriptor *ModelName; + + unsigned int i, TotalExtraCROMUnitSize; + unsigned short int TotalRootDirectorySizeInQuads; + + TotalExtraCROMUnitSize=0; + for(i=0; i<16; i++) if(ExtraCROMUnits[i]!=NULL) TotalExtraCROMUnitSize+=ExtraCROMUnitsSize[i]; + + TotalRootDirectorySizeInQuads=(sizeof(struct Root_Directory)+TotalExtraCROMUnitSize)/4; + + CROMSize=sizeof(struct BusInformationBlockHeader)+sizeof(struct BusInformationBlock); + CROMSize=CROMSize+sizeof(struct DirectoryHeader)+sizeof(struct Root_Directory)+TotalExtraCROMUnitSize; + CROMSize=CROMSize+sizeof(struct DirectoryHeader)+sizeof(struct Module_Vendor_ID_Texual_Descriptor); + CROMSize=CROMSize+sizeof(struct DirectoryHeader)+sizeof(struct Module_Vendor_Id); + CROMSize=CROMSize+sizeof(struct DirectoryHeader)+sizeof(struct ModelID_Textual_Descriptor); + CROMSize=CROMSize+sizeof(struct DirectoryHeader)+sizeof(struct Node_Unique_Id); + + ConfigurationROMSize=CROMSize; + + if((CROM_Buffer=malloc(CROMSize))==NULL) return; + + CurrentOffset=sizeof(struct BusInformationBlockHeader)+sizeof(struct BusInformationBlock); + /* Fill in the fields in the Root Directory (Exists immediately after the Bus Information block). */ + DirectoryHeader=(struct DirectoryHeader *)&CROM_Buffer[CurrentOffset]; + RootDirectory=(struct Root_Directory *)((unsigned char *)DirectoryHeader+sizeof(struct DirectoryHeader)); + RootDirectory->Module_Vendor_ID_Texual_Descriptor_Offset=(IEEE1394_CROM_VENDOR<<24)|(sizeof(struct DirectoryHeader)*2/4+TotalRootDirectorySizeInQuads-2+sizeof(struct Module_Vendor_Id)/4); /* Calculate the relative offset (In quadlets!!). */ + RootDirectory->Node_Capabilities=(IEEE1394_CROM_NODE_CAPS<<24)|0x0C0083C0; + RootDirectory->Node_Unique_ID_Offset=(IEEE1394_CROM_NODE_UID<<24)|(sizeof(struct DirectoryHeader)*3/4+TotalRootDirectorySizeInQuads-2+sizeof(struct Module_Vendor_Id)/4+sizeof(struct Module_Vendor_ID_Texual_Descriptor)/4); + RootDirectory->Module_Vendor_ID_Offset=(IEEE1394_CROM_MODULE_VENDOR_ID<<24)|(nExtraCROMUnits+1); + + ieee1394Swab32(RootDirectory, RootDirectory, sizeof(struct Root_Directory)/4); /* Convert this block of data to Big-endian data. */ + + CurrentOffset=CurrentOffset+sizeof(struct DirectoryHeader)+sizeof(struct Root_Directory); + + for(i=0; i<16; i++){ + if(ExtraCROMUnits[i]!=NULL){ + memcpy(&CROM_Buffer[CurrentOffset], ExtraCROMUnits[i], ExtraCROMUnitsSize[i]); /* Append the extra records to the end of the Root Directory. */ + CurrentOffset+=ExtraCROMUnitsSize[i]; + } + } + + DirectoryHeader->Directory_length=TotalRootDirectorySizeInQuads; + DirectoryHeader->CRC16=BSWAP16(iLinkCalculateCRC16(RootDirectory, DirectoryHeader->Directory_length)); + DirectoryHeader->Directory_length=BSWAP16(DirectoryHeader->Directory_length); + + /* Fill in the fields of the Module Vendor ID record. */ + ModuleVendorID=(struct Module_Vendor_Id *)&CROM_Buffer[CurrentOffset+sizeof(struct DirectoryHeader)]; + ModuleVendorID->Textual_Descriptor=(IEEE1394_CROM_MODEL_ID<<24)|((sizeof(struct DirectoryHeader)*2/4+sizeof(struct Module_Vendor_ID_Texual_Descriptor)+sizeof(struct Node_Unique_Id))/4); + + ieee1394Swab32(ModuleVendorID, ModuleVendorID, sizeof(struct Module_Vendor_Id)/4); /* Convert this block of data to Big-endian data. */ + + DirectoryHeader=(struct DirectoryHeader *)&CROM_Buffer[CurrentOffset]; + DirectoryHeader->Directory_length=1; + DirectoryHeader->CRC16=BSWAP16(iLinkCalculateCRC16(ModuleVendorID, DirectoryHeader->Directory_length)); + DirectoryHeader->Directory_length=BSWAP16(DirectoryHeader->Directory_length); + + CurrentOffset=CurrentOffset+sizeof(struct Module_Vendor_Id)+sizeof(struct DirectoryHeader); + + /* Fill in the fields of the Textual_Descriptor */ + DirectoryHeader=(struct DirectoryHeader *)&CROM_Buffer[CurrentOffset]; + ModuleTexualDescriptor=(struct Module_Vendor_ID_Texual_Descriptor *)((unsigned char *)DirectoryHeader+sizeof(struct DirectoryHeader)); + ModuleTexualDescriptor->Specifier_ID=0x00000000; + ModuleTexualDescriptor->Language_ID=0x00000000; + + ieee1394Swab32(ModuleTexualDescriptor, ModuleTexualDescriptor, sizeof(struct Module_Vendor_ID_Texual_Descriptor)/4); /* Convert this block of data to Big-endian data. */ + + memcpy(ModuleTexualDescriptor->Vendor_Name, "Sony", 4); /* Don't flop the "Sony" text. */ + + DirectoryHeader->Directory_length=3; + DirectoryHeader->CRC16=BSWAP16(iLinkCalculateCRC16(ModuleTexualDescriptor, DirectoryHeader->Directory_length)); + DirectoryHeader->Directory_length=BSWAP16(DirectoryHeader->Directory_length); + + CurrentOffset=CurrentOffset+sizeof(struct Module_Vendor_ID_Texual_Descriptor)+sizeof(struct DirectoryHeader); + + /* Fill in the fields in the Node Unique ID section. */ + DirectoryHeader=(struct DirectoryHeader *)&CROM_Buffer[CurrentOffset]; + NodeUniqueID=(struct Node_Unique_Id *)((unsigned char *)DirectoryHeader+sizeof(struct DirectoryHeader)); + + NodeUniqueID->HardwareID=BSWAP32((ConsoleGUID>>32)); + NodeUniqueID->Chip_ID_Low=BSWAP32((ConsoleGUID&0xFFFFFFFF)); + + DirectoryHeader->Directory_length=sizeof(struct Node_Unique_Id)/4; + DirectoryHeader->CRC16=BSWAP16(iLinkCalculateCRC16(NodeUniqueID, DirectoryHeader->Directory_length)); + DirectoryHeader->Directory_length=BSWAP16(DirectoryHeader->Directory_length); + + CurrentOffset=CurrentOffset+sizeof(struct DirectoryHeader)+sizeof(struct Node_Unique_Id); + + /* Fill in the fields in the modelname block. */ + DirectoryHeader=(struct DirectoryHeader *)&CROM_Buffer[CurrentOffset]; + ModelName=(struct ModelID_Textual_Descriptor *)((unsigned char *)DirectoryHeader+sizeof(struct DirectoryHeader)); + + ModelName->Specifier_ID=0x00000000; + ModelName->Language_ID=0x00000000; + + memcpy(ModelName->Model_Name, ConsoleModelName, sizeof(ModelName->Model_Name)); + + DirectoryHeader->Directory_length=sizeof(struct ModelID_Textual_Descriptor)/4; + DirectoryHeader->CRC16=BSWAP16(iLinkCalculateCRC16(ModelName, DirectoryHeader->Directory_length)); + DirectoryHeader->Directory_length=BSWAP16(DirectoryHeader->Directory_length); + + CurrentOffset=CurrentOffset+sizeof(struct DirectoryHeader)+sizeof(struct ModelID_Textual_Descriptor); + + /* Fill in the fields in the Bus Information Block. */ + BusInfoBlk=(struct BusInformationBlock *)&CROM_Buffer[sizeof(struct BusInformationBlockHeader)]; + memcpy(BusInfoBlk->BusName, "1394", 4); + BusInfoBlk->capabilities=NodeCapabilities<<3; + BusInfoBlk->Cyc_Clk_Acc=CycleClkAcc; + BusInfoBlk->Max_Rec=Max_Rec<<4; + BusInfoBlk->misc=LinkSpeed; + BusInfoBlk->HardwareID=NodeUniqueID->HardwareID; + BusInfoBlk->Chip_ID_Low=NodeUniqueID->Chip_ID_Low; + + /* Fill in the fields in the Bus Information Block Header. */ + ((struct BusInformationBlockHeader *)CROM_Buffer)->Bus_info_length=4; /* According to the standard. */ + ((struct BusInformationBlockHeader *)CROM_Buffer)->CRC_length=sizeof(struct BusInformationBlock)/4; + ((struct BusInformationBlockHeader *)CROM_Buffer)->ROM_CRC_value=BSWAP16(iLinkCalculateCRC16(BusInfoBlk, sizeof(struct BusInformationBlock)/4)); + + if(ConfigurationROM!=NULL) free(ConfigurationROM); + ConfigurationROM=(unsigned int *)CROM_Buffer; +} + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_internal.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_internal.c new file mode 100644 index 0000000..8b086c5 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_internal.c @@ -0,0 +1,186 @@ +/* iLink_internal.c + * Purpose: Contains the functions that are used internally by the iLinkman driver. + * + * Last Updated: 2012/02/28 + * Programmer: SP193 + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "iLinkman.h" +#include "iLink_internal.h" + +extern struct ILINKMemMap *ILINKRegisterBase; +extern struct DMAChannelRegBlock *iLinkDMACRegs; +extern struct DMARRegBlock *iLinkDMARRegs; + +extern void (*CallBackFunction)(int reason, unsigned int offset, unsigned int size); + +int GenerationNumber; +int nNodes; +int NodeCapabilities; +struct TransactionContextData TransactionContexts[10]; +extern int IntrEventFlag; + +extern const void *RequestHandlers[]; + +void UBUFThread(void *arg){ + void (*RequestResponseHandler)(unsigned int header, volatile unsigned int *buffer, unsigned int nQuads); + unsigned int data, DataBufferLevel; + u32 ef_bits; + + while(1){ + WaitEventFlag(IntrEventFlag, iLinkEventBusReset|iLinkEventURx, WEF_OR, &ef_bits); + ClearEventFlag(IntrEventFlag, ~(iLinkEventBusReset|iLinkEventURx)); + + while((DataBufferLevel=ILINKRegisterBase->ubufReceiveLevel)>0){ + data=ILINKRegisterBase->ubufReceive; + iDEBUG_PRINTF("Handling UBUF data... handler: 0x%02lx.\n", (data>>4)&0xF); + RequestResponseHandler=RequestHandlers[(data>>4)&0xF]; + RequestResponseHandler(data, (volatile unsigned int *)&ILINKRegisterBase->ubufReceive, DataBufferLevel-1); + } + } +} + +int GetConsoleIDs(u64 *guid, char *ModelName){ + u64 ilink_id; + u32 stat; + int result; + + if(sceCdRI((u8*)&ilink_id, &stat)<0 || stat!=0){ + result=-1; + DEBUG_PRINTF("Error reading console/ILINK ID.\n"); + } + else{ + *guid=(ilink_id&0xFFFFFFFF00000000) | ((*(u8*)&ilink_id)|0x08004600); + if(sceCdRM(ModelName, &stat)<0 || stat!=0){ + result=-1; + DEBUG_PRINTF("Error reading console model name.\n"); + } + + result=0; + } + + return result; +} + +void iLinkDisableIntr(void){ + ILINKRegisterBase->intr0Mask=0; + ILINKRegisterBase->intr1Mask=0; + ILINKRegisterBase->intr2Mask=0; + + /* Set all interrupt bits, to acknowledge any pending interrupts that there may be. */ + ILINKRegisterBase->intr0=0xFFFFFFFF; + ILINKRegisterBase->intr1=0xFFFFFFFF; + ILINKRegisterBase->intr2=0xFFFFFFFF; +} + +void iLinkEnableIntr(void){ + /* Enable the interrupt events */ + ILINKRegisterBase->intr0Mask=iLink_INTR0_CmdRst|iLink_INTR0_PhyRst|iLink_INTR0_RetEx|iLink_INTR0_STO|iLink_INTR0_PBCntR|iLink_INTR0_UResp|iLink_INTR0_URx; +#ifdef REQ_CHECK_DMAC_STAT + ILINKRegisterBase->intr0Mask|=iLink_INTR0_DRFR; +#endif + +#ifdef REQ_CHECK_ERRORS + ILINKRegisterBase->intr0Mask|=(iLink_INTR0_HdrErr|iLink_INTR0_SntBsyAck); /* For debugging purposes */ +#endif + ILINKRegisterBase->intr1Mask=iLink_INTR1_UTD; +} + +static void ShutDownDMAChannels(void){ + /* Stop all DMA-related activities */ + ILINKRegisterBase->dmaCtrlSR0=ILINKRegisterBase->dmaCtrlSR1=0; + + /* Stop all DMA-related activities */ + iLinkDMACRegs[0].chcr=iLinkDMACRegs[1].chcr=iLinkDMACRegs[2].chcr=0; + + /* Disable all DMAC channels connected to the i.Link hardware. + (Disable DMA channels 13, 14 and 15) */ + dmac_disable(IOP_DMAC_FDMA0); + dmac_disable(IOP_DMAC_FDMA1); + dmac_disable(IOP_DMAC_FDMA2); +} + +int iLinkResetHW(void){ + ShutDownDMAChannels(); + + /* Turn off, and then turn back on the LINK and PHY. If this is not done, the iLink hardware might not function correctly on some consoles. :( */ + ILINKRegisterBase->UnknownRegister7C=0x40; /* Shut down. */ + DelayThread(400000); + ILINKRegisterBase->UnknownRegister7C=0; + + /* If the LINK is off, switch it on. */ + if(!(ILINKRegisterBase->ctrl2&iLink_CTRL2_LPSEn)) ILINKRegisterBase->ctrl2=iLink_CTRL2_LPSEn; + + /* Wait for the clock to stabilize. */ + while(!(ILINKRegisterBase->ctrl2&iLink_CTRL2_SOK)) DelayThread(50); + + return 0; +} + +void iLinkShutdownHW(void){ + ShutDownDMAChannels(); + ILINKRegisterBase->ctrl2&=(~iLink_CTRL2_LPSEn); /* Set the LINK to enter standby mode. */ +} + +void iLinkHWInitialize(void){ + iLinkPHY_SetLCTRL(0); + + /* Configure the Control 0 register, resetting the transmitter and receiver at the same time. */ +// ILINKRegisterBase->ctrl0=iLink_CTRL0_TxRst|iLink_CTRL0_RxRst|iLink_CTRL0_RcvSelfID|iLink_CTRL0_BusIDRst|iLink_CTRL0_CycTmrEn|iLink_CTRL0_RetLim(0x0F)|iLink_CTRL0_RSP0|iLink_CTRL0_DELim(3); + ILINKRegisterBase->ctrl0=iLink_CTRL0_TxRst|iLink_CTRL0_RxRst|iLink_CTRL0_RcvSelfID|iLink_CTRL0_BusIDRst|iLink_CTRL0_CycTmrEn|iLink_CTRL0_RetLim(0x0F)|iLink_CTRL0_DELim(3); + while(ILINKRegisterBase->ctrl0&(iLink_CTRL0_RxRst|iLink_CTRL0_TxRst)){}; + + ILINKRegisterBase->ubufTransmitClear=0; /* Clear UBUF Tx FIFO. */ + ILINKRegisterBase->ubufReceiveClear=0; /* Clear UBUF Rx FIFO. */ + + ILINKRegisterBase->dbufFIFO_lvlR0=DBUF_FIFO_RESET_TX|DBUF_FIFO_RESET_RX; /* Reset DBUF FIFO 0 */ + ILINKRegisterBase->dbufFIFO_lvlR1=DBUF_FIFO_RESET_TX|DBUF_FIFO_RESET_RX; /* Reset DBUF FIFO 1 */ + + iLinkInitPHT(); + iLinkEnableIntr(); + + iLinkWritePhy(5, iLinkReadPhy(5)|REG05_EN_ACCL|REG05_EN_MULTI); /* Enable supported P1394A-2000 enhancements. */ + + /* Enable DMA channels 13 and 15. */ + dmac_enable(IOP_DMAC_FDMA0); + dmac_enable(IOP_DMAC_FDMA2); + + GenerationNumber=0; + NodeCapabilities=0; +} + +void iLinkEnableCMaster(void){ + ILINKRegisterBase->ctrl0|=iLink_CTRL0_CMstr; +} + +void iLinkBusEnable(void){ + ILINKRegisterBase->ctrl0|=(iLink_CTRL0_RxEn|iLink_CTRL0_TxEn); /* Enable transmitter and receiver. */ +} + +void *malloc(unsigned int nBytes){ + int OldState; + void *result; + + CpuSuspendIntr(&OldState); + result=AllocSysMemory(ALLOC_FIRST, nBytes, NULL); + CpuResumeIntr(OldState); + + return result; +} + +void free(void *buffer){ + int OldState; + + CpuSuspendIntr(&OldState); + FreeSysMemory(buffer); + CpuResumeIntr(OldState); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_intr.c b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_intr.c new file mode 100644 index 0000000..3e9d273 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/iLink_intr.c @@ -0,0 +1,401 @@ +/* iLink_intr.c + * Purpose: Contains the functions related to interrupt event management/response, and functions that manage IEEE1394 read/write requests and responses. + * + * Last Updated: 2012/02/24 + * Programmer: SP193 + */ + +#include +#include +#include +#include + +#include "iLinkman.h" +#include "iLink_internal.h" + +extern int IntrEventFlag; +extern unsigned short int LocalNodeID; +extern int NodeCapabilities; +extern int nNodes; +extern int GenerationNumber; +extern struct ILINKMemMap *ILINKRegisterBase; +extern struct DMAChannelRegBlock *iLinkDMACRegs; +extern void (*CallBackFunction)(int reason, unsigned int offset, unsigned int size); + +extern unsigned int *ConfigurationROM; +extern unsigned int ConfigurationROMSize; + +unsigned int *TargetBuffer, NodeData[63]; +unsigned int LocalCachedIntr0Register; + +unsigned char IsBusRoot=1; /* Assume that the console is the root, in case this variable is polled before it was set correctly. */ + +static void NoResponseHandler(unsigned int header, volatile unsigned int *buffer, unsigned int nQuads){ + unsigned int i; + + DEBUG_PRINTF("NULL response handler called.\n"); + + for(i=0; i0){ + if(data==PHY_SELF_ID_PACKET){ + DEBUG_PRINTF("Receiving SELFID packets...\n"); + nNodes=0; + } + else if((data!=1)&&(data!=0xE)){ + if((data>>30)==2){ /* SELFID entry. */ + DEBUG_PRINTF("SELFID received from Node 0x%04x. Speed: 0x%02x. Power: 0x%02x.\n", SELF_ID_NODEID(data), SELF_ID_SPEED(data), SELF_ID_POWER(data)); + NodeData[nNodes]=data; + nNodes++; + } + else DEBUG_PRINTF("Unknown quad received in SELF-ID phase: 0x%08x.\n", data); + } + else{ /* End of SELF ID packet receival. */ + /* The local node ID should be already valid at this point in execution. */ + LocalNodeID=ILINKRegisterBase->NodeID>>16; + + IsBusRoot=(ILINKRegisterBase->ctrl0&iLink_CTRL0_Root)?1:0; + + DEBUG_PRINTF("Local Node ID: 0x%04x.\n", LocalNodeID); + SetEventFlag(IntrEventFlag, iLinkEventGotSELFIDs); + if(CallBackFunction!=NULL) CallBackFunction(iLink_CB_BUS_RESET, 0, 0); + } + + data=*buffer; + } + } + else + if(header==PHY_CONFIG_PACKET){ + data = *buffer; + /* For monitoring only. It seems like the PHY will automatically configure itself with the data from the PHY packet. */ +/* if(PHY_CONFIG_R(data)) iLinkPHY_SetRootBit(PHY_CONFIG_ROOT_ID(data)==(LocalNodeID&0x3F)); + if(PHY_CONFIG_T(data)) iLinkPHY_SetGapCount(PHY_CONFIG_GAP_CNT(data)); */ + if(PHY_CONFIG_T(data)) DEBUG_PRINTF("gap count: %d.\n", PHY_CONFIG_GAP_CNT(data)); + } + else{ + DEBUG_PRINTF("DEBUG: Unknown PHY packet type: 0x%8x.\n", header); + NoResponseHandler(header, buffer, nQuads); + } +} + +static void ResponseHandler(unsigned int header, volatile unsigned int *buffer, unsigned int nQuads){ + unsigned int i, HeaderLength; + struct ieee1394_TrResponsePacketHdr ResponseData; + unsigned char tCode; + unsigned int data __attribute__((unused)); + + tCode=(header>>4)&0xF; + + HeaderLength=(tCode!=IEEE1394_TCODE_WRITE_RESPONSE)?4:3; /* Write response packets are shorter by other responses by one quadlet! */ + + ResponseData.header=header; + for(i=1; i>10)&0x3F); + } + + DEBUG_PRINTF("%u.\n", (ResponseData.header2>>12)&0xF); + if(tCode==IEEE1394_TCODE_READB_RESPONSE){ + DEBUG_PRINTF("data length: 0x%08x.\n", ResponseData.LastField>>16); /* This refers to the data_legnth field of a block read response packet. */ + for(i=0; i<(ResponseData.LastField>>16); i+=4){ + *TargetBuffer=*buffer; + TargetBuffer++; + } + } + + data=*buffer; /* Read the last quadlet of the read response that contains only the speed. */ + SetEventFlag(IntrEventFlag, iLinkEventDataReceived); +} + +static void WriteRequestHandler(unsigned int header, volatile unsigned int *buffer, unsigned int nQuads){ + struct ieee1394_TrPacketHdr WriteReqHeader; + unsigned int QuadsToRead, data; + unsigned int i; + unsigned char rCode, tLabel; + + DEBUG_PRINTF("Incoming write request. Header: 0x%08x; Buffer: 0x%p; nQuads: 0x%08x.\n", header, buffer, nQuads); + rCode=0; + + /* Read in the header. */ + WriteReqHeader.header=header; + QuadsToRead=sizeof(struct ieee1394_TrPacketHdr)>>2; + if(((header>>4)&0xF)==IEEE1394_TCODE_WRITEQ){ + QuadsToRead--; /* Quadlet write requests do not have the data length field. */ + WriteReqHeader.misc=4; /* nBytes=4 */ + DEBUG_PRINTF("Quadlet"); + } + else DEBUG_PRINTF("Block"); + + for(i=1; i>=16; + + DEBUG_PRINTF(" write request to 0x%08x %08x with length %u.\n", WriteReqHeader.offset_high, WriteReqHeader.offset_low, WriteReqHeader.misc); + + /* Using the information in the header, write the data to the destination. */ +#ifdef REQ_CHECK_MEM_BOUNDARIES + if(WriteReqHeader.offset_low<0x00200000){ /* Make sure that the write request falls within IOP memory. */ +#endif + for(i=0; i<(WriteReqHeader.misc>>2); i++){ + data=*buffer; + ((unsigned int *)WriteReqHeader.offset_low)[i]=data; + } +#ifdef REQ_CHECK_MEM_BOUNDARIES + } + else{ + DEBUG_PRINTF("Invalid write request."); + rCode=6; + } +#endif + + data=*buffer; /* Read in the last field that contains the speed. */ + + tLabel=(header>>10)&0x3F; + SendResponse(WriteReqHeader.offset_high>>16, (header>>16)>>6, rCode, tLabel, IEEE1394_TCODE_WRITE_RESPONSE, (data>>16)&0x7, NULL, 0); + + DEBUG_PRINTF("Response sent.\n"); + + if(CallBackFunction!=NULL) CallBackFunction(iLink_CB_WRITE_REQUEST, WriteReqHeader.offset_low, WriteReqHeader.misc); +} + +struct ieee1394_TrCommonRdPktHdr{ + unsigned int header; + unsigned int offset_high; + unsigned int offset_low; +}; + +struct ieee1394_TrBlockRdPacketHdr{ + struct ieee1394_TrCommonRdPktHdr header; + + unsigned int nBytes; + unsigned int trailer; +}; + +struct ieee1394_TrQuadRdPacketHdr{ + struct ieee1394_TrCommonRdPktHdr header; + + unsigned int trailer; +}; + +static void ReadRequestHandler(unsigned int header, volatile unsigned int *buffer, unsigned int nQuads){ + unsigned int QuadsToRead, offset_low, offset_high, nBytes; + unsigned int ReadReqHeader[5]; + unsigned int i; + unsigned short int DestinationNodeID; + unsigned char tCode, speed, rCode, tLabel; + + rCode=0; + DEBUG_PRINTF("Incoming read request. Header: 0x%08x; Buffer: 0x%p; nQuads: 0x%08x.\n", header, buffer, nQuads); + + /* Read in the header. */ + ReadReqHeader[0]=header; + tCode=(header>>4)&0xF; + if(tCode==IEEE1394_TCODE_READQ){ + QuadsToRead=sizeof(struct ieee1394_TrQuadRdPacketHdr)>>2; + DEBUG_PRINTF("Quadlet"); + } + else{ + QuadsToRead=sizeof(struct ieee1394_TrBlockRdPacketHdr)>>2; + DEBUG_PRINTF("Block"); + } + + for(i=1; ioffset_low); + offset_high=BSWAP32(((struct ieee1394_TrCommonRdPktHdr *)ReadReqHeader)->offset_high); + DestinationNodeID=BSWAP16((unsigned short int)offset_high); + } + else{ + offset_low=((struct ieee1394_TrCommonRdPktHdr *)ReadReqHeader)->offset_low; + offset_high=((struct ieee1394_TrCommonRdPktHdr *)ReadReqHeader)->offset_high; + DestinationNodeID=(unsigned short int)(offset_high>>16); + } + + if(tCode==IEEE1394_TCODE_READQ){ + nBytes=4; + speed=(((struct ieee1394_TrQuadRdPacketHdr *)ReadReqHeader)->trailer>>16)&0x7; + } + else{ + nBytes=((struct ieee1394_TrBlockRdPacketHdr *)ReadReqHeader)->nBytes>>16; + speed=(((struct ieee1394_TrBlockRdPacketHdr *)ReadReqHeader)->trailer>>16)&0x7; + } + + DEBUG_PRINTF(" read request to 0x%08x %08x with length %u.\n", offset_high, offset_low, nBytes); + +#ifdef REQ_CHECK_MEM_BOUNDARIES + if(((offset_high&0x0000FFFF)==0x0000FFFF)&&((offset_low&0xF0000000)==0xF0000000)){ +#endif + offset_low&=0x0FFFFFFF; + if((offset_low-0x400)=0x00200000)||(offset_low==0)){ + DEBUG_PRINTF("Invalid read request."); + rCode=6; + nBytes=0; + } +#endif + + tCode=(tCode==IEEE1394_TCODE_READQ)?IEEE1394_TCODE_READQ_RESPONSE:IEEE1394_TCODE_READB_RESPONSE; + tLabel=(header>>10)&0x3F; + SendResponse(DestinationNodeID, DestinationNodeID>>6, rCode, tLabel, tCode, speed, (unsigned int *)offset_low, nBytes>>2); + + DEBUG_PRINTF("Response sent!2.\n"); + + if(CallBackFunction!=NULL) CallBackFunction(iLink_CB_READ_REQUEST, offset_low, nBytes); +} + +const void *RequestHandlers[]={ + &WriteRequestHandler, /* 0: write quadlet */ + &WriteRequestHandler, /* 1: write block */ + &ResponseHandler, /* 2: write response */ + &NoResponseHandler, /* 3: reserved */ + &ReadRequestHandler, /* 4: read quadlet */ + &ReadRequestHandler, /* 5: read block */ + &ResponseHandler, /* 6: read quadlet response */ + &ResponseHandler, /* 7: read block response */ + &NoResponseHandler, /* 8: cycle start */ + &NoResponseHandler, /* 9: lock request */ + &NoResponseHandler, /* 10: ISO/stream data */ + &NoResponseHandler, /* 11: lock response */ + &NoResponseHandler, /* 12: reserved */ + &NoResponseHandler, /* 13: reserved */ + &PHYPacketHandler, /* 14: PHY packet */ + &NoResponseHandler /* 15: reserved */ +}; + +int iLinkIntrHandler(void *arg){ + unsigned int LocalCachedIntr1Register, EventFlagBitsToSet; +#ifdef REQ_CHECK_DMAC_STAT + unsigned int i; +#endif + + while(1){ + /* Acknowledge interrupts while determining which interrupt events have occurred. Some events need to be acknowledged as early as possible or they will prevent the hardware from working properly. */ + ILINKRegisterBase->intr0=LocalCachedIntr0Register=ILINKRegisterBase->intr0&ILINKRegisterBase->intr0Mask; + ILINKRegisterBase->intr1=LocalCachedIntr1Register=ILINKRegisterBase->intr1&ILINKRegisterBase->intr1Mask; + + if(!LocalCachedIntr0Register && !LocalCachedIntr1Register) break; + + EventFlagBitsToSet=0; + + DEBUG_PRINTF("iLink interrupt: 0x%08x 0x%08x\n", LocalCachedIntr0Register, LocalCachedIntr1Register); + + if(LocalCachedIntr1Register&iLink_INTR1_UTD) EventFlagBitsToSet|=iLinkEventDataSent; + +#ifdef REQ_CHECK_DMAC_STAT + if(LocalCachedIntr0Register&iLink_INTR0_DRFR){ + iDEBUG_PRINTF("Handling DBUF FIFO data...\n"); + + for(i=0; i<3; i++){ + iDEBUG_PRINTF("DMA Channel %d CHCR: 0x%08x MADR: 0x%08x DLEN: 0x%05x SLICE: 0x%03x\n", 13+i, iLinkDMACRegs[i].chcr, iLinkDMACRegs[i].madr, iLinkDMACRegs[i].dlen, iLinkDMACRegs[i].slice); + + if((i>0) && !(iLinkDMACRegs[i].chcr&DMAC_CHCR_AR)){ + iLinkDMACRegs[i].chcr=0; + switch(i){ + case 1: + ILINKRegisterBase->dmaCtrlSR0=0; + break; + case 2: + ILINKRegisterBase->dmaCtrlSR1=0; + break; + } + + iDEBUG_PRINTF("DMAC Channel %d stalled. Flushing FIFOs and reseting PHTs.\n", 13+i); + + iLinkInitPHT(); + } + } + } +#endif + + if(LocalCachedIntr0Register&iLink_INTR0_PhyRst){ + iDEBUG_PRINTF("-=Bus reset start detected=-\n"); + + GenerationNumber++; + + iLinkInitPHT(); + EventFlagBitsToSet|=(iLinkEventBusReady|iLinkEventBusReset); + + iDEBUG_PRINTF("-=PHTs initialized=-\n"); + } + + if(LocalCachedIntr0Register&iLink_INTR0_URx){ + EventFlagBitsToSet|=iLinkEventURx; + } + + if(LocalCachedIntr0Register&(iLink_INTR0_InvAck|iLink_INTR0_RetEx|iLink_INTR0_UResp)){ + EventFlagBitsToSet|=iLinkEventError; + iDEBUG_PRINTF("-=Missing/invalid response detected=-\n"); + } + + /* For debugging purposes */ +#ifdef REQ_CHECK_ERRORS + if(LocalCachedIntr0Register&iLink_INTR0_HdrErr){ + iDEBUG_PRINTF("-=HdrErr=-\n"); + } + + if(LocalCachedIntr0Register&iLink_INTR0_SntBsyAck){ + iDEBUG_PRINTF("-=iLink_INTR0_SntBsyAck=-\n"); + } +#endif + + if(LocalCachedIntr0Register&iLink_INTR0_PBCntR){ + EventFlagBitsToSet|=iLinkEventDMATransEnd; + iDEBUG_PRINTF("-=End of DMA transfer=-\n"); + } + + if(LocalCachedIntr0Register&iLink_INTR0_CmdRst){ + iDEBUG_PRINTF("-=CmdRst=-\n"); + iLinkPHYBusReset(); + } + + iSetEventFlag(IntrEventFlag, EventFlagBitsToSet); + } + + return 1; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/imports.lst new file mode 100644 index 0000000..bb5e1e9 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/imports.lst @@ -0,0 +1,74 @@ +cdvdman_IMPORTS_start +I_sceCdRI +I_sceCdRM +cdvdman_IMPORTS_end + +dmacman_IMPORTS_start +I_dmac_enable +I_dmac_disable +dmacman_IMPORTS_end + +intrman_IMPORTS_start +I_RegisterIntrHandler +I_ReleaseIntrHandler +I_EnableIntr +I_DisableIntr +I_QueryIntrContext +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +ioman_IMPORTS_start +I_open +I_read +I_close +ioman_IMPORTS_end + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +I_ReleaseLibraryEntries +loadcore_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +sysclib_IMPORTS_start +I_memset +I_memcpy +I_strtoul +sysclib_IMPORTS_end + +sysmem_IMPORTS_start +I_AllocSysMemory +I_FreeSysMemory +I_Kprintf +sysmem_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_DeleteThread +I_StartThread +I_DelayThread +I_TerminateThread +I_SetAlarm +I_CancelAlarm +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_DeleteEventFlag +I_ClearEventFlag +I_iClearEventFlag +I_SetEventFlag +I_iSetEventFlag +I_WaitEventFlag +I_PollEventFlag +thevent_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_WaitSema +I_SignalSema +I_DeleteSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/include/iLink_CROM.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/include/iLink_CROM.h new file mode 100644 index 0000000..e43c83f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/include/iLink_CROM.h @@ -0,0 +1,65 @@ +/* Configuration ROM keys */ +#define IEEE1394_CROM_DESC 0x01 +#define IEEE1394_CROM_VENDOR 0x03 +#define IEEE1394_CROM_NODE_CAPS 0x0C +#define IEEE1394_CROM_EUI64 0x0D +#define IEEE1394_CROM_UNIT 0x11 +#define IEEE1394_CROM_UNIT_SPEC 0x12 +#define IEEE1394_CROM_UNIT_SW_VERSION 0x13 +#define IEEE1394_CROM_MODEL 0x17 +#define IEEE1394_CROM_MODEL_ID 0x81 +#define IEEE1394_CROM_NODE_UID 0x8D +#define IEEE1394_CROM_MODULE_VENDOR_ID 0xC3 +#define IEEE1394_CROM_UNIT_DIRECTORY 0xD1 + +struct BusInformationBlockHeader{ + unsigned char Bus_info_length; + unsigned char CRC_length; + unsigned short int ROM_CRC_value; +}; + +struct BusInformationBlock{ + unsigned char BusName[4]; + unsigned char capabilities; + unsigned char Cyc_Clk_Acc; + unsigned char Max_Rec; + unsigned char misc; /* g, resv. and link_spd fields. */ + + unsigned int HardwareID; /* NodeVendorID | Chip_ID_High */ + unsigned int Chip_ID_Low; +}; + +struct DirectoryHeader{ + unsigned short int Directory_length; + unsigned short int CRC16; +}; + +struct Root_Directory{ + unsigned int VendorID; + unsigned int Module_Vendor_ID_Texual_Descriptor_Offset; + unsigned int Node_Capabilities; + unsigned int Node_Unique_ID_Offset; + unsigned int Module_Vendor_ID_Offset; +}; + +struct Module_Vendor_ID_Texual_Descriptor{ + unsigned int Specifier_ID; + unsigned int Language_ID; + unsigned char Vendor_Name[4]; /* "Sony" */ +}; + +struct Module_Vendor_Id{ /* For Playstation 2 consoles only? */ + unsigned int Textual_Descriptor; +}; + +struct ModelID_Textual_Descriptor{ + unsigned int Specifier_ID; + unsigned int Language_ID; + unsigned char Model_Name[12]; /* E.g. "SCPH-10000" + 2x00-bytes at the end. */ +}; + +struct Node_Unique_Id{ + unsigned int HardwareID; /* Node_Vendor_ID | Chip_ID_High */ + unsigned int Chip_ID_Low; +}; + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/include/iLink_internal.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/include/iLink_internal.h new file mode 100644 index 0000000..1500164 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/include/iLink_internal.h @@ -0,0 +1,313 @@ +//#define DEBUG_TTY_FEEDBACK /* Comment out to disable generation of debug TTY messages */ + +#ifdef DEBUG_TTY_FEEDBACK + #define DEBUG_PRINTF(args...) printf(args) + #define iDEBUG_PRINTF(args...) Kprintf(args) +#else + #define DEBUG_PRINTF(args...) + #define iDEBUG_PRINTF(args...) +#endif + +#define REQ_CHECK_MEM_BOUNDARIES /* Define this to enable memory address boundary checking for incoming requests. */ +#define REQ_CHECK_CONSOLE_VERSION /* Define this to enable version checks on the Playstation 2 console. */ +//#define REQ_CHECK_DMAC_STAT /* Define this to enable memory DMAC status checking. */ +//#define REQ_CHECK_ERRORS /* Define this to enable checking for HdrErr and SntBsyAck interrupts. Serves no purpose except for debugging. */ + +#define iLink_INTR0_DRFR 0x00000001 +#define iLink_INTR0_DRFO 0x00000002 +#define iLink_INTR0_TxStk 0x00000040 +#define iLink_INTR0_FmtE 0x00000080 +#define iLink_INTR0_UResp 0x00000100 +#define iLink_INTR0_PBCntR 0x00000200 +#define iLink_INTR0_STO 0x00000400 +#define iLink_INTR0_RetEx 0x00000800 +#define iLink_INTR0_InvAck 0x00001000 +#define iLink_INTR0_AckMiss 0x00002000 +#define iLink_INTR0_AckRcvd 0x00004000 +#define iLink_INTR0_CycArbFl 0x00008000 +#define iLink_INTR0_CycLost 0x00010000 +#define iLink_INTR0_CycSt 0x00080000 +#define iLink_INTR0_CycTL 0x00200000 +#define iLink_INTR0_URx 0x00400000 +#define iLink_INTR0_SubActGap 0x00800000 +#define iLink_INTR0_TCErr 0x01000000 +#define iLink_INTR0_HdrErr 0x02000000 +#define iLink_INTR0_SntBsyAck 0x04000000 +#define iLink_INTR0_CmdRst 0x08000000 +#define iLink_INTR0_ArbRstGap 0x10000000 +#define iLink_INTR0_PhyRst 0x20000000 +#define iLink_INTR0_PhyRRx 0x40000000 +#define iLink_INTR0_PhyInt 0x80000000 + +#define iLink_INTR1_DTFO 0x00000001 +#define iLink_INTR1_UTD 0x00000002 + +#define iLink_CTRL0_URcvM 0x00000010 +#define iLink_CTRL0_RSP0 0x00000020 +#define iLink_CTRL0_RetLim(x) (x<<12) +#define iLink_CTRL0_LooseTightIso 0x00010000 +#define iLink_CTRL0_STardy 0x00020000 +#define iLink_CTRL0_BRDE 0x00040000 +#define iLink_CTRL0_Root 0x00080000 +#define iLink_CTRL0_ExtCyc 0x00100000 +#define iLink_CTRL0_CycTmrEn 0x00200000 +#define iLink_CTRL0_CMstr 0x00400000 +#define iLink_CTRL0_BusIDRst 0x00800000 +#define iLink_CTRL0_RxRst 0x01000000 +#define iLink_CTRL0_TxRst 0x02000000 +#define iLink_CTRL0_RxEn 0x04000000 +#define iLink_CTRL0_TxEn 0x08000000 +#define iLink_CTRL0_DELim(x) (x<<28) +#define iLink_CTRL0_SIDF 0x40000000 +#define iLink_CTRL0_RcvSelfID 0x80000000 + +#define iLink_CTRL2_LPSRst 0x00000001 +#define iLink_CTRL2_LPSEn 0x00000002 +#define iLink_CTRL2_SRst 0x00000004 +#define iLink_CTRL2_SOK 0x00000008 + +#define iLinkDMA_CTRL_SR_DWidth(x) (x<<17) +#define iLinkDMA_CTRL_SR_DEn 0x080000 +#define iLinkDMA_CTRL_SR_RActl 0x010000 +#define iLinkDMA_CTRL_SR_LFirst 0x100000 + +#define PHT_CTRL_ST_PRBR 0x00000200 +#define PHT_CTRL_ST_PStk 0x00000400 +#define PHT_CTRL_ST_EnDMAS 0x00001000 +#define PHT_CTRL_ST_EBCNT 0x00008000 +#define PHT_CTRL_ST_EWREQ 0x00010000 +#define PHT_CTRL_ST_ERREQ 0x00020000 +#define PHT_CTRL_ST_EPCNT 0x00100000 +#define PHT_CTRL_ST_PHTRst 0x00200000 +#define PHT_CTRL_ST_IHdr 0x00400000 +#define PHT_CTRL_ST_EHdr 0x02000000 + +#define DBUF_FIFO_RESET_TX 0x00008000 +#define DBUF_FIFO_RESET_RX 0x80000000 + +#define PACKET_TCODE (((x)>>4)&0xF) + +/* PHY configuration packet data */ +#define PHY_CONFIG_PACKET 0xE0 +#define PHY_CONFIG_GAP_CNT(x) (((x)>>16)&0x3F) +#define PHY_CONFIG_T(x) (((x)>>22)&0x01) +#define PHY_CONFIG_R(x) (((x)>>23)&0x01) +#define PHY_CONFIG_ROOT_ID(x) (((x)>>24)&0x3F) + +/* SELF-ID packet data */ +#define PHY_SELF_ID_PACKET 0xE1 +#define PHY_SELF_ID_PKT_SIG 0x2 /* 10b */ +#define SELF_ID_SIGNATURE(x) (((x)>>30)&0x03) +#define SELF_ID_NODEID(x) (((x)>>24)&0x3F) +#define SELF_ID_L(x) (((x)>>22)&0x01) +#define SELF_ID_GAP_CNT(x) (((x)>>16)&0x3F) +#define SELF_ID_SPEED(x) (((x)>>14)&0x03) +#define SELF_ID_POWER(x) (((x)>>8)&0x07) +#define SELF_ID_M(x) (((x)&0x01) + +/* PHY Register bits. */ +#define REG01_IBR 0x40 +#define REG01_RHB 0x80 +#define REG04_LCTRL 0x80 +#define REG05_ISBR 0x40 +#define REG05_EN_ACCL 0x02 +#define REG05_EN_MULTI 0x01 + +/* Event flag bits. */ +#define iLinkEventInterrupt 0x00000001 +#define iLinkEventBusReady 0x00000002 +#define iLinkEventGotSELFIDs 0x00000004 +#define iLinkEventDataSent 0x00000008 +#define iLinkEventDataReceived 0x00000010 +#define iLinkEventDMATransEnd 0x00000020 +#define iLinkEventBusReset 0x00000040 +#define iLinkEventURx 0x00000080 +#define iLinkEventError 0x80000000 + +/* Structures. */ +#define IEEE1394_TCODE_WRITEQ 0 +#define IEEE1394_TCODE_WRITEB 1 +#define IEEE1394_TCODE_WRITE_RESPONSE 2 +#define IEEE1394_TCODE_READQ 4 +#define IEEE1394_TCODE_READB 5 +#define IEEE1394_TCODE_READQ_RESPONSE 6 +#define IEEE1394_TCODE_READB_RESPONSE 7 + +struct ieee1394_TrPacketHdr{ + unsigned int header; + unsigned int offset_high; + unsigned int offset_low; + unsigned int misc; +}; + +struct ieee1394_TrResponsePacketHdr{ + unsigned int header; + unsigned int header2; + unsigned int reserved; + unsigned int LastField; +}; + +#define ILINK_REGISTER_BASE 0xBF808400 + +struct ILINKMemMap{ + volatile unsigned int NodeID; /* 0x00 */ + volatile unsigned int CycleTime; /* 0x04 */ + + volatile unsigned int ctrl0; /* 0x08 */ + volatile unsigned int ctrl1; /* 0x0C */ + volatile unsigned int ctrl2; /* 0x10 */ + + volatile unsigned int PHYAccess; /* 0x14 */ + + volatile unsigned int UnknownRegister18; /* 0x18 */ + volatile unsigned int UnknownRegister1C; /* 0x1C */ + + volatile unsigned int intr0; /* 0x20 */ + volatile unsigned int intr0Mask; /* 0x24 */ + + volatile unsigned int intr1; /* 0x28 */ + volatile unsigned int intr1Mask; /* 0x2C */ + + volatile unsigned int intr2; /* 0x30 */ + volatile unsigned int intr2Mask; /* 0x34 */ + + volatile unsigned int dmar; /* 0x38 */ + volatile unsigned int ack_status; /* 0x3C */ + volatile unsigned int ubufTransmitNext; /* 0x40 */ + volatile unsigned int ubufTransmitLast; /* 0x44 */ + volatile unsigned int ubufTransmitClear; /* 0x48 */ + volatile unsigned int ubufReceiveClear; /* 0x4C */ + volatile unsigned int ubufReceive; /* 0x50 */ + volatile unsigned int ubufReceiveLevel; /* 0x54 */ + + volatile unsigned int unmapped1[0x06]; /* Registers 0x58-0x6C are unmapped. */ + + volatile unsigned int UnknownRegister70; /* 0x70 */ + volatile unsigned int UnknownRegister74; /* 0x74 */ + volatile unsigned int UnknownRegister78; /* 0x78 */ + volatile unsigned int UnknownRegister7C; /* 0x7C */ + + volatile unsigned int PHT_ctrl_ST_R0; /* 0x80 */ + volatile unsigned int PHT_split_TO_R0; /* 0x84 */ + volatile unsigned int PHT_ReqResHdr0_R0; /* 0x88 */ + volatile unsigned int PHT_ReqResHdr1_R0; /* 0x8C */ + volatile unsigned int PHT_ReqResHdr2_R0; /* 0x90 */ + + volatile unsigned int STRxNIDSel0_R0; /* 0x94 */ + volatile unsigned int STRxNIDSel1_R0; /* 0x98 */ + + volatile unsigned int STRxHDR_R0; /* 0x9C */ + volatile unsigned int STTxHDR_R0; /* 0xA0 */ + + volatile unsigned int DTransCTRL0; /* 0xA4 */ + volatile unsigned int CIPHdrTx0_R0; /* 0xA8 */ + volatile unsigned int CIPHdrTx1_R0; /* 0xAC */ + + volatile unsigned int padding4; /* 0xB0 */ + volatile unsigned int STTxTimeStampOffs_R0; /* 0xB4 */ + + volatile unsigned int dmaCtrlSR0; /* 0xB8 */ + volatile unsigned int dmaTransTRSH0; /* 0xBC */ + volatile unsigned int dbufFIFO_lvlR0; /* 0xC0 */ + volatile unsigned int dbufTxDataR0; /* 0xC4 */ + volatile unsigned int dbufRxDataR0; /* 0xC8 */ + + volatile unsigned int dbufWatermarksR0; /* 0xCC (Unmapped) */ + volatile unsigned int dbufFIFOSzR0; /* 0xD0 (Unmapped) */ + + volatile unsigned int unmapped2[0x0B]; /* Unmapped. */ + + volatile unsigned int PHT_ctrl_ST_R1; /* 0x100 */ + volatile unsigned int PHT_split_TO_R1; /* 0x104 */ + volatile unsigned int PHT_ReqResHdr0_R1; /* 0x108 */ + volatile unsigned int PHT_ReqResHdr1_R1; /* 0x10C */ + volatile unsigned int PHT_ReqResHdr2_R1; /* 0x110 */ + + volatile unsigned int STRxNIDSel0_R1; /* 0x114 */ + volatile unsigned int STRxNIDSel1_R1; /* 0x118 */ + + volatile unsigned int STRxHDR_R1; /* 0x11C */ + volatile unsigned int STTxHDR_R1; /* 0x120 */ + + volatile unsigned int DTransCTRL1; /* 0x124 */ + volatile unsigned int CIPHdrTx0_R1; /* 0x128 */ + volatile unsigned int CIPHdrTx1_R1; /* 0x12C */ + + volatile unsigned int padding5; /* 0x130 */ + volatile unsigned int STTxTimeStampOffs_R1; /* 0x134 */ + + volatile unsigned int dmaCtrlSR1; /* 0x138 */ + volatile unsigned int dmaTransTRSH1; /* 0x13C */ + volatile unsigned int dbufFIFO_lvlR1; /* 0x140 */ + volatile unsigned int dbufTxDataR1; /* 0x144 */ + volatile unsigned int dbufRxDataR1; /* 0x148 */ + + volatile unsigned int dbufWatermarksR1; /* 0x14C (Unmapped) */ + volatile unsigned int dbufFIFOSzR1; /* 0x150 (Unmapped) */ +}; + +#define ILINK_DMAC_REGISTER_BASE 0xBF801580 + +struct DMAChannelRegBlock{ /* The PS2 has 3 of these register blocks for DMAC #3 */ + volatile unsigned int madr; + volatile unsigned int dlen; + volatile unsigned int slice; + volatile unsigned int chcr; + volatile unsigned int rtar; + volatile unsigned int DmarReadStart; + volatile unsigned int DmarReadEnd; + + volatile unsigned int unused; /* This region contains either unmapped memory locations or registers that aren't for specific DMA channel control. */ +}; + +#define ILINK_DMAC_DMAR_CTRL_BASE 0xBF8015DC + +struct DMARRegBlock{ + volatile unsigned int DmarWriteStart; + volatile unsigned int DmarWriteEnd; +}; + +#define MAX_CONCURRENT_TRANSACTIONS 10 + +#define DMAC_CHCR_AR (1<<31) /* Automatic Response. */ +#define DMAC_CHCR_11 (1<<11) /* I don't know what this does, but it appears to be a bit that means something to the DMAC. */ + +struct TransactionContextData{ + int GenerationNumber; + unsigned short int NodeID; + unsigned char IsConnected; + unsigned char speed; +}; + +/* Function prototypes. */ +void UBUFThread(void *arg); +int GetConsoleIDs(u64 *guid, char *ModelName); +void iLinkDisableIntr(void); +int iLinkResetHW(void); +void iLinkShutdownHW(void); +void iLinkHWInitialize(void); +void iLinkEnableCMaster(void); +void iLinkBusEnable(void); +void *malloc(unsigned int nBytes); +void free(void *buffer); + +void InitializeConfigurationROM(void); + +unsigned char iLinkReadPhy(unsigned char address); +void iLinkWritePhy(unsigned char address, unsigned char data); +void iLinkPHY_SetRootBit(int isRoot); +void iLinkPHY_SetGapCount(unsigned char GapCount); +void iLinkPHY_SetLCTRL(int LCTRL_status); +void iLinkPHYBusReset(void); + +int iLinkIntrHandler(void *arg); +void iLinkIntrRegister0Handler(void *arg); + +void SendResponse(unsigned short int NodeID, unsigned short RcvdBusID, unsigned char rcode, unsigned char tLabel, unsigned char tCode, unsigned char speed, unsigned int *buffer, unsigned int nQuads); +int iLinkReadReq(struct TransactionContextData *trContext, unsigned short int offset_high, unsigned int offset_low, void *buffer, unsigned int nBytes); +int iLinkWriteReq(struct TransactionContextData *trContext, unsigned short int offset_high, unsigned int offset_low, void *buffer, unsigned int nBytes); + +void iLinkInitPHT(void); +void PHTSendResponse(unsigned short int NodeID, unsigned short RcvdBusID, unsigned char rcode, unsigned char tLabel, unsigned char tCode, unsigned char speed, unsigned int *buffer, unsigned int nQuads); +int iLinkReadPHTReq(struct TransactionContextData *trContext, unsigned short int offset_high, unsigned int offset_low, void *buffer, unsigned int nBytes); +int iLinkWritePHTReq(struct TransactionContextData *trContext, unsigned short int offset_high, unsigned int offset_low, void *buffer, unsigned int nBytes); diff --git a/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/irx_imports.h new file mode 100644 index 0000000..d3b2211 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/iLink/iLinkman/src/irx_imports.h @@ -0,0 +1,32 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ +#include +#include +#include "iLinkman.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/Makefile new file mode 100644 index 0000000..bcce721 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/Makefile @@ -0,0 +1,12 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +SUBDIRS = mcman mcserv xfromman + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/Rules.make diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/Makefile new file mode 100644 index 0000000..10cf3be --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/Makefile @@ -0,0 +1,18 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +# IOP_CFLAGS += -DSIO_DEBUG -DDEBUG + +IOP_INCS += -I$(PS2SDKSRC)/iop/system/sio2man/include + +IOP_OBJS = main.o mcdev.o mcsio2.o ps2mc_fio.o ps1mc_fio.o imports.o exports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/include/mcman.h b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/include/mcman.h new file mode 100644 index 0000000..a9a3023 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/include/mcman.h @@ -0,0 +1,128 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 jimmikaelkael +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +/** + * @file + * Memory card manager definitions + */ + +#ifndef __MCMAN_H__ +#define __MCMAN_H__ + +#include +#include +#include + +/* MCMAN public structure */ +typedef struct _sceMcTblGetDir { // size = 64 + sceMcStDateTime _Create; // 0 + sceMcStDateTime _Modify; // 8 + u32 FileSizeByte; // 16 + u16 AttrFile; // 20 + u16 Reserve1; // 22 + u32 Reserve2; // 24 + u32 PdaAplNo; // 28 + unsigned char EntryName[32]; // 32 +} sceMcTblGetDir; + +int McDetectCard(int port, int slot); +int McOpen(int port, int slot, char *filename, int flags); +int McClose(int fd); +int McRead(int fd, void *buf, int length); +int McWrite(int fd, void *buf, int length); +int McSeek(int fd, int offset, int origin); +int McFormat(int port, int slot); +int McGetDir(int port, int slot, char *dirname, int flags, int maxent, sceMcTblGetDir *info); +int McDelete(int port, int slot, char *filename, int flags); +int McFlush(int fd); +int McChDir(int port, int slot, char *newdir, char *currentdir); +int McSetFileInfo(int port, int slot, char *filename, sceMcTblGetDir *info, int flags); +int McEraseBlock(int port, int block, void **pagebuf, void *eccbuf); //MCMAN v1.1 does not have a slot argument +int McReadPage(int port, int slot, int page, void *buf); +int McWritePage(int port, int slot, int page, void *pagebuf, void *eccbuf); +void McDataChecksum(void *buf, void *ecc); +int McReadPS1PDACard(int port, int slot, int page, void *buf); +int McWritePS1PDACard(int port, int slot, int page, void *buf); +int McUnformat(int port, int slot); +int McRetOnly(int fd); +int McGetFreeClusters(int port, int slot); +int McGetMcType(int port, int slot); +void McSetPS1CardFlag(int flag); + +/* Available in XMCMAN only */ +int McEraseBlock2(int port, int slot, int block, void **pagebuf, void *eccbuf); +int McDetectCard2(int port, int slot); +int McGetFormat(int port, int slot); +int McGetEntSpace(int port, int slot, char *dirname); +int McReplaceBadBlock(void); +int McCloseAll(void); +struct irx_id *McGetModuleInfo(void); +int McGetCardSpec(int port, int slot, s16 *pagesize, u16 *blocksize, int *cardsize, u8 *flags); +int McGetFATentry(int port, int slot, int fat_index, int *fat_entry); +int McCheckBlock(int port, int slot, int block); +int McSetFATentry(int port, int slot, int fat_index, int fat_entry); +int McReadDirEntry(int port, int slot, int cluster, int fsindex, McFsEntry **pfse); +void Mc1stCacheEntSetWrFlagOff(void); +int McCreateDirentry(int port, int slot, int parent_cluster, int num_entries, int cluster, sceMcStDateTime *ctime); +int McReadCluster(int port, int slot, int cluster, McCacheEntry **pmce); +int McFlushCache(int port, int slot); +int McSetDirEntryState(int port, int slot, int cluster, int fsindex, int flags); + +#define xfromman_IMPORTS_start DECLARE_IMPORT_TABLE(xfromman, 2, 3) +#define xfromman_IMPORTS_end END_IMPORT_TABLE + +#define mcman_IMPORTS_start DECLARE_IMPORT_TABLE(mcman, 1, 1) +#define mcman_IMPORTS_end END_IMPORT_TABLE + +#define xmcman_IMPORTS_start DECLARE_IMPORT_TABLE(mcman, 2, 3) +#define xmcman_IMPORTS_end END_IMPORT_TABLE + +#define I_McDetectCard DECLARE_IMPORT(5, McDetectCard) +#define I_McOpen DECLARE_IMPORT(6, McOpen) +#define I_McClose DECLARE_IMPORT(7, McClose) +#define I_McRead DECLARE_IMPORT(8, McRead) +#define I_McWrite DECLARE_IMPORT(9, McWrite) +#define I_McSeek DECLARE_IMPORT(10, McSeek) +#define I_McFormat DECLARE_IMPORT(11, McFormat) +#define I_McGetDir DECLARE_IMPORT(12, McGetDir) +#define I_McDelete DECLARE_IMPORT(13, McDelete) +#define I_McFlush DECLARE_IMPORT(14, McFlush) +#define I_McChDir DECLARE_IMPORT(15, McChDir) +#define I_McSetFileInfo DECLARE_IMPORT(16, McSetFileInfo) +#define I_McEraseBlock DECLARE_IMPORT(17, McEraseBlock) +#define I_McReadPage DECLARE_IMPORT(18, McReadPage) +#define I_McWritePage DECLARE_IMPORT(19, McWritePage) +#define I_McDataChecksum DECLARE_IMPORT(20, McDataChecksum); +#define I_McReadPS1PDACard DECLARE_IMPORT(29, McReadPS1PDACard) +#define I_McWritePS1PDACard DECLARE_IMPORT(30, McWritePS1PDACard) +#define I_McUnformat DECLARE_IMPORT(36, McUnformat) +#define I_McRetOnly DECLARE_IMPORT(37, McRetOnly) +#define I_McGetFreeClusters DECLARE_IMPORT(38, McGetFreeClusters) +#define I_McGetMcType DECLARE_IMPORT(39, McGetMcType) +#define I_McSetPS1CardFlag DECLARE_IMPORT(40, McSetPS1CardFlag) +#define I_McEraseBlock2 DECLARE_IMPORT(17, McEraseBlock2) +#define I_McDetectCard2 DECLARE_IMPORT(21, McDetectCard2) +#define I_McGetFormat DECLARE_IMPORT(22, McGetFormat) +#define I_McGetEntSpace DECLARE_IMPORT(23, McGetEntSpace) +#define I_McReplaceBadBlock DECLARE_IMPORT(24, McReplaceBadBlock) +#define I_McCloseAll DECLARE_IMPORT(25, McCloseAll) +#define I_McGetModuleInfo DECLARE_IMPORT(42, McGetModuleInfo) +#define I_McGetCardSpec DECLARE_IMPORT(43, McGetCardSpec) +#define I_McGetFATentry DECLARE_IMPORT(44, McGetFATentry) +#define I_McCheckBlock DECLARE_IMPORT(45, McCheckBlock) +#define I_McSetFATentry DECLARE_IMPORT(46, McSetFATentry) +#define I_McReadDirEntry DECLARE_IMPORT(47, McReadDirEntry) +#define I_Mc1stCacheEntSetWrFlagOff DECLARE_IMPORT(48, Mc1stCacheEntSetWrFlagOff) +#define I_McCreateDirentry DECLARE_IMPORT(49, McCreateDirentry) +#define I_McReadCluster DECLARE_IMPORT(50, McReadCluster) +#define I_McFlushCache DECLARE_IMPORT(51, McFlushCache) +#define I_McSetDirEntryState DECLARE_IMPORT(52, McSetDirEntryState) + +#endif /* __MCMAN_H__ */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/exports.tab b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/exports.tab new file mode 100644 index 0000000..07c8bf1 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/exports.tab @@ -0,0 +1,120 @@ + +#ifndef BUILDING_XFROMMAN +DECLARE_EXPORT_TABLE(mcman, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(McDetectCard) + DECLARE_EXPORT(McOpen) + DECLARE_EXPORT(McClose) + DECLARE_EXPORT(McRead) + DECLARE_EXPORT(McWrite) + DECLARE_EXPORT(McSeek) + DECLARE_EXPORT(McFormat) + DECLARE_EXPORT(McGetDir) + DECLARE_EXPORT(McDelete) + DECLARE_EXPORT(McFlush) + DECLARE_EXPORT(McChDir) + DECLARE_EXPORT(McSetFileInfo) + DECLARE_EXPORT(McEraseBlock) + DECLARE_EXPORT(McReadPage) + DECLARE_EXPORT(McWritePage) + DECLARE_EXPORT(McDataChecksum) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(McReadPS1PDACard) + DECLARE_EXPORT(McWritePS1PDACard) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(McUnformat) + DECLARE_EXPORT(McRetOnly) + DECLARE_EXPORT(McGetFreeClusters) + DECLARE_EXPORT(McGetMcType) + DECLARE_EXPORT(McSetPS1CardFlag) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) +END_EXPORT_TABLE +#endif + +#ifdef BUILDING_XFROMMAN +DECLARE_EXPORT_TABLE(xfromman, 2, 3) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(McDetectCard) + DECLARE_EXPORT(McOpen) + DECLARE_EXPORT(McClose) + DECLARE_EXPORT(McRead) + DECLARE_EXPORT(McWrite) + DECLARE_EXPORT(McSeek) + DECLARE_EXPORT(McFormat) + DECLARE_EXPORT(McGetDir) + DECLARE_EXPORT(McDelete) + DECLARE_EXPORT(McFlush) + DECLARE_EXPORT(McChDir) + DECLARE_EXPORT(McSetFileInfo) + DECLARE_EXPORT(McEraseBlock2) + DECLARE_EXPORT(McReadPage) + DECLARE_EXPORT(McWritePage) + DECLARE_EXPORT(McDataChecksum) + DECLARE_EXPORT(McDetectCard2) + DECLARE_EXPORT(McGetFormat) + DECLARE_EXPORT(McGetEntSpace) + DECLARE_EXPORT(McReplaceBadBlock) + DECLARE_EXPORT(McCloseAll) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(McReadPS1PDACard) + DECLARE_EXPORT(McWritePS1PDACard) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(McUnformat) + DECLARE_EXPORT(McRetOnly) + DECLARE_EXPORT(McGetFreeClusters) + DECLARE_EXPORT(McGetMcType) + DECLARE_EXPORT(McSetPS1CardFlag) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(McGetModuleInfo) + DECLARE_EXPORT(McGetCardSpec) + DECLARE_EXPORT(McGetFATentry) + DECLARE_EXPORT(McCheckBlock) + DECLARE_EXPORT(McSetFATentry) + DECLARE_EXPORT(McReadDirEntry) + DECLARE_EXPORT(Mc1stCacheEntSetWrFlagOff) + DECLARE_EXPORT(McCreateDirentry) + DECLARE_EXPORT(McReadCluster) + DECLARE_EXPORT(McFlushCache) + DECLARE_EXPORT(McSetDirEntryState) + DECLARE_EXPORT(_dummy) +END_EXPORT_TABLE +#endif + +void _dummy() {} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/imports.lst new file mode 100644 index 0000000..77d6447 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/imports.lst @@ -0,0 +1,88 @@ +//--------------------------------------------------------------------------- +// File name: imports.lst +// Description: Used to generate code for IRX function imports +//--------------------------------------------------------------------------- + +#ifdef SIO_DEBUG +sior_IMPORTS_start +I_sio_init +I_sio_printf +sior_IMPORTS_end +#endif + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +I_GetLoadcoreInternalData +loadcore_IMPORTS_end + +intrman_IMPORTS_start +I_CpuEnableIntr +intrman_IMPORTS_end + +sysclib_IMPORTS_start +I_memcpy +I_memset +I_strcat +I_strcmp +I_strcpy +I_strlen +I_strncmp +I_strncpy +sysclib_IMPORTS_end + +thbase_IMPORTS_start +I_DelayThread +thbase_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_DeleteSema +I_SignalSema +I_WaitSema +thsemap_IMPORTS_end + +timrman_IMPORTS_start +I_AllocHardTimer +I_ReferHardTimer +I_SetTimerMode +I_GetTimerCounter +timrman_IMPORTS_end + +modload_IMPORTS_start +I_SetCheckKelfPathCallback +modload_IMPORTS_end + +ioman_IMPORTS_start +I_AddDrv +I_DelDrv +ioman_IMPORTS_end + +#ifndef BUILDING_XFROMMAN +secrman_IMPORTS_start +I_SecrSetMcCommandHandler +I_SecrSetMcDevIDHandler +I_SecrAuthCard +secrman_IMPORTS_end +#endif + +cdvdman_IMPORTS_start +I_sceCdRC +cdvdman_IMPORTS_end + +#ifdef BUILDING_XFROMMAN +fls_IMPORTS_start +I_flash_detect +I_flash_get_info +I_flash_page_erase +I_flash_page_read +I_flash_page_write +fls_IMPORTS_end +#endif + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +//--------------------------------------------------------------------------- +// End of file: imports.lst +//--------------------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/irx_imports.h new file mode 100644 index 0000000..d90b540 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/irx_imports.h @@ -0,0 +1,38 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ + +#include +#ifdef BUILDING_XFROMMAN +#include +#endif +#include +#include +#include +#include +#include +#ifdef SIO_DEBUG +#include +#endif +#include +#include +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/main.c b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/main.c new file mode 100644 index 0000000..749f2bd --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/main.c @@ -0,0 +1,4294 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 jimmikaelkael +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#define SIO2MAN_EXPORTS_IMPLEMENTATION +#include +#include "mcman-internal.h" + +// TODO: last sdk 3.1.0 has MCMAN module version 0x2,0x30 with significant changes. +// Check what was changed, and maybe port changes. +// CRC32: EC5F33F9 +// Note: currently is based on the last XMCMAN from BOOTROM: +// 0x02,0x0a (looks like mistake, cause last XMCMAN is 0x02,0x09) +IRX_ID(MODNAME, 2, 11); + +char sio2man_modname[8] = "sio2man\0"; +int sio2man_type = SIO2MAN; + +char SUPERBLOCK_MAGIC[] = "Sony PS2 Memory Card Format "; +char SUPERBLOCK_VERSION[] = "1.2.0.0"; + +int mcman_wr_port = -1; +int mcman_wr_slot = -1; +int mcman_wr_block = -1; +int mcman_wr_flag3 = -10; +int mcman_curdircluster = -1; + +int timer_ID; +int PS1CardFlag = 1; + +union mcman_pagebuf mcman_pagebuf; +union mcman_PS1PDApagebuf mcman_PS1PDApagebuf; + +#ifndef BUILDING_XFROMMAN +extern struct irx_export_table _exp_mcman; +#endif +#ifdef BUILDING_XFROMMAN +extern struct irx_export_table _exp_xfromman; +#endif +extern u8 mcman_sio2outbufs_PS1PDA[0x90]; + +static u8 mcman_cachebuf[MAX_CACHEENTRY * MCMAN_CLUSTERSIZE]; +static McCacheEntry mcman_entrycache[MAX_CACHEENTRY]; +static McCacheEntry *mcman_mccache[MAX_CACHEENTRY]; + +static McCacheEntry *pmcman_entrycache; +static McCacheEntry **pmcman_mccache; + +static void *mcman_pagedata[32]; +static u8 mcman_backupbuf[16384]; + +static int mcman_badblock_port; +static int mcman_badblock_slot; +static int mcman_badblock; +static int mcman_replacementcluster[16]; + +static McFatCache mcman_fatcache[2][MCMAN_MAXSLOT]; +McFsEntry mcman_dircache[MAX_CACHEDIRENTRY]; + +MC_FHANDLE mcman_fdhandles[MAX_FDHANDLES]; +MCDevInfo mcman_devinfos[4][MCMAN_MAXSLOT]; + +u8 mcman_eccdata[512]; // size for 32 ecc + +#ifndef BUILDING_XFROMMAN +int (*mcman_sio2transfer)(int port, int slot, sio2_transfer_data_t *sio2data); +int (*mc_detectcard)(int port, int slot); +#endif + +// mcman xor table +// clang-format off +static const u8 mcman_xortable[256] = { + 0x00, 0x87, 0x96, 0x11, 0xA5, 0x22, 0x33, 0xB4, + 0xB4, 0x33, 0x22, 0xA5, 0x11, 0x96, 0x87, 0x00, + 0xC3, 0x44, 0x55, 0xD2, 0x66, 0xE1, 0xF0, 0x77, + 0x77, 0xF0, 0xE1, 0x66, 0xD2, 0x55, 0x44, 0xC3, + 0xD2, 0x55, 0x44, 0xC3, 0x77, 0xF0, 0xE1, 0x66, + 0x66, 0xE1, 0xF0, 0x77, 0xC3, 0x44, 0x55, 0xD2, + 0x11, 0x96, 0x87, 0x00, 0xB4, 0x33, 0x22, 0xA5, + 0xA5, 0x22, 0x33, 0xB4, 0x00, 0x87, 0x96, 0x11, + 0xE1, 0x66, 0x77, 0xF0, 0x44, 0xC3, 0xD2, 0x55, + 0x55, 0xD2, 0xC3, 0x44, 0xF0, 0x77, 0x66, 0xE1, + 0x22, 0xA5, 0xB4, 0x33, 0x87, 0x00, 0x11, 0x96, + 0x96, 0x11, 0x00, 0x87, 0x33, 0xB4, 0xA5, 0x22, + 0x33, 0xB4, 0xA5, 0x22, 0x96, 0x11, 0x00, 0x87, + 0x87, 0x00, 0x11, 0x96, 0x22, 0xA5, 0xB4, 0x33, + 0xF0, 0x77, 0x66, 0xE1, 0x55, 0xD2, 0xC3, 0x44, + 0x44, 0xC3, 0xD2, 0x55, 0xE1, 0x66, 0x77, 0xF0, + 0xF0, 0x77, 0x66, 0xE1, 0x55, 0xD2, 0xC3, 0x44, + 0x44, 0xC3, 0xD2, 0x55, 0xE1, 0x66, 0x77, 0xF0, + 0x33, 0xB4, 0xA5, 0x22, 0x96, 0x11, 0x00, 0x87, + 0x87, 0x00, 0x11, 0x96, 0x22, 0xA5, 0xB4, 0x33, + 0x22, 0xA5, 0xB4, 0x33, 0x87, 0x00, 0x11, 0x96, + 0x96, 0x11, 0x00, 0x87, 0x33, 0xB4, 0xA5, 0x22, + 0xE1, 0x66, 0x77, 0xF0, 0x44, 0xC3, 0xD2, 0x55, + 0x55, 0xD2, 0xC3, 0x44, 0xF0, 0x77, 0x66, 0xE1, + 0x11, 0x96, 0x87, 0x00, 0xB4, 0x33, 0x22, 0xA5, + 0xA5, 0x22, 0x33, 0xB4, 0x00, 0x87, 0x96, 0x11, + 0xD2, 0x55, 0x44, 0xC3, 0x77, 0xF0, 0xE1, 0x66, + 0x66, 0xE1, 0xF0, 0x77, 0xC3, 0x44, 0x55, 0xD2, + 0xC3, 0x44, 0x55, 0xD2, 0x66, 0xE1, 0xF0, 0x77, + 0x77, 0xF0, 0xE1, 0x66, 0xD2, 0x55, 0x44, 0xC3, + 0x00, 0x87, 0x96, 0x11, 0xA5, 0x22, 0x33, 0xB4, + 0xB4, 0x33, 0x22, 0xA5, 0x11, 0x96, 0x87, 0x00 +}; +// clang-format on + +//-------------------------------------------------------------- +void long_multiply(u32 v1, u32 v2, u32 *HI, u32 *LO) +{ + register long a, b, c, d; + register long x, y; + + a = (v1 >> 16) & 0xffff; + b = v1 & 0xffff; + c = (v2 >> 16) & 0xffff; + d = v2 & 0xffff; + + *LO = b * d; + x = a * d + c * b; + y = ((*LO >> 16) & 0xffff) + x; + + *LO = (*LO & 0xffff) | ((y & 0xffff) << 16); + *HI = (y >> 16) & 0xffff; + + *HI += a * c; +} + +//-------------------------------------------------------------- +int mcman_chrpos(char *str, int chr) +{ + char *p; + + p = str; + if (*str) { + do { + if (*p == (chr & 0xff)) + break; + p++; + } while (*p); + } + if (*p != (chr & 0xff)) + return -1; + + return p - str; +} +//-------------------------------------------------------------- +int _start(int argc, const char **argv) +{ +#ifndef BUILDING_XFROMMAN + iop_library_t *libptr; + register int i, sio2man_loaded; + void **export_tab; +#endif + +#ifdef SIO_DEBUG + sio_init(38400, 0, 0, 0, 0); +#endif + DPRINTF("_start...\n"); + +#ifndef BUILDING_XFROMMAN + // Get sio2man lib ptr + sio2man_loaded = 0; + libptr = GetLoadcoreInternalData()->let_next; + while (libptr != 0) { + for (i=0; i<8; i++) { + if (libptr->name[i] != sio2man_modname[i]) + break; + } + if (i == 8) { + sio2man_loaded = 1; + break; + } + libptr = libptr->prev; + } + + if (!sio2man_loaded) { + DPRINTF("sio2man module is not loaded...\n"); + return MODULE_NO_RESIDENT_END; + } + + DPRINTF("sio2man version=0x%03x\n", libptr->version); + if (libptr->version >= 0x201) + sio2man_type = XSIO2MAN_V2; + else if (libptr->version > 0x101) + sio2man_type = XSIO2MAN; + + // Get sio2man export table + export_tab = (void **)(((struct irx_export_table *)libptr)->fptrs); + + // Set functions pointers to match SIO2MAN exports + psio2_mc_transfer_init = export_tab[24]; + psio2_transfer = export_tab[25]; + // set internals function pointers for MCMAN + mcman_sio2transfer = (void *)mcsio2_transfer; + mc_detectcard = (void *)McDetectCard2; + + if (sio2man_type >= XSIO2MAN) { + // Set functions pointers to match XSIO2MAN exports + psio2_transfer_reset = export_tab[26]; + if(sio2man_type == XSIO2MAN) + psio2_mtap_change_slot = export_tab[55]; + else + psio2_mtap_change_slot = export_tab[57]; + + // set internals function pointers for XMCMAN + mcman_sio2transfer = (void *)mcsio2_transfer2; + mc_detectcard = (void *)mcman_detectcard; + + // Modify mcman export ver + _exp_mcman.version = 0x203; + // Get mcman export table + export_tab = (void **)(struct irx_export_table *)&_exp_mcman.fptrs; + export_tab[17] = (void *)McEraseBlock2; + export_tab[21] = (void *)McDetectCard2; + export_tab[22] = (void *)McGetFormat; + export_tab[23] = (void *)McGetEntSpace; + export_tab[24] = (void *)McReplaceBadBlock; + export_tab[25] = (void *)McCloseAll; + export_tab[42] = (void *)McGetModuleInfo; + export_tab[43] = (void *)McGetCardSpec; + export_tab[44] = (void *)McGetFATentry; + export_tab[45] = (void *)McCheckBlock; + export_tab[46] = (void *)McSetFATentry; + export_tab[47] = (void *)McReadDirEntry; + export_tab[48] = (void *)Mc1stCacheEntSetWrFlagOff; + export_tab[49] = (void *)McCreateDirentry; + export_tab[50] = (void *)McReadCluster; + export_tab[51] = (void *)McFlushCache; + export_tab[52] = (void *)McSetDirEntryState; + } +#endif + + DPRINTF("registering exports...\n"); +#ifndef BUILDING_XFROMMAN + if (RegisterLibraryEntries(&_exp_mcman) != 0) + return MODULE_NO_RESIDENT_END; +#endif +#ifdef BUILDING_XFROMMAN + if (RegisterLibraryEntries(&_exp_xfromman) != 0) + return MODULE_NO_RESIDENT_END; +#endif + + CpuEnableIntr(); + + DPRINTF("initPS2com...\n"); + mcman_initPS2com(); + + DPRINTF("initPS1PDAcom...\n"); + mcman_initPS1PDAcom(); + + DPRINTF("initcache...\n"); + mcman_initcache(); + + DPRINTF("initdev...\n"); + mcman_initdev(); + + timer_ID = ReferHardTimer(1, 32, 0, 0x6309); + + if (timer_ID != -150) + return MODULE_RESIDENT_END; + + timer_ID = AllocHardTimer(1, 32, 1); + + if (timer_ID > 0) + SetTimerMode(timer_ID, 0); + + DPRINTF("_start returns MODULE_RESIDENT_END...\n"); + + return MODULE_RESIDENT_END; +} + +//-------------------------------------------------------------- +int McGetFormat(int port, int slot) // Export #22 XMCMAN only +{ + DPRINTF("McGetFormat port%d slot%d\n", port, slot); + return mcman_devinfos[port][slot].cardform; +} + +//-------------------------------------------------------------- +int McGetMcType(int port, int slot) // Export #39 +{ + DPRINTF("McGetMcType port%d slot%d\n", port, slot); + return mcman_devinfos[port][slot].cardtype; +} + +//-------------------------------------------------------------- +struct irx_id *McGetModuleInfo(void) // Export #42 XMCMAN only +{ + DPRINTF("McGetModuleInfo\n"); + return &_irx_id; +} + +//-------------------------------------------------------------- +void McSetPS1CardFlag(int flag) // Export #40 +{ + DPRINTF("McSetPS1CardFlag flag %x\n", flag); + PS1CardFlag = flag; +} + +//-------------------------------------------------------------- +int McGetFreeClusters(int port, int slot) // Export #38 +{ + register int r, mcfree; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + DPRINTF("McGetFreeClusters port%d slot%d\n", port, slot); + + mcfree = 0; + if (mcdi->cardform) { + switch (mcdi->cardtype) { + case sceMcTypePS2: + mcfree = mcman_findfree2(port, slot, 0); + break; + case sceMcTypePS1: + case sceMcTypePDA: + mcfree = mcman_findfree1(port, slot, 0); + break; + case sceMcTypeNoCard: + mcfree = 0; + break; + } + if (mcfree == sceMcResFullDevice) + mcfree = 0; + + r = mcfree; + } + else + return 0; + + return r; +} + +//-------------------------------------------------------------- +void mcman_wmemset(void *buf, int size, int value) +{ + int *p = buf; + size = (size >> 2) - 1; + + if (size > -1) { + do { + *p++ = value; + } while (--size > -1); + } +} + +//-------------------------------------------------------------- +int mcman_calcEDC(void *buf, int size) +{ + register u32 checksum; + register int i; + u8 *p = (u8 *)buf; + + checksum = 0; + + if (size > 0) { + size--; + i = 0; + while (size-- != -1) { + checksum ^= p[i]; + i++; + } + } + return checksum & 0xff; +} + +//-------------------------------------------------------------- +int mcman_checkpath(char *str) // check that a string do not contain special chars ( chr<32, ?, *) +{ + register int i; + u8 *p = (u8 *)str; + + i = 0; + while (p[i]) { + if (((p[i] & 0xff) == '?') || ((p[i] & 0xff) == '*')) + return 0; + if ((p[i] & 0xff) < 32) + return 0; + i++; + } + return 1; +} + +//-------------------------------------------------------------- +int mcman_checkdirpath(char *str1, char *str2) +{ + register int r, pos1, pos2, pos; + char *p1 = str1; + char *p2 = str2; + + do { + pos1 = mcman_chrpos(p2, '?'); + pos2 = mcman_chrpos(p2, '*'); + + if ((pos1 < 0) && (pos2 < 0)) { + if (!strcmp(p2, p1)) + return 1; + return 0; + } + pos = pos2; + if (pos1 >= 0) { + pos = pos1; + if (pos2 >= 0) { + pos = pos2; + if (pos1 < pos2) { + pos = pos1; + } + } + } + if (strncmp(p2, p1, pos) != 0) + return 0; + + p2 += pos; + p1 += pos; + + while (p2[0] == '?') { + if (p1[0] == 0) + return 1; + p2++; + p1++; + } + } while (p2[0] != '*'); + + while((p2[0] == '*') || (p2[0] == '?')) + p2++; + + if (p2[0] != 0) { + do { + pos = mcman_chrpos(p1, (u8)p2[0]); + p1 += pos; + if (pos < 0) + return 0; + r = mcman_checkdirpath(p1, p2); + p1++; + } while (r == 0); + } + return 1; +} + +//-------------------------------------------------------------- +void mcman_invhandles(int port, int slot) +{ + register int i = 0; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles; + + do { + if ((fh->port == port) && (fh->slot == slot)) + fh->status = 0; + fh++; + } while (++i < MAX_FDHANDLES); +} + +//-------------------------------------------------------------- +int McCloseAll(void) // Export #25 XMCMAN only +{ + register int fd = 0, rv = 0; + + do { + if (mcman_fdhandles[fd].status) { + register int rc; + + rc = McClose(fd); + if (rc < rv) + rv = rc; + } + fd++; + + } while (fd < MAX_FDHANDLES); + + return rv; +} + +//-------------------------------------------------------------- +int McDetectCard(int port, int slot) // Export #5 +{ +#ifndef BUILDING_XFROMMAN + return mc_detectcard(port, slot); +#endif +#ifdef BUILDING_XFROMMAN + return mcman_detectcard(port, slot); +#endif +} + +//-------------------------------------------------------------- +int mcman_detectcard(int port, int slot) +{ + register int r; + register MCDevInfo *mcdi; + + DPRINTF("mcman_detectcard port%d slot%d\n", port, slot); + mcdi = (MCDevInfo *)&mcman_devinfos[port][slot]; + +#ifndef BUILDING_XFROMMAN + if ((mcdi->cardtype == sceMcTypeNoCard) || (mcdi->cardtype == sceMcTypePS2)) { + r = mcman_probePS2Card2(port, slot); + if (r < -9) { + r = mcman_probePS1Card2(port, slot); + if (!(r < -9)) { + if (mcman_probePDACard(port, slot)) { + mcdi->cardtype = sceMcTypePS1; + return (!PS1CardFlag) ? sceMcResDeniedPS1Permit : r; + } + else { + mcdi->cardtype = sceMcTypePDA; + return r; + } + } + } + else { + mcdi->cardtype = sceMcTypePS2; + return r; + } + } + else { + r = mcman_probePS1Card2(port, slot); + if (r) { + if ((r < -9) || (r >= 0)) { + r = mcman_probePS2Card2(port, slot); + if (!(r < -9)) { + mcdi->cardtype = sceMcTypePS2; + return r; + } + } + else { + if (mcman_probePDACard(port, slot)) { + mcdi->cardtype = sceMcTypePS1; + return (!PS1CardFlag) ? sceMcResDeniedPS1Permit : r; + } + else { + mcdi->cardtype = sceMcTypePDA; + return r; + } + } + } + else { + if (PS1CardFlag) + return sceMcResSucceed; + if (mcdi->cardtype == sceMcTypePS1) + return sceMcResDeniedPS1Permit; + return sceMcResSucceed; + } + } +#endif +#ifdef BUILDING_XFROMMAN + r = mcman_probePS2Card2(port, slot); + if (r >= -9) { + mcdi->cardtype = sceMcTypePS2; + return r; + } +#endif + + mcdi->cardtype = 0; + mcdi->cardform = 0; + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + + return r; +} + +//-------------------------------------------------------------- +int McDetectCard2(int port, int slot) // Export #21 XMCMAN only +{ + register int r; + register MCDevInfo *mcdi; + + DPRINTF("McDetectCard2 port%d slot%d\n", port, slot); + + mcdi = (MCDevInfo *)&mcman_devinfos[port][slot]; + +#ifndef BUILDING_XFROMMAN + if ((mcdi->cardtype == sceMcTypeNoCard) || (mcdi->cardtype == sceMcTypePS2)) { + r = mcman_probePS2Card(port, slot); + if (r < -9) { + r = mcman_probePS1Card(port, slot); + if (!(r < -9)) { + if (mcman_probePDACard(port, slot)) { + mcdi->cardtype = sceMcTypePS1; + return (!PS1CardFlag) ? sceMcResDeniedPS1Permit : r; + } + else { + mcdi->cardtype = sceMcTypePDA; + return r; + } + } + } + else { + mcdi->cardtype = sceMcTypePS2; + return r; + } + } + else { + r = mcman_probePS1Card(port, slot); + if (r) { + if ((r < -9) || (r >= 0)) { + r = mcman_probePS2Card(port, slot); + if (!(r < -9)) { + mcdi->cardtype = sceMcTypePS2; + return r; + } + } + else { + if (mcman_probePDACard(port, slot)) { + mcdi->cardtype = sceMcTypePS1; + return (!PS1CardFlag) ? sceMcResDeniedPS1Permit : r; + } + else { + mcdi->cardtype = sceMcTypePDA; + return r; + } + } + } + else { + if (PS1CardFlag) + return sceMcResSucceed; + if (mcdi->cardtype == sceMcTypePS1) + return sceMcResDeniedPS1Permit; + return sceMcResSucceed; + } + } +#endif +#ifdef BUILDING_XFROMMAN + r = mcman_probePS2Card(port, slot); + if (r >= -9) { + mcdi->cardtype = sceMcTypePS2; + return r; + } +#endif + + mcdi->cardtype = 0; + mcdi->cardform = 0; + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + + return r; +} + +//-------------------------------------------------------------- +int McOpen(int port, int slot, char *filename, int flag) // Export #6 +{ + register int r; + + r = McDetectCard(port, slot); + if (r != sceMcResSucceed) + return r; + + if (!PS1CardFlag) + flag &= 0xFFFFDFFF; // disables FRCOM flag OR what is it + + if (mcman_devinfos[port][slot].cardtype == sceMcTypePS2) + r = mcman_open2(port, slot, filename, flag); + else + r = mcman_open1(port, slot, filename, flag); + + if (r < -9) { + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + } + + return r; +} + +//-------------------------------------------------------------- +int McClose(int fd) // Export #7 +{ + register MC_FHANDLE *fh; + register MCDevInfo *mcdi; + register int r; + + if (!((u32)fd < MAX_FDHANDLES)) + return sceMcResDeniedPermit; + + fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + if (!fh->status) + return sceMcResDeniedPermit; + + fh->status = 0; + r = McDetectCard(fh->port, fh->slot); + if (r != sceMcResSucceed) + return r; + + r = McFlushCache(fh->port, fh->slot); + if (r < -9) { + mcman_invhandles(fh->port, fh->slot); + mcman_clearcache(fh->port, fh->slot); + } + + if (r != sceMcResSucceed) + return r; + + if (fh->unknown2 != 0) { + fh->unknown2 = 0; + mcdi = (MCDevInfo *)&mcman_devinfos[fh->port][fh->slot]; + if (mcdi->cardtype == sceMcTypePS2) + r = mcman_close2(fd); + else + r = mcman_close1(fd); + + if (r < -9) { + mcman_invhandles(fh->port, fh->slot); + mcman_clearcache(fh->port, fh->slot); + } + + if (r != sceMcResSucceed) + return r; + } + + r = McFlushCache(fh->port, fh->slot); + if (r < -9) { + mcman_invhandles(fh->port, fh->slot); + mcman_clearcache(fh->port, fh->slot); + } + + return r; +} + +//-------------------------------------------------------------- +int McFlush(int fd) // Export #14 +{ + register int r; + register MC_FHANDLE *fh; + register MCDevInfo *mcdi; + + if (!((u32)fd < MAX_FDHANDLES)) + return sceMcResDeniedPermit; + + fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + if (!fh->status) + return sceMcResDeniedPermit; + + r = McDetectCard(fh->port, fh->slot); + if (r != sceMcResSucceed) + return r; + + r = McFlushCache(fh->port, fh->slot); + if (r < -9) { + mcman_invhandles(fh->port, fh->slot); + mcman_clearcache(fh->port, fh->slot); + } + + if (r != sceMcResSucceed) { + fh->status = 0; + return r; + } + + if (fh->unknown2 != 0) { + fh->unknown2 = 0; + mcdi = (MCDevInfo *)&mcman_devinfos[fh->port][fh->slot]; + if (mcdi->cardtype == sceMcTypePS2) + r = mcman_close2(fd); + else + r = mcman_close1(fd); + + if (r < -9) { + mcman_invhandles(fh->port, fh->slot); + mcman_clearcache(fh->port, fh->slot); + } + + if (r != sceMcResSucceed) { + fh->status = 0; + return r; + } + } + + r = McFlushCache(fh->port, fh->slot); + if (r < 0) + fh->status = 0; + + if (r < -9) { + mcman_invhandles(fh->port, fh->slot); + mcman_clearcache(fh->port, fh->slot); + } + + return r; +} + +//-------------------------------------------------------------- +int McSeek(int fd, int offset, int origin) // Export #10 +{ + register int r; + register MC_FHANDLE *fh; + + DPRINTF("McSeek fd %d offset %d origin %d\n", fd, offset, origin); + + if (!((u32)fd < MAX_FDHANDLES)) + return sceMcResDeniedPermit; + + fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + if (!fh->status) + return sceMcResDeniedPermit; + + r = McDetectCard(fh->port, fh->slot); + if (r != sceMcResSucceed) + return r; + + switch (origin) { + default: + case SEEK_CUR: + r = fh->position + offset; + break; + case SEEK_SET: + r = offset; + break; + case SEEK_END: + r = fh->filesize + offset; + break; + } + + return fh->position = (r < 0) ? 0 : r; +} + +//-------------------------------------------------------------- +int McRead(int fd, void *buf, int length) // Export #8 +{ + register int r; + register MC_FHANDLE *fh; + + if (!((u32)fd < MAX_FDHANDLES)) + return sceMcResDeniedPermit; + + fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + if (!fh->status) + return sceMcResDeniedPermit; + + if (!fh->rdflag) + return sceMcResDeniedPermit; + + r = McDetectCard(fh->port, fh->slot); + if (r != sceMcResSucceed) + return r; + + if (mcman_devinfos[fh->port][fh->slot].cardtype == sceMcTypePS2) + r = mcman_read2(fd, buf, length); + else + r = mcman_read1(fd, buf, length); + + if (r < 0) + fh->status = 0; + + if (r < -9) { + mcman_invhandles(fh->port, fh->slot); + mcman_clearcache(fh->port, fh->slot); + } + + return r; +} + +//-------------------------------------------------------------- +int McWrite(int fd, void *buf, int length) // Export #9 +{ + register int r; + register MC_FHANDLE *fh; + + if (!((u32)fd < MAX_FDHANDLES)) + return sceMcResDeniedPermit; + + fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + if (!fh->status) + return sceMcResDeniedPermit; + + if (!fh->wrflag) + return sceMcResDeniedPermit; + + r = McDetectCard(fh->port, fh->slot); + if (r != sceMcResSucceed) + return r; + + if (mcman_devinfos[fh->port][fh->slot].cardtype == sceMcTypePS2) + r = mcman_write2(fd, buf, length); + else + r = mcman_write1(fd, buf, length); + + if (r < 0) + fh->status = 0; + + if (r < -9) { + mcman_invhandles(fh->port, fh->slot); + mcman_clearcache(fh->port, fh->slot); + } + + return r; +} + +//-------------------------------------------------------------- +int McGetEntSpace(int port, int slot, char *dirname) // Export #23 XMCMAN only +{ + register int r; + + r = McDetectCard(port, slot); + if (r != sceMcResSucceed) + return r; + + if (mcman_devinfos[port][slot].cardtype == sceMcTypePS2) { + r = mcman_getentspace(port, slot, dirname); + } + + if (r < -9) { + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + } + + return r; +} + +//-------------------------------------------------------------- +int McGetDir(int port, int slot, char *dirname, int flags, int maxent, sceMcTblGetDir *info) // Export #12 +{ + register int r; + + r = McDetectCard(port, slot); + if (r != sceMcResSucceed) + return r; + + if (mcman_devinfos[port][slot].cardtype == sceMcTypePS2) + r = mcman_getdir2(port, slot, dirname, flags & 0xFFFF, maxent, info); + else + r = mcman_getdir1(port, slot, dirname, flags & 0xFFFF, maxent, info); + + if (r < -9) { + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + } + + return r; +} + +//-------------------------------------------------------------- +int mcman_dread(int fd, io_dirent_t *dirent) +{ + register int r; + register MC_FHANDLE *fh; + + if (!((u32)fd < MAX_FDHANDLES)) + return sceMcResDeniedPermit; + + fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + if (!fh->status) + return sceMcResDeniedPermit; + + if (!fh->drdflag) + return sceMcResDeniedPermit; + + r = McDetectCard(fh->port, fh->slot); + if (r != sceMcResSucceed) + return r; + + if (mcman_devinfos[fh->port][fh->slot].cardtype == sceMcTypePS2) + r = mcman_dread2(fd, dirent); + else + r = mcman_dread1(fd, dirent); + + if (r < 0) + fh->status = 0; + + if (r < -9) { + mcman_invhandles(fh->port, fh->slot); + mcman_clearcache(fh->port, fh->slot); + } + + return r; +} + +//-------------------------------------------------------------- +int mcman_getstat(int port, int slot, char *filename, io_stat_t *stat) +{ + register int r; + + r = McDetectCard(port, slot); + if (r != sceMcResSucceed) + return r; + + if (mcman_devinfos[port][slot].cardtype == sceMcTypePS2) + r = mcman_getstat2(port, slot, filename, stat); + else + r = mcman_getstat1(port, slot, filename, stat); + + if (r < -9) { + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + } + + return r; +} + +//-------------------------------------------------------------- +int McSetFileInfo(int port, int slot, char *filename, sceMcTblGetDir *info, int flags) // Export #16 +{ + register int r; + + r = McDetectCard(port, slot); + if (r != sceMcResSucceed) + return r; + + if (mcman_devinfos[port][slot].cardtype == sceMcTypePS2) + r = mcman_setinfo2(port, slot, filename, info, flags); + else + r = mcman_setinfo1(port, slot, filename, info, flags); + + if (r < -9) { + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + } + + if (r == sceMcResSucceed) { + r = McFlushCache(port, slot); + if (r < -9) { + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + } + } + + return r; +} + +//-------------------------------------------------------------- +int McChDir(int port, int slot, char *newdir, char *currentdir) // Export #15 +{ + register int r; + + r = McDetectCard(port, slot); + if (r != sceMcResSucceed) + return r; + + if (mcman_devinfos[port][slot].cardtype == sceMcTypePS2) + r = mcman_chdir(port, slot, newdir, currentdir); + else { + currentdir[0] = 0; + r = sceMcResSucceed; + } + + if (r < -9) { + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + } + + return r; +} + +//-------------------------------------------------------------- +int McDelete(int port, int slot, char *filename, int flags) // Export #13 +{ + register int r; + + r = McDetectCard(port, slot); + if (r != sceMcResSucceed) + return r; + + if (mcman_devinfos[port][slot].cardtype == sceMcTypePS2) + r = mcman_delete2(port, slot, filename, flags); + else + r = mcman_delete1(port, slot, filename, flags); + + if (r < -9) { + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + } + + return r; +} + +//-------------------------------------------------------------- +int McFormat(int port, int slot) // Export #11 +{ + register int r; + + mcman_invhandles(port, slot); + + r = McDetectCard(port, slot); + if (r < -2) + return r; + + mcman_clearcache(port, slot); + + if (mcman_devinfos[port][slot].cardtype == sceMcTypePS2) + r = mcman_format2(port, slot); + else + r = mcman_format1(port, slot); + + if (r < -9) { + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + } + + return r; +} + +//-------------------------------------------------------------- +int McUnformat(int port, int slot) // Export #36 +{ + register int r; + + mcman_invhandles(port, slot); + + r = McDetectCard(port, slot); + if (r < -2) + return r; + + mcman_clearcache(port, slot); + + if (mcman_devinfos[port][slot].cardtype == sceMcTypePS2) + r = mcman_unformat2(port, slot); + else + r = mcman_unformat1(port, slot); + + mcman_devinfos[port][slot].cardform = 0; + + if (r < -9) { + mcman_invhandles(port, slot); + mcman_clearcache(port, slot); + } + + return r; +} + +//-------------------------------------------------------------- +int mcman_getmcrtime(sceMcStDateTime *time) +{ + register int retries; + sceCdCLOCK cdtime; + + retries = 64; + + do { + if (sceCdRC(&cdtime)) + break; + } while (--retries > 0); + + if (cdtime.stat & 0x80) { + time->Year = 2000; + time->Month = 3; + time->Day = 4; + time->Hour = 0; + time->Min = 0; + time->Sec = 0; + time->Resv2 = 0; + } + else { + time->Resv2 = 0; + time->Sec = btoi(cdtime.second); + time->Min = btoi(cdtime.minute); + time->Hour = btoi(cdtime.hour); + time->Day = btoi(cdtime.day); + + if ((cdtime.month & 0x10) != 0) //Keep only valid bits: 0x1f (for month values 1-12 in BCD) + time->Month = (cdtime.month & 0xf) + 0xa; + else + time->Month = cdtime.month & 0xf; + + time->Year = btoi(cdtime.year) + 2000; + } + + return 0; +} + +//-------------------------------------------------------------- +int McEraseBlock(int port, int block, void **pagebuf, void *eccbuf) // Export #17 in MCMAN +{ + return mcman_eraseblock(port, 0, block, (void **)pagebuf, eccbuf); +} + +//-------------------------------------------------------------- +int McEraseBlock2(int port, int slot, int block, void **pagebuf, void *eccbuf) // Export #17 in XMCMAN +{ + return mcman_eraseblock(port, slot, block, (void **)pagebuf, eccbuf); +} + +//-------------------------------------------------------------- +int McReadPage(int port, int slot, int page, void *buf) // Export #18 +{ + register int r, index, ecres, retries, count, erase_byte; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + u8 eccbuf[32]; + u8 *pdata, *peccb; + + count = (mcdi->pagesize + 127) >> 7; + erase_byte = (mcdi->cardflags & CF_ERASE_ZEROES) ? 0x0 : 0xFF; + + retries = 0; + ecres = sceMcResSucceed; + do { + if (!mcman_readpage(port, slot, page, buf, eccbuf)) { + if (mcdi->cardflags & CF_USE_ECC) { // checking ECC from spare data block + // check for erased page (last byte of spare data set to 0xFF or 0x0)/ + if (eccbuf[mcman_sparesize(port, slot) - 1] == erase_byte) + break; + + index = 0; + + if (count > 0) { + peccb = (u8 *)eccbuf; + pdata = (u8 *)buf; + + do { + r = mcman_correctdata(pdata, peccb); + if (r < ecres) + ecres = r; + + peccb += 3; + pdata += 128; + } while (++index < count); + } + + if (ecres == sceMcResSucceed) + break; + + if ((retries == 4) && (!(ecres < sceMcResNoFormat))) + break; + } + else + { + break; + } + } + } while (++retries < 5); + + if (retries < 5) + return sceMcResSucceed; + + return (ecres != sceMcResSucceed) ? sceMcResNoFormat : sceMcResChangedCard; +} + +//-------------------------------------------------------------- +void McDataChecksum(void *buf, void *ecc) // Export #20 +{ + register u8 *p, *p_ecc; + register int i, a2, a3, v, t0; + + p = buf; + i = 0; + a2 = 0; + a3 = 0; + t0 = 0; + + do { + v = mcman_xortable[*p++]; + a2 ^= v; + if (v & 0x80) { + a3 ^= ~i; + t0 ^= i; + } + } while (++i < 0x80); + + p_ecc = ecc; + p_ecc[0] = ~a2 & 0x77; + p_ecc[1] = ~a3 & 0x7F; + p_ecc[2] = ~t0 & 0x7F; +} + +//-------------------------------------------------------------- +int mcman_getcnum(int port, int slot) +{ + return ((port & 1) << 3) + slot; +} + +//-------------------------------------------------------------- +int mcman_correctdata(void *buf, void *ecc) +{ + register int xor0, xor1, xor2, xor3, xor4; + u8 eccbuf[12]; + u8 *p = (u8 *)ecc; + + McDataChecksum(buf, eccbuf); + + xor0 = p[0] ^ eccbuf[0]; + xor1 = p[1] ^ eccbuf[1]; + xor2 = p[2] ^ eccbuf[2]; + + xor3 = xor1 ^ xor2; + xor4 = (xor0 & 0xf) ^ (xor0 >> 4); + + if (!xor0 && !xor1 && !xor2) + return 0; + + if ((xor3 == 0x7f) && (xor4 == 0x7)) { + p[xor2] ^= 1 << (xor0 >> 4); + return -1; + } + + xor0 = 0; + xor2 = 7; + do { + if ((xor3 & 1)) + xor0++; + xor2--; + xor3 = xor3 >> 1; + } while (xor2 >= 0); + + xor2 = 3; + do { + if ((xor4 & 1)) + xor0++; + xor2--; + xor4 = xor4 >> 1; + } while (xor2 >= 0); + + if (xor0 == 1) + return -2; + + return -3; +} + +//-------------------------------------------------------------- +int mcman_sparesize(int port, int slot) +{ // Get ps2 mc spare size by dividing pagesize / 32 + return (mcman_devinfos[port][slot].pagesize + 0x1F) >> 5; +} + +//-------------------------------------------------------------- +int mcman_setdevspec(int port, int slot) +{ + int cardsize; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + DPRINTF("mcman_setdevspec port%d, slot%d\n", port, slot); + + if (McGetCardSpec(port, slot, &mcdi->pagesize, &mcdi->blocksize, &cardsize, &mcdi->cardflags) != sceMcResSucceed) + return sceMcResFullDevice; + + mcdi->pages_per_cluster = MCMAN_CLUSTERSIZE / mcdi->pagesize; + mcdi->cluster_size = MCMAN_CLUSTERSIZE; + mcdi->unknown1 = 0; + mcdi->unknown2 = 0; + mcdi->unused = 0xff00; + mcdi->FATentries_per_cluster = MCMAN_CLUSTERFATENTRIES; + mcdi->unknown5 = -1; + mcdi->rootdir_cluster2 = mcdi->rootdir_cluster; + mcdi->clusters_per_block = mcdi->blocksize / mcdi->pages_per_cluster; + mcdi->clusters_per_card = (cardsize / mcdi->blocksize) * (mcdi->blocksize / mcdi->pages_per_cluster); + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_setdevinfos(int port, int slot) +{ + register int r, allocatable_clusters_per_card, iscluster_valid, current_allocatable_cluster, cluster_cnt; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McFsEntry *pfse; + + DPRINTF("mcman_setdevinfos port%d slot%d\n", port, slot); + + mcman_wmemset((void *)mcdi, sizeof(MCDevInfo), 0); + + r = mcman_setdevspec(port, slot); + if (r != sceMcResSucceed) + return -49; + + r = McReadPage(port, slot, 0, &mcman_pagebuf); + if (r == sceMcResNoFormat) + return sceMcResNoFormat; // should rebuild a valid superblock here + if (r != sceMcResSucceed) + return -48; + + if (strncmp(SUPERBLOCK_MAGIC, mcman_pagebuf.magic, 28) != 0) { + DPRINTF("mcman_setdevinfos No card format !!!\n"); + return sceMcResNoFormat; + } + + if (((mcman_pagebuf.byte[28] - 48) == 1) && ((mcman_pagebuf.byte[30] - 48) == 0)) // check ver major & minor + return sceMcResNoFormat; + + u8 *p = (u8 *)mcdi; + for (r=0; r<0x150; r++) + p[r] = mcman_pagebuf.byte[r]; + + mcdi->cardtype = sceMcTypePS2; // <-- + + r = mcman_checkBackupBlocks(port, slot); + if (r != sceMcResSucceed) + return -47; + + r = McReadDirEntry(port, slot, 0, 0, &pfse); + if (r != sceMcResSucceed) + return sceMcResNoFormat; // -46 + + if (strcmp(pfse->name, ".") != 0) + return sceMcResNoFormat; + + if (McReadDirEntry(port, slot, 0, 1, &pfse) != sceMcResSucceed) + return -45; + + if (strcmp(pfse->name, "..") != 0) + return sceMcResNoFormat; + + mcdi->cardform = 1; +// mcdi->cardtype = sceMcTypePS2; + + if (((mcman_pagebuf.byte[28] - 48) == 1) && ((mcman_pagebuf.byte[30] - 48) == 1)) { // check ver major & minor + if ((mcdi->clusters_per_block * mcdi->backup_block2) == mcdi->alloc_end) + mcdi->alloc_end = (mcdi->clusters_per_block * mcdi->backup_block2) - mcdi->alloc_offset; + } + + u32 hi, lo, temp; + + long_multiply(mcdi->clusters_per_card, 0x10624dd3, &hi, &lo); + temp = (hi >> 6) - (mcdi->clusters_per_card >> 31); + allocatable_clusters_per_card = (((((temp << 5) - temp) << 2) + temp) << 3) + 1; + iscluster_valid = 0; + cluster_cnt = 0; + current_allocatable_cluster = mcdi->alloc_offset; + + while (cluster_cnt < allocatable_clusters_per_card) { + if (current_allocatable_cluster >= mcdi->clusters_per_card) + break; + + if (((current_allocatable_cluster % mcdi->clusters_per_block) == 0) \ + || (mcdi->alloc_offset == current_allocatable_cluster)) { + iscluster_valid = 1; + for (r=0; r<16; r++) { + if ((current_allocatable_cluster / mcdi->clusters_per_block) == mcdi->bad_block_list[r]) + iscluster_valid = 0; + } + } + if (iscluster_valid == 1) + cluster_cnt++; + current_allocatable_cluster++; + } + + mcdi->max_allocatable_clusters = current_allocatable_cluster - mcdi->alloc_offset; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_reportBadBlocks(int port, int slot) +{ + register int r, i, block, bad_blocks, page, erase_byte, err_cnt, err_limit; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + u8 *p; + + DPRINTF("mcman_reportBadBlocks port%d, slot%d\n", port, slot); + + mcman_wmemset((void *)mcdi->bad_block_list, 128, -1); + + if ((mcdi->cardflags & CF_BAD_BLOCK) == 0) + return sceMcResSucceed; + + err_limit = (((mcdi->pagesize << 16) >> 16) + ((mcdi->pagesize << 16) >> 31)) >> 1; //s7 + + erase_byte = 0; + if ((mcdi->cardflags & CF_ERASE_ZEROES) != 0) + erase_byte = 0xff; + + bad_blocks = 0; // s2 + + if ((mcdi->clusters_per_card / mcdi->clusters_per_block) > 0) { + + block = 0; // s1 + + do { + if (bad_blocks >= 16) + break; + + err_cnt = 0; //s4 + page = 0; //s3 + do { + + r = McReadPage(port, slot, (block * mcdi->blocksize) + page, &mcman_pagebuf); + if (r == sceMcResNoFormat) { + mcdi->bad_block_list[bad_blocks] = block; + bad_blocks++; + break; + } + if (r != sceMcResSucceed) + return r; + + if ((mcdi->cardflags & CF_USE_ECC) == 0) { + p = mcman_pagebuf.byte; + for (i = 0; i < mcdi->pagesize; i++) { + // check if the content of page is clean + if (*p++ != erase_byte) + err_cnt++; + + if (err_cnt >= err_limit) { + mcdi->bad_block_list[bad_blocks] = block; + bad_blocks++; + break; + } + } + } + } while (++page < 2); + + } while (++block < (mcdi->clusters_per_card / mcdi->clusters_per_block)); + } + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int McCreateDirentry(int port, int slot, int parent_cluster, int num_entries, int cluster, sceMcStDateTime *ctime) +{ + register int r; + McCacheEntry *mce; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McFsEntry *mfe, *mfe_next, *pfse; + + DPRINTF("McCreateDirentry port%d slot%d parent_cluster %x num_entries %d cluster %x\n", port, slot, parent_cluster, num_entries, cluster); + + r = McReadCluster(port, slot, mcdi->alloc_offset + cluster, &mce); + if (r != sceMcResSucceed) + return r; + + mcman_wmemset(mce->cl_data, MCMAN_CLUSTERSIZE, 0); + + mfe = (McFsEntry*)mce->cl_data; + mfe_next = (McFsEntry*)(mce->cl_data + sizeof (McFsEntry)); + + mfe->mode = sceMcFileAttrReadable | sceMcFileAttrWriteable | sceMcFileAttrExecutable \ + | sceMcFileAttrSubdir | sceMcFile0400 | sceMcFileAttrExists; // 0x8427 + + if (ctime == NULL) + mcman_getmcrtime(&mfe->created); + else + mfe->created = *ctime; + + mfe->modified = mfe->created; + + mfe->length = 0; + mfe->dir_entry = num_entries; + mfe->cluster = parent_cluster; + mfe->name[0] = '.'; + mfe->name[1] = '\0'; + + if ((parent_cluster == 0) && (num_entries == 0)) { + // entry is root directory + mfe_next->created = mfe->created; + mfe->length = 2; + mfe++; + + mfe->mode = sceMcFileAttrWriteable | sceMcFileAttrExecutable | sceMcFileAttrSubdir \ + | sceMcFile0400 | sceMcFileAttrExists | sceMcFileAttrHidden; // 0xa426 + mfe->dir_entry = 0; + mfe->cluster = 0; + } + else { + // entry is normal "." / ".." + McReadDirEntry(port, slot, parent_cluster, 0, &pfse); + + mfe_next->created = pfse->created; + mfe++; + + mfe->mode = sceMcFileAttrReadable | sceMcFileAttrWriteable | sceMcFileAttrExecutable \ + | sceMcFileAttrSubdir | sceMcFile0400 | sceMcFileAttrExists; // 0x8427 + mfe->dir_entry = pfse->dir_entry; + + mfe->cluster = pfse->cluster; + } + + mfe->modified = mfe->created; + mfe->length = 0; + + mfe->name[0] = '.'; + mfe->name[1] = '.'; + mfe->name[2] = '\0'; + + mce->wr_flag = 1; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_fatRseek(int fd) +{ + register int r, entries_to_read, fat_index; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; //s1 + register MCDevInfo *mcdi = &mcman_devinfos[fh->port][fh->slot]; //s2 + int fat_entry; + + entries_to_read = fh->position / mcdi->cluster_size; //s0 + + //s5 = 0 + + if (entries_to_read < fh->clust_offset) //v1 = fh->fh->clust_offset + fat_index = fh->freeclink; + else { + fat_index = fh->clink; // a2 + entries_to_read -= fh->clust_offset; + } + + if (entries_to_read == 0) { + if (fat_index >= 0) + return fat_index + mcdi->alloc_offset; + + return sceMcResFullDevice; + } + + do { + r = McGetFATentry(fh->port, fh->slot, fat_index, &fat_entry); + if (r != sceMcResSucceed) + return r; + + fat_index = fat_entry; + + if (fat_index >= -1) + return sceMcResFullDevice; + + entries_to_read--; + + fat_index &= 0x7fffffff; + fh->clink = fat_index; + fh->clust_offset = (fh->position / mcdi->cluster_size) - entries_to_read; + + } while (entries_to_read > 0); + + return fat_index + mcdi->alloc_offset; +} + +//-------------------------------------------------------------- +int mcman_fatWseek(int fd) // modify FAT to hold new content for a file +{ + register int r, entries_to_write, fat_index; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + register MCDevInfo *mcdi = &mcman_devinfos[fh->port][fh->slot]; + register McCacheEntry *mce; + int fat_entry; + + entries_to_write = fh->position / mcdi->cluster_size; + + if ((fh->clust_offset == 0) || (entries_to_write < fh->clust_offset)) { + fat_index = fh->freeclink; + + if (fat_index < 0) { + fat_index = mcman_findfree2(fh->port, fh->slot, 1); + + if (fat_index < 0) + return sceMcResFullDevice; + + mce = (McCacheEntry *)mcman_get1stcacheEntp(); + fh->freeclink = fat_index; + + r = mcman_close2(fd); + if (r != sceMcResSucceed) + return r; + + mcman_addcacheentry(mce); + McFlushCache(fh->port, fh->slot); + } + } + else { + fat_index = fh->clink; + entries_to_write -= fh->clust_offset; + } + + if (entries_to_write != 0) { + do { + r = McGetFATentry(fh->port, fh->slot, fat_index, &fat_entry); + if (r != sceMcResSucceed) + return r; + + if (fat_entry >= 0xffffffff) { + r = mcman_findfree2(fh->port, fh->slot, 1); + if (r < 0) + return r; + fat_entry = r; + fat_entry |= 0x80000000; + + mce = (McCacheEntry *)mcman_get1stcacheEntp(); + + r = McSetFATentry(fh->port, fh->slot, fat_index, fat_entry); + if (r != sceMcResSucceed) + return r; + + mcman_addcacheentry(mce); + } + + entries_to_write--; + fat_index = fat_entry & 0x7fffffff; + } while (entries_to_write > 0); + } + + fh->clink = fat_index; + fh->clust_offset = fh->position / mcdi->cluster_size; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_findfree2(int port, int slot, int reserve) +{ + register int r, rfree, indirect_index, ifc_index, fat_offset, indirect_offset, fat_index, block; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McCacheEntry *mce1, *mce2; + + DPRINTF("mcman_findfree2 port%d slot%d reserve%d\n", port, slot, reserve); + + fat_index = mcdi->unknown2; + rfree = 0; + + for (fat_index = mcdi->unknown2; fat_index < mcdi->max_allocatable_clusters; fat_index++) { + + indirect_index = fat_index / mcdi->FATentries_per_cluster; + fat_offset = fat_index % mcdi->FATentries_per_cluster; + + if ((fat_offset == 0) || (fat_index == mcdi->unknown2)) { + + ifc_index = indirect_index / mcdi->FATentries_per_cluster; + r = McReadCluster(port, slot, mcdi->ifc_list[ifc_index], &mce1); + if (r != sceMcResSucceed) + return r; + //} + //if ((fat_offset == 0) || (fat_index == mcdi->unknown2)) { + indirect_offset = indirect_index % mcdi->FATentries_per_cluster; + McFatCluster *fc = (McFatCluster *)mce1->cl_data; + r = McReadCluster(port, slot, fc->entry[indirect_offset], &mce2); + if (r != sceMcResSucceed) + return r; + } + + McFatCluster *fc = (McFatCluster *)mce2->cl_data; + + if (fc->entry[fat_offset] >= 0) { + block = (mcdi->alloc_offset + fat_offset) / mcdi->clusters_per_block; + if (block != mcman_badblock) { + if (reserve) { + fc->entry[fat_offset] = 0xffffffff; + mce2->wr_flag = 1; + mcdi->unknown2 = fat_index; + return fat_index; + } + rfree++; + } + } + } + + if (reserve) + return sceMcResFullDevice; + + return (rfree) ? rfree : sceMcResFullDevice; +} + +//-------------------------------------------------------------- +int mcman_getentspace(int port, int slot, char *dirname) +{ + register int r, i, entspace; + McCacheDir cacheDir; + McFsEntry *fse; + McFsEntry mfe; + u8 *pfsentry, *pmfe, *pfseend; + + DPRINTF("mcman_getentspace port%d slot%d dirname %s\n", port, slot, dirname); + + r = mcman_cachedirentry(port, slot, dirname, &cacheDir, &fse, 1); + if (r > 0) + return sceMcResNoEntry; + if (r < 0) + return r; + + pfsentry = (u8 *)fse; + pmfe = (u8 *)&mfe; + pfseend = (u8 *)(pfsentry + sizeof (McFsEntry)); + + do { + *((u32 *)pmfe ) = *((u32 *)pfsentry ); + *((u32 *)pmfe+1) = *((u32 *)pfsentry+1); + *((u32 *)pmfe+2) = *((u32 *)pfsentry+2); + *((u32 *)pmfe+3) = *((u32 *)pfsentry+3); + pfsentry += 16; + pmfe += 16; + } while (pfsentry < pfseend); + + entspace = mfe.length & 1; + + for (i = 0; i < mfe.length; i++) { + + r = McReadDirEntry(port, slot, mfe.cluster, i, &fse); + if (r != sceMcResSucceed) + return r; + if ((fse->mode & sceMcFileAttrExists) == 0) + entspace++; + } + + return entspace; +} + +//-------------------------------------------------------------- +int mcman_cachedirentry(int port, int slot, char *filename, McCacheDir *pcacheDir, McFsEntry **pfse, int unknown_flag) +{ + register int r, fsindex, cluster, fmode; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McFsEntry *fse; + McCacheDir cacheDir; + u8 *pfsentry, *pcache, *pfseend; + char *p; + + DPRINTF("mcman_cachedirentry port%d slot%d name %s\n", port, slot, filename); + + if (pcacheDir == NULL) { + pcacheDir = &cacheDir; + pcacheDir->maxent = -1; + } + + p = filename; + if (*p == '/') { + p++; + cluster = 0; + fsindex = 0; + } + else { + cluster = mcdi->rootdir_cluster2; + fsindex = mcdi->unknown1; + } + + r = McReadDirEntry(port, slot, cluster, fsindex, &fse); + if (r != sceMcResSucceed) + return r; + + if (*p == 0) { + if (!(fse->mode & sceMcFileAttrExists)) + return 2; + + if (pcacheDir == NULL) { + *pfse = (McFsEntry *)fse; + return sceMcResSucceed; + } + + pfsentry = (u8 *)fse; + pcache = (u8 *)&mcman_dircache[0]; + pfseend = (u8 *)(pfsentry + sizeof (McFsEntry)); + + do { + *((u32 *)pcache ) = *((u32 *)pfsentry ); + *((u32 *)pcache+1) = *((u32 *)pfsentry+1); + *((u32 *)pcache+2) = *((u32 *)pfsentry+2); + *((u32 *)pcache+3) = *((u32 *)pfsentry+3); + pfsentry += 16; + pcache += 16; + } while (pfsentry < pfseend); + + r = mcman_getdirinfo(port, slot, (McFsEntry *)&mcman_dircache[0], ".", pcacheDir, unknown_flag); + + McReadDirEntry(port, slot, pcacheDir->cluster, pcacheDir->fsindex, pfse); + + if (r > 0) + return 2; + + return r; + + } else { + + do { + fmode = sceMcFileAttrReadable | sceMcFileAttrExecutable; + if ((fse->mode & fmode) != fmode) + return sceMcResDeniedPermit; + + pfsentry = (u8 *)fse; + pcache = (u8 *)&mcman_dircache[0]; + pfseend = (u8 *)(pfsentry + sizeof(McFsEntry)); + + do { + *((u32 *)pcache ) = *((u32 *)pfsentry ); + *((u32 *)pcache+1) = *((u32 *)pfsentry+1); + *((u32 *)pcache+2) = *((u32 *)pfsentry+2); + *((u32 *)pcache+3) = *((u32 *)pfsentry+3); + pfsentry += 16; + pcache += 16; + } while (pfsentry < pfseend); + + r = mcman_getdirinfo(port, slot, (McFsEntry *)&mcman_dircache[0], p, pcacheDir, unknown_flag); + + if (r > 0) { + if (mcman_chrpos(p, '/') >= 0) + return 2; + + pcacheDir->cluster = cluster; + pcacheDir->fsindex = fsindex; + + return 1; + } + + r = mcman_chrpos(p, '/'); + if ((r >= 0) && (p[r + 1] != 0)) { + p += mcman_chrpos(p, '/') + 1; + cluster = pcacheDir->cluster; + fsindex = pcacheDir->fsindex; + + McReadDirEntry(port, slot, cluster, fsindex, &fse); + } + else { + McReadDirEntry(port, slot, pcacheDir->cluster, pcacheDir->fsindex, pfse); + + return sceMcResSucceed; + } + } while (*p != 0); + } + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_getdirinfo(int port, int slot, McFsEntry *pfse, char *filename, McCacheDir *pcd, int unknown_flag) +{ + register int i, r, ret, len, pos; + McFsEntry *fse; + u8 *pfsentry, *pfsee, *pfseend; + + DPRINTF("mcman_getdirinfo port%d slot%d name %s\n", port, slot, filename); + + pos = mcman_chrpos(filename, '/'); + if (pos < 0) + pos = strlen(filename); + + ret = 0; + if ((pos == 2) && (!strncmp(filename, "..", 2))) { + + r = McReadDirEntry(port, slot, pfse->cluster, 0, &fse); + if (r != sceMcResSucceed) + return r; + + r = McReadDirEntry(port, slot, fse->cluster, 0, &fse); + if (r != sceMcResSucceed) + return r; + + if (pcd) { + pcd->cluster = fse->cluster; + pcd->fsindex = fse->dir_entry; + } + + r = McReadDirEntry(port, slot, fse->cluster, fse->dir_entry, &fse); + if (r != sceMcResSucceed) + return r; + + pfsentry = (u8 *)fse; + pfsee = (u8 *)pfse; + pfseend = (u8 *)(pfsentry + sizeof(McFsEntry)); + + do { + *((u32 *)pfsee ) = *((u32 *)pfsentry ); + *((u32 *)pfsee+1) = *((u32 *)pfsentry+1); + *((u32 *)pfsee+2) = *((u32 *)pfsentry+2); + *((u32 *)pfsee+3) = *((u32 *)pfsentry+3); + pfsentry += 16; + pfsee += 16; + } while (pfsentry < pfseend); + + if ((fse->mode & sceMcFileAttrHidden) != 0) { + ret = 1; + if (!PS1CardFlag) { + ret = 2; + if ((pcd == NULL) || (pcd->maxent < 0)) + return 3; + } + } + + if ((pcd == NULL) || (pcd->maxent < 0)) + return sceMcResSucceed; + } + else { + if ((pos == 1) && (!strncmp(filename, ".", 1))) { + + r = McReadDirEntry(port, slot, pfse->cluster, 0, &fse); + if (r != sceMcResSucceed) + return r; + + if (pcd) { + pcd->cluster = fse->cluster; + pcd->fsindex = fse->dir_entry; + } + + if ((fse->mode & sceMcFileAttrHidden) != 0) { + ret = 1; + if (!PS1CardFlag) { + ret = 2; + if ((pcd == NULL) || (pcd->maxent < 0)) + return 3; + } + else { + if ((pcd == NULL) || (pcd->maxent < 0)) + return sceMcResSucceed; + } + } + else { + ret = 1; + if ((pcd == NULL) || (pcd->maxent < 0)) + return sceMcResSucceed; + } + } + } + + if ((pcd) && (pcd->maxent >= 0)) + pcd->maxent = pfse->length; + + if (pfse->length > 0) { + + i = 0; + do { + r = McReadDirEntry(port, slot, pfse->cluster, i, &fse); + if (r != sceMcResSucceed) + return r; + + if (((fse->mode & sceMcFileAttrExists) == 0) && (pcd) && (i < pcd->maxent)) + pcd->maxent = i; + + if (unknown_flag) { + if ((fse->mode & sceMcFileAttrExists) == 0) + continue; + } + else { + if ((fse->mode & sceMcFileAttrExists) != 0) + continue; + } + + if (ret != 0) + continue; + + if ((pos >= 11) && (!strncmp(&filename[10], &fse->name[10], pos-10))) { + len = pos; + if (strlen(fse->name) >= pos) + len = strlen(fse->name); + + if (!strncmp(filename, fse->name, len)) + goto continue_check; + } + + if (strlen(fse->name) >= pos) + len = strlen(fse->name); + else + len = pos; + + if (strncmp(filename, fse->name, len)) + continue; + +continue_check: + ret = 1; + + if ((fse->mode & sceMcFileAttrHidden) != 0) { + if (!PS1CardFlag) + ret = 2; + } + + if (pcd == NULL) + break; + + pcd->fsindex = i; + pcd->cluster = pfse->cluster; + + if (pcd->maxent < 0) + break; + + } while (++i < pfse->length); + } + + if (ret == 2) + return 2; + + return ((ret < 1) ? 1 : 0); +} + +//-------------------------------------------------------------- +int mcman_writecluster(int port, int slot, int cluster, int flag) +{ + register int r, i, j, page, block, pageword_cnt; + register u32 erase_value; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + block = cluster / mcdi->clusters_per_block; + + if ((mcman_wr_port == port) && (mcman_wr_slot == slot) && (mcman_wr_block == block)) + return mcman_wr_flag3; + + mcman_wr_port = port; + mcman_wr_slot = slot; + mcman_wr_block = block; + mcman_wr_flag3 = -9; + + for (i = 0; i < 16; i++) { // check only 16 bad blocks ? + if (mcdi->bad_block_list[i] < 0) + break; + if (mcdi->bad_block_list[i] == block) { + mcman_wr_flag3 = 0; + return sceMcResSucceed; + } + } + + if (flag) { + for (i = 1; i < mcdi->blocksize; i++) + mcman_pagedata[i] = 0; + + mcman_pagedata[0] = mcman_pagebuf.byte; + + pageword_cnt = mcdi->pagesize >> 2; + page = block * mcdi->blocksize; + + if (mcdi->cardflags & CF_ERASE_ZEROES) + erase_value = 0xffffffff; + else + erase_value = 0x00000000; + + for (i = 0; i < pageword_cnt; i++) + mcman_pagebuf.word[i] = erase_value; + + r = mcman_eraseblock(port, slot, block, (void **)mcman_pagedata, (void *)mcman_eccdata); + if (r == sceMcResFailReplace) + return sceMcResSucceed; + if (r != sceMcResSucceed) + return sceMcResChangedCard; + + for (i = 1; i < mcdi->blocksize; i++) { + r = McWritePage(port, slot, page + i, &mcman_pagebuf, mcman_eccdata); + if (r == sceMcResFailReplace) + return sceMcResSucceed; + if (r != sceMcResSucceed) + return sceMcResNoFormat; + } + + for (i = 1; i < mcdi->blocksize; i++) { + r = McReadPage(port, slot, page + i, &mcman_pagebuf); + if (r == sceMcResNoFormat) + return sceMcResSucceed; + if (r != sceMcResSucceed) + return sceMcResFullDevice; + + for (j = 0; j < pageword_cnt; j++) { + if (mcman_pagebuf.word[j] != erase_value) { + mcman_wr_flag3 = 0; + return sceMcResSucceed; + } + } + } + + r = mcman_eraseblock(port, slot, block, NULL, NULL); + if (r != sceMcResSucceed) + return sceMcResChangedCard; + + r = McWritePage(port, slot, page, &mcman_pagebuf, mcman_eccdata); + if (r == sceMcResFailReplace) + return sceMcResSucceed; + if (r != sceMcResSucceed) + return sceMcResNoFormat; + + r = McReadPage(port, slot, page, &mcman_pagebuf); + if (r == sceMcResNoFormat) + return sceMcResSucceed; + if (r != sceMcResSucceed) + return sceMcResFullDevice; + + for (j = 0; j < pageword_cnt; j++) { + if (mcman_pagebuf.word[j] != erase_value) { + mcman_wr_flag3 = 0; + return sceMcResSucceed; + } + } + + r = mcman_eraseblock(port, slot, block, NULL, NULL); + if (r == sceMcResFailReplace) + return sceMcResSucceed; + if (r != sceMcResSucceed) + return sceMcResFullDevice; + + erase_value = ~erase_value; + + for (i = 0; i < mcdi->blocksize; i++) { + r = McReadPage(port, slot, page + i, &mcman_pagebuf); + if (r != sceMcResSucceed) + return sceMcResDeniedPermit; + + for (j = 0; j < pageword_cnt; j++) { + if (mcman_pagebuf.word[j] != erase_value) { + mcman_wr_flag3 = 0; + return sceMcResSucceed; + } + } + } + } + mcman_wr_flag3 = 1; + + return mcman_wr_flag3; +} + +//-------------------------------------------------------------- +int McSetDirEntryState(int port, int slot, int cluster, int fsindex, int flags) +{ + register int r, i, fat_index; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McFsEntry *fse; + int fat_entry; + + r = McReadDirEntry(port, slot, cluster, fsindex, &fse); + if (r != sceMcResSucceed) + return r; + + if (fse->name[0] == '.') { + if ((fse->name[1] == 0) || (fse->name[1] == '.')) + return sceMcResNoEntry; + } + + i = 0; + do { + if (mcman_fdhandles[i].status == 0) + continue; + + if ((mcman_fdhandles[i].port != port) || (mcman_fdhandles[i].slot != slot)) + continue; + + if (mcman_fdhandles[i].field_20 != cluster) + continue; + + if (mcman_fdhandles[i].field_24 == fsindex) + return sceMcResDeniedPermit; + + } while (++i < MAX_FDHANDLES); + + if (flags == 0) + fse->mode = fse->mode & (sceMcFileAttrExists - 1); + else + fse->mode = fse->mode | sceMcFileAttrExists; + + Mc1stCacheEntSetWrFlagOff(); + + fat_index = fse->cluster; + + if (fat_index >= 0) { + if (fat_index < mcdi->unknown2) + mcdi->unknown2 = fat_index; + mcdi->unknown5 = -1; + + do { + r = McGetFATentry(port, slot, fat_index, &fat_entry); + if (r != sceMcResSucceed) + return r; + + if (flags == 0) { + fat_entry &= 0x7fffffff; + if (fat_index < mcdi->unknown2) + mcdi->unknown2 = fat_entry; + } + else + fat_entry |= 0x80000000; + + r = McSetFATentry(port, slot, fat_index, fat_entry); + if (r != sceMcResSucceed) + return r; + + fat_index = fat_entry & 0x7fffffff; + + } while (fat_index != 0x7fffffff); + } + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_checkBackupBlocks(int port, int slot) +{ + register int r1, r2, r, eccsize; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McCacheEntry *mce; + u32 *pagebuf = mcman_pagebuf.word; + u32 value1, value2; + + // First check backup block2 to see if it's in erased state + r1 = McReadPage(port, slot, mcdi->backup_block2 * mcdi->blocksize, &mcman_pagebuf); //s1 + + value1 = *pagebuf; //s3 + if (((mcdi->cardflags & CF_ERASE_ZEROES) != 0) && (value1 == 0)) + value1 = 0xffffffff; + if (value1 != 0xffffffff) + value1 = value1 & 0x7fffffff; + + r2 = McReadPage(port, slot, (mcdi->backup_block2 * mcdi->blocksize) + 1, &mcman_pagebuf); //a0 + + value2 = *pagebuf; //s0 + if (((mcdi->cardflags & CF_ERASE_ZEROES) != 0) && (value2 == 0)) + value2 = 0xffffffff; + if (value2 != 0xffffffff) + value2 = value2 & 0x7fffffff; + + if ((value1 != 0xffffffff) && (value2 == 0xffffffff)) + goto check_done; + if ((r1 < 0) || (r2 < 0)) + goto check_done; + + if ((value1 == 0xffffffff) && (value1 == value2)) + return sceMcResSucceed; + + // bachup block2 is not erased, so programming is assumed to have not been completed + // reads content of backup block1 + for (r1 = 0; r1 < mcdi->clusters_per_block; r1++) { + + McReadCluster(port, slot, (mcdi->backup_block1 * mcdi->clusters_per_block) + r1, &mce); + mce->rd_flag = 1; + + for (r2 = 0; r2 < mcdi->pages_per_cluster; r2++) { + mcman_pagedata[(r1 * ((mcdi->pages_per_cluster << 16) >> 16)) + r2] = \ + (void *)(mce->cl_data + (r2 * mcdi->pagesize)); + } + } + + // Erase the block where data must be written + r = mcman_eraseblock(port, slot, value1, (void **)mcman_pagedata, (void *)mcman_eccdata); + if (r != sceMcResSucceed) + return r; + + // Write the block + for (r1 = 0; r1 < mcdi->blocksize; r1++) { + + eccsize = mcdi->pagesize; + if (eccsize < 0) + eccsize += 0x1f; + eccsize = eccsize >> 5; + + r = McWritePage(port, slot, (value1 * ((mcdi->blocksize << 16) >> 16)) + r1, \ + mcman_pagedata[r1], (void *)(mcman_eccdata + (eccsize * r1))); + + if (r != sceMcResSucceed) + return r; + } + + for (r1 = 0; r1 < mcdi->clusters_per_block; r1++) + mcman_freecluster(port, slot, (mcdi->backup_block1 * mcdi->clusters_per_block) + r1); + +check_done: + // Finally erase backup block2 + return mcman_eraseblock(port, slot, mcdi->backup_block2, NULL, NULL); +} + +//-------------------------------------------------------------- +int McCheckBlock(int port, int slot, int block) +{ + register int r, i, j, page, ecc_count, pageword_cnt, flag, erase_value; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + u8 *p_page, *p_ecc; + + DPRINTF("McCheckBlock port%d slot%d block 0x%x\n", port, slot, block); + + // sp50 = block; + page = block * mcdi->blocksize; //sp18 + pageword_cnt = mcdi->pagesize >> 2; //s6 + + ecc_count = mcdi->pagesize; + if (mcdi->pagesize < 0) + ecc_count += 127; + ecc_count = ecc_count >> 7; // s7 + + flag = 0; // s4 + + if (mcdi->cardform > 0) { + for (i = 0; i < 16; i++) { + if (mcdi->bad_block_list[i] <= 0) + break; + if (mcdi->bad_block_list[i] == block) + goto lbl_8764; + } + } + + flag = 16; // s4 + + for (i = 0; i < mcdi->blocksize; i++) { + r = mcman_readpage(port, slot, page + i, &mcman_pagebuf, mcman_eccdata); + if (r != sceMcResSucceed) + return -45; + + if ((mcdi->cardflags & CF_USE_ECC) != 0) { + if (mcman_eccdata[mcman_sparesize(port, slot) - 1] != 0xff) { + p_page = mcman_pagebuf.byte; //s1 + p_ecc = (void *)mcman_eccdata; //s2 + + for (j = 0; j < ecc_count; j++) { + r = mcman_correctdata(p_page, p_ecc); + if (r != sceMcResSucceed) { + flag = -1; + goto lbl_8764; + } + p_ecc += 3; + p_page += 128; + } + } + } + } + + for (j = 0; j < pageword_cnt; j++) + mcman_pagebuf.word[j] = 0x5a5aa5a5; + + for (j = 0; j < 128; j++) + *((u32 *)&mcman_eccdata + j) = 0x5a5aa5a5; + + r = mcman_eraseblock(port, slot, block, NULL, NULL); + if (r != sceMcResSucceed) { + r = mcman_probePS2Card2(port, slot); + if (r != sceMcResSucceed) + return -45; + flag = -1; + goto lbl_8764; + } + + for (i = 0; i < mcdi->blocksize; i++) { + r = McWritePage(port, slot, page + i, &mcman_pagebuf, mcman_eccdata); + if (r != sceMcResSucceed) { + r = mcman_probePS2Card2(port, slot); + if (r != sceMcResSucceed) + return -44; + flag = -1; + goto lbl_8764; + } + } + + for (i = 0; i < mcdi->blocksize; i++) { + r = mcman_readpage(port, slot, page + i, &mcman_pagebuf, mcman_eccdata); + if (r != sceMcResSucceed) + return -45; + + for (j = 0; j < pageword_cnt; j++) { + if (mcman_pagebuf.word[j] != 0x5a5aa5a5) { + flag = -1; + goto lbl_8764; + } + } + + for (j = 0; j < 128; j++) { + if (*((u32 *)&mcman_eccdata + j) != 0x5a5aa5a5) { + flag = -1; + goto lbl_8764; + } + } + } + + for (j = 0; j < pageword_cnt; j++) + mcman_pagebuf.word[j] = 0x05a55a5a; + + for (j = 0; j < 128; j++) + *((u32 *)&mcman_eccdata + j) = 0x05a55a5a; + + r = mcman_eraseblock(port, slot, block, NULL, NULL); + if (r != sceMcResSucceed) { + r = mcman_probePS2Card2(port, slot); + if (r != sceMcResSucceed) + return -42; + flag = -1; + goto lbl_8764; + } + + for (i = 0; i < mcdi->blocksize; i++) { + r = McWritePage(port, slot, page + i, &mcman_pagebuf, mcman_eccdata); + if (r != sceMcResSucceed) { + r = mcman_probePS2Card2(port, slot); + if (r != sceMcResSucceed) + return -46; + flag = -1; + goto lbl_8764; + } + } + + for (i = 0; i < mcdi->blocksize; i++) { + r = mcman_readpage(port, slot, page + i, &mcman_pagebuf, mcman_eccdata); + if (r != sceMcResSucceed) + return -45; + + for (j = 0; j < pageword_cnt; j++) { + if (mcman_pagebuf.word[j] != 0x05a55a5a) { + flag = -1; + goto lbl_8764; + } + } + + for (j = 0; j < 128; j++) { + if (*((u32 *)&mcman_eccdata + j) != 0x05a55a5a) { + flag = -1; + goto lbl_8764; + } + } + } + +lbl_8764: + if (flag == 16) { + mcman_eraseblock(port, slot, block, NULL, NULL); + return sceMcResSucceed; + } + + erase_value = 0x00000000; + if ((mcdi->cardflags & CF_ERASE_ZEROES) != 0) + erase_value = 0xffffffff; + + for (j = 0; j < pageword_cnt; j++) + mcman_pagebuf.word[j] = erase_value; + + for (j = 0; j < 128; j++) + *((u32 *)&mcman_eccdata + j) = erase_value; + + for (i = 0; i < mcdi->blocksize; i++) { + r = McWritePage(port, slot, page + i, &mcman_pagebuf, mcman_eccdata); + if (r != sceMcResSucceed) { + r = mcman_probePS2Card2(port, slot); + if (r != sceMcResSucceed) + return -48; + } + } + + return 1; +} + +//-------------------------------------------------------------- +int mcman_setPS1devinfos(int port, int slot) +{ + register int r, i; + MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + DPRINTF("mcman_setPS1devinfos port%d slot%d\n", port, slot); + + memset((void *)mcdi, 0, sizeof (MCDevInfo)); + memset((void *)&mcdi->bad_block_list[0], -1, 128); + + mcdi->pagesize = 128; + mcdi->blocksize = 128; + mcdi->pages_per_cluster = 64; + mcdi->unused = 0xff00; + mcdi->cluster_size = 8192; + mcdi->FATentries_per_cluster = 2048; + mcdi->clusters_per_card = 16; + mcdi->clusters_per_block = 0; + mcdi->cardform = 0; + mcdi->cardtype = 1; + + r = McReadPS1PDACard(port, slot, 0, &mcman_PS1PDApagebuf); + if (r < 0) + return -14; + +#ifndef BUILDING_XFROMMAN + if (mcman_sio2outbufs_PS1PDA[1] != 0) + return -15; +#endif + + if (mcman_PS1PDApagebuf.byte[0] != 0x4d) + return sceMcResNoFormat; + + if (mcman_PS1PDApagebuf.byte[1] != 0x43) + return sceMcResNoFormat; + + for (i = 0; i < 20; i++) { + r = McReadPS1PDACard(port, slot, i + 16, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return -43; + + if (mcman_PS1PDApagebuf.byte[127] == (mcman_calcEDC(&mcman_PS1PDApagebuf, 127) & 0xff)) { + mcdi->bad_block_list[i] = mcman_PS1PDApagebuf.word[0]; + } + } + + r = mcman_cachePS1dirs(port, slot); + + if (r != sceMcResSucceed) + return r; + + mcdi->cardform = 1; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_getPS1direntry(int port, int slot, char *filename, McFsEntryPS1 **pfse, int flag) +{ + register int r, i; + char *p = filename; + + DPRINTF("mcman_getPS1direntry port%d slot%d file %s flag %x\n", port, slot, filename, flag); + + if (*p == '/') + p++; + + i = 0; + do { + r = mcman_readdirentryPS1(port, slot, i, pfse); + if (r != sceMcResSucceed) + return r; + + if (flag != 0) { + if (pfse[0]->mode != 0x51) + continue; + } + else { + if (pfse[0]->mode != 0xa1) + continue; + } + + if (!strcmp(p, pfse[0]->name)) + return i; + + } while (++i < 15); + + return sceMcResNoEntry; +} + +//-------------------------------------------------------------- +int mcman_clearPS1direntry(int port, int slot, int cluster, int flags) +{ + register int r, i, temp; + McFsEntryPS1 *fse; + MC_FHANDLE *fh; + McCacheEntry *mce; + + DPRINTF("mcman_clearPS1direntry port%d slot%d cluster %x flags %x\n", port, slot, cluster, flags); + + r = mcman_readdirentryPS1(port, slot, cluster, &fse); + if (r != sceMcResSucceed) + return r; + + fh = (MC_FHANDLE *)&mcman_fdhandles[0]; + + for (i = 0; i < MAX_FDHANDLES; i++) { + if ((fh->status != 0) && (fh->port == port) && (fh->slot == slot)) { + if (fh->freeclink == cluster) + return sceMcResDeniedPermit; + + } + fh++; + } + + if (!flags) { + if (fse->mode != 0x51) + return sceMcResNoEntry; + } + else { + if (fse->mode != 0xa1) + return sceMcResNoEntry; + } + + do { +lbl0: + mce = mcman_get1stcacheEntp(); + + if (cluster + 1 < 0) + temp = cluster + 8; + else + temp = cluster + 1; + + mce->wr_flag |= 1 << ((cluster + 1) - ((temp >> 3) << 3)); + + if (flags == 0) + temp = (fse->mode & 0xf) | 0xa0; + else + temp = (fse->mode & 0xf) | 0x50; + + fse->mode = temp; + fse->edc = mcman_calcEDC((void *)fse, 127); + + if (fse->linked_block < 0) { + //cluster = 0; + goto lbl1; + } + + cluster = fse->linked_block; + + r = mcman_readdirentryPS1(port, slot, cluster, &fse); + if (r != sceMcResSucceed) + return r; + + if (flags == 0) { + if ((fse->mode & 0xf0) != 0x50) + break; + goto lbl0; + } + + } while ((fse->mode & 0xf0) == 0xa0); + + r = McFlushCache(port, slot); + if (r != sceMcResSucceed) + return r; + + return sceMcResNoEntry; + +lbl1: + r = McFlushCache(port, slot); + if (r != sceMcResSucceed) + return r; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_findfree1(int port, int slot, int reserve) +{ + register int r, i, free; + McFsEntryPS1 *fse; + + DPRINTF("mcman_findfree1 port%d slot%d reserve %d\n", port, slot, reserve); + + free = 0; + i = 0; + + do { + r = mcman_readdirentryPS1(port, slot, i, &fse); + if (r != sceMcResSucceed) + return -37; + + if ((fse->mode & 0xf0) == 0xa0) { + if (reserve) + return i; + free++; + } + } while (++i < 15); + + if (reserve) + return sceMcResFullDevice; + + if (free) + return free; + + return sceMcResFullDevice; +} + +//-------------------------------------------------------------- +int mcman_fatRseekPS1(int fd) +{ + register int r, rpos, numclust, clust; + MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + MCDevInfo *mcdi = &mcman_devinfos[fh->port][fh->slot]; + McFsEntryPS1 *fse; + + numclust = fh->position / mcdi->cluster_size; + numclust--; + clust = fh->freeclink; + + if (numclust > -1) { + do { + if (clust < 0) + return sceMcResFullDevice; + + r = mcman_readdirentryPS1(fh->port, fh->slot, clust, &fse); + if (r != sceMcResSucceed) + return r; + clust = fse->linked_block; + + } while (--numclust > -1); + } + + if (clust < 0) + return sceMcResFullDevice; + + rpos = fh->position % mcdi->cluster_size; + + if (rpos < 0) + rpos += 1023; + + return ((clust + 1) << 6) + ((rpos >> 10) * (1024 / mcdi->pagesize)); +} + +//-------------------------------------------------------------- +int mcman_fatWseekPS1(int fd) +{ + register int r, numclust, clust; + MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + MCDevInfo *mcdi = &mcman_devinfos[fh->port][fh->slot]; + McFsEntryPS1 *fse; + + numclust = fh->position / mcdi->cluster_size; + + if (numclust > 0) { + clust = fh->freeclink; + do { + r = mcman_readdirentryPS1(fh->port, fh->slot, clust, &fse); + if (r != sceMcResSucceed) + return r; + + clust = fse->linked_block; + + if (clust < 0) { + r = mcman_FNC8ca4(fh->port, fh->slot, (MC_FHANDLE *)fh); + if (r < 0) + return r; + clust = r; + } + } while (--numclust); + } + r = McFlushCache(fh->port, fh->slot); + + return r; +} + +//-------------------------------------------------------------- +int mcman_FNC8ca4(int port, int slot, MC_FHANDLE *fh) +{ + register int r, i, j, mcfree, cluster_size, pages_per_FATclust; + register int temp; + MCDevInfo *mcdi = &mcman_devinfos[fh->port][fh->slot]; + McFsEntryPS1 *fse1, *fse2, *fse3; + McCacheEntry *mce; + u8 *pfsentry, *pfsee, *pfseend; + + DPRINTF("mcman_FNC8ca4 port%d slot%d\n", port, slot); + + if (mcdi->cluster_size < 0) + cluster_size = mcdi->cluster_size + 1023; + else + cluster_size = mcdi->cluster_size; + + cluster_size = cluster_size >> 10; + + pages_per_FATclust = 1024 / mcdi->pagesize; + + r = mcman_findfree1(port, slot, 1); + if (r < 0) + return r; + + i = fh->freeclink; + mcfree = r; + j = -1; + + if (i >= 0) { + do { + if (mcfree < i) { + if (cluster_size > 0) { + i = 0; + + do { + mcman_freecluster(port, slot, ((mcfree * cluster_size) + i) * pages_per_FATclust); + + r = mcman_readclusterPS1(port, slot, ((i * cluster_size) + i) * pages_per_FATclust, &mce); + if (r != sceMcResSucceed) + return r; + + mce->wr_flag = -1; + mce->cluster -= (i - mcfree) * cluster_size; + + } while (++i < cluster_size); + } + + r = mcman_readdirentryPS1(port, slot, i, &fse1); + if (r != sceMcResSucceed) + return r; + + r = mcman_readdirentryPS1(port, slot, mcfree, &fse2); + if (r != sceMcResSucceed) + return r; + + mce = mcman_get1stcacheEntp(); + + if (mcfree + 1 < 0) + temp = mcfree + 8; + else + temp = mcfree + 1; + + mce->wr_flag |= 1 << ((mcfree + 1) - ((temp >> 3) << 3)); + + pfsentry = (u8 *)fse1; + pfsee = (u8 *)fse2; + pfseend = (u8 *)(pfsentry + sizeof(McFsEntryPS1)); + + do { + *((u32 *)pfsee ) = *((u32 *)pfsentry ); + *((u32 *)pfsee+1) = *((u32 *)pfsentry+1); + *((u32 *)pfsee+2) = *((u32 *)pfsentry+2); + *((u32 *)pfsee+3) = *((u32 *)pfsentry+3); + pfsentry += 16; + pfsee += 16; + } while (pfsentry < pfseend); + + if (j >= 0) { + r = mcman_readdirentryPS1(port, slot, j, &fse3); + if (r != sceMcResSucceed) + return r; + + mce = mcman_get1stcacheEntp(); + + if ((j + 1) < 0) + temp = j + 8; + else + temp = j + 1; + + mce->wr_flag |= 1 << ((j + 1) - ((temp >> 3) << 3)); + fse3->linked_block = mcfree; + fse3->edc = mcman_calcEDC((void *)fse3, 127); + } + else { + fh->freeclink = mcfree; + } + j = mcfree; + mcfree = i; + + } + else { + j = i; + r = mcman_readdirentryPS1(port, slot, j, &fse1); + if (r != sceMcResSucceed) + return r; + } + i = fse1->linked_block; + } while (i >= 0); + } + + r = mcman_readdirentryPS1(port, slot, mcfree, &fse2); + if (r != sceMcResSucceed) + return r; + + mce = mcman_get1stcacheEntp(); + + if (mcfree + 1 < 0) + temp = mcfree + 8; + else + temp = mcfree + 1; + + mce->wr_flag |= 1 << ((mcfree + 1) - ((temp >> 3) << 3)); + + mcman_wmemset((void *)fse2, sizeof(McFsEntryPS1), 0); + + fse2->mode = 0x53; + fse2->linked_block = -1; + fse2->edc = mcman_calcEDC((void *)fse2, 127); + + r = mcman_readdirentryPS1(port, slot, j, &fse3); + if (r != sceMcResSucceed) + return r; + + mce = mcman_get1stcacheEntp(); + + if ((j + 1) < 0) + temp = j + 8; + else + temp = j + 1; + + mce->wr_flag |= 1 << ((j + 1) - ((temp >> 3) << 3)); + + if (fse3->mode == 0x53) + fse3->mode = 0x52; + + fse3->linked_block = mcfree; + fse3->edc = mcman_calcEDC((void *)fse3, 127); + + return mcfree; +} + +//-------------------------------------------------------------- +int mcman_PS1pagetest(int port, int slot, int page) +{ + register int r, i; + + for (i = 0; i < 32; i++) + mcman_PS1PDApagebuf.word[i] = 0xffffffff; + + r = McWritePS1PDACard(port, slot, page, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return sceMcResDeniedPermit; + + r = McReadPS1PDACard(port, slot, page, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return sceMcResNotEmpty; + + for (i = 0; i < 32; i++) { + if (mcman_PS1PDApagebuf.word[i] != 0xffffffff) { + return 0; + } + } + + for (i = 0; i < 32; i++) + mcman_PS1PDApagebuf.word[i] = 0; + + r = McWritePS1PDACard(port, slot, page, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return sceMcResDeniedPermit; + + r = McReadPS1PDACard(port, slot, page, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return sceMcResNotEmpty; + + for (i = 0; i < 32; i++) { + if (mcman_PS1PDApagebuf.word[i] != 0) { + return 0; + } + } + + return 1; +} + +//-------------------------------------------------------------- +int mcman_cachePS1dirs(int port, int slot) +{ + register int r, i, j, temp1, temp2, index, linked_block; + McFsEntryPS1 *fs_t[15]; + McCacheEntry *mce[2]; + int cluster_t[15]; + + DPRINTF("mcman_cachePS1dirs port%d slot%d\n", port, slot); + + i = 0; + do { + r = mcman_readdirentryPS1(port, slot, i, &fs_t[i]); + if (r != sceMcResSucceed) + return r; + + fs_t[i]->field_38 = fs_t[i]->length; /// <-- Special fix for saves from a real PS1 + + if (i == 0) { + mce[0] = mcman_get1stcacheEntp(); + } + else { + if (i == 7) + mce[1] = mcman_get1stcacheEntp(); + } + } while (++i < 15); + + memset((void *)cluster_t, -1, sizeof(cluster_t)); + + i = 0; + do { + temp1 = fs_t[i]->mode & 0xf0; + + if ((fs_t[i]->mode & 0xf) != 1) + continue; + + cluster_t[i] = i; + + linked_block = fs_t[i]->linked_block; + if (linked_block >= 0) { + do { + if ((fs_t[linked_block]->mode & 0xf0) != temp1) + temp1 = 0; + + if (fs_t[linked_block]->mode == 0xa0) + break; + + if (cluster_t[linked_block] != -1) + break; + + cluster_t[linked_block] = i; + linked_block = fs_t[linked_block]->linked_block; + + } while (linked_block >= 0); + + if ((linked_block < 0) && (temp1 != 0)) + continue; + } + else { + if (temp1 != 0) + continue; + } + + j = 0; + do { + if (cluster_t[j] != i) + continue; + + memset((void *)fs_t[j], 0, sizeof (McFsEntryPS1)); + + fs_t[j]->mode = 0xa0; + fs_t[j]->linked_block = -1; + fs_t[j]->edc = mcman_calcEDC((void *)fs_t[j], 127); + + temp2 = j + 1; + + if (j < 7) + index = 0; + else + index = 1; + + if (temp2 < 0) + temp1 = j + 8; + else + temp1 = temp2; + + mce[index]->wr_flag |= (1 << (temp2 - ((temp1 >> 3) << 3))); + + } while (++j < 15); + + } while (++i < 15); + + i = 0; + do { + if ((cluster_t[i] != -1) || (fs_t[i]->mode == 0xa0)) + continue; + + memset((void *)fs_t[i], 0, sizeof (McFsEntryPS1)); + + fs_t[i]->mode = 0xa0; + fs_t[i]->linked_block = cluster_t[i]; + fs_t[i]->edc = mcman_calcEDC((void *)fs_t[i], 127); + + temp2 = i + 1; + + if (i < 7) + index = 0; + else + index = 1; + + if (temp2 < 0) + temp1 = i + 8; + else + temp1 = temp2; + + mce[index]->wr_flag |= (1 << (temp2 - ((temp1 >> 3) << 3))); + + } while (++i < 15); + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_fillPS1backuparea(int port, int slot, int block) +{ + register int r, i, curpage; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + memset(&mcman_PS1PDApagebuf, 0, 128); + + curpage = 16; + i = 0; + do { + if (mcdi->bad_block_list[i] == block) { + mcdi->bad_block_list[i] = block | 0x01000000; + mcman_PS1PDApagebuf.word[0] = block | 0x01000000; + mcman_PS1PDApagebuf.byte[127] = mcman_calcEDC(&mcman_PS1PDApagebuf, 127); + r = McWritePS1PDACard(port, slot, curpage, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return -43; + } + else { + if (mcdi->bad_block_list[i] < 0) { + mcman_PS1PDApagebuf.word[0] = block; + mcman_PS1PDApagebuf.byte[127] = mcman_calcEDC(&mcman_PS1PDApagebuf, 127); + r = McWritePS1PDACard(port, slot, curpage, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return -43; + mcdi->bad_block_list[i] = block; + break; + } + } + curpage++; + } while (++i < 20); + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +void mcman_initcache(void) +{ + register int i, j; + u8 *p; + + DPRINTF("mcman_initcache\n"); + + j = MAX_CACHEENTRY - 1; + p = (u8 *)mcman_cachebuf; + + for (i = 0; i < MAX_CACHEENTRY; i++) { + mcman_entrycache[i].cl_data = (u8 *)p; + mcman_mccache[i] = (McCacheEntry *)&mcman_entrycache[j - i]; + mcman_entrycache[i].cluster = -1; + p += MCMAN_CLUSTERSIZE; + } + + pmcman_entrycache = (McCacheEntry *)mcman_entrycache; + pmcman_mccache = (McCacheEntry **)mcman_mccache; + + for (i = 0; i < MCMAN_MAXSLOT; i++) { + mcman_devinfos[0][i].unknown3 = -1; + mcman_devinfos[0][i].unknown4 = -1; + mcman_devinfos[0][i].unknown5 = -1; + mcman_devinfos[1][i].unknown3 = -1; + mcman_devinfos[1][i].unknown4 = -1; + mcman_devinfos[1][i].unknown5 = -1; + } + + memset((void *)mcman_fatcache, -1, sizeof (mcman_fatcache)); + + for (i = 0; i < MCMAN_MAXSLOT; i++) { + mcman_fatcache[0][i].entry[0] = 0; + mcman_fatcache[1][i].entry[0] = 0; + } +} + +//-------------------------------------------------------------- +int McRetOnly(int fd) // Export #37 +{ + DPRINTF("McRetOnly param %x\n", fd); + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_clearcache(int port, int slot) +{ + register int i, j; + McCacheEntry **pmce = (McCacheEntry **)pmcman_mccache; + McCacheEntry *mce, *mce_save; + + DPRINTF("mcman_clearcache port%d, slot%d\n", port, slot); + + for (i = MAX_CACHEENTRY - 1; i >= 0; i--) { + mce = (McCacheEntry *)pmce[i]; + if ((mce->mc_port == port) && (mce->mc_slot == slot) && (mce->cluster >= 0)) { + mce->mc_port = -1; + mce->mc_slot = -1; + mce->wr_flag = 0; + mce->cluster = -1; + } + } + + for (i = 0; i < (MAX_CACHEENTRY - 1); i++) { + mce = (McCacheEntry *)pmce[i]; + mce_save = (McCacheEntry *)pmce[i]; + if (mce->cluster < 0) { + for (j = i+1; j < MAX_CACHEENTRY; j++) { + mce = (McCacheEntry *)pmce[j]; + if (mce->cluster >= 0) + break; + } + if (j == MAX_CACHEENTRY) + break; + + pmce[i] = (McCacheEntry *)pmce[j]; + pmce[j] = (McCacheEntry *)mce_save; + } + } + + memset((void *)&mcman_fatcache[port][slot], -1, sizeof (McFatCache)); + + mcman_fatcache[port][slot].entry[0] = 0; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +McCacheEntry *mcman_getcacheentry(int port, int slot, int cluster) +{ + register int i; + McCacheEntry *mce = (McCacheEntry *)pmcman_entrycache; + + //DPRINTF("mcman_getcacheentry port%d slot%d cluster %x\n", port, slot, cluster); + + for (i = 0; i < MAX_CACHEENTRY; i++) { + if ((mce->mc_port == port) && (mce->mc_slot == slot) && (mce->cluster == cluster)) + return mce; + mce++; + } + + return NULL; +} + +//-------------------------------------------------------------- +void mcman_freecluster(int port, int slot, int cluster) // release cluster from entrycache +{ + register int i; + McCacheEntry *mce = (McCacheEntry *)pmcman_entrycache; + + for (i = 0; i < MAX_CACHEENTRY; i++) { + if ((mce->mc_port == port) && (mce->mc_slot == slot) && (mce->cluster == cluster)) { + mce->cluster = -1; + mce->wr_flag = 0; + } + mce++; + } +} + +//-------------------------------------------------------------- +int mcman_getFATindex(int port, int slot, int num) +{ + return mcman_fatcache[port][slot].entry[num]; +} + +//-------------------------------------------------------------- +void Mc1stCacheEntSetWrFlagOff(void) +{ + McCacheEntry *mce = (McCacheEntry *)*pmcman_mccache; + + mce->wr_flag = -1; +} + +//-------------------------------------------------------------- +McCacheEntry *mcman_get1stcacheEntp(void) +{ + return *pmcman_mccache; +} + +//-------------------------------------------------------------- +void mcman_addcacheentry(McCacheEntry *mce) +{ + register int i; + McCacheEntry **pmce = (McCacheEntry **)pmcman_mccache; + + i = MAX_CACHEENTRY - 1; + + if (i < 0) + goto lbl1; + + do { + if (pmce[i] == mce) + break; + } while (--i >= 0); + + if (i != 0) { +lbl1: + do { + pmce[i] = pmce[i-1]; + } while (--i != 0); + } + + pmce[0] = (McCacheEntry *)mce; +} + +//-------------------------------------------------------------- +int McFlushCache(int port, int slot) +{ + register int i, r; + McCacheEntry **pmce = (McCacheEntry **)pmcman_mccache; + McCacheEntry *mce; + + DPRINTF("McFlushCache port%d slot%d\n", port, slot); + + i = MAX_CACHEENTRY - 1; + + if (i >= 0) { + do { + mce = (McCacheEntry *)pmce[i]; + if ((mce->mc_port == port) && (mce->mc_slot == slot) && (mce->wr_flag != 0)) { + r = mcman_flushcacheentry((McCacheEntry *)mce); + if (r != sceMcResSucceed) + return r; + } + i--; + } while (i >= 0); + } + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_flushcacheentry(McCacheEntry *mce) +{ + register int r, i, j, ecc_count; + register int temp1, temp2, offset, pageindex; + static int clusters_per_block, blocksize, cardtype, pagesize, sparesize, flag, cluster, block, pages_per_fatclust; + McCacheEntry *pmce[16]; // sp18 + register MCDevInfo *mcdi; + McCacheEntry *mcee; + static u8 eccbuf[32]; + void *p_page, *p_ecc; + + DPRINTF("mcman_flushcacheentry mce %x cluster %x\n", (int)mce, (int)mce->cluster); + + if (mce->wr_flag == 0) + return sceMcResSucceed; + + mcdi = (MCDevInfo *)&mcman_devinfos[mce->mc_port][mce->mc_slot]; + + //mcdi->pagesize = sp84 + pagesize = mcdi->pagesize; //sp84 + cardtype = mcdi->cardtype; + + if (cardtype == 0) { + mce->wr_flag = 0; + return sceMcResSucceed; + } + + if ((cardtype == sceMcTypePS1) || (cardtype == sceMcTypePDA)) { + pages_per_fatclust = MCMAN_CLUSTERSIZE / pagesize; + i = mce->cluster; //s0 + j = 0; //s1 + r = 0; + + if (pages_per_fatclust > 0) { +lbl0: + + do { + if (((mce->wr_flag >> j) & 1) != 0) { + //DPRINTF("flushing ent %x cl_data %x to page %d offset %d\n", mce, mce->cl_data, i, (pagesize * j)); + r = McWritePS1PDACard(mce->mc_port, mce->mc_slot, i, (void *)(mce->cl_data + (pagesize * j))); + if (r == sceMcResFailReplace) + break; + if (r != sceMcResSucceed) + return -50; + + } + i++; + } while (++j < pages_per_fatclust); + } + + if (j == pages_per_fatclust) { + r = mcman_probePS1Card2(mce->mc_port, mce->mc_slot); + if (r == -14) + r = sceMcResFailReplace; + } + if (cardtype != sceMcTypePS1) { + if (r == sceMcResFailReplace) + return r; + + mce->wr_flag = 0; + return sceMcResSucceed; + } + if (r != 8) { + mce->wr_flag = 0; + return sceMcResSucceed; + } + + if ((mce->wr_flag & ~(-1 << j)) == 0) { + mce->wr_flag = 0; + return sceMcResSucceed; + } + + if (j-- == 0) { + mce->wr_flag = 0; + return sceMcResSucceed; + } + + i--; + + do { + if (((mce->wr_flag >> j) & 1) != 0) { + r = mcman_fillPS1backuparea(mce->mc_port, mce->mc_slot, i); + if (r != sceMcResSucceed) + return sceMcResFailReplace; + + goto lbl0; + } + } while (j++); + + mce->wr_flag = 0; + return sceMcResSucceed; + } + + clusters_per_block = mcdi->clusters_per_block; //sp7c + block = mce->cluster / mcdi->clusters_per_block; //sp78 + blocksize = mcdi->blocksize; //sp80 + sparesize = mcman_sparesize(mce->mc_port, mce->mc_slot); //sp84 + flag = 0; //sp88 + + memset((void *)pmce, 0, 64); + + i = 0; //s1 + if (MAX_CACHEENTRY > 0) { + mcee = (McCacheEntry *)pmcman_entrycache; + do { + if ((mcee->mc_slot == mce->mc_slot) && (mcee->mc_port == mce->mc_port)) { + temp1 = mcee->cluster / clusters_per_block; + temp2 = mcee->cluster % clusters_per_block; + + if (temp1 == block) { + pmce[temp2] = (McCacheEntry *)mcee; + if (mcee->rd_flag == 0) + flag = 1; + } + } + mcee++; + } while (++i < MAX_CACHEENTRY); + } + + if (clusters_per_block > 0) { + i = 0; //s1 + pageindex = 0; //s5 + cluster = block * clusters_per_block; // sp8c + + do { + if (pmce[i] != 0) { + j = 0; // s0 + offset = 0; //a0 + for (j = 0; j < mcdi->pages_per_cluster; j++) { + mcman_pagedata[pageindex + j] = (void *)(pmce[i]->cl_data + offset); + offset += pagesize; + } + } + else { + //s3 = s5 + // s2 = (cluster + i) * mcdi->pages_per_cluster + j = 0; //s0 + do { + offset = (pageindex + j) * pagesize; // t0 + mcman_pagedata[pageindex + j] = (void *)(mcman_backupbuf + offset); + + r = McReadPage(mce->mc_port, mce->mc_slot, \ + ((cluster + i) * mcdi->pages_per_cluster) + j, \ + mcman_backupbuf + offset); + if (r != sceMcResSucceed) + return -51; + + } while (++j < mcdi->pages_per_cluster); + } + + pageindex += mcdi->pages_per_cluster; + } while (++i < clusters_per_block); + } + +lbl1: + if ((flag != 0) && (mcman_badblock <= 0)) { + r = mcman_eraseblock(mce->mc_port, mce->mc_slot, mcdi->backup_block1, (void**)mcman_pagedata, mcman_eccdata); + if (r == sceMcResFailReplace) { +lbl2: + r = mcman_replaceBackupBlock(mce->mc_port, mce->mc_slot, mcdi->backup_block1); + mcdi->backup_block1 = r; + goto lbl1; + } + if (r != sceMcResSucceed) + return -52; + + mcman_pagebuf.word[0] = block | 0x80000000; + p_page = (void *)&mcman_pagebuf; //s0 + p_ecc = (void *)eccbuf; //s2 = sp58 + + i = 0; //s1 + do { + if (pagesize < 0) + ecc_count = (pagesize + 0x7f) >> 7; + else + ecc_count = pagesize >> 7; + + if (i >= ecc_count) + break; + + McDataChecksum(p_page, p_ecc); + + p_ecc += 3; + p_page += 128; + i++; + } while (1); + + + r = McWritePage(mce->mc_port, mce->mc_slot, mcdi->backup_block2 * blocksize, &mcman_pagebuf, eccbuf); + if (r == sceMcResFailReplace) + goto lbl3; + if (r != sceMcResSucceed) + return -53; + + if (r < mcdi->blocksize) { + i = 0; //s0 + p_ecc = (void *)mcman_eccdata; + + do { + r = McWritePage(mce->mc_port, mce->mc_slot, (mcdi->backup_block1 * blocksize) + i, mcman_pagedata[i], p_ecc); + if (r == sceMcResFailReplace) + goto lbl2; + if (r != sceMcResSucceed) + return -54; + p_ecc += sparesize; + } while (++i < mcdi->blocksize); + } + + r = McWritePage(mce->mc_port, mce->mc_slot, (mcdi->backup_block2 * blocksize) + 1, &mcman_pagebuf, eccbuf); + if (r == sceMcResFailReplace) + goto lbl3; + if (r != sceMcResSucceed) + return -55; + } + + r = mcman_eraseblock(mce->mc_port, mce->mc_slot, block, (void**)mcman_pagedata, mcman_eccdata); + //if (block == 1) ///// + // r = sceMcResFailReplace; ///// + if (r == sceMcResFailReplace) { + r = mcman_fillbackupblock1(mce->mc_port, mce->mc_slot, block, (void**)mcman_pagedata, mcman_eccdata); + for (i = 0; i < clusters_per_block; i++) { + if (pmce[i] != 0) + pmce[i]->wr_flag = 0; + } + if (r == sceMcResFailReplace) + return r; + return -58; + } + if (r != sceMcResSucceed) + return -57; + + if (mcdi->blocksize > 0) { + i = 0; //s0 + p_ecc = (void *)mcman_eccdata; + + do { + if (pmce[i / mcdi->pages_per_cluster] == 0) { + r = McWritePage(mce->mc_port, mce->mc_slot, (block * blocksize) + i, mcman_pagedata[i], p_ecc); + if (r == sceMcResFailReplace) { + r = mcman_fillbackupblock1(mce->mc_port, mce->mc_slot, block, (void**)mcman_pagedata, mcman_eccdata); + for (i = 0; i < clusters_per_block; i++) { + if (pmce[i] != 0) + pmce[i]->wr_flag = 0; + } + if (r == sceMcResFailReplace) + return r; + return -58; + } + if (r != sceMcResSucceed) + return -57; + } + p_ecc += sparesize; + } while (++i < mcdi->blocksize); + } + + if (mcdi->blocksize > 0) { + i = 0; //s0 + p_ecc = (void *)mcman_eccdata; + + do { + if (pmce[i / mcdi->pages_per_cluster] != 0) { + r = McWritePage(mce->mc_port, mce->mc_slot, (block * blocksize) + i, mcman_pagedata[i], p_ecc); + if (r == sceMcResFailReplace) { + r = mcman_fillbackupblock1(mce->mc_port, mce->mc_slot, block, (void**)mcman_pagedata, mcman_eccdata); + for (i = 0; i < clusters_per_block; i++) { + if (pmce[i] != 0) + pmce[i]->wr_flag = 0; + } + if (r == sceMcResFailReplace) + return r; + return -58; + } + if (r != sceMcResSucceed) + return -57; + } + p_ecc += sparesize; + } while (++i < mcdi->blocksize); + } + + if (clusters_per_block > 0) { + i = 0; + do { + if (pmce[i] != 0) + pmce[i]->wr_flag = 0; + } while (++i < clusters_per_block); + } + + if ((flag != 0) && (mcman_badblock <= 0)) { + r = mcman_eraseblock(mce->mc_port, mce->mc_slot, mcdi->backup_block2, NULL, NULL); + if (r == sceMcResFailReplace) { + goto lbl3; + } + if (r != sceMcResSucceed) + return -58; + } + goto lbl_exit; + +lbl3: + r = mcman_replaceBackupBlock(mce->mc_port, mce->mc_slot, mcdi->backup_block2); + mcdi->backup_block2 = r; + goto lbl1; + +lbl_exit: + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int McReadCluster(int port, int slot, int cluster, McCacheEntry **pmce) +{ + register int r, i, block, block_offset; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McCacheEntry *mce; + + if (mcman_badblock > 0) { + block = cluster / mcdi->clusters_per_block; + block_offset = cluster % mcdi->clusters_per_block; + + if ((block == mcman_badblock) && (mcman_badblock_port == port) && (mcman_badblock_slot == slot)) { + cluster = (mcdi->backup_block1 * mcdi->clusters_per_block) + block_offset; + } + else { + if (mcman_badblock > 0) { + for (i = 0; i < mcdi->clusters_per_block; i++) { + if ((mcman_replacementcluster[i] != 0) && (mcman_replacementcluster[i] == cluster)) { + block_offset = i % mcdi->clusters_per_block; + cluster = (mcdi->backup_block1 * mcdi->clusters_per_block) + block_offset; + } + } + } + } + } + + mce = mcman_getcacheentry(port, slot, cluster); + if (mce == NULL) { + mce = pmcman_mccache[MAX_CACHEENTRY - 1]; + + if (mce->wr_flag != 0) { + r = mcman_flushcacheentry((McCacheEntry *)mce); + if (r != sceMcResSucceed) + return r; + } + + mce->mc_port = port; + mce->mc_slot = slot; + mce->cluster = cluster; + mce->rd_flag = 0; + //s3 = (cluster * mcdi->pages_per_cluster); + + for (i = 0; i < mcdi->pages_per_cluster; i++) { + r = McReadPage(port, slot, (cluster * mcdi->pages_per_cluster) + i, \ + (void *)(mce->cl_data + (i * mcdi->pagesize))); + if (r != sceMcResSucceed) + return -21; + + } + } + mcman_addcacheentry(mce); + *pmce = (McCacheEntry *)mce; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int McReadDirEntry(int port, int slot, int cluster, int fsindex, McFsEntry **pfse) // Export #47 XMCMAN only +{ + register int r, i; + static int maxent, index, clust; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + register McFatCache *fci = &mcman_fatcache[port][slot]; + McCacheEntry *mce; + + DPRINTF("McReadDirEntry port%d slot%d cluster %d fsindex %d\n", port, slot, cluster, fsindex); + + maxent = 0x402 / (mcdi->cluster_size >> 9); //a1 + index = fsindex / (mcdi->cluster_size >> 9);//s2 + + clust = cluster; + i = 0; // s0 + if ((cluster == 0) && (index != 0)) { + if (index < maxent) { + i = index; + if ((fci->entry[index]) >= 0 ) + clust = fci->entry[index]; + } + i = 0; + if (index > 0) { + do { + if (i >= maxent) + break; + if (fci->entry[i] < 0) + break; + clust = fci->entry[i]; + } while (++i < index); + } + i--; + } + + if (i < index) { + do { + r = McGetFATentry(port, slot, clust, &clust); + if (r != sceMcResSucceed) + return -70; + + if (clust == 0xffffffff) + return sceMcResNoEntry; + clust &= 0x7fffffff; + + i++; + if (cluster == 0) { + if (i < maxent) + fci->entry[i] = clust; + } + } while (i < index); + } + + r = McReadCluster(port ,slot, mcdi->alloc_offset + clust, &mce); + if (r != sceMcResSucceed) + return -71; + + *pfse = (McFsEntry *)(mce->cl_data + ((fsindex % (mcdi->cluster_size >> 9)) << 9)); + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_readdirentryPS1(int port, int slot, int cluster, McFsEntryPS1 **pfse) +{ + register int r, offset, index, pages_per_fatclust; + McCacheEntry *mce; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + if (cluster >= 15) + return -73; + + pages_per_fatclust = MCMAN_CLUSTERSIZE / mcdi->pagesize; + + cluster++; + index = cluster / pages_per_fatclust; + offset = cluster % pages_per_fatclust; + + r = mcman_readclusterPS1(port, slot, index * pages_per_fatclust, &mce); + if (r != sceMcResSucceed) + return -74; + + *pfse = (void *)&mce->cl_data[offset << 7]; + + if (sio2man_type >= XSIO2MAN) { + McFsEntryPS1 *fse = (McFsEntryPS1 *)*pfse; // <--- XMCMAN seems to work with this + fse->field_7d = 0; // + } + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int McSetFATentry(int port, int slot, int fat_index, int fat_entry) // Export #46 XMCMAN only +{ + register int r, ifc_index, indirect_index, indirect_offset, fat_offset; + McCacheEntry *mce; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + //DPRINTF("McSetFATentry port%d slot%d fat_index %x fat_entry %x\n", port, slot, fat_index, fat_entry); + + indirect_index = fat_index / mcdi->FATentries_per_cluster; + fat_offset = fat_index % mcdi->FATentries_per_cluster; + + ifc_index = indirect_index / mcdi->FATentries_per_cluster; + indirect_offset = indirect_index % mcdi->FATentries_per_cluster; + + r = McReadCluster(port, slot, mcdi->ifc_list[ifc_index], &mce); + if (r != sceMcResSucceed) + return -75; + + McFatCluster *fc = (McFatCluster *)mce->cl_data; + + r = McReadCluster(port, slot, fc->entry[indirect_offset], &mce); + if (r != sceMcResSucceed) + return -76; + + fc = (McFatCluster *)mce->cl_data; + + fc->entry[fat_offset] = fat_entry; + mce->wr_flag = 1; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int McGetFATentry(int port, int slot, int fat_index, int *fat_entry) // Export #44 XMCMAN only +{ + register int r, ifc_index, indirect_index, indirect_offset, fat_offset; + McCacheEntry *mce; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + indirect_index = fat_index / mcdi->FATentries_per_cluster; + fat_offset = fat_index % mcdi->FATentries_per_cluster; + + ifc_index = indirect_index / mcdi->FATentries_per_cluster; + indirect_offset = indirect_index % mcdi->FATentries_per_cluster; + + r = McReadCluster(port, slot, mcdi->ifc_list[ifc_index], &mce); + if (r != sceMcResSucceed) + return -78; + + McFatCluster *fc = (McFatCluster *)mce->cl_data; + + r = McReadCluster(port, slot, fc->entry[indirect_offset], &mce); + if (r != sceMcResSucceed) + return -79; + + fc = (McFatCluster *)mce->cl_data; + + *fat_entry = fc->entry[fat_offset]; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_readclusterPS1(int port, int slot, int cluster, McCacheEntry **pmce) +{ + register int r, i, pages_per_fatclust; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McCacheEntry *mce; + + mce = mcman_getcacheentry(port, slot, cluster); + if (mce == NULL) { + mce = pmcman_mccache[MAX_CACHEENTRY - 1]; + + if (mce->wr_flag != 0) { + r = mcman_flushcacheentry((McCacheEntry *)mce); + if (r != sceMcResSucceed) + return r; + } + + mce->mc_port = port; + mce->mc_slot = slot; + mce->cluster = cluster; + + pages_per_fatclust = MCMAN_CLUSTERSIZE / mcdi->pagesize; + + for (i = 0; i < pages_per_fatclust; i++) { + r = McReadPS1PDACard(port, slot, cluster + i, (void *)(mce->cl_data + (i * mcdi->pagesize))); + if (r != sceMcResSucceed) + return -21; + } + } + + mcman_addcacheentry(mce); + *pmce = (McCacheEntry *)mce; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_replaceBackupBlock(int port, int slot, int block) +{ + register int i; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + if (mcman_badblock > 0) + return sceMcResFailReplace; + + for (i = 0; i < 16; i++) { + if (mcdi->bad_block_list[i] == -1) + break; + } + + if (i < 16) { + if ((mcdi->alloc_end - mcdi->max_allocatable_clusters) < 8) + return sceMcResFullDevice; + + mcdi->alloc_end -= 8; + mcdi->bad_block_list[i] = block; + mcman_badblock_port = port; + mcman_badblock_slot = slot; + mcman_badblock = -1; + + return (mcdi->alloc_offset + mcdi->alloc_end) / mcdi->clusters_per_block; + } + + return sceMcResFullDevice; +} + +//-------------------------------------------------------------- +int mcman_fillbackupblock1(int port, int slot, int block, void **pagedata, void *eccdata) +{ + register int r, i, sparesize, page_offset; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + register u8 *p_ecc; + + DPRINTF("mcman_fillbackupblock1 port%d slot%d block %x mcman_badblock %x\n", port, slot, block, mcman_badblock); + + sparesize = mcman_sparesize(port, slot); + + if (mcman_badblock != 0) { + if ((mcman_badblock != block) || (mcman_badblock_port != port) || (mcman_badblock_slot != slot)) + return sceMcResFailReplace; + } + + if ((mcdi->alloc_offset / mcdi->clusters_per_block) == block) // Appparently this refuse to take care of a bad rootdir cluster + return sceMcResFailReplace; + + r = mcman_eraseblock(port, slot, mcdi->backup_block2, NULL, NULL); + if (r != sceMcResSucceed) + return r; + + r = mcman_eraseblock(port, slot, mcdi->backup_block1, NULL, NULL); + if (r != sceMcResSucceed) + return r; + + for (i = 0; i < 16; i++) { + if (mcdi->bad_block_list[i] == -1) + break; + } + + if (i >= 16) + return sceMcResFailReplace; + + page_offset = mcdi->backup_block1 * mcdi->blocksize; + p_ecc = (u8 *)eccdata; + + for (i = 0; i < mcdi->blocksize; i++) { + r = McWritePage(port, slot, page_offset + i, pagedata[i], p_ecc); + if (r != sceMcResSucceed) + return r; + p_ecc += sparesize; + } + + mcman_badblock_port = port; + mcman_badblock_slot = slot; + mcman_badblock = block; + + i = 15; + do { + mcman_replacementcluster[i] = 0; + } while (--i >= 0); + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int McReplaceBadBlock(void) +{ + register int r, i, curentry, clust, index, offset, numifc, fat_length, temp, length; + register int value, value2, cluster, index2, offset2, s3; + register MCDevInfo *mcdi = &mcman_devinfos[mcman_badblock_port][mcman_badblock_slot]; + int fat_entry[16]; + int fat_entry2; + McCacheEntry *mce; + McFsEntry *fse; + + DPRINTF("McReplaceBadBlock mcman_badblock_port%d mcman_badblock_slot%d mcman_badblock %x\n", mcman_badblock_port, mcman_badblock_slot, mcman_badblock); + + if (mcman_badblock == 0) + return sceMcResSucceed; + + if (mcman_badblock >= 0) { + McFlushCache(mcman_badblock_port, mcman_badblock_slot); + mcman_clearcache(mcman_badblock_port, mcman_badblock_slot); + + for (i = 0; i <16; i++) { + if (mcdi->bad_block_list[i] == -1) + break; + } + if (i >= 16) + goto lbl_e168; + + if (mcdi->alloc_end >= (mcdi->max_allocatable_clusters + 8)) { + mcdi->max_allocatable_clusters += 8; + mcdi->bad_block_list[i] = mcman_badblock; + } + + fat_length = (((mcdi->clusters_per_card << 2) - 1) / mcdi->cluster_size) + 1; + numifc = (((fat_length << 2) - 1) / mcdi->cluster_size) + 1; + + if (numifc > 32) { + numifc = 32; + fat_length = mcdi->FATentries_per_cluster << 5; + } + + i = 0; //sp5c + value = ~(-1 << mcdi->clusters_per_block); + do { + clust = (mcman_badblock * mcdi->clusters_per_block) + i; + if (clust < mcdi->alloc_offset) { + fat_entry[i] = 0; + } + else { + r = McGetFATentry(mcman_badblock_port, mcman_badblock_slot, clust - mcdi->alloc_offset, &fat_entry[i]); + if (r != sceMcResSucceed) + goto lbl_e168; + + if (((fat_entry[i] & 0x80000000) == 0) || ((fat_entry[i] < -1) && (fat_entry[i] >= -9))) + value &= ~(1 << i); + } + } while (++i < mcdi->clusters_per_block); + + if (mcdi->clusters_per_block > 0) { + i = 0; + do { + if ((value & (1 << i)) != 0) { + r = mcman_findfree2(mcman_badblock_port, mcman_badblock_slot, 1); + if (r < 0) { + mcman_replacementcluster[i] = r; + goto lbl_e168; + } + r += mcdi->alloc_offset; + mcman_replacementcluster[i] = r; + } + } while (++i < mcdi->clusters_per_block); + } + + if (mcdi->clusters_per_block > 0) { + i = 0; + do { + if ((value & (1 << i)) != 0) { + if (fat_entry[i] != 0) { + index = ((fat_entry[i] & 0x7fffffff) + mcdi->alloc_offset) / mcdi->clusters_per_block; + offset = ((fat_entry[i] & 0x7fffffff) + mcdi->alloc_offset) % mcdi->clusters_per_block; + if (index == mcman_badblock) { + fat_entry[i] = (mcman_replacementcluster[offset] - mcdi->alloc_offset) | 0x80000000; + } + } + } + } while (++i < mcdi->clusters_per_block); + } + + if (mcdi->clusters_per_block > 0) { + i = 0; + do { + if ((mcman_replacementcluster[i] != 0) && (fat_entry[i] != 0)) { + r = McSetFATentry(mcman_badblock_port, mcman_badblock_slot, mcman_replacementcluster[i] + mcdi->alloc_offset, fat_entry[i]); + if (r != sceMcResSucceed) + goto lbl_e168; + } + } while (++i < mcdi->clusters_per_block); + } + + for (i = 0; i < numifc; i++) { + index = mcdi->ifc_list[i] / mcdi->clusters_per_block; + offset = mcdi->ifc_list[i] % mcdi->clusters_per_block; + + if (index == mcman_badblock) { + value &= ~(1 << offset); + mcdi->ifc_list[i] = mcman_replacementcluster[i]; + } + } + + if (value == 0) + goto lbl_e030; + + for (i = 0; i < fat_length; i++) { + index = i / mcdi->FATentries_per_cluster; + offset = i % mcdi->FATentries_per_cluster; + + if (offset == 0) { + r = McReadCluster(mcman_badblock_port, mcman_badblock_slot, mcdi->ifc_list[index], &mce); + if (r != sceMcResSucceed) + goto lbl_e168; + } + offset = i % mcdi->FATentries_per_cluster; + index2 = *((u32 *)&mce->cl_data[offset]) / mcdi->clusters_per_block; + offset2 = *((u32 *)&mce->cl_data[offset]) % mcdi->clusters_per_block; + + if (index2 == mcman_badblock) { + value &= ~(1 << offset2); + *((u32 *)&mce->cl_data[offset]) = mcman_replacementcluster[offset2]; + mce->wr_flag = 1; + } + } + + McFlushCache(mcman_badblock_port, mcman_badblock_slot); + mcman_clearcache(mcman_badblock_port, mcman_badblock_slot); + + if (value == 0) + goto lbl_e030; + + value2 = value; + + for (i = 0; i < mcdi->alloc_end; i++) { + r = McGetFATentry(mcman_badblock_port, mcman_badblock_slot, i, &fat_entry2); + if (r != sceMcResSucceed) + goto lbl_e168; + + index = (u32)(((fat_entry2 & 0x7fffffff) + mcdi->alloc_offset) / mcdi->clusters_per_block); + offset = (u32)(((fat_entry2 & 0x7fffffff) + mcdi->alloc_offset) % mcdi->clusters_per_block); + + if (index == mcman_badblock) { + value &= ~(1 << offset); + r = McSetFATentry(mcman_badblock_port, mcman_badblock_slot, i, (mcman_replacementcluster[offset] - mcdi->alloc_offset) | 0x80000000); + if (r != sceMcResSucceed) + goto lbl_e168; + } + } + + if (value2 != value) + McFlushCache(mcman_badblock_port, mcman_badblock_slot); + + r = McReadDirEntry(mcman_badblock_port, mcman_badblock_slot, 0, 0, &fse); + if (r != sceMcResSucceed) + goto lbl_e168; + + curentry = 2; + s3 = 0; + length = fse->length; + +lbl_dd8c: + if (curentry >= length) + goto lbl_ded0; + + r = McReadDirEntry(mcman_badblock_port, mcman_badblock_slot, s3, curentry, &fse); + if (r != sceMcResSucceed) + goto lbl_e168; + + cluster = fse->cluster; + index = (fse->cluster + mcdi->alloc_offset) / mcdi->clusters_per_block; + offset = (fse->cluster + mcdi->alloc_offset) % mcdi->clusters_per_block; + + temp = fse->length; + + if (index == mcman_badblock) { + fse->cluster = mcman_replacementcluster[offset] - mcdi->alloc_offset; + Mc1stCacheEntSetWrFlagOff(); + } + + if ((fse->mode & sceMcFileAttrSubdir) == 0) { + curentry++; + goto lbl_dd8c; + } + + r = McReadDirEntry(mcman_badblock_port, mcman_badblock_slot, cluster, 0, &fse); + if (r != sceMcResSucceed) + goto lbl_e168; + + if ((fse->mode & sceMcFileAttrSubdir) == 0) { + curentry++; + goto lbl_dd8c; + } + + if (fse->cluster != 0) { + curentry++; + goto lbl_dd8c; + } + + if (fse->dir_entry != curentry) { + curentry++; + goto lbl_dd8c; + } + + curentry++; + + if (strcmp(fse->name, ".")) + goto lbl_dd8c; + + s3 = cluster; + curentry = 2; + length = temp; + goto lbl_dd8c; + +lbl_ded0: + r = McReadDirEntry(mcman_badblock_port, mcman_badblock_slot, s3, 1, &fse); + if (r != sceMcResSucceed) + goto lbl_e168; + + index = (fse->cluster + mcdi->alloc_offset) / mcdi->clusters_per_block; + offset = (fse->cluster + mcdi->alloc_offset) % mcdi->clusters_per_block; + + if (index == mcman_badblock) { + fse->cluster = mcman_replacementcluster[offset] - mcdi->alloc_offset; + Mc1stCacheEntSetWrFlagOff(); + } + + r = McReadDirEntry(mcman_badblock_port, mcman_badblock_slot, fse->cluster, fse->dir_entry, &fse); + if (r != sceMcResSucceed) + goto lbl_e168; + + length = fse->length; + + r = McReadDirEntry(mcman_badblock_port, mcman_badblock_slot, s3, 0, &fse); + if (r != sceMcResSucceed) + goto lbl_e168; + + s3 = fse->cluster; + index = (fse->cluster + mcdi->alloc_offset) / mcdi->clusters_per_block; + offset = (fse->cluster + mcdi->alloc_offset) % mcdi->clusters_per_block; + curentry = fse->dir_entry + 1; + + if (index == mcman_badblock) { + fse->cluster = mcman_replacementcluster[offset] - mcdi->alloc_offset; + Mc1stCacheEntSetWrFlagOff(); + } + + if (s3 != 0) + goto lbl_dd8c; + + if (curentry != 1) + goto lbl_dd8c; + +lbl_e030: + if (mcdi->clusters_per_block > 0) { + i = 0; + do { + clust = (mcman_badblock * mcdi->clusters_per_block) + i; + if (clust >= mcdi->alloc_offset) { + r = McSetFATentry(mcman_badblock_port, mcman_badblock_slot, clust - mcdi->alloc_offset, 0xfffffffd); + if (r != sceMcResSucceed) + goto lbl_e168; + } + } while (++i < mcdi->clusters_per_block); + } + + McFlushCache(mcman_badblock_port, mcman_badblock_slot); + mcman_clearcache(mcman_badblock_port, mcman_badblock_slot); + + mcman_badblock = 0; + + if (mcdi->clusters_per_block > 0) { + i = 0; + do { + if (mcman_replacementcluster[i] != 0) { + r = McReadCluster(mcman_badblock_port, mcman_badblock_slot, (mcdi->backup_block1 * mcdi->clusters_per_block) + i, &mce); + if (r != sceMcResSucceed) + goto lbl_e168; + + mce->cluster = mcman_replacementcluster[i]; + mce->wr_flag = 1; + } + } while (++i < mcdi->clusters_per_block); + } + + McFlushCache(mcman_badblock_port, mcman_badblock_slot); + } + else { + mcman_badblock = 0; + } + + r = mcman_clearsuperblock(mcman_badblock_port, mcman_badblock_slot); + return r; + +lbl_e168: + mcman_badblock = 0; + return sceMcResFailReplace; +} + +//-------------------------------------------------------------- +int mcman_clearsuperblock(int port, int slot) +{ + register int r, i, size, temp; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McCacheEntry *mce; + + // set superblock magic & version + memset((void *)mcdi->magic, 0, sizeof (mcdi->magic) + sizeof (mcdi->version)); + strcpy(mcdi->magic, SUPERBLOCK_MAGIC); + strcat(mcdi->magic, SUPERBLOCK_VERSION); + + for (i = 0; (u32)(i < sizeof(MCDevInfo)); i += 1024) { + temp = i; + if (i < 0) + temp = i + 1023; + r = McReadCluster(port, slot, temp >> 10, &mce); + if (r != sceMcResSucceed) + return -48; + mce->wr_flag = 1; + size = 1024; + temp = sizeof(MCDevInfo) - i; + + if (temp <= 1024) + size = temp; + + memcpy((void *)mce->cl_data, (void *)mcdi, size); + } + + r = McFlushCache(port, slot); + + return r; +} + +//-------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/mcdev.c b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/mcdev.c new file mode 100644 index 0000000..844a127 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/mcdev.c @@ -0,0 +1,494 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 jimmikaelkael +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include +#include "mcman-internal.h" + +// mc driver vars +static int mcman_mc_port = 0; +static int mcman_mc_slot = 0; +static int mcman_io_sema = 0; + +// mc driver ops functions prototypes +int mc_init(iop_device_t *iop_dev); +int mc_deinit(iop_device_t *dev); +int mc_open(iop_file_t *f, char *filename, int mode, int flags); +int mc_close(iop_file_t *f); +int mc_lseek(iop_file_t *f, int pos, int where); +int mc_read(iop_file_t *f, void *buf, int size); +int mc_write(iop_file_t *f, void *buf, int size); +int mc_format(iop_file_t *f, char *a1, char *a2, void *a3, int a4); +int mc_remove(iop_file_t *f, char *filename); +int mc_mkdir(iop_file_t *f, char *dirname); +int mc_rmdir(iop_file_t *f, char *dirname); +int mc_dopen(iop_file_t *f, char *dirname); +int mc_dclose(iop_file_t *f); +int mc_dread(iop_file_t *f, io_dirent_t *dirent); +int mc_getstat(iop_file_t *f, char *filename, io_stat_t *stat); +int mc_chstat(iop_file_t *f, char *filename, io_stat_t *stat, u32 statmask); +int mc_ioctl(iop_file_t *f, int a1, void* a2); + +// driver ops func tab +void *mcman_mcops[17] = { + (void*)mc_init, + (void*)mc_deinit, + (void*)mc_format, + (void*)mc_open, + (void*)mc_close, + (void*)mc_read, + (void*)mc_write, + (void*)mc_lseek, + (void*)mc_ioctl, + (void*)mc_remove, + (void*)mc_mkdir, + (void*)mc_rmdir, + (void*)mc_dopen, + (void*)mc_dclose, + (void*)mc_dread, + (void*)mc_getstat, + (void*)mc_chstat +}; + +// driver descriptor +static iop_device_t mcman_mcdev = { +#ifndef BUILDING_XFROMMAN + "mc", +#endif +#ifdef BUILDING_XFROMMAN + "xfrom", +#endif + IOP_DT_FS, + 1, +#ifndef BUILDING_XFROMMAN + "Memory Card", +#endif +#ifdef BUILDING_XFROMMAN + "External flash rom", +#endif + (struct _iop_device_ops *)&mcman_mcops +}; + +//-------------------------------------------------------------- +int mc_init(iop_device_t *dev) +{ + return 0; +} + +//-------------------------------------------------------------- +int mcman_ioerrcode(int errcode) +{ + register int r = errcode; + + if (r < 0) { + switch (r + 8) { + case 0: + r = -EIO; + break; + case 1: + r = -EMFILE; + break; + case 2: + r = -EEXIST; + break; + case 3: + r = -EACCES; + break; + case 4: + r = -ENOENT; + break; + case 5: + r = -ENOSPC; + break; + case 6: + r = -EFORMAT; + break; + default: + r = -ENXIO; + break; + } + } + return r; +} + +//-------------------------------------------------------------- +int mcman_modloadcb(char *filename, int *port, int *slot) +{ + register char *path = filename; + register int upos; + + if (*path == 0x20) { + path++; + while (*path == 0x20) + path++; + } + + if (((u8)path[0] | 0x20) != mcman_mcdev.name[0]) + return 0; + if (((u8)path[1] | 0x20) != mcman_mcdev.name[1]) + return 0; + + if ((u32)strlen(path) < 2) return 2; + + upos = mcman_chrpos(path, ':'); + + if (upos < 0) + upos = strlen(path); + + if (port) { + upos --; + if (((u8)path[upos] - 0x30) < 10) + *port = (u8)path[upos] - 0x30; + else *port = 0; + } + + upos--; + *port += 2; + + if (slot) { + register int m, v; + + *slot = 0; + for (m = 1; ((u8)path[upos --] - 0x30) < 10; m = v << 1) { + v = m << 2; + *slot += m * (path[upos] - 0x30); + v += m; + } + } + + return 1; +} + +//-------------------------------------------------------------- +void mcman_unit2card(u32 unit) +{ +#ifndef BUILDING_XFROMMAN + mcman_mc_port = unit & 1; + mcman_mc_slot = (unit >> 1) & (MCMAN_MAXSLOT - 1); +#endif +#ifdef BUILDING_XFROMMAN + mcman_mc_port = 0; + mcman_mc_slot = 0; +#endif + + // original mcman/xmcman code below is silly and I doubt it + // can support more than 2 units anyway... + /* + register u32 mask = 0xF0000000; + + while (!(unit & mask)) { + mask >>= 4; + if (mask < 0x10) + break; + } + + mcman_mc_port = unit & 0xf; + mcman_mc_slot = 0; + + if (mask < 0xf) { + while (mask) { + mcman_mc_slot = ((u32)(unit & mask)) / ((u32)(mask & (mask >> 0x3))) \ + + (((mcman_mc_slot << 2) + mcman_mc_slot) << 1); + mask >>= 4; + } + } + */ +} + +//-------------------------------------------------------------- +int mcman_initdev(void) +{ + iop_sema_t smp; + + SetCheckKelfPathCallback(mcman_modloadcb); + + DelDrv(mcman_mcdev.name); + if (AddDrv(&mcman_mcdev)) { + McCloseAll(); + return 1; + } + + smp.attr = 1; + smp.initial = 1; + smp.max = 1; + smp.option = 0; + mcman_io_sema = CreateSema(&smp); + + return 0; +} + +//-------------------------------------------------------------- +int mc_deinit(iop_device_t *dev) +{ + DeleteSema(mcman_io_sema); + McCloseAll(); + + return 0; +} + +//-------------------------------------------------------------- +int mc_open(iop_file_t *f, char *filename, int mode, int flags) +{ + register int r; + + WaitSema(mcman_io_sema); + mcman_unit2card(f->unit); + + r = McDetectCard2(mcman_mc_port, mcman_mc_slot); + if (r >= -1) { + r = McOpen(mcman_mc_port, mcman_mc_slot, filename, mode); + if (r >= 0) + f->privdata = (void*)r; + } + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_close(iop_file_t *f) +{ + register int r; + + WaitSema(mcman_io_sema); + r = McClose((int)f->privdata); + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_lseek(iop_file_t *f, int pos, int where) +{ + register int r; + + WaitSema(mcman_io_sema); + r = McSeek((int)f->privdata, pos, where); + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_read(iop_file_t *f, void *buf, int size) +{ + register int r; + + WaitSema(mcman_io_sema); + r = McRead((int)f->privdata, buf, size); + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_write(iop_file_t *f, void *buf, int size) +{ + register int r; + + WaitSema(mcman_io_sema); + r = McWrite((int)f->privdata, buf, size); + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_format(iop_file_t *f, char *a1, char *a2, void *a3, int a4) +{ + register int r; + + WaitSema(mcman_io_sema); + mcman_unit2card(f->unit); + + r = McDetectCard2(mcman_mc_port, mcman_mc_slot); + if (r >= -2) { + r = McFormat(mcman_mc_port, mcman_mc_slot); + } + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_remove(iop_file_t *f, char *filename) +{ + register int r; + + WaitSema(mcman_io_sema); + mcman_unit2card(f->unit); + + r = McDetectCard2(mcman_mc_port, mcman_mc_slot); + if (r >= -1) { + r = McDelete(mcman_mc_port, mcman_mc_slot, filename, 0); + } + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_mkdir(iop_file_t *f, char *dirname) +{ + register int r; + + WaitSema(mcman_io_sema); + mcman_unit2card(f->unit); + + r = McDetectCard2(mcman_mc_port, mcman_mc_slot); + if (r >= -1) { + r = McOpen(mcman_mc_port, mcman_mc_slot, dirname, 0x40); + } + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_rmdir(iop_file_t *f, char *dirname) +{ + register int r; + + WaitSema(mcman_io_sema); + mcman_unit2card(f->unit); + + r = McDetectCard2(mcman_mc_port, mcman_mc_slot); + if (r >= -1) { + r = McDelete(mcman_mc_port, mcman_mc_slot, dirname, 0); + } + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_dopen(iop_file_t *f, char *dirname) +{ + register int r; + + WaitSema(mcman_io_sema); + mcman_unit2card(f->unit); + + r = McDetectCard2(mcman_mc_port, mcman_mc_slot); + if (r >= -1) { + r = McOpen(mcman_mc_port, mcman_mc_slot, dirname, 0); + if (r >= 0) + f->privdata = (void*)r; + } + + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_dclose(iop_file_t *f) +{ + register int r; + + WaitSema(mcman_io_sema); + r = McClose((int)f->privdata); + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_dread(iop_file_t *f, io_dirent_t *dirent) +{ + register int r; + + WaitSema(mcman_io_sema); + r = mcman_dread((int)f->privdata, dirent); + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_getstat(iop_file_t *f, char *filename, io_stat_t *stat) +{ + register int r; + + WaitSema(mcman_io_sema); + mcman_unit2card(f->unit); + + r = McDetectCard2(mcman_mc_port, mcman_mc_slot); + if (r >= -1) { + r = mcman_getstat(mcman_mc_port, mcman_mc_slot, filename, stat); + } + + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_chstat(iop_file_t *f, char *filename, io_stat_t *stat, u32 statmask) +{ + register int r, flags; + sceMcTblGetDir mctbl; + + WaitSema(mcman_io_sema); + mcman_unit2card(f->unit); + + r = McDetectCard2(mcman_mc_port, mcman_mc_slot); + if (r >= -1) { + if (statmask & SCE_CST_ATTR) { + flags = 0x008; + mctbl.Reserve2 = stat->attr; + } + else flags = 0x000; + + if (statmask & SCE_CST_MODE) { + flags |= 0x200; + if (stat->mode & SCE_STM_R) mctbl.AttrFile |= sceMcFileAttrReadable; + else mctbl.AttrFile &= (unsigned short)~sceMcFileAttrReadable; + + if (stat->mode & SCE_STM_W) mctbl.AttrFile |= sceMcFileAttrWriteable; + else mctbl.AttrFile &= (unsigned short)~sceMcFileAttrWriteable; + + if (stat->mode & SCE_STM_X) mctbl.AttrFile |= sceMcFileAttrExecutable; + else mctbl.AttrFile &= (unsigned short)~sceMcFileAttrExecutable; + + if (stat->mode & SCE_STM_C) mctbl.AttrFile |= sceMcFileAttrDupProhibit; + else mctbl.AttrFile &= (unsigned short)~sceMcFileAttrDupProhibit; + + if (stat->mode & sceMcFileAttrPS1) mctbl.AttrFile |= sceMcFileAttrPS1; + else mctbl.AttrFile &= (unsigned short)~sceMcFileAttrPS1; + + if (stat->mode & sceMcFileAttrPDAExec) mctbl.AttrFile |= sceMcFileAttrPDAExec; + else mctbl.AttrFile &= (unsigned short)~sceMcFileAttrPDAExec; + } + + if (statmask & SCE_CST_CT) { + flags |= 0x001; + memcpy(&mctbl._Create, stat->ctime, sizeof(sceMcStDateTime)); + } + + if (statmask & SCE_CST_MT) { + flags |= 0x002; + memcpy(&mctbl._Modify, stat->mtime, sizeof(sceMcStDateTime)); + } + + r = McSetFileInfo(mcman_mc_port, mcman_mc_slot, filename, &mctbl, flags); + } + SignalSema(mcman_io_sema); + + return mcman_ioerrcode(r); +} + +//-------------------------------------------------------------- +int mc_ioctl(iop_file_t *f, int a1, void* a2) +{ + WaitSema(mcman_io_sema); + return 0; +} + +//-------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/mcman-internal.h b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/mcman-internal.h new file mode 100644 index 0000000..9804c7a --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/mcman-internal.h @@ -0,0 +1,246 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 jimmikaelkael +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef __MCMAN_INTERNAL_H__ +#define __MCMAN_INTERNAL_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef BUILDING_XFROMMAN +#include +#endif +#include "sio2man_imports.h" + +#ifndef BUILDING_XFROMMAN +#define MODNAME "mcman_cex" +#endif +#ifdef BUILDING_XFROMMAN +#define MODNAME "xfromman" +#endif +#define MODVER 0x20b + +#ifdef SIO_DEBUG + #include + #define DEBUG + #define DPRINTF(format, args...) \ + sio_printf(MODNAME ": " format, ##args) +#else + #ifdef DEBUG + #define DPRINTF(format, args...) \ + printf(MODNAME ": " format, ##args) + #else + #define DPRINTF(format, args...) + #endif +#endif + +typedef struct _MCCacheDir { + int cluster; // 0 + int fsindex; // 4 + int maxent; // 8 + u32 unused; +} McCacheDir; + +// Card Flags +#define CF_USE_ECC 0x01 +#define CF_BAD_BLOCK 0x08 +#define CF_ERASE_ZEROES 0x10 + +#define MCMAN_MAXSLOT 4 +#define MCMAN_CLUSTERSIZE 1024 +#define MCMAN_CLUSTERFATENTRIES 256 + +typedef struct _McFatCluster { + int entry[MCMAN_CLUSTERFATENTRIES]; +} McFatCluster; + +#define MAX_CACHEENTRY 0x24 + +typedef struct { + int entry[1 + (MCMAN_CLUSTERFATENTRIES * 2)]; +} McFatCache; + +#define MAX_CACHEDIRENTRY 0x3 + +typedef struct { // size = 48 + u8 status; // 0 + u8 wrflag; // 1 + u8 rdflag; // 2 + u8 unknown1; // 3 + u8 drdflag; // 4 + u8 unknown2; // 5 + u16 port; // 6 + u16 slot; // 8 + u16 unknown3; // 10 + u32 position; // 12 + u32 filesize; // 16 + u32 freeclink; // 20 link to next free cluster + u32 clink; // 24 link to next cluster + u32 clust_offset;// 28 + u32 field_20; // 32 + u32 field_24; // 36 + u32 field_28; // 40 + u32 field_2C; // 44 +} MC_FHANDLE; + +#define MAX_FDHANDLES 3 + +// internal functions prototypes +#ifndef BUILDING_XFROMMAN +int mcsio2_transfer(int port, int slot, sio2_transfer_data_t *sio2data); +int mcsio2_transfer2(int port, int slot, sio2_transfer_data_t *sio2data); +#endif +void long_multiply(u32 v1, u32 v2, u32 *HI, u32 *LO); +int mcman_chrpos(char *str, int chr); +void mcman_wmemset(void *buf, int size, int value); +int mcman_calcEDC(void *buf, int size); +int mcman_checkpath(char *str); +int mcman_checkdirpath(char *str1, char *str2); +void mcman_invhandles(int port, int slot); +int McCloseAll(void); +int mcman_detectcard(int port, int slot); +int mcman_dread(int fd, io_dirent_t *dirent); +int mcman_getstat(int port, int slot, char *filename, io_stat_t *stat); +int mcman_getmcrtime(sceMcStDateTime *time); +void mcman_initPS2com(void); +#ifndef BUILDING_XFROMMAN +void sio2packet_add(int port, int slot, int cmd, u8 *buf); +#endif +int mcman_eraseblock(int port, int slot, int block, void **pagebuf, void *eccbuf); +int mcman_readpage(int port, int slot, int page, void *buf, void *eccbuf); +int mcman_cardchanged(int port, int slot); +int mcman_resetauth(int port, int slot); +int mcman_probePS2Card2(int port, int slot); +int mcman_probePS2Card(int port, int slot); +int secrman_mc_command(int port, int slot, sio2_transfer_data_t *sio2data); +int mcman_getcnum (int port, int slot); +int mcman_correctdata(void *buf, void *ecc); +int mcman_sparesize(int port, int slot); +int mcman_setdevspec(int port, int slot); +int mcman_reportBadBlocks(int port, int slot); +int mcman_setdevinfos(int port, int slot); +int mcman_format2(int port, int slot); +int mcman_fatRseek(int fd); +int mcman_fatWseek(int fd); +int mcman_findfree2(int port, int slot, int reserve); +int mcman_dread2(int fd, io_dirent_t *dirent); +int mcman_getstat2(int port, int slot, char *filename, io_stat_t *stat); +int mcman_setinfo2(int port, int slot, char *filename, sceMcTblGetDir *info, int flags); +int mcman_read2(int fd, void *buffer, int nbyte); +int mcman_write2(int fd, void *buffer, int nbyte); +int mcman_close2(int fd); +int mcman_getentspace(int port, int slot, char *dirname); +int mcman_cachedirentry(int port, int slot, char *filename, McCacheDir *pcacheDir, McFsEntry **pfse, int unknown_flag); +int mcman_getdirinfo(int port, int slot, McFsEntry *pfse, char *filename, McCacheDir *pcd, int unknown_flag); +int mcman_open2(int port, int slot, char *filename, int flags); +int mcman_chdir(int port, int slot, char *newdir, char *currentdir); +int mcman_writecluster(int port, int slot, int cluster, int flag); +int mcman_getdir2(int port, int slot, char *dirname, int flags, int maxent, sceMcTblGetDir *info); +int mcman_delete2(int port, int slot, char *filename, int flags); +int mcman_checkBackupBlocks(int port, int slot); +int mcman_unformat2(int port, int slot); +void mcman_initPS1PDAcom(void); +int mcman_probePS1Card2(int port, int slot); +int mcman_probePS1Card(int port, int slot); +int mcman_probePDACard(int port, int slot); +int mcman_setPS1devinfos(int port, int slot); +int mcman_format1(int port, int slot); +int mcman_open1(int port, int slot, char *filename, int flags); +int mcman_read1(int fd, void *buffer, int nbyte); +int mcman_write1(int fd, void *buffer, int nbyte); +int mcman_getPS1direntry(int port, int slot, char *filename, McFsEntryPS1 **pfse, int flag); +int mcman_dread1(int fd, io_dirent_t *dirent); +int mcman_getstat1(int port, int slot, char *filename, io_stat_t *stat); +int mcman_setinfo1(int port, int slot, char *filename, sceMcTblGetDir *info, int flags); +int mcman_getdir1(int port, int slot, char *dirname, int flags, int maxent, sceMcTblGetDir *info); +int mcman_clearPS1direntry(int port, int slot, int cluster, int flags); +int mcman_delete1(int port, int slot, char *filename, int flags); +int mcman_close1(int fd); +int mcman_findfree1(int port, int slot, int reserve); +int mcman_fatRseekPS1(int fd); +int mcman_fatWseekPS1(int fd); +int mcman_FNC8ca4(int port, int slot, MC_FHANDLE *fh); +int mcman_PS1pagetest(int port, int slot, int page); +int mcman_unformat1(int port, int slot); +int mcman_cachePS1dirs(int port, int slot); +int mcman_fillPS1backuparea(int port, int slot, int block); +void mcman_initcache(void); +int mcman_clearcache(int port, int slot); +McCacheEntry *mcman_getcacheentry(int port, int slot, int cluster); +void mcman_freecluster(int port, int slot, int cluster); +int mcman_getFATindex(int port, int slot, int num); +McCacheEntry *mcman_get1stcacheEntp(void); +void mcman_addcacheentry(McCacheEntry *mce); +int mcman_flushcacheentry(McCacheEntry *mce); +int mcman_readdirentryPS1(int port, int slot, int cluster, McFsEntryPS1 **pfse); +int mcman_readclusterPS1(int port, int slot, int cluster, McCacheEntry **pmce); +int mcman_replaceBackupBlock(int port, int slot, int block); +int mcman_fillbackupblock1(int port, int slot, int block, void **pagedata, void *eccdata); +int mcman_clearsuperblock(int port, int slot); +int mcman_ioerrcode(int errcode); +int mcman_modloadcb(char *filename, int *port, int *slot); // used as callback by modload +void mcman_unit2card(u32 unit); +int mcman_initdev(void); + +typedef struct { // size = 384 + char magic[28]; // Superblock magic, on PS2 MC : "Sony PS2 Memory Card Format " + u8 version[12]; // Version number of the format used, 1.2 indicates full support for bad_block_list + s16 pagesize; // size in bytes of a memory card page + u16 pages_per_cluster; // number of pages in a cluster + u16 blocksize; // number of pages in an erase block + u16 unused; // unused + u32 clusters_per_card; // total size in clusters of the memory card + u32 alloc_offset; // Cluster offset of the first allocatable cluster. Cluster values in the FAT and directory entries are relative to this. This is the cluster immediately after the FAT + u32 alloc_end; // The cluster after the highest allocatable cluster. Relative to alloc_offset. Not used + u32 rootdir_cluster; // First cluster of the root directory. Relative to alloc_offset. Must be zero + u32 backup_block1; // Erase block used as a backup area during programming. Normally the the last block on the card, it may have a different value if that block was found to be bad + u32 backup_block2; // This block should be erased to all ones. Normally the the second last block on the card + u8 unused2[8]; + u32 ifc_list[32]; // List of indirect FAT clusters. On a standard 8M card there's only one indirect FAT cluster + int bad_block_list[32]; // List of erase blocks that have errors and shouldn't be used + u8 cardtype; // Memory card type. Must be 2, indicating that this is a PS2 memory card + u8 cardflags; // Physical characteristics of the memory card + u16 unused3; + u32 cluster_size; + u32 FATentries_per_cluster; + u32 clusters_per_block; + int cardform; + u32 rootdir_cluster2; + u32 unknown1; + u32 unknown2; + u32 max_allocatable_clusters; + u32 unknown3; + u32 unknown4; + int unknown5; +} MCDevInfo; + +union mcman_pagebuf { + u32 word[1056/sizeof(u32)]; + u8 byte[1056/sizeof(u8)]; + char magic[1056/sizeof(char)]; +}; + +union mcman_PS1PDApagebuf { + u32 word[128/sizeof(u32)]; + u16 half[128/sizeof(u16)]; + u8 byte[128/sizeof(u8)]; +}; + +#endif // __MCMAN_INTERNAL_H__ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/mcsio2.c b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/mcsio2.c new file mode 100644 index 0000000..36c2232 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/mcsio2.c @@ -0,0 +1,1184 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 jimmikaelkael +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include +#include "mcman-internal.h" + +extern int timer_ID; + +extern MCDevInfo mcman_devinfos[4][MCMAN_MAXSLOT]; + +#ifdef BUILDING_XFROMMAN +static flash_info_t dev9_flash_info; +#endif + +#ifndef BUILDING_XFROMMAN +static sio2_transfer_data_t mcman_sio2packet; // buffer for mcman sio2 packet +static u8 mcman_wdmabufs[0x0b * 0x90]; // buffer array for SIO2 DMA I/O (write) +static u8 mcman_rdmabufs[0x0b * 0x90]; // not sure here for size, buffer array for SIO2 DMA I/O (read) + +static sio2_transfer_data_t mcman_sio2packet_PS1PDA; +static u8 mcman_sio2inbufs_PS1PDA[0x90]; +u8 mcman_sio2outbufs_PS1PDA[0x90]; + +static u32 mcman_timercount; +static int mcman_timerthick; + +// mcman cmd table used by sio2packet_add fnc +static const u8 mcman_cmdtable[36] = { + 0x11, 0x04, 0x12, 0x04, 0x21, 0x09, 0x22, 0x09, + 0x23, 0x09, 0x24, 0x86, 0x25, 0x04, 0x26, 0x0d, + 0x27, 0x05, 0x28, 0x05, 0x42, 0x86, 0x43, 0x86, + 0x81, 0x04, 0x82, 0x04, 0x42, 0x06, 0x43, 0x06, + 0xbf, 0x05, 0xf3, 0x05 +}; + +extern int (*mcman_sio2transfer)(int port, int slot, sio2_transfer_data_t *sio2data); + +// sio2packet_add child functions +static void (*sio2packet_add_func)(int port, int slot, int cmd, u8 *buf, int pos); +static void sio2packet_add_wdma_u32(int port, int slot, int cmd, u8 *buf, int pos); +static void sio2packet_add_pagedata_out(int port, int slot, int cmd, u8 *buf, int pos); +static void sio2packet_add_pagedata_in(int port, int slot, int cmd, u8 *buf, int pos); +static void sio2packet_add_ecc_in(int port, int slot, int cmd, u8 *buf, int pos); +static void sio2packet_add_ecc_out(int port, int slot, int cmd, u8 *buf, int pos); +static void sio2packet_add_wdma_5a(int port, int slot, int cmd, u8 *buf, int pos); +static void sio2packet_add_wdma_00(int port, int slot, int cmd, u8 *buf, int pos); +static void sio2packet_add_wdma_u8(int port, int slot, int cmd, u8 *buf, int pos); +static void sio2packet_add_do_nothing(int port, int slot, int cmd, u8 *buf, int pos); + +// functions pointer array to handle sio2packet_add inner functions calls +static void *sio2packet_add_funcs_array[16] = { + (void *)sio2packet_add_wdma_00, // commands that needs to clear in_dma.addr[2] + (void *)sio2packet_add_wdma_u32, // commands that needs to copy an int to in_dma.addr[2..5] (an int* can be passed as arg into buf) + (void *)sio2packet_add_wdma_u32, // ... + (void *)sio2packet_add_wdma_u32, // ... + (void *)sio2packet_add_wdma_u8, // commands that needs to copy an u8 value to in_dma.addr[2] + (void *)sio2packet_add_do_nothing, // do nothing + (void *)sio2packet_add_do_nothing, // ... + (void *)sio2packet_add_wdma_5a, // commands that needs to set in_dma.addr[2] to value 0x5a, used to set termination code + (void *)sio2packet_add_do_nothing, // do nothing + (void *)sio2packet_add_pagedata_in, // commands that needs to copy pagedata buf into in_dma.addr + (void *)sio2packet_add_pagedata_out,// commands that needs to set in_dma.addr[2] to value 128 for pagedata out + (void *)sio2packet_add_do_nothing, // do nothing + (void *)sio2packet_add_do_nothing, // ... + (void *)sio2packet_add_ecc_in, // commands that needs to copy sparedata buf into in_dma.addr + (void *)sio2packet_add_ecc_out, // commands that needs to prepare regdata and in_dma.addr to receive sparedata + (void *)sio2packet_add_wdma_u8 // commands that needs to copy an u8 value to in_dma.addr[2] +}; + +//-------------------------------------------------------------- +void sio2packet_add(int port, int slot, int cmd, u8 *buf) +{ // Used to build the sio2packets for all mc commands + register u32 regdata; + register int pos; + u8 *p; + + if (cmd == 0xffffffff) { + mcman_sio2packet.in_dma.count = 0; + return; + } + + if (mcman_sio2packet.in_dma.count < 0xb) { + + if (cmd == 0xfffffffe) { + mcman_sio2packet.regdata[mcman_sio2packet.in_dma.count] = 0; + mcman_sio2packet.out_dma.count = mcman_sio2packet.in_dma.count; + return; + } + + regdata = (((port & 1) + 2) & 3) | 0x70; + regdata |= mcman_cmdtable[(cmd << 1) + 1] << 18; + regdata |= mcman_cmdtable[(cmd << 1) + 1] << 8; + + mcman_sio2packet.regdata[mcman_sio2packet.in_dma.count] = regdata; + + pos = ((mcman_sio2packet.in_dma.count + (mcman_sio2packet.in_dma.count << 3)) << 4); + + mcman_sio2packet.in_dma.count++; + + p = mcman_sio2packet.in_dma.addr + pos; + p[0] = 0x81; + p[1] = mcman_cmdtable[cmd << 1]; + + if (((cmd - 1) >= 16) || ((cmd - 1) < 0)) + return; + + sio2packet_add_func = (void*)sio2packet_add_funcs_array[(cmd - 1)]; + (sio2packet_add_func)(port, slot, cmd, buf, pos); // call to the needed child func + } +} + +//---- +// sio2packet child funcs + +static void sio2packet_add_wdma_u32(int port, int slot, int cmd, u8 *buf, int pos) +{ + u8 *p = mcman_sio2packet.in_dma.addr + pos; + p[2] = buf[0]; + p[3] = buf[1]; + p[4] = buf[2]; + p[5] = buf[3]; + p[6] = mcman_calcEDC(&p[2], 4); +} + +//-- + +static void sio2packet_add_pagedata_out(int port, int slot, int cmd, u8 *buf, int pos) +{ + // used for sio2 command 0x81 0x43 to read page data + u8 *p = mcman_sio2packet.in_dma.addr + pos; + p[2] = 128; +} + +//-- + +static void sio2packet_add_pagedata_in(int port, int slot, int cmd, u8 *buf, int pos) +{ + // used for sio2 command 0x81 0x42 to write page data + register int i; + u8 *p = mcman_sio2packet.in_dma.addr + pos; + p[2] = 128; + + for (i=0; i<128; i++) + p[3 + i] = buf[i]; + + p[3 + 128] = mcman_calcEDC(&buf[0], 128); +} + +//-- + +static void sio2packet_add_ecc_in(int port, int slot, int cmd, u8 *buf, int pos) +{ + // used for sio2 command 0x81 0x42 to write page ecc + register u32 regdata; + int i; + u8 *p = mcman_sio2packet.in_dma.addr + pos; + + p[2] = mcman_sparesize(port, slot); + + for (i=0; i<(p[2] & 0xff); i++) + p[3 + i] = buf[i]; + + p[3 + p[2]] = mcman_calcEDC(&buf[0], p[2]); + + regdata = (p[2] + mcman_cmdtable[(cmd << 1) + 1]) << 18; + regdata |= mcman_sio2packet.regdata[mcman_sio2packet.in_dma.count-1] & 0xf803ffff; + regdata &= 0xfffe00ff; + regdata |= (p[2] + mcman_cmdtable[(cmd << 1) + 1]) << 8; + + mcman_sio2packet.regdata[mcman_sio2packet.in_dma.count-1] = regdata; +} + +//-- + +static void sio2packet_add_ecc_out(int port, int slot, int cmd, u8 *buf, int pos) +{ + // used for sio2 command 0x81 0x43 to read page ecc + register u32 regdata; + u8 *p = mcman_sio2packet.in_dma.addr + pos; + + p[2] = mcman_sparesize(port, slot); + + regdata = (p[2] + mcman_cmdtable[(cmd << 1) + 1]) << 18; + regdata |= mcman_sio2packet.regdata[mcman_sio2packet.in_dma.count-1] & 0xf803ffff; + regdata &= 0xfffe00ff; + regdata |= (p[2] + mcman_cmdtable[(cmd << 1) + 1]) << 8; + + mcman_sio2packet.regdata[mcman_sio2packet.in_dma.count-1] = regdata; +} + +//-- + +static void sio2packet_add_wdma_5a(int port, int slot, int cmd, u8 *buf, int pos) +{ + // used for sio2 command 0x81 0x27 to set a termination code + u8 *p = mcman_sio2packet.in_dma.addr + pos; + p[2] = 0x5a; +} + +//-- + +static void sio2packet_add_wdma_00(int port, int slot, int cmd, u8 *buf, int pos) +{ + u8 *p = mcman_sio2packet.in_dma.addr + pos; + p[2] = 0x00; + +} + +//-- + +static void sio2packet_add_wdma_u8(int port, int slot, int cmd, u8 *buf, int pos) +{ + u8 *p = mcman_sio2packet.in_dma.addr + pos; + p[2] = buf[0]; +} + +//-- + +static void sio2packet_add_do_nothing(int port, int slot, int cmd, u8 *buf, int pos) +{ + // do nothing +} + +//-------------------------------------------------------------- +int mcsio2_transfer(int port, int slot, sio2_transfer_data_t *sio2data) +{ + register int r; + +#ifdef DEBUG + u8 *p = (u8 *)(sio2data->in_dma.addr); + if (p) + DPRINTF("mcsio2_transfer port%d slot%d cmd = %02x %02x %02x ", port, slot, p[0], p[1], p[2]); + else { + p = (u8 *)(sio2data->in); + DPRINTF("mcsio2_transfer for secrman port%d slot%d cmd = %02x %02x %02x ", port, slot, p[0], p[1], p[2]); + } +#endif + + // SIO2 transfer for MCMAN + psio2_mc_transfer_init(); + r = psio2_transfer(sio2data); + + DPRINTF("returns %d\n", r); + + return r; +} + +//-------------------------------------------------------------- +int mcsio2_transfer2(int port, int slot, sio2_transfer_data_t *sio2data) +{ + // SIO2 transfer for XMCMAN + register int r; + s32 port_ctrl[8]; + + DPRINTF("mcsio2_transfer2 port%d slot%d\n", port, slot); + + port_ctrl[0] = -1; + port_ctrl[1] = -1; + port_ctrl[2] = -1; + port_ctrl[3] = -1; + + port_ctrl[(port & 1) + 2] = slot; + + psio2_mc_transfer_init(); + psio2_mtap_change_slot(port_ctrl); + r = psio2_transfer(sio2data); + psio2_transfer_reset(); + + DPRINTF("mcsio2_transfer2 returns %d\n", r); + + return r; +} +#endif + +//-------------------------------------------------------------- +void mcman_initPS2com(void) +{ +#ifndef BUILDING_XFROMMAN + mcman_wmemset((void *)&mcman_sio2packet, sizeof (mcman_sio2packet), 0); + + mcman_sio2packet.port_ctrl1[2] = 0xff020405; + mcman_sio2packet.port_ctrl1[3] = 0xff020405; + mcman_sio2packet.port_ctrl2[2] = 0x0005ffff & 0xfcffffff; + mcman_sio2packet.port_ctrl2[3] = 0x0005ffff & 0xfcffffff; + + mcman_sio2packet.in_dma.addr = &mcman_wdmabufs; + mcman_sio2packet.in_dma.size = 0x24; + + mcman_sio2packet.out_dma.addr = &mcman_rdmabufs; + mcman_sio2packet.out_dma.size = 0x24; + + DPRINTF("mcman_initPS2com registering secrman_mc_command callback\n"); + SecrSetMcCommandHandler((void *)secrman_mc_command); + + DPRINTF("mcman_initPS2com registering mcman_getcnum callback\n"); + + SecrSetMcDevIDHandler((void *)mcman_getcnum); +#endif +#ifdef BUILDING_XFROMMAN + flash_detect(); + flash_get_info(&dev9_flash_info); +#endif +} + +//-------------------------------------------------------------- +void mcman_initPS1PDAcom(void) +{ +#ifndef BUILDING_XFROMMAN + memset((void *)&mcman_sio2packet_PS1PDA, 0, sizeof (mcman_sio2packet_PS1PDA)); + + mcman_sio2packet_PS1PDA.port_ctrl1[0] = 0xffc00505; + mcman_sio2packet_PS1PDA.port_ctrl1[1] = 0xffc00505; + mcman_sio2packet_PS1PDA.port_ctrl1[2] = 0xffc00505; + mcman_sio2packet_PS1PDA.port_ctrl1[3] = 0xffc00505; + + mcman_sio2packet_PS1PDA.port_ctrl2[0] = 0x000201f4 & 0xfcffffff; + mcman_sio2packet_PS1PDA.port_ctrl2[1] = 0x000201f4 & 0xfcffffff; + mcman_sio2packet_PS1PDA.port_ctrl2[2] = 0x000201f4 & 0xfcffffff; + mcman_sio2packet_PS1PDA.port_ctrl2[3] = 0x000201f4 & 0xfcffffff; + + mcman_sio2packet_PS1PDA.in = (u8 *)&mcman_sio2inbufs_PS1PDA; + mcman_sio2packet_PS1PDA.out = (u8 *)&mcman_sio2outbufs_PS1PDA; +#endif +} + +//-------------------------------------------------------------- +int secrman_mc_command(int port, int slot, sio2_transfer_data_t *sio2data) +{ + register int r; + + DPRINTF("secrman_mc_command port%d slot%d\n", port, slot); + +#ifndef BUILDING_XFROMMAN + r = mcman_sio2transfer(port, slot, sio2data); +#endif +#ifdef BUILDING_XFROMMAN + r = 0; +#endif + + return r; +} + +//-------------------------------------------------------------- +int mcman_cardchanged(int port, int slot) +{ +#ifndef BUILDING_XFROMMAN + register int retries; + u8 *p = mcman_sio2packet.out_dma.addr; + + DPRINTF("mcman_cardchanged sio2cmd port%d slot%d\n", port, slot); + + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0, NULL); + sio2packet_add(port, slot, 0xfffffffe, NULL); + + retries = 0; + do { + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if (((mcman_sio2packet.stat6c & 0xF000) == 0x1000) && (p[3] != 0x66)) + break; + + } while (++retries < 5); + + if (retries >= 5) { + DPRINTF("mcman_cardchanged sio2cmd card changed!\n"); + return sceMcResChangedCard; + } + + DPRINTF("mcman_cardchanged sio2cmd succeeded\n"); +#endif + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_eraseblock(int port, int slot, int block, void **pagebuf, void *eccbuf) +{ + register int retries, size, ecc_offset; + int page; +#ifndef BUILDING_XFROMMAN + u8 *p = mcman_sio2packet.out_dma.addr; +#endif + void *p_ecc; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + page = block * mcdi->blocksize; + +#ifndef BUILDING_XFROMMAN + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0x02, (u8 *)&page); + sio2packet_add(port, slot, 0x0d, NULL); + sio2packet_add(port, slot, 0xfffffffe, NULL); +#endif + + retries = 0; + do { +#ifndef BUILDING_XFROMMAN + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if (((mcman_sio2packet.stat6c & 0xF000) != 0x1000) || (p[8] != 0x5a)) + continue; + + if (p[0x93] == p[8]) + break; +#endif +#ifdef BUILDING_XFROMMAN + if (!flash_page_erase(&dev9_flash_info, page)) + break; +#endif + } while (++retries < 5); + + if (retries >= 5) + return sceMcResChangedCard; + + if (pagebuf && eccbuf) { // This part leave the first ecc byte of each block page in eccbuf + mcman_wmemset(eccbuf, 32, 0); + + page = 0; + while (page < mcdi->blocksize) { + ecc_offset = page * mcdi->pagesize; + if (ecc_offset < 0) + ecc_offset += 0x1f; + ecc_offset = ecc_offset >> 5; + p_ecc = (void *)(eccbuf + ecc_offset); + size = 0; + while (size < mcdi->pagesize) { + if (*pagebuf) + McDataChecksum((void *)(*pagebuf + size), p_ecc); + size += 128; + p_ecc += 3; + } + pagebuf++; + page++; + } + } + +#ifndef BUILDING_XFROMMAN + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0x1, NULL); + sio2packet_add(port, slot, 0xfffffffe, NULL); + + retries = 0; + do { + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if (((mcman_sio2packet.stat6c & 0xF000) != 0x1000)) + continue; + + if (p[3] == 0x5a) + return sceMcResSucceed; + } while (++retries < 100); + + if (p[3] == 0x66) + return sceMcResFailReplace; +#endif + + return sceMcResNoFormat; +} + +//-------------------------------------------------------------- +int McWritePage(int port, int slot, int page, void *pagebuf, void *eccbuf) // Export #19 +{ + register int retries; +#ifndef BUILDING_XFROMMAN + register int index, count; + u8 *p_pagebuf = (u8 *)pagebuf; + u8 *p = mcman_sio2packet.out_dma.addr; +#endif + +#ifdef BUILDING_XFROMMAN + char page_buf[528]; + memcpy(page_buf, pagebuf, 512); + memcpy(page_buf + 512, eccbuf, 16); +#endif + +#ifndef BUILDING_XFROMMAN + count = (mcman_devinfos[port][slot].pagesize + 127) >> 7; +#endif + + retries = 0; + + do { +#ifndef BUILDING_XFROMMAN + if (retries > 0) + mcman_cardchanged(port, slot); + + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0x03, (u8 *)&page); + + index = 0; + while (index < count) { + sio2packet_add(port, slot, 0x0a, (u8 *)&p_pagebuf[index << 7]); + index++; + } + + if (mcman_devinfos[port][slot].cardflags & CF_USE_ECC) { + // if memcard have ECC support + sio2packet_add(port, slot, 0x0e, eccbuf); + } + sio2packet_add(port, slot, 0xfffffffe, NULL); + + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if (((mcman_sio2packet.stat6c & 0xF000) != 0x1000) || (p[8] != 0x5a)) + continue; + + index = 0; + while (index < count) { + if (p[0x94 + 128 + 1 + ((index + (index << 3)) << 4)] != 0x5a) + break; + index++; + } + + if (index < count) + continue; + + if (mcman_devinfos[port][slot].cardflags & CF_USE_ECC) { + // if memcard have ECC support + index++; + if (p[5 + ((index + (index << 3)) << 4) + mcman_sparesize(port, slot)] != 0x5a) + continue; + } + + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0x0c, NULL); + sio2packet_add(port, slot, 0xfffffffe, NULL); + + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if (((mcman_sio2packet.stat6c & 0xF000) != 0x1000) || (p[3] != 0x5a)) + continue; +#endif + +#ifdef BUILDING_XFROMMAN + if (flash_page_write(&dev9_flash_info, page, page_buf)) + continue; +#endif + return sceMcResSucceed; + + } while (++retries < 5); + +#ifndef BUILDING_XFROMMAN + if (p[3] == 0x66) + return sceMcResFailReplace; + + return sceMcResNoFormat; +#endif +#ifdef BUILDING_XFROMMAN + return sceMcResFailReplace; +#endif +} + +//-------------------------------------------------------------- +int mcman_readpage(int port, int slot, int page, void *buf, void *eccbuf) +{ +#ifndef BUILDING_XFROMMAN + register int index, count, retries, r, i; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + u8 *pbuf = (u8 *)buf; + u8 *pecc = (u8 *)eccbuf; + u8 *p = mcman_sio2packet.out_dma.addr; + + count = (mcdi->pagesize + 127) >> 7; + + retries = 0; + + do { + if (retries > 0) + mcman_cardchanged(port, slot); + + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0x04, (u8 *)&page); + + if (count > 0) { + index = 0; + while (index < count) { + sio2packet_add(port, slot, 0x0b, NULL); + index++; + } + } + + if (mcdi->cardflags & CF_USE_ECC) // if memcard have ECC support + sio2packet_add(port, slot, 0x0f, NULL); + + sio2packet_add(port, slot, 0x0c, NULL); + sio2packet_add(port, slot, 0xfffffffe, NULL); + + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if (((mcman_sio2packet.stat6c & 0xF000) != 0x1000) + || (p[8] != 0x5a) + || (p[0x94 + 0x2cf] != 0x5a)) + continue; + + if (count > 0) { + index = 0; + while (index < count) { + // checking EDC + r = mcman_calcEDC(&p[0x94 + ((index + (index << 3)) << 4)], 128) & 0xFF; + if (r != p[0x94 + 128 + ((index + (index << 3)) << 4)]) + break; + index++; + } + + if (index < count) + continue; + + index = 0; + while (index < count) { + for (i=0; i<128; i++) + pbuf[(index << 7) + i] = p[0x94 + ((index + (index << 3)) << 4) + i]; + index++; + } + } + + memcpy(pecc, &p[0x94 + ((count + (count << 3)) << 4)] , mcman_sparesize(port, slot)); + break; + + } while (++retries < 5); + + if (retries < 5) + return sceMcResSucceed; +#endif + +#ifdef BUILDING_XFROMMAN + // No retry logic here. + char page_buf[528]; + if (!flash_page_read(&dev9_flash_info, page, 1, page_buf)) + { + if (buf) + { + memcpy(buf, page_buf, 512); + } + if (eccbuf) + { + memcpy(eccbuf, page_buf + 512, 16); + } + return sceMcResSucceed; + } +#endif + return sceMcResChangedCard; +} + +//-------------------------------------------------------------- +int McGetCardSpec(int port, int slot, s16 *pagesize, u16 *blocksize, int *cardsize, u8 *flags) +{ +#ifndef BUILDING_XFROMMAN + register int retries, r; + u8 *p = mcman_sio2packet.out_dma.addr; + + DPRINTF("McGetCardSpec sio2cmd port%d slot%d\n", port, slot); + + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0x07, NULL); + sio2packet_add(port, slot, 0xfffffffe, NULL); + + retries = 0; + + do { + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if (((mcman_sio2packet.stat6c & 0xF000) == 0x1000) && (p[12] == 0x5a)) { + // checking EDC + r = mcman_calcEDC(&p[3], 8) & 0xFF; + if (r == p[11]) + break; + } + } while (++retries < 5); + + if (retries >= 5) + return sceMcResChangedCard; + + *pagesize = (p[4] << 8) + p[3]; + *blocksize = (p[6] << 8) + p[5]; + *cardsize = (p[8] << 8) + p[7] + (p[9] << 16) + (p[10] << 24); + *flags = p[2]; +#endif +#ifdef BUILDING_XFROMMAN + flash_get_info(&dev9_flash_info); + *pagesize = dev9_flash_info.page_bytes; + *blocksize = dev9_flash_info.block_pages; + *cardsize = dev9_flash_info.blocks * dev9_flash_info.block_pages; + *flags = 43; + if ( *pagesize == 512 ) + *flags = 42; + *pagesize = 512; +#endif + + DPRINTF("McGetCardSpec sio2cmd pagesize=%d blocksize=%u cardsize=%d flags%x\n", *pagesize, *blocksize, *cardsize, *flags); + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_resetauth(int port, int slot) +{ +#ifndef BUILDING_XFROMMAN + register int retries; + + DPRINTF("mcman_resetauth sio2cmd port%d slot%d\n", port, slot); + + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0x11, NULL); + sio2packet_add(port, slot, 0xfffffffe, NULL); + + retries = 0; + + do { + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if ((mcman_sio2packet.stat6c & 0xF000) == 0x1000) + break; + + } while (++retries < 5); + + if (retries >= 5) { + DPRINTF("mcman_resetauth sio2cmd card changed!\n"); + + return sceMcResChangedCard; + } + + DPRINTF("mcman_resetauth sio2cmd succeeded\n"); +#endif + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_probePS2Card2(int port, int slot) +{ +#ifndef BUILDING_XFROMMAN + register int retries, r; + u8 *p = mcman_sio2packet.out_dma.addr; + + DPRINTF("mcman_probePS2Card2 sio2cmd port%d slot%d\n", port, slot); + + retries = 0; + do { + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0x09, NULL); + sio2packet_add(port, slot, 0xfffffffe, NULL); + + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if (((mcman_sio2packet.stat6c & 0xF000) == 0x1000) && (p[4] != 0x66)) + break; + } while (++retries < 5); + + if (retries >= 5) + return sceMcResFailDetect; + + if (p[3] == 0x5a) { + r = McGetFormat(port, slot); + if (r > 0) { + DPRINTF("mcman_probePS2Card2 succeeded\n"); + + return sceMcResSucceed; + } + + r = McGetFormat(port, slot); + if (r < 0) { + DPRINTF("mcman_probePS2Card2 sio2cmd failed (no format)\n"); + + return sceMcResNoFormat; + } + } + + DPRINTF("mcman_probePS2Card2 sio2cmd failed (mc detection failed)\n"); +#endif +#ifdef BUILDING_XFROMMAN + if (!McGetFormat(port, slot)) + { + mcman_probePS2Card(port, slot); + } + if (McGetFormat(port, slot) > 0) + return sceMcResSucceed; + if (McGetFormat(port, slot) < 0) + return sceMcResNoFormat; +#endif + + return sceMcResFailDetect2; +} + +//-------------------------------------------------------------- +int mcman_probePS2Card(int port, int slot) //2 +{ + register int r; + register MCDevInfo *mcdi; +#ifndef BUILDING_XFROMMAN + register int retries; + u8 *p = mcman_sio2packet.out_dma.addr; +#endif + + DPRINTF("mcman_probePS2Card sio2cmd port%d slot%d\n", port, slot); + + r = mcman_cardchanged(port, slot); + if (r == sceMcResSucceed) { + r = McGetFormat(port, slot); + if (r != 0) { + DPRINTF("mcman_probePS2Card sio2cmd succeeded\n"); + + return sceMcResSucceed; + } + } + +#ifndef BUILDING_XFROMMAN + if (mcman_resetauth(port, slot) != sceMcResSucceed) { + DPRINTF("mcman_probePS2Card sio2cmd failed (auth reset failed)\n"); + + return sceMcResFailResetAuth; + } + + if (SecrAuthCard(port + 2, slot, mcman_getcnum(port, slot)) == 0) { + DPRINTF("mcman_probePS2Card sio2cmd failed (auth failed)\n"); + + return sceMcResFailAuth; + } + + retries = 0; + do { + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0x09, NULL); + sio2packet_add(port, slot, 0xfffffffe, NULL); + + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if (((mcman_sio2packet.stat6c & 0xF000) == 0x1000) && (p[4] != 0x66)) + break; + } while (++retries < 5); + + if (retries >= 5) { + DPRINTF("mcman_probePS2Card sio2cmd failed (mc detection failed)\n"); + return sceMcResFailDetect; + } +#endif + + mcman_clearcache(port, slot); + +#ifndef BUILDING_XFROMMAN + sio2packet_add(port, slot, 0xffffffff, NULL); + sio2packet_add(port, slot, 0x08, NULL); + sio2packet_add(port, slot, 0xfffffffe, NULL); + + retries = 0; + do { + mcman_sio2transfer(port, slot, &mcman_sio2packet); + + if ((mcman_sio2packet.stat6c & 0xF000) != 0x1000) + continue; + + if (p[4] == 0x5a) + break; + } while (++retries < 5); + + if (retries >= 5) { + DPRINTF("mcman_probePS2Card sio2cmd failed (mc detection failed)\n"); + + return sceMcResFailDetect2; + } +#endif + + r = mcman_setdevinfos(port, slot); + if (r == 0) { + DPRINTF("mcman_probePS2Card sio2cmd card changed!\n"); + return sceMcResChangedCard; + } + if (r != sceMcResNoFormat) { + DPRINTF("mcman_probePS2Card sio2cmd failed (mc detection failed)\n"); + return sceMcResFailDetect2; + } + + mcdi = &mcman_devinfos[port][slot]; + mcdi->cardform = r; + + DPRINTF("mcman_probePS2Card sio2cmd succeeded\n"); + + return r; +} + +//-------------------------------------------------------------- +int mcman_probePS1Card2(int port, int slot) +{ +#ifndef BUILDING_XFROMMAN + register int retries; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + DPRINTF("mcman_probePS1Card2 port%d slot%d\n", port, slot); + + mcman_sio2packet_PS1PDA.regdata[0] = 0; + mcman_sio2packet_PS1PDA.regdata[0] = (((port & 1) + 2)) | 0x000c0340; + mcman_sio2packet_PS1PDA.in_size = 3; + mcman_sio2packet_PS1PDA.out_size = 3; + + mcman_sio2packet_PS1PDA.regdata[1] = 0; + mcman_sio2inbufs_PS1PDA[0] = 0x81; + mcman_sio2inbufs_PS1PDA[1] = 0x52; + + retries = 0; + do { + mcman_timercount = (u32)(GetTimerCounter(timer_ID) - mcman_timercount); + + u32 hi, lo; + long_multiply(mcman_timercount, 0x3e0f83e1, &hi, &lo); + + if ((u32)((hi >> 3) < mcman_timerthick)) + DelayThread(mcman_timerthick - (hi >> 3)); + + mcman_sio2transfer(port, slot, &mcman_sio2packet_PS1PDA); + + mcman_timercount = GetTimerCounter(timer_ID); + mcman_timerthick = 0; + + if (((mcman_sio2packet_PS1PDA.stat6c & 0xf000) == 0x1000) \ + && (mcman_sio2outbufs_PS1PDA[2] == 0x5a)) { + break; + } + } while (++retries < 5); + + if (retries >= 5) + return -12; + + if (mcman_sio2outbufs_PS1PDA[1] == 0) { + if (mcdi->cardform > 0) + return sceMcResSucceed; + if (mcdi->cardform < 0) + return sceMcResNoFormat; + } + else if (mcman_sio2outbufs_PS1PDA[1] != 8) { + return -14; + } +#endif + + return -13; +} + +//-------------------------------------------------------------- +int mcman_probePS1Card(int port, int slot) +{ +#ifndef BUILDING_XFROMMAN + register int i, r, retries; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + u32 *p; + + DPRINTF("mcman_probePS1Card port%d slot%d\n", port, slot); + + mcman_sio2packet_PS1PDA.regdata[0] = 0; + mcman_sio2packet_PS1PDA.regdata[0] = (((port & 1) + 2)) | 0x000c0340; + mcman_sio2packet_PS1PDA.in_size = 3; + mcman_sio2packet_PS1PDA.out_size = 3; + + mcman_sio2packet_PS1PDA.regdata[1] = 0; + mcman_sio2inbufs_PS1PDA[0] = 0x81; + mcman_sio2inbufs_PS1PDA[1] = 0x52; + + retries = 0; + do { + mcman_timercount = (u32)(GetTimerCounter(timer_ID) - mcman_timercount); + + u32 hi, lo; + long_multiply(mcman_timercount, 0x3e0f83e1, &hi, &lo); + + if ((u32)((hi >> 3) < mcman_timerthick)) + DelayThread(mcman_timerthick - (hi >> 3)); + + mcman_sio2transfer(port, slot, &mcman_sio2packet_PS1PDA); + + mcman_timercount = GetTimerCounter(timer_ID); + mcman_timerthick = 0; + + if (((mcman_sio2packet_PS1PDA.stat6c & 0xf000) == 0x1000) \ + && (mcman_sio2outbufs_PS1PDA[2] == 0x5a)) { + break; + } + } while (++retries < 5); + + if (retries >= 5) + return -11; + + if (mcman_sio2outbufs_PS1PDA[1] == 0) { + if (mcdi->cardform != 0) + return sceMcResSucceed; + } + else if (mcman_sio2outbufs_PS1PDA[1] != 8) { + return -12; + } + + mcman_clearcache(port, slot); + + p = (u32 *)&mcman_sio2outbufs_PS1PDA[124]; + for (i = 31; i >= 0; i--) + *p-- = 0; + + r = McWritePS1PDACard(port, slot, 63, mcman_sio2outbufs_PS1PDA); + if (r < 0) + return -13; + + r = mcman_setPS1devinfos(port, slot); + if (r == 0) + return sceMcResChangedCard; + + mcdi->cardform = r; + + return r; +#endif +#ifdef BUILDING_XFROMMAN + return sceMcResSucceed; +#endif +} + +//-------------------------------------------------------------- +int mcman_probePDACard(int port, int slot) +{ +#ifndef BUILDING_XFROMMAN + register int retries; + + DPRINTF("mcman_probePDACard port%d slot%d\n", port, slot); + + mcman_sio2packet_PS1PDA.regdata[0] = 0; + mcman_sio2packet_PS1PDA.regdata[0] = (port & 3) | 0x00140540; + mcman_sio2packet_PS1PDA.in_size = 5; + mcman_sio2packet_PS1PDA.out_size = 5; + + mcman_sio2packet_PS1PDA.regdata[1] = 0; + mcman_sio2inbufs_PS1PDA[0] = 0x81; + mcman_sio2inbufs_PS1PDA[1] = 0x58; + + retries = 0; + do { + mcman_sio2transfer(port, slot, &mcman_sio2packet_PS1PDA); + + if ((mcman_sio2packet_PS1PDA.stat6c & 0xf000) == 0x1000) + break; + + } while (++retries < 5); + + if (retries >= 5) + return -11; +#endif + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int McWritePS1PDACard(int port, int slot, int page, void *buf) // Export #30 +{ +#ifndef BUILDING_XFROMMAN + register int i, retries; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + u8 *p; + + //DPRINTF("McWritePS1PDACard port%d slot%d page %x\n", port, slot, page); + + mcman_sio2packet_PS1PDA.regdata[0] = 0; + mcman_sio2packet_PS1PDA.regdata[0] = (((port & 1) + 2) & 3) | 0x02288a40; + mcman_sio2packet_PS1PDA.in_size = 138; + mcman_sio2packet_PS1PDA.out_size = 138; + mcman_sio2packet_PS1PDA.regdata[1] = 0; + + for (i = 0; i < 20; i++) { + if (mcdi->bad_block_list[i] == page) + page += 36; + } + + mcman_sio2inbufs_PS1PDA[0] = 0x81; + mcman_sio2inbufs_PS1PDA[1] = 0x57; + mcman_sio2inbufs_PS1PDA[4] = (u8)(page >> 8); + mcman_sio2inbufs_PS1PDA[5] = (u8)page; + + p = (u8 *)buf; + for (i = 0; i < 128; i++) + mcman_sio2inbufs_PS1PDA[6 + i] = p[i]; + + mcman_sio2inbufs_PS1PDA[4 + 130] = mcman_calcEDC(&mcman_sio2inbufs_PS1PDA[4], 130); + + retries = 0; + do { + mcman_timercount = (u32)(GetTimerCounter(timer_ID) - mcman_timercount); + + u32 hi, lo; + long_multiply(mcman_timercount, 0x3e0f83e1, &hi, &lo); + + if ((u32)((hi >> 3) < mcman_timerthick)) + DelayThread(mcman_timerthick - (hi >> 3)); + + mcman_sio2transfer(port, slot, &mcman_sio2packet_PS1PDA); + + mcman_timercount = GetTimerCounter(timer_ID); + mcman_timerthick = 20000; + + if (((mcman_sio2packet_PS1PDA.stat6c & 0xf000) == 0x1000) \ + && (mcman_sio2outbufs_PS1PDA[2] == 0x5a) \ + && (mcman_sio2outbufs_PS1PDA[3] == 0x5d) \ + && (mcman_sio2outbufs_PS1PDA[137] == 0x47)) { + break; + } + } while (++retries < 5); + + if (retries >= 5) + return sceMcResNoEntry; + + if ((mcman_sio2outbufs_PS1PDA[1] != 0) && (mcman_sio2outbufs_PS1PDA[1] != 8)) + return sceMcResFullDevice; +#endif + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int McReadPS1PDACard(int port, int slot, int page, void *buf) // Export #29 +{ +#ifndef BUILDING_XFROMMAN + register int i, retries; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + u8 *p; + + //DPRINTF("McReadPS1PDACard port%d slot%d page %x\n", port, slot, page); + + mcman_sio2packet_PS1PDA.regdata[0] = 0; + mcman_sio2packet_PS1PDA.regdata[0] = (((port & 1) + 2) & 3) | 0x02308c40; + mcman_sio2packet_PS1PDA.in_size = 140; + mcman_sio2packet_PS1PDA.out_size = 140; + mcman_sio2packet_PS1PDA.regdata[1] = 0; + + for (i = 0; i < 20; i++) { + if (mcdi->bad_block_list[i] == page) + page += 36; + } + + mcman_sio2inbufs_PS1PDA[0] = 0x81; + mcman_sio2inbufs_PS1PDA[1] = 0x52; + mcman_sio2inbufs_PS1PDA[4] = (u8)(page >> 8); + mcman_sio2inbufs_PS1PDA[5] = (u8)page; + + retries = 0; + do { + mcman_timercount = (u32)(GetTimerCounter(timer_ID) - mcman_timercount); + + u32 hi, lo; + long_multiply(mcman_timercount, 0x3e0f83e1, &hi, &lo); + + if ((u32)((hi >> 3) < mcman_timerthick)) + DelayThread(mcman_timerthick - (hi >> 3)); + + mcman_sio2transfer(port, slot, &mcman_sio2packet_PS1PDA); + + mcman_timercount = GetTimerCounter(timer_ID); + mcman_timerthick = 10000; + + if (((mcman_sio2packet_PS1PDA.stat6c & 0xf000) == 0x1000) \ + && (mcman_sio2outbufs_PS1PDA[2] == 0x5a) \ + && (mcman_sio2outbufs_PS1PDA[3] == 0x5d) \ + && (mcman_sio2outbufs_PS1PDA[4] == 0x00) \ + && (mcman_sio2outbufs_PS1PDA[6] == 0x5c) \ + && (mcman_sio2outbufs_PS1PDA[7] == 0x5d) \ + && (mcman_sio2outbufs_PS1PDA[139] == 0x47)) { + + if (mcman_sio2outbufs_PS1PDA[138] == (mcman_calcEDC(&mcman_sio2outbufs_PS1PDA[8], 130) & 0xff)) + break; + } + } while (++retries < 5); + + if (retries >= 5) + return sceMcResNoEntry; + + p = (u8 *)buf; + for (i = 0; i < 128; i++) + p[i] = mcman_sio2outbufs_PS1PDA[10 + i]; + + if ((mcman_sio2outbufs_PS1PDA[1] != 0) && (mcman_sio2outbufs_PS1PDA[1] != 8)) + return sceMcResDeniedPermit; +#endif + + return sceMcResSucceed; +} + + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/ps1mc_fio.c b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/ps1mc_fio.c new file mode 100644 index 0000000..fb4fb2d --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/ps1mc_fio.c @@ -0,0 +1,710 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 jimmikaelkael +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include +#include "mcman-internal.h" + +extern union mcman_PS1PDApagebuf mcman_PS1PDApagebuf; + +extern int sio2man_type; + +extern MC_FHANDLE mcman_fdhandles[MAX_FDHANDLES]; +extern MCDevInfo mcman_devinfos[4][MCMAN_MAXSLOT]; + +static int mcman_PS1curcluster; +static char mcman_PS1curdir[64]; + +//-------------------------------------------------------------- +int mcman_format1(int port, int slot) +{ + register int r, i; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + DPRINTF("mcman_format1 port%d slot%d\n", port, slot); + + mcman_invhandles(port, slot); + + for (i = 0; i < 56; i++) { + r = mcman_PS1pagetest(port, slot, i); + if (r == 0) + return sceMcResNoFormat; + if (r != 1) + return -41; + } + + memset(&mcman_PS1PDApagebuf, 0, 128); + + mcman_PS1PDApagebuf.word[0] = 0xa0; + mcman_PS1PDApagebuf.half[2] = 0xffff; + + mcman_PS1PDApagebuf.byte[127] = mcman_calcEDC(&mcman_PS1PDApagebuf, 127); + + for (i = 1; i < 15; i++) { + r = McWritePS1PDACard(port, slot, i, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return -42; + } + + memset(&mcman_PS1PDApagebuf, 0, 128); + + mcman_PS1PDApagebuf.word[0] = 0xffffffff; + + for (i = 0; i < 20; i++) { + mcman_PS1PDApagebuf.word[0] = mcdi->bad_block_list[i]; + mcman_PS1PDApagebuf.byte[127] = mcman_calcEDC(&mcman_PS1PDApagebuf, 127); + + r = McWritePS1PDACard(port, slot, i + 16, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return -43; + } + + mcman_wmemset(&mcman_PS1PDApagebuf, 128, 0); + + mcman_PS1PDApagebuf.byte[0] = 0x4d; + mcman_PS1PDApagebuf.byte[1] = 0x43; + mcman_PS1PDApagebuf.byte[127] = 0x0e; + + r = McWritePS1PDACard(port, slot, 0, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return -44; + + mcdi->cardform = 1; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_open1(int port, int slot, char *filename, int flags) +{ + register int r, i, fd = 0, cluster, temp; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + McFsEntryPS1 *fse; //sp18 + McCacheEntry *mce; + char *p = filename; + + DPRINTF("mcman_open1 port%d slot%d filename %s flags %x\n", port, slot, filename, flags); + + if ((flags & sceMcFileCreateFile) != 0) + flags |= sceMcFileAttrWriteable; + + for (fd = 0; fd < MAX_FDHANDLES; fd++) { + fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + if (fh->status == 0) + break; + } + + if (fd == MAX_FDHANDLES) + return -7; + + mcman_wmemset((void *)fh, sizeof (MC_FHANDLE), 0); + + fh->port = port; + fh->slot = slot; + + if (*p == '/') + p++; + + if ((*p == 0) || ((*p == '.') && (p[1] == 0))) { + fh->filesize = 15; + fh->drdflag = 1; + fh->status = 1; + return fd; + } + + r = mcman_getPS1direntry(port, slot, p, &fse, 1); + if ((fse->mode & 0xf0) == 0xa0) + r = -4; + + fh->freeclink = r; + + if (r >= 0) { + if (fse->field_7d == 1) + fh->filesize = fse->field_38; + else + fh->filesize = fse->length; + } + else + fh->filesize = 0; + + fh->rdflag = flags & sceMcFileAttrReadable; + fh->wrflag = flags & sceMcFileAttrWriteable; + fh->unknown1 = 0; + + if ((flags & sceMcFileCreateFile) == 0) { + if (r < 0) + return sceMcResNoEntry; + + fh->status = 1; + return fd; + } + + for (i = 0; i < MAX_FDHANDLES; i++) { + if ((mcman_fdhandles[i].status != 0) && \ + (mcman_fdhandles[i].port == port) && (mcman_fdhandles[i].slot == slot) && \ + (mcman_fdhandles[i].freeclink == r) && (fh->wrflag != 0)) + return sceMcResDeniedPermit; + } + + if (r >= 0) { + r = mcman_clearPS1direntry(port, slot, r, 0); + if (r != sceMcResSucceed) + return r; + } + + cluster = -1; + for (i = 0; i < 15; i++) { + r = mcman_readdirentryPS1(port, slot, i, &fse); + if (r != sceMcResSucceed) + return r; + + if ((fse->mode & 0xf0) == 0xa0) { + if (cluster < 0) + cluster = i; + + if (fse->mode != 0xa0) { + + mcman_wmemset((void *)fse, sizeof(McFsEntryPS1), 0); + fse->mode = 0xa0; + fse->linked_block = -1; + fse->edc = mcman_calcEDC((void *)fse, 127); + + mce = mcman_get1stcacheEntp(); + + if ((i + 1) < 0) + temp = i + 8; + else + temp = i + 1; + + mce->wr_flag |= 1 << ((i + 1) - ((temp >> 3) << 3)); + } + } + } + + r = McFlushCache(port, slot); + if (r != sceMcResSucceed) + return r; + + if (cluster < 0) + return sceMcResFullDevice; + + r = mcman_readdirentryPS1(port, slot, cluster, &fse); + if (r != sceMcResSucceed) + return r; + + mcman_wmemset((void *)fse, sizeof(McFsEntryPS1), 0); + + fse->mode = 0x51; + fse->length = 0; + fse->linked_block = -1; + + strncpy(fse->name, p, 20); + + if ((flags & sceMcFileAttrPDAExec) != 0) + fse->field_7e = 1; + + fse->edc = mcman_calcEDC((void *)fse, 127); + fh->freeclink = cluster; + + mce = mcman_get1stcacheEntp(); + + if ((cluster + 1) < 0) + temp = cluster + 8; + else + temp = cluster + 1; + + mce->wr_flag |= 1 << ((cluster + 1) - ((temp >> 3) << 3)); + + r = McFlushCache(port, slot); + if (r != sceMcResSucceed) + return r; + + fh->unknown2 = 1; + fh->status = 1; + + return fd; +} + +//-------------------------------------------------------------- +int mcman_read1(int fd, void *buffer, int nbyte) +{ + register int r, size, temp, rpos, offset, maxsize; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + McCacheEntry *mce; + u8 *p = (u8 *)buffer; + + if (fh->position >= fh->filesize) + return 0; + + if (nbyte >= (fh->filesize - fh->position)) + nbyte = fh->filesize - fh->position; + + rpos = 0; + if (nbyte) { + do { + if (fh->position < 0) + temp = fh->position + 0x3ff; + else + temp = fh->position; + + offset = (fh->position - ((temp >> 10) << 10)); + maxsize = MCMAN_CLUSTERSIZE - offset; + if (maxsize < nbyte) + size = maxsize; + else + size = nbyte; + + r = mcman_fatRseekPS1(fd); + if (r < 0) + return r; + + r = mcman_readclusterPS1(fh->port, fh->slot, r, &mce); + if (r != sceMcResSucceed) + return r; + + memcpy(&p[rpos], (void *)(mce->cl_data + offset), size); + + rpos += size; + nbyte -= size; + fh->position += size; + + } while (nbyte); + } + + return rpos; +} + +//-------------------------------------------------------------- +int mcman_write1(int fd, void *buffer, int nbyte) +{ + register int r, size, temp, wpos, offset, maxsize; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + McCacheEntry *mce; + u8 *p = (u8 *)buffer; + + if (nbyte) { + if (fh->unknown2 == 0) { + fh->unknown2 = 1; + r = mcman_close1(fd); + if (r != sceMcResSucceed) + return r; + r = McFlushCache(fh->port, fh->slot); + if (r != sceMcResSucceed) + return r; + } + } + + wpos = 0; + if (nbyte) { + + do { + r = mcman_fatRseekPS1(fd); + + if (r == sceMcResFullDevice) { + r = mcman_fatWseekPS1(fd); + if (r == sceMcResFullDevice) + return r; + if (r!= sceMcResSucceed) + return r; + + r = mcman_fatRseekPS1(fd); + } + else { + if (r < 0) + return r; + } + + r = mcman_readclusterPS1(fh->port, fh->slot, r, &mce); + if (r != sceMcResSucceed) + return r; + + if (fh->position < 0) + temp = fh->position + 0x3ff; + else + temp = fh->position; + + offset = fh->position - ((temp >> 10) << 10); + maxsize = MCMAN_CLUSTERSIZE - offset; + if (maxsize < nbyte) + size = maxsize; + else + size = nbyte; + + memcpy((void *)(mce->cl_data + offset), &p[wpos], size); + + mce->wr_flag = -1; + fh->position += size; + if (fh->position >= fh->filesize) + fh->filesize = fh->position; + + nbyte -= size; + wpos += size; + + } while (nbyte); + + } + + mcman_close1(fd); + + return wpos; +} + +//-------------------------------------------------------------- +int mcman_dread1(int fd, io_dirent_t *dirent) +{ + register int r; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + McFsEntryPS1 *fse; + + if (fh->position < fh->filesize) { + do { + r = mcman_readdirentryPS1(fh->port, fh->slot, fh->position, &fse); + if (r != sceMcResSucceed) + return r; + + if (fse->mode == 0x51) + break; + + } while (++fh->position < fh->filesize); + } + + if (fh->position >= fh->filesize) + return 0; + + fh->position++; + mcman_wmemset((void *)dirent, sizeof(io_dirent_t), 0); + + strncpy(dirent->name, fse->name, 20); + dirent->name[20] = 0; + + dirent->stat.mode = 0x101f; + + if (fse->field_7e == 1) + dirent->stat.mode = 0x181f; + + if (fse->field_7d == 1) { + memcpy(dirent->stat.ctime, &fse->created, sizeof(sceMcStDateTime)); + memcpy(dirent->stat.mtime, &fse->modified, sizeof(sceMcStDateTime)); + dirent->stat.size = fse->field_38; + dirent->stat.attr = fse->field_28; + } + else { + dirent->stat.size = fse->length; + } + + return 1; +} + +//-------------------------------------------------------------- +int mcman_getstat1(int port, int slot, char *filename, io_stat_t *stat) +{ + register int r; + McFsEntryPS1 *fse; + + DPRINTF("mcman_getstat1 port%d slot%d filename %s\n", port, slot, filename); + + r = mcman_getPS1direntry(port, slot, filename, &fse, 1); + + if ((fse->mode & 0xf0) == 0xa0) + r = -4; + + if (r < 0) + return sceMcResNoEntry; + + mcman_wmemset(stat, sizeof(io_stat_t), 0); + + stat->mode = 0x1f; + + if (fse->field_7d == 1) { + + if ((fse->field_2c & sceMcFileAttrClosed) != 0) + stat->mode = 0x9f; + + memcpy(stat->ctime, &fse->created, sizeof(sceMcStDateTime)); + memcpy(stat->mtime, &fse->modified, sizeof(sceMcStDateTime)); + + stat->size = fse->field_38; + stat->attr = fse->field_28; + + return sceMcResSucceed; + } + + stat->size = fse->length; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_setinfo1(int port, int slot, char *filename, sceMcTblGetDir *info, int flags) +{ + register int r, temp, ret; + McFsEntryPS1 *fse1, *fse2; + McCacheEntry *mce; + + DPRINTF("mcman_setinfo1 port%d slot%d filename %s flags %x\n", port, slot, filename, flags); + + ret = 0; + if (sio2man_type >= XSIO2MAN) { + if ((flags & sceMcFileAttrFile) != 0) { + r = mcman_getPS1direntry(port, slot, (char*)info->EntryName, &fse1, 1); + if (r < 0) { + if (r != sceMcResNoEntry) { + ret = r; + } + else { + if ((!strcmp(".", (char*)info->EntryName)) || (!strcmp("..", (char*)info->EntryName)) || (info->EntryName[0] == 0)) + ret = sceMcResNoEntry; + } + } + } + } + + r = mcman_getPS1direntry(port, slot, filename, &fse2, 1); + + if ((fse2->mode & 0xf0) == 0) + r = sceMcResNoEntry; + + if (r < 0) + return r; + + if (sio2man_type >= XSIO2MAN) { + if (ret != sceMcResSucceed) + return sceMcResNoEntry; + } + + mce = mcman_get1stcacheEntp(); + + temp = r + 1; + if ((r + 1) < 0) + temp = r + 8; + + mce->wr_flag |= 1 << ((r + 1) - ((temp >> 3) << 3)); + + if (sio2man_type >= XSIO2MAN) { + fse2->field_7d = 0; + fse2->field_2c = 0; + flags &= -12; + } + else { + if(fse2->field_7d != 1) { + fse2->field_7d = 1; + fse2->field_38 = fse2->length; + } + } + + if ((flags & sceMcFileAttrExecutable) != 0) { + if ((info->AttrFile & sceMcFileAttrPDAExec) != 0) + fse2->field_7e = 1; + else + fse2->field_7e = 0; + } + + //Special fix clause for file managers (like uLaunchELF) + //This allows writing most entries that can be read by mcGetDir + //and without usual restrictions. This flags value should cause no conflict + //as Sony code never uses it, and the value is changed after its use here. + //This is primarily needed for PS2 MC backups, but must be implemented here + //too since the 'flags' argument may be used indiscriminately for both + if(flags == 0xFEED){ + flags = sceMcFileAttrReadable|sceMcFileAttrWriteable; + //The changed flags value allows more entries to be copied below + } + + if ((flags & sceMcFileAttrDupProhibit) != 0) + fse2->field_28 = info->Reserve2; + + if ((flags & sceMcFileAttrReadable) != 0) + fse2->created = info->_Create; + + if ((flags & sceMcFileAttrWriteable) != 0) + fse2->modified = info->_Modify; + + if ((flags & sceMcFileAttrFile) != 0) + strncpy(fse2->name, (char*)info->EntryName, 20); + + fse2->field_1e = 0; + + r = McFlushCache(port, slot); + + return r; +} + +//-------------------------------------------------------------- +int mcman_getdir1(int port, int slot, char *dirname, int flags, int maxent, sceMcTblGetDir *info) +{ + register int r, i; + char *p; + McFsEntryPS1 *fse; + + DPRINTF("mcman_getdir1 port%d slot%d dirname %s maxent %d flags %x\n", port, slot, dirname, maxent, flags); + + flags &= 0xffff; + + i = 0; + + if (!flags) { + mcman_PS1curcluster = 0; + p = dirname; + do { + r = mcman_chrpos(p, '/'); + if (r < 0) + break; + p += mcman_chrpos(p, '/') + 1; + } while (1); + + strncpy(mcman_PS1curdir, p, 63); + + } + + if (maxent) { + do { + if (mcman_PS1curcluster >= 15) + break; + + r = mcman_readdirentryPS1(port, slot, mcman_PS1curcluster, &fse); + if (r != sceMcResSucceed) + return r; + + mcman_PS1curcluster++; + + if (fse->mode != 0x51) + continue; + + if (!mcman_checkdirpath(fse->name, mcman_PS1curdir)) + continue; + + memset((void *)info, 0, sizeof (sceMcTblGetDir)); + + info->AttrFile = 0x9417; + + if (fse->field_7e == 1) + info->AttrFile = 0x9c17; //MC_ATTR_PDAEXEC set !!! + + if (fse->field_7d == 1) { + if ((fse->field_2c & sceMcFileAttrClosed) != 0) { + info->AttrFile |= sceMcFileAttrClosed; + } + info->Reserve1 = fse->field_2e; + info->_Create = fse->created; + info->_Modify = fse->modified; + info->FileSizeByte = fse->field_38; + info->Reserve2 = fse->field_28; + } + else { + info->FileSizeByte = fse->length; + } + + strncpy((char*)info->EntryName, fse->name, 20); + info->EntryName[20] = 0; + + i++; + info++; + maxent--; + } while (maxent); + } + return i; +} + +//-------------------------------------------------------------- +int mcman_delete1(int port, int slot, char *filename, int flags) +{ + register int r; + McFsEntryPS1 *fse; + + DPRINTF("mcman_delete1 port%d slot%d filename %s flags %x\n", port, slot, filename, flags); + + r = mcman_getPS1direntry(port, slot, filename, &fse, ((u32)flags < 1) ? 1 : 0); + if (r < 0) + return r; + + r = mcman_clearPS1direntry(port, slot, r, flags); + + return r; +} + +//-------------------------------------------------------------- +int mcman_close1(int fd) +{ + register int r, temp; + MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + McFsEntryPS1 *fse; + McCacheEntry *mce; + + DPRINTF("mcman_close1 fd %d\n", fd); + + r = mcman_readdirentryPS1(fh->port, fh->slot, fh->freeclink, &fse); + if (r != sceMcResSucceed) + return -31; + + mce = mcman_get1stcacheEntp(); + + if (fh->freeclink + 1 < 0) + temp = fh->freeclink + 8; + else + temp = fh->freeclink + 1; + + mce->wr_flag |= 1 << ((fh->freeclink + 1) - ((temp >> 3) << 3)); + + if (fh->filesize == 0) { + fse->length = 0x2000; + } + else { + if ((fh->filesize - 1) < 0) + temp = (fh->filesize + 8190) >> 13; + else + temp = (fh->filesize - 1) >> 13; + + temp++; + fse->length = temp << 13; + } + + if (sio2man_type >= XSIO2MAN) { + fse->field_7d = 0; // <--- To preserve for XMCMAN + fse->field_2c = 0; // + fse->field_38 = 0; // + memset((void *)&fse->created, 0, 8); // + memset((void *)&fse->modified, 0, 8); // + } + else { // MCMAN does as following + fse->field_7d = 1; + fse->field_38 = fh->filesize; + mcman_getmcrtime(&fse->modified); + } + + fse->edc = mcman_calcEDC((void *)fse, 127); + + r = McFlushCache(fh->port, fh->slot); + if (r != sceMcResSucceed) + return r; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_unformat1(int port, int slot) +{ + register int r, i; + u32 *p; + + DPRINTF("mcman_unformat1 port%d slot%d\n", port, slot); + + p = mcman_PS1PDApagebuf.word; + for (i = 0; i < 32; i++) + *p++ = 0; + + for (i = 0; i < 1024; i++) { + r = McWritePS1PDACard(port, slot, i, &mcman_PS1PDApagebuf); + if (r != sceMcResSucceed) + return -41; + } + + return r; +} + +//-------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/ps2mc_fio.c b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/ps2mc_fio.c new file mode 100644 index 0000000..4a02129 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/ps2mc_fio.c @@ -0,0 +1,1420 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 jimmikaelkael +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include +#include "mcman-internal.h" + +extern char SUPERBLOCK_MAGIC[]; +extern char SUPERBLOCK_VERSION[]; + +extern union mcman_pagebuf mcman_pagebuf; + +extern int mcman_wr_port; +extern int mcman_wr_slot; +extern int mcman_wr_block; +extern int mcman_wr_flag3; +extern int mcman_curdircluster; + +extern int PS1CardFlag; + +extern McFsEntry mcman_dircache[MAX_CACHEDIRENTRY]; +extern MC_FHANDLE mcman_fdhandles[MAX_FDHANDLES]; +extern MCDevInfo mcman_devinfos[4][MCMAN_MAXSLOT]; + +extern u8 mcman_eccdata[512]; // size for 32 ecc + +static int mcman_curdirmaxent; +static int mcman_curdirlength; +static char mcman_curdirpath[1024]; +static char *mcman_curdirname; +static sceMcStDateTime mcman_fsmodtime; + +//-------------------------------------------------------------- +int mcman_format2(int port, int slot) +{ + register int r, i, size, ifc_index, indirect_offset, allocatable_clusters_per_card; + register int ifc_length, fat_length, fat_entry, alloc_offset; + register int j = 0, z = 0; + MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McCacheEntry *mce; + + DPRINTF("mcman_format2 port%d, slot%d cardform %d\n", port, slot, mcdi->cardform); + + if (mcdi->cardform == sceMcResNoFormat) { + for (i = 0; i < 32; i++) + mcdi->bad_block_list[i] = -1; + mcdi->rootdir_cluster = 0; + mcdi->rootdir_cluster2 = 0; + goto lbl1; + } + + if (mcdi->cardform > 0) { + if (((mcdi->version[0] - 48) >= 2) || ((mcdi->version[2] - 48) >= 2)) + goto lbl1; + } + + r = mcman_reportBadBlocks(port, slot); + if ((r != sceMcResSucceed) && (r != sceMcResNoFormat)) + return sceMcResChangedCard; + +lbl1: + // set superblock magic & version + memset((void *)&mcdi->magic, 0, sizeof (mcdi->magic) + sizeof (mcdi->version)); + strcpy(mcdi->magic, SUPERBLOCK_MAGIC); + strcat(mcdi->magic, SUPERBLOCK_VERSION); + + //size = 8192 / mcdi->cluster_size; // get blocksize in cluster a better way must be found + size = mcdi->blocksize; + mcdi->cardform = -1; + + mcman_wr_port = -1; + mcman_wr_slot = -1; + mcman_wr_block = -1; + mcman_wr_flag3 = -10; + + //if (size <= 0) + // size = 1; + if (mcdi->blocksize <= 0) + size = 8; + + // clear first 8 clusters + for (i = 0; i < size; i++) { + r = mcman_writecluster(port, slot, i, 1); + if (r == 0) + return sceMcResNoFormat; + + if (r != 1) + return -40; + } + + fat_length = (((mcdi->clusters_per_card << 2) - 1) / mcdi->cluster_size) + 1; // get length of fat in clusters + ifc_length = (((fat_length << 2) - 1) / mcdi->cluster_size) + 1; // get number of needed ifc clusters + + if (!(ifc_length <= 32)) { + ifc_length = 32; + fat_length = mcdi->FATentries_per_cluster << 5; + } + + // clear ifc clusters + if (ifc_length > 0) { + j = 0; + do { + if (i >= mcdi->clusters_per_card) + return sceMcResNoFormat; + + do { + if (mcman_writecluster(port, slot, i, 1) != 0) + break; + + i++; + } while (i < mcdi->clusters_per_card); + + if (i >= mcdi->clusters_per_card) + return sceMcResNoFormat; + + mcdi->ifc_list[j] = i; + j++; + i++; + } while (j < ifc_length); + } + + // read ifc clusters to mc cache and clear fat clusters + if (fat_length > 0) { + j = 0; + + do { + ifc_index = j / mcdi->FATentries_per_cluster; + indirect_offset = j % mcdi->FATentries_per_cluster; + + if (indirect_offset == 0) { + if (McReadCluster(port, slot, mcdi->ifc_list[ifc_index], &mce) != sceMcResSucceed) + return -42; + mce->wr_flag = 1; + } + + if (i >= mcdi->clusters_per_card) + return sceMcResNoFormat; + + do { + r = mcman_writecluster(port, slot, i, 1); + if (r == 1) + break; + + if (r < 0) + return -43; + + i++; + } while (i < mcdi->clusters_per_card); + + if (i >= mcdi->clusters_per_card) + return sceMcResNoFormat; + + j++; + McFatCluster *fc = (McFatCluster *)mce->cl_data; + fc->entry[indirect_offset] = i; + i++; + + } while (j < fat_length); + } + alloc_offset = i; + + mcdi->backup_block1 = 0; + mcdi->backup_block2 = 0; + + // clear backup blocks + for (i = (mcdi->clusters_per_card / mcdi->clusters_per_block) - 1; i > 0; i--) { + + r = mcman_writecluster(port, slot, mcdi->clusters_per_block * i, 1); + if (r < 0) + return -44; + + if ((r != 0) && (mcdi->backup_block1 == 0)) + mcdi->backup_block1 = i; + else if ((r != 0) && (mcdi->backup_block2 == 0)) { + mcdi->backup_block2 = i; + break; + } + } + + // set backup block2 to erased state + if (mcman_eraseblock(port, slot, mcdi->backup_block2, NULL, NULL) != sceMcResSucceed) + return -45; + + u32 hi, lo, temp; + + long_multiply(mcdi->clusters_per_card, 0x10624dd3, &hi, &lo); + temp = (hi >> 6) - (mcdi->clusters_per_card >> 31); + allocatable_clusters_per_card = (((((temp << 5) - temp) << 2) + temp) << 3) + 1; + j = alloc_offset; + + // checking for bad allocated clusters and building FAT + if (j < i * mcdi->clusters_per_block) { + z = 0; + do { // quick check for bad clusters + r = mcman_writecluster(port, slot, j, 0); + if (r == 1) { + if (z == 0) { + mcdi->alloc_offset = j; + mcdi->rootdir_cluster = 0; + fat_entry = 0xffffffff; // marking rootdir end + } + else + fat_entry = 0x7fffffff; // marking free cluster + z++; + if (z == allocatable_clusters_per_card) + mcdi->max_allocatable_clusters = (j - mcdi->alloc_offset) + 1; + } + else { + if (r != 0) + return -45; + fat_entry = 0xfffffffd; // marking bad cluster + } + + if (McSetFATentry(port, slot, j - mcdi->alloc_offset, fat_entry) != sceMcResSucceed) + return -46; + + j++; + } while (j < (i * mcdi->clusters_per_block)); + } + + mcdi->alloc_end = (i * mcdi->clusters_per_block) - mcdi->alloc_offset; + + if (mcdi->max_allocatable_clusters == 0) + mcdi->max_allocatable_clusters = i * mcdi->clusters_per_block; + + if (z < mcdi->clusters_per_block) + return sceMcResNoFormat; + + // read superblock to mc cache + for (i = 0; i < sizeof (MCDevInfo); i += MCMAN_CLUSTERSIZE) { + if (i < 0) + size = i + (MCMAN_CLUSTERSIZE - 1); + else + size = i; + + if (McReadCluster(port, slot, size >> 10, &mce) != sceMcResSucceed) + return -48; + + size = MCMAN_CLUSTERSIZE; + mce->wr_flag = 1; + + if ((sizeof (MCDevInfo) - i) <= 1024) + size = sizeof (MCDevInfo) - i; + + memcpy((void *)mce->cl_data, (void *)(mcdi + i), size); + } + + mcdi->unknown1 = 0; + mcdi->unknown2 = 0; + mcdi->unknown5 = -1; + mcdi->rootdir_cluster2 = mcdi->rootdir_cluster; + + // Create root dir + if (McCreateDirentry(port, slot, 0, 0, 0, NULL) != sceMcResSucceed) + return -49; + + // finally flush cache to memcard + r = McFlushCache(port, slot); + if (r != sceMcResSucceed) + return r; + + mcdi->cardform = 1; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_dread2(int fd, io_dirent_t *dirent) +{ + register int r; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + McFsEntry *fse; + + DPRINTF("mcman_dread2 fd %d\n", fd); + + if (fh->position >= fh->filesize) + return sceMcResSucceed; + + do { + r = McReadDirEntry(fh->port, fh->slot, fh->freeclink, fh->position, &fse); + if (r != sceMcResSucceed) + return r; + + if (fse->mode & sceMcFileAttrExists) + break; + + fh->position++; + } while (fh->position < fh->filesize); + + if (fh->position >= fh->filesize) + return sceMcResSucceed; + + fh->position++; + mcman_wmemset((void *)dirent, sizeof (io_dirent_t), 0); + strcpy(dirent->name, fse->name); + *(u8 *)&dirent->name[32] = 0; + + if (fse->mode & sceMcFileAttrReadable) + dirent->stat.mode |= sceMcFileAttrReadable; + if (fse->mode & sceMcFileAttrWriteable) + dirent->stat.mode |= sceMcFileAttrWriteable; + if (fse->mode & sceMcFileAttrExecutable) + dirent->stat.mode |= sceMcFileAttrExecutable; + if (fse->mode & sceMcFileAttrPS1) + dirent->stat.mode |= sceMcFileAttrPS1; + if (fse->mode & sceMcFileAttrPDAExec) + dirent->stat.mode |= sceMcFileAttrPDAExec; + if (fse->mode & sceMcFileAttrDupProhibit) + dirent->stat.mode |= sceMcFileAttrDupProhibit; + if (fse->mode & sceMcFileAttrSubdir) + dirent->stat.mode |= sceMcFileAttrSubdir; + else + dirent->stat.mode |= sceMcFileAttrFile; + + dirent->stat.attr = fse->attr; + dirent->stat.size = fse->length; + memcpy(dirent->stat.ctime, &fse->created, sizeof(sceMcStDateTime)); + memcpy(dirent->stat.mtime, &fse->modified, sizeof(sceMcStDateTime)); + + return 1; +} + +//-------------------------------------------------------------- +int mcman_getstat2(int port, int slot, char *filename, io_stat_t *stat) +{ + register int r; + McFsEntry *fse; + + DPRINTF("mcman_getstat2 port%d slot%d filename %s\n", port, slot, filename); + + r = mcman_cachedirentry(port, slot, filename, NULL, &fse, 1); + if (r != sceMcResSucceed) + return r; + + mcman_wmemset((void *)stat, sizeof (io_stat_t), 0); + + if (fse->mode & sceMcFileAttrReadable) + stat->mode |= sceMcFileAttrReadable; + if (fse->mode & sceMcFileAttrWriteable) + stat->mode |= sceMcFileAttrWriteable; + if (fse->mode & sceMcFileAttrExecutable) + stat->mode |= sceMcFileAttrExecutable; + if (fse->mode & sceMcFileAttrPS1) + stat->mode |= sceMcFileAttrPS1; + if (fse->mode & sceMcFileAttrPDAExec) + stat->mode |= sceMcFileAttrPDAExec; + if (fse->mode & sceMcFileAttrDupProhibit) + stat->mode |= sceMcFileAttrDupProhibit; + if (fse->mode & sceMcFileAttrSubdir) + stat->mode |= sceMcFileAttrSubdir; + else + stat->mode |= sceMcFileAttrFile; + + stat->attr = fse->attr; + + if (!(fse->mode & sceMcFileAttrSubdir)) + stat->size = fse->length; + + memcpy(stat->ctime, &fse->created, sizeof(sceMcStDateTime)); + memcpy(stat->mtime, &fse->modified, sizeof(sceMcStDateTime)); + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_setinfo2(int port, int slot, char *filename, sceMcTblGetDir *info, int flags) +{ + register int r, fmode; + McFsEntry *fse; + McCacheDir dirInfo; + McFsEntry mfe; + u8 *pfsentry, *pfseend, *mfee; + + DPRINTF("mcman_setinfo2 port%d slot%d filename %s flags %x\n", port, slot, filename, flags); + + r = mcman_cachedirentry(port, slot, filename, &dirInfo, &fse, 1); //dirInfo=sp218 fse=sp228 + if (r != sceMcResSucceed) + return r; + + if ((flags & sceMcFileAttrFile) != 0) { + if ((!strcmp(".", (char*)info->EntryName)) || (!strcmp("..", (char*)info->EntryName))) + return sceMcResNoEntry; + + if (info->EntryName[0] == 0) + return sceMcResNoEntry; + + r = mcman_chrpos((char*)info->EntryName, '/'); + if (r >= 0) + return sceMcResNoEntry; + + if (dirInfo.fsindex < 2) + return sceMcResNoEntry; + + r = McReadDirEntry(port, slot, dirInfo.cluster, 0, &fse); + if (r != sceMcResSucceed) + return r; + + r = McReadDirEntry(port, slot, fse->cluster, fse->dir_entry, &fse); + if (r != sceMcResSucceed) + return r; + + pfsentry = (u8 *)fse; + mfee = (u8 *)&mfe; + pfseend = (u8 *)(pfsentry + sizeof (McFsEntry)); + + do { + *((u32 *)mfee ) = *((u32 *)pfsentry ); + *((u32 *)mfee+1) = *((u32 *)pfsentry+1); + *((u32 *)mfee+2) = *((u32 *)pfsentry+2); + *((u32 *)mfee+3) = *((u32 *)pfsentry+3); + pfsentry += 16; + mfee += 16; + } while (pfsentry < pfseend); + + r = mcman_getdirinfo(port, slot, &mfe, (char*)info->EntryName, NULL, 1); + if (r != 1) { + if (r < 2) { + if (r == 0) + return sceMcResNoEntry; + return r; + } + else { + if (r != 2) + return r; + return sceMcResDeniedPermit; + } + } + } + + r = McReadDirEntry(port, slot, dirInfo.cluster, dirInfo.fsindex, &fse); + if (r != sceMcResSucceed) + return r; + + Mc1stCacheEntSetWrFlagOff(); + + //Special fix clause for file managers (like uLaunchELF) + //This allows writing most entries that can be read by mcGetDir + //and without usual restrictions. This flags value should cause no conflict + //as Sony code never uses it, and the value is changed after its use here. + if(flags == 0xFEED){ + fse->mode = info->AttrFile; + //fse->unused = info->Reserve1; + //fse->length = info->FileSizeByte; + flags = sceMcFileAttrReadable|sceMcFileAttrWriteable; + //The changed flags value allows more entries to be copied below + } + + if ((flags & sceMcFileAttrDupProhibit) != 0) + fse->attr = info->Reserve2; + + if ((flags & sceMcFileAttrExecutable) != 0) { + fmode = 0xffff7fcf; + if (!PS1CardFlag) + fmode = 0x180f; + fse->mode = (fse->mode & ~fmode) | (info->AttrFile & fmode); + } + + if ((flags & sceMcFileCreateFile) != 0) { + fmode = 0x380f; + if (!PS1CardFlag) + fmode = 0x180f; + fse->mode = (fse->mode & ~fmode) | (info->AttrFile & fmode); + } + + if ((flags & sceMcFileAttrReadable) != 0) + fse->created = info->_Create; + + if ((flags & sceMcFileAttrWriteable) != 0) + fse->modified = info->_Modify; + + if ((flags & sceMcFileAttrFile) != 0) { + strncpy(fse->name, (char*)info->EntryName, 32); + fse->name[31] = 0; + } + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_read2(int fd, void *buffer, int nbyte) +{ + register int r, temp, rpos, size, offset; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + register MCDevInfo *mcdi = &mcman_devinfos[fh->port][fh->slot]; + McCacheEntry *mce; + + DPRINTF("mcman_read2 fd %d buf %x size %d\n", fd, (int)buffer, nbyte); + + if (fh->position < fh->filesize) { + + temp = fh->filesize - fh->position; + if (nbyte > temp) + nbyte = temp; + + rpos = 0; + if (nbyte > 0) { + + do { + offset = fh->position % mcdi->cluster_size; // file pointer offset % cluster size + temp = mcdi->cluster_size - offset; + if (temp < nbyte) + size = temp; + else + size = nbyte; + + r = mcman_fatRseek(fd); + + if (r <= 0) + return r; + + r = McReadCluster(fh->port, fh->slot, r, &mce); + if (r != sceMcResSucceed) + return r; + + memcpy((void *)(buffer + rpos), (void *)(mce->cl_data + offset), size); + + rpos += size; + mce->rd_flag = 1; + nbyte -= size; + fh->position += size; + + } while (nbyte); + } + return rpos; + } + + return 0; +} + +//-------------------------------------------------------------- +int mcman_write2(int fd, void *buffer, int nbyte) +{ + register int r, r2, wpos, size, offset; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + register MCDevInfo *mcdi = &mcman_devinfos[fh->port][fh->slot]; + McCacheEntry *mce; + + if (nbyte) { + if (fh->unknown2 == 0) { + fh->unknown2 = 1; + r = mcman_close2(fd); + if (r != sceMcResSucceed) + return r; + r = McFlushCache(fh->port, fh->slot); + if (r != sceMcResSucceed) + return r; + } + } + + wpos = 0; + if (nbyte) { + do { + r = mcman_fatRseek(fd); + if (r == sceMcResFullDevice) { + + r2 = mcman_fatWseek(fd); + if (r2 == r) + return sceMcResFullDevice; + + if (r2 != sceMcResSucceed) + return r2; + + r = mcman_fatRseek(fd); + } + else { + if (r < 0) + return r; + } + + r = McReadCluster(fh->port, fh->slot, r, &mce); + if (r != sceMcResSucceed) + return r; + + mce->rd_flag = 1; + + offset = fh->position % mcdi->cluster_size; // file pointer offset % cluster size + r2 = mcdi->cluster_size - offset; + if (r2 < nbyte) + size = r2; + else + size = nbyte; + + memcpy((void *)(mce->cl_data + offset), (void *)(buffer + wpos), size); + + mce->wr_flag = 1; + + r = fh->position + size; + fh->position += size; + + if (r < fh->filesize) + r = fh->filesize ; + + fh->filesize = r; + + nbyte -= size; + wpos += size; + + } while (nbyte); + } + + r = mcman_close2(fd); + if (r != sceMcResSucceed) + return r; + + return wpos; +} + +//-------------------------------------------------------------- +int mcman_close2(int fd) +{ + register int r, fmode; + register MC_FHANDLE *fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + McFsEntry *fse1, *fse2; + + DPRINTF("mcman_close2 fd %d\n", fd); + + r = McReadDirEntry(fh->port, fh->slot, fh->field_20, fh->field_24, &fse1); + if (r != sceMcResSucceed) + return -31; + + if (fh->unknown2 == 0) { + fmode = fse1->mode | sceMcFileAttrClosed; + } + else { + fmode = fse1->mode & 0xff7f; + } + fse1->mode = fmode; + + mcman_getmcrtime(&fse1->modified); + + fse1->cluster = fh->freeclink; + fse1->length = fh->filesize; + + Mc1stCacheEntSetWrFlagOff(); + + mcman_fsmodtime = fse1->modified; + + r = McReadDirEntry(fh->port, fh->slot, fh->field_28, fh->field_2C, &fse2); + if (r != sceMcResSucceed) + return r; + + fse2->modified = mcman_fsmodtime; + + Mc1stCacheEntSetWrFlagOff(); + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_open2(int port, int slot, char *filename, int flags) +{ + register int fd, i, r, fsindex, fsoffset, fat_index, rdflag, wrflag, pos, mcfree; + register MC_FHANDLE *fh, *fh2; + register MCDevInfo *mcdi; + McCacheDir cacheDir; + McFsEntry *fse1, *fse2; + McCacheEntry *mce; + u8 *pfsentry, *pcache, *pfseend; + char *p; + int fat_entry; + + DPRINTF("mcman_open2 port%d slot%d name %s flags %x\n", port, slot, filename, flags); + + if ((flags & sceMcFileCreateFile) != 0) + flags |= sceMcFileAttrWriteable; // s5 + + //if (!mcman_checkpath(filename)) + // return sceMcResNoEntry; + if (filename[0] == 0) + return sceMcResNoEntry; + + fd = 0; + do { + fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; + if (fh->status == 0) + break; + } while (++fd < MAX_FDHANDLES); + + if (fd == MAX_FDHANDLES) + return sceMcResUpLimitHandle; + + fh = (MC_FHANDLE *)&mcman_fdhandles[fd]; // s2 + + mcman_wmemset((void *)fh, sizeof (MC_FHANDLE), 0); + + mcdi = (MCDevInfo *)&mcman_devinfos[port][slot]; // s3 + + if ((flags & (sceMcFileCreateFile | sceMcFileCreateDir)) == 0) + cacheDir.maxent = -1; //sp20 + else + cacheDir.maxent = 0; //sp20 + + //fse1 = sp28 + //sp18 = cacheDir + + fse1 = NULL; + r = mcman_cachedirentry(port, slot, filename, &cacheDir, &fse1, 1); + if (r < 0) + return r; + + if (fse1) { + pfsentry = (u8 *)fse1; + pcache = (u8 *)&mcman_dircache[1]; + pfseend = (u8 *)(pfsentry + sizeof(McFsEntry)); + + do { + *((u32 *)pcache ) = *((u32 *)pfsentry ); + *((u32 *)pcache+1) = *((u32 *)pfsentry+1); + *((u32 *)pcache+2) = *((u32 *)pfsentry+2); + *((u32 *)pcache+3) = *((u32 *)pfsentry+3); + pfsentry += 16; + pcache += 16; + } while (pfsentry < pfseend); + } + + if ((flags == 0) && ((fse1->mode & sceMcFileAttrExists) == 0)) + r = 1; + + if (r == 2) + return sceMcResNoEntry; + + if (r == 3) + return sceMcResDeniedPermit; + + if ((r == 0) && ((flags & sceMcFileCreateDir) != 0)) + return sceMcResNoEntry; + + if ((r == 1) && ((flags & (sceMcFileCreateFile | sceMcFileCreateDir)) == 0)) + return sceMcResNoEntry; + + rdflag = flags & sceMcFileAttrReadable; + wrflag = flags & sceMcFileAttrWriteable; + fh->freeclink = -1; + fh->clink = -1; + fh->clust_offset = 0; + fh->filesize = 0; + fh->position = 0; + fh->port = port; + fh->slot = slot; + fh->unknown2 = 0; + fh->rdflag = rdflag; + fh->wrflag = wrflag; + fh->unknown1 = 0; + fh->field_20 = cacheDir.cluster; + fh->field_24 = cacheDir.fsindex; + + // fse2 = sp2c + + if (r == 0) { + + if ((wrflag != 0) && ((mcman_dircache[1].mode & sceMcFileAttrWriteable) == 0)) + return sceMcResDeniedPermit; + + if (!PS1CardFlag) { + if ((flags & sceMcFileAttrReadable) != 0) { + if ((mcman_dircache[1].mode & sceMcFileAttrReadable) == 0) + return sceMcResDeniedPermit; + } + } + r = McReadDirEntry(port, slot, cacheDir.cluster, 0, &fse2); + if (r != sceMcResSucceed) + return r; + + fh->field_28 = fse2->cluster; + fh->field_2C = fse2->dir_entry; + + if ((mcman_dircache[1].mode & sceMcFileAttrSubdir) != 0) { + if ((mcman_dircache[1].mode & sceMcFileAttrReadable) == 0) + return sceMcResDeniedPermit; + + fh->freeclink = mcman_dircache[1].cluster; + fh->rdflag = 0; + fh->wrflag = 0; + fh->unknown1 = 0; + fh->drdflag = 1; + fh->status = 1; + fh->filesize = mcman_dircache[1].length; + fh->clink = fh->freeclink; + + return fd; + } + + if ((flags & sceMcFileAttrWriteable) != 0) { + i = 0; + do { + fh2 = (MC_FHANDLE *)&mcman_fdhandles[i]; + + if ((fh2->status == 0) || (fh2->port != port) || (fh2->slot != slot) \ + || (fh2->field_20 != cacheDir.cluster) || (fh2->field_24 != cacheDir.fsindex)) + continue; + + if (fh2->wrflag != 0) + return sceMcResDeniedPermit; + + } while (++i < MAX_FDHANDLES); + } + + if ((flags & sceMcFileCreateFile) != 0) { + r = McSetDirEntryState(port, slot, cacheDir.cluster, cacheDir.fsindex, 0); + McFlushCache(port, slot); + + if (r != sceMcResSucceed) + return -43; + + if (cacheDir.fsindex < cacheDir.maxent) + cacheDir.maxent = cacheDir.fsindex; + } + else { + fh->freeclink = mcman_dircache[1].cluster; + fh->filesize = mcman_dircache[1].length; + fh->clink = fh->freeclink; + + if (fh->rdflag != 0) + fh->rdflag = (*((u8 *)&mcman_dircache[1].mode)) & sceMcFileAttrReadable; + else + fh->rdflag = 0; + + if (fh->wrflag != 0) + fh->wrflag = (mcman_dircache[1].mode >> 1) & sceMcFileAttrReadable; + else + fh->wrflag = 0; + + fh->status = 1; + + return fd; + } + } + else { + fh->field_28 = cacheDir.cluster; + fh->field_2C = cacheDir.fsindex; + } + + r = McReadDirEntry(port, slot, fh->field_28, fh->field_2C, &fse1); + if (r != sceMcResSucceed) + return r; + + pfsentry = (u8 *)fse1; + pcache = (u8 *)&mcman_dircache[2]; + pfseend = (u8 *)(pfsentry + sizeof(McFsEntry)); + + do { + *((u32 *)pcache ) = *((u32 *)pfsentry ); + *((u32 *)pcache+1) = *((u32 *)pfsentry+1); + *((u32 *)pcache+2) = *((u32 *)pfsentry+2); + *((u32 *)pcache+3) = *((u32 *)pfsentry+3); + pfsentry += 16; + pcache += 16; + } while (pfsentry < pfseend); + + i = -1; + if (mcman_dircache[2].length == cacheDir.maxent) { + + fsindex = mcman_dircache[2].length / (mcdi->cluster_size >> 9); //v1 + fsoffset = mcman_dircache[2].length % (mcdi->cluster_size >> 9); //v0 + + if (fsoffset == 0) { + fat_index = mcman_dircache[2].cluster; + i = fsindex; + + if ((mcman_dircache[2].cluster == 0) && (i >= 2)) { + if (mcman_getFATindex(port, slot, i - 1) >= 0) { + fat_index = mcman_getFATindex(port, slot, i - 1); // s3 + i = 1; + } + } + i--; + + if (i != -1) { + + do { + r = McGetFATentry(port, slot, fat_index, &fat_entry); + if (r != sceMcResSucceed) + return r; + + if (fat_entry >= -1) { + r = mcman_findfree2(port, slot, 1); + if (r < 0) + return r; + + fat_entry = r; + mce = mcman_get1stcacheEntp(); // s4 + + fat_entry |= 0x80000000; + + r = McSetFATentry(port, slot, fat_index, fat_entry); + if (r != sceMcResSucceed) + return r; + + mcman_addcacheentry(mce); + } + i--; + fat_index = fat_entry & 0x7fffffff; + + } while (i != -1); + } + } + + r = McFlushCache(port, slot); + if (r != sceMcResSucceed) + return r; + + i = -1; + + mcman_dircache[2].length++; + } + + do { + p = filename + i + 1; + pos = i + 1; + r = mcman_chrpos(p, '/'); + if (r < 0) + break; + i = pos + r; + } while (1); + + p = filename + pos; + + mcfree = 0; + + if ((flags & sceMcFileCreateDir) != 0) { + r = mcman_findfree2(port, slot, 1); // r = s3 + if (r < 0) + return r; + mcfree = r; + } + + mce = mcman_get1stcacheEntp(); // mce = s4 + + mcman_getmcrtime(&mcman_dircache[2].modified); + + r = McReadDirEntry(port, slot, mcman_dircache[2].cluster, cacheDir.maxent, &fse2); + if (r != sceMcResSucceed) + return r; + + mcman_wmemset((void *)fse2, sizeof (McFsEntry), 0); + + strncpy(fse2->name, p, 32); + + fse2->created = mcman_dircache[2].modified; + fse2->modified = mcman_dircache[2].modified; + + Mc1stCacheEntSetWrFlagOff(); + + mcman_addcacheentry(mce); + + if (!PS1CardFlag) + flags &= 0xffffdfff; + + if ((flags & sceMcFileCreateDir) != 0) { + + fse2->mode = ((flags & sceMcFileAttrHidden) | sceMcFileAttrReadable | sceMcFileAttrWriteable \ + | sceMcFileAttrExecutable | sceMcFileAttrSubdir | sceMcFile0400 | sceMcFileAttrExists) // 0x8427 + | (flags & (sceMcFileAttrPS1 | sceMcFileAttrPDAExec)); + fse2->length = 2; + fse2->cluster = mcfree; + + r = McCreateDirentry(port, slot, mcman_dircache[2].cluster, cacheDir.maxent, mcfree, (sceMcStDateTime *)&fse2->created); + if (r != sceMcResSucceed) + return -46; + + r = McReadDirEntry(port, slot, fh->field_28, fh->field_2C, &fse1); + if (r != sceMcResSucceed) + return r; + + pfsentry = (u8 *)fse1; + pcache = (u8 *)&mcman_dircache[2]; + pfseend = (u8 *)(pfsentry + sizeof(McFsEntry)); + + do { + *((u32 *)pfsentry ) = *((u32 *)pcache ); + *((u32 *)pfsentry+1) = *((u32 *)pcache+1); + *((u32 *)pfsentry+2) = *((u32 *)pcache+2); + *((u32 *)pfsentry+3) = *((u32 *)pcache+3); + pfsentry += 16; + pcache += 16; + } while (pfsentry < pfseend); + + Mc1stCacheEntSetWrFlagOff(); + + r = McFlushCache(port, slot); + if (r != sceMcResSucceed) + return r; + + return sceMcResSucceed; + } + else { + fse2->mode = ((flags & sceMcFileAttrHidden) | sceMcFileAttrReadable | sceMcFileAttrWriteable \ + | sceMcFileAttrExecutable | sceMcFileAttrFile | sceMcFile0400 | sceMcFileAttrExists) // 0x8417 + | (flags & (sceMcFileAttrPS1 | sceMcFileAttrPDAExec)); + + fse2->cluster = -1; + fh->field_20 = mcman_dircache[2].cluster; + fh->status = 1; + fh->field_24 = cacheDir.maxent; + + r = McReadDirEntry(port, slot, fh->field_28, fh->field_2C, &fse1); + if (r != sceMcResSucceed) + return r; + + pfsentry = (u8 *)fse1; + pcache = (u8 *)&mcman_dircache[2]; + pfseend = (u8 *)(pfsentry + sizeof(McFsEntry)); + + do { + *((u32 *)pfsentry ) = *((u32 *)pcache ); + *((u32 *)pfsentry+1) = *((u32 *)pcache+1); + *((u32 *)pfsentry+2) = *((u32 *)pcache+2); + *((u32 *)pfsentry+3) = *((u32 *)pcache+3); + pfsentry += 16; + pcache += 16; + } while (pfsentry < pfseend); + + Mc1stCacheEntSetWrFlagOff(); + + r = McFlushCache(port, slot); + if (r != sceMcResSucceed) + return r; + } + + return fd; +} + +//-------------------------------------------------------------- +int mcman_chdir(int port, int slot, char *newdir, char *currentdir) +{ + register int r, len, len2, cluster; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McCacheDir cacheDir; + McFsEntry *fse; + + DPRINTF("mcman_chdir port%d slot%d newdir %s\n", port, slot, newdir); + + //if (!mcman_checkpath(newdir)) + // return sceMcResNoEntry; + + cacheDir.maxent = -1; + + r = mcman_cachedirentry(port, slot, newdir, &cacheDir, &fse, 1); + if (r < 0) + return r; + + if (((u32)(r - 1)) < 2) + return sceMcResNoEntry; + + mcdi->rootdir_cluster2 = cacheDir.cluster; + mcdi->unknown1 = cacheDir.fsindex; + + cluster = cacheDir.cluster; + if (!strcmp(fse->name, "..")) { + r = McReadDirEntry(port, slot, cluster, 0, &fse); + if (r != sceMcResSucceed) + return r; + } + + if (!strcmp(fse->name, ".")) { + mcdi->rootdir_cluster2 = fse->cluster; + mcdi->unknown1 = fse->dir_entry; + + cluster = fse->cluster; + r = McReadDirEntry(port, slot, cluster, fse->dir_entry, &fse); + if (r != sceMcResSucceed) + return r; + } + + currentdir[0] = 0; + +lbl1: + if (strcmp(fse->name, ".")) { + + if (strlen(fse->name) < 32) + len = strlen(fse->name); + else + len = 32; + + if (strlen(currentdir)) { + len2 = strlen(currentdir); + if (len2 >= 0) { + do { + currentdir[1 + len2 + len] = currentdir[len2]; + } while (--len2 >= 0); + } + currentdir[len] = '/'; + strncpy(currentdir, fse->name, len); + } + else { + strncpy(currentdir, fse->name, 32); + currentdir[32] = 0; + } + + r = McReadDirEntry(port, slot, cluster, 0, &fse); + if (r != sceMcResSucceed) + return r; + + r = McReadDirEntry(port, slot, fse->cluster, fse->dir_entry, &fse); + + if (r == sceMcResSucceed) + goto lbl1; + + return r; + } + else { + len = strlen(currentdir); + + if (len >= 0) { + do { + currentdir[1 + len] = currentdir[len]; + } while (--len >= 0); + } + currentdir[0] = '/'; + + r = sceMcResSucceed; + } + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_getdir2(int port, int slot, char *dirname, int flags, int maxent, sceMcTblGetDir *info) +{ + register int r, pos, nument; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + McFsEntry *fse; + char *p; + + DPRINTF("mcman_getdir2 port%d slot%d dir=%s flags=%d maxent=%d\n", port, slot, dirname, flags, maxent); + + nument = 0; + flags &= 0xffff; + + if (!flags) { + + p = mcman_curdirpath; + strncpy(p, dirname, 1023); + mcman_curdirpath[1023] = 0; + + pos = -1; // s1 + p++; //s0 + do { + r = mcman_chrpos((void *)&p[pos], '/'); + if (r < 0) + break; + pos += 1 + r; + } while (1); + + if (pos <= 0) { + if (pos == 0) + *p = 0; + else + p[-1] = 0; + } + else { + mcman_curdirpath[pos] = 0; + } + + mcman_curdirname = &dirname[pos] + 1; + + r = mcman_cachedirentry(port, slot, mcman_curdirpath, NULL, &fse, 1); + if (r > 0) + return sceMcResNoEntry; + if (r < 0) + return r; + + if (!(fse->mode & sceMcFileAttrSubdir)) { + mcman_curdircluster = -1; + return sceMcResNoEntry; + } + + mcman_curdircluster = fse->cluster; + mcman_curdirlength = fse->length; + + if ((fse->cluster == mcdi->rootdir_cluster) && (fse->dir_entry == 0)) + mcman_curdirmaxent = 2; + else + mcman_curdirmaxent = 0; + } + else { + if (mcman_curdircluster < 0) + return sceMcResNoEntry; + } + + if (maxent != 0) { + do { + if (mcman_curdirmaxent >= mcman_curdirlength) + break; + + r = McReadDirEntry(port, slot, mcman_curdircluster, mcman_curdirmaxent, &fse); + if (r != sceMcResSucceed) + return r; + + mcman_curdirmaxent++; + + if (!(fse->mode & sceMcFileAttrExists)) + continue; + if ((fse->mode & sceMcFileAttrHidden) && (!PS1CardFlag)) + continue; + if (!mcman_checkdirpath(fse->name, mcman_curdirname)) + continue; + + mcman_wmemset((void *)info, sizeof (sceMcTblGetDir), 0); + + if (mcman_curdirmaxent == 2) { + + r = McReadDirEntry(port, slot, mcman_curdircluster, 0, &fse); + if (r != sceMcResSucceed) + return r; + + r = McReadDirEntry(port, slot, fse->cluster, 0, &fse); + if (r != sceMcResSucceed) + return r; + + r = McReadDirEntry(port, slot, fse->cluster, fse->dir_entry, &fse); + if (r != sceMcResSucceed) + return r; + + info->EntryName[0] = '.'; + info->EntryName[1] = '.'; + info->EntryName[2] = '\0'; + } + else if (mcman_curdirmaxent == 1) { + + r = McReadDirEntry(port, slot, mcman_curdircluster, 0, &fse); + if (r != sceMcResSucceed) + return r; + + r = McReadDirEntry(port, slot, fse->cluster, fse->dir_entry, &fse); + if (r != sceMcResSucceed) + return r; + + info->EntryName[0] = '.'; + info->EntryName[1] = '\0'; + } + else { + strncpy((char*)info->EntryName, fse->name, 32); + } + + info->AttrFile = fse->mode; + info->Reserve1 = fse->unused; + + info->_Create = fse->created; + info->_Modify = fse->modified; + + if (!(fse->mode & sceMcFileAttrSubdir)) + info->FileSizeByte = fse->length; + + nument++; + maxent--; + info++; + + } while (maxent); + } + + return nument; +} + +//-------------------------------------------------------------- +int mcman_delete2(int port, int slot, char *filename, int flags) +{ + register int r, i; + McCacheDir cacheDir; + McFsEntry *fse1, *fse2; + + DPRINTF("mcman_delete2 port%d slot%d filename %s flags %x\n", port, slot, filename, flags); + + //if (!mcman_checkpath(filename)) + // return sceMcResNoEntry; + + r = mcman_cachedirentry(port, slot, filename, &cacheDir, &fse1, ((u32)(flags < 1)) ? 1 : 0); + if (r > 0) + return sceMcResNoEntry; + if (r < 0) + return r; + + if (!flags) { + if (!(fse1->mode & sceMcFileAttrExists)) + return sceMcResNoEntry; + } + else { + if (fse1->mode & sceMcFileAttrExists) + return sceMcResNoEntry; + } + + if ((!PS1CardFlag) && (!flags)) { + if (!(fse1->mode & sceMcFileAttrWriteable)) + return sceMcResDeniedPermit; + } + + if ((!fse1->cluster) && (!fse1->dir_entry)) + return sceMcResNoEntry; + + i = 2; + if ((!flags) && (fse1->mode & sceMcFileAttrSubdir) && (i < fse1->length)) { + + do { + r = McReadDirEntry(port, slot, fse1->cluster, i, &fse2); + if (r != sceMcResSucceed) + return r; + + if (fse2->mode & sceMcFileAttrExists) + return sceMcResNotEmpty; + + } while (++i < fse1->length); + } + + r = McSetDirEntryState(port, slot, cacheDir.cluster, cacheDir.fsindex, flags); + if (r != sceMcResSucceed) + return r; + + r = McFlushCache(port, slot); + if (r != sceMcResSucceed) + return r; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- +int mcman_unformat2(int port, int slot) +{ + register int r, i, j, z, l, pageword_cnt, page, blocks_on_card, erase_byte, err_cnt; + register u32 erase_value; + register MCDevInfo *mcdi = &mcman_devinfos[port][slot]; + + DPRINTF("mcman_unformat2 port%d slot%d\n", port, slot); + + pageword_cnt = mcdi->pagesize >> 2; + blocks_on_card = mcdi->clusters_per_card / mcdi->clusters_per_block; //sp18 + + erase_value = 0xffffffff; //s6 + if (!(mcdi->cardflags & CF_ERASE_ZEROES)) + erase_value = 0x00000000; + + for (i = 0; i < pageword_cnt; i++) + mcman_pagebuf.word[i] = erase_value; + + for (i = 0; i < 128; i++) + *((u32 *)&mcman_eccdata + i) = erase_value; + + i = 1; + if (i < blocks_on_card) { + erase_byte = erase_value & 0xff; // sp20 + do { + page = i * mcdi->blocksize; + if (mcdi->cardform > 0) { + j = 0; + for (j = 0; j < 16; j++) { + if (mcdi->bad_block_list[j] <= 0) { + j = 16; + goto lbl1; + } + if (mcdi->bad_block_list[j] == i) + goto lbl1; + } + } + else { + err_cnt = 0; + j = -1; + z = 0; + if (mcdi->blocksize > 0) { + do { + r = McReadPage(port, slot, page + z, &mcman_pagebuf); + if (r == sceMcResNoFormat) { + j = -2; + break; + } + if (r != sceMcResSucceed) + return -42; + + if ((mcdi->cardflags & CF_USE_ECC) == 0) { + for (l = 0; l < mcdi->pagesize; l++) { + if (mcman_pagebuf.byte[l] != erase_byte) + err_cnt++; + if (err_cnt >= (mcdi->clusters_per_block << 6)) { + j = 16; + break; + } + } + if (j != -1) + break; + } + } while (++z < mcdi->blocksize); + } + } + + if (((mcdi->cardflags & CF_USE_ECC) != 0) && (j == -1)) + j = 16; +lbl1: + if (j == 16) { + r = mcman_eraseblock(port, slot, i, NULL, NULL); + if (r != sceMcResSucceed) + return -43; + } + else { + for (l = 0; l < pageword_cnt; l++) + mcman_pagebuf.word[l] = erase_value; + + if (mcdi->blocksize > 0) { + z = 0; + do { + r = McWritePage(port, slot, page + z, &mcman_pagebuf, mcman_eccdata); + if (r != sceMcResSucceed) + return -44; + } while (++z < mcdi->blocksize); + } + } + } while (++i < blocks_on_card); + } + + r = mcman_eraseblock(port, slot, 0, NULL, NULL); + if (r != sceMcResSucceed) + return -45; + + return sceMcResSucceed; +} + +//-------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/sio2man_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/sio2man_imports.h new file mode 100644 index 0000000..3d83fa2 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcman/src/sio2man_imports.h @@ -0,0 +1,27 @@ +#ifndef __SIO2MAN_IMPORTS_H__ +#define __SIO2MAN_IMPORTS_H__ + +#include +#include +#include + +#define SIO2MAN 0 +#define XSIO2MAN 1 +#define XSIO2MAN_V2 2 + +#ifndef SIO2MAN_EXPORTS_IMPLEMENTATION +#define SIO2MAN_EXPORTS_EXTERN extern +#else +#define SIO2MAN_EXPORTS_EXTERN +#endif +#ifndef BUILDING_XFROMMAN +// sio2man exports +/* 24 */ SIO2MAN_EXPORTS_EXTERN void (*psio2_mc_transfer_init)(void); +/* 25 */ SIO2MAN_EXPORTS_EXTERN int (*psio2_transfer)(sio2_transfer_data_t *sio2data); + +// xsio2man exports +/* 26 */ SIO2MAN_EXPORTS_EXTERN void (*psio2_transfer_reset)(void); +/* 55/57 */ SIO2MAN_EXPORTS_EXTERN int (*psio2_mtap_change_slot)(s32 *arg); +#endif + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/Makefile new file mode 100644 index 0000000..2675a78 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/Makefile @@ -0,0 +1,18 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +# IOP_CFLAGS += -DSIO_DEBUG -DDEBUG + +IOP_INCS += -I$(PS2SDKSRC)/iop/memorycard/mcman/include + +IOP_OBJS = mcserv.o imports.o exports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/exports.tab b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/exports.tab new file mode 100644 index 0000000..6a98959 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/exports.tab @@ -0,0 +1,12 @@ +DECLARE_EXPORT_TABLE(mcserv, 1, 1) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_start) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) + DECLARE_EXPORT(_dummy) +END_EXPORT_TABLE + +void _dummy() {} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/imports.lst new file mode 100644 index 0000000..d18714f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/imports.lst @@ -0,0 +1,57 @@ +//--------------------------------------------------------------------------- +// File name: imports.lst +// Description: Used to generate code for IRX function imports +//--------------------------------------------------------------------------- + +#ifdef SIO_DEBUG +sior_IMPORTS_start +I_sio_init +I_sio_printf +sior_IMPORTS_end +#endif + +loadcore_IMPORTS_start +I_RegisterLibraryEntries +I_GetLoadcoreInternalData +loadcore_IMPORTS_end + +intrman_IMPORTS_start +I_CpuEnableIntr +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +sysclib_IMPORTS_start +I_memcpy +I_memset +sysclib_IMPORTS_end + +sifman_IMPORTS_start +I_sceSifInit +I_sceSifSetDma +I_sceSifDmaStat +I_sceSifCheckInit +sifman_IMPORTS_end + +sifcmd_IMPORTS_start +I_sceSifInitRpc +I_sceSifRegisterRpc +I_sceSifSetRpcQueue +I_sceSifRpcLoop +I_sceSifGetOtherData +sifcmd_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_StartThread +I_GetThreadId +I_DelayThread +thbase_IMPORTS_end + +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end + +//--------------------------------------------------------------------------- +// End of file: imports.lst +//--------------------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/irx_imports.h new file mode 100644 index 0000000..5903046 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/irx_imports.h @@ -0,0 +1,31 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2009, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include + +/* Please keep these in alphabetical order! */ + +#include +#include +#include +#include +#ifdef SIO_DEBUG +#include +#endif +#include +#include +#include + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/mcman_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/mcman_imports.h new file mode 100644 index 0000000..fa96283 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/mcman_imports.h @@ -0,0 +1,45 @@ +#ifndef MCMAN_IMPORTS_H +#define MCMAN_IMPORTS_H + +#include "types.h" +#include "irx.h" + +#define MCMAN 0 +#define XMCMAN 1 + +char mcman_modname[8] = "mcman\0\0\0"; +int mcman_type = MCMAN; + +/* 05 */ int (*pMcDetectCard)(int port, int slot); +/* 06 */ int (*pMcOpen)(int port, int slot, char *filename, int flags); +/* 07 */ int (*pMcClose)(int fd); +/* 08 */ int (*pMcRead)(int fd, void *buf, int length); +/* 09 */ int (*pMcWrite)(int fd, void *buf, int length); +/* 10 */ int (*pMcSeek)(int fd, int offset, int origin); +/* 11 */ int (*pMcFormat)(int port, int slot); +/* 12 */ int (*pMcGetDir)(int port, int slot, char *dirname, int flags, int nument, sceMcTblGetDir *info); +/* 13 */ int (*pMcDelete)(int port, int slot, char *filename, int flags); +/* 14 */ int (*pMcFlush)(int fd); +/* 15 */ int (*pMcChDir)(int port, int slot, char *newdir, char *currentdir); +/* 16 */ int (*pMcSetFileInfo)(int port, int slot, char *filename, sceMcTblGetDir *info, int flags); +/* 17 */ int (*pMcEraseBlock)(int port, int block, void **pagebuf, void *eccbuf); +/* 18 */ int (*pMcReadPage)(int port, int slot, int page, void *buf); +/* 19 */ int (*pMcWritePage)(int port, int slot, int page, void *pagebuf, void *eccbuf); +/* 20 */ void (*pMcDataChecksum)(void *buf, void *ecc); +/* 29 */ int (*pMcReadPS1PDACard)(int port, int slot, int page, void *buf); +/* 30 */ int (*pMcWritePS1PDACard)(int port, int slot, int page, void *buf); +/* 36 */ int (*pMcUnformat)(int port, int slot); +/* 37 */ int (*pMcRetOnly)(int fd); +/* 38 */ int (*pMcGetFreeClusters)(int port, int slot); +/* 39 */ int (*pMcGetMcType)(int port, int slot); +/* 40 */ void (*pMcSetPS1CardFlag)(int flag); + +/* Available in XMCMAN only */ +/* 21 */ int (*pMcDetectCard2)(int port, int slot); +/* 22 */ int (*pMcGetFormat)(int port, int slot); +/* 23 */ int (*pMcGetEntSpace)(int port, int slot, char *dirname); +/* 24 */ int (*pMcReplaceBadBlock)(void); +/* 42 */ struct irx_id *(*pMcGetModuleInfo)(void); +/* 45 */ int (*pMcCheckBlock)(int port, int slot, int block); + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/mcserv.c b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/mcserv.c new file mode 100644 index 0000000..fba6c84 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/mcserv.c @@ -0,0 +1,1172 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 jimmikaelkael +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#include "mcserv.h" + +// TODO: last sdk 3.1.0 and sdk 3.0.3 has MCSERV module version 0x2,0x10 +// Check what was changed, and maybe port changes. +// Note: currently is based on the last XMCSERV from BOOTROM: +// 0x02,0x08 +IRX_ID(MODNAME, 2, 8); + +static const u8 XMCSERV_RpcCmd[2][16] = +{ // libmc rpc cmd values for XMCMAN/XMCSERV + { 0xFE, // CMD_INIT + 0x01, // CMD_GETINFO + 0x02, // CMD_OPEN + 0x03, // CMD_CLOSE + 0x04, // CMD_SEEK + 0x05, // CMD_READ + 0x06, // CMD_WRITE + 0x0A, // CMD_FLUSH + 0x0C, // CMD_CHDIR + 0x0D, // CMD_GETDIR + 0x0E, // CMD_SETFILEINFO + 0x0F, // CMD_DELETE + 0x10, // CMD_FORMAT + 0x11, // CMD_UNFORMAT + 0x12, // CMD_GETENTSPACE + 0x33 // CMD_CHECKBLOCK (calls xmcman_funcs: 45) + }, + { // corresponding internal rpc function + 0x00, // sceMcInit + 0x12, // sceMcGetInfo2 + 0x01, // sceMcOpen + 0x02, // sceMcClose + 0x05, // sceMcSeek + 0x11, // sceMcRead2 + 0x04, // sceMcWrite + 0x0A, // sceMcFlush + 0x0B, // sceMcChDir + 0x06, // sceMcGetDir + 0x0C, // sceMcSetFileInfo + 0x09, // sceMcDelete + 0x07, // sceMcFormat + 0x10, // sceMcUnformat + 0x13, // sceMcGetEntSpace + 0x14 // sceMcCheckBlock (calls xmcman_funcs: 45) + } +}; + +// rpc command handling array +static void *rpc_funcs_array[21] = { + (void *)sceMcInit, + (void *)sceMcOpen, + (void *)sceMcClose, + (void *)sceMcRead, + (void *)sceMcWrite, + (void *)sceMcSeek, + (void *)sceMcGetDir, + (void *)sceMcFormat, + (void *)sceMcGetInfo, + (void *)sceMcDelete, + (void *)sceMcFlush, + (void *)sceMcChDir, + (void *)sceMcSetFileInfo, + (void *)sceMcEraseBlock, + (void *)sceMcReadPage, + (void *)sceMcWritePage, + (void *)sceMcUnformat, + (void *)sceMcRead2, + (void *)sceMcGetInfo2, + (void *)sceMcGetEntSpace, + (void *)sceMcCheckBlock +}; + +static int mcserv_tidS_0400; + +static SifRpcDataQueue_t mcserv_qdS_0400 __attribute__((aligned(64))); +static SifRpcServerData_t mcserv_sdS_0400 __attribute__((aligned(64))); + +static u8 mcserv_rpc_buf[2048] __attribute__((aligned(64))); +static mcRpcStat_t rpc_stat __attribute__((aligned(64))); + +#define MCSERV_BUFSIZE 8192 +static u8 mcserv_buf[MCSERV_BUFSIZE] __attribute__((aligned(64))); + +extern struct irx_export_table _exp_mcserv; + +//-------------------------------------------------------------- +int _start(int argc, const char **argv) +{ + iop_thread_t thread_param; + register int thread_id; + iop_library_t *libptr; + int i, mcman_loaded; + void **export_tab; + +#ifdef SIO_DEBUG + sio_init(38400, 0, 0, 0, 0); +#endif + DPRINTF("_start...\n"); + + // Get mcman lib ptr + mcman_loaded = 0; + libptr = GetLoadcoreInternalData()->let_next; + while (libptr != 0) { + for (i=0; i<8; i++) { + if (libptr->name[i] != mcman_modname[i]) + break; + } + if (i == 8) { + mcman_loaded = 1; + break; + } + libptr = libptr->prev; + } + + if (!mcman_loaded) { + DPRINTF("mcman module is not loaded...\n"); + goto err_out; + } + + DPRINTF("mcman version=%03x\n", libptr->version); + if (libptr->version > 0x200) + mcman_type = XMCMAN; + + // Get mcman export table + export_tab = (void **)(((struct irx_export_table *)libptr)->fptrs); + + // Set functions pointers to match MCMAN exports + pMcDetectCard = export_tab[5]; + pMcOpen = export_tab[6]; + pMcClose = export_tab[7]; + pMcRead = export_tab[8]; + pMcWrite = export_tab[9]; + pMcSeek = export_tab[10]; + pMcFormat = export_tab[11]; + pMcGetDir = export_tab[12]; + pMcDelete = export_tab[13]; + pMcFlush = export_tab[14]; + pMcChDir = export_tab[15]; + pMcSetFileInfo = export_tab[16]; + pMcEraseBlock = export_tab[17]; + pMcReadPage = export_tab[18]; + pMcWritePage = export_tab[19]; + pMcDataChecksum = export_tab[20]; + pMcReplaceBadBlock = export_tab[24]; // dummy in MCMAN !!! + pMcReadPS1PDACard = export_tab[29]; + pMcWritePS1PDACard = export_tab[30]; + pMcUnformat = export_tab[36]; + pMcRetOnly = export_tab[37]; + pMcGetFreeClusters = export_tab[38]; + pMcGetMcType = export_tab[39]; + pMcSetPS1CardFlag = export_tab[40]; + + // Set functions pointers to match XMCMAN exports if needed + if (mcman_type == XMCMAN) { + pMcDetectCard2 = export_tab[21]; + pMcGetFormat = export_tab[22]; + pMcGetEntSpace = export_tab[23]; + pMcGetModuleInfo = export_tab[42]; + pMcCheckBlock = export_tab[45]; + } + + // Register mcserv dummy export table + DPRINTF("registering exports...\n"); + if (RegisterLibraryEntries(&_exp_mcserv) != 0) + goto err_out; + + CpuEnableIntr(); + + DPRINTF("starting RPC thread...\n"); + thread_param.attr = TH_C; + thread_param.thread = (void *)thread_rpc_S_0400; + thread_param.priority = 0x68; + thread_param.stacksize = 0x1000; + thread_param.option = 0; + + thread_id = CreateThread(&thread_param); + mcserv_tidS_0400 = thread_id; + + StartThread(thread_id, 0); + + DPRINTF("_start returns MODULE_RESIDENT_END...\n"); + + return MODULE_RESIDENT_END; + +err_out: + + DPRINTF("_start returns MODULE_NO_RESIDENT_END...\n"); + + return MODULE_NO_RESIDENT_END; +} + +//-------------------------------------------------------------- +void thread_rpc_S_0400(void* arg) +{ + if (!sceSifCheckInit()) + sceSifInit(); + + sceSifInitRpc(0); + sceSifSetRpcQueue(&mcserv_qdS_0400, GetThreadId()); + sceSifRegisterRpc(&mcserv_sdS_0400, 0x80000400, (void *)cb_rpc_S_0400, &mcserv_rpc_buf, NULL, NULL, &mcserv_qdS_0400); + sceSifRpcLoop(&mcserv_qdS_0400); +} + +//-------------------------------------------------------------- +void *cb_rpc_S_0400(u32 fno, void *buf, int size) +{ + // Rpc Callback function + int (*rpc_func)(void); + register int i; + + if (mcman_type == XMCMAN) { + for (i=0; i<16; i++) { // retrieve correct function number for xmcserv + if (fno == XMCSERV_RpcCmd[0][i]) { + fno = XMCSERV_RpcCmd[1][i]; + break; + } + } + } + else { // retrieve correct function number for mcserv + fno -= 112; + if (fno > 16) + return (void *)&rpc_stat; + } + + // Get function pointer + rpc_func = (void *)rpc_funcs_array[fno]; + + // Call needed rpc func + rpc_stat.result = rpc_func(); + + pMcReplaceBadBlock(); + + return (void *)&rpc_stat; +} + +//-------------------------------------------------------------- +int sceMcInit(void) +{ + register int r; + struct irx_id *ModuleInfo; + + r = _McInit(&mcserv_rpc_buf); + + if (mcman_type == XMCMAN) { + ModuleInfo = pMcGetModuleInfo(); + rpc_stat.mcserv_version = MODVER; + rpc_stat.mcman_version = ModuleInfo->v; + } + + return r; +} + +//-------------------------------------------------------------- +int sceMcOpen(void) +{ + return _McOpen(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcClose(void) +{ + return _McClose(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcRead(void) +{ + return _McRead(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcRead2(void) +{ + return _McRead2(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcWrite(void) +{ + return _McWrite(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcSeek(void) +{ + return _McSeek(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcGetDir(void) +{ + return _McGetDir(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcFormat(void) +{ + return _McFormat(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcUnformat(void) +{ + return _McUnformat(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcGetInfo(void) +{ + return _McGetInfo(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcGetInfo2(void) +{ + return _McGetInfo2(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcDelete(void) +{ + return _McDelete(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcFlush(void) +{ + return _McFlush(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcChDir(void) +{ + return _McChDir(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcEraseBlock(void) +{ + return _McEraseBlock(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcReadPage(void) +{ + return _McReadPage(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcWritePage(void) +{ + return _McWritePage(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcSetFileInfo(void) +{ + return _McSetFileInfo(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcGetEntSpace(void) +{ + return _McGetEntSpace(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int sceMcCheckBlock(void) +{ + return _McCheckBlock(&mcserv_rpc_buf); +} + +//-------------------------------------------------------------- +int _McInit(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + int ps1flag = 0; + + DPRINTF("_McInit fd %d offset %d\n", dP->fd, dP->offset); + + if (mcman_type == MCMAN) { + if (dP->offset == -217) + ps1flag = 1; + + pMcSetPS1CardFlag(ps1flag); + } + + return pMcRetOnly(dP->fd); +} + +//-------------------------------------------------------------- +int _McOpen(void *rpc_buf) +{ + mcNameParam_t *nP = (mcNameParam_t *)rpc_buf; + + DPRINTF("_McOpen port%d slot%d file %s flags %d\n", nP->port, nP->slot, nP->name, nP->flags); + + return pMcOpen(nP->port, nP->slot, nP->name, nP->flags); +} + +//-------------------------------------------------------------- +int _McClose(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + + DPRINTF("_McClose fd %d\n", dP->fd); + + return pMcClose(dP->fd); +} + +//-------------------------------------------------------------- +int _McSeek(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + + DPRINTF("_McSeek fd %d offset %d origin %d\n", dP->fd, dP->offset, dP->origin); + + return pMcSeek(dP->fd, dP->offset, dP->origin); +} + +//-------------------------------------------------------------- +int _McRead(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + register int file_offset, status; + register int left_to_read, size_readed, size_to_read; + mcEndParam_t eP; + SifDmaTransfer_t dmaStruct; + int intStatus; + void *eedata; + + DPRINTF("_McRead fd %d ee buffer addr %x size %d\n", dP->fd, (int)dP->buffer, dP->size); + + eP.size1 = 0; + eP.size2 = 0; + eP.dest1 = NULL; + eP.dest2 = NULL; + + size_readed = 0; + file_offset = 0; + + eedata = dP->buffer; + + eP.size1 = dP->size; + + if (dP->size > 16) + eP.size1 = (((int)(eedata)-1) & 0xfffffff0) - ((int)(eedata) - 16); + + eP.size2 = (dP->size - eP.size1) & 0x0f; + left_to_read = (dP->size - eP.size1) - eP.size2; + + if (eP.size2 != 0) + eP.dest2 = (void *)(eedata + eP.size1 + left_to_read); + + if (eP.size1 != 0) { + size_readed = pMcRead(dP->fd, eP.src1, eP.size1); + + if (size_readed < 0) { + eP.size1 = 0; + eP.size2 = 0; + goto dma_transfer2; + } + else { + file_offset = size_readed; + eP.dest1 = eedata; + eedata += size_readed; + + if (size_readed != eP.size1) { + eP.size1 = size_readed; + eP.size2 = 0; + size_readed = 0; + goto dma_transfer2; + } + else + size_readed = 0; + } + } + + while (left_to_read > 0) { + + size_to_read = left_to_read; + + if (left_to_read > MCSERV_BUFSIZE) + size_to_read = MCSERV_BUFSIZE; + + size_readed = pMcRead(dP->fd, mcserv_buf, size_to_read); + + if (size_readed < 0) { + eP.size2 = 0; + goto dma_transfer2; + } + + dmaStruct.src = (void *)mcserv_buf; + dmaStruct.dest = (void *)eedata; + dmaStruct.size = size_readed; + dmaStruct.attr = 0; + + CpuSuspendIntr(&intStatus); + sceSifSetDma(&dmaStruct, 1); + + file_offset += size_readed; + left_to_read -= size_readed; + + CpuResumeIntr(intStatus); + + eedata += size_readed; + + if (size_to_read != size_readed) { + eP.size2 = 0; + size_readed = 0; + goto dma_transfer2; + } + size_readed = 0; + } + + if (eP.size2 == 0) + goto dma_transfer2; + + size_readed = pMcRead(dP->fd, eP.src2, eP.size2); + + if (size_readed < 0) { + eP.size2 = 0; + goto dma_transfer2; + } + + file_offset += size_readed; + eP.size2 = size_readed; + size_readed = 0; + +dma_transfer2: + dmaStruct.src = (void *)&eP; + dmaStruct.dest = (void *)dP->param; + dmaStruct.size = sizeof (mcEndParam_t); + dmaStruct.attr = 0; + + CpuSuspendIntr(&intStatus); + status = sceSifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + + while (sceSifDmaStat(status) >= 0) + DelayThread(100); + + if (size_readed != 0) + return size_readed; + + return file_offset; +} + +//-------------------------------------------------------------- +int _McRead2(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + register int file_offset, status; + register int left_to_read, size_readed, size_to_read; + mcEndParam2_t eP; + SifDmaTransfer_t dmaStruct; + int intStatus; + void *eedata; + + DPRINTF("_McRead2 fd %d ee buffer addr %x size %d\n", dP->fd, (int)dP->buffer, dP->size); + + eP.size1 = 0; + eP.size2 = 0; + eP.dest1 = NULL; + eP.dest2 = NULL; + + size_readed = 0; + file_offset = 0; + + eedata = dP->buffer; + + eP.size1 = dP->size; + + if (dP->size > 64) + eP.size1 = (((u32)(eedata)-1) & 0xffffffc0) - ((u32)(eedata) - 64); + + eP.size2 = (dP->size - eP.size1) & 0x3f; + left_to_read = (dP->size - eP.size1) - eP.size2; + + if (eP.size2 != 0) + eP.dest2 = (void *)(eedata + eP.size1 + left_to_read); + + if (eP.size1 != 0) { + size_readed = pMcRead(dP->fd, eP.src1, eP.size1); + + if (size_readed < 0) { + eP.size1 = 0; + eP.size2 = 0; + goto dma_transfer2; + } + else { + file_offset = size_readed; + eP.dest1 = eedata; + eedata += size_readed; + + if (size_readed != eP.size1) { + eP.size1 = size_readed; + eP.size2 = 0; + size_readed = 0; + goto dma_transfer2; + } + else + size_readed = 0; + } + } + + while (left_to_read > 0) { + + size_to_read = left_to_read; + + if (left_to_read > MCSERV_BUFSIZE) + size_to_read = MCSERV_BUFSIZE; + + size_readed = pMcRead(dP->fd, mcserv_buf, size_to_read); + + if (size_readed < 0) { + eP.size2 = 0; + goto dma_transfer2; + } + + if (size_readed == size_to_read) { + dmaStruct.size = size_readed; + goto dma_transfer; + } + + eP.size2 = size_readed & 0x3f; + if ((size_readed & 0x3f) != 0) { + eP.dest2 = (void *)(eedata + (size_readed & 0xffffffc0)); + memcpy(eP.src2, (void *)(mcserv_buf + (size_readed & 0xffffffc0)), size_readed & 0x3f); + } + + if (eP.size2 == size_readed) + goto skip_dma_transfer; + + dmaStruct.size = size_readed - eP.size2; + +dma_transfer: + dmaStruct.src = (void *)mcserv_buf; + dmaStruct.dest = (void *)eedata; + dmaStruct.attr = 0; + + CpuSuspendIntr(&intStatus); + sceSifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + +skip_dma_transfer: + file_offset += size_readed; + left_to_read -= size_readed; + eedata += size_readed; + + if (size_to_read != size_readed) { + size_readed = 0; + goto dma_transfer2; + } + size_readed = 0; + } + + if (eP.size2 == 0) + goto dma_transfer2; + + size_readed = pMcRead(dP->fd, eP.src2, eP.size2); + + if (size_readed < 0) { + eP.size2 = 0; + goto dma_transfer2; + } + + file_offset += size_readed; + eP.size2 = size_readed; + size_readed = 0; + +dma_transfer2: + dmaStruct.src = (void *)&eP; + dmaStruct.dest = (void *)dP->param; + dmaStruct.size = sizeof (mcEndParam2_t); + dmaStruct.attr = 0; + + CpuSuspendIntr(&intStatus); + status = sceSifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + + while (sceSifDmaStat(status) >= 0) + DelayThread(100); + + if (size_readed != 0) + return size_readed; + + return file_offset; +} + +//-------------------------------------------------------------- +int _McWrite(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + SifRpcReceiveData_t rD; + register int size_to_write, size_written, r; + + DPRINTF("_McWrite fd %d ee buffer addr %x size %d\n", dP->fd, (int)dP->buffer, dP->size); + + size_written = 0; + + if (dP->origin != 0) { + size_written = pMcWrite(dP->fd, dP->data, dP->origin); + + if (size_written != dP->origin) + return size_written; + } + + while (dP->size > 0) { + + size_to_write = dP->size; + + if (dP->size > MCSERV_BUFSIZE) + size_to_write = MCSERV_BUFSIZE; + + sceSifGetOtherData(&rD, dP->buffer, &mcserv_buf, size_to_write, 0); + + r = pMcWrite(dP->fd, &mcserv_buf, size_to_write); + if (r != size_to_write) { + if (r < 0) + return r; + return r + size_written; + } + + size_written += size_to_write; + dP->size -= size_to_write; + + dP->buffer += size_to_write; + } + + return size_written; +} + +//-------------------------------------------------------------- +int _McGetDir(void *rpc_buf) +{ + mcNameParam_t *nP = (mcNameParam_t *)rpc_buf; + register int status, file_entries, flags, r; + SifDmaTransfer_t dmaStruct; + int intStatus; + + DPRINTF("_McGetDir port%d slot%d dir %s flags %d maxent %d mcT addr %x\n", nP->port, nP->slot, nP->name, nP->flags, nP->maxent, (int)nP->mcT); + + status = 0; + file_entries = 0; + flags = nP->flags; + + nP->maxent--; + + while (nP->maxent > -1) { + + r = pMcGetDir(nP->port, nP->slot, nP->name, flags & 0xffff, 1, (sceMcTblGetDir *)mcserv_buf); + if (r < 0) + return r; + if (r == 0) + goto dma_wait; + + file_entries++; + + dmaStruct.src = (void *)mcserv_buf; + dmaStruct.dest = (void *)nP->mcT; + dmaStruct.size = sizeof (sceMcTblGetDir); + dmaStruct.attr = 0; + + CpuSuspendIntr(&intStatus); + status = sceSifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + + flags = 1; + nP->mcT++; + nP->maxent--; + } + +dma_wait: + if (status == 0) + return file_entries; + + while (sceSifDmaStat(status) >= 0) + DelayThread(100); + + return file_entries; +} + +//-------------------------------------------------------------- +int _McChDir(void *rpc_buf) +{ + mcNameParam_t *nP = (mcNameParam_t *)rpc_buf; + register int status, r; + SifDmaTransfer_t dmaStruct; + int intStatus; + + DPRINTF("_McChDir port%d slot%d newdir %s\n", nP->port, nP->slot, nP->name); + + r = pMcChDir(nP->port, nP->slot, nP->name, (char *)mcserv_buf); + + dmaStruct.src = (void *)mcserv_buf; + dmaStruct.dest = (void *)nP->curdir; + dmaStruct.size = 1024; + dmaStruct.attr = 0; + + CpuSuspendIntr(&intStatus); + status = sceSifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + + while (sceSifDmaStat(status) >= 0) + DelayThread(100); + + return r; +} + +//-------------------------------------------------------------- +int _McFormat(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + + DPRINTF("_McFormat port%d slot%d\n", dP->port, dP->slot); + + return pMcFormat(dP->port, dP->slot); +} + +//-------------------------------------------------------------- +int _McUnformat(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + + DPRINTF("_McUnformat port%d slot%d\n", dP->port, dP->slot); + + return pMcUnformat(dP->port, dP->slot); +} + +//-------------------------------------------------------------- +int _McGetInfo(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + register int status, mc_free, r; + mcEndParam_t eP; + SifDmaTransfer_t dmaStruct; + int intStatus; + + DPRINTF("_McGetInfo port%d slot%d\n", dP->port, dP->slot); + + mc_free = 0; + + r = pMcDetectCard(dP->port, dP->slot); + + if (dP->size > 0) + eP.type = pMcGetMcType(dP->port, dP->slot); + + eP.free = 0; + if (r >= -1) { + if (dP->offset == 0) + goto dma_transfer; + + mc_free = pMcGetFreeClusters(dP->port, dP->slot); + if (mc_free >= 0) + eP.free = mc_free; + } + +dma_transfer: + + dmaStruct.src = (void *)&eP; + dmaStruct.dest = (void *)dP->param; + dmaStruct.size = sizeof (mcEndParam_t); + dmaStruct.attr = 0; + + CpuSuspendIntr(&intStatus); + status = sceSifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + + while (sceSifDmaStat(status) >= 0) + DelayThread(100); + + if (mc_free < 0) + return mc_free; + + return r; +} + +//-------------------------------------------------------------- +int _McGetInfo2(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + register int status, mc_free, r; + mcEndParam2_t eP; + SifDmaTransfer_t dmaStruct; + int intStatus; + + DPRINTF("_McGetInfo2 port%d slot%d\n", dP->port, dP->slot); + + mc_free = 0; + + r = pMcDetectCard2(dP->port, dP->slot); + + if (dP->origin > 0) + eP.type = pMcGetMcType(dP->port, dP->slot); + + if (r < -1) { + eP.free = 0; + eP.formatted = 0; + goto dma_transfer; + } + + if (dP->offset > 0) { + mc_free = pMcGetFreeClusters(dP->port, dP->slot); + + if (mc_free < 0) + eP.free = 0; + else + eP.free = mc_free; + } + + if (dP->size > 0) { + eP.formatted = 0; + if (pMcGetFormat(dP->port, dP->slot) > 0) + eP.formatted = 1; + } + +dma_transfer: + + dmaStruct.src = (void *)&eP; + dmaStruct.dest = (void *)dP->param; + dmaStruct.size = sizeof (mcEndParam2_t); + dmaStruct.attr = 0; + + CpuSuspendIntr(&intStatus); + status = sceSifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + + while (sceSifDmaStat(status) >= 0) + DelayThread(100); + + if (mc_free < 0) + return mc_free; + + return r; +} + +//-------------------------------------------------------------- +int _McGetEntSpace(void *rpc_buf) +{ + mcNameParam_t *nP = (mcNameParam_t *)rpc_buf; + + DPRINTF("_McGetEntSpace port%d slot%d dirname %s\n", nP->port, nP->slot, nP->name); + + return pMcGetEntSpace(nP->port, nP->slot, nP->name); +} + +//-------------------------------------------------------------- +int _McDelete(void *rpc_buf) +{ + mcNameParam_t *nP = (mcNameParam_t *)rpc_buf; + + DPRINTF("_McDelete port%d slot%d file %s flags %d\n", nP->port, nP->slot, nP->name, nP->flags); + + return pMcDelete(nP->port, nP->slot, nP->name, nP->flags); +} + +//-------------------------------------------------------------- +int _McFlush(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + + DPRINTF("_McFlush fd %d\n", dP->fd); + + return pMcFlush(dP->fd); +} + +//-------------------------------------------------------------- +int _McEraseBlock(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + register int pagenum, r; + u8 eccbuf[16]; + + DPRINTF("_McEraseBlock port%d slot%d offset %d\n", dP->port, dP->slot, dP->offset); + + dP->port = (dP->port & 1) + 2; + + if (pMcGetMcType(dP->port, dP->slot) == 2) { + r = pMcEraseBlock(dP->port, dP->offset, NULL, NULL); + if (r != 0) + return r; + + if (dP->origin == -1) + return r; + + memset(mcserv_buf, dP->origin, 512); + + pMcDataChecksum(&mcserv_buf[0], &eccbuf[0]); + pMcDataChecksum(&mcserv_buf[128], &eccbuf[3]); + pMcDataChecksum(&mcserv_buf[256], &eccbuf[6]); + pMcDataChecksum(&mcserv_buf[384], &eccbuf[9]); + + pagenum = 0; + + do { + r = pMcWritePage(dP->port, dP->slot, (dP->offset << 4) + pagenum, mcserv_buf, eccbuf); + + } while (++pagenum < 16); // <-- and the last page of the block ??? + + return r; + + } + + memset(mcserv_buf, dP->origin, 128); + + r = pMcWritePS1PDACard(dP->port, dP->slot, dP->offset, mcserv_buf); + + return r; +} + +//-------------------------------------------------------------- +int _McReadPage(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + mcEndParam_t eP; + register int status, fastsize, r, i, j; + SifDmaTransfer_t dmaStruct; + int intStatus; + + DPRINTF("_McReadPage port%d slot%d page %d\n", dP->port, dP->slot, dP->fd); + + eP.dest1 = dP->buffer; + + fastsize = ((u32)dP->buffer) & 0xf; + dP->port = (dP->port & 1) + 2; + + if (pMcGetMcType(dP->port, dP->slot) == 2) { + r = 0; + pMcReadPage(dP->port, dP->slot, dP->fd, (void *)(mcserv_buf + fastsize)); + } + else { + memset((void *)(mcserv_buf + fastsize), 0, 512); + r = pMcReadPS1PDACard(dP->port, dP->slot, dP->fd, (void *)(mcserv_buf + fastsize)); + } + + if (fastsize == 0) + goto fullpage; + + i = 0; + j = fastsize; + while (j < 16) { + eP.src1[i] = mcserv_buf[j]; + j++; + i++; + } + + j = 0; + if (fastsize > 0) { + while (j < 16) { + eP.src1[i] = mcserv_buf[512 + j]; + j++; + i++; + } + } + + dmaStruct.src = (void *)(mcserv_buf + 16); + dmaStruct.dest = (void *)(dP->buffer - (fastsize - 16)); + dmaStruct.size = 496; + dmaStruct.attr = 0; + goto dma_transfer; + +fullpage: + dmaStruct.src = (void *)mcserv_buf; + dmaStruct.dest = (void *)dP->buffer; + dmaStruct.size = 512; + dmaStruct.attr = 0; + +dma_transfer: + CpuSuspendIntr(&intStatus); + status = sceSifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + + dmaStruct.src = (void *)&eP; + dmaStruct.dest = (void *)dP->param; + dmaStruct.size = sizeof (mcEndParam_t); + dmaStruct.attr = 0; + + CpuSuspendIntr(&intStatus); + status = sceSifSetDma(&dmaStruct, 1); + CpuResumeIntr(intStatus); + + while (sceSifDmaStat(status) >= 0) + DelayThread(100); + + return r; +} + +//-------------------------------------------------------------- +int _McWritePage(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + register int fastsize, i, j; + SifRpcReceiveData_t rD; + u8 eccbuf[16]; + + DPRINTF("_McWritePage port%d slot%d page %d\n", dP->port, dP->slot, dP->fd); + + fastsize = ((u32)dP->buffer) & 0xf; + if (fastsize == 0) + goto fullpage; + + sceSifGetOtherData(&rD, (void *)(dP->buffer - (fastsize - 16)), &mcserv_buf, 496, 0); + + i = fastsize; + while (i < 16) { + mcserv_buf[i] = dP->data[i - fastsize]; + i++; + } + + if (fastsize == 0) + goto ecc_calc; + + + j = 16; + i = 0; + while (i < fastsize) { + mcserv_buf[496 + j] = dP->data[j - fastsize]; + i++; + j++; + } + + goto ecc_calc; + +fullpage: + + sceSifGetOtherData(&rD, dP->buffer, &mcserv_buf, 512, 0); + +ecc_calc: + + pMcDataChecksum((void *)(mcserv_buf + fastsize), &eccbuf[0]); + pMcDataChecksum(&mcserv_buf[128], &eccbuf[3]); + pMcDataChecksum(&mcserv_buf[256], &eccbuf[6]); + pMcDataChecksum(&mcserv_buf[384], &eccbuf[9]); + + return pMcWritePage((dP->port & 1) | 2, dP->slot, dP->fd, (void *)(mcserv_buf + fastsize), eccbuf); +} + +//-------------------------------------------------------------- +int _McSetFileInfo(void *rpc_buf) +{ + mcNameParam_t *nP = (mcNameParam_t *)rpc_buf; + SifRpcReceiveData_t rD; + + DPRINTF("_McSetFileInfo port%d slot%d file %s flags %d\n", nP->port, nP->slot, nP->name, nP->flags); + + sceSifGetOtherData(&rD, (void *)nP->mcT, &mcserv_buf, sizeof (sceMcTblGetDir), 0); + + return pMcSetFileInfo(nP->port, nP->slot, nP->name, (sceMcTblGetDir *)mcserv_buf, nP->flags); +} + +//-------------------------------------------------------------- +int _McCheckBlock(void *rpc_buf) +{ + mcDescParam_t *dP = (mcDescParam_t *)rpc_buf; + + DPRINTF("_McCheckBlock port%d slot%d block %d\n", dP->port, dP->slot, dP->offset); + + return pMcCheckBlock(dP->port, dP->slot, dP->offset); +} + +//-------------------------------------------------------------- diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/mcserv.h b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/mcserv.h new file mode 100644 index 0000000..8c7d5d7 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/mcserv/src/mcserv.h @@ -0,0 +1,105 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright (c) 2009 jimmikaelkael +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +*/ + +#ifndef __MCSERV_H__ +#define __MCSERV_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "mcman_imports.h" + +//#define DEBUG + +#define MODNAME "mcserv" +#define MODVER 0x208 + +#ifdef SIO_DEBUG + #include + #define DEBUG + #define DPRINTF(format, args...) \ + sio_printf(MODNAME ": " format, ##args) +#else + #ifdef DEBUG + #define DPRINTF(format, args...) \ + printf(MODNAME ": " format, ##args) + #else + #define DPRINTF(format, args...) + #endif +#endif + + +// internal function prototypes +void *cb_rpc_S_0400(u32 fno, void *buf, int size); +void thread_rpc_S_0400(void* param); +int sceMcInit(void); +int sceMcOpen(void); +int sceMcClose(void); +int sceMcRead(void); +int sceMcWrite(void); +int sceMcSeek(void); +int sceMcGetDir(void); +int sceMcFormat(void); +int sceMcGetInfo(void); +int sceMcDelete(void); +int sceMcFlush(void); +int sceMcChDir(void); +int sceMcSetFileInfo(void); +int sceMcEraseBlock(void); +int sceMcReadPage(void); +int sceMcWritePage(void); +int sceMcUnformat(void); +int sceMcRead2(void); +int sceMcGetInfo2(void); +int sceMcGetEntSpace(void); +int sceMcCheckBlock(void); + +int _McInit(void *rpc_buf); +int _McOpen(void *rpc_buf); +int _McClose(void *rpc_buf); +int _McRead(void *rpc_buf); +int _McWrite(void *rpc_buf); +int _McSeek(void *rpc_buf); +int _McGetDir(void *rpc_buf); +int _McFormat(void *rpc_buf); +int _McGetInfo(void *rpc_buf); +int _McDelete(void *rpc_buf); +int _McFlush(void *rpc_buf); +int _McChDir(void *rpc_buf); +int _McSetFileInfo(void *rpc_buf); +int _McEraseBlock(void *rpc_buf); +int _McReadPage(void *rpc_buf); +int _McWritePage(void *rpc_buf); +int _McUnformat(void *rpc_buf); +int _McRead2(void *rpc_buf); +int _McGetInfo2(void *rpc_buf); +int _McGetEntSpace(void *rpc_buf); +int _McCheckBlock(void *rpc_buf); + +// filename related mc command +// used by: mcOpen, mcGetDir, mcChdir, mcDelete, mcSetFileInfo, mcRename, mcGetEntSpace +typedef struct { // size = 1044 + int port; // 0 + int slot; // 4 + int flags; // 8 + int maxent; // 12 + union { + sceMcTblGetDir *mcT; // 16 + char *curdir; + }; + char name[1024]; // 20 +} mcNameParam_t; + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/memorycard/xfromman/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/xfromman/Makefile new file mode 100644 index 0000000..4f6022e --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/memorycard/xfromman/Makefile @@ -0,0 +1,18 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +IOP_SRC_DIR = $(PS2SDKSRC)/iop/memorycard/mcman/src/ +IOP_INC_DIR = $(PS2SDKSRC)/iop/memorycard/mcman/include/ + +IOP_BIN ?= xfromman.irx + +IOP_CFLAGS += -DBUILDING_XFROMMAN + +IOP_INCS += -I$(PS2SDKSRC)/iop/dev9/extflash/include + +include $(PS2SDKSRC)/iop/memorycard/mcman/Makefile diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/sio/Makefile new file mode 100644 index 0000000..5cbec08 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/Makefile @@ -0,0 +1,12 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + +SUBDIRS = mx4sio_bd mx4sio_bd_mini + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/Rules.make diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/Makefile b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/Makefile new file mode 100644 index 0000000..7359169 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/Makefile @@ -0,0 +1,17 @@ +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. + + +IOP_INCS += -I$(PS2SDKSRC)/iop/fs/bdm/include -I$(PS2SDKSRC)/iop/system/sio2man/include + +IOP_OBJS = spi_sdcard_crc7.o spi_sdcard_driver.o crc16.o ioplib.o sio2man_hook.o mx4sio.o imports.o + +include $(PS2SDKSRC)/Defs.make +include $(PS2SDKSRC)/iop/Rules.bin.make +include $(PS2SDKSRC)/iop/Rules.make +include $(PS2SDKSRC)/iop/Rules.release diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/crc16.c b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/crc16.c new file mode 100644 index 0000000..ddcb341 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/crc16.c @@ -0,0 +1,26 @@ +#include "crc16.h" + + +uint16_t crc16(void* buf, int len) +{ + uint16_t* bf = buf; + uint32_t poly = 0, polyIn, di; //Initializing poly to 0 AND using it as initializer in the loop for polyIn results in the compiler forcing it always to 0 in the loop (so don't use variables as initializers - i.e. u32 polyIn = poly; ). + int i; + len /= 2; //to u16 + for (i = 0; i < len; i++) { + di = (((bf[i]) << 8) & 0xFF00) | (((bf[i]) >> 8) & 0xFF); + polyIn = poly; + //PPC has an instruction for shifting and masking (continuous mask) at the same time. + //This sequence must be folowed because some of the bits altered in the first operations are used in the folowing. + polyIn ^= ((polyIn ^ di) >> 4) & 0x0F00; + polyIn ^= ((polyIn ^ di) >> 4) & 0x00F0; + polyIn ^= ((polyIn ^ di) >> 11) & 0x001F; + polyIn ^= ((polyIn ^ di) >> 4) & 0x000F; + polyIn ^= di; + poly = polyIn ^ (polyIn << 5) ^ (polyIn << 12); + } + + uint16_t crc = poly; + return crc; +} + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/crc16.h b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/crc16.h new file mode 100644 index 0000000..884b73a --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/crc16.h @@ -0,0 +1,8 @@ +#ifndef CRC16_H +#define CRC16_H + +#include "stdint.h" + +uint16_t crc16(void* buf, int len); + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/imports.lst b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/imports.lst new file mode 100644 index 0000000..e959396 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/imports.lst @@ -0,0 +1,57 @@ +bdm_IMPORTS_start +I_bdm_connect_bd +I_bdm_disconnect_bd +bdm_IMPORTS_end + +dmacman_IMPORTS_start +I_dmac_request +I_dmac_transfer +I_dmac_ch_set_dpcr +I_dmac_enable +//I_dmac_disable +dmacman_IMPORTS_end + +intrman_IMPORTS_start +I_DisableIntr +I_EnableIntr +I_RegisterIntrHandler +I_CpuSuspendIntr +I_CpuResumeIntr +intrman_IMPORTS_end + +loadcore_IMPORTS_start +I_GetLoadcoreInternalData +loadcore_IMPORTS_end + +#ifndef MINI_DRIVER +stdio_IMPORTS_start +I_printf +stdio_IMPORTS_end +#endif + +sysclib_IMPORTS_start +I_strcmp +stdio_IMPORTS_end + +thbase_IMPORTS_start +I_CreateThread +I_StartThread +I_DeleteThread +I_DelayThread +thbase_IMPORTS_end + +thevent_IMPORTS_start +I_CreateEventFlag +I_DeleteEventFlag +//I_SetEventFlag +I_iSetEventFlag +I_ClearEventFlag +I_WaitEventFlag +thevent_IMPORTS_end + +thsemap_IMPORTS_start +I_CreateSema +I_WaitSema +I_SignalSema +I_DeleteSema +thsemap_IMPORTS_end diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/ioplib.c b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/ioplib.c new file mode 100644 index 0000000..501a172 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/ioplib.c @@ -0,0 +1,78 @@ +#include "ioplib.h" +#include + +iop_library_t* ioplib_getByName(char* name) +{ + iop_library_t* libptr; + int i; + + // Get first loaded library + libptr = GetLoadcoreInternalData()->let_next; + // Loop through all loaded libraries + while (libptr != NULL) { + // Compare library name only + for (i = 0; i < 8; i++) { + if (libptr->name[i] != name[i]) + break; + } + + // Return if match + if (i == 8) + return libptr; + + // Next library + libptr = libptr->prev; + } + + return NULL; +} + +unsigned int ioplib_getTableSize(iop_library_t* lib) +{ + void** exp; + unsigned int size; + + exp = lib->exports; + size = 0; + + if (exp != NULL) + while (*exp++ != NULL) + size++; + + return size; +} + +void* ioplib_hookExportEntry(iop_library_t* lib, unsigned int entry, void* func) +{ + if (entry < ioplib_getTableSize(lib)) { + int oldstate; + void **exp, *temp; + + exp = &lib->exports[entry]; + + CpuSuspendIntr(&oldstate); + temp = *exp; + *exp = func; + func = temp; + CpuResumeIntr(oldstate); + + return func; + } + + return NULL; +} + +void ioplib_relinkExports(iop_library_t* lib) +{ + struct irx_import_table* table; + struct irx_import_stub* stub; + + // go through each table that imports the library + for (table = lib->caller; table != NULL; table = table->next) { + // go through each import in the table + for (stub = (struct irx_import_stub*)table->stubs; stub->jump != 0; stub++) { + // patch the stub to jump to the address specified in the library export table for "fno" + stub->jump = 0x08000000 | (((u32)lib->exports[stub->fno] << 4) >> 6); + } + } +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/ioplib.h b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/ioplib.h new file mode 100644 index 0000000..04a7a2e --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/ioplib.h @@ -0,0 +1,14 @@ +#ifndef IOPLIB_H +#define IOPLIB_H + + +#include + + +iop_library_t *ioplib_getByName(char *name); +unsigned int ioplib_getTableSize(iop_library_t *lib); +void *ioplib_hookExportEntry(iop_library_t *lib, unsigned int entry, void *func); +void ioplib_relinkExports(iop_library_t *lib); + + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/irx_imports.h b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/irx_imports.h new file mode 100644 index 0000000..39ad21b --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/irx_imports.h @@ -0,0 +1,31 @@ +/* +# _____ ___ ____ ___ ____ +# ____| | ____| | | |____| +# | ___| |____ ___| ____| | \ PS2DEV Open Source Project. +#----------------------------------------------------------------------- +# Copyright 2001-2004, ps2dev - http://www.ps2dev.org +# Licenced under Academic Free License version 2.0 +# Review ps2sdk README & LICENSE files for further details. +# +# $Id$ +# Defines all IRX imports. +*/ + +#ifndef IOP_IRX_IMPORTS_H +#define IOP_IRX_IMPORTS_H + +#include "irx.h" + +/* Please keep these in alphabetical order! */ +#include "bdm.h" +#include "dmacman.h" +#include "intrman.h" +#include "loadcore.h" +#include "stdio.h" +#include "sysclib.h" +#include "thbase.h" +#include "thevent.h" +#include "thsemap.h" + + +#endif /* IOP_IRX_IMPORTS_H */ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/module_debug.h b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/module_debug.h new file mode 100644 index 0000000..ba5ca8c --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/module_debug.h @@ -0,0 +1,19 @@ +#ifndef _MODULE_DEBUG_H +#define _MODULE_DEBUG_H + +//#define MINI_DRIVER + +#ifndef MINI_DRIVER +#include "stdio.h" +#define M_PRINTF(format, args...) printf("MX4SIO: " format, ##args) +#else +#define M_PRINTF(format, args...) +#endif + +#ifdef DEBUG +#define M_DEBUG M_PRINTF +#else +#define M_DEBUG(format, args...) +#endif + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/mx4sio.c b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/mx4sio.c new file mode 100644 index 0000000..c179f5d --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/mx4sio.c @@ -0,0 +1,997 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "crc16.h" +#include "ioplib.h" +#include "sio2man_hook.h" +#include "sio2regs.h" +#include "spi_sdcard_driver.h" + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +IRX_ID("mx4sio", 1, 1); + +#define WELCOME_STR "mx4sio v1.1\n" + +// Options +#define CONFIG_USE_CRC16 // A little slower ~ 1700 KB/s -> 1400 KB/s + +// 3 is the second memory card slot +#define PORT_NR 3 +#define MAX_SIO2_TRANSFER_SIZE 256 // 0x100 +#define SECTOR_SIZE 512 +#define MAX_SECTORS 64 +#define MAX_RETRIES 4 + +/* Event flags */ +#define EF_SIO2_INTR_REVERSE 0x00000100 +#define EF_SIO2_INTR_COMPLETE 0x00000200 + +static int event_flag = -1; +static int sd_detect_thread_id = -1; +static u32 sio2man_save_crtl; +static int card_used = 0; +static int card_inserted = 0; +// Fast SPI clock +static int fastDiv = 0; +// Slave/Chip Select +static int spi_ss = 0; +// SIO tranfer data, only 1 transfer at a time possible +static sio2_transfer_data_t global_td; + +struct dma_command { + uint8_t* buffer; + u16 sector_count; + volatile u16 sectors_transferred; // written by isr, read by thread + u16 sectors_reversed; + u16 portNr; +#ifdef CONFIG_USE_CRC16 + u16 crc[MAX_SECTORS]; +#endif + uint8_t response; + volatile uint8_t abort; // written by thread, read by isr +}; +struct dma_command cmd; + +static uint8_t wait_equal(uint8_t value, int count, int portNr); +static void sendCmd_Rx_DMA_start(uint8_t* rdBufA, int portNr); +static inline u8 reverseByte_LUT8(u8 n); +static inline void reverseBuffer32(u32* buffer, u32 count); + +int sio2_intr_handler(void* arg) +{ + int ef = *(int *)arg; + int eflags = EF_SIO2_INTR_REVERSE; + + // Clear interrupt? + inl_sio2_stat_set(inl_sio2_stat_get()); + + // Wait for completion + while ((inl_sio2_stat6c_get() & (1 << 12)) == 0) + ; + + // Finish sector read, read 2 crc bytes +#ifdef CONFIG_USE_CRC16 + cmd.crc[cmd.sectors_transferred] = reverseByte_LUT8(inl_sio2_data_in()) << 8; + cmd.crc[cmd.sectors_transferred] |= reverseByte_LUT8(inl_sio2_data_in()); +#else + inl_sio2_data_in(); + inl_sio2_data_in(); +#endif + cmd.sectors_transferred++; + + if ((cmd.abort == 0) && (cmd.sectors_transferred < cmd.sector_count)) { + // Start next DMA transfer ASAP + cmd.response = wait_equal(0xFE, 200, cmd.portNr); + if (cmd.response == SPISD_RESULT_OK) + sendCmd_Rx_DMA_start(&cmd.buffer[cmd.sectors_transferred * SECTOR_SIZE], cmd.portNr); + } + + if ((cmd.abort == 1) || (cmd.sectors_transferred >= cmd.sector_count) || (cmd.response != SPISD_RESULT_OK)) { + // Done or error, notify user task + eflags |= EF_SIO2_INTR_COMPLETE; + } + + iSetEventFlag(ef, eflags); + + return 1; +} + +static unsigned char reverseByte_LUT8_table[256] = { + 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, + 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, + 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, + 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, + 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, + 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, + 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, + 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, + 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, + 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, + 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, + 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, + 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, + 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, + 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, + 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, + 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, + 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, + 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, + 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, + 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, + 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, + 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, + 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, + 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, + 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, + 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, + 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, + 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, + 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, + 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, + 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff +}; + +static inline u8 reverseByte_LUT8(u8 n) +{ + return reverseByte_LUT8_table[n]; +} + +static u32 reverseByteInWord_mask(u32 n, u32 maskF, u32 mask3, u32 mask5) +{ + n = ((n & (maskF << 4)) >> 4) | ((n & maskF) << 4); + n = ((n & (mask3 << 2)) >> 2) | ((n & mask3) << 2); + n = ((n & (mask5 << 1)) >> 1) | ((n & mask5) << 1); + return n; +} + +static inline u32 reverseByteInWord(u32 n) +{ + return reverseByteInWord_mask(n, 0x0F0F0F0F, 0x33333333, 0x55555555); +} + +/* The masks need to be defined as registers outside of the loop + * This extra function makes sure gcc 3.2.3 generates an efficient function + * Inner loop with 19 instructions: + $L38: + and $2,$2,$10 + sll $3,$3,4 + srl $2,$2,4 + or $2,$2,$3 + and $4,$2,$7 + and $2,$2,$9 + srl $2,$2,2 + sll $4,$4,2 + or $2,$2,$4 + and $3,$2,$12 + and $2,$2,$5 + srl $2,$2,1 + sll $3,$3,1 + or $2,$2,$3 + sw $2,0($8) + addu $8,$8,4 + lw $2,0($8) + bne $8,$11,$L38 + and $3,$2,$6 +*/ +static void reverseBuffer32_mask(u32* buffer, u32 count, u32 maskF, u32 mask3, u32 mask5) +{ + u32 n = *buffer; + u32* end = buffer + count; + + while (buffer != end) { + n = ((n & (maskF <<4)) >>4) | ((n & maskF) <<4); + n = ((n & (mask3 <<2)) >>2) | ((n & mask3) <<2); + n = ((n & (mask5 <<1)) >>1) | ((n & mask5) <<1); + + *buffer = n; + buffer++; + n = *buffer; + } +} + +// 7037KB/s (FAT PS2, GCC 3.2.3, -O3) +// 12052KB/s (slim PS2, GCC 3.2.3, -O3) +static inline void reverseBuffer32(u32* buffer, u32 count) +{ + reverseBuffer32_mask(buffer, count, 0x0F0F0F0F, 0x33333333, 0x55555555); +} + +// 4194KB/s (FAT PS2, GCC 3.2.3, -O3) +// 3771KB/s (slim PS2, GCC 3.2.3, -O3) +static inline void reverseBuffer8x1_LUT(u8* buffer, u32 count) +{ + u8* end = buffer + count; + + while (buffer != end) { + *buffer = reverseByte_LUT8(*buffer); + buffer++; + } +} + +static void _init_td(sio2_transfer_data_t* td, int portNr) +{ + static const uint8_t TxByte = 0xff; + static uint8_t RxByte; + int i; + + /* + * Clock divider for 48MHz clock: + * 1 = 48 MHz - Damaged data + * 2 = 24 MHz - Fastest usable speed + * 3 = 16 MHz + * 4 = 12 MHz + * 5 = 9.6MHz + * 6 = 6 MHz + * ... + * 0x78 = 400KHz - Initialization speed + */ + const int slowDivVal = 0x78; + const int fastDivVal = 2; + const int interBytePer = 0; //2; + + for (i = 0; i < 4; i++) { + td->port_ctrl1[i] = 0; + td->port_ctrl2[i] = 0; + } + + td->port_ctrl1[portNr] = + PCTRL0_ATT_LOW_PER(0x5) | + PCTRL0_ATT_MIN_HIGH_PER(0x5) | + PCTRL0_BAUD0_DIV(slowDivVal) | + PCTRL0_BAUD1_DIV(fastDivVal); + + td->port_ctrl2[portNr] = + PCTRL1_ACK_TIMEOUT_PER(0x12C) | + PCTRL1_INTER_BYTE_PER(interBytePer) | + PCTRL1_UNK24(0) | + PCTRL1_IF_MODE_SPI_DIFF(0); + + // create dummy transfer to unlock old rom0:SIO2MAN + // - Tx 1 byte PIO + // - Rx 1 byte PIO + td->regdata[0] = + TR_CTRL_PORT_NR(portNr) | + TR_CTRL_PAUSE(0) | + TR_CTRL_TX_MODE_PIO_DMA(0) | + TR_CTRL_RX_MODE_PIO_DMA(0) | + TR_CTRL_NORMAL_TR(1) | + TR_CTRL_SPECIAL_TR(0) | + TR_CTRL_TX_DATA_SZ(1) | + TR_CTRL_RX_DATA_SZ(1) | + TR_CTRL_BAUD_DIV(fastDiv) | + TR_CTRL_WAIT_ACK_FOREVER(0); + td->regdata[1] = 0; + + // Tx 1 byte PIO + td->in_size = 1; + td->in = (void*)&TxByte; + td->in_dma.addr = NULL; + td->in_dma.size = 0; + td->in_dma.count = 0; + + // Rx 1 byte PIO + td->out_size = 1; + td->out = &RxByte; + td->out_dma.addr = NULL; + td->out_dma.size = 0; + td->out_dma.count = 0; +} + +static void _init_ports(sio2_transfer_data_t* td) +{ + int i; + + for (i = 0; i < 4; i++) { + inl_sio2_portN_ctrl1_set(i, td->port_ctrl1[i]); + inl_sio2_portN_ctrl2_set(i, td->port_ctrl2[i]); + } +} + +static uint8_t sendCmd_Tx1_Rx1(uint8_t data, int portNr) +{ + inl_sio2_ctrl_set(0x0bc); // no interrupt + + inl_sio2_regN_set(0, + TR_CTRL_PORT_NR(portNr) | + TR_CTRL_PAUSE(0) | + TR_CTRL_TX_MODE_PIO_DMA(0) | + TR_CTRL_RX_MODE_PIO_DMA(0) | + TR_CTRL_NORMAL_TR(1) | + TR_CTRL_SPECIAL_TR(0) | + TR_CTRL_BAUD_DIV(fastDiv) | + TR_CTRL_WAIT_ACK_FOREVER(0) | + TR_CTRL_TX_DATA_SZ(1) | + TR_CTRL_RX_DATA_SZ(1)); + inl_sio2_regN_set(1, 0); + + // Put byte in queue + inl_sio2_data_out(reverseByte_LUT8(data)); + + // Start queue exec + inl_sio2_ctrl_set(inl_sio2_ctrl_get() | 1); + + // Wait for completion + while ((inl_sio2_stat6c_get() & (1 << 12)) == 0) + ; + + // Get byte from queue + return reverseByte_LUT8(inl_sio2_data_in()); +} + +static void sendCmd_Tx_PIO(const uint8_t* wrBufA, int sndSz, int portNr) +{ + inl_sio2_ctrl_set(0x0bc); // no interrupt + + inl_sio2_regN_set(0, + TR_CTRL_PORT_NR(portNr) | + TR_CTRL_PAUSE(0) | + TR_CTRL_TX_MODE_PIO_DMA(0) | + TR_CTRL_RX_MODE_PIO_DMA(0) | + TR_CTRL_NORMAL_TR(1) | + TR_CTRL_SPECIAL_TR(0) | + TR_CTRL_BAUD_DIV(fastDiv) | + TR_CTRL_WAIT_ACK_FOREVER(0) | + TR_CTRL_TX_DATA_SZ(sndSz) | + TR_CTRL_RX_DATA_SZ(0)); + inl_sio2_regN_set(1, 0); + + // PIO: IOP -> SIO2 + // Fill the queue + while (sndSz--) + inl_sio2_data_out(reverseByte_LUT8(*wrBufA++)); + + // Start queue exec + inl_sio2_ctrl_set(inl_sio2_ctrl_get() | 1); + + // Wait for completion + while ((inl_sio2_stat6c_get() & (1 << 12)) == 0) + ; +} + +static void sendCmd_Rx_PIO(uint8_t* rdBufA, int rcvSz, int portNr) +{ + inl_sio2_ctrl_set(0x0bc); // no interrupt + + inl_sio2_regN_set(0, + TR_CTRL_PORT_NR(portNr) | + TR_CTRL_PAUSE(0) | + TR_CTRL_TX_MODE_PIO_DMA(0) | + TR_CTRL_RX_MODE_PIO_DMA(0) | + TR_CTRL_NORMAL_TR(1) | + TR_CTRL_SPECIAL_TR(0) | + TR_CTRL_BAUD_DIV(fastDiv) | + TR_CTRL_WAIT_ACK_FOREVER(0) | + TR_CTRL_TX_DATA_SZ(0) | + TR_CTRL_RX_DATA_SZ(rcvSz)); + inl_sio2_regN_set(1, 0); + + // Start queue exec + inl_sio2_ctrl_set(inl_sio2_ctrl_get() | 1); + + // Wait for completion + while ((inl_sio2_stat6c_get() & (1 << 12)) == 0) + ; + + // PIO: IOP <- SIO2 + // Empty the queue + while (rcvSz--) + *rdBufA++ = reverseByte_LUT8(inl_sio2_data_in()); +} + +static uint8_t wait_equal(uint8_t value, int count, int portNr) +{ + uint32_t i; + uint8_t response = 0; + + for (i = 0; i < count; i++) { + response = sendCmd_Tx1_Rx1(0xff, portNr); + if (response == value) + break; + } + + return (response != value) ? SPISD_RESULT_ERROR : SPISD_RESULT_OK; +} + +static void sendCmd_Rx_DMA_start(uint8_t* rdBufA, int portNr) +{ + const uint32_t trSettingsDMA = + TR_CTRL_PAUSE(0) | + TR_CTRL_TX_MODE_PIO_DMA(0) | + TR_CTRL_RX_MODE_PIO_DMA(1) | + TR_CTRL_NORMAL_TR(1) | + TR_CTRL_SPECIAL_TR(0) | + TR_CTRL_TX_DATA_SZ(0) | + TR_CTRL_RX_DATA_SZ(0x100) | + TR_CTRL_BAUD_DIV(1) | + TR_CTRL_WAIT_ACK_FOREVER(0); + + const uint32_t trSettingsPIO = + TR_CTRL_PAUSE(0) | + TR_CTRL_TX_MODE_PIO_DMA(0) | + TR_CTRL_RX_MODE_PIO_DMA(0) | + TR_CTRL_NORMAL_TR(1) | + TR_CTRL_SPECIAL_TR(0) | + TR_CTRL_TX_DATA_SZ(0) | + TR_CTRL_RX_DATA_SZ(2) | + TR_CTRL_BAUD_DIV(1) | + TR_CTRL_WAIT_ACK_FOREVER(0); + + inl_sio2_ctrl_set(0x0bc); // no interrupt + + inl_sio2_regN_set(0, trSettingsDMA | TR_CTRL_PORT_NR(portNr)); + inl_sio2_regN_set(1, trSettingsDMA | TR_CTRL_PORT_NR(portNr)); + inl_sio2_regN_set(2, trSettingsPIO | TR_CTRL_PORT_NR(portNr)); + inl_sio2_regN_set(3, 0); + + dmac_request(IOP_DMAC_SIO2out, rdBufA, 0x100 >> 2, 2, DMAC_TO_MEM); + dmac_transfer(IOP_DMAC_SIO2out); + + // Start queue exec + inl_sio2_ctrl_set(inl_sio2_ctrl_get() | 1); +} + +static void sio2_lock() +{ + int state; + + //M_DEBUG("%s()\n", __FUNCTION__); + + // Lock sio2man driver so we can use it exclusively + sio2man_hook_sio2_lock(); + + // Save ctrl state + sio2man_save_crtl = inl_sio2_ctrl_get(); + + // We're in control, setup the ports for our use + _init_ports(&global_td); + + // Enable DMA interrupts + CpuSuspendIntr(&state); + RegisterIntrHandler(IOP_IRQ_DMA_SIO2_OUT, 1, sio2_intr_handler, &event_flag); + EnableIntr(IOP_IRQ_DMA_SIO2_OUT); + CpuResumeIntr(state); +} + +static void sio2_unlock() +{ + int state; + int res; + + // Disable DMA interrupts + CpuSuspendIntr(&state); + DisableIntr(IOP_IRQ_DMA_SIO2_OUT, &res); + CpuResumeIntr(state); + + // Restore ctrl state, and reset STATE + FIFOS + inl_sio2_ctrl_set(sio2man_save_crtl | 0xc); + + // Unlock sio2man driver + sio2man_hook_sio2_unlock(); + + //M_DEBUG("%s()\n", __FUNCTION__); +} + +/* + * SPI interface: + * - "spi_sdcard" library -> SPI + */ +static void ps2_spi_set_speed(uint32_t freq) +{ + int newFastDiv = freq > 400000; + + //M_DEBUG("%s(%d)\n", __FUNCTION__, (int)freq); + + if (fastDiv != newFastDiv) { + M_DEBUG("%s(%d)\n", __FUNCTION__, (int)freq); + + fastDiv = newFastDiv; + _init_td(&global_td, PORT_NR); + _init_ports(&global_td); + } +} + +static void ps2_spi_select(void) +{ + //M_DEBUG("%s()\n", __FUNCTION__); + spi_ss = 1; +} + +static void ps2_spi_relese(void) +{ + //M_DEBUG("%s()\n", __FUNCTION__); + spi_ss = 0; +} + +static bool ps2_spi_is_present(void) +{ + //M_DEBUG("%s()\n", __FUNCTION__); + return true; +} + +static uint8_t ps2_spi_wr_rd_byte(uint8_t byte) +{ + if (spi_ss == 0) { + // We're ignoring a lot of dummy read/writes, this is not an error + //M_DEBUG("%s(%d) - ignoring, not selected\n", __FUNCTION__, byte); + return 0; + } + + //M_DEBUG("%s(%d)\n", __FUNCTION__, byte); + return sendCmd_Tx1_Rx1(byte, PORT_NR); +} + +static void ps2_spi_write(uint8_t const* buffer, uint32_t size) +{ + uint32_t ts; + + if (spi_ss == 0) { + M_DEBUG("%s(..., %d) - ignoring, not selected\n", __FUNCTION__, (int)size); + return; + } + + //M_DEBUG("%s(..., %d)\n", __FUNCTION__, (int)size); + while (size > 0) { + ts = size > MAX_SIO2_TRANSFER_SIZE ? MAX_SIO2_TRANSFER_SIZE : size; + sendCmd_Tx_PIO(buffer, ts, PORT_NR); + buffer += ts; + size -= ts; + } +} + +static void ps2_spi_read(uint8_t* buffer, uint32_t size) +{ + uint32_t ts; + + if (spi_ss == 0) { + M_DEBUG("%s(..., %d) - ignoring, not selected\n", __FUNCTION__, (int)size); + return; + } + + //M_DEBUG("%s(..., %d)\n", __FUNCTION__, (int)size); + while (size > 0) { + ts = size > MAX_SIO2_TRANSFER_SIZE ? MAX_SIO2_TRANSFER_SIZE : size; + sendCmd_Rx_PIO((uint8_t*)buffer, ts, PORT_NR); + buffer += ts; + size -= ts; + } +} + +static spisd_interface_t spi = { + ps2_spi_set_speed, + ps2_spi_select, + ps2_spi_relese, + ps2_spi_is_present, + ps2_spi_wr_rd_byte, + ps2_spi_write, + ps2_spi_read +}; + +static int spisd_init_recovery() +{ + int rv, i; + + M_DEBUG("%s\n", __FUNCTION__); + + // Flush 256B + for (i = 0; i < 64; i++) + sendCmd_Rx_PIO((void*)&rv, 4, PORT_NR); + + return spisd_init(&spi); +} + +static int _msread_start(struct block_device* bd, u32 sector) +{ + int rv, i; + + for (i = 0; i < 10; i++) { + // Wait idle + rv = wait_equal(0xFF, 4000, PORT_NR); + if (rv != SPISD_RESULT_OK) { + M_PRINTF("ERROR: card is not idle\n"); + goto recovery; + } + + // Send multi block read command + rv = spisd_read_multi_block_begin(sector); + if (rv != SPISD_RESULT_OK) { + M_PRINTF("ERROR: failed to start multi-block read\n"); + goto recovery; + } + + // Wait for first start token (first one takes a long time) + rv = wait_equal(0xFE, 100000, PORT_NR); + if (rv != SPISD_RESULT_OK) { + M_PRINTF("ERROR: no start token\n"); + goto recovery; + } + break; + +recovery: + spisd_init_recovery(); + } + + return rv; +} + +static int _msread_do(struct block_device* bd, void* buffer, u16 count) +{ + // Setup DMA cmd struct + cmd.buffer = buffer; + cmd.portNr = PORT_NR; + cmd.sector_count = count; + cmd.sectors_transferred = 0; + cmd.sectors_reversed = 0; + cmd.response = SPISD_RESULT_OK; + cmd.abort = 0; + + // Start first DMA transfer (1 sector) + sendCmd_Rx_DMA_start(buffer, PORT_NR); + + // Process events from DMA completion interrupt + while (1) { + uint32_t resbits; + + WaitEventFlag(event_flag, EF_SIO2_INTR_REVERSE | EF_SIO2_INTR_COMPLETE, 1, &resbits); + + if (resbits & EF_SIO2_INTR_REVERSE) { + ClearEventFlag(event_flag, ~EF_SIO2_INTR_REVERSE); + while (cmd.sectors_reversed < cmd.sectors_transferred && cmd.abort == 0) { + void *buf = (u32*)&cmd.buffer[cmd.sectors_reversed * SECTOR_SIZE]; + reverseBuffer32(buf, SECTOR_SIZE / 4); +#ifdef CONFIG_USE_CRC16 + u16 crc_a = crc16(buf, SECTOR_SIZE); + u16 crc_b = cmd.crc[cmd.sectors_reversed]; + if (crc_a != crc_b) { + // CRC mismatch: + // - Signal ISR to stop reading + // - Wait for complete event from ISR + cmd.abort = 1; + M_PRINTF("ERROR: crc invalid (0x%x != 0x%x) @ sector %d of %d -> 0x%x\n", crc_a, crc_b, cmd.sectors_reversed, count, (int)buffer); + } +#endif + if (cmd.abort == 0) + cmd.sectors_reversed++; + } + } + + if (resbits & EF_SIO2_INTR_COMPLETE) { + ClearEventFlag(event_flag, ~EF_SIO2_INTR_COMPLETE); + break; + } + } + + return cmd.sectors_reversed; +} + +/* + * BDM interface: + * - BDM -> "spi_sdcard" library + */ +static int spi_sdcard_read(struct block_device* bd, u32 sector, void* buffer, u16 count) +{ + int rv; + int count_left = count; + int retry_count; + + //M_DEBUG("%s(%d,%d)\n", __FUNCTION__, (int)sector, (int)count); + + if (count == 0) + return 0; + + sio2_lock(); + + for (retry_count = 0; retry_count < MAX_RETRIES; retry_count++) { + rv = _msread_start(bd, sector); + if (rv != SPISD_RESULT_OK) { + M_PRINTF("ERROR: failed to start multi-block read (%d)\n", rv); + break; + } + + while(count_left > 0) { + // Read sectors + int count_do = (count_left < MAX_SECTORS) ? count_left : MAX_SECTORS; + rv = _msread_do(bd, buffer, count_do); + + // Update statistics + count_left -= rv; + sector += rv; + buffer = (u8 *)buffer + (rv * 512); + + if (rv != count_do) { + // Read failed, have outer loop retry + M_PRINTF("ERROR: _msread_do: %d != %d\n", rv, count_do); + M_PRINTF(" - %s(%d,%d)\n", __FUNCTION__, (int)sector, (int)count); + break; + } + + if (count_left > 0) { + // Wait for next start token + if (wait_equal(0xFE, 200, PORT_NR) != SPISD_RESULT_OK) { + M_PRINTF("ERROR: no start token\n"); + break; + } + } + + } + + rv = spisd_read_multi_block_end(); + if (rv != SPISD_RESULT_OK) { + M_PRINTF("ERROR: spisd_read_multi_block_end = %d\n", rv); + break; + } + + if (count_left <= 0) + break; + } + + // Let detection thread know the card has been used succesfully + if (count_left == 0) + card_used = 1; + + sio2_unlock(); + + return count - count_left; +} + +static int spi_sdcard_write(struct block_device* bd, u32 sector, const void* buffer, u16 count) +{ + int rv; + + //M_DEBUG("%s(%d,%d)\n", __FUNCTION__, (int)sector, (int)count); + + if (count == 0) + return 0; + + sio2_lock(); + + rv = spisd_write_multi_block(sector, buffer, count); + if (rv != SPISD_RESULT_OK) { + M_PRINTF("ERROR: spisd_write_multi_block = %d\n", rv); + sio2_unlock(); + return 0; + } + + // Let detection thread know the card has been used succesfully + card_used = 1; + + sio2_unlock(); + + return count; +} + +static void spi_sdcard_flush(struct block_device* bd) +{ + //M_DEBUG("%s\n", __FUNCTION__); + + return; +} + +static int spi_sdcard_stop(struct block_device* bd) +{ + //M_DEBUG("%s\n", __FUNCTION__); + + return 0; +} + +// BDM interface +static struct block_device bd = { + NULL, /* priv */ + "sdc", /* name */ + 0, /* devNr */ + 0, /* parNr */ + 0x00, /* parId */ + SECTOR_SIZE, /* sectorSize */ + 0, /* sectorOffset */ + 0, /* sectorCount */ + spi_sdcard_read, + spi_sdcard_write, + spi_sdcard_flush, + spi_sdcard_stop +}; + +static void sd_detect() +{ + spisd_info_t cardinfo; + int rv = SPISD_RESULT_ERROR; + + //M_DEBUG("%s\n", __FUNCTION__); + + // Detect card + sio2_lock(); + if (card_inserted == 0) { + // Try to detect a card by initializing + rv = spisd_init(&spi); + } else { + // Try to detect card removal by sending a dummy command + rv = spisd_read_multi_block_begin(0); + if (rv == SPISD_RESULT_OK) + rv = spisd_read_multi_block_end(); + if (rv != SPISD_RESULT_OK) + rv = spisd_init_recovery(); + } + sio2_unlock(); + + // Change state + if ((card_inserted == 0) && (rv == SPISD_RESULT_OK)) { + M_PRINTF("card insertion detected\n"); + card_inserted = 1; + + sio2_lock(); + rv = spisd_get_card_info(&cardinfo); + sio2_unlock(); + + if (rv != 0) { + M_PRINTF("ERROR: spisd_get_card_info returned %d\n", rv); + return; + } + + struct t_csdVer1* csdv1 = (struct t_csdVer1*)cardinfo.csd; + struct t_csdVer2* csdv2 = (struct t_csdVer2*)cardinfo.csd; + if (csdv1->csd_structure == 0) { //ver 1 + unsigned int c_size_mult = (csdv1->c_size_multHi << 1) | csdv1->c_size_multLo; + unsigned int c_size = (csdv1->c_sizeHi << 10) | (csdv1->c_sizeMd << 2) | csdv1->c_sizeLo; + unsigned int blockNr = (c_size + 1) << (c_size_mult + 2); + unsigned int blockLen = 1 << csdv1->read_bl_len; + unsigned int capacity = blockNr * blockLen; + + bd.sectorCount = capacity / 512; + } else if (csdv1->csd_structure == 1) { //ver 2 + unsigned int c_size = (csdv2->c_sizeHi << 16) | (csdv2->c_sizeMd << 8) | csdv2->c_sizeLo; + + bd.sectorCount = (c_size + 1) * 1024; + } + + M_PRINTF("%u %u-byte logical blocks: (%uMB / %uMiB)\n", bd.sectorCount, bd.sectorSize, bd.sectorCount / ((1000 * 1000) / bd.sectorSize), bd.sectorCount / ((1024 * 1024) / bd.sectorSize)); + + // Connect to block device manager + bdm_connect_bd(&bd); + } else if ((card_inserted == 1) && (rv != SPISD_RESULT_OK)) { + M_PRINTF("card removal detected\n"); + card_inserted = 0; + + // Disconnect from block device manager + bdm_disconnect_bd(&bd); + } +} + +// SD card detection thread +static void sd_detect_thread(void* arg) +{ + M_PRINTF("card detection thread running\n"); + + while (1) { + // Sleep for 1 second + DelayThread(1000 * 1000); + + M_DEBUG("Check card, inserted=%d, used=%d\n", card_inserted, card_used); + + // Detect card if it has not been used recently + if (card_used == 0) + sd_detect(); + card_used = 0; + } +} + +/* + * Module start/stop + */ +int module_start(int argc, char* argv[]) +{ + iop_library_t* lib_modload; + iop_event_t event; + iop_thread_t thread; + int i, rv; + + M_PRINTF("Starting module\n"); + for (i = 0; i < argc; i++) + M_PRINTF(" - argv[%d] = %s\n", i, argv[i]); + + // Create default tranfer descriptor + _init_td(&global_td, PORT_NR); + + // Create event flag + event.attr = 2; + event.option = 0; + event.bits = 0; + rv = event_flag = CreateEventFlag(&event); + if (rv < 0) { + M_PRINTF("ERROR: CreateEventFlag returned %d\n", rv); + goto error1; + } + + rv = sio2man_hook_init(); + if (rv < 0) { + M_PRINTF("ERROR: sio2man_hook_init returned %d\n", rv); + goto error2; + } + + // Just in case sio2man was not loaded, we initialize the dmac channels too + dmac_ch_set_dpcr(IOP_DMAC_SIO2in, 3); + dmac_ch_set_dpcr(IOP_DMAC_SIO2out, 3); + dmac_enable(IOP_DMAC_SIO2in); + dmac_enable(IOP_DMAC_SIO2out); + + /* After a reboot the SD will always respond with: + * - 0xff 0xff 0xc1 0x3f + * - followed by an infinite amount of 0xff + */ + sio2_lock(); + sendCmd_Rx_PIO((void*)&rv, 4, PORT_NR); + sio2_unlock(); + + // Creat SD card detection thread + thread.attr = TH_C; + thread.thread = sd_detect_thread; + thread.option = 0; + thread.priority = USER_LOWEST_PRIORITY; + thread.stacksize = 0x1000; // 4KiB + rv = sd_detect_thread_id = CreateThread(&thread); + if (rv < 0) { + M_PRINTF("ERROR: CreateThread returned %d\n", rv); + goto error3; + } + + // Start thread + rv = StartThread(sd_detect_thread_id, NULL); + if (rv < 0) { + M_PRINTF("ERROR: StartThread returned %d\n", rv); + goto error4; + } + + M_DEBUG("Loaded succesfully!\n"); + + lib_modload = ioplib_getByName("modload"); + if (lib_modload != NULL) { + M_DEBUG("modload 0x%x detected\n", lib_modload->version); + // Newer modload versions allow modules to be unloaded + // Let modload know we support unloading + if (lib_modload->version > 0x102) + return MODULE_REMOVABLE_END; + } else { + M_DEBUG("modload not detected!\n"); + } + + return MODULE_RESIDENT_END; + +error4: + DeleteThread(sd_detect_thread_id); +error3: + sio2man_hook_deinit(); +error2: + DeleteEventFlag(event_flag); +error1: + return MODULE_NO_RESIDENT_END; +} + +int module_stop(int argc, char* argv[]) +{ + int i; + + M_PRINTF("Stopping module\n"); + for (i = 0; i < argc; i++) + M_PRINTF(" - argv[%d] = %s\n", i, argv[i]); + + DeleteThread(sd_detect_thread_id); + sio2man_hook_deinit(); + DeleteEventFlag(event_flag); + + return MODULE_NO_RESIDENT_END; +} + +int _start(int argc, char* argv[]) +{ + M_PRINTF(WELCOME_STR); + + if (argc >= 0) + return module_start(argc, argv); + else + return module_stop(-argc, argv); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/sio2man_hook.c b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/sio2man_hook.c new file mode 100644 index 0000000..578e19d --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/sio2man_hook.c @@ -0,0 +1,237 @@ +#include +#include +#include + +#include "ioplib.h" +#include "sio2man.h" +#include "sio2man_hook.h" + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" + +#define PORT_NR 3 + +static int lock_sema = -1; +static int lock_sema2 = -1; +static u16 hooked_version = 0; + + +// sio2man function typedefs +typedef void (*psio2_transfer_init)(void); +typedef int (*psio2_transfer)(sio2_transfer_data_t *td); +typedef void (*psio2_transfer_reset)(void); + +// Original sio2man function pointers +psio2_transfer_init _23_psio2_pad_transfer_init; +psio2_transfer_init _24_psio2_mc_transfer_init; +psio2_transfer_init _46_psio2_pad_transfer_init; +psio2_transfer_init _47_psio2_mc_transfer_init; +psio2_transfer_init _48_psio2_mtap_transfer_init; +psio2_transfer_init _49_psio2_rm_transfer_init; +psio2_transfer_init _50_psio2_unk_transfer_init; +psio2_transfer _25_psio2_transfer; +psio2_transfer _51_psio2_transfer; +psio2_transfer_reset _26_psio2_transfer_reset; +psio2_transfer_reset _52_psio2_transfer_reset; + +// Generic sio2man init function +static void _sio2_transfer_init(psio2_transfer_init init_func) +{ + WaitSema(lock_sema); + init_func(); +} + +// Generic sio2man transfer function +static int _sio2_transfer(psio2_transfer transfer_func, sio2_transfer_data_t* td) +{ + int rv, i; + + // Do not allow transfers to/from our used port + for (i = 0; i < 16; i++) { + // Last transfer, we're ok. + if (td->regdata[i] == 0) + break; + + // Wrong port, abort. + if ((td->regdata[i] & 3) == PORT_NR) + return 1; + } + + WaitSema(lock_sema2); + rv = transfer_func(td); + SignalSema(lock_sema2); + + return rv; +} + +// Generic sio2man transfer_reset function +static void _sio2_transfer_reset(psio2_transfer_reset reset_func) +{ + reset_func(); + SignalSema(lock_sema); +} + +// Hooked sio2man functions +static void _23_sio2_pad_transfer_init (){ _sio2_transfer_init (_23_psio2_pad_transfer_init ); } +static void _24_sio2_mc_transfer_init (){ _sio2_transfer_init (_24_psio2_mc_transfer_init ); } +static void _46_sio2_pad_transfer_init (){ _sio2_transfer_init (_46_psio2_pad_transfer_init ); } +static void _47_sio2_mc_transfer_init (){ _sio2_transfer_init (_47_psio2_mc_transfer_init ); } +static void _48_sio2_mtap_transfer_init(){ _sio2_transfer_init (_48_psio2_mtap_transfer_init); } +static void _49_sio2_rm_transfer_init (){ _sio2_transfer_init (_49_psio2_rm_transfer_init ); } +static void _50_sio2_unk_transfer_init (){ _sio2_transfer_init (_50_psio2_unk_transfer_init ); } +static void _26_sio2_transfer_reset (){ _sio2_transfer_reset(_26_psio2_transfer_reset ); } +static void _52_sio2_transfer_reset (){ _sio2_transfer_reset(_52_psio2_transfer_reset ); } +static void _25_sio2_transfer(sio2_transfer_data_t* td){ _sio2_transfer(_25_psio2_transfer, td); } +static void _51_sio2_transfer(sio2_transfer_data_t* td){ _sio2_transfer(_51_psio2_transfer, td); } + +static void _sio2man_unhook(iop_library_t* lib) +{ + if (hooked_version == 0) { + M_DEBUG("Warning: trying to unhook sio2man while not hooked\n"); + return; + } + + ioplib_hookExportEntry(lib, 23, _23_psio2_pad_transfer_init); + ioplib_hookExportEntry(lib, 24, _24_psio2_mc_transfer_init); + ioplib_hookExportEntry(lib, 25, _25_psio2_transfer); + ioplib_hookExportEntry(lib, 26, _26_psio2_transfer_reset); + ioplib_hookExportEntry(lib, 46, _46_psio2_pad_transfer_init); + ioplib_hookExportEntry(lib, 47, _47_psio2_mc_transfer_init); + ioplib_hookExportEntry(lib, 48, _48_psio2_mtap_transfer_init); + + if ((hooked_version >= IRX_VER(1, 2)) && (hooked_version < IRX_VER(2, 0))) { + // Only for the newer rom0:XSIO2MAN + // Assume all v1.x libraries to use this interface (reset at 50) + ioplib_hookExportEntry(lib, 49, _51_psio2_transfer); + ioplib_hookExportEntry(lib, 50, _52_psio2_transfer_reset); + } else /*if (hooked_version >= IRX_VER(2, 3))*/ { + // Only for the newer rom1:SIO2MAN + // Assume all v2.x libraries to use this interface (reset at 52) + ioplib_hookExportEntry(lib, 49, _49_psio2_rm_transfer_init); + ioplib_hookExportEntry(lib, 50, _50_psio2_unk_transfer_init); + ioplib_hookExportEntry(lib, 51, _51_psio2_transfer); + ioplib_hookExportEntry(lib, 52, _52_psio2_transfer_reset); + } + + hooked_version = 0; +} + +static void _sio2man_hook(iop_library_t* lib) +{ + if (hooked_version != 0) { + M_DEBUG("Warning: trying to hook sio2man version 0x%x\n", lib->version); + M_DEBUG(" while version 0x%x already hooked\n", hooked_version); + return; + } + + // Only the newer sio2man libraries (with reset functions) are supported + if (lib->version > IRX_VER(1, 1)) { + M_DEBUG("Installing sio2man hooks for version 0x%x\n", lib->version); + + _23_psio2_pad_transfer_init = ioplib_hookExportEntry(lib, 23, _23_sio2_pad_transfer_init); + _24_psio2_mc_transfer_init = ioplib_hookExportEntry(lib, 24, _24_sio2_mc_transfer_init); + _25_psio2_transfer = ioplib_hookExportEntry(lib, 25, _25_sio2_transfer); + _26_psio2_transfer_reset = ioplib_hookExportEntry(lib, 26, _26_sio2_transfer_reset); + _46_psio2_pad_transfer_init = ioplib_hookExportEntry(lib, 46, _46_sio2_pad_transfer_init); + _47_psio2_mc_transfer_init = ioplib_hookExportEntry(lib, 47, _47_sio2_mc_transfer_init); + _48_psio2_mtap_transfer_init = ioplib_hookExportEntry(lib, 48, _48_sio2_mtap_transfer_init); + + if ((lib->version >= IRX_VER(1, 2)) && (lib->version < IRX_VER(2, 0))) { + // Only for the newer rom0:XSIO2MAN + // Assume all v1.x libraries to use this interface (reset at 50) + _51_psio2_transfer = ioplib_hookExportEntry(lib, 49, _51_sio2_transfer); + _52_psio2_transfer_reset = ioplib_hookExportEntry(lib, 50, _52_sio2_transfer_reset); + } else /*if (lib->version >= IRX_VER(2, 3))*/ { + // Only for the newer rom1:SIO2MAN + // Assume all v2.x libraries to use this interface (reset at 52) + _49_psio2_rm_transfer_init = ioplib_hookExportEntry(lib, 49, _49_sio2_rm_transfer_init); + _50_psio2_unk_transfer_init = ioplib_hookExportEntry(lib, 50, _50_sio2_unk_transfer_init); + _51_psio2_transfer = ioplib_hookExportEntry(lib, 51, _51_sio2_transfer); + _52_psio2_transfer_reset = ioplib_hookExportEntry(lib, 52, _52_sio2_transfer_reset); + } + + hooked_version = lib->version; + } else { + M_DEBUG("ERROR: sio2man version 0x%x not supported\n", lib->version); + } +} + +int (*pRegisterLibraryEntries)(iop_library_t* lib); +static int hookRegisterLibraryEntries(iop_library_t* lib) +{ + M_DEBUG("RegisterLibraryEntries: %s 0x%x\n", lib->name, lib->version); + + if (!strcmp(lib->name, "sio2man")) + _sio2man_hook(lib); + + return pRegisterLibraryEntries(lib); +} + +int sio2man_hook_init() +{ + iop_sema_t sema; + iop_library_t* lib; + + M_DEBUG("%s\n", __FUNCTION__); + + // Create semaphore for locking sio2man exclusively + sema.attr = 1; + sema.initial = 1; + sema.max = 1; + sema.option = 0; + lock_sema = CreateSema(&sema); + lock_sema2 = CreateSema(&sema); + + // Hook into 'loadcore' so we know when sio2man is loaded in the future + lib = ioplib_getByName("loadcore"); + if (lib == NULL) { + DeleteSema(lock_sema); + DeleteSema(lock_sema2); + return -1; + } + pRegisterLibraryEntries = ioplib_hookExportEntry(lib, 6, hookRegisterLibraryEntries); + + // Hook into 'sio2man' now if it's already loaded + lib = ioplib_getByName("sio2man"); + if (lib != NULL) { + _sio2man_hook(lib); + ioplib_relinkExports(lib); + } + + return 0; +} + +void sio2man_hook_deinit() +{ + iop_library_t* lib; + + M_DEBUG("%s\n", __FUNCTION__); + + // Unhook 'sio2man' + lib = ioplib_getByName("sio2man"); + if (lib != NULL) { + _sio2man_unhook(lib); + ioplib_relinkExports(lib); + } + + // Unhook 'loadcore' + ioplib_hookExportEntry(lib, 6, pRegisterLibraryEntries); + + // Delete locking semaphore + DeleteSema(lock_sema); + DeleteSema(lock_sema2); +} + +void sio2man_hook_sio2_lock() +{ + // Lock sio2man driver so we can use it exclusively + WaitSema(lock_sema); + WaitSema(lock_sema2); +} + +void sio2man_hook_sio2_unlock() +{ + // Unlock sio2man driver + SignalSema(lock_sema2); + SignalSema(lock_sema); +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/sio2man_hook.h b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/sio2man_hook.h new file mode 100644 index 0000000..5e88f0c --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/sio2man_hook.h @@ -0,0 +1,15 @@ +#ifndef SIO2MAN_HOOK_H +#define SIO2MAN_HOOK_H + + +int sio2man_hook_init(); +void sio2man_hook_deinit(); + +// Lock all communication to SIO2MAN +// this is needed for drivers that communicate directly to sio2, like mx4sio. +// Do NOT lock for long duration, only for single (high speed) transfers +void sio2man_hook_sio2_lock(); +void sio2man_hook_sio2_unlock(); + + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/sio2regs.h b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/sio2regs.h new file mode 100644 index 0000000..8da812f --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/sio2regs.h @@ -0,0 +1,174 @@ +#ifndef SIO2REGS_H +#define SIO2REGS_H + + +//SIO2 registers: + +#define SIO2_REL_BASE 0x1F808000 +#define SIO2_SEG 0xA0000000 //Uncached +#define SIO2_BASE (SIO2_REL_BASE + SIO2_SEG) + +#define SIO2_REG_BASE (SIO2_BASE + 0x200) +#define SIO2_REG_PORT0_CTRL1 (SIO2_BASE + 0x240) +#define SIO2_REG_PORT0_CTRL2 (SIO2_BASE + 0x244) +#define SIO2_REG_DATA_OUT (SIO2_BASE + 0x260) +#define SIO2_REG_DATA_IN (SIO2_BASE + 0x264) +#define SIO2_REG_CTRL (SIO2_BASE + 0x268) +#define SIO2_REG_STAT6C (SIO2_BASE + 0x26C) +#define SIO2_REG_STAT70 (SIO2_BASE + 0x270) +#define SIO2_REG_STAT74 (SIO2_BASE + 0x274) +#define SIO2_REG_UNKN78 (SIO2_BASE + 0x278) +#define SIO2_REG_UNKN7C (SIO2_BASE + 0x27C) +#define SIO2_REG_STAT (SIO2_BASE + 0x280) + +#define SIO2_A_QUEUE (SIO2_BASE + 0x200) +#define SIO2_A_PORT0_CTRL1 (SIO2_BASE + 0x240) +#define SIO2_A_PORT0_CTRL2 (SIO2_BASE + 0x244) +#define SIO2_A_DATA_OUT (SIO2_BASE + 0x260) +#define SIO2_A_DATA_IN (SIO2_BASE + 0x264) +#define SIO2_A_CTRL (SIO2_BASE + 0x268) +#define SIO2_A_STAT6C (SIO2_BASE + 0x26C) +#define SIO2_A_CONN_STAT70 (SIO2_BASE + 0x270) +#define SIO2_A_FIFO_STAT74 (SIO2_BASE + 0x274) +#define SIO2_A_TX_FIFO_PT (SIO2_BASE + 0x278) +#define SIO2_A_RX_FIFO_PT (SIO2_BASE + 0x27C) +#define SIO2_A_INTR_STAT (SIO2_BASE + 0x280) + +//Bit-field definitions: + +#define PCTRL0_ATT_LOW_PER(x) (((x) << 0) & 0xFF) +#define PCTRL0_ATT_MIN_HIGH_PER(x) (((x) << 8) & 0xFF00) +#define PCTRL0_BAUD0_DIV(x) (((x) << 16) & 0xFF0000) +#define PCTRL0_BAUD1_DIV(x) (((x) << 24) & 0xFF000000) + +#define PCTRL1_ACK_TIMEOUT_PER(x) (((x) << 0) & 0xFFFF) +#define PCTRL1_INTER_BYTE_PER(x) (((x) << 16) & 0xFF0000) +#define PCTRL1_UNK24(x) (((x)&1) << 24) +#define PCTRL1_IF_MODE_SPI_DIFF(x) (((x)&1) << 25) + +#define TR_CTRL_PORT_NR(x) (((x)&0x3) << 0) +#define TR_CTRL_PAUSE(x) (((x)&1) << 2) +#define TR_CTRL_UNK03(x) (((x)&1) << 3) +//Each of the folowing is 0 for PIO transfer in the given direction. to select DMA, set to 1. +#define TR_CTRL_TX_MODE_PIO_DMA(x) (((x)&1) << 4) +#define TR_CTRL_RX_MODE_PIO_DMA(x) (((x)&1) << 5) +/* +normal special +0 0 no transfer done(???) +1 0 normal transfer - usually used +0 1 "special" transfer (not known to have been ever used by anything, no known difference from normal). +1 1 no transfer takes place +*/ +#define TR_CTRL_NORMAL_TR(x) (((x)&1) << 6) +#define TR_CTRL_SPECIAL_TR(x) (((x)&1) << 7) +//In bytes 0 - 0x100: +#define TR_CTRL_TX_DATA_SZ(x) (((x)&0x1FF) << 8) +#define TR_CTRL_UNK17(x) (((x)&1) << 17) +#define TR_CTRL_RX_DATA_SZ(x) (((x)&0x1FF) << 18) +#define TR_CTRL_UNK27(x) (((x)&1) << 27) +//28 and 29 can't be set +#define TR_CTRL_UNK28(x) (((x)&1) << 28) +#define TR_CTRL_UNK29(x) (((x)&1) << 29) +//selects between baud rate divisors 0 and 1 +#define TR_CTRL_BAUD_DIV(x) (((x)&1) << 30) +#define TR_CTRL_WAIT_ACK_FOREVER(x) (((x)&1) << 31) + +//8268 SIO2 (main) CTRL register. +#define CTRL_TR_START(x) (((x)&1) << 0) +#define CTRL_TR_RESUME_PAUSED(x) (((x)&1) << 1) +#define CTRL_RESET_STATE(x) (((x)&1) << 2) +#define CTRL_RESET_FIFOS(x) (((x)&1) << 3) +#define CTRL_USE_ACK_WAIT_TIMEOUT(x) (((x)&1) << 4) +#define CTRL_NO_MISSING_ACK_ERR(x) (((x)&1) << 5) +//bit6 unknonw r/o, 0 +#define CTRL_UNK06(x) (((x)&1) << 6) +//bit7 unknonw r/w, usually set to 1 by software +#define CTRL_UNK07(x) (((x)&1) << 7) +#define CTRL_ERROR_INTR_EN(x) (((x)&1) << 8) +#define CTRL_TR_COMP_INTR_EN(x) (((x)&1) << 9) +//bits 10, 11 unknonw r/w, usually set to 0 by software +#define CTRL_UNK10(x) (((x)&1) << 10) +#define CTRL_UNK11(x) (((x)&1) << 11) +//Unknown r/o, 0: +#define CTRL_UNK2912(x) (((x)&0x3FFFF) << 12) +#define CTRL_PS1_MODE_EN(x) (((x)&1) << 30) +#define CTRL_SLAVE_MODE_EN(x) (((x)&1) << 31) + +//826C SIO2 (main) STAT register. (read-only) +#define STAT_UNK0300(x) (((x) >> 0) & 0xF) +//Needs more data through DMA to complete transfer: +#define STAT_NEED_DMA_DATA_TX(x) (((x) >> 4) & 1) +#define STAT_NEED_DMA_DATA_RX(x) (((x) >> 5) & 1) +#define STAT_UNK0706(x) (((x) >> 6) & 3) +//Queue slot number that is going to be processed next (0-15): +#define STAT_QUEUE_SLOT_PROC(x) (((x) >> 8) & 0xF) +//Kept clear only while tranfer is running, and set while idle. 1 can also signify transfer completion: +#define STAT_TR_IDLE(x) (((x) >> 12) & 1) +//FIFO underflow / overflow errors: (I am not sure if they really correspond to the TX and RX FIFOs) +#define STAT_ERR_TX_FIFO_UOFLOW(x) (((x) >> 13) & 1) +#define STAT_ERR_RX_FIFO_UOFLOW(x) (((x) >> 14) & 1) +#define STAT_ERR_ACK_MISSING(x) (((x) >> 15) & 1) +//Flags used to determine the transfers of which queue slots triggered erroirs. Slot = 0 - 15: +#define STAT_ERR_QUEUE_SLOT(x, slot) (((x) >> (slot + 16)) & 1) + +//8270 SIO2 Device connected detection status register. (read-only) +//For ports 0-3. Only SAS0 and SAS1 are actually connected to the physical port and only on early PS2 models (~ SCPH-30000). +#define CONN_STAT_CDC0(x) (((x) >> 0) & 1) +#define CONN_STAT_CDC1(x) (((x) >> 1) & 1) +#define CONN_STAT_CDC2(x) (((x) >> 2) & 1) +#define CONN_STAT_CDC3(x) (((x) >> 3) & 1) +#define CONN_STAT_SAS0(x) (((x) >> 4) & 1) +#define CONN_STAT_SAS1(x) (((x) >> 5) & 1) +#define CONN_STAT_SAS2(x) (((x) >> 6) & 1) +#define CONN_STAT_SAS3(x) (((x) >> 7) & 1) + +//8274 SIO2 FIFO status register. (read-only) +//values 0 - 0x100 bytes: +#define FSTAT_TX_SZ(x) (((x) >> 0) & 0x1FF) +#define FSTAT_TX_UNK09(x) (((x) >> 9) & 1) +#define FSTAT_TX_OVERFLOW(x) (((x) >> 10) & 1) +#define FSTAT_TX_UNDERFLOW(x) (((x) >> 11) & 1) +#define FSTAT_UNK1512(x) (((x) >> 12) & 0xF) +#define FSTAT_RX_SZ(x) (((x) >> 16) & 0x1FF) +#define FSTAT_RX_UNK09(x) (((x) >> 25) & 1) +#define FSTAT_RX_OVERFLOW(x) (((x) >> 26) & 1) +#define FSTAT_RX_UNDERFLOW(x) (((x) >> 27) & 1) +#define FSTAT_UNK3128(x) (((x) >> 28) & 0xF) + +//8278 SIO2_REG_UNKN78 TX FIFO pointers. (read/write) +//#define GET_TXFPNTS_HEAD(x) (((x)>>0)&0xFF) +//#define SET_TXFPNTS_HEAD(x) (((x)>>0)&0xFF) +//... +//Better not add the FIFO pointers, as to change only one of them would require more complex macros. +//827C SIO2_REG_UNKN7C RX FIFO pointers. + +//8280 SIO2_REG_STAT u32 Interrupt status. Writing 1 to an interrupt flag clears it. +#define GET_ISTAT_TR_COMP(x) (((x) >> 0) & 1) +//Any error: +#define GET_ISTAT_TR_ERR(x) (((x) >> 1) & 1) + +// Inline (faster) versions of sio2_* functions +/* 04 */ static inline void inl_sio2_ctrl_set(u32 val) { _sw(val, SIO2_REG_CTRL); } +/* 05 */ static inline u32 inl_sio2_ctrl_get() { return _lw(SIO2_REG_CTRL); } +/* 06 */ static inline u32 inl_sio2_stat6c_get() { return _lw(SIO2_REG_STAT6C); } +/* 07 */ static inline void inl_sio2_portN_ctrl1_set(int N, u32 val) { _sw(val, SIO2_REG_PORT0_CTRL1 + (N * 8)); } +/* 08 */ static inline u32 inl_sio2_portN_ctrl1_get(int N) { return _lw(SIO2_REG_PORT0_CTRL1 + (N * 8)); } +/* 09 */ static inline void inl_sio2_portN_ctrl2_set(int N, u32 val) { _sw(val, SIO2_REG_PORT0_CTRL2 + (N * 8)); } +/* 10 */ static inline u32 inl_sio2_portN_ctrl2_get(int N) { return _lw(SIO2_REG_PORT0_CTRL2 + (N * 8)); } +/* 11 */ static inline u32 inl_sio2_stat70_get() { return _lw(SIO2_REG_STAT70); } +/* 12 */ static inline void inl_sio2_regN_set(int N, u32 val) { _sw(val, SIO2_REG_BASE + (N * 4)); } +/* 13 */ static inline u32 inl_sio2_regN_get(int N) { return _lw(SIO2_REG_BASE + (N * 4)); } +/* 14 */ static inline u32 inl_sio2_stat74_get() { return _lw(SIO2_REG_STAT74); } +/* 15 */ static inline void inl_sio2_unkn78_set(u32 val) { _sw(val, SIO2_REG_UNKN78); } +/* 16 */ static inline u32 inl_sio2_unkn78_get() { return _lw(SIO2_REG_UNKN78); } +/* 17 */ static inline void inl_sio2_unkn7c_set(u32 val) { _sw(val, SIO2_REG_UNKN7C); } +/* 18 */ static inline u32 inl_sio2_unkn7c_get() { return _lw(SIO2_REG_UNKN7C); } +/* 19 */ static inline void inl_sio2_data_out(u8 val) { _sb(val, SIO2_REG_DATA_OUT); } +/* 20 */ static inline u8 inl_sio2_data_in() { return _lb(SIO2_REG_DATA_IN); } +/* 21 */ static inline void inl_sio2_stat_set(u32 val) { _sw(val, SIO2_REG_STAT); } +/* 22 */ static inline u32 inl_sio2_stat_get() { return _lw(SIO2_REG_STAT); } + +static inline u16 inl_sio2_data_inh() { return _lh(SIO2_REG_DATA_IN); } +static inline u32 inl_sio2_data_inw() { return _lw(SIO2_REG_DATA_IN); } + +#endif diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_crc7.c b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_crc7.c new file mode 100644 index 0000000..5e03057 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_crc7.c @@ -0,0 +1,81 @@ +/* Includes ------------------------------------------------------------------*/ +#include "spi_sdcard_driver_config.h" +#include "spi_sdcard_crc7.h" + +#if SD_CRC7_MODE == SD_CRC7_MODE_RAM_TABLE || SD_CRC7_MODE == SD_CRC7_MODE_ROM_TABLE + +# if SD_CRC7_MODE == CRC7_MODE_RAM_TABLE +uint8_t crc7_table[256]; + +void crc7_generate_table(void) { + int i, j; + uint8_t poly = 0x89; // the value of our CRC-7 polynomial + + for (i = 0; i < 256; ++i) { + crc7_table[i] = (i & 0x80) ? i ^ poly : i; + + for (j = 1; j < 8; ++j) { + crc7_table[i] <<= 1; + + if (crc7_table[i] & 0x80) { + crc7_table[i] ^= poly; + } + } + } +} +# else// SD_CRC7_MODE == SD_CRC7_MODE_ROM_TABLE +const uint8_t crc7_table[256] = { + 0x00, 0x09, 0x12, 0x1B, 0x24, 0x2D, 0x36, 0x3F, 0x48, 0x41, 0x5A, 0x53, 0x6C, 0x65, 0x7E, 0x77, + 0x19, 0x10, 0x0B, 0x02, 0x3D, 0x34, 0x2F, 0x26, 0x51, 0x58, 0x43, 0x4A, 0x75, 0x7C, 0x67, 0x6E, + 0x32, 0x3B, 0x20, 0x29, 0x16, 0x1F, 0x04, 0x0D, 0x7A, 0x73, 0x68, 0x61, 0x5E, 0x57, 0x4C, 0x45, + 0x2B, 0x22, 0x39, 0x30, 0x0F, 0x06, 0x1D, 0x14, 0x63, 0x6A, 0x71, 0x78, 0x47, 0x4E, 0x55, 0x5C, + 0x64, 0x6D, 0x76, 0x7F, 0x40, 0x49, 0x52, 0x5B, 0x2C, 0x25, 0x3E, 0x37, 0x08, 0x01, 0x1A, 0x13, + 0x7D, 0x74, 0x6F, 0x66, 0x59, 0x50, 0x4B, 0x42, 0x35, 0x3C, 0x27, 0x2E, 0x11, 0x18, 0x03, 0x0A, + 0x56, 0x5F, 0x44, 0x4D, 0x72, 0x7B, 0x60, 0x69, 0x1E, 0x17, 0x0C, 0x05, 0x3A, 0x33, 0x28, 0x21, + 0x4F, 0x46, 0x5D, 0x54, 0x6B, 0x62, 0x79, 0x70, 0x07, 0x0E, 0x15, 0x1C, 0x23, 0x2A, 0x31, 0x38, + 0x41, 0x48, 0x53, 0x5A, 0x65, 0x6C, 0x77, 0x7E, 0x09, 0x00, 0x1B, 0x12, 0x2D, 0x24, 0x3F, 0x36, + 0x58, 0x51, 0x4A, 0x43, 0x7C, 0x75, 0x6E, 0x67, 0x10, 0x19, 0x02, 0x0B, 0x34, 0x3D, 0x26, 0x2F, + 0x73, 0x7A, 0x61, 0x68, 0x57, 0x5E, 0x45, 0x4C, 0x3B, 0x32, 0x29, 0x20, 0x1F, 0x16, 0x0D, 0x04, + 0x6A, 0x63, 0x78, 0x71, 0x4E, 0x47, 0x5C, 0x55, 0x22, 0x2B, 0x30, 0x39, 0x06, 0x0F, 0x14, 0x1D, + 0x25, 0x2C, 0x37, 0x3E, 0x01, 0x08, 0x13, 0x1A, 0x6D, 0x64, 0x7F, 0x76, 0x49, 0x40, 0x5B, 0x52, + 0x3C, 0x35, 0x2E, 0x27, 0x18, 0x11, 0x0A, 0x03, 0x74, 0x7D, 0x66, 0x6F, 0x50, 0x59, 0x42, 0x4B, + 0x17, 0x1E, 0x05, 0x0C, 0x33, 0x3A, 0x21, 0x28, 0x5F, 0x56, 0x4D, 0x44, 0x7B, 0x72, 0x69, 0x60, + 0x0E, 0x07, 0x1C, 0x15, 0x2A, 0x23, 0x38, 0x31, 0x46, 0x4F, 0x54, 0x5D, 0x62, 0x6B, 0x70, 0x79 +}; +# endif //SD_CRC7_MODE == SD_CRC7_MODE_RAM_TABLE + +static uint8_t _crc7_get_item(uint8_t init_crc, uint8_t message_byte) { + return crc7_table[(init_crc << 1) ^ message_byte]; +} + +uint8_t crc7(const uint8_t message[], size_t length) { + size_t i; + uint8_t crc = 0; + + for (i = 0; i < length; ++i) { + crc = _crc7_get_item(crc, message[i]); + } + + return crc; +} +#elif SD_CRC7_MODE == SD_CRC7_MODE_RUNTIME + +uint8_t crc7(const uint8_t message[], size_t length) { + const uint8_t poly = 0x89; + uint8_t crc = 0; + + for (size_t i = 0; i < length; i++) { + crc ^= message[i]; + + for (size_t j = 0; j < 8; j++) { + crc = (crc & 0x80u) ? ((crc << 1) ^ (poly << 1)) : (crc << 1); + } + } + + return crc >> 1; +} + +#else +#error set corret SD_CRC7_MODE +#endif + diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_crc7.h b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_crc7.h new file mode 100644 index 0000000..4fa5263 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_crc7.h @@ -0,0 +1,16 @@ +#ifndef __SPI_SDCARD_CRC7_H__ +#define __SPI_SDCARD_CRC7_H__ + +/* Includes ------------------------------------------------------------------*/ +#include +#include +#include "spi_sdcard_driver_config.h" +// Set + +#if SD_CRC7_MODE == CRC7_MODE_RAM_TABLE +void crc7_generate_table(void); +#endif + +uint8_t crc7(const uint8_t message[], size_t length); + +#endif //__SPI_SDCARD_CRC7_H__ diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_driver.c b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_driver.c new file mode 100644 index 0000000..64ab933 --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_driver.c @@ -0,0 +1,591 @@ +/* Includes ------------------------------------------------------------------*/ +#include "spi_sdcard_driver.h" +#include "spi_sdcard_driver_config.h" +#include "spi_sdcard_crc7.h" + +//#define DEBUG //comment out this line when not debugging +#include "module_debug.h" +#define SPISD_LOG M_PRINTF + +/* Private types -------------------------------------------------------------*/ +typedef enum card_type_e { + CARD_TYPE_MMC = 0x00, + CARD_TYPE_SDV1 = 0x01, + CARD_TYPE_SDV2 = 0x02, + CARD_TYPE_SDV2HC = 0x04 +} card_type_t; + +/* Private define ------------------------------------------------------------*/ + +#define DUMMY_BYTE 0xFF +#define BLOCK_SIZE 512 + +#define CMD0 0 /* Reset */ +#define CMD1 1 /* Send Operator Condition - SEND_OP_COND */ +#define CMD8 8 /* Send Interface Condition - SEND_IF_COND */ +#define CMD9 9 /* Read CSD */ +#define CMD10 10 /* Read CID */ +#define CMD12 12 /* Stop data transmit */ +#define CMD16 16 /* Set block size, should return 0x00 */ +#define CMD17 17 /* Read single block */ +#define CMD18 18 /* Read multi block */ +#define ACMD23 23 /* Prepare erase N-blokcs before multi block write */ +#define CMD24 24 /* Write single block */ +#define CMD25 25 /* Write multi block */ +#define ACMD41 41 /* should return 0x00 */ +#define CMD55 55 /* should return 0x01 */ +#define CMD58 58 /* Read OCR */ +#define CMD59 59 /* CRC disable/enbale, should return 0x00 */ + +#define CMD_WAIT_RESP_TIMEOUT (100U) +#define WAIT_IDLE_TIMEOUT (50U) + +#define SPI_SPEED_NO_INIT_HZ (400000U) +#define SPI_SPEED_MAX_HZ (25000000U) + +#define CMD_CRC_OFFSET 5 +#define CRC7_SHIFT_MASK(crc7) ((crc7) << 1U | 1U) + +/* Private variables ---------------------------------------------------------*/ +static card_type_t _card_type; +static spisd_interface_t const*_io = NULL; + +static uint8_t _send_command(uint8_t cmd, uint32_t arg) { + uint32_t i; + uint8_t response = 0xFF; + + /* Dummy byte and chip enable */ + _io->wr_rd_byte(DUMMY_BYTE); + _io->select(); + + uint8_t packet[] = {cmd | 0x40, arg >> 24, arg >> 16, arg >> 8, arg, 0}; + packet[CMD_CRC_OFFSET] = CRC7_SHIFT_MASK(crc7(packet, CMD_CRC_OFFSET)); + + _io->write(packet, sizeof(packet)); + + /* Discard stuff byte for CMD12 */ + if (cmd == CMD12) { + _io->wr_rd_byte(DUMMY_BYTE); + } + + /* Wait response, quit till timeout */ + for (i = 0; i < CMD_WAIT_RESP_TIMEOUT; i++) { + response = _io->wr_rd_byte(DUMMY_BYTE); + + if (response != 0xFF) { + break; + } + } + + /* Chip disable and dummy byte */ + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + + return response; +} + +static uint8_t _send_command_recv_response(uint8_t cmd, uint32_t arg, uint8_t* data, size_t size) { + uint32_t i; + + /* Dummy byte and chip enable */ + _io->wr_rd_byte(DUMMY_BYTE); + _io->select(); + + uint8_t packet[] = {cmd | 0x40, arg >> 24, arg >> 16, arg >> 8, arg, 0}; + packet[CMD_CRC_OFFSET] = CRC7_SHIFT_MASK(crc7(packet, CMD_CRC_OFFSET)); + _io->write(packet, sizeof(packet)); + + uint8_t response = DUMMY_BYTE; + + /* Wait response, quit till timeout */ + for (i = 0; i < CMD_WAIT_RESP_TIMEOUT; i++) { + + response = _io->wr_rd_byte(DUMMY_BYTE); + + if (response != DUMMY_BYTE) { + _io->read(data, size); + break; + } + } + + /* Chip disable and dummy byte */ + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + + return response; +} + +static uint8_t _send_command_hold(uint8_t cmd, uint32_t arg) { + uint32_t i; + + /* Dummy byte and chip enable */ + _io->wr_rd_byte(DUMMY_BYTE); + _io->select(); + + uint8_t packet[] = {cmd | 0x40, arg >> 24, arg >> 16, arg >> 8, arg, 0}; + packet[CMD_CRC_OFFSET] = CRC7_SHIFT_MASK(crc7(packet, CMD_CRC_OFFSET)); + _io->write(packet, sizeof(packet)); + + + /* Wait response, quit till timeout */ + for (i = 0; i < 200; i++) { + + uint8_t response = _io->wr_rd_byte(DUMMY_BYTE); + + if (response != 0xFF) { + return response; + } + } + + return 0xFF; +} + +static spisd_result_t _read_buffer(uint8_t *buff, uint32_t len) { + uint32_t i; + uint8_t response = 0; + + /* Wait start-token 0xFE */ + for (i = 0; i < 2000; i++) { + response = _io->wr_rd_byte(DUMMY_BYTE); + + if (response == 0xFE) { + break; + } + } + + if (response != 0xFE) { + + return SPISD_RESULT_ERROR; + } + + _io->read(buff, len); + + /* 2bytes dummy CRC */ + _io->wr_rd_byte(DUMMY_BYTE); + _io->wr_rd_byte(DUMMY_BYTE); + + return SPISD_RESULT_OK; +} + +spisd_result_t spisd_init(spisd_interface_t const *const io) { + uint32_t i; + SPISD_ASSERT(io); + + _io = io; + + if ( !_io->is_present() ) { + SPISD_LOG("There is no card detected! \r\n"); + return SPISD_RESULT_NO_CARD; + } + +#if CRC7_RAM_TABLE == 1 + crc7_generate_table(); +#endif //CRC7_RAM_TABLE == 1 + + _io->relese(); + _io->set_speed(SPI_SPEED_NO_INIT_HZ); + + /* Start send 74 clocks at least */ + for (i = 0; i < 20; i++) { + _io->wr_rd_byte(DUMMY_BYTE); + } + + uint32_t timeout = WAIT_IDLE_TIMEOUT; + uint8_t response = 0; + + do { + response = _send_command(CMD0, 0); + timeout--; + } while ((response != SPISD_R1_IDLE_FLAG) && timeout > 0 ); + + if (!timeout) { + //SPISD_LOG("Reset card into IDLE state failed!\r\n"); + return SPISD_RESULT_TIMEOUT; + } + + uint8_t buff[4]; + response = _send_command_recv_response(CMD8, 0x1AA, buff, sizeof(buff)); + + if (response == SPISD_R1_IDLE_FLAG) { + + /* Check voltage range be 2.7-3.6V */ + if (buff[2] == 0x01 && buff[3] == 0xAA) { + + for (i = 0; i < 0xFFF; i++) { + response = _send_command(CMD55, 0); /* should be return 0x01 */ + + if (response != 0x01) { + SPISD_LOG("Send CMD55 should return 0x01, response=0x%02x\r\n", response); + return SPISD_RESULT_TIMEOUT; + } + + response = _send_command(ACMD41, 0x40000000); /* should be return 0x00 */ + + if (response == 0x00) { + break; + } + } + + if (response != 0x00) { + SPISD_LOG("Send ACMD41 should return 0x00, response=0x%02x\r\n", response); + return SPISD_RESULT_TIMEOUT; + } + + /* Read OCR by CMD58 */ + response = _send_command_recv_response(CMD58, 0, buff, sizeof(buff)); + + if (response != 0x00) { + SPISD_LOG("Send CMD58 should return 0x00, response=0x%02x\r\n", response); + return SPISD_RESULT_TIMEOUT; + } + + /* OCR -> CCS(bit30) 1: SDV2HC 0: SDV2 */ + _card_type = (buff[0] & 0x40) ? CARD_TYPE_SDV2HC : CARD_TYPE_SDV2; + + _io->set_speed(SPI_SPEED_MAX_HZ); + } + +#if USE_MMC_CARD == 1 + } else if (response & SPISD_R1_ILLEGAL_CMD_FLAG) { + + _card_type = CARD_TYPE_SDV1; + + /* End of CMD8, chip disable and dummy byte */ + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + + /* SD1.0/MMC start initialize */ + /* Send CMD55+ACMD41, No-response is a MMC card, otherwise is a SD1.0 card */ + for (i = 0; i < 0xFFF; i++) { + response = _send_command(CMD55, 0); + + if (response != 0x01) { + SPISD_LOG("Send CMD55 should return 0x01, response=0x%02x\r\n", response); + return SPISD_RESULT_TIMEOUT; + } + + response = _send_command(ACMD41, 0); + + if (response == 0x00) { + break; + } + } + + /* MMC card initialize start */ + if (response != 0x00) { + for (i = 0; i < 0xFFF; i++) { + response = _send_command(CMD1, 0); + + if (response == 0x00) { + break; + } + } + + /* Timeout return */ + if (response != 0x00) { + SPISD_LOG("Send CMD1 should return 0x00, response=0x%02x\r\n", response); + return SPISD_RESULT_TIMEOUT; + } + + _card_type = CARD_TYPE_MMC; + SPISD_LOG("Card Type : MMC\r\n"); + } else { + SPISD_LOG("Card Type : SD V1\r\n"); + } + + _io->set_speed(true); + + /* CRC disable */ + response = _send_command(CMD59, 0); + + if (response != 0x00) { + SPISD_LOG("Send CMD59 should return 0x00, response=0x%02x\r\n", response); + return SPISD_RESULT_TIMEOUT; + } + + /* Set the block size */ + response = _send_command(CMD16, BLOCK_SIZE); + + if (response != 0x00) { + SPISD_LOG("Send CMD16 should return 0x00, response=0x%02x\r\n", response); + return SPISD_RESULT_TIMEOUT; + } + +#endif // + } else { + SPISD_LOG("Send CMD8 should return 0x01, response=0x%02x\r\n", response); + return SPISD_RESULT_ERROR; + } + + return SPISD_RESULT_OK; +} + +int spisd_get_card_info(spisd_info_t *cardinfo) { + + _io->wr_rd_byte(DUMMY_BYTE); + + /* Send CMD9, Read CSD */ + uint8_t response = _send_command(CMD9, 0); + + if (response != 0x00) { + return response; + } + + uint8_t temp[16]; + + _io->select(); + + spisd_result_t ret = _read_buffer(cardinfo->csd, 16); + /* chip disable and dummy byte */ + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + + if (ret != SPISD_RESULT_OK) { + return 1; + } + + /* Send CMD10, Read CID */ + response = _send_command(CMD10, 0); + + if (response != 0x00) { + return response; + } + + _io->select(); + ret = _read_buffer(temp, sizeof(temp)); + /* chip disable and dummy byte */ + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + + if (ret != SPISD_RESULT_OK) { + return 2; + } + + /* Byte 0 */ + cardinfo->cid.ManufacturerID = temp[0]; + /* Byte 1 */ + cardinfo->cid.OEM_AppliID = temp[1] << 8; + /* Byte 2 */ + cardinfo->cid.OEM_AppliID |= temp[2]; + /* Byte 3 */ + cardinfo->cid.ProdName1 = temp[3] << 24; + /* Byte 4 */ + cardinfo->cid.ProdName1 |= temp[4] << 16; + /* Byte 5 */ + cardinfo->cid.ProdName1 |= temp[5] << 8; + /* Byte 6 */ + cardinfo->cid.ProdName1 |= temp[6]; + /* Byte 7 */ + cardinfo->cid.ProdName2 = temp[7]; + /* Byte 8 */ + cardinfo->cid.ProdRev = temp[8]; + /* Byte 9 */ + cardinfo->cid.ProdSN = temp[9] << 24; + /* Byte 10 */ + cardinfo->cid.ProdSN |= temp[10] << 16; + /* Byte 11 */ + cardinfo->cid.ProdSN |= temp[11] << 8; + /* Byte 12 */ + cardinfo->cid.ProdSN |= temp[12]; + /* Byte 13 */ + cardinfo->cid.Reserved1 |= (temp[13] & 0xF0) >> 4; + /* Byte 14 */ + cardinfo->cid.ManufactDate = (temp[13] & 0x0F) << 8; + /* Byte 15 */ + cardinfo->cid.ManufactDate |= temp[14]; + /* Byte 16 */ + cardinfo->cid.CID_CRC = (temp[15] & 0xFE) >> 1; + cardinfo->cid.Reserved2 = 1; + + return 0; +} + +spisd_result_t spisd_read_block(uint32_t sector, uint8_t *buffer) { + + if (_card_type != CARD_TYPE_SDV2HC) { + sector = sector << 9; + } + + spisd_result_t ret = SPISD_RESULT_ERROR; + + if (_send_command_hold(CMD17, sector) == 0x00) { + + ret = _read_buffer(buffer, BLOCK_SIZE); + } + + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + + return ret; +} + +spisd_result_t spisd_write_block(uint32_t sector, const uint8_t *buffer) { + uint32_t i; + spisd_result_t ret = SPISD_RESULT_ERROR; + + if (_card_type != CARD_TYPE_SDV2HC) { + sector = sector << 9; + } + + if (_send_command(CMD24, sector) != 0x00) { + return ret; + } + + _io->select(); + + _io->wr_rd_byte(DUMMY_BYTE); + _io->wr_rd_byte(DUMMY_BYTE); + _io->wr_rd_byte(DUMMY_BYTE); + + /* Start data write token: 0xFE */ + _io->wr_rd_byte(0xFE); + + _io->write(buffer, BLOCK_SIZE); + + /* 2Bytes dummy CRC */ + _io->wr_rd_byte(DUMMY_BYTE); + _io->wr_rd_byte(DUMMY_BYTE); + + /* MSD card accept the data */ + uint8_t response = _io->wr_rd_byte(DUMMY_BYTE); + + if ((response & 0x1F) == 0x05) { + + /* Wait all the data programm finished */ + for (i = 0; i < 0x40000; i++) { + if ( _io->wr_rd_byte(DUMMY_BYTE) != 0x00) { + ret = SPISD_RESULT_OK; + break; + } + } + } + + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + + return ret; +} + +spisd_result_t spisd_read_multi_block_begin(uint32_t sector) { + + /* if ver = SD2.0 HC, sector need <<9 */ + if (_card_type != CARD_TYPE_SDV2HC) { + sector = sector << 9; + } + + if (_send_command(CMD18, sector) != 0x00) { + return SPISD_RESULT_ERROR; + } + + return SPISD_RESULT_OK; +} + +spisd_result_t spisd_read_multi_block_read(uint8_t *buffer, uint32_t num_sectors) { + uint32_t i; + _io->wr_rd_byte(DUMMY_BYTE); //todo it + _io->select(); + + for (i = 0; i < num_sectors; i++) { + + spisd_result_t ret = _read_buffer(&buffer[i * BLOCK_SIZE], BLOCK_SIZE); + + if (ret != SPISD_RESULT_OK) { + /* Send stop data transmit command - CMD12 */ + spisd_read_multi_block_end(); + return SPISD_RESULT_ERROR; + } + } + + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + + return SPISD_RESULT_OK; +} + +spisd_result_t spisd_read_multi_block_end(void) { + + /* Send stop data transmit command - CMD12 */ + _send_command(CMD12, 0); + + return SPISD_RESULT_OK; +} + +spisd_result_t spisd_write_multi_block(uint32_t sector, uint8_t const *buffer, uint32_t num_sectors) { + uint32_t i, j; + /* if ver = SD2.0 HC, sector need <<9 */ + if (_card_type != CARD_TYPE_SDV2HC) { + sector = sector << 9; + } + + /* Send command ACMD23 berfore multi write if is not a MMC card */ + if (_card_type != CARD_TYPE_MMC) { + _send_command(CMD55, 0); + _send_command(ACMD23, num_sectors); + } + + if (_send_command(CMD25, sector) != 0x00) { + return SPISD_RESULT_ERROR; + } + + _io->select(); + _io->wr_rd_byte(DUMMY_BYTE); + _io->wr_rd_byte(DUMMY_BYTE); + _io->wr_rd_byte(DUMMY_BYTE); + + for (i = 0; i < num_sectors; i++) { + + /* Start multi block write token: 0xFC */ + _io->wr_rd_byte(0xFC); + + _io->write(&buffer[i * BLOCK_SIZE], BLOCK_SIZE); + + /* 2Bytes dummy CRC */ + _io->wr_rd_byte(DUMMY_BYTE); + _io->wr_rd_byte(DUMMY_BYTE); + + /* MSD card accept the data */ + if ((_io->wr_rd_byte(DUMMY_BYTE) & 0x1F) != 0x05) { + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + return SPISD_RESULT_ERROR; + } + + /* Wait all the data programm finished */ + uint32_t timeout = 0; + + while (_io->wr_rd_byte(DUMMY_BYTE) != 0xFF) { + /* Timeout return */ + if (timeout++ == 0x40000) { + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + return SPISD_RESULT_ERROR; + } + } + } + + /* Send end of transmit token: 0xFD */ + if (_io->wr_rd_byte(0xFD) != 0x00) { + + _io->wr_rd_byte(DUMMY_BYTE); + _io->wr_rd_byte(DUMMY_BYTE); + + /* Wait all the data programm finished */ + for (i = 0; i < 0x40000; i++) { + if (_io->wr_rd_byte(DUMMY_BYTE) == 0xFF) { + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + + for (j = 0; j < 0x40000; j++) { + if (_io->wr_rd_byte(DUMMY_BYTE) == 0xFF) { + return SPISD_RESULT_OK; + } + } + } + } + } + + _io->relese(); + _io->wr_rd_byte(DUMMY_BYTE); + + return SPISD_RESULT_ERROR; +} diff --git a/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_driver.h b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_driver.h new file mode 100644 index 0000000..151e52c --- /dev/null +++ b/sps2_basement/hardware/sbus/iop/pereferial/sio/mx4sio_bd/src/spi_sdcard_driver.h @@ -0,0 +1,238 @@ +#ifndef __SPI_SDCARD_DRIVER_H__ +#define __SPI_SDCARD_DRIVER_H__ + +/* Includes ------------------------------------------------------------------*/ +#include "spi_sdcard_driver_config.h" +#include +#include + +typedef enum spisd_result_s { + SPISD_RESULT_OK = 0, + SPISD_RESULT_ERROR, + SPISD_RESULT_NO_CARD, + SPISD_RESULT_TIMEOUT, +} spisd_result_t; + +#define SPISD_R1_IDLE_FLAG (0x01) +#define SPISD_R1_ERASE_RESET_FLAG (0x02) +#define SPISD_R1_ILLEGAL_CMD_FLAG (0x04) +#define SPISD_R1_CMD_CRC_FLAG (0x08) +#define SPISD_R1_ERASE_SEQ_ERROR_FLAG (0x10) +#define SPISD_R1_ADDR_ERROR_FLAG (0x20) +#define SPISD_R1_PARAM_ERROR_FLAG (0x40) +#define SPISD_R1_ZERO_FLAG (0x80) + +typedef union sppisd_r1_u { + + uint8_t raw; + struct { + uint8_t idle: 1; /*